blob: 3f4185e63307f6f208f51660ce3f10dda6872308 [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";
1406 if (verbose)
1407 outs() << "fat_magic FAT_MAGIC\n";
1408 else
1409 outs() << "fat_magic " << format("0x%" PRIx32, MachO::FAT_MAGIC) << "\n";
1410
1411 uint32_t nfat_arch = UB->getNumberOfObjects();
1412 StringRef Buf = UB->getData();
1413 uint64_t size = Buf.size();
1414 uint64_t big_size = sizeof(struct MachO::fat_header) +
1415 nfat_arch * sizeof(struct MachO::fat_arch);
1416 outs() << "nfat_arch " << UB->getNumberOfObjects();
1417 if (nfat_arch == 0)
1418 outs() << " (malformed, contains zero architecture types)\n";
1419 else if (big_size > size)
1420 outs() << " (malformed, architectures past end of file)\n";
1421 else
1422 outs() << "\n";
1423
1424 for (uint32_t i = 0; i < nfat_arch; ++i) {
1425 MachOUniversalBinary::ObjectForArch OFA(UB, i);
1426 uint32_t cputype = OFA.getCPUType();
1427 uint32_t cpusubtype = OFA.getCPUSubType();
1428 outs() << "architecture ";
1429 for (uint32_t j = 0; i != 0 && j <= i - 1; j++) {
1430 MachOUniversalBinary::ObjectForArch other_OFA(UB, j);
1431 uint32_t other_cputype = other_OFA.getCPUType();
1432 uint32_t other_cpusubtype = other_OFA.getCPUSubType();
Kevin Enderby0512bd72015-01-09 21:55:03 +00001433 if (cputype != 0 && cpusubtype != 0 && cputype == other_cputype &&
Kevin Enderby131d1772015-01-09 19:22:37 +00001434 (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) ==
Kevin Enderby0512bd72015-01-09 21:55:03 +00001435 (other_cpusubtype & ~MachO::CPU_SUBTYPE_MASK)) {
Kevin Enderby131d1772015-01-09 19:22:37 +00001436 outs() << "(illegal duplicate architecture) ";
1437 break;
Kevin Enderby0512bd72015-01-09 21:55:03 +00001438 }
Kevin Enderby131d1772015-01-09 19:22:37 +00001439 }
1440 if (verbose) {
1441 outs() << OFA.getArchTypeName() << "\n";
1442 printCPUType(cputype, cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
1443 } else {
1444 outs() << i << "\n";
1445 outs() << " cputype " << cputype << "\n";
1446 outs() << " cpusubtype " << (cpusubtype & ~MachO::CPU_SUBTYPE_MASK)
1447 << "\n";
1448 }
1449 if (verbose &&
1450 (cpusubtype & MachO::CPU_SUBTYPE_MASK) == MachO::CPU_SUBTYPE_LIB64)
1451 outs() << " capabilities CPU_SUBTYPE_LIB64\n";
1452 else
1453 outs() << " capabilities "
1454 << format("0x%" PRIx32,
1455 (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24) << "\n";
1456 outs() << " offset " << OFA.getOffset();
1457 if (OFA.getOffset() > size)
1458 outs() << " (past end of file)";
1459 if (OFA.getOffset() % (1 << OFA.getAlign()) != 0)
1460 outs() << " (not aligned on it's alignment (2^" << OFA.getAlign() << ")";
1461 outs() << "\n";
1462 outs() << " size " << OFA.getSize();
1463 big_size = OFA.getOffset() + OFA.getSize();
1464 if (big_size > size)
1465 outs() << " (past end of file)";
1466 outs() << "\n";
1467 outs() << " align 2^" << OFA.getAlign() << " (" << (1 << OFA.getAlign())
1468 << ")\n";
1469 }
1470}
1471
Rafael Espindola266b4fe2015-10-31 22:25:59 +00001472static void printArchiveChild(const Archive::Child &C, bool verbose,
Kevin Enderby13023a12015-01-15 23:19:11 +00001473 bool print_offset) {
1474 if (print_offset)
1475 outs() << C.getChildOffset() << "\t";
1476 sys::fs::perms Mode = C.getAccessMode();
1477 if (verbose) {
1478 // FIXME: this first dash, "-", is for (Mode & S_IFMT) == S_IFREG.
1479 // But there is nothing in sys::fs::perms for S_IFMT or S_IFREG.
1480 outs() << "-";
Davide Italianobb9a6cc2015-09-07 20:47:03 +00001481 outs() << ((Mode & sys::fs::owner_read) ? "r" : "-");
1482 outs() << ((Mode & sys::fs::owner_write) ? "w" : "-");
1483 outs() << ((Mode & sys::fs::owner_exe) ? "x" : "-");
1484 outs() << ((Mode & sys::fs::group_read) ? "r" : "-");
1485 outs() << ((Mode & sys::fs::group_write) ? "w" : "-");
1486 outs() << ((Mode & sys::fs::group_exe) ? "x" : "-");
1487 outs() << ((Mode & sys::fs::others_read) ? "r" : "-");
1488 outs() << ((Mode & sys::fs::others_write) ? "w" : "-");
1489 outs() << ((Mode & sys::fs::others_exe) ? "x" : "-");
Kevin Enderby13023a12015-01-15 23:19:11 +00001490 } else {
1491 outs() << format("0%o ", Mode);
1492 }
1493
1494 unsigned UID = C.getUID();
1495 outs() << format("%3d/", UID);
1496 unsigned GID = C.getGID();
1497 outs() << format("%-3d ", GID);
Kevin Enderby7a969422015-11-05 19:24:56 +00001498 ErrorOr<uint64_t> Size = C.getRawSize();
1499 if (std::error_code EC = Size.getError())
1500 report_fatal_error(EC.message());
1501 outs() << format("%5" PRId64, Size.get()) << " ";
Kevin Enderby13023a12015-01-15 23:19:11 +00001502
1503 StringRef RawLastModified = C.getRawLastModified();
1504 if (verbose) {
1505 unsigned Seconds;
1506 if (RawLastModified.getAsInteger(10, Seconds))
1507 outs() << "(date: \"%s\" contains non-decimal chars) " << RawLastModified;
1508 else {
1509 // Since cime(3) returns a 26 character string of the form:
1510 // "Sun Sep 16 01:03:52 1973\n\0"
1511 // just print 24 characters.
1512 time_t t = Seconds;
1513 outs() << format("%.24s ", ctime(&t));
1514 }
1515 } else {
1516 outs() << RawLastModified << " ";
1517 }
1518
1519 if (verbose) {
1520 ErrorOr<StringRef> NameOrErr = C.getName();
1521 if (NameOrErr.getError()) {
1522 StringRef RawName = C.getRawName();
1523 outs() << RawName << "\n";
1524 } else {
1525 StringRef Name = NameOrErr.get();
1526 outs() << Name << "\n";
1527 }
1528 } else {
1529 StringRef RawName = C.getRawName();
1530 outs() << RawName << "\n";
1531 }
1532}
1533
1534static void printArchiveHeaders(Archive *A, bool verbose, bool print_offset) {
Rafael Espindola4a782fb2015-10-31 21:03:29 +00001535 for (Archive::child_iterator I = A->child_begin(false), E = A->child_end();
1536 I != E; ++I) {
Kevin Enderby7a969422015-11-05 19:24:56 +00001537 if (std::error_code EC = I->getError())
1538 report_fatal_error(EC.message());
1539 const Archive::Child &C = **I;
Kevin Enderby13023a12015-01-15 23:19:11 +00001540 printArchiveChild(C, verbose, print_offset);
1541 }
1542}
1543
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001544// ParseInputMachO() parses the named Mach-O file in Filename and handles the
1545// -arch flags selecting just those slices as specified by them and also parses
1546// archive files. Then for each individual Mach-O file ProcessMachO() is
1547// called to process the file based on the command line options.
1548void llvm::ParseInputMachO(StringRef Filename) {
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001549 // Check for -arch all and verifiy the -arch flags are valid.
1550 for (unsigned i = 0; i < ArchFlags.size(); ++i) {
1551 if (ArchFlags[i] == "all") {
1552 ArchAll = true;
1553 } else {
1554 if (!MachOObjectFile::isValidArch(ArchFlags[i])) {
1555 errs() << "llvm-objdump: Unknown architecture named '" + ArchFlags[i] +
1556 "'for the -arch option\n";
1557 return;
1558 }
1559 }
1560 }
1561
1562 // Attempt to open the binary.
Kevin Enderby3fcdf6a2016-04-06 22:14:09 +00001563 Expected<OwningBinary<Binary>> BinaryOrErr = createBinary(Filename);
1564 if (!BinaryOrErr)
1565 report_error(Filename, BinaryOrErr.takeError());
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001566 Binary &Bin = *BinaryOrErr.get().getBinary();
Kevin Enderby3f0ffab2014-12-03 22:29:40 +00001567
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001568 if (Archive *A = dyn_cast<Archive>(&Bin)) {
1569 outs() << "Archive : " << Filename << "\n";
Kevin Enderby13023a12015-01-15 23:19:11 +00001570 if (ArchiveHeaders)
Kevin Enderby8972e482015-04-30 20:30:42 +00001571 printArchiveHeaders(A, !NonVerbose, ArchiveMemberOffsets);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001572 for (Archive::child_iterator I = A->child_begin(), E = A->child_end();
1573 I != E; ++I) {
Davide Italianob13edeb2015-12-08 02:45:59 +00001574 if (std::error_code EC = I->getError())
1575 report_error(Filename, EC);
Kevin Enderby7a969422015-11-05 19:24:56 +00001576 auto &C = I->get();
Kevin Enderbyac9e1552016-05-17 17:10:12 +00001577 Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
1578 if (!ChildOrErr) {
1579 if (auto E = isNotObjectErrorInvalidFileType(ChildOrErr.takeError()))
1580 report_error(Filename, C, std::move(E));
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001581 continue;
Kevin Enderbyac9e1552016-05-17 17:10:12 +00001582 }
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001583 if (MachOObjectFile *O = dyn_cast<MachOObjectFile>(&*ChildOrErr.get())) {
1584 if (!checkMachOAndArchFlags(O, Filename))
1585 return;
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001586 ProcessMachO(Filename, O, O->getFileName());
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001587 }
1588 }
1589 return;
1590 }
Kevin Enderby131d1772015-01-09 19:22:37 +00001591 if (UniversalHeaders) {
1592 if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(&Bin))
Kevin Enderbyf0640752015-03-13 17:56:32 +00001593 printMachOUniversalHeaders(UB, !NonVerbose);
Kevin Enderby131d1772015-01-09 19:22:37 +00001594 }
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001595 if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(&Bin)) {
1596 // If we have a list of architecture flags specified dump only those.
1597 if (!ArchAll && ArchFlags.size() != 0) {
1598 // Look for a slice in the universal binary that matches each ArchFlag.
1599 bool ArchFound;
1600 for (unsigned i = 0; i < ArchFlags.size(); ++i) {
1601 ArchFound = false;
1602 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
1603 E = UB->end_objects();
1604 I != E; ++I) {
1605 if (ArchFlags[i] == I->getArchTypeName()) {
1606 ArchFound = true;
Kevin Enderby9acb1092016-05-31 20:35:34 +00001607 Expected<std::unique_ptr<ObjectFile>> ObjOrErr =
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001608 I->getAsObjectFile();
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001609 std::string ArchitectureName = "";
1610 if (ArchFlags.size() > 1)
1611 ArchitectureName = I->getArchTypeName();
1612 if (ObjOrErr) {
1613 ObjectFile &O = *ObjOrErr.get();
1614 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&O))
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001615 ProcessMachO(Filename, MachOOF, "", ArchitectureName);
Kevin Enderby9acb1092016-05-31 20:35:34 +00001616 } else if (auto E = isNotObjectErrorInvalidFileType(
1617 ObjOrErr.takeError())) {
1618 report_error(Filename, StringRef(), std::move(E),
1619 ArchitectureName);
1620 continue;
Rafael Espindola0bfe8282014-12-09 21:05:36 +00001621 } else if (ErrorOr<std::unique_ptr<Archive>> AOrErr =
1622 I->getAsArchive()) {
1623 std::unique_ptr<Archive> &A = *AOrErr;
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001624 outs() << "Archive : " << Filename;
1625 if (!ArchitectureName.empty())
1626 outs() << " (architecture " << ArchitectureName << ")";
1627 outs() << "\n";
Kevin Enderby13023a12015-01-15 23:19:11 +00001628 if (ArchiveHeaders)
Kevin Enderby8972e482015-04-30 20:30:42 +00001629 printArchiveHeaders(A.get(), !NonVerbose, ArchiveMemberOffsets);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001630 for (Archive::child_iterator AI = A->child_begin(),
1631 AE = A->child_end();
1632 AI != AE; ++AI) {
Davide Italianob13edeb2015-12-08 02:45:59 +00001633 if (std::error_code EC = AI->getError())
1634 report_error(Filename, EC);
Kevin Enderby7a969422015-11-05 19:24:56 +00001635 auto &C = AI->get();
Kevin Enderbyac9e1552016-05-17 17:10:12 +00001636 Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
1637 if (!ChildOrErr) {
1638 if (auto E = isNotObjectErrorInvalidFileType(ChildOrErr.takeError()))
Kevin Enderby9acb1092016-05-31 20:35:34 +00001639 report_error(Filename, C, std::move(E), ArchitectureName);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001640 continue;
Kevin Enderbyac9e1552016-05-17 17:10:12 +00001641 }
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001642 if (MachOObjectFile *O =
1643 dyn_cast<MachOObjectFile>(&*ChildOrErr.get()))
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001644 ProcessMachO(Filename, O, O->getFileName(), ArchitectureName);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001645 }
1646 }
1647 }
1648 }
1649 if (!ArchFound) {
1650 errs() << "llvm-objdump: file: " + Filename + " does not contain "
1651 << "architecture: " + ArchFlags[i] + "\n";
1652 return;
1653 }
1654 }
1655 return;
1656 }
1657 // No architecture flags were specified so if this contains a slice that
1658 // matches the host architecture dump only that.
1659 if (!ArchAll) {
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001660 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
1661 E = UB->end_objects();
1662 I != E; ++I) {
Kevin Enderby0512bd72015-01-09 21:55:03 +00001663 if (MachOObjectFile::getHostArch().getArchName() ==
1664 I->getArchTypeName()) {
Kevin Enderby9acb1092016-05-31 20:35:34 +00001665 Expected<std::unique_ptr<ObjectFile>> ObjOrErr = I->getAsObjectFile();
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001666 std::string ArchiveName;
1667 ArchiveName.clear();
1668 if (ObjOrErr) {
1669 ObjectFile &O = *ObjOrErr.get();
1670 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&O))
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001671 ProcessMachO(Filename, MachOOF);
Kevin Enderby9acb1092016-05-31 20:35:34 +00001672 } else if (auto E = isNotObjectErrorInvalidFileType(
1673 ObjOrErr.takeError())) {
1674 report_error(Filename, std::move(E));
1675 continue;
Rafael Espindola0bfe8282014-12-09 21:05:36 +00001676 } else if (ErrorOr<std::unique_ptr<Archive>> AOrErr =
1677 I->getAsArchive()) {
1678 std::unique_ptr<Archive> &A = *AOrErr;
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001679 outs() << "Archive : " << Filename << "\n";
Kevin Enderby13023a12015-01-15 23:19:11 +00001680 if (ArchiveHeaders)
Kevin Enderby8972e482015-04-30 20:30:42 +00001681 printArchiveHeaders(A.get(), !NonVerbose, ArchiveMemberOffsets);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001682 for (Archive::child_iterator AI = A->child_begin(),
1683 AE = A->child_end();
1684 AI != AE; ++AI) {
Davide Italianob13edeb2015-12-08 02:45:59 +00001685 if (std::error_code EC = AI->getError())
1686 report_error(Filename, EC);
Kevin Enderby7a969422015-11-05 19:24:56 +00001687 auto &C = AI->get();
Kevin Enderbyac9e1552016-05-17 17:10:12 +00001688 Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
1689 if (!ChildOrErr) {
1690 if (auto E = isNotObjectErrorInvalidFileType(ChildOrErr.takeError()))
1691 report_error(Filename, C, std::move(E));
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001692 continue;
Kevin Enderbyac9e1552016-05-17 17:10:12 +00001693 }
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001694 if (MachOObjectFile *O =
1695 dyn_cast<MachOObjectFile>(&*ChildOrErr.get()))
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001696 ProcessMachO(Filename, O, O->getFileName());
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001697 }
1698 }
1699 return;
1700 }
1701 }
1702 }
1703 // Either all architectures have been specified or none have been specified
1704 // and this does not contain the host architecture so dump all the slices.
1705 bool moreThanOneArch = UB->getNumberOfObjects() > 1;
1706 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
1707 E = UB->end_objects();
1708 I != E; ++I) {
Kevin Enderby9acb1092016-05-31 20:35:34 +00001709 Expected<std::unique_ptr<ObjectFile>> ObjOrErr = I->getAsObjectFile();
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001710 std::string ArchitectureName = "";
1711 if (moreThanOneArch)
1712 ArchitectureName = I->getArchTypeName();
1713 if (ObjOrErr) {
1714 ObjectFile &Obj = *ObjOrErr.get();
1715 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&Obj))
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001716 ProcessMachO(Filename, MachOOF, "", ArchitectureName);
Kevin Enderby9acb1092016-05-31 20:35:34 +00001717 } else if (auto E = isNotObjectErrorInvalidFileType(
1718 ObjOrErr.takeError())) {
1719 report_error(StringRef(), Filename, std::move(E), ArchitectureName);
1720 continue;
Rafael Espindola0bfe8282014-12-09 21:05:36 +00001721 } else if (ErrorOr<std::unique_ptr<Archive>> AOrErr = I->getAsArchive()) {
1722 std::unique_ptr<Archive> &A = *AOrErr;
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001723 outs() << "Archive : " << Filename;
1724 if (!ArchitectureName.empty())
1725 outs() << " (architecture " << ArchitectureName << ")";
1726 outs() << "\n";
Kevin Enderby13023a12015-01-15 23:19:11 +00001727 if (ArchiveHeaders)
Kevin Enderby8972e482015-04-30 20:30:42 +00001728 printArchiveHeaders(A.get(), !NonVerbose, ArchiveMemberOffsets);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001729 for (Archive::child_iterator AI = A->child_begin(), AE = A->child_end();
1730 AI != AE; ++AI) {
Davide Italianob13edeb2015-12-08 02:45:59 +00001731 if (std::error_code EC = AI->getError())
1732 report_error(Filename, EC);
Kevin Enderby7a969422015-11-05 19:24:56 +00001733 auto &C = AI->get();
Kevin Enderbyac9e1552016-05-17 17:10:12 +00001734 Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
1735 if (!ChildOrErr) {
1736 if (auto E = isNotObjectErrorInvalidFileType(ChildOrErr.takeError()))
Kevin Enderby9acb1092016-05-31 20:35:34 +00001737 report_error(Filename, C, std::move(E), ArchitectureName);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001738 continue;
Kevin Enderbyac9e1552016-05-17 17:10:12 +00001739 }
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001740 if (MachOObjectFile *O =
1741 dyn_cast<MachOObjectFile>(&*ChildOrErr.get())) {
1742 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(O))
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001743 ProcessMachO(Filename, MachOOF, MachOOF->getFileName(),
1744 ArchitectureName);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001745 }
1746 }
1747 }
1748 }
1749 return;
1750 }
1751 if (ObjectFile *O = dyn_cast<ObjectFile>(&Bin)) {
1752 if (!checkMachOAndArchFlags(O, Filename))
1753 return;
1754 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&*O)) {
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001755 ProcessMachO(Filename, MachOOF);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001756 } else
1757 errs() << "llvm-objdump: '" << Filename << "': "
1758 << "Object is not a Mach-O file type.\n";
Davide Italiano25d84582016-01-13 04:11:36 +00001759 return;
1760 }
1761 llvm_unreachable("Input object can't be invalid at this point");
Rafael Espindola9b709252013-04-13 01:45:40 +00001762}
1763
Kevin Enderby6f326ce2014-10-23 19:37:31 +00001764typedef std::pair<uint64_t, const char *> BindInfoEntry;
1765typedef std::vector<BindInfoEntry> BindTable;
1766typedef BindTable::iterator bind_table_iterator;
Kevin Enderbybf246f52014-09-24 23:08:22 +00001767
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001768// The block of info used by the Symbolizer call backs.
1769struct DisassembleInfo {
1770 bool verbose;
1771 MachOObjectFile *O;
1772 SectionRef S;
Kevin Enderbybf246f52014-09-24 23:08:22 +00001773 SymbolAddressMap *AddrMap;
Kevin Enderby6f326ce2014-10-23 19:37:31 +00001774 std::vector<SectionRef> *Sections;
1775 const char *class_name;
1776 const char *selector_name;
1777 char *method;
Kevin Enderby04bf6932014-10-28 23:39:46 +00001778 char *demangled_name;
Kevin Enderbyae3c1262014-11-14 21:52:18 +00001779 uint64_t adrp_addr;
1780 uint32_t adrp_inst;
Kevin Enderby078be602014-10-23 19:53:12 +00001781 BindTable *bindtable;
Kevin Enderbyaac75382015-10-08 16:56:35 +00001782 uint32_t depth;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001783};
1784
1785// SymbolizerGetOpInfo() is the operand information call back function.
1786// This is called to get the symbolic information for operand(s) of an
1787// instruction when it is being done. This routine does this from
1788// the relocation information, symbol table, etc. That block of information
1789// is a pointer to the struct DisassembleInfo that was passed when the
1790// disassembler context was created and passed to back to here when
1791// called back by the disassembler for instruction operands that could have
1792// relocation information. The address of the instruction containing operand is
1793// at the Pc parameter. The immediate value the operand has is passed in
1794// op_info->Value and is at Offset past the start of the instruction and has a
1795// byte Size of 1, 2 or 4. The symbolc information is returned in TagBuf is the
1796// LLVMOpInfo1 struct defined in the header "llvm-c/Disassembler.h" as symbol
1797// names and addends of the symbolic expression to add for the operand. The
1798// value of TagType is currently 1 (for the LLVMOpInfo1 struct). If symbolic
1799// information is returned then this function returns 1 else it returns 0.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00001800static int SymbolizerGetOpInfo(void *DisInfo, uint64_t Pc, uint64_t Offset,
1801 uint64_t Size, int TagType, void *TagBuf) {
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001802 struct DisassembleInfo *info = (struct DisassembleInfo *)DisInfo;
1803 struct LLVMOpInfo1 *op_info = (struct LLVMOpInfo1 *)TagBuf;
Kevin Enderbyae3c1262014-11-14 21:52:18 +00001804 uint64_t value = op_info->Value;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001805
1806 // Make sure all fields returned are zero if we don't set them.
1807 memset((void *)op_info, '\0', sizeof(struct LLVMOpInfo1));
1808 op_info->Value = value;
1809
1810 // If the TagType is not the value 1 which it code knows about or if no
1811 // verbose symbolic information is wanted then just return 0, indicating no
1812 // information is being returned.
David Blaikie33dd45d02015-03-23 18:39:02 +00001813 if (TagType != 1 || !info->verbose)
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001814 return 0;
1815
1816 unsigned int Arch = info->O->getArch();
1817 if (Arch == Triple::x86) {
Kevin Enderby9907d0a2014-11-04 00:43:16 +00001818 if (Size != 1 && Size != 2 && Size != 4 && Size != 0)
1819 return 0;
Kevin Enderbyd90a4172015-10-10 00:05:01 +00001820 if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
1821 // TODO:
1822 // Search the external relocation entries of a fully linked image
1823 // (if any) for an entry that matches this segment offset.
1824 // uint32_t seg_offset = (Pc + Offset);
1825 return 0;
1826 }
1827 // In MH_OBJECT filetypes search the section's relocation entries (if any)
1828 // for an entry for this section offset.
Kevin Enderby9907d0a2014-11-04 00:43:16 +00001829 uint32_t sect_addr = info->S.getAddress();
1830 uint32_t sect_offset = (Pc + Offset) - sect_addr;
1831 bool reloc_found = false;
1832 DataRefImpl Rel;
1833 MachO::any_relocation_info RE;
1834 bool isExtern = false;
1835 SymbolRef Symbol;
1836 bool r_scattered = false;
1837 uint32_t r_value, pair_r_value, r_type;
1838 for (const RelocationRef &Reloc : info->S.relocations()) {
Rafael Espindola96d071c2015-06-29 23:29:12 +00001839 uint64_t RelocOffset = Reloc.getOffset();
Kevin Enderby9907d0a2014-11-04 00:43:16 +00001840 if (RelocOffset == sect_offset) {
1841 Rel = Reloc.getRawDataRefImpl();
1842 RE = info->O->getRelocation(Rel);
Kevin Enderby3eb73e12014-11-11 19:16:45 +00001843 r_type = info->O->getAnyRelocationType(RE);
Kevin Enderby9907d0a2014-11-04 00:43:16 +00001844 r_scattered = info->O->isRelocationScattered(RE);
1845 if (r_scattered) {
1846 r_value = info->O->getScatteredRelocationValue(RE);
Kevin Enderby9907d0a2014-11-04 00:43:16 +00001847 if (r_type == MachO::GENERIC_RELOC_SECTDIFF ||
1848 r_type == MachO::GENERIC_RELOC_LOCAL_SECTDIFF) {
1849 DataRefImpl RelNext = Rel;
1850 info->O->moveRelocationNext(RelNext);
1851 MachO::any_relocation_info RENext;
1852 RENext = info->O->getRelocation(RelNext);
1853 if (info->O->isRelocationScattered(RENext))
Kevin Enderby930fdc72014-11-06 19:00:13 +00001854 pair_r_value = info->O->getScatteredRelocationValue(RENext);
Kevin Enderby9907d0a2014-11-04 00:43:16 +00001855 else
1856 return 0;
1857 }
1858 } else {
1859 isExtern = info->O->getPlainRelocationExternal(RE);
1860 if (isExtern) {
1861 symbol_iterator RelocSym = Reloc.getSymbol();
1862 Symbol = *RelocSym;
1863 }
1864 }
1865 reloc_found = true;
1866 break;
1867 }
1868 }
1869 if (reloc_found && isExtern) {
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00001870 Expected<StringRef> SymName = Symbol.getName();
1871 if (!SymName) {
1872 std::string Buf;
1873 raw_string_ostream OS(Buf);
1874 logAllUnhandledErrors(SymName.takeError(), OS, "");
1875 OS.flush();
1876 report_fatal_error(Buf);
1877 }
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00001878 const char *name = SymName->data();
Kevin Enderby9907d0a2014-11-04 00:43:16 +00001879 op_info->AddSymbol.Present = 1;
1880 op_info->AddSymbol.Name = name;
1881 // For i386 extern relocation entries the value in the instruction is
1882 // the offset from the symbol, and value is already set in op_info->Value.
1883 return 1;
1884 }
1885 if (reloc_found && (r_type == MachO::GENERIC_RELOC_SECTDIFF ||
1886 r_type == MachO::GENERIC_RELOC_LOCAL_SECTDIFF)) {
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001887 const char *add = GuessSymbolName(r_value, info->AddrMap);
1888 const char *sub = GuessSymbolName(pair_r_value, info->AddrMap);
Kevin Enderby9907d0a2014-11-04 00:43:16 +00001889 uint32_t offset = value - (r_value - pair_r_value);
1890 op_info->AddSymbol.Present = 1;
1891 if (add != nullptr)
1892 op_info->AddSymbol.Name = add;
1893 else
1894 op_info->AddSymbol.Value = r_value;
1895 op_info->SubtractSymbol.Present = 1;
1896 if (sub != nullptr)
1897 op_info->SubtractSymbol.Name = sub;
1898 else
1899 op_info->SubtractSymbol.Value = pair_r_value;
1900 op_info->Value = offset;
1901 return 1;
1902 }
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001903 return 0;
David Blaikie33dd45d02015-03-23 18:39:02 +00001904 }
1905 if (Arch == Triple::x86_64) {
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001906 if (Size != 1 && Size != 2 && Size != 4 && Size != 0)
1907 return 0;
Kevin Enderbyd90a4172015-10-10 00:05:01 +00001908 if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
1909 // TODO:
1910 // Search the external relocation entries of a fully linked image
1911 // (if any) for an entry that matches this segment offset.
1912 // uint64_t seg_offset = (Pc + Offset);
1913 return 0;
1914 }
1915 // In MH_OBJECT filetypes search the section's relocation entries (if any)
1916 // for an entry for this section offset.
Rafael Espindola80291272014-10-08 15:28:58 +00001917 uint64_t sect_addr = info->S.getAddress();
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001918 uint64_t sect_offset = (Pc + Offset) - sect_addr;
1919 bool reloc_found = false;
1920 DataRefImpl Rel;
1921 MachO::any_relocation_info RE;
1922 bool isExtern = false;
1923 SymbolRef Symbol;
1924 for (const RelocationRef &Reloc : info->S.relocations()) {
Rafael Espindola96d071c2015-06-29 23:29:12 +00001925 uint64_t RelocOffset = Reloc.getOffset();
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001926 if (RelocOffset == sect_offset) {
1927 Rel = Reloc.getRawDataRefImpl();
1928 RE = info->O->getRelocation(Rel);
1929 // NOTE: Scattered relocations don't exist on x86_64.
1930 isExtern = info->O->getPlainRelocationExternal(RE);
1931 if (isExtern) {
1932 symbol_iterator RelocSym = Reloc.getSymbol();
1933 Symbol = *RelocSym;
1934 }
1935 reloc_found = true;
1936 break;
1937 }
1938 }
1939 if (reloc_found && isExtern) {
1940 // The Value passed in will be adjusted by the Pc if the instruction
1941 // adds the Pc. But for x86_64 external relocation entries the Value
1942 // is the offset from the external symbol.
1943 if (info->O->getAnyRelocationPCRel(RE))
1944 op_info->Value -= Pc + Offset + Size;
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00001945 Expected<StringRef> SymName = Symbol.getName();
1946 if (!SymName) {
1947 std::string Buf;
1948 raw_string_ostream OS(Buf);
1949 logAllUnhandledErrors(SymName.takeError(), OS, "");
1950 OS.flush();
1951 report_fatal_error(Buf);
1952 }
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00001953 const char *name = SymName->data();
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001954 unsigned Type = info->O->getAnyRelocationType(RE);
1955 if (Type == MachO::X86_64_RELOC_SUBTRACTOR) {
1956 DataRefImpl RelNext = Rel;
1957 info->O->moveRelocationNext(RelNext);
1958 MachO::any_relocation_info RENext = info->O->getRelocation(RelNext);
1959 unsigned TypeNext = info->O->getAnyRelocationType(RENext);
1960 bool isExternNext = info->O->getPlainRelocationExternal(RENext);
1961 unsigned SymbolNum = info->O->getPlainRelocationSymbolNum(RENext);
1962 if (TypeNext == MachO::X86_64_RELOC_UNSIGNED && isExternNext) {
1963 op_info->SubtractSymbol.Present = 1;
1964 op_info->SubtractSymbol.Name = name;
1965 symbol_iterator RelocSymNext = info->O->getSymbolByIndex(SymbolNum);
1966 Symbol = *RelocSymNext;
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00001967 Expected<StringRef> SymNameNext = Symbol.getName();
1968 if (!SymNameNext) {
1969 std::string Buf;
1970 raw_string_ostream OS(Buf);
1971 logAllUnhandledErrors(SymNameNext.takeError(), OS, "");
1972 OS.flush();
1973 report_fatal_error(Buf);
1974 }
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00001975 name = SymNameNext->data();
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001976 }
1977 }
1978 // TODO: add the VariantKinds to op_info->VariantKind for relocation types
1979 // like: X86_64_RELOC_TLV, X86_64_RELOC_GOT_LOAD and X86_64_RELOC_GOT.
1980 op_info->AddSymbol.Present = 1;
1981 op_info->AddSymbol.Name = name;
1982 return 1;
1983 }
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001984 return 0;
David Blaikie33dd45d02015-03-23 18:39:02 +00001985 }
1986 if (Arch == Triple::arm) {
Kevin Enderby930fdc72014-11-06 19:00:13 +00001987 if (Offset != 0 || (Size != 4 && Size != 2))
1988 return 0;
Kevin Enderbyd90a4172015-10-10 00:05:01 +00001989 if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
1990 // TODO:
1991 // Search the external relocation entries of a fully linked image
1992 // (if any) for an entry that matches this segment offset.
1993 // uint32_t seg_offset = (Pc + Offset);
1994 return 0;
1995 }
1996 // In MH_OBJECT filetypes search the section's relocation entries (if any)
1997 // for an entry for this section offset.
Kevin Enderby930fdc72014-11-06 19:00:13 +00001998 uint32_t sect_addr = info->S.getAddress();
1999 uint32_t sect_offset = (Pc + Offset) - sect_addr;
Kevin Enderby930fdc72014-11-06 19:00:13 +00002000 DataRefImpl Rel;
2001 MachO::any_relocation_info RE;
2002 bool isExtern = false;
2003 SymbolRef Symbol;
2004 bool r_scattered = false;
2005 uint32_t r_value, pair_r_value, r_type, r_length, other_half;
David Blaikie33dd45d02015-03-23 18:39:02 +00002006 auto Reloc =
2007 std::find_if(info->S.relocations().begin(), info->S.relocations().end(),
2008 [&](const RelocationRef &Reloc) {
Rafael Espindola96d071c2015-06-29 23:29:12 +00002009 uint64_t RelocOffset = Reloc.getOffset();
David Blaikie33dd45d02015-03-23 18:39:02 +00002010 return RelocOffset == sect_offset;
2011 });
2012
2013 if (Reloc == info->S.relocations().end())
2014 return 0;
2015
2016 Rel = Reloc->getRawDataRefImpl();
2017 RE = info->O->getRelocation(Rel);
2018 r_length = info->O->getAnyRelocationLength(RE);
2019 r_scattered = info->O->isRelocationScattered(RE);
2020 if (r_scattered) {
2021 r_value = info->O->getScatteredRelocationValue(RE);
2022 r_type = info->O->getScatteredRelocationType(RE);
2023 } else {
2024 r_type = info->O->getAnyRelocationType(RE);
2025 isExtern = info->O->getPlainRelocationExternal(RE);
2026 if (isExtern) {
2027 symbol_iterator RelocSym = Reloc->getSymbol();
2028 Symbol = *RelocSym;
Kevin Enderby930fdc72014-11-06 19:00:13 +00002029 }
2030 }
David Blaikie33dd45d02015-03-23 18:39:02 +00002031 if (r_type == MachO::ARM_RELOC_HALF ||
2032 r_type == MachO::ARM_RELOC_SECTDIFF ||
2033 r_type == MachO::ARM_RELOC_LOCAL_SECTDIFF ||
2034 r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
2035 DataRefImpl RelNext = Rel;
2036 info->O->moveRelocationNext(RelNext);
2037 MachO::any_relocation_info RENext;
2038 RENext = info->O->getRelocation(RelNext);
2039 other_half = info->O->getAnyRelocationAddress(RENext) & 0xffff;
2040 if (info->O->isRelocationScattered(RENext))
2041 pair_r_value = info->O->getScatteredRelocationValue(RENext);
2042 }
2043
2044 if (isExtern) {
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00002045 Expected<StringRef> SymName = Symbol.getName();
2046 if (!SymName) {
2047 std::string Buf;
2048 raw_string_ostream OS(Buf);
2049 logAllUnhandledErrors(SymName.takeError(), OS, "");
2050 OS.flush();
2051 report_fatal_error(Buf);
2052 }
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00002053 const char *name = SymName->data();
Kevin Enderby930fdc72014-11-06 19:00:13 +00002054 op_info->AddSymbol.Present = 1;
2055 op_info->AddSymbol.Name = name;
Sylvestre Ledru648cced2015-02-05 17:00:23 +00002056 switch (r_type) {
2057 case MachO::ARM_RELOC_HALF:
2058 if ((r_length & 0x1) == 1) {
2059 op_info->Value = value << 16 | other_half;
2060 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
2061 } else {
2062 op_info->Value = other_half << 16 | value;
2063 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
Sylvestre Ledrufe0c7ad2015-02-05 16:35:44 +00002064 }
Sylvestre Ledru648cced2015-02-05 17:00:23 +00002065 break;
2066 default:
2067 break;
Kevin Enderby930fdc72014-11-06 19:00:13 +00002068 }
2069 return 1;
2070 }
2071 // If we have a branch that is not an external relocation entry then
2072 // return 0 so the code in tryAddingSymbolicOperand() can use the
2073 // SymbolLookUp call back with the branch target address to look up the
2074 // symbol and possiblity add an annotation for a symbol stub.
David Blaikie33dd45d02015-03-23 18:39:02 +00002075 if (isExtern == 0 && (r_type == MachO::ARM_RELOC_BR24 ||
2076 r_type == MachO::ARM_THUMB_RELOC_BR22))
Kevin Enderby930fdc72014-11-06 19:00:13 +00002077 return 0;
2078
2079 uint32_t offset = 0;
David Blaikie33dd45d02015-03-23 18:39:02 +00002080 if (r_type == MachO::ARM_RELOC_HALF ||
2081 r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
2082 if ((r_length & 0x1) == 1)
2083 value = value << 16 | other_half;
2084 else
2085 value = other_half << 16 | value;
2086 }
2087 if (r_scattered && (r_type != MachO::ARM_RELOC_HALF &&
2088 r_type != MachO::ARM_RELOC_HALF_SECTDIFF)) {
2089 offset = value - r_value;
2090 value = r_value;
Kevin Enderby930fdc72014-11-06 19:00:13 +00002091 }
2092
David Blaikie33dd45d02015-03-23 18:39:02 +00002093 if (r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
Kevin Enderby930fdc72014-11-06 19:00:13 +00002094 if ((r_length & 0x1) == 1)
2095 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
2096 else
2097 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
Kevin Enderbyf6d25852015-01-31 00:37:11 +00002098 const char *add = GuessSymbolName(r_value, info->AddrMap);
2099 const char *sub = GuessSymbolName(pair_r_value, info->AddrMap);
Kevin Enderby930fdc72014-11-06 19:00:13 +00002100 int32_t offset = value - (r_value - pair_r_value);
2101 op_info->AddSymbol.Present = 1;
2102 if (add != nullptr)
2103 op_info->AddSymbol.Name = add;
2104 else
2105 op_info->AddSymbol.Value = r_value;
2106 op_info->SubtractSymbol.Present = 1;
2107 if (sub != nullptr)
2108 op_info->SubtractSymbol.Name = sub;
2109 else
2110 op_info->SubtractSymbol.Value = pair_r_value;
2111 op_info->Value = offset;
2112 return 1;
2113 }
2114
Kevin Enderby930fdc72014-11-06 19:00:13 +00002115 op_info->AddSymbol.Present = 1;
2116 op_info->Value = offset;
David Blaikie33dd45d02015-03-23 18:39:02 +00002117 if (r_type == MachO::ARM_RELOC_HALF) {
2118 if ((r_length & 0x1) == 1)
2119 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
2120 else
2121 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
Kevin Enderby930fdc72014-11-06 19:00:13 +00002122 }
Kevin Enderbyf6d25852015-01-31 00:37:11 +00002123 const char *add = GuessSymbolName(value, info->AddrMap);
Kevin Enderby930fdc72014-11-06 19:00:13 +00002124 if (add != nullptr) {
2125 op_info->AddSymbol.Name = add;
2126 return 1;
2127 }
2128 op_info->AddSymbol.Value = value;
2129 return 1;
David Blaikie33dd45d02015-03-23 18:39:02 +00002130 }
2131 if (Arch == Triple::aarch64) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002132 if (Offset != 0 || Size != 4)
2133 return 0;
Kevin Enderbyd90a4172015-10-10 00:05:01 +00002134 if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
2135 // TODO:
2136 // Search the external relocation entries of a fully linked image
2137 // (if any) for an entry that matches this segment offset.
2138 // uint64_t seg_offset = (Pc + Offset);
2139 return 0;
2140 }
2141 // In MH_OBJECT filetypes search the section's relocation entries (if any)
2142 // for an entry for this section offset.
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002143 uint64_t sect_addr = info->S.getAddress();
2144 uint64_t sect_offset = (Pc + Offset) - sect_addr;
David Blaikie33dd45d02015-03-23 18:39:02 +00002145 auto Reloc =
2146 std::find_if(info->S.relocations().begin(), info->S.relocations().end(),
2147 [&](const RelocationRef &Reloc) {
Rafael Espindola96d071c2015-06-29 23:29:12 +00002148 uint64_t RelocOffset = Reloc.getOffset();
David Blaikie33dd45d02015-03-23 18:39:02 +00002149 return RelocOffset == sect_offset;
2150 });
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002151
David Blaikie33dd45d02015-03-23 18:39:02 +00002152 if (Reloc == info->S.relocations().end())
2153 return 0;
2154
2155 DataRefImpl Rel = Reloc->getRawDataRefImpl();
2156 MachO::any_relocation_info RE = info->O->getRelocation(Rel);
2157 uint32_t r_type = info->O->getAnyRelocationType(RE);
2158 if (r_type == MachO::ARM64_RELOC_ADDEND) {
2159 DataRefImpl RelNext = Rel;
2160 info->O->moveRelocationNext(RelNext);
2161 MachO::any_relocation_info RENext = info->O->getRelocation(RelNext);
2162 if (value == 0) {
2163 value = info->O->getPlainRelocationSymbolNum(RENext);
2164 op_info->Value = value;
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002165 }
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002166 }
David Blaikie33dd45d02015-03-23 18:39:02 +00002167 // NOTE: Scattered relocations don't exist on arm64.
2168 if (!info->O->getPlainRelocationExternal(RE))
2169 return 0;
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00002170 Expected<StringRef> SymName = Reloc->getSymbol()->getName();
2171 if (!SymName) {
2172 std::string Buf;
2173 raw_string_ostream OS(Buf);
2174 logAllUnhandledErrors(SymName.takeError(), OS, "");
2175 OS.flush();
2176 report_fatal_error(Buf);
2177 }
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00002178 const char *name = SymName->data();
David Blaikie33dd45d02015-03-23 18:39:02 +00002179 op_info->AddSymbol.Present = 1;
2180 op_info->AddSymbol.Name = name;
2181
2182 switch (r_type) {
2183 case MachO::ARM64_RELOC_PAGE21:
2184 /* @page */
2185 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_PAGE;
2186 break;
2187 case MachO::ARM64_RELOC_PAGEOFF12:
2188 /* @pageoff */
2189 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_PAGEOFF;
2190 break;
2191 case MachO::ARM64_RELOC_GOT_LOAD_PAGE21:
2192 /* @gotpage */
2193 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_GOTPAGE;
2194 break;
2195 case MachO::ARM64_RELOC_GOT_LOAD_PAGEOFF12:
2196 /* @gotpageoff */
2197 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_GOTPAGEOFF;
2198 break;
2199 case MachO::ARM64_RELOC_TLVP_LOAD_PAGE21:
2200 /* @tvlppage is not implemented in llvm-mc */
2201 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_TLVP;
2202 break;
2203 case MachO::ARM64_RELOC_TLVP_LOAD_PAGEOFF12:
2204 /* @tvlppageoff is not implemented in llvm-mc */
2205 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_TLVOFF;
2206 break;
2207 default:
2208 case MachO::ARM64_RELOC_BRANCH26:
2209 op_info->VariantKind = LLVMDisassembler_VariantKind_None;
2210 break;
2211 }
2212 return 1;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002213 }
David Blaikie33dd45d02015-03-23 18:39:02 +00002214 return 0;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002215}
2216
Kevin Enderbybf246f52014-09-24 23:08:22 +00002217// GuessCstringPointer is passed the address of what might be a pointer to a
2218// literal string in a cstring section. If that address is in a cstring section
2219// it returns a pointer to that string. Else it returns nullptr.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00002220static const char *GuessCstringPointer(uint64_t ReferenceValue,
2221 struct DisassembleInfo *info) {
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00002222 for (const auto &Load : info->O->load_commands()) {
Kevin Enderbybf246f52014-09-24 23:08:22 +00002223 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
2224 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
2225 for (unsigned J = 0; J < Seg.nsects; ++J) {
2226 MachO::section_64 Sec = info->O->getSection64(Load, J);
2227 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
2228 if (section_type == MachO::S_CSTRING_LITERALS &&
2229 ReferenceValue >= Sec.addr &&
2230 ReferenceValue < Sec.addr + Sec.size) {
2231 uint64_t sect_offset = ReferenceValue - Sec.addr;
2232 uint64_t object_offset = Sec.offset + sect_offset;
2233 StringRef MachOContents = info->O->getData();
2234 uint64_t object_size = MachOContents.size();
2235 const char *object_addr = (const char *)MachOContents.data();
2236 if (object_offset < object_size) {
2237 const char *name = object_addr + object_offset;
2238 return name;
2239 } else {
2240 return nullptr;
2241 }
2242 }
2243 }
2244 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
2245 MachO::segment_command Seg = info->O->getSegmentLoadCommand(Load);
2246 for (unsigned J = 0; J < Seg.nsects; ++J) {
2247 MachO::section Sec = info->O->getSection(Load, J);
2248 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
2249 if (section_type == MachO::S_CSTRING_LITERALS &&
2250 ReferenceValue >= Sec.addr &&
2251 ReferenceValue < Sec.addr + Sec.size) {
2252 uint64_t sect_offset = ReferenceValue - Sec.addr;
2253 uint64_t object_offset = Sec.offset + sect_offset;
2254 StringRef MachOContents = info->O->getData();
2255 uint64_t object_size = MachOContents.size();
2256 const char *object_addr = (const char *)MachOContents.data();
2257 if (object_offset < object_size) {
2258 const char *name = object_addr + object_offset;
2259 return name;
2260 } else {
2261 return nullptr;
2262 }
2263 }
2264 }
2265 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00002266 }
2267 return nullptr;
2268}
2269
Kevin Enderby85974882014-09-26 22:20:44 +00002270// GuessIndirectSymbol returns the name of the indirect symbol for the
2271// ReferenceValue passed in or nullptr. This is used when ReferenceValue maybe
2272// an address of a symbol stub or a lazy or non-lazy pointer to associate the
2273// symbol name being referenced by the stub or pointer.
2274static const char *GuessIndirectSymbol(uint64_t ReferenceValue,
2275 struct DisassembleInfo *info) {
Kevin Enderby85974882014-09-26 22:20:44 +00002276 MachO::dysymtab_command Dysymtab = info->O->getDysymtabLoadCommand();
2277 MachO::symtab_command Symtab = info->O->getSymtabLoadCommand();
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00002278 for (const auto &Load : info->O->load_commands()) {
Kevin Enderby85974882014-09-26 22:20:44 +00002279 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
2280 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
2281 for (unsigned J = 0; J < Seg.nsects; ++J) {
2282 MachO::section_64 Sec = info->O->getSection64(Load, J);
2283 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
2284 if ((section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
2285 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
2286 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
2287 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
2288 section_type == MachO::S_SYMBOL_STUBS) &&
2289 ReferenceValue >= Sec.addr &&
2290 ReferenceValue < Sec.addr + Sec.size) {
2291 uint32_t stride;
2292 if (section_type == MachO::S_SYMBOL_STUBS)
2293 stride = Sec.reserved2;
2294 else
2295 stride = 8;
2296 if (stride == 0)
2297 return nullptr;
2298 uint32_t index = Sec.reserved1 + (ReferenceValue - Sec.addr) / stride;
2299 if (index < Dysymtab.nindirectsyms) {
2300 uint32_t indirect_symbol =
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002301 info->O->getIndirectSymbolTableEntry(Dysymtab, index);
Kevin Enderby85974882014-09-26 22:20:44 +00002302 if (indirect_symbol < Symtab.nsyms) {
2303 symbol_iterator Sym = info->O->getSymbolByIndex(indirect_symbol);
2304 SymbolRef Symbol = *Sym;
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00002305 Expected<StringRef> SymName = Symbol.getName();
2306 if (!SymName) {
2307 std::string Buf;
2308 raw_string_ostream OS(Buf);
2309 logAllUnhandledErrors(SymName.takeError(), OS, "");
2310 OS.flush();
2311 report_fatal_error(Buf);
2312 }
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00002313 const char *name = SymName->data();
Kevin Enderby85974882014-09-26 22:20:44 +00002314 return name;
2315 }
2316 }
2317 }
2318 }
2319 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
2320 MachO::segment_command Seg = info->O->getSegmentLoadCommand(Load);
2321 for (unsigned J = 0; J < Seg.nsects; ++J) {
2322 MachO::section Sec = info->O->getSection(Load, J);
2323 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
2324 if ((section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
2325 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
2326 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
2327 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
2328 section_type == MachO::S_SYMBOL_STUBS) &&
2329 ReferenceValue >= Sec.addr &&
2330 ReferenceValue < Sec.addr + Sec.size) {
2331 uint32_t stride;
2332 if (section_type == MachO::S_SYMBOL_STUBS)
2333 stride = Sec.reserved2;
2334 else
2335 stride = 4;
2336 if (stride == 0)
2337 return nullptr;
2338 uint32_t index = Sec.reserved1 + (ReferenceValue - Sec.addr) / stride;
2339 if (index < Dysymtab.nindirectsyms) {
2340 uint32_t indirect_symbol =
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002341 info->O->getIndirectSymbolTableEntry(Dysymtab, index);
Kevin Enderby85974882014-09-26 22:20:44 +00002342 if (indirect_symbol < Symtab.nsyms) {
2343 symbol_iterator Sym = info->O->getSymbolByIndex(indirect_symbol);
2344 SymbolRef Symbol = *Sym;
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00002345 Expected<StringRef> SymName = Symbol.getName();
2346 if (!SymName) {
2347 std::string Buf;
2348 raw_string_ostream OS(Buf);
2349 logAllUnhandledErrors(SymName.takeError(), OS, "");
2350 OS.flush();
2351 report_fatal_error(Buf);
2352 }
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00002353 const char *name = SymName->data();
Kevin Enderby85974882014-09-26 22:20:44 +00002354 return name;
2355 }
2356 }
2357 }
2358 }
2359 }
Kevin Enderby85974882014-09-26 22:20:44 +00002360 }
2361 return nullptr;
2362}
2363
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002364// method_reference() is called passing it the ReferenceName that might be
2365// a reference it to an Objective-C method call. If so then it allocates and
2366// assembles a method call string with the values last seen and saved in
2367// the DisassembleInfo's class_name and selector_name fields. This is saved
2368// into the method field of the info and any previous string is free'ed.
2369// Then the class_name field in the info is set to nullptr. The method call
2370// string is set into ReferenceName and ReferenceType is set to
2371// LLVMDisassembler_ReferenceType_Out_Objc_Message. If this not a method call
2372// then both ReferenceType and ReferenceName are left unchanged.
2373static void method_reference(struct DisassembleInfo *info,
2374 uint64_t *ReferenceType,
2375 const char **ReferenceName) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002376 unsigned int Arch = info->O->getArch();
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002377 if (*ReferenceName != nullptr) {
2378 if (strcmp(*ReferenceName, "_objc_msgSend") == 0) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002379 if (info->selector_name != nullptr) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002380 if (info->method != nullptr)
2381 free(info->method);
2382 if (info->class_name != nullptr) {
2383 info->method = (char *)malloc(5 + strlen(info->class_name) +
2384 strlen(info->selector_name));
2385 if (info->method != nullptr) {
2386 strcpy(info->method, "+[");
2387 strcat(info->method, info->class_name);
2388 strcat(info->method, " ");
2389 strcat(info->method, info->selector_name);
2390 strcat(info->method, "]");
2391 *ReferenceName = info->method;
2392 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
2393 }
2394 } else {
2395 info->method = (char *)malloc(9 + strlen(info->selector_name));
2396 if (info->method != nullptr) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002397 if (Arch == Triple::x86_64)
2398 strcpy(info->method, "-[%rdi ");
2399 else if (Arch == Triple::aarch64)
2400 strcpy(info->method, "-[x0 ");
2401 else
2402 strcpy(info->method, "-[r? ");
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002403 strcat(info->method, info->selector_name);
2404 strcat(info->method, "]");
2405 *ReferenceName = info->method;
2406 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
2407 }
2408 }
2409 info->class_name = nullptr;
2410 }
2411 } else if (strcmp(*ReferenceName, "_objc_msgSendSuper2") == 0) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002412 if (info->selector_name != nullptr) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002413 if (info->method != nullptr)
2414 free(info->method);
2415 info->method = (char *)malloc(17 + strlen(info->selector_name));
2416 if (info->method != nullptr) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002417 if (Arch == Triple::x86_64)
2418 strcpy(info->method, "-[[%rdi super] ");
2419 else if (Arch == Triple::aarch64)
2420 strcpy(info->method, "-[[x0 super] ");
2421 else
2422 strcpy(info->method, "-[[r? super] ");
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002423 strcat(info->method, info->selector_name);
2424 strcat(info->method, "]");
2425 *ReferenceName = info->method;
2426 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
2427 }
2428 info->class_name = nullptr;
2429 }
2430 }
2431 }
2432}
2433
2434// GuessPointerPointer() is passed the address of what might be a pointer to
2435// a reference to an Objective-C class, selector, message ref or cfstring.
2436// If so the value of the pointer is returned and one of the booleans are set
2437// to true. If not zero is returned and all the booleans are set to false.
2438static uint64_t GuessPointerPointer(uint64_t ReferenceValue,
2439 struct DisassembleInfo *info,
2440 bool &classref, bool &selref, bool &msgref,
2441 bool &cfstring) {
2442 classref = false;
2443 selref = false;
2444 msgref = false;
2445 cfstring = false;
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00002446 for (const auto &Load : info->O->load_commands()) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002447 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
2448 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
2449 for (unsigned J = 0; J < Seg.nsects; ++J) {
2450 MachO::section_64 Sec = info->O->getSection64(Load, J);
2451 if ((strncmp(Sec.sectname, "__objc_selrefs", 16) == 0 ||
2452 strncmp(Sec.sectname, "__objc_classrefs", 16) == 0 ||
2453 strncmp(Sec.sectname, "__objc_superrefs", 16) == 0 ||
2454 strncmp(Sec.sectname, "__objc_msgrefs", 16) == 0 ||
2455 strncmp(Sec.sectname, "__cfstring", 16) == 0) &&
2456 ReferenceValue >= Sec.addr &&
2457 ReferenceValue < Sec.addr + Sec.size) {
2458 uint64_t sect_offset = ReferenceValue - Sec.addr;
2459 uint64_t object_offset = Sec.offset + sect_offset;
2460 StringRef MachOContents = info->O->getData();
2461 uint64_t object_size = MachOContents.size();
2462 const char *object_addr = (const char *)MachOContents.data();
2463 if (object_offset < object_size) {
2464 uint64_t pointer_value;
2465 memcpy(&pointer_value, object_addr + object_offset,
2466 sizeof(uint64_t));
2467 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
2468 sys::swapByteOrder(pointer_value);
2469 if (strncmp(Sec.sectname, "__objc_selrefs", 16) == 0)
2470 selref = true;
2471 else if (strncmp(Sec.sectname, "__objc_classrefs", 16) == 0 ||
2472 strncmp(Sec.sectname, "__objc_superrefs", 16) == 0)
2473 classref = true;
2474 else if (strncmp(Sec.sectname, "__objc_msgrefs", 16) == 0 &&
2475 ReferenceValue + 8 < Sec.addr + Sec.size) {
2476 msgref = true;
2477 memcpy(&pointer_value, object_addr + object_offset + 8,
2478 sizeof(uint64_t));
2479 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
2480 sys::swapByteOrder(pointer_value);
2481 } else if (strncmp(Sec.sectname, "__cfstring", 16) == 0)
2482 cfstring = true;
2483 return pointer_value;
2484 } else {
2485 return 0;
2486 }
2487 }
2488 }
2489 }
2490 // TODO: Look for LC_SEGMENT for 32-bit Mach-O files.
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002491 }
2492 return 0;
2493}
2494
2495// get_pointer_64 returns a pointer to the bytes in the object file at the
2496// Address from a section in the Mach-O file. And indirectly returns the
2497// offset into the section, number of bytes left in the section past the offset
2498// and which section is was being referenced. If the Address is not in a
2499// section nullptr is returned.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00002500static const char *get_pointer_64(uint64_t Address, uint32_t &offset,
2501 uint32_t &left, SectionRef &S,
Kevin Enderby846c0002015-04-16 17:19:59 +00002502 DisassembleInfo *info,
2503 bool objc_only = false) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002504 offset = 0;
2505 left = 0;
2506 S = SectionRef();
2507 for (unsigned SectIdx = 0; SectIdx != info->Sections->size(); SectIdx++) {
2508 uint64_t SectAddress = ((*(info->Sections))[SectIdx]).getAddress();
2509 uint64_t SectSize = ((*(info->Sections))[SectIdx]).getSize();
Kevin Enderby46e642f2015-10-08 22:50:55 +00002510 if (SectSize == 0)
2511 continue;
Kevin Enderby846c0002015-04-16 17:19:59 +00002512 if (objc_only) {
2513 StringRef SectName;
2514 ((*(info->Sections))[SectIdx]).getName(SectName);
2515 DataRefImpl Ref = ((*(info->Sections))[SectIdx]).getRawDataRefImpl();
2516 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
2517 if (SegName != "__OBJC" && SectName != "__cstring")
2518 continue;
2519 }
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002520 if (Address >= SectAddress && Address < SectAddress + SectSize) {
2521 S = (*(info->Sections))[SectIdx];
2522 offset = Address - SectAddress;
2523 left = SectSize - offset;
2524 StringRef SectContents;
2525 ((*(info->Sections))[SectIdx]).getContents(SectContents);
2526 return SectContents.data() + offset;
2527 }
2528 }
2529 return nullptr;
2530}
2531
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002532static const char *get_pointer_32(uint32_t Address, uint32_t &offset,
2533 uint32_t &left, SectionRef &S,
Kevin Enderby846c0002015-04-16 17:19:59 +00002534 DisassembleInfo *info,
2535 bool objc_only = false) {
2536 return get_pointer_64(Address, offset, left, S, info, objc_only);
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002537}
2538
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002539// get_symbol_64() returns the name of a symbol (or nullptr) and the address of
2540// the symbol indirectly through n_value. Based on the relocation information
2541// for the specified section offset in the specified section reference.
Kevin Enderby0fc11822015-04-01 20:57:01 +00002542// If no relocation information is found and a non-zero ReferenceValue for the
2543// symbol is passed, look up that address in the info's AddrMap.
Rafael Espindolad7a32ea2015-06-24 10:20:30 +00002544static const char *get_symbol_64(uint32_t sect_offset, SectionRef S,
2545 DisassembleInfo *info, uint64_t &n_value,
Rafael Espindolabe8b0ea2015-07-07 17:12:59 +00002546 uint64_t ReferenceValue = 0) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002547 n_value = 0;
David Blaikie33dd45d02015-03-23 18:39:02 +00002548 if (!info->verbose)
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002549 return nullptr;
2550
2551 // See if there is an external relocation entry at the sect_offset.
2552 bool reloc_found = false;
2553 DataRefImpl Rel;
2554 MachO::any_relocation_info RE;
2555 bool isExtern = false;
2556 SymbolRef Symbol;
2557 for (const RelocationRef &Reloc : S.relocations()) {
Rafael Espindola96d071c2015-06-29 23:29:12 +00002558 uint64_t RelocOffset = Reloc.getOffset();
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002559 if (RelocOffset == sect_offset) {
2560 Rel = Reloc.getRawDataRefImpl();
2561 RE = info->O->getRelocation(Rel);
2562 if (info->O->isRelocationScattered(RE))
2563 continue;
2564 isExtern = info->O->getPlainRelocationExternal(RE);
2565 if (isExtern) {
2566 symbol_iterator RelocSym = Reloc.getSymbol();
2567 Symbol = *RelocSym;
2568 }
2569 reloc_found = true;
2570 break;
2571 }
2572 }
2573 // If there is an external relocation entry for a symbol in this section
2574 // at this section_offset then use that symbol's value for the n_value
2575 // and return its name.
2576 const char *SymbolName = nullptr;
2577 if (reloc_found && isExtern) {
Rafael Espindoladea00162015-07-03 17:44:18 +00002578 n_value = Symbol.getValue();
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00002579 Expected<StringRef> NameOrError = Symbol.getName();
2580 if (!NameOrError) {
2581 std::string Buf;
2582 raw_string_ostream OS(Buf);
2583 logAllUnhandledErrors(NameOrError.takeError(), OS, "");
2584 OS.flush();
2585 report_fatal_error(Buf);
2586 }
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00002587 StringRef Name = *NameOrError;
2588 if (!Name.empty()) {
2589 SymbolName = Name.data();
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002590 return SymbolName;
2591 }
2592 }
2593
2594 // TODO: For fully linked images, look through the external relocation
2595 // entries off the dynamic symtab command. For these the r_offset is from the
2596 // start of the first writeable segment in the Mach-O file. So the offset
2597 // to this section from that segment is passed to this routine by the caller,
2598 // as the database_offset. Which is the difference of the section's starting
2599 // address and the first writable segment.
2600 //
2601 // NOTE: need add passing the database_offset to this routine.
2602
Kevin Enderby0fc11822015-04-01 20:57:01 +00002603 // We did not find an external relocation entry so look up the ReferenceValue
2604 // as an address of a symbol and if found return that symbol's name.
Rafael Espindolabe8b0ea2015-07-07 17:12:59 +00002605 SymbolName = GuessSymbolName(ReferenceValue, info->AddrMap);
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002606
2607 return SymbolName;
2608}
2609
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002610static const char *get_symbol_32(uint32_t sect_offset, SectionRef S,
2611 DisassembleInfo *info,
2612 uint32_t ReferenceValue) {
2613 uint64_t n_value64;
2614 return get_symbol_64(sect_offset, S, info, n_value64, ReferenceValue);
2615}
2616
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002617// These are structs in the Objective-C meta data and read to produce the
2618// comments for disassembly. While these are part of the ABI they are no
2619// public defintions. So the are here not in include/llvm/Support/MachO.h .
2620
2621// The cfstring object in a 64-bit Mach-O file.
2622struct cfstring64_t {
2623 uint64_t isa; // class64_t * (64-bit pointer)
2624 uint64_t flags; // flag bits
2625 uint64_t characters; // char * (64-bit pointer)
2626 uint64_t length; // number of non-NULL characters in above
2627};
2628
2629// The class object in a 64-bit Mach-O file.
2630struct class64_t {
2631 uint64_t isa; // class64_t * (64-bit pointer)
2632 uint64_t superclass; // class64_t * (64-bit pointer)
2633 uint64_t cache; // Cache (64-bit pointer)
2634 uint64_t vtable; // IMP * (64-bit pointer)
2635 uint64_t data; // class_ro64_t * (64-bit pointer)
2636};
2637
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002638struct class32_t {
2639 uint32_t isa; /* class32_t * (32-bit pointer) */
2640 uint32_t superclass; /* class32_t * (32-bit pointer) */
2641 uint32_t cache; /* Cache (32-bit pointer) */
2642 uint32_t vtable; /* IMP * (32-bit pointer) */
2643 uint32_t data; /* class_ro32_t * (32-bit pointer) */
2644};
2645
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002646struct class_ro64_t {
2647 uint32_t flags;
2648 uint32_t instanceStart;
2649 uint32_t instanceSize;
2650 uint32_t reserved;
2651 uint64_t ivarLayout; // const uint8_t * (64-bit pointer)
2652 uint64_t name; // const char * (64-bit pointer)
2653 uint64_t baseMethods; // const method_list_t * (64-bit pointer)
2654 uint64_t baseProtocols; // const protocol_list_t * (64-bit pointer)
2655 uint64_t ivars; // const ivar_list_t * (64-bit pointer)
2656 uint64_t weakIvarLayout; // const uint8_t * (64-bit pointer)
2657 uint64_t baseProperties; // const struct objc_property_list (64-bit pointer)
2658};
2659
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002660struct class_ro32_t {
2661 uint32_t flags;
2662 uint32_t instanceStart;
2663 uint32_t instanceSize;
2664 uint32_t ivarLayout; /* const uint8_t * (32-bit pointer) */
2665 uint32_t name; /* const char * (32-bit pointer) */
2666 uint32_t baseMethods; /* const method_list_t * (32-bit pointer) */
2667 uint32_t baseProtocols; /* const protocol_list_t * (32-bit pointer) */
2668 uint32_t ivars; /* const ivar_list_t * (32-bit pointer) */
2669 uint32_t weakIvarLayout; /* const uint8_t * (32-bit pointer) */
2670 uint32_t baseProperties; /* const struct objc_property_list *
2671 (32-bit pointer) */
2672};
2673
2674/* Values for class_ro{64,32}_t->flags */
Kevin Enderby0fc11822015-04-01 20:57:01 +00002675#define RO_META (1 << 0)
2676#define RO_ROOT (1 << 1)
2677#define RO_HAS_CXX_STRUCTORS (1 << 2)
2678
2679struct method_list64_t {
2680 uint32_t entsize;
2681 uint32_t count;
2682 /* struct method64_t first; These structures follow inline */
2683};
2684
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002685struct method_list32_t {
2686 uint32_t entsize;
2687 uint32_t count;
2688 /* struct method32_t first; These structures follow inline */
2689};
2690
Kevin Enderby0fc11822015-04-01 20:57:01 +00002691struct method64_t {
2692 uint64_t name; /* SEL (64-bit pointer) */
2693 uint64_t types; /* const char * (64-bit pointer) */
2694 uint64_t imp; /* IMP (64-bit pointer) */
2695};
2696
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002697struct method32_t {
2698 uint32_t name; /* SEL (32-bit pointer) */
2699 uint32_t types; /* const char * (32-bit pointer) */
2700 uint32_t imp; /* IMP (32-bit pointer) */
2701};
2702
Kevin Enderby0fc11822015-04-01 20:57:01 +00002703struct protocol_list64_t {
2704 uint64_t count; /* uintptr_t (a 64-bit value) */
2705 /* struct protocol64_t * list[0]; These pointers follow inline */
2706};
2707
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002708struct protocol_list32_t {
2709 uint32_t count; /* uintptr_t (a 32-bit value) */
2710 /* struct protocol32_t * list[0]; These pointers follow inline */
2711};
2712
Kevin Enderby0fc11822015-04-01 20:57:01 +00002713struct protocol64_t {
2714 uint64_t isa; /* id * (64-bit pointer) */
2715 uint64_t name; /* const char * (64-bit pointer) */
2716 uint64_t protocols; /* struct protocol_list64_t *
2717 (64-bit pointer) */
2718 uint64_t instanceMethods; /* method_list_t * (64-bit pointer) */
2719 uint64_t classMethods; /* method_list_t * (64-bit pointer) */
2720 uint64_t optionalInstanceMethods; /* method_list_t * (64-bit pointer) */
2721 uint64_t optionalClassMethods; /* method_list_t * (64-bit pointer) */
2722 uint64_t instanceProperties; /* struct objc_property_list *
2723 (64-bit pointer) */
2724};
2725
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002726struct protocol32_t {
2727 uint32_t isa; /* id * (32-bit pointer) */
2728 uint32_t name; /* const char * (32-bit pointer) */
2729 uint32_t protocols; /* struct protocol_list_t *
2730 (32-bit pointer) */
2731 uint32_t instanceMethods; /* method_list_t * (32-bit pointer) */
2732 uint32_t classMethods; /* method_list_t * (32-bit pointer) */
2733 uint32_t optionalInstanceMethods; /* method_list_t * (32-bit pointer) */
2734 uint32_t optionalClassMethods; /* method_list_t * (32-bit pointer) */
2735 uint32_t instanceProperties; /* struct objc_property_list *
2736 (32-bit pointer) */
2737};
2738
Kevin Enderby0fc11822015-04-01 20:57:01 +00002739struct ivar_list64_t {
2740 uint32_t entsize;
2741 uint32_t count;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002742 /* struct ivar64_t first; These structures follow inline */
2743};
2744
2745struct ivar_list32_t {
2746 uint32_t entsize;
2747 uint32_t count;
2748 /* struct ivar32_t first; These structures follow inline */
Kevin Enderby0fc11822015-04-01 20:57:01 +00002749};
2750
2751struct ivar64_t {
2752 uint64_t offset; /* uintptr_t * (64-bit pointer) */
2753 uint64_t name; /* const char * (64-bit pointer) */
2754 uint64_t type; /* const char * (64-bit pointer) */
2755 uint32_t alignment;
2756 uint32_t size;
2757};
2758
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002759struct ivar32_t {
2760 uint32_t offset; /* uintptr_t * (32-bit pointer) */
2761 uint32_t name; /* const char * (32-bit pointer) */
2762 uint32_t type; /* const char * (32-bit pointer) */
2763 uint32_t alignment;
2764 uint32_t size;
2765};
2766
Kevin Enderby0fc11822015-04-01 20:57:01 +00002767struct objc_property_list64 {
2768 uint32_t entsize;
2769 uint32_t count;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002770 /* struct objc_property64 first; These structures follow inline */
2771};
2772
2773struct objc_property_list32 {
2774 uint32_t entsize;
2775 uint32_t count;
2776 /* struct objc_property32 first; These structures follow inline */
Kevin Enderby0fc11822015-04-01 20:57:01 +00002777};
2778
2779struct objc_property64 {
2780 uint64_t name; /* const char * (64-bit pointer) */
2781 uint64_t attributes; /* const char * (64-bit pointer) */
2782};
2783
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002784struct objc_property32 {
2785 uint32_t name; /* const char * (32-bit pointer) */
2786 uint32_t attributes; /* const char * (32-bit pointer) */
2787};
2788
Kevin Enderby0fc11822015-04-01 20:57:01 +00002789struct category64_t {
2790 uint64_t name; /* const char * (64-bit pointer) */
2791 uint64_t cls; /* struct class_t * (64-bit pointer) */
2792 uint64_t instanceMethods; /* struct method_list_t * (64-bit pointer) */
2793 uint64_t classMethods; /* struct method_list_t * (64-bit pointer) */
2794 uint64_t protocols; /* struct protocol_list_t * (64-bit pointer) */
2795 uint64_t instanceProperties; /* struct objc_property_list *
2796 (64-bit pointer) */
2797};
2798
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002799struct category32_t {
2800 uint32_t name; /* const char * (32-bit pointer) */
2801 uint32_t cls; /* struct class_t * (32-bit pointer) */
2802 uint32_t instanceMethods; /* struct method_list_t * (32-bit pointer) */
2803 uint32_t classMethods; /* struct method_list_t * (32-bit pointer) */
2804 uint32_t protocols; /* struct protocol_list_t * (32-bit pointer) */
2805 uint32_t instanceProperties; /* struct objc_property_list *
2806 (32-bit pointer) */
2807};
2808
Kevin Enderby0fc11822015-04-01 20:57:01 +00002809struct objc_image_info64 {
2810 uint32_t version;
2811 uint32_t flags;
2812};
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002813struct objc_image_info32 {
2814 uint32_t version;
2815 uint32_t flags;
2816};
Kevin Enderby846c0002015-04-16 17:19:59 +00002817struct imageInfo_t {
2818 uint32_t version;
2819 uint32_t flags;
2820};
Kevin Enderby0fc11822015-04-01 20:57:01 +00002821/* masks for objc_image_info.flags */
2822#define OBJC_IMAGE_IS_REPLACEMENT (1 << 0)
2823#define OBJC_IMAGE_SUPPORTS_GC (1 << 1)
2824
2825struct message_ref64 {
2826 uint64_t imp; /* IMP (64-bit pointer) */
2827 uint64_t sel; /* SEL (64-bit pointer) */
2828};
2829
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002830struct message_ref32 {
2831 uint32_t imp; /* IMP (32-bit pointer) */
2832 uint32_t sel; /* SEL (32-bit pointer) */
2833};
2834
Kevin Enderby846c0002015-04-16 17:19:59 +00002835// Objective-C 1 (32-bit only) meta data structs.
2836
2837struct objc_module_t {
2838 uint32_t version;
2839 uint32_t size;
2840 uint32_t name; /* char * (32-bit pointer) */
2841 uint32_t symtab; /* struct objc_symtab * (32-bit pointer) */
2842};
2843
2844struct objc_symtab_t {
2845 uint32_t sel_ref_cnt;
2846 uint32_t refs; /* SEL * (32-bit pointer) */
2847 uint16_t cls_def_cnt;
2848 uint16_t cat_def_cnt;
2849 // uint32_t defs[1]; /* void * (32-bit pointer) variable size */
2850};
2851
2852struct objc_class_t {
2853 uint32_t isa; /* struct objc_class * (32-bit pointer) */
2854 uint32_t super_class; /* struct objc_class * (32-bit pointer) */
2855 uint32_t name; /* const char * (32-bit pointer) */
2856 int32_t version;
2857 int32_t info;
2858 int32_t instance_size;
2859 uint32_t ivars; /* struct objc_ivar_list * (32-bit pointer) */
2860 uint32_t methodLists; /* struct objc_method_list ** (32-bit pointer) */
2861 uint32_t cache; /* struct objc_cache * (32-bit pointer) */
2862 uint32_t protocols; /* struct objc_protocol_list * (32-bit pointer) */
2863};
2864
2865#define CLS_GETINFO(cls, infomask) ((cls)->info & (infomask))
2866// class is not a metaclass
2867#define CLS_CLASS 0x1
2868// class is a metaclass
2869#define CLS_META 0x2
2870
2871struct objc_category_t {
2872 uint32_t category_name; /* char * (32-bit pointer) */
2873 uint32_t class_name; /* char * (32-bit pointer) */
2874 uint32_t instance_methods; /* struct objc_method_list * (32-bit pointer) */
2875 uint32_t class_methods; /* struct objc_method_list * (32-bit pointer) */
2876 uint32_t protocols; /* struct objc_protocol_list * (32-bit ptr) */
2877};
2878
2879struct objc_ivar_t {
2880 uint32_t ivar_name; /* char * (32-bit pointer) */
2881 uint32_t ivar_type; /* char * (32-bit pointer) */
2882 int32_t ivar_offset;
2883};
2884
2885struct objc_ivar_list_t {
2886 int32_t ivar_count;
2887 // struct objc_ivar_t ivar_list[1]; /* variable length structure */
2888};
2889
2890struct objc_method_list_t {
2891 uint32_t obsolete; /* struct objc_method_list * (32-bit pointer) */
2892 int32_t method_count;
2893 // struct objc_method_t method_list[1]; /* variable length structure */
2894};
2895
2896struct objc_method_t {
2897 uint32_t method_name; /* SEL, aka struct objc_selector * (32-bit pointer) */
2898 uint32_t method_types; /* char * (32-bit pointer) */
2899 uint32_t method_imp; /* IMP, aka function pointer, (*IMP)(id, SEL, ...)
2900 (32-bit pointer) */
2901};
2902
2903struct objc_protocol_list_t {
2904 uint32_t next; /* struct objc_protocol_list * (32-bit pointer) */
2905 int32_t count;
2906 // uint32_t list[1]; /* Protocol *, aka struct objc_protocol_t *
2907 // (32-bit pointer) */
2908};
2909
2910struct objc_protocol_t {
2911 uint32_t isa; /* struct objc_class * (32-bit pointer) */
2912 uint32_t protocol_name; /* char * (32-bit pointer) */
2913 uint32_t protocol_list; /* struct objc_protocol_list * (32-bit pointer) */
2914 uint32_t instance_methods; /* struct objc_method_description_list *
2915 (32-bit pointer) */
2916 uint32_t class_methods; /* struct objc_method_description_list *
2917 (32-bit pointer) */
2918};
2919
2920struct objc_method_description_list_t {
2921 int32_t count;
2922 // struct objc_method_description_t list[1];
2923};
2924
2925struct objc_method_description_t {
2926 uint32_t name; /* SEL, aka struct objc_selector * (32-bit pointer) */
2927 uint32_t types; /* char * (32-bit pointer) */
2928};
2929
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002930inline void swapStruct(struct cfstring64_t &cfs) {
2931 sys::swapByteOrder(cfs.isa);
2932 sys::swapByteOrder(cfs.flags);
2933 sys::swapByteOrder(cfs.characters);
2934 sys::swapByteOrder(cfs.length);
2935}
2936
2937inline void swapStruct(struct class64_t &c) {
2938 sys::swapByteOrder(c.isa);
2939 sys::swapByteOrder(c.superclass);
2940 sys::swapByteOrder(c.cache);
2941 sys::swapByteOrder(c.vtable);
2942 sys::swapByteOrder(c.data);
2943}
2944
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002945inline void swapStruct(struct class32_t &c) {
2946 sys::swapByteOrder(c.isa);
2947 sys::swapByteOrder(c.superclass);
2948 sys::swapByteOrder(c.cache);
2949 sys::swapByteOrder(c.vtable);
2950 sys::swapByteOrder(c.data);
2951}
2952
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002953inline void swapStruct(struct class_ro64_t &cro) {
2954 sys::swapByteOrder(cro.flags);
2955 sys::swapByteOrder(cro.instanceStart);
2956 sys::swapByteOrder(cro.instanceSize);
2957 sys::swapByteOrder(cro.reserved);
2958 sys::swapByteOrder(cro.ivarLayout);
2959 sys::swapByteOrder(cro.name);
2960 sys::swapByteOrder(cro.baseMethods);
2961 sys::swapByteOrder(cro.baseProtocols);
2962 sys::swapByteOrder(cro.ivars);
2963 sys::swapByteOrder(cro.weakIvarLayout);
2964 sys::swapByteOrder(cro.baseProperties);
2965}
2966
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002967inline void swapStruct(struct class_ro32_t &cro) {
2968 sys::swapByteOrder(cro.flags);
2969 sys::swapByteOrder(cro.instanceStart);
2970 sys::swapByteOrder(cro.instanceSize);
2971 sys::swapByteOrder(cro.ivarLayout);
2972 sys::swapByteOrder(cro.name);
2973 sys::swapByteOrder(cro.baseMethods);
2974 sys::swapByteOrder(cro.baseProtocols);
2975 sys::swapByteOrder(cro.ivars);
2976 sys::swapByteOrder(cro.weakIvarLayout);
2977 sys::swapByteOrder(cro.baseProperties);
2978}
2979
Kevin Enderby0fc11822015-04-01 20:57:01 +00002980inline void swapStruct(struct method_list64_t &ml) {
2981 sys::swapByteOrder(ml.entsize);
2982 sys::swapByteOrder(ml.count);
2983}
2984
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002985inline void swapStruct(struct method_list32_t &ml) {
2986 sys::swapByteOrder(ml.entsize);
2987 sys::swapByteOrder(ml.count);
2988}
2989
Kevin Enderby0fc11822015-04-01 20:57:01 +00002990inline void swapStruct(struct method64_t &m) {
2991 sys::swapByteOrder(m.name);
2992 sys::swapByteOrder(m.types);
2993 sys::swapByteOrder(m.imp);
2994}
2995
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002996inline void swapStruct(struct method32_t &m) {
2997 sys::swapByteOrder(m.name);
2998 sys::swapByteOrder(m.types);
2999 sys::swapByteOrder(m.imp);
3000}
3001
Kevin Enderby0fc11822015-04-01 20:57:01 +00003002inline void swapStruct(struct protocol_list64_t &pl) {
3003 sys::swapByteOrder(pl.count);
3004}
3005
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003006inline void swapStruct(struct protocol_list32_t &pl) {
3007 sys::swapByteOrder(pl.count);
3008}
3009
Kevin Enderby0fc11822015-04-01 20:57:01 +00003010inline void swapStruct(struct protocol64_t &p) {
3011 sys::swapByteOrder(p.isa);
3012 sys::swapByteOrder(p.name);
3013 sys::swapByteOrder(p.protocols);
3014 sys::swapByteOrder(p.instanceMethods);
3015 sys::swapByteOrder(p.classMethods);
3016 sys::swapByteOrder(p.optionalInstanceMethods);
3017 sys::swapByteOrder(p.optionalClassMethods);
3018 sys::swapByteOrder(p.instanceProperties);
3019}
3020
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003021inline void swapStruct(struct protocol32_t &p) {
3022 sys::swapByteOrder(p.isa);
3023 sys::swapByteOrder(p.name);
3024 sys::swapByteOrder(p.protocols);
3025 sys::swapByteOrder(p.instanceMethods);
3026 sys::swapByteOrder(p.classMethods);
3027 sys::swapByteOrder(p.optionalInstanceMethods);
3028 sys::swapByteOrder(p.optionalClassMethods);
3029 sys::swapByteOrder(p.instanceProperties);
3030}
3031
Kevin Enderby0fc11822015-04-01 20:57:01 +00003032inline void swapStruct(struct ivar_list64_t &il) {
3033 sys::swapByteOrder(il.entsize);
3034 sys::swapByteOrder(il.count);
3035}
3036
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003037inline void swapStruct(struct ivar_list32_t &il) {
3038 sys::swapByteOrder(il.entsize);
3039 sys::swapByteOrder(il.count);
3040}
3041
Kevin Enderby0fc11822015-04-01 20:57:01 +00003042inline void swapStruct(struct ivar64_t &i) {
3043 sys::swapByteOrder(i.offset);
3044 sys::swapByteOrder(i.name);
3045 sys::swapByteOrder(i.type);
3046 sys::swapByteOrder(i.alignment);
3047 sys::swapByteOrder(i.size);
3048}
3049
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003050inline void swapStruct(struct ivar32_t &i) {
3051 sys::swapByteOrder(i.offset);
3052 sys::swapByteOrder(i.name);
3053 sys::swapByteOrder(i.type);
3054 sys::swapByteOrder(i.alignment);
3055 sys::swapByteOrder(i.size);
3056}
3057
Kevin Enderby0fc11822015-04-01 20:57:01 +00003058inline void swapStruct(struct objc_property_list64 &pl) {
3059 sys::swapByteOrder(pl.entsize);
3060 sys::swapByteOrder(pl.count);
3061}
3062
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003063inline void swapStruct(struct objc_property_list32 &pl) {
3064 sys::swapByteOrder(pl.entsize);
3065 sys::swapByteOrder(pl.count);
3066}
3067
Kevin Enderby0fc11822015-04-01 20:57:01 +00003068inline void swapStruct(struct objc_property64 &op) {
3069 sys::swapByteOrder(op.name);
3070 sys::swapByteOrder(op.attributes);
3071}
3072
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003073inline void swapStruct(struct objc_property32 &op) {
3074 sys::swapByteOrder(op.name);
3075 sys::swapByteOrder(op.attributes);
3076}
3077
Kevin Enderby0fc11822015-04-01 20:57:01 +00003078inline void swapStruct(struct category64_t &c) {
3079 sys::swapByteOrder(c.name);
3080 sys::swapByteOrder(c.cls);
3081 sys::swapByteOrder(c.instanceMethods);
3082 sys::swapByteOrder(c.classMethods);
3083 sys::swapByteOrder(c.protocols);
3084 sys::swapByteOrder(c.instanceProperties);
3085}
3086
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003087inline void swapStruct(struct category32_t &c) {
3088 sys::swapByteOrder(c.name);
3089 sys::swapByteOrder(c.cls);
3090 sys::swapByteOrder(c.instanceMethods);
3091 sys::swapByteOrder(c.classMethods);
3092 sys::swapByteOrder(c.protocols);
3093 sys::swapByteOrder(c.instanceProperties);
3094}
3095
Kevin Enderby0fc11822015-04-01 20:57:01 +00003096inline void swapStruct(struct objc_image_info64 &o) {
3097 sys::swapByteOrder(o.version);
3098 sys::swapByteOrder(o.flags);
3099}
3100
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003101inline void swapStruct(struct objc_image_info32 &o) {
3102 sys::swapByteOrder(o.version);
3103 sys::swapByteOrder(o.flags);
3104}
3105
Kevin Enderby846c0002015-04-16 17:19:59 +00003106inline void swapStruct(struct imageInfo_t &o) {
3107 sys::swapByteOrder(o.version);
3108 sys::swapByteOrder(o.flags);
3109}
3110
Kevin Enderby0fc11822015-04-01 20:57:01 +00003111inline void swapStruct(struct message_ref64 &mr) {
3112 sys::swapByteOrder(mr.imp);
3113 sys::swapByteOrder(mr.sel);
3114}
3115
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003116inline void swapStruct(struct message_ref32 &mr) {
3117 sys::swapByteOrder(mr.imp);
3118 sys::swapByteOrder(mr.sel);
3119}
3120
Kevin Enderby846c0002015-04-16 17:19:59 +00003121inline void swapStruct(struct objc_module_t &module) {
3122 sys::swapByteOrder(module.version);
3123 sys::swapByteOrder(module.size);
3124 sys::swapByteOrder(module.name);
3125 sys::swapByteOrder(module.symtab);
Jingyue Wufedecc42015-04-16 18:43:44 +00003126}
Kevin Enderby846c0002015-04-16 17:19:59 +00003127
3128inline void swapStruct(struct objc_symtab_t &symtab) {
3129 sys::swapByteOrder(symtab.sel_ref_cnt);
3130 sys::swapByteOrder(symtab.refs);
3131 sys::swapByteOrder(symtab.cls_def_cnt);
3132 sys::swapByteOrder(symtab.cat_def_cnt);
Jingyue Wufedecc42015-04-16 18:43:44 +00003133}
Kevin Enderby846c0002015-04-16 17:19:59 +00003134
3135inline void swapStruct(struct objc_class_t &objc_class) {
3136 sys::swapByteOrder(objc_class.isa);
3137 sys::swapByteOrder(objc_class.super_class);
3138 sys::swapByteOrder(objc_class.name);
3139 sys::swapByteOrder(objc_class.version);
3140 sys::swapByteOrder(objc_class.info);
3141 sys::swapByteOrder(objc_class.instance_size);
3142 sys::swapByteOrder(objc_class.ivars);
3143 sys::swapByteOrder(objc_class.methodLists);
3144 sys::swapByteOrder(objc_class.cache);
3145 sys::swapByteOrder(objc_class.protocols);
Jingyue Wufedecc42015-04-16 18:43:44 +00003146}
Kevin Enderby846c0002015-04-16 17:19:59 +00003147
3148inline void swapStruct(struct objc_category_t &objc_category) {
3149 sys::swapByteOrder(objc_category.category_name);
3150 sys::swapByteOrder(objc_category.class_name);
3151 sys::swapByteOrder(objc_category.instance_methods);
3152 sys::swapByteOrder(objc_category.class_methods);
3153 sys::swapByteOrder(objc_category.protocols);
3154}
3155
3156inline void swapStruct(struct objc_ivar_list_t &objc_ivar_list) {
3157 sys::swapByteOrder(objc_ivar_list.ivar_count);
3158}
3159
3160inline void swapStruct(struct objc_ivar_t &objc_ivar) {
3161 sys::swapByteOrder(objc_ivar.ivar_name);
3162 sys::swapByteOrder(objc_ivar.ivar_type);
3163 sys::swapByteOrder(objc_ivar.ivar_offset);
Jingyue Wufedecc42015-04-16 18:43:44 +00003164}
Kevin Enderby846c0002015-04-16 17:19:59 +00003165
3166inline void swapStruct(struct objc_method_list_t &method_list) {
3167 sys::swapByteOrder(method_list.obsolete);
3168 sys::swapByteOrder(method_list.method_count);
3169}
3170
3171inline void swapStruct(struct objc_method_t &method) {
3172 sys::swapByteOrder(method.method_name);
3173 sys::swapByteOrder(method.method_types);
3174 sys::swapByteOrder(method.method_imp);
3175}
3176
3177inline void swapStruct(struct objc_protocol_list_t &protocol_list) {
3178 sys::swapByteOrder(protocol_list.next);
3179 sys::swapByteOrder(protocol_list.count);
3180}
3181
3182inline void swapStruct(struct objc_protocol_t &protocol) {
3183 sys::swapByteOrder(protocol.isa);
3184 sys::swapByteOrder(protocol.protocol_name);
3185 sys::swapByteOrder(protocol.protocol_list);
3186 sys::swapByteOrder(protocol.instance_methods);
3187 sys::swapByteOrder(protocol.class_methods);
3188}
3189
3190inline void swapStruct(struct objc_method_description_list_t &mdl) {
3191 sys::swapByteOrder(mdl.count);
3192}
3193
3194inline void swapStruct(struct objc_method_description_t &md) {
3195 sys::swapByteOrder(md.name);
3196 sys::swapByteOrder(md.types);
3197}
3198
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003199static const char *get_dyld_bind_info_symbolname(uint64_t ReferenceValue,
3200 struct DisassembleInfo *info);
3201
3202// get_objc2_64bit_class_name() is used for disassembly and is passed a pointer
3203// to an Objective-C class and returns the class name. It is also passed the
3204// address of the pointer, so when the pointer is zero as it can be in an .o
3205// file, that is used to look for an external relocation entry with a symbol
3206// name.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00003207static const char *get_objc2_64bit_class_name(uint64_t pointer_value,
3208 uint64_t ReferenceValue,
3209 struct DisassembleInfo *info) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003210 const char *r;
3211 uint32_t offset, left;
3212 SectionRef S;
3213
3214 // The pointer_value can be 0 in an object file and have a relocation
3215 // entry for the class symbol at the ReferenceValue (the address of the
3216 // pointer).
3217 if (pointer_value == 0) {
3218 r = get_pointer_64(ReferenceValue, offset, left, S, info);
3219 if (r == nullptr || left < sizeof(uint64_t))
3220 return nullptr;
3221 uint64_t n_value;
3222 const char *symbol_name = get_symbol_64(offset, S, info, n_value);
3223 if (symbol_name == nullptr)
3224 return nullptr;
Hans Wennborgdb53e302014-10-23 21:59:17 +00003225 const char *class_name = strrchr(symbol_name, '$');
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003226 if (class_name != nullptr && class_name[1] == '_' && class_name[2] != '\0')
3227 return class_name + 2;
3228 else
3229 return nullptr;
3230 }
3231
3232 // The case were the pointer_value is non-zero and points to a class defined
3233 // in this Mach-O file.
3234 r = get_pointer_64(pointer_value, offset, left, S, info);
3235 if (r == nullptr || left < sizeof(struct class64_t))
3236 return nullptr;
3237 struct class64_t c;
3238 memcpy(&c, r, sizeof(struct class64_t));
3239 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3240 swapStruct(c);
3241 if (c.data == 0)
3242 return nullptr;
3243 r = get_pointer_64(c.data, offset, left, S, info);
3244 if (r == nullptr || left < sizeof(struct class_ro64_t))
3245 return nullptr;
3246 struct class_ro64_t cro;
3247 memcpy(&cro, r, sizeof(struct class_ro64_t));
3248 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3249 swapStruct(cro);
3250 if (cro.name == 0)
3251 return nullptr;
3252 const char *name = get_pointer_64(cro.name, offset, left, S, info);
3253 return name;
3254}
3255
3256// get_objc2_64bit_cfstring_name is used for disassembly and is passed a
3257// pointer to a cfstring and returns its name or nullptr.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00003258static const char *get_objc2_64bit_cfstring_name(uint64_t ReferenceValue,
3259 struct DisassembleInfo *info) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003260 const char *r, *name;
3261 uint32_t offset, left;
3262 SectionRef S;
3263 struct cfstring64_t cfs;
3264 uint64_t cfs_characters;
3265
3266 r = get_pointer_64(ReferenceValue, offset, left, S, info);
3267 if (r == nullptr || left < sizeof(struct cfstring64_t))
3268 return nullptr;
3269 memcpy(&cfs, r, sizeof(struct cfstring64_t));
3270 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3271 swapStruct(cfs);
3272 if (cfs.characters == 0) {
3273 uint64_t n_value;
3274 const char *symbol_name = get_symbol_64(
3275 offset + offsetof(struct cfstring64_t, characters), S, info, n_value);
3276 if (symbol_name == nullptr)
3277 return nullptr;
3278 cfs_characters = n_value;
3279 } else
3280 cfs_characters = cfs.characters;
3281 name = get_pointer_64(cfs_characters, offset, left, S, info);
3282
3283 return name;
3284}
3285
3286// get_objc2_64bit_selref() is used for disassembly and is passed a the address
3287// of a pointer to an Objective-C selector reference when the pointer value is
3288// zero as in a .o file and is likely to have a external relocation entry with
3289// who's symbol's n_value is the real pointer to the selector name. If that is
3290// the case the real pointer to the selector name is returned else 0 is
3291// returned
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00003292static uint64_t get_objc2_64bit_selref(uint64_t ReferenceValue,
3293 struct DisassembleInfo *info) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003294 uint32_t offset, left;
3295 SectionRef S;
3296
3297 const char *r = get_pointer_64(ReferenceValue, offset, left, S, info);
3298 if (r == nullptr || left < sizeof(uint64_t))
3299 return 0;
3300 uint64_t n_value;
3301 const char *symbol_name = get_symbol_64(offset, S, info, n_value);
3302 if (symbol_name == nullptr)
3303 return 0;
3304 return n_value;
3305}
3306
Kevin Enderby0fc11822015-04-01 20:57:01 +00003307static const SectionRef get_section(MachOObjectFile *O, const char *segname,
3308 const char *sectname) {
3309 for (const SectionRef &Section : O->sections()) {
3310 StringRef SectName;
3311 Section.getName(SectName);
3312 DataRefImpl Ref = Section.getRawDataRefImpl();
3313 StringRef SegName = O->getSectionFinalSegmentName(Ref);
3314 if (SegName == segname && SectName == sectname)
3315 return Section;
3316 }
3317 return SectionRef();
3318}
3319
3320static void
3321walk_pointer_list_64(const char *listname, const SectionRef S,
3322 MachOObjectFile *O, struct DisassembleInfo *info,
3323 void (*func)(uint64_t, struct DisassembleInfo *info)) {
3324 if (S == SectionRef())
3325 return;
3326
3327 StringRef SectName;
3328 S.getName(SectName);
3329 DataRefImpl Ref = S.getRawDataRefImpl();
3330 StringRef SegName = O->getSectionFinalSegmentName(Ref);
3331 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
3332
3333 StringRef BytesStr;
3334 S.getContents(BytesStr);
3335 const char *Contents = reinterpret_cast<const char *>(BytesStr.data());
3336
3337 for (uint32_t i = 0; i < S.getSize(); i += sizeof(uint64_t)) {
3338 uint32_t left = S.getSize() - i;
3339 uint32_t size = left < sizeof(uint64_t) ? left : sizeof(uint64_t);
3340 uint64_t p = 0;
3341 memcpy(&p, Contents + i, size);
3342 if (i + sizeof(uint64_t) > S.getSize())
3343 outs() << listname << " list pointer extends past end of (" << SegName
3344 << "," << SectName << ") section\n";
3345 outs() << format("%016" PRIx64, S.getAddress() + i) << " ";
3346
3347 if (O->isLittleEndian() != sys::IsLittleEndianHost)
3348 sys::swapByteOrder(p);
3349
3350 uint64_t n_value = 0;
3351 const char *name = get_symbol_64(i, S, info, n_value, p);
3352 if (name == nullptr)
3353 name = get_dyld_bind_info_symbolname(S.getAddress() + i, info);
3354
3355 if (n_value != 0) {
3356 outs() << format("0x%" PRIx64, n_value);
3357 if (p != 0)
3358 outs() << " + " << format("0x%" PRIx64, p);
3359 } else
3360 outs() << format("0x%" PRIx64, p);
3361 if (name != nullptr)
3362 outs() << " " << name;
3363 outs() << "\n";
3364
3365 p += n_value;
3366 if (func)
3367 func(p, info);
3368 }
3369}
3370
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003371static void
3372walk_pointer_list_32(const char *listname, const SectionRef S,
3373 MachOObjectFile *O, struct DisassembleInfo *info,
3374 void (*func)(uint32_t, struct DisassembleInfo *info)) {
3375 if (S == SectionRef())
3376 return;
3377
3378 StringRef SectName;
3379 S.getName(SectName);
3380 DataRefImpl Ref = S.getRawDataRefImpl();
3381 StringRef SegName = O->getSectionFinalSegmentName(Ref);
3382 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
3383
3384 StringRef BytesStr;
3385 S.getContents(BytesStr);
3386 const char *Contents = reinterpret_cast<const char *>(BytesStr.data());
3387
3388 for (uint32_t i = 0; i < S.getSize(); i += sizeof(uint32_t)) {
3389 uint32_t left = S.getSize() - i;
3390 uint32_t size = left < sizeof(uint32_t) ? left : sizeof(uint32_t);
3391 uint32_t p = 0;
3392 memcpy(&p, Contents + i, size);
3393 if (i + sizeof(uint32_t) > S.getSize())
3394 outs() << listname << " list pointer extends past end of (" << SegName
3395 << "," << SectName << ") section\n";
Kevin Enderbycf261312015-04-06 22:33:43 +00003396 uint32_t Address = S.getAddress() + i;
3397 outs() << format("%08" PRIx32, Address) << " ";
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003398
3399 if (O->isLittleEndian() != sys::IsLittleEndianHost)
3400 sys::swapByteOrder(p);
3401 outs() << format("0x%" PRIx32, p);
3402
3403 const char *name = get_symbol_32(i, S, info, p);
3404 if (name != nullptr)
3405 outs() << " " << name;
3406 outs() << "\n";
3407
3408 if (func)
3409 func(p, info);
3410 }
3411}
3412
3413static void print_layout_map(const char *layout_map, uint32_t left) {
Kevin Enderbya59824a2015-10-06 22:27:08 +00003414 if (layout_map == nullptr)
3415 return;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003416 outs() << " layout map: ";
3417 do {
3418 outs() << format("0x%02" PRIx32, (*layout_map) & 0xff) << " ";
3419 left--;
3420 layout_map++;
3421 } while (*layout_map != '\0' && left != 0);
3422 outs() << "\n";
3423}
3424
Kevin Enderby0fc11822015-04-01 20:57:01 +00003425static void print_layout_map64(uint64_t p, struct DisassembleInfo *info) {
3426 uint32_t offset, left;
3427 SectionRef S;
3428 const char *layout_map;
3429
3430 if (p == 0)
3431 return;
3432 layout_map = get_pointer_64(p, offset, left, S, info);
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003433 print_layout_map(layout_map, left);
3434}
3435
3436static void print_layout_map32(uint32_t p, struct DisassembleInfo *info) {
3437 uint32_t offset, left;
3438 SectionRef S;
3439 const char *layout_map;
3440
3441 if (p == 0)
3442 return;
3443 layout_map = get_pointer_32(p, offset, left, S, info);
3444 print_layout_map(layout_map, left);
Kevin Enderby0fc11822015-04-01 20:57:01 +00003445}
3446
3447static void print_method_list64_t(uint64_t p, struct DisassembleInfo *info,
3448 const char *indent) {
3449 struct method_list64_t ml;
3450 struct method64_t m;
3451 const char *r;
3452 uint32_t offset, xoffset, left, i;
3453 SectionRef S, xS;
3454 const char *name, *sym_name;
3455 uint64_t n_value;
3456
3457 r = get_pointer_64(p, offset, left, S, info);
3458 if (r == nullptr)
3459 return;
3460 memset(&ml, '\0', sizeof(struct method_list64_t));
3461 if (left < sizeof(struct method_list64_t)) {
3462 memcpy(&ml, r, left);
3463 outs() << " (method_list_t entends past the end of the section)\n";
3464 } else
3465 memcpy(&ml, r, sizeof(struct method_list64_t));
3466 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3467 swapStruct(ml);
3468 outs() << indent << "\t\t entsize " << ml.entsize << "\n";
3469 outs() << indent << "\t\t count " << ml.count << "\n";
3470
3471 p += sizeof(struct method_list64_t);
3472 offset += sizeof(struct method_list64_t);
3473 for (i = 0; i < ml.count; i++) {
3474 r = get_pointer_64(p, offset, left, S, info);
3475 if (r == nullptr)
3476 return;
3477 memset(&m, '\0', sizeof(struct method64_t));
3478 if (left < sizeof(struct method64_t)) {
Kevin Enderbya59824a2015-10-06 22:27:08 +00003479 memcpy(&m, r, left);
3480 outs() << indent << " (method_t extends past the end of the section)\n";
Kevin Enderby0fc11822015-04-01 20:57:01 +00003481 } else
3482 memcpy(&m, r, sizeof(struct method64_t));
3483 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3484 swapStruct(m);
3485
3486 outs() << indent << "\t\t name ";
3487 sym_name = get_symbol_64(offset + offsetof(struct method64_t, name), S,
3488 info, n_value, m.name);
3489 if (n_value != 0) {
3490 if (info->verbose && sym_name != nullptr)
3491 outs() << sym_name;
3492 else
3493 outs() << format("0x%" PRIx64, n_value);
3494 if (m.name != 0)
3495 outs() << " + " << format("0x%" PRIx64, m.name);
3496 } else
3497 outs() << format("0x%" PRIx64, m.name);
3498 name = get_pointer_64(m.name + n_value, xoffset, left, xS, info);
3499 if (name != nullptr)
3500 outs() << format(" %.*s", left, name);
3501 outs() << "\n";
3502
3503 outs() << indent << "\t\t types ";
3504 sym_name = get_symbol_64(offset + offsetof(struct method64_t, types), S,
3505 info, n_value, m.types);
3506 if (n_value != 0) {
3507 if (info->verbose && sym_name != nullptr)
3508 outs() << sym_name;
3509 else
3510 outs() << format("0x%" PRIx64, n_value);
3511 if (m.types != 0)
3512 outs() << " + " << format("0x%" PRIx64, m.types);
3513 } else
3514 outs() << format("0x%" PRIx64, m.types);
3515 name = get_pointer_64(m.types + n_value, xoffset, left, xS, info);
3516 if (name != nullptr)
3517 outs() << format(" %.*s", left, name);
3518 outs() << "\n";
3519
3520 outs() << indent << "\t\t imp ";
3521 name = get_symbol_64(offset + offsetof(struct method64_t, imp), S, info,
3522 n_value, m.imp);
3523 if (info->verbose && name == nullptr) {
3524 if (n_value != 0) {
3525 outs() << format("0x%" PRIx64, n_value) << " ";
3526 if (m.imp != 0)
3527 outs() << "+ " << format("0x%" PRIx64, m.imp) << " ";
3528 } else
3529 outs() << format("0x%" PRIx64, m.imp) << " ";
3530 }
3531 if (name != nullptr)
3532 outs() << name;
3533 outs() << "\n";
3534
3535 p += sizeof(struct method64_t);
3536 offset += sizeof(struct method64_t);
3537 }
3538}
3539
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003540static void print_method_list32_t(uint64_t p, struct DisassembleInfo *info,
3541 const char *indent) {
3542 struct method_list32_t ml;
3543 struct method32_t m;
Kevin Enderby846c0002015-04-16 17:19:59 +00003544 const char *r, *name;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003545 uint32_t offset, xoffset, left, i;
3546 SectionRef S, xS;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003547
3548 r = get_pointer_32(p, offset, left, S, info);
3549 if (r == nullptr)
3550 return;
3551 memset(&ml, '\0', sizeof(struct method_list32_t));
3552 if (left < sizeof(struct method_list32_t)) {
3553 memcpy(&ml, r, left);
3554 outs() << " (method_list_t entends past the end of the section)\n";
3555 } else
3556 memcpy(&ml, r, sizeof(struct method_list32_t));
3557 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3558 swapStruct(ml);
3559 outs() << indent << "\t\t entsize " << ml.entsize << "\n";
3560 outs() << indent << "\t\t count " << ml.count << "\n";
3561
3562 p += sizeof(struct method_list32_t);
3563 offset += sizeof(struct method_list32_t);
3564 for (i = 0; i < ml.count; i++) {
3565 r = get_pointer_32(p, offset, left, S, info);
3566 if (r == nullptr)
3567 return;
3568 memset(&m, '\0', sizeof(struct method32_t));
3569 if (left < sizeof(struct method32_t)) {
3570 memcpy(&ml, r, left);
3571 outs() << indent << " (method_t entends past the end of the section)\n";
3572 } else
3573 memcpy(&m, r, sizeof(struct method32_t));
3574 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3575 swapStruct(m);
3576
3577 outs() << indent << "\t\t name " << format("0x%" PRIx32, m.name);
3578 name = get_pointer_32(m.name, xoffset, left, xS, info);
3579 if (name != nullptr)
3580 outs() << format(" %.*s", left, name);
3581 outs() << "\n";
3582
3583 outs() << indent << "\t\t types " << format("0x%" PRIx32, m.types);
3584 name = get_pointer_32(m.types, xoffset, left, xS, info);
3585 if (name != nullptr)
3586 outs() << format(" %.*s", left, name);
3587 outs() << "\n";
3588
3589 outs() << indent << "\t\t imp " << format("0x%" PRIx32, m.imp);
3590 name = get_symbol_32(offset + offsetof(struct method32_t, imp), S, info,
3591 m.imp);
3592 if (name != nullptr)
3593 outs() << " " << name;
3594 outs() << "\n";
3595
3596 p += sizeof(struct method32_t);
3597 offset += sizeof(struct method32_t);
3598 }
3599}
3600
Kevin Enderby846c0002015-04-16 17:19:59 +00003601static bool print_method_list(uint32_t p, struct DisassembleInfo *info) {
3602 uint32_t offset, left, xleft;
3603 SectionRef S;
3604 struct objc_method_list_t method_list;
3605 struct objc_method_t method;
3606 const char *r, *methods, *name, *SymbolName;
3607 int32_t i;
3608
3609 r = get_pointer_32(p, offset, left, S, info, true);
3610 if (r == nullptr)
3611 return true;
3612
3613 outs() << "\n";
3614 if (left > sizeof(struct objc_method_list_t)) {
3615 memcpy(&method_list, r, sizeof(struct objc_method_list_t));
3616 } else {
3617 outs() << "\t\t objc_method_list extends past end of the section\n";
3618 memset(&method_list, '\0', sizeof(struct objc_method_list_t));
3619 memcpy(&method_list, r, left);
3620 }
3621 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3622 swapStruct(method_list);
3623
3624 outs() << "\t\t obsolete "
3625 << format("0x%08" PRIx32, method_list.obsolete) << "\n";
3626 outs() << "\t\t method_count " << method_list.method_count << "\n";
3627
3628 methods = r + sizeof(struct objc_method_list_t);
3629 for (i = 0; i < method_list.method_count; i++) {
3630 if ((i + 1) * sizeof(struct objc_method_t) > left) {
3631 outs() << "\t\t remaining method's extend past the of the section\n";
3632 break;
3633 }
3634 memcpy(&method, methods + i * sizeof(struct objc_method_t),
3635 sizeof(struct objc_method_t));
3636 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3637 swapStruct(method);
3638
3639 outs() << "\t\t method_name "
3640 << format("0x%08" PRIx32, method.method_name);
3641 if (info->verbose) {
3642 name = get_pointer_32(method.method_name, offset, xleft, S, info, true);
3643 if (name != nullptr)
3644 outs() << format(" %.*s", xleft, name);
3645 else
3646 outs() << " (not in an __OBJC section)";
3647 }
3648 outs() << "\n";
3649
3650 outs() << "\t\t method_types "
3651 << format("0x%08" PRIx32, method.method_types);
3652 if (info->verbose) {
3653 name = get_pointer_32(method.method_types, offset, xleft, S, info, true);
3654 if (name != nullptr)
3655 outs() << format(" %.*s", xleft, name);
3656 else
3657 outs() << " (not in an __OBJC section)";
3658 }
3659 outs() << "\n";
3660
3661 outs() << "\t\t method_imp "
3662 << format("0x%08" PRIx32, method.method_imp) << " ";
3663 if (info->verbose) {
3664 SymbolName = GuessSymbolName(method.method_imp, info->AddrMap);
3665 if (SymbolName != nullptr)
3666 outs() << SymbolName;
3667 }
3668 outs() << "\n";
3669 }
3670 return false;
3671}
3672
Kevin Enderby0fc11822015-04-01 20:57:01 +00003673static void print_protocol_list64_t(uint64_t p, struct DisassembleInfo *info) {
3674 struct protocol_list64_t pl;
3675 uint64_t q, n_value;
3676 struct protocol64_t pc;
3677 const char *r;
3678 uint32_t offset, xoffset, left, i;
3679 SectionRef S, xS;
3680 const char *name, *sym_name;
3681
3682 r = get_pointer_64(p, offset, left, S, info);
3683 if (r == nullptr)
3684 return;
3685 memset(&pl, '\0', sizeof(struct protocol_list64_t));
3686 if (left < sizeof(struct protocol_list64_t)) {
3687 memcpy(&pl, r, left);
3688 outs() << " (protocol_list_t entends past the end of the section)\n";
3689 } else
3690 memcpy(&pl, r, sizeof(struct protocol_list64_t));
3691 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3692 swapStruct(pl);
3693 outs() << " count " << pl.count << "\n";
3694
3695 p += sizeof(struct protocol_list64_t);
3696 offset += sizeof(struct protocol_list64_t);
3697 for (i = 0; i < pl.count; i++) {
3698 r = get_pointer_64(p, offset, left, S, info);
3699 if (r == nullptr)
3700 return;
3701 q = 0;
3702 if (left < sizeof(uint64_t)) {
3703 memcpy(&q, r, left);
3704 outs() << " (protocol_t * entends past the end of the section)\n";
3705 } else
3706 memcpy(&q, r, sizeof(uint64_t));
3707 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3708 sys::swapByteOrder(q);
3709
3710 outs() << "\t\t list[" << i << "] ";
3711 sym_name = get_symbol_64(offset, S, info, n_value, q);
3712 if (n_value != 0) {
3713 if (info->verbose && sym_name != nullptr)
3714 outs() << sym_name;
3715 else
3716 outs() << format("0x%" PRIx64, n_value);
3717 if (q != 0)
3718 outs() << " + " << format("0x%" PRIx64, q);
3719 } else
3720 outs() << format("0x%" PRIx64, q);
3721 outs() << " (struct protocol_t *)\n";
3722
3723 r = get_pointer_64(q + n_value, offset, left, S, info);
3724 if (r == nullptr)
3725 return;
3726 memset(&pc, '\0', sizeof(struct protocol64_t));
3727 if (left < sizeof(struct protocol64_t)) {
3728 memcpy(&pc, r, left);
3729 outs() << " (protocol_t entends past the end of the section)\n";
3730 } else
3731 memcpy(&pc, r, sizeof(struct protocol64_t));
3732 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3733 swapStruct(pc);
3734
3735 outs() << "\t\t\t isa " << format("0x%" PRIx64, pc.isa) << "\n";
3736
3737 outs() << "\t\t\t name ";
3738 sym_name = get_symbol_64(offset + offsetof(struct protocol64_t, name), S,
3739 info, n_value, pc.name);
3740 if (n_value != 0) {
3741 if (info->verbose && sym_name != nullptr)
3742 outs() << sym_name;
3743 else
3744 outs() << format("0x%" PRIx64, n_value);
3745 if (pc.name != 0)
3746 outs() << " + " << format("0x%" PRIx64, pc.name);
3747 } else
3748 outs() << format("0x%" PRIx64, pc.name);
3749 name = get_pointer_64(pc.name + n_value, xoffset, left, xS, info);
3750 if (name != nullptr)
3751 outs() << format(" %.*s", left, name);
3752 outs() << "\n";
3753
3754 outs() << "\t\t\tprotocols " << format("0x%" PRIx64, pc.protocols) << "\n";
3755
3756 outs() << "\t\t instanceMethods ";
3757 sym_name =
3758 get_symbol_64(offset + offsetof(struct protocol64_t, instanceMethods),
3759 S, info, n_value, pc.instanceMethods);
3760 if (n_value != 0) {
3761 if (info->verbose && sym_name != nullptr)
3762 outs() << sym_name;
3763 else
3764 outs() << format("0x%" PRIx64, n_value);
3765 if (pc.instanceMethods != 0)
3766 outs() << " + " << format("0x%" PRIx64, pc.instanceMethods);
3767 } else
3768 outs() << format("0x%" PRIx64, pc.instanceMethods);
3769 outs() << " (struct method_list_t *)\n";
3770 if (pc.instanceMethods + n_value != 0)
3771 print_method_list64_t(pc.instanceMethods + n_value, info, "\t");
3772
3773 outs() << "\t\t classMethods ";
3774 sym_name =
3775 get_symbol_64(offset + offsetof(struct protocol64_t, classMethods), S,
3776 info, n_value, pc.classMethods);
3777 if (n_value != 0) {
3778 if (info->verbose && sym_name != nullptr)
3779 outs() << sym_name;
3780 else
3781 outs() << format("0x%" PRIx64, n_value);
3782 if (pc.classMethods != 0)
3783 outs() << " + " << format("0x%" PRIx64, pc.classMethods);
3784 } else
3785 outs() << format("0x%" PRIx64, pc.classMethods);
3786 outs() << " (struct method_list_t *)\n";
3787 if (pc.classMethods + n_value != 0)
3788 print_method_list64_t(pc.classMethods + n_value, info, "\t");
3789
3790 outs() << "\t optionalInstanceMethods "
3791 << format("0x%" PRIx64, pc.optionalInstanceMethods) << "\n";
3792 outs() << "\t optionalClassMethods "
3793 << format("0x%" PRIx64, pc.optionalClassMethods) << "\n";
3794 outs() << "\t instanceProperties "
3795 << format("0x%" PRIx64, pc.instanceProperties) << "\n";
3796
3797 p += sizeof(uint64_t);
3798 offset += sizeof(uint64_t);
3799 }
3800}
3801
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003802static void print_protocol_list32_t(uint32_t p, struct DisassembleInfo *info) {
3803 struct protocol_list32_t pl;
3804 uint32_t q;
3805 struct protocol32_t pc;
3806 const char *r;
3807 uint32_t offset, xoffset, left, i;
3808 SectionRef S, xS;
3809 const char *name;
3810
3811 r = get_pointer_32(p, offset, left, S, info);
3812 if (r == nullptr)
3813 return;
3814 memset(&pl, '\0', sizeof(struct protocol_list32_t));
3815 if (left < sizeof(struct protocol_list32_t)) {
3816 memcpy(&pl, r, left);
3817 outs() << " (protocol_list_t entends past the end of the section)\n";
3818 } else
3819 memcpy(&pl, r, sizeof(struct protocol_list32_t));
3820 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3821 swapStruct(pl);
3822 outs() << " count " << pl.count << "\n";
3823
3824 p += sizeof(struct protocol_list32_t);
3825 offset += sizeof(struct protocol_list32_t);
3826 for (i = 0; i < pl.count; i++) {
3827 r = get_pointer_32(p, offset, left, S, info);
3828 if (r == nullptr)
3829 return;
3830 q = 0;
3831 if (left < sizeof(uint32_t)) {
3832 memcpy(&q, r, left);
3833 outs() << " (protocol_t * entends past the end of the section)\n";
3834 } else
3835 memcpy(&q, r, sizeof(uint32_t));
3836 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3837 sys::swapByteOrder(q);
3838 outs() << "\t\t list[" << i << "] " << format("0x%" PRIx32, q)
3839 << " (struct protocol_t *)\n";
3840 r = get_pointer_32(q, offset, left, S, info);
3841 if (r == nullptr)
3842 return;
3843 memset(&pc, '\0', sizeof(struct protocol32_t));
3844 if (left < sizeof(struct protocol32_t)) {
3845 memcpy(&pc, r, left);
3846 outs() << " (protocol_t entends past the end of the section)\n";
3847 } else
3848 memcpy(&pc, r, sizeof(struct protocol32_t));
3849 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3850 swapStruct(pc);
3851 outs() << "\t\t\t isa " << format("0x%" PRIx32, pc.isa) << "\n";
3852 outs() << "\t\t\t name " << format("0x%" PRIx32, pc.name);
3853 name = get_pointer_32(pc.name, xoffset, left, xS, info);
3854 if (name != nullptr)
3855 outs() << format(" %.*s", left, name);
3856 outs() << "\n";
3857 outs() << "\t\t\tprotocols " << format("0x%" PRIx32, pc.protocols) << "\n";
3858 outs() << "\t\t instanceMethods "
3859 << format("0x%" PRIx32, pc.instanceMethods)
3860 << " (struct method_list_t *)\n";
3861 if (pc.instanceMethods != 0)
3862 print_method_list32_t(pc.instanceMethods, info, "\t");
3863 outs() << "\t\t classMethods " << format("0x%" PRIx32, pc.classMethods)
3864 << " (struct method_list_t *)\n";
3865 if (pc.classMethods != 0)
3866 print_method_list32_t(pc.classMethods, info, "\t");
3867 outs() << "\t optionalInstanceMethods "
3868 << format("0x%" PRIx32, pc.optionalInstanceMethods) << "\n";
3869 outs() << "\t optionalClassMethods "
3870 << format("0x%" PRIx32, pc.optionalClassMethods) << "\n";
3871 outs() << "\t instanceProperties "
3872 << format("0x%" PRIx32, pc.instanceProperties) << "\n";
3873 p += sizeof(uint32_t);
3874 offset += sizeof(uint32_t);
3875 }
3876}
3877
Kevin Enderby846c0002015-04-16 17:19:59 +00003878static void print_indent(uint32_t indent) {
3879 for (uint32_t i = 0; i < indent;) {
3880 if (indent - i >= 8) {
3881 outs() << "\t";
3882 i += 8;
3883 } else {
3884 for (uint32_t j = i; j < indent; j++)
3885 outs() << " ";
3886 return;
3887 }
3888 }
3889}
3890
3891static bool print_method_description_list(uint32_t p, uint32_t indent,
3892 struct DisassembleInfo *info) {
3893 uint32_t offset, left, xleft;
3894 SectionRef S;
3895 struct objc_method_description_list_t mdl;
3896 struct objc_method_description_t md;
3897 const char *r, *list, *name;
3898 int32_t i;
3899
3900 r = get_pointer_32(p, offset, left, S, info, true);
3901 if (r == nullptr)
3902 return true;
3903
3904 outs() << "\n";
3905 if (left > sizeof(struct objc_method_description_list_t)) {
3906 memcpy(&mdl, r, sizeof(struct objc_method_description_list_t));
3907 } else {
3908 print_indent(indent);
3909 outs() << " objc_method_description_list extends past end of the section\n";
3910 memset(&mdl, '\0', sizeof(struct objc_method_description_list_t));
3911 memcpy(&mdl, r, left);
3912 }
3913 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3914 swapStruct(mdl);
3915
3916 print_indent(indent);
3917 outs() << " count " << mdl.count << "\n";
3918
3919 list = r + sizeof(struct objc_method_description_list_t);
3920 for (i = 0; i < mdl.count; i++) {
3921 if ((i + 1) * sizeof(struct objc_method_description_t) > left) {
3922 print_indent(indent);
3923 outs() << " remaining list entries extend past the of the section\n";
3924 break;
3925 }
3926 print_indent(indent);
3927 outs() << " list[" << i << "]\n";
3928 memcpy(&md, list + i * sizeof(struct objc_method_description_t),
3929 sizeof(struct objc_method_description_t));
3930 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3931 swapStruct(md);
3932
3933 print_indent(indent);
3934 outs() << " name " << format("0x%08" PRIx32, md.name);
3935 if (info->verbose) {
3936 name = get_pointer_32(md.name, offset, xleft, S, info, true);
3937 if (name != nullptr)
3938 outs() << format(" %.*s", xleft, name);
3939 else
3940 outs() << " (not in an __OBJC section)";
3941 }
3942 outs() << "\n";
3943
3944 print_indent(indent);
3945 outs() << " types " << format("0x%08" PRIx32, md.types);
3946 if (info->verbose) {
3947 name = get_pointer_32(md.types, offset, xleft, S, info, true);
3948 if (name != nullptr)
3949 outs() << format(" %.*s", xleft, name);
3950 else
3951 outs() << " (not in an __OBJC section)";
3952 }
3953 outs() << "\n";
3954 }
3955 return false;
3956}
3957
3958static bool print_protocol_list(uint32_t p, uint32_t indent,
3959 struct DisassembleInfo *info);
3960
3961static bool print_protocol(uint32_t p, uint32_t indent,
3962 struct DisassembleInfo *info) {
3963 uint32_t offset, left;
3964 SectionRef S;
3965 struct objc_protocol_t protocol;
3966 const char *r, *name;
3967
3968 r = get_pointer_32(p, offset, left, S, info, true);
3969 if (r == nullptr)
3970 return true;
3971
3972 outs() << "\n";
3973 if (left >= sizeof(struct objc_protocol_t)) {
3974 memcpy(&protocol, r, sizeof(struct objc_protocol_t));
3975 } else {
3976 print_indent(indent);
3977 outs() << " Protocol extends past end of the section\n";
3978 memset(&protocol, '\0', sizeof(struct objc_protocol_t));
3979 memcpy(&protocol, r, left);
3980 }
3981 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3982 swapStruct(protocol);
3983
3984 print_indent(indent);
3985 outs() << " isa " << format("0x%08" PRIx32, protocol.isa)
3986 << "\n";
3987
3988 print_indent(indent);
3989 outs() << " protocol_name "
3990 << format("0x%08" PRIx32, protocol.protocol_name);
3991 if (info->verbose) {
3992 name = get_pointer_32(protocol.protocol_name, offset, left, S, info, true);
3993 if (name != nullptr)
3994 outs() << format(" %.*s", left, name);
3995 else
3996 outs() << " (not in an __OBJC section)";
3997 }
3998 outs() << "\n";
3999
4000 print_indent(indent);
4001 outs() << " protocol_list "
4002 << format("0x%08" PRIx32, protocol.protocol_list);
4003 if (print_protocol_list(protocol.protocol_list, indent + 4, info))
4004 outs() << " (not in an __OBJC section)\n";
4005
4006 print_indent(indent);
4007 outs() << " instance_methods "
4008 << format("0x%08" PRIx32, protocol.instance_methods);
4009 if (print_method_description_list(protocol.instance_methods, indent, info))
4010 outs() << " (not in an __OBJC section)\n";
4011
4012 print_indent(indent);
4013 outs() << " class_methods "
4014 << format("0x%08" PRIx32, protocol.class_methods);
4015 if (print_method_description_list(protocol.class_methods, indent, info))
4016 outs() << " (not in an __OBJC section)\n";
4017
4018 return false;
4019}
4020
4021static bool print_protocol_list(uint32_t p, uint32_t indent,
4022 struct DisassembleInfo *info) {
4023 uint32_t offset, left, l;
4024 SectionRef S;
4025 struct objc_protocol_list_t protocol_list;
4026 const char *r, *list;
4027 int32_t i;
4028
4029 r = get_pointer_32(p, offset, left, S, info, true);
4030 if (r == nullptr)
4031 return true;
4032
4033 outs() << "\n";
4034 if (left > sizeof(struct objc_protocol_list_t)) {
4035 memcpy(&protocol_list, r, sizeof(struct objc_protocol_list_t));
4036 } else {
4037 outs() << "\t\t objc_protocol_list_t extends past end of the section\n";
4038 memset(&protocol_list, '\0', sizeof(struct objc_protocol_list_t));
4039 memcpy(&protocol_list, r, left);
4040 }
4041 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4042 swapStruct(protocol_list);
4043
4044 print_indent(indent);
4045 outs() << " next " << format("0x%08" PRIx32, protocol_list.next)
4046 << "\n";
4047 print_indent(indent);
4048 outs() << " count " << protocol_list.count << "\n";
4049
4050 list = r + sizeof(struct objc_protocol_list_t);
4051 for (i = 0; i < protocol_list.count; i++) {
4052 if ((i + 1) * sizeof(uint32_t) > left) {
4053 outs() << "\t\t remaining list entries extend past the of the section\n";
4054 break;
4055 }
4056 memcpy(&l, list + i * sizeof(uint32_t), sizeof(uint32_t));
4057 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4058 sys::swapByteOrder(l);
4059
4060 print_indent(indent);
4061 outs() << " list[" << i << "] " << format("0x%08" PRIx32, l);
4062 if (print_protocol(l, indent, info))
4063 outs() << "(not in an __OBJC section)\n";
4064 }
4065 return false;
4066}
4067
Kevin Enderby0fc11822015-04-01 20:57:01 +00004068static void print_ivar_list64_t(uint64_t p, struct DisassembleInfo *info) {
4069 struct ivar_list64_t il;
4070 struct ivar64_t i;
4071 const char *r;
4072 uint32_t offset, xoffset, left, j;
4073 SectionRef S, xS;
4074 const char *name, *sym_name, *ivar_offset_p;
4075 uint64_t ivar_offset, n_value;
4076
4077 r = get_pointer_64(p, offset, left, S, info);
4078 if (r == nullptr)
4079 return;
4080 memset(&il, '\0', sizeof(struct ivar_list64_t));
4081 if (left < sizeof(struct ivar_list64_t)) {
4082 memcpy(&il, r, left);
4083 outs() << " (ivar_list_t entends past the end of the section)\n";
4084 } else
4085 memcpy(&il, r, sizeof(struct ivar_list64_t));
4086 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4087 swapStruct(il);
4088 outs() << " entsize " << il.entsize << "\n";
4089 outs() << " count " << il.count << "\n";
4090
4091 p += sizeof(struct ivar_list64_t);
4092 offset += sizeof(struct ivar_list64_t);
4093 for (j = 0; j < il.count; j++) {
4094 r = get_pointer_64(p, offset, left, S, info);
4095 if (r == nullptr)
4096 return;
4097 memset(&i, '\0', sizeof(struct ivar64_t));
4098 if (left < sizeof(struct ivar64_t)) {
4099 memcpy(&i, r, left);
4100 outs() << " (ivar_t entends past the end of the section)\n";
4101 } else
4102 memcpy(&i, r, sizeof(struct ivar64_t));
4103 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4104 swapStruct(i);
4105
4106 outs() << "\t\t\t offset ";
4107 sym_name = get_symbol_64(offset + offsetof(struct ivar64_t, offset), S,
4108 info, n_value, i.offset);
4109 if (n_value != 0) {
4110 if (info->verbose && sym_name != nullptr)
4111 outs() << sym_name;
4112 else
4113 outs() << format("0x%" PRIx64, n_value);
4114 if (i.offset != 0)
4115 outs() << " + " << format("0x%" PRIx64, i.offset);
4116 } else
4117 outs() << format("0x%" PRIx64, i.offset);
4118 ivar_offset_p = get_pointer_64(i.offset + n_value, xoffset, left, xS, info);
4119 if (ivar_offset_p != nullptr && left >= sizeof(*ivar_offset_p)) {
4120 memcpy(&ivar_offset, ivar_offset_p, sizeof(ivar_offset));
4121 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4122 sys::swapByteOrder(ivar_offset);
4123 outs() << " " << ivar_offset << "\n";
4124 } else
4125 outs() << "\n";
4126
4127 outs() << "\t\t\t name ";
4128 sym_name = get_symbol_64(offset + offsetof(struct ivar64_t, name), S, info,
4129 n_value, i.name);
4130 if (n_value != 0) {
4131 if (info->verbose && sym_name != nullptr)
4132 outs() << sym_name;
4133 else
4134 outs() << format("0x%" PRIx64, n_value);
4135 if (i.name != 0)
4136 outs() << " + " << format("0x%" PRIx64, i.name);
4137 } else
4138 outs() << format("0x%" PRIx64, i.name);
4139 name = get_pointer_64(i.name + n_value, xoffset, left, xS, info);
4140 if (name != nullptr)
4141 outs() << format(" %.*s", left, name);
4142 outs() << "\n";
4143
4144 outs() << "\t\t\t type ";
4145 sym_name = get_symbol_64(offset + offsetof(struct ivar64_t, type), S, info,
4146 n_value, i.name);
4147 name = get_pointer_64(i.type + n_value, xoffset, left, xS, info);
4148 if (n_value != 0) {
4149 if (info->verbose && sym_name != nullptr)
4150 outs() << sym_name;
4151 else
4152 outs() << format("0x%" PRIx64, n_value);
4153 if (i.type != 0)
4154 outs() << " + " << format("0x%" PRIx64, i.type);
4155 } else
4156 outs() << format("0x%" PRIx64, i.type);
4157 if (name != nullptr)
4158 outs() << format(" %.*s", left, name);
4159 outs() << "\n";
4160
4161 outs() << "\t\t\talignment " << i.alignment << "\n";
4162 outs() << "\t\t\t size " << i.size << "\n";
4163
4164 p += sizeof(struct ivar64_t);
4165 offset += sizeof(struct ivar64_t);
4166 }
4167}
4168
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004169static void print_ivar_list32_t(uint32_t p, struct DisassembleInfo *info) {
4170 struct ivar_list32_t il;
4171 struct ivar32_t i;
4172 const char *r;
4173 uint32_t offset, xoffset, left, j;
4174 SectionRef S, xS;
4175 const char *name, *ivar_offset_p;
4176 uint32_t ivar_offset;
4177
4178 r = get_pointer_32(p, offset, left, S, info);
4179 if (r == nullptr)
4180 return;
4181 memset(&il, '\0', sizeof(struct ivar_list32_t));
4182 if (left < sizeof(struct ivar_list32_t)) {
4183 memcpy(&il, r, left);
4184 outs() << " (ivar_list_t entends past the end of the section)\n";
4185 } else
4186 memcpy(&il, r, sizeof(struct ivar_list32_t));
4187 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4188 swapStruct(il);
4189 outs() << " entsize " << il.entsize << "\n";
4190 outs() << " count " << il.count << "\n";
4191
4192 p += sizeof(struct ivar_list32_t);
4193 offset += sizeof(struct ivar_list32_t);
4194 for (j = 0; j < il.count; j++) {
4195 r = get_pointer_32(p, offset, left, S, info);
4196 if (r == nullptr)
4197 return;
4198 memset(&i, '\0', sizeof(struct ivar32_t));
4199 if (left < sizeof(struct ivar32_t)) {
4200 memcpy(&i, r, left);
4201 outs() << " (ivar_t entends past the end of the section)\n";
4202 } else
4203 memcpy(&i, r, sizeof(struct ivar32_t));
4204 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4205 swapStruct(i);
4206
4207 outs() << "\t\t\t offset " << format("0x%" PRIx32, i.offset);
4208 ivar_offset_p = get_pointer_32(i.offset, xoffset, left, xS, info);
4209 if (ivar_offset_p != nullptr && left >= sizeof(*ivar_offset_p)) {
4210 memcpy(&ivar_offset, ivar_offset_p, sizeof(ivar_offset));
4211 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4212 sys::swapByteOrder(ivar_offset);
4213 outs() << " " << ivar_offset << "\n";
4214 } else
4215 outs() << "\n";
4216
4217 outs() << "\t\t\t name " << format("0x%" PRIx32, i.name);
4218 name = get_pointer_32(i.name, xoffset, left, xS, info);
4219 if (name != nullptr)
4220 outs() << format(" %.*s", left, name);
4221 outs() << "\n";
4222
4223 outs() << "\t\t\t type " << format("0x%" PRIx32, i.type);
4224 name = get_pointer_32(i.type, xoffset, left, xS, info);
4225 if (name != nullptr)
4226 outs() << format(" %.*s", left, name);
4227 outs() << "\n";
4228
4229 outs() << "\t\t\talignment " << i.alignment << "\n";
4230 outs() << "\t\t\t size " << i.size << "\n";
4231
4232 p += sizeof(struct ivar32_t);
4233 offset += sizeof(struct ivar32_t);
4234 }
4235}
4236
Kevin Enderby0fc11822015-04-01 20:57:01 +00004237static void print_objc_property_list64(uint64_t p,
4238 struct DisassembleInfo *info) {
4239 struct objc_property_list64 opl;
4240 struct objc_property64 op;
4241 const char *r;
4242 uint32_t offset, xoffset, left, j;
4243 SectionRef S, xS;
4244 const char *name, *sym_name;
4245 uint64_t n_value;
4246
4247 r = get_pointer_64(p, offset, left, S, info);
4248 if (r == nullptr)
4249 return;
4250 memset(&opl, '\0', sizeof(struct objc_property_list64));
4251 if (left < sizeof(struct objc_property_list64)) {
4252 memcpy(&opl, r, left);
4253 outs() << " (objc_property_list entends past the end of the section)\n";
4254 } else
4255 memcpy(&opl, r, sizeof(struct objc_property_list64));
4256 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4257 swapStruct(opl);
4258 outs() << " entsize " << opl.entsize << "\n";
4259 outs() << " count " << opl.count << "\n";
4260
4261 p += sizeof(struct objc_property_list64);
4262 offset += sizeof(struct objc_property_list64);
4263 for (j = 0; j < opl.count; j++) {
4264 r = get_pointer_64(p, offset, left, S, info);
4265 if (r == nullptr)
4266 return;
4267 memset(&op, '\0', sizeof(struct objc_property64));
4268 if (left < sizeof(struct objc_property64)) {
4269 memcpy(&op, r, left);
4270 outs() << " (objc_property entends past the end of the section)\n";
4271 } else
4272 memcpy(&op, r, sizeof(struct objc_property64));
4273 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4274 swapStruct(op);
4275
4276 outs() << "\t\t\t name ";
4277 sym_name = get_symbol_64(offset + offsetof(struct objc_property64, name), S,
4278 info, n_value, op.name);
4279 if (n_value != 0) {
4280 if (info->verbose && sym_name != nullptr)
4281 outs() << sym_name;
4282 else
4283 outs() << format("0x%" PRIx64, n_value);
4284 if (op.name != 0)
4285 outs() << " + " << format("0x%" PRIx64, op.name);
4286 } else
4287 outs() << format("0x%" PRIx64, op.name);
4288 name = get_pointer_64(op.name + n_value, xoffset, left, xS, info);
4289 if (name != nullptr)
4290 outs() << format(" %.*s", left, name);
4291 outs() << "\n";
4292
4293 outs() << "\t\t\tattributes ";
4294 sym_name =
4295 get_symbol_64(offset + offsetof(struct objc_property64, attributes), S,
4296 info, n_value, op.attributes);
4297 if (n_value != 0) {
4298 if (info->verbose && sym_name != nullptr)
4299 outs() << sym_name;
4300 else
4301 outs() << format("0x%" PRIx64, n_value);
4302 if (op.attributes != 0)
4303 outs() << " + " << format("0x%" PRIx64, op.attributes);
4304 } else
4305 outs() << format("0x%" PRIx64, op.attributes);
4306 name = get_pointer_64(op.attributes + n_value, xoffset, left, xS, info);
4307 if (name != nullptr)
4308 outs() << format(" %.*s", left, name);
4309 outs() << "\n";
4310
4311 p += sizeof(struct objc_property64);
4312 offset += sizeof(struct objc_property64);
4313 }
4314}
4315
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004316static void print_objc_property_list32(uint32_t p,
4317 struct DisassembleInfo *info) {
4318 struct objc_property_list32 opl;
4319 struct objc_property32 op;
4320 const char *r;
4321 uint32_t offset, xoffset, left, j;
4322 SectionRef S, xS;
4323 const char *name;
4324
4325 r = get_pointer_32(p, offset, left, S, info);
4326 if (r == nullptr)
4327 return;
4328 memset(&opl, '\0', sizeof(struct objc_property_list32));
4329 if (left < sizeof(struct objc_property_list32)) {
4330 memcpy(&opl, r, left);
4331 outs() << " (objc_property_list entends past the end of the section)\n";
4332 } else
4333 memcpy(&opl, r, sizeof(struct objc_property_list32));
4334 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4335 swapStruct(opl);
4336 outs() << " entsize " << opl.entsize << "\n";
4337 outs() << " count " << opl.count << "\n";
4338
4339 p += sizeof(struct objc_property_list32);
4340 offset += sizeof(struct objc_property_list32);
4341 for (j = 0; j < opl.count; j++) {
4342 r = get_pointer_32(p, offset, left, S, info);
4343 if (r == nullptr)
4344 return;
4345 memset(&op, '\0', sizeof(struct objc_property32));
4346 if (left < sizeof(struct objc_property32)) {
4347 memcpy(&op, r, left);
4348 outs() << " (objc_property entends past the end of the section)\n";
4349 } else
4350 memcpy(&op, r, sizeof(struct objc_property32));
4351 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4352 swapStruct(op);
4353
4354 outs() << "\t\t\t name " << format("0x%" PRIx32, op.name);
4355 name = get_pointer_32(op.name, xoffset, left, xS, info);
4356 if (name != nullptr)
4357 outs() << format(" %.*s", left, name);
4358 outs() << "\n";
4359
4360 outs() << "\t\t\tattributes " << format("0x%" PRIx32, op.attributes);
4361 name = get_pointer_32(op.attributes, xoffset, left, xS, info);
4362 if (name != nullptr)
4363 outs() << format(" %.*s", left, name);
4364 outs() << "\n";
4365
4366 p += sizeof(struct objc_property32);
4367 offset += sizeof(struct objc_property32);
4368 }
4369}
4370
Richard Smith81ff44d2015-10-09 22:09:56 +00004371static bool print_class_ro64_t(uint64_t p, struct DisassembleInfo *info,
Kevin Enderby0fc11822015-04-01 20:57:01 +00004372 bool &is_meta_class) {
4373 struct class_ro64_t cro;
4374 const char *r;
4375 uint32_t offset, xoffset, left;
4376 SectionRef S, xS;
4377 const char *name, *sym_name;
4378 uint64_t n_value;
4379
4380 r = get_pointer_64(p, offset, left, S, info);
4381 if (r == nullptr || left < sizeof(struct class_ro64_t))
Richard Smith81ff44d2015-10-09 22:09:56 +00004382 return false;
Kevin Enderby0fc11822015-04-01 20:57:01 +00004383 memset(&cro, '\0', sizeof(struct class_ro64_t));
4384 if (left < sizeof(struct class_ro64_t)) {
4385 memcpy(&cro, r, left);
4386 outs() << " (class_ro_t entends past the end of the section)\n";
4387 } else
4388 memcpy(&cro, r, sizeof(struct class_ro64_t));
4389 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4390 swapStruct(cro);
4391 outs() << " flags " << format("0x%" PRIx32, cro.flags);
4392 if (cro.flags & RO_META)
4393 outs() << " RO_META";
4394 if (cro.flags & RO_ROOT)
4395 outs() << " RO_ROOT";
4396 if (cro.flags & RO_HAS_CXX_STRUCTORS)
4397 outs() << " RO_HAS_CXX_STRUCTORS";
4398 outs() << "\n";
4399 outs() << " instanceStart " << cro.instanceStart << "\n";
4400 outs() << " instanceSize " << cro.instanceSize << "\n";
4401 outs() << " reserved " << format("0x%" PRIx32, cro.reserved)
4402 << "\n";
4403 outs() << " ivarLayout " << format("0x%" PRIx64, cro.ivarLayout)
4404 << "\n";
4405 print_layout_map64(cro.ivarLayout, info);
4406
4407 outs() << " name ";
4408 sym_name = get_symbol_64(offset + offsetof(struct class_ro64_t, name), S,
4409 info, n_value, cro.name);
4410 if (n_value != 0) {
4411 if (info->verbose && sym_name != nullptr)
4412 outs() << sym_name;
4413 else
4414 outs() << format("0x%" PRIx64, n_value);
4415 if (cro.name != 0)
4416 outs() << " + " << format("0x%" PRIx64, cro.name);
4417 } else
4418 outs() << format("0x%" PRIx64, cro.name);
4419 name = get_pointer_64(cro.name + n_value, xoffset, left, xS, info);
4420 if (name != nullptr)
4421 outs() << format(" %.*s", left, name);
4422 outs() << "\n";
4423
4424 outs() << " baseMethods ";
4425 sym_name = get_symbol_64(offset + offsetof(struct class_ro64_t, baseMethods),
4426 S, info, n_value, cro.baseMethods);
4427 if (n_value != 0) {
4428 if (info->verbose && sym_name != nullptr)
4429 outs() << sym_name;
4430 else
4431 outs() << format("0x%" PRIx64, n_value);
4432 if (cro.baseMethods != 0)
4433 outs() << " + " << format("0x%" PRIx64, cro.baseMethods);
4434 } else
4435 outs() << format("0x%" PRIx64, cro.baseMethods);
4436 outs() << " (struct method_list_t *)\n";
4437 if (cro.baseMethods + n_value != 0)
4438 print_method_list64_t(cro.baseMethods + n_value, info, "");
4439
4440 outs() << " baseProtocols ";
4441 sym_name =
4442 get_symbol_64(offset + offsetof(struct class_ro64_t, baseProtocols), S,
4443 info, n_value, cro.baseProtocols);
4444 if (n_value != 0) {
4445 if (info->verbose && sym_name != nullptr)
4446 outs() << sym_name;
4447 else
4448 outs() << format("0x%" PRIx64, n_value);
4449 if (cro.baseProtocols != 0)
4450 outs() << " + " << format("0x%" PRIx64, cro.baseProtocols);
4451 } else
4452 outs() << format("0x%" PRIx64, cro.baseProtocols);
4453 outs() << "\n";
4454 if (cro.baseProtocols + n_value != 0)
4455 print_protocol_list64_t(cro.baseProtocols + n_value, info);
4456
4457 outs() << " ivars ";
4458 sym_name = get_symbol_64(offset + offsetof(struct class_ro64_t, ivars), S,
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004459 info, n_value, cro.ivars);
Kevin Enderby0fc11822015-04-01 20:57:01 +00004460 if (n_value != 0) {
4461 if (info->verbose && sym_name != nullptr)
4462 outs() << sym_name;
4463 else
4464 outs() << format("0x%" PRIx64, n_value);
4465 if (cro.ivars != 0)
4466 outs() << " + " << format("0x%" PRIx64, cro.ivars);
4467 } else
4468 outs() << format("0x%" PRIx64, cro.ivars);
4469 outs() << "\n";
4470 if (cro.ivars + n_value != 0)
4471 print_ivar_list64_t(cro.ivars + n_value, info);
4472
4473 outs() << " weakIvarLayout ";
4474 sym_name =
4475 get_symbol_64(offset + offsetof(struct class_ro64_t, weakIvarLayout), S,
4476 info, n_value, cro.weakIvarLayout);
4477 if (n_value != 0) {
4478 if (info->verbose && sym_name != nullptr)
4479 outs() << sym_name;
4480 else
4481 outs() << format("0x%" PRIx64, n_value);
4482 if (cro.weakIvarLayout != 0)
4483 outs() << " + " << format("0x%" PRIx64, cro.weakIvarLayout);
4484 } else
4485 outs() << format("0x%" PRIx64, cro.weakIvarLayout);
4486 outs() << "\n";
4487 print_layout_map64(cro.weakIvarLayout + n_value, info);
4488
4489 outs() << " baseProperties ";
4490 sym_name =
4491 get_symbol_64(offset + offsetof(struct class_ro64_t, baseProperties), S,
4492 info, n_value, cro.baseProperties);
4493 if (n_value != 0) {
4494 if (info->verbose && sym_name != nullptr)
4495 outs() << sym_name;
4496 else
4497 outs() << format("0x%" PRIx64, n_value);
4498 if (cro.baseProperties != 0)
4499 outs() << " + " << format("0x%" PRIx64, cro.baseProperties);
4500 } else
4501 outs() << format("0x%" PRIx64, cro.baseProperties);
4502 outs() << "\n";
4503 if (cro.baseProperties + n_value != 0)
4504 print_objc_property_list64(cro.baseProperties + n_value, info);
4505
Rafael Espindolab9091322015-10-24 23:19:10 +00004506 is_meta_class = (cro.flags & RO_META) != 0;
Richard Smith81ff44d2015-10-09 22:09:56 +00004507 return true;
Kevin Enderby0fc11822015-04-01 20:57:01 +00004508}
4509
Richard Smith81ff44d2015-10-09 22:09:56 +00004510static bool print_class_ro32_t(uint32_t p, struct DisassembleInfo *info,
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004511 bool &is_meta_class) {
4512 struct class_ro32_t cro;
4513 const char *r;
4514 uint32_t offset, xoffset, left;
4515 SectionRef S, xS;
4516 const char *name;
4517
4518 r = get_pointer_32(p, offset, left, S, info);
4519 if (r == nullptr)
Richard Smith81ff44d2015-10-09 22:09:56 +00004520 return false;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004521 memset(&cro, '\0', sizeof(struct class_ro32_t));
4522 if (left < sizeof(struct class_ro32_t)) {
4523 memcpy(&cro, r, left);
4524 outs() << " (class_ro_t entends past the end of the section)\n";
4525 } else
4526 memcpy(&cro, r, sizeof(struct class_ro32_t));
4527 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4528 swapStruct(cro);
4529 outs() << " flags " << format("0x%" PRIx32, cro.flags);
4530 if (cro.flags & RO_META)
4531 outs() << " RO_META";
4532 if (cro.flags & RO_ROOT)
4533 outs() << " RO_ROOT";
4534 if (cro.flags & RO_HAS_CXX_STRUCTORS)
4535 outs() << " RO_HAS_CXX_STRUCTORS";
4536 outs() << "\n";
4537 outs() << " instanceStart " << cro.instanceStart << "\n";
4538 outs() << " instanceSize " << cro.instanceSize << "\n";
4539 outs() << " ivarLayout " << format("0x%" PRIx32, cro.ivarLayout)
4540 << "\n";
4541 print_layout_map32(cro.ivarLayout, info);
4542
4543 outs() << " name " << format("0x%" PRIx32, cro.name);
4544 name = get_pointer_32(cro.name, xoffset, left, xS, info);
4545 if (name != nullptr)
4546 outs() << format(" %.*s", left, name);
4547 outs() << "\n";
4548
4549 outs() << " baseMethods "
4550 << format("0x%" PRIx32, cro.baseMethods)
4551 << " (struct method_list_t *)\n";
4552 if (cro.baseMethods != 0)
4553 print_method_list32_t(cro.baseMethods, info, "");
4554
4555 outs() << " baseProtocols "
4556 << format("0x%" PRIx32, cro.baseProtocols) << "\n";
4557 if (cro.baseProtocols != 0)
4558 print_protocol_list32_t(cro.baseProtocols, info);
4559 outs() << " ivars " << format("0x%" PRIx32, cro.ivars)
4560 << "\n";
4561 if (cro.ivars != 0)
4562 print_ivar_list32_t(cro.ivars, info);
4563 outs() << " weakIvarLayout "
4564 << format("0x%" PRIx32, cro.weakIvarLayout) << "\n";
4565 print_layout_map32(cro.weakIvarLayout, info);
4566 outs() << " baseProperties "
4567 << format("0x%" PRIx32, cro.baseProperties) << "\n";
4568 if (cro.baseProperties != 0)
4569 print_objc_property_list32(cro.baseProperties, info);
Rafael Espindolab9091322015-10-24 23:19:10 +00004570 is_meta_class = (cro.flags & RO_META) != 0;
Richard Smith81ff44d2015-10-09 22:09:56 +00004571 return true;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004572}
4573
Kevin Enderby0fc11822015-04-01 20:57:01 +00004574static void print_class64_t(uint64_t p, struct DisassembleInfo *info) {
4575 struct class64_t c;
4576 const char *r;
4577 uint32_t offset, left;
4578 SectionRef S;
4579 const char *name;
4580 uint64_t isa_n_value, n_value;
4581
4582 r = get_pointer_64(p, offset, left, S, info);
4583 if (r == nullptr || left < sizeof(struct class64_t))
4584 return;
4585 memset(&c, '\0', sizeof(struct class64_t));
4586 if (left < sizeof(struct class64_t)) {
4587 memcpy(&c, r, left);
4588 outs() << " (class_t entends past the end of the section)\n";
4589 } else
4590 memcpy(&c, r, sizeof(struct class64_t));
4591 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4592 swapStruct(c);
4593
4594 outs() << " isa " << format("0x%" PRIx64, c.isa);
4595 name = get_symbol_64(offset + offsetof(struct class64_t, isa), S, info,
4596 isa_n_value, c.isa);
4597 if (name != nullptr)
4598 outs() << " " << name;
4599 outs() << "\n";
4600
4601 outs() << " superclass " << format("0x%" PRIx64, c.superclass);
4602 name = get_symbol_64(offset + offsetof(struct class64_t, superclass), S, info,
4603 n_value, c.superclass);
4604 if (name != nullptr)
4605 outs() << " " << name;
4606 outs() << "\n";
4607
4608 outs() << " cache " << format("0x%" PRIx64, c.cache);
4609 name = get_symbol_64(offset + offsetof(struct class64_t, cache), S, info,
4610 n_value, c.cache);
4611 if (name != nullptr)
4612 outs() << " " << name;
4613 outs() << "\n";
4614
4615 outs() << " vtable " << format("0x%" PRIx64, c.vtable);
4616 name = get_symbol_64(offset + offsetof(struct class64_t, vtable), S, info,
4617 n_value, c.vtable);
4618 if (name != nullptr)
4619 outs() << " " << name;
4620 outs() << "\n";
4621
4622 name = get_symbol_64(offset + offsetof(struct class64_t, data), S, info,
4623 n_value, c.data);
4624 outs() << " data ";
4625 if (n_value != 0) {
4626 if (info->verbose && name != nullptr)
4627 outs() << name;
4628 else
4629 outs() << format("0x%" PRIx64, n_value);
4630 if (c.data != 0)
4631 outs() << " + " << format("0x%" PRIx64, c.data);
4632 } else
4633 outs() << format("0x%" PRIx64, c.data);
4634 outs() << " (struct class_ro_t *)";
4635
4636 // This is a Swift class if some of the low bits of the pointer are set.
4637 if ((c.data + n_value) & 0x7)
4638 outs() << " Swift class";
4639 outs() << "\n";
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004640 bool is_meta_class;
Richard Smith81ff44d2015-10-09 22:09:56 +00004641 if (!print_class_ro64_t((c.data + n_value) & ~0x7, info, is_meta_class))
4642 return;
Kevin Enderby0fc11822015-04-01 20:57:01 +00004643
Kevin Enderbyaac75382015-10-08 16:56:35 +00004644 if (!is_meta_class &&
4645 c.isa + isa_n_value != p &&
4646 c.isa + isa_n_value != 0 &&
4647 info->depth < 100) {
4648 info->depth++;
4649 outs() << "Meta Class\n";
4650 print_class64_t(c.isa + isa_n_value, info);
Kevin Enderby0fc11822015-04-01 20:57:01 +00004651 }
4652}
4653
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004654static void print_class32_t(uint32_t p, struct DisassembleInfo *info) {
4655 struct class32_t c;
4656 const char *r;
4657 uint32_t offset, left;
4658 SectionRef S;
4659 const char *name;
4660
4661 r = get_pointer_32(p, offset, left, S, info);
4662 if (r == nullptr)
4663 return;
4664 memset(&c, '\0', sizeof(struct class32_t));
4665 if (left < sizeof(struct class32_t)) {
4666 memcpy(&c, r, left);
4667 outs() << " (class_t entends past the end of the section)\n";
4668 } else
4669 memcpy(&c, r, sizeof(struct class32_t));
4670 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4671 swapStruct(c);
4672
4673 outs() << " isa " << format("0x%" PRIx32, c.isa);
4674 name =
4675 get_symbol_32(offset + offsetof(struct class32_t, isa), S, info, c.isa);
4676 if (name != nullptr)
4677 outs() << " " << name;
4678 outs() << "\n";
4679
4680 outs() << " superclass " << format("0x%" PRIx32, c.superclass);
4681 name = get_symbol_32(offset + offsetof(struct class32_t, superclass), S, info,
4682 c.superclass);
4683 if (name != nullptr)
4684 outs() << " " << name;
4685 outs() << "\n";
4686
4687 outs() << " cache " << format("0x%" PRIx32, c.cache);
4688 name = get_symbol_32(offset + offsetof(struct class32_t, cache), S, info,
4689 c.cache);
4690 if (name != nullptr)
4691 outs() << " " << name;
4692 outs() << "\n";
4693
4694 outs() << " vtable " << format("0x%" PRIx32, c.vtable);
4695 name = get_symbol_32(offset + offsetof(struct class32_t, vtable), S, info,
4696 c.vtable);
4697 if (name != nullptr)
4698 outs() << " " << name;
4699 outs() << "\n";
4700
4701 name =
4702 get_symbol_32(offset + offsetof(struct class32_t, data), S, info, c.data);
4703 outs() << " data " << format("0x%" PRIx32, c.data)
4704 << " (struct class_ro_t *)";
4705
4706 // This is a Swift class if some of the low bits of the pointer are set.
4707 if (c.data & 0x3)
4708 outs() << " Swift class";
4709 outs() << "\n";
4710 bool is_meta_class;
Richard Smith81ff44d2015-10-09 22:09:56 +00004711 if (!print_class_ro32_t(c.data & ~0x3, info, is_meta_class))
4712 return;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004713
Hans Wennborgcc9deb42015-09-29 18:02:48 +00004714 if (!is_meta_class) {
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004715 outs() << "Meta Class\n";
4716 print_class32_t(c.isa, info);
4717 }
4718}
4719
Kevin Enderby846c0002015-04-16 17:19:59 +00004720static void print_objc_class_t(struct objc_class_t *objc_class,
4721 struct DisassembleInfo *info) {
4722 uint32_t offset, left, xleft;
4723 const char *name, *p, *ivar_list;
4724 SectionRef S;
4725 int32_t i;
4726 struct objc_ivar_list_t objc_ivar_list;
4727 struct objc_ivar_t ivar;
4728
4729 outs() << "\t\t isa " << format("0x%08" PRIx32, objc_class->isa);
4730 if (info->verbose && CLS_GETINFO(objc_class, CLS_META)) {
4731 name = get_pointer_32(objc_class->isa, offset, left, S, info, true);
4732 if (name != nullptr)
4733 outs() << format(" %.*s", left, name);
4734 else
4735 outs() << " (not in an __OBJC section)";
4736 }
4737 outs() << "\n";
4738
4739 outs() << "\t super_class "
4740 << format("0x%08" PRIx32, objc_class->super_class);
4741 if (info->verbose) {
4742 name = get_pointer_32(objc_class->super_class, offset, left, S, info, true);
4743 if (name != nullptr)
4744 outs() << format(" %.*s", left, name);
4745 else
4746 outs() << " (not in an __OBJC section)";
4747 }
4748 outs() << "\n";
4749
4750 outs() << "\t\t name " << format("0x%08" PRIx32, objc_class->name);
4751 if (info->verbose) {
4752 name = get_pointer_32(objc_class->name, offset, left, S, info, true);
4753 if (name != nullptr)
4754 outs() << format(" %.*s", left, name);
4755 else
4756 outs() << " (not in an __OBJC section)";
4757 }
4758 outs() << "\n";
4759
4760 outs() << "\t\t version " << format("0x%08" PRIx32, objc_class->version)
4761 << "\n";
4762
4763 outs() << "\t\t info " << format("0x%08" PRIx32, objc_class->info);
4764 if (info->verbose) {
4765 if (CLS_GETINFO(objc_class, CLS_CLASS))
4766 outs() << " CLS_CLASS";
4767 else if (CLS_GETINFO(objc_class, CLS_META))
4768 outs() << " CLS_META";
4769 }
4770 outs() << "\n";
4771
4772 outs() << "\t instance_size "
4773 << format("0x%08" PRIx32, objc_class->instance_size) << "\n";
4774
4775 p = get_pointer_32(objc_class->ivars, offset, left, S, info, true);
4776 outs() << "\t\t ivars " << format("0x%08" PRIx32, objc_class->ivars);
4777 if (p != nullptr) {
4778 if (left > sizeof(struct objc_ivar_list_t)) {
4779 outs() << "\n";
4780 memcpy(&objc_ivar_list, p, sizeof(struct objc_ivar_list_t));
4781 } else {
4782 outs() << " (entends past the end of the section)\n";
4783 memset(&objc_ivar_list, '\0', sizeof(struct objc_ivar_list_t));
4784 memcpy(&objc_ivar_list, p, left);
4785 }
4786 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4787 swapStruct(objc_ivar_list);
4788 outs() << "\t\t ivar_count " << objc_ivar_list.ivar_count << "\n";
4789 ivar_list = p + sizeof(struct objc_ivar_list_t);
4790 for (i = 0; i < objc_ivar_list.ivar_count; i++) {
4791 if ((i + 1) * sizeof(struct objc_ivar_t) > left) {
4792 outs() << "\t\t remaining ivar's extend past the of the section\n";
4793 break;
4794 }
4795 memcpy(&ivar, ivar_list + i * sizeof(struct objc_ivar_t),
4796 sizeof(struct objc_ivar_t));
4797 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4798 swapStruct(ivar);
4799
4800 outs() << "\t\t\tivar_name " << format("0x%08" PRIx32, ivar.ivar_name);
4801 if (info->verbose) {
4802 name = get_pointer_32(ivar.ivar_name, offset, xleft, S, info, true);
4803 if (name != nullptr)
4804 outs() << format(" %.*s", xleft, name);
4805 else
4806 outs() << " (not in an __OBJC section)";
4807 }
4808 outs() << "\n";
4809
4810 outs() << "\t\t\tivar_type " << format("0x%08" PRIx32, ivar.ivar_type);
4811 if (info->verbose) {
4812 name = get_pointer_32(ivar.ivar_type, offset, xleft, S, info, true);
4813 if (name != nullptr)
4814 outs() << format(" %.*s", xleft, name);
4815 else
4816 outs() << " (not in an __OBJC section)";
4817 }
4818 outs() << "\n";
4819
4820 outs() << "\t\t ivar_offset "
4821 << format("0x%08" PRIx32, ivar.ivar_offset) << "\n";
4822 }
4823 } else {
4824 outs() << " (not in an __OBJC section)\n";
4825 }
4826
4827 outs() << "\t\t methods " << format("0x%08" PRIx32, objc_class->methodLists);
4828 if (print_method_list(objc_class->methodLists, info))
4829 outs() << " (not in an __OBJC section)\n";
4830
4831 outs() << "\t\t cache " << format("0x%08" PRIx32, objc_class->cache)
4832 << "\n";
4833
4834 outs() << "\t\tprotocols " << format("0x%08" PRIx32, objc_class->protocols);
4835 if (print_protocol_list(objc_class->protocols, 16, info))
4836 outs() << " (not in an __OBJC section)\n";
4837}
4838
4839static void print_objc_objc_category_t(struct objc_category_t *objc_category,
4840 struct DisassembleInfo *info) {
4841 uint32_t offset, left;
4842 const char *name;
4843 SectionRef S;
4844
4845 outs() << "\t category name "
4846 << format("0x%08" PRIx32, objc_category->category_name);
4847 if (info->verbose) {
4848 name = get_pointer_32(objc_category->category_name, offset, left, S, info,
4849 true);
4850 if (name != nullptr)
4851 outs() << format(" %.*s", left, name);
4852 else
4853 outs() << " (not in an __OBJC section)";
4854 }
4855 outs() << "\n";
4856
4857 outs() << "\t\t class name "
4858 << format("0x%08" PRIx32, objc_category->class_name);
4859 if (info->verbose) {
4860 name =
4861 get_pointer_32(objc_category->class_name, offset, left, S, info, true);
4862 if (name != nullptr)
4863 outs() << format(" %.*s", left, name);
4864 else
4865 outs() << " (not in an __OBJC section)";
4866 }
4867 outs() << "\n";
4868
4869 outs() << "\t instance methods "
4870 << format("0x%08" PRIx32, objc_category->instance_methods);
4871 if (print_method_list(objc_category->instance_methods, info))
4872 outs() << " (not in an __OBJC section)\n";
4873
4874 outs() << "\t class methods "
4875 << format("0x%08" PRIx32, objc_category->class_methods);
4876 if (print_method_list(objc_category->class_methods, info))
4877 outs() << " (not in an __OBJC section)\n";
4878}
4879
Kevin Enderby0fc11822015-04-01 20:57:01 +00004880static void print_category64_t(uint64_t p, struct DisassembleInfo *info) {
4881 struct category64_t c;
4882 const char *r;
4883 uint32_t offset, xoffset, left;
4884 SectionRef S, xS;
4885 const char *name, *sym_name;
4886 uint64_t n_value;
4887
4888 r = get_pointer_64(p, offset, left, S, info);
4889 if (r == nullptr)
4890 return;
4891 memset(&c, '\0', sizeof(struct category64_t));
4892 if (left < sizeof(struct category64_t)) {
4893 memcpy(&c, r, left);
4894 outs() << " (category_t entends past the end of the section)\n";
4895 } else
4896 memcpy(&c, r, sizeof(struct category64_t));
4897 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4898 swapStruct(c);
4899
4900 outs() << " name ";
4901 sym_name = get_symbol_64(offset + offsetof(struct category64_t, name), S,
4902 info, n_value, c.name);
4903 if (n_value != 0) {
4904 if (info->verbose && sym_name != nullptr)
4905 outs() << sym_name;
4906 else
4907 outs() << format("0x%" PRIx64, n_value);
4908 if (c.name != 0)
4909 outs() << " + " << format("0x%" PRIx64, c.name);
4910 } else
4911 outs() << format("0x%" PRIx64, c.name);
4912 name = get_pointer_64(c.name + n_value, xoffset, left, xS, info);
4913 if (name != nullptr)
4914 outs() << format(" %.*s", left, name);
4915 outs() << "\n";
4916
4917 outs() << " cls ";
4918 sym_name = get_symbol_64(offset + offsetof(struct category64_t, cls), S, info,
4919 n_value, c.cls);
4920 if (n_value != 0) {
4921 if (info->verbose && sym_name != nullptr)
4922 outs() << sym_name;
4923 else
4924 outs() << format("0x%" PRIx64, n_value);
4925 if (c.cls != 0)
4926 outs() << " + " << format("0x%" PRIx64, c.cls);
4927 } else
4928 outs() << format("0x%" PRIx64, c.cls);
4929 outs() << "\n";
4930 if (c.cls + n_value != 0)
4931 print_class64_t(c.cls + n_value, info);
4932
4933 outs() << " instanceMethods ";
4934 sym_name =
4935 get_symbol_64(offset + offsetof(struct category64_t, instanceMethods), S,
4936 info, n_value, c.instanceMethods);
4937 if (n_value != 0) {
4938 if (info->verbose && sym_name != nullptr)
4939 outs() << sym_name;
4940 else
4941 outs() << format("0x%" PRIx64, n_value);
4942 if (c.instanceMethods != 0)
4943 outs() << " + " << format("0x%" PRIx64, c.instanceMethods);
4944 } else
4945 outs() << format("0x%" PRIx64, c.instanceMethods);
4946 outs() << "\n";
4947 if (c.instanceMethods + n_value != 0)
4948 print_method_list64_t(c.instanceMethods + n_value, info, "");
4949
4950 outs() << " classMethods ";
4951 sym_name = get_symbol_64(offset + offsetof(struct category64_t, classMethods),
4952 S, info, n_value, c.classMethods);
4953 if (n_value != 0) {
4954 if (info->verbose && sym_name != nullptr)
4955 outs() << sym_name;
4956 else
4957 outs() << format("0x%" PRIx64, n_value);
4958 if (c.classMethods != 0)
4959 outs() << " + " << format("0x%" PRIx64, c.classMethods);
4960 } else
4961 outs() << format("0x%" PRIx64, c.classMethods);
4962 outs() << "\n";
4963 if (c.classMethods + n_value != 0)
4964 print_method_list64_t(c.classMethods + n_value, info, "");
4965
4966 outs() << " protocols ";
4967 sym_name = get_symbol_64(offset + offsetof(struct category64_t, protocols), S,
4968 info, n_value, c.protocols);
4969 if (n_value != 0) {
4970 if (info->verbose && sym_name != nullptr)
4971 outs() << sym_name;
4972 else
4973 outs() << format("0x%" PRIx64, n_value);
4974 if (c.protocols != 0)
4975 outs() << " + " << format("0x%" PRIx64, c.protocols);
4976 } else
4977 outs() << format("0x%" PRIx64, c.protocols);
4978 outs() << "\n";
4979 if (c.protocols + n_value != 0)
4980 print_protocol_list64_t(c.protocols + n_value, info);
4981
4982 outs() << "instanceProperties ";
4983 sym_name =
4984 get_symbol_64(offset + offsetof(struct category64_t, instanceProperties),
4985 S, info, n_value, c.instanceProperties);
4986 if (n_value != 0) {
4987 if (info->verbose && sym_name != nullptr)
4988 outs() << sym_name;
4989 else
4990 outs() << format("0x%" PRIx64, n_value);
4991 if (c.instanceProperties != 0)
4992 outs() << " + " << format("0x%" PRIx64, c.instanceProperties);
4993 } else
4994 outs() << format("0x%" PRIx64, c.instanceProperties);
4995 outs() << "\n";
4996 if (c.instanceProperties + n_value != 0)
4997 print_objc_property_list64(c.instanceProperties + n_value, info);
4998}
4999
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005000static void print_category32_t(uint32_t p, struct DisassembleInfo *info) {
5001 struct category32_t c;
5002 const char *r;
5003 uint32_t offset, left;
5004 SectionRef S, xS;
5005 const char *name;
5006
5007 r = get_pointer_32(p, offset, left, S, info);
5008 if (r == nullptr)
5009 return;
5010 memset(&c, '\0', sizeof(struct category32_t));
5011 if (left < sizeof(struct category32_t)) {
5012 memcpy(&c, r, left);
5013 outs() << " (category_t entends past the end of the section)\n";
5014 } else
5015 memcpy(&c, r, sizeof(struct category32_t));
5016 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5017 swapStruct(c);
5018
5019 outs() << " name " << format("0x%" PRIx32, c.name);
5020 name = get_symbol_32(offset + offsetof(struct category32_t, name), S, info,
5021 c.name);
Hans Wennborgcc9deb42015-09-29 18:02:48 +00005022 if (name)
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005023 outs() << " " << name;
5024 outs() << "\n";
5025
5026 outs() << " cls " << format("0x%" PRIx32, c.cls) << "\n";
5027 if (c.cls != 0)
5028 print_class32_t(c.cls, info);
5029 outs() << " instanceMethods " << format("0x%" PRIx32, c.instanceMethods)
5030 << "\n";
5031 if (c.instanceMethods != 0)
5032 print_method_list32_t(c.instanceMethods, info, "");
5033 outs() << " classMethods " << format("0x%" PRIx32, c.classMethods)
5034 << "\n";
5035 if (c.classMethods != 0)
5036 print_method_list32_t(c.classMethods, info, "");
5037 outs() << " protocols " << format("0x%" PRIx32, c.protocols) << "\n";
5038 if (c.protocols != 0)
5039 print_protocol_list32_t(c.protocols, info);
5040 outs() << "instanceProperties " << format("0x%" PRIx32, c.instanceProperties)
5041 << "\n";
5042 if (c.instanceProperties != 0)
5043 print_objc_property_list32(c.instanceProperties, info);
5044}
5045
Kevin Enderby0fc11822015-04-01 20:57:01 +00005046static void print_message_refs64(SectionRef S, struct DisassembleInfo *info) {
5047 uint32_t i, left, offset, xoffset;
5048 uint64_t p, n_value;
5049 struct message_ref64 mr;
5050 const char *name, *sym_name;
5051 const char *r;
5052 SectionRef xS;
5053
5054 if (S == SectionRef())
5055 return;
5056
5057 StringRef SectName;
5058 S.getName(SectName);
5059 DataRefImpl Ref = S.getRawDataRefImpl();
5060 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5061 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5062 offset = 0;
5063 for (i = 0; i < S.getSize(); i += sizeof(struct message_ref64)) {
5064 p = S.getAddress() + i;
5065 r = get_pointer_64(p, offset, left, S, info);
5066 if (r == nullptr)
5067 return;
5068 memset(&mr, '\0', sizeof(struct message_ref64));
5069 if (left < sizeof(struct message_ref64)) {
5070 memcpy(&mr, r, left);
5071 outs() << " (message_ref entends past the end of the section)\n";
5072 } else
5073 memcpy(&mr, r, sizeof(struct message_ref64));
5074 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5075 swapStruct(mr);
5076
5077 outs() << " imp ";
5078 name = get_symbol_64(offset + offsetof(struct message_ref64, imp), S, info,
5079 n_value, mr.imp);
5080 if (n_value != 0) {
5081 outs() << format("0x%" PRIx64, n_value) << " ";
5082 if (mr.imp != 0)
5083 outs() << "+ " << format("0x%" PRIx64, mr.imp) << " ";
5084 } else
5085 outs() << format("0x%" PRIx64, mr.imp) << " ";
5086 if (name != nullptr)
5087 outs() << " " << name;
5088 outs() << "\n";
5089
5090 outs() << " sel ";
5091 sym_name = get_symbol_64(offset + offsetof(struct message_ref64, sel), S,
5092 info, n_value, mr.sel);
5093 if (n_value != 0) {
5094 if (info->verbose && sym_name != nullptr)
5095 outs() << sym_name;
5096 else
5097 outs() << format("0x%" PRIx64, n_value);
5098 if (mr.sel != 0)
5099 outs() << " + " << format("0x%" PRIx64, mr.sel);
5100 } else
5101 outs() << format("0x%" PRIx64, mr.sel);
5102 name = get_pointer_64(mr.sel + n_value, xoffset, left, xS, info);
5103 if (name != nullptr)
5104 outs() << format(" %.*s", left, name);
5105 outs() << "\n";
5106
5107 offset += sizeof(struct message_ref64);
5108 }
5109}
5110
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005111static void print_message_refs32(SectionRef S, struct DisassembleInfo *info) {
5112 uint32_t i, left, offset, xoffset, p;
5113 struct message_ref32 mr;
5114 const char *name, *r;
5115 SectionRef xS;
5116
5117 if (S == SectionRef())
5118 return;
5119
5120 StringRef SectName;
5121 S.getName(SectName);
5122 DataRefImpl Ref = S.getRawDataRefImpl();
5123 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5124 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5125 offset = 0;
5126 for (i = 0; i < S.getSize(); i += sizeof(struct message_ref64)) {
5127 p = S.getAddress() + i;
5128 r = get_pointer_32(p, offset, left, S, info);
5129 if (r == nullptr)
5130 return;
5131 memset(&mr, '\0', sizeof(struct message_ref32));
5132 if (left < sizeof(struct message_ref32)) {
5133 memcpy(&mr, r, left);
5134 outs() << " (message_ref entends past the end of the section)\n";
5135 } else
5136 memcpy(&mr, r, sizeof(struct message_ref32));
5137 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5138 swapStruct(mr);
5139
5140 outs() << " imp " << format("0x%" PRIx32, mr.imp);
5141 name = get_symbol_32(offset + offsetof(struct message_ref32, imp), S, info,
5142 mr.imp);
5143 if (name != nullptr)
5144 outs() << " " << name;
5145 outs() << "\n";
5146
5147 outs() << " sel " << format("0x%" PRIx32, mr.sel);
5148 name = get_pointer_32(mr.sel, xoffset, left, xS, info);
5149 if (name != nullptr)
5150 outs() << " " << name;
5151 outs() << "\n";
5152
5153 offset += sizeof(struct message_ref32);
5154 }
5155}
5156
Kevin Enderby0fc11822015-04-01 20:57:01 +00005157static void print_image_info64(SectionRef S, struct DisassembleInfo *info) {
5158 uint32_t left, offset, swift_version;
5159 uint64_t p;
5160 struct objc_image_info64 o;
5161 const char *r;
5162
Kevin Enderbyaf7c9d02015-10-09 16:48:44 +00005163 if (S == SectionRef())
5164 return;
5165
Kevin Enderby0fc11822015-04-01 20:57:01 +00005166 StringRef SectName;
5167 S.getName(SectName);
5168 DataRefImpl Ref = S.getRawDataRefImpl();
5169 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5170 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5171 p = S.getAddress();
5172 r = get_pointer_64(p, offset, left, S, info);
5173 if (r == nullptr)
5174 return;
5175 memset(&o, '\0', sizeof(struct objc_image_info64));
5176 if (left < sizeof(struct objc_image_info64)) {
5177 memcpy(&o, r, left);
5178 outs() << " (objc_image_info entends past the end of the section)\n";
5179 } else
5180 memcpy(&o, r, sizeof(struct objc_image_info64));
5181 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5182 swapStruct(o);
5183 outs() << " version " << o.version << "\n";
5184 outs() << " flags " << format("0x%" PRIx32, o.flags);
5185 if (o.flags & OBJC_IMAGE_IS_REPLACEMENT)
5186 outs() << " OBJC_IMAGE_IS_REPLACEMENT";
5187 if (o.flags & OBJC_IMAGE_SUPPORTS_GC)
5188 outs() << " OBJC_IMAGE_SUPPORTS_GC";
5189 swift_version = (o.flags >> 8) & 0xff;
5190 if (swift_version != 0) {
5191 if (swift_version == 1)
5192 outs() << " Swift 1.0";
5193 else if (swift_version == 2)
5194 outs() << " Swift 1.1";
5195 else
5196 outs() << " unknown future Swift version (" << swift_version << ")";
5197 }
5198 outs() << "\n";
5199}
5200
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005201static void print_image_info32(SectionRef S, struct DisassembleInfo *info) {
5202 uint32_t left, offset, swift_version, p;
5203 struct objc_image_info32 o;
5204 const char *r;
5205
Kevin Enderby19be2512016-04-21 19:49:29 +00005206 if (S == SectionRef())
5207 return;
5208
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005209 StringRef SectName;
5210 S.getName(SectName);
5211 DataRefImpl Ref = S.getRawDataRefImpl();
5212 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5213 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5214 p = S.getAddress();
5215 r = get_pointer_32(p, offset, left, S, info);
5216 if (r == nullptr)
5217 return;
5218 memset(&o, '\0', sizeof(struct objc_image_info32));
5219 if (left < sizeof(struct objc_image_info32)) {
5220 memcpy(&o, r, left);
5221 outs() << " (objc_image_info entends past the end of the section)\n";
5222 } else
5223 memcpy(&o, r, sizeof(struct objc_image_info32));
5224 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5225 swapStruct(o);
5226 outs() << " version " << o.version << "\n";
5227 outs() << " flags " << format("0x%" PRIx32, o.flags);
5228 if (o.flags & OBJC_IMAGE_IS_REPLACEMENT)
5229 outs() << " OBJC_IMAGE_IS_REPLACEMENT";
5230 if (o.flags & OBJC_IMAGE_SUPPORTS_GC)
5231 outs() << " OBJC_IMAGE_SUPPORTS_GC";
5232 swift_version = (o.flags >> 8) & 0xff;
5233 if (swift_version != 0) {
5234 if (swift_version == 1)
5235 outs() << " Swift 1.0";
5236 else if (swift_version == 2)
5237 outs() << " Swift 1.1";
5238 else
5239 outs() << " unknown future Swift version (" << swift_version << ")";
5240 }
5241 outs() << "\n";
5242}
5243
Kevin Enderby846c0002015-04-16 17:19:59 +00005244static void print_image_info(SectionRef S, struct DisassembleInfo *info) {
5245 uint32_t left, offset, p;
5246 struct imageInfo_t o;
5247 const char *r;
5248
5249 StringRef SectName;
5250 S.getName(SectName);
5251 DataRefImpl Ref = S.getRawDataRefImpl();
5252 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5253 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5254 p = S.getAddress();
5255 r = get_pointer_32(p, offset, left, S, info);
5256 if (r == nullptr)
5257 return;
5258 memset(&o, '\0', sizeof(struct imageInfo_t));
5259 if (left < sizeof(struct imageInfo_t)) {
5260 memcpy(&o, r, left);
5261 outs() << " (imageInfo entends past the end of the section)\n";
5262 } else
5263 memcpy(&o, r, sizeof(struct imageInfo_t));
5264 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5265 swapStruct(o);
5266 outs() << " version " << o.version << "\n";
5267 outs() << " flags " << format("0x%" PRIx32, o.flags);
5268 if (o.flags & 0x1)
5269 outs() << " F&C";
5270 if (o.flags & 0x2)
5271 outs() << " GC";
5272 if (o.flags & 0x4)
5273 outs() << " GC-only";
5274 else
5275 outs() << " RR";
5276 outs() << "\n";
5277}
5278
Kevin Enderby0fc11822015-04-01 20:57:01 +00005279static void printObjc2_64bit_MetaData(MachOObjectFile *O, bool verbose) {
5280 SymbolAddressMap AddrMap;
5281 if (verbose)
5282 CreateSymbolAddressMap(O, &AddrMap);
5283
5284 std::vector<SectionRef> Sections;
5285 for (const SectionRef &Section : O->sections()) {
5286 StringRef SectName;
5287 Section.getName(SectName);
5288 Sections.push_back(Section);
5289 }
5290
5291 struct DisassembleInfo info;
5292 // Set up the block of info used by the Symbolizer call backs.
5293 info.verbose = verbose;
5294 info.O = O;
5295 info.AddrMap = &AddrMap;
5296 info.Sections = &Sections;
5297 info.class_name = nullptr;
5298 info.selector_name = nullptr;
5299 info.method = nullptr;
5300 info.demangled_name = nullptr;
5301 info.bindtable = nullptr;
5302 info.adrp_addr = 0;
5303 info.adrp_inst = 0;
5304
Kevin Enderbyaac75382015-10-08 16:56:35 +00005305 info.depth = 0;
Davide Italiano62507042015-12-11 22:27:59 +00005306 SectionRef CL = get_section(O, "__OBJC2", "__class_list");
5307 if (CL == SectionRef())
5308 CL = get_section(O, "__DATA", "__objc_classlist");
5309 info.S = CL;
5310 walk_pointer_list_64("class", CL, O, &info, print_class64_t);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005311
Davide Italiano62507042015-12-11 22:27:59 +00005312 SectionRef CR = get_section(O, "__OBJC2", "__class_refs");
5313 if (CR == SectionRef())
5314 CR = get_section(O, "__DATA", "__objc_classrefs");
5315 info.S = CR;
5316 walk_pointer_list_64("class refs", CR, O, &info, nullptr);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005317
Davide Italiano62507042015-12-11 22:27:59 +00005318 SectionRef SR = get_section(O, "__OBJC2", "__super_refs");
5319 if (SR == SectionRef())
5320 SR = get_section(O, "__DATA", "__objc_superrefs");
5321 info.S = SR;
5322 walk_pointer_list_64("super refs", SR, O, &info, nullptr);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005323
Davide Italiano62507042015-12-11 22:27:59 +00005324 SectionRef CA = get_section(O, "__OBJC2", "__category_list");
5325 if (CA == SectionRef())
5326 CA = get_section(O, "__DATA", "__objc_catlist");
5327 info.S = CA;
5328 walk_pointer_list_64("category", CA, O, &info, print_category64_t);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005329
Davide Italiano62507042015-12-11 22:27:59 +00005330 SectionRef PL = get_section(O, "__OBJC2", "__protocol_list");
5331 if (PL == SectionRef())
5332 PL = get_section(O, "__DATA", "__objc_protolist");
5333 info.S = PL;
5334 walk_pointer_list_64("protocol", PL, O, &info, nullptr);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005335
Davide Italiano62507042015-12-11 22:27:59 +00005336 SectionRef MR = get_section(O, "__OBJC2", "__message_refs");
5337 if (MR == SectionRef())
5338 MR = get_section(O, "__DATA", "__objc_msgrefs");
5339 info.S = MR;
5340 print_message_refs64(MR, &info);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005341
Davide Italiano62507042015-12-11 22:27:59 +00005342 SectionRef II = get_section(O, "__OBJC2", "__image_info");
5343 if (II == SectionRef())
5344 II = get_section(O, "__DATA", "__objc_imageinfo");
5345 info.S = II;
5346 print_image_info64(II, &info);
Kevin Enderby0bc6ed42015-04-01 21:50:45 +00005347
5348 if (info.bindtable != nullptr)
5349 delete info.bindtable;
Kevin Enderby0fc11822015-04-01 20:57:01 +00005350}
5351
5352static void printObjc2_32bit_MetaData(MachOObjectFile *O, bool verbose) {
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005353 SymbolAddressMap AddrMap;
5354 if (verbose)
5355 CreateSymbolAddressMap(O, &AddrMap);
5356
5357 std::vector<SectionRef> Sections;
5358 for (const SectionRef &Section : O->sections()) {
5359 StringRef SectName;
5360 Section.getName(SectName);
5361 Sections.push_back(Section);
5362 }
5363
5364 struct DisassembleInfo info;
5365 // Set up the block of info used by the Symbolizer call backs.
5366 info.verbose = verbose;
5367 info.O = O;
5368 info.AddrMap = &AddrMap;
5369 info.Sections = &Sections;
5370 info.class_name = nullptr;
5371 info.selector_name = nullptr;
5372 info.method = nullptr;
5373 info.demangled_name = nullptr;
5374 info.bindtable = nullptr;
5375 info.adrp_addr = 0;
5376 info.adrp_inst = 0;
5377
5378 const SectionRef CL = get_section(O, "__OBJC2", "__class_list");
5379 if (CL != SectionRef()) {
5380 info.S = CL;
5381 walk_pointer_list_32("class", CL, O, &info, print_class32_t);
5382 } else {
5383 const SectionRef CL = get_section(O, "__DATA", "__objc_classlist");
5384 info.S = CL;
5385 walk_pointer_list_32("class", CL, O, &info, print_class32_t);
5386 }
5387
5388 const SectionRef CR = get_section(O, "__OBJC2", "__class_refs");
5389 if (CR != SectionRef()) {
5390 info.S = CR;
5391 walk_pointer_list_32("class refs", CR, O, &info, nullptr);
5392 } else {
5393 const SectionRef CR = get_section(O, "__DATA", "__objc_classrefs");
5394 info.S = CR;
5395 walk_pointer_list_32("class refs", CR, O, &info, nullptr);
5396 }
5397
5398 const SectionRef SR = get_section(O, "__OBJC2", "__super_refs");
5399 if (SR != SectionRef()) {
5400 info.S = SR;
5401 walk_pointer_list_32("super refs", SR, O, &info, nullptr);
5402 } else {
5403 const SectionRef SR = get_section(O, "__DATA", "__objc_superrefs");
5404 info.S = SR;
5405 walk_pointer_list_32("super refs", SR, O, &info, nullptr);
5406 }
5407
5408 const SectionRef CA = get_section(O, "__OBJC2", "__category_list");
5409 if (CA != SectionRef()) {
5410 info.S = CA;
5411 walk_pointer_list_32("category", CA, O, &info, print_category32_t);
5412 } else {
5413 const SectionRef CA = get_section(O, "__DATA", "__objc_catlist");
5414 info.S = CA;
5415 walk_pointer_list_32("category", CA, O, &info, print_category32_t);
5416 }
5417
5418 const SectionRef PL = get_section(O, "__OBJC2", "__protocol_list");
5419 if (PL != SectionRef()) {
5420 info.S = PL;
5421 walk_pointer_list_32("protocol", PL, O, &info, nullptr);
5422 } else {
5423 const SectionRef PL = get_section(O, "__DATA", "__objc_protolist");
5424 info.S = PL;
5425 walk_pointer_list_32("protocol", PL, O, &info, nullptr);
5426 }
5427
5428 const SectionRef MR = get_section(O, "__OBJC2", "__message_refs");
5429 if (MR != SectionRef()) {
5430 info.S = MR;
5431 print_message_refs32(MR, &info);
5432 } else {
5433 const SectionRef MR = get_section(O, "__DATA", "__objc_msgrefs");
5434 info.S = MR;
5435 print_message_refs32(MR, &info);
5436 }
5437
5438 const SectionRef II = get_section(O, "__OBJC2", "__image_info");
5439 if (II != SectionRef()) {
5440 info.S = II;
5441 print_image_info32(II, &info);
5442 } else {
5443 const SectionRef II = get_section(O, "__DATA", "__objc_imageinfo");
5444 info.S = II;
5445 print_image_info32(II, &info);
5446 }
Kevin Enderby0fc11822015-04-01 20:57:01 +00005447}
5448
5449static bool printObjc1_32bit_MetaData(MachOObjectFile *O, bool verbose) {
Kevin Enderby846c0002015-04-16 17:19:59 +00005450 uint32_t i, j, p, offset, xoffset, left, defs_left, def;
5451 const char *r, *name, *defs;
5452 struct objc_module_t module;
5453 SectionRef S, xS;
5454 struct objc_symtab_t symtab;
5455 struct objc_class_t objc_class;
5456 struct objc_category_t objc_category;
5457
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005458 outs() << "Objective-C segment\n";
Kevin Enderby846c0002015-04-16 17:19:59 +00005459 S = get_section(O, "__OBJC", "__module_info");
5460 if (S == SectionRef())
5461 return false;
5462
5463 SymbolAddressMap AddrMap;
5464 if (verbose)
5465 CreateSymbolAddressMap(O, &AddrMap);
5466
5467 std::vector<SectionRef> Sections;
5468 for (const SectionRef &Section : O->sections()) {
5469 StringRef SectName;
5470 Section.getName(SectName);
5471 Sections.push_back(Section);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005472 }
Kevin Enderby846c0002015-04-16 17:19:59 +00005473
5474 struct DisassembleInfo info;
5475 // Set up the block of info used by the Symbolizer call backs.
5476 info.verbose = verbose;
5477 info.O = O;
5478 info.AddrMap = &AddrMap;
5479 info.Sections = &Sections;
5480 info.class_name = nullptr;
5481 info.selector_name = nullptr;
5482 info.method = nullptr;
5483 info.demangled_name = nullptr;
5484 info.bindtable = nullptr;
5485 info.adrp_addr = 0;
5486 info.adrp_inst = 0;
5487
5488 for (i = 0; i < S.getSize(); i += sizeof(struct objc_module_t)) {
5489 p = S.getAddress() + i;
5490 r = get_pointer_32(p, offset, left, S, &info, true);
5491 if (r == nullptr)
5492 return true;
5493 memset(&module, '\0', sizeof(struct objc_module_t));
5494 if (left < sizeof(struct objc_module_t)) {
5495 memcpy(&module, r, left);
5496 outs() << " (module extends past end of __module_info section)\n";
5497 } else
5498 memcpy(&module, r, sizeof(struct objc_module_t));
5499 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5500 swapStruct(module);
5501
5502 outs() << "Module " << format("0x%" PRIx32, p) << "\n";
5503 outs() << " version " << module.version << "\n";
5504 outs() << " size " << module.size << "\n";
5505 outs() << " name ";
5506 name = get_pointer_32(module.name, xoffset, left, xS, &info, true);
5507 if (name != nullptr)
5508 outs() << format("%.*s", left, name);
5509 else
5510 outs() << format("0x%08" PRIx32, module.name)
5511 << "(not in an __OBJC section)";
5512 outs() << "\n";
5513
5514 r = get_pointer_32(module.symtab, xoffset, left, xS, &info, true);
5515 if (module.symtab == 0 || r == nullptr) {
5516 outs() << " symtab " << format("0x%08" PRIx32, module.symtab)
5517 << " (not in an __OBJC section)\n";
5518 continue;
5519 }
5520 outs() << " symtab " << format("0x%08" PRIx32, module.symtab) << "\n";
5521 memset(&symtab, '\0', sizeof(struct objc_symtab_t));
5522 defs_left = 0;
5523 defs = nullptr;
5524 if (left < sizeof(struct objc_symtab_t)) {
5525 memcpy(&symtab, r, left);
5526 outs() << "\tsymtab extends past end of an __OBJC section)\n";
5527 } else {
5528 memcpy(&symtab, r, sizeof(struct objc_symtab_t));
5529 if (left > sizeof(struct objc_symtab_t)) {
5530 defs_left = left - sizeof(struct objc_symtab_t);
5531 defs = r + sizeof(struct objc_symtab_t);
5532 }
5533 }
5534 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5535 swapStruct(symtab);
5536
5537 outs() << "\tsel_ref_cnt " << symtab.sel_ref_cnt << "\n";
5538 r = get_pointer_32(symtab.refs, xoffset, left, xS, &info, true);
5539 outs() << "\trefs " << format("0x%08" PRIx32, symtab.refs);
5540 if (r == nullptr)
5541 outs() << " (not in an __OBJC section)";
5542 outs() << "\n";
5543 outs() << "\tcls_def_cnt " << symtab.cls_def_cnt << "\n";
5544 outs() << "\tcat_def_cnt " << symtab.cat_def_cnt << "\n";
5545 if (symtab.cls_def_cnt > 0)
5546 outs() << "\tClass Definitions\n";
5547 for (j = 0; j < symtab.cls_def_cnt; j++) {
5548 if ((j + 1) * sizeof(uint32_t) > defs_left) {
5549 outs() << "\t(remaining class defs entries entends past the end of the "
5550 << "section)\n";
5551 break;
5552 }
5553 memcpy(&def, defs + j * sizeof(uint32_t), sizeof(uint32_t));
5554 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5555 sys::swapByteOrder(def);
5556
5557 r = get_pointer_32(def, xoffset, left, xS, &info, true);
5558 outs() << "\tdefs[" << j << "] " << format("0x%08" PRIx32, def);
5559 if (r != nullptr) {
5560 if (left > sizeof(struct objc_class_t)) {
5561 outs() << "\n";
5562 memcpy(&objc_class, r, sizeof(struct objc_class_t));
5563 } else {
5564 outs() << " (entends past the end of the section)\n";
5565 memset(&objc_class, '\0', sizeof(struct objc_class_t));
5566 memcpy(&objc_class, r, left);
5567 }
5568 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5569 swapStruct(objc_class);
5570 print_objc_class_t(&objc_class, &info);
5571 } else {
5572 outs() << "(not in an __OBJC section)\n";
5573 }
5574
5575 if (CLS_GETINFO(&objc_class, CLS_CLASS)) {
5576 outs() << "\tMeta Class";
5577 r = get_pointer_32(objc_class.isa, xoffset, left, xS, &info, true);
5578 if (r != nullptr) {
5579 if (left > sizeof(struct objc_class_t)) {
5580 outs() << "\n";
5581 memcpy(&objc_class, r, sizeof(struct objc_class_t));
5582 } else {
5583 outs() << " (entends past the end of the section)\n";
5584 memset(&objc_class, '\0', sizeof(struct objc_class_t));
5585 memcpy(&objc_class, r, left);
5586 }
5587 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5588 swapStruct(objc_class);
5589 print_objc_class_t(&objc_class, &info);
5590 } else {
5591 outs() << "(not in an __OBJC section)\n";
5592 }
5593 }
5594 }
5595 if (symtab.cat_def_cnt > 0)
5596 outs() << "\tCategory Definitions\n";
5597 for (j = 0; j < symtab.cat_def_cnt; j++) {
5598 if ((j + symtab.cls_def_cnt + 1) * sizeof(uint32_t) > defs_left) {
5599 outs() << "\t(remaining category defs entries entends past the end of "
5600 << "the section)\n";
5601 break;
5602 }
5603 memcpy(&def, defs + (j + symtab.cls_def_cnt) * sizeof(uint32_t),
5604 sizeof(uint32_t));
5605 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5606 sys::swapByteOrder(def);
5607
5608 r = get_pointer_32(def, xoffset, left, xS, &info, true);
5609 outs() << "\tdefs[" << j + symtab.cls_def_cnt << "] "
5610 << format("0x%08" PRIx32, def);
5611 if (r != nullptr) {
5612 if (left > sizeof(struct objc_category_t)) {
5613 outs() << "\n";
5614 memcpy(&objc_category, r, sizeof(struct objc_category_t));
5615 } else {
5616 outs() << " (entends past the end of the section)\n";
5617 memset(&objc_category, '\0', sizeof(struct objc_category_t));
5618 memcpy(&objc_category, r, left);
5619 }
5620 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5621 swapStruct(objc_category);
5622 print_objc_objc_category_t(&objc_category, &info);
5623 } else {
5624 outs() << "(not in an __OBJC section)\n";
5625 }
5626 }
5627 }
5628 const SectionRef II = get_section(O, "__OBJC", "__image_info");
5629 if (II != SectionRef())
5630 print_image_info(II, &info);
5631
5632 return true;
Kevin Enderby0fc11822015-04-01 20:57:01 +00005633}
5634
Kevin Enderby4ad9bde2015-04-16 22:33:20 +00005635static void DumpProtocolSection(MachOObjectFile *O, const char *sect,
5636 uint32_t size, uint32_t addr) {
5637 SymbolAddressMap AddrMap;
5638 CreateSymbolAddressMap(O, &AddrMap);
5639
5640 std::vector<SectionRef> Sections;
5641 for (const SectionRef &Section : O->sections()) {
5642 StringRef SectName;
5643 Section.getName(SectName);
5644 Sections.push_back(Section);
5645 }
5646
5647 struct DisassembleInfo info;
5648 // Set up the block of info used by the Symbolizer call backs.
5649 info.verbose = true;
5650 info.O = O;
5651 info.AddrMap = &AddrMap;
5652 info.Sections = &Sections;
5653 info.class_name = nullptr;
5654 info.selector_name = nullptr;
5655 info.method = nullptr;
5656 info.demangled_name = nullptr;
5657 info.bindtable = nullptr;
5658 info.adrp_addr = 0;
5659 info.adrp_inst = 0;
5660
5661 const char *p;
5662 struct objc_protocol_t protocol;
5663 uint32_t left, paddr;
5664 for (p = sect; p < sect + size; p += sizeof(struct objc_protocol_t)) {
5665 memset(&protocol, '\0', sizeof(struct objc_protocol_t));
5666 left = size - (p - sect);
5667 if (left < sizeof(struct objc_protocol_t)) {
5668 outs() << "Protocol extends past end of __protocol section\n";
5669 memcpy(&protocol, p, left);
5670 } else
5671 memcpy(&protocol, p, sizeof(struct objc_protocol_t));
5672 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5673 swapStruct(protocol);
5674 paddr = addr + (p - sect);
5675 outs() << "Protocol " << format("0x%" PRIx32, paddr);
5676 if (print_protocol(paddr, 0, &info))
5677 outs() << "(not in an __OBJC section)\n";
5678 }
5679}
5680
Kevin Enderby9873e2c2016-05-23 21:34:12 +00005681#ifdef HAVE_LIBXAR
5682inline void swapStruct(struct xar_header &xar) {
5683 sys::swapByteOrder(xar.magic);
5684 sys::swapByteOrder(xar.size);
5685 sys::swapByteOrder(xar.version);
5686 sys::swapByteOrder(xar.toc_length_compressed);
5687 sys::swapByteOrder(xar.toc_length_uncompressed);
5688 sys::swapByteOrder(xar.cksum_alg);
5689}
5690
5691static void PrintModeVerbose(uint32_t mode) {
5692 switch(mode & S_IFMT){
5693 case S_IFDIR:
5694 outs() << "d";
5695 break;
5696 case S_IFCHR:
5697 outs() << "c";
5698 break;
5699 case S_IFBLK:
5700 outs() << "b";
5701 break;
5702 case S_IFREG:
5703 outs() << "-";
5704 break;
5705 case S_IFLNK:
5706 outs() << "l";
5707 break;
5708 case S_IFSOCK:
5709 outs() << "s";
5710 break;
5711 default:
5712 outs() << "?";
5713 break;
5714 }
5715
5716 /* owner permissions */
5717 if(mode & S_IREAD)
5718 outs() << "r";
5719 else
5720 outs() << "-";
5721 if(mode & S_IWRITE)
5722 outs() << "w";
5723 else
5724 outs() << "-";
5725 if(mode & S_ISUID)
5726 outs() << "s";
5727 else if(mode & S_IEXEC)
5728 outs() << "x";
5729 else
5730 outs() << "-";
5731
5732 /* group permissions */
5733 if(mode & (S_IREAD >> 3))
5734 outs() << "r";
5735 else
5736 outs() << "-";
5737 if(mode & (S_IWRITE >> 3))
5738 outs() << "w";
5739 else
5740 outs() << "-";
5741 if(mode & S_ISGID)
5742 outs() << "s";
5743 else if(mode & (S_IEXEC >> 3))
5744 outs() << "x";
5745 else
5746 outs() << "-";
5747
5748 /* other permissions */
5749 if(mode & (S_IREAD >> 6))
5750 outs() << "r";
5751 else
5752 outs() << "-";
5753 if(mode & (S_IWRITE >> 6))
5754 outs() << "w";
5755 else
5756 outs() << "-";
5757 if(mode & S_ISVTX)
5758 outs() << "t";
5759 else if(mode & (S_IEXEC >> 6))
5760 outs() << "x";
5761 else
5762 outs() << "-";
5763}
5764
5765static void PrintXarFilesSummary(const char *XarFilename, xar_t xar) {
5766 xar_iter_t xi;
5767 xar_file_t xf;
5768 xar_iter_t xp;
5769 const char *key, *type, *mode, *user, *group, *size, *mtime, *name, *m;
5770 char *endp;
5771 uint32_t mode_value;
5772
5773 xi = xar_iter_new();
5774 if (!xi) {
5775 errs() << "Can't obtain an xar iterator for xar archive "
5776 << XarFilename << "\n";
5777 return;
5778 }
5779
5780 // Go through the xar's files.
5781 for (xf = xar_file_first(xar, xi); xf; xf = xar_file_next(xi)) {
5782 xp = xar_iter_new();
5783 if(!xp){
5784 errs() << "Can't obtain an xar iterator for xar archive "
5785 << XarFilename << "\n";
5786 return;
5787 }
5788 type = nullptr;
5789 mode = nullptr;
5790 user = nullptr;
5791 group = nullptr;
5792 size = nullptr;
5793 mtime = nullptr;
5794 name = nullptr;
5795 for(key = xar_prop_first(xf, xp); key; key = xar_prop_next(xp)){
5796 const char *val = nullptr;
5797 xar_prop_get(xf, key, &val);
5798#if 0 // Useful for debugging.
5799 outs() << "key: " << key << " value: " << val << "\n";
5800#endif
5801 if(strcmp(key, "type") == 0)
5802 type = val;
5803 if(strcmp(key, "mode") == 0)
5804 mode = val;
5805 if(strcmp(key, "user") == 0)
5806 user = val;
5807 if(strcmp(key, "group") == 0)
5808 group = val;
5809 if(strcmp(key, "data/size") == 0)
5810 size = val;
5811 if(strcmp(key, "mtime") == 0)
5812 mtime = val;
5813 if(strcmp(key, "name") == 0)
5814 name = val;
5815 }
5816 if(mode != nullptr){
5817 mode_value = strtoul(mode, &endp, 8);
5818 if(*endp != '\0')
5819 outs() << "(mode: \"" << mode << "\" contains non-octal chars) ";
5820 if(strcmp(type, "file") == 0)
5821 mode_value |= S_IFREG;
5822 PrintModeVerbose(mode_value);
5823 outs() << " ";
5824 }
5825 if(user != nullptr)
5826 outs() << format("%10s/", user);
5827 if(group != nullptr)
5828 outs() << format("%-10s ", group);
5829 if(size != nullptr)
5830 outs() << format("%7s ", size);
5831 if(mtime != nullptr){
5832 for(m = mtime; *m != 'T' && *m != '\0'; m++)
5833 outs() << *m;
5834 if(*m == 'T')
5835 m++;
5836 outs() << " ";
5837 for( ; *m != 'Z' && *m != '\0'; m++)
5838 outs() << *m;
5839 outs() << " ";
5840 }
5841 if(name != nullptr)
5842 outs() << name;
5843 outs() << "\n";
5844 }
5845}
5846
5847static void DumpBitcodeSection(MachOObjectFile *O, const char *sect,
5848 uint32_t size, bool verbose,
5849 bool PrintXarHeader, bool PrintXarFileHeaders,
5850 std::string XarMemberName) {
5851 if(size < sizeof(struct xar_header)) {
5852 outs() << "size of (__LLVM,__bundle) section too small (smaller than size "
5853 "of struct xar_header)\n";
5854 return;
5855 }
5856 struct xar_header XarHeader;
5857 memcpy(&XarHeader, sect, sizeof(struct xar_header));
5858 if (sys::IsLittleEndianHost)
5859 swapStruct(XarHeader);
5860 if (PrintXarHeader) {
5861 if (!XarMemberName.empty())
5862 outs() << "In xar member " << XarMemberName << ": ";
5863 else
5864 outs() << "For (__LLVM,__bundle) section: ";
5865 outs() << "xar header\n";
5866 if (XarHeader.magic == XAR_HEADER_MAGIC)
5867 outs() << " magic XAR_HEADER_MAGIC\n";
5868 else
5869 outs() << " magic "
5870 << format_hex(XarHeader.magic, 10, true)
5871 << " (not XAR_HEADER_MAGIC)\n";
5872 outs() << " size " << XarHeader.size << "\n";
5873 outs() << " version " << XarHeader.version << "\n";
5874 outs() << " toc_length_compressed " << XarHeader.toc_length_compressed
5875 << "\n";
5876 outs() << "toc_length_uncompressed " << XarHeader.toc_length_uncompressed
5877 << "\n";
5878 outs() << " cksum_alg ";
5879 switch (XarHeader.cksum_alg) {
5880 case XAR_CKSUM_NONE:
5881 outs() << "XAR_CKSUM_NONE\n";
5882 break;
5883 case XAR_CKSUM_SHA1:
5884 outs() << "XAR_CKSUM_SHA1\n";
5885 break;
5886 case XAR_CKSUM_MD5:
5887 outs() << "XAR_CKSUM_MD5\n";
5888 break;
Kevin Enderby42882282016-05-23 22:18:59 +00005889#ifdef XAR_CKSUM_SHA256
Kevin Enderby9873e2c2016-05-23 21:34:12 +00005890 case XAR_CKSUM_SHA256:
5891 outs() << "XAR_CKSUM_SHA256\n";
5892 break;
Kevin Enderby42882282016-05-23 22:18:59 +00005893#endif
5894#ifdef XAR_CKSUM_SHA512
Kevin Enderby9873e2c2016-05-23 21:34:12 +00005895 case XAR_CKSUM_SHA512:
5896 outs() << "XAR_CKSUM_SHA512\n";
5897 break;
Kevin Enderby42882282016-05-23 22:18:59 +00005898#endif
Kevin Enderby9873e2c2016-05-23 21:34:12 +00005899 default:
5900 outs() << XarHeader.cksum_alg << "\n";
5901 }
5902 }
5903
5904 SmallString<128> XarFilename;
5905 int FD;
5906 std::error_code XarEC =
5907 sys::fs::createTemporaryFile("llvm-objdump", "xar", FD, XarFilename);
5908 if (XarEC) {
5909 errs() << XarEC.message() << "\n";
5910 return;
5911 }
5912 tool_output_file XarFile(XarFilename, FD);
5913 raw_fd_ostream &XarOut = XarFile.os();
5914 StringRef XarContents(sect, size);
5915 XarOut << XarContents;
5916 XarOut.close();
5917 if (XarOut.has_error())
5918 return;
5919
5920 xar_t xar = xar_open(XarFilename.c_str(), READ);
5921 if (!xar) {
5922 errs() << "Can't create temporary xar archive " << XarFilename << "\n";
5923 return;
5924 }
5925
5926 SmallString<128> TocFilename;
5927 std::error_code TocEC =
5928 sys::fs::createTemporaryFile("llvm-objdump", "toc", TocFilename);
5929 if (TocEC) {
5930 errs() << TocEC.message() << "\n";
5931 return;
5932 }
5933 xar_serialize(xar, TocFilename.c_str());
5934
5935 if (PrintXarFileHeaders) {
5936 if (!XarMemberName.empty())
5937 outs() << "In xar member " << XarMemberName << ": ";
5938 else
5939 outs() << "For (__LLVM,__bundle) section: ";
5940 outs() << "xar archive files:\n";
5941 PrintXarFilesSummary(XarFilename.c_str(), xar);
5942 }
5943
5944 ErrorOr<std::unique_ptr<MemoryBuffer>> FileOrErr =
5945 MemoryBuffer::getFileOrSTDIN(TocFilename.c_str());
5946 if (std::error_code EC = FileOrErr.getError()) {
5947 errs() << EC.message() << "\n";
5948 return;
5949 }
5950 std::unique_ptr<MemoryBuffer> &Buffer = FileOrErr.get();
5951
5952 if (!XarMemberName.empty())
5953 outs() << "In xar member " << XarMemberName << ": ";
5954 else
5955 outs() << "For (__LLVM,__bundle) section: ";
5956 outs() << "xar table of contents:\n";
5957 outs() << Buffer->getBuffer() << "\n";
5958
5959 // TODO: Go through the xar's files.
5960 xar_iter_t xi = xar_iter_new();
5961 if(!xi){
5962 errs() << "Can't obtain an xar iterator for xar archive "
5963 << XarFilename.c_str() << "\n";
5964 xar_close(xar);
5965 return;
5966 }
5967 for(xar_file_t xf = xar_file_first(xar, xi); xf; xf = xar_file_next(xi)){
5968 const char *key;
5969 xar_iter_t xp;
5970 const char *member_name, *member_type, *member_size_string;
5971 size_t member_size;
5972
5973 xp = xar_iter_new();
5974 if(!xp){
5975 errs() << "Can't obtain an xar iterator for xar archive "
5976 << XarFilename.c_str() << "\n";
5977 xar_close(xar);
5978 return;
5979 }
5980 member_name = NULL;
5981 member_type = NULL;
5982 member_size_string = NULL;
5983 for(key = xar_prop_first(xf, xp); key; key = xar_prop_next(xp)){
5984 const char *val = nullptr;
5985 xar_prop_get(xf, key, &val);
5986#if 0 // Useful for debugging.
5987 outs() << "key: " << key << " value: " << val << "\n";
5988#endif
5989 if(strcmp(key, "name") == 0)
5990 member_name = val;
5991 if(strcmp(key, "type") == 0)
5992 member_type = val;
5993 if(strcmp(key, "data/size") == 0)
5994 member_size_string = val;
5995 }
5996 /*
5997 * If we find a file with a name, date/size and type properties
5998 * and with the type being "file" see if that is a xar file.
5999 */
6000 if (member_name != NULL && member_type != NULL &&
6001 strcmp(member_type, "file") == 0 &&
6002 member_size_string != NULL){
6003 // Extract the file into a buffer.
6004 char *endptr;
6005 member_size = strtoul(member_size_string, &endptr, 10);
6006 if (*endptr == '\0' && member_size != 0) {
6007 char *buffer = (char *) ::operator new (member_size);
6008 if (xar_extract_tobuffersz(xar, xf, &buffer, &member_size) == 0) {
6009#if 0 // Useful for debugging.
6010 outs() << "xar member: " << member_name << " extracted\n";
6011#endif
6012 // Set the XarMemberName we want to see printed in the header.
6013 std::string OldXarMemberName;
6014 // If XarMemberName is already set this is nested. So
6015 // save the old name and create the nested name.
6016 if (!XarMemberName.empty()) {
6017 OldXarMemberName = XarMemberName;
6018 XarMemberName =
6019 (Twine("[") + XarMemberName + "]" + member_name).str();
6020 } else {
6021 OldXarMemberName = "";
6022 XarMemberName = member_name;
6023 }
6024 // See if this is could be a xar file (nested).
6025 if (member_size >= sizeof(struct xar_header)) {
6026#if 0 // Useful for debugging.
6027 outs() << "could be a xar file: " << member_name << "\n";
6028#endif
6029 memcpy((char *)&XarHeader, buffer, sizeof(struct xar_header));
6030 if (sys::IsLittleEndianHost)
6031 swapStruct(XarHeader);
6032 if(XarHeader.magic == XAR_HEADER_MAGIC)
6033 DumpBitcodeSection(O, buffer, member_size, verbose,
6034 PrintXarHeader, PrintXarFileHeaders,
6035 XarMemberName);
6036 }
6037 XarMemberName = OldXarMemberName;
6038 }
6039 delete buffer;
6040 }
6041 }
6042 xar_iter_free(xp);
6043 }
6044 xar_close(xar);
6045}
6046#endif // defined(HAVE_LIBXAR)
6047
Kevin Enderby0fc11822015-04-01 20:57:01 +00006048static void printObjcMetaData(MachOObjectFile *O, bool verbose) {
6049 if (O->is64Bit())
6050 printObjc2_64bit_MetaData(O, verbose);
6051 else {
6052 MachO::mach_header H;
6053 H = O->getHeader();
6054 if (H.cputype == MachO::CPU_TYPE_ARM)
6055 printObjc2_32bit_MetaData(O, verbose);
6056 else {
6057 // This is the 32-bit non-arm cputype case. Which is normally
6058 // the first Objective-C ABI. But it may be the case of a
6059 // binary for the iOS simulator which is the second Objective-C
6060 // ABI. In that case printObjc1_32bit_MetaData() will determine that
6061 // and return false.
Hans Wennborgcc9deb42015-09-29 18:02:48 +00006062 if (!printObjc1_32bit_MetaData(O, verbose))
Kevin Enderby0fc11822015-04-01 20:57:01 +00006063 printObjc2_32bit_MetaData(O, verbose);
6064 }
6065 }
6066}
6067
Kevin Enderbybf246f52014-09-24 23:08:22 +00006068// GuessLiteralPointer returns a string which for the item in the Mach-O file
6069// for the address passed in as ReferenceValue for printing as a comment with
6070// the instruction and also returns the corresponding type of that item
6071// indirectly through ReferenceType.
6072//
6073// If ReferenceValue is an address of literal cstring then a pointer to the
6074// cstring is returned and ReferenceType is set to
6075// LLVMDisassembler_ReferenceType_Out_LitPool_CstrAddr .
6076//
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006077// If ReferenceValue is an address of an Objective-C CFString, Selector ref or
6078// Class ref that name is returned and the ReferenceType is set accordingly.
6079//
6080// Lastly, literals which are Symbol address in a literal pool are looked for
6081// and if found the symbol name is returned and ReferenceType is set to
6082// LLVMDisassembler_ReferenceType_Out_LitPool_SymAddr .
6083//
6084// If there is no item in the Mach-O file for the address passed in as
6085// ReferenceValue nullptr is returned and ReferenceType is unchanged.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00006086static const char *GuessLiteralPointer(uint64_t ReferenceValue,
6087 uint64_t ReferencePC,
6088 uint64_t *ReferenceType,
6089 struct DisassembleInfo *info) {
Kevin Enderbybf246f52014-09-24 23:08:22 +00006090 // First see if there is an external relocation entry at the ReferencePC.
Kevin Enderbyd90a4172015-10-10 00:05:01 +00006091 if (info->O->getHeader().filetype == MachO::MH_OBJECT) {
6092 uint64_t sect_addr = info->S.getAddress();
6093 uint64_t sect_offset = ReferencePC - sect_addr;
6094 bool reloc_found = false;
6095 DataRefImpl Rel;
6096 MachO::any_relocation_info RE;
6097 bool isExtern = false;
6098 SymbolRef Symbol;
6099 for (const RelocationRef &Reloc : info->S.relocations()) {
6100 uint64_t RelocOffset = Reloc.getOffset();
6101 if (RelocOffset == sect_offset) {
6102 Rel = Reloc.getRawDataRefImpl();
6103 RE = info->O->getRelocation(Rel);
6104 if (info->O->isRelocationScattered(RE))
6105 continue;
6106 isExtern = info->O->getPlainRelocationExternal(RE);
6107 if (isExtern) {
6108 symbol_iterator RelocSym = Reloc.getSymbol();
6109 Symbol = *RelocSym;
6110 }
6111 reloc_found = true;
6112 break;
Kevin Enderbybf246f52014-09-24 23:08:22 +00006113 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00006114 }
Kevin Enderbyd90a4172015-10-10 00:05:01 +00006115 // If there is an external relocation entry for a symbol in a section
6116 // then used that symbol's value for the value of the reference.
6117 if (reloc_found && isExtern) {
6118 if (info->O->getAnyRelocationPCRel(RE)) {
6119 unsigned Type = info->O->getAnyRelocationType(RE);
6120 if (Type == MachO::X86_64_RELOC_SIGNED) {
6121 ReferenceValue = Symbol.getValue();
6122 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00006123 }
6124 }
6125 }
6126
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006127 // Look for literals such as Objective-C CFStrings refs, Selector refs,
6128 // Message refs and Class refs.
6129 bool classref, selref, msgref, cfstring;
6130 uint64_t pointer_value = GuessPointerPointer(ReferenceValue, info, classref,
6131 selref, msgref, cfstring);
David Blaikie33dd45d02015-03-23 18:39:02 +00006132 if (classref && pointer_value == 0) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006133 // Note the ReferenceValue is a pointer into the __objc_classrefs section.
6134 // And the pointer_value in that section is typically zero as it will be
6135 // set by dyld as part of the "bind information".
6136 const char *name = get_dyld_bind_info_symbolname(ReferenceValue, info);
6137 if (name != nullptr) {
6138 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Class_Ref;
Hans Wennborgdb53e302014-10-23 21:59:17 +00006139 const char *class_name = strrchr(name, '$');
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006140 if (class_name != nullptr && class_name[1] == '_' &&
6141 class_name[2] != '\0') {
6142 info->class_name = class_name + 2;
6143 return name;
6144 }
6145 }
6146 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00006147
David Blaikie33dd45d02015-03-23 18:39:02 +00006148 if (classref) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006149 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Class_Ref;
6150 const char *name =
6151 get_objc2_64bit_class_name(pointer_value, ReferenceValue, info);
6152 if (name != nullptr)
6153 info->class_name = name;
6154 else
6155 name = "bad class ref";
Kevin Enderbybf246f52014-09-24 23:08:22 +00006156 return name;
6157 }
6158
David Blaikie33dd45d02015-03-23 18:39:02 +00006159 if (cfstring) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006160 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_CFString_Ref;
6161 const char *name = get_objc2_64bit_cfstring_name(ReferenceValue, info);
6162 return name;
6163 }
6164
David Blaikie33dd45d02015-03-23 18:39:02 +00006165 if (selref && pointer_value == 0)
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006166 pointer_value = get_objc2_64bit_selref(ReferenceValue, info);
6167
6168 if (pointer_value != 0)
6169 ReferenceValue = pointer_value;
6170
6171 const char *name = GuessCstringPointer(ReferenceValue, info);
6172 if (name) {
David Blaikie33dd45d02015-03-23 18:39:02 +00006173 if (pointer_value != 0 && selref) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006174 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Selector_Ref;
6175 info->selector_name = name;
David Blaikie33dd45d02015-03-23 18:39:02 +00006176 } else if (pointer_value != 0 && msgref) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006177 info->class_name = nullptr;
6178 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message_Ref;
6179 info->selector_name = name;
6180 } else
6181 *ReferenceType = LLVMDisassembler_ReferenceType_Out_LitPool_CstrAddr;
6182 return name;
6183 }
6184
6185 // Lastly look for an indirect symbol with this ReferenceValue which is in
6186 // a literal pool. If found return that symbol name.
6187 name = GuessIndirectSymbol(ReferenceValue, info);
6188 if (name) {
6189 *ReferenceType = LLVMDisassembler_ReferenceType_Out_LitPool_SymAddr;
6190 return name;
6191 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00006192
6193 return nullptr;
6194}
6195
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006196// SymbolizerSymbolLookUp is the symbol lookup function passed when creating
Kevin Enderbybf246f52014-09-24 23:08:22 +00006197// the Symbolizer. It looks up the ReferenceValue using the info passed via the
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006198// pointer to the struct DisassembleInfo that was passed when MCSymbolizer
6199// is created and returns the symbol name that matches the ReferenceValue or
6200// nullptr if none. The ReferenceType is passed in for the IN type of
6201// reference the instruction is making from the values in defined in the header
6202// "llvm-c/Disassembler.h". On return the ReferenceType can set to a specific
6203// Out type and the ReferenceName will also be set which is added as a comment
6204// to the disassembled instruction.
6205//
Kevin Enderby04bf6932014-10-28 23:39:46 +00006206#if HAVE_CXXABI_H
6207// If the symbol name is a C++ mangled name then the demangled name is
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006208// returned through ReferenceName and ReferenceType is set to
6209// LLVMDisassembler_ReferenceType_DeMangled_Name .
Kevin Enderby04bf6932014-10-28 23:39:46 +00006210#endif
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006211//
6212// When this is called to get a symbol name for a branch target then the
6213// ReferenceType will be LLVMDisassembler_ReferenceType_In_Branch and then
6214// SymbolValue will be looked for in the indirect symbol table to determine if
6215// it is an address for a symbol stub. If so then the symbol name for that
6216// stub is returned indirectly through ReferenceName and then ReferenceType is
6217// set to LLVMDisassembler_ReferenceType_Out_SymbolStub.
6218//
Kevin Enderbybf246f52014-09-24 23:08:22 +00006219// When this is called with an value loaded via a PC relative load then
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006220// ReferenceType will be LLVMDisassembler_ReferenceType_In_PCrel_Load then the
6221// SymbolValue is checked to be an address of literal pointer, symbol pointer,
6222// or an Objective-C meta data reference. If so the output ReferenceType is
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006223// set to correspond to that as well as setting the ReferenceName.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00006224static const char *SymbolizerSymbolLookUp(void *DisInfo,
6225 uint64_t ReferenceValue,
6226 uint64_t *ReferenceType,
6227 uint64_t ReferencePC,
6228 const char **ReferenceName) {
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006229 struct DisassembleInfo *info = (struct DisassembleInfo *)DisInfo;
Kevin Enderbybf246f52014-09-24 23:08:22 +00006230 // If no verbose symbolic information is wanted then just return nullptr.
David Blaikie33dd45d02015-03-23 18:39:02 +00006231 if (!info->verbose) {
Kevin Enderbybf246f52014-09-24 23:08:22 +00006232 *ReferenceName = nullptr;
6233 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006234 return nullptr;
6235 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00006236
Kevin Enderbyf6d25852015-01-31 00:37:11 +00006237 const char *SymbolName = GuessSymbolName(ReferenceValue, info->AddrMap);
Kevin Enderbybf246f52014-09-24 23:08:22 +00006238
Kevin Enderby85974882014-09-26 22:20:44 +00006239 if (*ReferenceType == LLVMDisassembler_ReferenceType_In_Branch) {
6240 *ReferenceName = GuessIndirectSymbol(ReferenceValue, info);
Kevin Enderby04bf6932014-10-28 23:39:46 +00006241 if (*ReferenceName != nullptr) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006242 method_reference(info, ReferenceType, ReferenceName);
6243 if (*ReferenceType != LLVMDisassembler_ReferenceType_Out_Objc_Message)
6244 *ReferenceType = LLVMDisassembler_ReferenceType_Out_SymbolStub;
6245 } else
Kevin Enderby04bf6932014-10-28 23:39:46 +00006246#if HAVE_CXXABI_H
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006247 if (SymbolName != nullptr && strncmp(SymbolName, "__Z", 3) == 0) {
Kevin Enderby04bf6932014-10-28 23:39:46 +00006248 if (info->demangled_name != nullptr)
6249 free(info->demangled_name);
6250 int status;
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006251 info->demangled_name =
6252 abi::__cxa_demangle(SymbolName + 1, nullptr, nullptr, &status);
Kevin Enderby04bf6932014-10-28 23:39:46 +00006253 if (info->demangled_name != nullptr) {
6254 *ReferenceName = info->demangled_name;
6255 *ReferenceType = LLVMDisassembler_ReferenceType_DeMangled_Name;
6256 } else
6257 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
6258 } else
6259#endif
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006260 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
6261 } else if (*ReferenceType == LLVMDisassembler_ReferenceType_In_PCrel_Load) {
6262 *ReferenceName =
6263 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
Kevin Enderby85974882014-09-26 22:20:44 +00006264 if (*ReferenceName)
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006265 method_reference(info, ReferenceType, ReferenceName);
Kevin Enderby85974882014-09-26 22:20:44 +00006266 else
6267 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
Kevin Enderbyae3c1262014-11-14 21:52:18 +00006268 // If this is arm64 and the reference is an adrp instruction save the
6269 // instruction, passed in ReferenceValue and the address of the instruction
6270 // for use later if we see and add immediate instruction.
6271 } else if (info->O->getArch() == Triple::aarch64 &&
6272 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADRP) {
6273 info->adrp_inst = ReferenceValue;
6274 info->adrp_addr = ReferencePC;
6275 SymbolName = nullptr;
6276 *ReferenceName = nullptr;
6277 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
6278 // If this is arm64 and reference is an add immediate instruction and we
6279 // have
6280 // seen an adrp instruction just before it and the adrp's Xd register
6281 // matches
6282 // this add's Xn register reconstruct the value being referenced and look to
6283 // see if it is a literal pointer. Note the add immediate instruction is
6284 // passed in ReferenceValue.
6285 } else if (info->O->getArch() == Triple::aarch64 &&
6286 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADDXri &&
6287 ReferencePC - 4 == info->adrp_addr &&
6288 (info->adrp_inst & 0x9f000000) == 0x90000000 &&
6289 (info->adrp_inst & 0x1f) == ((ReferenceValue >> 5) & 0x1f)) {
6290 uint32_t addxri_inst;
6291 uint64_t adrp_imm, addxri_imm;
6292
6293 adrp_imm =
6294 ((info->adrp_inst & 0x00ffffe0) >> 3) | ((info->adrp_inst >> 29) & 0x3);
6295 if (info->adrp_inst & 0x0200000)
6296 adrp_imm |= 0xfffffffffc000000LL;
6297
6298 addxri_inst = ReferenceValue;
6299 addxri_imm = (addxri_inst >> 10) & 0xfff;
6300 if (((addxri_inst >> 22) & 0x3) == 1)
6301 addxri_imm <<= 12;
6302
6303 ReferenceValue = (info->adrp_addr & 0xfffffffffffff000LL) +
6304 (adrp_imm << 12) + addxri_imm;
6305
6306 *ReferenceName =
6307 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
6308 if (*ReferenceName == nullptr)
6309 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
6310 // If this is arm64 and the reference is a load register instruction and we
6311 // have seen an adrp instruction just before it and the adrp's Xd register
6312 // matches this add's Xn register reconstruct the value being referenced and
6313 // look to see if it is a literal pointer. Note the load register
6314 // instruction is passed in ReferenceValue.
6315 } else if (info->O->getArch() == Triple::aarch64 &&
6316 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_LDRXui &&
6317 ReferencePC - 4 == info->adrp_addr &&
6318 (info->adrp_inst & 0x9f000000) == 0x90000000 &&
6319 (info->adrp_inst & 0x1f) == ((ReferenceValue >> 5) & 0x1f)) {
6320 uint32_t ldrxui_inst;
6321 uint64_t adrp_imm, ldrxui_imm;
6322
6323 adrp_imm =
6324 ((info->adrp_inst & 0x00ffffe0) >> 3) | ((info->adrp_inst >> 29) & 0x3);
6325 if (info->adrp_inst & 0x0200000)
6326 adrp_imm |= 0xfffffffffc000000LL;
6327
6328 ldrxui_inst = ReferenceValue;
6329 ldrxui_imm = (ldrxui_inst >> 10) & 0xfff;
6330
6331 ReferenceValue = (info->adrp_addr & 0xfffffffffffff000LL) +
6332 (adrp_imm << 12) + (ldrxui_imm << 3);
6333
6334 *ReferenceName =
6335 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
6336 if (*ReferenceName == nullptr)
6337 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
6338 }
6339 // If this arm64 and is an load register (PC-relative) instruction the
6340 // ReferenceValue is the PC plus the immediate value.
6341 else if (info->O->getArch() == Triple::aarch64 &&
6342 (*ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_LDRXl ||
6343 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADR)) {
6344 *ReferenceName =
6345 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
6346 if (*ReferenceName == nullptr)
6347 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
Kevin Enderby85974882014-09-26 22:20:44 +00006348 }
Kevin Enderby04bf6932014-10-28 23:39:46 +00006349#if HAVE_CXXABI_H
6350 else if (SymbolName != nullptr && strncmp(SymbolName, "__Z", 3) == 0) {
6351 if (info->demangled_name != nullptr)
6352 free(info->demangled_name);
6353 int status;
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006354 info->demangled_name =
6355 abi::__cxa_demangle(SymbolName + 1, nullptr, nullptr, &status);
Kevin Enderby04bf6932014-10-28 23:39:46 +00006356 if (info->demangled_name != nullptr) {
6357 *ReferenceName = info->demangled_name;
6358 *ReferenceType = LLVMDisassembler_ReferenceType_DeMangled_Name;
6359 }
6360 }
6361#endif
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006362 else {
Kevin Enderbybf246f52014-09-24 23:08:22 +00006363 *ReferenceName = nullptr;
6364 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
6365 }
6366
6367 return SymbolName;
6368}
6369
Kevin Enderbybf246f52014-09-24 23:08:22 +00006370/// \brief Emits the comments that are stored in the CommentStream.
6371/// Each comment in the CommentStream must end with a newline.
6372static void emitComments(raw_svector_ostream &CommentStream,
6373 SmallString<128> &CommentsToEmit,
6374 formatted_raw_ostream &FormattedOS,
6375 const MCAsmInfo &MAI) {
6376 // Flush the stream before taking its content.
Kevin Enderbybf246f52014-09-24 23:08:22 +00006377 StringRef Comments = CommentsToEmit.str();
6378 // Get the default information for printing a comment.
6379 const char *CommentBegin = MAI.getCommentString();
6380 unsigned CommentColumn = MAI.getCommentColumn();
6381 bool IsFirst = true;
6382 while (!Comments.empty()) {
6383 if (!IsFirst)
6384 FormattedOS << '\n';
6385 // Emit a line of comments.
6386 FormattedOS.PadToColumn(CommentColumn);
6387 size_t Position = Comments.find('\n');
6388 FormattedOS << CommentBegin << ' ' << Comments.substr(0, Position);
6389 // Move after the newline character.
6390 Comments = Comments.substr(Position + 1);
6391 IsFirst = false;
6392 }
6393 FormattedOS.flush();
6394
6395 // Tell the comment stream that the vector changed underneath it.
6396 CommentsToEmit.clear();
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006397}
6398
Kevin Enderby95df54c2015-02-04 01:01:38 +00006399static void DisassembleMachO(StringRef Filename, MachOObjectFile *MachOOF,
6400 StringRef DisSegName, StringRef DisSectName) {
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006401 const char *McpuDefault = nullptr;
6402 const Target *ThumbTarget = nullptr;
6403 const Target *TheTarget = GetTarget(MachOOF, &McpuDefault, &ThumbTarget);
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006404 if (!TheTarget) {
6405 // GetTarget prints out stuff.
6406 return;
6407 }
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006408 if (MCPU.empty() && McpuDefault)
6409 MCPU = McpuDefault;
6410
Ahmed Charles56440fd2014-03-06 05:51:42 +00006411 std::unique_ptr<const MCInstrInfo> InstrInfo(TheTarget->createMCInstrInfo());
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006412 std::unique_ptr<const MCInstrInfo> ThumbInstrInfo;
Kevin Enderbyae3c1262014-11-14 21:52:18 +00006413 if (ThumbTarget)
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006414 ThumbInstrInfo.reset(ThumbTarget->createMCInstrInfo());
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006415
Kevin Enderbyc9595622014-08-06 23:24:41 +00006416 // Package up features to be passed to target/subtarget
6417 std::string FeaturesStr;
6418 if (MAttrs.size()) {
6419 SubtargetFeatures Features;
6420 for (unsigned i = 0; i != MAttrs.size(); ++i)
6421 Features.AddFeature(MAttrs[i]);
6422 FeaturesStr = Features.getString();
6423 }
6424
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006425 // Set up disassembler.
Ahmed Charles56440fd2014-03-06 05:51:42 +00006426 std::unique_ptr<const MCRegisterInfo> MRI(
6427 TheTarget->createMCRegInfo(TripleName));
6428 std::unique_ptr<const MCAsmInfo> AsmInfo(
Rafael Espindola227144c2013-05-13 01:16:13 +00006429 TheTarget->createMCAsmInfo(*MRI, TripleName));
Ahmed Charles56440fd2014-03-06 05:51:42 +00006430 std::unique_ptr<const MCSubtargetInfo> STI(
Kevin Enderbyc9595622014-08-06 23:24:41 +00006431 TheTarget->createMCSubtargetInfo(TripleName, MCPU, FeaturesStr));
Craig Toppere6cb63e2014-04-25 04:24:47 +00006432 MCContext Ctx(AsmInfo.get(), MRI.get(), nullptr);
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006433 std::unique_ptr<MCDisassembler> DisAsm(
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006434 TheTarget->createMCDisassembler(*STI, Ctx));
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006435 std::unique_ptr<MCSymbolizer> Symbolizer;
6436 struct DisassembleInfo SymbolizerInfo;
6437 std::unique_ptr<MCRelocationInfo> RelInfo(
6438 TheTarget->createMCRelocationInfo(TripleName, Ctx));
6439 if (RelInfo) {
6440 Symbolizer.reset(TheTarget->createMCSymbolizer(
6441 TripleName, SymbolizerGetOpInfo, SymbolizerSymbolLookUp,
David Blaikie186db432015-01-18 20:45:48 +00006442 &SymbolizerInfo, &Ctx, std::move(RelInfo)));
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006443 DisAsm->setSymbolizer(std::move(Symbolizer));
6444 }
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006445 int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
Ahmed Charles56440fd2014-03-06 05:51:42 +00006446 std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
Daniel Sanders50f17232015-09-15 16:17:27 +00006447 Triple(TripleName), AsmPrinterVariant, *AsmInfo, *InstrInfo, *MRI));
Kevin Enderbybf246f52014-09-24 23:08:22 +00006448 // Set the display preference for hex vs. decimal immediates.
6449 IP->setPrintImmHex(PrintImmHex);
6450 // Comment stream and backing vector.
6451 SmallString<128> CommentsToEmit;
6452 raw_svector_ostream CommentStream(CommentsToEmit);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00006453 // FIXME: Setting the CommentStream in the InstPrinter is problematic in that
6454 // if it is done then arm64 comments for string literals don't get printed
6455 // and some constant get printed instead and not setting it causes intel
6456 // (32-bit and 64-bit) comments printed with different spacing before the
6457 // comment causing different diffs with the 'C' disassembler library API.
6458 // IP->setCommentStream(CommentStream);
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00006459
Kevin Enderbyae3c1262014-11-14 21:52:18 +00006460 if (!AsmInfo || !STI || !DisAsm || !IP) {
Michael J. Spencerc1363cf2011-10-07 19:25:47 +00006461 errs() << "error: couldn't initialize disassembler for target "
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00006462 << TripleName << '\n';
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006463 return;
6464 }
6465
Tim Northover09ca33e2016-04-22 23:23:31 +00006466 // Set up separate thumb disassembler if needed.
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006467 std::unique_ptr<const MCRegisterInfo> ThumbMRI;
6468 std::unique_ptr<const MCAsmInfo> ThumbAsmInfo;
6469 std::unique_ptr<const MCSubtargetInfo> ThumbSTI;
Kevin Enderby930fdc72014-11-06 19:00:13 +00006470 std::unique_ptr<MCDisassembler> ThumbDisAsm;
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006471 std::unique_ptr<MCInstPrinter> ThumbIP;
6472 std::unique_ptr<MCContext> ThumbCtx;
Kevin Enderby930fdc72014-11-06 19:00:13 +00006473 std::unique_ptr<MCSymbolizer> ThumbSymbolizer;
6474 struct DisassembleInfo ThumbSymbolizerInfo;
6475 std::unique_ptr<MCRelocationInfo> ThumbRelInfo;
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006476 if (ThumbTarget) {
6477 ThumbMRI.reset(ThumbTarget->createMCRegInfo(ThumbTripleName));
6478 ThumbAsmInfo.reset(
6479 ThumbTarget->createMCAsmInfo(*ThumbMRI, ThumbTripleName));
6480 ThumbSTI.reset(
6481 ThumbTarget->createMCSubtargetInfo(ThumbTripleName, MCPU, FeaturesStr));
6482 ThumbCtx.reset(new MCContext(ThumbAsmInfo.get(), ThumbMRI.get(), nullptr));
6483 ThumbDisAsm.reset(ThumbTarget->createMCDisassembler(*ThumbSTI, *ThumbCtx));
Kevin Enderby930fdc72014-11-06 19:00:13 +00006484 MCContext *PtrThumbCtx = ThumbCtx.get();
6485 ThumbRelInfo.reset(
6486 ThumbTarget->createMCRelocationInfo(ThumbTripleName, *PtrThumbCtx));
6487 if (ThumbRelInfo) {
6488 ThumbSymbolizer.reset(ThumbTarget->createMCSymbolizer(
6489 ThumbTripleName, SymbolizerGetOpInfo, SymbolizerSymbolLookUp,
David Blaikie186db432015-01-18 20:45:48 +00006490 &ThumbSymbolizerInfo, PtrThumbCtx, std::move(ThumbRelInfo)));
Kevin Enderby930fdc72014-11-06 19:00:13 +00006491 ThumbDisAsm->setSymbolizer(std::move(ThumbSymbolizer));
6492 }
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006493 int ThumbAsmPrinterVariant = ThumbAsmInfo->getAssemblerDialect();
6494 ThumbIP.reset(ThumbTarget->createMCInstPrinter(
Daniel Sanders50f17232015-09-15 16:17:27 +00006495 Triple(ThumbTripleName), ThumbAsmPrinterVariant, *ThumbAsmInfo,
6496 *ThumbInstrInfo, *ThumbMRI));
Kevin Enderbybf246f52014-09-24 23:08:22 +00006497 // Set the display preference for hex vs. decimal immediates.
6498 ThumbIP->setPrintImmHex(PrintImmHex);
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006499 }
6500
Kevin Enderbyae3c1262014-11-14 21:52:18 +00006501 if (ThumbTarget && (!ThumbAsmInfo || !ThumbSTI || !ThumbDisAsm || !ThumbIP)) {
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006502 errs() << "error: couldn't initialize disassembler for target "
6503 << ThumbTripleName << '\n';
6504 return;
6505 }
6506
Charles Davis8bdfafd2013-09-01 04:28:48 +00006507 MachO::mach_header Header = MachOOF->getHeader();
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006508
Ahmed Bougachaaa790682013-05-24 01:07:04 +00006509 // FIXME: Using the -cfg command line option, this code used to be able to
6510 // annotate relocations with the referenced symbol's name, and if this was
6511 // inside a __[cf]string section, the data it points to. This is now replaced
6512 // by the upcoming MCSymbolizer, which needs the appropriate setup done above.
Owen Andersond9243c42011-10-17 21:37:35 +00006513 std::vector<SectionRef> Sections;
6514 std::vector<SymbolRef> Symbols;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006515 SmallVector<uint64_t, 8> FoundFns;
Kevin Enderby273ae012013-06-06 17:20:50 +00006516 uint64_t BaseSegmentAddress;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006517
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00006518 getSectionsAndSymbols(MachOOF, Sections, Symbols, FoundFns,
Kevin Enderby273ae012013-06-06 17:20:50 +00006519 BaseSegmentAddress);
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006520
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006521 // Sort the symbols by address, just in case they didn't come in that way.
Owen Andersond9243c42011-10-17 21:37:35 +00006522 std::sort(Symbols.begin(), Symbols.end(), SymbolSorter());
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006523
Kevin Enderby273ae012013-06-06 17:20:50 +00006524 // Build a data in code table that is sorted on by the address of each entry.
6525 uint64_t BaseAddress = 0;
Charles Davis8bdfafd2013-09-01 04:28:48 +00006526 if (Header.filetype == MachO::MH_OBJECT)
Rafael Espindola80291272014-10-08 15:28:58 +00006527 BaseAddress = Sections[0].getAddress();
Kevin Enderby273ae012013-06-06 17:20:50 +00006528 else
6529 BaseAddress = BaseSegmentAddress;
6530 DiceTable Dices;
Kevin Enderby273ae012013-06-06 17:20:50 +00006531 for (dice_iterator DI = MachOOF->begin_dices(), DE = MachOOF->end_dices();
Rafael Espindola5e812af2014-01-30 02:49:50 +00006532 DI != DE; ++DI) {
Kevin Enderby273ae012013-06-06 17:20:50 +00006533 uint32_t Offset;
6534 DI->getOffset(Offset);
6535 Dices.push_back(std::make_pair(BaseAddress + Offset, *DI));
6536 }
6537 array_pod_sort(Dices.begin(), Dices.end());
6538
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006539#ifndef NDEBUG
6540 raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls();
6541#else
6542 raw_ostream &DebugOut = nulls();
6543#endif
6544
Ahmed Charles56440fd2014-03-06 05:51:42 +00006545 std::unique_ptr<DIContext> diContext;
Rafael Espindola9b709252013-04-13 01:45:40 +00006546 ObjectFile *DbgObj = MachOOF;
Benjamin Kramer699128e2011-09-21 01:13:19 +00006547 // Try to find debug info and set up the DIContext for it.
6548 if (UseDbg) {
Benjamin Kramer699128e2011-09-21 01:13:19 +00006549 // A separate DSym file path was specified, parse it as a macho file,
6550 // get the sections and supply it to the section name parsing machinery.
6551 if (!DSYMFile.empty()) {
Rafael Espindola48af1c22014-08-19 18:44:46 +00006552 ErrorOr<std::unique_ptr<MemoryBuffer>> BufOrErr =
Rafael Espindolaadf21f22014-07-06 17:43:13 +00006553 MemoryBuffer::getFileOrSTDIN(DSYMFile);
Rafael Espindola48af1c22014-08-19 18:44:46 +00006554 if (std::error_code EC = BufOrErr.getError()) {
Rafael Espindolaadf21f22014-07-06 17:43:13 +00006555 errs() << "llvm-objdump: " << Filename << ": " << EC.message() << '\n';
Benjamin Kramer699128e2011-09-21 01:13:19 +00006556 return;
6557 }
Rafael Espindola48af1c22014-08-19 18:44:46 +00006558 DbgObj =
6559 ObjectFile::createMachOObjectFile(BufOrErr.get()->getMemBufferRef())
6560 .get()
6561 .release();
Benjamin Kramer699128e2011-09-21 01:13:19 +00006562 }
6563
Eric Christopher7370b552012-11-12 21:40:38 +00006564 // Setup the DIContext
Zachary Turner6489d7b2015-04-23 17:37:47 +00006565 diContext.reset(new DWARFContextInMemory(*DbgObj));
Benjamin Kramer699128e2011-09-21 01:13:19 +00006566 }
6567
Colin LeMahieufcc32762015-07-29 19:08:10 +00006568 if (FilterSections.size() == 0)
Kevin Enderby95df54c2015-02-04 01:01:38 +00006569 outs() << "(" << DisSegName << "," << DisSectName << ") section\n";
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00006570
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006571 for (unsigned SectIdx = 0; SectIdx != Sections.size(); SectIdx++) {
Owen Andersond9243c42011-10-17 21:37:35 +00006572 StringRef SectName;
Kevin Enderby95df54c2015-02-04 01:01:38 +00006573 if (Sections[SectIdx].getName(SectName) || SectName != DisSectName)
6574 continue;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006575
Rafael Espindolaa9f810b2012-12-21 03:47:03 +00006576 DataRefImpl DR = Sections[SectIdx].getRawDataRefImpl();
Ahmed Bougachaaa790682013-05-24 01:07:04 +00006577
Rafael Espindolab0f76a42013-04-05 15:15:22 +00006578 StringRef SegmentName = MachOOF->getSectionFinalSegmentName(DR);
Kevin Enderby95df54c2015-02-04 01:01:38 +00006579 if (SegmentName != DisSegName)
Rafael Espindolaa9f810b2012-12-21 03:47:03 +00006580 continue;
6581
Rafael Espindola7fc5b872014-11-12 02:04:27 +00006582 StringRef BytesStr;
6583 Sections[SectIdx].getContents(BytesStr);
Aaron Ballman106fd7b2014-11-12 14:01:17 +00006584 ArrayRef<uint8_t> Bytes(reinterpret_cast<const uint8_t *>(BytesStr.data()),
6585 BytesStr.size());
Rafael Espindola80291272014-10-08 15:28:58 +00006586 uint64_t SectAddress = Sections[SectIdx].getAddress();
Rafael Espindolabd604f22014-11-07 00:52:15 +00006587
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006588 bool symbolTableWorked = false;
6589
Kevin Enderbybf246f52014-09-24 23:08:22 +00006590 // Create a map of symbol addresses to symbol names for use by
6591 // the SymbolizerSymbolLookUp() routine.
6592 SymbolAddressMap AddrMap;
Kevin Enderby6a221752015-03-17 17:10:57 +00006593 bool DisSymNameFound = false;
Kevin Enderbybf246f52014-09-24 23:08:22 +00006594 for (const SymbolRef &Symbol : MachOOF->symbols()) {
Kevin Enderby7bd8d992016-05-02 20:28:12 +00006595 Expected<SymbolRef::Type> STOrErr = Symbol.getType();
6596 if (!STOrErr) {
6597 std::string Buf;
6598 raw_string_ostream OS(Buf);
6599 logAllUnhandledErrors(STOrErr.takeError(), OS, "");
6600 OS.flush();
6601 report_fatal_error(Buf);
6602 }
Kevin Enderby5afbc1c2016-03-23 20:27:00 +00006603 SymbolRef::Type ST = *STOrErr;
Kevin Enderbybf246f52014-09-24 23:08:22 +00006604 if (ST == SymbolRef::ST_Function || ST == SymbolRef::ST_Data ||
6605 ST == SymbolRef::ST_Other) {
Rafael Espindoladea00162015-07-03 17:44:18 +00006606 uint64_t Address = Symbol.getValue();
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00006607 Expected<StringRef> SymNameOrErr = Symbol.getName();
6608 if (!SymNameOrErr) {
6609 std::string Buf;
6610 raw_string_ostream OS(Buf);
6611 logAllUnhandledErrors(SymNameOrErr.takeError(), OS, "");
6612 OS.flush();
6613 report_fatal_error(Buf);
6614 }
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00006615 StringRef SymName = *SymNameOrErr;
Kevin Enderbybf246f52014-09-24 23:08:22 +00006616 AddrMap[Address] = SymName;
Kevin Enderby6a221752015-03-17 17:10:57 +00006617 if (!DisSymName.empty() && DisSymName == SymName)
6618 DisSymNameFound = true;
Kevin Enderbybf246f52014-09-24 23:08:22 +00006619 }
6620 }
David Blaikie33dd45d02015-03-23 18:39:02 +00006621 if (!DisSymName.empty() && !DisSymNameFound) {
Kevin Enderby6a221752015-03-17 17:10:57 +00006622 outs() << "Can't find -dis-symname: " << DisSymName << "\n";
6623 return;
6624 }
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006625 // Set up the block of info used by the Symbolizer call backs.
Kevin Enderby8e29ec92015-03-17 22:26:11 +00006626 SymbolizerInfo.verbose = !NoSymbolicOperands;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006627 SymbolizerInfo.O = MachOOF;
6628 SymbolizerInfo.S = Sections[SectIdx];
Kevin Enderbybf246f52014-09-24 23:08:22 +00006629 SymbolizerInfo.AddrMap = &AddrMap;
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006630 SymbolizerInfo.Sections = &Sections;
6631 SymbolizerInfo.class_name = nullptr;
6632 SymbolizerInfo.selector_name = nullptr;
6633 SymbolizerInfo.method = nullptr;
Kevin Enderby04bf6932014-10-28 23:39:46 +00006634 SymbolizerInfo.demangled_name = nullptr;
Kevin Enderby078be602014-10-23 19:53:12 +00006635 SymbolizerInfo.bindtable = nullptr;
Kevin Enderby10738222014-11-19 20:20:16 +00006636 SymbolizerInfo.adrp_addr = 0;
6637 SymbolizerInfo.adrp_inst = 0;
Kevin Enderby930fdc72014-11-06 19:00:13 +00006638 // Same for the ThumbSymbolizer
Kevin Enderby8e29ec92015-03-17 22:26:11 +00006639 ThumbSymbolizerInfo.verbose = !NoSymbolicOperands;
Kevin Enderby930fdc72014-11-06 19:00:13 +00006640 ThumbSymbolizerInfo.O = MachOOF;
6641 ThumbSymbolizerInfo.S = Sections[SectIdx];
6642 ThumbSymbolizerInfo.AddrMap = &AddrMap;
6643 ThumbSymbolizerInfo.Sections = &Sections;
6644 ThumbSymbolizerInfo.class_name = nullptr;
6645 ThumbSymbolizerInfo.selector_name = nullptr;
6646 ThumbSymbolizerInfo.method = nullptr;
6647 ThumbSymbolizerInfo.demangled_name = nullptr;
6648 ThumbSymbolizerInfo.bindtable = nullptr;
Kevin Enderby10738222014-11-19 20:20:16 +00006649 ThumbSymbolizerInfo.adrp_addr = 0;
6650 ThumbSymbolizerInfo.adrp_inst = 0;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006651
Kevin Enderby4b627be2016-04-28 20:14:13 +00006652 unsigned int Arch = MachOOF->getArch();
6653
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00006654 // Disassemble symbol by symbol.
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006655 for (unsigned SymIdx = 0; SymIdx != Symbols.size(); SymIdx++) {
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00006656 Expected<StringRef> SymNameOrErr = Symbols[SymIdx].getName();
6657 if (!SymNameOrErr) {
6658 std::string Buf;
6659 raw_string_ostream OS(Buf);
6660 logAllUnhandledErrors(SymNameOrErr.takeError(), OS, "");
6661 OS.flush();
6662 report_fatal_error(Buf);
6663 }
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00006664 StringRef SymName = *SymNameOrErr;
Owen Andersond9243c42011-10-17 21:37:35 +00006665
Kevin Enderby7bd8d992016-05-02 20:28:12 +00006666 Expected<SymbolRef::Type> STOrErr = Symbols[SymIdx].getType();
6667 if (!STOrErr) {
6668 std::string Buf;
6669 raw_string_ostream OS(Buf);
6670 logAllUnhandledErrors(STOrErr.takeError(), OS, "");
6671 OS.flush();
6672 report_fatal_error(Buf);
6673 }
Kevin Enderby5afbc1c2016-03-23 20:27:00 +00006674 SymbolRef::Type ST = *STOrErr;
Kuba Breckade833222015-11-12 09:40:29 +00006675 if (ST != SymbolRef::ST_Function && ST != SymbolRef::ST_Data)
Owen Andersond9243c42011-10-17 21:37:35 +00006676 continue;
6677
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00006678 // Make sure the symbol is defined in this section.
Rafael Espindola80291272014-10-08 15:28:58 +00006679 bool containsSym = Sections[SectIdx].containsSymbol(Symbols[SymIdx]);
Kevin Enderbyd8a6e832016-06-15 21:14:01 +00006680 if (!containsSym) {
6681 if (!DisSymName.empty() && DisSymName == SymName) {
6682 outs() << "-dis-symname: " << DisSymName << " not in the section\n";
6683 return;
6684 }
6685 continue;
6686 }
6687 // The __mh_execute_header is special and we need to deal with that fact
6688 // this symbol is before the start of the (__TEXT,__text) section and at the
6689 // address of the start of the __TEXT segment. This is because this symbol
6690 // is an N_SECT symbol in the (__TEXT,__text) but its address is before the
6691 // start of the section in a standard MH_EXECUTE filetype.
6692 if (!DisSymName.empty() && DisSymName == "__mh_execute_header") {
6693 outs() << "-dis-symname: __mh_execute_header not in any section\n";
6694 return;
6695 }
6696 // When this code is trying to disassemble a symbol at a time and in the case
6697 // there is only the __mh_execute_header symbol left as in a stripped
6698 // executable, we need to deal with this by ignoring this symbol so the whole
6699 // section is disassembled and this symbol is then not displayed.
6700 if (SymName == "__mh_execute_header")
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006701 continue;
6702
Kevin Enderby6a221752015-03-17 17:10:57 +00006703 // If we are only disassembling one symbol see if this is that symbol.
6704 if (!DisSymName.empty() && DisSymName != SymName)
6705 continue;
6706
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00006707 // Start at the address of the symbol relative to the section's address.
Rafael Espindoladea00162015-07-03 17:44:18 +00006708 uint64_t Start = Symbols[SymIdx].getValue();
Rafael Espindola80291272014-10-08 15:28:58 +00006709 uint64_t SectionAddress = Sections[SectIdx].getAddress();
Cameron Zwarich54478a52012-02-03 05:42:17 +00006710 Start -= SectionAddress;
Owen Andersond9243c42011-10-17 21:37:35 +00006711
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00006712 // Stop disassembling either at the beginning of the next symbol or at
6713 // the end of the section.
Kevin Enderbyedd58722012-05-15 18:57:14 +00006714 bool containsNextSym = false;
Owen Andersond9243c42011-10-17 21:37:35 +00006715 uint64_t NextSym = 0;
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006716 uint64_t NextSymIdx = SymIdx + 1;
Owen Andersond9243c42011-10-17 21:37:35 +00006717 while (Symbols.size() > NextSymIdx) {
Kevin Enderby7bd8d992016-05-02 20:28:12 +00006718 Expected<SymbolRef::Type> STOrErr = Symbols[NextSymIdx].getType();
6719 if (!STOrErr) {
6720 std::string Buf;
6721 raw_string_ostream OS(Buf);
6722 logAllUnhandledErrors(STOrErr.takeError(), OS, "");
6723 OS.flush();
6724 report_fatal_error(Buf);
6725 }
Kevin Enderby5afbc1c2016-03-23 20:27:00 +00006726 SymbolRef::Type NextSymType = *STOrErr;
Owen Andersond9243c42011-10-17 21:37:35 +00006727 if (NextSymType == SymbolRef::ST_Function) {
Rafael Espindola80291272014-10-08 15:28:58 +00006728 containsNextSym =
6729 Sections[SectIdx].containsSymbol(Symbols[NextSymIdx]);
Rafael Espindoladea00162015-07-03 17:44:18 +00006730 NextSym = Symbols[NextSymIdx].getValue();
Cameron Zwarich54478a52012-02-03 05:42:17 +00006731 NextSym -= SectionAddress;
Owen Andersond9243c42011-10-17 21:37:35 +00006732 break;
6733 }
6734 ++NextSymIdx;
6735 }
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006736
Rafael Espindola80291272014-10-08 15:28:58 +00006737 uint64_t SectSize = Sections[SectIdx].getSize();
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006738 uint64_t End = containsNextSym ? NextSym : SectSize;
Owen Andersond9243c42011-10-17 21:37:35 +00006739 uint64_t Size;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006740
6741 symbolTableWorked = true;
Rafael Espindolabd604f22014-11-07 00:52:15 +00006742
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006743 DataRefImpl Symb = Symbols[SymIdx].getRawDataRefImpl();
Tim Northover09ca33e2016-04-22 23:23:31 +00006744 bool IsThumb = MachOOF->getSymbolFlags(Symb) & SymbolRef::SF_Thumb;
6745
6746 // We only need the dedicated Thumb target if there's a real choice
6747 // (i.e. we're not targeting M-class) and the function is Thumb.
6748 bool UseThumbTarget = IsThumb && ThumbTarget;
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006749
Ahmed Bougachaaa790682013-05-24 01:07:04 +00006750 outs() << SymName << ":\n";
6751 DILineInfo lastLine;
6752 for (uint64_t Index = Start; Index < End; Index += Size) {
6753 MCInst Inst;
Owen Andersond9243c42011-10-17 21:37:35 +00006754
Kevin Enderbybf246f52014-09-24 23:08:22 +00006755 uint64_t PC = SectAddress + Index;
Kevin Enderbyab5e6c92015-03-17 21:07:39 +00006756 if (!NoLeadingAddr) {
6757 if (FullLeadingAddr) {
6758 if (MachOOF->is64Bit())
6759 outs() << format("%016" PRIx64, PC);
6760 else
6761 outs() << format("%08" PRIx64, PC);
6762 } else {
6763 outs() << format("%8" PRIx64 ":", PC);
6764 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00006765 }
Kevin Enderby4b627be2016-04-28 20:14:13 +00006766 if (!NoShowRawInsn || Arch == Triple::arm)
Kevin Enderbybf246f52014-09-24 23:08:22 +00006767 outs() << "\t";
Kevin Enderby273ae012013-06-06 17:20:50 +00006768
6769 // Check the data in code table here to see if this is data not an
6770 // instruction to be disassembled.
6771 DiceTable Dice;
Kevin Enderbybf246f52014-09-24 23:08:22 +00006772 Dice.push_back(std::make_pair(PC, DiceRef()));
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006773 dice_table_iterator DTI =
6774 std::search(Dices.begin(), Dices.end(), Dice.begin(), Dice.end(),
6775 compareDiceTableEntries);
6776 if (DTI != Dices.end()) {
Kevin Enderby273ae012013-06-06 17:20:50 +00006777 uint16_t Length;
6778 DTI->second.getLength(Length);
Kevin Enderby273ae012013-06-06 17:20:50 +00006779 uint16_t Kind;
6780 DTI->second.getKind(Kind);
Colin LeMahieufc32b1b2015-03-18 19:27:31 +00006781 Size = DumpDataInCode(Bytes.data() + Index, Length, Kind);
Kevin Enderby930fdc72014-11-06 19:00:13 +00006782 if ((Kind == MachO::DICE_KIND_JUMP_TABLE8) &&
6783 (PC == (DTI->first + Length - 1)) && (Length & 1))
6784 Size++;
Kevin Enderby273ae012013-06-06 17:20:50 +00006785 continue;
6786 }
6787
Kevin Enderbybf246f52014-09-24 23:08:22 +00006788 SmallVector<char, 64> AnnotationsBytes;
6789 raw_svector_ostream Annotations(AnnotationsBytes);
6790
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006791 bool gotInst;
Tim Northover09ca33e2016-04-22 23:23:31 +00006792 if (UseThumbTarget)
Rafael Espindola7fc5b872014-11-12 02:04:27 +00006793 gotInst = ThumbDisAsm->getInstruction(Inst, Size, Bytes.slice(Index),
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006794 PC, DebugOut, Annotations);
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006795 else
Rafael Espindola7fc5b872014-11-12 02:04:27 +00006796 gotInst = DisAsm->getInstruction(Inst, Size, Bytes.slice(Index), PC,
Kevin Enderbybf246f52014-09-24 23:08:22 +00006797 DebugOut, Annotations);
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006798 if (gotInst) {
Kevin Enderby4b627be2016-04-28 20:14:13 +00006799 if (!NoShowRawInsn || Arch == Triple::arm) {
Craig Topper0013be12015-09-21 05:32:41 +00006800 dumpBytes(makeArrayRef(Bytes.data() + Index, Size), outs());
Kevin Enderbybf246f52014-09-24 23:08:22 +00006801 }
6802 formatted_raw_ostream FormattedOS(outs());
Kevin Enderbybf246f52014-09-24 23:08:22 +00006803 StringRef AnnotationsStr = Annotations.str();
Tim Northover09ca33e2016-04-22 23:23:31 +00006804 if (UseThumbTarget)
Akira Hatanakab46d0232015-03-27 20:36:02 +00006805 ThumbIP->printInst(&Inst, FormattedOS, AnnotationsStr, *ThumbSTI);
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006806 else
Akira Hatanaka1d079942015-03-28 20:44:05 +00006807 IP->printInst(&Inst, FormattedOS, AnnotationsStr, *STI);
Kevin Enderbybf246f52014-09-24 23:08:22 +00006808 emitComments(CommentStream, CommentsToEmit, FormattedOS, *AsmInfo);
Owen Andersond9243c42011-10-17 21:37:35 +00006809
Ahmed Bougachaaa790682013-05-24 01:07:04 +00006810 // Print debug info.
6811 if (diContext) {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006812 DILineInfo dli = diContext->getLineInfoForAddress(PC);
Ahmed Bougachaaa790682013-05-24 01:07:04 +00006813 // Print valid line info if it changed.
Alexey Samsonovd0109992014-04-18 21:36:39 +00006814 if (dli != lastLine && dli.Line != 0)
6815 outs() << "\t## " << dli.FileName << ':' << dli.Line << ':'
6816 << dli.Column;
Ahmed Bougachaaa790682013-05-24 01:07:04 +00006817 lastLine = dli;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006818 }
Ahmed Bougachaaa790682013-05-24 01:07:04 +00006819 outs() << "\n";
6820 } else {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006821 unsigned int Arch = MachOOF->getArch();
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006822 if (Arch == Triple::x86_64 || Arch == Triple::x86) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006823 outs() << format("\t.byte 0x%02x #bad opcode\n",
6824 *(Bytes.data() + Index) & 0xff);
6825 Size = 1; // skip exactly one illegible byte and move on.
Tim Northover09ca33e2016-04-22 23:23:31 +00006826 } else if (Arch == Triple::aarch64 ||
6827 (Arch == Triple::arm && !IsThumb)) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00006828 uint32_t opcode = (*(Bytes.data() + Index) & 0xff) |
6829 (*(Bytes.data() + Index + 1) & 0xff) << 8 |
6830 (*(Bytes.data() + Index + 2) & 0xff) << 16 |
6831 (*(Bytes.data() + Index + 3) & 0xff) << 24;
6832 outs() << format("\t.long\t0x%08x\n", opcode);
6833 Size = 4;
Tim Northover09ca33e2016-04-22 23:23:31 +00006834 } else if (Arch == Triple::arm) {
6835 assert(IsThumb && "ARM mode should have been dealt with above");
6836 uint32_t opcode = (*(Bytes.data() + Index) & 0xff) |
6837 (*(Bytes.data() + Index + 1) & 0xff) << 8;
6838 outs() << format("\t.short\t0x%04x\n", opcode);
6839 Size = 2;
6840 } else{
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006841 errs() << "llvm-objdump: warning: invalid instruction encoding\n";
6842 if (Size == 0)
6843 Size = 1; // skip illegible bytes
6844 }
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006845 }
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006846 }
6847 }
Ahmed Bougachaaa790682013-05-24 01:07:04 +00006848 if (!symbolTableWorked) {
Rafael Espindola80291272014-10-08 15:28:58 +00006849 // Reading the symbol table didn't work, disassemble the whole section.
6850 uint64_t SectAddress = Sections[SectIdx].getAddress();
6851 uint64_t SectSize = Sections[SectIdx].getSize();
Kevin Enderbybadd1002012-05-18 00:13:56 +00006852 uint64_t InstSize;
6853 for (uint64_t Index = 0; Index < SectSize; Index += InstSize) {
Bill Wendling4e68e062012-07-19 00:17:40 +00006854 MCInst Inst;
Kevin Enderbybadd1002012-05-18 00:13:56 +00006855
Kevin Enderbybf246f52014-09-24 23:08:22 +00006856 uint64_t PC = SectAddress + Index;
Rafael Espindola7fc5b872014-11-12 02:04:27 +00006857 if (DisAsm->getInstruction(Inst, InstSize, Bytes.slice(Index), PC,
6858 DebugOut, nulls())) {
Kevin Enderbyab5e6c92015-03-17 21:07:39 +00006859 if (!NoLeadingAddr) {
6860 if (FullLeadingAddr) {
6861 if (MachOOF->is64Bit())
6862 outs() << format("%016" PRIx64, PC);
6863 else
6864 outs() << format("%08" PRIx64, PC);
6865 } else {
6866 outs() << format("%8" PRIx64 ":", PC);
6867 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00006868 }
Kevin Enderby4b627be2016-04-28 20:14:13 +00006869 if (!NoShowRawInsn || Arch == Triple::arm) {
Kevin Enderbybf246f52014-09-24 23:08:22 +00006870 outs() << "\t";
Craig Topper0013be12015-09-21 05:32:41 +00006871 dumpBytes(makeArrayRef(Bytes.data() + Index, InstSize), outs());
Kevin Enderbybf246f52014-09-24 23:08:22 +00006872 }
Akira Hatanaka1d079942015-03-28 20:44:05 +00006873 IP->printInst(&Inst, outs(), "", *STI);
Bill Wendling4e68e062012-07-19 00:17:40 +00006874 outs() << "\n";
6875 } else {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006876 unsigned int Arch = MachOOF->getArch();
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006877 if (Arch == Triple::x86_64 || Arch == Triple::x86) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006878 outs() << format("\t.byte 0x%02x #bad opcode\n",
6879 *(Bytes.data() + Index) & 0xff);
6880 InstSize = 1; // skip exactly one illegible byte and move on.
6881 } else {
6882 errs() << "llvm-objdump: warning: invalid instruction encoding\n";
6883 if (InstSize == 0)
6884 InstSize = 1; // skip illegible bytes
6885 }
Bill Wendling4e68e062012-07-19 00:17:40 +00006886 }
Kevin Enderbybadd1002012-05-18 00:13:56 +00006887 }
6888 }
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00006889 // The TripleName's need to be reset if we are called again for a different
6890 // archtecture.
6891 TripleName = "";
6892 ThumbTripleName = "";
6893
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006894 if (SymbolizerInfo.method != nullptr)
6895 free(SymbolizerInfo.method);
Kevin Enderby04bf6932014-10-28 23:39:46 +00006896 if (SymbolizerInfo.demangled_name != nullptr)
6897 free(SymbolizerInfo.demangled_name);
Kevin Enderby078be602014-10-23 19:53:12 +00006898 if (SymbolizerInfo.bindtable != nullptr)
6899 delete SymbolizerInfo.bindtable;
Kevin Enderby930fdc72014-11-06 19:00:13 +00006900 if (ThumbSymbolizerInfo.method != nullptr)
6901 free(ThumbSymbolizerInfo.method);
6902 if (ThumbSymbolizerInfo.demangled_name != nullptr)
6903 free(ThumbSymbolizerInfo.demangled_name);
6904 if (ThumbSymbolizerInfo.bindtable != nullptr)
6905 delete ThumbSymbolizerInfo.bindtable;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006906 }
6907}
Tim Northover4bd286a2014-08-01 13:07:19 +00006908
Tim Northover39c70bb2014-08-12 11:52:59 +00006909//===----------------------------------------------------------------------===//
6910// __compact_unwind section dumping
6911//===----------------------------------------------------------------------===//
6912
Tim Northover4bd286a2014-08-01 13:07:19 +00006913namespace {
Tim Northover39c70bb2014-08-12 11:52:59 +00006914
6915template <typename T> static uint64_t readNext(const char *&Buf) {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006916 using llvm::support::little;
6917 using llvm::support::unaligned;
Tim Northover39c70bb2014-08-12 11:52:59 +00006918
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006919 uint64_t Val = support::endian::read<T, little, unaligned>(Buf);
6920 Buf += sizeof(T);
6921 return Val;
6922}
Tim Northover39c70bb2014-08-12 11:52:59 +00006923
Tim Northover4bd286a2014-08-01 13:07:19 +00006924struct CompactUnwindEntry {
6925 uint32_t OffsetInSection;
6926
6927 uint64_t FunctionAddr;
6928 uint32_t Length;
6929 uint32_t CompactEncoding;
6930 uint64_t PersonalityAddr;
6931 uint64_t LSDAAddr;
6932
6933 RelocationRef FunctionReloc;
6934 RelocationRef PersonalityReloc;
6935 RelocationRef LSDAReloc;
6936
6937 CompactUnwindEntry(StringRef Contents, unsigned Offset, bool Is64)
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006938 : OffsetInSection(Offset) {
Tim Northover4bd286a2014-08-01 13:07:19 +00006939 if (Is64)
6940 read<uint64_t>(Contents.data() + Offset);
6941 else
6942 read<uint32_t>(Contents.data() + Offset);
6943 }
6944
6945private:
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006946 template <typename UIntPtr> void read(const char *Buf) {
Tim Northover4bd286a2014-08-01 13:07:19 +00006947 FunctionAddr = readNext<UIntPtr>(Buf);
6948 Length = readNext<uint32_t>(Buf);
6949 CompactEncoding = readNext<uint32_t>(Buf);
6950 PersonalityAddr = readNext<UIntPtr>(Buf);
6951 LSDAAddr = readNext<UIntPtr>(Buf);
6952 }
6953};
6954}
6955
6956/// Given a relocation from __compact_unwind, consisting of the RelocationRef
6957/// and data being relocated, determine the best base Name and Addend to use for
6958/// display purposes.
6959///
6960/// 1. An Extern relocation will directly reference a symbol (and the data is
6961/// then already an addend), so use that.
6962/// 2. Otherwise the data is an offset in the object file's layout; try to find
6963// a symbol before it in the same section, and use the offset from there.
6964/// 3. Finally, if all that fails, fall back to an offset from the start of the
6965/// referenced section.
6966static void findUnwindRelocNameAddend(const MachOObjectFile *Obj,
6967 std::map<uint64_t, SymbolRef> &Symbols,
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006968 const RelocationRef &Reloc, uint64_t Addr,
Tim Northover4bd286a2014-08-01 13:07:19 +00006969 StringRef &Name, uint64_t &Addend) {
6970 if (Reloc.getSymbol() != Obj->symbol_end()) {
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00006971 Expected<StringRef> NameOrErr = Reloc.getSymbol()->getName();
6972 if (!NameOrErr) {
6973 std::string Buf;
6974 raw_string_ostream OS(Buf);
6975 logAllUnhandledErrors(NameOrErr.takeError(), OS, "");
6976 OS.flush();
6977 report_fatal_error(Buf);
6978 }
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00006979 Name = *NameOrErr;
Tim Northover4bd286a2014-08-01 13:07:19 +00006980 Addend = Addr;
6981 return;
6982 }
6983
6984 auto RE = Obj->getRelocation(Reloc.getRawDataRefImpl());
Keno Fischerc780e8e2015-05-21 21:24:32 +00006985 SectionRef RelocSection = Obj->getAnyRelocationSection(RE);
Tim Northover4bd286a2014-08-01 13:07:19 +00006986
Rafael Espindola80291272014-10-08 15:28:58 +00006987 uint64_t SectionAddr = RelocSection.getAddress();
Tim Northover4bd286a2014-08-01 13:07:19 +00006988
6989 auto Sym = Symbols.upper_bound(Addr);
6990 if (Sym == Symbols.begin()) {
6991 // The first symbol in the object is after this reference, the best we can
6992 // do is section-relative notation.
6993 RelocSection.getName(Name);
6994 Addend = Addr - SectionAddr;
6995 return;
6996 }
6997
6998 // Go back one so that SymbolAddress <= Addr.
6999 --Sym;
7000
Kevin Enderby7bd8d992016-05-02 20:28:12 +00007001 auto SectOrErr = Sym->second.getSection();
7002 if (!SectOrErr) {
7003 std::string Buf;
7004 raw_string_ostream OS(Buf);
7005 logAllUnhandledErrors(SectOrErr.takeError(), OS, "");
7006 OS.flush();
7007 report_fatal_error(Buf);
7008 }
7009 section_iterator SymSection = *SectOrErr;
Tim Northover4bd286a2014-08-01 13:07:19 +00007010 if (RelocSection == *SymSection) {
7011 // There's a valid symbol in the same section before this reference.
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00007012 Expected<StringRef> NameOrErr = Sym->second.getName();
7013 if (!NameOrErr) {
7014 std::string Buf;
7015 raw_string_ostream OS(Buf);
7016 logAllUnhandledErrors(NameOrErr.takeError(), OS, "");
7017 OS.flush();
7018 report_fatal_error(Buf);
7019 }
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00007020 Name = *NameOrErr;
Tim Northover4bd286a2014-08-01 13:07:19 +00007021 Addend = Addr - Sym->first;
7022 return;
7023 }
7024
7025 // There is a symbol before this reference, but it's in a different
7026 // section. Probably not helpful to mention it, so use the section name.
7027 RelocSection.getName(Name);
7028 Addend = Addr - SectionAddr;
7029}
7030
7031static void printUnwindRelocDest(const MachOObjectFile *Obj,
7032 std::map<uint64_t, SymbolRef> &Symbols,
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007033 const RelocationRef &Reloc, uint64_t Addr) {
Tim Northover4bd286a2014-08-01 13:07:19 +00007034 StringRef Name;
7035 uint64_t Addend;
7036
Rafael Espindola854038e2015-06-26 14:51:16 +00007037 if (!Reloc.getObject())
Tim Northover0b0add52014-09-09 10:45:06 +00007038 return;
7039
Tim Northover4bd286a2014-08-01 13:07:19 +00007040 findUnwindRelocNameAddend(Obj, Symbols, Reloc, Addr, Name, Addend);
7041
7042 outs() << Name;
7043 if (Addend)
Tim Northover63a25622014-08-11 09:14:06 +00007044 outs() << " + " << format("0x%" PRIx64, Addend);
Tim Northover4bd286a2014-08-01 13:07:19 +00007045}
7046
7047static void
7048printMachOCompactUnwindSection(const MachOObjectFile *Obj,
7049 std::map<uint64_t, SymbolRef> &Symbols,
7050 const SectionRef &CompactUnwind) {
7051
7052 assert(Obj->isLittleEndian() &&
7053 "There should not be a big-endian .o with __compact_unwind");
7054
7055 bool Is64 = Obj->is64Bit();
7056 uint32_t PointerSize = Is64 ? sizeof(uint64_t) : sizeof(uint32_t);
7057 uint32_t EntrySize = 3 * PointerSize + 2 * sizeof(uint32_t);
7058
7059 StringRef Contents;
7060 CompactUnwind.getContents(Contents);
7061
7062 SmallVector<CompactUnwindEntry, 4> CompactUnwinds;
7063
7064 // First populate the initial raw offsets, encodings and so on from the entry.
7065 for (unsigned Offset = 0; Offset < Contents.size(); Offset += EntrySize) {
7066 CompactUnwindEntry Entry(Contents.data(), Offset, Is64);
7067 CompactUnwinds.push_back(Entry);
7068 }
7069
7070 // Next we need to look at the relocations to find out what objects are
7071 // actually being referred to.
7072 for (const RelocationRef &Reloc : CompactUnwind.relocations()) {
Rafael Espindola96d071c2015-06-29 23:29:12 +00007073 uint64_t RelocAddress = Reloc.getOffset();
Tim Northover4bd286a2014-08-01 13:07:19 +00007074
7075 uint32_t EntryIdx = RelocAddress / EntrySize;
7076 uint32_t OffsetInEntry = RelocAddress - EntryIdx * EntrySize;
7077 CompactUnwindEntry &Entry = CompactUnwinds[EntryIdx];
7078
7079 if (OffsetInEntry == 0)
7080 Entry.FunctionReloc = Reloc;
7081 else if (OffsetInEntry == PointerSize + 2 * sizeof(uint32_t))
7082 Entry.PersonalityReloc = Reloc;
7083 else if (OffsetInEntry == 2 * PointerSize + 2 * sizeof(uint32_t))
7084 Entry.LSDAReloc = Reloc;
7085 else
7086 llvm_unreachable("Unexpected relocation in __compact_unwind section");
7087 }
7088
7089 // Finally, we're ready to print the data we've gathered.
7090 outs() << "Contents of __compact_unwind section:\n";
7091 for (auto &Entry : CompactUnwinds) {
Tim Northover06af2602014-08-08 12:08:51 +00007092 outs() << " Entry at offset "
7093 << format("0x%" PRIx32, Entry.OffsetInSection) << ":\n";
Tim Northover4bd286a2014-08-01 13:07:19 +00007094
7095 // 1. Start of the region this entry applies to.
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007096 outs() << " start: " << format("0x%" PRIx64,
7097 Entry.FunctionAddr) << ' ';
7098 printUnwindRelocDest(Obj, Symbols, Entry.FunctionReloc, Entry.FunctionAddr);
Tim Northover4bd286a2014-08-01 13:07:19 +00007099 outs() << '\n';
7100
7101 // 2. Length of the region this entry applies to.
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007102 outs() << " length: " << format("0x%" PRIx32, Entry.Length)
7103 << '\n';
Tim Northover4bd286a2014-08-01 13:07:19 +00007104 // 3. The 32-bit compact encoding.
7105 outs() << " compact encoding: "
Tim Northoverb911bf82014-08-08 12:00:09 +00007106 << format("0x%08" PRIx32, Entry.CompactEncoding) << '\n';
Tim Northover4bd286a2014-08-01 13:07:19 +00007107
7108 // 4. The personality function, if present.
Rafael Espindola854038e2015-06-26 14:51:16 +00007109 if (Entry.PersonalityReloc.getObject()) {
Tim Northover4bd286a2014-08-01 13:07:19 +00007110 outs() << " personality function: "
Tim Northoverb911bf82014-08-08 12:00:09 +00007111 << format("0x%" PRIx64, Entry.PersonalityAddr) << ' ';
Tim Northover4bd286a2014-08-01 13:07:19 +00007112 printUnwindRelocDest(Obj, Symbols, Entry.PersonalityReloc,
7113 Entry.PersonalityAddr);
7114 outs() << '\n';
7115 }
7116
7117 // 5. This entry's language-specific data area.
Rafael Espindola854038e2015-06-26 14:51:16 +00007118 if (Entry.LSDAReloc.getObject()) {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007119 outs() << " LSDA: " << format("0x%" PRIx64,
7120 Entry.LSDAAddr) << ' ';
Tim Northover4bd286a2014-08-01 13:07:19 +00007121 printUnwindRelocDest(Obj, Symbols, Entry.LSDAReloc, Entry.LSDAAddr);
7122 outs() << '\n';
7123 }
7124 }
7125}
7126
Tim Northover39c70bb2014-08-12 11:52:59 +00007127//===----------------------------------------------------------------------===//
7128// __unwind_info section dumping
7129//===----------------------------------------------------------------------===//
7130
7131static void printRegularSecondLevelUnwindPage(const char *PageStart) {
7132 const char *Pos = PageStart;
7133 uint32_t Kind = readNext<uint32_t>(Pos);
7134 (void)Kind;
7135 assert(Kind == 2 && "kind for a regular 2nd level index should be 2");
7136
7137 uint16_t EntriesStart = readNext<uint16_t>(Pos);
7138 uint16_t NumEntries = readNext<uint16_t>(Pos);
7139
7140 Pos = PageStart + EntriesStart;
7141 for (unsigned i = 0; i < NumEntries; ++i) {
7142 uint32_t FunctionOffset = readNext<uint32_t>(Pos);
7143 uint32_t Encoding = readNext<uint32_t>(Pos);
7144
7145 outs() << " [" << i << "]: "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007146 << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
7147 << ", "
7148 << "encoding=" << format("0x%08" PRIx32, Encoding) << '\n';
Tim Northover39c70bb2014-08-12 11:52:59 +00007149 }
7150}
7151
7152static void printCompressedSecondLevelUnwindPage(
7153 const char *PageStart, uint32_t FunctionBase,
7154 const SmallVectorImpl<uint32_t> &CommonEncodings) {
7155 const char *Pos = PageStart;
7156 uint32_t Kind = readNext<uint32_t>(Pos);
7157 (void)Kind;
7158 assert(Kind == 3 && "kind for a compressed 2nd level index should be 3");
7159
7160 uint16_t EntriesStart = readNext<uint16_t>(Pos);
7161 uint16_t NumEntries = readNext<uint16_t>(Pos);
7162
7163 uint16_t EncodingsStart = readNext<uint16_t>(Pos);
7164 readNext<uint16_t>(Pos);
Aaron Ballman80930af2014-08-14 13:53:19 +00007165 const auto *PageEncodings = reinterpret_cast<const support::ulittle32_t *>(
7166 PageStart + EncodingsStart);
Tim Northover39c70bb2014-08-12 11:52:59 +00007167
7168 Pos = PageStart + EntriesStart;
7169 for (unsigned i = 0; i < NumEntries; ++i) {
7170 uint32_t Entry = readNext<uint32_t>(Pos);
7171 uint32_t FunctionOffset = FunctionBase + (Entry & 0xffffff);
7172 uint32_t EncodingIdx = Entry >> 24;
7173
7174 uint32_t Encoding;
7175 if (EncodingIdx < CommonEncodings.size())
7176 Encoding = CommonEncodings[EncodingIdx];
7177 else
7178 Encoding = PageEncodings[EncodingIdx - CommonEncodings.size()];
7179
7180 outs() << " [" << i << "]: "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007181 << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
7182 << ", "
7183 << "encoding[" << EncodingIdx
7184 << "]=" << format("0x%08" PRIx32, Encoding) << '\n';
Tim Northover39c70bb2014-08-12 11:52:59 +00007185 }
7186}
7187
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007188static void printMachOUnwindInfoSection(const MachOObjectFile *Obj,
7189 std::map<uint64_t, SymbolRef> &Symbols,
7190 const SectionRef &UnwindInfo) {
Tim Northover39c70bb2014-08-12 11:52:59 +00007191
7192 assert(Obj->isLittleEndian() &&
7193 "There should not be a big-endian .o with __unwind_info");
7194
7195 outs() << "Contents of __unwind_info section:\n";
7196
7197 StringRef Contents;
7198 UnwindInfo.getContents(Contents);
7199 const char *Pos = Contents.data();
7200
7201 //===----------------------------------
7202 // Section header
7203 //===----------------------------------
7204
7205 uint32_t Version = readNext<uint32_t>(Pos);
7206 outs() << " Version: "
7207 << format("0x%" PRIx32, Version) << '\n';
7208 assert(Version == 1 && "only understand version 1");
7209
7210 uint32_t CommonEncodingsStart = readNext<uint32_t>(Pos);
7211 outs() << " Common encodings array section offset: "
7212 << format("0x%" PRIx32, CommonEncodingsStart) << '\n';
7213 uint32_t NumCommonEncodings = readNext<uint32_t>(Pos);
7214 outs() << " Number of common encodings in array: "
7215 << format("0x%" PRIx32, NumCommonEncodings) << '\n';
7216
7217 uint32_t PersonalitiesStart = readNext<uint32_t>(Pos);
7218 outs() << " Personality function array section offset: "
7219 << format("0x%" PRIx32, PersonalitiesStart) << '\n';
7220 uint32_t NumPersonalities = readNext<uint32_t>(Pos);
7221 outs() << " Number of personality functions in array: "
7222 << format("0x%" PRIx32, NumPersonalities) << '\n';
7223
7224 uint32_t IndicesStart = readNext<uint32_t>(Pos);
7225 outs() << " Index array section offset: "
7226 << format("0x%" PRIx32, IndicesStart) << '\n';
7227 uint32_t NumIndices = readNext<uint32_t>(Pos);
7228 outs() << " Number of indices in array: "
7229 << format("0x%" PRIx32, NumIndices) << '\n';
7230
7231 //===----------------------------------
7232 // A shared list of common encodings
7233 //===----------------------------------
7234
7235 // These occupy indices in the range [0, N] whenever an encoding is referenced
7236 // from a compressed 2nd level index table. In practice the linker only
7237 // creates ~128 of these, so that indices are available to embed encodings in
7238 // the 2nd level index.
7239
7240 SmallVector<uint32_t, 64> CommonEncodings;
7241 outs() << " Common encodings: (count = " << NumCommonEncodings << ")\n";
7242 Pos = Contents.data() + CommonEncodingsStart;
7243 for (unsigned i = 0; i < NumCommonEncodings; ++i) {
7244 uint32_t Encoding = readNext<uint32_t>(Pos);
7245 CommonEncodings.push_back(Encoding);
7246
7247 outs() << " encoding[" << i << "]: " << format("0x%08" PRIx32, Encoding)
7248 << '\n';
7249 }
7250
Tim Northover39c70bb2014-08-12 11:52:59 +00007251 //===----------------------------------
7252 // Personality functions used in this executable
7253 //===----------------------------------
7254
7255 // There should be only a handful of these (one per source language,
7256 // roughly). Particularly since they only get 2 bits in the compact encoding.
7257
7258 outs() << " Personality functions: (count = " << NumPersonalities << ")\n";
7259 Pos = Contents.data() + PersonalitiesStart;
7260 for (unsigned i = 0; i < NumPersonalities; ++i) {
7261 uint32_t PersonalityFn = readNext<uint32_t>(Pos);
7262 outs() << " personality[" << i + 1
7263 << "]: " << format("0x%08" PRIx32, PersonalityFn) << '\n';
7264 }
7265
7266 //===----------------------------------
7267 // The level 1 index entries
7268 //===----------------------------------
7269
7270 // These specify an approximate place to start searching for the more detailed
7271 // information, sorted by PC.
7272
7273 struct IndexEntry {
7274 uint32_t FunctionOffset;
7275 uint32_t SecondLevelPageStart;
7276 uint32_t LSDAStart;
7277 };
7278
7279 SmallVector<IndexEntry, 4> IndexEntries;
7280
7281 outs() << " Top level indices: (count = " << NumIndices << ")\n";
7282 Pos = Contents.data() + IndicesStart;
7283 for (unsigned i = 0; i < NumIndices; ++i) {
7284 IndexEntry Entry;
7285
7286 Entry.FunctionOffset = readNext<uint32_t>(Pos);
7287 Entry.SecondLevelPageStart = readNext<uint32_t>(Pos);
7288 Entry.LSDAStart = readNext<uint32_t>(Pos);
7289 IndexEntries.push_back(Entry);
7290
7291 outs() << " [" << i << "]: "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007292 << "function offset=" << format("0x%08" PRIx32, Entry.FunctionOffset)
7293 << ", "
Tim Northover39c70bb2014-08-12 11:52:59 +00007294 << "2nd level page offset="
7295 << format("0x%08" PRIx32, Entry.SecondLevelPageStart) << ", "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007296 << "LSDA offset=" << format("0x%08" PRIx32, Entry.LSDAStart) << '\n';
Tim Northover39c70bb2014-08-12 11:52:59 +00007297 }
7298
Tim Northover39c70bb2014-08-12 11:52:59 +00007299 //===----------------------------------
7300 // Next come the LSDA tables
7301 //===----------------------------------
7302
7303 // The LSDA layout is rather implicit: it's a contiguous array of entries from
7304 // the first top-level index's LSDAOffset to the last (sentinel).
7305
7306 outs() << " LSDA descriptors:\n";
7307 Pos = Contents.data() + IndexEntries[0].LSDAStart;
7308 int NumLSDAs = (IndexEntries.back().LSDAStart - IndexEntries[0].LSDAStart) /
7309 (2 * sizeof(uint32_t));
7310 for (int i = 0; i < NumLSDAs; ++i) {
7311 uint32_t FunctionOffset = readNext<uint32_t>(Pos);
7312 uint32_t LSDAOffset = readNext<uint32_t>(Pos);
7313 outs() << " [" << i << "]: "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007314 << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
7315 << ", "
7316 << "LSDA offset=" << format("0x%08" PRIx32, LSDAOffset) << '\n';
Tim Northover39c70bb2014-08-12 11:52:59 +00007317 }
7318
7319 //===----------------------------------
7320 // Finally, the 2nd level indices
7321 //===----------------------------------
7322
7323 // Generally these are 4K in size, and have 2 possible forms:
7324 // + Regular stores up to 511 entries with disparate encodings
7325 // + Compressed stores up to 1021 entries if few enough compact encoding
7326 // values are used.
7327 outs() << " Second level indices:\n";
7328 for (unsigned i = 0; i < IndexEntries.size() - 1; ++i) {
7329 // The final sentinel top-level index has no associated 2nd level page
7330 if (IndexEntries[i].SecondLevelPageStart == 0)
7331 break;
7332
7333 outs() << " Second level index[" << i << "]: "
7334 << "offset in section="
7335 << format("0x%08" PRIx32, IndexEntries[i].SecondLevelPageStart)
7336 << ", "
7337 << "base function offset="
7338 << format("0x%08" PRIx32, IndexEntries[i].FunctionOffset) << '\n';
7339
7340 Pos = Contents.data() + IndexEntries[i].SecondLevelPageStart;
Aaron Ballman80930af2014-08-14 13:53:19 +00007341 uint32_t Kind = *reinterpret_cast<const support::ulittle32_t *>(Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007342 if (Kind == 2)
7343 printRegularSecondLevelUnwindPage(Pos);
7344 else if (Kind == 3)
7345 printCompressedSecondLevelUnwindPage(Pos, IndexEntries[i].FunctionOffset,
7346 CommonEncodings);
7347 else
7348 llvm_unreachable("Do not know how to print this kind of 2nd level page");
Tim Northover39c70bb2014-08-12 11:52:59 +00007349 }
7350}
7351
Tim Northover4bd286a2014-08-01 13:07:19 +00007352void llvm::printMachOUnwindInfo(const MachOObjectFile *Obj) {
7353 std::map<uint64_t, SymbolRef> Symbols;
7354 for (const SymbolRef &SymRef : Obj->symbols()) {
7355 // Discard any undefined or absolute symbols. They're not going to take part
7356 // in the convenience lookup for unwind info and just take up resources.
Kevin Enderby7bd8d992016-05-02 20:28:12 +00007357 auto SectOrErr = SymRef.getSection();
7358 if (!SectOrErr) {
7359 // TODO: Actually report errors helpfully.
7360 consumeError(SectOrErr.takeError());
7361 continue;
7362 }
7363 section_iterator Section = *SectOrErr;
Tim Northover4bd286a2014-08-01 13:07:19 +00007364 if (Section == Obj->section_end())
7365 continue;
7366
Rafael Espindoladea00162015-07-03 17:44:18 +00007367 uint64_t Addr = SymRef.getValue();
Tim Northover4bd286a2014-08-01 13:07:19 +00007368 Symbols.insert(std::make_pair(Addr, SymRef));
7369 }
7370
7371 for (const SectionRef &Section : Obj->sections()) {
7372 StringRef SectName;
7373 Section.getName(SectName);
7374 if (SectName == "__compact_unwind")
7375 printMachOCompactUnwindSection(Obj, Symbols, Section);
7376 else if (SectName == "__unwind_info")
Tim Northover39c70bb2014-08-12 11:52:59 +00007377 printMachOUnwindInfoSection(Obj, Symbols, Section);
Tim Northover4bd286a2014-08-01 13:07:19 +00007378 }
7379}
Kevin Enderbyb76d3862014-08-22 20:35:18 +00007380
7381static void PrintMachHeader(uint32_t magic, uint32_t cputype,
7382 uint32_t cpusubtype, uint32_t filetype,
7383 uint32_t ncmds, uint32_t sizeofcmds, uint32_t flags,
7384 bool verbose) {
7385 outs() << "Mach header\n";
7386 outs() << " magic cputype cpusubtype caps filetype ncmds "
7387 "sizeofcmds flags\n";
7388 if (verbose) {
7389 if (magic == MachO::MH_MAGIC)
7390 outs() << " MH_MAGIC";
7391 else if (magic == MachO::MH_MAGIC_64)
7392 outs() << "MH_MAGIC_64";
7393 else
7394 outs() << format(" 0x%08" PRIx32, magic);
7395 switch (cputype) {
7396 case MachO::CPU_TYPE_I386:
7397 outs() << " I386";
7398 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
7399 case MachO::CPU_SUBTYPE_I386_ALL:
7400 outs() << " ALL";
7401 break;
7402 default:
7403 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
7404 break;
7405 }
7406 break;
7407 case MachO::CPU_TYPE_X86_64:
7408 outs() << " X86_64";
Kevin Enderby131d1772015-01-09 19:22:37 +00007409 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
7410 case MachO::CPU_SUBTYPE_X86_64_ALL:
7411 outs() << " ALL";
7412 break;
7413 case MachO::CPU_SUBTYPE_X86_64_H:
7414 outs() << " Haswell";
7415 break;
7416 default:
7417 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
7418 break;
7419 }
Kevin Enderbyb76d3862014-08-22 20:35:18 +00007420 break;
7421 case MachO::CPU_TYPE_ARM:
7422 outs() << " ARM";
7423 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
7424 case MachO::CPU_SUBTYPE_ARM_ALL:
7425 outs() << " ALL";
7426 break;
7427 case MachO::CPU_SUBTYPE_ARM_V4T:
7428 outs() << " V4T";
7429 break;
7430 case MachO::CPU_SUBTYPE_ARM_V5TEJ:
7431 outs() << " V5TEJ";
7432 break;
7433 case MachO::CPU_SUBTYPE_ARM_XSCALE:
7434 outs() << " XSCALE";
7435 break;
7436 case MachO::CPU_SUBTYPE_ARM_V6:
7437 outs() << " V6";
7438 break;
7439 case MachO::CPU_SUBTYPE_ARM_V6M:
7440 outs() << " V6M";
7441 break;
7442 case MachO::CPU_SUBTYPE_ARM_V7:
7443 outs() << " V7";
7444 break;
7445 case MachO::CPU_SUBTYPE_ARM_V7EM:
7446 outs() << " V7EM";
7447 break;
7448 case MachO::CPU_SUBTYPE_ARM_V7K:
7449 outs() << " V7K";
7450 break;
7451 case MachO::CPU_SUBTYPE_ARM_V7M:
7452 outs() << " V7M";
7453 break;
7454 case MachO::CPU_SUBTYPE_ARM_V7S:
7455 outs() << " V7S";
7456 break;
7457 default:
7458 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
7459 break;
7460 }
7461 break;
7462 case MachO::CPU_TYPE_ARM64:
7463 outs() << " ARM64";
7464 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
7465 case MachO::CPU_SUBTYPE_ARM64_ALL:
7466 outs() << " ALL";
7467 break;
7468 default:
7469 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
7470 break;
7471 }
7472 break;
7473 case MachO::CPU_TYPE_POWERPC:
7474 outs() << " PPC";
7475 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
7476 case MachO::CPU_SUBTYPE_POWERPC_ALL:
7477 outs() << " ALL";
7478 break;
7479 default:
7480 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
7481 break;
7482 }
7483 break;
7484 case MachO::CPU_TYPE_POWERPC64:
7485 outs() << " PPC64";
7486 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
7487 case MachO::CPU_SUBTYPE_POWERPC_ALL:
7488 outs() << " ALL";
7489 break;
7490 default:
7491 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
7492 break;
7493 }
7494 break;
Kevin Enderby40fdbf82016-01-26 18:20:49 +00007495 default:
7496 outs() << format(" %7d", cputype);
7497 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
7498 break;
Kevin Enderbyb76d3862014-08-22 20:35:18 +00007499 }
7500 if ((cpusubtype & MachO::CPU_SUBTYPE_MASK) == MachO::CPU_SUBTYPE_LIB64) {
Kevin Enderby8ae63c12014-09-04 16:54:47 +00007501 outs() << " LIB64";
Kevin Enderbyb76d3862014-08-22 20:35:18 +00007502 } else {
7503 outs() << format(" 0x%02" PRIx32,
7504 (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24);
7505 }
7506 switch (filetype) {
7507 case MachO::MH_OBJECT:
7508 outs() << " OBJECT";
7509 break;
7510 case MachO::MH_EXECUTE:
7511 outs() << " EXECUTE";
7512 break;
7513 case MachO::MH_FVMLIB:
7514 outs() << " FVMLIB";
7515 break;
7516 case MachO::MH_CORE:
7517 outs() << " CORE";
7518 break;
7519 case MachO::MH_PRELOAD:
7520 outs() << " PRELOAD";
7521 break;
7522 case MachO::MH_DYLIB:
7523 outs() << " DYLIB";
7524 break;
7525 case MachO::MH_DYLIB_STUB:
7526 outs() << " DYLIB_STUB";
7527 break;
7528 case MachO::MH_DYLINKER:
7529 outs() << " DYLINKER";
7530 break;
7531 case MachO::MH_BUNDLE:
7532 outs() << " BUNDLE";
7533 break;
7534 case MachO::MH_DSYM:
7535 outs() << " DSYM";
7536 break;
7537 case MachO::MH_KEXT_BUNDLE:
7538 outs() << " KEXTBUNDLE";
7539 break;
7540 default:
7541 outs() << format(" %10u", filetype);
7542 break;
7543 }
7544 outs() << format(" %5u", ncmds);
7545 outs() << format(" %10u", sizeofcmds);
7546 uint32_t f = flags;
7547 if (f & MachO::MH_NOUNDEFS) {
7548 outs() << " NOUNDEFS";
7549 f &= ~MachO::MH_NOUNDEFS;
7550 }
7551 if (f & MachO::MH_INCRLINK) {
7552 outs() << " INCRLINK";
7553 f &= ~MachO::MH_INCRLINK;
7554 }
7555 if (f & MachO::MH_DYLDLINK) {
7556 outs() << " DYLDLINK";
7557 f &= ~MachO::MH_DYLDLINK;
7558 }
7559 if (f & MachO::MH_BINDATLOAD) {
7560 outs() << " BINDATLOAD";
7561 f &= ~MachO::MH_BINDATLOAD;
7562 }
7563 if (f & MachO::MH_PREBOUND) {
7564 outs() << " PREBOUND";
7565 f &= ~MachO::MH_PREBOUND;
7566 }
7567 if (f & MachO::MH_SPLIT_SEGS) {
7568 outs() << " SPLIT_SEGS";
7569 f &= ~MachO::MH_SPLIT_SEGS;
7570 }
7571 if (f & MachO::MH_LAZY_INIT) {
7572 outs() << " LAZY_INIT";
7573 f &= ~MachO::MH_LAZY_INIT;
7574 }
7575 if (f & MachO::MH_TWOLEVEL) {
7576 outs() << " TWOLEVEL";
7577 f &= ~MachO::MH_TWOLEVEL;
7578 }
7579 if (f & MachO::MH_FORCE_FLAT) {
7580 outs() << " FORCE_FLAT";
7581 f &= ~MachO::MH_FORCE_FLAT;
7582 }
7583 if (f & MachO::MH_NOMULTIDEFS) {
7584 outs() << " NOMULTIDEFS";
7585 f &= ~MachO::MH_NOMULTIDEFS;
7586 }
7587 if (f & MachO::MH_NOFIXPREBINDING) {
7588 outs() << " NOFIXPREBINDING";
7589 f &= ~MachO::MH_NOFIXPREBINDING;
7590 }
7591 if (f & MachO::MH_PREBINDABLE) {
7592 outs() << " PREBINDABLE";
7593 f &= ~MachO::MH_PREBINDABLE;
7594 }
7595 if (f & MachO::MH_ALLMODSBOUND) {
7596 outs() << " ALLMODSBOUND";
7597 f &= ~MachO::MH_ALLMODSBOUND;
7598 }
7599 if (f & MachO::MH_SUBSECTIONS_VIA_SYMBOLS) {
7600 outs() << " SUBSECTIONS_VIA_SYMBOLS";
7601 f &= ~MachO::MH_SUBSECTIONS_VIA_SYMBOLS;
7602 }
7603 if (f & MachO::MH_CANONICAL) {
7604 outs() << " CANONICAL";
7605 f &= ~MachO::MH_CANONICAL;
7606 }
7607 if (f & MachO::MH_WEAK_DEFINES) {
7608 outs() << " WEAK_DEFINES";
7609 f &= ~MachO::MH_WEAK_DEFINES;
7610 }
7611 if (f & MachO::MH_BINDS_TO_WEAK) {
7612 outs() << " BINDS_TO_WEAK";
7613 f &= ~MachO::MH_BINDS_TO_WEAK;
7614 }
7615 if (f & MachO::MH_ALLOW_STACK_EXECUTION) {
7616 outs() << " ALLOW_STACK_EXECUTION";
7617 f &= ~MachO::MH_ALLOW_STACK_EXECUTION;
7618 }
7619 if (f & MachO::MH_DEAD_STRIPPABLE_DYLIB) {
7620 outs() << " DEAD_STRIPPABLE_DYLIB";
7621 f &= ~MachO::MH_DEAD_STRIPPABLE_DYLIB;
7622 }
7623 if (f & MachO::MH_PIE) {
7624 outs() << " PIE";
7625 f &= ~MachO::MH_PIE;
7626 }
7627 if (f & MachO::MH_NO_REEXPORTED_DYLIBS) {
7628 outs() << " NO_REEXPORTED_DYLIBS";
7629 f &= ~MachO::MH_NO_REEXPORTED_DYLIBS;
7630 }
7631 if (f & MachO::MH_HAS_TLV_DESCRIPTORS) {
7632 outs() << " MH_HAS_TLV_DESCRIPTORS";
7633 f &= ~MachO::MH_HAS_TLV_DESCRIPTORS;
7634 }
7635 if (f & MachO::MH_NO_HEAP_EXECUTION) {
7636 outs() << " MH_NO_HEAP_EXECUTION";
7637 f &= ~MachO::MH_NO_HEAP_EXECUTION;
7638 }
7639 if (f & MachO::MH_APP_EXTENSION_SAFE) {
7640 outs() << " APP_EXTENSION_SAFE";
7641 f &= ~MachO::MH_APP_EXTENSION_SAFE;
7642 }
7643 if (f != 0 || flags == 0)
7644 outs() << format(" 0x%08" PRIx32, f);
7645 } else {
7646 outs() << format(" 0x%08" PRIx32, magic);
7647 outs() << format(" %7d", cputype);
7648 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
7649 outs() << format(" 0x%02" PRIx32,
7650 (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24);
7651 outs() << format(" %10u", filetype);
7652 outs() << format(" %5u", ncmds);
7653 outs() << format(" %10u", sizeofcmds);
7654 outs() << format(" 0x%08" PRIx32, flags);
7655 }
7656 outs() << "\n";
7657}
7658
Kevin Enderby956366c2014-08-29 22:30:52 +00007659static void PrintSegmentCommand(uint32_t cmd, uint32_t cmdsize,
7660 StringRef SegName, uint64_t vmaddr,
7661 uint64_t vmsize, uint64_t fileoff,
7662 uint64_t filesize, uint32_t maxprot,
7663 uint32_t initprot, uint32_t nsects,
7664 uint32_t flags, uint32_t object_size,
7665 bool verbose) {
7666 uint64_t expected_cmdsize;
7667 if (cmd == MachO::LC_SEGMENT) {
7668 outs() << " cmd LC_SEGMENT\n";
7669 expected_cmdsize = nsects;
7670 expected_cmdsize *= sizeof(struct MachO::section);
7671 expected_cmdsize += sizeof(struct MachO::segment_command);
7672 } else {
7673 outs() << " cmd LC_SEGMENT_64\n";
7674 expected_cmdsize = nsects;
7675 expected_cmdsize *= sizeof(struct MachO::section_64);
7676 expected_cmdsize += sizeof(struct MachO::segment_command_64);
7677 }
7678 outs() << " cmdsize " << cmdsize;
7679 if (cmdsize != expected_cmdsize)
7680 outs() << " Inconsistent size\n";
7681 else
7682 outs() << "\n";
7683 outs() << " segname " << SegName << "\n";
7684 if (cmd == MachO::LC_SEGMENT_64) {
7685 outs() << " vmaddr " << format("0x%016" PRIx64, vmaddr) << "\n";
7686 outs() << " vmsize " << format("0x%016" PRIx64, vmsize) << "\n";
7687 } else {
Kevin Enderbyadb7c432014-12-16 18:58:11 +00007688 outs() << " vmaddr " << format("0x%08" PRIx64, vmaddr) << "\n";
7689 outs() << " vmsize " << format("0x%08" PRIx64, vmsize) << "\n";
Kevin Enderby956366c2014-08-29 22:30:52 +00007690 }
7691 outs() << " fileoff " << fileoff;
7692 if (fileoff > object_size)
7693 outs() << " (past end of file)\n";
7694 else
7695 outs() << "\n";
7696 outs() << " filesize " << filesize;
7697 if (fileoff + filesize > object_size)
7698 outs() << " (past end of file)\n";
7699 else
7700 outs() << "\n";
7701 if (verbose) {
7702 if ((maxprot &
7703 ~(MachO::VM_PROT_READ | MachO::VM_PROT_WRITE |
7704 MachO::VM_PROT_EXECUTE)) != 0)
7705 outs() << " maxprot ?" << format("0x%08" PRIx32, maxprot) << "\n";
7706 else {
Davide Italiano37ff06a2015-09-02 16:53:25 +00007707 outs() << " maxprot ";
7708 outs() << ((maxprot & MachO::VM_PROT_READ) ? "r" : "-");
7709 outs() << ((maxprot & MachO::VM_PROT_WRITE) ? "w" : "-");
7710 outs() << ((maxprot & MachO::VM_PROT_EXECUTE) ? "x\n" : "-\n");
Kevin Enderby956366c2014-08-29 22:30:52 +00007711 }
7712 if ((initprot &
7713 ~(MachO::VM_PROT_READ | MachO::VM_PROT_WRITE |
7714 MachO::VM_PROT_EXECUTE)) != 0)
7715 outs() << " initprot ?" << format("0x%08" PRIx32, initprot) << "\n";
7716 else {
Davide Italiano37ff06a2015-09-02 16:53:25 +00007717 outs() << " initprot ";
7718 outs() << ((initprot & MachO::VM_PROT_READ) ? "r" : "-");
7719 outs() << ((initprot & MachO::VM_PROT_WRITE) ? "w" : "-");
7720 outs() << ((initprot & MachO::VM_PROT_EXECUTE) ? "x\n" : "-\n");
Kevin Enderby956366c2014-08-29 22:30:52 +00007721 }
7722 } else {
7723 outs() << " maxprot " << format("0x%08" PRIx32, maxprot) << "\n";
7724 outs() << " initprot " << format("0x%08" PRIx32, initprot) << "\n";
7725 }
7726 outs() << " nsects " << nsects << "\n";
7727 if (verbose) {
7728 outs() << " flags";
7729 if (flags == 0)
7730 outs() << " (none)\n";
7731 else {
7732 if (flags & MachO::SG_HIGHVM) {
7733 outs() << " HIGHVM";
7734 flags &= ~MachO::SG_HIGHVM;
7735 }
7736 if (flags & MachO::SG_FVMLIB) {
7737 outs() << " FVMLIB";
7738 flags &= ~MachO::SG_FVMLIB;
7739 }
7740 if (flags & MachO::SG_NORELOC) {
7741 outs() << " NORELOC";
7742 flags &= ~MachO::SG_NORELOC;
7743 }
7744 if (flags & MachO::SG_PROTECTED_VERSION_1) {
7745 outs() << " PROTECTED_VERSION_1";
7746 flags &= ~MachO::SG_PROTECTED_VERSION_1;
7747 }
7748 if (flags)
7749 outs() << format(" 0x%08" PRIx32, flags) << " (unknown flags)\n";
7750 else
7751 outs() << "\n";
7752 }
7753 } else {
7754 outs() << " flags " << format("0x%" PRIx32, flags) << "\n";
7755 }
7756}
7757
7758static void PrintSection(const char *sectname, const char *segname,
7759 uint64_t addr, uint64_t size, uint32_t offset,
7760 uint32_t align, uint32_t reloff, uint32_t nreloc,
7761 uint32_t flags, uint32_t reserved1, uint32_t reserved2,
7762 uint32_t cmd, const char *sg_segname,
7763 uint32_t filetype, uint32_t object_size,
7764 bool verbose) {
7765 outs() << "Section\n";
7766 outs() << " sectname " << format("%.16s\n", sectname);
7767 outs() << " segname " << format("%.16s", segname);
7768 if (filetype != MachO::MH_OBJECT && strncmp(sg_segname, segname, 16) != 0)
7769 outs() << " (does not match segment)\n";
7770 else
7771 outs() << "\n";
7772 if (cmd == MachO::LC_SEGMENT_64) {
7773 outs() << " addr " << format("0x%016" PRIx64, addr) << "\n";
7774 outs() << " size " << format("0x%016" PRIx64, size);
7775 } else {
Kevin Enderby75594b62014-12-16 21:00:25 +00007776 outs() << " addr " << format("0x%08" PRIx64, addr) << "\n";
7777 outs() << " size " << format("0x%08" PRIx64, size);
Kevin Enderby956366c2014-08-29 22:30:52 +00007778 }
7779 if ((flags & MachO::S_ZEROFILL) != 0 && offset + size > object_size)
7780 outs() << " (past end of file)\n";
7781 else
7782 outs() << "\n";
7783 outs() << " offset " << offset;
7784 if (offset > object_size)
7785 outs() << " (past end of file)\n";
7786 else
7787 outs() << "\n";
7788 uint32_t align_shifted = 1 << align;
7789 outs() << " align 2^" << align << " (" << align_shifted << ")\n";
7790 outs() << " reloff " << reloff;
7791 if (reloff > object_size)
7792 outs() << " (past end of file)\n";
7793 else
7794 outs() << "\n";
7795 outs() << " nreloc " << nreloc;
7796 if (reloff + nreloc * sizeof(struct MachO::relocation_info) > object_size)
7797 outs() << " (past end of file)\n";
7798 else
7799 outs() << "\n";
7800 uint32_t section_type = flags & MachO::SECTION_TYPE;
7801 if (verbose) {
7802 outs() << " type";
7803 if (section_type == MachO::S_REGULAR)
7804 outs() << " S_REGULAR\n";
7805 else if (section_type == MachO::S_ZEROFILL)
7806 outs() << " S_ZEROFILL\n";
7807 else if (section_type == MachO::S_CSTRING_LITERALS)
7808 outs() << " S_CSTRING_LITERALS\n";
7809 else if (section_type == MachO::S_4BYTE_LITERALS)
7810 outs() << " S_4BYTE_LITERALS\n";
7811 else if (section_type == MachO::S_8BYTE_LITERALS)
7812 outs() << " S_8BYTE_LITERALS\n";
7813 else if (section_type == MachO::S_16BYTE_LITERALS)
7814 outs() << " S_16BYTE_LITERALS\n";
7815 else if (section_type == MachO::S_LITERAL_POINTERS)
7816 outs() << " S_LITERAL_POINTERS\n";
7817 else if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS)
7818 outs() << " S_NON_LAZY_SYMBOL_POINTERS\n";
7819 else if (section_type == MachO::S_LAZY_SYMBOL_POINTERS)
7820 outs() << " S_LAZY_SYMBOL_POINTERS\n";
7821 else if (section_type == MachO::S_SYMBOL_STUBS)
7822 outs() << " S_SYMBOL_STUBS\n";
7823 else if (section_type == MachO::S_MOD_INIT_FUNC_POINTERS)
7824 outs() << " S_MOD_INIT_FUNC_POINTERS\n";
7825 else if (section_type == MachO::S_MOD_TERM_FUNC_POINTERS)
7826 outs() << " S_MOD_TERM_FUNC_POINTERS\n";
7827 else if (section_type == MachO::S_COALESCED)
7828 outs() << " S_COALESCED\n";
7829 else if (section_type == MachO::S_INTERPOSING)
7830 outs() << " S_INTERPOSING\n";
7831 else if (section_type == MachO::S_DTRACE_DOF)
7832 outs() << " S_DTRACE_DOF\n";
7833 else if (section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS)
7834 outs() << " S_LAZY_DYLIB_SYMBOL_POINTERS\n";
7835 else if (section_type == MachO::S_THREAD_LOCAL_REGULAR)
7836 outs() << " S_THREAD_LOCAL_REGULAR\n";
7837 else if (section_type == MachO::S_THREAD_LOCAL_ZEROFILL)
7838 outs() << " S_THREAD_LOCAL_ZEROFILL\n";
7839 else if (section_type == MachO::S_THREAD_LOCAL_VARIABLES)
7840 outs() << " S_THREAD_LOCAL_VARIABLES\n";
7841 else if (section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS)
7842 outs() << " S_THREAD_LOCAL_VARIABLE_POINTERS\n";
7843 else if (section_type == MachO::S_THREAD_LOCAL_INIT_FUNCTION_POINTERS)
7844 outs() << " S_THREAD_LOCAL_INIT_FUNCTION_POINTERS\n";
7845 else
7846 outs() << format("0x%08" PRIx32, section_type) << "\n";
7847 outs() << "attributes";
7848 uint32_t section_attributes = flags & MachO::SECTION_ATTRIBUTES;
7849 if (section_attributes & MachO::S_ATTR_PURE_INSTRUCTIONS)
7850 outs() << " PURE_INSTRUCTIONS";
7851 if (section_attributes & MachO::S_ATTR_NO_TOC)
7852 outs() << " NO_TOC";
7853 if (section_attributes & MachO::S_ATTR_STRIP_STATIC_SYMS)
7854 outs() << " STRIP_STATIC_SYMS";
7855 if (section_attributes & MachO::S_ATTR_NO_DEAD_STRIP)
7856 outs() << " NO_DEAD_STRIP";
7857 if (section_attributes & MachO::S_ATTR_LIVE_SUPPORT)
7858 outs() << " LIVE_SUPPORT";
7859 if (section_attributes & MachO::S_ATTR_SELF_MODIFYING_CODE)
7860 outs() << " SELF_MODIFYING_CODE";
7861 if (section_attributes & MachO::S_ATTR_DEBUG)
7862 outs() << " DEBUG";
7863 if (section_attributes & MachO::S_ATTR_SOME_INSTRUCTIONS)
7864 outs() << " SOME_INSTRUCTIONS";
7865 if (section_attributes & MachO::S_ATTR_EXT_RELOC)
7866 outs() << " EXT_RELOC";
7867 if (section_attributes & MachO::S_ATTR_LOC_RELOC)
7868 outs() << " LOC_RELOC";
7869 if (section_attributes == 0)
7870 outs() << " (none)";
7871 outs() << "\n";
7872 } else
7873 outs() << " flags " << format("0x%08" PRIx32, flags) << "\n";
7874 outs() << " reserved1 " << reserved1;
7875 if (section_type == MachO::S_SYMBOL_STUBS ||
7876 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
7877 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
7878 section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
7879 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS)
7880 outs() << " (index into indirect symbol table)\n";
7881 else
7882 outs() << "\n";
7883 outs() << " reserved2 " << reserved2;
7884 if (section_type == MachO::S_SYMBOL_STUBS)
7885 outs() << " (size of stubs)\n";
7886 else
7887 outs() << "\n";
7888}
7889
David Majnemer73cc6ff2014-11-13 19:48:56 +00007890static void PrintSymtabLoadCommand(MachO::symtab_command st, bool Is64Bit,
Kevin Enderby956366c2014-08-29 22:30:52 +00007891 uint32_t object_size) {
7892 outs() << " cmd LC_SYMTAB\n";
7893 outs() << " cmdsize " << st.cmdsize;
7894 if (st.cmdsize != sizeof(struct MachO::symtab_command))
7895 outs() << " Incorrect size\n";
7896 else
7897 outs() << "\n";
7898 outs() << " symoff " << st.symoff;
7899 if (st.symoff > object_size)
7900 outs() << " (past end of file)\n";
7901 else
7902 outs() << "\n";
7903 outs() << " nsyms " << st.nsyms;
7904 uint64_t big_size;
David Majnemer73cc6ff2014-11-13 19:48:56 +00007905 if (Is64Bit) {
Kevin Enderby956366c2014-08-29 22:30:52 +00007906 big_size = st.nsyms;
7907 big_size *= sizeof(struct MachO::nlist_64);
7908 big_size += st.symoff;
7909 if (big_size > object_size)
7910 outs() << " (past end of file)\n";
7911 else
7912 outs() << "\n";
7913 } else {
7914 big_size = st.nsyms;
7915 big_size *= sizeof(struct MachO::nlist);
7916 big_size += st.symoff;
7917 if (big_size > object_size)
7918 outs() << " (past end of file)\n";
7919 else
7920 outs() << "\n";
7921 }
7922 outs() << " stroff " << st.stroff;
7923 if (st.stroff > object_size)
7924 outs() << " (past end of file)\n";
7925 else
7926 outs() << "\n";
7927 outs() << " strsize " << st.strsize;
7928 big_size = st.stroff;
7929 big_size += st.strsize;
7930 if (big_size > object_size)
7931 outs() << " (past end of file)\n";
7932 else
7933 outs() << "\n";
7934}
7935
7936static void PrintDysymtabLoadCommand(MachO::dysymtab_command dyst,
7937 uint32_t nsyms, uint32_t object_size,
David Majnemer73cc6ff2014-11-13 19:48:56 +00007938 bool Is64Bit) {
Kevin Enderby956366c2014-08-29 22:30:52 +00007939 outs() << " cmd LC_DYSYMTAB\n";
7940 outs() << " cmdsize " << dyst.cmdsize;
7941 if (dyst.cmdsize != sizeof(struct MachO::dysymtab_command))
7942 outs() << " Incorrect size\n";
7943 else
7944 outs() << "\n";
7945 outs() << " ilocalsym " << dyst.ilocalsym;
7946 if (dyst.ilocalsym > nsyms)
7947 outs() << " (greater than the number of symbols)\n";
7948 else
7949 outs() << "\n";
7950 outs() << " nlocalsym " << dyst.nlocalsym;
7951 uint64_t big_size;
7952 big_size = dyst.ilocalsym;
7953 big_size += dyst.nlocalsym;
7954 if (big_size > nsyms)
7955 outs() << " (past the end of the symbol table)\n";
7956 else
7957 outs() << "\n";
7958 outs() << " iextdefsym " << dyst.iextdefsym;
7959 if (dyst.iextdefsym > nsyms)
7960 outs() << " (greater than the number of symbols)\n";
7961 else
7962 outs() << "\n";
7963 outs() << " nextdefsym " << dyst.nextdefsym;
7964 big_size = dyst.iextdefsym;
7965 big_size += dyst.nextdefsym;
7966 if (big_size > nsyms)
7967 outs() << " (past the end of the symbol table)\n";
7968 else
7969 outs() << "\n";
7970 outs() << " iundefsym " << dyst.iundefsym;
7971 if (dyst.iundefsym > nsyms)
7972 outs() << " (greater than the number of symbols)\n";
7973 else
7974 outs() << "\n";
7975 outs() << " nundefsym " << dyst.nundefsym;
7976 big_size = dyst.iundefsym;
7977 big_size += dyst.nundefsym;
7978 if (big_size > nsyms)
7979 outs() << " (past the end of the symbol table)\n";
7980 else
7981 outs() << "\n";
7982 outs() << " tocoff " << dyst.tocoff;
7983 if (dyst.tocoff > object_size)
7984 outs() << " (past end of file)\n";
7985 else
7986 outs() << "\n";
7987 outs() << " ntoc " << dyst.ntoc;
7988 big_size = dyst.ntoc;
7989 big_size *= sizeof(struct MachO::dylib_table_of_contents);
7990 big_size += dyst.tocoff;
7991 if (big_size > object_size)
7992 outs() << " (past end of file)\n";
7993 else
7994 outs() << "\n";
7995 outs() << " modtaboff " << dyst.modtaboff;
7996 if (dyst.modtaboff > object_size)
7997 outs() << " (past end of file)\n";
7998 else
7999 outs() << "\n";
8000 outs() << " nmodtab " << dyst.nmodtab;
8001 uint64_t modtabend;
David Majnemer73cc6ff2014-11-13 19:48:56 +00008002 if (Is64Bit) {
Kevin Enderby956366c2014-08-29 22:30:52 +00008003 modtabend = dyst.nmodtab;
8004 modtabend *= sizeof(struct MachO::dylib_module_64);
8005 modtabend += dyst.modtaboff;
8006 } else {
8007 modtabend = dyst.nmodtab;
8008 modtabend *= sizeof(struct MachO::dylib_module);
8009 modtabend += dyst.modtaboff;
8010 }
8011 if (modtabend > object_size)
8012 outs() << " (past end of file)\n";
8013 else
8014 outs() << "\n";
8015 outs() << " extrefsymoff " << dyst.extrefsymoff;
8016 if (dyst.extrefsymoff > object_size)
8017 outs() << " (past end of file)\n";
8018 else
8019 outs() << "\n";
8020 outs() << " nextrefsyms " << dyst.nextrefsyms;
8021 big_size = dyst.nextrefsyms;
8022 big_size *= sizeof(struct MachO::dylib_reference);
8023 big_size += dyst.extrefsymoff;
8024 if (big_size > object_size)
8025 outs() << " (past end of file)\n";
8026 else
8027 outs() << "\n";
8028 outs() << " indirectsymoff " << dyst.indirectsymoff;
8029 if (dyst.indirectsymoff > object_size)
8030 outs() << " (past end of file)\n";
8031 else
8032 outs() << "\n";
8033 outs() << " nindirectsyms " << dyst.nindirectsyms;
8034 big_size = dyst.nindirectsyms;
8035 big_size *= sizeof(uint32_t);
8036 big_size += dyst.indirectsymoff;
8037 if (big_size > object_size)
8038 outs() << " (past end of file)\n";
8039 else
8040 outs() << "\n";
8041 outs() << " extreloff " << dyst.extreloff;
8042 if (dyst.extreloff > object_size)
8043 outs() << " (past end of file)\n";
8044 else
8045 outs() << "\n";
8046 outs() << " nextrel " << dyst.nextrel;
8047 big_size = dyst.nextrel;
8048 big_size *= sizeof(struct MachO::relocation_info);
8049 big_size += dyst.extreloff;
8050 if (big_size > object_size)
8051 outs() << " (past end of file)\n";
8052 else
8053 outs() << "\n";
8054 outs() << " locreloff " << dyst.locreloff;
8055 if (dyst.locreloff > object_size)
8056 outs() << " (past end of file)\n";
8057 else
8058 outs() << "\n";
8059 outs() << " nlocrel " << dyst.nlocrel;
8060 big_size = dyst.nlocrel;
8061 big_size *= sizeof(struct MachO::relocation_info);
8062 big_size += dyst.locreloff;
8063 if (big_size > object_size)
8064 outs() << " (past end of file)\n";
8065 else
8066 outs() << "\n";
8067}
8068
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008069static void PrintDyldInfoLoadCommand(MachO::dyld_info_command dc,
8070 uint32_t object_size) {
8071 if (dc.cmd == MachO::LC_DYLD_INFO)
8072 outs() << " cmd LC_DYLD_INFO\n";
8073 else
8074 outs() << " cmd LC_DYLD_INFO_ONLY\n";
8075 outs() << " cmdsize " << dc.cmdsize;
8076 if (dc.cmdsize != sizeof(struct MachO::dyld_info_command))
8077 outs() << " Incorrect size\n";
8078 else
8079 outs() << "\n";
8080 outs() << " rebase_off " << dc.rebase_off;
8081 if (dc.rebase_off > object_size)
8082 outs() << " (past end of file)\n";
8083 else
8084 outs() << "\n";
8085 outs() << " rebase_size " << dc.rebase_size;
8086 uint64_t big_size;
8087 big_size = dc.rebase_off;
8088 big_size += dc.rebase_size;
8089 if (big_size > object_size)
8090 outs() << " (past end of file)\n";
8091 else
8092 outs() << "\n";
8093 outs() << " bind_off " << dc.bind_off;
8094 if (dc.bind_off > object_size)
8095 outs() << " (past end of file)\n";
8096 else
8097 outs() << "\n";
8098 outs() << " bind_size " << dc.bind_size;
8099 big_size = dc.bind_off;
8100 big_size += dc.bind_size;
8101 if (big_size > object_size)
8102 outs() << " (past end of file)\n";
8103 else
8104 outs() << "\n";
8105 outs() << " weak_bind_off " << dc.weak_bind_off;
8106 if (dc.weak_bind_off > object_size)
8107 outs() << " (past end of file)\n";
8108 else
8109 outs() << "\n";
8110 outs() << " weak_bind_size " << dc.weak_bind_size;
8111 big_size = dc.weak_bind_off;
8112 big_size += dc.weak_bind_size;
8113 if (big_size > object_size)
8114 outs() << " (past end of file)\n";
8115 else
8116 outs() << "\n";
8117 outs() << " lazy_bind_off " << dc.lazy_bind_off;
8118 if (dc.lazy_bind_off > object_size)
8119 outs() << " (past end of file)\n";
8120 else
8121 outs() << "\n";
8122 outs() << " lazy_bind_size " << dc.lazy_bind_size;
8123 big_size = dc.lazy_bind_off;
8124 big_size += dc.lazy_bind_size;
8125 if (big_size > object_size)
8126 outs() << " (past end of file)\n";
8127 else
8128 outs() << "\n";
8129 outs() << " export_off " << dc.export_off;
8130 if (dc.export_off > object_size)
8131 outs() << " (past end of file)\n";
8132 else
8133 outs() << "\n";
8134 outs() << " export_size " << dc.export_size;
8135 big_size = dc.export_off;
8136 big_size += dc.export_size;
8137 if (big_size > object_size)
8138 outs() << " (past end of file)\n";
8139 else
8140 outs() << "\n";
8141}
8142
8143static void PrintDyldLoadCommand(MachO::dylinker_command dyld,
8144 const char *Ptr) {
8145 if (dyld.cmd == MachO::LC_ID_DYLINKER)
8146 outs() << " cmd LC_ID_DYLINKER\n";
8147 else if (dyld.cmd == MachO::LC_LOAD_DYLINKER)
8148 outs() << " cmd LC_LOAD_DYLINKER\n";
8149 else if (dyld.cmd == MachO::LC_DYLD_ENVIRONMENT)
8150 outs() << " cmd LC_DYLD_ENVIRONMENT\n";
8151 else
8152 outs() << " cmd ?(" << dyld.cmd << ")\n";
8153 outs() << " cmdsize " << dyld.cmdsize;
8154 if (dyld.cmdsize < sizeof(struct MachO::dylinker_command))
8155 outs() << " Incorrect size\n";
8156 else
8157 outs() << "\n";
8158 if (dyld.name >= dyld.cmdsize)
8159 outs() << " name ?(bad offset " << dyld.name << ")\n";
8160 else {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00008161 const char *P = (const char *)(Ptr) + dyld.name;
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008162 outs() << " name " << P << " (offset " << dyld.name << ")\n";
8163 }
8164}
8165
8166static void PrintUuidLoadCommand(MachO::uuid_command uuid) {
8167 outs() << " cmd LC_UUID\n";
8168 outs() << " cmdsize " << uuid.cmdsize;
8169 if (uuid.cmdsize != sizeof(struct MachO::uuid_command))
8170 outs() << " Incorrect size\n";
8171 else
8172 outs() << "\n";
8173 outs() << " uuid ";
Davide Italianoc74277a2015-12-07 00:03:28 +00008174 for (int i = 0; i < 16; ++i) {
8175 outs() << format("%02" PRIX32, uuid.uuid[i]);
8176 if (i == 3 || i == 5 || i == 7 || i == 9)
8177 outs() << "-";
8178 }
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008179 outs() << "\n";
8180}
8181
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008182static void PrintRpathLoadCommand(MachO::rpath_command rpath, const char *Ptr) {
Jean-Daniel Dupas00cc1f52014-12-04 07:37:02 +00008183 outs() << " cmd LC_RPATH\n";
8184 outs() << " cmdsize " << rpath.cmdsize;
8185 if (rpath.cmdsize < sizeof(struct MachO::rpath_command))
8186 outs() << " Incorrect size\n";
8187 else
8188 outs() << "\n";
8189 if (rpath.path >= rpath.cmdsize)
8190 outs() << " path ?(bad offset " << rpath.path << ")\n";
8191 else {
8192 const char *P = (const char *)(Ptr) + rpath.path;
8193 outs() << " path " << P << " (offset " << rpath.path << ")\n";
8194 }
8195}
8196
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008197static void PrintVersionMinLoadCommand(MachO::version_min_command vd) {
Tim Northoverbfbfb122015-11-02 21:26:58 +00008198 StringRef LoadCmdName;
8199 switch (vd.cmd) {
8200 case MachO::LC_VERSION_MIN_MACOSX:
8201 LoadCmdName = "LC_VERSION_MIN_MACOSX";
8202 break;
8203 case MachO::LC_VERSION_MIN_IPHONEOS:
8204 LoadCmdName = "LC_VERSION_MIN_IPHONEOS";
8205 break;
8206 case MachO::LC_VERSION_MIN_TVOS:
8207 LoadCmdName = "LC_VERSION_MIN_TVOS";
8208 break;
8209 case MachO::LC_VERSION_MIN_WATCHOS:
8210 LoadCmdName = "LC_VERSION_MIN_WATCHOS";
8211 break;
8212 default:
8213 llvm_unreachable("Unknown version min load command");
8214 }
8215
8216 outs() << " cmd " << LoadCmdName << '\n';
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008217 outs() << " cmdsize " << vd.cmdsize;
8218 if (vd.cmdsize != sizeof(struct MachO::version_min_command))
8219 outs() << " Incorrect size\n";
8220 else
8221 outs() << "\n";
Davide Italiano56baef32015-08-26 12:26:11 +00008222 outs() << " version "
8223 << MachOObjectFile::getVersionMinMajor(vd, false) << "."
8224 << MachOObjectFile::getVersionMinMinor(vd, false);
8225 uint32_t Update = MachOObjectFile::getVersionMinUpdate(vd, false);
8226 if (Update != 0)
8227 outs() << "." << Update;
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008228 outs() << "\n";
8229 if (vd.sdk == 0)
Kevin Enderby57538292014-12-17 01:01:30 +00008230 outs() << " sdk n/a";
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008231 else {
Davide Italiano56baef32015-08-26 12:26:11 +00008232 outs() << " sdk "
8233 << MachOObjectFile::getVersionMinMajor(vd, true) << "."
8234 << MachOObjectFile::getVersionMinMinor(vd, true);
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008235 }
Davide Italiano56baef32015-08-26 12:26:11 +00008236 Update = MachOObjectFile::getVersionMinUpdate(vd, true);
8237 if (Update != 0)
8238 outs() << "." << Update;
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008239 outs() << "\n";
8240}
8241
8242static void PrintSourceVersionCommand(MachO::source_version_command sd) {
8243 outs() << " cmd LC_SOURCE_VERSION\n";
8244 outs() << " cmdsize " << sd.cmdsize;
8245 if (sd.cmdsize != sizeof(struct MachO::source_version_command))
8246 outs() << " Incorrect size\n";
8247 else
8248 outs() << "\n";
8249 uint64_t a = (sd.version >> 40) & 0xffffff;
8250 uint64_t b = (sd.version >> 30) & 0x3ff;
8251 uint64_t c = (sd.version >> 20) & 0x3ff;
8252 uint64_t d = (sd.version >> 10) & 0x3ff;
8253 uint64_t e = sd.version & 0x3ff;
8254 outs() << " version " << a << "." << b;
8255 if (e != 0)
8256 outs() << "." << c << "." << d << "." << e;
8257 else if (d != 0)
8258 outs() << "." << c << "." << d;
8259 else if (c != 0)
8260 outs() << "." << c;
8261 outs() << "\n";
8262}
8263
8264static void PrintEntryPointCommand(MachO::entry_point_command ep) {
8265 outs() << " cmd LC_MAIN\n";
8266 outs() << " cmdsize " << ep.cmdsize;
8267 if (ep.cmdsize != sizeof(struct MachO::entry_point_command))
8268 outs() << " Incorrect size\n";
8269 else
8270 outs() << "\n";
8271 outs() << " entryoff " << ep.entryoff << "\n";
8272 outs() << " stacksize " << ep.stacksize << "\n";
8273}
8274
Kevin Enderby0804f4672014-12-16 23:25:52 +00008275static void PrintEncryptionInfoCommand(MachO::encryption_info_command ec,
8276 uint32_t object_size) {
8277 outs() << " cmd LC_ENCRYPTION_INFO\n";
8278 outs() << " cmdsize " << ec.cmdsize;
8279 if (ec.cmdsize != sizeof(struct MachO::encryption_info_command))
8280 outs() << " Incorrect size\n";
8281 else
8282 outs() << "\n";
8283 outs() << " cryptoff " << ec.cryptoff;
8284 if (ec.cryptoff > object_size)
8285 outs() << " (past end of file)\n";
8286 else
8287 outs() << "\n";
8288 outs() << " cryptsize " << ec.cryptsize;
8289 if (ec.cryptsize > object_size)
8290 outs() << " (past end of file)\n";
8291 else
8292 outs() << "\n";
8293 outs() << " cryptid " << ec.cryptid << "\n";
8294}
8295
Kevin Enderby57538292014-12-17 01:01:30 +00008296static void PrintEncryptionInfoCommand64(MachO::encryption_info_command_64 ec,
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008297 uint32_t object_size) {
Kevin Enderby57538292014-12-17 01:01:30 +00008298 outs() << " cmd LC_ENCRYPTION_INFO_64\n";
8299 outs() << " cmdsize " << ec.cmdsize;
8300 if (ec.cmdsize != sizeof(struct MachO::encryption_info_command_64))
8301 outs() << " Incorrect size\n";
8302 else
8303 outs() << "\n";
8304 outs() << " cryptoff " << ec.cryptoff;
8305 if (ec.cryptoff > object_size)
8306 outs() << " (past end of file)\n";
8307 else
8308 outs() << "\n";
8309 outs() << " cryptsize " << ec.cryptsize;
8310 if (ec.cryptsize > object_size)
8311 outs() << " (past end of file)\n";
8312 else
8313 outs() << "\n";
8314 outs() << " cryptid " << ec.cryptid << "\n";
8315 outs() << " pad " << ec.pad << "\n";
8316}
8317
Kevin Enderbyd0b6b7f2014-12-18 00:53:40 +00008318static void PrintLinkerOptionCommand(MachO::linker_option_command lo,
8319 const char *Ptr) {
8320 outs() << " cmd LC_LINKER_OPTION\n";
8321 outs() << " cmdsize " << lo.cmdsize;
8322 if (lo.cmdsize < sizeof(struct MachO::linker_option_command))
8323 outs() << " Incorrect size\n";
8324 else
8325 outs() << "\n";
8326 outs() << " count " << lo.count << "\n";
8327 const char *string = Ptr + sizeof(struct MachO::linker_option_command);
8328 uint32_t left = lo.cmdsize - sizeof(struct MachO::linker_option_command);
8329 uint32_t i = 0;
8330 while (left > 0) {
8331 while (*string == '\0' && left > 0) {
8332 string++;
8333 left--;
8334 }
8335 if (left > 0) {
8336 i++;
8337 outs() << " string #" << i << " " << format("%.*s\n", left, string);
David Majnemerd4449ed2014-12-20 08:24:43 +00008338 uint32_t NullPos = StringRef(string, left).find('\0');
8339 uint32_t len = std::min(NullPos, left) + 1;
Kevin Enderbyd0b6b7f2014-12-18 00:53:40 +00008340 string += len;
8341 left -= len;
8342 }
8343 }
8344 if (lo.count != i)
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008345 outs() << " count " << lo.count << " does not match number of strings "
8346 << i << "\n";
Kevin Enderbyd0b6b7f2014-12-18 00:53:40 +00008347}
8348
Kevin Enderbyb4b79312014-12-18 19:24:35 +00008349static void PrintSubFrameworkCommand(MachO::sub_framework_command sub,
8350 const char *Ptr) {
8351 outs() << " cmd LC_SUB_FRAMEWORK\n";
8352 outs() << " cmdsize " << sub.cmdsize;
8353 if (sub.cmdsize < sizeof(struct MachO::sub_framework_command))
8354 outs() << " Incorrect size\n";
8355 else
8356 outs() << "\n";
8357 if (sub.umbrella < sub.cmdsize) {
8358 const char *P = Ptr + sub.umbrella;
8359 outs() << " umbrella " << P << " (offset " << sub.umbrella << ")\n";
8360 } else {
8361 outs() << " umbrella ?(bad offset " << sub.umbrella << ")\n";
8362 }
8363}
8364
Kevin Enderbya2bd8d92014-12-18 23:13:26 +00008365static void PrintSubUmbrellaCommand(MachO::sub_umbrella_command sub,
8366 const char *Ptr) {
8367 outs() << " cmd LC_SUB_UMBRELLA\n";
8368 outs() << " cmdsize " << sub.cmdsize;
8369 if (sub.cmdsize < sizeof(struct MachO::sub_umbrella_command))
8370 outs() << " Incorrect size\n";
8371 else
8372 outs() << "\n";
8373 if (sub.sub_umbrella < sub.cmdsize) {
8374 const char *P = Ptr + sub.sub_umbrella;
8375 outs() << " sub_umbrella " << P << " (offset " << sub.sub_umbrella << ")\n";
8376 } else {
8377 outs() << " sub_umbrella ?(bad offset " << sub.sub_umbrella << ")\n";
8378 }
8379}
8380
Kevin Enderby36c8d3a2014-12-19 19:48:16 +00008381static void PrintSubLibraryCommand(MachO::sub_library_command sub,
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008382 const char *Ptr) {
Kevin Enderby36c8d3a2014-12-19 19:48:16 +00008383 outs() << " cmd LC_SUB_LIBRARY\n";
8384 outs() << " cmdsize " << sub.cmdsize;
8385 if (sub.cmdsize < sizeof(struct MachO::sub_library_command))
8386 outs() << " Incorrect size\n";
8387 else
8388 outs() << "\n";
8389 if (sub.sub_library < sub.cmdsize) {
8390 const char *P = Ptr + sub.sub_library;
8391 outs() << " sub_library " << P << " (offset " << sub.sub_library << ")\n";
8392 } else {
8393 outs() << " sub_library ?(bad offset " << sub.sub_library << ")\n";
8394 }
8395}
8396
Kevin Enderby186eac32014-12-19 21:06:24 +00008397static void PrintSubClientCommand(MachO::sub_client_command sub,
8398 const char *Ptr) {
8399 outs() << " cmd LC_SUB_CLIENT\n";
8400 outs() << " cmdsize " << sub.cmdsize;
8401 if (sub.cmdsize < sizeof(struct MachO::sub_client_command))
8402 outs() << " Incorrect size\n";
8403 else
8404 outs() << "\n";
8405 if (sub.client < sub.cmdsize) {
8406 const char *P = Ptr + sub.client;
8407 outs() << " client " << P << " (offset " << sub.client << ")\n";
8408 } else {
8409 outs() << " client ?(bad offset " << sub.client << ")\n";
8410 }
8411}
Kevin Enderby36c8d3a2014-12-19 19:48:16 +00008412
Kevin Enderby52e4ce42014-12-19 22:25:22 +00008413static void PrintRoutinesCommand(MachO::routines_command r) {
8414 outs() << " cmd LC_ROUTINES\n";
8415 outs() << " cmdsize " << r.cmdsize;
8416 if (r.cmdsize != sizeof(struct MachO::routines_command))
8417 outs() << " Incorrect size\n";
8418 else
8419 outs() << "\n";
8420 outs() << " init_address " << format("0x%08" PRIx32, r.init_address) << "\n";
8421 outs() << " init_module " << r.init_module << "\n";
8422 outs() << " reserved1 " << r.reserved1 << "\n";
8423 outs() << " reserved2 " << r.reserved2 << "\n";
8424 outs() << " reserved3 " << r.reserved3 << "\n";
8425 outs() << " reserved4 " << r.reserved4 << "\n";
8426 outs() << " reserved5 " << r.reserved5 << "\n";
8427 outs() << " reserved6 " << r.reserved6 << "\n";
8428}
8429
8430static void PrintRoutinesCommand64(MachO::routines_command_64 r) {
8431 outs() << " cmd LC_ROUTINES_64\n";
8432 outs() << " cmdsize " << r.cmdsize;
8433 if (r.cmdsize != sizeof(struct MachO::routines_command_64))
8434 outs() << " Incorrect size\n";
8435 else
8436 outs() << "\n";
8437 outs() << " init_address " << format("0x%016" PRIx64, r.init_address) << "\n";
8438 outs() << " init_module " << r.init_module << "\n";
8439 outs() << " reserved1 " << r.reserved1 << "\n";
8440 outs() << " reserved2 " << r.reserved2 << "\n";
8441 outs() << " reserved3 " << r.reserved3 << "\n";
8442 outs() << " reserved4 " << r.reserved4 << "\n";
8443 outs() << " reserved5 " << r.reserved5 << "\n";
8444 outs() << " reserved6 " << r.reserved6 << "\n";
8445}
8446
Kevin Enderby48ef5342014-12-23 22:56:39 +00008447static void Print_x86_thread_state64_t(MachO::x86_thread_state64_t &cpu64) {
8448 outs() << " rax " << format("0x%016" PRIx64, cpu64.rax);
8449 outs() << " rbx " << format("0x%016" PRIx64, cpu64.rbx);
8450 outs() << " rcx " << format("0x%016" PRIx64, cpu64.rcx) << "\n";
8451 outs() << " rdx " << format("0x%016" PRIx64, cpu64.rdx);
8452 outs() << " rdi " << format("0x%016" PRIx64, cpu64.rdi);
8453 outs() << " rsi " << format("0x%016" PRIx64, cpu64.rsi) << "\n";
8454 outs() << " rbp " << format("0x%016" PRIx64, cpu64.rbp);
8455 outs() << " rsp " << format("0x%016" PRIx64, cpu64.rsp);
8456 outs() << " r8 " << format("0x%016" PRIx64, cpu64.r8) << "\n";
8457 outs() << " r9 " << format("0x%016" PRIx64, cpu64.r9);
8458 outs() << " r10 " << format("0x%016" PRIx64, cpu64.r10);
8459 outs() << " r11 " << format("0x%016" PRIx64, cpu64.r11) << "\n";
8460 outs() << " r12 " << format("0x%016" PRIx64, cpu64.r12);
8461 outs() << " r13 " << format("0x%016" PRIx64, cpu64.r13);
8462 outs() << " r14 " << format("0x%016" PRIx64, cpu64.r14) << "\n";
8463 outs() << " r15 " << format("0x%016" PRIx64, cpu64.r15);
8464 outs() << " rip " << format("0x%016" PRIx64, cpu64.rip) << "\n";
8465 outs() << "rflags " << format("0x%016" PRIx64, cpu64.rflags);
8466 outs() << " cs " << format("0x%016" PRIx64, cpu64.cs);
8467 outs() << " fs " << format("0x%016" PRIx64, cpu64.fs) << "\n";
8468 outs() << " gs " << format("0x%016" PRIx64, cpu64.gs) << "\n";
8469}
8470
Kevin Enderby227df342014-12-23 23:43:59 +00008471static void Print_mmst_reg(MachO::mmst_reg_t &r) {
Kevin Enderby48ef5342014-12-23 22:56:39 +00008472 uint32_t f;
8473 outs() << "\t mmst_reg ";
8474 for (f = 0; f < 10; f++)
8475 outs() << format("%02" PRIx32, (r.mmst_reg[f] & 0xff)) << " ";
8476 outs() << "\n";
8477 outs() << "\t mmst_rsrv ";
8478 for (f = 0; f < 6; f++)
8479 outs() << format("%02" PRIx32, (r.mmst_rsrv[f] & 0xff)) << " ";
8480 outs() << "\n";
8481}
8482
Kevin Enderbyaefb0032014-12-24 00:16:51 +00008483static void Print_xmm_reg(MachO::xmm_reg_t &r) {
Kevin Enderby48ef5342014-12-23 22:56:39 +00008484 uint32_t f;
8485 outs() << "\t xmm_reg ";
8486 for (f = 0; f < 16; f++)
8487 outs() << format("%02" PRIx32, (r.xmm_reg[f] & 0xff)) << " ";
8488 outs() << "\n";
8489}
8490
8491static void Print_x86_float_state_t(MachO::x86_float_state64_t &fpu) {
8492 outs() << "\t fpu_reserved[0] " << fpu.fpu_reserved[0];
8493 outs() << " fpu_reserved[1] " << fpu.fpu_reserved[1] << "\n";
8494 outs() << "\t control: invalid " << fpu.fpu_fcw.invalid;
8495 outs() << " denorm " << fpu.fpu_fcw.denorm;
8496 outs() << " zdiv " << fpu.fpu_fcw.zdiv;
8497 outs() << " ovrfl " << fpu.fpu_fcw.ovrfl;
8498 outs() << " undfl " << fpu.fpu_fcw.undfl;
8499 outs() << " precis " << fpu.fpu_fcw.precis << "\n";
8500 outs() << "\t\t pc ";
8501 if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_24B)
8502 outs() << "FP_PREC_24B ";
8503 else if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_53B)
8504 outs() << "FP_PREC_53B ";
8505 else if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_64B)
8506 outs() << "FP_PREC_64B ";
8507 else
8508 outs() << fpu.fpu_fcw.pc << " ";
8509 outs() << "rc ";
8510 if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_NEAR)
8511 outs() << "FP_RND_NEAR ";
8512 else if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_DOWN)
8513 outs() << "FP_RND_DOWN ";
8514 else if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_UP)
8515 outs() << "FP_RND_UP ";
8516 else if (fpu.fpu_fcw.rc == MachO::x86_FP_CHOP)
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008517 outs() << "FP_CHOP ";
Kevin Enderby48ef5342014-12-23 22:56:39 +00008518 outs() << "\n";
8519 outs() << "\t status: invalid " << fpu.fpu_fsw.invalid;
8520 outs() << " denorm " << fpu.fpu_fsw.denorm;
8521 outs() << " zdiv " << fpu.fpu_fsw.zdiv;
8522 outs() << " ovrfl " << fpu.fpu_fsw.ovrfl;
8523 outs() << " undfl " << fpu.fpu_fsw.undfl;
8524 outs() << " precis " << fpu.fpu_fsw.precis;
8525 outs() << " stkflt " << fpu.fpu_fsw.stkflt << "\n";
8526 outs() << "\t errsumm " << fpu.fpu_fsw.errsumm;
8527 outs() << " c0 " << fpu.fpu_fsw.c0;
8528 outs() << " c1 " << fpu.fpu_fsw.c1;
8529 outs() << " c2 " << fpu.fpu_fsw.c2;
8530 outs() << " tos " << fpu.fpu_fsw.tos;
8531 outs() << " c3 " << fpu.fpu_fsw.c3;
8532 outs() << " busy " << fpu.fpu_fsw.busy << "\n";
8533 outs() << "\t fpu_ftw " << format("0x%02" PRIx32, fpu.fpu_ftw);
8534 outs() << " fpu_rsrv1 " << format("0x%02" PRIx32, fpu.fpu_rsrv1);
8535 outs() << " fpu_fop " << format("0x%04" PRIx32, fpu.fpu_fop);
8536 outs() << " fpu_ip " << format("0x%08" PRIx32, fpu.fpu_ip) << "\n";
8537 outs() << "\t fpu_cs " << format("0x%04" PRIx32, fpu.fpu_cs);
8538 outs() << " fpu_rsrv2 " << format("0x%04" PRIx32, fpu.fpu_rsrv2);
8539 outs() << " fpu_dp " << format("0x%08" PRIx32, fpu.fpu_dp);
8540 outs() << " fpu_ds " << format("0x%04" PRIx32, fpu.fpu_ds) << "\n";
8541 outs() << "\t fpu_rsrv3 " << format("0x%04" PRIx32, fpu.fpu_rsrv3);
8542 outs() << " fpu_mxcsr " << format("0x%08" PRIx32, fpu.fpu_mxcsr);
8543 outs() << " fpu_mxcsrmask " << format("0x%08" PRIx32, fpu.fpu_mxcsrmask);
8544 outs() << "\n";
8545 outs() << "\t fpu_stmm0:\n";
8546 Print_mmst_reg(fpu.fpu_stmm0);
8547 outs() << "\t fpu_stmm1:\n";
8548 Print_mmst_reg(fpu.fpu_stmm1);
8549 outs() << "\t fpu_stmm2:\n";
8550 Print_mmst_reg(fpu.fpu_stmm2);
8551 outs() << "\t fpu_stmm3:\n";
8552 Print_mmst_reg(fpu.fpu_stmm3);
8553 outs() << "\t fpu_stmm4:\n";
8554 Print_mmst_reg(fpu.fpu_stmm4);
8555 outs() << "\t fpu_stmm5:\n";
8556 Print_mmst_reg(fpu.fpu_stmm5);
8557 outs() << "\t fpu_stmm6:\n";
8558 Print_mmst_reg(fpu.fpu_stmm6);
8559 outs() << "\t fpu_stmm7:\n";
8560 Print_mmst_reg(fpu.fpu_stmm7);
8561 outs() << "\t fpu_xmm0:\n";
8562 Print_xmm_reg(fpu.fpu_xmm0);
8563 outs() << "\t fpu_xmm1:\n";
8564 Print_xmm_reg(fpu.fpu_xmm1);
8565 outs() << "\t fpu_xmm2:\n";
8566 Print_xmm_reg(fpu.fpu_xmm2);
8567 outs() << "\t fpu_xmm3:\n";
8568 Print_xmm_reg(fpu.fpu_xmm3);
8569 outs() << "\t fpu_xmm4:\n";
8570 Print_xmm_reg(fpu.fpu_xmm4);
8571 outs() << "\t fpu_xmm5:\n";
8572 Print_xmm_reg(fpu.fpu_xmm5);
8573 outs() << "\t fpu_xmm6:\n";
8574 Print_xmm_reg(fpu.fpu_xmm6);
8575 outs() << "\t fpu_xmm7:\n";
8576 Print_xmm_reg(fpu.fpu_xmm7);
8577 outs() << "\t fpu_xmm8:\n";
8578 Print_xmm_reg(fpu.fpu_xmm8);
8579 outs() << "\t fpu_xmm9:\n";
8580 Print_xmm_reg(fpu.fpu_xmm9);
8581 outs() << "\t fpu_xmm10:\n";
8582 Print_xmm_reg(fpu.fpu_xmm10);
8583 outs() << "\t fpu_xmm11:\n";
8584 Print_xmm_reg(fpu.fpu_xmm11);
8585 outs() << "\t fpu_xmm12:\n";
8586 Print_xmm_reg(fpu.fpu_xmm12);
8587 outs() << "\t fpu_xmm13:\n";
8588 Print_xmm_reg(fpu.fpu_xmm13);
8589 outs() << "\t fpu_xmm14:\n";
8590 Print_xmm_reg(fpu.fpu_xmm14);
8591 outs() << "\t fpu_xmm15:\n";
8592 Print_xmm_reg(fpu.fpu_xmm15);
8593 outs() << "\t fpu_rsrv4:\n";
8594 for (uint32_t f = 0; f < 6; f++) {
8595 outs() << "\t ";
8596 for (uint32_t g = 0; g < 16; g++)
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008597 outs() << format("%02" PRIx32, fpu.fpu_rsrv4[f * g]) << " ";
Kevin Enderby48ef5342014-12-23 22:56:39 +00008598 outs() << "\n";
8599 }
8600 outs() << "\t fpu_reserved1 " << format("0x%08" PRIx32, fpu.fpu_reserved1);
8601 outs() << "\n";
8602}
8603
8604static void Print_x86_exception_state_t(MachO::x86_exception_state64_t &exc64) {
8605 outs() << "\t trapno " << format("0x%08" PRIx32, exc64.trapno);
8606 outs() << " err " << format("0x%08" PRIx32, exc64.err);
8607 outs() << " faultvaddr " << format("0x%016" PRIx64, exc64.faultvaddr) << "\n";
8608}
8609
8610static void PrintThreadCommand(MachO::thread_command t, const char *Ptr,
8611 bool isLittleEndian, uint32_t cputype) {
8612 if (t.cmd == MachO::LC_THREAD)
8613 outs() << " cmd LC_THREAD\n";
8614 else if (t.cmd == MachO::LC_UNIXTHREAD)
8615 outs() << " cmd LC_UNIXTHREAD\n";
8616 else
8617 outs() << " cmd " << t.cmd << " (unknown)\n";
8618 outs() << " cmdsize " << t.cmdsize;
8619 if (t.cmdsize < sizeof(struct MachO::thread_command) + 2 * sizeof(uint32_t))
8620 outs() << " Incorrect size\n";
8621 else
8622 outs() << "\n";
8623
8624 const char *begin = Ptr + sizeof(struct MachO::thread_command);
8625 const char *end = Ptr + t.cmdsize;
8626 uint32_t flavor, count, left;
8627 if (cputype == MachO::CPU_TYPE_X86_64) {
8628 while (begin < end) {
8629 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
8630 memcpy((char *)&flavor, begin, sizeof(uint32_t));
8631 begin += sizeof(uint32_t);
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008632 } else {
Kevin Enderby48ef5342014-12-23 22:56:39 +00008633 flavor = 0;
8634 begin = end;
8635 }
8636 if (isLittleEndian != sys::IsLittleEndianHost)
8637 sys::swapByteOrder(flavor);
8638 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
8639 memcpy((char *)&count, begin, sizeof(uint32_t));
8640 begin += sizeof(uint32_t);
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008641 } else {
Kevin Enderby48ef5342014-12-23 22:56:39 +00008642 count = 0;
8643 begin = end;
8644 }
8645 if (isLittleEndian != sys::IsLittleEndianHost)
8646 sys::swapByteOrder(count);
8647 if (flavor == MachO::x86_THREAD_STATE64) {
8648 outs() << " flavor x86_THREAD_STATE64\n";
8649 if (count == MachO::x86_THREAD_STATE64_COUNT)
8650 outs() << " count x86_THREAD_STATE64_COUNT\n";
8651 else
8652 outs() << " count " << count
8653 << " (not x86_THREAD_STATE64_COUNT)\n";
8654 MachO::x86_thread_state64_t cpu64;
8655 left = end - begin;
8656 if (left >= sizeof(MachO::x86_thread_state64_t)) {
8657 memcpy(&cpu64, begin, sizeof(MachO::x86_thread_state64_t));
8658 begin += sizeof(MachO::x86_thread_state64_t);
8659 } else {
8660 memset(&cpu64, '\0', sizeof(MachO::x86_thread_state64_t));
8661 memcpy(&cpu64, begin, left);
8662 begin += left;
8663 }
8664 if (isLittleEndian != sys::IsLittleEndianHost)
8665 swapStruct(cpu64);
8666 Print_x86_thread_state64_t(cpu64);
8667 } else if (flavor == MachO::x86_THREAD_STATE) {
8668 outs() << " flavor x86_THREAD_STATE\n";
8669 if (count == MachO::x86_THREAD_STATE_COUNT)
8670 outs() << " count x86_THREAD_STATE_COUNT\n";
8671 else
8672 outs() << " count " << count
8673 << " (not x86_THREAD_STATE_COUNT)\n";
8674 struct MachO::x86_thread_state_t ts;
8675 left = end - begin;
8676 if (left >= sizeof(MachO::x86_thread_state_t)) {
8677 memcpy(&ts, begin, sizeof(MachO::x86_thread_state_t));
8678 begin += sizeof(MachO::x86_thread_state_t);
8679 } else {
8680 memset(&ts, '\0', sizeof(MachO::x86_thread_state_t));
8681 memcpy(&ts, begin, left);
8682 begin += left;
8683 }
8684 if (isLittleEndian != sys::IsLittleEndianHost)
8685 swapStruct(ts);
8686 if (ts.tsh.flavor == MachO::x86_THREAD_STATE64) {
8687 outs() << "\t tsh.flavor x86_THREAD_STATE64 ";
8688 if (ts.tsh.count == MachO::x86_THREAD_STATE64_COUNT)
8689 outs() << "tsh.count x86_THREAD_STATE64_COUNT\n";
8690 else
8691 outs() << "tsh.count " << ts.tsh.count
8692 << " (not x86_THREAD_STATE64_COUNT\n";
8693 Print_x86_thread_state64_t(ts.uts.ts64);
8694 } else {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008695 outs() << "\t tsh.flavor " << ts.tsh.flavor << " tsh.count "
8696 << ts.tsh.count << "\n";
Kevin Enderby48ef5342014-12-23 22:56:39 +00008697 }
8698 } else if (flavor == MachO::x86_FLOAT_STATE) {
8699 outs() << " flavor x86_FLOAT_STATE\n";
8700 if (count == MachO::x86_FLOAT_STATE_COUNT)
8701 outs() << " count x86_FLOAT_STATE_COUNT\n";
8702 else
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008703 outs() << " count " << count << " (not x86_FLOAT_STATE_COUNT)\n";
Kevin Enderby48ef5342014-12-23 22:56:39 +00008704 struct MachO::x86_float_state_t fs;
8705 left = end - begin;
8706 if (left >= sizeof(MachO::x86_float_state_t)) {
8707 memcpy(&fs, begin, sizeof(MachO::x86_float_state_t));
8708 begin += sizeof(MachO::x86_float_state_t);
8709 } else {
8710 memset(&fs, '\0', sizeof(MachO::x86_float_state_t));
8711 memcpy(&fs, begin, left);
8712 begin += left;
8713 }
8714 if (isLittleEndian != sys::IsLittleEndianHost)
8715 swapStruct(fs);
8716 if (fs.fsh.flavor == MachO::x86_FLOAT_STATE64) {
8717 outs() << "\t fsh.flavor x86_FLOAT_STATE64 ";
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008718 if (fs.fsh.count == MachO::x86_FLOAT_STATE64_COUNT)
Kevin Enderby48ef5342014-12-23 22:56:39 +00008719 outs() << "fsh.count x86_FLOAT_STATE64_COUNT\n";
8720 else
8721 outs() << "fsh.count " << fs.fsh.count
8722 << " (not x86_FLOAT_STATE64_COUNT\n";
8723 Print_x86_float_state_t(fs.ufs.fs64);
8724 } else {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008725 outs() << "\t fsh.flavor " << fs.fsh.flavor << " fsh.count "
8726 << fs.fsh.count << "\n";
Kevin Enderby48ef5342014-12-23 22:56:39 +00008727 }
8728 } else if (flavor == MachO::x86_EXCEPTION_STATE) {
8729 outs() << " flavor x86_EXCEPTION_STATE\n";
8730 if (count == MachO::x86_EXCEPTION_STATE_COUNT)
8731 outs() << " count x86_EXCEPTION_STATE_COUNT\n";
8732 else
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008733 outs() << " count " << count
Kevin Enderby48ef5342014-12-23 22:56:39 +00008734 << " (not x86_EXCEPTION_STATE_COUNT)\n";
8735 struct MachO::x86_exception_state_t es;
8736 left = end - begin;
8737 if (left >= sizeof(MachO::x86_exception_state_t)) {
8738 memcpy(&es, begin, sizeof(MachO::x86_exception_state_t));
8739 begin += sizeof(MachO::x86_exception_state_t);
8740 } else {
8741 memset(&es, '\0', sizeof(MachO::x86_exception_state_t));
8742 memcpy(&es, begin, left);
8743 begin += left;
8744 }
8745 if (isLittleEndian != sys::IsLittleEndianHost)
8746 swapStruct(es);
8747 if (es.esh.flavor == MachO::x86_EXCEPTION_STATE64) {
8748 outs() << "\t esh.flavor x86_EXCEPTION_STATE64\n";
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008749 if (es.esh.count == MachO::x86_EXCEPTION_STATE64_COUNT)
Kevin Enderby48ef5342014-12-23 22:56:39 +00008750 outs() << "\t esh.count x86_EXCEPTION_STATE64_COUNT\n";
8751 else
8752 outs() << "\t esh.count " << es.esh.count
8753 << " (not x86_EXCEPTION_STATE64_COUNT\n";
8754 Print_x86_exception_state_t(es.ues.es64);
8755 } else {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008756 outs() << "\t esh.flavor " << es.esh.flavor << " esh.count "
8757 << es.esh.count << "\n";
Kevin Enderby48ef5342014-12-23 22:56:39 +00008758 }
8759 } else {
8760 outs() << " flavor " << flavor << " (unknown)\n";
8761 outs() << " count " << count << "\n";
8762 outs() << " state (unknown)\n";
8763 begin += count * sizeof(uint32_t);
8764 }
8765 }
8766 } else {
8767 while (begin < end) {
8768 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
8769 memcpy((char *)&flavor, begin, sizeof(uint32_t));
8770 begin += sizeof(uint32_t);
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008771 } else {
Kevin Enderby48ef5342014-12-23 22:56:39 +00008772 flavor = 0;
8773 begin = end;
8774 }
8775 if (isLittleEndian != sys::IsLittleEndianHost)
8776 sys::swapByteOrder(flavor);
8777 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
8778 memcpy((char *)&count, begin, sizeof(uint32_t));
8779 begin += sizeof(uint32_t);
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008780 } else {
Kevin Enderby48ef5342014-12-23 22:56:39 +00008781 count = 0;
8782 begin = end;
8783 }
8784 if (isLittleEndian != sys::IsLittleEndianHost)
8785 sys::swapByteOrder(count);
8786 outs() << " flavor " << flavor << "\n";
8787 outs() << " count " << count << "\n";
8788 outs() << " state (Unknown cputype/cpusubtype)\n";
8789 begin += count * sizeof(uint32_t);
8790 }
8791 }
8792}
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008793
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008794static void PrintDylibCommand(MachO::dylib_command dl, const char *Ptr) {
8795 if (dl.cmd == MachO::LC_ID_DYLIB)
8796 outs() << " cmd LC_ID_DYLIB\n";
8797 else if (dl.cmd == MachO::LC_LOAD_DYLIB)
8798 outs() << " cmd LC_LOAD_DYLIB\n";
8799 else if (dl.cmd == MachO::LC_LOAD_WEAK_DYLIB)
8800 outs() << " cmd LC_LOAD_WEAK_DYLIB\n";
8801 else if (dl.cmd == MachO::LC_REEXPORT_DYLIB)
8802 outs() << " cmd LC_REEXPORT_DYLIB\n";
8803 else if (dl.cmd == MachO::LC_LAZY_LOAD_DYLIB)
8804 outs() << " cmd LC_LAZY_LOAD_DYLIB\n";
8805 else if (dl.cmd == MachO::LC_LOAD_UPWARD_DYLIB)
8806 outs() << " cmd LC_LOAD_UPWARD_DYLIB\n";
8807 else
8808 outs() << " cmd " << dl.cmd << " (unknown)\n";
8809 outs() << " cmdsize " << dl.cmdsize;
8810 if (dl.cmdsize < sizeof(struct MachO::dylib_command))
8811 outs() << " Incorrect size\n";
8812 else
8813 outs() << "\n";
8814 if (dl.dylib.name < dl.cmdsize) {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00008815 const char *P = (const char *)(Ptr) + dl.dylib.name;
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008816 outs() << " name " << P << " (offset " << dl.dylib.name << ")\n";
8817 } else {
8818 outs() << " name ?(bad offset " << dl.dylib.name << ")\n";
8819 }
8820 outs() << " time stamp " << dl.dylib.timestamp << " ";
8821 time_t t = dl.dylib.timestamp;
8822 outs() << ctime(&t);
8823 outs() << " current version ";
8824 if (dl.dylib.current_version == 0xffffffff)
8825 outs() << "n/a\n";
8826 else
8827 outs() << ((dl.dylib.current_version >> 16) & 0xffff) << "."
8828 << ((dl.dylib.current_version >> 8) & 0xff) << "."
8829 << (dl.dylib.current_version & 0xff) << "\n";
8830 outs() << "compatibility version ";
8831 if (dl.dylib.compatibility_version == 0xffffffff)
8832 outs() << "n/a\n";
8833 else
8834 outs() << ((dl.dylib.compatibility_version >> 16) & 0xffff) << "."
8835 << ((dl.dylib.compatibility_version >> 8) & 0xff) << "."
8836 << (dl.dylib.compatibility_version & 0xff) << "\n";
8837}
8838
8839static void PrintLinkEditDataCommand(MachO::linkedit_data_command ld,
8840 uint32_t object_size) {
8841 if (ld.cmd == MachO::LC_CODE_SIGNATURE)
Kevin Enderby1be37a32016-04-28 21:07:20 +00008842 outs() << " cmd LC_CODE_SIGNATURE\n";
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008843 else if (ld.cmd == MachO::LC_SEGMENT_SPLIT_INFO)
8844 outs() << " cmd LC_SEGMENT_SPLIT_INFO\n";
8845 else if (ld.cmd == MachO::LC_FUNCTION_STARTS)
8846 outs() << " cmd LC_FUNCTION_STARTS\n";
8847 else if (ld.cmd == MachO::LC_DATA_IN_CODE)
8848 outs() << " cmd LC_DATA_IN_CODE\n";
8849 else if (ld.cmd == MachO::LC_DYLIB_CODE_SIGN_DRS)
8850 outs() << " cmd LC_DYLIB_CODE_SIGN_DRS\n";
8851 else if (ld.cmd == MachO::LC_LINKER_OPTIMIZATION_HINT)
8852 outs() << " cmd LC_LINKER_OPTIMIZATION_HINT\n";
8853 else
8854 outs() << " cmd " << ld.cmd << " (?)\n";
8855 outs() << " cmdsize " << ld.cmdsize;
8856 if (ld.cmdsize != sizeof(struct MachO::linkedit_data_command))
8857 outs() << " Incorrect size\n";
8858 else
8859 outs() << "\n";
8860 outs() << " dataoff " << ld.dataoff;
8861 if (ld.dataoff > object_size)
8862 outs() << " (past end of file)\n";
8863 else
8864 outs() << "\n";
8865 outs() << " datasize " << ld.datasize;
8866 uint64_t big_size = ld.dataoff;
8867 big_size += ld.datasize;
8868 if (big_size > object_size)
8869 outs() << " (past end of file)\n";
8870 else
8871 outs() << "\n";
8872}
8873
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00008874static void PrintLoadCommands(const MachOObjectFile *Obj, uint32_t filetype,
8875 uint32_t cputype, bool verbose) {
Kevin Enderby956366c2014-08-29 22:30:52 +00008876 StringRef Buf = Obj->getData();
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00008877 unsigned Index = 0;
8878 for (const auto &Command : Obj->load_commands()) {
8879 outs() << "Load command " << Index++ << "\n";
Kevin Enderby956366c2014-08-29 22:30:52 +00008880 if (Command.C.cmd == MachO::LC_SEGMENT) {
8881 MachO::segment_command SLC = Obj->getSegmentLoadCommand(Command);
8882 const char *sg_segname = SLC.segname;
8883 PrintSegmentCommand(SLC.cmd, SLC.cmdsize, SLC.segname, SLC.vmaddr,
8884 SLC.vmsize, SLC.fileoff, SLC.filesize, SLC.maxprot,
8885 SLC.initprot, SLC.nsects, SLC.flags, Buf.size(),
8886 verbose);
8887 for (unsigned j = 0; j < SLC.nsects; j++) {
Kevin Enderbyc9713382014-12-16 01:14:45 +00008888 MachO::section S = Obj->getSection(Command, j);
Kevin Enderby956366c2014-08-29 22:30:52 +00008889 PrintSection(S.sectname, S.segname, S.addr, S.size, S.offset, S.align,
8890 S.reloff, S.nreloc, S.flags, S.reserved1, S.reserved2,
8891 SLC.cmd, sg_segname, filetype, Buf.size(), verbose);
8892 }
8893 } else if (Command.C.cmd == MachO::LC_SEGMENT_64) {
8894 MachO::segment_command_64 SLC_64 = Obj->getSegment64LoadCommand(Command);
8895 const char *sg_segname = SLC_64.segname;
8896 PrintSegmentCommand(SLC_64.cmd, SLC_64.cmdsize, SLC_64.segname,
8897 SLC_64.vmaddr, SLC_64.vmsize, SLC_64.fileoff,
8898 SLC_64.filesize, SLC_64.maxprot, SLC_64.initprot,
8899 SLC_64.nsects, SLC_64.flags, Buf.size(), verbose);
8900 for (unsigned j = 0; j < SLC_64.nsects; j++) {
8901 MachO::section_64 S_64 = Obj->getSection64(Command, j);
8902 PrintSection(S_64.sectname, S_64.segname, S_64.addr, S_64.size,
8903 S_64.offset, S_64.align, S_64.reloff, S_64.nreloc,
8904 S_64.flags, S_64.reserved1, S_64.reserved2, SLC_64.cmd,
8905 sg_segname, filetype, Buf.size(), verbose);
8906 }
8907 } else if (Command.C.cmd == MachO::LC_SYMTAB) {
8908 MachO::symtab_command Symtab = Obj->getSymtabLoadCommand();
David Majnemer73cc6ff2014-11-13 19:48:56 +00008909 PrintSymtabLoadCommand(Symtab, Obj->is64Bit(), Buf.size());
Kevin Enderby956366c2014-08-29 22:30:52 +00008910 } else if (Command.C.cmd == MachO::LC_DYSYMTAB) {
8911 MachO::dysymtab_command Dysymtab = Obj->getDysymtabLoadCommand();
8912 MachO::symtab_command Symtab = Obj->getSymtabLoadCommand();
David Majnemer73cc6ff2014-11-13 19:48:56 +00008913 PrintDysymtabLoadCommand(Dysymtab, Symtab.nsyms, Buf.size(),
8914 Obj->is64Bit());
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008915 } else if (Command.C.cmd == MachO::LC_DYLD_INFO ||
8916 Command.C.cmd == MachO::LC_DYLD_INFO_ONLY) {
8917 MachO::dyld_info_command DyldInfo = Obj->getDyldInfoLoadCommand(Command);
8918 PrintDyldInfoLoadCommand(DyldInfo, Buf.size());
8919 } else if (Command.C.cmd == MachO::LC_LOAD_DYLINKER ||
8920 Command.C.cmd == MachO::LC_ID_DYLINKER ||
8921 Command.C.cmd == MachO::LC_DYLD_ENVIRONMENT) {
8922 MachO::dylinker_command Dyld = Obj->getDylinkerCommand(Command);
8923 PrintDyldLoadCommand(Dyld, Command.Ptr);
8924 } else if (Command.C.cmd == MachO::LC_UUID) {
8925 MachO::uuid_command Uuid = Obj->getUuidCommand(Command);
8926 PrintUuidLoadCommand(Uuid);
Jean-Daniel Dupas00cc1f52014-12-04 07:37:02 +00008927 } else if (Command.C.cmd == MachO::LC_RPATH) {
8928 MachO::rpath_command Rpath = Obj->getRpathCommand(Command);
8929 PrintRpathLoadCommand(Rpath, Command.Ptr);
Kevin Enderby1ff0ecc2014-12-16 21:48:27 +00008930 } else if (Command.C.cmd == MachO::LC_VERSION_MIN_MACOSX ||
Tim Northoverbfbfb122015-11-02 21:26:58 +00008931 Command.C.cmd == MachO::LC_VERSION_MIN_IPHONEOS ||
8932 Command.C.cmd == MachO::LC_VERSION_MIN_TVOS ||
8933 Command.C.cmd == MachO::LC_VERSION_MIN_WATCHOS) {
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008934 MachO::version_min_command Vd = Obj->getVersionMinLoadCommand(Command);
8935 PrintVersionMinLoadCommand(Vd);
8936 } else if (Command.C.cmd == MachO::LC_SOURCE_VERSION) {
8937 MachO::source_version_command Sd = Obj->getSourceVersionCommand(Command);
8938 PrintSourceVersionCommand(Sd);
8939 } else if (Command.C.cmd == MachO::LC_MAIN) {
8940 MachO::entry_point_command Ep = Obj->getEntryPointCommand(Command);
8941 PrintEntryPointCommand(Ep);
Kevin Enderby0804f4672014-12-16 23:25:52 +00008942 } else if (Command.C.cmd == MachO::LC_ENCRYPTION_INFO) {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008943 MachO::encryption_info_command Ei =
8944 Obj->getEncryptionInfoCommand(Command);
Kevin Enderby0804f4672014-12-16 23:25:52 +00008945 PrintEncryptionInfoCommand(Ei, Buf.size());
Kevin Enderby57538292014-12-17 01:01:30 +00008946 } else if (Command.C.cmd == MachO::LC_ENCRYPTION_INFO_64) {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008947 MachO::encryption_info_command_64 Ei =
8948 Obj->getEncryptionInfoCommand64(Command);
Kevin Enderby57538292014-12-17 01:01:30 +00008949 PrintEncryptionInfoCommand64(Ei, Buf.size());
Kevin Enderbyd0b6b7f2014-12-18 00:53:40 +00008950 } else if (Command.C.cmd == MachO::LC_LINKER_OPTION) {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008951 MachO::linker_option_command Lo =
8952 Obj->getLinkerOptionLoadCommand(Command);
Kevin Enderbyd0b6b7f2014-12-18 00:53:40 +00008953 PrintLinkerOptionCommand(Lo, Command.Ptr);
Kevin Enderbyb4b79312014-12-18 19:24:35 +00008954 } else if (Command.C.cmd == MachO::LC_SUB_FRAMEWORK) {
8955 MachO::sub_framework_command Sf = Obj->getSubFrameworkCommand(Command);
8956 PrintSubFrameworkCommand(Sf, Command.Ptr);
Kevin Enderbya2bd8d92014-12-18 23:13:26 +00008957 } else if (Command.C.cmd == MachO::LC_SUB_UMBRELLA) {
8958 MachO::sub_umbrella_command Sf = Obj->getSubUmbrellaCommand(Command);
8959 PrintSubUmbrellaCommand(Sf, Command.Ptr);
Kevin Enderby36c8d3a2014-12-19 19:48:16 +00008960 } else if (Command.C.cmd == MachO::LC_SUB_LIBRARY) {
8961 MachO::sub_library_command Sl = Obj->getSubLibraryCommand(Command);
8962 PrintSubLibraryCommand(Sl, Command.Ptr);
Kevin Enderby186eac32014-12-19 21:06:24 +00008963 } else if (Command.C.cmd == MachO::LC_SUB_CLIENT) {
8964 MachO::sub_client_command Sc = Obj->getSubClientCommand(Command);
8965 PrintSubClientCommand(Sc, Command.Ptr);
Kevin Enderby52e4ce42014-12-19 22:25:22 +00008966 } else if (Command.C.cmd == MachO::LC_ROUTINES) {
8967 MachO::routines_command Rc = Obj->getRoutinesCommand(Command);
8968 PrintRoutinesCommand(Rc);
8969 } else if (Command.C.cmd == MachO::LC_ROUTINES_64) {
8970 MachO::routines_command_64 Rc = Obj->getRoutinesCommand64(Command);
8971 PrintRoutinesCommand64(Rc);
Kevin Enderby48ef5342014-12-23 22:56:39 +00008972 } else if (Command.C.cmd == MachO::LC_THREAD ||
8973 Command.C.cmd == MachO::LC_UNIXTHREAD) {
8974 MachO::thread_command Tc = Obj->getThreadCommand(Command);
8975 PrintThreadCommand(Tc, Command.Ptr, Obj->isLittleEndian(), cputype);
Nick Kledzik15558912014-10-16 18:58:20 +00008976 } else if (Command.C.cmd == MachO::LC_LOAD_DYLIB ||
8977 Command.C.cmd == MachO::LC_ID_DYLIB ||
8978 Command.C.cmd == MachO::LC_LOAD_WEAK_DYLIB ||
8979 Command.C.cmd == MachO::LC_REEXPORT_DYLIB ||
8980 Command.C.cmd == MachO::LC_LAZY_LOAD_DYLIB ||
8981 Command.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB) {
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008982 MachO::dylib_command Dl = Obj->getDylibIDLoadCommand(Command);
8983 PrintDylibCommand(Dl, Command.Ptr);
8984 } else if (Command.C.cmd == MachO::LC_CODE_SIGNATURE ||
8985 Command.C.cmd == MachO::LC_SEGMENT_SPLIT_INFO ||
8986 Command.C.cmd == MachO::LC_FUNCTION_STARTS ||
8987 Command.C.cmd == MachO::LC_DATA_IN_CODE ||
8988 Command.C.cmd == MachO::LC_DYLIB_CODE_SIGN_DRS ||
8989 Command.C.cmd == MachO::LC_LINKER_OPTIMIZATION_HINT) {
8990 MachO::linkedit_data_command Ld =
8991 Obj->getLinkeditDataLoadCommand(Command);
8992 PrintLinkEditDataCommand(Ld, Buf.size());
Kevin Enderby956366c2014-08-29 22:30:52 +00008993 } else {
8994 outs() << " cmd ?(" << format("0x%08" PRIx32, Command.C.cmd)
8995 << ")\n";
8996 outs() << " cmdsize " << Command.C.cmdsize << "\n";
8997 // TODO: get and print the raw bytes of the load command.
8998 }
8999 // TODO: print all the other kinds of load commands.
Kevin Enderby956366c2014-08-29 22:30:52 +00009000 }
9001}
9002
Kevin Enderby0ae163f2016-01-13 00:25:36 +00009003static void PrintMachHeader(const MachOObjectFile *Obj, bool verbose) {
Kevin Enderbyb76d3862014-08-22 20:35:18 +00009004 if (Obj->is64Bit()) {
9005 MachO::mach_header_64 H_64;
9006 H_64 = Obj->getHeader64();
9007 PrintMachHeader(H_64.magic, H_64.cputype, H_64.cpusubtype, H_64.filetype,
9008 H_64.ncmds, H_64.sizeofcmds, H_64.flags, verbose);
9009 } else {
9010 MachO::mach_header H;
9011 H = Obj->getHeader();
9012 PrintMachHeader(H.magic, H.cputype, H.cpusubtype, H.filetype, H.ncmds,
9013 H.sizeofcmds, H.flags, verbose);
9014 }
9015}
9016
9017void llvm::printMachOFileHeader(const object::ObjectFile *Obj) {
9018 const MachOObjectFile *file = dyn_cast<const MachOObjectFile>(Obj);
Kevin Enderby0ae163f2016-01-13 00:25:36 +00009019 PrintMachHeader(file, !NonVerbose);
9020}
9021
9022void llvm::printMachOLoadCommands(const object::ObjectFile *Obj) {
9023 const MachOObjectFile *file = dyn_cast<const MachOObjectFile>(Obj);
Kevin Enderby956366c2014-08-29 22:30:52 +00009024 uint32_t filetype = 0;
9025 uint32_t cputype = 0;
Kevin Enderby0ae163f2016-01-13 00:25:36 +00009026 if (file->is64Bit()) {
9027 MachO::mach_header_64 H_64;
9028 H_64 = file->getHeader64();
9029 filetype = H_64.filetype;
9030 cputype = H_64.cputype;
9031 } else {
9032 MachO::mach_header H;
9033 H = file->getHeader();
9034 filetype = H.filetype;
9035 cputype = H.cputype;
9036 }
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00009037 PrintLoadCommands(file, filetype, cputype, !NonVerbose);
Kevin Enderbyb76d3862014-08-22 20:35:18 +00009038}
Nick Kledzikd04bc352014-08-30 00:20:14 +00009039
9040//===----------------------------------------------------------------------===//
9041// export trie dumping
9042//===----------------------------------------------------------------------===//
9043
9044void llvm::printMachOExportsTrie(const object::MachOObjectFile *Obj) {
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00009045 for (const llvm::object::ExportEntry &Entry : Obj->exports()) {
9046 uint64_t Flags = Entry.flags();
Nick Kledzikd04bc352014-08-30 00:20:14 +00009047 bool ReExport = (Flags & MachO::EXPORT_SYMBOL_FLAGS_REEXPORT);
9048 bool WeakDef = (Flags & MachO::EXPORT_SYMBOL_FLAGS_WEAK_DEFINITION);
9049 bool ThreadLocal = ((Flags & MachO::EXPORT_SYMBOL_FLAGS_KIND_MASK) ==
9050 MachO::EXPORT_SYMBOL_FLAGS_KIND_THREAD_LOCAL);
9051 bool Abs = ((Flags & MachO::EXPORT_SYMBOL_FLAGS_KIND_MASK) ==
9052 MachO::EXPORT_SYMBOL_FLAGS_KIND_ABSOLUTE);
9053 bool Resolver = (Flags & MachO::EXPORT_SYMBOL_FLAGS_STUB_AND_RESOLVER);
9054 if (ReExport)
9055 outs() << "[re-export] ";
9056 else
Kevin Enderbyb28ed012014-10-29 21:28:24 +00009057 outs() << format("0x%08llX ",
9058 Entry.address()); // FIXME:add in base address
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00009059 outs() << Entry.name();
Nick Kledzikd04bc352014-08-30 00:20:14 +00009060 if (WeakDef || ThreadLocal || Resolver || Abs) {
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00009061 bool NeedsComma = false;
Nick Kledzik1d1ac4b2014-09-03 01:12:52 +00009062 outs() << " [";
Nick Kledzikd04bc352014-08-30 00:20:14 +00009063 if (WeakDef) {
9064 outs() << "weak_def";
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00009065 NeedsComma = true;
Nick Kledzikd04bc352014-08-30 00:20:14 +00009066 }
9067 if (ThreadLocal) {
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00009068 if (NeedsComma)
Nick Kledzikd04bc352014-08-30 00:20:14 +00009069 outs() << ", ";
9070 outs() << "per-thread";
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00009071 NeedsComma = true;
Nick Kledzikd04bc352014-08-30 00:20:14 +00009072 }
9073 if (Abs) {
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00009074 if (NeedsComma)
Nick Kledzikd04bc352014-08-30 00:20:14 +00009075 outs() << ", ";
9076 outs() << "absolute";
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00009077 NeedsComma = true;
Nick Kledzikd04bc352014-08-30 00:20:14 +00009078 }
9079 if (Resolver) {
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00009080 if (NeedsComma)
Nick Kledzikd04bc352014-08-30 00:20:14 +00009081 outs() << ", ";
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00009082 outs() << format("resolver=0x%08llX", Entry.other());
9083 NeedsComma = true;
Nick Kledzikd04bc352014-08-30 00:20:14 +00009084 }
9085 outs() << "]";
9086 }
9087 if (ReExport) {
9088 StringRef DylibName = "unknown";
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00009089 int Ordinal = Entry.other() - 1;
9090 Obj->getLibraryShortNameByIndex(Ordinal, DylibName);
9091 if (Entry.otherName().empty())
Nick Kledzikd04bc352014-08-30 00:20:14 +00009092 outs() << " (from " << DylibName << ")";
9093 else
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00009094 outs() << " (" << Entry.otherName() << " from " << DylibName << ")";
Nick Kledzikd04bc352014-08-30 00:20:14 +00009095 }
9096 outs() << "\n";
9097 }
9098}
Nick Kledzikac431442014-09-12 21:34:15 +00009099
Nick Kledzikac431442014-09-12 21:34:15 +00009100//===----------------------------------------------------------------------===//
9101// rebase table dumping
9102//===----------------------------------------------------------------------===//
9103
9104namespace {
9105class SegInfo {
9106public:
9107 SegInfo(const object::MachOObjectFile *Obj);
9108
9109 StringRef segmentName(uint32_t SegIndex);
9110 StringRef sectionName(uint32_t SegIndex, uint64_t SegOffset);
9111 uint64_t address(uint32_t SegIndex, uint64_t SegOffset);
Kevin Enderbyaf7c9d02015-10-09 16:48:44 +00009112 bool isValidSegIndexAndOffset(uint32_t SegIndex, uint64_t SegOffset);
Nick Kledzikac431442014-09-12 21:34:15 +00009113
9114private:
9115 struct SectionInfo {
9116 uint64_t Address;
9117 uint64_t Size;
9118 StringRef SectionName;
9119 StringRef SegmentName;
9120 uint64_t OffsetInSegment;
9121 uint64_t SegmentStartAddress;
9122 uint32_t SegmentIndex;
9123 };
9124 const SectionInfo &findSection(uint32_t SegIndex, uint64_t SegOffset);
9125 SmallVector<SectionInfo, 32> Sections;
9126};
9127}
9128
9129SegInfo::SegInfo(const object::MachOObjectFile *Obj) {
9130 // Build table of sections so segIndex/offset pairs can be translated.
Nick Kledzik56ebef42014-09-16 01:41:51 +00009131 uint32_t CurSegIndex = Obj->hasPageZeroSegment() ? 1 : 0;
Nick Kledzikac431442014-09-12 21:34:15 +00009132 StringRef CurSegName;
9133 uint64_t CurSegAddress;
9134 for (const SectionRef &Section : Obj->sections()) {
9135 SectionInfo Info;
Davide Italianoccd53fe2015-08-05 07:18:31 +00009136 error(Section.getName(Info.SectionName));
Rafael Espindola80291272014-10-08 15:28:58 +00009137 Info.Address = Section.getAddress();
9138 Info.Size = Section.getSize();
Nick Kledzikac431442014-09-12 21:34:15 +00009139 Info.SegmentName =
9140 Obj->getSectionFinalSegmentName(Section.getRawDataRefImpl());
9141 if (!Info.SegmentName.equals(CurSegName)) {
9142 ++CurSegIndex;
9143 CurSegName = Info.SegmentName;
9144 CurSegAddress = Info.Address;
9145 }
9146 Info.SegmentIndex = CurSegIndex - 1;
9147 Info.OffsetInSegment = Info.Address - CurSegAddress;
9148 Info.SegmentStartAddress = CurSegAddress;
9149 Sections.push_back(Info);
9150 }
9151}
9152
9153StringRef SegInfo::segmentName(uint32_t SegIndex) {
9154 for (const SectionInfo &SI : Sections) {
9155 if (SI.SegmentIndex == SegIndex)
9156 return SI.SegmentName;
9157 }
9158 llvm_unreachable("invalid segIndex");
9159}
9160
Kevin Enderbyaf7c9d02015-10-09 16:48:44 +00009161bool SegInfo::isValidSegIndexAndOffset(uint32_t SegIndex,
9162 uint64_t OffsetInSeg) {
9163 for (const SectionInfo &SI : Sections) {
9164 if (SI.SegmentIndex != SegIndex)
9165 continue;
9166 if (SI.OffsetInSegment > OffsetInSeg)
9167 continue;
9168 if (OffsetInSeg >= (SI.OffsetInSegment + SI.Size))
9169 continue;
9170 return true;
9171 }
9172 return false;
9173}
9174
Nick Kledzikac431442014-09-12 21:34:15 +00009175const SegInfo::SectionInfo &SegInfo::findSection(uint32_t SegIndex,
9176 uint64_t OffsetInSeg) {
9177 for (const SectionInfo &SI : Sections) {
9178 if (SI.SegmentIndex != SegIndex)
9179 continue;
9180 if (SI.OffsetInSegment > OffsetInSeg)
9181 continue;
9182 if (OffsetInSeg >= (SI.OffsetInSegment + SI.Size))
9183 continue;
9184 return SI;
9185 }
9186 llvm_unreachable("segIndex and offset not in any section");
9187}
9188
9189StringRef SegInfo::sectionName(uint32_t SegIndex, uint64_t OffsetInSeg) {
9190 return findSection(SegIndex, OffsetInSeg).SectionName;
9191}
9192
9193uint64_t SegInfo::address(uint32_t SegIndex, uint64_t OffsetInSeg) {
9194 const SectionInfo &SI = findSection(SegIndex, OffsetInSeg);
9195 return SI.SegmentStartAddress + OffsetInSeg;
9196}
9197
9198void llvm::printMachORebaseTable(const object::MachOObjectFile *Obj) {
9199 // Build table of sections so names can used in final output.
9200 SegInfo sectionTable(Obj);
9201
9202 outs() << "segment section address type\n";
9203 for (const llvm::object::MachORebaseEntry &Entry : Obj->rebaseTable()) {
9204 uint32_t SegIndex = Entry.segmentIndex();
9205 uint64_t OffsetInSeg = Entry.segmentOffset();
9206 StringRef SegmentName = sectionTable.segmentName(SegIndex);
9207 StringRef SectionName = sectionTable.sectionName(SegIndex, OffsetInSeg);
9208 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
9209
9210 // Table lines look like: __DATA __nl_symbol_ptr 0x0000F00C pointer
Kevin Enderbyb28ed012014-10-29 21:28:24 +00009211 outs() << format("%-8s %-18s 0x%08" PRIX64 " %s\n",
9212 SegmentName.str().c_str(), SectionName.str().c_str(),
9213 Address, Entry.typeName().str().c_str());
Nick Kledzikac431442014-09-12 21:34:15 +00009214 }
9215}
Nick Kledzik56ebef42014-09-16 01:41:51 +00009216
9217static StringRef ordinalName(const object::MachOObjectFile *Obj, int Ordinal) {
9218 StringRef DylibName;
9219 switch (Ordinal) {
9220 case MachO::BIND_SPECIAL_DYLIB_SELF:
9221 return "this-image";
9222 case MachO::BIND_SPECIAL_DYLIB_MAIN_EXECUTABLE:
9223 return "main-executable";
9224 case MachO::BIND_SPECIAL_DYLIB_FLAT_LOOKUP:
9225 return "flat-namespace";
9226 default:
Nick Kledzikabd29872014-09-16 22:03:13 +00009227 if (Ordinal > 0) {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00009228 std::error_code EC =
9229 Obj->getLibraryShortNameByIndex(Ordinal - 1, DylibName);
Nick Kledzikabd29872014-09-16 22:03:13 +00009230 if (EC)
Nick Kledzik51d2c2b2014-10-14 23:29:38 +00009231 return "<<bad library ordinal>>";
Nick Kledzikabd29872014-09-16 22:03:13 +00009232 return DylibName;
9233 }
Nick Kledzik56ebef42014-09-16 01:41:51 +00009234 }
Nick Kledzikabd29872014-09-16 22:03:13 +00009235 return "<<unknown special ordinal>>";
Nick Kledzik56ebef42014-09-16 01:41:51 +00009236}
9237
9238//===----------------------------------------------------------------------===//
9239// bind table dumping
9240//===----------------------------------------------------------------------===//
9241
9242void llvm::printMachOBindTable(const object::MachOObjectFile *Obj) {
9243 // Build table of sections so names can used in final output.
9244 SegInfo sectionTable(Obj);
9245
Nick Kledzik5ffacc12014-09-30 00:19:58 +00009246 outs() << "segment section address type "
9247 "addend dylib symbol\n";
Nick Kledzik56ebef42014-09-16 01:41:51 +00009248 for (const llvm::object::MachOBindEntry &Entry : Obj->bindTable()) {
9249 uint32_t SegIndex = Entry.segmentIndex();
9250 uint64_t OffsetInSeg = Entry.segmentOffset();
9251 StringRef SegmentName = sectionTable.segmentName(SegIndex);
9252 StringRef SectionName = sectionTable.sectionName(SegIndex, OffsetInSeg);
9253 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
9254
9255 // Table lines look like:
9256 // __DATA __got 0x00012010 pointer 0 libSystem ___stack_chk_guard
Nick Kledzik5ffacc12014-09-30 00:19:58 +00009257 StringRef Attr;
Nick Kledzik56ebef42014-09-16 01:41:51 +00009258 if (Entry.flags() & MachO::BIND_SYMBOL_FLAGS_WEAK_IMPORT)
Nick Kledzik5ffacc12014-09-30 00:19:58 +00009259 Attr = " (weak_import)";
Kevin Enderbyb28ed012014-10-29 21:28:24 +00009260 outs() << left_justify(SegmentName, 8) << " "
Nick Kledzik5ffacc12014-09-30 00:19:58 +00009261 << left_justify(SectionName, 18) << " "
9262 << format_hex(Address, 10, true) << " "
9263 << left_justify(Entry.typeName(), 8) << " "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00009264 << format_decimal(Entry.addend(), 8) << " "
Nick Kledzik5ffacc12014-09-30 00:19:58 +00009265 << left_justify(ordinalName(Obj, Entry.ordinal()), 16) << " "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00009266 << Entry.symbolName() << Attr << "\n";
Nick Kledzik56ebef42014-09-16 01:41:51 +00009267 }
9268}
9269
9270//===----------------------------------------------------------------------===//
9271// lazy bind table dumping
9272//===----------------------------------------------------------------------===//
9273
9274void llvm::printMachOLazyBindTable(const object::MachOObjectFile *Obj) {
9275 // Build table of sections so names can used in final output.
9276 SegInfo sectionTable(Obj);
9277
Nick Kledzik5ffacc12014-09-30 00:19:58 +00009278 outs() << "segment section address "
9279 "dylib symbol\n";
Nick Kledzik56ebef42014-09-16 01:41:51 +00009280 for (const llvm::object::MachOBindEntry &Entry : Obj->lazyBindTable()) {
9281 uint32_t SegIndex = Entry.segmentIndex();
9282 uint64_t OffsetInSeg = Entry.segmentOffset();
9283 StringRef SegmentName = sectionTable.segmentName(SegIndex);
9284 StringRef SectionName = sectionTable.sectionName(SegIndex, OffsetInSeg);
9285 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
9286
9287 // Table lines look like:
9288 // __DATA __got 0x00012010 libSystem ___stack_chk_guard
Kevin Enderbyb28ed012014-10-29 21:28:24 +00009289 outs() << left_justify(SegmentName, 8) << " "
Nick Kledzik5ffacc12014-09-30 00:19:58 +00009290 << left_justify(SectionName, 18) << " "
9291 << format_hex(Address, 10, true) << " "
9292 << left_justify(ordinalName(Obj, Entry.ordinal()), 16) << " "
Nick Kledzik56ebef42014-09-16 01:41:51 +00009293 << Entry.symbolName() << "\n";
9294 }
9295}
9296
Nick Kledzik56ebef42014-09-16 01:41:51 +00009297//===----------------------------------------------------------------------===//
9298// weak bind table dumping
9299//===----------------------------------------------------------------------===//
9300
9301void llvm::printMachOWeakBindTable(const object::MachOObjectFile *Obj) {
9302 // Build table of sections so names can used in final output.
9303 SegInfo sectionTable(Obj);
9304
Nick Kledzik5ffacc12014-09-30 00:19:58 +00009305 outs() << "segment section address "
9306 "type addend symbol\n";
Nick Kledzik56ebef42014-09-16 01:41:51 +00009307 for (const llvm::object::MachOBindEntry &Entry : Obj->weakBindTable()) {
9308 // Strong symbols don't have a location to update.
9309 if (Entry.flags() & MachO::BIND_SYMBOL_FLAGS_NON_WEAK_DEFINITION) {
Nick Kledzik5ffacc12014-09-30 00:19:58 +00009310 outs() << " strong "
Nick Kledzik56ebef42014-09-16 01:41:51 +00009311 << Entry.symbolName() << "\n";
9312 continue;
9313 }
9314 uint32_t SegIndex = Entry.segmentIndex();
9315 uint64_t OffsetInSeg = Entry.segmentOffset();
9316 StringRef SegmentName = sectionTable.segmentName(SegIndex);
9317 StringRef SectionName = sectionTable.sectionName(SegIndex, OffsetInSeg);
9318 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
9319
9320 // Table lines look like:
9321 // __DATA __data 0x00001000 pointer 0 _foo
Kevin Enderbyb28ed012014-10-29 21:28:24 +00009322 outs() << left_justify(SegmentName, 8) << " "
Nick Kledzik5ffacc12014-09-30 00:19:58 +00009323 << left_justify(SectionName, 18) << " "
9324 << format_hex(Address, 10, true) << " "
9325 << left_justify(Entry.typeName(), 8) << " "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00009326 << format_decimal(Entry.addend(), 8) << " " << Entry.symbolName()
9327 << "\n";
Nick Kledzik56ebef42014-09-16 01:41:51 +00009328 }
9329}
9330
Kevin Enderby6f326ce2014-10-23 19:37:31 +00009331// get_dyld_bind_info_symbolname() is used for disassembly and passed an
9332// address, ReferenceValue, in the Mach-O file and looks in the dyld bind
9333// information for that address. If the address is found its binding symbol
9334// name is returned. If not nullptr is returned.
9335static const char *get_dyld_bind_info_symbolname(uint64_t ReferenceValue,
9336 struct DisassembleInfo *info) {
Kevin Enderby078be602014-10-23 19:53:12 +00009337 if (info->bindtable == nullptr) {
9338 info->bindtable = new (BindTable);
Kevin Enderby6f326ce2014-10-23 19:37:31 +00009339 SegInfo sectionTable(info->O);
9340 for (const llvm::object::MachOBindEntry &Entry : info->O->bindTable()) {
9341 uint32_t SegIndex = Entry.segmentIndex();
9342 uint64_t OffsetInSeg = Entry.segmentOffset();
Kevin Enderbyaf7c9d02015-10-09 16:48:44 +00009343 if (!sectionTable.isValidSegIndexAndOffset(SegIndex, OffsetInSeg))
9344 continue;
Kevin Enderby6f326ce2014-10-23 19:37:31 +00009345 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
9346 const char *SymbolName = nullptr;
9347 StringRef name = Entry.symbolName();
9348 if (!name.empty())
9349 SymbolName = name.data();
Kevin Enderby078be602014-10-23 19:53:12 +00009350 info->bindtable->push_back(std::make_pair(Address, SymbolName));
Kevin Enderby6f326ce2014-10-23 19:37:31 +00009351 }
9352 }
Kevin Enderby078be602014-10-23 19:53:12 +00009353 for (bind_table_iterator BI = info->bindtable->begin(),
9354 BE = info->bindtable->end();
Kevin Enderby6f326ce2014-10-23 19:37:31 +00009355 BI != BE; ++BI) {
9356 uint64_t Address = BI->first;
9357 if (ReferenceValue == Address) {
9358 const char *SymbolName = BI->second;
9359 return SymbolName;
9360 }
9361 }
9362 return nullptr;
9363}