blob: b92599a02f8f477252a92e6b7f5f760a4d749bb9 [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
Rafael Espindola266b4fe2015-10-31 22:25:59 +00001475static void printArchiveChild(const Archive::Child &C, bool verbose,
Kevin Enderby13023a12015-01-15 23:19:11 +00001476 bool print_offset) {
1477 if (print_offset)
1478 outs() << C.getChildOffset() << "\t";
1479 sys::fs::perms Mode = C.getAccessMode();
1480 if (verbose) {
1481 // FIXME: this first dash, "-", is for (Mode & S_IFMT) == S_IFREG.
1482 // But there is nothing in sys::fs::perms for S_IFMT or S_IFREG.
1483 outs() << "-";
Davide Italianobb9a6cc2015-09-07 20:47:03 +00001484 outs() << ((Mode & sys::fs::owner_read) ? "r" : "-");
1485 outs() << ((Mode & sys::fs::owner_write) ? "w" : "-");
1486 outs() << ((Mode & sys::fs::owner_exe) ? "x" : "-");
1487 outs() << ((Mode & sys::fs::group_read) ? "r" : "-");
1488 outs() << ((Mode & sys::fs::group_write) ? "w" : "-");
1489 outs() << ((Mode & sys::fs::group_exe) ? "x" : "-");
1490 outs() << ((Mode & sys::fs::others_read) ? "r" : "-");
1491 outs() << ((Mode & sys::fs::others_write) ? "w" : "-");
1492 outs() << ((Mode & sys::fs::others_exe) ? "x" : "-");
Kevin Enderby13023a12015-01-15 23:19:11 +00001493 } else {
1494 outs() << format("0%o ", Mode);
1495 }
1496
1497 unsigned UID = C.getUID();
1498 outs() << format("%3d/", UID);
1499 unsigned GID = C.getGID();
1500 outs() << format("%-3d ", GID);
Kevin Enderby7a969422015-11-05 19:24:56 +00001501 ErrorOr<uint64_t> Size = C.getRawSize();
1502 if (std::error_code EC = Size.getError())
1503 report_fatal_error(EC.message());
1504 outs() << format("%5" PRId64, Size.get()) << " ";
Kevin Enderby13023a12015-01-15 23:19:11 +00001505
1506 StringRef RawLastModified = C.getRawLastModified();
1507 if (verbose) {
1508 unsigned Seconds;
1509 if (RawLastModified.getAsInteger(10, Seconds))
1510 outs() << "(date: \"%s\" contains non-decimal chars) " << RawLastModified;
1511 else {
1512 // Since cime(3) returns a 26 character string of the form:
1513 // "Sun Sep 16 01:03:52 1973\n\0"
1514 // just print 24 characters.
1515 time_t t = Seconds;
1516 outs() << format("%.24s ", ctime(&t));
1517 }
1518 } else {
1519 outs() << RawLastModified << " ";
1520 }
1521
1522 if (verbose) {
1523 ErrorOr<StringRef> NameOrErr = C.getName();
1524 if (NameOrErr.getError()) {
1525 StringRef RawName = C.getRawName();
1526 outs() << RawName << "\n";
1527 } else {
1528 StringRef Name = NameOrErr.get();
1529 outs() << Name << "\n";
1530 }
1531 } else {
1532 StringRef RawName = C.getRawName();
1533 outs() << RawName << "\n";
1534 }
1535}
1536
1537static void printArchiveHeaders(Archive *A, bool verbose, bool print_offset) {
Rafael Espindola4a782fb2015-10-31 21:03:29 +00001538 for (Archive::child_iterator I = A->child_begin(false), E = A->child_end();
1539 I != E; ++I) {
Kevin Enderby7a969422015-11-05 19:24:56 +00001540 if (std::error_code EC = I->getError())
1541 report_fatal_error(EC.message());
1542 const Archive::Child &C = **I;
Kevin Enderby13023a12015-01-15 23:19:11 +00001543 printArchiveChild(C, verbose, print_offset);
1544 }
1545}
1546
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001547// ParseInputMachO() parses the named Mach-O file in Filename and handles the
1548// -arch flags selecting just those slices as specified by them and also parses
1549// archive files. Then for each individual Mach-O file ProcessMachO() is
1550// called to process the file based on the command line options.
1551void llvm::ParseInputMachO(StringRef Filename) {
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001552 // Check for -arch all and verifiy the -arch flags are valid.
1553 for (unsigned i = 0; i < ArchFlags.size(); ++i) {
1554 if (ArchFlags[i] == "all") {
1555 ArchAll = true;
1556 } else {
1557 if (!MachOObjectFile::isValidArch(ArchFlags[i])) {
1558 errs() << "llvm-objdump: Unknown architecture named '" + ArchFlags[i] +
1559 "'for the -arch option\n";
1560 return;
1561 }
1562 }
1563 }
1564
1565 // Attempt to open the binary.
Kevin Enderby3fcdf6a2016-04-06 22:14:09 +00001566 Expected<OwningBinary<Binary>> BinaryOrErr = createBinary(Filename);
1567 if (!BinaryOrErr)
1568 report_error(Filename, BinaryOrErr.takeError());
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001569 Binary &Bin = *BinaryOrErr.get().getBinary();
Kevin Enderby3f0ffab2014-12-03 22:29:40 +00001570
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001571 if (Archive *A = dyn_cast<Archive>(&Bin)) {
1572 outs() << "Archive : " << Filename << "\n";
Kevin Enderby13023a12015-01-15 23:19:11 +00001573 if (ArchiveHeaders)
Kevin Enderby8972e482015-04-30 20:30:42 +00001574 printArchiveHeaders(A, !NonVerbose, ArchiveMemberOffsets);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001575 for (Archive::child_iterator I = A->child_begin(), E = A->child_end();
1576 I != E; ++I) {
Davide Italianob13edeb2015-12-08 02:45:59 +00001577 if (std::error_code EC = I->getError())
1578 report_error(Filename, EC);
Kevin Enderby7a969422015-11-05 19:24:56 +00001579 auto &C = I->get();
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 }
1592 return;
1593 }
Kevin Enderby131d1772015-01-09 19:22:37 +00001594 if (UniversalHeaders) {
1595 if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(&Bin))
Kevin Enderbyf0640752015-03-13 17:56:32 +00001596 printMachOUniversalHeaders(UB, !NonVerbose);
Kevin Enderby131d1772015-01-09 19:22:37 +00001597 }
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001598 if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(&Bin)) {
1599 // If we have a list of architecture flags specified dump only those.
1600 if (!ArchAll && ArchFlags.size() != 0) {
1601 // Look for a slice in the universal binary that matches each ArchFlag.
1602 bool ArchFound;
1603 for (unsigned i = 0; i < ArchFlags.size(); ++i) {
1604 ArchFound = false;
1605 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
1606 E = UB->end_objects();
1607 I != E; ++I) {
1608 if (ArchFlags[i] == I->getArchTypeName()) {
1609 ArchFound = true;
Kevin Enderby9acb1092016-05-31 20:35:34 +00001610 Expected<std::unique_ptr<ObjectFile>> ObjOrErr =
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001611 I->getAsObjectFile();
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001612 std::string ArchitectureName = "";
1613 if (ArchFlags.size() > 1)
1614 ArchitectureName = I->getArchTypeName();
1615 if (ObjOrErr) {
1616 ObjectFile &O = *ObjOrErr.get();
1617 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&O))
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001618 ProcessMachO(Filename, MachOOF, "", ArchitectureName);
Kevin Enderby9acb1092016-05-31 20:35:34 +00001619 } else if (auto E = isNotObjectErrorInvalidFileType(
1620 ObjOrErr.takeError())) {
1621 report_error(Filename, StringRef(), std::move(E),
1622 ArchitectureName);
1623 continue;
Rafael Espindola0bfe8282014-12-09 21:05:36 +00001624 } else if (ErrorOr<std::unique_ptr<Archive>> AOrErr =
1625 I->getAsArchive()) {
1626 std::unique_ptr<Archive> &A = *AOrErr;
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001627 outs() << "Archive : " << Filename;
1628 if (!ArchitectureName.empty())
1629 outs() << " (architecture " << ArchitectureName << ")";
1630 outs() << "\n";
Kevin Enderby13023a12015-01-15 23:19:11 +00001631 if (ArchiveHeaders)
Kevin Enderby8972e482015-04-30 20:30:42 +00001632 printArchiveHeaders(A.get(), !NonVerbose, ArchiveMemberOffsets);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001633 for (Archive::child_iterator AI = A->child_begin(),
1634 AE = A->child_end();
1635 AI != AE; ++AI) {
Davide Italianob13edeb2015-12-08 02:45:59 +00001636 if (std::error_code EC = AI->getError())
1637 report_error(Filename, EC);
Kevin Enderby7a969422015-11-05 19:24:56 +00001638 auto &C = AI->get();
Kevin Enderbyac9e1552016-05-17 17:10:12 +00001639 Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
1640 if (!ChildOrErr) {
1641 if (auto E = isNotObjectErrorInvalidFileType(ChildOrErr.takeError()))
Kevin Enderby9acb1092016-05-31 20:35:34 +00001642 report_error(Filename, C, std::move(E), ArchitectureName);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001643 continue;
Kevin Enderbyac9e1552016-05-17 17:10:12 +00001644 }
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001645 if (MachOObjectFile *O =
1646 dyn_cast<MachOObjectFile>(&*ChildOrErr.get()))
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001647 ProcessMachO(Filename, O, O->getFileName(), ArchitectureName);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001648 }
1649 }
1650 }
1651 }
1652 if (!ArchFound) {
1653 errs() << "llvm-objdump: file: " + Filename + " does not contain "
1654 << "architecture: " + ArchFlags[i] + "\n";
1655 return;
1656 }
1657 }
1658 return;
1659 }
1660 // No architecture flags were specified so if this contains a slice that
1661 // matches the host architecture dump only that.
1662 if (!ArchAll) {
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001663 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
1664 E = UB->end_objects();
1665 I != E; ++I) {
Kevin Enderby0512bd72015-01-09 21:55:03 +00001666 if (MachOObjectFile::getHostArch().getArchName() ==
1667 I->getArchTypeName()) {
Kevin Enderby9acb1092016-05-31 20:35:34 +00001668 Expected<std::unique_ptr<ObjectFile>> ObjOrErr = I->getAsObjectFile();
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001669 std::string ArchiveName;
1670 ArchiveName.clear();
1671 if (ObjOrErr) {
1672 ObjectFile &O = *ObjOrErr.get();
1673 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&O))
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001674 ProcessMachO(Filename, MachOOF);
Kevin Enderby9acb1092016-05-31 20:35:34 +00001675 } else if (auto E = isNotObjectErrorInvalidFileType(
1676 ObjOrErr.takeError())) {
1677 report_error(Filename, std::move(E));
1678 continue;
Rafael Espindola0bfe8282014-12-09 21:05:36 +00001679 } else if (ErrorOr<std::unique_ptr<Archive>> AOrErr =
1680 I->getAsArchive()) {
1681 std::unique_ptr<Archive> &A = *AOrErr;
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001682 outs() << "Archive : " << Filename << "\n";
Kevin Enderby13023a12015-01-15 23:19:11 +00001683 if (ArchiveHeaders)
Kevin Enderby8972e482015-04-30 20:30:42 +00001684 printArchiveHeaders(A.get(), !NonVerbose, ArchiveMemberOffsets);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001685 for (Archive::child_iterator AI = A->child_begin(),
1686 AE = A->child_end();
1687 AI != AE; ++AI) {
Davide Italianob13edeb2015-12-08 02:45:59 +00001688 if (std::error_code EC = AI->getError())
1689 report_error(Filename, EC);
Kevin Enderby7a969422015-11-05 19:24:56 +00001690 auto &C = AI->get();
Kevin Enderbyac9e1552016-05-17 17:10:12 +00001691 Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
1692 if (!ChildOrErr) {
1693 if (auto E = isNotObjectErrorInvalidFileType(ChildOrErr.takeError()))
1694 report_error(Filename, C, std::move(E));
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001695 continue;
Kevin Enderbyac9e1552016-05-17 17:10:12 +00001696 }
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001697 if (MachOObjectFile *O =
1698 dyn_cast<MachOObjectFile>(&*ChildOrErr.get()))
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001699 ProcessMachO(Filename, O, O->getFileName());
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001700 }
1701 }
1702 return;
1703 }
1704 }
1705 }
1706 // Either all architectures have been specified or none have been specified
1707 // and this does not contain the host architecture so dump all the slices.
1708 bool moreThanOneArch = UB->getNumberOfObjects() > 1;
1709 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
1710 E = UB->end_objects();
1711 I != E; ++I) {
Kevin Enderby9acb1092016-05-31 20:35:34 +00001712 Expected<std::unique_ptr<ObjectFile>> ObjOrErr = I->getAsObjectFile();
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001713 std::string ArchitectureName = "";
1714 if (moreThanOneArch)
1715 ArchitectureName = I->getArchTypeName();
1716 if (ObjOrErr) {
1717 ObjectFile &Obj = *ObjOrErr.get();
1718 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&Obj))
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001719 ProcessMachO(Filename, MachOOF, "", ArchitectureName);
Kevin Enderby9acb1092016-05-31 20:35:34 +00001720 } else if (auto E = isNotObjectErrorInvalidFileType(
1721 ObjOrErr.takeError())) {
1722 report_error(StringRef(), Filename, std::move(E), ArchitectureName);
1723 continue;
Rafael Espindola0bfe8282014-12-09 21:05:36 +00001724 } else if (ErrorOr<std::unique_ptr<Archive>> AOrErr = I->getAsArchive()) {
1725 std::unique_ptr<Archive> &A = *AOrErr;
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001726 outs() << "Archive : " << Filename;
1727 if (!ArchitectureName.empty())
1728 outs() << " (architecture " << ArchitectureName << ")";
1729 outs() << "\n";
Kevin Enderby13023a12015-01-15 23:19:11 +00001730 if (ArchiveHeaders)
Kevin Enderby8972e482015-04-30 20:30:42 +00001731 printArchiveHeaders(A.get(), !NonVerbose, ArchiveMemberOffsets);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001732 for (Archive::child_iterator AI = A->child_begin(), AE = A->child_end();
1733 AI != AE; ++AI) {
Davide Italianob13edeb2015-12-08 02:45:59 +00001734 if (std::error_code EC = AI->getError())
1735 report_error(Filename, EC);
Kevin Enderby7a969422015-11-05 19:24:56 +00001736 auto &C = AI->get();
Kevin Enderbyac9e1552016-05-17 17:10:12 +00001737 Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
1738 if (!ChildOrErr) {
1739 if (auto E = isNotObjectErrorInvalidFileType(ChildOrErr.takeError()))
Kevin Enderby9acb1092016-05-31 20:35:34 +00001740 report_error(Filename, C, std::move(E), ArchitectureName);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001741 continue;
Kevin Enderbyac9e1552016-05-17 17:10:12 +00001742 }
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001743 if (MachOObjectFile *O =
1744 dyn_cast<MachOObjectFile>(&*ChildOrErr.get())) {
1745 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(O))
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001746 ProcessMachO(Filename, MachOOF, MachOOF->getFileName(),
1747 ArchitectureName);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001748 }
1749 }
1750 }
1751 }
1752 return;
1753 }
1754 if (ObjectFile *O = dyn_cast<ObjectFile>(&Bin)) {
1755 if (!checkMachOAndArchFlags(O, Filename))
1756 return;
1757 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&*O)) {
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001758 ProcessMachO(Filename, MachOOF);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001759 } else
1760 errs() << "llvm-objdump: '" << Filename << "': "
1761 << "Object is not a Mach-O file type.\n";
Davide Italiano25d84582016-01-13 04:11:36 +00001762 return;
1763 }
1764 llvm_unreachable("Input object can't be invalid at this point");
Rafael Espindola9b709252013-04-13 01:45:40 +00001765}
1766
Kevin Enderby6f326ce2014-10-23 19:37:31 +00001767typedef std::pair<uint64_t, const char *> BindInfoEntry;
1768typedef std::vector<BindInfoEntry> BindTable;
1769typedef BindTable::iterator bind_table_iterator;
Kevin Enderbybf246f52014-09-24 23:08:22 +00001770
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001771// The block of info used by the Symbolizer call backs.
1772struct DisassembleInfo {
1773 bool verbose;
1774 MachOObjectFile *O;
1775 SectionRef S;
Kevin Enderbybf246f52014-09-24 23:08:22 +00001776 SymbolAddressMap *AddrMap;
Kevin Enderby6f326ce2014-10-23 19:37:31 +00001777 std::vector<SectionRef> *Sections;
1778 const char *class_name;
1779 const char *selector_name;
1780 char *method;
Kevin Enderby04bf6932014-10-28 23:39:46 +00001781 char *demangled_name;
Kevin Enderbyae3c1262014-11-14 21:52:18 +00001782 uint64_t adrp_addr;
1783 uint32_t adrp_inst;
Kevin Enderby078be602014-10-23 19:53:12 +00001784 BindTable *bindtable;
Kevin Enderbyaac75382015-10-08 16:56:35 +00001785 uint32_t depth;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001786};
1787
1788// SymbolizerGetOpInfo() is the operand information call back function.
1789// This is called to get the symbolic information for operand(s) of an
1790// instruction when it is being done. This routine does this from
1791// the relocation information, symbol table, etc. That block of information
1792// is a pointer to the struct DisassembleInfo that was passed when the
1793// disassembler context was created and passed to back to here when
1794// called back by the disassembler for instruction operands that could have
1795// relocation information. The address of the instruction containing operand is
1796// at the Pc parameter. The immediate value the operand has is passed in
1797// op_info->Value and is at Offset past the start of the instruction and has a
1798// byte Size of 1, 2 or 4. The symbolc information is returned in TagBuf is the
1799// LLVMOpInfo1 struct defined in the header "llvm-c/Disassembler.h" as symbol
1800// names and addends of the symbolic expression to add for the operand. The
1801// value of TagType is currently 1 (for the LLVMOpInfo1 struct). If symbolic
1802// information is returned then this function returns 1 else it returns 0.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00001803static int SymbolizerGetOpInfo(void *DisInfo, uint64_t Pc, uint64_t Offset,
1804 uint64_t Size, int TagType, void *TagBuf) {
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001805 struct DisassembleInfo *info = (struct DisassembleInfo *)DisInfo;
1806 struct LLVMOpInfo1 *op_info = (struct LLVMOpInfo1 *)TagBuf;
Kevin Enderbyae3c1262014-11-14 21:52:18 +00001807 uint64_t value = op_info->Value;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001808
1809 // Make sure all fields returned are zero if we don't set them.
1810 memset((void *)op_info, '\0', sizeof(struct LLVMOpInfo1));
1811 op_info->Value = value;
1812
1813 // If the TagType is not the value 1 which it code knows about or if no
1814 // verbose symbolic information is wanted then just return 0, indicating no
1815 // information is being returned.
David Blaikie33dd45d02015-03-23 18:39:02 +00001816 if (TagType != 1 || !info->verbose)
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001817 return 0;
1818
1819 unsigned int Arch = info->O->getArch();
1820 if (Arch == Triple::x86) {
Kevin Enderby9907d0a2014-11-04 00:43:16 +00001821 if (Size != 1 && Size != 2 && Size != 4 && Size != 0)
1822 return 0;
Kevin Enderbyd90a4172015-10-10 00:05:01 +00001823 if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
1824 // TODO:
1825 // Search the external relocation entries of a fully linked image
1826 // (if any) for an entry that matches this segment offset.
1827 // uint32_t seg_offset = (Pc + Offset);
1828 return 0;
1829 }
1830 // In MH_OBJECT filetypes search the section's relocation entries (if any)
1831 // for an entry for this section offset.
Kevin Enderby9907d0a2014-11-04 00:43:16 +00001832 uint32_t sect_addr = info->S.getAddress();
1833 uint32_t sect_offset = (Pc + Offset) - sect_addr;
1834 bool reloc_found = false;
1835 DataRefImpl Rel;
1836 MachO::any_relocation_info RE;
1837 bool isExtern = false;
1838 SymbolRef Symbol;
1839 bool r_scattered = false;
1840 uint32_t r_value, pair_r_value, r_type;
1841 for (const RelocationRef &Reloc : info->S.relocations()) {
Rafael Espindola96d071c2015-06-29 23:29:12 +00001842 uint64_t RelocOffset = Reloc.getOffset();
Kevin Enderby9907d0a2014-11-04 00:43:16 +00001843 if (RelocOffset == sect_offset) {
1844 Rel = Reloc.getRawDataRefImpl();
1845 RE = info->O->getRelocation(Rel);
Kevin Enderby3eb73e12014-11-11 19:16:45 +00001846 r_type = info->O->getAnyRelocationType(RE);
Kevin Enderby9907d0a2014-11-04 00:43:16 +00001847 r_scattered = info->O->isRelocationScattered(RE);
1848 if (r_scattered) {
1849 r_value = info->O->getScatteredRelocationValue(RE);
Kevin Enderby9907d0a2014-11-04 00:43:16 +00001850 if (r_type == MachO::GENERIC_RELOC_SECTDIFF ||
1851 r_type == MachO::GENERIC_RELOC_LOCAL_SECTDIFF) {
1852 DataRefImpl RelNext = Rel;
1853 info->O->moveRelocationNext(RelNext);
1854 MachO::any_relocation_info RENext;
1855 RENext = info->O->getRelocation(RelNext);
1856 if (info->O->isRelocationScattered(RENext))
Kevin Enderby930fdc72014-11-06 19:00:13 +00001857 pair_r_value = info->O->getScatteredRelocationValue(RENext);
Kevin Enderby9907d0a2014-11-04 00:43:16 +00001858 else
1859 return 0;
1860 }
1861 } else {
1862 isExtern = info->O->getPlainRelocationExternal(RE);
1863 if (isExtern) {
1864 symbol_iterator RelocSym = Reloc.getSymbol();
1865 Symbol = *RelocSym;
1866 }
1867 }
1868 reloc_found = true;
1869 break;
1870 }
1871 }
1872 if (reloc_found && isExtern) {
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00001873 Expected<StringRef> SymName = Symbol.getName();
1874 if (!SymName) {
1875 std::string Buf;
1876 raw_string_ostream OS(Buf);
1877 logAllUnhandledErrors(SymName.takeError(), OS, "");
1878 OS.flush();
1879 report_fatal_error(Buf);
1880 }
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00001881 const char *name = SymName->data();
Kevin Enderby9907d0a2014-11-04 00:43:16 +00001882 op_info->AddSymbol.Present = 1;
1883 op_info->AddSymbol.Name = name;
1884 // For i386 extern relocation entries the value in the instruction is
1885 // the offset from the symbol, and value is already set in op_info->Value.
1886 return 1;
1887 }
1888 if (reloc_found && (r_type == MachO::GENERIC_RELOC_SECTDIFF ||
1889 r_type == MachO::GENERIC_RELOC_LOCAL_SECTDIFF)) {
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001890 const char *add = GuessSymbolName(r_value, info->AddrMap);
1891 const char *sub = GuessSymbolName(pair_r_value, info->AddrMap);
Kevin Enderby9907d0a2014-11-04 00:43:16 +00001892 uint32_t offset = value - (r_value - pair_r_value);
1893 op_info->AddSymbol.Present = 1;
1894 if (add != nullptr)
1895 op_info->AddSymbol.Name = add;
1896 else
1897 op_info->AddSymbol.Value = r_value;
1898 op_info->SubtractSymbol.Present = 1;
1899 if (sub != nullptr)
1900 op_info->SubtractSymbol.Name = sub;
1901 else
1902 op_info->SubtractSymbol.Value = pair_r_value;
1903 op_info->Value = offset;
1904 return 1;
1905 }
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001906 return 0;
David Blaikie33dd45d02015-03-23 18:39:02 +00001907 }
1908 if (Arch == Triple::x86_64) {
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001909 if (Size != 1 && Size != 2 && Size != 4 && Size != 0)
1910 return 0;
Kevin Enderbyd90a4172015-10-10 00:05:01 +00001911 if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
1912 // TODO:
1913 // Search the external relocation entries of a fully linked image
1914 // (if any) for an entry that matches this segment offset.
1915 // uint64_t seg_offset = (Pc + Offset);
1916 return 0;
1917 }
1918 // In MH_OBJECT filetypes search the section's relocation entries (if any)
1919 // for an entry for this section offset.
Rafael Espindola80291272014-10-08 15:28:58 +00001920 uint64_t sect_addr = info->S.getAddress();
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001921 uint64_t sect_offset = (Pc + Offset) - sect_addr;
1922 bool reloc_found = false;
1923 DataRefImpl Rel;
1924 MachO::any_relocation_info RE;
1925 bool isExtern = false;
1926 SymbolRef Symbol;
1927 for (const RelocationRef &Reloc : info->S.relocations()) {
Rafael Espindola96d071c2015-06-29 23:29:12 +00001928 uint64_t RelocOffset = Reloc.getOffset();
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001929 if (RelocOffset == sect_offset) {
1930 Rel = Reloc.getRawDataRefImpl();
1931 RE = info->O->getRelocation(Rel);
1932 // NOTE: Scattered relocations don't exist on x86_64.
1933 isExtern = info->O->getPlainRelocationExternal(RE);
1934 if (isExtern) {
1935 symbol_iterator RelocSym = Reloc.getSymbol();
1936 Symbol = *RelocSym;
1937 }
1938 reloc_found = true;
1939 break;
1940 }
1941 }
1942 if (reloc_found && isExtern) {
1943 // The Value passed in will be adjusted by the Pc if the instruction
1944 // adds the Pc. But for x86_64 external relocation entries the Value
1945 // is the offset from the external symbol.
1946 if (info->O->getAnyRelocationPCRel(RE))
1947 op_info->Value -= Pc + Offset + Size;
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00001948 Expected<StringRef> SymName = Symbol.getName();
1949 if (!SymName) {
1950 std::string Buf;
1951 raw_string_ostream OS(Buf);
1952 logAllUnhandledErrors(SymName.takeError(), OS, "");
1953 OS.flush();
1954 report_fatal_error(Buf);
1955 }
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00001956 const char *name = SymName->data();
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001957 unsigned Type = info->O->getAnyRelocationType(RE);
1958 if (Type == MachO::X86_64_RELOC_SUBTRACTOR) {
1959 DataRefImpl RelNext = Rel;
1960 info->O->moveRelocationNext(RelNext);
1961 MachO::any_relocation_info RENext = info->O->getRelocation(RelNext);
1962 unsigned TypeNext = info->O->getAnyRelocationType(RENext);
1963 bool isExternNext = info->O->getPlainRelocationExternal(RENext);
1964 unsigned SymbolNum = info->O->getPlainRelocationSymbolNum(RENext);
1965 if (TypeNext == MachO::X86_64_RELOC_UNSIGNED && isExternNext) {
1966 op_info->SubtractSymbol.Present = 1;
1967 op_info->SubtractSymbol.Name = name;
1968 symbol_iterator RelocSymNext = info->O->getSymbolByIndex(SymbolNum);
1969 Symbol = *RelocSymNext;
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00001970 Expected<StringRef> SymNameNext = Symbol.getName();
1971 if (!SymNameNext) {
1972 std::string Buf;
1973 raw_string_ostream OS(Buf);
1974 logAllUnhandledErrors(SymNameNext.takeError(), OS, "");
1975 OS.flush();
1976 report_fatal_error(Buf);
1977 }
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00001978 name = SymNameNext->data();
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001979 }
1980 }
1981 // TODO: add the VariantKinds to op_info->VariantKind for relocation types
1982 // like: X86_64_RELOC_TLV, X86_64_RELOC_GOT_LOAD and X86_64_RELOC_GOT.
1983 op_info->AddSymbol.Present = 1;
1984 op_info->AddSymbol.Name = name;
1985 return 1;
1986 }
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001987 return 0;
David Blaikie33dd45d02015-03-23 18:39:02 +00001988 }
1989 if (Arch == Triple::arm) {
Kevin Enderby930fdc72014-11-06 19:00:13 +00001990 if (Offset != 0 || (Size != 4 && Size != 2))
1991 return 0;
Kevin Enderbyd90a4172015-10-10 00:05:01 +00001992 if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
1993 // TODO:
1994 // Search the external relocation entries of a fully linked image
1995 // (if any) for an entry that matches this segment offset.
1996 // uint32_t seg_offset = (Pc + Offset);
1997 return 0;
1998 }
1999 // In MH_OBJECT filetypes search the section's relocation entries (if any)
2000 // for an entry for this section offset.
Kevin Enderby930fdc72014-11-06 19:00:13 +00002001 uint32_t sect_addr = info->S.getAddress();
2002 uint32_t sect_offset = (Pc + Offset) - sect_addr;
Kevin Enderby930fdc72014-11-06 19:00:13 +00002003 DataRefImpl Rel;
2004 MachO::any_relocation_info RE;
2005 bool isExtern = false;
2006 SymbolRef Symbol;
2007 bool r_scattered = false;
2008 uint32_t r_value, pair_r_value, r_type, r_length, other_half;
David Blaikie33dd45d02015-03-23 18:39:02 +00002009 auto Reloc =
2010 std::find_if(info->S.relocations().begin(), info->S.relocations().end(),
2011 [&](const RelocationRef &Reloc) {
Rafael Espindola96d071c2015-06-29 23:29:12 +00002012 uint64_t RelocOffset = Reloc.getOffset();
David Blaikie33dd45d02015-03-23 18:39:02 +00002013 return RelocOffset == sect_offset;
2014 });
2015
2016 if (Reloc == info->S.relocations().end())
2017 return 0;
2018
2019 Rel = Reloc->getRawDataRefImpl();
2020 RE = info->O->getRelocation(Rel);
2021 r_length = info->O->getAnyRelocationLength(RE);
2022 r_scattered = info->O->isRelocationScattered(RE);
2023 if (r_scattered) {
2024 r_value = info->O->getScatteredRelocationValue(RE);
2025 r_type = info->O->getScatteredRelocationType(RE);
2026 } else {
2027 r_type = info->O->getAnyRelocationType(RE);
2028 isExtern = info->O->getPlainRelocationExternal(RE);
2029 if (isExtern) {
2030 symbol_iterator RelocSym = Reloc->getSymbol();
2031 Symbol = *RelocSym;
Kevin Enderby930fdc72014-11-06 19:00:13 +00002032 }
2033 }
David Blaikie33dd45d02015-03-23 18:39:02 +00002034 if (r_type == MachO::ARM_RELOC_HALF ||
2035 r_type == MachO::ARM_RELOC_SECTDIFF ||
2036 r_type == MachO::ARM_RELOC_LOCAL_SECTDIFF ||
2037 r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
2038 DataRefImpl RelNext = Rel;
2039 info->O->moveRelocationNext(RelNext);
2040 MachO::any_relocation_info RENext;
2041 RENext = info->O->getRelocation(RelNext);
2042 other_half = info->O->getAnyRelocationAddress(RENext) & 0xffff;
2043 if (info->O->isRelocationScattered(RENext))
2044 pair_r_value = info->O->getScatteredRelocationValue(RENext);
2045 }
2046
2047 if (isExtern) {
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00002048 Expected<StringRef> SymName = Symbol.getName();
2049 if (!SymName) {
2050 std::string Buf;
2051 raw_string_ostream OS(Buf);
2052 logAllUnhandledErrors(SymName.takeError(), OS, "");
2053 OS.flush();
2054 report_fatal_error(Buf);
2055 }
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00002056 const char *name = SymName->data();
Kevin Enderby930fdc72014-11-06 19:00:13 +00002057 op_info->AddSymbol.Present = 1;
2058 op_info->AddSymbol.Name = name;
Sylvestre Ledru648cced2015-02-05 17:00:23 +00002059 switch (r_type) {
2060 case MachO::ARM_RELOC_HALF:
2061 if ((r_length & 0x1) == 1) {
2062 op_info->Value = value << 16 | other_half;
2063 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
2064 } else {
2065 op_info->Value = other_half << 16 | value;
2066 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
Sylvestre Ledrufe0c7ad2015-02-05 16:35:44 +00002067 }
Sylvestre Ledru648cced2015-02-05 17:00:23 +00002068 break;
2069 default:
2070 break;
Kevin Enderby930fdc72014-11-06 19:00:13 +00002071 }
2072 return 1;
2073 }
2074 // If we have a branch that is not an external relocation entry then
2075 // return 0 so the code in tryAddingSymbolicOperand() can use the
2076 // SymbolLookUp call back with the branch target address to look up the
2077 // symbol and possiblity add an annotation for a symbol stub.
David Blaikie33dd45d02015-03-23 18:39:02 +00002078 if (isExtern == 0 && (r_type == MachO::ARM_RELOC_BR24 ||
2079 r_type == MachO::ARM_THUMB_RELOC_BR22))
Kevin Enderby930fdc72014-11-06 19:00:13 +00002080 return 0;
2081
2082 uint32_t offset = 0;
David Blaikie33dd45d02015-03-23 18:39:02 +00002083 if (r_type == MachO::ARM_RELOC_HALF ||
2084 r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
2085 if ((r_length & 0x1) == 1)
2086 value = value << 16 | other_half;
2087 else
2088 value = other_half << 16 | value;
2089 }
2090 if (r_scattered && (r_type != MachO::ARM_RELOC_HALF &&
2091 r_type != MachO::ARM_RELOC_HALF_SECTDIFF)) {
2092 offset = value - r_value;
2093 value = r_value;
Kevin Enderby930fdc72014-11-06 19:00:13 +00002094 }
2095
David Blaikie33dd45d02015-03-23 18:39:02 +00002096 if (r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
Kevin Enderby930fdc72014-11-06 19:00:13 +00002097 if ((r_length & 0x1) == 1)
2098 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
2099 else
2100 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
Kevin Enderbyf6d25852015-01-31 00:37:11 +00002101 const char *add = GuessSymbolName(r_value, info->AddrMap);
2102 const char *sub = GuessSymbolName(pair_r_value, info->AddrMap);
Kevin Enderby930fdc72014-11-06 19:00:13 +00002103 int32_t offset = value - (r_value - pair_r_value);
2104 op_info->AddSymbol.Present = 1;
2105 if (add != nullptr)
2106 op_info->AddSymbol.Name = add;
2107 else
2108 op_info->AddSymbol.Value = r_value;
2109 op_info->SubtractSymbol.Present = 1;
2110 if (sub != nullptr)
2111 op_info->SubtractSymbol.Name = sub;
2112 else
2113 op_info->SubtractSymbol.Value = pair_r_value;
2114 op_info->Value = offset;
2115 return 1;
2116 }
2117
Kevin Enderby930fdc72014-11-06 19:00:13 +00002118 op_info->AddSymbol.Present = 1;
2119 op_info->Value = offset;
David Blaikie33dd45d02015-03-23 18:39:02 +00002120 if (r_type == MachO::ARM_RELOC_HALF) {
2121 if ((r_length & 0x1) == 1)
2122 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
2123 else
2124 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
Kevin Enderby930fdc72014-11-06 19:00:13 +00002125 }
Kevin Enderbyf6d25852015-01-31 00:37:11 +00002126 const char *add = GuessSymbolName(value, info->AddrMap);
Kevin Enderby930fdc72014-11-06 19:00:13 +00002127 if (add != nullptr) {
2128 op_info->AddSymbol.Name = add;
2129 return 1;
2130 }
2131 op_info->AddSymbol.Value = value;
2132 return 1;
David Blaikie33dd45d02015-03-23 18:39:02 +00002133 }
2134 if (Arch == Triple::aarch64) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002135 if (Offset != 0 || Size != 4)
2136 return 0;
Kevin Enderbyd90a4172015-10-10 00:05:01 +00002137 if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
2138 // TODO:
2139 // Search the external relocation entries of a fully linked image
2140 // (if any) for an entry that matches this segment offset.
2141 // uint64_t seg_offset = (Pc + Offset);
2142 return 0;
2143 }
2144 // In MH_OBJECT filetypes search the section's relocation entries (if any)
2145 // for an entry for this section offset.
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002146 uint64_t sect_addr = info->S.getAddress();
2147 uint64_t sect_offset = (Pc + Offset) - sect_addr;
David Blaikie33dd45d02015-03-23 18:39:02 +00002148 auto Reloc =
2149 std::find_if(info->S.relocations().begin(), info->S.relocations().end(),
2150 [&](const RelocationRef &Reloc) {
Rafael Espindola96d071c2015-06-29 23:29:12 +00002151 uint64_t RelocOffset = Reloc.getOffset();
David Blaikie33dd45d02015-03-23 18:39:02 +00002152 return RelocOffset == sect_offset;
2153 });
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002154
David Blaikie33dd45d02015-03-23 18:39:02 +00002155 if (Reloc == info->S.relocations().end())
2156 return 0;
2157
2158 DataRefImpl Rel = Reloc->getRawDataRefImpl();
2159 MachO::any_relocation_info RE = info->O->getRelocation(Rel);
2160 uint32_t r_type = info->O->getAnyRelocationType(RE);
2161 if (r_type == MachO::ARM64_RELOC_ADDEND) {
2162 DataRefImpl RelNext = Rel;
2163 info->O->moveRelocationNext(RelNext);
2164 MachO::any_relocation_info RENext = info->O->getRelocation(RelNext);
2165 if (value == 0) {
2166 value = info->O->getPlainRelocationSymbolNum(RENext);
2167 op_info->Value = value;
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002168 }
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002169 }
David Blaikie33dd45d02015-03-23 18:39:02 +00002170 // NOTE: Scattered relocations don't exist on arm64.
2171 if (!info->O->getPlainRelocationExternal(RE))
2172 return 0;
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00002173 Expected<StringRef> SymName = Reloc->getSymbol()->getName();
2174 if (!SymName) {
2175 std::string Buf;
2176 raw_string_ostream OS(Buf);
2177 logAllUnhandledErrors(SymName.takeError(), OS, "");
2178 OS.flush();
2179 report_fatal_error(Buf);
2180 }
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00002181 const char *name = SymName->data();
David Blaikie33dd45d02015-03-23 18:39:02 +00002182 op_info->AddSymbol.Present = 1;
2183 op_info->AddSymbol.Name = name;
2184
2185 switch (r_type) {
2186 case MachO::ARM64_RELOC_PAGE21:
2187 /* @page */
2188 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_PAGE;
2189 break;
2190 case MachO::ARM64_RELOC_PAGEOFF12:
2191 /* @pageoff */
2192 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_PAGEOFF;
2193 break;
2194 case MachO::ARM64_RELOC_GOT_LOAD_PAGE21:
2195 /* @gotpage */
2196 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_GOTPAGE;
2197 break;
2198 case MachO::ARM64_RELOC_GOT_LOAD_PAGEOFF12:
2199 /* @gotpageoff */
2200 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_GOTPAGEOFF;
2201 break;
2202 case MachO::ARM64_RELOC_TLVP_LOAD_PAGE21:
2203 /* @tvlppage is not implemented in llvm-mc */
2204 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_TLVP;
2205 break;
2206 case MachO::ARM64_RELOC_TLVP_LOAD_PAGEOFF12:
2207 /* @tvlppageoff is not implemented in llvm-mc */
2208 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_TLVOFF;
2209 break;
2210 default:
2211 case MachO::ARM64_RELOC_BRANCH26:
2212 op_info->VariantKind = LLVMDisassembler_VariantKind_None;
2213 break;
2214 }
2215 return 1;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002216 }
David Blaikie33dd45d02015-03-23 18:39:02 +00002217 return 0;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002218}
2219
Kevin Enderbybf246f52014-09-24 23:08:22 +00002220// GuessCstringPointer is passed the address of what might be a pointer to a
2221// literal string in a cstring section. If that address is in a cstring section
2222// it returns a pointer to that string. Else it returns nullptr.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00002223static const char *GuessCstringPointer(uint64_t ReferenceValue,
2224 struct DisassembleInfo *info) {
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00002225 for (const auto &Load : info->O->load_commands()) {
Kevin Enderbybf246f52014-09-24 23:08:22 +00002226 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
2227 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
2228 for (unsigned J = 0; J < Seg.nsects; ++J) {
2229 MachO::section_64 Sec = info->O->getSection64(Load, J);
2230 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
2231 if (section_type == MachO::S_CSTRING_LITERALS &&
2232 ReferenceValue >= Sec.addr &&
2233 ReferenceValue < Sec.addr + Sec.size) {
2234 uint64_t sect_offset = ReferenceValue - Sec.addr;
2235 uint64_t object_offset = Sec.offset + sect_offset;
2236 StringRef MachOContents = info->O->getData();
2237 uint64_t object_size = MachOContents.size();
2238 const char *object_addr = (const char *)MachOContents.data();
2239 if (object_offset < object_size) {
2240 const char *name = object_addr + object_offset;
2241 return name;
2242 } else {
2243 return nullptr;
2244 }
2245 }
2246 }
2247 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
2248 MachO::segment_command Seg = info->O->getSegmentLoadCommand(Load);
2249 for (unsigned J = 0; J < Seg.nsects; ++J) {
2250 MachO::section Sec = info->O->getSection(Load, J);
2251 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
2252 if (section_type == MachO::S_CSTRING_LITERALS &&
2253 ReferenceValue >= Sec.addr &&
2254 ReferenceValue < Sec.addr + Sec.size) {
2255 uint64_t sect_offset = ReferenceValue - Sec.addr;
2256 uint64_t object_offset = Sec.offset + sect_offset;
2257 StringRef MachOContents = info->O->getData();
2258 uint64_t object_size = MachOContents.size();
2259 const char *object_addr = (const char *)MachOContents.data();
2260 if (object_offset < object_size) {
2261 const char *name = object_addr + object_offset;
2262 return name;
2263 } else {
2264 return nullptr;
2265 }
2266 }
2267 }
2268 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00002269 }
2270 return nullptr;
2271}
2272
Kevin Enderby85974882014-09-26 22:20:44 +00002273// GuessIndirectSymbol returns the name of the indirect symbol for the
2274// ReferenceValue passed in or nullptr. This is used when ReferenceValue maybe
2275// an address of a symbol stub or a lazy or non-lazy pointer to associate the
2276// symbol name being referenced by the stub or pointer.
2277static const char *GuessIndirectSymbol(uint64_t ReferenceValue,
2278 struct DisassembleInfo *info) {
Kevin Enderby85974882014-09-26 22:20:44 +00002279 MachO::dysymtab_command Dysymtab = info->O->getDysymtabLoadCommand();
2280 MachO::symtab_command Symtab = info->O->getSymtabLoadCommand();
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00002281 for (const auto &Load : info->O->load_commands()) {
Kevin Enderby85974882014-09-26 22:20:44 +00002282 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
2283 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
2284 for (unsigned J = 0; J < Seg.nsects; ++J) {
2285 MachO::section_64 Sec = info->O->getSection64(Load, J);
2286 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
2287 if ((section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
2288 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
2289 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
2290 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
2291 section_type == MachO::S_SYMBOL_STUBS) &&
2292 ReferenceValue >= Sec.addr &&
2293 ReferenceValue < Sec.addr + Sec.size) {
2294 uint32_t stride;
2295 if (section_type == MachO::S_SYMBOL_STUBS)
2296 stride = Sec.reserved2;
2297 else
2298 stride = 8;
2299 if (stride == 0)
2300 return nullptr;
2301 uint32_t index = Sec.reserved1 + (ReferenceValue - Sec.addr) / stride;
2302 if (index < Dysymtab.nindirectsyms) {
2303 uint32_t indirect_symbol =
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002304 info->O->getIndirectSymbolTableEntry(Dysymtab, index);
Kevin Enderby85974882014-09-26 22:20:44 +00002305 if (indirect_symbol < Symtab.nsyms) {
2306 symbol_iterator Sym = info->O->getSymbolByIndex(indirect_symbol);
2307 SymbolRef Symbol = *Sym;
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00002308 Expected<StringRef> SymName = Symbol.getName();
2309 if (!SymName) {
2310 std::string Buf;
2311 raw_string_ostream OS(Buf);
2312 logAllUnhandledErrors(SymName.takeError(), OS, "");
2313 OS.flush();
2314 report_fatal_error(Buf);
2315 }
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00002316 const char *name = SymName->data();
Kevin Enderby85974882014-09-26 22:20:44 +00002317 return name;
2318 }
2319 }
2320 }
2321 }
2322 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
2323 MachO::segment_command Seg = info->O->getSegmentLoadCommand(Load);
2324 for (unsigned J = 0; J < Seg.nsects; ++J) {
2325 MachO::section Sec = info->O->getSection(Load, J);
2326 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
2327 if ((section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
2328 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
2329 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
2330 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
2331 section_type == MachO::S_SYMBOL_STUBS) &&
2332 ReferenceValue >= Sec.addr &&
2333 ReferenceValue < Sec.addr + Sec.size) {
2334 uint32_t stride;
2335 if (section_type == MachO::S_SYMBOL_STUBS)
2336 stride = Sec.reserved2;
2337 else
2338 stride = 4;
2339 if (stride == 0)
2340 return nullptr;
2341 uint32_t index = Sec.reserved1 + (ReferenceValue - Sec.addr) / stride;
2342 if (index < Dysymtab.nindirectsyms) {
2343 uint32_t indirect_symbol =
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002344 info->O->getIndirectSymbolTableEntry(Dysymtab, index);
Kevin Enderby85974882014-09-26 22:20:44 +00002345 if (indirect_symbol < Symtab.nsyms) {
2346 symbol_iterator Sym = info->O->getSymbolByIndex(indirect_symbol);
2347 SymbolRef Symbol = *Sym;
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00002348 Expected<StringRef> SymName = Symbol.getName();
2349 if (!SymName) {
2350 std::string Buf;
2351 raw_string_ostream OS(Buf);
2352 logAllUnhandledErrors(SymName.takeError(), OS, "");
2353 OS.flush();
2354 report_fatal_error(Buf);
2355 }
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00002356 const char *name = SymName->data();
Kevin Enderby85974882014-09-26 22:20:44 +00002357 return name;
2358 }
2359 }
2360 }
2361 }
2362 }
Kevin Enderby85974882014-09-26 22:20:44 +00002363 }
2364 return nullptr;
2365}
2366
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002367// method_reference() is called passing it the ReferenceName that might be
2368// a reference it to an Objective-C method call. If so then it allocates and
2369// assembles a method call string with the values last seen and saved in
2370// the DisassembleInfo's class_name and selector_name fields. This is saved
2371// into the method field of the info and any previous string is free'ed.
2372// Then the class_name field in the info is set to nullptr. The method call
2373// string is set into ReferenceName and ReferenceType is set to
2374// LLVMDisassembler_ReferenceType_Out_Objc_Message. If this not a method call
2375// then both ReferenceType and ReferenceName are left unchanged.
2376static void method_reference(struct DisassembleInfo *info,
2377 uint64_t *ReferenceType,
2378 const char **ReferenceName) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002379 unsigned int Arch = info->O->getArch();
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002380 if (*ReferenceName != nullptr) {
2381 if (strcmp(*ReferenceName, "_objc_msgSend") == 0) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002382 if (info->selector_name != nullptr) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002383 if (info->method != nullptr)
2384 free(info->method);
2385 if (info->class_name != nullptr) {
2386 info->method = (char *)malloc(5 + strlen(info->class_name) +
2387 strlen(info->selector_name));
2388 if (info->method != nullptr) {
2389 strcpy(info->method, "+[");
2390 strcat(info->method, info->class_name);
2391 strcat(info->method, " ");
2392 strcat(info->method, info->selector_name);
2393 strcat(info->method, "]");
2394 *ReferenceName = info->method;
2395 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
2396 }
2397 } else {
2398 info->method = (char *)malloc(9 + strlen(info->selector_name));
2399 if (info->method != nullptr) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002400 if (Arch == Triple::x86_64)
2401 strcpy(info->method, "-[%rdi ");
2402 else if (Arch == Triple::aarch64)
2403 strcpy(info->method, "-[x0 ");
2404 else
2405 strcpy(info->method, "-[r? ");
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002406 strcat(info->method, info->selector_name);
2407 strcat(info->method, "]");
2408 *ReferenceName = info->method;
2409 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
2410 }
2411 }
2412 info->class_name = nullptr;
2413 }
2414 } else if (strcmp(*ReferenceName, "_objc_msgSendSuper2") == 0) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002415 if (info->selector_name != nullptr) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002416 if (info->method != nullptr)
2417 free(info->method);
2418 info->method = (char *)malloc(17 + strlen(info->selector_name));
2419 if (info->method != nullptr) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002420 if (Arch == Triple::x86_64)
2421 strcpy(info->method, "-[[%rdi super] ");
2422 else if (Arch == Triple::aarch64)
2423 strcpy(info->method, "-[[x0 super] ");
2424 else
2425 strcpy(info->method, "-[[r? super] ");
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002426 strcat(info->method, info->selector_name);
2427 strcat(info->method, "]");
2428 *ReferenceName = info->method;
2429 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
2430 }
2431 info->class_name = nullptr;
2432 }
2433 }
2434 }
2435}
2436
2437// GuessPointerPointer() is passed the address of what might be a pointer to
2438// a reference to an Objective-C class, selector, message ref or cfstring.
2439// If so the value of the pointer is returned and one of the booleans are set
2440// to true. If not zero is returned and all the booleans are set to false.
2441static uint64_t GuessPointerPointer(uint64_t ReferenceValue,
2442 struct DisassembleInfo *info,
2443 bool &classref, bool &selref, bool &msgref,
2444 bool &cfstring) {
2445 classref = false;
2446 selref = false;
2447 msgref = false;
2448 cfstring = false;
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00002449 for (const auto &Load : info->O->load_commands()) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002450 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
2451 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
2452 for (unsigned J = 0; J < Seg.nsects; ++J) {
2453 MachO::section_64 Sec = info->O->getSection64(Load, J);
2454 if ((strncmp(Sec.sectname, "__objc_selrefs", 16) == 0 ||
2455 strncmp(Sec.sectname, "__objc_classrefs", 16) == 0 ||
2456 strncmp(Sec.sectname, "__objc_superrefs", 16) == 0 ||
2457 strncmp(Sec.sectname, "__objc_msgrefs", 16) == 0 ||
2458 strncmp(Sec.sectname, "__cfstring", 16) == 0) &&
2459 ReferenceValue >= Sec.addr &&
2460 ReferenceValue < Sec.addr + Sec.size) {
2461 uint64_t sect_offset = ReferenceValue - Sec.addr;
2462 uint64_t object_offset = Sec.offset + sect_offset;
2463 StringRef MachOContents = info->O->getData();
2464 uint64_t object_size = MachOContents.size();
2465 const char *object_addr = (const char *)MachOContents.data();
2466 if (object_offset < object_size) {
2467 uint64_t pointer_value;
2468 memcpy(&pointer_value, object_addr + object_offset,
2469 sizeof(uint64_t));
2470 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
2471 sys::swapByteOrder(pointer_value);
2472 if (strncmp(Sec.sectname, "__objc_selrefs", 16) == 0)
2473 selref = true;
2474 else if (strncmp(Sec.sectname, "__objc_classrefs", 16) == 0 ||
2475 strncmp(Sec.sectname, "__objc_superrefs", 16) == 0)
2476 classref = true;
2477 else if (strncmp(Sec.sectname, "__objc_msgrefs", 16) == 0 &&
2478 ReferenceValue + 8 < Sec.addr + Sec.size) {
2479 msgref = true;
2480 memcpy(&pointer_value, object_addr + object_offset + 8,
2481 sizeof(uint64_t));
2482 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
2483 sys::swapByteOrder(pointer_value);
2484 } else if (strncmp(Sec.sectname, "__cfstring", 16) == 0)
2485 cfstring = true;
2486 return pointer_value;
2487 } else {
2488 return 0;
2489 }
2490 }
2491 }
2492 }
2493 // TODO: Look for LC_SEGMENT for 32-bit Mach-O files.
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002494 }
2495 return 0;
2496}
2497
2498// get_pointer_64 returns a pointer to the bytes in the object file at the
2499// Address from a section in the Mach-O file. And indirectly returns the
2500// offset into the section, number of bytes left in the section past the offset
2501// and which section is was being referenced. If the Address is not in a
2502// section nullptr is returned.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00002503static const char *get_pointer_64(uint64_t Address, uint32_t &offset,
2504 uint32_t &left, SectionRef &S,
Kevin Enderby846c0002015-04-16 17:19:59 +00002505 DisassembleInfo *info,
2506 bool objc_only = false) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002507 offset = 0;
2508 left = 0;
2509 S = SectionRef();
2510 for (unsigned SectIdx = 0; SectIdx != info->Sections->size(); SectIdx++) {
2511 uint64_t SectAddress = ((*(info->Sections))[SectIdx]).getAddress();
2512 uint64_t SectSize = ((*(info->Sections))[SectIdx]).getSize();
Kevin Enderby46e642f2015-10-08 22:50:55 +00002513 if (SectSize == 0)
2514 continue;
Kevin Enderby846c0002015-04-16 17:19:59 +00002515 if (objc_only) {
2516 StringRef SectName;
2517 ((*(info->Sections))[SectIdx]).getName(SectName);
2518 DataRefImpl Ref = ((*(info->Sections))[SectIdx]).getRawDataRefImpl();
2519 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
2520 if (SegName != "__OBJC" && SectName != "__cstring")
2521 continue;
2522 }
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002523 if (Address >= SectAddress && Address < SectAddress + SectSize) {
2524 S = (*(info->Sections))[SectIdx];
2525 offset = Address - SectAddress;
2526 left = SectSize - offset;
2527 StringRef SectContents;
2528 ((*(info->Sections))[SectIdx]).getContents(SectContents);
2529 return SectContents.data() + offset;
2530 }
2531 }
2532 return nullptr;
2533}
2534
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002535static const char *get_pointer_32(uint32_t Address, uint32_t &offset,
2536 uint32_t &left, SectionRef &S,
Kevin Enderby846c0002015-04-16 17:19:59 +00002537 DisassembleInfo *info,
2538 bool objc_only = false) {
2539 return get_pointer_64(Address, offset, left, S, info, objc_only);
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002540}
2541
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002542// get_symbol_64() returns the name of a symbol (or nullptr) and the address of
2543// the symbol indirectly through n_value. Based on the relocation information
2544// for the specified section offset in the specified section reference.
Kevin Enderby0fc11822015-04-01 20:57:01 +00002545// If no relocation information is found and a non-zero ReferenceValue for the
2546// symbol is passed, look up that address in the info's AddrMap.
Rafael Espindolad7a32ea2015-06-24 10:20:30 +00002547static const char *get_symbol_64(uint32_t sect_offset, SectionRef S,
2548 DisassembleInfo *info, uint64_t &n_value,
Rafael Espindolabe8b0ea2015-07-07 17:12:59 +00002549 uint64_t ReferenceValue = 0) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002550 n_value = 0;
David Blaikie33dd45d02015-03-23 18:39:02 +00002551 if (!info->verbose)
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002552 return nullptr;
2553
2554 // See if there is an external relocation entry at the sect_offset.
2555 bool reloc_found = false;
2556 DataRefImpl Rel;
2557 MachO::any_relocation_info RE;
2558 bool isExtern = false;
2559 SymbolRef Symbol;
2560 for (const RelocationRef &Reloc : S.relocations()) {
Rafael Espindola96d071c2015-06-29 23:29:12 +00002561 uint64_t RelocOffset = Reloc.getOffset();
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002562 if (RelocOffset == sect_offset) {
2563 Rel = Reloc.getRawDataRefImpl();
2564 RE = info->O->getRelocation(Rel);
2565 if (info->O->isRelocationScattered(RE))
2566 continue;
2567 isExtern = info->O->getPlainRelocationExternal(RE);
2568 if (isExtern) {
2569 symbol_iterator RelocSym = Reloc.getSymbol();
2570 Symbol = *RelocSym;
2571 }
2572 reloc_found = true;
2573 break;
2574 }
2575 }
2576 // If there is an external relocation entry for a symbol in this section
2577 // at this section_offset then use that symbol's value for the n_value
2578 // and return its name.
2579 const char *SymbolName = nullptr;
2580 if (reloc_found && isExtern) {
Rafael Espindoladea00162015-07-03 17:44:18 +00002581 n_value = Symbol.getValue();
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00002582 Expected<StringRef> NameOrError = Symbol.getName();
2583 if (!NameOrError) {
2584 std::string Buf;
2585 raw_string_ostream OS(Buf);
2586 logAllUnhandledErrors(NameOrError.takeError(), OS, "");
2587 OS.flush();
2588 report_fatal_error(Buf);
2589 }
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00002590 StringRef Name = *NameOrError;
2591 if (!Name.empty()) {
2592 SymbolName = Name.data();
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002593 return SymbolName;
2594 }
2595 }
2596
2597 // TODO: For fully linked images, look through the external relocation
2598 // entries off the dynamic symtab command. For these the r_offset is from the
2599 // start of the first writeable segment in the Mach-O file. So the offset
2600 // to this section from that segment is passed to this routine by the caller,
2601 // as the database_offset. Which is the difference of the section's starting
2602 // address and the first writable segment.
2603 //
2604 // NOTE: need add passing the database_offset to this routine.
2605
Kevin Enderby0fc11822015-04-01 20:57:01 +00002606 // We did not find an external relocation entry so look up the ReferenceValue
2607 // as an address of a symbol and if found return that symbol's name.
Rafael Espindolabe8b0ea2015-07-07 17:12:59 +00002608 SymbolName = GuessSymbolName(ReferenceValue, info->AddrMap);
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002609
2610 return SymbolName;
2611}
2612
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002613static const char *get_symbol_32(uint32_t sect_offset, SectionRef S,
2614 DisassembleInfo *info,
2615 uint32_t ReferenceValue) {
2616 uint64_t n_value64;
2617 return get_symbol_64(sect_offset, S, info, n_value64, ReferenceValue);
2618}
2619
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002620// These are structs in the Objective-C meta data and read to produce the
2621// comments for disassembly. While these are part of the ABI they are no
2622// public defintions. So the are here not in include/llvm/Support/MachO.h .
2623
2624// The cfstring object in a 64-bit Mach-O file.
2625struct cfstring64_t {
2626 uint64_t isa; // class64_t * (64-bit pointer)
2627 uint64_t flags; // flag bits
2628 uint64_t characters; // char * (64-bit pointer)
2629 uint64_t length; // number of non-NULL characters in above
2630};
2631
2632// The class object in a 64-bit Mach-O file.
2633struct class64_t {
2634 uint64_t isa; // class64_t * (64-bit pointer)
2635 uint64_t superclass; // class64_t * (64-bit pointer)
2636 uint64_t cache; // Cache (64-bit pointer)
2637 uint64_t vtable; // IMP * (64-bit pointer)
2638 uint64_t data; // class_ro64_t * (64-bit pointer)
2639};
2640
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002641struct class32_t {
2642 uint32_t isa; /* class32_t * (32-bit pointer) */
2643 uint32_t superclass; /* class32_t * (32-bit pointer) */
2644 uint32_t cache; /* Cache (32-bit pointer) */
2645 uint32_t vtable; /* IMP * (32-bit pointer) */
2646 uint32_t data; /* class_ro32_t * (32-bit pointer) */
2647};
2648
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002649struct class_ro64_t {
2650 uint32_t flags;
2651 uint32_t instanceStart;
2652 uint32_t instanceSize;
2653 uint32_t reserved;
2654 uint64_t ivarLayout; // const uint8_t * (64-bit pointer)
2655 uint64_t name; // const char * (64-bit pointer)
2656 uint64_t baseMethods; // const method_list_t * (64-bit pointer)
2657 uint64_t baseProtocols; // const protocol_list_t * (64-bit pointer)
2658 uint64_t ivars; // const ivar_list_t * (64-bit pointer)
2659 uint64_t weakIvarLayout; // const uint8_t * (64-bit pointer)
2660 uint64_t baseProperties; // const struct objc_property_list (64-bit pointer)
2661};
2662
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002663struct class_ro32_t {
2664 uint32_t flags;
2665 uint32_t instanceStart;
2666 uint32_t instanceSize;
2667 uint32_t ivarLayout; /* const uint8_t * (32-bit pointer) */
2668 uint32_t name; /* const char * (32-bit pointer) */
2669 uint32_t baseMethods; /* const method_list_t * (32-bit pointer) */
2670 uint32_t baseProtocols; /* const protocol_list_t * (32-bit pointer) */
2671 uint32_t ivars; /* const ivar_list_t * (32-bit pointer) */
2672 uint32_t weakIvarLayout; /* const uint8_t * (32-bit pointer) */
2673 uint32_t baseProperties; /* const struct objc_property_list *
2674 (32-bit pointer) */
2675};
2676
2677/* Values for class_ro{64,32}_t->flags */
Kevin Enderby0fc11822015-04-01 20:57:01 +00002678#define RO_META (1 << 0)
2679#define RO_ROOT (1 << 1)
2680#define RO_HAS_CXX_STRUCTORS (1 << 2)
2681
2682struct method_list64_t {
2683 uint32_t entsize;
2684 uint32_t count;
2685 /* struct method64_t first; These structures follow inline */
2686};
2687
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002688struct method_list32_t {
2689 uint32_t entsize;
2690 uint32_t count;
2691 /* struct method32_t first; These structures follow inline */
2692};
2693
Kevin Enderby0fc11822015-04-01 20:57:01 +00002694struct method64_t {
2695 uint64_t name; /* SEL (64-bit pointer) */
2696 uint64_t types; /* const char * (64-bit pointer) */
2697 uint64_t imp; /* IMP (64-bit pointer) */
2698};
2699
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002700struct method32_t {
2701 uint32_t name; /* SEL (32-bit pointer) */
2702 uint32_t types; /* const char * (32-bit pointer) */
2703 uint32_t imp; /* IMP (32-bit pointer) */
2704};
2705
Kevin Enderby0fc11822015-04-01 20:57:01 +00002706struct protocol_list64_t {
2707 uint64_t count; /* uintptr_t (a 64-bit value) */
2708 /* struct protocol64_t * list[0]; These pointers follow inline */
2709};
2710
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002711struct protocol_list32_t {
2712 uint32_t count; /* uintptr_t (a 32-bit value) */
2713 /* struct protocol32_t * list[0]; These pointers follow inline */
2714};
2715
Kevin Enderby0fc11822015-04-01 20:57:01 +00002716struct protocol64_t {
2717 uint64_t isa; /* id * (64-bit pointer) */
2718 uint64_t name; /* const char * (64-bit pointer) */
2719 uint64_t protocols; /* struct protocol_list64_t *
2720 (64-bit pointer) */
2721 uint64_t instanceMethods; /* method_list_t * (64-bit pointer) */
2722 uint64_t classMethods; /* method_list_t * (64-bit pointer) */
2723 uint64_t optionalInstanceMethods; /* method_list_t * (64-bit pointer) */
2724 uint64_t optionalClassMethods; /* method_list_t * (64-bit pointer) */
2725 uint64_t instanceProperties; /* struct objc_property_list *
2726 (64-bit pointer) */
2727};
2728
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002729struct protocol32_t {
2730 uint32_t isa; /* id * (32-bit pointer) */
2731 uint32_t name; /* const char * (32-bit pointer) */
2732 uint32_t protocols; /* struct protocol_list_t *
2733 (32-bit pointer) */
2734 uint32_t instanceMethods; /* method_list_t * (32-bit pointer) */
2735 uint32_t classMethods; /* method_list_t * (32-bit pointer) */
2736 uint32_t optionalInstanceMethods; /* method_list_t * (32-bit pointer) */
2737 uint32_t optionalClassMethods; /* method_list_t * (32-bit pointer) */
2738 uint32_t instanceProperties; /* struct objc_property_list *
2739 (32-bit pointer) */
2740};
2741
Kevin Enderby0fc11822015-04-01 20:57:01 +00002742struct ivar_list64_t {
2743 uint32_t entsize;
2744 uint32_t count;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002745 /* struct ivar64_t first; These structures follow inline */
2746};
2747
2748struct ivar_list32_t {
2749 uint32_t entsize;
2750 uint32_t count;
2751 /* struct ivar32_t first; These structures follow inline */
Kevin Enderby0fc11822015-04-01 20:57:01 +00002752};
2753
2754struct ivar64_t {
2755 uint64_t offset; /* uintptr_t * (64-bit pointer) */
2756 uint64_t name; /* const char * (64-bit pointer) */
2757 uint64_t type; /* const char * (64-bit pointer) */
2758 uint32_t alignment;
2759 uint32_t size;
2760};
2761
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002762struct ivar32_t {
2763 uint32_t offset; /* uintptr_t * (32-bit pointer) */
2764 uint32_t name; /* const char * (32-bit pointer) */
2765 uint32_t type; /* const char * (32-bit pointer) */
2766 uint32_t alignment;
2767 uint32_t size;
2768};
2769
Kevin Enderby0fc11822015-04-01 20:57:01 +00002770struct objc_property_list64 {
2771 uint32_t entsize;
2772 uint32_t count;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002773 /* struct objc_property64 first; These structures follow inline */
2774};
2775
2776struct objc_property_list32 {
2777 uint32_t entsize;
2778 uint32_t count;
2779 /* struct objc_property32 first; These structures follow inline */
Kevin Enderby0fc11822015-04-01 20:57:01 +00002780};
2781
2782struct objc_property64 {
2783 uint64_t name; /* const char * (64-bit pointer) */
2784 uint64_t attributes; /* const char * (64-bit pointer) */
2785};
2786
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002787struct objc_property32 {
2788 uint32_t name; /* const char * (32-bit pointer) */
2789 uint32_t attributes; /* const char * (32-bit pointer) */
2790};
2791
Kevin Enderby0fc11822015-04-01 20:57:01 +00002792struct category64_t {
2793 uint64_t name; /* const char * (64-bit pointer) */
2794 uint64_t cls; /* struct class_t * (64-bit pointer) */
2795 uint64_t instanceMethods; /* struct method_list_t * (64-bit pointer) */
2796 uint64_t classMethods; /* struct method_list_t * (64-bit pointer) */
2797 uint64_t protocols; /* struct protocol_list_t * (64-bit pointer) */
2798 uint64_t instanceProperties; /* struct objc_property_list *
2799 (64-bit pointer) */
2800};
2801
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002802struct category32_t {
2803 uint32_t name; /* const char * (32-bit pointer) */
2804 uint32_t cls; /* struct class_t * (32-bit pointer) */
2805 uint32_t instanceMethods; /* struct method_list_t * (32-bit pointer) */
2806 uint32_t classMethods; /* struct method_list_t * (32-bit pointer) */
2807 uint32_t protocols; /* struct protocol_list_t * (32-bit pointer) */
2808 uint32_t instanceProperties; /* struct objc_property_list *
2809 (32-bit pointer) */
2810};
2811
Kevin Enderby0fc11822015-04-01 20:57:01 +00002812struct objc_image_info64 {
2813 uint32_t version;
2814 uint32_t flags;
2815};
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002816struct objc_image_info32 {
2817 uint32_t version;
2818 uint32_t flags;
2819};
Kevin Enderby846c0002015-04-16 17:19:59 +00002820struct imageInfo_t {
2821 uint32_t version;
2822 uint32_t flags;
2823};
Kevin Enderby0fc11822015-04-01 20:57:01 +00002824/* masks for objc_image_info.flags */
2825#define OBJC_IMAGE_IS_REPLACEMENT (1 << 0)
2826#define OBJC_IMAGE_SUPPORTS_GC (1 << 1)
2827
2828struct message_ref64 {
2829 uint64_t imp; /* IMP (64-bit pointer) */
2830 uint64_t sel; /* SEL (64-bit pointer) */
2831};
2832
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002833struct message_ref32 {
2834 uint32_t imp; /* IMP (32-bit pointer) */
2835 uint32_t sel; /* SEL (32-bit pointer) */
2836};
2837
Kevin Enderby846c0002015-04-16 17:19:59 +00002838// Objective-C 1 (32-bit only) meta data structs.
2839
2840struct objc_module_t {
2841 uint32_t version;
2842 uint32_t size;
2843 uint32_t name; /* char * (32-bit pointer) */
2844 uint32_t symtab; /* struct objc_symtab * (32-bit pointer) */
2845};
2846
2847struct objc_symtab_t {
2848 uint32_t sel_ref_cnt;
2849 uint32_t refs; /* SEL * (32-bit pointer) */
2850 uint16_t cls_def_cnt;
2851 uint16_t cat_def_cnt;
2852 // uint32_t defs[1]; /* void * (32-bit pointer) variable size */
2853};
2854
2855struct objc_class_t {
2856 uint32_t isa; /* struct objc_class * (32-bit pointer) */
2857 uint32_t super_class; /* struct objc_class * (32-bit pointer) */
2858 uint32_t name; /* const char * (32-bit pointer) */
2859 int32_t version;
2860 int32_t info;
2861 int32_t instance_size;
2862 uint32_t ivars; /* struct objc_ivar_list * (32-bit pointer) */
2863 uint32_t methodLists; /* struct objc_method_list ** (32-bit pointer) */
2864 uint32_t cache; /* struct objc_cache * (32-bit pointer) */
2865 uint32_t protocols; /* struct objc_protocol_list * (32-bit pointer) */
2866};
2867
2868#define CLS_GETINFO(cls, infomask) ((cls)->info & (infomask))
2869// class is not a metaclass
2870#define CLS_CLASS 0x1
2871// class is a metaclass
2872#define CLS_META 0x2
2873
2874struct objc_category_t {
2875 uint32_t category_name; /* char * (32-bit pointer) */
2876 uint32_t class_name; /* char * (32-bit pointer) */
2877 uint32_t instance_methods; /* struct objc_method_list * (32-bit pointer) */
2878 uint32_t class_methods; /* struct objc_method_list * (32-bit pointer) */
2879 uint32_t protocols; /* struct objc_protocol_list * (32-bit ptr) */
2880};
2881
2882struct objc_ivar_t {
2883 uint32_t ivar_name; /* char * (32-bit pointer) */
2884 uint32_t ivar_type; /* char * (32-bit pointer) */
2885 int32_t ivar_offset;
2886};
2887
2888struct objc_ivar_list_t {
2889 int32_t ivar_count;
2890 // struct objc_ivar_t ivar_list[1]; /* variable length structure */
2891};
2892
2893struct objc_method_list_t {
2894 uint32_t obsolete; /* struct objc_method_list * (32-bit pointer) */
2895 int32_t method_count;
2896 // struct objc_method_t method_list[1]; /* variable length structure */
2897};
2898
2899struct objc_method_t {
2900 uint32_t method_name; /* SEL, aka struct objc_selector * (32-bit pointer) */
2901 uint32_t method_types; /* char * (32-bit pointer) */
2902 uint32_t method_imp; /* IMP, aka function pointer, (*IMP)(id, SEL, ...)
2903 (32-bit pointer) */
2904};
2905
2906struct objc_protocol_list_t {
2907 uint32_t next; /* struct objc_protocol_list * (32-bit pointer) */
2908 int32_t count;
2909 // uint32_t list[1]; /* Protocol *, aka struct objc_protocol_t *
2910 // (32-bit pointer) */
2911};
2912
2913struct objc_protocol_t {
2914 uint32_t isa; /* struct objc_class * (32-bit pointer) */
2915 uint32_t protocol_name; /* char * (32-bit pointer) */
2916 uint32_t protocol_list; /* struct objc_protocol_list * (32-bit pointer) */
2917 uint32_t instance_methods; /* struct objc_method_description_list *
2918 (32-bit pointer) */
2919 uint32_t class_methods; /* struct objc_method_description_list *
2920 (32-bit pointer) */
2921};
2922
2923struct objc_method_description_list_t {
2924 int32_t count;
2925 // struct objc_method_description_t list[1];
2926};
2927
2928struct objc_method_description_t {
2929 uint32_t name; /* SEL, aka struct objc_selector * (32-bit pointer) */
2930 uint32_t types; /* char * (32-bit pointer) */
2931};
2932
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002933inline void swapStruct(struct cfstring64_t &cfs) {
2934 sys::swapByteOrder(cfs.isa);
2935 sys::swapByteOrder(cfs.flags);
2936 sys::swapByteOrder(cfs.characters);
2937 sys::swapByteOrder(cfs.length);
2938}
2939
2940inline void swapStruct(struct class64_t &c) {
2941 sys::swapByteOrder(c.isa);
2942 sys::swapByteOrder(c.superclass);
2943 sys::swapByteOrder(c.cache);
2944 sys::swapByteOrder(c.vtable);
2945 sys::swapByteOrder(c.data);
2946}
2947
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002948inline void swapStruct(struct class32_t &c) {
2949 sys::swapByteOrder(c.isa);
2950 sys::swapByteOrder(c.superclass);
2951 sys::swapByteOrder(c.cache);
2952 sys::swapByteOrder(c.vtable);
2953 sys::swapByteOrder(c.data);
2954}
2955
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002956inline void swapStruct(struct class_ro64_t &cro) {
2957 sys::swapByteOrder(cro.flags);
2958 sys::swapByteOrder(cro.instanceStart);
2959 sys::swapByteOrder(cro.instanceSize);
2960 sys::swapByteOrder(cro.reserved);
2961 sys::swapByteOrder(cro.ivarLayout);
2962 sys::swapByteOrder(cro.name);
2963 sys::swapByteOrder(cro.baseMethods);
2964 sys::swapByteOrder(cro.baseProtocols);
2965 sys::swapByteOrder(cro.ivars);
2966 sys::swapByteOrder(cro.weakIvarLayout);
2967 sys::swapByteOrder(cro.baseProperties);
2968}
2969
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002970inline void swapStruct(struct class_ro32_t &cro) {
2971 sys::swapByteOrder(cro.flags);
2972 sys::swapByteOrder(cro.instanceStart);
2973 sys::swapByteOrder(cro.instanceSize);
2974 sys::swapByteOrder(cro.ivarLayout);
2975 sys::swapByteOrder(cro.name);
2976 sys::swapByteOrder(cro.baseMethods);
2977 sys::swapByteOrder(cro.baseProtocols);
2978 sys::swapByteOrder(cro.ivars);
2979 sys::swapByteOrder(cro.weakIvarLayout);
2980 sys::swapByteOrder(cro.baseProperties);
2981}
2982
Kevin Enderby0fc11822015-04-01 20:57:01 +00002983inline void swapStruct(struct method_list64_t &ml) {
2984 sys::swapByteOrder(ml.entsize);
2985 sys::swapByteOrder(ml.count);
2986}
2987
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002988inline void swapStruct(struct method_list32_t &ml) {
2989 sys::swapByteOrder(ml.entsize);
2990 sys::swapByteOrder(ml.count);
2991}
2992
Kevin Enderby0fc11822015-04-01 20:57:01 +00002993inline void swapStruct(struct method64_t &m) {
2994 sys::swapByteOrder(m.name);
2995 sys::swapByteOrder(m.types);
2996 sys::swapByteOrder(m.imp);
2997}
2998
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002999inline void swapStruct(struct method32_t &m) {
3000 sys::swapByteOrder(m.name);
3001 sys::swapByteOrder(m.types);
3002 sys::swapByteOrder(m.imp);
3003}
3004
Kevin Enderby0fc11822015-04-01 20:57:01 +00003005inline void swapStruct(struct protocol_list64_t &pl) {
3006 sys::swapByteOrder(pl.count);
3007}
3008
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003009inline void swapStruct(struct protocol_list32_t &pl) {
3010 sys::swapByteOrder(pl.count);
3011}
3012
Kevin Enderby0fc11822015-04-01 20:57:01 +00003013inline void swapStruct(struct protocol64_t &p) {
3014 sys::swapByteOrder(p.isa);
3015 sys::swapByteOrder(p.name);
3016 sys::swapByteOrder(p.protocols);
3017 sys::swapByteOrder(p.instanceMethods);
3018 sys::swapByteOrder(p.classMethods);
3019 sys::swapByteOrder(p.optionalInstanceMethods);
3020 sys::swapByteOrder(p.optionalClassMethods);
3021 sys::swapByteOrder(p.instanceProperties);
3022}
3023
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003024inline void swapStruct(struct protocol32_t &p) {
3025 sys::swapByteOrder(p.isa);
3026 sys::swapByteOrder(p.name);
3027 sys::swapByteOrder(p.protocols);
3028 sys::swapByteOrder(p.instanceMethods);
3029 sys::swapByteOrder(p.classMethods);
3030 sys::swapByteOrder(p.optionalInstanceMethods);
3031 sys::swapByteOrder(p.optionalClassMethods);
3032 sys::swapByteOrder(p.instanceProperties);
3033}
3034
Kevin Enderby0fc11822015-04-01 20:57:01 +00003035inline void swapStruct(struct ivar_list64_t &il) {
3036 sys::swapByteOrder(il.entsize);
3037 sys::swapByteOrder(il.count);
3038}
3039
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003040inline void swapStruct(struct ivar_list32_t &il) {
3041 sys::swapByteOrder(il.entsize);
3042 sys::swapByteOrder(il.count);
3043}
3044
Kevin Enderby0fc11822015-04-01 20:57:01 +00003045inline void swapStruct(struct ivar64_t &i) {
3046 sys::swapByteOrder(i.offset);
3047 sys::swapByteOrder(i.name);
3048 sys::swapByteOrder(i.type);
3049 sys::swapByteOrder(i.alignment);
3050 sys::swapByteOrder(i.size);
3051}
3052
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003053inline void swapStruct(struct ivar32_t &i) {
3054 sys::swapByteOrder(i.offset);
3055 sys::swapByteOrder(i.name);
3056 sys::swapByteOrder(i.type);
3057 sys::swapByteOrder(i.alignment);
3058 sys::swapByteOrder(i.size);
3059}
3060
Kevin Enderby0fc11822015-04-01 20:57:01 +00003061inline void swapStruct(struct objc_property_list64 &pl) {
3062 sys::swapByteOrder(pl.entsize);
3063 sys::swapByteOrder(pl.count);
3064}
3065
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003066inline void swapStruct(struct objc_property_list32 &pl) {
3067 sys::swapByteOrder(pl.entsize);
3068 sys::swapByteOrder(pl.count);
3069}
3070
Kevin Enderby0fc11822015-04-01 20:57:01 +00003071inline void swapStruct(struct objc_property64 &op) {
3072 sys::swapByteOrder(op.name);
3073 sys::swapByteOrder(op.attributes);
3074}
3075
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003076inline void swapStruct(struct objc_property32 &op) {
3077 sys::swapByteOrder(op.name);
3078 sys::swapByteOrder(op.attributes);
3079}
3080
Kevin Enderby0fc11822015-04-01 20:57:01 +00003081inline void swapStruct(struct category64_t &c) {
3082 sys::swapByteOrder(c.name);
3083 sys::swapByteOrder(c.cls);
3084 sys::swapByteOrder(c.instanceMethods);
3085 sys::swapByteOrder(c.classMethods);
3086 sys::swapByteOrder(c.protocols);
3087 sys::swapByteOrder(c.instanceProperties);
3088}
3089
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003090inline void swapStruct(struct category32_t &c) {
3091 sys::swapByteOrder(c.name);
3092 sys::swapByteOrder(c.cls);
3093 sys::swapByteOrder(c.instanceMethods);
3094 sys::swapByteOrder(c.classMethods);
3095 sys::swapByteOrder(c.protocols);
3096 sys::swapByteOrder(c.instanceProperties);
3097}
3098
Kevin Enderby0fc11822015-04-01 20:57:01 +00003099inline void swapStruct(struct objc_image_info64 &o) {
3100 sys::swapByteOrder(o.version);
3101 sys::swapByteOrder(o.flags);
3102}
3103
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003104inline void swapStruct(struct objc_image_info32 &o) {
3105 sys::swapByteOrder(o.version);
3106 sys::swapByteOrder(o.flags);
3107}
3108
Kevin Enderby846c0002015-04-16 17:19:59 +00003109inline void swapStruct(struct imageInfo_t &o) {
3110 sys::swapByteOrder(o.version);
3111 sys::swapByteOrder(o.flags);
3112}
3113
Kevin Enderby0fc11822015-04-01 20:57:01 +00003114inline void swapStruct(struct message_ref64 &mr) {
3115 sys::swapByteOrder(mr.imp);
3116 sys::swapByteOrder(mr.sel);
3117}
3118
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003119inline void swapStruct(struct message_ref32 &mr) {
3120 sys::swapByteOrder(mr.imp);
3121 sys::swapByteOrder(mr.sel);
3122}
3123
Kevin Enderby846c0002015-04-16 17:19:59 +00003124inline void swapStruct(struct objc_module_t &module) {
3125 sys::swapByteOrder(module.version);
3126 sys::swapByteOrder(module.size);
3127 sys::swapByteOrder(module.name);
3128 sys::swapByteOrder(module.symtab);
Jingyue Wufedecc42015-04-16 18:43:44 +00003129}
Kevin Enderby846c0002015-04-16 17:19:59 +00003130
3131inline void swapStruct(struct objc_symtab_t &symtab) {
3132 sys::swapByteOrder(symtab.sel_ref_cnt);
3133 sys::swapByteOrder(symtab.refs);
3134 sys::swapByteOrder(symtab.cls_def_cnt);
3135 sys::swapByteOrder(symtab.cat_def_cnt);
Jingyue Wufedecc42015-04-16 18:43:44 +00003136}
Kevin Enderby846c0002015-04-16 17:19:59 +00003137
3138inline void swapStruct(struct objc_class_t &objc_class) {
3139 sys::swapByteOrder(objc_class.isa);
3140 sys::swapByteOrder(objc_class.super_class);
3141 sys::swapByteOrder(objc_class.name);
3142 sys::swapByteOrder(objc_class.version);
3143 sys::swapByteOrder(objc_class.info);
3144 sys::swapByteOrder(objc_class.instance_size);
3145 sys::swapByteOrder(objc_class.ivars);
3146 sys::swapByteOrder(objc_class.methodLists);
3147 sys::swapByteOrder(objc_class.cache);
3148 sys::swapByteOrder(objc_class.protocols);
Jingyue Wufedecc42015-04-16 18:43:44 +00003149}
Kevin Enderby846c0002015-04-16 17:19:59 +00003150
3151inline void swapStruct(struct objc_category_t &objc_category) {
3152 sys::swapByteOrder(objc_category.category_name);
3153 sys::swapByteOrder(objc_category.class_name);
3154 sys::swapByteOrder(objc_category.instance_methods);
3155 sys::swapByteOrder(objc_category.class_methods);
3156 sys::swapByteOrder(objc_category.protocols);
3157}
3158
3159inline void swapStruct(struct objc_ivar_list_t &objc_ivar_list) {
3160 sys::swapByteOrder(objc_ivar_list.ivar_count);
3161}
3162
3163inline void swapStruct(struct objc_ivar_t &objc_ivar) {
3164 sys::swapByteOrder(objc_ivar.ivar_name);
3165 sys::swapByteOrder(objc_ivar.ivar_type);
3166 sys::swapByteOrder(objc_ivar.ivar_offset);
Jingyue Wufedecc42015-04-16 18:43:44 +00003167}
Kevin Enderby846c0002015-04-16 17:19:59 +00003168
3169inline void swapStruct(struct objc_method_list_t &method_list) {
3170 sys::swapByteOrder(method_list.obsolete);
3171 sys::swapByteOrder(method_list.method_count);
3172}
3173
3174inline void swapStruct(struct objc_method_t &method) {
3175 sys::swapByteOrder(method.method_name);
3176 sys::swapByteOrder(method.method_types);
3177 sys::swapByteOrder(method.method_imp);
3178}
3179
3180inline void swapStruct(struct objc_protocol_list_t &protocol_list) {
3181 sys::swapByteOrder(protocol_list.next);
3182 sys::swapByteOrder(protocol_list.count);
3183}
3184
3185inline void swapStruct(struct objc_protocol_t &protocol) {
3186 sys::swapByteOrder(protocol.isa);
3187 sys::swapByteOrder(protocol.protocol_name);
3188 sys::swapByteOrder(protocol.protocol_list);
3189 sys::swapByteOrder(protocol.instance_methods);
3190 sys::swapByteOrder(protocol.class_methods);
3191}
3192
3193inline void swapStruct(struct objc_method_description_list_t &mdl) {
3194 sys::swapByteOrder(mdl.count);
3195}
3196
3197inline void swapStruct(struct objc_method_description_t &md) {
3198 sys::swapByteOrder(md.name);
3199 sys::swapByteOrder(md.types);
3200}
3201
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003202static const char *get_dyld_bind_info_symbolname(uint64_t ReferenceValue,
3203 struct DisassembleInfo *info);
3204
3205// get_objc2_64bit_class_name() is used for disassembly and is passed a pointer
3206// to an Objective-C class and returns the class name. It is also passed the
3207// address of the pointer, so when the pointer is zero as it can be in an .o
3208// file, that is used to look for an external relocation entry with a symbol
3209// name.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00003210static const char *get_objc2_64bit_class_name(uint64_t pointer_value,
3211 uint64_t ReferenceValue,
3212 struct DisassembleInfo *info) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003213 const char *r;
3214 uint32_t offset, left;
3215 SectionRef S;
3216
3217 // The pointer_value can be 0 in an object file and have a relocation
3218 // entry for the class symbol at the ReferenceValue (the address of the
3219 // pointer).
3220 if (pointer_value == 0) {
3221 r = get_pointer_64(ReferenceValue, offset, left, S, info);
3222 if (r == nullptr || left < sizeof(uint64_t))
3223 return nullptr;
3224 uint64_t n_value;
3225 const char *symbol_name = get_symbol_64(offset, S, info, n_value);
3226 if (symbol_name == nullptr)
3227 return nullptr;
Hans Wennborgdb53e302014-10-23 21:59:17 +00003228 const char *class_name = strrchr(symbol_name, '$');
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003229 if (class_name != nullptr && class_name[1] == '_' && class_name[2] != '\0')
3230 return class_name + 2;
3231 else
3232 return nullptr;
3233 }
3234
3235 // The case were the pointer_value is non-zero and points to a class defined
3236 // in this Mach-O file.
3237 r = get_pointer_64(pointer_value, offset, left, S, info);
3238 if (r == nullptr || left < sizeof(struct class64_t))
3239 return nullptr;
3240 struct class64_t c;
3241 memcpy(&c, r, sizeof(struct class64_t));
3242 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3243 swapStruct(c);
3244 if (c.data == 0)
3245 return nullptr;
3246 r = get_pointer_64(c.data, offset, left, S, info);
3247 if (r == nullptr || left < sizeof(struct class_ro64_t))
3248 return nullptr;
3249 struct class_ro64_t cro;
3250 memcpy(&cro, r, sizeof(struct class_ro64_t));
3251 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3252 swapStruct(cro);
3253 if (cro.name == 0)
3254 return nullptr;
3255 const char *name = get_pointer_64(cro.name, offset, left, S, info);
3256 return name;
3257}
3258
3259// get_objc2_64bit_cfstring_name is used for disassembly and is passed a
3260// pointer to a cfstring and returns its name or nullptr.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00003261static const char *get_objc2_64bit_cfstring_name(uint64_t ReferenceValue,
3262 struct DisassembleInfo *info) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003263 const char *r, *name;
3264 uint32_t offset, left;
3265 SectionRef S;
3266 struct cfstring64_t cfs;
3267 uint64_t cfs_characters;
3268
3269 r = get_pointer_64(ReferenceValue, offset, left, S, info);
3270 if (r == nullptr || left < sizeof(struct cfstring64_t))
3271 return nullptr;
3272 memcpy(&cfs, r, sizeof(struct cfstring64_t));
3273 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3274 swapStruct(cfs);
3275 if (cfs.characters == 0) {
3276 uint64_t n_value;
3277 const char *symbol_name = get_symbol_64(
3278 offset + offsetof(struct cfstring64_t, characters), S, info, n_value);
3279 if (symbol_name == nullptr)
3280 return nullptr;
3281 cfs_characters = n_value;
3282 } else
3283 cfs_characters = cfs.characters;
3284 name = get_pointer_64(cfs_characters, offset, left, S, info);
3285
3286 return name;
3287}
3288
3289// get_objc2_64bit_selref() is used for disassembly and is passed a the address
3290// of a pointer to an Objective-C selector reference when the pointer value is
3291// zero as in a .o file and is likely to have a external relocation entry with
3292// who's symbol's n_value is the real pointer to the selector name. If that is
3293// the case the real pointer to the selector name is returned else 0 is
3294// returned
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00003295static uint64_t get_objc2_64bit_selref(uint64_t ReferenceValue,
3296 struct DisassembleInfo *info) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003297 uint32_t offset, left;
3298 SectionRef S;
3299
3300 const char *r = get_pointer_64(ReferenceValue, offset, left, S, info);
3301 if (r == nullptr || left < sizeof(uint64_t))
3302 return 0;
3303 uint64_t n_value;
3304 const char *symbol_name = get_symbol_64(offset, S, info, n_value);
3305 if (symbol_name == nullptr)
3306 return 0;
3307 return n_value;
3308}
3309
Kevin Enderby0fc11822015-04-01 20:57:01 +00003310static const SectionRef get_section(MachOObjectFile *O, const char *segname,
3311 const char *sectname) {
3312 for (const SectionRef &Section : O->sections()) {
3313 StringRef SectName;
3314 Section.getName(SectName);
3315 DataRefImpl Ref = Section.getRawDataRefImpl();
3316 StringRef SegName = O->getSectionFinalSegmentName(Ref);
3317 if (SegName == segname && SectName == sectname)
3318 return Section;
3319 }
3320 return SectionRef();
3321}
3322
3323static void
3324walk_pointer_list_64(const char *listname, const SectionRef S,
3325 MachOObjectFile *O, struct DisassembleInfo *info,
3326 void (*func)(uint64_t, struct DisassembleInfo *info)) {
3327 if (S == SectionRef())
3328 return;
3329
3330 StringRef SectName;
3331 S.getName(SectName);
3332 DataRefImpl Ref = S.getRawDataRefImpl();
3333 StringRef SegName = O->getSectionFinalSegmentName(Ref);
3334 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
3335
3336 StringRef BytesStr;
3337 S.getContents(BytesStr);
3338 const char *Contents = reinterpret_cast<const char *>(BytesStr.data());
3339
3340 for (uint32_t i = 0; i < S.getSize(); i += sizeof(uint64_t)) {
3341 uint32_t left = S.getSize() - i;
3342 uint32_t size = left < sizeof(uint64_t) ? left : sizeof(uint64_t);
3343 uint64_t p = 0;
3344 memcpy(&p, Contents + i, size);
3345 if (i + sizeof(uint64_t) > S.getSize())
3346 outs() << listname << " list pointer extends past end of (" << SegName
3347 << "," << SectName << ") section\n";
3348 outs() << format("%016" PRIx64, S.getAddress() + i) << " ";
3349
3350 if (O->isLittleEndian() != sys::IsLittleEndianHost)
3351 sys::swapByteOrder(p);
3352
3353 uint64_t n_value = 0;
3354 const char *name = get_symbol_64(i, S, info, n_value, p);
3355 if (name == nullptr)
3356 name = get_dyld_bind_info_symbolname(S.getAddress() + i, info);
3357
3358 if (n_value != 0) {
3359 outs() << format("0x%" PRIx64, n_value);
3360 if (p != 0)
3361 outs() << " + " << format("0x%" PRIx64, p);
3362 } else
3363 outs() << format("0x%" PRIx64, p);
3364 if (name != nullptr)
3365 outs() << " " << name;
3366 outs() << "\n";
3367
3368 p += n_value;
3369 if (func)
3370 func(p, info);
3371 }
3372}
3373
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003374static void
3375walk_pointer_list_32(const char *listname, const SectionRef S,
3376 MachOObjectFile *O, struct DisassembleInfo *info,
3377 void (*func)(uint32_t, struct DisassembleInfo *info)) {
3378 if (S == SectionRef())
3379 return;
3380
3381 StringRef SectName;
3382 S.getName(SectName);
3383 DataRefImpl Ref = S.getRawDataRefImpl();
3384 StringRef SegName = O->getSectionFinalSegmentName(Ref);
3385 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
3386
3387 StringRef BytesStr;
3388 S.getContents(BytesStr);
3389 const char *Contents = reinterpret_cast<const char *>(BytesStr.data());
3390
3391 for (uint32_t i = 0; i < S.getSize(); i += sizeof(uint32_t)) {
3392 uint32_t left = S.getSize() - i;
3393 uint32_t size = left < sizeof(uint32_t) ? left : sizeof(uint32_t);
3394 uint32_t p = 0;
3395 memcpy(&p, Contents + i, size);
3396 if (i + sizeof(uint32_t) > S.getSize())
3397 outs() << listname << " list pointer extends past end of (" << SegName
3398 << "," << SectName << ") section\n";
Kevin Enderbycf261312015-04-06 22:33:43 +00003399 uint32_t Address = S.getAddress() + i;
3400 outs() << format("%08" PRIx32, Address) << " ";
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003401
3402 if (O->isLittleEndian() != sys::IsLittleEndianHost)
3403 sys::swapByteOrder(p);
3404 outs() << format("0x%" PRIx32, p);
3405
3406 const char *name = get_symbol_32(i, S, info, p);
3407 if (name != nullptr)
3408 outs() << " " << name;
3409 outs() << "\n";
3410
3411 if (func)
3412 func(p, info);
3413 }
3414}
3415
3416static void print_layout_map(const char *layout_map, uint32_t left) {
Kevin Enderbya59824a2015-10-06 22:27:08 +00003417 if (layout_map == nullptr)
3418 return;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003419 outs() << " layout map: ";
3420 do {
3421 outs() << format("0x%02" PRIx32, (*layout_map) & 0xff) << " ";
3422 left--;
3423 layout_map++;
3424 } while (*layout_map != '\0' && left != 0);
3425 outs() << "\n";
3426}
3427
Kevin Enderby0fc11822015-04-01 20:57:01 +00003428static void print_layout_map64(uint64_t p, struct DisassembleInfo *info) {
3429 uint32_t offset, left;
3430 SectionRef S;
3431 const char *layout_map;
3432
3433 if (p == 0)
3434 return;
3435 layout_map = get_pointer_64(p, offset, left, S, info);
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003436 print_layout_map(layout_map, left);
3437}
3438
3439static void print_layout_map32(uint32_t p, struct DisassembleInfo *info) {
3440 uint32_t offset, left;
3441 SectionRef S;
3442 const char *layout_map;
3443
3444 if (p == 0)
3445 return;
3446 layout_map = get_pointer_32(p, offset, left, S, info);
3447 print_layout_map(layout_map, left);
Kevin Enderby0fc11822015-04-01 20:57:01 +00003448}
3449
3450static void print_method_list64_t(uint64_t p, struct DisassembleInfo *info,
3451 const char *indent) {
3452 struct method_list64_t ml;
3453 struct method64_t m;
3454 const char *r;
3455 uint32_t offset, xoffset, left, i;
3456 SectionRef S, xS;
3457 const char *name, *sym_name;
3458 uint64_t n_value;
3459
3460 r = get_pointer_64(p, offset, left, S, info);
3461 if (r == nullptr)
3462 return;
3463 memset(&ml, '\0', sizeof(struct method_list64_t));
3464 if (left < sizeof(struct method_list64_t)) {
3465 memcpy(&ml, r, left);
3466 outs() << " (method_list_t entends past the end of the section)\n";
3467 } else
3468 memcpy(&ml, r, sizeof(struct method_list64_t));
3469 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3470 swapStruct(ml);
3471 outs() << indent << "\t\t entsize " << ml.entsize << "\n";
3472 outs() << indent << "\t\t count " << ml.count << "\n";
3473
3474 p += sizeof(struct method_list64_t);
3475 offset += sizeof(struct method_list64_t);
3476 for (i = 0; i < ml.count; i++) {
3477 r = get_pointer_64(p, offset, left, S, info);
3478 if (r == nullptr)
3479 return;
3480 memset(&m, '\0', sizeof(struct method64_t));
3481 if (left < sizeof(struct method64_t)) {
Kevin Enderbya59824a2015-10-06 22:27:08 +00003482 memcpy(&m, r, left);
3483 outs() << indent << " (method_t extends past the end of the section)\n";
Kevin Enderby0fc11822015-04-01 20:57:01 +00003484 } else
3485 memcpy(&m, r, sizeof(struct method64_t));
3486 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3487 swapStruct(m);
3488
3489 outs() << indent << "\t\t name ";
3490 sym_name = get_symbol_64(offset + offsetof(struct method64_t, name), S,
3491 info, n_value, m.name);
3492 if (n_value != 0) {
3493 if (info->verbose && sym_name != nullptr)
3494 outs() << sym_name;
3495 else
3496 outs() << format("0x%" PRIx64, n_value);
3497 if (m.name != 0)
3498 outs() << " + " << format("0x%" PRIx64, m.name);
3499 } else
3500 outs() << format("0x%" PRIx64, m.name);
3501 name = get_pointer_64(m.name + n_value, xoffset, left, xS, info);
3502 if (name != nullptr)
3503 outs() << format(" %.*s", left, name);
3504 outs() << "\n";
3505
3506 outs() << indent << "\t\t types ";
3507 sym_name = get_symbol_64(offset + offsetof(struct method64_t, types), S,
3508 info, n_value, m.types);
3509 if (n_value != 0) {
3510 if (info->verbose && sym_name != nullptr)
3511 outs() << sym_name;
3512 else
3513 outs() << format("0x%" PRIx64, n_value);
3514 if (m.types != 0)
3515 outs() << " + " << format("0x%" PRIx64, m.types);
3516 } else
3517 outs() << format("0x%" PRIx64, m.types);
3518 name = get_pointer_64(m.types + n_value, xoffset, left, xS, info);
3519 if (name != nullptr)
3520 outs() << format(" %.*s", left, name);
3521 outs() << "\n";
3522
3523 outs() << indent << "\t\t imp ";
3524 name = get_symbol_64(offset + offsetof(struct method64_t, imp), S, info,
3525 n_value, m.imp);
3526 if (info->verbose && name == nullptr) {
3527 if (n_value != 0) {
3528 outs() << format("0x%" PRIx64, n_value) << " ";
3529 if (m.imp != 0)
3530 outs() << "+ " << format("0x%" PRIx64, m.imp) << " ";
3531 } else
3532 outs() << format("0x%" PRIx64, m.imp) << " ";
3533 }
3534 if (name != nullptr)
3535 outs() << name;
3536 outs() << "\n";
3537
3538 p += sizeof(struct method64_t);
3539 offset += sizeof(struct method64_t);
3540 }
3541}
3542
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003543static void print_method_list32_t(uint64_t p, struct DisassembleInfo *info,
3544 const char *indent) {
3545 struct method_list32_t ml;
3546 struct method32_t m;
Kevin Enderby846c0002015-04-16 17:19:59 +00003547 const char *r, *name;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003548 uint32_t offset, xoffset, left, i;
3549 SectionRef S, xS;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003550
3551 r = get_pointer_32(p, offset, left, S, info);
3552 if (r == nullptr)
3553 return;
3554 memset(&ml, '\0', sizeof(struct method_list32_t));
3555 if (left < sizeof(struct method_list32_t)) {
3556 memcpy(&ml, r, left);
3557 outs() << " (method_list_t entends past the end of the section)\n";
3558 } else
3559 memcpy(&ml, r, sizeof(struct method_list32_t));
3560 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3561 swapStruct(ml);
3562 outs() << indent << "\t\t entsize " << ml.entsize << "\n";
3563 outs() << indent << "\t\t count " << ml.count << "\n";
3564
3565 p += sizeof(struct method_list32_t);
3566 offset += sizeof(struct method_list32_t);
3567 for (i = 0; i < ml.count; i++) {
3568 r = get_pointer_32(p, offset, left, S, info);
3569 if (r == nullptr)
3570 return;
3571 memset(&m, '\0', sizeof(struct method32_t));
3572 if (left < sizeof(struct method32_t)) {
3573 memcpy(&ml, r, left);
3574 outs() << indent << " (method_t entends past the end of the section)\n";
3575 } else
3576 memcpy(&m, r, sizeof(struct method32_t));
3577 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3578 swapStruct(m);
3579
3580 outs() << indent << "\t\t name " << format("0x%" PRIx32, m.name);
3581 name = get_pointer_32(m.name, xoffset, left, xS, info);
3582 if (name != nullptr)
3583 outs() << format(" %.*s", left, name);
3584 outs() << "\n";
3585
3586 outs() << indent << "\t\t types " << format("0x%" PRIx32, m.types);
3587 name = get_pointer_32(m.types, xoffset, left, xS, info);
3588 if (name != nullptr)
3589 outs() << format(" %.*s", left, name);
3590 outs() << "\n";
3591
3592 outs() << indent << "\t\t imp " << format("0x%" PRIx32, m.imp);
3593 name = get_symbol_32(offset + offsetof(struct method32_t, imp), S, info,
3594 m.imp);
3595 if (name != nullptr)
3596 outs() << " " << name;
3597 outs() << "\n";
3598
3599 p += sizeof(struct method32_t);
3600 offset += sizeof(struct method32_t);
3601 }
3602}
3603
Kevin Enderby846c0002015-04-16 17:19:59 +00003604static bool print_method_list(uint32_t p, struct DisassembleInfo *info) {
3605 uint32_t offset, left, xleft;
3606 SectionRef S;
3607 struct objc_method_list_t method_list;
3608 struct objc_method_t method;
3609 const char *r, *methods, *name, *SymbolName;
3610 int32_t i;
3611
3612 r = get_pointer_32(p, offset, left, S, info, true);
3613 if (r == nullptr)
3614 return true;
3615
3616 outs() << "\n";
3617 if (left > sizeof(struct objc_method_list_t)) {
3618 memcpy(&method_list, r, sizeof(struct objc_method_list_t));
3619 } else {
3620 outs() << "\t\t objc_method_list extends past end of the section\n";
3621 memset(&method_list, '\0', sizeof(struct objc_method_list_t));
3622 memcpy(&method_list, r, left);
3623 }
3624 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3625 swapStruct(method_list);
3626
3627 outs() << "\t\t obsolete "
3628 << format("0x%08" PRIx32, method_list.obsolete) << "\n";
3629 outs() << "\t\t method_count " << method_list.method_count << "\n";
3630
3631 methods = r + sizeof(struct objc_method_list_t);
3632 for (i = 0; i < method_list.method_count; i++) {
3633 if ((i + 1) * sizeof(struct objc_method_t) > left) {
3634 outs() << "\t\t remaining method's extend past the of the section\n";
3635 break;
3636 }
3637 memcpy(&method, methods + i * sizeof(struct objc_method_t),
3638 sizeof(struct objc_method_t));
3639 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3640 swapStruct(method);
3641
3642 outs() << "\t\t method_name "
3643 << format("0x%08" PRIx32, method.method_name);
3644 if (info->verbose) {
3645 name = get_pointer_32(method.method_name, offset, xleft, S, info, true);
3646 if (name != nullptr)
3647 outs() << format(" %.*s", xleft, name);
3648 else
3649 outs() << " (not in an __OBJC section)";
3650 }
3651 outs() << "\n";
3652
3653 outs() << "\t\t method_types "
3654 << format("0x%08" PRIx32, method.method_types);
3655 if (info->verbose) {
3656 name = get_pointer_32(method.method_types, offset, xleft, S, info, true);
3657 if (name != nullptr)
3658 outs() << format(" %.*s", xleft, name);
3659 else
3660 outs() << " (not in an __OBJC section)";
3661 }
3662 outs() << "\n";
3663
3664 outs() << "\t\t method_imp "
3665 << format("0x%08" PRIx32, method.method_imp) << " ";
3666 if (info->verbose) {
3667 SymbolName = GuessSymbolName(method.method_imp, info->AddrMap);
3668 if (SymbolName != nullptr)
3669 outs() << SymbolName;
3670 }
3671 outs() << "\n";
3672 }
3673 return false;
3674}
3675
Kevin Enderby0fc11822015-04-01 20:57:01 +00003676static void print_protocol_list64_t(uint64_t p, struct DisassembleInfo *info) {
3677 struct protocol_list64_t pl;
3678 uint64_t q, n_value;
3679 struct protocol64_t pc;
3680 const char *r;
3681 uint32_t offset, xoffset, left, i;
3682 SectionRef S, xS;
3683 const char *name, *sym_name;
3684
3685 r = get_pointer_64(p, offset, left, S, info);
3686 if (r == nullptr)
3687 return;
3688 memset(&pl, '\0', sizeof(struct protocol_list64_t));
3689 if (left < sizeof(struct protocol_list64_t)) {
3690 memcpy(&pl, r, left);
3691 outs() << " (protocol_list_t entends past the end of the section)\n";
3692 } else
3693 memcpy(&pl, r, sizeof(struct protocol_list64_t));
3694 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3695 swapStruct(pl);
3696 outs() << " count " << pl.count << "\n";
3697
3698 p += sizeof(struct protocol_list64_t);
3699 offset += sizeof(struct protocol_list64_t);
3700 for (i = 0; i < pl.count; i++) {
3701 r = get_pointer_64(p, offset, left, S, info);
3702 if (r == nullptr)
3703 return;
3704 q = 0;
3705 if (left < sizeof(uint64_t)) {
3706 memcpy(&q, r, left);
3707 outs() << " (protocol_t * entends past the end of the section)\n";
3708 } else
3709 memcpy(&q, r, sizeof(uint64_t));
3710 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3711 sys::swapByteOrder(q);
3712
3713 outs() << "\t\t list[" << i << "] ";
3714 sym_name = get_symbol_64(offset, S, info, n_value, q);
3715 if (n_value != 0) {
3716 if (info->verbose && sym_name != nullptr)
3717 outs() << sym_name;
3718 else
3719 outs() << format("0x%" PRIx64, n_value);
3720 if (q != 0)
3721 outs() << " + " << format("0x%" PRIx64, q);
3722 } else
3723 outs() << format("0x%" PRIx64, q);
3724 outs() << " (struct protocol_t *)\n";
3725
3726 r = get_pointer_64(q + n_value, offset, left, S, info);
3727 if (r == nullptr)
3728 return;
3729 memset(&pc, '\0', sizeof(struct protocol64_t));
3730 if (left < sizeof(struct protocol64_t)) {
3731 memcpy(&pc, r, left);
3732 outs() << " (protocol_t entends past the end of the section)\n";
3733 } else
3734 memcpy(&pc, r, sizeof(struct protocol64_t));
3735 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3736 swapStruct(pc);
3737
3738 outs() << "\t\t\t isa " << format("0x%" PRIx64, pc.isa) << "\n";
3739
3740 outs() << "\t\t\t name ";
3741 sym_name = get_symbol_64(offset + offsetof(struct protocol64_t, name), S,
3742 info, n_value, pc.name);
3743 if (n_value != 0) {
3744 if (info->verbose && sym_name != nullptr)
3745 outs() << sym_name;
3746 else
3747 outs() << format("0x%" PRIx64, n_value);
3748 if (pc.name != 0)
3749 outs() << " + " << format("0x%" PRIx64, pc.name);
3750 } else
3751 outs() << format("0x%" PRIx64, pc.name);
3752 name = get_pointer_64(pc.name + n_value, xoffset, left, xS, info);
3753 if (name != nullptr)
3754 outs() << format(" %.*s", left, name);
3755 outs() << "\n";
3756
3757 outs() << "\t\t\tprotocols " << format("0x%" PRIx64, pc.protocols) << "\n";
3758
3759 outs() << "\t\t instanceMethods ";
3760 sym_name =
3761 get_symbol_64(offset + offsetof(struct protocol64_t, instanceMethods),
3762 S, info, n_value, pc.instanceMethods);
3763 if (n_value != 0) {
3764 if (info->verbose && sym_name != nullptr)
3765 outs() << sym_name;
3766 else
3767 outs() << format("0x%" PRIx64, n_value);
3768 if (pc.instanceMethods != 0)
3769 outs() << " + " << format("0x%" PRIx64, pc.instanceMethods);
3770 } else
3771 outs() << format("0x%" PRIx64, pc.instanceMethods);
3772 outs() << " (struct method_list_t *)\n";
3773 if (pc.instanceMethods + n_value != 0)
3774 print_method_list64_t(pc.instanceMethods + n_value, info, "\t");
3775
3776 outs() << "\t\t classMethods ";
3777 sym_name =
3778 get_symbol_64(offset + offsetof(struct protocol64_t, classMethods), S,
3779 info, n_value, pc.classMethods);
3780 if (n_value != 0) {
3781 if (info->verbose && sym_name != nullptr)
3782 outs() << sym_name;
3783 else
3784 outs() << format("0x%" PRIx64, n_value);
3785 if (pc.classMethods != 0)
3786 outs() << " + " << format("0x%" PRIx64, pc.classMethods);
3787 } else
3788 outs() << format("0x%" PRIx64, pc.classMethods);
3789 outs() << " (struct method_list_t *)\n";
3790 if (pc.classMethods + n_value != 0)
3791 print_method_list64_t(pc.classMethods + n_value, info, "\t");
3792
3793 outs() << "\t optionalInstanceMethods "
3794 << format("0x%" PRIx64, pc.optionalInstanceMethods) << "\n";
3795 outs() << "\t optionalClassMethods "
3796 << format("0x%" PRIx64, pc.optionalClassMethods) << "\n";
3797 outs() << "\t instanceProperties "
3798 << format("0x%" PRIx64, pc.instanceProperties) << "\n";
3799
3800 p += sizeof(uint64_t);
3801 offset += sizeof(uint64_t);
3802 }
3803}
3804
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003805static void print_protocol_list32_t(uint32_t p, struct DisassembleInfo *info) {
3806 struct protocol_list32_t pl;
3807 uint32_t q;
3808 struct protocol32_t pc;
3809 const char *r;
3810 uint32_t offset, xoffset, left, i;
3811 SectionRef S, xS;
3812 const char *name;
3813
3814 r = get_pointer_32(p, offset, left, S, info);
3815 if (r == nullptr)
3816 return;
3817 memset(&pl, '\0', sizeof(struct protocol_list32_t));
3818 if (left < sizeof(struct protocol_list32_t)) {
3819 memcpy(&pl, r, left);
3820 outs() << " (protocol_list_t entends past the end of the section)\n";
3821 } else
3822 memcpy(&pl, r, sizeof(struct protocol_list32_t));
3823 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3824 swapStruct(pl);
3825 outs() << " count " << pl.count << "\n";
3826
3827 p += sizeof(struct protocol_list32_t);
3828 offset += sizeof(struct protocol_list32_t);
3829 for (i = 0; i < pl.count; i++) {
3830 r = get_pointer_32(p, offset, left, S, info);
3831 if (r == nullptr)
3832 return;
3833 q = 0;
3834 if (left < sizeof(uint32_t)) {
3835 memcpy(&q, r, left);
3836 outs() << " (protocol_t * entends past the end of the section)\n";
3837 } else
3838 memcpy(&q, r, sizeof(uint32_t));
3839 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3840 sys::swapByteOrder(q);
3841 outs() << "\t\t list[" << i << "] " << format("0x%" PRIx32, q)
3842 << " (struct protocol_t *)\n";
3843 r = get_pointer_32(q, offset, left, S, info);
3844 if (r == nullptr)
3845 return;
3846 memset(&pc, '\0', sizeof(struct protocol32_t));
3847 if (left < sizeof(struct protocol32_t)) {
3848 memcpy(&pc, r, left);
3849 outs() << " (protocol_t entends past the end of the section)\n";
3850 } else
3851 memcpy(&pc, r, sizeof(struct protocol32_t));
3852 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3853 swapStruct(pc);
3854 outs() << "\t\t\t isa " << format("0x%" PRIx32, pc.isa) << "\n";
3855 outs() << "\t\t\t name " << format("0x%" PRIx32, pc.name);
3856 name = get_pointer_32(pc.name, xoffset, left, xS, info);
3857 if (name != nullptr)
3858 outs() << format(" %.*s", left, name);
3859 outs() << "\n";
3860 outs() << "\t\t\tprotocols " << format("0x%" PRIx32, pc.protocols) << "\n";
3861 outs() << "\t\t instanceMethods "
3862 << format("0x%" PRIx32, pc.instanceMethods)
3863 << " (struct method_list_t *)\n";
3864 if (pc.instanceMethods != 0)
3865 print_method_list32_t(pc.instanceMethods, info, "\t");
3866 outs() << "\t\t classMethods " << format("0x%" PRIx32, pc.classMethods)
3867 << " (struct method_list_t *)\n";
3868 if (pc.classMethods != 0)
3869 print_method_list32_t(pc.classMethods, info, "\t");
3870 outs() << "\t optionalInstanceMethods "
3871 << format("0x%" PRIx32, pc.optionalInstanceMethods) << "\n";
3872 outs() << "\t optionalClassMethods "
3873 << format("0x%" PRIx32, pc.optionalClassMethods) << "\n";
3874 outs() << "\t instanceProperties "
3875 << format("0x%" PRIx32, pc.instanceProperties) << "\n";
3876 p += sizeof(uint32_t);
3877 offset += sizeof(uint32_t);
3878 }
3879}
3880
Kevin Enderby846c0002015-04-16 17:19:59 +00003881static void print_indent(uint32_t indent) {
3882 for (uint32_t i = 0; i < indent;) {
3883 if (indent - i >= 8) {
3884 outs() << "\t";
3885 i += 8;
3886 } else {
3887 for (uint32_t j = i; j < indent; j++)
3888 outs() << " ";
3889 return;
3890 }
3891 }
3892}
3893
3894static bool print_method_description_list(uint32_t p, uint32_t indent,
3895 struct DisassembleInfo *info) {
3896 uint32_t offset, left, xleft;
3897 SectionRef S;
3898 struct objc_method_description_list_t mdl;
3899 struct objc_method_description_t md;
3900 const char *r, *list, *name;
3901 int32_t i;
3902
3903 r = get_pointer_32(p, offset, left, S, info, true);
3904 if (r == nullptr)
3905 return true;
3906
3907 outs() << "\n";
3908 if (left > sizeof(struct objc_method_description_list_t)) {
3909 memcpy(&mdl, r, sizeof(struct objc_method_description_list_t));
3910 } else {
3911 print_indent(indent);
3912 outs() << " objc_method_description_list extends past end of the section\n";
3913 memset(&mdl, '\0', sizeof(struct objc_method_description_list_t));
3914 memcpy(&mdl, r, left);
3915 }
3916 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3917 swapStruct(mdl);
3918
3919 print_indent(indent);
3920 outs() << " count " << mdl.count << "\n";
3921
3922 list = r + sizeof(struct objc_method_description_list_t);
3923 for (i = 0; i < mdl.count; i++) {
3924 if ((i + 1) * sizeof(struct objc_method_description_t) > left) {
3925 print_indent(indent);
3926 outs() << " remaining list entries extend past the of the section\n";
3927 break;
3928 }
3929 print_indent(indent);
3930 outs() << " list[" << i << "]\n";
3931 memcpy(&md, list + i * sizeof(struct objc_method_description_t),
3932 sizeof(struct objc_method_description_t));
3933 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3934 swapStruct(md);
3935
3936 print_indent(indent);
3937 outs() << " name " << format("0x%08" PRIx32, md.name);
3938 if (info->verbose) {
3939 name = get_pointer_32(md.name, offset, xleft, S, info, true);
3940 if (name != nullptr)
3941 outs() << format(" %.*s", xleft, name);
3942 else
3943 outs() << " (not in an __OBJC section)";
3944 }
3945 outs() << "\n";
3946
3947 print_indent(indent);
3948 outs() << " types " << format("0x%08" PRIx32, md.types);
3949 if (info->verbose) {
3950 name = get_pointer_32(md.types, offset, xleft, S, info, true);
3951 if (name != nullptr)
3952 outs() << format(" %.*s", xleft, name);
3953 else
3954 outs() << " (not in an __OBJC section)";
3955 }
3956 outs() << "\n";
3957 }
3958 return false;
3959}
3960
3961static bool print_protocol_list(uint32_t p, uint32_t indent,
3962 struct DisassembleInfo *info);
3963
3964static bool print_protocol(uint32_t p, uint32_t indent,
3965 struct DisassembleInfo *info) {
3966 uint32_t offset, left;
3967 SectionRef S;
3968 struct objc_protocol_t protocol;
3969 const char *r, *name;
3970
3971 r = get_pointer_32(p, offset, left, S, info, true);
3972 if (r == nullptr)
3973 return true;
3974
3975 outs() << "\n";
3976 if (left >= sizeof(struct objc_protocol_t)) {
3977 memcpy(&protocol, r, sizeof(struct objc_protocol_t));
3978 } else {
3979 print_indent(indent);
3980 outs() << " Protocol extends past end of the section\n";
3981 memset(&protocol, '\0', sizeof(struct objc_protocol_t));
3982 memcpy(&protocol, r, left);
3983 }
3984 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3985 swapStruct(protocol);
3986
3987 print_indent(indent);
3988 outs() << " isa " << format("0x%08" PRIx32, protocol.isa)
3989 << "\n";
3990
3991 print_indent(indent);
3992 outs() << " protocol_name "
3993 << format("0x%08" PRIx32, protocol.protocol_name);
3994 if (info->verbose) {
3995 name = get_pointer_32(protocol.protocol_name, offset, left, S, info, true);
3996 if (name != nullptr)
3997 outs() << format(" %.*s", left, name);
3998 else
3999 outs() << " (not in an __OBJC section)";
4000 }
4001 outs() << "\n";
4002
4003 print_indent(indent);
4004 outs() << " protocol_list "
4005 << format("0x%08" PRIx32, protocol.protocol_list);
4006 if (print_protocol_list(protocol.protocol_list, indent + 4, info))
4007 outs() << " (not in an __OBJC section)\n";
4008
4009 print_indent(indent);
4010 outs() << " instance_methods "
4011 << format("0x%08" PRIx32, protocol.instance_methods);
4012 if (print_method_description_list(protocol.instance_methods, indent, info))
4013 outs() << " (not in an __OBJC section)\n";
4014
4015 print_indent(indent);
4016 outs() << " class_methods "
4017 << format("0x%08" PRIx32, protocol.class_methods);
4018 if (print_method_description_list(protocol.class_methods, indent, info))
4019 outs() << " (not in an __OBJC section)\n";
4020
4021 return false;
4022}
4023
4024static bool print_protocol_list(uint32_t p, uint32_t indent,
4025 struct DisassembleInfo *info) {
4026 uint32_t offset, left, l;
4027 SectionRef S;
4028 struct objc_protocol_list_t protocol_list;
4029 const char *r, *list;
4030 int32_t i;
4031
4032 r = get_pointer_32(p, offset, left, S, info, true);
4033 if (r == nullptr)
4034 return true;
4035
4036 outs() << "\n";
4037 if (left > sizeof(struct objc_protocol_list_t)) {
4038 memcpy(&protocol_list, r, sizeof(struct objc_protocol_list_t));
4039 } else {
4040 outs() << "\t\t objc_protocol_list_t extends past end of the section\n";
4041 memset(&protocol_list, '\0', sizeof(struct objc_protocol_list_t));
4042 memcpy(&protocol_list, r, left);
4043 }
4044 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4045 swapStruct(protocol_list);
4046
4047 print_indent(indent);
4048 outs() << " next " << format("0x%08" PRIx32, protocol_list.next)
4049 << "\n";
4050 print_indent(indent);
4051 outs() << " count " << protocol_list.count << "\n";
4052
4053 list = r + sizeof(struct objc_protocol_list_t);
4054 for (i = 0; i < protocol_list.count; i++) {
4055 if ((i + 1) * sizeof(uint32_t) > left) {
4056 outs() << "\t\t remaining list entries extend past the of the section\n";
4057 break;
4058 }
4059 memcpy(&l, list + i * sizeof(uint32_t), sizeof(uint32_t));
4060 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4061 sys::swapByteOrder(l);
4062
4063 print_indent(indent);
4064 outs() << " list[" << i << "] " << format("0x%08" PRIx32, l);
4065 if (print_protocol(l, indent, info))
4066 outs() << "(not in an __OBJC section)\n";
4067 }
4068 return false;
4069}
4070
Kevin Enderby0fc11822015-04-01 20:57:01 +00004071static void print_ivar_list64_t(uint64_t p, struct DisassembleInfo *info) {
4072 struct ivar_list64_t il;
4073 struct ivar64_t i;
4074 const char *r;
4075 uint32_t offset, xoffset, left, j;
4076 SectionRef S, xS;
4077 const char *name, *sym_name, *ivar_offset_p;
4078 uint64_t ivar_offset, n_value;
4079
4080 r = get_pointer_64(p, offset, left, S, info);
4081 if (r == nullptr)
4082 return;
4083 memset(&il, '\0', sizeof(struct ivar_list64_t));
4084 if (left < sizeof(struct ivar_list64_t)) {
4085 memcpy(&il, r, left);
4086 outs() << " (ivar_list_t entends past the end of the section)\n";
4087 } else
4088 memcpy(&il, r, sizeof(struct ivar_list64_t));
4089 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4090 swapStruct(il);
4091 outs() << " entsize " << il.entsize << "\n";
4092 outs() << " count " << il.count << "\n";
4093
4094 p += sizeof(struct ivar_list64_t);
4095 offset += sizeof(struct ivar_list64_t);
4096 for (j = 0; j < il.count; j++) {
4097 r = get_pointer_64(p, offset, left, S, info);
4098 if (r == nullptr)
4099 return;
4100 memset(&i, '\0', sizeof(struct ivar64_t));
4101 if (left < sizeof(struct ivar64_t)) {
4102 memcpy(&i, r, left);
4103 outs() << " (ivar_t entends past the end of the section)\n";
4104 } else
4105 memcpy(&i, r, sizeof(struct ivar64_t));
4106 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4107 swapStruct(i);
4108
4109 outs() << "\t\t\t offset ";
4110 sym_name = get_symbol_64(offset + offsetof(struct ivar64_t, offset), S,
4111 info, n_value, i.offset);
4112 if (n_value != 0) {
4113 if (info->verbose && sym_name != nullptr)
4114 outs() << sym_name;
4115 else
4116 outs() << format("0x%" PRIx64, n_value);
4117 if (i.offset != 0)
4118 outs() << " + " << format("0x%" PRIx64, i.offset);
4119 } else
4120 outs() << format("0x%" PRIx64, i.offset);
4121 ivar_offset_p = get_pointer_64(i.offset + n_value, xoffset, left, xS, info);
4122 if (ivar_offset_p != nullptr && left >= sizeof(*ivar_offset_p)) {
4123 memcpy(&ivar_offset, ivar_offset_p, sizeof(ivar_offset));
4124 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4125 sys::swapByteOrder(ivar_offset);
4126 outs() << " " << ivar_offset << "\n";
4127 } else
4128 outs() << "\n";
4129
4130 outs() << "\t\t\t name ";
4131 sym_name = get_symbol_64(offset + offsetof(struct ivar64_t, name), S, info,
4132 n_value, i.name);
4133 if (n_value != 0) {
4134 if (info->verbose && sym_name != nullptr)
4135 outs() << sym_name;
4136 else
4137 outs() << format("0x%" PRIx64, n_value);
4138 if (i.name != 0)
4139 outs() << " + " << format("0x%" PRIx64, i.name);
4140 } else
4141 outs() << format("0x%" PRIx64, i.name);
4142 name = get_pointer_64(i.name + n_value, xoffset, left, xS, info);
4143 if (name != nullptr)
4144 outs() << format(" %.*s", left, name);
4145 outs() << "\n";
4146
4147 outs() << "\t\t\t type ";
4148 sym_name = get_symbol_64(offset + offsetof(struct ivar64_t, type), S, info,
4149 n_value, i.name);
4150 name = get_pointer_64(i.type + n_value, xoffset, left, xS, info);
4151 if (n_value != 0) {
4152 if (info->verbose && sym_name != nullptr)
4153 outs() << sym_name;
4154 else
4155 outs() << format("0x%" PRIx64, n_value);
4156 if (i.type != 0)
4157 outs() << " + " << format("0x%" PRIx64, i.type);
4158 } else
4159 outs() << format("0x%" PRIx64, i.type);
4160 if (name != nullptr)
4161 outs() << format(" %.*s", left, name);
4162 outs() << "\n";
4163
4164 outs() << "\t\t\talignment " << i.alignment << "\n";
4165 outs() << "\t\t\t size " << i.size << "\n";
4166
4167 p += sizeof(struct ivar64_t);
4168 offset += sizeof(struct ivar64_t);
4169 }
4170}
4171
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004172static void print_ivar_list32_t(uint32_t p, struct DisassembleInfo *info) {
4173 struct ivar_list32_t il;
4174 struct ivar32_t i;
4175 const char *r;
4176 uint32_t offset, xoffset, left, j;
4177 SectionRef S, xS;
4178 const char *name, *ivar_offset_p;
4179 uint32_t ivar_offset;
4180
4181 r = get_pointer_32(p, offset, left, S, info);
4182 if (r == nullptr)
4183 return;
4184 memset(&il, '\0', sizeof(struct ivar_list32_t));
4185 if (left < sizeof(struct ivar_list32_t)) {
4186 memcpy(&il, r, left);
4187 outs() << " (ivar_list_t entends past the end of the section)\n";
4188 } else
4189 memcpy(&il, r, sizeof(struct ivar_list32_t));
4190 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4191 swapStruct(il);
4192 outs() << " entsize " << il.entsize << "\n";
4193 outs() << " count " << il.count << "\n";
4194
4195 p += sizeof(struct ivar_list32_t);
4196 offset += sizeof(struct ivar_list32_t);
4197 for (j = 0; j < il.count; j++) {
4198 r = get_pointer_32(p, offset, left, S, info);
4199 if (r == nullptr)
4200 return;
4201 memset(&i, '\0', sizeof(struct ivar32_t));
4202 if (left < sizeof(struct ivar32_t)) {
4203 memcpy(&i, r, left);
4204 outs() << " (ivar_t entends past the end of the section)\n";
4205 } else
4206 memcpy(&i, r, sizeof(struct ivar32_t));
4207 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4208 swapStruct(i);
4209
4210 outs() << "\t\t\t offset " << format("0x%" PRIx32, i.offset);
4211 ivar_offset_p = get_pointer_32(i.offset, xoffset, left, xS, info);
4212 if (ivar_offset_p != nullptr && left >= sizeof(*ivar_offset_p)) {
4213 memcpy(&ivar_offset, ivar_offset_p, sizeof(ivar_offset));
4214 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4215 sys::swapByteOrder(ivar_offset);
4216 outs() << " " << ivar_offset << "\n";
4217 } else
4218 outs() << "\n";
4219
4220 outs() << "\t\t\t name " << format("0x%" PRIx32, i.name);
4221 name = get_pointer_32(i.name, xoffset, left, xS, info);
4222 if (name != nullptr)
4223 outs() << format(" %.*s", left, name);
4224 outs() << "\n";
4225
4226 outs() << "\t\t\t type " << format("0x%" PRIx32, i.type);
4227 name = get_pointer_32(i.type, xoffset, left, xS, info);
4228 if (name != nullptr)
4229 outs() << format(" %.*s", left, name);
4230 outs() << "\n";
4231
4232 outs() << "\t\t\talignment " << i.alignment << "\n";
4233 outs() << "\t\t\t size " << i.size << "\n";
4234
4235 p += sizeof(struct ivar32_t);
4236 offset += sizeof(struct ivar32_t);
4237 }
4238}
4239
Kevin Enderby0fc11822015-04-01 20:57:01 +00004240static void print_objc_property_list64(uint64_t p,
4241 struct DisassembleInfo *info) {
4242 struct objc_property_list64 opl;
4243 struct objc_property64 op;
4244 const char *r;
4245 uint32_t offset, xoffset, left, j;
4246 SectionRef S, xS;
4247 const char *name, *sym_name;
4248 uint64_t n_value;
4249
4250 r = get_pointer_64(p, offset, left, S, info);
4251 if (r == nullptr)
4252 return;
4253 memset(&opl, '\0', sizeof(struct objc_property_list64));
4254 if (left < sizeof(struct objc_property_list64)) {
4255 memcpy(&opl, r, left);
4256 outs() << " (objc_property_list entends past the end of the section)\n";
4257 } else
4258 memcpy(&opl, r, sizeof(struct objc_property_list64));
4259 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4260 swapStruct(opl);
4261 outs() << " entsize " << opl.entsize << "\n";
4262 outs() << " count " << opl.count << "\n";
4263
4264 p += sizeof(struct objc_property_list64);
4265 offset += sizeof(struct objc_property_list64);
4266 for (j = 0; j < opl.count; j++) {
4267 r = get_pointer_64(p, offset, left, S, info);
4268 if (r == nullptr)
4269 return;
4270 memset(&op, '\0', sizeof(struct objc_property64));
4271 if (left < sizeof(struct objc_property64)) {
4272 memcpy(&op, r, left);
4273 outs() << " (objc_property entends past the end of the section)\n";
4274 } else
4275 memcpy(&op, r, sizeof(struct objc_property64));
4276 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4277 swapStruct(op);
4278
4279 outs() << "\t\t\t name ";
4280 sym_name = get_symbol_64(offset + offsetof(struct objc_property64, name), S,
4281 info, n_value, op.name);
4282 if (n_value != 0) {
4283 if (info->verbose && sym_name != nullptr)
4284 outs() << sym_name;
4285 else
4286 outs() << format("0x%" PRIx64, n_value);
4287 if (op.name != 0)
4288 outs() << " + " << format("0x%" PRIx64, op.name);
4289 } else
4290 outs() << format("0x%" PRIx64, op.name);
4291 name = get_pointer_64(op.name + n_value, xoffset, left, xS, info);
4292 if (name != nullptr)
4293 outs() << format(" %.*s", left, name);
4294 outs() << "\n";
4295
4296 outs() << "\t\t\tattributes ";
4297 sym_name =
4298 get_symbol_64(offset + offsetof(struct objc_property64, attributes), S,
4299 info, n_value, op.attributes);
4300 if (n_value != 0) {
4301 if (info->verbose && sym_name != nullptr)
4302 outs() << sym_name;
4303 else
4304 outs() << format("0x%" PRIx64, n_value);
4305 if (op.attributes != 0)
4306 outs() << " + " << format("0x%" PRIx64, op.attributes);
4307 } else
4308 outs() << format("0x%" PRIx64, op.attributes);
4309 name = get_pointer_64(op.attributes + n_value, xoffset, left, xS, info);
4310 if (name != nullptr)
4311 outs() << format(" %.*s", left, name);
4312 outs() << "\n";
4313
4314 p += sizeof(struct objc_property64);
4315 offset += sizeof(struct objc_property64);
4316 }
4317}
4318
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004319static void print_objc_property_list32(uint32_t p,
4320 struct DisassembleInfo *info) {
4321 struct objc_property_list32 opl;
4322 struct objc_property32 op;
4323 const char *r;
4324 uint32_t offset, xoffset, left, j;
4325 SectionRef S, xS;
4326 const char *name;
4327
4328 r = get_pointer_32(p, offset, left, S, info);
4329 if (r == nullptr)
4330 return;
4331 memset(&opl, '\0', sizeof(struct objc_property_list32));
4332 if (left < sizeof(struct objc_property_list32)) {
4333 memcpy(&opl, r, left);
4334 outs() << " (objc_property_list entends past the end of the section)\n";
4335 } else
4336 memcpy(&opl, r, sizeof(struct objc_property_list32));
4337 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4338 swapStruct(opl);
4339 outs() << " entsize " << opl.entsize << "\n";
4340 outs() << " count " << opl.count << "\n";
4341
4342 p += sizeof(struct objc_property_list32);
4343 offset += sizeof(struct objc_property_list32);
4344 for (j = 0; j < opl.count; j++) {
4345 r = get_pointer_32(p, offset, left, S, info);
4346 if (r == nullptr)
4347 return;
4348 memset(&op, '\0', sizeof(struct objc_property32));
4349 if (left < sizeof(struct objc_property32)) {
4350 memcpy(&op, r, left);
4351 outs() << " (objc_property entends past the end of the section)\n";
4352 } else
4353 memcpy(&op, r, sizeof(struct objc_property32));
4354 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4355 swapStruct(op);
4356
4357 outs() << "\t\t\t name " << format("0x%" PRIx32, op.name);
4358 name = get_pointer_32(op.name, xoffset, left, xS, info);
4359 if (name != nullptr)
4360 outs() << format(" %.*s", left, name);
4361 outs() << "\n";
4362
4363 outs() << "\t\t\tattributes " << format("0x%" PRIx32, op.attributes);
4364 name = get_pointer_32(op.attributes, xoffset, left, xS, info);
4365 if (name != nullptr)
4366 outs() << format(" %.*s", left, name);
4367 outs() << "\n";
4368
4369 p += sizeof(struct objc_property32);
4370 offset += sizeof(struct objc_property32);
4371 }
4372}
4373
Richard Smith81ff44d2015-10-09 22:09:56 +00004374static bool print_class_ro64_t(uint64_t p, struct DisassembleInfo *info,
Kevin Enderby0fc11822015-04-01 20:57:01 +00004375 bool &is_meta_class) {
4376 struct class_ro64_t cro;
4377 const char *r;
4378 uint32_t offset, xoffset, left;
4379 SectionRef S, xS;
4380 const char *name, *sym_name;
4381 uint64_t n_value;
4382
4383 r = get_pointer_64(p, offset, left, S, info);
4384 if (r == nullptr || left < sizeof(struct class_ro64_t))
Richard Smith81ff44d2015-10-09 22:09:56 +00004385 return false;
Kevin Enderby0fc11822015-04-01 20:57:01 +00004386 memset(&cro, '\0', sizeof(struct class_ro64_t));
4387 if (left < sizeof(struct class_ro64_t)) {
4388 memcpy(&cro, r, left);
4389 outs() << " (class_ro_t entends past the end of the section)\n";
4390 } else
4391 memcpy(&cro, r, sizeof(struct class_ro64_t));
4392 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4393 swapStruct(cro);
4394 outs() << " flags " << format("0x%" PRIx32, cro.flags);
4395 if (cro.flags & RO_META)
4396 outs() << " RO_META";
4397 if (cro.flags & RO_ROOT)
4398 outs() << " RO_ROOT";
4399 if (cro.flags & RO_HAS_CXX_STRUCTORS)
4400 outs() << " RO_HAS_CXX_STRUCTORS";
4401 outs() << "\n";
4402 outs() << " instanceStart " << cro.instanceStart << "\n";
4403 outs() << " instanceSize " << cro.instanceSize << "\n";
4404 outs() << " reserved " << format("0x%" PRIx32, cro.reserved)
4405 << "\n";
4406 outs() << " ivarLayout " << format("0x%" PRIx64, cro.ivarLayout)
4407 << "\n";
4408 print_layout_map64(cro.ivarLayout, info);
4409
4410 outs() << " name ";
4411 sym_name = get_symbol_64(offset + offsetof(struct class_ro64_t, name), S,
4412 info, n_value, cro.name);
4413 if (n_value != 0) {
4414 if (info->verbose && sym_name != nullptr)
4415 outs() << sym_name;
4416 else
4417 outs() << format("0x%" PRIx64, n_value);
4418 if (cro.name != 0)
4419 outs() << " + " << format("0x%" PRIx64, cro.name);
4420 } else
4421 outs() << format("0x%" PRIx64, cro.name);
4422 name = get_pointer_64(cro.name + n_value, xoffset, left, xS, info);
4423 if (name != nullptr)
4424 outs() << format(" %.*s", left, name);
4425 outs() << "\n";
4426
4427 outs() << " baseMethods ";
4428 sym_name = get_symbol_64(offset + offsetof(struct class_ro64_t, baseMethods),
4429 S, info, n_value, cro.baseMethods);
4430 if (n_value != 0) {
4431 if (info->verbose && sym_name != nullptr)
4432 outs() << sym_name;
4433 else
4434 outs() << format("0x%" PRIx64, n_value);
4435 if (cro.baseMethods != 0)
4436 outs() << " + " << format("0x%" PRIx64, cro.baseMethods);
4437 } else
4438 outs() << format("0x%" PRIx64, cro.baseMethods);
4439 outs() << " (struct method_list_t *)\n";
4440 if (cro.baseMethods + n_value != 0)
4441 print_method_list64_t(cro.baseMethods + n_value, info, "");
4442
4443 outs() << " baseProtocols ";
4444 sym_name =
4445 get_symbol_64(offset + offsetof(struct class_ro64_t, baseProtocols), S,
4446 info, n_value, cro.baseProtocols);
4447 if (n_value != 0) {
4448 if (info->verbose && sym_name != nullptr)
4449 outs() << sym_name;
4450 else
4451 outs() << format("0x%" PRIx64, n_value);
4452 if (cro.baseProtocols != 0)
4453 outs() << " + " << format("0x%" PRIx64, cro.baseProtocols);
4454 } else
4455 outs() << format("0x%" PRIx64, cro.baseProtocols);
4456 outs() << "\n";
4457 if (cro.baseProtocols + n_value != 0)
4458 print_protocol_list64_t(cro.baseProtocols + n_value, info);
4459
4460 outs() << " ivars ";
4461 sym_name = get_symbol_64(offset + offsetof(struct class_ro64_t, ivars), S,
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004462 info, n_value, cro.ivars);
Kevin Enderby0fc11822015-04-01 20:57:01 +00004463 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.ivars != 0)
4469 outs() << " + " << format("0x%" PRIx64, cro.ivars);
4470 } else
4471 outs() << format("0x%" PRIx64, cro.ivars);
4472 outs() << "\n";
4473 if (cro.ivars + n_value != 0)
4474 print_ivar_list64_t(cro.ivars + n_value, info);
4475
4476 outs() << " weakIvarLayout ";
4477 sym_name =
4478 get_symbol_64(offset + offsetof(struct class_ro64_t, weakIvarLayout), S,
4479 info, n_value, cro.weakIvarLayout);
4480 if (n_value != 0) {
4481 if (info->verbose && sym_name != nullptr)
4482 outs() << sym_name;
4483 else
4484 outs() << format("0x%" PRIx64, n_value);
4485 if (cro.weakIvarLayout != 0)
4486 outs() << " + " << format("0x%" PRIx64, cro.weakIvarLayout);
4487 } else
4488 outs() << format("0x%" PRIx64, cro.weakIvarLayout);
4489 outs() << "\n";
4490 print_layout_map64(cro.weakIvarLayout + n_value, info);
4491
4492 outs() << " baseProperties ";
4493 sym_name =
4494 get_symbol_64(offset + offsetof(struct class_ro64_t, baseProperties), S,
4495 info, n_value, cro.baseProperties);
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.baseProperties != 0)
4502 outs() << " + " << format("0x%" PRIx64, cro.baseProperties);
4503 } else
4504 outs() << format("0x%" PRIx64, cro.baseProperties);
4505 outs() << "\n";
4506 if (cro.baseProperties + n_value != 0)
4507 print_objc_property_list64(cro.baseProperties + n_value, info);
4508
Rafael Espindolab9091322015-10-24 23:19:10 +00004509 is_meta_class = (cro.flags & RO_META) != 0;
Richard Smith81ff44d2015-10-09 22:09:56 +00004510 return true;
Kevin Enderby0fc11822015-04-01 20:57:01 +00004511}
4512
Richard Smith81ff44d2015-10-09 22:09:56 +00004513static bool print_class_ro32_t(uint32_t p, struct DisassembleInfo *info,
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004514 bool &is_meta_class) {
4515 struct class_ro32_t cro;
4516 const char *r;
4517 uint32_t offset, xoffset, left;
4518 SectionRef S, xS;
4519 const char *name;
4520
4521 r = get_pointer_32(p, offset, left, S, info);
4522 if (r == nullptr)
Richard Smith81ff44d2015-10-09 22:09:56 +00004523 return false;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004524 memset(&cro, '\0', sizeof(struct class_ro32_t));
4525 if (left < sizeof(struct class_ro32_t)) {
4526 memcpy(&cro, r, left);
4527 outs() << " (class_ro_t entends past the end of the section)\n";
4528 } else
4529 memcpy(&cro, r, sizeof(struct class_ro32_t));
4530 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4531 swapStruct(cro);
4532 outs() << " flags " << format("0x%" PRIx32, cro.flags);
4533 if (cro.flags & RO_META)
4534 outs() << " RO_META";
4535 if (cro.flags & RO_ROOT)
4536 outs() << " RO_ROOT";
4537 if (cro.flags & RO_HAS_CXX_STRUCTORS)
4538 outs() << " RO_HAS_CXX_STRUCTORS";
4539 outs() << "\n";
4540 outs() << " instanceStart " << cro.instanceStart << "\n";
4541 outs() << " instanceSize " << cro.instanceSize << "\n";
4542 outs() << " ivarLayout " << format("0x%" PRIx32, cro.ivarLayout)
4543 << "\n";
4544 print_layout_map32(cro.ivarLayout, info);
4545
4546 outs() << " name " << format("0x%" PRIx32, cro.name);
4547 name = get_pointer_32(cro.name, xoffset, left, xS, info);
4548 if (name != nullptr)
4549 outs() << format(" %.*s", left, name);
4550 outs() << "\n";
4551
4552 outs() << " baseMethods "
4553 << format("0x%" PRIx32, cro.baseMethods)
4554 << " (struct method_list_t *)\n";
4555 if (cro.baseMethods != 0)
4556 print_method_list32_t(cro.baseMethods, info, "");
4557
4558 outs() << " baseProtocols "
4559 << format("0x%" PRIx32, cro.baseProtocols) << "\n";
4560 if (cro.baseProtocols != 0)
4561 print_protocol_list32_t(cro.baseProtocols, info);
4562 outs() << " ivars " << format("0x%" PRIx32, cro.ivars)
4563 << "\n";
4564 if (cro.ivars != 0)
4565 print_ivar_list32_t(cro.ivars, info);
4566 outs() << " weakIvarLayout "
4567 << format("0x%" PRIx32, cro.weakIvarLayout) << "\n";
4568 print_layout_map32(cro.weakIvarLayout, info);
4569 outs() << " baseProperties "
4570 << format("0x%" PRIx32, cro.baseProperties) << "\n";
4571 if (cro.baseProperties != 0)
4572 print_objc_property_list32(cro.baseProperties, info);
Rafael Espindolab9091322015-10-24 23:19:10 +00004573 is_meta_class = (cro.flags & RO_META) != 0;
Richard Smith81ff44d2015-10-09 22:09:56 +00004574 return true;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004575}
4576
Kevin Enderby0fc11822015-04-01 20:57:01 +00004577static void print_class64_t(uint64_t p, struct DisassembleInfo *info) {
4578 struct class64_t c;
4579 const char *r;
4580 uint32_t offset, left;
4581 SectionRef S;
4582 const char *name;
4583 uint64_t isa_n_value, n_value;
4584
4585 r = get_pointer_64(p, offset, left, S, info);
4586 if (r == nullptr || left < sizeof(struct class64_t))
4587 return;
4588 memset(&c, '\0', sizeof(struct class64_t));
4589 if (left < sizeof(struct class64_t)) {
4590 memcpy(&c, r, left);
4591 outs() << " (class_t entends past the end of the section)\n";
4592 } else
4593 memcpy(&c, r, sizeof(struct class64_t));
4594 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4595 swapStruct(c);
4596
4597 outs() << " isa " << format("0x%" PRIx64, c.isa);
4598 name = get_symbol_64(offset + offsetof(struct class64_t, isa), S, info,
4599 isa_n_value, c.isa);
4600 if (name != nullptr)
4601 outs() << " " << name;
4602 outs() << "\n";
4603
4604 outs() << " superclass " << format("0x%" PRIx64, c.superclass);
4605 name = get_symbol_64(offset + offsetof(struct class64_t, superclass), S, info,
4606 n_value, c.superclass);
4607 if (name != nullptr)
4608 outs() << " " << name;
4609 outs() << "\n";
4610
4611 outs() << " cache " << format("0x%" PRIx64, c.cache);
4612 name = get_symbol_64(offset + offsetof(struct class64_t, cache), S, info,
4613 n_value, c.cache);
4614 if (name != nullptr)
4615 outs() << " " << name;
4616 outs() << "\n";
4617
4618 outs() << " vtable " << format("0x%" PRIx64, c.vtable);
4619 name = get_symbol_64(offset + offsetof(struct class64_t, vtable), S, info,
4620 n_value, c.vtable);
4621 if (name != nullptr)
4622 outs() << " " << name;
4623 outs() << "\n";
4624
4625 name = get_symbol_64(offset + offsetof(struct class64_t, data), S, info,
4626 n_value, c.data);
4627 outs() << " data ";
4628 if (n_value != 0) {
4629 if (info->verbose && name != nullptr)
4630 outs() << name;
4631 else
4632 outs() << format("0x%" PRIx64, n_value);
4633 if (c.data != 0)
4634 outs() << " + " << format("0x%" PRIx64, c.data);
4635 } else
4636 outs() << format("0x%" PRIx64, c.data);
4637 outs() << " (struct class_ro_t *)";
4638
4639 // This is a Swift class if some of the low bits of the pointer are set.
4640 if ((c.data + n_value) & 0x7)
4641 outs() << " Swift class";
4642 outs() << "\n";
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004643 bool is_meta_class;
Richard Smith81ff44d2015-10-09 22:09:56 +00004644 if (!print_class_ro64_t((c.data + n_value) & ~0x7, info, is_meta_class))
4645 return;
Kevin Enderby0fc11822015-04-01 20:57:01 +00004646
Kevin Enderbyaac75382015-10-08 16:56:35 +00004647 if (!is_meta_class &&
4648 c.isa + isa_n_value != p &&
4649 c.isa + isa_n_value != 0 &&
4650 info->depth < 100) {
4651 info->depth++;
4652 outs() << "Meta Class\n";
4653 print_class64_t(c.isa + isa_n_value, info);
Kevin Enderby0fc11822015-04-01 20:57:01 +00004654 }
4655}
4656
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004657static void print_class32_t(uint32_t p, struct DisassembleInfo *info) {
4658 struct class32_t c;
4659 const char *r;
4660 uint32_t offset, left;
4661 SectionRef S;
4662 const char *name;
4663
4664 r = get_pointer_32(p, offset, left, S, info);
4665 if (r == nullptr)
4666 return;
4667 memset(&c, '\0', sizeof(struct class32_t));
4668 if (left < sizeof(struct class32_t)) {
4669 memcpy(&c, r, left);
4670 outs() << " (class_t entends past the end of the section)\n";
4671 } else
4672 memcpy(&c, r, sizeof(struct class32_t));
4673 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4674 swapStruct(c);
4675
4676 outs() << " isa " << format("0x%" PRIx32, c.isa);
4677 name =
4678 get_symbol_32(offset + offsetof(struct class32_t, isa), S, info, c.isa);
4679 if (name != nullptr)
4680 outs() << " " << name;
4681 outs() << "\n";
4682
4683 outs() << " superclass " << format("0x%" PRIx32, c.superclass);
4684 name = get_symbol_32(offset + offsetof(struct class32_t, superclass), S, info,
4685 c.superclass);
4686 if (name != nullptr)
4687 outs() << " " << name;
4688 outs() << "\n";
4689
4690 outs() << " cache " << format("0x%" PRIx32, c.cache);
4691 name = get_symbol_32(offset + offsetof(struct class32_t, cache), S, info,
4692 c.cache);
4693 if (name != nullptr)
4694 outs() << " " << name;
4695 outs() << "\n";
4696
4697 outs() << " vtable " << format("0x%" PRIx32, c.vtable);
4698 name = get_symbol_32(offset + offsetof(struct class32_t, vtable), S, info,
4699 c.vtable);
4700 if (name != nullptr)
4701 outs() << " " << name;
4702 outs() << "\n";
4703
4704 name =
4705 get_symbol_32(offset + offsetof(struct class32_t, data), S, info, c.data);
4706 outs() << " data " << format("0x%" PRIx32, c.data)
4707 << " (struct class_ro_t *)";
4708
4709 // This is a Swift class if some of the low bits of the pointer are set.
4710 if (c.data & 0x3)
4711 outs() << " Swift class";
4712 outs() << "\n";
4713 bool is_meta_class;
Richard Smith81ff44d2015-10-09 22:09:56 +00004714 if (!print_class_ro32_t(c.data & ~0x3, info, is_meta_class))
4715 return;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004716
Hans Wennborgcc9deb42015-09-29 18:02:48 +00004717 if (!is_meta_class) {
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004718 outs() << "Meta Class\n";
4719 print_class32_t(c.isa, info);
4720 }
4721}
4722
Kevin Enderby846c0002015-04-16 17:19:59 +00004723static void print_objc_class_t(struct objc_class_t *objc_class,
4724 struct DisassembleInfo *info) {
4725 uint32_t offset, left, xleft;
4726 const char *name, *p, *ivar_list;
4727 SectionRef S;
4728 int32_t i;
4729 struct objc_ivar_list_t objc_ivar_list;
4730 struct objc_ivar_t ivar;
4731
4732 outs() << "\t\t isa " << format("0x%08" PRIx32, objc_class->isa);
4733 if (info->verbose && CLS_GETINFO(objc_class, CLS_META)) {
4734 name = get_pointer_32(objc_class->isa, offset, left, S, info, true);
4735 if (name != nullptr)
4736 outs() << format(" %.*s", left, name);
4737 else
4738 outs() << " (not in an __OBJC section)";
4739 }
4740 outs() << "\n";
4741
4742 outs() << "\t super_class "
4743 << format("0x%08" PRIx32, objc_class->super_class);
4744 if (info->verbose) {
4745 name = get_pointer_32(objc_class->super_class, offset, left, S, info, true);
4746 if (name != nullptr)
4747 outs() << format(" %.*s", left, name);
4748 else
4749 outs() << " (not in an __OBJC section)";
4750 }
4751 outs() << "\n";
4752
4753 outs() << "\t\t name " << format("0x%08" PRIx32, objc_class->name);
4754 if (info->verbose) {
4755 name = get_pointer_32(objc_class->name, offset, left, S, info, true);
4756 if (name != nullptr)
4757 outs() << format(" %.*s", left, name);
4758 else
4759 outs() << " (not in an __OBJC section)";
4760 }
4761 outs() << "\n";
4762
4763 outs() << "\t\t version " << format("0x%08" PRIx32, objc_class->version)
4764 << "\n";
4765
4766 outs() << "\t\t info " << format("0x%08" PRIx32, objc_class->info);
4767 if (info->verbose) {
4768 if (CLS_GETINFO(objc_class, CLS_CLASS))
4769 outs() << " CLS_CLASS";
4770 else if (CLS_GETINFO(objc_class, CLS_META))
4771 outs() << " CLS_META";
4772 }
4773 outs() << "\n";
4774
4775 outs() << "\t instance_size "
4776 << format("0x%08" PRIx32, objc_class->instance_size) << "\n";
4777
4778 p = get_pointer_32(objc_class->ivars, offset, left, S, info, true);
4779 outs() << "\t\t ivars " << format("0x%08" PRIx32, objc_class->ivars);
4780 if (p != nullptr) {
4781 if (left > sizeof(struct objc_ivar_list_t)) {
4782 outs() << "\n";
4783 memcpy(&objc_ivar_list, p, sizeof(struct objc_ivar_list_t));
4784 } else {
4785 outs() << " (entends past the end of the section)\n";
4786 memset(&objc_ivar_list, '\0', sizeof(struct objc_ivar_list_t));
4787 memcpy(&objc_ivar_list, p, left);
4788 }
4789 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4790 swapStruct(objc_ivar_list);
4791 outs() << "\t\t ivar_count " << objc_ivar_list.ivar_count << "\n";
4792 ivar_list = p + sizeof(struct objc_ivar_list_t);
4793 for (i = 0; i < objc_ivar_list.ivar_count; i++) {
4794 if ((i + 1) * sizeof(struct objc_ivar_t) > left) {
4795 outs() << "\t\t remaining ivar's extend past the of the section\n";
4796 break;
4797 }
4798 memcpy(&ivar, ivar_list + i * sizeof(struct objc_ivar_t),
4799 sizeof(struct objc_ivar_t));
4800 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4801 swapStruct(ivar);
4802
4803 outs() << "\t\t\tivar_name " << format("0x%08" PRIx32, ivar.ivar_name);
4804 if (info->verbose) {
4805 name = get_pointer_32(ivar.ivar_name, offset, xleft, S, info, true);
4806 if (name != nullptr)
4807 outs() << format(" %.*s", xleft, name);
4808 else
4809 outs() << " (not in an __OBJC section)";
4810 }
4811 outs() << "\n";
4812
4813 outs() << "\t\t\tivar_type " << format("0x%08" PRIx32, ivar.ivar_type);
4814 if (info->verbose) {
4815 name = get_pointer_32(ivar.ivar_type, offset, xleft, S, info, true);
4816 if (name != nullptr)
4817 outs() << format(" %.*s", xleft, name);
4818 else
4819 outs() << " (not in an __OBJC section)";
4820 }
4821 outs() << "\n";
4822
4823 outs() << "\t\t ivar_offset "
4824 << format("0x%08" PRIx32, ivar.ivar_offset) << "\n";
4825 }
4826 } else {
4827 outs() << " (not in an __OBJC section)\n";
4828 }
4829
4830 outs() << "\t\t methods " << format("0x%08" PRIx32, objc_class->methodLists);
4831 if (print_method_list(objc_class->methodLists, info))
4832 outs() << " (not in an __OBJC section)\n";
4833
4834 outs() << "\t\t cache " << format("0x%08" PRIx32, objc_class->cache)
4835 << "\n";
4836
4837 outs() << "\t\tprotocols " << format("0x%08" PRIx32, objc_class->protocols);
4838 if (print_protocol_list(objc_class->protocols, 16, info))
4839 outs() << " (not in an __OBJC section)\n";
4840}
4841
4842static void print_objc_objc_category_t(struct objc_category_t *objc_category,
4843 struct DisassembleInfo *info) {
4844 uint32_t offset, left;
4845 const char *name;
4846 SectionRef S;
4847
4848 outs() << "\t category name "
4849 << format("0x%08" PRIx32, objc_category->category_name);
4850 if (info->verbose) {
4851 name = get_pointer_32(objc_category->category_name, offset, left, S, info,
4852 true);
4853 if (name != nullptr)
4854 outs() << format(" %.*s", left, name);
4855 else
4856 outs() << " (not in an __OBJC section)";
4857 }
4858 outs() << "\n";
4859
4860 outs() << "\t\t class name "
4861 << format("0x%08" PRIx32, objc_category->class_name);
4862 if (info->verbose) {
4863 name =
4864 get_pointer_32(objc_category->class_name, offset, left, S, info, true);
4865 if (name != nullptr)
4866 outs() << format(" %.*s", left, name);
4867 else
4868 outs() << " (not in an __OBJC section)";
4869 }
4870 outs() << "\n";
4871
4872 outs() << "\t instance methods "
4873 << format("0x%08" PRIx32, objc_category->instance_methods);
4874 if (print_method_list(objc_category->instance_methods, info))
4875 outs() << " (not in an __OBJC section)\n";
4876
4877 outs() << "\t class methods "
4878 << format("0x%08" PRIx32, objc_category->class_methods);
4879 if (print_method_list(objc_category->class_methods, info))
4880 outs() << " (not in an __OBJC section)\n";
4881}
4882
Kevin Enderby0fc11822015-04-01 20:57:01 +00004883static void print_category64_t(uint64_t p, struct DisassembleInfo *info) {
4884 struct category64_t c;
4885 const char *r;
4886 uint32_t offset, xoffset, left;
4887 SectionRef S, xS;
4888 const char *name, *sym_name;
4889 uint64_t n_value;
4890
4891 r = get_pointer_64(p, offset, left, S, info);
4892 if (r == nullptr)
4893 return;
4894 memset(&c, '\0', sizeof(struct category64_t));
4895 if (left < sizeof(struct category64_t)) {
4896 memcpy(&c, r, left);
4897 outs() << " (category_t entends past the end of the section)\n";
4898 } else
4899 memcpy(&c, r, sizeof(struct category64_t));
4900 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4901 swapStruct(c);
4902
4903 outs() << " name ";
4904 sym_name = get_symbol_64(offset + offsetof(struct category64_t, name), S,
4905 info, n_value, c.name);
4906 if (n_value != 0) {
4907 if (info->verbose && sym_name != nullptr)
4908 outs() << sym_name;
4909 else
4910 outs() << format("0x%" PRIx64, n_value);
4911 if (c.name != 0)
4912 outs() << " + " << format("0x%" PRIx64, c.name);
4913 } else
4914 outs() << format("0x%" PRIx64, c.name);
4915 name = get_pointer_64(c.name + n_value, xoffset, left, xS, info);
4916 if (name != nullptr)
4917 outs() << format(" %.*s", left, name);
4918 outs() << "\n";
4919
4920 outs() << " cls ";
4921 sym_name = get_symbol_64(offset + offsetof(struct category64_t, cls), S, info,
4922 n_value, c.cls);
4923 if (n_value != 0) {
4924 if (info->verbose && sym_name != nullptr)
4925 outs() << sym_name;
4926 else
4927 outs() << format("0x%" PRIx64, n_value);
4928 if (c.cls != 0)
4929 outs() << " + " << format("0x%" PRIx64, c.cls);
4930 } else
4931 outs() << format("0x%" PRIx64, c.cls);
4932 outs() << "\n";
4933 if (c.cls + n_value != 0)
4934 print_class64_t(c.cls + n_value, info);
4935
4936 outs() << " instanceMethods ";
4937 sym_name =
4938 get_symbol_64(offset + offsetof(struct category64_t, instanceMethods), S,
4939 info, n_value, c.instanceMethods);
4940 if (n_value != 0) {
4941 if (info->verbose && sym_name != nullptr)
4942 outs() << sym_name;
4943 else
4944 outs() << format("0x%" PRIx64, n_value);
4945 if (c.instanceMethods != 0)
4946 outs() << " + " << format("0x%" PRIx64, c.instanceMethods);
4947 } else
4948 outs() << format("0x%" PRIx64, c.instanceMethods);
4949 outs() << "\n";
4950 if (c.instanceMethods + n_value != 0)
4951 print_method_list64_t(c.instanceMethods + n_value, info, "");
4952
4953 outs() << " classMethods ";
4954 sym_name = get_symbol_64(offset + offsetof(struct category64_t, classMethods),
4955 S, info, n_value, c.classMethods);
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.classMethods != 0)
4962 outs() << " + " << format("0x%" PRIx64, c.classMethods);
4963 } else
4964 outs() << format("0x%" PRIx64, c.classMethods);
4965 outs() << "\n";
4966 if (c.classMethods + n_value != 0)
4967 print_method_list64_t(c.classMethods + n_value, info, "");
4968
4969 outs() << " protocols ";
4970 sym_name = get_symbol_64(offset + offsetof(struct category64_t, protocols), S,
4971 info, n_value, c.protocols);
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.protocols != 0)
4978 outs() << " + " << format("0x%" PRIx64, c.protocols);
4979 } else
4980 outs() << format("0x%" PRIx64, c.protocols);
4981 outs() << "\n";
4982 if (c.protocols + n_value != 0)
4983 print_protocol_list64_t(c.protocols + n_value, info);
4984
4985 outs() << "instanceProperties ";
4986 sym_name =
4987 get_symbol_64(offset + offsetof(struct category64_t, instanceProperties),
4988 S, info, n_value, c.instanceProperties);
4989 if (n_value != 0) {
4990 if (info->verbose && sym_name != nullptr)
4991 outs() << sym_name;
4992 else
4993 outs() << format("0x%" PRIx64, n_value);
4994 if (c.instanceProperties != 0)
4995 outs() << " + " << format("0x%" PRIx64, c.instanceProperties);
4996 } else
4997 outs() << format("0x%" PRIx64, c.instanceProperties);
4998 outs() << "\n";
4999 if (c.instanceProperties + n_value != 0)
5000 print_objc_property_list64(c.instanceProperties + n_value, info);
5001}
5002
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005003static void print_category32_t(uint32_t p, struct DisassembleInfo *info) {
5004 struct category32_t c;
5005 const char *r;
5006 uint32_t offset, left;
5007 SectionRef S, xS;
5008 const char *name;
5009
5010 r = get_pointer_32(p, offset, left, S, info);
5011 if (r == nullptr)
5012 return;
5013 memset(&c, '\0', sizeof(struct category32_t));
5014 if (left < sizeof(struct category32_t)) {
5015 memcpy(&c, r, left);
5016 outs() << " (category_t entends past the end of the section)\n";
5017 } else
5018 memcpy(&c, r, sizeof(struct category32_t));
5019 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5020 swapStruct(c);
5021
5022 outs() << " name " << format("0x%" PRIx32, c.name);
5023 name = get_symbol_32(offset + offsetof(struct category32_t, name), S, info,
5024 c.name);
Hans Wennborgcc9deb42015-09-29 18:02:48 +00005025 if (name)
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005026 outs() << " " << name;
5027 outs() << "\n";
5028
5029 outs() << " cls " << format("0x%" PRIx32, c.cls) << "\n";
5030 if (c.cls != 0)
5031 print_class32_t(c.cls, info);
5032 outs() << " instanceMethods " << format("0x%" PRIx32, c.instanceMethods)
5033 << "\n";
5034 if (c.instanceMethods != 0)
5035 print_method_list32_t(c.instanceMethods, info, "");
5036 outs() << " classMethods " << format("0x%" PRIx32, c.classMethods)
5037 << "\n";
5038 if (c.classMethods != 0)
5039 print_method_list32_t(c.classMethods, info, "");
5040 outs() << " protocols " << format("0x%" PRIx32, c.protocols) << "\n";
5041 if (c.protocols != 0)
5042 print_protocol_list32_t(c.protocols, info);
5043 outs() << "instanceProperties " << format("0x%" PRIx32, c.instanceProperties)
5044 << "\n";
5045 if (c.instanceProperties != 0)
5046 print_objc_property_list32(c.instanceProperties, info);
5047}
5048
Kevin Enderby0fc11822015-04-01 20:57:01 +00005049static void print_message_refs64(SectionRef S, struct DisassembleInfo *info) {
5050 uint32_t i, left, offset, xoffset;
5051 uint64_t p, n_value;
5052 struct message_ref64 mr;
5053 const char *name, *sym_name;
5054 const char *r;
5055 SectionRef xS;
5056
5057 if (S == SectionRef())
5058 return;
5059
5060 StringRef SectName;
5061 S.getName(SectName);
5062 DataRefImpl Ref = S.getRawDataRefImpl();
5063 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5064 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5065 offset = 0;
5066 for (i = 0; i < S.getSize(); i += sizeof(struct message_ref64)) {
5067 p = S.getAddress() + i;
5068 r = get_pointer_64(p, offset, left, S, info);
5069 if (r == nullptr)
5070 return;
5071 memset(&mr, '\0', sizeof(struct message_ref64));
5072 if (left < sizeof(struct message_ref64)) {
5073 memcpy(&mr, r, left);
5074 outs() << " (message_ref entends past the end of the section)\n";
5075 } else
5076 memcpy(&mr, r, sizeof(struct message_ref64));
5077 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5078 swapStruct(mr);
5079
5080 outs() << " imp ";
5081 name = get_symbol_64(offset + offsetof(struct message_ref64, imp), S, info,
5082 n_value, mr.imp);
5083 if (n_value != 0) {
5084 outs() << format("0x%" PRIx64, n_value) << " ";
5085 if (mr.imp != 0)
5086 outs() << "+ " << format("0x%" PRIx64, mr.imp) << " ";
5087 } else
5088 outs() << format("0x%" PRIx64, mr.imp) << " ";
5089 if (name != nullptr)
5090 outs() << " " << name;
5091 outs() << "\n";
5092
5093 outs() << " sel ";
5094 sym_name = get_symbol_64(offset + offsetof(struct message_ref64, sel), S,
5095 info, n_value, mr.sel);
5096 if (n_value != 0) {
5097 if (info->verbose && sym_name != nullptr)
5098 outs() << sym_name;
5099 else
5100 outs() << format("0x%" PRIx64, n_value);
5101 if (mr.sel != 0)
5102 outs() << " + " << format("0x%" PRIx64, mr.sel);
5103 } else
5104 outs() << format("0x%" PRIx64, mr.sel);
5105 name = get_pointer_64(mr.sel + n_value, xoffset, left, xS, info);
5106 if (name != nullptr)
5107 outs() << format(" %.*s", left, name);
5108 outs() << "\n";
5109
5110 offset += sizeof(struct message_ref64);
5111 }
5112}
5113
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005114static void print_message_refs32(SectionRef S, struct DisassembleInfo *info) {
5115 uint32_t i, left, offset, xoffset, p;
5116 struct message_ref32 mr;
5117 const char *name, *r;
5118 SectionRef xS;
5119
5120 if (S == SectionRef())
5121 return;
5122
5123 StringRef SectName;
5124 S.getName(SectName);
5125 DataRefImpl Ref = S.getRawDataRefImpl();
5126 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5127 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5128 offset = 0;
5129 for (i = 0; i < S.getSize(); i += sizeof(struct message_ref64)) {
5130 p = S.getAddress() + i;
5131 r = get_pointer_32(p, offset, left, S, info);
5132 if (r == nullptr)
5133 return;
5134 memset(&mr, '\0', sizeof(struct message_ref32));
5135 if (left < sizeof(struct message_ref32)) {
5136 memcpy(&mr, r, left);
5137 outs() << " (message_ref entends past the end of the section)\n";
5138 } else
5139 memcpy(&mr, r, sizeof(struct message_ref32));
5140 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5141 swapStruct(mr);
5142
5143 outs() << " imp " << format("0x%" PRIx32, mr.imp);
5144 name = get_symbol_32(offset + offsetof(struct message_ref32, imp), S, info,
5145 mr.imp);
5146 if (name != nullptr)
5147 outs() << " " << name;
5148 outs() << "\n";
5149
5150 outs() << " sel " << format("0x%" PRIx32, mr.sel);
5151 name = get_pointer_32(mr.sel, xoffset, left, xS, info);
5152 if (name != nullptr)
5153 outs() << " " << name;
5154 outs() << "\n";
5155
5156 offset += sizeof(struct message_ref32);
5157 }
5158}
5159
Kevin Enderby0fc11822015-04-01 20:57:01 +00005160static void print_image_info64(SectionRef S, struct DisassembleInfo *info) {
5161 uint32_t left, offset, swift_version;
5162 uint64_t p;
5163 struct objc_image_info64 o;
5164 const char *r;
5165
Kevin Enderbyaf7c9d02015-10-09 16:48:44 +00005166 if (S == SectionRef())
5167 return;
5168
Kevin Enderby0fc11822015-04-01 20:57:01 +00005169 StringRef SectName;
5170 S.getName(SectName);
5171 DataRefImpl Ref = S.getRawDataRefImpl();
5172 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5173 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5174 p = S.getAddress();
5175 r = get_pointer_64(p, offset, left, S, info);
5176 if (r == nullptr)
5177 return;
5178 memset(&o, '\0', sizeof(struct objc_image_info64));
5179 if (left < sizeof(struct objc_image_info64)) {
5180 memcpy(&o, r, left);
5181 outs() << " (objc_image_info entends past the end of the section)\n";
5182 } else
5183 memcpy(&o, r, sizeof(struct objc_image_info64));
5184 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5185 swapStruct(o);
5186 outs() << " version " << o.version << "\n";
5187 outs() << " flags " << format("0x%" PRIx32, o.flags);
5188 if (o.flags & OBJC_IMAGE_IS_REPLACEMENT)
5189 outs() << " OBJC_IMAGE_IS_REPLACEMENT";
5190 if (o.flags & OBJC_IMAGE_SUPPORTS_GC)
5191 outs() << " OBJC_IMAGE_SUPPORTS_GC";
5192 swift_version = (o.flags >> 8) & 0xff;
5193 if (swift_version != 0) {
5194 if (swift_version == 1)
5195 outs() << " Swift 1.0";
5196 else if (swift_version == 2)
5197 outs() << " Swift 1.1";
5198 else
5199 outs() << " unknown future Swift version (" << swift_version << ")";
5200 }
5201 outs() << "\n";
5202}
5203
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005204static void print_image_info32(SectionRef S, struct DisassembleInfo *info) {
5205 uint32_t left, offset, swift_version, p;
5206 struct objc_image_info32 o;
5207 const char *r;
5208
Kevin Enderby19be2512016-04-21 19:49:29 +00005209 if (S == SectionRef())
5210 return;
5211
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005212 StringRef SectName;
5213 S.getName(SectName);
5214 DataRefImpl Ref = S.getRawDataRefImpl();
5215 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5216 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5217 p = S.getAddress();
5218 r = get_pointer_32(p, offset, left, S, info);
5219 if (r == nullptr)
5220 return;
5221 memset(&o, '\0', sizeof(struct objc_image_info32));
5222 if (left < sizeof(struct objc_image_info32)) {
5223 memcpy(&o, r, left);
5224 outs() << " (objc_image_info entends past the end of the section)\n";
5225 } else
5226 memcpy(&o, r, sizeof(struct objc_image_info32));
5227 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5228 swapStruct(o);
5229 outs() << " version " << o.version << "\n";
5230 outs() << " flags " << format("0x%" PRIx32, o.flags);
5231 if (o.flags & OBJC_IMAGE_IS_REPLACEMENT)
5232 outs() << " OBJC_IMAGE_IS_REPLACEMENT";
5233 if (o.flags & OBJC_IMAGE_SUPPORTS_GC)
5234 outs() << " OBJC_IMAGE_SUPPORTS_GC";
5235 swift_version = (o.flags >> 8) & 0xff;
5236 if (swift_version != 0) {
5237 if (swift_version == 1)
5238 outs() << " Swift 1.0";
5239 else if (swift_version == 2)
5240 outs() << " Swift 1.1";
5241 else
5242 outs() << " unknown future Swift version (" << swift_version << ")";
5243 }
5244 outs() << "\n";
5245}
5246
Kevin Enderby846c0002015-04-16 17:19:59 +00005247static void print_image_info(SectionRef S, struct DisassembleInfo *info) {
5248 uint32_t left, offset, p;
5249 struct imageInfo_t o;
5250 const char *r;
5251
5252 StringRef SectName;
5253 S.getName(SectName);
5254 DataRefImpl Ref = S.getRawDataRefImpl();
5255 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5256 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5257 p = S.getAddress();
5258 r = get_pointer_32(p, offset, left, S, info);
5259 if (r == nullptr)
5260 return;
5261 memset(&o, '\0', sizeof(struct imageInfo_t));
5262 if (left < sizeof(struct imageInfo_t)) {
5263 memcpy(&o, r, left);
5264 outs() << " (imageInfo entends past the end of the section)\n";
5265 } else
5266 memcpy(&o, r, sizeof(struct imageInfo_t));
5267 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5268 swapStruct(o);
5269 outs() << " version " << o.version << "\n";
5270 outs() << " flags " << format("0x%" PRIx32, o.flags);
5271 if (o.flags & 0x1)
5272 outs() << " F&C";
5273 if (o.flags & 0x2)
5274 outs() << " GC";
5275 if (o.flags & 0x4)
5276 outs() << " GC-only";
5277 else
5278 outs() << " RR";
5279 outs() << "\n";
5280}
5281
Kevin Enderby0fc11822015-04-01 20:57:01 +00005282static void printObjc2_64bit_MetaData(MachOObjectFile *O, bool verbose) {
5283 SymbolAddressMap AddrMap;
5284 if (verbose)
5285 CreateSymbolAddressMap(O, &AddrMap);
5286
5287 std::vector<SectionRef> Sections;
5288 for (const SectionRef &Section : O->sections()) {
5289 StringRef SectName;
5290 Section.getName(SectName);
5291 Sections.push_back(Section);
5292 }
5293
5294 struct DisassembleInfo info;
5295 // Set up the block of info used by the Symbolizer call backs.
5296 info.verbose = verbose;
5297 info.O = O;
5298 info.AddrMap = &AddrMap;
5299 info.Sections = &Sections;
5300 info.class_name = nullptr;
5301 info.selector_name = nullptr;
5302 info.method = nullptr;
5303 info.demangled_name = nullptr;
5304 info.bindtable = nullptr;
5305 info.adrp_addr = 0;
5306 info.adrp_inst = 0;
5307
Kevin Enderbyaac75382015-10-08 16:56:35 +00005308 info.depth = 0;
Davide Italiano62507042015-12-11 22:27:59 +00005309 SectionRef CL = get_section(O, "__OBJC2", "__class_list");
5310 if (CL == SectionRef())
5311 CL = get_section(O, "__DATA", "__objc_classlist");
5312 info.S = CL;
5313 walk_pointer_list_64("class", CL, O, &info, print_class64_t);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005314
Davide Italiano62507042015-12-11 22:27:59 +00005315 SectionRef CR = get_section(O, "__OBJC2", "__class_refs");
5316 if (CR == SectionRef())
5317 CR = get_section(O, "__DATA", "__objc_classrefs");
5318 info.S = CR;
5319 walk_pointer_list_64("class refs", CR, O, &info, nullptr);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005320
Davide Italiano62507042015-12-11 22:27:59 +00005321 SectionRef SR = get_section(O, "__OBJC2", "__super_refs");
5322 if (SR == SectionRef())
5323 SR = get_section(O, "__DATA", "__objc_superrefs");
5324 info.S = SR;
5325 walk_pointer_list_64("super refs", SR, O, &info, nullptr);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005326
Davide Italiano62507042015-12-11 22:27:59 +00005327 SectionRef CA = get_section(O, "__OBJC2", "__category_list");
5328 if (CA == SectionRef())
5329 CA = get_section(O, "__DATA", "__objc_catlist");
5330 info.S = CA;
5331 walk_pointer_list_64("category", CA, O, &info, print_category64_t);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005332
Davide Italiano62507042015-12-11 22:27:59 +00005333 SectionRef PL = get_section(O, "__OBJC2", "__protocol_list");
5334 if (PL == SectionRef())
5335 PL = get_section(O, "__DATA", "__objc_protolist");
5336 info.S = PL;
5337 walk_pointer_list_64("protocol", PL, O, &info, nullptr);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005338
Davide Italiano62507042015-12-11 22:27:59 +00005339 SectionRef MR = get_section(O, "__OBJC2", "__message_refs");
5340 if (MR == SectionRef())
5341 MR = get_section(O, "__DATA", "__objc_msgrefs");
5342 info.S = MR;
5343 print_message_refs64(MR, &info);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005344
Davide Italiano62507042015-12-11 22:27:59 +00005345 SectionRef II = get_section(O, "__OBJC2", "__image_info");
5346 if (II == SectionRef())
5347 II = get_section(O, "__DATA", "__objc_imageinfo");
5348 info.S = II;
5349 print_image_info64(II, &info);
Kevin Enderby0bc6ed42015-04-01 21:50:45 +00005350
5351 if (info.bindtable != nullptr)
5352 delete info.bindtable;
Kevin Enderby0fc11822015-04-01 20:57:01 +00005353}
5354
5355static void printObjc2_32bit_MetaData(MachOObjectFile *O, bool verbose) {
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005356 SymbolAddressMap AddrMap;
5357 if (verbose)
5358 CreateSymbolAddressMap(O, &AddrMap);
5359
5360 std::vector<SectionRef> Sections;
5361 for (const SectionRef &Section : O->sections()) {
5362 StringRef SectName;
5363 Section.getName(SectName);
5364 Sections.push_back(Section);
5365 }
5366
5367 struct DisassembleInfo info;
5368 // Set up the block of info used by the Symbolizer call backs.
5369 info.verbose = verbose;
5370 info.O = O;
5371 info.AddrMap = &AddrMap;
5372 info.Sections = &Sections;
5373 info.class_name = nullptr;
5374 info.selector_name = nullptr;
5375 info.method = nullptr;
5376 info.demangled_name = nullptr;
5377 info.bindtable = nullptr;
5378 info.adrp_addr = 0;
5379 info.adrp_inst = 0;
5380
5381 const SectionRef CL = get_section(O, "__OBJC2", "__class_list");
5382 if (CL != SectionRef()) {
5383 info.S = CL;
5384 walk_pointer_list_32("class", CL, O, &info, print_class32_t);
5385 } else {
5386 const SectionRef CL = get_section(O, "__DATA", "__objc_classlist");
5387 info.S = CL;
5388 walk_pointer_list_32("class", CL, O, &info, print_class32_t);
5389 }
5390
5391 const SectionRef CR = get_section(O, "__OBJC2", "__class_refs");
5392 if (CR != SectionRef()) {
5393 info.S = CR;
5394 walk_pointer_list_32("class refs", CR, O, &info, nullptr);
5395 } else {
5396 const SectionRef CR = get_section(O, "__DATA", "__objc_classrefs");
5397 info.S = CR;
5398 walk_pointer_list_32("class refs", CR, O, &info, nullptr);
5399 }
5400
5401 const SectionRef SR = get_section(O, "__OBJC2", "__super_refs");
5402 if (SR != SectionRef()) {
5403 info.S = SR;
5404 walk_pointer_list_32("super refs", SR, O, &info, nullptr);
5405 } else {
5406 const SectionRef SR = get_section(O, "__DATA", "__objc_superrefs");
5407 info.S = SR;
5408 walk_pointer_list_32("super refs", SR, O, &info, nullptr);
5409 }
5410
5411 const SectionRef CA = get_section(O, "__OBJC2", "__category_list");
5412 if (CA != SectionRef()) {
5413 info.S = CA;
5414 walk_pointer_list_32("category", CA, O, &info, print_category32_t);
5415 } else {
5416 const SectionRef CA = get_section(O, "__DATA", "__objc_catlist");
5417 info.S = CA;
5418 walk_pointer_list_32("category", CA, O, &info, print_category32_t);
5419 }
5420
5421 const SectionRef PL = get_section(O, "__OBJC2", "__protocol_list");
5422 if (PL != SectionRef()) {
5423 info.S = PL;
5424 walk_pointer_list_32("protocol", PL, O, &info, nullptr);
5425 } else {
5426 const SectionRef PL = get_section(O, "__DATA", "__objc_protolist");
5427 info.S = PL;
5428 walk_pointer_list_32("protocol", PL, O, &info, nullptr);
5429 }
5430
5431 const SectionRef MR = get_section(O, "__OBJC2", "__message_refs");
5432 if (MR != SectionRef()) {
5433 info.S = MR;
5434 print_message_refs32(MR, &info);
5435 } else {
5436 const SectionRef MR = get_section(O, "__DATA", "__objc_msgrefs");
5437 info.S = MR;
5438 print_message_refs32(MR, &info);
5439 }
5440
5441 const SectionRef II = get_section(O, "__OBJC2", "__image_info");
5442 if (II != SectionRef()) {
5443 info.S = II;
5444 print_image_info32(II, &info);
5445 } else {
5446 const SectionRef II = get_section(O, "__DATA", "__objc_imageinfo");
5447 info.S = II;
5448 print_image_info32(II, &info);
5449 }
Kevin Enderby0fc11822015-04-01 20:57:01 +00005450}
5451
5452static bool printObjc1_32bit_MetaData(MachOObjectFile *O, bool verbose) {
Kevin Enderby846c0002015-04-16 17:19:59 +00005453 uint32_t i, j, p, offset, xoffset, left, defs_left, def;
5454 const char *r, *name, *defs;
5455 struct objc_module_t module;
5456 SectionRef S, xS;
5457 struct objc_symtab_t symtab;
5458 struct objc_class_t objc_class;
5459 struct objc_category_t objc_category;
5460
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005461 outs() << "Objective-C segment\n";
Kevin Enderby846c0002015-04-16 17:19:59 +00005462 S = get_section(O, "__OBJC", "__module_info");
5463 if (S == SectionRef())
5464 return false;
5465
5466 SymbolAddressMap AddrMap;
5467 if (verbose)
5468 CreateSymbolAddressMap(O, &AddrMap);
5469
5470 std::vector<SectionRef> Sections;
5471 for (const SectionRef &Section : O->sections()) {
5472 StringRef SectName;
5473 Section.getName(SectName);
5474 Sections.push_back(Section);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005475 }
Kevin Enderby846c0002015-04-16 17:19:59 +00005476
5477 struct DisassembleInfo info;
5478 // Set up the block of info used by the Symbolizer call backs.
5479 info.verbose = verbose;
5480 info.O = O;
5481 info.AddrMap = &AddrMap;
5482 info.Sections = &Sections;
5483 info.class_name = nullptr;
5484 info.selector_name = nullptr;
5485 info.method = nullptr;
5486 info.demangled_name = nullptr;
5487 info.bindtable = nullptr;
5488 info.adrp_addr = 0;
5489 info.adrp_inst = 0;
5490
5491 for (i = 0; i < S.getSize(); i += sizeof(struct objc_module_t)) {
5492 p = S.getAddress() + i;
5493 r = get_pointer_32(p, offset, left, S, &info, true);
5494 if (r == nullptr)
5495 return true;
5496 memset(&module, '\0', sizeof(struct objc_module_t));
5497 if (left < sizeof(struct objc_module_t)) {
5498 memcpy(&module, r, left);
5499 outs() << " (module extends past end of __module_info section)\n";
5500 } else
5501 memcpy(&module, r, sizeof(struct objc_module_t));
5502 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5503 swapStruct(module);
5504
5505 outs() << "Module " << format("0x%" PRIx32, p) << "\n";
5506 outs() << " version " << module.version << "\n";
5507 outs() << " size " << module.size << "\n";
5508 outs() << " name ";
5509 name = get_pointer_32(module.name, xoffset, left, xS, &info, true);
5510 if (name != nullptr)
5511 outs() << format("%.*s", left, name);
5512 else
5513 outs() << format("0x%08" PRIx32, module.name)
5514 << "(not in an __OBJC section)";
5515 outs() << "\n";
5516
5517 r = get_pointer_32(module.symtab, xoffset, left, xS, &info, true);
5518 if (module.symtab == 0 || r == nullptr) {
5519 outs() << " symtab " << format("0x%08" PRIx32, module.symtab)
5520 << " (not in an __OBJC section)\n";
5521 continue;
5522 }
5523 outs() << " symtab " << format("0x%08" PRIx32, module.symtab) << "\n";
5524 memset(&symtab, '\0', sizeof(struct objc_symtab_t));
5525 defs_left = 0;
5526 defs = nullptr;
5527 if (left < sizeof(struct objc_symtab_t)) {
5528 memcpy(&symtab, r, left);
5529 outs() << "\tsymtab extends past end of an __OBJC section)\n";
5530 } else {
5531 memcpy(&symtab, r, sizeof(struct objc_symtab_t));
5532 if (left > sizeof(struct objc_symtab_t)) {
5533 defs_left = left - sizeof(struct objc_symtab_t);
5534 defs = r + sizeof(struct objc_symtab_t);
5535 }
5536 }
5537 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5538 swapStruct(symtab);
5539
5540 outs() << "\tsel_ref_cnt " << symtab.sel_ref_cnt << "\n";
5541 r = get_pointer_32(symtab.refs, xoffset, left, xS, &info, true);
5542 outs() << "\trefs " << format("0x%08" PRIx32, symtab.refs);
5543 if (r == nullptr)
5544 outs() << " (not in an __OBJC section)";
5545 outs() << "\n";
5546 outs() << "\tcls_def_cnt " << symtab.cls_def_cnt << "\n";
5547 outs() << "\tcat_def_cnt " << symtab.cat_def_cnt << "\n";
5548 if (symtab.cls_def_cnt > 0)
5549 outs() << "\tClass Definitions\n";
5550 for (j = 0; j < symtab.cls_def_cnt; j++) {
5551 if ((j + 1) * sizeof(uint32_t) > defs_left) {
5552 outs() << "\t(remaining class defs entries entends past the end of the "
5553 << "section)\n";
5554 break;
5555 }
5556 memcpy(&def, defs + j * sizeof(uint32_t), sizeof(uint32_t));
5557 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5558 sys::swapByteOrder(def);
5559
5560 r = get_pointer_32(def, xoffset, left, xS, &info, true);
5561 outs() << "\tdefs[" << j << "] " << format("0x%08" PRIx32, def);
5562 if (r != nullptr) {
5563 if (left > sizeof(struct objc_class_t)) {
5564 outs() << "\n";
5565 memcpy(&objc_class, r, sizeof(struct objc_class_t));
5566 } else {
5567 outs() << " (entends past the end of the section)\n";
5568 memset(&objc_class, '\0', sizeof(struct objc_class_t));
5569 memcpy(&objc_class, r, left);
5570 }
5571 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5572 swapStruct(objc_class);
5573 print_objc_class_t(&objc_class, &info);
5574 } else {
5575 outs() << "(not in an __OBJC section)\n";
5576 }
5577
5578 if (CLS_GETINFO(&objc_class, CLS_CLASS)) {
5579 outs() << "\tMeta Class";
5580 r = get_pointer_32(objc_class.isa, xoffset, left, xS, &info, true);
5581 if (r != nullptr) {
5582 if (left > sizeof(struct objc_class_t)) {
5583 outs() << "\n";
5584 memcpy(&objc_class, r, sizeof(struct objc_class_t));
5585 } else {
5586 outs() << " (entends past the end of the section)\n";
5587 memset(&objc_class, '\0', sizeof(struct objc_class_t));
5588 memcpy(&objc_class, r, left);
5589 }
5590 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5591 swapStruct(objc_class);
5592 print_objc_class_t(&objc_class, &info);
5593 } else {
5594 outs() << "(not in an __OBJC section)\n";
5595 }
5596 }
5597 }
5598 if (symtab.cat_def_cnt > 0)
5599 outs() << "\tCategory Definitions\n";
5600 for (j = 0; j < symtab.cat_def_cnt; j++) {
5601 if ((j + symtab.cls_def_cnt + 1) * sizeof(uint32_t) > defs_left) {
5602 outs() << "\t(remaining category defs entries entends past the end of "
5603 << "the section)\n";
5604 break;
5605 }
5606 memcpy(&def, defs + (j + symtab.cls_def_cnt) * sizeof(uint32_t),
5607 sizeof(uint32_t));
5608 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5609 sys::swapByteOrder(def);
5610
5611 r = get_pointer_32(def, xoffset, left, xS, &info, true);
5612 outs() << "\tdefs[" << j + symtab.cls_def_cnt << "] "
5613 << format("0x%08" PRIx32, def);
5614 if (r != nullptr) {
5615 if (left > sizeof(struct objc_category_t)) {
5616 outs() << "\n";
5617 memcpy(&objc_category, r, sizeof(struct objc_category_t));
5618 } else {
5619 outs() << " (entends past the end of the section)\n";
5620 memset(&objc_category, '\0', sizeof(struct objc_category_t));
5621 memcpy(&objc_category, r, left);
5622 }
5623 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5624 swapStruct(objc_category);
5625 print_objc_objc_category_t(&objc_category, &info);
5626 } else {
5627 outs() << "(not in an __OBJC section)\n";
5628 }
5629 }
5630 }
5631 const SectionRef II = get_section(O, "__OBJC", "__image_info");
5632 if (II != SectionRef())
5633 print_image_info(II, &info);
5634
5635 return true;
Kevin Enderby0fc11822015-04-01 20:57:01 +00005636}
5637
Kevin Enderby4ad9bde2015-04-16 22:33:20 +00005638static void DumpProtocolSection(MachOObjectFile *O, const char *sect,
5639 uint32_t size, uint32_t addr) {
5640 SymbolAddressMap AddrMap;
5641 CreateSymbolAddressMap(O, &AddrMap);
5642
5643 std::vector<SectionRef> Sections;
5644 for (const SectionRef &Section : O->sections()) {
5645 StringRef SectName;
5646 Section.getName(SectName);
5647 Sections.push_back(Section);
5648 }
5649
5650 struct DisassembleInfo info;
5651 // Set up the block of info used by the Symbolizer call backs.
5652 info.verbose = true;
5653 info.O = O;
5654 info.AddrMap = &AddrMap;
5655 info.Sections = &Sections;
5656 info.class_name = nullptr;
5657 info.selector_name = nullptr;
5658 info.method = nullptr;
5659 info.demangled_name = nullptr;
5660 info.bindtable = nullptr;
5661 info.adrp_addr = 0;
5662 info.adrp_inst = 0;
5663
5664 const char *p;
5665 struct objc_protocol_t protocol;
5666 uint32_t left, paddr;
5667 for (p = sect; p < sect + size; p += sizeof(struct objc_protocol_t)) {
5668 memset(&protocol, '\0', sizeof(struct objc_protocol_t));
5669 left = size - (p - sect);
5670 if (left < sizeof(struct objc_protocol_t)) {
5671 outs() << "Protocol extends past end of __protocol section\n";
5672 memcpy(&protocol, p, left);
5673 } else
5674 memcpy(&protocol, p, sizeof(struct objc_protocol_t));
5675 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5676 swapStruct(protocol);
5677 paddr = addr + (p - sect);
5678 outs() << "Protocol " << format("0x%" PRIx32, paddr);
5679 if (print_protocol(paddr, 0, &info))
5680 outs() << "(not in an __OBJC section)\n";
5681 }
5682}
5683
Kevin Enderby9873e2c2016-05-23 21:34:12 +00005684#ifdef HAVE_LIBXAR
5685inline void swapStruct(struct xar_header &xar) {
5686 sys::swapByteOrder(xar.magic);
5687 sys::swapByteOrder(xar.size);
5688 sys::swapByteOrder(xar.version);
5689 sys::swapByteOrder(xar.toc_length_compressed);
5690 sys::swapByteOrder(xar.toc_length_uncompressed);
5691 sys::swapByteOrder(xar.cksum_alg);
5692}
5693
5694static void PrintModeVerbose(uint32_t mode) {
5695 switch(mode & S_IFMT){
5696 case S_IFDIR:
5697 outs() << "d";
5698 break;
5699 case S_IFCHR:
5700 outs() << "c";
5701 break;
5702 case S_IFBLK:
5703 outs() << "b";
5704 break;
5705 case S_IFREG:
5706 outs() << "-";
5707 break;
5708 case S_IFLNK:
5709 outs() << "l";
5710 break;
5711 case S_IFSOCK:
5712 outs() << "s";
5713 break;
5714 default:
5715 outs() << "?";
5716 break;
5717 }
5718
5719 /* owner permissions */
5720 if(mode & S_IREAD)
5721 outs() << "r";
5722 else
5723 outs() << "-";
5724 if(mode & S_IWRITE)
5725 outs() << "w";
5726 else
5727 outs() << "-";
5728 if(mode & S_ISUID)
5729 outs() << "s";
5730 else if(mode & S_IEXEC)
5731 outs() << "x";
5732 else
5733 outs() << "-";
5734
5735 /* group permissions */
5736 if(mode & (S_IREAD >> 3))
5737 outs() << "r";
5738 else
5739 outs() << "-";
5740 if(mode & (S_IWRITE >> 3))
5741 outs() << "w";
5742 else
5743 outs() << "-";
5744 if(mode & S_ISGID)
5745 outs() << "s";
5746 else if(mode & (S_IEXEC >> 3))
5747 outs() << "x";
5748 else
5749 outs() << "-";
5750
5751 /* other permissions */
5752 if(mode & (S_IREAD >> 6))
5753 outs() << "r";
5754 else
5755 outs() << "-";
5756 if(mode & (S_IWRITE >> 6))
5757 outs() << "w";
5758 else
5759 outs() << "-";
5760 if(mode & S_ISVTX)
5761 outs() << "t";
5762 else if(mode & (S_IEXEC >> 6))
5763 outs() << "x";
5764 else
5765 outs() << "-";
5766}
5767
5768static void PrintXarFilesSummary(const char *XarFilename, xar_t xar) {
5769 xar_iter_t xi;
5770 xar_file_t xf;
5771 xar_iter_t xp;
5772 const char *key, *type, *mode, *user, *group, *size, *mtime, *name, *m;
5773 char *endp;
5774 uint32_t mode_value;
5775
5776 xi = xar_iter_new();
5777 if (!xi) {
5778 errs() << "Can't obtain an xar iterator for xar archive "
5779 << XarFilename << "\n";
5780 return;
5781 }
5782
5783 // Go through the xar's files.
5784 for (xf = xar_file_first(xar, xi); xf; xf = xar_file_next(xi)) {
5785 xp = xar_iter_new();
5786 if(!xp){
5787 errs() << "Can't obtain an xar iterator for xar archive "
5788 << XarFilename << "\n";
5789 return;
5790 }
5791 type = nullptr;
5792 mode = nullptr;
5793 user = nullptr;
5794 group = nullptr;
5795 size = nullptr;
5796 mtime = nullptr;
5797 name = nullptr;
5798 for(key = xar_prop_first(xf, xp); key; key = xar_prop_next(xp)){
5799 const char *val = nullptr;
5800 xar_prop_get(xf, key, &val);
5801#if 0 // Useful for debugging.
5802 outs() << "key: " << key << " value: " << val << "\n";
5803#endif
5804 if(strcmp(key, "type") == 0)
5805 type = val;
5806 if(strcmp(key, "mode") == 0)
5807 mode = val;
5808 if(strcmp(key, "user") == 0)
5809 user = val;
5810 if(strcmp(key, "group") == 0)
5811 group = val;
5812 if(strcmp(key, "data/size") == 0)
5813 size = val;
5814 if(strcmp(key, "mtime") == 0)
5815 mtime = val;
5816 if(strcmp(key, "name") == 0)
5817 name = val;
5818 }
5819 if(mode != nullptr){
5820 mode_value = strtoul(mode, &endp, 8);
5821 if(*endp != '\0')
5822 outs() << "(mode: \"" << mode << "\" contains non-octal chars) ";
5823 if(strcmp(type, "file") == 0)
5824 mode_value |= S_IFREG;
5825 PrintModeVerbose(mode_value);
5826 outs() << " ";
5827 }
5828 if(user != nullptr)
5829 outs() << format("%10s/", user);
5830 if(group != nullptr)
5831 outs() << format("%-10s ", group);
5832 if(size != nullptr)
5833 outs() << format("%7s ", size);
5834 if(mtime != nullptr){
5835 for(m = mtime; *m != 'T' && *m != '\0'; m++)
5836 outs() << *m;
5837 if(*m == 'T')
5838 m++;
5839 outs() << " ";
5840 for( ; *m != 'Z' && *m != '\0'; m++)
5841 outs() << *m;
5842 outs() << " ";
5843 }
5844 if(name != nullptr)
5845 outs() << name;
5846 outs() << "\n";
5847 }
5848}
5849
5850static void DumpBitcodeSection(MachOObjectFile *O, const char *sect,
5851 uint32_t size, bool verbose,
5852 bool PrintXarHeader, bool PrintXarFileHeaders,
5853 std::string XarMemberName) {
5854 if(size < sizeof(struct xar_header)) {
5855 outs() << "size of (__LLVM,__bundle) section too small (smaller than size "
5856 "of struct xar_header)\n";
5857 return;
5858 }
5859 struct xar_header XarHeader;
5860 memcpy(&XarHeader, sect, sizeof(struct xar_header));
5861 if (sys::IsLittleEndianHost)
5862 swapStruct(XarHeader);
5863 if (PrintXarHeader) {
5864 if (!XarMemberName.empty())
5865 outs() << "In xar member " << XarMemberName << ": ";
5866 else
5867 outs() << "For (__LLVM,__bundle) section: ";
5868 outs() << "xar header\n";
5869 if (XarHeader.magic == XAR_HEADER_MAGIC)
5870 outs() << " magic XAR_HEADER_MAGIC\n";
5871 else
5872 outs() << " magic "
5873 << format_hex(XarHeader.magic, 10, true)
5874 << " (not XAR_HEADER_MAGIC)\n";
5875 outs() << " size " << XarHeader.size << "\n";
5876 outs() << " version " << XarHeader.version << "\n";
5877 outs() << " toc_length_compressed " << XarHeader.toc_length_compressed
5878 << "\n";
5879 outs() << "toc_length_uncompressed " << XarHeader.toc_length_uncompressed
5880 << "\n";
5881 outs() << " cksum_alg ";
5882 switch (XarHeader.cksum_alg) {
5883 case XAR_CKSUM_NONE:
5884 outs() << "XAR_CKSUM_NONE\n";
5885 break;
5886 case XAR_CKSUM_SHA1:
5887 outs() << "XAR_CKSUM_SHA1\n";
5888 break;
5889 case XAR_CKSUM_MD5:
5890 outs() << "XAR_CKSUM_MD5\n";
5891 break;
Kevin Enderby42882282016-05-23 22:18:59 +00005892#ifdef XAR_CKSUM_SHA256
Kevin Enderby9873e2c2016-05-23 21:34:12 +00005893 case XAR_CKSUM_SHA256:
5894 outs() << "XAR_CKSUM_SHA256\n";
5895 break;
Kevin Enderby42882282016-05-23 22:18:59 +00005896#endif
5897#ifdef XAR_CKSUM_SHA512
Kevin Enderby9873e2c2016-05-23 21:34:12 +00005898 case XAR_CKSUM_SHA512:
5899 outs() << "XAR_CKSUM_SHA512\n";
5900 break;
Kevin Enderby42882282016-05-23 22:18:59 +00005901#endif
Kevin Enderby9873e2c2016-05-23 21:34:12 +00005902 default:
5903 outs() << XarHeader.cksum_alg << "\n";
5904 }
5905 }
5906
5907 SmallString<128> XarFilename;
5908 int FD;
5909 std::error_code XarEC =
5910 sys::fs::createTemporaryFile("llvm-objdump", "xar", FD, XarFilename);
5911 if (XarEC) {
5912 errs() << XarEC.message() << "\n";
5913 return;
5914 }
5915 tool_output_file XarFile(XarFilename, FD);
5916 raw_fd_ostream &XarOut = XarFile.os();
5917 StringRef XarContents(sect, size);
5918 XarOut << XarContents;
5919 XarOut.close();
5920 if (XarOut.has_error())
5921 return;
5922
5923 xar_t xar = xar_open(XarFilename.c_str(), READ);
5924 if (!xar) {
5925 errs() << "Can't create temporary xar archive " << XarFilename << "\n";
5926 return;
5927 }
5928
5929 SmallString<128> TocFilename;
5930 std::error_code TocEC =
5931 sys::fs::createTemporaryFile("llvm-objdump", "toc", TocFilename);
5932 if (TocEC) {
5933 errs() << TocEC.message() << "\n";
5934 return;
5935 }
5936 xar_serialize(xar, TocFilename.c_str());
5937
5938 if (PrintXarFileHeaders) {
5939 if (!XarMemberName.empty())
5940 outs() << "In xar member " << XarMemberName << ": ";
5941 else
5942 outs() << "For (__LLVM,__bundle) section: ";
5943 outs() << "xar archive files:\n";
5944 PrintXarFilesSummary(XarFilename.c_str(), xar);
5945 }
5946
5947 ErrorOr<std::unique_ptr<MemoryBuffer>> FileOrErr =
5948 MemoryBuffer::getFileOrSTDIN(TocFilename.c_str());
5949 if (std::error_code EC = FileOrErr.getError()) {
5950 errs() << EC.message() << "\n";
5951 return;
5952 }
5953 std::unique_ptr<MemoryBuffer> &Buffer = FileOrErr.get();
5954
5955 if (!XarMemberName.empty())
5956 outs() << "In xar member " << XarMemberName << ": ";
5957 else
5958 outs() << "For (__LLVM,__bundle) section: ";
5959 outs() << "xar table of contents:\n";
5960 outs() << Buffer->getBuffer() << "\n";
5961
5962 // TODO: Go through the xar's files.
5963 xar_iter_t xi = xar_iter_new();
5964 if(!xi){
5965 errs() << "Can't obtain an xar iterator for xar archive "
5966 << XarFilename.c_str() << "\n";
5967 xar_close(xar);
5968 return;
5969 }
5970 for(xar_file_t xf = xar_file_first(xar, xi); xf; xf = xar_file_next(xi)){
5971 const char *key;
5972 xar_iter_t xp;
5973 const char *member_name, *member_type, *member_size_string;
5974 size_t member_size;
5975
5976 xp = xar_iter_new();
5977 if(!xp){
5978 errs() << "Can't obtain an xar iterator for xar archive "
5979 << XarFilename.c_str() << "\n";
5980 xar_close(xar);
5981 return;
5982 }
5983 member_name = NULL;
5984 member_type = NULL;
5985 member_size_string = NULL;
5986 for(key = xar_prop_first(xf, xp); key; key = xar_prop_next(xp)){
5987 const char *val = nullptr;
5988 xar_prop_get(xf, key, &val);
5989#if 0 // Useful for debugging.
5990 outs() << "key: " << key << " value: " << val << "\n";
5991#endif
5992 if(strcmp(key, "name") == 0)
5993 member_name = val;
5994 if(strcmp(key, "type") == 0)
5995 member_type = val;
5996 if(strcmp(key, "data/size") == 0)
5997 member_size_string = val;
5998 }
5999 /*
6000 * If we find a file with a name, date/size and type properties
6001 * and with the type being "file" see if that is a xar file.
6002 */
6003 if (member_name != NULL && member_type != NULL &&
6004 strcmp(member_type, "file") == 0 &&
6005 member_size_string != NULL){
6006 // Extract the file into a buffer.
6007 char *endptr;
6008 member_size = strtoul(member_size_string, &endptr, 10);
6009 if (*endptr == '\0' && member_size != 0) {
6010 char *buffer = (char *) ::operator new (member_size);
6011 if (xar_extract_tobuffersz(xar, xf, &buffer, &member_size) == 0) {
6012#if 0 // Useful for debugging.
6013 outs() << "xar member: " << member_name << " extracted\n";
6014#endif
6015 // Set the XarMemberName we want to see printed in the header.
6016 std::string OldXarMemberName;
6017 // If XarMemberName is already set this is nested. So
6018 // save the old name and create the nested name.
6019 if (!XarMemberName.empty()) {
6020 OldXarMemberName = XarMemberName;
6021 XarMemberName =
6022 (Twine("[") + XarMemberName + "]" + member_name).str();
6023 } else {
6024 OldXarMemberName = "";
6025 XarMemberName = member_name;
6026 }
6027 // See if this is could be a xar file (nested).
6028 if (member_size >= sizeof(struct xar_header)) {
6029#if 0 // Useful for debugging.
6030 outs() << "could be a xar file: " << member_name << "\n";
6031#endif
6032 memcpy((char *)&XarHeader, buffer, sizeof(struct xar_header));
6033 if (sys::IsLittleEndianHost)
6034 swapStruct(XarHeader);
6035 if(XarHeader.magic == XAR_HEADER_MAGIC)
6036 DumpBitcodeSection(O, buffer, member_size, verbose,
6037 PrintXarHeader, PrintXarFileHeaders,
6038 XarMemberName);
6039 }
6040 XarMemberName = OldXarMemberName;
6041 }
6042 delete buffer;
6043 }
6044 }
6045 xar_iter_free(xp);
6046 }
6047 xar_close(xar);
6048}
6049#endif // defined(HAVE_LIBXAR)
6050
Kevin Enderby0fc11822015-04-01 20:57:01 +00006051static void printObjcMetaData(MachOObjectFile *O, bool verbose) {
6052 if (O->is64Bit())
6053 printObjc2_64bit_MetaData(O, verbose);
6054 else {
6055 MachO::mach_header H;
6056 H = O->getHeader();
6057 if (H.cputype == MachO::CPU_TYPE_ARM)
6058 printObjc2_32bit_MetaData(O, verbose);
6059 else {
6060 // This is the 32-bit non-arm cputype case. Which is normally
6061 // the first Objective-C ABI. But it may be the case of a
6062 // binary for the iOS simulator which is the second Objective-C
6063 // ABI. In that case printObjc1_32bit_MetaData() will determine that
6064 // and return false.
Hans Wennborgcc9deb42015-09-29 18:02:48 +00006065 if (!printObjc1_32bit_MetaData(O, verbose))
Kevin Enderby0fc11822015-04-01 20:57:01 +00006066 printObjc2_32bit_MetaData(O, verbose);
6067 }
6068 }
6069}
6070
Kevin Enderbybf246f52014-09-24 23:08:22 +00006071// GuessLiteralPointer returns a string which for the item in the Mach-O file
6072// for the address passed in as ReferenceValue for printing as a comment with
6073// the instruction and also returns the corresponding type of that item
6074// indirectly through ReferenceType.
6075//
6076// If ReferenceValue is an address of literal cstring then a pointer to the
6077// cstring is returned and ReferenceType is set to
6078// LLVMDisassembler_ReferenceType_Out_LitPool_CstrAddr .
6079//
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006080// If ReferenceValue is an address of an Objective-C CFString, Selector ref or
6081// Class ref that name is returned and the ReferenceType is set accordingly.
6082//
6083// Lastly, literals which are Symbol address in a literal pool are looked for
6084// and if found the symbol name is returned and ReferenceType is set to
6085// LLVMDisassembler_ReferenceType_Out_LitPool_SymAddr .
6086//
6087// If there is no item in the Mach-O file for the address passed in as
6088// ReferenceValue nullptr is returned and ReferenceType is unchanged.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00006089static const char *GuessLiteralPointer(uint64_t ReferenceValue,
6090 uint64_t ReferencePC,
6091 uint64_t *ReferenceType,
6092 struct DisassembleInfo *info) {
Kevin Enderbybf246f52014-09-24 23:08:22 +00006093 // First see if there is an external relocation entry at the ReferencePC.
Kevin Enderbyd90a4172015-10-10 00:05:01 +00006094 if (info->O->getHeader().filetype == MachO::MH_OBJECT) {
6095 uint64_t sect_addr = info->S.getAddress();
6096 uint64_t sect_offset = ReferencePC - sect_addr;
6097 bool reloc_found = false;
6098 DataRefImpl Rel;
6099 MachO::any_relocation_info RE;
6100 bool isExtern = false;
6101 SymbolRef Symbol;
6102 for (const RelocationRef &Reloc : info->S.relocations()) {
6103 uint64_t RelocOffset = Reloc.getOffset();
6104 if (RelocOffset == sect_offset) {
6105 Rel = Reloc.getRawDataRefImpl();
6106 RE = info->O->getRelocation(Rel);
6107 if (info->O->isRelocationScattered(RE))
6108 continue;
6109 isExtern = info->O->getPlainRelocationExternal(RE);
6110 if (isExtern) {
6111 symbol_iterator RelocSym = Reloc.getSymbol();
6112 Symbol = *RelocSym;
6113 }
6114 reloc_found = true;
6115 break;
Kevin Enderbybf246f52014-09-24 23:08:22 +00006116 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00006117 }
Kevin Enderbyd90a4172015-10-10 00:05:01 +00006118 // If there is an external relocation entry for a symbol in a section
6119 // then used that symbol's value for the value of the reference.
6120 if (reloc_found && isExtern) {
6121 if (info->O->getAnyRelocationPCRel(RE)) {
6122 unsigned Type = info->O->getAnyRelocationType(RE);
6123 if (Type == MachO::X86_64_RELOC_SIGNED) {
6124 ReferenceValue = Symbol.getValue();
6125 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00006126 }
6127 }
6128 }
6129
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006130 // Look for literals such as Objective-C CFStrings refs, Selector refs,
6131 // Message refs and Class refs.
6132 bool classref, selref, msgref, cfstring;
6133 uint64_t pointer_value = GuessPointerPointer(ReferenceValue, info, classref,
6134 selref, msgref, cfstring);
David Blaikie33dd45d02015-03-23 18:39:02 +00006135 if (classref && pointer_value == 0) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006136 // Note the ReferenceValue is a pointer into the __objc_classrefs section.
6137 // And the pointer_value in that section is typically zero as it will be
6138 // set by dyld as part of the "bind information".
6139 const char *name = get_dyld_bind_info_symbolname(ReferenceValue, info);
6140 if (name != nullptr) {
6141 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Class_Ref;
Hans Wennborgdb53e302014-10-23 21:59:17 +00006142 const char *class_name = strrchr(name, '$');
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006143 if (class_name != nullptr && class_name[1] == '_' &&
6144 class_name[2] != '\0') {
6145 info->class_name = class_name + 2;
6146 return name;
6147 }
6148 }
6149 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00006150
David Blaikie33dd45d02015-03-23 18:39:02 +00006151 if (classref) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006152 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Class_Ref;
6153 const char *name =
6154 get_objc2_64bit_class_name(pointer_value, ReferenceValue, info);
6155 if (name != nullptr)
6156 info->class_name = name;
6157 else
6158 name = "bad class ref";
Kevin Enderbybf246f52014-09-24 23:08:22 +00006159 return name;
6160 }
6161
David Blaikie33dd45d02015-03-23 18:39:02 +00006162 if (cfstring) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006163 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_CFString_Ref;
6164 const char *name = get_objc2_64bit_cfstring_name(ReferenceValue, info);
6165 return name;
6166 }
6167
David Blaikie33dd45d02015-03-23 18:39:02 +00006168 if (selref && pointer_value == 0)
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006169 pointer_value = get_objc2_64bit_selref(ReferenceValue, info);
6170
6171 if (pointer_value != 0)
6172 ReferenceValue = pointer_value;
6173
6174 const char *name = GuessCstringPointer(ReferenceValue, info);
6175 if (name) {
David Blaikie33dd45d02015-03-23 18:39:02 +00006176 if (pointer_value != 0 && selref) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006177 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Selector_Ref;
6178 info->selector_name = name;
David Blaikie33dd45d02015-03-23 18:39:02 +00006179 } else if (pointer_value != 0 && msgref) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006180 info->class_name = nullptr;
6181 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message_Ref;
6182 info->selector_name = name;
6183 } else
6184 *ReferenceType = LLVMDisassembler_ReferenceType_Out_LitPool_CstrAddr;
6185 return name;
6186 }
6187
6188 // Lastly look for an indirect symbol with this ReferenceValue which is in
6189 // a literal pool. If found return that symbol name.
6190 name = GuessIndirectSymbol(ReferenceValue, info);
6191 if (name) {
6192 *ReferenceType = LLVMDisassembler_ReferenceType_Out_LitPool_SymAddr;
6193 return name;
6194 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00006195
6196 return nullptr;
6197}
6198
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006199// SymbolizerSymbolLookUp is the symbol lookup function passed when creating
Kevin Enderbybf246f52014-09-24 23:08:22 +00006200// the Symbolizer. It looks up the ReferenceValue using the info passed via the
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006201// pointer to the struct DisassembleInfo that was passed when MCSymbolizer
6202// is created and returns the symbol name that matches the ReferenceValue or
6203// nullptr if none. The ReferenceType is passed in for the IN type of
6204// reference the instruction is making from the values in defined in the header
6205// "llvm-c/Disassembler.h". On return the ReferenceType can set to a specific
6206// Out type and the ReferenceName will also be set which is added as a comment
6207// to the disassembled instruction.
6208//
Kevin Enderby04bf6932014-10-28 23:39:46 +00006209#if HAVE_CXXABI_H
6210// If the symbol name is a C++ mangled name then the demangled name is
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006211// returned through ReferenceName and ReferenceType is set to
6212// LLVMDisassembler_ReferenceType_DeMangled_Name .
Kevin Enderby04bf6932014-10-28 23:39:46 +00006213#endif
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006214//
6215// When this is called to get a symbol name for a branch target then the
6216// ReferenceType will be LLVMDisassembler_ReferenceType_In_Branch and then
6217// SymbolValue will be looked for in the indirect symbol table to determine if
6218// it is an address for a symbol stub. If so then the symbol name for that
6219// stub is returned indirectly through ReferenceName and then ReferenceType is
6220// set to LLVMDisassembler_ReferenceType_Out_SymbolStub.
6221//
Kevin Enderbybf246f52014-09-24 23:08:22 +00006222// When this is called with an value loaded via a PC relative load then
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006223// ReferenceType will be LLVMDisassembler_ReferenceType_In_PCrel_Load then the
6224// SymbolValue is checked to be an address of literal pointer, symbol pointer,
6225// or an Objective-C meta data reference. If so the output ReferenceType is
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006226// set to correspond to that as well as setting the ReferenceName.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00006227static const char *SymbolizerSymbolLookUp(void *DisInfo,
6228 uint64_t ReferenceValue,
6229 uint64_t *ReferenceType,
6230 uint64_t ReferencePC,
6231 const char **ReferenceName) {
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006232 struct DisassembleInfo *info = (struct DisassembleInfo *)DisInfo;
Kevin Enderbybf246f52014-09-24 23:08:22 +00006233 // If no verbose symbolic information is wanted then just return nullptr.
David Blaikie33dd45d02015-03-23 18:39:02 +00006234 if (!info->verbose) {
Kevin Enderbybf246f52014-09-24 23:08:22 +00006235 *ReferenceName = nullptr;
6236 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006237 return nullptr;
6238 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00006239
Kevin Enderbyf6d25852015-01-31 00:37:11 +00006240 const char *SymbolName = GuessSymbolName(ReferenceValue, info->AddrMap);
Kevin Enderbybf246f52014-09-24 23:08:22 +00006241
Kevin Enderby85974882014-09-26 22:20:44 +00006242 if (*ReferenceType == LLVMDisassembler_ReferenceType_In_Branch) {
6243 *ReferenceName = GuessIndirectSymbol(ReferenceValue, info);
Kevin Enderby04bf6932014-10-28 23:39:46 +00006244 if (*ReferenceName != nullptr) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006245 method_reference(info, ReferenceType, ReferenceName);
6246 if (*ReferenceType != LLVMDisassembler_ReferenceType_Out_Objc_Message)
6247 *ReferenceType = LLVMDisassembler_ReferenceType_Out_SymbolStub;
6248 } else
Kevin Enderby04bf6932014-10-28 23:39:46 +00006249#if HAVE_CXXABI_H
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006250 if (SymbolName != nullptr && strncmp(SymbolName, "__Z", 3) == 0) {
Kevin Enderby04bf6932014-10-28 23:39:46 +00006251 if (info->demangled_name != nullptr)
6252 free(info->demangled_name);
6253 int status;
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006254 info->demangled_name =
6255 abi::__cxa_demangle(SymbolName + 1, nullptr, nullptr, &status);
Kevin Enderby04bf6932014-10-28 23:39:46 +00006256 if (info->demangled_name != nullptr) {
6257 *ReferenceName = info->demangled_name;
6258 *ReferenceType = LLVMDisassembler_ReferenceType_DeMangled_Name;
6259 } else
6260 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
6261 } else
6262#endif
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006263 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
6264 } else if (*ReferenceType == LLVMDisassembler_ReferenceType_In_PCrel_Load) {
6265 *ReferenceName =
6266 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
Kevin Enderby85974882014-09-26 22:20:44 +00006267 if (*ReferenceName)
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006268 method_reference(info, ReferenceType, ReferenceName);
Kevin Enderby85974882014-09-26 22:20:44 +00006269 else
6270 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
Kevin Enderbyae3c1262014-11-14 21:52:18 +00006271 // If this is arm64 and the reference is an adrp instruction save the
6272 // instruction, passed in ReferenceValue and the address of the instruction
6273 // for use later if we see and add immediate instruction.
6274 } else if (info->O->getArch() == Triple::aarch64 &&
6275 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADRP) {
6276 info->adrp_inst = ReferenceValue;
6277 info->adrp_addr = ReferencePC;
6278 SymbolName = nullptr;
6279 *ReferenceName = nullptr;
6280 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
6281 // If this is arm64 and reference is an add immediate instruction and we
6282 // have
6283 // seen an adrp instruction just before it and the adrp's Xd register
6284 // matches
6285 // this add's Xn register reconstruct the value being referenced and look to
6286 // see if it is a literal pointer. Note the add immediate instruction is
6287 // passed in ReferenceValue.
6288 } else if (info->O->getArch() == Triple::aarch64 &&
6289 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADDXri &&
6290 ReferencePC - 4 == info->adrp_addr &&
6291 (info->adrp_inst & 0x9f000000) == 0x90000000 &&
6292 (info->adrp_inst & 0x1f) == ((ReferenceValue >> 5) & 0x1f)) {
6293 uint32_t addxri_inst;
6294 uint64_t adrp_imm, addxri_imm;
6295
6296 adrp_imm =
6297 ((info->adrp_inst & 0x00ffffe0) >> 3) | ((info->adrp_inst >> 29) & 0x3);
6298 if (info->adrp_inst & 0x0200000)
6299 adrp_imm |= 0xfffffffffc000000LL;
6300
6301 addxri_inst = ReferenceValue;
6302 addxri_imm = (addxri_inst >> 10) & 0xfff;
6303 if (((addxri_inst >> 22) & 0x3) == 1)
6304 addxri_imm <<= 12;
6305
6306 ReferenceValue = (info->adrp_addr & 0xfffffffffffff000LL) +
6307 (adrp_imm << 12) + addxri_imm;
6308
6309 *ReferenceName =
6310 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
6311 if (*ReferenceName == nullptr)
6312 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
6313 // If this is arm64 and the reference is a load register instruction and we
6314 // have seen an adrp instruction just before it and the adrp's Xd register
6315 // matches this add's Xn register reconstruct the value being referenced and
6316 // look to see if it is a literal pointer. Note the load register
6317 // instruction is passed in ReferenceValue.
6318 } else if (info->O->getArch() == Triple::aarch64 &&
6319 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_LDRXui &&
6320 ReferencePC - 4 == info->adrp_addr &&
6321 (info->adrp_inst & 0x9f000000) == 0x90000000 &&
6322 (info->adrp_inst & 0x1f) == ((ReferenceValue >> 5) & 0x1f)) {
6323 uint32_t ldrxui_inst;
6324 uint64_t adrp_imm, ldrxui_imm;
6325
6326 adrp_imm =
6327 ((info->adrp_inst & 0x00ffffe0) >> 3) | ((info->adrp_inst >> 29) & 0x3);
6328 if (info->adrp_inst & 0x0200000)
6329 adrp_imm |= 0xfffffffffc000000LL;
6330
6331 ldrxui_inst = ReferenceValue;
6332 ldrxui_imm = (ldrxui_inst >> 10) & 0xfff;
6333
6334 ReferenceValue = (info->adrp_addr & 0xfffffffffffff000LL) +
6335 (adrp_imm << 12) + (ldrxui_imm << 3);
6336
6337 *ReferenceName =
6338 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
6339 if (*ReferenceName == nullptr)
6340 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
6341 }
6342 // If this arm64 and is an load register (PC-relative) instruction the
6343 // ReferenceValue is the PC plus the immediate value.
6344 else if (info->O->getArch() == Triple::aarch64 &&
6345 (*ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_LDRXl ||
6346 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADR)) {
6347 *ReferenceName =
6348 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
6349 if (*ReferenceName == nullptr)
6350 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
Kevin Enderby85974882014-09-26 22:20:44 +00006351 }
Kevin Enderby04bf6932014-10-28 23:39:46 +00006352#if HAVE_CXXABI_H
6353 else if (SymbolName != nullptr && strncmp(SymbolName, "__Z", 3) == 0) {
6354 if (info->demangled_name != nullptr)
6355 free(info->demangled_name);
6356 int status;
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006357 info->demangled_name =
6358 abi::__cxa_demangle(SymbolName + 1, nullptr, nullptr, &status);
Kevin Enderby04bf6932014-10-28 23:39:46 +00006359 if (info->demangled_name != nullptr) {
6360 *ReferenceName = info->demangled_name;
6361 *ReferenceType = LLVMDisassembler_ReferenceType_DeMangled_Name;
6362 }
6363 }
6364#endif
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006365 else {
Kevin Enderbybf246f52014-09-24 23:08:22 +00006366 *ReferenceName = nullptr;
6367 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
6368 }
6369
6370 return SymbolName;
6371}
6372
Kevin Enderbybf246f52014-09-24 23:08:22 +00006373/// \brief Emits the comments that are stored in the CommentStream.
6374/// Each comment in the CommentStream must end with a newline.
6375static void emitComments(raw_svector_ostream &CommentStream,
6376 SmallString<128> &CommentsToEmit,
6377 formatted_raw_ostream &FormattedOS,
6378 const MCAsmInfo &MAI) {
6379 // Flush the stream before taking its content.
Kevin Enderbybf246f52014-09-24 23:08:22 +00006380 StringRef Comments = CommentsToEmit.str();
6381 // Get the default information for printing a comment.
6382 const char *CommentBegin = MAI.getCommentString();
6383 unsigned CommentColumn = MAI.getCommentColumn();
6384 bool IsFirst = true;
6385 while (!Comments.empty()) {
6386 if (!IsFirst)
6387 FormattedOS << '\n';
6388 // Emit a line of comments.
6389 FormattedOS.PadToColumn(CommentColumn);
6390 size_t Position = Comments.find('\n');
6391 FormattedOS << CommentBegin << ' ' << Comments.substr(0, Position);
6392 // Move after the newline character.
6393 Comments = Comments.substr(Position + 1);
6394 IsFirst = false;
6395 }
6396 FormattedOS.flush();
6397
6398 // Tell the comment stream that the vector changed underneath it.
6399 CommentsToEmit.clear();
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006400}
6401
Kevin Enderby95df54c2015-02-04 01:01:38 +00006402static void DisassembleMachO(StringRef Filename, MachOObjectFile *MachOOF,
6403 StringRef DisSegName, StringRef DisSectName) {
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006404 const char *McpuDefault = nullptr;
6405 const Target *ThumbTarget = nullptr;
6406 const Target *TheTarget = GetTarget(MachOOF, &McpuDefault, &ThumbTarget);
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006407 if (!TheTarget) {
6408 // GetTarget prints out stuff.
6409 return;
6410 }
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006411 if (MCPU.empty() && McpuDefault)
6412 MCPU = McpuDefault;
6413
Ahmed Charles56440fd2014-03-06 05:51:42 +00006414 std::unique_ptr<const MCInstrInfo> InstrInfo(TheTarget->createMCInstrInfo());
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006415 std::unique_ptr<const MCInstrInfo> ThumbInstrInfo;
Kevin Enderbyae3c1262014-11-14 21:52:18 +00006416 if (ThumbTarget)
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006417 ThumbInstrInfo.reset(ThumbTarget->createMCInstrInfo());
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006418
Kevin Enderbyc9595622014-08-06 23:24:41 +00006419 // Package up features to be passed to target/subtarget
6420 std::string FeaturesStr;
6421 if (MAttrs.size()) {
6422 SubtargetFeatures Features;
6423 for (unsigned i = 0; i != MAttrs.size(); ++i)
6424 Features.AddFeature(MAttrs[i]);
6425 FeaturesStr = Features.getString();
6426 }
6427
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006428 // Set up disassembler.
Ahmed Charles56440fd2014-03-06 05:51:42 +00006429 std::unique_ptr<const MCRegisterInfo> MRI(
6430 TheTarget->createMCRegInfo(TripleName));
6431 std::unique_ptr<const MCAsmInfo> AsmInfo(
Rafael Espindola227144c2013-05-13 01:16:13 +00006432 TheTarget->createMCAsmInfo(*MRI, TripleName));
Ahmed Charles56440fd2014-03-06 05:51:42 +00006433 std::unique_ptr<const MCSubtargetInfo> STI(
Kevin Enderbyc9595622014-08-06 23:24:41 +00006434 TheTarget->createMCSubtargetInfo(TripleName, MCPU, FeaturesStr));
Craig Toppere6cb63e2014-04-25 04:24:47 +00006435 MCContext Ctx(AsmInfo.get(), MRI.get(), nullptr);
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006436 std::unique_ptr<MCDisassembler> DisAsm(
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006437 TheTarget->createMCDisassembler(*STI, Ctx));
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006438 std::unique_ptr<MCSymbolizer> Symbolizer;
6439 struct DisassembleInfo SymbolizerInfo;
6440 std::unique_ptr<MCRelocationInfo> RelInfo(
6441 TheTarget->createMCRelocationInfo(TripleName, Ctx));
6442 if (RelInfo) {
6443 Symbolizer.reset(TheTarget->createMCSymbolizer(
6444 TripleName, SymbolizerGetOpInfo, SymbolizerSymbolLookUp,
David Blaikie186db432015-01-18 20:45:48 +00006445 &SymbolizerInfo, &Ctx, std::move(RelInfo)));
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006446 DisAsm->setSymbolizer(std::move(Symbolizer));
6447 }
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006448 int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
Ahmed Charles56440fd2014-03-06 05:51:42 +00006449 std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
Daniel Sanders50f17232015-09-15 16:17:27 +00006450 Triple(TripleName), AsmPrinterVariant, *AsmInfo, *InstrInfo, *MRI));
Kevin Enderbybf246f52014-09-24 23:08:22 +00006451 // Set the display preference for hex vs. decimal immediates.
6452 IP->setPrintImmHex(PrintImmHex);
6453 // Comment stream and backing vector.
6454 SmallString<128> CommentsToEmit;
6455 raw_svector_ostream CommentStream(CommentsToEmit);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00006456 // FIXME: Setting the CommentStream in the InstPrinter is problematic in that
6457 // if it is done then arm64 comments for string literals don't get printed
6458 // and some constant get printed instead and not setting it causes intel
6459 // (32-bit and 64-bit) comments printed with different spacing before the
6460 // comment causing different diffs with the 'C' disassembler library API.
6461 // IP->setCommentStream(CommentStream);
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00006462
Kevin Enderbyae3c1262014-11-14 21:52:18 +00006463 if (!AsmInfo || !STI || !DisAsm || !IP) {
Michael J. Spencerc1363cf2011-10-07 19:25:47 +00006464 errs() << "error: couldn't initialize disassembler for target "
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00006465 << TripleName << '\n';
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006466 return;
6467 }
6468
Tim Northover09ca33e2016-04-22 23:23:31 +00006469 // Set up separate thumb disassembler if needed.
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006470 std::unique_ptr<const MCRegisterInfo> ThumbMRI;
6471 std::unique_ptr<const MCAsmInfo> ThumbAsmInfo;
6472 std::unique_ptr<const MCSubtargetInfo> ThumbSTI;
Kevin Enderby930fdc72014-11-06 19:00:13 +00006473 std::unique_ptr<MCDisassembler> ThumbDisAsm;
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006474 std::unique_ptr<MCInstPrinter> ThumbIP;
6475 std::unique_ptr<MCContext> ThumbCtx;
Kevin Enderby930fdc72014-11-06 19:00:13 +00006476 std::unique_ptr<MCSymbolizer> ThumbSymbolizer;
6477 struct DisassembleInfo ThumbSymbolizerInfo;
6478 std::unique_ptr<MCRelocationInfo> ThumbRelInfo;
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006479 if (ThumbTarget) {
6480 ThumbMRI.reset(ThumbTarget->createMCRegInfo(ThumbTripleName));
6481 ThumbAsmInfo.reset(
6482 ThumbTarget->createMCAsmInfo(*ThumbMRI, ThumbTripleName));
6483 ThumbSTI.reset(
6484 ThumbTarget->createMCSubtargetInfo(ThumbTripleName, MCPU, FeaturesStr));
6485 ThumbCtx.reset(new MCContext(ThumbAsmInfo.get(), ThumbMRI.get(), nullptr));
6486 ThumbDisAsm.reset(ThumbTarget->createMCDisassembler(*ThumbSTI, *ThumbCtx));
Kevin Enderby930fdc72014-11-06 19:00:13 +00006487 MCContext *PtrThumbCtx = ThumbCtx.get();
6488 ThumbRelInfo.reset(
6489 ThumbTarget->createMCRelocationInfo(ThumbTripleName, *PtrThumbCtx));
6490 if (ThumbRelInfo) {
6491 ThumbSymbolizer.reset(ThumbTarget->createMCSymbolizer(
6492 ThumbTripleName, SymbolizerGetOpInfo, SymbolizerSymbolLookUp,
David Blaikie186db432015-01-18 20:45:48 +00006493 &ThumbSymbolizerInfo, PtrThumbCtx, std::move(ThumbRelInfo)));
Kevin Enderby930fdc72014-11-06 19:00:13 +00006494 ThumbDisAsm->setSymbolizer(std::move(ThumbSymbolizer));
6495 }
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006496 int ThumbAsmPrinterVariant = ThumbAsmInfo->getAssemblerDialect();
6497 ThumbIP.reset(ThumbTarget->createMCInstPrinter(
Daniel Sanders50f17232015-09-15 16:17:27 +00006498 Triple(ThumbTripleName), ThumbAsmPrinterVariant, *ThumbAsmInfo,
6499 *ThumbInstrInfo, *ThumbMRI));
Kevin Enderbybf246f52014-09-24 23:08:22 +00006500 // Set the display preference for hex vs. decimal immediates.
6501 ThumbIP->setPrintImmHex(PrintImmHex);
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006502 }
6503
Kevin Enderbyae3c1262014-11-14 21:52:18 +00006504 if (ThumbTarget && (!ThumbAsmInfo || !ThumbSTI || !ThumbDisAsm || !ThumbIP)) {
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006505 errs() << "error: couldn't initialize disassembler for target "
6506 << ThumbTripleName << '\n';
6507 return;
6508 }
6509
Charles Davis8bdfafd2013-09-01 04:28:48 +00006510 MachO::mach_header Header = MachOOF->getHeader();
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006511
Ahmed Bougachaaa790682013-05-24 01:07:04 +00006512 // FIXME: Using the -cfg command line option, this code used to be able to
6513 // annotate relocations with the referenced symbol's name, and if this was
6514 // inside a __[cf]string section, the data it points to. This is now replaced
6515 // by the upcoming MCSymbolizer, which needs the appropriate setup done above.
Owen Andersond9243c42011-10-17 21:37:35 +00006516 std::vector<SectionRef> Sections;
6517 std::vector<SymbolRef> Symbols;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006518 SmallVector<uint64_t, 8> FoundFns;
Kevin Enderby273ae012013-06-06 17:20:50 +00006519 uint64_t BaseSegmentAddress;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006520
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00006521 getSectionsAndSymbols(MachOOF, Sections, Symbols, FoundFns,
Kevin Enderby273ae012013-06-06 17:20:50 +00006522 BaseSegmentAddress);
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006523
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006524 // Sort the symbols by address, just in case they didn't come in that way.
Owen Andersond9243c42011-10-17 21:37:35 +00006525 std::sort(Symbols.begin(), Symbols.end(), SymbolSorter());
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006526
Kevin Enderby273ae012013-06-06 17:20:50 +00006527 // Build a data in code table that is sorted on by the address of each entry.
6528 uint64_t BaseAddress = 0;
Charles Davis8bdfafd2013-09-01 04:28:48 +00006529 if (Header.filetype == MachO::MH_OBJECT)
Rafael Espindola80291272014-10-08 15:28:58 +00006530 BaseAddress = Sections[0].getAddress();
Kevin Enderby273ae012013-06-06 17:20:50 +00006531 else
6532 BaseAddress = BaseSegmentAddress;
6533 DiceTable Dices;
Kevin Enderby273ae012013-06-06 17:20:50 +00006534 for (dice_iterator DI = MachOOF->begin_dices(), DE = MachOOF->end_dices();
Rafael Espindola5e812af2014-01-30 02:49:50 +00006535 DI != DE; ++DI) {
Kevin Enderby273ae012013-06-06 17:20:50 +00006536 uint32_t Offset;
6537 DI->getOffset(Offset);
6538 Dices.push_back(std::make_pair(BaseAddress + Offset, *DI));
6539 }
6540 array_pod_sort(Dices.begin(), Dices.end());
6541
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006542#ifndef NDEBUG
6543 raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls();
6544#else
6545 raw_ostream &DebugOut = nulls();
6546#endif
6547
Ahmed Charles56440fd2014-03-06 05:51:42 +00006548 std::unique_ptr<DIContext> diContext;
Rafael Espindola9b709252013-04-13 01:45:40 +00006549 ObjectFile *DbgObj = MachOOF;
Benjamin Kramer699128e2011-09-21 01:13:19 +00006550 // Try to find debug info and set up the DIContext for it.
6551 if (UseDbg) {
Benjamin Kramer699128e2011-09-21 01:13:19 +00006552 // A separate DSym file path was specified, parse it as a macho file,
6553 // get the sections and supply it to the section name parsing machinery.
6554 if (!DSYMFile.empty()) {
Rafael Espindola48af1c22014-08-19 18:44:46 +00006555 ErrorOr<std::unique_ptr<MemoryBuffer>> BufOrErr =
Rafael Espindolaadf21f22014-07-06 17:43:13 +00006556 MemoryBuffer::getFileOrSTDIN(DSYMFile);
Rafael Espindola48af1c22014-08-19 18:44:46 +00006557 if (std::error_code EC = BufOrErr.getError()) {
Rafael Espindolaadf21f22014-07-06 17:43:13 +00006558 errs() << "llvm-objdump: " << Filename << ": " << EC.message() << '\n';
Benjamin Kramer699128e2011-09-21 01:13:19 +00006559 return;
6560 }
Rafael Espindola48af1c22014-08-19 18:44:46 +00006561 DbgObj =
6562 ObjectFile::createMachOObjectFile(BufOrErr.get()->getMemBufferRef())
6563 .get()
6564 .release();
Benjamin Kramer699128e2011-09-21 01:13:19 +00006565 }
6566
Eric Christopher7370b552012-11-12 21:40:38 +00006567 // Setup the DIContext
Zachary Turner6489d7b2015-04-23 17:37:47 +00006568 diContext.reset(new DWARFContextInMemory(*DbgObj));
Benjamin Kramer699128e2011-09-21 01:13:19 +00006569 }
6570
Colin LeMahieufcc32762015-07-29 19:08:10 +00006571 if (FilterSections.size() == 0)
Kevin Enderby95df54c2015-02-04 01:01:38 +00006572 outs() << "(" << DisSegName << "," << DisSectName << ") section\n";
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00006573
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006574 for (unsigned SectIdx = 0; SectIdx != Sections.size(); SectIdx++) {
Owen Andersond9243c42011-10-17 21:37:35 +00006575 StringRef SectName;
Kevin Enderby95df54c2015-02-04 01:01:38 +00006576 if (Sections[SectIdx].getName(SectName) || SectName != DisSectName)
6577 continue;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006578
Rafael Espindolaa9f810b2012-12-21 03:47:03 +00006579 DataRefImpl DR = Sections[SectIdx].getRawDataRefImpl();
Ahmed Bougachaaa790682013-05-24 01:07:04 +00006580
Rafael Espindolab0f76a42013-04-05 15:15:22 +00006581 StringRef SegmentName = MachOOF->getSectionFinalSegmentName(DR);
Kevin Enderby95df54c2015-02-04 01:01:38 +00006582 if (SegmentName != DisSegName)
Rafael Espindolaa9f810b2012-12-21 03:47:03 +00006583 continue;
6584
Rafael Espindola7fc5b872014-11-12 02:04:27 +00006585 StringRef BytesStr;
6586 Sections[SectIdx].getContents(BytesStr);
Aaron Ballman106fd7b2014-11-12 14:01:17 +00006587 ArrayRef<uint8_t> Bytes(reinterpret_cast<const uint8_t *>(BytesStr.data()),
6588 BytesStr.size());
Rafael Espindola80291272014-10-08 15:28:58 +00006589 uint64_t SectAddress = Sections[SectIdx].getAddress();
Rafael Espindolabd604f22014-11-07 00:52:15 +00006590
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006591 bool symbolTableWorked = false;
6592
Kevin Enderbybf246f52014-09-24 23:08:22 +00006593 // Create a map of symbol addresses to symbol names for use by
6594 // the SymbolizerSymbolLookUp() routine.
6595 SymbolAddressMap AddrMap;
Kevin Enderby6a221752015-03-17 17:10:57 +00006596 bool DisSymNameFound = false;
Kevin Enderbybf246f52014-09-24 23:08:22 +00006597 for (const SymbolRef &Symbol : MachOOF->symbols()) {
Kevin Enderby7bd8d992016-05-02 20:28:12 +00006598 Expected<SymbolRef::Type> STOrErr = Symbol.getType();
6599 if (!STOrErr) {
6600 std::string Buf;
6601 raw_string_ostream OS(Buf);
6602 logAllUnhandledErrors(STOrErr.takeError(), OS, "");
6603 OS.flush();
6604 report_fatal_error(Buf);
6605 }
Kevin Enderby5afbc1c2016-03-23 20:27:00 +00006606 SymbolRef::Type ST = *STOrErr;
Kevin Enderbybf246f52014-09-24 23:08:22 +00006607 if (ST == SymbolRef::ST_Function || ST == SymbolRef::ST_Data ||
6608 ST == SymbolRef::ST_Other) {
Rafael Espindoladea00162015-07-03 17:44:18 +00006609 uint64_t Address = Symbol.getValue();
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00006610 Expected<StringRef> SymNameOrErr = Symbol.getName();
6611 if (!SymNameOrErr) {
6612 std::string Buf;
6613 raw_string_ostream OS(Buf);
6614 logAllUnhandledErrors(SymNameOrErr.takeError(), OS, "");
6615 OS.flush();
6616 report_fatal_error(Buf);
6617 }
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00006618 StringRef SymName = *SymNameOrErr;
Kevin Enderbybf246f52014-09-24 23:08:22 +00006619 AddrMap[Address] = SymName;
Kevin Enderby6a221752015-03-17 17:10:57 +00006620 if (!DisSymName.empty() && DisSymName == SymName)
6621 DisSymNameFound = true;
Kevin Enderbybf246f52014-09-24 23:08:22 +00006622 }
6623 }
David Blaikie33dd45d02015-03-23 18:39:02 +00006624 if (!DisSymName.empty() && !DisSymNameFound) {
Kevin Enderby6a221752015-03-17 17:10:57 +00006625 outs() << "Can't find -dis-symname: " << DisSymName << "\n";
6626 return;
6627 }
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006628 // Set up the block of info used by the Symbolizer call backs.
Kevin Enderby8e29ec92015-03-17 22:26:11 +00006629 SymbolizerInfo.verbose = !NoSymbolicOperands;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006630 SymbolizerInfo.O = MachOOF;
6631 SymbolizerInfo.S = Sections[SectIdx];
Kevin Enderbybf246f52014-09-24 23:08:22 +00006632 SymbolizerInfo.AddrMap = &AddrMap;
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006633 SymbolizerInfo.Sections = &Sections;
6634 SymbolizerInfo.class_name = nullptr;
6635 SymbolizerInfo.selector_name = nullptr;
6636 SymbolizerInfo.method = nullptr;
Kevin Enderby04bf6932014-10-28 23:39:46 +00006637 SymbolizerInfo.demangled_name = nullptr;
Kevin Enderby078be602014-10-23 19:53:12 +00006638 SymbolizerInfo.bindtable = nullptr;
Kevin Enderby10738222014-11-19 20:20:16 +00006639 SymbolizerInfo.adrp_addr = 0;
6640 SymbolizerInfo.adrp_inst = 0;
Kevin Enderby930fdc72014-11-06 19:00:13 +00006641 // Same for the ThumbSymbolizer
Kevin Enderby8e29ec92015-03-17 22:26:11 +00006642 ThumbSymbolizerInfo.verbose = !NoSymbolicOperands;
Kevin Enderby930fdc72014-11-06 19:00:13 +00006643 ThumbSymbolizerInfo.O = MachOOF;
6644 ThumbSymbolizerInfo.S = Sections[SectIdx];
6645 ThumbSymbolizerInfo.AddrMap = &AddrMap;
6646 ThumbSymbolizerInfo.Sections = &Sections;
6647 ThumbSymbolizerInfo.class_name = nullptr;
6648 ThumbSymbolizerInfo.selector_name = nullptr;
6649 ThumbSymbolizerInfo.method = nullptr;
6650 ThumbSymbolizerInfo.demangled_name = nullptr;
6651 ThumbSymbolizerInfo.bindtable = nullptr;
Kevin Enderby10738222014-11-19 20:20:16 +00006652 ThumbSymbolizerInfo.adrp_addr = 0;
6653 ThumbSymbolizerInfo.adrp_inst = 0;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006654
Kevin Enderby4b627be2016-04-28 20:14:13 +00006655 unsigned int Arch = MachOOF->getArch();
6656
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00006657 // Disassemble symbol by symbol.
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006658 for (unsigned SymIdx = 0; SymIdx != Symbols.size(); SymIdx++) {
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00006659 Expected<StringRef> SymNameOrErr = Symbols[SymIdx].getName();
6660 if (!SymNameOrErr) {
6661 std::string Buf;
6662 raw_string_ostream OS(Buf);
6663 logAllUnhandledErrors(SymNameOrErr.takeError(), OS, "");
6664 OS.flush();
6665 report_fatal_error(Buf);
6666 }
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00006667 StringRef SymName = *SymNameOrErr;
Owen Andersond9243c42011-10-17 21:37:35 +00006668
Kevin Enderby7bd8d992016-05-02 20:28:12 +00006669 Expected<SymbolRef::Type> STOrErr = Symbols[SymIdx].getType();
6670 if (!STOrErr) {
6671 std::string Buf;
6672 raw_string_ostream OS(Buf);
6673 logAllUnhandledErrors(STOrErr.takeError(), OS, "");
6674 OS.flush();
6675 report_fatal_error(Buf);
6676 }
Kevin Enderby5afbc1c2016-03-23 20:27:00 +00006677 SymbolRef::Type ST = *STOrErr;
Kuba Breckade833222015-11-12 09:40:29 +00006678 if (ST != SymbolRef::ST_Function && ST != SymbolRef::ST_Data)
Owen Andersond9243c42011-10-17 21:37:35 +00006679 continue;
6680
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00006681 // Make sure the symbol is defined in this section.
Rafael Espindola80291272014-10-08 15:28:58 +00006682 bool containsSym = Sections[SectIdx].containsSymbol(Symbols[SymIdx]);
Kevin Enderbyd8a6e832016-06-15 21:14:01 +00006683 if (!containsSym) {
6684 if (!DisSymName.empty() && DisSymName == SymName) {
6685 outs() << "-dis-symname: " << DisSymName << " not in the section\n";
6686 return;
6687 }
6688 continue;
6689 }
6690 // The __mh_execute_header is special and we need to deal with that fact
6691 // this symbol is before the start of the (__TEXT,__text) section and at the
6692 // address of the start of the __TEXT segment. This is because this symbol
6693 // is an N_SECT symbol in the (__TEXT,__text) but its address is before the
6694 // start of the section in a standard MH_EXECUTE filetype.
6695 if (!DisSymName.empty() && DisSymName == "__mh_execute_header") {
6696 outs() << "-dis-symname: __mh_execute_header not in any section\n";
6697 return;
6698 }
6699 // When this code is trying to disassemble a symbol at a time and in the case
6700 // there is only the __mh_execute_header symbol left as in a stripped
6701 // executable, we need to deal with this by ignoring this symbol so the whole
6702 // section is disassembled and this symbol is then not displayed.
6703 if (SymName == "__mh_execute_header")
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006704 continue;
6705
Kevin Enderby6a221752015-03-17 17:10:57 +00006706 // If we are only disassembling one symbol see if this is that symbol.
6707 if (!DisSymName.empty() && DisSymName != SymName)
6708 continue;
6709
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00006710 // Start at the address of the symbol relative to the section's address.
Rafael Espindoladea00162015-07-03 17:44:18 +00006711 uint64_t Start = Symbols[SymIdx].getValue();
Rafael Espindola80291272014-10-08 15:28:58 +00006712 uint64_t SectionAddress = Sections[SectIdx].getAddress();
Cameron Zwarich54478a52012-02-03 05:42:17 +00006713 Start -= SectionAddress;
Owen Andersond9243c42011-10-17 21:37:35 +00006714
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00006715 // Stop disassembling either at the beginning of the next symbol or at
6716 // the end of the section.
Kevin Enderbyedd58722012-05-15 18:57:14 +00006717 bool containsNextSym = false;
Owen Andersond9243c42011-10-17 21:37:35 +00006718 uint64_t NextSym = 0;
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006719 uint64_t NextSymIdx = SymIdx + 1;
Owen Andersond9243c42011-10-17 21:37:35 +00006720 while (Symbols.size() > NextSymIdx) {
Kevin Enderby7bd8d992016-05-02 20:28:12 +00006721 Expected<SymbolRef::Type> STOrErr = Symbols[NextSymIdx].getType();
6722 if (!STOrErr) {
6723 std::string Buf;
6724 raw_string_ostream OS(Buf);
6725 logAllUnhandledErrors(STOrErr.takeError(), OS, "");
6726 OS.flush();
6727 report_fatal_error(Buf);
6728 }
Kevin Enderby5afbc1c2016-03-23 20:27:00 +00006729 SymbolRef::Type NextSymType = *STOrErr;
Owen Andersond9243c42011-10-17 21:37:35 +00006730 if (NextSymType == SymbolRef::ST_Function) {
Rafael Espindola80291272014-10-08 15:28:58 +00006731 containsNextSym =
6732 Sections[SectIdx].containsSymbol(Symbols[NextSymIdx]);
Rafael Espindoladea00162015-07-03 17:44:18 +00006733 NextSym = Symbols[NextSymIdx].getValue();
Cameron Zwarich54478a52012-02-03 05:42:17 +00006734 NextSym -= SectionAddress;
Owen Andersond9243c42011-10-17 21:37:35 +00006735 break;
6736 }
6737 ++NextSymIdx;
6738 }
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006739
Rafael Espindola80291272014-10-08 15:28:58 +00006740 uint64_t SectSize = Sections[SectIdx].getSize();
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006741 uint64_t End = containsNextSym ? NextSym : SectSize;
Owen Andersond9243c42011-10-17 21:37:35 +00006742 uint64_t Size;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006743
6744 symbolTableWorked = true;
Rafael Espindolabd604f22014-11-07 00:52:15 +00006745
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006746 DataRefImpl Symb = Symbols[SymIdx].getRawDataRefImpl();
Tim Northover09ca33e2016-04-22 23:23:31 +00006747 bool IsThumb = MachOOF->getSymbolFlags(Symb) & SymbolRef::SF_Thumb;
6748
6749 // We only need the dedicated Thumb target if there's a real choice
6750 // (i.e. we're not targeting M-class) and the function is Thumb.
6751 bool UseThumbTarget = IsThumb && ThumbTarget;
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006752
Ahmed Bougachaaa790682013-05-24 01:07:04 +00006753 outs() << SymName << ":\n";
6754 DILineInfo lastLine;
6755 for (uint64_t Index = Start; Index < End; Index += Size) {
6756 MCInst Inst;
Owen Andersond9243c42011-10-17 21:37:35 +00006757
Kevin Enderbybf246f52014-09-24 23:08:22 +00006758 uint64_t PC = SectAddress + Index;
Kevin Enderbyab5e6c92015-03-17 21:07:39 +00006759 if (!NoLeadingAddr) {
6760 if (FullLeadingAddr) {
6761 if (MachOOF->is64Bit())
6762 outs() << format("%016" PRIx64, PC);
6763 else
6764 outs() << format("%08" PRIx64, PC);
6765 } else {
6766 outs() << format("%8" PRIx64 ":", PC);
6767 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00006768 }
Kevin Enderby4b627be2016-04-28 20:14:13 +00006769 if (!NoShowRawInsn || Arch == Triple::arm)
Kevin Enderbybf246f52014-09-24 23:08:22 +00006770 outs() << "\t";
Kevin Enderby273ae012013-06-06 17:20:50 +00006771
6772 // Check the data in code table here to see if this is data not an
6773 // instruction to be disassembled.
6774 DiceTable Dice;
Kevin Enderbybf246f52014-09-24 23:08:22 +00006775 Dice.push_back(std::make_pair(PC, DiceRef()));
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006776 dice_table_iterator DTI =
6777 std::search(Dices.begin(), Dices.end(), Dice.begin(), Dice.end(),
6778 compareDiceTableEntries);
6779 if (DTI != Dices.end()) {
Kevin Enderby273ae012013-06-06 17:20:50 +00006780 uint16_t Length;
6781 DTI->second.getLength(Length);
Kevin Enderby273ae012013-06-06 17:20:50 +00006782 uint16_t Kind;
6783 DTI->second.getKind(Kind);
Colin LeMahieufc32b1b2015-03-18 19:27:31 +00006784 Size = DumpDataInCode(Bytes.data() + Index, Length, Kind);
Kevin Enderby930fdc72014-11-06 19:00:13 +00006785 if ((Kind == MachO::DICE_KIND_JUMP_TABLE8) &&
6786 (PC == (DTI->first + Length - 1)) && (Length & 1))
6787 Size++;
Kevin Enderby273ae012013-06-06 17:20:50 +00006788 continue;
6789 }
6790
Kevin Enderbybf246f52014-09-24 23:08:22 +00006791 SmallVector<char, 64> AnnotationsBytes;
6792 raw_svector_ostream Annotations(AnnotationsBytes);
6793
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006794 bool gotInst;
Tim Northover09ca33e2016-04-22 23:23:31 +00006795 if (UseThumbTarget)
Rafael Espindola7fc5b872014-11-12 02:04:27 +00006796 gotInst = ThumbDisAsm->getInstruction(Inst, Size, Bytes.slice(Index),
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006797 PC, DebugOut, Annotations);
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006798 else
Rafael Espindola7fc5b872014-11-12 02:04:27 +00006799 gotInst = DisAsm->getInstruction(Inst, Size, Bytes.slice(Index), PC,
Kevin Enderbybf246f52014-09-24 23:08:22 +00006800 DebugOut, Annotations);
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006801 if (gotInst) {
Kevin Enderby4b627be2016-04-28 20:14:13 +00006802 if (!NoShowRawInsn || Arch == Triple::arm) {
Craig Topper0013be12015-09-21 05:32:41 +00006803 dumpBytes(makeArrayRef(Bytes.data() + Index, Size), outs());
Kevin Enderbybf246f52014-09-24 23:08:22 +00006804 }
6805 formatted_raw_ostream FormattedOS(outs());
Kevin Enderbybf246f52014-09-24 23:08:22 +00006806 StringRef AnnotationsStr = Annotations.str();
Tim Northover09ca33e2016-04-22 23:23:31 +00006807 if (UseThumbTarget)
Akira Hatanakab46d0232015-03-27 20:36:02 +00006808 ThumbIP->printInst(&Inst, FormattedOS, AnnotationsStr, *ThumbSTI);
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006809 else
Akira Hatanaka1d079942015-03-28 20:44:05 +00006810 IP->printInst(&Inst, FormattedOS, AnnotationsStr, *STI);
Kevin Enderbybf246f52014-09-24 23:08:22 +00006811 emitComments(CommentStream, CommentsToEmit, FormattedOS, *AsmInfo);
Owen Andersond9243c42011-10-17 21:37:35 +00006812
Ahmed Bougachaaa790682013-05-24 01:07:04 +00006813 // Print debug info.
6814 if (diContext) {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006815 DILineInfo dli = diContext->getLineInfoForAddress(PC);
Ahmed Bougachaaa790682013-05-24 01:07:04 +00006816 // Print valid line info if it changed.
Alexey Samsonovd0109992014-04-18 21:36:39 +00006817 if (dli != lastLine && dli.Line != 0)
6818 outs() << "\t## " << dli.FileName << ':' << dli.Line << ':'
6819 << dli.Column;
Ahmed Bougachaaa790682013-05-24 01:07:04 +00006820 lastLine = dli;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006821 }
Ahmed Bougachaaa790682013-05-24 01:07:04 +00006822 outs() << "\n";
6823 } else {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006824 unsigned int Arch = MachOOF->getArch();
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006825 if (Arch == Triple::x86_64 || Arch == Triple::x86) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006826 outs() << format("\t.byte 0x%02x #bad opcode\n",
6827 *(Bytes.data() + Index) & 0xff);
6828 Size = 1; // skip exactly one illegible byte and move on.
Tim Northover09ca33e2016-04-22 23:23:31 +00006829 } else if (Arch == Triple::aarch64 ||
6830 (Arch == Triple::arm && !IsThumb)) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00006831 uint32_t opcode = (*(Bytes.data() + Index) & 0xff) |
6832 (*(Bytes.data() + Index + 1) & 0xff) << 8 |
6833 (*(Bytes.data() + Index + 2) & 0xff) << 16 |
6834 (*(Bytes.data() + Index + 3) & 0xff) << 24;
6835 outs() << format("\t.long\t0x%08x\n", opcode);
6836 Size = 4;
Tim Northover09ca33e2016-04-22 23:23:31 +00006837 } else if (Arch == Triple::arm) {
6838 assert(IsThumb && "ARM mode should have been dealt with above");
6839 uint32_t opcode = (*(Bytes.data() + Index) & 0xff) |
6840 (*(Bytes.data() + Index + 1) & 0xff) << 8;
6841 outs() << format("\t.short\t0x%04x\n", opcode);
6842 Size = 2;
6843 } else{
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006844 errs() << "llvm-objdump: warning: invalid instruction encoding\n";
6845 if (Size == 0)
6846 Size = 1; // skip illegible bytes
6847 }
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006848 }
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006849 }
6850 }
Ahmed Bougachaaa790682013-05-24 01:07:04 +00006851 if (!symbolTableWorked) {
Rafael Espindola80291272014-10-08 15:28:58 +00006852 // Reading the symbol table didn't work, disassemble the whole section.
6853 uint64_t SectAddress = Sections[SectIdx].getAddress();
6854 uint64_t SectSize = Sections[SectIdx].getSize();
Kevin Enderbybadd1002012-05-18 00:13:56 +00006855 uint64_t InstSize;
6856 for (uint64_t Index = 0; Index < SectSize; Index += InstSize) {
Bill Wendling4e68e062012-07-19 00:17:40 +00006857 MCInst Inst;
Kevin Enderbybadd1002012-05-18 00:13:56 +00006858
Kevin Enderbybf246f52014-09-24 23:08:22 +00006859 uint64_t PC = SectAddress + Index;
Rafael Espindola7fc5b872014-11-12 02:04:27 +00006860 if (DisAsm->getInstruction(Inst, InstSize, Bytes.slice(Index), PC,
6861 DebugOut, nulls())) {
Kevin Enderbyab5e6c92015-03-17 21:07:39 +00006862 if (!NoLeadingAddr) {
6863 if (FullLeadingAddr) {
6864 if (MachOOF->is64Bit())
6865 outs() << format("%016" PRIx64, PC);
6866 else
6867 outs() << format("%08" PRIx64, PC);
6868 } else {
6869 outs() << format("%8" PRIx64 ":", PC);
6870 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00006871 }
Kevin Enderby4b627be2016-04-28 20:14:13 +00006872 if (!NoShowRawInsn || Arch == Triple::arm) {
Kevin Enderbybf246f52014-09-24 23:08:22 +00006873 outs() << "\t";
Craig Topper0013be12015-09-21 05:32:41 +00006874 dumpBytes(makeArrayRef(Bytes.data() + Index, InstSize), outs());
Kevin Enderbybf246f52014-09-24 23:08:22 +00006875 }
Akira Hatanaka1d079942015-03-28 20:44:05 +00006876 IP->printInst(&Inst, outs(), "", *STI);
Bill Wendling4e68e062012-07-19 00:17:40 +00006877 outs() << "\n";
6878 } else {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006879 unsigned int Arch = MachOOF->getArch();
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006880 if (Arch == Triple::x86_64 || Arch == Triple::x86) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006881 outs() << format("\t.byte 0x%02x #bad opcode\n",
6882 *(Bytes.data() + Index) & 0xff);
6883 InstSize = 1; // skip exactly one illegible byte and move on.
6884 } else {
6885 errs() << "llvm-objdump: warning: invalid instruction encoding\n";
6886 if (InstSize == 0)
6887 InstSize = 1; // skip illegible bytes
6888 }
Bill Wendling4e68e062012-07-19 00:17:40 +00006889 }
Kevin Enderbybadd1002012-05-18 00:13:56 +00006890 }
6891 }
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00006892 // The TripleName's need to be reset if we are called again for a different
6893 // archtecture.
6894 TripleName = "";
6895 ThumbTripleName = "";
6896
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006897 if (SymbolizerInfo.method != nullptr)
6898 free(SymbolizerInfo.method);
Kevin Enderby04bf6932014-10-28 23:39:46 +00006899 if (SymbolizerInfo.demangled_name != nullptr)
6900 free(SymbolizerInfo.demangled_name);
Kevin Enderby078be602014-10-23 19:53:12 +00006901 if (SymbolizerInfo.bindtable != nullptr)
6902 delete SymbolizerInfo.bindtable;
Kevin Enderby930fdc72014-11-06 19:00:13 +00006903 if (ThumbSymbolizerInfo.method != nullptr)
6904 free(ThumbSymbolizerInfo.method);
6905 if (ThumbSymbolizerInfo.demangled_name != nullptr)
6906 free(ThumbSymbolizerInfo.demangled_name);
6907 if (ThumbSymbolizerInfo.bindtable != nullptr)
6908 delete ThumbSymbolizerInfo.bindtable;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006909 }
6910}
Tim Northover4bd286a2014-08-01 13:07:19 +00006911
Tim Northover39c70bb2014-08-12 11:52:59 +00006912//===----------------------------------------------------------------------===//
6913// __compact_unwind section dumping
6914//===----------------------------------------------------------------------===//
6915
Tim Northover4bd286a2014-08-01 13:07:19 +00006916namespace {
Tim Northover39c70bb2014-08-12 11:52:59 +00006917
6918template <typename T> static uint64_t readNext(const char *&Buf) {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006919 using llvm::support::little;
6920 using llvm::support::unaligned;
Tim Northover39c70bb2014-08-12 11:52:59 +00006921
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006922 uint64_t Val = support::endian::read<T, little, unaligned>(Buf);
6923 Buf += sizeof(T);
6924 return Val;
6925}
Tim Northover39c70bb2014-08-12 11:52:59 +00006926
Tim Northover4bd286a2014-08-01 13:07:19 +00006927struct CompactUnwindEntry {
6928 uint32_t OffsetInSection;
6929
6930 uint64_t FunctionAddr;
6931 uint32_t Length;
6932 uint32_t CompactEncoding;
6933 uint64_t PersonalityAddr;
6934 uint64_t LSDAAddr;
6935
6936 RelocationRef FunctionReloc;
6937 RelocationRef PersonalityReloc;
6938 RelocationRef LSDAReloc;
6939
6940 CompactUnwindEntry(StringRef Contents, unsigned Offset, bool Is64)
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006941 : OffsetInSection(Offset) {
Tim Northover4bd286a2014-08-01 13:07:19 +00006942 if (Is64)
6943 read<uint64_t>(Contents.data() + Offset);
6944 else
6945 read<uint32_t>(Contents.data() + Offset);
6946 }
6947
6948private:
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006949 template <typename UIntPtr> void read(const char *Buf) {
Tim Northover4bd286a2014-08-01 13:07:19 +00006950 FunctionAddr = readNext<UIntPtr>(Buf);
6951 Length = readNext<uint32_t>(Buf);
6952 CompactEncoding = readNext<uint32_t>(Buf);
6953 PersonalityAddr = readNext<UIntPtr>(Buf);
6954 LSDAAddr = readNext<UIntPtr>(Buf);
6955 }
6956};
6957}
6958
6959/// Given a relocation from __compact_unwind, consisting of the RelocationRef
6960/// and data being relocated, determine the best base Name and Addend to use for
6961/// display purposes.
6962///
6963/// 1. An Extern relocation will directly reference a symbol (and the data is
6964/// then already an addend), so use that.
6965/// 2. Otherwise the data is an offset in the object file's layout; try to find
6966// a symbol before it in the same section, and use the offset from there.
6967/// 3. Finally, if all that fails, fall back to an offset from the start of the
6968/// referenced section.
6969static void findUnwindRelocNameAddend(const MachOObjectFile *Obj,
6970 std::map<uint64_t, SymbolRef> &Symbols,
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006971 const RelocationRef &Reloc, uint64_t Addr,
Tim Northover4bd286a2014-08-01 13:07:19 +00006972 StringRef &Name, uint64_t &Addend) {
6973 if (Reloc.getSymbol() != Obj->symbol_end()) {
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00006974 Expected<StringRef> NameOrErr = Reloc.getSymbol()->getName();
6975 if (!NameOrErr) {
6976 std::string Buf;
6977 raw_string_ostream OS(Buf);
6978 logAllUnhandledErrors(NameOrErr.takeError(), OS, "");
6979 OS.flush();
6980 report_fatal_error(Buf);
6981 }
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00006982 Name = *NameOrErr;
Tim Northover4bd286a2014-08-01 13:07:19 +00006983 Addend = Addr;
6984 return;
6985 }
6986
6987 auto RE = Obj->getRelocation(Reloc.getRawDataRefImpl());
Keno Fischerc780e8e2015-05-21 21:24:32 +00006988 SectionRef RelocSection = Obj->getAnyRelocationSection(RE);
Tim Northover4bd286a2014-08-01 13:07:19 +00006989
Rafael Espindola80291272014-10-08 15:28:58 +00006990 uint64_t SectionAddr = RelocSection.getAddress();
Tim Northover4bd286a2014-08-01 13:07:19 +00006991
6992 auto Sym = Symbols.upper_bound(Addr);
6993 if (Sym == Symbols.begin()) {
6994 // The first symbol in the object is after this reference, the best we can
6995 // do is section-relative notation.
6996 RelocSection.getName(Name);
6997 Addend = Addr - SectionAddr;
6998 return;
6999 }
7000
7001 // Go back one so that SymbolAddress <= Addr.
7002 --Sym;
7003
Kevin Enderby7bd8d992016-05-02 20:28:12 +00007004 auto SectOrErr = Sym->second.getSection();
7005 if (!SectOrErr) {
7006 std::string Buf;
7007 raw_string_ostream OS(Buf);
7008 logAllUnhandledErrors(SectOrErr.takeError(), OS, "");
7009 OS.flush();
7010 report_fatal_error(Buf);
7011 }
7012 section_iterator SymSection = *SectOrErr;
Tim Northover4bd286a2014-08-01 13:07:19 +00007013 if (RelocSection == *SymSection) {
7014 // There's a valid symbol in the same section before this reference.
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00007015 Expected<StringRef> NameOrErr = Sym->second.getName();
7016 if (!NameOrErr) {
7017 std::string Buf;
7018 raw_string_ostream OS(Buf);
7019 logAllUnhandledErrors(NameOrErr.takeError(), OS, "");
7020 OS.flush();
7021 report_fatal_error(Buf);
7022 }
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00007023 Name = *NameOrErr;
Tim Northover4bd286a2014-08-01 13:07:19 +00007024 Addend = Addr - Sym->first;
7025 return;
7026 }
7027
7028 // There is a symbol before this reference, but it's in a different
7029 // section. Probably not helpful to mention it, so use the section name.
7030 RelocSection.getName(Name);
7031 Addend = Addr - SectionAddr;
7032}
7033
7034static void printUnwindRelocDest(const MachOObjectFile *Obj,
7035 std::map<uint64_t, SymbolRef> &Symbols,
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007036 const RelocationRef &Reloc, uint64_t Addr) {
Tim Northover4bd286a2014-08-01 13:07:19 +00007037 StringRef Name;
7038 uint64_t Addend;
7039
Rafael Espindola854038e2015-06-26 14:51:16 +00007040 if (!Reloc.getObject())
Tim Northover0b0add52014-09-09 10:45:06 +00007041 return;
7042
Tim Northover4bd286a2014-08-01 13:07:19 +00007043 findUnwindRelocNameAddend(Obj, Symbols, Reloc, Addr, Name, Addend);
7044
7045 outs() << Name;
7046 if (Addend)
Tim Northover63a25622014-08-11 09:14:06 +00007047 outs() << " + " << format("0x%" PRIx64, Addend);
Tim Northover4bd286a2014-08-01 13:07:19 +00007048}
7049
7050static void
7051printMachOCompactUnwindSection(const MachOObjectFile *Obj,
7052 std::map<uint64_t, SymbolRef> &Symbols,
7053 const SectionRef &CompactUnwind) {
7054
7055 assert(Obj->isLittleEndian() &&
7056 "There should not be a big-endian .o with __compact_unwind");
7057
7058 bool Is64 = Obj->is64Bit();
7059 uint32_t PointerSize = Is64 ? sizeof(uint64_t) : sizeof(uint32_t);
7060 uint32_t EntrySize = 3 * PointerSize + 2 * sizeof(uint32_t);
7061
7062 StringRef Contents;
7063 CompactUnwind.getContents(Contents);
7064
7065 SmallVector<CompactUnwindEntry, 4> CompactUnwinds;
7066
7067 // First populate the initial raw offsets, encodings and so on from the entry.
7068 for (unsigned Offset = 0; Offset < Contents.size(); Offset += EntrySize) {
7069 CompactUnwindEntry Entry(Contents.data(), Offset, Is64);
7070 CompactUnwinds.push_back(Entry);
7071 }
7072
7073 // Next we need to look at the relocations to find out what objects are
7074 // actually being referred to.
7075 for (const RelocationRef &Reloc : CompactUnwind.relocations()) {
Rafael Espindola96d071c2015-06-29 23:29:12 +00007076 uint64_t RelocAddress = Reloc.getOffset();
Tim Northover4bd286a2014-08-01 13:07:19 +00007077
7078 uint32_t EntryIdx = RelocAddress / EntrySize;
7079 uint32_t OffsetInEntry = RelocAddress - EntryIdx * EntrySize;
7080 CompactUnwindEntry &Entry = CompactUnwinds[EntryIdx];
7081
7082 if (OffsetInEntry == 0)
7083 Entry.FunctionReloc = Reloc;
7084 else if (OffsetInEntry == PointerSize + 2 * sizeof(uint32_t))
7085 Entry.PersonalityReloc = Reloc;
7086 else if (OffsetInEntry == 2 * PointerSize + 2 * sizeof(uint32_t))
7087 Entry.LSDAReloc = Reloc;
7088 else
7089 llvm_unreachable("Unexpected relocation in __compact_unwind section");
7090 }
7091
7092 // Finally, we're ready to print the data we've gathered.
7093 outs() << "Contents of __compact_unwind section:\n";
7094 for (auto &Entry : CompactUnwinds) {
Tim Northover06af2602014-08-08 12:08:51 +00007095 outs() << " Entry at offset "
7096 << format("0x%" PRIx32, Entry.OffsetInSection) << ":\n";
Tim Northover4bd286a2014-08-01 13:07:19 +00007097
7098 // 1. Start of the region this entry applies to.
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007099 outs() << " start: " << format("0x%" PRIx64,
7100 Entry.FunctionAddr) << ' ';
7101 printUnwindRelocDest(Obj, Symbols, Entry.FunctionReloc, Entry.FunctionAddr);
Tim Northover4bd286a2014-08-01 13:07:19 +00007102 outs() << '\n';
7103
7104 // 2. Length of the region this entry applies to.
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007105 outs() << " length: " << format("0x%" PRIx32, Entry.Length)
7106 << '\n';
Tim Northover4bd286a2014-08-01 13:07:19 +00007107 // 3. The 32-bit compact encoding.
7108 outs() << " compact encoding: "
Tim Northoverb911bf82014-08-08 12:00:09 +00007109 << format("0x%08" PRIx32, Entry.CompactEncoding) << '\n';
Tim Northover4bd286a2014-08-01 13:07:19 +00007110
7111 // 4. The personality function, if present.
Rafael Espindola854038e2015-06-26 14:51:16 +00007112 if (Entry.PersonalityReloc.getObject()) {
Tim Northover4bd286a2014-08-01 13:07:19 +00007113 outs() << " personality function: "
Tim Northoverb911bf82014-08-08 12:00:09 +00007114 << format("0x%" PRIx64, Entry.PersonalityAddr) << ' ';
Tim Northover4bd286a2014-08-01 13:07:19 +00007115 printUnwindRelocDest(Obj, Symbols, Entry.PersonalityReloc,
7116 Entry.PersonalityAddr);
7117 outs() << '\n';
7118 }
7119
7120 // 5. This entry's language-specific data area.
Rafael Espindola854038e2015-06-26 14:51:16 +00007121 if (Entry.LSDAReloc.getObject()) {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007122 outs() << " LSDA: " << format("0x%" PRIx64,
7123 Entry.LSDAAddr) << ' ';
Tim Northover4bd286a2014-08-01 13:07:19 +00007124 printUnwindRelocDest(Obj, Symbols, Entry.LSDAReloc, Entry.LSDAAddr);
7125 outs() << '\n';
7126 }
7127 }
7128}
7129
Tim Northover39c70bb2014-08-12 11:52:59 +00007130//===----------------------------------------------------------------------===//
7131// __unwind_info section dumping
7132//===----------------------------------------------------------------------===//
7133
7134static void printRegularSecondLevelUnwindPage(const char *PageStart) {
7135 const char *Pos = PageStart;
7136 uint32_t Kind = readNext<uint32_t>(Pos);
7137 (void)Kind;
7138 assert(Kind == 2 && "kind for a regular 2nd level index should be 2");
7139
7140 uint16_t EntriesStart = readNext<uint16_t>(Pos);
7141 uint16_t NumEntries = readNext<uint16_t>(Pos);
7142
7143 Pos = PageStart + EntriesStart;
7144 for (unsigned i = 0; i < NumEntries; ++i) {
7145 uint32_t FunctionOffset = readNext<uint32_t>(Pos);
7146 uint32_t Encoding = readNext<uint32_t>(Pos);
7147
7148 outs() << " [" << i << "]: "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007149 << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
7150 << ", "
7151 << "encoding=" << format("0x%08" PRIx32, Encoding) << '\n';
Tim Northover39c70bb2014-08-12 11:52:59 +00007152 }
7153}
7154
7155static void printCompressedSecondLevelUnwindPage(
7156 const char *PageStart, uint32_t FunctionBase,
7157 const SmallVectorImpl<uint32_t> &CommonEncodings) {
7158 const char *Pos = PageStart;
7159 uint32_t Kind = readNext<uint32_t>(Pos);
7160 (void)Kind;
7161 assert(Kind == 3 && "kind for a compressed 2nd level index should be 3");
7162
7163 uint16_t EntriesStart = readNext<uint16_t>(Pos);
7164 uint16_t NumEntries = readNext<uint16_t>(Pos);
7165
7166 uint16_t EncodingsStart = readNext<uint16_t>(Pos);
7167 readNext<uint16_t>(Pos);
Aaron Ballman80930af2014-08-14 13:53:19 +00007168 const auto *PageEncodings = reinterpret_cast<const support::ulittle32_t *>(
7169 PageStart + EncodingsStart);
Tim Northover39c70bb2014-08-12 11:52:59 +00007170
7171 Pos = PageStart + EntriesStart;
7172 for (unsigned i = 0; i < NumEntries; ++i) {
7173 uint32_t Entry = readNext<uint32_t>(Pos);
7174 uint32_t FunctionOffset = FunctionBase + (Entry & 0xffffff);
7175 uint32_t EncodingIdx = Entry >> 24;
7176
7177 uint32_t Encoding;
7178 if (EncodingIdx < CommonEncodings.size())
7179 Encoding = CommonEncodings[EncodingIdx];
7180 else
7181 Encoding = PageEncodings[EncodingIdx - CommonEncodings.size()];
7182
7183 outs() << " [" << i << "]: "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007184 << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
7185 << ", "
7186 << "encoding[" << EncodingIdx
7187 << "]=" << format("0x%08" PRIx32, Encoding) << '\n';
Tim Northover39c70bb2014-08-12 11:52:59 +00007188 }
7189}
7190
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007191static void printMachOUnwindInfoSection(const MachOObjectFile *Obj,
7192 std::map<uint64_t, SymbolRef> &Symbols,
7193 const SectionRef &UnwindInfo) {
Tim Northover39c70bb2014-08-12 11:52:59 +00007194
7195 assert(Obj->isLittleEndian() &&
7196 "There should not be a big-endian .o with __unwind_info");
7197
7198 outs() << "Contents of __unwind_info section:\n";
7199
7200 StringRef Contents;
7201 UnwindInfo.getContents(Contents);
7202 const char *Pos = Contents.data();
7203
7204 //===----------------------------------
7205 // Section header
7206 //===----------------------------------
7207
7208 uint32_t Version = readNext<uint32_t>(Pos);
7209 outs() << " Version: "
7210 << format("0x%" PRIx32, Version) << '\n';
7211 assert(Version == 1 && "only understand version 1");
7212
7213 uint32_t CommonEncodingsStart = readNext<uint32_t>(Pos);
7214 outs() << " Common encodings array section offset: "
7215 << format("0x%" PRIx32, CommonEncodingsStart) << '\n';
7216 uint32_t NumCommonEncodings = readNext<uint32_t>(Pos);
7217 outs() << " Number of common encodings in array: "
7218 << format("0x%" PRIx32, NumCommonEncodings) << '\n';
7219
7220 uint32_t PersonalitiesStart = readNext<uint32_t>(Pos);
7221 outs() << " Personality function array section offset: "
7222 << format("0x%" PRIx32, PersonalitiesStart) << '\n';
7223 uint32_t NumPersonalities = readNext<uint32_t>(Pos);
7224 outs() << " Number of personality functions in array: "
7225 << format("0x%" PRIx32, NumPersonalities) << '\n';
7226
7227 uint32_t IndicesStart = readNext<uint32_t>(Pos);
7228 outs() << " Index array section offset: "
7229 << format("0x%" PRIx32, IndicesStart) << '\n';
7230 uint32_t NumIndices = readNext<uint32_t>(Pos);
7231 outs() << " Number of indices in array: "
7232 << format("0x%" PRIx32, NumIndices) << '\n';
7233
7234 //===----------------------------------
7235 // A shared list of common encodings
7236 //===----------------------------------
7237
7238 // These occupy indices in the range [0, N] whenever an encoding is referenced
7239 // from a compressed 2nd level index table. In practice the linker only
7240 // creates ~128 of these, so that indices are available to embed encodings in
7241 // the 2nd level index.
7242
7243 SmallVector<uint32_t, 64> CommonEncodings;
7244 outs() << " Common encodings: (count = " << NumCommonEncodings << ")\n";
7245 Pos = Contents.data() + CommonEncodingsStart;
7246 for (unsigned i = 0; i < NumCommonEncodings; ++i) {
7247 uint32_t Encoding = readNext<uint32_t>(Pos);
7248 CommonEncodings.push_back(Encoding);
7249
7250 outs() << " encoding[" << i << "]: " << format("0x%08" PRIx32, Encoding)
7251 << '\n';
7252 }
7253
Tim Northover39c70bb2014-08-12 11:52:59 +00007254 //===----------------------------------
7255 // Personality functions used in this executable
7256 //===----------------------------------
7257
7258 // There should be only a handful of these (one per source language,
7259 // roughly). Particularly since they only get 2 bits in the compact encoding.
7260
7261 outs() << " Personality functions: (count = " << NumPersonalities << ")\n";
7262 Pos = Contents.data() + PersonalitiesStart;
7263 for (unsigned i = 0; i < NumPersonalities; ++i) {
7264 uint32_t PersonalityFn = readNext<uint32_t>(Pos);
7265 outs() << " personality[" << i + 1
7266 << "]: " << format("0x%08" PRIx32, PersonalityFn) << '\n';
7267 }
7268
7269 //===----------------------------------
7270 // The level 1 index entries
7271 //===----------------------------------
7272
7273 // These specify an approximate place to start searching for the more detailed
7274 // information, sorted by PC.
7275
7276 struct IndexEntry {
7277 uint32_t FunctionOffset;
7278 uint32_t SecondLevelPageStart;
7279 uint32_t LSDAStart;
7280 };
7281
7282 SmallVector<IndexEntry, 4> IndexEntries;
7283
7284 outs() << " Top level indices: (count = " << NumIndices << ")\n";
7285 Pos = Contents.data() + IndicesStart;
7286 for (unsigned i = 0; i < NumIndices; ++i) {
7287 IndexEntry Entry;
7288
7289 Entry.FunctionOffset = readNext<uint32_t>(Pos);
7290 Entry.SecondLevelPageStart = readNext<uint32_t>(Pos);
7291 Entry.LSDAStart = readNext<uint32_t>(Pos);
7292 IndexEntries.push_back(Entry);
7293
7294 outs() << " [" << i << "]: "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007295 << "function offset=" << format("0x%08" PRIx32, Entry.FunctionOffset)
7296 << ", "
Tim Northover39c70bb2014-08-12 11:52:59 +00007297 << "2nd level page offset="
7298 << format("0x%08" PRIx32, Entry.SecondLevelPageStart) << ", "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007299 << "LSDA offset=" << format("0x%08" PRIx32, Entry.LSDAStart) << '\n';
Tim Northover39c70bb2014-08-12 11:52:59 +00007300 }
7301
Tim Northover39c70bb2014-08-12 11:52:59 +00007302 //===----------------------------------
7303 // Next come the LSDA tables
7304 //===----------------------------------
7305
7306 // The LSDA layout is rather implicit: it's a contiguous array of entries from
7307 // the first top-level index's LSDAOffset to the last (sentinel).
7308
7309 outs() << " LSDA descriptors:\n";
7310 Pos = Contents.data() + IndexEntries[0].LSDAStart;
7311 int NumLSDAs = (IndexEntries.back().LSDAStart - IndexEntries[0].LSDAStart) /
7312 (2 * sizeof(uint32_t));
7313 for (int i = 0; i < NumLSDAs; ++i) {
7314 uint32_t FunctionOffset = readNext<uint32_t>(Pos);
7315 uint32_t LSDAOffset = readNext<uint32_t>(Pos);
7316 outs() << " [" << i << "]: "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007317 << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
7318 << ", "
7319 << "LSDA offset=" << format("0x%08" PRIx32, LSDAOffset) << '\n';
Tim Northover39c70bb2014-08-12 11:52:59 +00007320 }
7321
7322 //===----------------------------------
7323 // Finally, the 2nd level indices
7324 //===----------------------------------
7325
7326 // Generally these are 4K in size, and have 2 possible forms:
7327 // + Regular stores up to 511 entries with disparate encodings
7328 // + Compressed stores up to 1021 entries if few enough compact encoding
7329 // values are used.
7330 outs() << " Second level indices:\n";
7331 for (unsigned i = 0; i < IndexEntries.size() - 1; ++i) {
7332 // The final sentinel top-level index has no associated 2nd level page
7333 if (IndexEntries[i].SecondLevelPageStart == 0)
7334 break;
7335
7336 outs() << " Second level index[" << i << "]: "
7337 << "offset in section="
7338 << format("0x%08" PRIx32, IndexEntries[i].SecondLevelPageStart)
7339 << ", "
7340 << "base function offset="
7341 << format("0x%08" PRIx32, IndexEntries[i].FunctionOffset) << '\n';
7342
7343 Pos = Contents.data() + IndexEntries[i].SecondLevelPageStart;
Aaron Ballman80930af2014-08-14 13:53:19 +00007344 uint32_t Kind = *reinterpret_cast<const support::ulittle32_t *>(Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007345 if (Kind == 2)
7346 printRegularSecondLevelUnwindPage(Pos);
7347 else if (Kind == 3)
7348 printCompressedSecondLevelUnwindPage(Pos, IndexEntries[i].FunctionOffset,
7349 CommonEncodings);
7350 else
7351 llvm_unreachable("Do not know how to print this kind of 2nd level page");
Tim Northover39c70bb2014-08-12 11:52:59 +00007352 }
7353}
7354
Tim Northover4bd286a2014-08-01 13:07:19 +00007355void llvm::printMachOUnwindInfo(const MachOObjectFile *Obj) {
7356 std::map<uint64_t, SymbolRef> Symbols;
7357 for (const SymbolRef &SymRef : Obj->symbols()) {
7358 // Discard any undefined or absolute symbols. They're not going to take part
7359 // in the convenience lookup for unwind info and just take up resources.
Kevin Enderby7bd8d992016-05-02 20:28:12 +00007360 auto SectOrErr = SymRef.getSection();
7361 if (!SectOrErr) {
7362 // TODO: Actually report errors helpfully.
7363 consumeError(SectOrErr.takeError());
7364 continue;
7365 }
7366 section_iterator Section = *SectOrErr;
Tim Northover4bd286a2014-08-01 13:07:19 +00007367 if (Section == Obj->section_end())
7368 continue;
7369
Rafael Espindoladea00162015-07-03 17:44:18 +00007370 uint64_t Addr = SymRef.getValue();
Tim Northover4bd286a2014-08-01 13:07:19 +00007371 Symbols.insert(std::make_pair(Addr, SymRef));
7372 }
7373
7374 for (const SectionRef &Section : Obj->sections()) {
7375 StringRef SectName;
7376 Section.getName(SectName);
7377 if (SectName == "__compact_unwind")
7378 printMachOCompactUnwindSection(Obj, Symbols, Section);
7379 else if (SectName == "__unwind_info")
Tim Northover39c70bb2014-08-12 11:52:59 +00007380 printMachOUnwindInfoSection(Obj, Symbols, Section);
Tim Northover4bd286a2014-08-01 13:07:19 +00007381 }
7382}
Kevin Enderbyb76d3862014-08-22 20:35:18 +00007383
7384static void PrintMachHeader(uint32_t magic, uint32_t cputype,
7385 uint32_t cpusubtype, uint32_t filetype,
7386 uint32_t ncmds, uint32_t sizeofcmds, uint32_t flags,
7387 bool verbose) {
7388 outs() << "Mach header\n";
7389 outs() << " magic cputype cpusubtype caps filetype ncmds "
7390 "sizeofcmds flags\n";
7391 if (verbose) {
7392 if (magic == MachO::MH_MAGIC)
7393 outs() << " MH_MAGIC";
7394 else if (magic == MachO::MH_MAGIC_64)
7395 outs() << "MH_MAGIC_64";
7396 else
7397 outs() << format(" 0x%08" PRIx32, magic);
7398 switch (cputype) {
7399 case MachO::CPU_TYPE_I386:
7400 outs() << " I386";
7401 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
7402 case MachO::CPU_SUBTYPE_I386_ALL:
7403 outs() << " ALL";
7404 break;
7405 default:
7406 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
7407 break;
7408 }
7409 break;
7410 case MachO::CPU_TYPE_X86_64:
7411 outs() << " X86_64";
Kevin Enderby131d1772015-01-09 19:22:37 +00007412 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
7413 case MachO::CPU_SUBTYPE_X86_64_ALL:
7414 outs() << " ALL";
7415 break;
7416 case MachO::CPU_SUBTYPE_X86_64_H:
7417 outs() << " Haswell";
7418 break;
7419 default:
7420 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
7421 break;
7422 }
Kevin Enderbyb76d3862014-08-22 20:35:18 +00007423 break;
7424 case MachO::CPU_TYPE_ARM:
7425 outs() << " ARM";
7426 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
7427 case MachO::CPU_SUBTYPE_ARM_ALL:
7428 outs() << " ALL";
7429 break;
7430 case MachO::CPU_SUBTYPE_ARM_V4T:
7431 outs() << " V4T";
7432 break;
7433 case MachO::CPU_SUBTYPE_ARM_V5TEJ:
7434 outs() << " V5TEJ";
7435 break;
7436 case MachO::CPU_SUBTYPE_ARM_XSCALE:
7437 outs() << " XSCALE";
7438 break;
7439 case MachO::CPU_SUBTYPE_ARM_V6:
7440 outs() << " V6";
7441 break;
7442 case MachO::CPU_SUBTYPE_ARM_V6M:
7443 outs() << " V6M";
7444 break;
7445 case MachO::CPU_SUBTYPE_ARM_V7:
7446 outs() << " V7";
7447 break;
7448 case MachO::CPU_SUBTYPE_ARM_V7EM:
7449 outs() << " V7EM";
7450 break;
7451 case MachO::CPU_SUBTYPE_ARM_V7K:
7452 outs() << " V7K";
7453 break;
7454 case MachO::CPU_SUBTYPE_ARM_V7M:
7455 outs() << " V7M";
7456 break;
7457 case MachO::CPU_SUBTYPE_ARM_V7S:
7458 outs() << " V7S";
7459 break;
7460 default:
7461 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
7462 break;
7463 }
7464 break;
7465 case MachO::CPU_TYPE_ARM64:
7466 outs() << " ARM64";
7467 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
7468 case MachO::CPU_SUBTYPE_ARM64_ALL:
7469 outs() << " ALL";
7470 break;
7471 default:
7472 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
7473 break;
7474 }
7475 break;
7476 case MachO::CPU_TYPE_POWERPC:
7477 outs() << " PPC";
7478 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
7479 case MachO::CPU_SUBTYPE_POWERPC_ALL:
7480 outs() << " ALL";
7481 break;
7482 default:
7483 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
7484 break;
7485 }
7486 break;
7487 case MachO::CPU_TYPE_POWERPC64:
7488 outs() << " PPC64";
7489 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
7490 case MachO::CPU_SUBTYPE_POWERPC_ALL:
7491 outs() << " ALL";
7492 break;
7493 default:
7494 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
7495 break;
7496 }
7497 break;
Kevin Enderby40fdbf82016-01-26 18:20:49 +00007498 default:
7499 outs() << format(" %7d", cputype);
7500 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
7501 break;
Kevin Enderbyb76d3862014-08-22 20:35:18 +00007502 }
7503 if ((cpusubtype & MachO::CPU_SUBTYPE_MASK) == MachO::CPU_SUBTYPE_LIB64) {
Kevin Enderby8ae63c12014-09-04 16:54:47 +00007504 outs() << " LIB64";
Kevin Enderbyb76d3862014-08-22 20:35:18 +00007505 } else {
7506 outs() << format(" 0x%02" PRIx32,
7507 (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24);
7508 }
7509 switch (filetype) {
7510 case MachO::MH_OBJECT:
7511 outs() << " OBJECT";
7512 break;
7513 case MachO::MH_EXECUTE:
7514 outs() << " EXECUTE";
7515 break;
7516 case MachO::MH_FVMLIB:
7517 outs() << " FVMLIB";
7518 break;
7519 case MachO::MH_CORE:
7520 outs() << " CORE";
7521 break;
7522 case MachO::MH_PRELOAD:
7523 outs() << " PRELOAD";
7524 break;
7525 case MachO::MH_DYLIB:
7526 outs() << " DYLIB";
7527 break;
7528 case MachO::MH_DYLIB_STUB:
7529 outs() << " DYLIB_STUB";
7530 break;
7531 case MachO::MH_DYLINKER:
7532 outs() << " DYLINKER";
7533 break;
7534 case MachO::MH_BUNDLE:
7535 outs() << " BUNDLE";
7536 break;
7537 case MachO::MH_DSYM:
7538 outs() << " DSYM";
7539 break;
7540 case MachO::MH_KEXT_BUNDLE:
7541 outs() << " KEXTBUNDLE";
7542 break;
7543 default:
7544 outs() << format(" %10u", filetype);
7545 break;
7546 }
7547 outs() << format(" %5u", ncmds);
7548 outs() << format(" %10u", sizeofcmds);
7549 uint32_t f = flags;
7550 if (f & MachO::MH_NOUNDEFS) {
7551 outs() << " NOUNDEFS";
7552 f &= ~MachO::MH_NOUNDEFS;
7553 }
7554 if (f & MachO::MH_INCRLINK) {
7555 outs() << " INCRLINK";
7556 f &= ~MachO::MH_INCRLINK;
7557 }
7558 if (f & MachO::MH_DYLDLINK) {
7559 outs() << " DYLDLINK";
7560 f &= ~MachO::MH_DYLDLINK;
7561 }
7562 if (f & MachO::MH_BINDATLOAD) {
7563 outs() << " BINDATLOAD";
7564 f &= ~MachO::MH_BINDATLOAD;
7565 }
7566 if (f & MachO::MH_PREBOUND) {
7567 outs() << " PREBOUND";
7568 f &= ~MachO::MH_PREBOUND;
7569 }
7570 if (f & MachO::MH_SPLIT_SEGS) {
7571 outs() << " SPLIT_SEGS";
7572 f &= ~MachO::MH_SPLIT_SEGS;
7573 }
7574 if (f & MachO::MH_LAZY_INIT) {
7575 outs() << " LAZY_INIT";
7576 f &= ~MachO::MH_LAZY_INIT;
7577 }
7578 if (f & MachO::MH_TWOLEVEL) {
7579 outs() << " TWOLEVEL";
7580 f &= ~MachO::MH_TWOLEVEL;
7581 }
7582 if (f & MachO::MH_FORCE_FLAT) {
7583 outs() << " FORCE_FLAT";
7584 f &= ~MachO::MH_FORCE_FLAT;
7585 }
7586 if (f & MachO::MH_NOMULTIDEFS) {
7587 outs() << " NOMULTIDEFS";
7588 f &= ~MachO::MH_NOMULTIDEFS;
7589 }
7590 if (f & MachO::MH_NOFIXPREBINDING) {
7591 outs() << " NOFIXPREBINDING";
7592 f &= ~MachO::MH_NOFIXPREBINDING;
7593 }
7594 if (f & MachO::MH_PREBINDABLE) {
7595 outs() << " PREBINDABLE";
7596 f &= ~MachO::MH_PREBINDABLE;
7597 }
7598 if (f & MachO::MH_ALLMODSBOUND) {
7599 outs() << " ALLMODSBOUND";
7600 f &= ~MachO::MH_ALLMODSBOUND;
7601 }
7602 if (f & MachO::MH_SUBSECTIONS_VIA_SYMBOLS) {
7603 outs() << " SUBSECTIONS_VIA_SYMBOLS";
7604 f &= ~MachO::MH_SUBSECTIONS_VIA_SYMBOLS;
7605 }
7606 if (f & MachO::MH_CANONICAL) {
7607 outs() << " CANONICAL";
7608 f &= ~MachO::MH_CANONICAL;
7609 }
7610 if (f & MachO::MH_WEAK_DEFINES) {
7611 outs() << " WEAK_DEFINES";
7612 f &= ~MachO::MH_WEAK_DEFINES;
7613 }
7614 if (f & MachO::MH_BINDS_TO_WEAK) {
7615 outs() << " BINDS_TO_WEAK";
7616 f &= ~MachO::MH_BINDS_TO_WEAK;
7617 }
7618 if (f & MachO::MH_ALLOW_STACK_EXECUTION) {
7619 outs() << " ALLOW_STACK_EXECUTION";
7620 f &= ~MachO::MH_ALLOW_STACK_EXECUTION;
7621 }
7622 if (f & MachO::MH_DEAD_STRIPPABLE_DYLIB) {
7623 outs() << " DEAD_STRIPPABLE_DYLIB";
7624 f &= ~MachO::MH_DEAD_STRIPPABLE_DYLIB;
7625 }
7626 if (f & MachO::MH_PIE) {
7627 outs() << " PIE";
7628 f &= ~MachO::MH_PIE;
7629 }
7630 if (f & MachO::MH_NO_REEXPORTED_DYLIBS) {
7631 outs() << " NO_REEXPORTED_DYLIBS";
7632 f &= ~MachO::MH_NO_REEXPORTED_DYLIBS;
7633 }
7634 if (f & MachO::MH_HAS_TLV_DESCRIPTORS) {
7635 outs() << " MH_HAS_TLV_DESCRIPTORS";
7636 f &= ~MachO::MH_HAS_TLV_DESCRIPTORS;
7637 }
7638 if (f & MachO::MH_NO_HEAP_EXECUTION) {
7639 outs() << " MH_NO_HEAP_EXECUTION";
7640 f &= ~MachO::MH_NO_HEAP_EXECUTION;
7641 }
7642 if (f & MachO::MH_APP_EXTENSION_SAFE) {
7643 outs() << " APP_EXTENSION_SAFE";
7644 f &= ~MachO::MH_APP_EXTENSION_SAFE;
7645 }
7646 if (f != 0 || flags == 0)
7647 outs() << format(" 0x%08" PRIx32, f);
7648 } else {
7649 outs() << format(" 0x%08" PRIx32, magic);
7650 outs() << format(" %7d", cputype);
7651 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
7652 outs() << format(" 0x%02" PRIx32,
7653 (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24);
7654 outs() << format(" %10u", filetype);
7655 outs() << format(" %5u", ncmds);
7656 outs() << format(" %10u", sizeofcmds);
7657 outs() << format(" 0x%08" PRIx32, flags);
7658 }
7659 outs() << "\n";
7660}
7661
Kevin Enderby956366c2014-08-29 22:30:52 +00007662static void PrintSegmentCommand(uint32_t cmd, uint32_t cmdsize,
7663 StringRef SegName, uint64_t vmaddr,
7664 uint64_t vmsize, uint64_t fileoff,
7665 uint64_t filesize, uint32_t maxprot,
7666 uint32_t initprot, uint32_t nsects,
7667 uint32_t flags, uint32_t object_size,
7668 bool verbose) {
7669 uint64_t expected_cmdsize;
7670 if (cmd == MachO::LC_SEGMENT) {
7671 outs() << " cmd LC_SEGMENT\n";
7672 expected_cmdsize = nsects;
7673 expected_cmdsize *= sizeof(struct MachO::section);
7674 expected_cmdsize += sizeof(struct MachO::segment_command);
7675 } else {
7676 outs() << " cmd LC_SEGMENT_64\n";
7677 expected_cmdsize = nsects;
7678 expected_cmdsize *= sizeof(struct MachO::section_64);
7679 expected_cmdsize += sizeof(struct MachO::segment_command_64);
7680 }
7681 outs() << " cmdsize " << cmdsize;
7682 if (cmdsize != expected_cmdsize)
7683 outs() << " Inconsistent size\n";
7684 else
7685 outs() << "\n";
7686 outs() << " segname " << SegName << "\n";
7687 if (cmd == MachO::LC_SEGMENT_64) {
7688 outs() << " vmaddr " << format("0x%016" PRIx64, vmaddr) << "\n";
7689 outs() << " vmsize " << format("0x%016" PRIx64, vmsize) << "\n";
7690 } else {
Kevin Enderbyadb7c432014-12-16 18:58:11 +00007691 outs() << " vmaddr " << format("0x%08" PRIx64, vmaddr) << "\n";
7692 outs() << " vmsize " << format("0x%08" PRIx64, vmsize) << "\n";
Kevin Enderby956366c2014-08-29 22:30:52 +00007693 }
7694 outs() << " fileoff " << fileoff;
7695 if (fileoff > object_size)
7696 outs() << " (past end of file)\n";
7697 else
7698 outs() << "\n";
7699 outs() << " filesize " << filesize;
7700 if (fileoff + filesize > object_size)
7701 outs() << " (past end of file)\n";
7702 else
7703 outs() << "\n";
7704 if (verbose) {
7705 if ((maxprot &
7706 ~(MachO::VM_PROT_READ | MachO::VM_PROT_WRITE |
7707 MachO::VM_PROT_EXECUTE)) != 0)
7708 outs() << " maxprot ?" << format("0x%08" PRIx32, maxprot) << "\n";
7709 else {
Davide Italiano37ff06a2015-09-02 16:53:25 +00007710 outs() << " maxprot ";
7711 outs() << ((maxprot & MachO::VM_PROT_READ) ? "r" : "-");
7712 outs() << ((maxprot & MachO::VM_PROT_WRITE) ? "w" : "-");
7713 outs() << ((maxprot & MachO::VM_PROT_EXECUTE) ? "x\n" : "-\n");
Kevin Enderby956366c2014-08-29 22:30:52 +00007714 }
7715 if ((initprot &
7716 ~(MachO::VM_PROT_READ | MachO::VM_PROT_WRITE |
7717 MachO::VM_PROT_EXECUTE)) != 0)
7718 outs() << " initprot ?" << format("0x%08" PRIx32, initprot) << "\n";
7719 else {
Davide Italiano37ff06a2015-09-02 16:53:25 +00007720 outs() << " initprot ";
7721 outs() << ((initprot & MachO::VM_PROT_READ) ? "r" : "-");
7722 outs() << ((initprot & MachO::VM_PROT_WRITE) ? "w" : "-");
7723 outs() << ((initprot & MachO::VM_PROT_EXECUTE) ? "x\n" : "-\n");
Kevin Enderby956366c2014-08-29 22:30:52 +00007724 }
7725 } else {
7726 outs() << " maxprot " << format("0x%08" PRIx32, maxprot) << "\n";
7727 outs() << " initprot " << format("0x%08" PRIx32, initprot) << "\n";
7728 }
7729 outs() << " nsects " << nsects << "\n";
7730 if (verbose) {
7731 outs() << " flags";
7732 if (flags == 0)
7733 outs() << " (none)\n";
7734 else {
7735 if (flags & MachO::SG_HIGHVM) {
7736 outs() << " HIGHVM";
7737 flags &= ~MachO::SG_HIGHVM;
7738 }
7739 if (flags & MachO::SG_FVMLIB) {
7740 outs() << " FVMLIB";
7741 flags &= ~MachO::SG_FVMLIB;
7742 }
7743 if (flags & MachO::SG_NORELOC) {
7744 outs() << " NORELOC";
7745 flags &= ~MachO::SG_NORELOC;
7746 }
7747 if (flags & MachO::SG_PROTECTED_VERSION_1) {
7748 outs() << " PROTECTED_VERSION_1";
7749 flags &= ~MachO::SG_PROTECTED_VERSION_1;
7750 }
7751 if (flags)
7752 outs() << format(" 0x%08" PRIx32, flags) << " (unknown flags)\n";
7753 else
7754 outs() << "\n";
7755 }
7756 } else {
7757 outs() << " flags " << format("0x%" PRIx32, flags) << "\n";
7758 }
7759}
7760
7761static void PrintSection(const char *sectname, const char *segname,
7762 uint64_t addr, uint64_t size, uint32_t offset,
7763 uint32_t align, uint32_t reloff, uint32_t nreloc,
7764 uint32_t flags, uint32_t reserved1, uint32_t reserved2,
7765 uint32_t cmd, const char *sg_segname,
7766 uint32_t filetype, uint32_t object_size,
7767 bool verbose) {
7768 outs() << "Section\n";
7769 outs() << " sectname " << format("%.16s\n", sectname);
7770 outs() << " segname " << format("%.16s", segname);
7771 if (filetype != MachO::MH_OBJECT && strncmp(sg_segname, segname, 16) != 0)
7772 outs() << " (does not match segment)\n";
7773 else
7774 outs() << "\n";
7775 if (cmd == MachO::LC_SEGMENT_64) {
7776 outs() << " addr " << format("0x%016" PRIx64, addr) << "\n";
7777 outs() << " size " << format("0x%016" PRIx64, size);
7778 } else {
Kevin Enderby75594b62014-12-16 21:00:25 +00007779 outs() << " addr " << format("0x%08" PRIx64, addr) << "\n";
7780 outs() << " size " << format("0x%08" PRIx64, size);
Kevin Enderby956366c2014-08-29 22:30:52 +00007781 }
7782 if ((flags & MachO::S_ZEROFILL) != 0 && offset + size > object_size)
7783 outs() << " (past end of file)\n";
7784 else
7785 outs() << "\n";
7786 outs() << " offset " << offset;
7787 if (offset > object_size)
7788 outs() << " (past end of file)\n";
7789 else
7790 outs() << "\n";
7791 uint32_t align_shifted = 1 << align;
7792 outs() << " align 2^" << align << " (" << align_shifted << ")\n";
7793 outs() << " reloff " << reloff;
7794 if (reloff > object_size)
7795 outs() << " (past end of file)\n";
7796 else
7797 outs() << "\n";
7798 outs() << " nreloc " << nreloc;
7799 if (reloff + nreloc * sizeof(struct MachO::relocation_info) > object_size)
7800 outs() << " (past end of file)\n";
7801 else
7802 outs() << "\n";
7803 uint32_t section_type = flags & MachO::SECTION_TYPE;
7804 if (verbose) {
7805 outs() << " type";
7806 if (section_type == MachO::S_REGULAR)
7807 outs() << " S_REGULAR\n";
7808 else if (section_type == MachO::S_ZEROFILL)
7809 outs() << " S_ZEROFILL\n";
7810 else if (section_type == MachO::S_CSTRING_LITERALS)
7811 outs() << " S_CSTRING_LITERALS\n";
7812 else if (section_type == MachO::S_4BYTE_LITERALS)
7813 outs() << " S_4BYTE_LITERALS\n";
7814 else if (section_type == MachO::S_8BYTE_LITERALS)
7815 outs() << " S_8BYTE_LITERALS\n";
7816 else if (section_type == MachO::S_16BYTE_LITERALS)
7817 outs() << " S_16BYTE_LITERALS\n";
7818 else if (section_type == MachO::S_LITERAL_POINTERS)
7819 outs() << " S_LITERAL_POINTERS\n";
7820 else if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS)
7821 outs() << " S_NON_LAZY_SYMBOL_POINTERS\n";
7822 else if (section_type == MachO::S_LAZY_SYMBOL_POINTERS)
7823 outs() << " S_LAZY_SYMBOL_POINTERS\n";
7824 else if (section_type == MachO::S_SYMBOL_STUBS)
7825 outs() << " S_SYMBOL_STUBS\n";
7826 else if (section_type == MachO::S_MOD_INIT_FUNC_POINTERS)
7827 outs() << " S_MOD_INIT_FUNC_POINTERS\n";
7828 else if (section_type == MachO::S_MOD_TERM_FUNC_POINTERS)
7829 outs() << " S_MOD_TERM_FUNC_POINTERS\n";
7830 else if (section_type == MachO::S_COALESCED)
7831 outs() << " S_COALESCED\n";
7832 else if (section_type == MachO::S_INTERPOSING)
7833 outs() << " S_INTERPOSING\n";
7834 else if (section_type == MachO::S_DTRACE_DOF)
7835 outs() << " S_DTRACE_DOF\n";
7836 else if (section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS)
7837 outs() << " S_LAZY_DYLIB_SYMBOL_POINTERS\n";
7838 else if (section_type == MachO::S_THREAD_LOCAL_REGULAR)
7839 outs() << " S_THREAD_LOCAL_REGULAR\n";
7840 else if (section_type == MachO::S_THREAD_LOCAL_ZEROFILL)
7841 outs() << " S_THREAD_LOCAL_ZEROFILL\n";
7842 else if (section_type == MachO::S_THREAD_LOCAL_VARIABLES)
7843 outs() << " S_THREAD_LOCAL_VARIABLES\n";
7844 else if (section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS)
7845 outs() << " S_THREAD_LOCAL_VARIABLE_POINTERS\n";
7846 else if (section_type == MachO::S_THREAD_LOCAL_INIT_FUNCTION_POINTERS)
7847 outs() << " S_THREAD_LOCAL_INIT_FUNCTION_POINTERS\n";
7848 else
7849 outs() << format("0x%08" PRIx32, section_type) << "\n";
7850 outs() << "attributes";
7851 uint32_t section_attributes = flags & MachO::SECTION_ATTRIBUTES;
7852 if (section_attributes & MachO::S_ATTR_PURE_INSTRUCTIONS)
7853 outs() << " PURE_INSTRUCTIONS";
7854 if (section_attributes & MachO::S_ATTR_NO_TOC)
7855 outs() << " NO_TOC";
7856 if (section_attributes & MachO::S_ATTR_STRIP_STATIC_SYMS)
7857 outs() << " STRIP_STATIC_SYMS";
7858 if (section_attributes & MachO::S_ATTR_NO_DEAD_STRIP)
7859 outs() << " NO_DEAD_STRIP";
7860 if (section_attributes & MachO::S_ATTR_LIVE_SUPPORT)
7861 outs() << " LIVE_SUPPORT";
7862 if (section_attributes & MachO::S_ATTR_SELF_MODIFYING_CODE)
7863 outs() << " SELF_MODIFYING_CODE";
7864 if (section_attributes & MachO::S_ATTR_DEBUG)
7865 outs() << " DEBUG";
7866 if (section_attributes & MachO::S_ATTR_SOME_INSTRUCTIONS)
7867 outs() << " SOME_INSTRUCTIONS";
7868 if (section_attributes & MachO::S_ATTR_EXT_RELOC)
7869 outs() << " EXT_RELOC";
7870 if (section_attributes & MachO::S_ATTR_LOC_RELOC)
7871 outs() << " LOC_RELOC";
7872 if (section_attributes == 0)
7873 outs() << " (none)";
7874 outs() << "\n";
7875 } else
7876 outs() << " flags " << format("0x%08" PRIx32, flags) << "\n";
7877 outs() << " reserved1 " << reserved1;
7878 if (section_type == MachO::S_SYMBOL_STUBS ||
7879 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
7880 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
7881 section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
7882 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS)
7883 outs() << " (index into indirect symbol table)\n";
7884 else
7885 outs() << "\n";
7886 outs() << " reserved2 " << reserved2;
7887 if (section_type == MachO::S_SYMBOL_STUBS)
7888 outs() << " (size of stubs)\n";
7889 else
7890 outs() << "\n";
7891}
7892
David Majnemer73cc6ff2014-11-13 19:48:56 +00007893static void PrintSymtabLoadCommand(MachO::symtab_command st, bool Is64Bit,
Kevin Enderby956366c2014-08-29 22:30:52 +00007894 uint32_t object_size) {
7895 outs() << " cmd LC_SYMTAB\n";
7896 outs() << " cmdsize " << st.cmdsize;
7897 if (st.cmdsize != sizeof(struct MachO::symtab_command))
7898 outs() << " Incorrect size\n";
7899 else
7900 outs() << "\n";
7901 outs() << " symoff " << st.symoff;
7902 if (st.symoff > object_size)
7903 outs() << " (past end of file)\n";
7904 else
7905 outs() << "\n";
7906 outs() << " nsyms " << st.nsyms;
7907 uint64_t big_size;
David Majnemer73cc6ff2014-11-13 19:48:56 +00007908 if (Is64Bit) {
Kevin Enderby956366c2014-08-29 22:30:52 +00007909 big_size = st.nsyms;
7910 big_size *= sizeof(struct MachO::nlist_64);
7911 big_size += st.symoff;
7912 if (big_size > object_size)
7913 outs() << " (past end of file)\n";
7914 else
7915 outs() << "\n";
7916 } else {
7917 big_size = st.nsyms;
7918 big_size *= sizeof(struct MachO::nlist);
7919 big_size += st.symoff;
7920 if (big_size > object_size)
7921 outs() << " (past end of file)\n";
7922 else
7923 outs() << "\n";
7924 }
7925 outs() << " stroff " << st.stroff;
7926 if (st.stroff > object_size)
7927 outs() << " (past end of file)\n";
7928 else
7929 outs() << "\n";
7930 outs() << " strsize " << st.strsize;
7931 big_size = st.stroff;
7932 big_size += st.strsize;
7933 if (big_size > object_size)
7934 outs() << " (past end of file)\n";
7935 else
7936 outs() << "\n";
7937}
7938
7939static void PrintDysymtabLoadCommand(MachO::dysymtab_command dyst,
7940 uint32_t nsyms, uint32_t object_size,
David Majnemer73cc6ff2014-11-13 19:48:56 +00007941 bool Is64Bit) {
Kevin Enderby956366c2014-08-29 22:30:52 +00007942 outs() << " cmd LC_DYSYMTAB\n";
7943 outs() << " cmdsize " << dyst.cmdsize;
7944 if (dyst.cmdsize != sizeof(struct MachO::dysymtab_command))
7945 outs() << " Incorrect size\n";
7946 else
7947 outs() << "\n";
7948 outs() << " ilocalsym " << dyst.ilocalsym;
7949 if (dyst.ilocalsym > nsyms)
7950 outs() << " (greater than the number of symbols)\n";
7951 else
7952 outs() << "\n";
7953 outs() << " nlocalsym " << dyst.nlocalsym;
7954 uint64_t big_size;
7955 big_size = dyst.ilocalsym;
7956 big_size += dyst.nlocalsym;
7957 if (big_size > nsyms)
7958 outs() << " (past the end of the symbol table)\n";
7959 else
7960 outs() << "\n";
7961 outs() << " iextdefsym " << dyst.iextdefsym;
7962 if (dyst.iextdefsym > nsyms)
7963 outs() << " (greater than the number of symbols)\n";
7964 else
7965 outs() << "\n";
7966 outs() << " nextdefsym " << dyst.nextdefsym;
7967 big_size = dyst.iextdefsym;
7968 big_size += dyst.nextdefsym;
7969 if (big_size > nsyms)
7970 outs() << " (past the end of the symbol table)\n";
7971 else
7972 outs() << "\n";
7973 outs() << " iundefsym " << dyst.iundefsym;
7974 if (dyst.iundefsym > nsyms)
7975 outs() << " (greater than the number of symbols)\n";
7976 else
7977 outs() << "\n";
7978 outs() << " nundefsym " << dyst.nundefsym;
7979 big_size = dyst.iundefsym;
7980 big_size += dyst.nundefsym;
7981 if (big_size > nsyms)
7982 outs() << " (past the end of the symbol table)\n";
7983 else
7984 outs() << "\n";
7985 outs() << " tocoff " << dyst.tocoff;
7986 if (dyst.tocoff > object_size)
7987 outs() << " (past end of file)\n";
7988 else
7989 outs() << "\n";
7990 outs() << " ntoc " << dyst.ntoc;
7991 big_size = dyst.ntoc;
7992 big_size *= sizeof(struct MachO::dylib_table_of_contents);
7993 big_size += dyst.tocoff;
7994 if (big_size > object_size)
7995 outs() << " (past end of file)\n";
7996 else
7997 outs() << "\n";
7998 outs() << " modtaboff " << dyst.modtaboff;
7999 if (dyst.modtaboff > object_size)
8000 outs() << " (past end of file)\n";
8001 else
8002 outs() << "\n";
8003 outs() << " nmodtab " << dyst.nmodtab;
8004 uint64_t modtabend;
David Majnemer73cc6ff2014-11-13 19:48:56 +00008005 if (Is64Bit) {
Kevin Enderby956366c2014-08-29 22:30:52 +00008006 modtabend = dyst.nmodtab;
8007 modtabend *= sizeof(struct MachO::dylib_module_64);
8008 modtabend += dyst.modtaboff;
8009 } else {
8010 modtabend = dyst.nmodtab;
8011 modtabend *= sizeof(struct MachO::dylib_module);
8012 modtabend += dyst.modtaboff;
8013 }
8014 if (modtabend > object_size)
8015 outs() << " (past end of file)\n";
8016 else
8017 outs() << "\n";
8018 outs() << " extrefsymoff " << dyst.extrefsymoff;
8019 if (dyst.extrefsymoff > object_size)
8020 outs() << " (past end of file)\n";
8021 else
8022 outs() << "\n";
8023 outs() << " nextrefsyms " << dyst.nextrefsyms;
8024 big_size = dyst.nextrefsyms;
8025 big_size *= sizeof(struct MachO::dylib_reference);
8026 big_size += dyst.extrefsymoff;
8027 if (big_size > object_size)
8028 outs() << " (past end of file)\n";
8029 else
8030 outs() << "\n";
8031 outs() << " indirectsymoff " << dyst.indirectsymoff;
8032 if (dyst.indirectsymoff > object_size)
8033 outs() << " (past end of file)\n";
8034 else
8035 outs() << "\n";
8036 outs() << " nindirectsyms " << dyst.nindirectsyms;
8037 big_size = dyst.nindirectsyms;
8038 big_size *= sizeof(uint32_t);
8039 big_size += dyst.indirectsymoff;
8040 if (big_size > object_size)
8041 outs() << " (past end of file)\n";
8042 else
8043 outs() << "\n";
8044 outs() << " extreloff " << dyst.extreloff;
8045 if (dyst.extreloff > object_size)
8046 outs() << " (past end of file)\n";
8047 else
8048 outs() << "\n";
8049 outs() << " nextrel " << dyst.nextrel;
8050 big_size = dyst.nextrel;
8051 big_size *= sizeof(struct MachO::relocation_info);
8052 big_size += dyst.extreloff;
8053 if (big_size > object_size)
8054 outs() << " (past end of file)\n";
8055 else
8056 outs() << "\n";
8057 outs() << " locreloff " << dyst.locreloff;
8058 if (dyst.locreloff > object_size)
8059 outs() << " (past end of file)\n";
8060 else
8061 outs() << "\n";
8062 outs() << " nlocrel " << dyst.nlocrel;
8063 big_size = dyst.nlocrel;
8064 big_size *= sizeof(struct MachO::relocation_info);
8065 big_size += dyst.locreloff;
8066 if (big_size > object_size)
8067 outs() << " (past end of file)\n";
8068 else
8069 outs() << "\n";
8070}
8071
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008072static void PrintDyldInfoLoadCommand(MachO::dyld_info_command dc,
8073 uint32_t object_size) {
8074 if (dc.cmd == MachO::LC_DYLD_INFO)
8075 outs() << " cmd LC_DYLD_INFO\n";
8076 else
8077 outs() << " cmd LC_DYLD_INFO_ONLY\n";
8078 outs() << " cmdsize " << dc.cmdsize;
8079 if (dc.cmdsize != sizeof(struct MachO::dyld_info_command))
8080 outs() << " Incorrect size\n";
8081 else
8082 outs() << "\n";
8083 outs() << " rebase_off " << dc.rebase_off;
8084 if (dc.rebase_off > object_size)
8085 outs() << " (past end of file)\n";
8086 else
8087 outs() << "\n";
8088 outs() << " rebase_size " << dc.rebase_size;
8089 uint64_t big_size;
8090 big_size = dc.rebase_off;
8091 big_size += dc.rebase_size;
8092 if (big_size > object_size)
8093 outs() << " (past end of file)\n";
8094 else
8095 outs() << "\n";
8096 outs() << " bind_off " << dc.bind_off;
8097 if (dc.bind_off > object_size)
8098 outs() << " (past end of file)\n";
8099 else
8100 outs() << "\n";
8101 outs() << " bind_size " << dc.bind_size;
8102 big_size = dc.bind_off;
8103 big_size += dc.bind_size;
8104 if (big_size > object_size)
8105 outs() << " (past end of file)\n";
8106 else
8107 outs() << "\n";
8108 outs() << " weak_bind_off " << dc.weak_bind_off;
8109 if (dc.weak_bind_off > object_size)
8110 outs() << " (past end of file)\n";
8111 else
8112 outs() << "\n";
8113 outs() << " weak_bind_size " << dc.weak_bind_size;
8114 big_size = dc.weak_bind_off;
8115 big_size += dc.weak_bind_size;
8116 if (big_size > object_size)
8117 outs() << " (past end of file)\n";
8118 else
8119 outs() << "\n";
8120 outs() << " lazy_bind_off " << dc.lazy_bind_off;
8121 if (dc.lazy_bind_off > object_size)
8122 outs() << " (past end of file)\n";
8123 else
8124 outs() << "\n";
8125 outs() << " lazy_bind_size " << dc.lazy_bind_size;
8126 big_size = dc.lazy_bind_off;
8127 big_size += dc.lazy_bind_size;
8128 if (big_size > object_size)
8129 outs() << " (past end of file)\n";
8130 else
8131 outs() << "\n";
8132 outs() << " export_off " << dc.export_off;
8133 if (dc.export_off > object_size)
8134 outs() << " (past end of file)\n";
8135 else
8136 outs() << "\n";
8137 outs() << " export_size " << dc.export_size;
8138 big_size = dc.export_off;
8139 big_size += dc.export_size;
8140 if (big_size > object_size)
8141 outs() << " (past end of file)\n";
8142 else
8143 outs() << "\n";
8144}
8145
8146static void PrintDyldLoadCommand(MachO::dylinker_command dyld,
8147 const char *Ptr) {
8148 if (dyld.cmd == MachO::LC_ID_DYLINKER)
8149 outs() << " cmd LC_ID_DYLINKER\n";
8150 else if (dyld.cmd == MachO::LC_LOAD_DYLINKER)
8151 outs() << " cmd LC_LOAD_DYLINKER\n";
8152 else if (dyld.cmd == MachO::LC_DYLD_ENVIRONMENT)
8153 outs() << " cmd LC_DYLD_ENVIRONMENT\n";
8154 else
8155 outs() << " cmd ?(" << dyld.cmd << ")\n";
8156 outs() << " cmdsize " << dyld.cmdsize;
8157 if (dyld.cmdsize < sizeof(struct MachO::dylinker_command))
8158 outs() << " Incorrect size\n";
8159 else
8160 outs() << "\n";
8161 if (dyld.name >= dyld.cmdsize)
8162 outs() << " name ?(bad offset " << dyld.name << ")\n";
8163 else {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00008164 const char *P = (const char *)(Ptr) + dyld.name;
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008165 outs() << " name " << P << " (offset " << dyld.name << ")\n";
8166 }
8167}
8168
8169static void PrintUuidLoadCommand(MachO::uuid_command uuid) {
8170 outs() << " cmd LC_UUID\n";
8171 outs() << " cmdsize " << uuid.cmdsize;
8172 if (uuid.cmdsize != sizeof(struct MachO::uuid_command))
8173 outs() << " Incorrect size\n";
8174 else
8175 outs() << "\n";
8176 outs() << " uuid ";
Davide Italianoc74277a2015-12-07 00:03:28 +00008177 for (int i = 0; i < 16; ++i) {
8178 outs() << format("%02" PRIX32, uuid.uuid[i]);
8179 if (i == 3 || i == 5 || i == 7 || i == 9)
8180 outs() << "-";
8181 }
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008182 outs() << "\n";
8183}
8184
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008185static void PrintRpathLoadCommand(MachO::rpath_command rpath, const char *Ptr) {
Jean-Daniel Dupas00cc1f52014-12-04 07:37:02 +00008186 outs() << " cmd LC_RPATH\n";
8187 outs() << " cmdsize " << rpath.cmdsize;
8188 if (rpath.cmdsize < sizeof(struct MachO::rpath_command))
8189 outs() << " Incorrect size\n";
8190 else
8191 outs() << "\n";
8192 if (rpath.path >= rpath.cmdsize)
8193 outs() << " path ?(bad offset " << rpath.path << ")\n";
8194 else {
8195 const char *P = (const char *)(Ptr) + rpath.path;
8196 outs() << " path " << P << " (offset " << rpath.path << ")\n";
8197 }
8198}
8199
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008200static void PrintVersionMinLoadCommand(MachO::version_min_command vd) {
Tim Northoverbfbfb122015-11-02 21:26:58 +00008201 StringRef LoadCmdName;
8202 switch (vd.cmd) {
8203 case MachO::LC_VERSION_MIN_MACOSX:
8204 LoadCmdName = "LC_VERSION_MIN_MACOSX";
8205 break;
8206 case MachO::LC_VERSION_MIN_IPHONEOS:
8207 LoadCmdName = "LC_VERSION_MIN_IPHONEOS";
8208 break;
8209 case MachO::LC_VERSION_MIN_TVOS:
8210 LoadCmdName = "LC_VERSION_MIN_TVOS";
8211 break;
8212 case MachO::LC_VERSION_MIN_WATCHOS:
8213 LoadCmdName = "LC_VERSION_MIN_WATCHOS";
8214 break;
8215 default:
8216 llvm_unreachable("Unknown version min load command");
8217 }
8218
8219 outs() << " cmd " << LoadCmdName << '\n';
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008220 outs() << " cmdsize " << vd.cmdsize;
8221 if (vd.cmdsize != sizeof(struct MachO::version_min_command))
8222 outs() << " Incorrect size\n";
8223 else
8224 outs() << "\n";
Davide Italiano56baef32015-08-26 12:26:11 +00008225 outs() << " version "
8226 << MachOObjectFile::getVersionMinMajor(vd, false) << "."
8227 << MachOObjectFile::getVersionMinMinor(vd, false);
8228 uint32_t Update = MachOObjectFile::getVersionMinUpdate(vd, false);
8229 if (Update != 0)
8230 outs() << "." << Update;
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008231 outs() << "\n";
8232 if (vd.sdk == 0)
Kevin Enderby57538292014-12-17 01:01:30 +00008233 outs() << " sdk n/a";
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008234 else {
Davide Italiano56baef32015-08-26 12:26:11 +00008235 outs() << " sdk "
8236 << MachOObjectFile::getVersionMinMajor(vd, true) << "."
8237 << MachOObjectFile::getVersionMinMinor(vd, true);
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008238 }
Davide Italiano56baef32015-08-26 12:26:11 +00008239 Update = MachOObjectFile::getVersionMinUpdate(vd, true);
8240 if (Update != 0)
8241 outs() << "." << Update;
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008242 outs() << "\n";
8243}
8244
8245static void PrintSourceVersionCommand(MachO::source_version_command sd) {
8246 outs() << " cmd LC_SOURCE_VERSION\n";
8247 outs() << " cmdsize " << sd.cmdsize;
8248 if (sd.cmdsize != sizeof(struct MachO::source_version_command))
8249 outs() << " Incorrect size\n";
8250 else
8251 outs() << "\n";
8252 uint64_t a = (sd.version >> 40) & 0xffffff;
8253 uint64_t b = (sd.version >> 30) & 0x3ff;
8254 uint64_t c = (sd.version >> 20) & 0x3ff;
8255 uint64_t d = (sd.version >> 10) & 0x3ff;
8256 uint64_t e = sd.version & 0x3ff;
8257 outs() << " version " << a << "." << b;
8258 if (e != 0)
8259 outs() << "." << c << "." << d << "." << e;
8260 else if (d != 0)
8261 outs() << "." << c << "." << d;
8262 else if (c != 0)
8263 outs() << "." << c;
8264 outs() << "\n";
8265}
8266
8267static void PrintEntryPointCommand(MachO::entry_point_command ep) {
8268 outs() << " cmd LC_MAIN\n";
8269 outs() << " cmdsize " << ep.cmdsize;
8270 if (ep.cmdsize != sizeof(struct MachO::entry_point_command))
8271 outs() << " Incorrect size\n";
8272 else
8273 outs() << "\n";
8274 outs() << " entryoff " << ep.entryoff << "\n";
8275 outs() << " stacksize " << ep.stacksize << "\n";
8276}
8277
Kevin Enderby0804f4672014-12-16 23:25:52 +00008278static void PrintEncryptionInfoCommand(MachO::encryption_info_command ec,
8279 uint32_t object_size) {
8280 outs() << " cmd LC_ENCRYPTION_INFO\n";
8281 outs() << " cmdsize " << ec.cmdsize;
8282 if (ec.cmdsize != sizeof(struct MachO::encryption_info_command))
8283 outs() << " Incorrect size\n";
8284 else
8285 outs() << "\n";
8286 outs() << " cryptoff " << ec.cryptoff;
8287 if (ec.cryptoff > object_size)
8288 outs() << " (past end of file)\n";
8289 else
8290 outs() << "\n";
8291 outs() << " cryptsize " << ec.cryptsize;
8292 if (ec.cryptsize > object_size)
8293 outs() << " (past end of file)\n";
8294 else
8295 outs() << "\n";
8296 outs() << " cryptid " << ec.cryptid << "\n";
8297}
8298
Kevin Enderby57538292014-12-17 01:01:30 +00008299static void PrintEncryptionInfoCommand64(MachO::encryption_info_command_64 ec,
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008300 uint32_t object_size) {
Kevin Enderby57538292014-12-17 01:01:30 +00008301 outs() << " cmd LC_ENCRYPTION_INFO_64\n";
8302 outs() << " cmdsize " << ec.cmdsize;
8303 if (ec.cmdsize != sizeof(struct MachO::encryption_info_command_64))
8304 outs() << " Incorrect size\n";
8305 else
8306 outs() << "\n";
8307 outs() << " cryptoff " << ec.cryptoff;
8308 if (ec.cryptoff > object_size)
8309 outs() << " (past end of file)\n";
8310 else
8311 outs() << "\n";
8312 outs() << " cryptsize " << ec.cryptsize;
8313 if (ec.cryptsize > object_size)
8314 outs() << " (past end of file)\n";
8315 else
8316 outs() << "\n";
8317 outs() << " cryptid " << ec.cryptid << "\n";
8318 outs() << " pad " << ec.pad << "\n";
8319}
8320
Kevin Enderbyd0b6b7f2014-12-18 00:53:40 +00008321static void PrintLinkerOptionCommand(MachO::linker_option_command lo,
8322 const char *Ptr) {
8323 outs() << " cmd LC_LINKER_OPTION\n";
8324 outs() << " cmdsize " << lo.cmdsize;
8325 if (lo.cmdsize < sizeof(struct MachO::linker_option_command))
8326 outs() << " Incorrect size\n";
8327 else
8328 outs() << "\n";
8329 outs() << " count " << lo.count << "\n";
8330 const char *string = Ptr + sizeof(struct MachO::linker_option_command);
8331 uint32_t left = lo.cmdsize - sizeof(struct MachO::linker_option_command);
8332 uint32_t i = 0;
8333 while (left > 0) {
8334 while (*string == '\0' && left > 0) {
8335 string++;
8336 left--;
8337 }
8338 if (left > 0) {
8339 i++;
8340 outs() << " string #" << i << " " << format("%.*s\n", left, string);
David Majnemerd4449ed2014-12-20 08:24:43 +00008341 uint32_t NullPos = StringRef(string, left).find('\0');
8342 uint32_t len = std::min(NullPos, left) + 1;
Kevin Enderbyd0b6b7f2014-12-18 00:53:40 +00008343 string += len;
8344 left -= len;
8345 }
8346 }
8347 if (lo.count != i)
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008348 outs() << " count " << lo.count << " does not match number of strings "
8349 << i << "\n";
Kevin Enderbyd0b6b7f2014-12-18 00:53:40 +00008350}
8351
Kevin Enderbyb4b79312014-12-18 19:24:35 +00008352static void PrintSubFrameworkCommand(MachO::sub_framework_command sub,
8353 const char *Ptr) {
8354 outs() << " cmd LC_SUB_FRAMEWORK\n";
8355 outs() << " cmdsize " << sub.cmdsize;
8356 if (sub.cmdsize < sizeof(struct MachO::sub_framework_command))
8357 outs() << " Incorrect size\n";
8358 else
8359 outs() << "\n";
8360 if (sub.umbrella < sub.cmdsize) {
8361 const char *P = Ptr + sub.umbrella;
8362 outs() << " umbrella " << P << " (offset " << sub.umbrella << ")\n";
8363 } else {
8364 outs() << " umbrella ?(bad offset " << sub.umbrella << ")\n";
8365 }
8366}
8367
Kevin Enderbya2bd8d92014-12-18 23:13:26 +00008368static void PrintSubUmbrellaCommand(MachO::sub_umbrella_command sub,
8369 const char *Ptr) {
8370 outs() << " cmd LC_SUB_UMBRELLA\n";
8371 outs() << " cmdsize " << sub.cmdsize;
8372 if (sub.cmdsize < sizeof(struct MachO::sub_umbrella_command))
8373 outs() << " Incorrect size\n";
8374 else
8375 outs() << "\n";
8376 if (sub.sub_umbrella < sub.cmdsize) {
8377 const char *P = Ptr + sub.sub_umbrella;
8378 outs() << " sub_umbrella " << P << " (offset " << sub.sub_umbrella << ")\n";
8379 } else {
8380 outs() << " sub_umbrella ?(bad offset " << sub.sub_umbrella << ")\n";
8381 }
8382}
8383
Kevin Enderby36c8d3a2014-12-19 19:48:16 +00008384static void PrintSubLibraryCommand(MachO::sub_library_command sub,
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008385 const char *Ptr) {
Kevin Enderby36c8d3a2014-12-19 19:48:16 +00008386 outs() << " cmd LC_SUB_LIBRARY\n";
8387 outs() << " cmdsize " << sub.cmdsize;
8388 if (sub.cmdsize < sizeof(struct MachO::sub_library_command))
8389 outs() << " Incorrect size\n";
8390 else
8391 outs() << "\n";
8392 if (sub.sub_library < sub.cmdsize) {
8393 const char *P = Ptr + sub.sub_library;
8394 outs() << " sub_library " << P << " (offset " << sub.sub_library << ")\n";
8395 } else {
8396 outs() << " sub_library ?(bad offset " << sub.sub_library << ")\n";
8397 }
8398}
8399
Kevin Enderby186eac32014-12-19 21:06:24 +00008400static void PrintSubClientCommand(MachO::sub_client_command sub,
8401 const char *Ptr) {
8402 outs() << " cmd LC_SUB_CLIENT\n";
8403 outs() << " cmdsize " << sub.cmdsize;
8404 if (sub.cmdsize < sizeof(struct MachO::sub_client_command))
8405 outs() << " Incorrect size\n";
8406 else
8407 outs() << "\n";
8408 if (sub.client < sub.cmdsize) {
8409 const char *P = Ptr + sub.client;
8410 outs() << " client " << P << " (offset " << sub.client << ")\n";
8411 } else {
8412 outs() << " client ?(bad offset " << sub.client << ")\n";
8413 }
8414}
Kevin Enderby36c8d3a2014-12-19 19:48:16 +00008415
Kevin Enderby52e4ce42014-12-19 22:25:22 +00008416static void PrintRoutinesCommand(MachO::routines_command r) {
8417 outs() << " cmd LC_ROUTINES\n";
8418 outs() << " cmdsize " << r.cmdsize;
8419 if (r.cmdsize != sizeof(struct MachO::routines_command))
8420 outs() << " Incorrect size\n";
8421 else
8422 outs() << "\n";
8423 outs() << " init_address " << format("0x%08" PRIx32, r.init_address) << "\n";
8424 outs() << " init_module " << r.init_module << "\n";
8425 outs() << " reserved1 " << r.reserved1 << "\n";
8426 outs() << " reserved2 " << r.reserved2 << "\n";
8427 outs() << " reserved3 " << r.reserved3 << "\n";
8428 outs() << " reserved4 " << r.reserved4 << "\n";
8429 outs() << " reserved5 " << r.reserved5 << "\n";
8430 outs() << " reserved6 " << r.reserved6 << "\n";
8431}
8432
8433static void PrintRoutinesCommand64(MachO::routines_command_64 r) {
8434 outs() << " cmd LC_ROUTINES_64\n";
8435 outs() << " cmdsize " << r.cmdsize;
8436 if (r.cmdsize != sizeof(struct MachO::routines_command_64))
8437 outs() << " Incorrect size\n";
8438 else
8439 outs() << "\n";
8440 outs() << " init_address " << format("0x%016" PRIx64, r.init_address) << "\n";
8441 outs() << " init_module " << r.init_module << "\n";
8442 outs() << " reserved1 " << r.reserved1 << "\n";
8443 outs() << " reserved2 " << r.reserved2 << "\n";
8444 outs() << " reserved3 " << r.reserved3 << "\n";
8445 outs() << " reserved4 " << r.reserved4 << "\n";
8446 outs() << " reserved5 " << r.reserved5 << "\n";
8447 outs() << " reserved6 " << r.reserved6 << "\n";
8448}
8449
Kevin Enderby48ef5342014-12-23 22:56:39 +00008450static void Print_x86_thread_state64_t(MachO::x86_thread_state64_t &cpu64) {
8451 outs() << " rax " << format("0x%016" PRIx64, cpu64.rax);
8452 outs() << " rbx " << format("0x%016" PRIx64, cpu64.rbx);
8453 outs() << " rcx " << format("0x%016" PRIx64, cpu64.rcx) << "\n";
8454 outs() << " rdx " << format("0x%016" PRIx64, cpu64.rdx);
8455 outs() << " rdi " << format("0x%016" PRIx64, cpu64.rdi);
8456 outs() << " rsi " << format("0x%016" PRIx64, cpu64.rsi) << "\n";
8457 outs() << " rbp " << format("0x%016" PRIx64, cpu64.rbp);
8458 outs() << " rsp " << format("0x%016" PRIx64, cpu64.rsp);
8459 outs() << " r8 " << format("0x%016" PRIx64, cpu64.r8) << "\n";
8460 outs() << " r9 " << format("0x%016" PRIx64, cpu64.r9);
8461 outs() << " r10 " << format("0x%016" PRIx64, cpu64.r10);
8462 outs() << " r11 " << format("0x%016" PRIx64, cpu64.r11) << "\n";
8463 outs() << " r12 " << format("0x%016" PRIx64, cpu64.r12);
8464 outs() << " r13 " << format("0x%016" PRIx64, cpu64.r13);
8465 outs() << " r14 " << format("0x%016" PRIx64, cpu64.r14) << "\n";
8466 outs() << " r15 " << format("0x%016" PRIx64, cpu64.r15);
8467 outs() << " rip " << format("0x%016" PRIx64, cpu64.rip) << "\n";
8468 outs() << "rflags " << format("0x%016" PRIx64, cpu64.rflags);
8469 outs() << " cs " << format("0x%016" PRIx64, cpu64.cs);
8470 outs() << " fs " << format("0x%016" PRIx64, cpu64.fs) << "\n";
8471 outs() << " gs " << format("0x%016" PRIx64, cpu64.gs) << "\n";
8472}
8473
Kevin Enderby227df342014-12-23 23:43:59 +00008474static void Print_mmst_reg(MachO::mmst_reg_t &r) {
Kevin Enderby48ef5342014-12-23 22:56:39 +00008475 uint32_t f;
8476 outs() << "\t mmst_reg ";
8477 for (f = 0; f < 10; f++)
8478 outs() << format("%02" PRIx32, (r.mmst_reg[f] & 0xff)) << " ";
8479 outs() << "\n";
8480 outs() << "\t mmst_rsrv ";
8481 for (f = 0; f < 6; f++)
8482 outs() << format("%02" PRIx32, (r.mmst_rsrv[f] & 0xff)) << " ";
8483 outs() << "\n";
8484}
8485
Kevin Enderbyaefb0032014-12-24 00:16:51 +00008486static void Print_xmm_reg(MachO::xmm_reg_t &r) {
Kevin Enderby48ef5342014-12-23 22:56:39 +00008487 uint32_t f;
8488 outs() << "\t xmm_reg ";
8489 for (f = 0; f < 16; f++)
8490 outs() << format("%02" PRIx32, (r.xmm_reg[f] & 0xff)) << " ";
8491 outs() << "\n";
8492}
8493
8494static void Print_x86_float_state_t(MachO::x86_float_state64_t &fpu) {
8495 outs() << "\t fpu_reserved[0] " << fpu.fpu_reserved[0];
8496 outs() << " fpu_reserved[1] " << fpu.fpu_reserved[1] << "\n";
8497 outs() << "\t control: invalid " << fpu.fpu_fcw.invalid;
8498 outs() << " denorm " << fpu.fpu_fcw.denorm;
8499 outs() << " zdiv " << fpu.fpu_fcw.zdiv;
8500 outs() << " ovrfl " << fpu.fpu_fcw.ovrfl;
8501 outs() << " undfl " << fpu.fpu_fcw.undfl;
8502 outs() << " precis " << fpu.fpu_fcw.precis << "\n";
8503 outs() << "\t\t pc ";
8504 if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_24B)
8505 outs() << "FP_PREC_24B ";
8506 else if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_53B)
8507 outs() << "FP_PREC_53B ";
8508 else if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_64B)
8509 outs() << "FP_PREC_64B ";
8510 else
8511 outs() << fpu.fpu_fcw.pc << " ";
8512 outs() << "rc ";
8513 if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_NEAR)
8514 outs() << "FP_RND_NEAR ";
8515 else if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_DOWN)
8516 outs() << "FP_RND_DOWN ";
8517 else if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_UP)
8518 outs() << "FP_RND_UP ";
8519 else if (fpu.fpu_fcw.rc == MachO::x86_FP_CHOP)
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008520 outs() << "FP_CHOP ";
Kevin Enderby48ef5342014-12-23 22:56:39 +00008521 outs() << "\n";
8522 outs() << "\t status: invalid " << fpu.fpu_fsw.invalid;
8523 outs() << " denorm " << fpu.fpu_fsw.denorm;
8524 outs() << " zdiv " << fpu.fpu_fsw.zdiv;
8525 outs() << " ovrfl " << fpu.fpu_fsw.ovrfl;
8526 outs() << " undfl " << fpu.fpu_fsw.undfl;
8527 outs() << " precis " << fpu.fpu_fsw.precis;
8528 outs() << " stkflt " << fpu.fpu_fsw.stkflt << "\n";
8529 outs() << "\t errsumm " << fpu.fpu_fsw.errsumm;
8530 outs() << " c0 " << fpu.fpu_fsw.c0;
8531 outs() << " c1 " << fpu.fpu_fsw.c1;
8532 outs() << " c2 " << fpu.fpu_fsw.c2;
8533 outs() << " tos " << fpu.fpu_fsw.tos;
8534 outs() << " c3 " << fpu.fpu_fsw.c3;
8535 outs() << " busy " << fpu.fpu_fsw.busy << "\n";
8536 outs() << "\t fpu_ftw " << format("0x%02" PRIx32, fpu.fpu_ftw);
8537 outs() << " fpu_rsrv1 " << format("0x%02" PRIx32, fpu.fpu_rsrv1);
8538 outs() << " fpu_fop " << format("0x%04" PRIx32, fpu.fpu_fop);
8539 outs() << " fpu_ip " << format("0x%08" PRIx32, fpu.fpu_ip) << "\n";
8540 outs() << "\t fpu_cs " << format("0x%04" PRIx32, fpu.fpu_cs);
8541 outs() << " fpu_rsrv2 " << format("0x%04" PRIx32, fpu.fpu_rsrv2);
8542 outs() << " fpu_dp " << format("0x%08" PRIx32, fpu.fpu_dp);
8543 outs() << " fpu_ds " << format("0x%04" PRIx32, fpu.fpu_ds) << "\n";
8544 outs() << "\t fpu_rsrv3 " << format("0x%04" PRIx32, fpu.fpu_rsrv3);
8545 outs() << " fpu_mxcsr " << format("0x%08" PRIx32, fpu.fpu_mxcsr);
8546 outs() << " fpu_mxcsrmask " << format("0x%08" PRIx32, fpu.fpu_mxcsrmask);
8547 outs() << "\n";
8548 outs() << "\t fpu_stmm0:\n";
8549 Print_mmst_reg(fpu.fpu_stmm0);
8550 outs() << "\t fpu_stmm1:\n";
8551 Print_mmst_reg(fpu.fpu_stmm1);
8552 outs() << "\t fpu_stmm2:\n";
8553 Print_mmst_reg(fpu.fpu_stmm2);
8554 outs() << "\t fpu_stmm3:\n";
8555 Print_mmst_reg(fpu.fpu_stmm3);
8556 outs() << "\t fpu_stmm4:\n";
8557 Print_mmst_reg(fpu.fpu_stmm4);
8558 outs() << "\t fpu_stmm5:\n";
8559 Print_mmst_reg(fpu.fpu_stmm5);
8560 outs() << "\t fpu_stmm6:\n";
8561 Print_mmst_reg(fpu.fpu_stmm6);
8562 outs() << "\t fpu_stmm7:\n";
8563 Print_mmst_reg(fpu.fpu_stmm7);
8564 outs() << "\t fpu_xmm0:\n";
8565 Print_xmm_reg(fpu.fpu_xmm0);
8566 outs() << "\t fpu_xmm1:\n";
8567 Print_xmm_reg(fpu.fpu_xmm1);
8568 outs() << "\t fpu_xmm2:\n";
8569 Print_xmm_reg(fpu.fpu_xmm2);
8570 outs() << "\t fpu_xmm3:\n";
8571 Print_xmm_reg(fpu.fpu_xmm3);
8572 outs() << "\t fpu_xmm4:\n";
8573 Print_xmm_reg(fpu.fpu_xmm4);
8574 outs() << "\t fpu_xmm5:\n";
8575 Print_xmm_reg(fpu.fpu_xmm5);
8576 outs() << "\t fpu_xmm6:\n";
8577 Print_xmm_reg(fpu.fpu_xmm6);
8578 outs() << "\t fpu_xmm7:\n";
8579 Print_xmm_reg(fpu.fpu_xmm7);
8580 outs() << "\t fpu_xmm8:\n";
8581 Print_xmm_reg(fpu.fpu_xmm8);
8582 outs() << "\t fpu_xmm9:\n";
8583 Print_xmm_reg(fpu.fpu_xmm9);
8584 outs() << "\t fpu_xmm10:\n";
8585 Print_xmm_reg(fpu.fpu_xmm10);
8586 outs() << "\t fpu_xmm11:\n";
8587 Print_xmm_reg(fpu.fpu_xmm11);
8588 outs() << "\t fpu_xmm12:\n";
8589 Print_xmm_reg(fpu.fpu_xmm12);
8590 outs() << "\t fpu_xmm13:\n";
8591 Print_xmm_reg(fpu.fpu_xmm13);
8592 outs() << "\t fpu_xmm14:\n";
8593 Print_xmm_reg(fpu.fpu_xmm14);
8594 outs() << "\t fpu_xmm15:\n";
8595 Print_xmm_reg(fpu.fpu_xmm15);
8596 outs() << "\t fpu_rsrv4:\n";
8597 for (uint32_t f = 0; f < 6; f++) {
8598 outs() << "\t ";
8599 for (uint32_t g = 0; g < 16; g++)
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008600 outs() << format("%02" PRIx32, fpu.fpu_rsrv4[f * g]) << " ";
Kevin Enderby48ef5342014-12-23 22:56:39 +00008601 outs() << "\n";
8602 }
8603 outs() << "\t fpu_reserved1 " << format("0x%08" PRIx32, fpu.fpu_reserved1);
8604 outs() << "\n";
8605}
8606
8607static void Print_x86_exception_state_t(MachO::x86_exception_state64_t &exc64) {
8608 outs() << "\t trapno " << format("0x%08" PRIx32, exc64.trapno);
8609 outs() << " err " << format("0x%08" PRIx32, exc64.err);
8610 outs() << " faultvaddr " << format("0x%016" PRIx64, exc64.faultvaddr) << "\n";
8611}
8612
8613static void PrintThreadCommand(MachO::thread_command t, const char *Ptr,
8614 bool isLittleEndian, uint32_t cputype) {
8615 if (t.cmd == MachO::LC_THREAD)
8616 outs() << " cmd LC_THREAD\n";
8617 else if (t.cmd == MachO::LC_UNIXTHREAD)
8618 outs() << " cmd LC_UNIXTHREAD\n";
8619 else
8620 outs() << " cmd " << t.cmd << " (unknown)\n";
8621 outs() << " cmdsize " << t.cmdsize;
8622 if (t.cmdsize < sizeof(struct MachO::thread_command) + 2 * sizeof(uint32_t))
8623 outs() << " Incorrect size\n";
8624 else
8625 outs() << "\n";
8626
8627 const char *begin = Ptr + sizeof(struct MachO::thread_command);
8628 const char *end = Ptr + t.cmdsize;
8629 uint32_t flavor, count, left;
8630 if (cputype == MachO::CPU_TYPE_X86_64) {
8631 while (begin < end) {
8632 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
8633 memcpy((char *)&flavor, begin, sizeof(uint32_t));
8634 begin += sizeof(uint32_t);
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008635 } else {
Kevin Enderby48ef5342014-12-23 22:56:39 +00008636 flavor = 0;
8637 begin = end;
8638 }
8639 if (isLittleEndian != sys::IsLittleEndianHost)
8640 sys::swapByteOrder(flavor);
8641 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
8642 memcpy((char *)&count, begin, sizeof(uint32_t));
8643 begin += sizeof(uint32_t);
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008644 } else {
Kevin Enderby48ef5342014-12-23 22:56:39 +00008645 count = 0;
8646 begin = end;
8647 }
8648 if (isLittleEndian != sys::IsLittleEndianHost)
8649 sys::swapByteOrder(count);
8650 if (flavor == MachO::x86_THREAD_STATE64) {
8651 outs() << " flavor x86_THREAD_STATE64\n";
8652 if (count == MachO::x86_THREAD_STATE64_COUNT)
8653 outs() << " count x86_THREAD_STATE64_COUNT\n";
8654 else
8655 outs() << " count " << count
8656 << " (not x86_THREAD_STATE64_COUNT)\n";
8657 MachO::x86_thread_state64_t cpu64;
8658 left = end - begin;
8659 if (left >= sizeof(MachO::x86_thread_state64_t)) {
8660 memcpy(&cpu64, begin, sizeof(MachO::x86_thread_state64_t));
8661 begin += sizeof(MachO::x86_thread_state64_t);
8662 } else {
8663 memset(&cpu64, '\0', sizeof(MachO::x86_thread_state64_t));
8664 memcpy(&cpu64, begin, left);
8665 begin += left;
8666 }
8667 if (isLittleEndian != sys::IsLittleEndianHost)
8668 swapStruct(cpu64);
8669 Print_x86_thread_state64_t(cpu64);
8670 } else if (flavor == MachO::x86_THREAD_STATE) {
8671 outs() << " flavor x86_THREAD_STATE\n";
8672 if (count == MachO::x86_THREAD_STATE_COUNT)
8673 outs() << " count x86_THREAD_STATE_COUNT\n";
8674 else
8675 outs() << " count " << count
8676 << " (not x86_THREAD_STATE_COUNT)\n";
8677 struct MachO::x86_thread_state_t ts;
8678 left = end - begin;
8679 if (left >= sizeof(MachO::x86_thread_state_t)) {
8680 memcpy(&ts, begin, sizeof(MachO::x86_thread_state_t));
8681 begin += sizeof(MachO::x86_thread_state_t);
8682 } else {
8683 memset(&ts, '\0', sizeof(MachO::x86_thread_state_t));
8684 memcpy(&ts, begin, left);
8685 begin += left;
8686 }
8687 if (isLittleEndian != sys::IsLittleEndianHost)
8688 swapStruct(ts);
8689 if (ts.tsh.flavor == MachO::x86_THREAD_STATE64) {
8690 outs() << "\t tsh.flavor x86_THREAD_STATE64 ";
8691 if (ts.tsh.count == MachO::x86_THREAD_STATE64_COUNT)
8692 outs() << "tsh.count x86_THREAD_STATE64_COUNT\n";
8693 else
8694 outs() << "tsh.count " << ts.tsh.count
8695 << " (not x86_THREAD_STATE64_COUNT\n";
8696 Print_x86_thread_state64_t(ts.uts.ts64);
8697 } else {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008698 outs() << "\t tsh.flavor " << ts.tsh.flavor << " tsh.count "
8699 << ts.tsh.count << "\n";
Kevin Enderby48ef5342014-12-23 22:56:39 +00008700 }
8701 } else if (flavor == MachO::x86_FLOAT_STATE) {
8702 outs() << " flavor x86_FLOAT_STATE\n";
8703 if (count == MachO::x86_FLOAT_STATE_COUNT)
8704 outs() << " count x86_FLOAT_STATE_COUNT\n";
8705 else
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008706 outs() << " count " << count << " (not x86_FLOAT_STATE_COUNT)\n";
Kevin Enderby48ef5342014-12-23 22:56:39 +00008707 struct MachO::x86_float_state_t fs;
8708 left = end - begin;
8709 if (left >= sizeof(MachO::x86_float_state_t)) {
8710 memcpy(&fs, begin, sizeof(MachO::x86_float_state_t));
8711 begin += sizeof(MachO::x86_float_state_t);
8712 } else {
8713 memset(&fs, '\0', sizeof(MachO::x86_float_state_t));
8714 memcpy(&fs, begin, left);
8715 begin += left;
8716 }
8717 if (isLittleEndian != sys::IsLittleEndianHost)
8718 swapStruct(fs);
8719 if (fs.fsh.flavor == MachO::x86_FLOAT_STATE64) {
8720 outs() << "\t fsh.flavor x86_FLOAT_STATE64 ";
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008721 if (fs.fsh.count == MachO::x86_FLOAT_STATE64_COUNT)
Kevin Enderby48ef5342014-12-23 22:56:39 +00008722 outs() << "fsh.count x86_FLOAT_STATE64_COUNT\n";
8723 else
8724 outs() << "fsh.count " << fs.fsh.count
8725 << " (not x86_FLOAT_STATE64_COUNT\n";
8726 Print_x86_float_state_t(fs.ufs.fs64);
8727 } else {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008728 outs() << "\t fsh.flavor " << fs.fsh.flavor << " fsh.count "
8729 << fs.fsh.count << "\n";
Kevin Enderby48ef5342014-12-23 22:56:39 +00008730 }
8731 } else if (flavor == MachO::x86_EXCEPTION_STATE) {
8732 outs() << " flavor x86_EXCEPTION_STATE\n";
8733 if (count == MachO::x86_EXCEPTION_STATE_COUNT)
8734 outs() << " count x86_EXCEPTION_STATE_COUNT\n";
8735 else
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008736 outs() << " count " << count
Kevin Enderby48ef5342014-12-23 22:56:39 +00008737 << " (not x86_EXCEPTION_STATE_COUNT)\n";
8738 struct MachO::x86_exception_state_t es;
8739 left = end - begin;
8740 if (left >= sizeof(MachO::x86_exception_state_t)) {
8741 memcpy(&es, begin, sizeof(MachO::x86_exception_state_t));
8742 begin += sizeof(MachO::x86_exception_state_t);
8743 } else {
8744 memset(&es, '\0', sizeof(MachO::x86_exception_state_t));
8745 memcpy(&es, begin, left);
8746 begin += left;
8747 }
8748 if (isLittleEndian != sys::IsLittleEndianHost)
8749 swapStruct(es);
8750 if (es.esh.flavor == MachO::x86_EXCEPTION_STATE64) {
8751 outs() << "\t esh.flavor x86_EXCEPTION_STATE64\n";
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008752 if (es.esh.count == MachO::x86_EXCEPTION_STATE64_COUNT)
Kevin Enderby48ef5342014-12-23 22:56:39 +00008753 outs() << "\t esh.count x86_EXCEPTION_STATE64_COUNT\n";
8754 else
8755 outs() << "\t esh.count " << es.esh.count
8756 << " (not x86_EXCEPTION_STATE64_COUNT\n";
8757 Print_x86_exception_state_t(es.ues.es64);
8758 } else {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008759 outs() << "\t esh.flavor " << es.esh.flavor << " esh.count "
8760 << es.esh.count << "\n";
Kevin Enderby48ef5342014-12-23 22:56:39 +00008761 }
8762 } else {
8763 outs() << " flavor " << flavor << " (unknown)\n";
8764 outs() << " count " << count << "\n";
8765 outs() << " state (unknown)\n";
8766 begin += count * sizeof(uint32_t);
8767 }
8768 }
8769 } else {
8770 while (begin < end) {
8771 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
8772 memcpy((char *)&flavor, begin, sizeof(uint32_t));
8773 begin += sizeof(uint32_t);
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008774 } else {
Kevin Enderby48ef5342014-12-23 22:56:39 +00008775 flavor = 0;
8776 begin = end;
8777 }
8778 if (isLittleEndian != sys::IsLittleEndianHost)
8779 sys::swapByteOrder(flavor);
8780 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
8781 memcpy((char *)&count, begin, sizeof(uint32_t));
8782 begin += sizeof(uint32_t);
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008783 } else {
Kevin Enderby48ef5342014-12-23 22:56:39 +00008784 count = 0;
8785 begin = end;
8786 }
8787 if (isLittleEndian != sys::IsLittleEndianHost)
8788 sys::swapByteOrder(count);
8789 outs() << " flavor " << flavor << "\n";
8790 outs() << " count " << count << "\n";
8791 outs() << " state (Unknown cputype/cpusubtype)\n";
8792 begin += count * sizeof(uint32_t);
8793 }
8794 }
8795}
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008796
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008797static void PrintDylibCommand(MachO::dylib_command dl, const char *Ptr) {
8798 if (dl.cmd == MachO::LC_ID_DYLIB)
8799 outs() << " cmd LC_ID_DYLIB\n";
8800 else if (dl.cmd == MachO::LC_LOAD_DYLIB)
8801 outs() << " cmd LC_LOAD_DYLIB\n";
8802 else if (dl.cmd == MachO::LC_LOAD_WEAK_DYLIB)
8803 outs() << " cmd LC_LOAD_WEAK_DYLIB\n";
8804 else if (dl.cmd == MachO::LC_REEXPORT_DYLIB)
8805 outs() << " cmd LC_REEXPORT_DYLIB\n";
8806 else if (dl.cmd == MachO::LC_LAZY_LOAD_DYLIB)
8807 outs() << " cmd LC_LAZY_LOAD_DYLIB\n";
8808 else if (dl.cmd == MachO::LC_LOAD_UPWARD_DYLIB)
8809 outs() << " cmd LC_LOAD_UPWARD_DYLIB\n";
8810 else
8811 outs() << " cmd " << dl.cmd << " (unknown)\n";
8812 outs() << " cmdsize " << dl.cmdsize;
8813 if (dl.cmdsize < sizeof(struct MachO::dylib_command))
8814 outs() << " Incorrect size\n";
8815 else
8816 outs() << "\n";
8817 if (dl.dylib.name < dl.cmdsize) {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00008818 const char *P = (const char *)(Ptr) + dl.dylib.name;
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008819 outs() << " name " << P << " (offset " << dl.dylib.name << ")\n";
8820 } else {
8821 outs() << " name ?(bad offset " << dl.dylib.name << ")\n";
8822 }
8823 outs() << " time stamp " << dl.dylib.timestamp << " ";
8824 time_t t = dl.dylib.timestamp;
8825 outs() << ctime(&t);
8826 outs() << " current version ";
8827 if (dl.dylib.current_version == 0xffffffff)
8828 outs() << "n/a\n";
8829 else
8830 outs() << ((dl.dylib.current_version >> 16) & 0xffff) << "."
8831 << ((dl.dylib.current_version >> 8) & 0xff) << "."
8832 << (dl.dylib.current_version & 0xff) << "\n";
8833 outs() << "compatibility version ";
8834 if (dl.dylib.compatibility_version == 0xffffffff)
8835 outs() << "n/a\n";
8836 else
8837 outs() << ((dl.dylib.compatibility_version >> 16) & 0xffff) << "."
8838 << ((dl.dylib.compatibility_version >> 8) & 0xff) << "."
8839 << (dl.dylib.compatibility_version & 0xff) << "\n";
8840}
8841
8842static void PrintLinkEditDataCommand(MachO::linkedit_data_command ld,
8843 uint32_t object_size) {
8844 if (ld.cmd == MachO::LC_CODE_SIGNATURE)
Kevin Enderby1be37a32016-04-28 21:07:20 +00008845 outs() << " cmd LC_CODE_SIGNATURE\n";
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008846 else if (ld.cmd == MachO::LC_SEGMENT_SPLIT_INFO)
8847 outs() << " cmd LC_SEGMENT_SPLIT_INFO\n";
8848 else if (ld.cmd == MachO::LC_FUNCTION_STARTS)
8849 outs() << " cmd LC_FUNCTION_STARTS\n";
8850 else if (ld.cmd == MachO::LC_DATA_IN_CODE)
8851 outs() << " cmd LC_DATA_IN_CODE\n";
8852 else if (ld.cmd == MachO::LC_DYLIB_CODE_SIGN_DRS)
8853 outs() << " cmd LC_DYLIB_CODE_SIGN_DRS\n";
8854 else if (ld.cmd == MachO::LC_LINKER_OPTIMIZATION_HINT)
8855 outs() << " cmd LC_LINKER_OPTIMIZATION_HINT\n";
8856 else
8857 outs() << " cmd " << ld.cmd << " (?)\n";
8858 outs() << " cmdsize " << ld.cmdsize;
8859 if (ld.cmdsize != sizeof(struct MachO::linkedit_data_command))
8860 outs() << " Incorrect size\n";
8861 else
8862 outs() << "\n";
8863 outs() << " dataoff " << ld.dataoff;
8864 if (ld.dataoff > object_size)
8865 outs() << " (past end of file)\n";
8866 else
8867 outs() << "\n";
8868 outs() << " datasize " << ld.datasize;
8869 uint64_t big_size = ld.dataoff;
8870 big_size += ld.datasize;
8871 if (big_size > object_size)
8872 outs() << " (past end of file)\n";
8873 else
8874 outs() << "\n";
8875}
8876
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00008877static void PrintLoadCommands(const MachOObjectFile *Obj, uint32_t filetype,
8878 uint32_t cputype, bool verbose) {
Kevin Enderby956366c2014-08-29 22:30:52 +00008879 StringRef Buf = Obj->getData();
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00008880 unsigned Index = 0;
8881 for (const auto &Command : Obj->load_commands()) {
8882 outs() << "Load command " << Index++ << "\n";
Kevin Enderby956366c2014-08-29 22:30:52 +00008883 if (Command.C.cmd == MachO::LC_SEGMENT) {
8884 MachO::segment_command SLC = Obj->getSegmentLoadCommand(Command);
8885 const char *sg_segname = SLC.segname;
8886 PrintSegmentCommand(SLC.cmd, SLC.cmdsize, SLC.segname, SLC.vmaddr,
8887 SLC.vmsize, SLC.fileoff, SLC.filesize, SLC.maxprot,
8888 SLC.initprot, SLC.nsects, SLC.flags, Buf.size(),
8889 verbose);
8890 for (unsigned j = 0; j < SLC.nsects; j++) {
Kevin Enderbyc9713382014-12-16 01:14:45 +00008891 MachO::section S = Obj->getSection(Command, j);
Kevin Enderby956366c2014-08-29 22:30:52 +00008892 PrintSection(S.sectname, S.segname, S.addr, S.size, S.offset, S.align,
8893 S.reloff, S.nreloc, S.flags, S.reserved1, S.reserved2,
8894 SLC.cmd, sg_segname, filetype, Buf.size(), verbose);
8895 }
8896 } else if (Command.C.cmd == MachO::LC_SEGMENT_64) {
8897 MachO::segment_command_64 SLC_64 = Obj->getSegment64LoadCommand(Command);
8898 const char *sg_segname = SLC_64.segname;
8899 PrintSegmentCommand(SLC_64.cmd, SLC_64.cmdsize, SLC_64.segname,
8900 SLC_64.vmaddr, SLC_64.vmsize, SLC_64.fileoff,
8901 SLC_64.filesize, SLC_64.maxprot, SLC_64.initprot,
8902 SLC_64.nsects, SLC_64.flags, Buf.size(), verbose);
8903 for (unsigned j = 0; j < SLC_64.nsects; j++) {
8904 MachO::section_64 S_64 = Obj->getSection64(Command, j);
8905 PrintSection(S_64.sectname, S_64.segname, S_64.addr, S_64.size,
8906 S_64.offset, S_64.align, S_64.reloff, S_64.nreloc,
8907 S_64.flags, S_64.reserved1, S_64.reserved2, SLC_64.cmd,
8908 sg_segname, filetype, Buf.size(), verbose);
8909 }
8910 } else if (Command.C.cmd == MachO::LC_SYMTAB) {
8911 MachO::symtab_command Symtab = Obj->getSymtabLoadCommand();
David Majnemer73cc6ff2014-11-13 19:48:56 +00008912 PrintSymtabLoadCommand(Symtab, Obj->is64Bit(), Buf.size());
Kevin Enderby956366c2014-08-29 22:30:52 +00008913 } else if (Command.C.cmd == MachO::LC_DYSYMTAB) {
8914 MachO::dysymtab_command Dysymtab = Obj->getDysymtabLoadCommand();
8915 MachO::symtab_command Symtab = Obj->getSymtabLoadCommand();
David Majnemer73cc6ff2014-11-13 19:48:56 +00008916 PrintDysymtabLoadCommand(Dysymtab, Symtab.nsyms, Buf.size(),
8917 Obj->is64Bit());
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008918 } else if (Command.C.cmd == MachO::LC_DYLD_INFO ||
8919 Command.C.cmd == MachO::LC_DYLD_INFO_ONLY) {
8920 MachO::dyld_info_command DyldInfo = Obj->getDyldInfoLoadCommand(Command);
8921 PrintDyldInfoLoadCommand(DyldInfo, Buf.size());
8922 } else if (Command.C.cmd == MachO::LC_LOAD_DYLINKER ||
8923 Command.C.cmd == MachO::LC_ID_DYLINKER ||
8924 Command.C.cmd == MachO::LC_DYLD_ENVIRONMENT) {
8925 MachO::dylinker_command Dyld = Obj->getDylinkerCommand(Command);
8926 PrintDyldLoadCommand(Dyld, Command.Ptr);
8927 } else if (Command.C.cmd == MachO::LC_UUID) {
8928 MachO::uuid_command Uuid = Obj->getUuidCommand(Command);
8929 PrintUuidLoadCommand(Uuid);
Jean-Daniel Dupas00cc1f52014-12-04 07:37:02 +00008930 } else if (Command.C.cmd == MachO::LC_RPATH) {
8931 MachO::rpath_command Rpath = Obj->getRpathCommand(Command);
8932 PrintRpathLoadCommand(Rpath, Command.Ptr);
Kevin Enderby1ff0ecc2014-12-16 21:48:27 +00008933 } else if (Command.C.cmd == MachO::LC_VERSION_MIN_MACOSX ||
Tim Northoverbfbfb122015-11-02 21:26:58 +00008934 Command.C.cmd == MachO::LC_VERSION_MIN_IPHONEOS ||
8935 Command.C.cmd == MachO::LC_VERSION_MIN_TVOS ||
8936 Command.C.cmd == MachO::LC_VERSION_MIN_WATCHOS) {
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008937 MachO::version_min_command Vd = Obj->getVersionMinLoadCommand(Command);
8938 PrintVersionMinLoadCommand(Vd);
8939 } else if (Command.C.cmd == MachO::LC_SOURCE_VERSION) {
8940 MachO::source_version_command Sd = Obj->getSourceVersionCommand(Command);
8941 PrintSourceVersionCommand(Sd);
8942 } else if (Command.C.cmd == MachO::LC_MAIN) {
8943 MachO::entry_point_command Ep = Obj->getEntryPointCommand(Command);
8944 PrintEntryPointCommand(Ep);
Kevin Enderby0804f4672014-12-16 23:25:52 +00008945 } else if (Command.C.cmd == MachO::LC_ENCRYPTION_INFO) {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008946 MachO::encryption_info_command Ei =
8947 Obj->getEncryptionInfoCommand(Command);
Kevin Enderby0804f4672014-12-16 23:25:52 +00008948 PrintEncryptionInfoCommand(Ei, Buf.size());
Kevin Enderby57538292014-12-17 01:01:30 +00008949 } else if (Command.C.cmd == MachO::LC_ENCRYPTION_INFO_64) {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008950 MachO::encryption_info_command_64 Ei =
8951 Obj->getEncryptionInfoCommand64(Command);
Kevin Enderby57538292014-12-17 01:01:30 +00008952 PrintEncryptionInfoCommand64(Ei, Buf.size());
Kevin Enderbyd0b6b7f2014-12-18 00:53:40 +00008953 } else if (Command.C.cmd == MachO::LC_LINKER_OPTION) {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008954 MachO::linker_option_command Lo =
8955 Obj->getLinkerOptionLoadCommand(Command);
Kevin Enderbyd0b6b7f2014-12-18 00:53:40 +00008956 PrintLinkerOptionCommand(Lo, Command.Ptr);
Kevin Enderbyb4b79312014-12-18 19:24:35 +00008957 } else if (Command.C.cmd == MachO::LC_SUB_FRAMEWORK) {
8958 MachO::sub_framework_command Sf = Obj->getSubFrameworkCommand(Command);
8959 PrintSubFrameworkCommand(Sf, Command.Ptr);
Kevin Enderbya2bd8d92014-12-18 23:13:26 +00008960 } else if (Command.C.cmd == MachO::LC_SUB_UMBRELLA) {
8961 MachO::sub_umbrella_command Sf = Obj->getSubUmbrellaCommand(Command);
8962 PrintSubUmbrellaCommand(Sf, Command.Ptr);
Kevin Enderby36c8d3a2014-12-19 19:48:16 +00008963 } else if (Command.C.cmd == MachO::LC_SUB_LIBRARY) {
8964 MachO::sub_library_command Sl = Obj->getSubLibraryCommand(Command);
8965 PrintSubLibraryCommand(Sl, Command.Ptr);
Kevin Enderby186eac32014-12-19 21:06:24 +00008966 } else if (Command.C.cmd == MachO::LC_SUB_CLIENT) {
8967 MachO::sub_client_command Sc = Obj->getSubClientCommand(Command);
8968 PrintSubClientCommand(Sc, Command.Ptr);
Kevin Enderby52e4ce42014-12-19 22:25:22 +00008969 } else if (Command.C.cmd == MachO::LC_ROUTINES) {
8970 MachO::routines_command Rc = Obj->getRoutinesCommand(Command);
8971 PrintRoutinesCommand(Rc);
8972 } else if (Command.C.cmd == MachO::LC_ROUTINES_64) {
8973 MachO::routines_command_64 Rc = Obj->getRoutinesCommand64(Command);
8974 PrintRoutinesCommand64(Rc);
Kevin Enderby48ef5342014-12-23 22:56:39 +00008975 } else if (Command.C.cmd == MachO::LC_THREAD ||
8976 Command.C.cmd == MachO::LC_UNIXTHREAD) {
8977 MachO::thread_command Tc = Obj->getThreadCommand(Command);
8978 PrintThreadCommand(Tc, Command.Ptr, Obj->isLittleEndian(), cputype);
Nick Kledzik15558912014-10-16 18:58:20 +00008979 } else if (Command.C.cmd == MachO::LC_LOAD_DYLIB ||
8980 Command.C.cmd == MachO::LC_ID_DYLIB ||
8981 Command.C.cmd == MachO::LC_LOAD_WEAK_DYLIB ||
8982 Command.C.cmd == MachO::LC_REEXPORT_DYLIB ||
8983 Command.C.cmd == MachO::LC_LAZY_LOAD_DYLIB ||
8984 Command.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB) {
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008985 MachO::dylib_command Dl = Obj->getDylibIDLoadCommand(Command);
8986 PrintDylibCommand(Dl, Command.Ptr);
8987 } else if (Command.C.cmd == MachO::LC_CODE_SIGNATURE ||
8988 Command.C.cmd == MachO::LC_SEGMENT_SPLIT_INFO ||
8989 Command.C.cmd == MachO::LC_FUNCTION_STARTS ||
8990 Command.C.cmd == MachO::LC_DATA_IN_CODE ||
8991 Command.C.cmd == MachO::LC_DYLIB_CODE_SIGN_DRS ||
8992 Command.C.cmd == MachO::LC_LINKER_OPTIMIZATION_HINT) {
8993 MachO::linkedit_data_command Ld =
8994 Obj->getLinkeditDataLoadCommand(Command);
8995 PrintLinkEditDataCommand(Ld, Buf.size());
Kevin Enderby956366c2014-08-29 22:30:52 +00008996 } else {
8997 outs() << " cmd ?(" << format("0x%08" PRIx32, Command.C.cmd)
8998 << ")\n";
8999 outs() << " cmdsize " << Command.C.cmdsize << "\n";
9000 // TODO: get and print the raw bytes of the load command.
9001 }
9002 // TODO: print all the other kinds of load commands.
Kevin Enderby956366c2014-08-29 22:30:52 +00009003 }
9004}
9005
Kevin Enderby0ae163f2016-01-13 00:25:36 +00009006static void PrintMachHeader(const MachOObjectFile *Obj, bool verbose) {
Kevin Enderbyb76d3862014-08-22 20:35:18 +00009007 if (Obj->is64Bit()) {
9008 MachO::mach_header_64 H_64;
9009 H_64 = Obj->getHeader64();
9010 PrintMachHeader(H_64.magic, H_64.cputype, H_64.cpusubtype, H_64.filetype,
9011 H_64.ncmds, H_64.sizeofcmds, H_64.flags, verbose);
9012 } else {
9013 MachO::mach_header H;
9014 H = Obj->getHeader();
9015 PrintMachHeader(H.magic, H.cputype, H.cpusubtype, H.filetype, H.ncmds,
9016 H.sizeofcmds, H.flags, verbose);
9017 }
9018}
9019
9020void llvm::printMachOFileHeader(const object::ObjectFile *Obj) {
9021 const MachOObjectFile *file = dyn_cast<const MachOObjectFile>(Obj);
Kevin Enderby0ae163f2016-01-13 00:25:36 +00009022 PrintMachHeader(file, !NonVerbose);
9023}
9024
9025void llvm::printMachOLoadCommands(const object::ObjectFile *Obj) {
9026 const MachOObjectFile *file = dyn_cast<const MachOObjectFile>(Obj);
Kevin Enderby956366c2014-08-29 22:30:52 +00009027 uint32_t filetype = 0;
9028 uint32_t cputype = 0;
Kevin Enderby0ae163f2016-01-13 00:25:36 +00009029 if (file->is64Bit()) {
9030 MachO::mach_header_64 H_64;
9031 H_64 = file->getHeader64();
9032 filetype = H_64.filetype;
9033 cputype = H_64.cputype;
9034 } else {
9035 MachO::mach_header H;
9036 H = file->getHeader();
9037 filetype = H.filetype;
9038 cputype = H.cputype;
9039 }
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00009040 PrintLoadCommands(file, filetype, cputype, !NonVerbose);
Kevin Enderbyb76d3862014-08-22 20:35:18 +00009041}
Nick Kledzikd04bc352014-08-30 00:20:14 +00009042
9043//===----------------------------------------------------------------------===//
9044// export trie dumping
9045//===----------------------------------------------------------------------===//
9046
9047void llvm::printMachOExportsTrie(const object::MachOObjectFile *Obj) {
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00009048 for (const llvm::object::ExportEntry &Entry : Obj->exports()) {
9049 uint64_t Flags = Entry.flags();
Nick Kledzikd04bc352014-08-30 00:20:14 +00009050 bool ReExport = (Flags & MachO::EXPORT_SYMBOL_FLAGS_REEXPORT);
9051 bool WeakDef = (Flags & MachO::EXPORT_SYMBOL_FLAGS_WEAK_DEFINITION);
9052 bool ThreadLocal = ((Flags & MachO::EXPORT_SYMBOL_FLAGS_KIND_MASK) ==
9053 MachO::EXPORT_SYMBOL_FLAGS_KIND_THREAD_LOCAL);
9054 bool Abs = ((Flags & MachO::EXPORT_SYMBOL_FLAGS_KIND_MASK) ==
9055 MachO::EXPORT_SYMBOL_FLAGS_KIND_ABSOLUTE);
9056 bool Resolver = (Flags & MachO::EXPORT_SYMBOL_FLAGS_STUB_AND_RESOLVER);
9057 if (ReExport)
9058 outs() << "[re-export] ";
9059 else
Kevin Enderbyb28ed012014-10-29 21:28:24 +00009060 outs() << format("0x%08llX ",
9061 Entry.address()); // FIXME:add in base address
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00009062 outs() << Entry.name();
Nick Kledzikd04bc352014-08-30 00:20:14 +00009063 if (WeakDef || ThreadLocal || Resolver || Abs) {
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00009064 bool NeedsComma = false;
Nick Kledzik1d1ac4b2014-09-03 01:12:52 +00009065 outs() << " [";
Nick Kledzikd04bc352014-08-30 00:20:14 +00009066 if (WeakDef) {
9067 outs() << "weak_def";
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00009068 NeedsComma = true;
Nick Kledzikd04bc352014-08-30 00:20:14 +00009069 }
9070 if (ThreadLocal) {
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00009071 if (NeedsComma)
Nick Kledzikd04bc352014-08-30 00:20:14 +00009072 outs() << ", ";
9073 outs() << "per-thread";
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00009074 NeedsComma = true;
Nick Kledzikd04bc352014-08-30 00:20:14 +00009075 }
9076 if (Abs) {
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00009077 if (NeedsComma)
Nick Kledzikd04bc352014-08-30 00:20:14 +00009078 outs() << ", ";
9079 outs() << "absolute";
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00009080 NeedsComma = true;
Nick Kledzikd04bc352014-08-30 00:20:14 +00009081 }
9082 if (Resolver) {
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00009083 if (NeedsComma)
Nick Kledzikd04bc352014-08-30 00:20:14 +00009084 outs() << ", ";
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00009085 outs() << format("resolver=0x%08llX", Entry.other());
9086 NeedsComma = true;
Nick Kledzikd04bc352014-08-30 00:20:14 +00009087 }
9088 outs() << "]";
9089 }
9090 if (ReExport) {
9091 StringRef DylibName = "unknown";
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00009092 int Ordinal = Entry.other() - 1;
9093 Obj->getLibraryShortNameByIndex(Ordinal, DylibName);
9094 if (Entry.otherName().empty())
Nick Kledzikd04bc352014-08-30 00:20:14 +00009095 outs() << " (from " << DylibName << ")";
9096 else
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00009097 outs() << " (" << Entry.otherName() << " from " << DylibName << ")";
Nick Kledzikd04bc352014-08-30 00:20:14 +00009098 }
9099 outs() << "\n";
9100 }
9101}
Nick Kledzikac431442014-09-12 21:34:15 +00009102
Nick Kledzikac431442014-09-12 21:34:15 +00009103//===----------------------------------------------------------------------===//
9104// rebase table dumping
9105//===----------------------------------------------------------------------===//
9106
9107namespace {
9108class SegInfo {
9109public:
9110 SegInfo(const object::MachOObjectFile *Obj);
9111
9112 StringRef segmentName(uint32_t SegIndex);
9113 StringRef sectionName(uint32_t SegIndex, uint64_t SegOffset);
9114 uint64_t address(uint32_t SegIndex, uint64_t SegOffset);
Kevin Enderbyaf7c9d02015-10-09 16:48:44 +00009115 bool isValidSegIndexAndOffset(uint32_t SegIndex, uint64_t SegOffset);
Nick Kledzikac431442014-09-12 21:34:15 +00009116
9117private:
9118 struct SectionInfo {
9119 uint64_t Address;
9120 uint64_t Size;
9121 StringRef SectionName;
9122 StringRef SegmentName;
9123 uint64_t OffsetInSegment;
9124 uint64_t SegmentStartAddress;
9125 uint32_t SegmentIndex;
9126 };
9127 const SectionInfo &findSection(uint32_t SegIndex, uint64_t SegOffset);
9128 SmallVector<SectionInfo, 32> Sections;
9129};
9130}
9131
9132SegInfo::SegInfo(const object::MachOObjectFile *Obj) {
9133 // Build table of sections so segIndex/offset pairs can be translated.
Nick Kledzik56ebef42014-09-16 01:41:51 +00009134 uint32_t CurSegIndex = Obj->hasPageZeroSegment() ? 1 : 0;
Nick Kledzikac431442014-09-12 21:34:15 +00009135 StringRef CurSegName;
9136 uint64_t CurSegAddress;
9137 for (const SectionRef &Section : Obj->sections()) {
9138 SectionInfo Info;
Davide Italianoccd53fe2015-08-05 07:18:31 +00009139 error(Section.getName(Info.SectionName));
Rafael Espindola80291272014-10-08 15:28:58 +00009140 Info.Address = Section.getAddress();
9141 Info.Size = Section.getSize();
Nick Kledzikac431442014-09-12 21:34:15 +00009142 Info.SegmentName =
9143 Obj->getSectionFinalSegmentName(Section.getRawDataRefImpl());
9144 if (!Info.SegmentName.equals(CurSegName)) {
9145 ++CurSegIndex;
9146 CurSegName = Info.SegmentName;
9147 CurSegAddress = Info.Address;
9148 }
9149 Info.SegmentIndex = CurSegIndex - 1;
9150 Info.OffsetInSegment = Info.Address - CurSegAddress;
9151 Info.SegmentStartAddress = CurSegAddress;
9152 Sections.push_back(Info);
9153 }
9154}
9155
9156StringRef SegInfo::segmentName(uint32_t SegIndex) {
9157 for (const SectionInfo &SI : Sections) {
9158 if (SI.SegmentIndex == SegIndex)
9159 return SI.SegmentName;
9160 }
9161 llvm_unreachable("invalid segIndex");
9162}
9163
Kevin Enderbyaf7c9d02015-10-09 16:48:44 +00009164bool SegInfo::isValidSegIndexAndOffset(uint32_t SegIndex,
9165 uint64_t OffsetInSeg) {
9166 for (const SectionInfo &SI : Sections) {
9167 if (SI.SegmentIndex != SegIndex)
9168 continue;
9169 if (SI.OffsetInSegment > OffsetInSeg)
9170 continue;
9171 if (OffsetInSeg >= (SI.OffsetInSegment + SI.Size))
9172 continue;
9173 return true;
9174 }
9175 return false;
9176}
9177
Nick Kledzikac431442014-09-12 21:34:15 +00009178const SegInfo::SectionInfo &SegInfo::findSection(uint32_t SegIndex,
9179 uint64_t OffsetInSeg) {
9180 for (const SectionInfo &SI : Sections) {
9181 if (SI.SegmentIndex != SegIndex)
9182 continue;
9183 if (SI.OffsetInSegment > OffsetInSeg)
9184 continue;
9185 if (OffsetInSeg >= (SI.OffsetInSegment + SI.Size))
9186 continue;
9187 return SI;
9188 }
9189 llvm_unreachable("segIndex and offset not in any section");
9190}
9191
9192StringRef SegInfo::sectionName(uint32_t SegIndex, uint64_t OffsetInSeg) {
9193 return findSection(SegIndex, OffsetInSeg).SectionName;
9194}
9195
9196uint64_t SegInfo::address(uint32_t SegIndex, uint64_t OffsetInSeg) {
9197 const SectionInfo &SI = findSection(SegIndex, OffsetInSeg);
9198 return SI.SegmentStartAddress + OffsetInSeg;
9199}
9200
9201void llvm::printMachORebaseTable(const object::MachOObjectFile *Obj) {
9202 // Build table of sections so names can used in final output.
9203 SegInfo sectionTable(Obj);
9204
9205 outs() << "segment section address type\n";
9206 for (const llvm::object::MachORebaseEntry &Entry : Obj->rebaseTable()) {
9207 uint32_t SegIndex = Entry.segmentIndex();
9208 uint64_t OffsetInSeg = Entry.segmentOffset();
9209 StringRef SegmentName = sectionTable.segmentName(SegIndex);
9210 StringRef SectionName = sectionTable.sectionName(SegIndex, OffsetInSeg);
9211 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
9212
9213 // Table lines look like: __DATA __nl_symbol_ptr 0x0000F00C pointer
Kevin Enderbyb28ed012014-10-29 21:28:24 +00009214 outs() << format("%-8s %-18s 0x%08" PRIX64 " %s\n",
9215 SegmentName.str().c_str(), SectionName.str().c_str(),
9216 Address, Entry.typeName().str().c_str());
Nick Kledzikac431442014-09-12 21:34:15 +00009217 }
9218}
Nick Kledzik56ebef42014-09-16 01:41:51 +00009219
9220static StringRef ordinalName(const object::MachOObjectFile *Obj, int Ordinal) {
9221 StringRef DylibName;
9222 switch (Ordinal) {
9223 case MachO::BIND_SPECIAL_DYLIB_SELF:
9224 return "this-image";
9225 case MachO::BIND_SPECIAL_DYLIB_MAIN_EXECUTABLE:
9226 return "main-executable";
9227 case MachO::BIND_SPECIAL_DYLIB_FLAT_LOOKUP:
9228 return "flat-namespace";
9229 default:
Nick Kledzikabd29872014-09-16 22:03:13 +00009230 if (Ordinal > 0) {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00009231 std::error_code EC =
9232 Obj->getLibraryShortNameByIndex(Ordinal - 1, DylibName);
Nick Kledzikabd29872014-09-16 22:03:13 +00009233 if (EC)
Nick Kledzik51d2c2b2014-10-14 23:29:38 +00009234 return "<<bad library ordinal>>";
Nick Kledzikabd29872014-09-16 22:03:13 +00009235 return DylibName;
9236 }
Nick Kledzik56ebef42014-09-16 01:41:51 +00009237 }
Nick Kledzikabd29872014-09-16 22:03:13 +00009238 return "<<unknown special ordinal>>";
Nick Kledzik56ebef42014-09-16 01:41:51 +00009239}
9240
9241//===----------------------------------------------------------------------===//
9242// bind table dumping
9243//===----------------------------------------------------------------------===//
9244
9245void llvm::printMachOBindTable(const object::MachOObjectFile *Obj) {
9246 // Build table of sections so names can used in final output.
9247 SegInfo sectionTable(Obj);
9248
Nick Kledzik5ffacc12014-09-30 00:19:58 +00009249 outs() << "segment section address type "
9250 "addend dylib symbol\n";
Nick Kledzik56ebef42014-09-16 01:41:51 +00009251 for (const llvm::object::MachOBindEntry &Entry : Obj->bindTable()) {
9252 uint32_t SegIndex = Entry.segmentIndex();
9253 uint64_t OffsetInSeg = Entry.segmentOffset();
9254 StringRef SegmentName = sectionTable.segmentName(SegIndex);
9255 StringRef SectionName = sectionTable.sectionName(SegIndex, OffsetInSeg);
9256 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
9257
9258 // Table lines look like:
9259 // __DATA __got 0x00012010 pointer 0 libSystem ___stack_chk_guard
Nick Kledzik5ffacc12014-09-30 00:19:58 +00009260 StringRef Attr;
Nick Kledzik56ebef42014-09-16 01:41:51 +00009261 if (Entry.flags() & MachO::BIND_SYMBOL_FLAGS_WEAK_IMPORT)
Nick Kledzik5ffacc12014-09-30 00:19:58 +00009262 Attr = " (weak_import)";
Kevin Enderbyb28ed012014-10-29 21:28:24 +00009263 outs() << left_justify(SegmentName, 8) << " "
Nick Kledzik5ffacc12014-09-30 00:19:58 +00009264 << left_justify(SectionName, 18) << " "
9265 << format_hex(Address, 10, true) << " "
9266 << left_justify(Entry.typeName(), 8) << " "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00009267 << format_decimal(Entry.addend(), 8) << " "
Nick Kledzik5ffacc12014-09-30 00:19:58 +00009268 << left_justify(ordinalName(Obj, Entry.ordinal()), 16) << " "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00009269 << Entry.symbolName() << Attr << "\n";
Nick Kledzik56ebef42014-09-16 01:41:51 +00009270 }
9271}
9272
9273//===----------------------------------------------------------------------===//
9274// lazy bind table dumping
9275//===----------------------------------------------------------------------===//
9276
9277void llvm::printMachOLazyBindTable(const object::MachOObjectFile *Obj) {
9278 // Build table of sections so names can used in final output.
9279 SegInfo sectionTable(Obj);
9280
Nick Kledzik5ffacc12014-09-30 00:19:58 +00009281 outs() << "segment section address "
9282 "dylib symbol\n";
Nick Kledzik56ebef42014-09-16 01:41:51 +00009283 for (const llvm::object::MachOBindEntry &Entry : Obj->lazyBindTable()) {
9284 uint32_t SegIndex = Entry.segmentIndex();
9285 uint64_t OffsetInSeg = Entry.segmentOffset();
9286 StringRef SegmentName = sectionTable.segmentName(SegIndex);
9287 StringRef SectionName = sectionTable.sectionName(SegIndex, OffsetInSeg);
9288 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
9289
9290 // Table lines look like:
9291 // __DATA __got 0x00012010 libSystem ___stack_chk_guard
Kevin Enderbyb28ed012014-10-29 21:28:24 +00009292 outs() << left_justify(SegmentName, 8) << " "
Nick Kledzik5ffacc12014-09-30 00:19:58 +00009293 << left_justify(SectionName, 18) << " "
9294 << format_hex(Address, 10, true) << " "
9295 << left_justify(ordinalName(Obj, Entry.ordinal()), 16) << " "
Nick Kledzik56ebef42014-09-16 01:41:51 +00009296 << Entry.symbolName() << "\n";
9297 }
9298}
9299
Nick Kledzik56ebef42014-09-16 01:41:51 +00009300//===----------------------------------------------------------------------===//
9301// weak bind table dumping
9302//===----------------------------------------------------------------------===//
9303
9304void llvm::printMachOWeakBindTable(const object::MachOObjectFile *Obj) {
9305 // Build table of sections so names can used in final output.
9306 SegInfo sectionTable(Obj);
9307
Nick Kledzik5ffacc12014-09-30 00:19:58 +00009308 outs() << "segment section address "
9309 "type addend symbol\n";
Nick Kledzik56ebef42014-09-16 01:41:51 +00009310 for (const llvm::object::MachOBindEntry &Entry : Obj->weakBindTable()) {
9311 // Strong symbols don't have a location to update.
9312 if (Entry.flags() & MachO::BIND_SYMBOL_FLAGS_NON_WEAK_DEFINITION) {
Nick Kledzik5ffacc12014-09-30 00:19:58 +00009313 outs() << " strong "
Nick Kledzik56ebef42014-09-16 01:41:51 +00009314 << Entry.symbolName() << "\n";
9315 continue;
9316 }
9317 uint32_t SegIndex = Entry.segmentIndex();
9318 uint64_t OffsetInSeg = Entry.segmentOffset();
9319 StringRef SegmentName = sectionTable.segmentName(SegIndex);
9320 StringRef SectionName = sectionTable.sectionName(SegIndex, OffsetInSeg);
9321 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
9322
9323 // Table lines look like:
9324 // __DATA __data 0x00001000 pointer 0 _foo
Kevin Enderbyb28ed012014-10-29 21:28:24 +00009325 outs() << left_justify(SegmentName, 8) << " "
Nick Kledzik5ffacc12014-09-30 00:19:58 +00009326 << left_justify(SectionName, 18) << " "
9327 << format_hex(Address, 10, true) << " "
9328 << left_justify(Entry.typeName(), 8) << " "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00009329 << format_decimal(Entry.addend(), 8) << " " << Entry.symbolName()
9330 << "\n";
Nick Kledzik56ebef42014-09-16 01:41:51 +00009331 }
9332}
9333
Kevin Enderby6f326ce2014-10-23 19:37:31 +00009334// get_dyld_bind_info_symbolname() is used for disassembly and passed an
9335// address, ReferenceValue, in the Mach-O file and looks in the dyld bind
9336// information for that address. If the address is found its binding symbol
9337// name is returned. If not nullptr is returned.
9338static const char *get_dyld_bind_info_symbolname(uint64_t ReferenceValue,
9339 struct DisassembleInfo *info) {
Kevin Enderby078be602014-10-23 19:53:12 +00009340 if (info->bindtable == nullptr) {
9341 info->bindtable = new (BindTable);
Kevin Enderby6f326ce2014-10-23 19:37:31 +00009342 SegInfo sectionTable(info->O);
9343 for (const llvm::object::MachOBindEntry &Entry : info->O->bindTable()) {
9344 uint32_t SegIndex = Entry.segmentIndex();
9345 uint64_t OffsetInSeg = Entry.segmentOffset();
Kevin Enderbyaf7c9d02015-10-09 16:48:44 +00009346 if (!sectionTable.isValidSegIndexAndOffset(SegIndex, OffsetInSeg))
9347 continue;
Kevin Enderby6f326ce2014-10-23 19:37:31 +00009348 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
9349 const char *SymbolName = nullptr;
9350 StringRef name = Entry.symbolName();
9351 if (!name.empty())
9352 SymbolName = name.data();
Kevin Enderby078be602014-10-23 19:53:12 +00009353 info->bindtable->push_back(std::make_pair(Address, SymbolName));
Kevin Enderby6f326ce2014-10-23 19:37:31 +00009354 }
9355 }
Kevin Enderby078be602014-10-23 19:53:12 +00009356 for (bind_table_iterator BI = info->bindtable->begin(),
9357 BE = info->bindtable->end();
Kevin Enderby6f326ce2014-10-23 19:37:31 +00009358 BI != BE; ++BI) {
9359 uint64_t Address = BI->first;
9360 if (ReferenceValue == Address) {
9361 const char *SymbolName = BI->second;
9362 return SymbolName;
9363 }
9364 }
9365 return nullptr;
9366}