blob: 8d924e568b7381ee437964807ac0e32464e4aabb [file] [log] [blame]
Benjamin Kramer43a772e2011-09-19 17:56:04 +00001//===-- MachODump.cpp - Object file dumping utility for llvm --------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the MachO-specific dumper for llvm-objdump.
11//
12//===----------------------------------------------------------------------===//
13
Mehdi Aminib550cb12016-04-18 09:17:29 +000014#include "llvm/Object/MachO.h"
Benjamin Kramer43a772e2011-09-19 17:56:04 +000015#include "llvm-objdump.h"
Kevin Enderby98c9acc2014-09-16 18:00:57 +000016#include "llvm-c/Disassembler.h"
Benjamin Kramer43a772e2011-09-19 17:56:04 +000017#include "llvm/ADT/STLExtras.h"
Ahmed Bougachaaa790682013-05-24 01:07:04 +000018#include "llvm/ADT/StringExtras.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000019#include "llvm/ADT/Triple.h"
Kevin Enderby04bf6932014-10-28 23:39:46 +000020#include "llvm/Config/config.h"
Zachary Turner6489d7b2015-04-23 17:37:47 +000021#include "llvm/DebugInfo/DIContext.h"
22#include "llvm/DebugInfo/DWARF/DWARFContext.h"
Benjamin Kramer43a772e2011-09-19 17:56:04 +000023#include "llvm/MC/MCAsmInfo.h"
Lang Hamesa1bc0f52014-04-15 04:40:56 +000024#include "llvm/MC/MCContext.h"
Benjamin Kramerf57c1972016-01-26 16:44:37 +000025#include "llvm/MC/MCDisassembler/MCDisassembler.h"
Benjamin Kramer43a772e2011-09-19 17:56:04 +000026#include "llvm/MC/MCInst.h"
27#include "llvm/MC/MCInstPrinter.h"
Benjamin Kramer43a772e2011-09-19 17:56:04 +000028#include "llvm/MC/MCInstrDesc.h"
29#include "llvm/MC/MCInstrInfo.h"
Jim Grosbachfd93a592012-03-05 19:33:20 +000030#include "llvm/MC/MCRegisterInfo.h"
Benjamin Kramer43a772e2011-09-19 17:56:04 +000031#include "llvm/MC/MCSubtargetInfo.h"
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +000032#include "llvm/Object/MachOUniversal.h"
Rafael Espindola9b709252013-04-13 01:45:40 +000033#include "llvm/Support/Casting.h"
Benjamin Kramer43a772e2011-09-19 17:56:04 +000034#include "llvm/Support/CommandLine.h"
35#include "llvm/Support/Debug.h"
Tim Northover4bd286a2014-08-01 13:07:19 +000036#include "llvm/Support/Endian.h"
Benjamin Kramer43a772e2011-09-19 17:56:04 +000037#include "llvm/Support/Format.h"
Chandler Carruthd9903882015-01-14 11:23:27 +000038#include "llvm/Support/FormattedStream.h"
Benjamin Kramer43a772e2011-09-19 17:56:04 +000039#include "llvm/Support/GraphWriter.h"
Kevin Enderby9a509442015-01-27 21:28:24 +000040#include "llvm/Support/LEB128.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000041#include "llvm/Support/MachO.h"
Benjamin Kramer43a772e2011-09-19 17:56:04 +000042#include "llvm/Support/MemoryBuffer.h"
43#include "llvm/Support/TargetRegistry.h"
44#include "llvm/Support/TargetSelect.h"
Kevin Enderby9873e2c2016-05-23 21:34:12 +000045#include "llvm/Support/ToolOutputFile.h"
Benjamin Kramer43a772e2011-09-19 17:56:04 +000046#include "llvm/Support/raw_ostream.h"
Benjamin Kramer43a772e2011-09-19 17:56:04 +000047#include <algorithm>
48#include <cstring>
Rafael Espindolaa6e9c3e2014-06-12 17:38:55 +000049#include <system_error>
Kevin Enderby04bf6932014-10-28 23:39:46 +000050
51#if HAVE_CXXABI_H
52#include <cxxabi.h>
53#endif
54
Kevin Enderby9873e2c2016-05-23 21:34:12 +000055#ifdef HAVE_LIBXAR
56extern "C" {
57#include <xar/xar.h>
58}
59#endif
60
Benjamin Kramer43a772e2011-09-19 17:56:04 +000061using namespace llvm;
62using namespace object;
63
64static cl::opt<bool>
Kevin Enderbyb28ed012014-10-29 21:28:24 +000065 UseDbg("g",
66 cl::desc("Print line information from debug info if available"));
Benjamin Kramer699128e2011-09-21 01:13:19 +000067
Kevin Enderbyb28ed012014-10-29 21:28:24 +000068static cl::opt<std::string> DSYMFile("dsym",
69 cl::desc("Use .dSYM file for debug info"));
Benjamin Kramer699128e2011-09-21 01:13:19 +000070
Kevin Enderbyb28ed012014-10-29 21:28:24 +000071static cl::opt<bool> FullLeadingAddr("full-leading-addr",
72 cl::desc("Print full leading address"));
Kevin Enderbybf246f52014-09-24 23:08:22 +000073
Kevin Enderbyab5e6c92015-03-17 21:07:39 +000074static cl::opt<bool> NoLeadingAddr("no-leading-addr",
75 cl::desc("Print no leading address"));
76
Kevin Enderby13023a12015-01-15 23:19:11 +000077cl::opt<bool> llvm::UniversalHeaders("universal-headers",
78 cl::desc("Print Mach-O universal headers "
79 "(requires -macho)"));
80
Kevin Enderby131d1772015-01-09 19:22:37 +000081cl::opt<bool>
Kevin Enderby13023a12015-01-15 23:19:11 +000082 llvm::ArchiveHeaders("archive-headers",
83 cl::desc("Print archive headers for Mach-O archives "
84 "(requires -macho)"));
Kevin Enderby131d1772015-01-09 19:22:37 +000085
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +000086cl::opt<bool>
Kevin Enderby8972e482015-04-30 20:30:42 +000087 ArchiveMemberOffsets("archive-member-offsets",
88 cl::desc("Print the offset to each archive member for "
89 "Mach-O archives (requires -macho and "
90 "-archive-headers)"));
91
92cl::opt<bool>
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +000093 llvm::IndirectSymbols("indirect-symbols",
94 cl::desc("Print indirect symbol table for Mach-O "
95 "objects (requires -macho)"));
96
Kevin Enderby69fe98d2015-01-23 18:52:17 +000097cl::opt<bool>
98 llvm::DataInCode("data-in-code",
99 cl::desc("Print the data in code table for Mach-O objects "
100 "(requires -macho)"));
101
Kevin Enderby9a509442015-01-27 21:28:24 +0000102cl::opt<bool>
103 llvm::LinkOptHints("link-opt-hints",
104 cl::desc("Print the linker optimization hints for "
105 "Mach-O objects (requires -macho)"));
106
Kevin Enderbycd66be52015-03-11 22:06:32 +0000107cl::opt<bool>
108 llvm::InfoPlist("info-plist",
109 cl::desc("Print the info plist section as strings for "
110 "Mach-O objects (requires -macho)"));
111
Kevin Enderbyf0640752015-03-13 17:56:32 +0000112cl::opt<bool>
Kevin Enderbybc847fa2015-03-16 20:08:09 +0000113 llvm::DylibsUsed("dylibs-used",
114 cl::desc("Print the shared libraries used for linked "
115 "Mach-O files (requires -macho)"));
116
117cl::opt<bool>
118 llvm::DylibId("dylib-id",
119 cl::desc("Print the shared library's id for the dylib Mach-O "
120 "file (requires -macho)"));
121
122cl::opt<bool>
Kevin Enderbyf0640752015-03-13 17:56:32 +0000123 llvm::NonVerbose("non-verbose",
124 cl::desc("Print the info for Mach-O objects in "
125 "non-verbose or numeric form (requires -macho)"));
126
Kevin Enderby0fc11822015-04-01 20:57:01 +0000127cl::opt<bool>
128 llvm::ObjcMetaData("objc-meta-data",
129 cl::desc("Print the Objective-C runtime meta data for "
130 "Mach-O files (requires -macho)"));
131
Kevin Enderby6a221752015-03-17 17:10:57 +0000132cl::opt<std::string> llvm::DisSymName(
133 "dis-symname",
134 cl::desc("disassemble just this symbol's instructions (requires -macho"));
135
Kevin Enderby8e29ec92015-03-17 22:26:11 +0000136static cl::opt<bool> NoSymbolicOperands(
137 "no-symbolic-operands",
138 cl::desc("do not symbolic operands when disassembling (requires -macho)"));
139
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +0000140static cl::list<std::string>
141 ArchFlags("arch", cl::desc("architecture(s) from a Mach-O file to dump"),
142 cl::ZeroOrMore);
Hans Wennborgcc9deb42015-09-29 18:02:48 +0000143
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +0000144bool ArchAll = false;
145
Kevin Enderbyec5ca032014-08-18 20:21:02 +0000146static std::string ThumbTripleName;
147
148static const Target *GetTarget(const MachOObjectFile *MachOObj,
149 const char **McpuDefault,
150 const Target **ThumbTarget) {
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000151 // Figure out the target triple.
Tim Northover9e8eb412016-04-22 23:21:13 +0000152 llvm::Triple TT(TripleName);
Cameron Zwarich88cc16a2012-02-03 06:35:22 +0000153 if (TripleName.empty()) {
Tim Northover9e8eb412016-04-22 23:21:13 +0000154 TT = MachOObj->getArchTriple(McpuDefault);
Cameron Zwarich88cc16a2012-02-03 06:35:22 +0000155 TripleName = TT.str();
Tim Northover9e8eb412016-04-22 23:21:13 +0000156 }
157
158 if (TT.getArch() == Triple::arm) {
159 // We've inferred a 32-bit ARM target from the object file. All MachO CPUs
160 // that support ARM are also capable of Thumb mode.
161 llvm::Triple ThumbTriple = TT;
162 std::string ThumbName = (Twine("thumb") + TT.getArchName().substr(3)).str();
163 ThumbTriple.setArchName(ThumbName);
Kevin Enderbyec5ca032014-08-18 20:21:02 +0000164 ThumbTripleName = ThumbTriple.str();
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000165 }
166
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000167 // Get the target specific parser.
168 std::string Error;
169 const Target *TheTarget = TargetRegistry::lookupTarget(TripleName, Error);
Kevin Enderbyec5ca032014-08-18 20:21:02 +0000170 if (TheTarget && ThumbTripleName.empty())
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000171 return TheTarget;
172
Kevin Enderbyec5ca032014-08-18 20:21:02 +0000173 *ThumbTarget = TargetRegistry::lookupTarget(ThumbTripleName, Error);
174 if (*ThumbTarget)
175 return TheTarget;
176
177 errs() << "llvm-objdump: error: unable to get target for '";
178 if (!TheTarget)
179 errs() << TripleName;
180 else
181 errs() << ThumbTripleName;
182 errs() << "', see --version and --triple.\n";
Craig Toppere6cb63e2014-04-25 04:24:47 +0000183 return nullptr;
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000184}
185
Owen Andersond9243c42011-10-17 21:37:35 +0000186struct SymbolSorter {
187 bool operator()(const SymbolRef &A, const SymbolRef &B) {
Kevin Enderby7bd8d992016-05-02 20:28:12 +0000188 Expected<SymbolRef::Type> ATypeOrErr = A.getType();
189 if (!ATypeOrErr) {
190 std::string Buf;
191 raw_string_ostream OS(Buf);
192 logAllUnhandledErrors(ATypeOrErr.takeError(), OS, "");
193 OS.flush();
194 report_fatal_error(Buf);
195 }
Kevin Enderby5afbc1c2016-03-23 20:27:00 +0000196 SymbolRef::Type AType = *ATypeOrErr;
Kevin Enderby7bd8d992016-05-02 20:28:12 +0000197 Expected<SymbolRef::Type> BTypeOrErr = B.getType();
198 if (!BTypeOrErr) {
199 std::string Buf;
200 raw_string_ostream OS(Buf);
201 logAllUnhandledErrors(BTypeOrErr.takeError(), OS, "");
202 OS.flush();
203 report_fatal_error(Buf);
204 }
Kevin Enderby74f58d42016-03-23 21:45:21 +0000205 SymbolRef::Type BType = *BTypeOrErr;
Kevin Enderby5afbc1c2016-03-23 20:27:00 +0000206 uint64_t AAddr = (AType != SymbolRef::ST_Function) ? 0 : A.getValue();
207 uint64_t BAddr = (BType != SymbolRef::ST_Function) ? 0 : B.getValue();
Owen Andersond9243c42011-10-17 21:37:35 +0000208 return AAddr < BAddr;
209 }
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000210};
211
Kevin Enderby273ae012013-06-06 17:20:50 +0000212// Types for the storted data in code table that is built before disassembly
213// and the predicate function to sort them.
214typedef std::pair<uint64_t, DiceRef> DiceTableEntry;
215typedef std::vector<DiceTableEntry> DiceTable;
216typedef DiceTable::iterator dice_table_iterator;
217
Kevin Enderby930fdc72014-11-06 19:00:13 +0000218// This is used to search for a data in code table entry for the PC being
219// disassembled. The j parameter has the PC in j.first. A single data in code
220// table entry can cover many bytes for each of its Kind's. So if the offset,
221// aka the i.first value, of the data in code table entry plus its Length
222// covers the PC being searched for this will return true. If not it will
223// return false.
David Majnemerea9b8ee2014-11-04 08:41:48 +0000224static bool compareDiceTableEntries(const DiceTableEntry &i,
225 const DiceTableEntry &j) {
Kevin Enderby930fdc72014-11-06 19:00:13 +0000226 uint16_t Length;
227 i.second.getLength(Length);
228
229 return j.first >= i.first && j.first < i.first + Length;
Kevin Enderby273ae012013-06-06 17:20:50 +0000230}
231
Colin LeMahieufc32b1b2015-03-18 19:27:31 +0000232static uint64_t DumpDataInCode(const uint8_t *bytes, uint64_t Length,
Kevin Enderby930fdc72014-11-06 19:00:13 +0000233 unsigned short Kind) {
234 uint32_t Value, Size = 1;
Kevin Enderby273ae012013-06-06 17:20:50 +0000235
236 switch (Kind) {
Kevin Enderby930fdc72014-11-06 19:00:13 +0000237 default:
Charles Davis8bdfafd2013-09-01 04:28:48 +0000238 case MachO::DICE_KIND_DATA:
Kevin Enderby930fdc72014-11-06 19:00:13 +0000239 if (Length >= 4) {
240 if (!NoShowRawInsn)
Craig Topper0013be12015-09-21 05:32:41 +0000241 dumpBytes(makeArrayRef(bytes, 4), outs());
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000242 Value = bytes[3] << 24 | bytes[2] << 16 | bytes[1] << 8 | bytes[0];
Kevin Enderby273ae012013-06-06 17:20:50 +0000243 outs() << "\t.long " << Value;
Kevin Enderby930fdc72014-11-06 19:00:13 +0000244 Size = 4;
245 } else if (Length >= 2) {
246 if (!NoShowRawInsn)
Craig Topper0013be12015-09-21 05:32:41 +0000247 dumpBytes(makeArrayRef(bytes, 2), outs());
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000248 Value = bytes[1] << 8 | bytes[0];
Kevin Enderby273ae012013-06-06 17:20:50 +0000249 outs() << "\t.short " << Value;
Kevin Enderby930fdc72014-11-06 19:00:13 +0000250 Size = 2;
251 } else {
252 if (!NoShowRawInsn)
Craig Topper0013be12015-09-21 05:32:41 +0000253 dumpBytes(makeArrayRef(bytes, 2), outs());
Kevin Enderby273ae012013-06-06 17:20:50 +0000254 Value = bytes[0];
255 outs() << "\t.byte " << Value;
Kevin Enderby930fdc72014-11-06 19:00:13 +0000256 Size = 1;
Kevin Enderby273ae012013-06-06 17:20:50 +0000257 }
Kevin Enderby930fdc72014-11-06 19:00:13 +0000258 if (Kind == MachO::DICE_KIND_DATA)
259 outs() << "\t@ KIND_DATA\n";
260 else
261 outs() << "\t@ data in code kind = " << Kind << "\n";
Kevin Enderby273ae012013-06-06 17:20:50 +0000262 break;
Charles Davis8bdfafd2013-09-01 04:28:48 +0000263 case MachO::DICE_KIND_JUMP_TABLE8:
Kevin Enderby930fdc72014-11-06 19:00:13 +0000264 if (!NoShowRawInsn)
Craig Topper0013be12015-09-21 05:32:41 +0000265 dumpBytes(makeArrayRef(bytes, 1), outs());
Kevin Enderby273ae012013-06-06 17:20:50 +0000266 Value = bytes[0];
Kevin Enderby930fdc72014-11-06 19:00:13 +0000267 outs() << "\t.byte " << format("%3u", Value) << "\t@ KIND_JUMP_TABLE8\n";
268 Size = 1;
Kevin Enderby273ae012013-06-06 17:20:50 +0000269 break;
Charles Davis8bdfafd2013-09-01 04:28:48 +0000270 case MachO::DICE_KIND_JUMP_TABLE16:
Kevin Enderby930fdc72014-11-06 19:00:13 +0000271 if (!NoShowRawInsn)
Craig Topper0013be12015-09-21 05:32:41 +0000272 dumpBytes(makeArrayRef(bytes, 2), outs());
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000273 Value = bytes[1] << 8 | bytes[0];
Kevin Enderby930fdc72014-11-06 19:00:13 +0000274 outs() << "\t.short " << format("%5u", Value & 0xffff)
275 << "\t@ KIND_JUMP_TABLE16\n";
276 Size = 2;
Kevin Enderby273ae012013-06-06 17:20:50 +0000277 break;
Charles Davis8bdfafd2013-09-01 04:28:48 +0000278 case MachO::DICE_KIND_JUMP_TABLE32:
Kevin Enderby930fdc72014-11-06 19:00:13 +0000279 case MachO::DICE_KIND_ABS_JUMP_TABLE32:
280 if (!NoShowRawInsn)
Craig Topper0013be12015-09-21 05:32:41 +0000281 dumpBytes(makeArrayRef(bytes, 4), outs());
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000282 Value = bytes[3] << 24 | bytes[2] << 16 | bytes[1] << 8 | bytes[0];
Kevin Enderby930fdc72014-11-06 19:00:13 +0000283 outs() << "\t.long " << Value;
284 if (Kind == MachO::DICE_KIND_JUMP_TABLE32)
285 outs() << "\t@ KIND_JUMP_TABLE32\n";
286 else
287 outs() << "\t@ KIND_ABS_JUMP_TABLE32\n";
288 Size = 4;
Kevin Enderby273ae012013-06-06 17:20:50 +0000289 break;
290 }
Kevin Enderby930fdc72014-11-06 19:00:13 +0000291 return Size;
Kevin Enderby273ae012013-06-06 17:20:50 +0000292}
293
Alexey Samsonovd319c4f2015-06-03 22:19:36 +0000294static void getSectionsAndSymbols(MachOObjectFile *MachOObj,
Alexey Samsonov464d2e42014-03-17 07:28:19 +0000295 std::vector<SectionRef> &Sections,
296 std::vector<SymbolRef> &Symbols,
297 SmallVectorImpl<uint64_t> &FoundFns,
298 uint64_t &BaseSegmentAddress) {
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +0000299 for (const SymbolRef &Symbol : MachOObj->symbols()) {
Kevin Enderby81e8b7d2016-04-20 21:24:34 +0000300 Expected<StringRef> SymName = Symbol.getName();
301 if (!SymName) {
302 std::string Buf;
303 raw_string_ostream OS(Buf);
304 logAllUnhandledErrors(SymName.takeError(), OS, "");
305 OS.flush();
306 report_fatal_error(Buf);
307 }
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +0000308 if (!SymName->startswith("ltmp"))
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +0000309 Symbols.push_back(Symbol);
310 }
Owen Andersond9243c42011-10-17 21:37:35 +0000311
Alexey Samsonov48803e52014-03-13 14:37:36 +0000312 for (const SectionRef &Section : MachOObj->sections()) {
Owen Andersond9243c42011-10-17 21:37:35 +0000313 StringRef SectName;
Alexey Samsonov48803e52014-03-13 14:37:36 +0000314 Section.getName(SectName);
315 Sections.push_back(Section);
Owen Andersond9243c42011-10-17 21:37:35 +0000316 }
317
Kevin Enderby273ae012013-06-06 17:20:50 +0000318 bool BaseSegmentAddressSet = false;
Alexey Samsonovd319c4f2015-06-03 22:19:36 +0000319 for (const auto &Command : MachOObj->load_commands()) {
Charles Davis8bdfafd2013-09-01 04:28:48 +0000320 if (Command.C.cmd == MachO::LC_FUNCTION_STARTS) {
Benjamin Kramer699128e2011-09-21 01:13:19 +0000321 // We found a function starts segment, parse the addresses for later
322 // consumption.
Charles Davis8bdfafd2013-09-01 04:28:48 +0000323 MachO::linkedit_data_command LLC =
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000324 MachOObj->getLinkeditDataLoadCommand(Command);
Benjamin Kramer699128e2011-09-21 01:13:19 +0000325
Charles Davis8bdfafd2013-09-01 04:28:48 +0000326 MachOObj->ReadULEB128s(LLC.dataoff, FoundFns);
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000327 } else if (Command.C.cmd == MachO::LC_SEGMENT) {
328 MachO::segment_command SLC = MachOObj->getSegmentLoadCommand(Command);
Charles Davis8bdfafd2013-09-01 04:28:48 +0000329 StringRef SegName = SLC.segname;
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000330 if (!BaseSegmentAddressSet && SegName != "__PAGEZERO") {
Kevin Enderby273ae012013-06-06 17:20:50 +0000331 BaseSegmentAddressSet = true;
Charles Davis8bdfafd2013-09-01 04:28:48 +0000332 BaseSegmentAddress = SLC.vmaddr;
Kevin Enderby273ae012013-06-06 17:20:50 +0000333 }
334 }
Benjamin Kramer8a529dc2011-09-21 22:16:43 +0000335 }
Benjamin Kramer699128e2011-09-21 01:13:19 +0000336}
337
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +0000338static void PrintIndirectSymbolTable(MachOObjectFile *O, bool verbose,
339 uint32_t n, uint32_t count,
340 uint32_t stride, uint64_t addr) {
341 MachO::dysymtab_command Dysymtab = O->getDysymtabLoadCommand();
342 uint32_t nindirectsyms = Dysymtab.nindirectsyms;
343 if (n > nindirectsyms)
344 outs() << " (entries start past the end of the indirect symbol "
345 "table) (reserved1 field greater than the table size)";
346 else if (n + count > nindirectsyms)
347 outs() << " (entries extends past the end of the indirect symbol "
348 "table)";
349 outs() << "\n";
350 uint32_t cputype = O->getHeader().cputype;
351 if (cputype & MachO::CPU_ARCH_ABI64)
352 outs() << "address index";
353 else
354 outs() << "address index";
355 if (verbose)
356 outs() << " name\n";
357 else
358 outs() << "\n";
359 for (uint32_t j = 0; j < count && n + j < nindirectsyms; j++) {
360 if (cputype & MachO::CPU_ARCH_ABI64)
361 outs() << format("0x%016" PRIx64, addr + j * stride) << " ";
362 else
Tim Northover43978372016-04-26 18:29:16 +0000363 outs() << format("0x%08" PRIx32, (uint32_t)addr + j * stride) << " ";
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +0000364 MachO::dysymtab_command Dysymtab = O->getDysymtabLoadCommand();
365 uint32_t indirect_symbol = O->getIndirectSymbolTableEntry(Dysymtab, n + j);
366 if (indirect_symbol == MachO::INDIRECT_SYMBOL_LOCAL) {
367 outs() << "LOCAL\n";
368 continue;
369 }
370 if (indirect_symbol ==
371 (MachO::INDIRECT_SYMBOL_LOCAL | MachO::INDIRECT_SYMBOL_ABS)) {
372 outs() << "LOCAL ABSOLUTE\n";
373 continue;
374 }
375 if (indirect_symbol == MachO::INDIRECT_SYMBOL_ABS) {
376 outs() << "ABSOLUTE\n";
377 continue;
378 }
379 outs() << format("%5u ", indirect_symbol);
Kevin Enderbyf0640752015-03-13 17:56:32 +0000380 if (verbose) {
381 MachO::symtab_command Symtab = O->getSymtabLoadCommand();
382 if (indirect_symbol < Symtab.nsyms) {
383 symbol_iterator Sym = O->getSymbolByIndex(indirect_symbol);
384 SymbolRef Symbol = *Sym;
Kevin Enderby81e8b7d2016-04-20 21:24:34 +0000385 Expected<StringRef> SymName = Symbol.getName();
386 if (!SymName) {
387 std::string Buf;
388 raw_string_ostream OS(Buf);
389 logAllUnhandledErrors(SymName.takeError(), OS, "");
390 OS.flush();
391 report_fatal_error(Buf);
392 }
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +0000393 outs() << *SymName;
Kevin Enderbyf0640752015-03-13 17:56:32 +0000394 } else {
395 outs() << "?";
396 }
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +0000397 }
398 outs() << "\n";
399 }
400}
401
402static void PrintIndirectSymbols(MachOObjectFile *O, bool verbose) {
Alexey Samsonovd319c4f2015-06-03 22:19:36 +0000403 for (const auto &Load : O->load_commands()) {
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +0000404 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
405 MachO::segment_command_64 Seg = O->getSegment64LoadCommand(Load);
406 for (unsigned J = 0; J < Seg.nsects; ++J) {
407 MachO::section_64 Sec = O->getSection64(Load, J);
408 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
409 if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
410 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
411 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
412 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
413 section_type == MachO::S_SYMBOL_STUBS) {
414 uint32_t stride;
415 if (section_type == MachO::S_SYMBOL_STUBS)
416 stride = Sec.reserved2;
417 else
418 stride = 8;
419 if (stride == 0) {
420 outs() << "Can't print indirect symbols for (" << Sec.segname << ","
421 << Sec.sectname << ") "
422 << "(size of stubs in reserved2 field is zero)\n";
423 continue;
424 }
425 uint32_t count = Sec.size / stride;
426 outs() << "Indirect symbols for (" << Sec.segname << ","
427 << Sec.sectname << ") " << count << " entries";
428 uint32_t n = Sec.reserved1;
429 PrintIndirectSymbolTable(O, verbose, n, count, stride, Sec.addr);
430 }
431 }
432 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
433 MachO::segment_command Seg = O->getSegmentLoadCommand(Load);
434 for (unsigned J = 0; J < Seg.nsects; ++J) {
435 MachO::section Sec = O->getSection(Load, J);
436 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
437 if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
438 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
439 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
440 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
441 section_type == MachO::S_SYMBOL_STUBS) {
442 uint32_t stride;
443 if (section_type == MachO::S_SYMBOL_STUBS)
444 stride = Sec.reserved2;
445 else
446 stride = 4;
447 if (stride == 0) {
448 outs() << "Can't print indirect symbols for (" << Sec.segname << ","
449 << Sec.sectname << ") "
450 << "(size of stubs in reserved2 field is zero)\n";
451 continue;
452 }
453 uint32_t count = Sec.size / stride;
454 outs() << "Indirect symbols for (" << Sec.segname << ","
455 << Sec.sectname << ") " << count << " entries";
456 uint32_t n = Sec.reserved1;
457 PrintIndirectSymbolTable(O, verbose, n, count, stride, Sec.addr);
458 }
459 }
460 }
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +0000461 }
462}
463
Kevin Enderby69fe98d2015-01-23 18:52:17 +0000464static void PrintDataInCodeTable(MachOObjectFile *O, bool verbose) {
465 MachO::linkedit_data_command DIC = O->getDataInCodeLoadCommand();
466 uint32_t nentries = DIC.datasize / sizeof(struct MachO::data_in_code_entry);
467 outs() << "Data in code table (" << nentries << " entries)\n";
468 outs() << "offset length kind\n";
469 for (dice_iterator DI = O->begin_dices(), DE = O->end_dices(); DI != DE;
470 ++DI) {
471 uint32_t Offset;
472 DI->getOffset(Offset);
473 outs() << format("0x%08" PRIx32, Offset) << " ";
474 uint16_t Length;
475 DI->getLength(Length);
476 outs() << format("%6u", Length) << " ";
477 uint16_t Kind;
478 DI->getKind(Kind);
479 if (verbose) {
480 switch (Kind) {
481 case MachO::DICE_KIND_DATA:
482 outs() << "DATA";
483 break;
484 case MachO::DICE_KIND_JUMP_TABLE8:
485 outs() << "JUMP_TABLE8";
486 break;
487 case MachO::DICE_KIND_JUMP_TABLE16:
488 outs() << "JUMP_TABLE16";
489 break;
490 case MachO::DICE_KIND_JUMP_TABLE32:
491 outs() << "JUMP_TABLE32";
492 break;
493 case MachO::DICE_KIND_ABS_JUMP_TABLE32:
494 outs() << "ABS_JUMP_TABLE32";
495 break;
496 default:
497 outs() << format("0x%04" PRIx32, Kind);
498 break;
499 }
500 } else
501 outs() << format("0x%04" PRIx32, Kind);
502 outs() << "\n";
503 }
504}
505
Kevin Enderby9a509442015-01-27 21:28:24 +0000506static void PrintLinkOptHints(MachOObjectFile *O) {
507 MachO::linkedit_data_command LohLC = O->getLinkOptHintsLoadCommand();
508 const char *loh = O->getData().substr(LohLC.dataoff, 1).data();
509 uint32_t nloh = LohLC.datasize;
510 outs() << "Linker optimiztion hints (" << nloh << " total bytes)\n";
511 for (uint32_t i = 0; i < nloh;) {
512 unsigned n;
513 uint64_t identifier = decodeULEB128((const uint8_t *)(loh + i), &n);
514 i += n;
515 outs() << " identifier " << identifier << " ";
516 if (i >= nloh)
517 return;
518 switch (identifier) {
519 case 1:
520 outs() << "AdrpAdrp\n";
521 break;
522 case 2:
523 outs() << "AdrpLdr\n";
524 break;
525 case 3:
526 outs() << "AdrpAddLdr\n";
527 break;
528 case 4:
529 outs() << "AdrpLdrGotLdr\n";
530 break;
531 case 5:
532 outs() << "AdrpAddStr\n";
533 break;
534 case 6:
535 outs() << "AdrpLdrGotStr\n";
536 break;
537 case 7:
538 outs() << "AdrpAdd\n";
539 break;
540 case 8:
541 outs() << "AdrpLdrGot\n";
542 break;
543 default:
544 outs() << "Unknown identifier value\n";
545 break;
546 }
547 uint64_t narguments = decodeULEB128((const uint8_t *)(loh + i), &n);
548 i += n;
549 outs() << " narguments " << narguments << "\n";
550 if (i >= nloh)
551 return;
552
553 for (uint32_t j = 0; j < narguments; j++) {
554 uint64_t value = decodeULEB128((const uint8_t *)(loh + i), &n);
555 i += n;
556 outs() << "\tvalue " << format("0x%" PRIx64, value) << "\n";
557 if (i >= nloh)
558 return;
559 }
560 }
561}
562
Kevin Enderbybc847fa2015-03-16 20:08:09 +0000563static void PrintDylibs(MachOObjectFile *O, bool JustId) {
Alexey Samsonovd319c4f2015-06-03 22:19:36 +0000564 unsigned Index = 0;
565 for (const auto &Load : O->load_commands()) {
Kevin Enderbybc847fa2015-03-16 20:08:09 +0000566 if ((JustId && Load.C.cmd == MachO::LC_ID_DYLIB) ||
567 (!JustId && (Load.C.cmd == MachO::LC_ID_DYLIB ||
568 Load.C.cmd == MachO::LC_LOAD_DYLIB ||
569 Load.C.cmd == MachO::LC_LOAD_WEAK_DYLIB ||
570 Load.C.cmd == MachO::LC_REEXPORT_DYLIB ||
571 Load.C.cmd == MachO::LC_LAZY_LOAD_DYLIB ||
572 Load.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB))) {
573 MachO::dylib_command dl = O->getDylibIDLoadCommand(Load);
574 if (dl.dylib.name < dl.cmdsize) {
575 const char *p = (const char *)(Load.Ptr) + dl.dylib.name;
576 if (JustId)
577 outs() << p << "\n";
578 else {
579 outs() << "\t" << p;
580 outs() << " (compatibility version "
581 << ((dl.dylib.compatibility_version >> 16) & 0xffff) << "."
582 << ((dl.dylib.compatibility_version >> 8) & 0xff) << "."
583 << (dl.dylib.compatibility_version & 0xff) << ",";
584 outs() << " current version "
585 << ((dl.dylib.current_version >> 16) & 0xffff) << "."
586 << ((dl.dylib.current_version >> 8) & 0xff) << "."
587 << (dl.dylib.current_version & 0xff) << ")\n";
588 }
589 } else {
590 outs() << "\tBad offset (" << dl.dylib.name << ") for name of ";
591 if (Load.C.cmd == MachO::LC_ID_DYLIB)
592 outs() << "LC_ID_DYLIB ";
593 else if (Load.C.cmd == MachO::LC_LOAD_DYLIB)
594 outs() << "LC_LOAD_DYLIB ";
595 else if (Load.C.cmd == MachO::LC_LOAD_WEAK_DYLIB)
596 outs() << "LC_LOAD_WEAK_DYLIB ";
597 else if (Load.C.cmd == MachO::LC_LAZY_LOAD_DYLIB)
598 outs() << "LC_LAZY_LOAD_DYLIB ";
599 else if (Load.C.cmd == MachO::LC_REEXPORT_DYLIB)
600 outs() << "LC_REEXPORT_DYLIB ";
601 else if (Load.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB)
602 outs() << "LC_LOAD_UPWARD_DYLIB ";
603 else
604 outs() << "LC_??? ";
Alexey Samsonovd319c4f2015-06-03 22:19:36 +0000605 outs() << "command " << Index++ << "\n";
Kevin Enderbybc847fa2015-03-16 20:08:09 +0000606 }
607 }
Kevin Enderbybc847fa2015-03-16 20:08:09 +0000608 }
609}
610
Kevin Enderbyf6d25852015-01-31 00:37:11 +0000611typedef DenseMap<uint64_t, StringRef> SymbolAddressMap;
612
613static void CreateSymbolAddressMap(MachOObjectFile *O,
614 SymbolAddressMap *AddrMap) {
615 // Create a map of symbol addresses to symbol names.
616 for (const SymbolRef &Symbol : O->symbols()) {
Kevin Enderby7bd8d992016-05-02 20:28:12 +0000617 Expected<SymbolRef::Type> STOrErr = Symbol.getType();
618 if (!STOrErr) {
619 std::string Buf;
620 raw_string_ostream OS(Buf);
621 logAllUnhandledErrors(STOrErr.takeError(), OS, "");
622 OS.flush();
623 report_fatal_error(Buf);
624 }
Kevin Enderby5afbc1c2016-03-23 20:27:00 +0000625 SymbolRef::Type ST = *STOrErr;
Kevin Enderbyf6d25852015-01-31 00:37:11 +0000626 if (ST == SymbolRef::ST_Function || ST == SymbolRef::ST_Data ||
627 ST == SymbolRef::ST_Other) {
Rafael Espindoladea00162015-07-03 17:44:18 +0000628 uint64_t Address = Symbol.getValue();
Kevin Enderby81e8b7d2016-04-20 21:24:34 +0000629 Expected<StringRef> SymNameOrErr = Symbol.getName();
630 if (!SymNameOrErr) {
631 std::string Buf;
632 raw_string_ostream OS(Buf);
633 logAllUnhandledErrors(SymNameOrErr.takeError(), OS, "");
634 OS.flush();
635 report_fatal_error(Buf);
636 }
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +0000637 StringRef SymName = *SymNameOrErr;
Kevin Enderby846c0002015-04-16 17:19:59 +0000638 if (!SymName.startswith(".objc"))
639 (*AddrMap)[Address] = SymName;
Kevin Enderbyf6d25852015-01-31 00:37:11 +0000640 }
641 }
642}
643
644// GuessSymbolName is passed the address of what might be a symbol and a
645// pointer to the SymbolAddressMap. It returns the name of a symbol
646// with that address or nullptr if no symbol is found with that address.
647static const char *GuessSymbolName(uint64_t value, SymbolAddressMap *AddrMap) {
648 const char *SymbolName = nullptr;
649 // A DenseMap can't lookup up some values.
650 if (value != 0xffffffffffffffffULL && value != 0xfffffffffffffffeULL) {
651 StringRef name = AddrMap->lookup(value);
652 if (!name.empty())
653 SymbolName = name.data();
654 }
655 return SymbolName;
656}
657
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000658static void DumpCstringChar(const char c) {
659 char p[2];
660 p[0] = c;
661 p[1] = '\0';
662 outs().write_escaped(p);
663}
664
Kevin Enderby10ba0412015-02-04 21:38:42 +0000665static void DumpCstringSection(MachOObjectFile *O, const char *sect,
666 uint32_t sect_size, uint64_t sect_addr,
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000667 bool print_addresses) {
Kevin Enderby10ba0412015-02-04 21:38:42 +0000668 for (uint32_t i = 0; i < sect_size; i++) {
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000669 if (print_addresses) {
670 if (O->is64Bit())
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000671 outs() << format("%016" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000672 else
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000673 outs() << format("%08" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000674 }
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000675 for (; i < sect_size && sect[i] != '\0'; i++)
676 DumpCstringChar(sect[i]);
Kevin Enderby10ba0412015-02-04 21:38:42 +0000677 if (i < sect_size && sect[i] == '\0')
678 outs() << "\n";
679 }
680}
681
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000682static void DumpLiteral4(uint32_t l, float f) {
683 outs() << format("0x%08" PRIx32, l);
684 if ((l & 0x7f800000) != 0x7f800000)
685 outs() << format(" (%.16e)\n", f);
686 else {
687 if (l == 0x7f800000)
688 outs() << " (+Infinity)\n";
689 else if (l == 0xff800000)
690 outs() << " (-Infinity)\n";
691 else if ((l & 0x00400000) == 0x00400000)
692 outs() << " (non-signaling Not-a-Number)\n";
693 else
694 outs() << " (signaling Not-a-Number)\n";
695 }
696}
697
698static void DumpLiteral4Section(MachOObjectFile *O, const char *sect,
699 uint32_t sect_size, uint64_t sect_addr,
700 bool print_addresses) {
701 for (uint32_t i = 0; i < sect_size; i += sizeof(float)) {
702 if (print_addresses) {
703 if (O->is64Bit())
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000704 outs() << format("%016" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000705 else
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000706 outs() << format("%08" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000707 }
708 float f;
709 memcpy(&f, sect + i, sizeof(float));
710 if (O->isLittleEndian() != sys::IsLittleEndianHost)
711 sys::swapByteOrder(f);
712 uint32_t l;
713 memcpy(&l, sect + i, sizeof(uint32_t));
714 if (O->isLittleEndian() != sys::IsLittleEndianHost)
715 sys::swapByteOrder(l);
716 DumpLiteral4(l, f);
717 }
718}
719
720static void DumpLiteral8(MachOObjectFile *O, uint32_t l0, uint32_t l1,
721 double d) {
722 outs() << format("0x%08" PRIx32, l0) << " " << format("0x%08" PRIx32, l1);
723 uint32_t Hi, Lo;
Davide Italianob627d9f2015-12-12 21:50:11 +0000724 Hi = (O->isLittleEndian()) ? l1 : l0;
725 Lo = (O->isLittleEndian()) ? l0 : l1;
726
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000727 // Hi is the high word, so this is equivalent to if(isfinite(d))
728 if ((Hi & 0x7ff00000) != 0x7ff00000)
729 outs() << format(" (%.16e)\n", d);
730 else {
731 if (Hi == 0x7ff00000 && Lo == 0)
732 outs() << " (+Infinity)\n";
733 else if (Hi == 0xfff00000 && Lo == 0)
734 outs() << " (-Infinity)\n";
735 else if ((Hi & 0x00080000) == 0x00080000)
736 outs() << " (non-signaling Not-a-Number)\n";
737 else
738 outs() << " (signaling Not-a-Number)\n";
739 }
740}
741
742static void DumpLiteral8Section(MachOObjectFile *O, const char *sect,
743 uint32_t sect_size, uint64_t sect_addr,
744 bool print_addresses) {
745 for (uint32_t i = 0; i < sect_size; i += sizeof(double)) {
746 if (print_addresses) {
747 if (O->is64Bit())
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000748 outs() << format("%016" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000749 else
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000750 outs() << format("%08" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000751 }
752 double d;
753 memcpy(&d, sect + i, sizeof(double));
754 if (O->isLittleEndian() != sys::IsLittleEndianHost)
755 sys::swapByteOrder(d);
756 uint32_t l0, l1;
757 memcpy(&l0, sect + i, sizeof(uint32_t));
758 memcpy(&l1, sect + i + sizeof(uint32_t), sizeof(uint32_t));
759 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
760 sys::swapByteOrder(l0);
761 sys::swapByteOrder(l1);
762 }
763 DumpLiteral8(O, l0, l1, d);
764 }
765}
766
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000767static void DumpLiteral16(uint32_t l0, uint32_t l1, uint32_t l2, uint32_t l3) {
768 outs() << format("0x%08" PRIx32, l0) << " ";
769 outs() << format("0x%08" PRIx32, l1) << " ";
770 outs() << format("0x%08" PRIx32, l2) << " ";
771 outs() << format("0x%08" PRIx32, l3) << "\n";
772}
773
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000774static void DumpLiteral16Section(MachOObjectFile *O, const char *sect,
775 uint32_t sect_size, uint64_t sect_addr,
776 bool print_addresses) {
777 for (uint32_t i = 0; i < sect_size; i += 16) {
778 if (print_addresses) {
779 if (O->is64Bit())
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000780 outs() << format("%016" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000781 else
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000782 outs() << format("%08" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000783 }
784 uint32_t l0, l1, l2, l3;
785 memcpy(&l0, sect + i, sizeof(uint32_t));
786 memcpy(&l1, sect + i + sizeof(uint32_t), sizeof(uint32_t));
787 memcpy(&l2, sect + i + 2 * sizeof(uint32_t), sizeof(uint32_t));
788 memcpy(&l3, sect + i + 3 * sizeof(uint32_t), sizeof(uint32_t));
789 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
790 sys::swapByteOrder(l0);
791 sys::swapByteOrder(l1);
792 sys::swapByteOrder(l2);
793 sys::swapByteOrder(l3);
794 }
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000795 DumpLiteral16(l0, l1, l2, l3);
796 }
797}
798
799static void DumpLiteralPointerSection(MachOObjectFile *O,
800 const SectionRef &Section,
801 const char *sect, uint32_t sect_size,
802 uint64_t sect_addr,
803 bool print_addresses) {
804 // Collect the literal sections in this Mach-O file.
805 std::vector<SectionRef> LiteralSections;
806 for (const SectionRef &Section : O->sections()) {
807 DataRefImpl Ref = Section.getRawDataRefImpl();
808 uint32_t section_type;
809 if (O->is64Bit()) {
810 const MachO::section_64 Sec = O->getSection64(Ref);
811 section_type = Sec.flags & MachO::SECTION_TYPE;
812 } else {
813 const MachO::section Sec = O->getSection(Ref);
814 section_type = Sec.flags & MachO::SECTION_TYPE;
815 }
816 if (section_type == MachO::S_CSTRING_LITERALS ||
817 section_type == MachO::S_4BYTE_LITERALS ||
818 section_type == MachO::S_8BYTE_LITERALS ||
819 section_type == MachO::S_16BYTE_LITERALS)
820 LiteralSections.push_back(Section);
821 }
822
823 // Set the size of the literal pointer.
824 uint32_t lp_size = O->is64Bit() ? 8 : 4;
825
Eric Christopher572e03a2015-06-19 01:53:21 +0000826 // Collect the external relocation symbols for the literal pointers.
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000827 std::vector<std::pair<uint64_t, SymbolRef>> Relocs;
828 for (const RelocationRef &Reloc : Section.relocations()) {
829 DataRefImpl Rel;
830 MachO::any_relocation_info RE;
831 bool isExtern = false;
832 Rel = Reloc.getRawDataRefImpl();
833 RE = O->getRelocation(Rel);
834 isExtern = O->getPlainRelocationExternal(RE);
835 if (isExtern) {
Rafael Espindola96d071c2015-06-29 23:29:12 +0000836 uint64_t RelocOffset = Reloc.getOffset();
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000837 symbol_iterator RelocSym = Reloc.getSymbol();
838 Relocs.push_back(std::make_pair(RelocOffset, *RelocSym));
839 }
840 }
841 array_pod_sort(Relocs.begin(), Relocs.end());
842
843 // Dump each literal pointer.
844 for (uint32_t i = 0; i < sect_size; i += lp_size) {
845 if (print_addresses) {
846 if (O->is64Bit())
847 outs() << format("%016" PRIx64, sect_addr + i) << " ";
848 else
849 outs() << format("%08" PRIx64, sect_addr + i) << " ";
850 }
851 uint64_t lp;
852 if (O->is64Bit()) {
853 memcpy(&lp, sect + i, sizeof(uint64_t));
854 if (O->isLittleEndian() != sys::IsLittleEndianHost)
855 sys::swapByteOrder(lp);
856 } else {
857 uint32_t li;
858 memcpy(&li, sect + i, sizeof(uint32_t));
859 if (O->isLittleEndian() != sys::IsLittleEndianHost)
860 sys::swapByteOrder(li);
861 lp = li;
862 }
863
864 // First look for an external relocation entry for this literal pointer.
David Blaikie33dd45d02015-03-23 18:39:02 +0000865 auto Reloc = std::find_if(
866 Relocs.begin(), Relocs.end(),
867 [&](const std::pair<uint64_t, SymbolRef> &P) { return P.first == i; });
868 if (Reloc != Relocs.end()) {
869 symbol_iterator RelocSym = Reloc->second;
Kevin Enderby81e8b7d2016-04-20 21:24:34 +0000870 Expected<StringRef> SymName = RelocSym->getName();
871 if (!SymName) {
872 std::string Buf;
873 raw_string_ostream OS(Buf);
874 logAllUnhandledErrors(SymName.takeError(), OS, "");
875 OS.flush();
876 report_fatal_error(Buf);
877 }
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +0000878 outs() << "external relocation entry for symbol:" << *SymName << "\n";
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000879 continue;
David Blaikie33dd45d02015-03-23 18:39:02 +0000880 }
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000881
882 // For local references see what the section the literal pointer points to.
David Blaikie33dd45d02015-03-23 18:39:02 +0000883 auto Sect = std::find_if(LiteralSections.begin(), LiteralSections.end(),
884 [&](const SectionRef &R) {
885 return lp >= R.getAddress() &&
886 lp < R.getAddress() + R.getSize();
887 });
888 if (Sect == LiteralSections.end()) {
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000889 outs() << format("0x%" PRIx64, lp) << " (not in a literal section)\n";
David Blaikie33dd45d02015-03-23 18:39:02 +0000890 continue;
891 }
892
893 uint64_t SectAddress = Sect->getAddress();
894 uint64_t SectSize = Sect->getSize();
895
896 StringRef SectName;
897 Sect->getName(SectName);
898 DataRefImpl Ref = Sect->getRawDataRefImpl();
899 StringRef SegmentName = O->getSectionFinalSegmentName(Ref);
900 outs() << SegmentName << ":" << SectName << ":";
901
902 uint32_t section_type;
903 if (O->is64Bit()) {
904 const MachO::section_64 Sec = O->getSection64(Ref);
905 section_type = Sec.flags & MachO::SECTION_TYPE;
906 } else {
907 const MachO::section Sec = O->getSection(Ref);
908 section_type = Sec.flags & MachO::SECTION_TYPE;
909 }
910
911 StringRef BytesStr;
912 Sect->getContents(BytesStr);
913 const char *Contents = reinterpret_cast<const char *>(BytesStr.data());
914
915 switch (section_type) {
916 case MachO::S_CSTRING_LITERALS:
917 for (uint64_t i = lp - SectAddress; i < SectSize && Contents[i] != '\0';
918 i++) {
919 DumpCstringChar(Contents[i]);
920 }
921 outs() << "\n";
922 break;
923 case MachO::S_4BYTE_LITERALS:
924 float f;
925 memcpy(&f, Contents + (lp - SectAddress), sizeof(float));
926 uint32_t l;
927 memcpy(&l, Contents + (lp - SectAddress), sizeof(uint32_t));
928 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
929 sys::swapByteOrder(f);
930 sys::swapByteOrder(l);
931 }
932 DumpLiteral4(l, f);
933 break;
934 case MachO::S_8BYTE_LITERALS: {
935 double d;
936 memcpy(&d, Contents + (lp - SectAddress), sizeof(double));
937 uint32_t l0, l1;
938 memcpy(&l0, Contents + (lp - SectAddress), sizeof(uint32_t));
939 memcpy(&l1, Contents + (lp - SectAddress) + sizeof(uint32_t),
940 sizeof(uint32_t));
941 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
942 sys::swapByteOrder(f);
943 sys::swapByteOrder(l0);
944 sys::swapByteOrder(l1);
945 }
946 DumpLiteral8(O, l0, l1, d);
947 break;
948 }
949 case MachO::S_16BYTE_LITERALS: {
950 uint32_t l0, l1, l2, l3;
951 memcpy(&l0, Contents + (lp - SectAddress), sizeof(uint32_t));
952 memcpy(&l1, Contents + (lp - SectAddress) + sizeof(uint32_t),
953 sizeof(uint32_t));
954 memcpy(&l2, Contents + (lp - SectAddress) + 2 * sizeof(uint32_t),
955 sizeof(uint32_t));
956 memcpy(&l3, Contents + (lp - SectAddress) + 3 * sizeof(uint32_t),
957 sizeof(uint32_t));
958 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
959 sys::swapByteOrder(l0);
960 sys::swapByteOrder(l1);
961 sys::swapByteOrder(l2);
962 sys::swapByteOrder(l3);
963 }
964 DumpLiteral16(l0, l1, l2, l3);
965 break;
966 }
967 }
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000968 }
969}
970
Kevin Enderbyf6d25852015-01-31 00:37:11 +0000971static void DumpInitTermPointerSection(MachOObjectFile *O, const char *sect,
972 uint32_t sect_size, uint64_t sect_addr,
973 SymbolAddressMap *AddrMap,
974 bool verbose) {
975 uint32_t stride;
Davide Italiano3eb47e22015-12-15 23:14:21 +0000976 stride = (O->is64Bit()) ? sizeof(uint64_t) : sizeof(uint32_t);
Kevin Enderbyf6d25852015-01-31 00:37:11 +0000977 for (uint32_t i = 0; i < sect_size; i += stride) {
978 const char *SymbolName = nullptr;
979 if (O->is64Bit()) {
980 outs() << format("0x%016" PRIx64, sect_addr + i * stride) << " ";
981 uint64_t pointer_value;
982 memcpy(&pointer_value, sect + i, stride);
983 if (O->isLittleEndian() != sys::IsLittleEndianHost)
984 sys::swapByteOrder(pointer_value);
985 outs() << format("0x%016" PRIx64, pointer_value);
986 if (verbose)
987 SymbolName = GuessSymbolName(pointer_value, AddrMap);
988 } else {
989 outs() << format("0x%08" PRIx64, sect_addr + i * stride) << " ";
990 uint32_t pointer_value;
991 memcpy(&pointer_value, sect + i, stride);
992 if (O->isLittleEndian() != sys::IsLittleEndianHost)
993 sys::swapByteOrder(pointer_value);
994 outs() << format("0x%08" PRIx32, pointer_value);
995 if (verbose)
996 SymbolName = GuessSymbolName(pointer_value, AddrMap);
997 }
998 if (SymbolName)
999 outs() << " " << SymbolName;
1000 outs() << "\n";
1001 }
1002}
1003
1004static void DumpRawSectionContents(MachOObjectFile *O, const char *sect,
1005 uint32_t size, uint64_t addr) {
1006 uint32_t cputype = O->getHeader().cputype;
1007 if (cputype == MachO::CPU_TYPE_I386 || cputype == MachO::CPU_TYPE_X86_64) {
1008 uint32_t j;
1009 for (uint32_t i = 0; i < size; i += j, addr += j) {
1010 if (O->is64Bit())
1011 outs() << format("%016" PRIx64, addr) << "\t";
1012 else
Kevin Enderbyf0640752015-03-13 17:56:32 +00001013 outs() << format("%08" PRIx64, addr) << "\t";
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001014 for (j = 0; j < 16 && i + j < size; j++) {
1015 uint8_t byte_word = *(sect + i + j);
1016 outs() << format("%02" PRIx32, (uint32_t)byte_word) << " ";
1017 }
1018 outs() << "\n";
1019 }
1020 } else {
1021 uint32_t j;
1022 for (uint32_t i = 0; i < size; i += j, addr += j) {
1023 if (O->is64Bit())
1024 outs() << format("%016" PRIx64, addr) << "\t";
1025 else
Kevin Enderbyc4930852016-04-27 22:36:18 +00001026 outs() << format("%08" PRIx64, addr) << "\t";
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001027 for (j = 0; j < 4 * sizeof(int32_t) && i + j < size;
1028 j += sizeof(int32_t)) {
Kevin Enderby8eccdad2016-04-27 23:43:00 +00001029 if (i + j + sizeof(int32_t) <= size) {
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001030 uint32_t long_word;
1031 memcpy(&long_word, sect + i + j, sizeof(int32_t));
1032 if (O->isLittleEndian() != sys::IsLittleEndianHost)
1033 sys::swapByteOrder(long_word);
1034 outs() << format("%08" PRIx32, long_word) << " ";
1035 } else {
1036 for (uint32_t k = 0; i + j + k < size; k++) {
Kevin Enderby8eccdad2016-04-27 23:43:00 +00001037 uint8_t byte_word = *(sect + i + j + k);
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001038 outs() << format("%02" PRIx32, (uint32_t)byte_word) << " ";
1039 }
1040 }
1041 }
1042 outs() << "\n";
1043 }
1044 }
1045}
1046
Kevin Enderby95df54c2015-02-04 01:01:38 +00001047static void DisassembleMachO(StringRef Filename, MachOObjectFile *MachOOF,
1048 StringRef DisSegName, StringRef DisSectName);
Kevin Enderby4ad9bde2015-04-16 22:33:20 +00001049static void DumpProtocolSection(MachOObjectFile *O, const char *sect,
1050 uint32_t size, uint32_t addr);
Kevin Enderby9873e2c2016-05-23 21:34:12 +00001051#ifdef HAVE_LIBXAR
1052static void DumpBitcodeSection(MachOObjectFile *O, const char *sect,
1053 uint32_t size, bool verbose,
1054 bool PrintXarHeader, bool PrintXarFileHeaders,
1055 std::string XarMemberName);
1056#endif // defined(HAVE_LIBXAR)
Kevin Enderby95df54c2015-02-04 01:01:38 +00001057
1058static void DumpSectionContents(StringRef Filename, MachOObjectFile *O,
1059 bool verbose) {
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001060 SymbolAddressMap AddrMap;
1061 if (verbose)
1062 CreateSymbolAddressMap(O, &AddrMap);
1063
Colin LeMahieufcc32762015-07-29 19:08:10 +00001064 for (unsigned i = 0; i < FilterSections.size(); ++i) {
1065 StringRef DumpSection = FilterSections[i];
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001066 std::pair<StringRef, StringRef> DumpSegSectName;
1067 DumpSegSectName = DumpSection.split(',');
1068 StringRef DumpSegName, DumpSectName;
1069 if (DumpSegSectName.second.size()) {
1070 DumpSegName = DumpSegSectName.first;
1071 DumpSectName = DumpSegSectName.second;
1072 } else {
1073 DumpSegName = "";
1074 DumpSectName = DumpSegSectName.first;
1075 }
1076 for (const SectionRef &Section : O->sections()) {
1077 StringRef SectName;
1078 Section.getName(SectName);
1079 DataRefImpl Ref = Section.getRawDataRefImpl();
1080 StringRef SegName = O->getSectionFinalSegmentName(Ref);
1081 if ((DumpSegName.empty() || SegName == DumpSegName) &&
1082 (SectName == DumpSectName)) {
Adrian Prantlc2401dd2015-03-27 17:31:15 +00001083
Kevin Enderby95df54c2015-02-04 01:01:38 +00001084 uint32_t section_flags;
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001085 if (O->is64Bit()) {
1086 const MachO::section_64 Sec = O->getSection64(Ref);
Kevin Enderby95df54c2015-02-04 01:01:38 +00001087 section_flags = Sec.flags;
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001088
1089 } else {
1090 const MachO::section Sec = O->getSection(Ref);
Kevin Enderby95df54c2015-02-04 01:01:38 +00001091 section_flags = Sec.flags;
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001092 }
Kevin Enderby95df54c2015-02-04 01:01:38 +00001093 uint32_t section_type = section_flags & MachO::SECTION_TYPE;
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001094
1095 StringRef BytesStr;
1096 Section.getContents(BytesStr);
1097 const char *sect = reinterpret_cast<const char *>(BytesStr.data());
1098 uint32_t sect_size = BytesStr.size();
1099 uint64_t sect_addr = Section.getAddress();
1100
Adrian Prantlc2401dd2015-03-27 17:31:15 +00001101 outs() << "Contents of (" << SegName << "," << SectName
1102 << ") section\n";
1103
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001104 if (verbose) {
Kevin Enderby95df54c2015-02-04 01:01:38 +00001105 if ((section_flags & MachO::S_ATTR_PURE_INSTRUCTIONS) ||
1106 (section_flags & MachO::S_ATTR_SOME_INSTRUCTIONS)) {
1107 DisassembleMachO(Filename, O, SegName, SectName);
1108 continue;
1109 }
Kevin Enderbycd66be52015-03-11 22:06:32 +00001110 if (SegName == "__TEXT" && SectName == "__info_plist") {
1111 outs() << sect;
1112 continue;
1113 }
Kevin Enderby4ad9bde2015-04-16 22:33:20 +00001114 if (SegName == "__OBJC" && SectName == "__protocol") {
1115 DumpProtocolSection(O, sect, sect_size, sect_addr);
1116 continue;
1117 }
Kevin Enderby9873e2c2016-05-23 21:34:12 +00001118#ifdef HAVE_LIBXAR
1119 if (SegName == "__LLVM" && SectName == "__bundle") {
1120 DumpBitcodeSection(O, sect, sect_size, verbose, !NoSymbolicOperands,
1121 ArchiveHeaders, "");
1122 continue;
1123 }
1124#endif // defined(HAVE_LIBXAR)
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001125 switch (section_type) {
1126 case MachO::S_REGULAR:
1127 DumpRawSectionContents(O, sect, sect_size, sect_addr);
1128 break;
1129 case MachO::S_ZEROFILL:
1130 outs() << "zerofill section and has no contents in the file\n";
1131 break;
Kevin Enderby10ba0412015-02-04 21:38:42 +00001132 case MachO::S_CSTRING_LITERALS:
Kevin Enderbyab5e6c92015-03-17 21:07:39 +00001133 DumpCstringSection(O, sect, sect_size, sect_addr, !NoLeadingAddr);
Kevin Enderby10ba0412015-02-04 21:38:42 +00001134 break;
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001135 case MachO::S_4BYTE_LITERALS:
Kevin Enderbyab5e6c92015-03-17 21:07:39 +00001136 DumpLiteral4Section(O, sect, sect_size, sect_addr, !NoLeadingAddr);
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001137 break;
1138 case MachO::S_8BYTE_LITERALS:
Kevin Enderbyab5e6c92015-03-17 21:07:39 +00001139 DumpLiteral8Section(O, sect, sect_size, sect_addr, !NoLeadingAddr);
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001140 break;
1141 case MachO::S_16BYTE_LITERALS:
Kevin Enderby0fc11822015-04-01 20:57:01 +00001142 DumpLiteral16Section(O, sect, sect_size, sect_addr, !NoLeadingAddr);
1143 break;
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001144 case MachO::S_LITERAL_POINTERS:
1145 DumpLiteralPointerSection(O, Section, sect, sect_size, sect_addr,
Kevin Enderbyab5e6c92015-03-17 21:07:39 +00001146 !NoLeadingAddr);
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001147 break;
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001148 case MachO::S_MOD_INIT_FUNC_POINTERS:
1149 case MachO::S_MOD_TERM_FUNC_POINTERS:
1150 DumpInitTermPointerSection(O, sect, sect_size, sect_addr, &AddrMap,
1151 verbose);
1152 break;
1153 default:
1154 outs() << "Unknown section type ("
1155 << format("0x%08" PRIx32, section_type) << ")\n";
1156 DumpRawSectionContents(O, sect, sect_size, sect_addr);
1157 break;
1158 }
1159 } else {
1160 if (section_type == MachO::S_ZEROFILL)
1161 outs() << "zerofill section and has no contents in the file\n";
1162 else
1163 DumpRawSectionContents(O, sect, sect_size, sect_addr);
1164 }
1165 }
1166 }
1167 }
1168}
1169
Kevin Enderbycd66be52015-03-11 22:06:32 +00001170static void DumpInfoPlistSectionContents(StringRef Filename,
1171 MachOObjectFile *O) {
1172 for (const SectionRef &Section : O->sections()) {
1173 StringRef SectName;
1174 Section.getName(SectName);
1175 DataRefImpl Ref = Section.getRawDataRefImpl();
1176 StringRef SegName = O->getSectionFinalSegmentName(Ref);
1177 if (SegName == "__TEXT" && SectName == "__info_plist") {
1178 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
1179 StringRef BytesStr;
1180 Section.getContents(BytesStr);
1181 const char *sect = reinterpret_cast<const char *>(BytesStr.data());
1182 outs() << sect;
1183 return;
1184 }
1185 }
1186}
1187
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001188// checkMachOAndArchFlags() checks to see if the ObjectFile is a Mach-O file
1189// and if it is and there is a list of architecture flags is specified then
1190// check to make sure this Mach-O file is one of those architectures or all
1191// architectures were specified. If not then an error is generated and this
1192// routine returns false. Else it returns true.
1193static bool checkMachOAndArchFlags(ObjectFile *O, StringRef Filename) {
1194 if (isa<MachOObjectFile>(O) && !ArchAll && ArchFlags.size() != 0) {
1195 MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(O);
1196 bool ArchFound = false;
1197 MachO::mach_header H;
1198 MachO::mach_header_64 H_64;
1199 Triple T;
1200 if (MachO->is64Bit()) {
1201 H_64 = MachO->MachOObjectFile::getHeader64();
Tim Northover9e8eb412016-04-22 23:21:13 +00001202 T = MachOObjectFile::getArchTriple(H_64.cputype, H_64.cpusubtype);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001203 } else {
1204 H = MachO->MachOObjectFile::getHeader();
Tim Northover9e8eb412016-04-22 23:21:13 +00001205 T = MachOObjectFile::getArchTriple(H.cputype, H.cpusubtype);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001206 }
1207 unsigned i;
1208 for (i = 0; i < ArchFlags.size(); ++i) {
1209 if (ArchFlags[i] == T.getArchName())
1210 ArchFound = true;
1211 break;
1212 }
1213 if (!ArchFound) {
1214 errs() << "llvm-objdump: file: " + Filename + " does not contain "
1215 << "architecture: " + ArchFlags[i] + "\n";
1216 return false;
1217 }
1218 }
1219 return true;
1220}
1221
Kevin Enderby0fc11822015-04-01 20:57:01 +00001222static void printObjcMetaData(MachOObjectFile *O, bool verbose);
1223
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001224// ProcessMachO() is passed a single opened Mach-O file, which may be an
1225// archive member and or in a slice of a universal file. It prints the
1226// the file name and header info and then processes it according to the
1227// command line options.
1228static void ProcessMachO(StringRef Filename, MachOObjectFile *MachOOF,
1229 StringRef ArchiveMemberName = StringRef(),
1230 StringRef ArchitectureName = StringRef()) {
Kevin Enderby131d1772015-01-09 19:22:37 +00001231 // If we are doing some processing here on the Mach-O file print the header
1232 // info. And don't print it otherwise like in the case of printing the
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +00001233 // UniversalHeaders or ArchiveHeaders.
Kevin Enderbyac9e1552016-05-17 17:10:12 +00001234 if (Disassemble || PrivateHeaders || ExportsTrie || Rebase || Bind || SymbolTable ||
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001235 LazyBind || WeakBind || IndirectSymbols || DataInCode || LinkOptHints ||
Colin LeMahieufcc32762015-07-29 19:08:10 +00001236 DylibsUsed || DylibId || ObjcMetaData || (FilterSections.size() != 0)) {
Kevin Enderby131d1772015-01-09 19:22:37 +00001237 outs() << Filename;
1238 if (!ArchiveMemberName.empty())
1239 outs() << '(' << ArchiveMemberName << ')';
1240 if (!ArchitectureName.empty())
1241 outs() << " (architecture " << ArchitectureName << ")";
1242 outs() << ":\n";
1243 }
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001244
1245 if (Disassemble)
Kevin Enderby95df54c2015-02-04 01:01:38 +00001246 DisassembleMachO(Filename, MachOOF, "__TEXT", "__text");
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +00001247 if (IndirectSymbols)
Kevin Enderbyf0640752015-03-13 17:56:32 +00001248 PrintIndirectSymbols(MachOOF, !NonVerbose);
Kevin Enderby69fe98d2015-01-23 18:52:17 +00001249 if (DataInCode)
Kevin Enderbyf0640752015-03-13 17:56:32 +00001250 PrintDataInCodeTable(MachOOF, !NonVerbose);
Kevin Enderby9a509442015-01-27 21:28:24 +00001251 if (LinkOptHints)
1252 PrintLinkOptHints(MachOOF);
Kevin Enderby98da6132015-01-20 21:47:46 +00001253 if (Relocations)
1254 PrintRelocations(MachOOF);
1255 if (SectionHeaders)
1256 PrintSectionHeaders(MachOOF);
1257 if (SectionContents)
1258 PrintSectionContents(MachOOF);
Colin LeMahieufcc32762015-07-29 19:08:10 +00001259 if (FilterSections.size() != 0)
Kevin Enderbyf0640752015-03-13 17:56:32 +00001260 DumpSectionContents(Filename, MachOOF, !NonVerbose);
Kevin Enderbycd66be52015-03-11 22:06:32 +00001261 if (InfoPlist)
1262 DumpInfoPlistSectionContents(Filename, MachOOF);
Kevin Enderbybc847fa2015-03-16 20:08:09 +00001263 if (DylibsUsed)
1264 PrintDylibs(MachOOF, false);
1265 if (DylibId)
1266 PrintDylibs(MachOOF, true);
Kevin Enderbyac9e1552016-05-17 17:10:12 +00001267 if (SymbolTable) {
1268 StringRef ArchiveName = ArchiveMemberName == StringRef() ? "" : Filename;
Kevin Enderby9acb1092016-05-31 20:35:34 +00001269 PrintSymbolTable(MachOOF, ArchiveName, ArchitectureName);
Kevin Enderbyac9e1552016-05-17 17:10:12 +00001270 }
Kevin Enderby98da6132015-01-20 21:47:46 +00001271 if (UnwindInfo)
1272 printMachOUnwindInfo(MachOOF);
Kevin Enderby0ae163f2016-01-13 00:25:36 +00001273 if (PrivateHeaders) {
1274 printMachOFileHeader(MachOOF);
1275 printMachOLoadCommands(MachOOF);
1276 }
1277 if (FirstPrivateHeader)
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001278 printMachOFileHeader(MachOOF);
Kevin Enderby0fc11822015-04-01 20:57:01 +00001279 if (ObjcMetaData)
1280 printObjcMetaData(MachOOF, !NonVerbose);
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001281 if (ExportsTrie)
1282 printExportsTrie(MachOOF);
1283 if (Rebase)
1284 printRebaseTable(MachOOF);
1285 if (Bind)
1286 printBindTable(MachOOF);
1287 if (LazyBind)
1288 printLazyBindTable(MachOOF);
1289 if (WeakBind)
1290 printWeakBindTable(MachOOF);
Igor Laevsky03a670c2016-01-26 15:09:42 +00001291
1292 if (DwarfDumpType != DIDT_Null) {
1293 std::unique_ptr<DIContext> DICtx(new DWARFContextInMemory(*MachOOF));
1294 // Dump the complete DWARF structure.
1295 DICtx->dump(outs(), DwarfDumpType, true /* DumpEH */);
1296 }
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001297}
1298
Kevin Enderby131d1772015-01-09 19:22:37 +00001299// printUnknownCPUType() helps print_fat_headers for unknown CPU's.
1300static void printUnknownCPUType(uint32_t cputype, uint32_t cpusubtype) {
1301 outs() << " cputype (" << cputype << ")\n";
1302 outs() << " cpusubtype (" << cpusubtype << ")\n";
1303}
1304
1305// printCPUType() helps print_fat_headers by printing the cputype and
1306// pusubtype (symbolically for the one's it knows about).
1307static void printCPUType(uint32_t cputype, uint32_t cpusubtype) {
1308 switch (cputype) {
1309 case MachO::CPU_TYPE_I386:
1310 switch (cpusubtype) {
1311 case MachO::CPU_SUBTYPE_I386_ALL:
1312 outs() << " cputype CPU_TYPE_I386\n";
1313 outs() << " cpusubtype CPU_SUBTYPE_I386_ALL\n";
1314 break;
1315 default:
1316 printUnknownCPUType(cputype, cpusubtype);
1317 break;
1318 }
1319 break;
1320 case MachO::CPU_TYPE_X86_64:
1321 switch (cpusubtype) {
1322 case MachO::CPU_SUBTYPE_X86_64_ALL:
1323 outs() << " cputype CPU_TYPE_X86_64\n";
1324 outs() << " cpusubtype CPU_SUBTYPE_X86_64_ALL\n";
1325 break;
1326 case MachO::CPU_SUBTYPE_X86_64_H:
1327 outs() << " cputype CPU_TYPE_X86_64\n";
1328 outs() << " cpusubtype CPU_SUBTYPE_X86_64_H\n";
1329 break;
1330 default:
1331 printUnknownCPUType(cputype, cpusubtype);
1332 break;
1333 }
1334 break;
1335 case MachO::CPU_TYPE_ARM:
1336 switch (cpusubtype) {
1337 case MachO::CPU_SUBTYPE_ARM_ALL:
1338 outs() << " cputype CPU_TYPE_ARM\n";
1339 outs() << " cpusubtype CPU_SUBTYPE_ARM_ALL\n";
1340 break;
1341 case MachO::CPU_SUBTYPE_ARM_V4T:
1342 outs() << " cputype CPU_TYPE_ARM\n";
1343 outs() << " cpusubtype CPU_SUBTYPE_ARM_V4T\n";
1344 break;
1345 case MachO::CPU_SUBTYPE_ARM_V5TEJ:
1346 outs() << " cputype CPU_TYPE_ARM\n";
1347 outs() << " cpusubtype CPU_SUBTYPE_ARM_V5TEJ\n";
1348 break;
1349 case MachO::CPU_SUBTYPE_ARM_XSCALE:
1350 outs() << " cputype CPU_TYPE_ARM\n";
1351 outs() << " cpusubtype CPU_SUBTYPE_ARM_XSCALE\n";
1352 break;
1353 case MachO::CPU_SUBTYPE_ARM_V6:
1354 outs() << " cputype CPU_TYPE_ARM\n";
1355 outs() << " cpusubtype CPU_SUBTYPE_ARM_V6\n";
1356 break;
1357 case MachO::CPU_SUBTYPE_ARM_V6M:
1358 outs() << " cputype CPU_TYPE_ARM\n";
1359 outs() << " cpusubtype CPU_SUBTYPE_ARM_V6M\n";
1360 break;
1361 case MachO::CPU_SUBTYPE_ARM_V7:
1362 outs() << " cputype CPU_TYPE_ARM\n";
1363 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7\n";
1364 break;
1365 case MachO::CPU_SUBTYPE_ARM_V7EM:
1366 outs() << " cputype CPU_TYPE_ARM\n";
1367 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7EM\n";
1368 break;
1369 case MachO::CPU_SUBTYPE_ARM_V7K:
1370 outs() << " cputype CPU_TYPE_ARM\n";
1371 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7K\n";
1372 break;
1373 case MachO::CPU_SUBTYPE_ARM_V7M:
1374 outs() << " cputype CPU_TYPE_ARM\n";
1375 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7M\n";
1376 break;
1377 case MachO::CPU_SUBTYPE_ARM_V7S:
1378 outs() << " cputype CPU_TYPE_ARM\n";
1379 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7S\n";
1380 break;
1381 default:
1382 printUnknownCPUType(cputype, cpusubtype);
1383 break;
1384 }
1385 break;
1386 case MachO::CPU_TYPE_ARM64:
1387 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
1388 case MachO::CPU_SUBTYPE_ARM64_ALL:
1389 outs() << " cputype CPU_TYPE_ARM64\n";
1390 outs() << " cpusubtype CPU_SUBTYPE_ARM64_ALL\n";
1391 break;
1392 default:
1393 printUnknownCPUType(cputype, cpusubtype);
1394 break;
1395 }
1396 break;
1397 default:
1398 printUnknownCPUType(cputype, cpusubtype);
1399 break;
1400 }
1401}
1402
1403static void printMachOUniversalHeaders(const object::MachOUniversalBinary *UB,
1404 bool verbose) {
1405 outs() << "Fat headers\n";
Kevin Enderby606a3382016-06-21 21:55:01 +00001406 if (verbose) {
1407 if (UB->getMagic() == MachO::FAT_MAGIC)
1408 outs() << "fat_magic FAT_MAGIC\n";
1409 else // UB->getMagic() == MachO::FAT_MAGIC_64
1410 outs() << "fat_magic FAT_MAGIC_64\n";
1411 } else
Kevin Enderby131d1772015-01-09 19:22:37 +00001412 outs() << "fat_magic " << format("0x%" PRIx32, MachO::FAT_MAGIC) << "\n";
1413
1414 uint32_t nfat_arch = UB->getNumberOfObjects();
1415 StringRef Buf = UB->getData();
1416 uint64_t size = Buf.size();
1417 uint64_t big_size = sizeof(struct MachO::fat_header) +
1418 nfat_arch * sizeof(struct MachO::fat_arch);
1419 outs() << "nfat_arch " << UB->getNumberOfObjects();
1420 if (nfat_arch == 0)
1421 outs() << " (malformed, contains zero architecture types)\n";
1422 else if (big_size > size)
1423 outs() << " (malformed, architectures past end of file)\n";
1424 else
1425 outs() << "\n";
1426
1427 for (uint32_t i = 0; i < nfat_arch; ++i) {
1428 MachOUniversalBinary::ObjectForArch OFA(UB, i);
1429 uint32_t cputype = OFA.getCPUType();
1430 uint32_t cpusubtype = OFA.getCPUSubType();
1431 outs() << "architecture ";
1432 for (uint32_t j = 0; i != 0 && j <= i - 1; j++) {
1433 MachOUniversalBinary::ObjectForArch other_OFA(UB, j);
1434 uint32_t other_cputype = other_OFA.getCPUType();
1435 uint32_t other_cpusubtype = other_OFA.getCPUSubType();
Kevin Enderby0512bd72015-01-09 21:55:03 +00001436 if (cputype != 0 && cpusubtype != 0 && cputype == other_cputype &&
Kevin Enderby131d1772015-01-09 19:22:37 +00001437 (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) ==
Kevin Enderby0512bd72015-01-09 21:55:03 +00001438 (other_cpusubtype & ~MachO::CPU_SUBTYPE_MASK)) {
Kevin Enderby131d1772015-01-09 19:22:37 +00001439 outs() << "(illegal duplicate architecture) ";
1440 break;
Kevin Enderby0512bd72015-01-09 21:55:03 +00001441 }
Kevin Enderby131d1772015-01-09 19:22:37 +00001442 }
1443 if (verbose) {
1444 outs() << OFA.getArchTypeName() << "\n";
1445 printCPUType(cputype, cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
1446 } else {
1447 outs() << i << "\n";
1448 outs() << " cputype " << cputype << "\n";
1449 outs() << " cpusubtype " << (cpusubtype & ~MachO::CPU_SUBTYPE_MASK)
1450 << "\n";
1451 }
1452 if (verbose &&
1453 (cpusubtype & MachO::CPU_SUBTYPE_MASK) == MachO::CPU_SUBTYPE_LIB64)
1454 outs() << " capabilities CPU_SUBTYPE_LIB64\n";
1455 else
1456 outs() << " capabilities "
1457 << format("0x%" PRIx32,
1458 (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24) << "\n";
1459 outs() << " offset " << OFA.getOffset();
1460 if (OFA.getOffset() > size)
1461 outs() << " (past end of file)";
1462 if (OFA.getOffset() % (1 << OFA.getAlign()) != 0)
1463 outs() << " (not aligned on it's alignment (2^" << OFA.getAlign() << ")";
1464 outs() << "\n";
1465 outs() << " size " << OFA.getSize();
1466 big_size = OFA.getOffset() + OFA.getSize();
1467 if (big_size > size)
1468 outs() << " (past end of file)";
1469 outs() << "\n";
1470 outs() << " align 2^" << OFA.getAlign() << " (" << (1 << OFA.getAlign())
1471 << ")\n";
1472 }
1473}
1474
Kevin Enderby6524bd82016-07-19 20:47:07 +00001475static void printArchiveChild(StringRef Filename, const Archive::Child &C,
1476 bool verbose, bool print_offset,
1477 StringRef ArchitectureName = StringRef()) {
Kevin Enderby13023a12015-01-15 23:19:11 +00001478 if (print_offset)
1479 outs() << C.getChildOffset() << "\t";
1480 sys::fs::perms Mode = C.getAccessMode();
1481 if (verbose) {
1482 // FIXME: this first dash, "-", is for (Mode & S_IFMT) == S_IFREG.
1483 // But there is nothing in sys::fs::perms for S_IFMT or S_IFREG.
1484 outs() << "-";
Davide Italianobb9a6cc2015-09-07 20:47:03 +00001485 outs() << ((Mode & sys::fs::owner_read) ? "r" : "-");
1486 outs() << ((Mode & sys::fs::owner_write) ? "w" : "-");
1487 outs() << ((Mode & sys::fs::owner_exe) ? "x" : "-");
1488 outs() << ((Mode & sys::fs::group_read) ? "r" : "-");
1489 outs() << ((Mode & sys::fs::group_write) ? "w" : "-");
1490 outs() << ((Mode & sys::fs::group_exe) ? "x" : "-");
1491 outs() << ((Mode & sys::fs::others_read) ? "r" : "-");
1492 outs() << ((Mode & sys::fs::others_write) ? "w" : "-");
1493 outs() << ((Mode & sys::fs::others_exe) ? "x" : "-");
Kevin Enderby13023a12015-01-15 23:19:11 +00001494 } else {
1495 outs() << format("0%o ", Mode);
1496 }
1497
1498 unsigned UID = C.getUID();
1499 outs() << format("%3d/", UID);
1500 unsigned GID = C.getGID();
1501 outs() << format("%-3d ", GID);
Kevin Enderby6524bd82016-07-19 20:47:07 +00001502 Expected<uint64_t> Size = C.getRawSize();
1503 if (!Size)
1504 report_error(Filename, C, Size.takeError(), ArchitectureName);
Kevin Enderby7a969422015-11-05 19:24:56 +00001505 outs() << format("%5" PRId64, Size.get()) << " ";
Kevin Enderby13023a12015-01-15 23:19:11 +00001506
1507 StringRef RawLastModified = C.getRawLastModified();
1508 if (verbose) {
1509 unsigned Seconds;
1510 if (RawLastModified.getAsInteger(10, Seconds))
1511 outs() << "(date: \"%s\" contains non-decimal chars) " << RawLastModified;
1512 else {
1513 // Since cime(3) returns a 26 character string of the form:
1514 // "Sun Sep 16 01:03:52 1973\n\0"
1515 // just print 24 characters.
1516 time_t t = Seconds;
1517 outs() << format("%.24s ", ctime(&t));
1518 }
1519 } else {
1520 outs() << RawLastModified << " ";
1521 }
1522
1523 if (verbose) {
Kevin Enderbyf4586032016-07-29 17:44:13 +00001524 Expected<StringRef> NameOrErr = C.getName();
1525 if (!NameOrErr) {
1526 consumeError(NameOrErr.takeError());
1527 Expected<StringRef> NameOrErr = C.getRawName();
1528 if (!NameOrErr)
1529 report_error(Filename, C, NameOrErr.takeError(), ArchitectureName);
1530 StringRef RawName = NameOrErr.get();
Kevin Enderby13023a12015-01-15 23:19:11 +00001531 outs() << RawName << "\n";
1532 } else {
1533 StringRef Name = NameOrErr.get();
1534 outs() << Name << "\n";
1535 }
1536 } else {
Kevin Enderbyf4586032016-07-29 17:44:13 +00001537 Expected<StringRef> NameOrErr = C.getRawName();
1538 if (!NameOrErr)
1539 report_error(Filename, C, NameOrErr.takeError(), ArchitectureName);
1540 StringRef RawName = NameOrErr.get();
Kevin Enderby13023a12015-01-15 23:19:11 +00001541 outs() << RawName << "\n";
1542 }
1543}
1544
Kevin Enderby6524bd82016-07-19 20:47:07 +00001545static void printArchiveHeaders(StringRef Filename, Archive *A, bool verbose,
1546 bool print_offset,
1547 StringRef ArchitectureName = StringRef()) {
Lang Hamesfc209622016-07-14 02:24:01 +00001548 Error Err;
1549 for (const auto &C : A->children(Err, false))
Kevin Enderby6524bd82016-07-19 20:47:07 +00001550 printArchiveChild(Filename, C, verbose, print_offset, ArchitectureName);
1551
Lang Hamesfc209622016-07-14 02:24:01 +00001552 if (Err)
Kevin Enderby6524bd82016-07-19 20:47:07 +00001553 report_error(Filename, std::move(Err));
Kevin Enderby13023a12015-01-15 23:19:11 +00001554}
1555
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001556// ParseInputMachO() parses the named Mach-O file in Filename and handles the
1557// -arch flags selecting just those slices as specified by them and also parses
1558// archive files. Then for each individual Mach-O file ProcessMachO() is
1559// called to process the file based on the command line options.
1560void llvm::ParseInputMachO(StringRef Filename) {
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001561 // Check for -arch all and verifiy the -arch flags are valid.
1562 for (unsigned i = 0; i < ArchFlags.size(); ++i) {
1563 if (ArchFlags[i] == "all") {
1564 ArchAll = true;
1565 } else {
1566 if (!MachOObjectFile::isValidArch(ArchFlags[i])) {
1567 errs() << "llvm-objdump: Unknown architecture named '" + ArchFlags[i] +
1568 "'for the -arch option\n";
1569 return;
1570 }
1571 }
1572 }
1573
1574 // Attempt to open the binary.
Kevin Enderby3fcdf6a2016-04-06 22:14:09 +00001575 Expected<OwningBinary<Binary>> BinaryOrErr = createBinary(Filename);
1576 if (!BinaryOrErr)
1577 report_error(Filename, BinaryOrErr.takeError());
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001578 Binary &Bin = *BinaryOrErr.get().getBinary();
Kevin Enderby3f0ffab2014-12-03 22:29:40 +00001579
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001580 if (Archive *A = dyn_cast<Archive>(&Bin)) {
1581 outs() << "Archive : " << Filename << "\n";
Kevin Enderby13023a12015-01-15 23:19:11 +00001582 if (ArchiveHeaders)
Kevin Enderby6524bd82016-07-19 20:47:07 +00001583 printArchiveHeaders(Filename, A, !NonVerbose, ArchiveMemberOffsets);
1584
Lang Hamesfc209622016-07-14 02:24:01 +00001585 Error Err;
1586 for (auto &C : A->children(Err)) {
Kevin Enderbyac9e1552016-05-17 17:10:12 +00001587 Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
1588 if (!ChildOrErr) {
1589 if (auto E = isNotObjectErrorInvalidFileType(ChildOrErr.takeError()))
1590 report_error(Filename, C, std::move(E));
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001591 continue;
Kevin Enderbyac9e1552016-05-17 17:10:12 +00001592 }
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001593 if (MachOObjectFile *O = dyn_cast<MachOObjectFile>(&*ChildOrErr.get())) {
1594 if (!checkMachOAndArchFlags(O, Filename))
1595 return;
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001596 ProcessMachO(Filename, O, O->getFileName());
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001597 }
1598 }
Lang Hamesfc209622016-07-14 02:24:01 +00001599 if (Err)
1600 report_error(Filename, std::move(Err));
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001601 return;
1602 }
Kevin Enderby131d1772015-01-09 19:22:37 +00001603 if (UniversalHeaders) {
1604 if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(&Bin))
Kevin Enderbyf0640752015-03-13 17:56:32 +00001605 printMachOUniversalHeaders(UB, !NonVerbose);
Kevin Enderby131d1772015-01-09 19:22:37 +00001606 }
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001607 if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(&Bin)) {
1608 // If we have a list of architecture flags specified dump only those.
1609 if (!ArchAll && ArchFlags.size() != 0) {
1610 // Look for a slice in the universal binary that matches each ArchFlag.
1611 bool ArchFound;
1612 for (unsigned i = 0; i < ArchFlags.size(); ++i) {
1613 ArchFound = false;
1614 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
1615 E = UB->end_objects();
1616 I != E; ++I) {
1617 if (ArchFlags[i] == I->getArchTypeName()) {
1618 ArchFound = true;
Kevin Enderby9acb1092016-05-31 20:35:34 +00001619 Expected<std::unique_ptr<ObjectFile>> ObjOrErr =
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001620 I->getAsObjectFile();
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001621 std::string ArchitectureName = "";
1622 if (ArchFlags.size() > 1)
1623 ArchitectureName = I->getArchTypeName();
1624 if (ObjOrErr) {
1625 ObjectFile &O = *ObjOrErr.get();
1626 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&O))
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001627 ProcessMachO(Filename, MachOOF, "", ArchitectureName);
Kevin Enderby9acb1092016-05-31 20:35:34 +00001628 } else if (auto E = isNotObjectErrorInvalidFileType(
1629 ObjOrErr.takeError())) {
1630 report_error(Filename, StringRef(), std::move(E),
1631 ArchitectureName);
1632 continue;
Kevin Enderby42398052016-06-28 23:16:13 +00001633 } else if (Expected<std::unique_ptr<Archive>> AOrErr =
Rafael Espindola0bfe8282014-12-09 21:05:36 +00001634 I->getAsArchive()) {
1635 std::unique_ptr<Archive> &A = *AOrErr;
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001636 outs() << "Archive : " << Filename;
1637 if (!ArchitectureName.empty())
1638 outs() << " (architecture " << ArchitectureName << ")";
1639 outs() << "\n";
Kevin Enderby13023a12015-01-15 23:19:11 +00001640 if (ArchiveHeaders)
Kevin Enderby6524bd82016-07-19 20:47:07 +00001641 printArchiveHeaders(Filename, A.get(), !NonVerbose,
1642 ArchiveMemberOffsets, ArchitectureName);
Lang Hamesfc209622016-07-14 02:24:01 +00001643 Error Err;
1644 for (auto &C : A->children(Err)) {
Kevin Enderbyac9e1552016-05-17 17:10:12 +00001645 Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
1646 if (!ChildOrErr) {
1647 if (auto E = isNotObjectErrorInvalidFileType(ChildOrErr.takeError()))
Kevin Enderby9acb1092016-05-31 20:35:34 +00001648 report_error(Filename, C, std::move(E), ArchitectureName);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001649 continue;
Kevin Enderbyac9e1552016-05-17 17:10:12 +00001650 }
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001651 if (MachOObjectFile *O =
1652 dyn_cast<MachOObjectFile>(&*ChildOrErr.get()))
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001653 ProcessMachO(Filename, O, O->getFileName(), ArchitectureName);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001654 }
Lang Hamesfc209622016-07-14 02:24:01 +00001655 if (Err)
1656 report_error(Filename, std::move(Err));
Kevin Enderby42398052016-06-28 23:16:13 +00001657 } else {
1658 consumeError(AOrErr.takeError());
1659 error("Mach-O universal file: " + Filename + " for " +
1660 "architecture " + StringRef(I->getArchTypeName()) +
1661 " is not a Mach-O file or an archive file");
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001662 }
1663 }
1664 }
1665 if (!ArchFound) {
1666 errs() << "llvm-objdump: file: " + Filename + " does not contain "
1667 << "architecture: " + ArchFlags[i] + "\n";
1668 return;
1669 }
1670 }
1671 return;
1672 }
1673 // No architecture flags were specified so if this contains a slice that
1674 // matches the host architecture dump only that.
1675 if (!ArchAll) {
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001676 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
1677 E = UB->end_objects();
1678 I != E; ++I) {
Kevin Enderby0512bd72015-01-09 21:55:03 +00001679 if (MachOObjectFile::getHostArch().getArchName() ==
1680 I->getArchTypeName()) {
Kevin Enderby9acb1092016-05-31 20:35:34 +00001681 Expected<std::unique_ptr<ObjectFile>> ObjOrErr = I->getAsObjectFile();
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001682 std::string ArchiveName;
1683 ArchiveName.clear();
1684 if (ObjOrErr) {
1685 ObjectFile &O = *ObjOrErr.get();
1686 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&O))
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001687 ProcessMachO(Filename, MachOOF);
Kevin Enderby9acb1092016-05-31 20:35:34 +00001688 } else if (auto E = isNotObjectErrorInvalidFileType(
1689 ObjOrErr.takeError())) {
1690 report_error(Filename, std::move(E));
1691 continue;
Kevin Enderby42398052016-06-28 23:16:13 +00001692 } else if (Expected<std::unique_ptr<Archive>> AOrErr =
Rafael Espindola0bfe8282014-12-09 21:05:36 +00001693 I->getAsArchive()) {
1694 std::unique_ptr<Archive> &A = *AOrErr;
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001695 outs() << "Archive : " << Filename << "\n";
Kevin Enderby13023a12015-01-15 23:19:11 +00001696 if (ArchiveHeaders)
Kevin Enderby6524bd82016-07-19 20:47:07 +00001697 printArchiveHeaders(Filename, A.get(), !NonVerbose,
1698 ArchiveMemberOffsets);
Lang Hamesfc209622016-07-14 02:24:01 +00001699 Error Err;
1700 for (auto &C : A->children(Err)) {
Kevin Enderbyac9e1552016-05-17 17:10:12 +00001701 Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
1702 if (!ChildOrErr) {
1703 if (auto E = isNotObjectErrorInvalidFileType(ChildOrErr.takeError()))
1704 report_error(Filename, C, std::move(E));
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001705 continue;
Kevin Enderbyac9e1552016-05-17 17:10:12 +00001706 }
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001707 if (MachOObjectFile *O =
1708 dyn_cast<MachOObjectFile>(&*ChildOrErr.get()))
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001709 ProcessMachO(Filename, O, O->getFileName());
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001710 }
Lang Hamesfc209622016-07-14 02:24:01 +00001711 if (Err)
1712 report_error(Filename, std::move(Err));
Kevin Enderby42398052016-06-28 23:16:13 +00001713 } else {
1714 consumeError(AOrErr.takeError());
1715 error("Mach-O universal file: " + Filename + " for architecture " +
1716 StringRef(I->getArchTypeName()) +
1717 " is not a Mach-O file or an archive file");
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001718 }
1719 return;
1720 }
1721 }
1722 }
1723 // Either all architectures have been specified or none have been specified
1724 // and this does not contain the host architecture so dump all the slices.
1725 bool moreThanOneArch = UB->getNumberOfObjects() > 1;
1726 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
1727 E = UB->end_objects();
1728 I != E; ++I) {
Kevin Enderby9acb1092016-05-31 20:35:34 +00001729 Expected<std::unique_ptr<ObjectFile>> ObjOrErr = I->getAsObjectFile();
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001730 std::string ArchitectureName = "";
1731 if (moreThanOneArch)
1732 ArchitectureName = I->getArchTypeName();
1733 if (ObjOrErr) {
1734 ObjectFile &Obj = *ObjOrErr.get();
1735 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&Obj))
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001736 ProcessMachO(Filename, MachOOF, "", ArchitectureName);
Kevin Enderby9acb1092016-05-31 20:35:34 +00001737 } else if (auto E = isNotObjectErrorInvalidFileType(
1738 ObjOrErr.takeError())) {
1739 report_error(StringRef(), Filename, std::move(E), ArchitectureName);
1740 continue;
Kevin Enderby42398052016-06-28 23:16:13 +00001741 } else if (Expected<std::unique_ptr<Archive>> AOrErr =
1742 I->getAsArchive()) {
Rafael Espindola0bfe8282014-12-09 21:05:36 +00001743 std::unique_ptr<Archive> &A = *AOrErr;
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001744 outs() << "Archive : " << Filename;
1745 if (!ArchitectureName.empty())
1746 outs() << " (architecture " << ArchitectureName << ")";
1747 outs() << "\n";
Kevin Enderby13023a12015-01-15 23:19:11 +00001748 if (ArchiveHeaders)
Kevin Enderby6524bd82016-07-19 20:47:07 +00001749 printArchiveHeaders(Filename, A.get(), !NonVerbose,
1750 ArchiveMemberOffsets, ArchitectureName);
Lang Hamesfc209622016-07-14 02:24:01 +00001751 Error Err;
1752 for (auto &C : A->children(Err)) {
Kevin Enderbyac9e1552016-05-17 17:10:12 +00001753 Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
1754 if (!ChildOrErr) {
1755 if (auto E = isNotObjectErrorInvalidFileType(ChildOrErr.takeError()))
Kevin Enderby9acb1092016-05-31 20:35:34 +00001756 report_error(Filename, C, std::move(E), ArchitectureName);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001757 continue;
Kevin Enderbyac9e1552016-05-17 17:10:12 +00001758 }
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001759 if (MachOObjectFile *O =
1760 dyn_cast<MachOObjectFile>(&*ChildOrErr.get())) {
1761 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(O))
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001762 ProcessMachO(Filename, MachOOF, MachOOF->getFileName(),
1763 ArchitectureName);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001764 }
1765 }
Lang Hamesfc209622016-07-14 02:24:01 +00001766 if (Err)
1767 report_error(Filename, std::move(Err));
Kevin Enderby42398052016-06-28 23:16:13 +00001768 } else {
1769 consumeError(AOrErr.takeError());
1770 error("Mach-O universal file: " + Filename + " for architecture " +
1771 StringRef(I->getArchTypeName()) +
1772 " is not a Mach-O file or an archive file");
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001773 }
1774 }
1775 return;
1776 }
1777 if (ObjectFile *O = dyn_cast<ObjectFile>(&Bin)) {
1778 if (!checkMachOAndArchFlags(O, Filename))
1779 return;
1780 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&*O)) {
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001781 ProcessMachO(Filename, MachOOF);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001782 } else
1783 errs() << "llvm-objdump: '" << Filename << "': "
1784 << "Object is not a Mach-O file type.\n";
Davide Italiano25d84582016-01-13 04:11:36 +00001785 return;
1786 }
1787 llvm_unreachable("Input object can't be invalid at this point");
Rafael Espindola9b709252013-04-13 01:45:40 +00001788}
1789
Kevin Enderby6f326ce2014-10-23 19:37:31 +00001790typedef std::pair<uint64_t, const char *> BindInfoEntry;
1791typedef std::vector<BindInfoEntry> BindTable;
1792typedef BindTable::iterator bind_table_iterator;
Kevin Enderbybf246f52014-09-24 23:08:22 +00001793
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001794// The block of info used by the Symbolizer call backs.
1795struct DisassembleInfo {
1796 bool verbose;
1797 MachOObjectFile *O;
1798 SectionRef S;
Kevin Enderbybf246f52014-09-24 23:08:22 +00001799 SymbolAddressMap *AddrMap;
Kevin Enderby6f326ce2014-10-23 19:37:31 +00001800 std::vector<SectionRef> *Sections;
1801 const char *class_name;
1802 const char *selector_name;
1803 char *method;
Kevin Enderby04bf6932014-10-28 23:39:46 +00001804 char *demangled_name;
Kevin Enderbyae3c1262014-11-14 21:52:18 +00001805 uint64_t adrp_addr;
1806 uint32_t adrp_inst;
Kevin Enderby078be602014-10-23 19:53:12 +00001807 BindTable *bindtable;
Kevin Enderbyaac75382015-10-08 16:56:35 +00001808 uint32_t depth;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001809};
1810
1811// SymbolizerGetOpInfo() is the operand information call back function.
1812// This is called to get the symbolic information for operand(s) of an
1813// instruction when it is being done. This routine does this from
1814// the relocation information, symbol table, etc. That block of information
1815// is a pointer to the struct DisassembleInfo that was passed when the
1816// disassembler context was created and passed to back to here when
1817// called back by the disassembler for instruction operands that could have
1818// relocation information. The address of the instruction containing operand is
1819// at the Pc parameter. The immediate value the operand has is passed in
1820// op_info->Value and is at Offset past the start of the instruction and has a
1821// byte Size of 1, 2 or 4. The symbolc information is returned in TagBuf is the
1822// LLVMOpInfo1 struct defined in the header "llvm-c/Disassembler.h" as symbol
1823// names and addends of the symbolic expression to add for the operand. The
1824// value of TagType is currently 1 (for the LLVMOpInfo1 struct). If symbolic
1825// information is returned then this function returns 1 else it returns 0.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00001826static int SymbolizerGetOpInfo(void *DisInfo, uint64_t Pc, uint64_t Offset,
1827 uint64_t Size, int TagType, void *TagBuf) {
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001828 struct DisassembleInfo *info = (struct DisassembleInfo *)DisInfo;
1829 struct LLVMOpInfo1 *op_info = (struct LLVMOpInfo1 *)TagBuf;
Kevin Enderbyae3c1262014-11-14 21:52:18 +00001830 uint64_t value = op_info->Value;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001831
1832 // Make sure all fields returned are zero if we don't set them.
1833 memset((void *)op_info, '\0', sizeof(struct LLVMOpInfo1));
1834 op_info->Value = value;
1835
1836 // If the TagType is not the value 1 which it code knows about or if no
1837 // verbose symbolic information is wanted then just return 0, indicating no
1838 // information is being returned.
David Blaikie33dd45d02015-03-23 18:39:02 +00001839 if (TagType != 1 || !info->verbose)
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001840 return 0;
1841
1842 unsigned int Arch = info->O->getArch();
1843 if (Arch == Triple::x86) {
Kevin Enderby9907d0a2014-11-04 00:43:16 +00001844 if (Size != 1 && Size != 2 && Size != 4 && Size != 0)
1845 return 0;
Kevin Enderbyd90a4172015-10-10 00:05:01 +00001846 if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
1847 // TODO:
1848 // Search the external relocation entries of a fully linked image
1849 // (if any) for an entry that matches this segment offset.
1850 // uint32_t seg_offset = (Pc + Offset);
1851 return 0;
1852 }
1853 // In MH_OBJECT filetypes search the section's relocation entries (if any)
1854 // for an entry for this section offset.
Kevin Enderby9907d0a2014-11-04 00:43:16 +00001855 uint32_t sect_addr = info->S.getAddress();
1856 uint32_t sect_offset = (Pc + Offset) - sect_addr;
1857 bool reloc_found = false;
1858 DataRefImpl Rel;
1859 MachO::any_relocation_info RE;
1860 bool isExtern = false;
1861 SymbolRef Symbol;
1862 bool r_scattered = false;
1863 uint32_t r_value, pair_r_value, r_type;
1864 for (const RelocationRef &Reloc : info->S.relocations()) {
Rafael Espindola96d071c2015-06-29 23:29:12 +00001865 uint64_t RelocOffset = Reloc.getOffset();
Kevin Enderby9907d0a2014-11-04 00:43:16 +00001866 if (RelocOffset == sect_offset) {
1867 Rel = Reloc.getRawDataRefImpl();
1868 RE = info->O->getRelocation(Rel);
Kevin Enderby3eb73e12014-11-11 19:16:45 +00001869 r_type = info->O->getAnyRelocationType(RE);
Kevin Enderby9907d0a2014-11-04 00:43:16 +00001870 r_scattered = info->O->isRelocationScattered(RE);
1871 if (r_scattered) {
1872 r_value = info->O->getScatteredRelocationValue(RE);
Kevin Enderby9907d0a2014-11-04 00:43:16 +00001873 if (r_type == MachO::GENERIC_RELOC_SECTDIFF ||
1874 r_type == MachO::GENERIC_RELOC_LOCAL_SECTDIFF) {
1875 DataRefImpl RelNext = Rel;
1876 info->O->moveRelocationNext(RelNext);
1877 MachO::any_relocation_info RENext;
1878 RENext = info->O->getRelocation(RelNext);
1879 if (info->O->isRelocationScattered(RENext))
Kevin Enderby930fdc72014-11-06 19:00:13 +00001880 pair_r_value = info->O->getScatteredRelocationValue(RENext);
Kevin Enderby9907d0a2014-11-04 00:43:16 +00001881 else
1882 return 0;
1883 }
1884 } else {
1885 isExtern = info->O->getPlainRelocationExternal(RE);
1886 if (isExtern) {
1887 symbol_iterator RelocSym = Reloc.getSymbol();
1888 Symbol = *RelocSym;
1889 }
1890 }
1891 reloc_found = true;
1892 break;
1893 }
1894 }
1895 if (reloc_found && isExtern) {
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00001896 Expected<StringRef> SymName = Symbol.getName();
1897 if (!SymName) {
1898 std::string Buf;
1899 raw_string_ostream OS(Buf);
1900 logAllUnhandledErrors(SymName.takeError(), OS, "");
1901 OS.flush();
1902 report_fatal_error(Buf);
1903 }
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00001904 const char *name = SymName->data();
Kevin Enderby9907d0a2014-11-04 00:43:16 +00001905 op_info->AddSymbol.Present = 1;
1906 op_info->AddSymbol.Name = name;
1907 // For i386 extern relocation entries the value in the instruction is
1908 // the offset from the symbol, and value is already set in op_info->Value.
1909 return 1;
1910 }
1911 if (reloc_found && (r_type == MachO::GENERIC_RELOC_SECTDIFF ||
1912 r_type == MachO::GENERIC_RELOC_LOCAL_SECTDIFF)) {
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001913 const char *add = GuessSymbolName(r_value, info->AddrMap);
1914 const char *sub = GuessSymbolName(pair_r_value, info->AddrMap);
Kevin Enderby9907d0a2014-11-04 00:43:16 +00001915 uint32_t offset = value - (r_value - pair_r_value);
1916 op_info->AddSymbol.Present = 1;
1917 if (add != nullptr)
1918 op_info->AddSymbol.Name = add;
1919 else
1920 op_info->AddSymbol.Value = r_value;
1921 op_info->SubtractSymbol.Present = 1;
1922 if (sub != nullptr)
1923 op_info->SubtractSymbol.Name = sub;
1924 else
1925 op_info->SubtractSymbol.Value = pair_r_value;
1926 op_info->Value = offset;
1927 return 1;
1928 }
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001929 return 0;
David Blaikie33dd45d02015-03-23 18:39:02 +00001930 }
1931 if (Arch == Triple::x86_64) {
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001932 if (Size != 1 && Size != 2 && Size != 4 && Size != 0)
1933 return 0;
Kevin Enderbyd90a4172015-10-10 00:05:01 +00001934 if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
1935 // TODO:
1936 // Search the external relocation entries of a fully linked image
1937 // (if any) for an entry that matches this segment offset.
1938 // uint64_t seg_offset = (Pc + Offset);
1939 return 0;
1940 }
1941 // In MH_OBJECT filetypes search the section's relocation entries (if any)
1942 // for an entry for this section offset.
Rafael Espindola80291272014-10-08 15:28:58 +00001943 uint64_t sect_addr = info->S.getAddress();
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001944 uint64_t sect_offset = (Pc + Offset) - sect_addr;
1945 bool reloc_found = false;
1946 DataRefImpl Rel;
1947 MachO::any_relocation_info RE;
1948 bool isExtern = false;
1949 SymbolRef Symbol;
1950 for (const RelocationRef &Reloc : info->S.relocations()) {
Rafael Espindola96d071c2015-06-29 23:29:12 +00001951 uint64_t RelocOffset = Reloc.getOffset();
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001952 if (RelocOffset == sect_offset) {
1953 Rel = Reloc.getRawDataRefImpl();
1954 RE = info->O->getRelocation(Rel);
1955 // NOTE: Scattered relocations don't exist on x86_64.
1956 isExtern = info->O->getPlainRelocationExternal(RE);
1957 if (isExtern) {
1958 symbol_iterator RelocSym = Reloc.getSymbol();
1959 Symbol = *RelocSym;
1960 }
1961 reloc_found = true;
1962 break;
1963 }
1964 }
1965 if (reloc_found && isExtern) {
1966 // The Value passed in will be adjusted by the Pc if the instruction
1967 // adds the Pc. But for x86_64 external relocation entries the Value
1968 // is the offset from the external symbol.
1969 if (info->O->getAnyRelocationPCRel(RE))
1970 op_info->Value -= Pc + Offset + Size;
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00001971 Expected<StringRef> SymName = Symbol.getName();
1972 if (!SymName) {
1973 std::string Buf;
1974 raw_string_ostream OS(Buf);
1975 logAllUnhandledErrors(SymName.takeError(), OS, "");
1976 OS.flush();
1977 report_fatal_error(Buf);
1978 }
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00001979 const char *name = SymName->data();
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001980 unsigned Type = info->O->getAnyRelocationType(RE);
1981 if (Type == MachO::X86_64_RELOC_SUBTRACTOR) {
1982 DataRefImpl RelNext = Rel;
1983 info->O->moveRelocationNext(RelNext);
1984 MachO::any_relocation_info RENext = info->O->getRelocation(RelNext);
1985 unsigned TypeNext = info->O->getAnyRelocationType(RENext);
1986 bool isExternNext = info->O->getPlainRelocationExternal(RENext);
1987 unsigned SymbolNum = info->O->getPlainRelocationSymbolNum(RENext);
1988 if (TypeNext == MachO::X86_64_RELOC_UNSIGNED && isExternNext) {
1989 op_info->SubtractSymbol.Present = 1;
1990 op_info->SubtractSymbol.Name = name;
1991 symbol_iterator RelocSymNext = info->O->getSymbolByIndex(SymbolNum);
1992 Symbol = *RelocSymNext;
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00001993 Expected<StringRef> SymNameNext = Symbol.getName();
1994 if (!SymNameNext) {
1995 std::string Buf;
1996 raw_string_ostream OS(Buf);
1997 logAllUnhandledErrors(SymNameNext.takeError(), OS, "");
1998 OS.flush();
1999 report_fatal_error(Buf);
2000 }
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00002001 name = SymNameNext->data();
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002002 }
2003 }
2004 // TODO: add the VariantKinds to op_info->VariantKind for relocation types
2005 // like: X86_64_RELOC_TLV, X86_64_RELOC_GOT_LOAD and X86_64_RELOC_GOT.
2006 op_info->AddSymbol.Present = 1;
2007 op_info->AddSymbol.Name = name;
2008 return 1;
2009 }
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002010 return 0;
David Blaikie33dd45d02015-03-23 18:39:02 +00002011 }
2012 if (Arch == Triple::arm) {
Kevin Enderby930fdc72014-11-06 19:00:13 +00002013 if (Offset != 0 || (Size != 4 && Size != 2))
2014 return 0;
Kevin Enderbyd90a4172015-10-10 00:05:01 +00002015 if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
2016 // TODO:
2017 // Search the external relocation entries of a fully linked image
2018 // (if any) for an entry that matches this segment offset.
2019 // uint32_t seg_offset = (Pc + Offset);
2020 return 0;
2021 }
2022 // In MH_OBJECT filetypes search the section's relocation entries (if any)
2023 // for an entry for this section offset.
Kevin Enderby930fdc72014-11-06 19:00:13 +00002024 uint32_t sect_addr = info->S.getAddress();
2025 uint32_t sect_offset = (Pc + Offset) - sect_addr;
Kevin Enderby930fdc72014-11-06 19:00:13 +00002026 DataRefImpl Rel;
2027 MachO::any_relocation_info RE;
2028 bool isExtern = false;
2029 SymbolRef Symbol;
2030 bool r_scattered = false;
2031 uint32_t r_value, pair_r_value, r_type, r_length, other_half;
David Blaikie33dd45d02015-03-23 18:39:02 +00002032 auto Reloc =
2033 std::find_if(info->S.relocations().begin(), info->S.relocations().end(),
2034 [&](const RelocationRef &Reloc) {
Rafael Espindola96d071c2015-06-29 23:29:12 +00002035 uint64_t RelocOffset = Reloc.getOffset();
David Blaikie33dd45d02015-03-23 18:39:02 +00002036 return RelocOffset == sect_offset;
2037 });
2038
2039 if (Reloc == info->S.relocations().end())
2040 return 0;
2041
2042 Rel = Reloc->getRawDataRefImpl();
2043 RE = info->O->getRelocation(Rel);
2044 r_length = info->O->getAnyRelocationLength(RE);
2045 r_scattered = info->O->isRelocationScattered(RE);
2046 if (r_scattered) {
2047 r_value = info->O->getScatteredRelocationValue(RE);
2048 r_type = info->O->getScatteredRelocationType(RE);
2049 } else {
2050 r_type = info->O->getAnyRelocationType(RE);
2051 isExtern = info->O->getPlainRelocationExternal(RE);
2052 if (isExtern) {
2053 symbol_iterator RelocSym = Reloc->getSymbol();
2054 Symbol = *RelocSym;
Kevin Enderby930fdc72014-11-06 19:00:13 +00002055 }
2056 }
David Blaikie33dd45d02015-03-23 18:39:02 +00002057 if (r_type == MachO::ARM_RELOC_HALF ||
2058 r_type == MachO::ARM_RELOC_SECTDIFF ||
2059 r_type == MachO::ARM_RELOC_LOCAL_SECTDIFF ||
2060 r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
2061 DataRefImpl RelNext = Rel;
2062 info->O->moveRelocationNext(RelNext);
2063 MachO::any_relocation_info RENext;
2064 RENext = info->O->getRelocation(RelNext);
2065 other_half = info->O->getAnyRelocationAddress(RENext) & 0xffff;
2066 if (info->O->isRelocationScattered(RENext))
2067 pair_r_value = info->O->getScatteredRelocationValue(RENext);
2068 }
2069
2070 if (isExtern) {
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00002071 Expected<StringRef> SymName = Symbol.getName();
2072 if (!SymName) {
2073 std::string Buf;
2074 raw_string_ostream OS(Buf);
2075 logAllUnhandledErrors(SymName.takeError(), OS, "");
2076 OS.flush();
2077 report_fatal_error(Buf);
2078 }
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00002079 const char *name = SymName->data();
Kevin Enderby930fdc72014-11-06 19:00:13 +00002080 op_info->AddSymbol.Present = 1;
2081 op_info->AddSymbol.Name = name;
Sylvestre Ledru648cced2015-02-05 17:00:23 +00002082 switch (r_type) {
2083 case MachO::ARM_RELOC_HALF:
2084 if ((r_length & 0x1) == 1) {
2085 op_info->Value = value << 16 | other_half;
2086 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
2087 } else {
2088 op_info->Value = other_half << 16 | value;
2089 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
Sylvestre Ledrufe0c7ad2015-02-05 16:35:44 +00002090 }
Sylvestre Ledru648cced2015-02-05 17:00:23 +00002091 break;
2092 default:
2093 break;
Kevin Enderby930fdc72014-11-06 19:00:13 +00002094 }
2095 return 1;
2096 }
2097 // If we have a branch that is not an external relocation entry then
2098 // return 0 so the code in tryAddingSymbolicOperand() can use the
2099 // SymbolLookUp call back with the branch target address to look up the
2100 // symbol and possiblity add an annotation for a symbol stub.
David Blaikie33dd45d02015-03-23 18:39:02 +00002101 if (isExtern == 0 && (r_type == MachO::ARM_RELOC_BR24 ||
2102 r_type == MachO::ARM_THUMB_RELOC_BR22))
Kevin Enderby930fdc72014-11-06 19:00:13 +00002103 return 0;
2104
2105 uint32_t offset = 0;
David Blaikie33dd45d02015-03-23 18:39:02 +00002106 if (r_type == MachO::ARM_RELOC_HALF ||
2107 r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
2108 if ((r_length & 0x1) == 1)
2109 value = value << 16 | other_half;
2110 else
2111 value = other_half << 16 | value;
2112 }
2113 if (r_scattered && (r_type != MachO::ARM_RELOC_HALF &&
2114 r_type != MachO::ARM_RELOC_HALF_SECTDIFF)) {
2115 offset = value - r_value;
2116 value = r_value;
Kevin Enderby930fdc72014-11-06 19:00:13 +00002117 }
2118
David Blaikie33dd45d02015-03-23 18:39:02 +00002119 if (r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
Kevin Enderby930fdc72014-11-06 19:00:13 +00002120 if ((r_length & 0x1) == 1)
2121 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
2122 else
2123 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
Kevin Enderbyf6d25852015-01-31 00:37:11 +00002124 const char *add = GuessSymbolName(r_value, info->AddrMap);
2125 const char *sub = GuessSymbolName(pair_r_value, info->AddrMap);
Kevin Enderby930fdc72014-11-06 19:00:13 +00002126 int32_t offset = value - (r_value - pair_r_value);
2127 op_info->AddSymbol.Present = 1;
2128 if (add != nullptr)
2129 op_info->AddSymbol.Name = add;
2130 else
2131 op_info->AddSymbol.Value = r_value;
2132 op_info->SubtractSymbol.Present = 1;
2133 if (sub != nullptr)
2134 op_info->SubtractSymbol.Name = sub;
2135 else
2136 op_info->SubtractSymbol.Value = pair_r_value;
2137 op_info->Value = offset;
2138 return 1;
2139 }
2140
Kevin Enderby930fdc72014-11-06 19:00:13 +00002141 op_info->AddSymbol.Present = 1;
2142 op_info->Value = offset;
David Blaikie33dd45d02015-03-23 18:39:02 +00002143 if (r_type == MachO::ARM_RELOC_HALF) {
2144 if ((r_length & 0x1) == 1)
2145 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
2146 else
2147 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
Kevin Enderby930fdc72014-11-06 19:00:13 +00002148 }
Kevin Enderbyf6d25852015-01-31 00:37:11 +00002149 const char *add = GuessSymbolName(value, info->AddrMap);
Kevin Enderby930fdc72014-11-06 19:00:13 +00002150 if (add != nullptr) {
2151 op_info->AddSymbol.Name = add;
2152 return 1;
2153 }
2154 op_info->AddSymbol.Value = value;
2155 return 1;
David Blaikie33dd45d02015-03-23 18:39:02 +00002156 }
2157 if (Arch == Triple::aarch64) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002158 if (Offset != 0 || Size != 4)
2159 return 0;
Kevin Enderbyd90a4172015-10-10 00:05:01 +00002160 if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
2161 // TODO:
2162 // Search the external relocation entries of a fully linked image
2163 // (if any) for an entry that matches this segment offset.
2164 // uint64_t seg_offset = (Pc + Offset);
2165 return 0;
2166 }
2167 // In MH_OBJECT filetypes search the section's relocation entries (if any)
2168 // for an entry for this section offset.
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002169 uint64_t sect_addr = info->S.getAddress();
2170 uint64_t sect_offset = (Pc + Offset) - sect_addr;
David Blaikie33dd45d02015-03-23 18:39:02 +00002171 auto Reloc =
2172 std::find_if(info->S.relocations().begin(), info->S.relocations().end(),
2173 [&](const RelocationRef &Reloc) {
Rafael Espindola96d071c2015-06-29 23:29:12 +00002174 uint64_t RelocOffset = Reloc.getOffset();
David Blaikie33dd45d02015-03-23 18:39:02 +00002175 return RelocOffset == sect_offset;
2176 });
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002177
David Blaikie33dd45d02015-03-23 18:39:02 +00002178 if (Reloc == info->S.relocations().end())
2179 return 0;
2180
2181 DataRefImpl Rel = Reloc->getRawDataRefImpl();
2182 MachO::any_relocation_info RE = info->O->getRelocation(Rel);
2183 uint32_t r_type = info->O->getAnyRelocationType(RE);
2184 if (r_type == MachO::ARM64_RELOC_ADDEND) {
2185 DataRefImpl RelNext = Rel;
2186 info->O->moveRelocationNext(RelNext);
2187 MachO::any_relocation_info RENext = info->O->getRelocation(RelNext);
2188 if (value == 0) {
2189 value = info->O->getPlainRelocationSymbolNum(RENext);
2190 op_info->Value = value;
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002191 }
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002192 }
David Blaikie33dd45d02015-03-23 18:39:02 +00002193 // NOTE: Scattered relocations don't exist on arm64.
2194 if (!info->O->getPlainRelocationExternal(RE))
2195 return 0;
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00002196 Expected<StringRef> SymName = Reloc->getSymbol()->getName();
2197 if (!SymName) {
2198 std::string Buf;
2199 raw_string_ostream OS(Buf);
2200 logAllUnhandledErrors(SymName.takeError(), OS, "");
2201 OS.flush();
2202 report_fatal_error(Buf);
2203 }
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00002204 const char *name = SymName->data();
David Blaikie33dd45d02015-03-23 18:39:02 +00002205 op_info->AddSymbol.Present = 1;
2206 op_info->AddSymbol.Name = name;
2207
2208 switch (r_type) {
2209 case MachO::ARM64_RELOC_PAGE21:
2210 /* @page */
2211 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_PAGE;
2212 break;
2213 case MachO::ARM64_RELOC_PAGEOFF12:
2214 /* @pageoff */
2215 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_PAGEOFF;
2216 break;
2217 case MachO::ARM64_RELOC_GOT_LOAD_PAGE21:
2218 /* @gotpage */
2219 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_GOTPAGE;
2220 break;
2221 case MachO::ARM64_RELOC_GOT_LOAD_PAGEOFF12:
2222 /* @gotpageoff */
2223 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_GOTPAGEOFF;
2224 break;
2225 case MachO::ARM64_RELOC_TLVP_LOAD_PAGE21:
2226 /* @tvlppage is not implemented in llvm-mc */
2227 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_TLVP;
2228 break;
2229 case MachO::ARM64_RELOC_TLVP_LOAD_PAGEOFF12:
2230 /* @tvlppageoff is not implemented in llvm-mc */
2231 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_TLVOFF;
2232 break;
2233 default:
2234 case MachO::ARM64_RELOC_BRANCH26:
2235 op_info->VariantKind = LLVMDisassembler_VariantKind_None;
2236 break;
2237 }
2238 return 1;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002239 }
David Blaikie33dd45d02015-03-23 18:39:02 +00002240 return 0;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002241}
2242
Kevin Enderbybf246f52014-09-24 23:08:22 +00002243// GuessCstringPointer is passed the address of what might be a pointer to a
2244// literal string in a cstring section. If that address is in a cstring section
2245// it returns a pointer to that string. Else it returns nullptr.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00002246static const char *GuessCstringPointer(uint64_t ReferenceValue,
2247 struct DisassembleInfo *info) {
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00002248 for (const auto &Load : info->O->load_commands()) {
Kevin Enderbybf246f52014-09-24 23:08:22 +00002249 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
2250 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
2251 for (unsigned J = 0; J < Seg.nsects; ++J) {
2252 MachO::section_64 Sec = info->O->getSection64(Load, J);
2253 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
2254 if (section_type == MachO::S_CSTRING_LITERALS &&
2255 ReferenceValue >= Sec.addr &&
2256 ReferenceValue < Sec.addr + Sec.size) {
2257 uint64_t sect_offset = ReferenceValue - Sec.addr;
2258 uint64_t object_offset = Sec.offset + sect_offset;
2259 StringRef MachOContents = info->O->getData();
2260 uint64_t object_size = MachOContents.size();
2261 const char *object_addr = (const char *)MachOContents.data();
2262 if (object_offset < object_size) {
2263 const char *name = object_addr + object_offset;
2264 return name;
2265 } else {
2266 return nullptr;
2267 }
2268 }
2269 }
2270 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
2271 MachO::segment_command Seg = info->O->getSegmentLoadCommand(Load);
2272 for (unsigned J = 0; J < Seg.nsects; ++J) {
2273 MachO::section Sec = info->O->getSection(Load, J);
2274 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
2275 if (section_type == MachO::S_CSTRING_LITERALS &&
2276 ReferenceValue >= Sec.addr &&
2277 ReferenceValue < Sec.addr + Sec.size) {
2278 uint64_t sect_offset = ReferenceValue - Sec.addr;
2279 uint64_t object_offset = Sec.offset + sect_offset;
2280 StringRef MachOContents = info->O->getData();
2281 uint64_t object_size = MachOContents.size();
2282 const char *object_addr = (const char *)MachOContents.data();
2283 if (object_offset < object_size) {
2284 const char *name = object_addr + object_offset;
2285 return name;
2286 } else {
2287 return nullptr;
2288 }
2289 }
2290 }
2291 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00002292 }
2293 return nullptr;
2294}
2295
Kevin Enderby85974882014-09-26 22:20:44 +00002296// GuessIndirectSymbol returns the name of the indirect symbol for the
2297// ReferenceValue passed in or nullptr. This is used when ReferenceValue maybe
2298// an address of a symbol stub or a lazy or non-lazy pointer to associate the
2299// symbol name being referenced by the stub or pointer.
2300static const char *GuessIndirectSymbol(uint64_t ReferenceValue,
2301 struct DisassembleInfo *info) {
Kevin Enderby85974882014-09-26 22:20:44 +00002302 MachO::dysymtab_command Dysymtab = info->O->getDysymtabLoadCommand();
2303 MachO::symtab_command Symtab = info->O->getSymtabLoadCommand();
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00002304 for (const auto &Load : info->O->load_commands()) {
Kevin Enderby85974882014-09-26 22:20:44 +00002305 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
2306 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
2307 for (unsigned J = 0; J < Seg.nsects; ++J) {
2308 MachO::section_64 Sec = info->O->getSection64(Load, J);
2309 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
2310 if ((section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
2311 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
2312 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
2313 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
2314 section_type == MachO::S_SYMBOL_STUBS) &&
2315 ReferenceValue >= Sec.addr &&
2316 ReferenceValue < Sec.addr + Sec.size) {
2317 uint32_t stride;
2318 if (section_type == MachO::S_SYMBOL_STUBS)
2319 stride = Sec.reserved2;
2320 else
2321 stride = 8;
2322 if (stride == 0)
2323 return nullptr;
2324 uint32_t index = Sec.reserved1 + (ReferenceValue - Sec.addr) / stride;
2325 if (index < Dysymtab.nindirectsyms) {
2326 uint32_t indirect_symbol =
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002327 info->O->getIndirectSymbolTableEntry(Dysymtab, index);
Kevin Enderby85974882014-09-26 22:20:44 +00002328 if (indirect_symbol < Symtab.nsyms) {
2329 symbol_iterator Sym = info->O->getSymbolByIndex(indirect_symbol);
2330 SymbolRef Symbol = *Sym;
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00002331 Expected<StringRef> SymName = Symbol.getName();
2332 if (!SymName) {
2333 std::string Buf;
2334 raw_string_ostream OS(Buf);
2335 logAllUnhandledErrors(SymName.takeError(), OS, "");
2336 OS.flush();
2337 report_fatal_error(Buf);
2338 }
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00002339 const char *name = SymName->data();
Kevin Enderby85974882014-09-26 22:20:44 +00002340 return name;
2341 }
2342 }
2343 }
2344 }
2345 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
2346 MachO::segment_command Seg = info->O->getSegmentLoadCommand(Load);
2347 for (unsigned J = 0; J < Seg.nsects; ++J) {
2348 MachO::section Sec = info->O->getSection(Load, J);
2349 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
2350 if ((section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
2351 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
2352 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
2353 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
2354 section_type == MachO::S_SYMBOL_STUBS) &&
2355 ReferenceValue >= Sec.addr &&
2356 ReferenceValue < Sec.addr + Sec.size) {
2357 uint32_t stride;
2358 if (section_type == MachO::S_SYMBOL_STUBS)
2359 stride = Sec.reserved2;
2360 else
2361 stride = 4;
2362 if (stride == 0)
2363 return nullptr;
2364 uint32_t index = Sec.reserved1 + (ReferenceValue - Sec.addr) / stride;
2365 if (index < Dysymtab.nindirectsyms) {
2366 uint32_t indirect_symbol =
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002367 info->O->getIndirectSymbolTableEntry(Dysymtab, index);
Kevin Enderby85974882014-09-26 22:20:44 +00002368 if (indirect_symbol < Symtab.nsyms) {
2369 symbol_iterator Sym = info->O->getSymbolByIndex(indirect_symbol);
2370 SymbolRef Symbol = *Sym;
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00002371 Expected<StringRef> SymName = Symbol.getName();
2372 if (!SymName) {
2373 std::string Buf;
2374 raw_string_ostream OS(Buf);
2375 logAllUnhandledErrors(SymName.takeError(), OS, "");
2376 OS.flush();
2377 report_fatal_error(Buf);
2378 }
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00002379 const char *name = SymName->data();
Kevin Enderby85974882014-09-26 22:20:44 +00002380 return name;
2381 }
2382 }
2383 }
2384 }
2385 }
Kevin Enderby85974882014-09-26 22:20:44 +00002386 }
2387 return nullptr;
2388}
2389
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002390// method_reference() is called passing it the ReferenceName that might be
2391// a reference it to an Objective-C method call. If so then it allocates and
2392// assembles a method call string with the values last seen and saved in
2393// the DisassembleInfo's class_name and selector_name fields. This is saved
2394// into the method field of the info and any previous string is free'ed.
2395// Then the class_name field in the info is set to nullptr. The method call
2396// string is set into ReferenceName and ReferenceType is set to
2397// LLVMDisassembler_ReferenceType_Out_Objc_Message. If this not a method call
2398// then both ReferenceType and ReferenceName are left unchanged.
2399static void method_reference(struct DisassembleInfo *info,
2400 uint64_t *ReferenceType,
2401 const char **ReferenceName) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002402 unsigned int Arch = info->O->getArch();
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002403 if (*ReferenceName != nullptr) {
2404 if (strcmp(*ReferenceName, "_objc_msgSend") == 0) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002405 if (info->selector_name != nullptr) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002406 if (info->method != nullptr)
2407 free(info->method);
2408 if (info->class_name != nullptr) {
2409 info->method = (char *)malloc(5 + strlen(info->class_name) +
2410 strlen(info->selector_name));
2411 if (info->method != nullptr) {
2412 strcpy(info->method, "+[");
2413 strcat(info->method, info->class_name);
2414 strcat(info->method, " ");
2415 strcat(info->method, info->selector_name);
2416 strcat(info->method, "]");
2417 *ReferenceName = info->method;
2418 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
2419 }
2420 } else {
2421 info->method = (char *)malloc(9 + strlen(info->selector_name));
2422 if (info->method != nullptr) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002423 if (Arch == Triple::x86_64)
2424 strcpy(info->method, "-[%rdi ");
2425 else if (Arch == Triple::aarch64)
2426 strcpy(info->method, "-[x0 ");
2427 else
2428 strcpy(info->method, "-[r? ");
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002429 strcat(info->method, info->selector_name);
2430 strcat(info->method, "]");
2431 *ReferenceName = info->method;
2432 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
2433 }
2434 }
2435 info->class_name = nullptr;
2436 }
2437 } else if (strcmp(*ReferenceName, "_objc_msgSendSuper2") == 0) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002438 if (info->selector_name != nullptr) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002439 if (info->method != nullptr)
2440 free(info->method);
2441 info->method = (char *)malloc(17 + strlen(info->selector_name));
2442 if (info->method != nullptr) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002443 if (Arch == Triple::x86_64)
2444 strcpy(info->method, "-[[%rdi super] ");
2445 else if (Arch == Triple::aarch64)
2446 strcpy(info->method, "-[[x0 super] ");
2447 else
2448 strcpy(info->method, "-[[r? super] ");
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002449 strcat(info->method, info->selector_name);
2450 strcat(info->method, "]");
2451 *ReferenceName = info->method;
2452 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
2453 }
2454 info->class_name = nullptr;
2455 }
2456 }
2457 }
2458}
2459
2460// GuessPointerPointer() is passed the address of what might be a pointer to
2461// a reference to an Objective-C class, selector, message ref or cfstring.
2462// If so the value of the pointer is returned and one of the booleans are set
2463// to true. If not zero is returned and all the booleans are set to false.
2464static uint64_t GuessPointerPointer(uint64_t ReferenceValue,
2465 struct DisassembleInfo *info,
2466 bool &classref, bool &selref, bool &msgref,
2467 bool &cfstring) {
2468 classref = false;
2469 selref = false;
2470 msgref = false;
2471 cfstring = false;
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00002472 for (const auto &Load : info->O->load_commands()) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002473 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
2474 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
2475 for (unsigned J = 0; J < Seg.nsects; ++J) {
2476 MachO::section_64 Sec = info->O->getSection64(Load, J);
2477 if ((strncmp(Sec.sectname, "__objc_selrefs", 16) == 0 ||
2478 strncmp(Sec.sectname, "__objc_classrefs", 16) == 0 ||
2479 strncmp(Sec.sectname, "__objc_superrefs", 16) == 0 ||
2480 strncmp(Sec.sectname, "__objc_msgrefs", 16) == 0 ||
2481 strncmp(Sec.sectname, "__cfstring", 16) == 0) &&
2482 ReferenceValue >= Sec.addr &&
2483 ReferenceValue < Sec.addr + Sec.size) {
2484 uint64_t sect_offset = ReferenceValue - Sec.addr;
2485 uint64_t object_offset = Sec.offset + sect_offset;
2486 StringRef MachOContents = info->O->getData();
2487 uint64_t object_size = MachOContents.size();
2488 const char *object_addr = (const char *)MachOContents.data();
2489 if (object_offset < object_size) {
2490 uint64_t pointer_value;
2491 memcpy(&pointer_value, object_addr + object_offset,
2492 sizeof(uint64_t));
2493 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
2494 sys::swapByteOrder(pointer_value);
2495 if (strncmp(Sec.sectname, "__objc_selrefs", 16) == 0)
2496 selref = true;
2497 else if (strncmp(Sec.sectname, "__objc_classrefs", 16) == 0 ||
2498 strncmp(Sec.sectname, "__objc_superrefs", 16) == 0)
2499 classref = true;
2500 else if (strncmp(Sec.sectname, "__objc_msgrefs", 16) == 0 &&
2501 ReferenceValue + 8 < Sec.addr + Sec.size) {
2502 msgref = true;
2503 memcpy(&pointer_value, object_addr + object_offset + 8,
2504 sizeof(uint64_t));
2505 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
2506 sys::swapByteOrder(pointer_value);
2507 } else if (strncmp(Sec.sectname, "__cfstring", 16) == 0)
2508 cfstring = true;
2509 return pointer_value;
2510 } else {
2511 return 0;
2512 }
2513 }
2514 }
2515 }
2516 // TODO: Look for LC_SEGMENT for 32-bit Mach-O files.
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002517 }
2518 return 0;
2519}
2520
2521// get_pointer_64 returns a pointer to the bytes in the object file at the
2522// Address from a section in the Mach-O file. And indirectly returns the
2523// offset into the section, number of bytes left in the section past the offset
2524// and which section is was being referenced. If the Address is not in a
2525// section nullptr is returned.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00002526static const char *get_pointer_64(uint64_t Address, uint32_t &offset,
2527 uint32_t &left, SectionRef &S,
Kevin Enderby846c0002015-04-16 17:19:59 +00002528 DisassembleInfo *info,
2529 bool objc_only = false) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002530 offset = 0;
2531 left = 0;
2532 S = SectionRef();
2533 for (unsigned SectIdx = 0; SectIdx != info->Sections->size(); SectIdx++) {
2534 uint64_t SectAddress = ((*(info->Sections))[SectIdx]).getAddress();
2535 uint64_t SectSize = ((*(info->Sections))[SectIdx]).getSize();
Kevin Enderby46e642f2015-10-08 22:50:55 +00002536 if (SectSize == 0)
2537 continue;
Kevin Enderby846c0002015-04-16 17:19:59 +00002538 if (objc_only) {
2539 StringRef SectName;
2540 ((*(info->Sections))[SectIdx]).getName(SectName);
2541 DataRefImpl Ref = ((*(info->Sections))[SectIdx]).getRawDataRefImpl();
2542 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
2543 if (SegName != "__OBJC" && SectName != "__cstring")
2544 continue;
2545 }
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002546 if (Address >= SectAddress && Address < SectAddress + SectSize) {
2547 S = (*(info->Sections))[SectIdx];
2548 offset = Address - SectAddress;
2549 left = SectSize - offset;
2550 StringRef SectContents;
2551 ((*(info->Sections))[SectIdx]).getContents(SectContents);
2552 return SectContents.data() + offset;
2553 }
2554 }
2555 return nullptr;
2556}
2557
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002558static const char *get_pointer_32(uint32_t Address, uint32_t &offset,
2559 uint32_t &left, SectionRef &S,
Kevin Enderby846c0002015-04-16 17:19:59 +00002560 DisassembleInfo *info,
2561 bool objc_only = false) {
2562 return get_pointer_64(Address, offset, left, S, info, objc_only);
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002563}
2564
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002565// get_symbol_64() returns the name of a symbol (or nullptr) and the address of
2566// the symbol indirectly through n_value. Based on the relocation information
2567// for the specified section offset in the specified section reference.
Kevin Enderby0fc11822015-04-01 20:57:01 +00002568// If no relocation information is found and a non-zero ReferenceValue for the
2569// symbol is passed, look up that address in the info's AddrMap.
Rafael Espindolad7a32ea2015-06-24 10:20:30 +00002570static const char *get_symbol_64(uint32_t sect_offset, SectionRef S,
2571 DisassembleInfo *info, uint64_t &n_value,
Rafael Espindolabe8b0ea2015-07-07 17:12:59 +00002572 uint64_t ReferenceValue = 0) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002573 n_value = 0;
David Blaikie33dd45d02015-03-23 18:39:02 +00002574 if (!info->verbose)
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002575 return nullptr;
2576
2577 // See if there is an external relocation entry at the sect_offset.
2578 bool reloc_found = false;
2579 DataRefImpl Rel;
2580 MachO::any_relocation_info RE;
2581 bool isExtern = false;
2582 SymbolRef Symbol;
2583 for (const RelocationRef &Reloc : S.relocations()) {
Rafael Espindola96d071c2015-06-29 23:29:12 +00002584 uint64_t RelocOffset = Reloc.getOffset();
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002585 if (RelocOffset == sect_offset) {
2586 Rel = Reloc.getRawDataRefImpl();
2587 RE = info->O->getRelocation(Rel);
2588 if (info->O->isRelocationScattered(RE))
2589 continue;
2590 isExtern = info->O->getPlainRelocationExternal(RE);
2591 if (isExtern) {
2592 symbol_iterator RelocSym = Reloc.getSymbol();
2593 Symbol = *RelocSym;
2594 }
2595 reloc_found = true;
2596 break;
2597 }
2598 }
2599 // If there is an external relocation entry for a symbol in this section
2600 // at this section_offset then use that symbol's value for the n_value
2601 // and return its name.
2602 const char *SymbolName = nullptr;
2603 if (reloc_found && isExtern) {
Rafael Espindoladea00162015-07-03 17:44:18 +00002604 n_value = Symbol.getValue();
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00002605 Expected<StringRef> NameOrError = Symbol.getName();
2606 if (!NameOrError) {
2607 std::string Buf;
2608 raw_string_ostream OS(Buf);
2609 logAllUnhandledErrors(NameOrError.takeError(), OS, "");
2610 OS.flush();
2611 report_fatal_error(Buf);
2612 }
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00002613 StringRef Name = *NameOrError;
2614 if (!Name.empty()) {
2615 SymbolName = Name.data();
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002616 return SymbolName;
2617 }
2618 }
2619
2620 // TODO: For fully linked images, look through the external relocation
2621 // entries off the dynamic symtab command. For these the r_offset is from the
2622 // start of the first writeable segment in the Mach-O file. So the offset
2623 // to this section from that segment is passed to this routine by the caller,
2624 // as the database_offset. Which is the difference of the section's starting
2625 // address and the first writable segment.
2626 //
2627 // NOTE: need add passing the database_offset to this routine.
2628
Kevin Enderby0fc11822015-04-01 20:57:01 +00002629 // We did not find an external relocation entry so look up the ReferenceValue
2630 // as an address of a symbol and if found return that symbol's name.
Rafael Espindolabe8b0ea2015-07-07 17:12:59 +00002631 SymbolName = GuessSymbolName(ReferenceValue, info->AddrMap);
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002632
2633 return SymbolName;
2634}
2635
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002636static const char *get_symbol_32(uint32_t sect_offset, SectionRef S,
2637 DisassembleInfo *info,
2638 uint32_t ReferenceValue) {
2639 uint64_t n_value64;
2640 return get_symbol_64(sect_offset, S, info, n_value64, ReferenceValue);
2641}
2642
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002643// These are structs in the Objective-C meta data and read to produce the
2644// comments for disassembly. While these are part of the ABI they are no
2645// public defintions. So the are here not in include/llvm/Support/MachO.h .
2646
2647// The cfstring object in a 64-bit Mach-O file.
2648struct cfstring64_t {
2649 uint64_t isa; // class64_t * (64-bit pointer)
2650 uint64_t flags; // flag bits
2651 uint64_t characters; // char * (64-bit pointer)
2652 uint64_t length; // number of non-NULL characters in above
2653};
2654
2655// The class object in a 64-bit Mach-O file.
2656struct class64_t {
2657 uint64_t isa; // class64_t * (64-bit pointer)
2658 uint64_t superclass; // class64_t * (64-bit pointer)
2659 uint64_t cache; // Cache (64-bit pointer)
2660 uint64_t vtable; // IMP * (64-bit pointer)
2661 uint64_t data; // class_ro64_t * (64-bit pointer)
2662};
2663
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002664struct class32_t {
2665 uint32_t isa; /* class32_t * (32-bit pointer) */
2666 uint32_t superclass; /* class32_t * (32-bit pointer) */
2667 uint32_t cache; /* Cache (32-bit pointer) */
2668 uint32_t vtable; /* IMP * (32-bit pointer) */
2669 uint32_t data; /* class_ro32_t * (32-bit pointer) */
2670};
2671
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002672struct class_ro64_t {
2673 uint32_t flags;
2674 uint32_t instanceStart;
2675 uint32_t instanceSize;
2676 uint32_t reserved;
2677 uint64_t ivarLayout; // const uint8_t * (64-bit pointer)
2678 uint64_t name; // const char * (64-bit pointer)
2679 uint64_t baseMethods; // const method_list_t * (64-bit pointer)
2680 uint64_t baseProtocols; // const protocol_list_t * (64-bit pointer)
2681 uint64_t ivars; // const ivar_list_t * (64-bit pointer)
2682 uint64_t weakIvarLayout; // const uint8_t * (64-bit pointer)
2683 uint64_t baseProperties; // const struct objc_property_list (64-bit pointer)
2684};
2685
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002686struct class_ro32_t {
2687 uint32_t flags;
2688 uint32_t instanceStart;
2689 uint32_t instanceSize;
2690 uint32_t ivarLayout; /* const uint8_t * (32-bit pointer) */
2691 uint32_t name; /* const char * (32-bit pointer) */
2692 uint32_t baseMethods; /* const method_list_t * (32-bit pointer) */
2693 uint32_t baseProtocols; /* const protocol_list_t * (32-bit pointer) */
2694 uint32_t ivars; /* const ivar_list_t * (32-bit pointer) */
2695 uint32_t weakIvarLayout; /* const uint8_t * (32-bit pointer) */
2696 uint32_t baseProperties; /* const struct objc_property_list *
2697 (32-bit pointer) */
2698};
2699
2700/* Values for class_ro{64,32}_t->flags */
Kevin Enderby0fc11822015-04-01 20:57:01 +00002701#define RO_META (1 << 0)
2702#define RO_ROOT (1 << 1)
2703#define RO_HAS_CXX_STRUCTORS (1 << 2)
2704
2705struct method_list64_t {
2706 uint32_t entsize;
2707 uint32_t count;
2708 /* struct method64_t first; These structures follow inline */
2709};
2710
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002711struct method_list32_t {
2712 uint32_t entsize;
2713 uint32_t count;
2714 /* struct method32_t first; These structures follow inline */
2715};
2716
Kevin Enderby0fc11822015-04-01 20:57:01 +00002717struct method64_t {
2718 uint64_t name; /* SEL (64-bit pointer) */
2719 uint64_t types; /* const char * (64-bit pointer) */
2720 uint64_t imp; /* IMP (64-bit pointer) */
2721};
2722
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002723struct method32_t {
2724 uint32_t name; /* SEL (32-bit pointer) */
2725 uint32_t types; /* const char * (32-bit pointer) */
2726 uint32_t imp; /* IMP (32-bit pointer) */
2727};
2728
Kevin Enderby0fc11822015-04-01 20:57:01 +00002729struct protocol_list64_t {
2730 uint64_t count; /* uintptr_t (a 64-bit value) */
2731 /* struct protocol64_t * list[0]; These pointers follow inline */
2732};
2733
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002734struct protocol_list32_t {
2735 uint32_t count; /* uintptr_t (a 32-bit value) */
2736 /* struct protocol32_t * list[0]; These pointers follow inline */
2737};
2738
Kevin Enderby0fc11822015-04-01 20:57:01 +00002739struct protocol64_t {
2740 uint64_t isa; /* id * (64-bit pointer) */
2741 uint64_t name; /* const char * (64-bit pointer) */
2742 uint64_t protocols; /* struct protocol_list64_t *
2743 (64-bit pointer) */
2744 uint64_t instanceMethods; /* method_list_t * (64-bit pointer) */
2745 uint64_t classMethods; /* method_list_t * (64-bit pointer) */
2746 uint64_t optionalInstanceMethods; /* method_list_t * (64-bit pointer) */
2747 uint64_t optionalClassMethods; /* method_list_t * (64-bit pointer) */
2748 uint64_t instanceProperties; /* struct objc_property_list *
2749 (64-bit pointer) */
2750};
2751
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002752struct protocol32_t {
2753 uint32_t isa; /* id * (32-bit pointer) */
2754 uint32_t name; /* const char * (32-bit pointer) */
2755 uint32_t protocols; /* struct protocol_list_t *
2756 (32-bit pointer) */
2757 uint32_t instanceMethods; /* method_list_t * (32-bit pointer) */
2758 uint32_t classMethods; /* method_list_t * (32-bit pointer) */
2759 uint32_t optionalInstanceMethods; /* method_list_t * (32-bit pointer) */
2760 uint32_t optionalClassMethods; /* method_list_t * (32-bit pointer) */
2761 uint32_t instanceProperties; /* struct objc_property_list *
2762 (32-bit pointer) */
2763};
2764
Kevin Enderby0fc11822015-04-01 20:57:01 +00002765struct ivar_list64_t {
2766 uint32_t entsize;
2767 uint32_t count;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002768 /* struct ivar64_t first; These structures follow inline */
2769};
2770
2771struct ivar_list32_t {
2772 uint32_t entsize;
2773 uint32_t count;
2774 /* struct ivar32_t first; These structures follow inline */
Kevin Enderby0fc11822015-04-01 20:57:01 +00002775};
2776
2777struct ivar64_t {
2778 uint64_t offset; /* uintptr_t * (64-bit pointer) */
2779 uint64_t name; /* const char * (64-bit pointer) */
2780 uint64_t type; /* const char * (64-bit pointer) */
2781 uint32_t alignment;
2782 uint32_t size;
2783};
2784
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002785struct ivar32_t {
2786 uint32_t offset; /* uintptr_t * (32-bit pointer) */
2787 uint32_t name; /* const char * (32-bit pointer) */
2788 uint32_t type; /* const char * (32-bit pointer) */
2789 uint32_t alignment;
2790 uint32_t size;
2791};
2792
Kevin Enderby0fc11822015-04-01 20:57:01 +00002793struct objc_property_list64 {
2794 uint32_t entsize;
2795 uint32_t count;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002796 /* struct objc_property64 first; These structures follow inline */
2797};
2798
2799struct objc_property_list32 {
2800 uint32_t entsize;
2801 uint32_t count;
2802 /* struct objc_property32 first; These structures follow inline */
Kevin Enderby0fc11822015-04-01 20:57:01 +00002803};
2804
2805struct objc_property64 {
2806 uint64_t name; /* const char * (64-bit pointer) */
2807 uint64_t attributes; /* const char * (64-bit pointer) */
2808};
2809
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002810struct objc_property32 {
2811 uint32_t name; /* const char * (32-bit pointer) */
2812 uint32_t attributes; /* const char * (32-bit pointer) */
2813};
2814
Kevin Enderby0fc11822015-04-01 20:57:01 +00002815struct category64_t {
2816 uint64_t name; /* const char * (64-bit pointer) */
2817 uint64_t cls; /* struct class_t * (64-bit pointer) */
2818 uint64_t instanceMethods; /* struct method_list_t * (64-bit pointer) */
2819 uint64_t classMethods; /* struct method_list_t * (64-bit pointer) */
2820 uint64_t protocols; /* struct protocol_list_t * (64-bit pointer) */
2821 uint64_t instanceProperties; /* struct objc_property_list *
2822 (64-bit pointer) */
2823};
2824
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002825struct category32_t {
2826 uint32_t name; /* const char * (32-bit pointer) */
2827 uint32_t cls; /* struct class_t * (32-bit pointer) */
2828 uint32_t instanceMethods; /* struct method_list_t * (32-bit pointer) */
2829 uint32_t classMethods; /* struct method_list_t * (32-bit pointer) */
2830 uint32_t protocols; /* struct protocol_list_t * (32-bit pointer) */
2831 uint32_t instanceProperties; /* struct objc_property_list *
2832 (32-bit pointer) */
2833};
2834
Kevin Enderby0fc11822015-04-01 20:57:01 +00002835struct objc_image_info64 {
2836 uint32_t version;
2837 uint32_t flags;
2838};
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002839struct objc_image_info32 {
2840 uint32_t version;
2841 uint32_t flags;
2842};
Kevin Enderby846c0002015-04-16 17:19:59 +00002843struct imageInfo_t {
2844 uint32_t version;
2845 uint32_t flags;
2846};
Kevin Enderby0fc11822015-04-01 20:57:01 +00002847/* masks for objc_image_info.flags */
2848#define OBJC_IMAGE_IS_REPLACEMENT (1 << 0)
2849#define OBJC_IMAGE_SUPPORTS_GC (1 << 1)
2850
2851struct message_ref64 {
2852 uint64_t imp; /* IMP (64-bit pointer) */
2853 uint64_t sel; /* SEL (64-bit pointer) */
2854};
2855
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002856struct message_ref32 {
2857 uint32_t imp; /* IMP (32-bit pointer) */
2858 uint32_t sel; /* SEL (32-bit pointer) */
2859};
2860
Kevin Enderby846c0002015-04-16 17:19:59 +00002861// Objective-C 1 (32-bit only) meta data structs.
2862
2863struct objc_module_t {
2864 uint32_t version;
2865 uint32_t size;
2866 uint32_t name; /* char * (32-bit pointer) */
2867 uint32_t symtab; /* struct objc_symtab * (32-bit pointer) */
2868};
2869
2870struct objc_symtab_t {
2871 uint32_t sel_ref_cnt;
2872 uint32_t refs; /* SEL * (32-bit pointer) */
2873 uint16_t cls_def_cnt;
2874 uint16_t cat_def_cnt;
2875 // uint32_t defs[1]; /* void * (32-bit pointer) variable size */
2876};
2877
2878struct objc_class_t {
2879 uint32_t isa; /* struct objc_class * (32-bit pointer) */
2880 uint32_t super_class; /* struct objc_class * (32-bit pointer) */
2881 uint32_t name; /* const char * (32-bit pointer) */
2882 int32_t version;
2883 int32_t info;
2884 int32_t instance_size;
2885 uint32_t ivars; /* struct objc_ivar_list * (32-bit pointer) */
2886 uint32_t methodLists; /* struct objc_method_list ** (32-bit pointer) */
2887 uint32_t cache; /* struct objc_cache * (32-bit pointer) */
2888 uint32_t protocols; /* struct objc_protocol_list * (32-bit pointer) */
2889};
2890
2891#define CLS_GETINFO(cls, infomask) ((cls)->info & (infomask))
2892// class is not a metaclass
2893#define CLS_CLASS 0x1
2894// class is a metaclass
2895#define CLS_META 0x2
2896
2897struct objc_category_t {
2898 uint32_t category_name; /* char * (32-bit pointer) */
2899 uint32_t class_name; /* char * (32-bit pointer) */
2900 uint32_t instance_methods; /* struct objc_method_list * (32-bit pointer) */
2901 uint32_t class_methods; /* struct objc_method_list * (32-bit pointer) */
2902 uint32_t protocols; /* struct objc_protocol_list * (32-bit ptr) */
2903};
2904
2905struct objc_ivar_t {
2906 uint32_t ivar_name; /* char * (32-bit pointer) */
2907 uint32_t ivar_type; /* char * (32-bit pointer) */
2908 int32_t ivar_offset;
2909};
2910
2911struct objc_ivar_list_t {
2912 int32_t ivar_count;
2913 // struct objc_ivar_t ivar_list[1]; /* variable length structure */
2914};
2915
2916struct objc_method_list_t {
2917 uint32_t obsolete; /* struct objc_method_list * (32-bit pointer) */
2918 int32_t method_count;
2919 // struct objc_method_t method_list[1]; /* variable length structure */
2920};
2921
2922struct objc_method_t {
2923 uint32_t method_name; /* SEL, aka struct objc_selector * (32-bit pointer) */
2924 uint32_t method_types; /* char * (32-bit pointer) */
2925 uint32_t method_imp; /* IMP, aka function pointer, (*IMP)(id, SEL, ...)
2926 (32-bit pointer) */
2927};
2928
2929struct objc_protocol_list_t {
2930 uint32_t next; /* struct objc_protocol_list * (32-bit pointer) */
2931 int32_t count;
2932 // uint32_t list[1]; /* Protocol *, aka struct objc_protocol_t *
2933 // (32-bit pointer) */
2934};
2935
2936struct objc_protocol_t {
2937 uint32_t isa; /* struct objc_class * (32-bit pointer) */
2938 uint32_t protocol_name; /* char * (32-bit pointer) */
2939 uint32_t protocol_list; /* struct objc_protocol_list * (32-bit pointer) */
2940 uint32_t instance_methods; /* struct objc_method_description_list *
2941 (32-bit pointer) */
2942 uint32_t class_methods; /* struct objc_method_description_list *
2943 (32-bit pointer) */
2944};
2945
2946struct objc_method_description_list_t {
2947 int32_t count;
2948 // struct objc_method_description_t list[1];
2949};
2950
2951struct objc_method_description_t {
2952 uint32_t name; /* SEL, aka struct objc_selector * (32-bit pointer) */
2953 uint32_t types; /* char * (32-bit pointer) */
2954};
2955
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002956inline void swapStruct(struct cfstring64_t &cfs) {
2957 sys::swapByteOrder(cfs.isa);
2958 sys::swapByteOrder(cfs.flags);
2959 sys::swapByteOrder(cfs.characters);
2960 sys::swapByteOrder(cfs.length);
2961}
2962
2963inline void swapStruct(struct class64_t &c) {
2964 sys::swapByteOrder(c.isa);
2965 sys::swapByteOrder(c.superclass);
2966 sys::swapByteOrder(c.cache);
2967 sys::swapByteOrder(c.vtable);
2968 sys::swapByteOrder(c.data);
2969}
2970
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002971inline void swapStruct(struct class32_t &c) {
2972 sys::swapByteOrder(c.isa);
2973 sys::swapByteOrder(c.superclass);
2974 sys::swapByteOrder(c.cache);
2975 sys::swapByteOrder(c.vtable);
2976 sys::swapByteOrder(c.data);
2977}
2978
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002979inline void swapStruct(struct class_ro64_t &cro) {
2980 sys::swapByteOrder(cro.flags);
2981 sys::swapByteOrder(cro.instanceStart);
2982 sys::swapByteOrder(cro.instanceSize);
2983 sys::swapByteOrder(cro.reserved);
2984 sys::swapByteOrder(cro.ivarLayout);
2985 sys::swapByteOrder(cro.name);
2986 sys::swapByteOrder(cro.baseMethods);
2987 sys::swapByteOrder(cro.baseProtocols);
2988 sys::swapByteOrder(cro.ivars);
2989 sys::swapByteOrder(cro.weakIvarLayout);
2990 sys::swapByteOrder(cro.baseProperties);
2991}
2992
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002993inline void swapStruct(struct class_ro32_t &cro) {
2994 sys::swapByteOrder(cro.flags);
2995 sys::swapByteOrder(cro.instanceStart);
2996 sys::swapByteOrder(cro.instanceSize);
2997 sys::swapByteOrder(cro.ivarLayout);
2998 sys::swapByteOrder(cro.name);
2999 sys::swapByteOrder(cro.baseMethods);
3000 sys::swapByteOrder(cro.baseProtocols);
3001 sys::swapByteOrder(cro.ivars);
3002 sys::swapByteOrder(cro.weakIvarLayout);
3003 sys::swapByteOrder(cro.baseProperties);
3004}
3005
Kevin Enderby0fc11822015-04-01 20:57:01 +00003006inline void swapStruct(struct method_list64_t &ml) {
3007 sys::swapByteOrder(ml.entsize);
3008 sys::swapByteOrder(ml.count);
3009}
3010
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003011inline void swapStruct(struct method_list32_t &ml) {
3012 sys::swapByteOrder(ml.entsize);
3013 sys::swapByteOrder(ml.count);
3014}
3015
Kevin Enderby0fc11822015-04-01 20:57:01 +00003016inline void swapStruct(struct method64_t &m) {
3017 sys::swapByteOrder(m.name);
3018 sys::swapByteOrder(m.types);
3019 sys::swapByteOrder(m.imp);
3020}
3021
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003022inline void swapStruct(struct method32_t &m) {
3023 sys::swapByteOrder(m.name);
3024 sys::swapByteOrder(m.types);
3025 sys::swapByteOrder(m.imp);
3026}
3027
Kevin Enderby0fc11822015-04-01 20:57:01 +00003028inline void swapStruct(struct protocol_list64_t &pl) {
3029 sys::swapByteOrder(pl.count);
3030}
3031
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003032inline void swapStruct(struct protocol_list32_t &pl) {
3033 sys::swapByteOrder(pl.count);
3034}
3035
Kevin Enderby0fc11822015-04-01 20:57:01 +00003036inline void swapStruct(struct protocol64_t &p) {
3037 sys::swapByteOrder(p.isa);
3038 sys::swapByteOrder(p.name);
3039 sys::swapByteOrder(p.protocols);
3040 sys::swapByteOrder(p.instanceMethods);
3041 sys::swapByteOrder(p.classMethods);
3042 sys::swapByteOrder(p.optionalInstanceMethods);
3043 sys::swapByteOrder(p.optionalClassMethods);
3044 sys::swapByteOrder(p.instanceProperties);
3045}
3046
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003047inline void swapStruct(struct protocol32_t &p) {
3048 sys::swapByteOrder(p.isa);
3049 sys::swapByteOrder(p.name);
3050 sys::swapByteOrder(p.protocols);
3051 sys::swapByteOrder(p.instanceMethods);
3052 sys::swapByteOrder(p.classMethods);
3053 sys::swapByteOrder(p.optionalInstanceMethods);
3054 sys::swapByteOrder(p.optionalClassMethods);
3055 sys::swapByteOrder(p.instanceProperties);
3056}
3057
Kevin Enderby0fc11822015-04-01 20:57:01 +00003058inline void swapStruct(struct ivar_list64_t &il) {
3059 sys::swapByteOrder(il.entsize);
3060 sys::swapByteOrder(il.count);
3061}
3062
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003063inline void swapStruct(struct ivar_list32_t &il) {
3064 sys::swapByteOrder(il.entsize);
3065 sys::swapByteOrder(il.count);
3066}
3067
Kevin Enderby0fc11822015-04-01 20:57:01 +00003068inline void swapStruct(struct ivar64_t &i) {
3069 sys::swapByteOrder(i.offset);
3070 sys::swapByteOrder(i.name);
3071 sys::swapByteOrder(i.type);
3072 sys::swapByteOrder(i.alignment);
3073 sys::swapByteOrder(i.size);
3074}
3075
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003076inline void swapStruct(struct ivar32_t &i) {
3077 sys::swapByteOrder(i.offset);
3078 sys::swapByteOrder(i.name);
3079 sys::swapByteOrder(i.type);
3080 sys::swapByteOrder(i.alignment);
3081 sys::swapByteOrder(i.size);
3082}
3083
Kevin Enderby0fc11822015-04-01 20:57:01 +00003084inline void swapStruct(struct objc_property_list64 &pl) {
3085 sys::swapByteOrder(pl.entsize);
3086 sys::swapByteOrder(pl.count);
3087}
3088
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003089inline void swapStruct(struct objc_property_list32 &pl) {
3090 sys::swapByteOrder(pl.entsize);
3091 sys::swapByteOrder(pl.count);
3092}
3093
Kevin Enderby0fc11822015-04-01 20:57:01 +00003094inline void swapStruct(struct objc_property64 &op) {
3095 sys::swapByteOrder(op.name);
3096 sys::swapByteOrder(op.attributes);
3097}
3098
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003099inline void swapStruct(struct objc_property32 &op) {
3100 sys::swapByteOrder(op.name);
3101 sys::swapByteOrder(op.attributes);
3102}
3103
Kevin Enderby0fc11822015-04-01 20:57:01 +00003104inline void swapStruct(struct category64_t &c) {
3105 sys::swapByteOrder(c.name);
3106 sys::swapByteOrder(c.cls);
3107 sys::swapByteOrder(c.instanceMethods);
3108 sys::swapByteOrder(c.classMethods);
3109 sys::swapByteOrder(c.protocols);
3110 sys::swapByteOrder(c.instanceProperties);
3111}
3112
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003113inline void swapStruct(struct category32_t &c) {
3114 sys::swapByteOrder(c.name);
3115 sys::swapByteOrder(c.cls);
3116 sys::swapByteOrder(c.instanceMethods);
3117 sys::swapByteOrder(c.classMethods);
3118 sys::swapByteOrder(c.protocols);
3119 sys::swapByteOrder(c.instanceProperties);
3120}
3121
Kevin Enderby0fc11822015-04-01 20:57:01 +00003122inline void swapStruct(struct objc_image_info64 &o) {
3123 sys::swapByteOrder(o.version);
3124 sys::swapByteOrder(o.flags);
3125}
3126
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003127inline void swapStruct(struct objc_image_info32 &o) {
3128 sys::swapByteOrder(o.version);
3129 sys::swapByteOrder(o.flags);
3130}
3131
Kevin Enderby846c0002015-04-16 17:19:59 +00003132inline void swapStruct(struct imageInfo_t &o) {
3133 sys::swapByteOrder(o.version);
3134 sys::swapByteOrder(o.flags);
3135}
3136
Kevin Enderby0fc11822015-04-01 20:57:01 +00003137inline void swapStruct(struct message_ref64 &mr) {
3138 sys::swapByteOrder(mr.imp);
3139 sys::swapByteOrder(mr.sel);
3140}
3141
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003142inline void swapStruct(struct message_ref32 &mr) {
3143 sys::swapByteOrder(mr.imp);
3144 sys::swapByteOrder(mr.sel);
3145}
3146
Kevin Enderby846c0002015-04-16 17:19:59 +00003147inline void swapStruct(struct objc_module_t &module) {
3148 sys::swapByteOrder(module.version);
3149 sys::swapByteOrder(module.size);
3150 sys::swapByteOrder(module.name);
3151 sys::swapByteOrder(module.symtab);
Jingyue Wufedecc42015-04-16 18:43:44 +00003152}
Kevin Enderby846c0002015-04-16 17:19:59 +00003153
3154inline void swapStruct(struct objc_symtab_t &symtab) {
3155 sys::swapByteOrder(symtab.sel_ref_cnt);
3156 sys::swapByteOrder(symtab.refs);
3157 sys::swapByteOrder(symtab.cls_def_cnt);
3158 sys::swapByteOrder(symtab.cat_def_cnt);
Jingyue Wufedecc42015-04-16 18:43:44 +00003159}
Kevin Enderby846c0002015-04-16 17:19:59 +00003160
3161inline void swapStruct(struct objc_class_t &objc_class) {
3162 sys::swapByteOrder(objc_class.isa);
3163 sys::swapByteOrder(objc_class.super_class);
3164 sys::swapByteOrder(objc_class.name);
3165 sys::swapByteOrder(objc_class.version);
3166 sys::swapByteOrder(objc_class.info);
3167 sys::swapByteOrder(objc_class.instance_size);
3168 sys::swapByteOrder(objc_class.ivars);
3169 sys::swapByteOrder(objc_class.methodLists);
3170 sys::swapByteOrder(objc_class.cache);
3171 sys::swapByteOrder(objc_class.protocols);
Jingyue Wufedecc42015-04-16 18:43:44 +00003172}
Kevin Enderby846c0002015-04-16 17:19:59 +00003173
3174inline void swapStruct(struct objc_category_t &objc_category) {
3175 sys::swapByteOrder(objc_category.category_name);
3176 sys::swapByteOrder(objc_category.class_name);
3177 sys::swapByteOrder(objc_category.instance_methods);
3178 sys::swapByteOrder(objc_category.class_methods);
3179 sys::swapByteOrder(objc_category.protocols);
3180}
3181
3182inline void swapStruct(struct objc_ivar_list_t &objc_ivar_list) {
3183 sys::swapByteOrder(objc_ivar_list.ivar_count);
3184}
3185
3186inline void swapStruct(struct objc_ivar_t &objc_ivar) {
3187 sys::swapByteOrder(objc_ivar.ivar_name);
3188 sys::swapByteOrder(objc_ivar.ivar_type);
3189 sys::swapByteOrder(objc_ivar.ivar_offset);
Jingyue Wufedecc42015-04-16 18:43:44 +00003190}
Kevin Enderby846c0002015-04-16 17:19:59 +00003191
3192inline void swapStruct(struct objc_method_list_t &method_list) {
3193 sys::swapByteOrder(method_list.obsolete);
3194 sys::swapByteOrder(method_list.method_count);
3195}
3196
3197inline void swapStruct(struct objc_method_t &method) {
3198 sys::swapByteOrder(method.method_name);
3199 sys::swapByteOrder(method.method_types);
3200 sys::swapByteOrder(method.method_imp);
3201}
3202
3203inline void swapStruct(struct objc_protocol_list_t &protocol_list) {
3204 sys::swapByteOrder(protocol_list.next);
3205 sys::swapByteOrder(protocol_list.count);
3206}
3207
3208inline void swapStruct(struct objc_protocol_t &protocol) {
3209 sys::swapByteOrder(protocol.isa);
3210 sys::swapByteOrder(protocol.protocol_name);
3211 sys::swapByteOrder(protocol.protocol_list);
3212 sys::swapByteOrder(protocol.instance_methods);
3213 sys::swapByteOrder(protocol.class_methods);
3214}
3215
3216inline void swapStruct(struct objc_method_description_list_t &mdl) {
3217 sys::swapByteOrder(mdl.count);
3218}
3219
3220inline void swapStruct(struct objc_method_description_t &md) {
3221 sys::swapByteOrder(md.name);
3222 sys::swapByteOrder(md.types);
3223}
3224
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003225static const char *get_dyld_bind_info_symbolname(uint64_t ReferenceValue,
3226 struct DisassembleInfo *info);
3227
3228// get_objc2_64bit_class_name() is used for disassembly and is passed a pointer
3229// to an Objective-C class and returns the class name. It is also passed the
3230// address of the pointer, so when the pointer is zero as it can be in an .o
3231// file, that is used to look for an external relocation entry with a symbol
3232// name.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00003233static const char *get_objc2_64bit_class_name(uint64_t pointer_value,
3234 uint64_t ReferenceValue,
3235 struct DisassembleInfo *info) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003236 const char *r;
3237 uint32_t offset, left;
3238 SectionRef S;
3239
3240 // The pointer_value can be 0 in an object file and have a relocation
3241 // entry for the class symbol at the ReferenceValue (the address of the
3242 // pointer).
3243 if (pointer_value == 0) {
3244 r = get_pointer_64(ReferenceValue, offset, left, S, info);
3245 if (r == nullptr || left < sizeof(uint64_t))
3246 return nullptr;
3247 uint64_t n_value;
3248 const char *symbol_name = get_symbol_64(offset, S, info, n_value);
3249 if (symbol_name == nullptr)
3250 return nullptr;
Hans Wennborgdb53e302014-10-23 21:59:17 +00003251 const char *class_name = strrchr(symbol_name, '$');
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003252 if (class_name != nullptr && class_name[1] == '_' && class_name[2] != '\0')
3253 return class_name + 2;
3254 else
3255 return nullptr;
3256 }
3257
3258 // The case were the pointer_value is non-zero and points to a class defined
3259 // in this Mach-O file.
3260 r = get_pointer_64(pointer_value, offset, left, S, info);
3261 if (r == nullptr || left < sizeof(struct class64_t))
3262 return nullptr;
3263 struct class64_t c;
3264 memcpy(&c, r, sizeof(struct class64_t));
3265 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3266 swapStruct(c);
3267 if (c.data == 0)
3268 return nullptr;
3269 r = get_pointer_64(c.data, offset, left, S, info);
3270 if (r == nullptr || left < sizeof(struct class_ro64_t))
3271 return nullptr;
3272 struct class_ro64_t cro;
3273 memcpy(&cro, r, sizeof(struct class_ro64_t));
3274 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3275 swapStruct(cro);
3276 if (cro.name == 0)
3277 return nullptr;
3278 const char *name = get_pointer_64(cro.name, offset, left, S, info);
3279 return name;
3280}
3281
3282// get_objc2_64bit_cfstring_name is used for disassembly and is passed a
3283// pointer to a cfstring and returns its name or nullptr.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00003284static const char *get_objc2_64bit_cfstring_name(uint64_t ReferenceValue,
3285 struct DisassembleInfo *info) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003286 const char *r, *name;
3287 uint32_t offset, left;
3288 SectionRef S;
3289 struct cfstring64_t cfs;
3290 uint64_t cfs_characters;
3291
3292 r = get_pointer_64(ReferenceValue, offset, left, S, info);
3293 if (r == nullptr || left < sizeof(struct cfstring64_t))
3294 return nullptr;
3295 memcpy(&cfs, r, sizeof(struct cfstring64_t));
3296 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3297 swapStruct(cfs);
3298 if (cfs.characters == 0) {
3299 uint64_t n_value;
3300 const char *symbol_name = get_symbol_64(
3301 offset + offsetof(struct cfstring64_t, characters), S, info, n_value);
3302 if (symbol_name == nullptr)
3303 return nullptr;
3304 cfs_characters = n_value;
3305 } else
3306 cfs_characters = cfs.characters;
3307 name = get_pointer_64(cfs_characters, offset, left, S, info);
3308
3309 return name;
3310}
3311
3312// get_objc2_64bit_selref() is used for disassembly and is passed a the address
3313// of a pointer to an Objective-C selector reference when the pointer value is
3314// zero as in a .o file and is likely to have a external relocation entry with
3315// who's symbol's n_value is the real pointer to the selector name. If that is
3316// the case the real pointer to the selector name is returned else 0 is
3317// returned
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00003318static uint64_t get_objc2_64bit_selref(uint64_t ReferenceValue,
3319 struct DisassembleInfo *info) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003320 uint32_t offset, left;
3321 SectionRef S;
3322
3323 const char *r = get_pointer_64(ReferenceValue, offset, left, S, info);
3324 if (r == nullptr || left < sizeof(uint64_t))
3325 return 0;
3326 uint64_t n_value;
3327 const char *symbol_name = get_symbol_64(offset, S, info, n_value);
3328 if (symbol_name == nullptr)
3329 return 0;
3330 return n_value;
3331}
3332
Kevin Enderby0fc11822015-04-01 20:57:01 +00003333static const SectionRef get_section(MachOObjectFile *O, const char *segname,
3334 const char *sectname) {
3335 for (const SectionRef &Section : O->sections()) {
3336 StringRef SectName;
3337 Section.getName(SectName);
3338 DataRefImpl Ref = Section.getRawDataRefImpl();
3339 StringRef SegName = O->getSectionFinalSegmentName(Ref);
3340 if (SegName == segname && SectName == sectname)
3341 return Section;
3342 }
3343 return SectionRef();
3344}
3345
3346static void
3347walk_pointer_list_64(const char *listname, const SectionRef S,
3348 MachOObjectFile *O, struct DisassembleInfo *info,
3349 void (*func)(uint64_t, struct DisassembleInfo *info)) {
3350 if (S == SectionRef())
3351 return;
3352
3353 StringRef SectName;
3354 S.getName(SectName);
3355 DataRefImpl Ref = S.getRawDataRefImpl();
3356 StringRef SegName = O->getSectionFinalSegmentName(Ref);
3357 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
3358
3359 StringRef BytesStr;
3360 S.getContents(BytesStr);
3361 const char *Contents = reinterpret_cast<const char *>(BytesStr.data());
3362
3363 for (uint32_t i = 0; i < S.getSize(); i += sizeof(uint64_t)) {
3364 uint32_t left = S.getSize() - i;
3365 uint32_t size = left < sizeof(uint64_t) ? left : sizeof(uint64_t);
3366 uint64_t p = 0;
3367 memcpy(&p, Contents + i, size);
3368 if (i + sizeof(uint64_t) > S.getSize())
3369 outs() << listname << " list pointer extends past end of (" << SegName
3370 << "," << SectName << ") section\n";
3371 outs() << format("%016" PRIx64, S.getAddress() + i) << " ";
3372
3373 if (O->isLittleEndian() != sys::IsLittleEndianHost)
3374 sys::swapByteOrder(p);
3375
3376 uint64_t n_value = 0;
3377 const char *name = get_symbol_64(i, S, info, n_value, p);
3378 if (name == nullptr)
3379 name = get_dyld_bind_info_symbolname(S.getAddress() + i, info);
3380
3381 if (n_value != 0) {
3382 outs() << format("0x%" PRIx64, n_value);
3383 if (p != 0)
3384 outs() << " + " << format("0x%" PRIx64, p);
3385 } else
3386 outs() << format("0x%" PRIx64, p);
3387 if (name != nullptr)
3388 outs() << " " << name;
3389 outs() << "\n";
3390
3391 p += n_value;
3392 if (func)
3393 func(p, info);
3394 }
3395}
3396
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003397static void
3398walk_pointer_list_32(const char *listname, const SectionRef S,
3399 MachOObjectFile *O, struct DisassembleInfo *info,
3400 void (*func)(uint32_t, struct DisassembleInfo *info)) {
3401 if (S == SectionRef())
3402 return;
3403
3404 StringRef SectName;
3405 S.getName(SectName);
3406 DataRefImpl Ref = S.getRawDataRefImpl();
3407 StringRef SegName = O->getSectionFinalSegmentName(Ref);
3408 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
3409
3410 StringRef BytesStr;
3411 S.getContents(BytesStr);
3412 const char *Contents = reinterpret_cast<const char *>(BytesStr.data());
3413
3414 for (uint32_t i = 0; i < S.getSize(); i += sizeof(uint32_t)) {
3415 uint32_t left = S.getSize() - i;
3416 uint32_t size = left < sizeof(uint32_t) ? left : sizeof(uint32_t);
3417 uint32_t p = 0;
3418 memcpy(&p, Contents + i, size);
3419 if (i + sizeof(uint32_t) > S.getSize())
3420 outs() << listname << " list pointer extends past end of (" << SegName
3421 << "," << SectName << ") section\n";
Kevin Enderbycf261312015-04-06 22:33:43 +00003422 uint32_t Address = S.getAddress() + i;
3423 outs() << format("%08" PRIx32, Address) << " ";
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003424
3425 if (O->isLittleEndian() != sys::IsLittleEndianHost)
3426 sys::swapByteOrder(p);
3427 outs() << format("0x%" PRIx32, p);
3428
3429 const char *name = get_symbol_32(i, S, info, p);
3430 if (name != nullptr)
3431 outs() << " " << name;
3432 outs() << "\n";
3433
3434 if (func)
3435 func(p, info);
3436 }
3437}
3438
3439static void print_layout_map(const char *layout_map, uint32_t left) {
Kevin Enderbya59824a2015-10-06 22:27:08 +00003440 if (layout_map == nullptr)
3441 return;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003442 outs() << " layout map: ";
3443 do {
3444 outs() << format("0x%02" PRIx32, (*layout_map) & 0xff) << " ";
3445 left--;
3446 layout_map++;
3447 } while (*layout_map != '\0' && left != 0);
3448 outs() << "\n";
3449}
3450
Kevin Enderby0fc11822015-04-01 20:57:01 +00003451static void print_layout_map64(uint64_t p, struct DisassembleInfo *info) {
3452 uint32_t offset, left;
3453 SectionRef S;
3454 const char *layout_map;
3455
3456 if (p == 0)
3457 return;
3458 layout_map = get_pointer_64(p, offset, left, S, info);
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003459 print_layout_map(layout_map, left);
3460}
3461
3462static void print_layout_map32(uint32_t p, struct DisassembleInfo *info) {
3463 uint32_t offset, left;
3464 SectionRef S;
3465 const char *layout_map;
3466
3467 if (p == 0)
3468 return;
3469 layout_map = get_pointer_32(p, offset, left, S, info);
3470 print_layout_map(layout_map, left);
Kevin Enderby0fc11822015-04-01 20:57:01 +00003471}
3472
3473static void print_method_list64_t(uint64_t p, struct DisassembleInfo *info,
3474 const char *indent) {
3475 struct method_list64_t ml;
3476 struct method64_t m;
3477 const char *r;
3478 uint32_t offset, xoffset, left, i;
3479 SectionRef S, xS;
3480 const char *name, *sym_name;
3481 uint64_t n_value;
3482
3483 r = get_pointer_64(p, offset, left, S, info);
3484 if (r == nullptr)
3485 return;
3486 memset(&ml, '\0', sizeof(struct method_list64_t));
3487 if (left < sizeof(struct method_list64_t)) {
3488 memcpy(&ml, r, left);
3489 outs() << " (method_list_t entends past the end of the section)\n";
3490 } else
3491 memcpy(&ml, r, sizeof(struct method_list64_t));
3492 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3493 swapStruct(ml);
3494 outs() << indent << "\t\t entsize " << ml.entsize << "\n";
3495 outs() << indent << "\t\t count " << ml.count << "\n";
3496
3497 p += sizeof(struct method_list64_t);
3498 offset += sizeof(struct method_list64_t);
3499 for (i = 0; i < ml.count; i++) {
3500 r = get_pointer_64(p, offset, left, S, info);
3501 if (r == nullptr)
3502 return;
3503 memset(&m, '\0', sizeof(struct method64_t));
3504 if (left < sizeof(struct method64_t)) {
Kevin Enderbya59824a2015-10-06 22:27:08 +00003505 memcpy(&m, r, left);
3506 outs() << indent << " (method_t extends past the end of the section)\n";
Kevin Enderby0fc11822015-04-01 20:57:01 +00003507 } else
3508 memcpy(&m, r, sizeof(struct method64_t));
3509 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3510 swapStruct(m);
3511
3512 outs() << indent << "\t\t name ";
3513 sym_name = get_symbol_64(offset + offsetof(struct method64_t, name), S,
3514 info, n_value, m.name);
3515 if (n_value != 0) {
3516 if (info->verbose && sym_name != nullptr)
3517 outs() << sym_name;
3518 else
3519 outs() << format("0x%" PRIx64, n_value);
3520 if (m.name != 0)
3521 outs() << " + " << format("0x%" PRIx64, m.name);
3522 } else
3523 outs() << format("0x%" PRIx64, m.name);
3524 name = get_pointer_64(m.name + n_value, xoffset, left, xS, info);
3525 if (name != nullptr)
3526 outs() << format(" %.*s", left, name);
3527 outs() << "\n";
3528
3529 outs() << indent << "\t\t types ";
3530 sym_name = get_symbol_64(offset + offsetof(struct method64_t, types), S,
3531 info, n_value, m.types);
3532 if (n_value != 0) {
3533 if (info->verbose && sym_name != nullptr)
3534 outs() << sym_name;
3535 else
3536 outs() << format("0x%" PRIx64, n_value);
3537 if (m.types != 0)
3538 outs() << " + " << format("0x%" PRIx64, m.types);
3539 } else
3540 outs() << format("0x%" PRIx64, m.types);
3541 name = get_pointer_64(m.types + n_value, xoffset, left, xS, info);
3542 if (name != nullptr)
3543 outs() << format(" %.*s", left, name);
3544 outs() << "\n";
3545
3546 outs() << indent << "\t\t imp ";
3547 name = get_symbol_64(offset + offsetof(struct method64_t, imp), S, info,
3548 n_value, m.imp);
3549 if (info->verbose && name == nullptr) {
3550 if (n_value != 0) {
3551 outs() << format("0x%" PRIx64, n_value) << " ";
3552 if (m.imp != 0)
3553 outs() << "+ " << format("0x%" PRIx64, m.imp) << " ";
3554 } else
3555 outs() << format("0x%" PRIx64, m.imp) << " ";
3556 }
3557 if (name != nullptr)
3558 outs() << name;
3559 outs() << "\n";
3560
3561 p += sizeof(struct method64_t);
3562 offset += sizeof(struct method64_t);
3563 }
3564}
3565
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003566static void print_method_list32_t(uint64_t p, struct DisassembleInfo *info,
3567 const char *indent) {
3568 struct method_list32_t ml;
3569 struct method32_t m;
Kevin Enderby846c0002015-04-16 17:19:59 +00003570 const char *r, *name;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003571 uint32_t offset, xoffset, left, i;
3572 SectionRef S, xS;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003573
3574 r = get_pointer_32(p, offset, left, S, info);
3575 if (r == nullptr)
3576 return;
3577 memset(&ml, '\0', sizeof(struct method_list32_t));
3578 if (left < sizeof(struct method_list32_t)) {
3579 memcpy(&ml, r, left);
3580 outs() << " (method_list_t entends past the end of the section)\n";
3581 } else
3582 memcpy(&ml, r, sizeof(struct method_list32_t));
3583 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3584 swapStruct(ml);
3585 outs() << indent << "\t\t entsize " << ml.entsize << "\n";
3586 outs() << indent << "\t\t count " << ml.count << "\n";
3587
3588 p += sizeof(struct method_list32_t);
3589 offset += sizeof(struct method_list32_t);
3590 for (i = 0; i < ml.count; i++) {
3591 r = get_pointer_32(p, offset, left, S, info);
3592 if (r == nullptr)
3593 return;
3594 memset(&m, '\0', sizeof(struct method32_t));
3595 if (left < sizeof(struct method32_t)) {
3596 memcpy(&ml, r, left);
3597 outs() << indent << " (method_t entends past the end of the section)\n";
3598 } else
3599 memcpy(&m, r, sizeof(struct method32_t));
3600 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3601 swapStruct(m);
3602
3603 outs() << indent << "\t\t name " << format("0x%" PRIx32, m.name);
3604 name = get_pointer_32(m.name, xoffset, left, xS, info);
3605 if (name != nullptr)
3606 outs() << format(" %.*s", left, name);
3607 outs() << "\n";
3608
3609 outs() << indent << "\t\t types " << format("0x%" PRIx32, m.types);
3610 name = get_pointer_32(m.types, xoffset, left, xS, info);
3611 if (name != nullptr)
3612 outs() << format(" %.*s", left, name);
3613 outs() << "\n";
3614
3615 outs() << indent << "\t\t imp " << format("0x%" PRIx32, m.imp);
3616 name = get_symbol_32(offset + offsetof(struct method32_t, imp), S, info,
3617 m.imp);
3618 if (name != nullptr)
3619 outs() << " " << name;
3620 outs() << "\n";
3621
3622 p += sizeof(struct method32_t);
3623 offset += sizeof(struct method32_t);
3624 }
3625}
3626
Kevin Enderby846c0002015-04-16 17:19:59 +00003627static bool print_method_list(uint32_t p, struct DisassembleInfo *info) {
3628 uint32_t offset, left, xleft;
3629 SectionRef S;
3630 struct objc_method_list_t method_list;
3631 struct objc_method_t method;
3632 const char *r, *methods, *name, *SymbolName;
3633 int32_t i;
3634
3635 r = get_pointer_32(p, offset, left, S, info, true);
3636 if (r == nullptr)
3637 return true;
3638
3639 outs() << "\n";
3640 if (left > sizeof(struct objc_method_list_t)) {
3641 memcpy(&method_list, r, sizeof(struct objc_method_list_t));
3642 } else {
3643 outs() << "\t\t objc_method_list extends past end of the section\n";
3644 memset(&method_list, '\0', sizeof(struct objc_method_list_t));
3645 memcpy(&method_list, r, left);
3646 }
3647 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3648 swapStruct(method_list);
3649
3650 outs() << "\t\t obsolete "
3651 << format("0x%08" PRIx32, method_list.obsolete) << "\n";
3652 outs() << "\t\t method_count " << method_list.method_count << "\n";
3653
3654 methods = r + sizeof(struct objc_method_list_t);
3655 for (i = 0; i < method_list.method_count; i++) {
3656 if ((i + 1) * sizeof(struct objc_method_t) > left) {
3657 outs() << "\t\t remaining method's extend past the of the section\n";
3658 break;
3659 }
3660 memcpy(&method, methods + i * sizeof(struct objc_method_t),
3661 sizeof(struct objc_method_t));
3662 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3663 swapStruct(method);
3664
3665 outs() << "\t\t method_name "
3666 << format("0x%08" PRIx32, method.method_name);
3667 if (info->verbose) {
3668 name = get_pointer_32(method.method_name, offset, xleft, S, info, true);
3669 if (name != nullptr)
3670 outs() << format(" %.*s", xleft, name);
3671 else
3672 outs() << " (not in an __OBJC section)";
3673 }
3674 outs() << "\n";
3675
3676 outs() << "\t\t method_types "
3677 << format("0x%08" PRIx32, method.method_types);
3678 if (info->verbose) {
3679 name = get_pointer_32(method.method_types, offset, xleft, S, info, true);
3680 if (name != nullptr)
3681 outs() << format(" %.*s", xleft, name);
3682 else
3683 outs() << " (not in an __OBJC section)";
3684 }
3685 outs() << "\n";
3686
3687 outs() << "\t\t method_imp "
3688 << format("0x%08" PRIx32, method.method_imp) << " ";
3689 if (info->verbose) {
3690 SymbolName = GuessSymbolName(method.method_imp, info->AddrMap);
3691 if (SymbolName != nullptr)
3692 outs() << SymbolName;
3693 }
3694 outs() << "\n";
3695 }
3696 return false;
3697}
3698
Kevin Enderby0fc11822015-04-01 20:57:01 +00003699static void print_protocol_list64_t(uint64_t p, struct DisassembleInfo *info) {
3700 struct protocol_list64_t pl;
3701 uint64_t q, n_value;
3702 struct protocol64_t pc;
3703 const char *r;
3704 uint32_t offset, xoffset, left, i;
3705 SectionRef S, xS;
3706 const char *name, *sym_name;
3707
3708 r = get_pointer_64(p, offset, left, S, info);
3709 if (r == nullptr)
3710 return;
3711 memset(&pl, '\0', sizeof(struct protocol_list64_t));
3712 if (left < sizeof(struct protocol_list64_t)) {
3713 memcpy(&pl, r, left);
3714 outs() << " (protocol_list_t entends past the end of the section)\n";
3715 } else
3716 memcpy(&pl, r, sizeof(struct protocol_list64_t));
3717 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3718 swapStruct(pl);
3719 outs() << " count " << pl.count << "\n";
3720
3721 p += sizeof(struct protocol_list64_t);
3722 offset += sizeof(struct protocol_list64_t);
3723 for (i = 0; i < pl.count; i++) {
3724 r = get_pointer_64(p, offset, left, S, info);
3725 if (r == nullptr)
3726 return;
3727 q = 0;
3728 if (left < sizeof(uint64_t)) {
3729 memcpy(&q, r, left);
3730 outs() << " (protocol_t * entends past the end of the section)\n";
3731 } else
3732 memcpy(&q, r, sizeof(uint64_t));
3733 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3734 sys::swapByteOrder(q);
3735
3736 outs() << "\t\t list[" << i << "] ";
3737 sym_name = get_symbol_64(offset, S, info, n_value, q);
3738 if (n_value != 0) {
3739 if (info->verbose && sym_name != nullptr)
3740 outs() << sym_name;
3741 else
3742 outs() << format("0x%" PRIx64, n_value);
3743 if (q != 0)
3744 outs() << " + " << format("0x%" PRIx64, q);
3745 } else
3746 outs() << format("0x%" PRIx64, q);
3747 outs() << " (struct protocol_t *)\n";
3748
3749 r = get_pointer_64(q + n_value, offset, left, S, info);
3750 if (r == nullptr)
3751 return;
3752 memset(&pc, '\0', sizeof(struct protocol64_t));
3753 if (left < sizeof(struct protocol64_t)) {
3754 memcpy(&pc, r, left);
3755 outs() << " (protocol_t entends past the end of the section)\n";
3756 } else
3757 memcpy(&pc, r, sizeof(struct protocol64_t));
3758 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3759 swapStruct(pc);
3760
3761 outs() << "\t\t\t isa " << format("0x%" PRIx64, pc.isa) << "\n";
3762
3763 outs() << "\t\t\t name ";
3764 sym_name = get_symbol_64(offset + offsetof(struct protocol64_t, name), S,
3765 info, n_value, pc.name);
3766 if (n_value != 0) {
3767 if (info->verbose && sym_name != nullptr)
3768 outs() << sym_name;
3769 else
3770 outs() << format("0x%" PRIx64, n_value);
3771 if (pc.name != 0)
3772 outs() << " + " << format("0x%" PRIx64, pc.name);
3773 } else
3774 outs() << format("0x%" PRIx64, pc.name);
3775 name = get_pointer_64(pc.name + n_value, xoffset, left, xS, info);
3776 if (name != nullptr)
3777 outs() << format(" %.*s", left, name);
3778 outs() << "\n";
3779
3780 outs() << "\t\t\tprotocols " << format("0x%" PRIx64, pc.protocols) << "\n";
3781
3782 outs() << "\t\t instanceMethods ";
3783 sym_name =
3784 get_symbol_64(offset + offsetof(struct protocol64_t, instanceMethods),
3785 S, info, n_value, pc.instanceMethods);
3786 if (n_value != 0) {
3787 if (info->verbose && sym_name != nullptr)
3788 outs() << sym_name;
3789 else
3790 outs() << format("0x%" PRIx64, n_value);
3791 if (pc.instanceMethods != 0)
3792 outs() << " + " << format("0x%" PRIx64, pc.instanceMethods);
3793 } else
3794 outs() << format("0x%" PRIx64, pc.instanceMethods);
3795 outs() << " (struct method_list_t *)\n";
3796 if (pc.instanceMethods + n_value != 0)
3797 print_method_list64_t(pc.instanceMethods + n_value, info, "\t");
3798
3799 outs() << "\t\t classMethods ";
3800 sym_name =
3801 get_symbol_64(offset + offsetof(struct protocol64_t, classMethods), S,
3802 info, n_value, pc.classMethods);
3803 if (n_value != 0) {
3804 if (info->verbose && sym_name != nullptr)
3805 outs() << sym_name;
3806 else
3807 outs() << format("0x%" PRIx64, n_value);
3808 if (pc.classMethods != 0)
3809 outs() << " + " << format("0x%" PRIx64, pc.classMethods);
3810 } else
3811 outs() << format("0x%" PRIx64, pc.classMethods);
3812 outs() << " (struct method_list_t *)\n";
3813 if (pc.classMethods + n_value != 0)
3814 print_method_list64_t(pc.classMethods + n_value, info, "\t");
3815
3816 outs() << "\t optionalInstanceMethods "
3817 << format("0x%" PRIx64, pc.optionalInstanceMethods) << "\n";
3818 outs() << "\t optionalClassMethods "
3819 << format("0x%" PRIx64, pc.optionalClassMethods) << "\n";
3820 outs() << "\t instanceProperties "
3821 << format("0x%" PRIx64, pc.instanceProperties) << "\n";
3822
3823 p += sizeof(uint64_t);
3824 offset += sizeof(uint64_t);
3825 }
3826}
3827
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003828static void print_protocol_list32_t(uint32_t p, struct DisassembleInfo *info) {
3829 struct protocol_list32_t pl;
3830 uint32_t q;
3831 struct protocol32_t pc;
3832 const char *r;
3833 uint32_t offset, xoffset, left, i;
3834 SectionRef S, xS;
3835 const char *name;
3836
3837 r = get_pointer_32(p, offset, left, S, info);
3838 if (r == nullptr)
3839 return;
3840 memset(&pl, '\0', sizeof(struct protocol_list32_t));
3841 if (left < sizeof(struct protocol_list32_t)) {
3842 memcpy(&pl, r, left);
3843 outs() << " (protocol_list_t entends past the end of the section)\n";
3844 } else
3845 memcpy(&pl, r, sizeof(struct protocol_list32_t));
3846 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3847 swapStruct(pl);
3848 outs() << " count " << pl.count << "\n";
3849
3850 p += sizeof(struct protocol_list32_t);
3851 offset += sizeof(struct protocol_list32_t);
3852 for (i = 0; i < pl.count; i++) {
3853 r = get_pointer_32(p, offset, left, S, info);
3854 if (r == nullptr)
3855 return;
3856 q = 0;
3857 if (left < sizeof(uint32_t)) {
3858 memcpy(&q, r, left);
3859 outs() << " (protocol_t * entends past the end of the section)\n";
3860 } else
3861 memcpy(&q, r, sizeof(uint32_t));
3862 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3863 sys::swapByteOrder(q);
3864 outs() << "\t\t list[" << i << "] " << format("0x%" PRIx32, q)
3865 << " (struct protocol_t *)\n";
3866 r = get_pointer_32(q, offset, left, S, info);
3867 if (r == nullptr)
3868 return;
3869 memset(&pc, '\0', sizeof(struct protocol32_t));
3870 if (left < sizeof(struct protocol32_t)) {
3871 memcpy(&pc, r, left);
3872 outs() << " (protocol_t entends past the end of the section)\n";
3873 } else
3874 memcpy(&pc, r, sizeof(struct protocol32_t));
3875 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3876 swapStruct(pc);
3877 outs() << "\t\t\t isa " << format("0x%" PRIx32, pc.isa) << "\n";
3878 outs() << "\t\t\t name " << format("0x%" PRIx32, pc.name);
3879 name = get_pointer_32(pc.name, xoffset, left, xS, info);
3880 if (name != nullptr)
3881 outs() << format(" %.*s", left, name);
3882 outs() << "\n";
3883 outs() << "\t\t\tprotocols " << format("0x%" PRIx32, pc.protocols) << "\n";
3884 outs() << "\t\t instanceMethods "
3885 << format("0x%" PRIx32, pc.instanceMethods)
3886 << " (struct method_list_t *)\n";
3887 if (pc.instanceMethods != 0)
3888 print_method_list32_t(pc.instanceMethods, info, "\t");
3889 outs() << "\t\t classMethods " << format("0x%" PRIx32, pc.classMethods)
3890 << " (struct method_list_t *)\n";
3891 if (pc.classMethods != 0)
3892 print_method_list32_t(pc.classMethods, info, "\t");
3893 outs() << "\t optionalInstanceMethods "
3894 << format("0x%" PRIx32, pc.optionalInstanceMethods) << "\n";
3895 outs() << "\t optionalClassMethods "
3896 << format("0x%" PRIx32, pc.optionalClassMethods) << "\n";
3897 outs() << "\t instanceProperties "
3898 << format("0x%" PRIx32, pc.instanceProperties) << "\n";
3899 p += sizeof(uint32_t);
3900 offset += sizeof(uint32_t);
3901 }
3902}
3903
Kevin Enderby846c0002015-04-16 17:19:59 +00003904static void print_indent(uint32_t indent) {
3905 for (uint32_t i = 0; i < indent;) {
3906 if (indent - i >= 8) {
3907 outs() << "\t";
3908 i += 8;
3909 } else {
3910 for (uint32_t j = i; j < indent; j++)
3911 outs() << " ";
3912 return;
3913 }
3914 }
3915}
3916
3917static bool print_method_description_list(uint32_t p, uint32_t indent,
3918 struct DisassembleInfo *info) {
3919 uint32_t offset, left, xleft;
3920 SectionRef S;
3921 struct objc_method_description_list_t mdl;
3922 struct objc_method_description_t md;
3923 const char *r, *list, *name;
3924 int32_t i;
3925
3926 r = get_pointer_32(p, offset, left, S, info, true);
3927 if (r == nullptr)
3928 return true;
3929
3930 outs() << "\n";
3931 if (left > sizeof(struct objc_method_description_list_t)) {
3932 memcpy(&mdl, r, sizeof(struct objc_method_description_list_t));
3933 } else {
3934 print_indent(indent);
3935 outs() << " objc_method_description_list extends past end of the section\n";
3936 memset(&mdl, '\0', sizeof(struct objc_method_description_list_t));
3937 memcpy(&mdl, r, left);
3938 }
3939 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3940 swapStruct(mdl);
3941
3942 print_indent(indent);
3943 outs() << " count " << mdl.count << "\n";
3944
3945 list = r + sizeof(struct objc_method_description_list_t);
3946 for (i = 0; i < mdl.count; i++) {
3947 if ((i + 1) * sizeof(struct objc_method_description_t) > left) {
3948 print_indent(indent);
3949 outs() << " remaining list entries extend past the of the section\n";
3950 break;
3951 }
3952 print_indent(indent);
3953 outs() << " list[" << i << "]\n";
3954 memcpy(&md, list + i * sizeof(struct objc_method_description_t),
3955 sizeof(struct objc_method_description_t));
3956 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3957 swapStruct(md);
3958
3959 print_indent(indent);
3960 outs() << " name " << format("0x%08" PRIx32, md.name);
3961 if (info->verbose) {
3962 name = get_pointer_32(md.name, offset, xleft, S, info, true);
3963 if (name != nullptr)
3964 outs() << format(" %.*s", xleft, name);
3965 else
3966 outs() << " (not in an __OBJC section)";
3967 }
3968 outs() << "\n";
3969
3970 print_indent(indent);
3971 outs() << " types " << format("0x%08" PRIx32, md.types);
3972 if (info->verbose) {
3973 name = get_pointer_32(md.types, offset, xleft, S, info, true);
3974 if (name != nullptr)
3975 outs() << format(" %.*s", xleft, name);
3976 else
3977 outs() << " (not in an __OBJC section)";
3978 }
3979 outs() << "\n";
3980 }
3981 return false;
3982}
3983
3984static bool print_protocol_list(uint32_t p, uint32_t indent,
3985 struct DisassembleInfo *info);
3986
3987static bool print_protocol(uint32_t p, uint32_t indent,
3988 struct DisassembleInfo *info) {
3989 uint32_t offset, left;
3990 SectionRef S;
3991 struct objc_protocol_t protocol;
3992 const char *r, *name;
3993
3994 r = get_pointer_32(p, offset, left, S, info, true);
3995 if (r == nullptr)
3996 return true;
3997
3998 outs() << "\n";
3999 if (left >= sizeof(struct objc_protocol_t)) {
4000 memcpy(&protocol, r, sizeof(struct objc_protocol_t));
4001 } else {
4002 print_indent(indent);
4003 outs() << " Protocol extends past end of the section\n";
4004 memset(&protocol, '\0', sizeof(struct objc_protocol_t));
4005 memcpy(&protocol, r, left);
4006 }
4007 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4008 swapStruct(protocol);
4009
4010 print_indent(indent);
4011 outs() << " isa " << format("0x%08" PRIx32, protocol.isa)
4012 << "\n";
4013
4014 print_indent(indent);
4015 outs() << " protocol_name "
4016 << format("0x%08" PRIx32, protocol.protocol_name);
4017 if (info->verbose) {
4018 name = get_pointer_32(protocol.protocol_name, offset, left, S, info, true);
4019 if (name != nullptr)
4020 outs() << format(" %.*s", left, name);
4021 else
4022 outs() << " (not in an __OBJC section)";
4023 }
4024 outs() << "\n";
4025
4026 print_indent(indent);
4027 outs() << " protocol_list "
4028 << format("0x%08" PRIx32, protocol.protocol_list);
4029 if (print_protocol_list(protocol.protocol_list, indent + 4, info))
4030 outs() << " (not in an __OBJC section)\n";
4031
4032 print_indent(indent);
4033 outs() << " instance_methods "
4034 << format("0x%08" PRIx32, protocol.instance_methods);
4035 if (print_method_description_list(protocol.instance_methods, indent, info))
4036 outs() << " (not in an __OBJC section)\n";
4037
4038 print_indent(indent);
4039 outs() << " class_methods "
4040 << format("0x%08" PRIx32, protocol.class_methods);
4041 if (print_method_description_list(protocol.class_methods, indent, info))
4042 outs() << " (not in an __OBJC section)\n";
4043
4044 return false;
4045}
4046
4047static bool print_protocol_list(uint32_t p, uint32_t indent,
4048 struct DisassembleInfo *info) {
4049 uint32_t offset, left, l;
4050 SectionRef S;
4051 struct objc_protocol_list_t protocol_list;
4052 const char *r, *list;
4053 int32_t i;
4054
4055 r = get_pointer_32(p, offset, left, S, info, true);
4056 if (r == nullptr)
4057 return true;
4058
4059 outs() << "\n";
4060 if (left > sizeof(struct objc_protocol_list_t)) {
4061 memcpy(&protocol_list, r, sizeof(struct objc_protocol_list_t));
4062 } else {
4063 outs() << "\t\t objc_protocol_list_t extends past end of the section\n";
4064 memset(&protocol_list, '\0', sizeof(struct objc_protocol_list_t));
4065 memcpy(&protocol_list, r, left);
4066 }
4067 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4068 swapStruct(protocol_list);
4069
4070 print_indent(indent);
4071 outs() << " next " << format("0x%08" PRIx32, protocol_list.next)
4072 << "\n";
4073 print_indent(indent);
4074 outs() << " count " << protocol_list.count << "\n";
4075
4076 list = r + sizeof(struct objc_protocol_list_t);
4077 for (i = 0; i < protocol_list.count; i++) {
4078 if ((i + 1) * sizeof(uint32_t) > left) {
4079 outs() << "\t\t remaining list entries extend past the of the section\n";
4080 break;
4081 }
4082 memcpy(&l, list + i * sizeof(uint32_t), sizeof(uint32_t));
4083 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4084 sys::swapByteOrder(l);
4085
4086 print_indent(indent);
4087 outs() << " list[" << i << "] " << format("0x%08" PRIx32, l);
4088 if (print_protocol(l, indent, info))
4089 outs() << "(not in an __OBJC section)\n";
4090 }
4091 return false;
4092}
4093
Kevin Enderby0fc11822015-04-01 20:57:01 +00004094static void print_ivar_list64_t(uint64_t p, struct DisassembleInfo *info) {
4095 struct ivar_list64_t il;
4096 struct ivar64_t i;
4097 const char *r;
4098 uint32_t offset, xoffset, left, j;
4099 SectionRef S, xS;
4100 const char *name, *sym_name, *ivar_offset_p;
4101 uint64_t ivar_offset, n_value;
4102
4103 r = get_pointer_64(p, offset, left, S, info);
4104 if (r == nullptr)
4105 return;
4106 memset(&il, '\0', sizeof(struct ivar_list64_t));
4107 if (left < sizeof(struct ivar_list64_t)) {
4108 memcpy(&il, r, left);
4109 outs() << " (ivar_list_t entends past the end of the section)\n";
4110 } else
4111 memcpy(&il, r, sizeof(struct ivar_list64_t));
4112 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4113 swapStruct(il);
4114 outs() << " entsize " << il.entsize << "\n";
4115 outs() << " count " << il.count << "\n";
4116
4117 p += sizeof(struct ivar_list64_t);
4118 offset += sizeof(struct ivar_list64_t);
4119 for (j = 0; j < il.count; j++) {
4120 r = get_pointer_64(p, offset, left, S, info);
4121 if (r == nullptr)
4122 return;
4123 memset(&i, '\0', sizeof(struct ivar64_t));
4124 if (left < sizeof(struct ivar64_t)) {
4125 memcpy(&i, r, left);
4126 outs() << " (ivar_t entends past the end of the section)\n";
4127 } else
4128 memcpy(&i, r, sizeof(struct ivar64_t));
4129 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4130 swapStruct(i);
4131
4132 outs() << "\t\t\t offset ";
4133 sym_name = get_symbol_64(offset + offsetof(struct ivar64_t, offset), S,
4134 info, n_value, i.offset);
4135 if (n_value != 0) {
4136 if (info->verbose && sym_name != nullptr)
4137 outs() << sym_name;
4138 else
4139 outs() << format("0x%" PRIx64, n_value);
4140 if (i.offset != 0)
4141 outs() << " + " << format("0x%" PRIx64, i.offset);
4142 } else
4143 outs() << format("0x%" PRIx64, i.offset);
4144 ivar_offset_p = get_pointer_64(i.offset + n_value, xoffset, left, xS, info);
4145 if (ivar_offset_p != nullptr && left >= sizeof(*ivar_offset_p)) {
4146 memcpy(&ivar_offset, ivar_offset_p, sizeof(ivar_offset));
4147 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4148 sys::swapByteOrder(ivar_offset);
4149 outs() << " " << ivar_offset << "\n";
4150 } else
4151 outs() << "\n";
4152
4153 outs() << "\t\t\t name ";
4154 sym_name = get_symbol_64(offset + offsetof(struct ivar64_t, name), S, info,
4155 n_value, i.name);
4156 if (n_value != 0) {
4157 if (info->verbose && sym_name != nullptr)
4158 outs() << sym_name;
4159 else
4160 outs() << format("0x%" PRIx64, n_value);
4161 if (i.name != 0)
4162 outs() << " + " << format("0x%" PRIx64, i.name);
4163 } else
4164 outs() << format("0x%" PRIx64, i.name);
4165 name = get_pointer_64(i.name + n_value, xoffset, left, xS, info);
4166 if (name != nullptr)
4167 outs() << format(" %.*s", left, name);
4168 outs() << "\n";
4169
4170 outs() << "\t\t\t type ";
4171 sym_name = get_symbol_64(offset + offsetof(struct ivar64_t, type), S, info,
4172 n_value, i.name);
4173 name = get_pointer_64(i.type + n_value, xoffset, left, xS, info);
4174 if (n_value != 0) {
4175 if (info->verbose && sym_name != nullptr)
4176 outs() << sym_name;
4177 else
4178 outs() << format("0x%" PRIx64, n_value);
4179 if (i.type != 0)
4180 outs() << " + " << format("0x%" PRIx64, i.type);
4181 } else
4182 outs() << format("0x%" PRIx64, i.type);
4183 if (name != nullptr)
4184 outs() << format(" %.*s", left, name);
4185 outs() << "\n";
4186
4187 outs() << "\t\t\talignment " << i.alignment << "\n";
4188 outs() << "\t\t\t size " << i.size << "\n";
4189
4190 p += sizeof(struct ivar64_t);
4191 offset += sizeof(struct ivar64_t);
4192 }
4193}
4194
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004195static void print_ivar_list32_t(uint32_t p, struct DisassembleInfo *info) {
4196 struct ivar_list32_t il;
4197 struct ivar32_t i;
4198 const char *r;
4199 uint32_t offset, xoffset, left, j;
4200 SectionRef S, xS;
4201 const char *name, *ivar_offset_p;
4202 uint32_t ivar_offset;
4203
4204 r = get_pointer_32(p, offset, left, S, info);
4205 if (r == nullptr)
4206 return;
4207 memset(&il, '\0', sizeof(struct ivar_list32_t));
4208 if (left < sizeof(struct ivar_list32_t)) {
4209 memcpy(&il, r, left);
4210 outs() << " (ivar_list_t entends past the end of the section)\n";
4211 } else
4212 memcpy(&il, r, sizeof(struct ivar_list32_t));
4213 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4214 swapStruct(il);
4215 outs() << " entsize " << il.entsize << "\n";
4216 outs() << " count " << il.count << "\n";
4217
4218 p += sizeof(struct ivar_list32_t);
4219 offset += sizeof(struct ivar_list32_t);
4220 for (j = 0; j < il.count; j++) {
4221 r = get_pointer_32(p, offset, left, S, info);
4222 if (r == nullptr)
4223 return;
4224 memset(&i, '\0', sizeof(struct ivar32_t));
4225 if (left < sizeof(struct ivar32_t)) {
4226 memcpy(&i, r, left);
4227 outs() << " (ivar_t entends past the end of the section)\n";
4228 } else
4229 memcpy(&i, r, sizeof(struct ivar32_t));
4230 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4231 swapStruct(i);
4232
4233 outs() << "\t\t\t offset " << format("0x%" PRIx32, i.offset);
4234 ivar_offset_p = get_pointer_32(i.offset, xoffset, left, xS, info);
4235 if (ivar_offset_p != nullptr && left >= sizeof(*ivar_offset_p)) {
4236 memcpy(&ivar_offset, ivar_offset_p, sizeof(ivar_offset));
4237 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4238 sys::swapByteOrder(ivar_offset);
4239 outs() << " " << ivar_offset << "\n";
4240 } else
4241 outs() << "\n";
4242
4243 outs() << "\t\t\t name " << format("0x%" PRIx32, i.name);
4244 name = get_pointer_32(i.name, xoffset, left, xS, info);
4245 if (name != nullptr)
4246 outs() << format(" %.*s", left, name);
4247 outs() << "\n";
4248
4249 outs() << "\t\t\t type " << format("0x%" PRIx32, i.type);
4250 name = get_pointer_32(i.type, xoffset, left, xS, info);
4251 if (name != nullptr)
4252 outs() << format(" %.*s", left, name);
4253 outs() << "\n";
4254
4255 outs() << "\t\t\talignment " << i.alignment << "\n";
4256 outs() << "\t\t\t size " << i.size << "\n";
4257
4258 p += sizeof(struct ivar32_t);
4259 offset += sizeof(struct ivar32_t);
4260 }
4261}
4262
Kevin Enderby0fc11822015-04-01 20:57:01 +00004263static void print_objc_property_list64(uint64_t p,
4264 struct DisassembleInfo *info) {
4265 struct objc_property_list64 opl;
4266 struct objc_property64 op;
4267 const char *r;
4268 uint32_t offset, xoffset, left, j;
4269 SectionRef S, xS;
4270 const char *name, *sym_name;
4271 uint64_t n_value;
4272
4273 r = get_pointer_64(p, offset, left, S, info);
4274 if (r == nullptr)
4275 return;
4276 memset(&opl, '\0', sizeof(struct objc_property_list64));
4277 if (left < sizeof(struct objc_property_list64)) {
4278 memcpy(&opl, r, left);
4279 outs() << " (objc_property_list entends past the end of the section)\n";
4280 } else
4281 memcpy(&opl, r, sizeof(struct objc_property_list64));
4282 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4283 swapStruct(opl);
4284 outs() << " entsize " << opl.entsize << "\n";
4285 outs() << " count " << opl.count << "\n";
4286
4287 p += sizeof(struct objc_property_list64);
4288 offset += sizeof(struct objc_property_list64);
4289 for (j = 0; j < opl.count; j++) {
4290 r = get_pointer_64(p, offset, left, S, info);
4291 if (r == nullptr)
4292 return;
4293 memset(&op, '\0', sizeof(struct objc_property64));
4294 if (left < sizeof(struct objc_property64)) {
4295 memcpy(&op, r, left);
4296 outs() << " (objc_property entends past the end of the section)\n";
4297 } else
4298 memcpy(&op, r, sizeof(struct objc_property64));
4299 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4300 swapStruct(op);
4301
4302 outs() << "\t\t\t name ";
4303 sym_name = get_symbol_64(offset + offsetof(struct objc_property64, name), S,
4304 info, n_value, op.name);
4305 if (n_value != 0) {
4306 if (info->verbose && sym_name != nullptr)
4307 outs() << sym_name;
4308 else
4309 outs() << format("0x%" PRIx64, n_value);
4310 if (op.name != 0)
4311 outs() << " + " << format("0x%" PRIx64, op.name);
4312 } else
4313 outs() << format("0x%" PRIx64, op.name);
4314 name = get_pointer_64(op.name + n_value, xoffset, left, xS, info);
4315 if (name != nullptr)
4316 outs() << format(" %.*s", left, name);
4317 outs() << "\n";
4318
4319 outs() << "\t\t\tattributes ";
4320 sym_name =
4321 get_symbol_64(offset + offsetof(struct objc_property64, attributes), S,
4322 info, n_value, op.attributes);
4323 if (n_value != 0) {
4324 if (info->verbose && sym_name != nullptr)
4325 outs() << sym_name;
4326 else
4327 outs() << format("0x%" PRIx64, n_value);
4328 if (op.attributes != 0)
4329 outs() << " + " << format("0x%" PRIx64, op.attributes);
4330 } else
4331 outs() << format("0x%" PRIx64, op.attributes);
4332 name = get_pointer_64(op.attributes + n_value, xoffset, left, xS, info);
4333 if (name != nullptr)
4334 outs() << format(" %.*s", left, name);
4335 outs() << "\n";
4336
4337 p += sizeof(struct objc_property64);
4338 offset += sizeof(struct objc_property64);
4339 }
4340}
4341
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004342static void print_objc_property_list32(uint32_t p,
4343 struct DisassembleInfo *info) {
4344 struct objc_property_list32 opl;
4345 struct objc_property32 op;
4346 const char *r;
4347 uint32_t offset, xoffset, left, j;
4348 SectionRef S, xS;
4349 const char *name;
4350
4351 r = get_pointer_32(p, offset, left, S, info);
4352 if (r == nullptr)
4353 return;
4354 memset(&opl, '\0', sizeof(struct objc_property_list32));
4355 if (left < sizeof(struct objc_property_list32)) {
4356 memcpy(&opl, r, left);
4357 outs() << " (objc_property_list entends past the end of the section)\n";
4358 } else
4359 memcpy(&opl, r, sizeof(struct objc_property_list32));
4360 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4361 swapStruct(opl);
4362 outs() << " entsize " << opl.entsize << "\n";
4363 outs() << " count " << opl.count << "\n";
4364
4365 p += sizeof(struct objc_property_list32);
4366 offset += sizeof(struct objc_property_list32);
4367 for (j = 0; j < opl.count; j++) {
4368 r = get_pointer_32(p, offset, left, S, info);
4369 if (r == nullptr)
4370 return;
4371 memset(&op, '\0', sizeof(struct objc_property32));
4372 if (left < sizeof(struct objc_property32)) {
4373 memcpy(&op, r, left);
4374 outs() << " (objc_property entends past the end of the section)\n";
4375 } else
4376 memcpy(&op, r, sizeof(struct objc_property32));
4377 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4378 swapStruct(op);
4379
4380 outs() << "\t\t\t name " << format("0x%" PRIx32, op.name);
4381 name = get_pointer_32(op.name, xoffset, left, xS, info);
4382 if (name != nullptr)
4383 outs() << format(" %.*s", left, name);
4384 outs() << "\n";
4385
4386 outs() << "\t\t\tattributes " << format("0x%" PRIx32, op.attributes);
4387 name = get_pointer_32(op.attributes, xoffset, left, xS, info);
4388 if (name != nullptr)
4389 outs() << format(" %.*s", left, name);
4390 outs() << "\n";
4391
4392 p += sizeof(struct objc_property32);
4393 offset += sizeof(struct objc_property32);
4394 }
4395}
4396
Richard Smith81ff44d2015-10-09 22:09:56 +00004397static bool print_class_ro64_t(uint64_t p, struct DisassembleInfo *info,
Kevin Enderby0fc11822015-04-01 20:57:01 +00004398 bool &is_meta_class) {
4399 struct class_ro64_t cro;
4400 const char *r;
4401 uint32_t offset, xoffset, left;
4402 SectionRef S, xS;
4403 const char *name, *sym_name;
4404 uint64_t n_value;
4405
4406 r = get_pointer_64(p, offset, left, S, info);
4407 if (r == nullptr || left < sizeof(struct class_ro64_t))
Richard Smith81ff44d2015-10-09 22:09:56 +00004408 return false;
Kevin Enderby0fc11822015-04-01 20:57:01 +00004409 memset(&cro, '\0', sizeof(struct class_ro64_t));
4410 if (left < sizeof(struct class_ro64_t)) {
4411 memcpy(&cro, r, left);
4412 outs() << " (class_ro_t entends past the end of the section)\n";
4413 } else
4414 memcpy(&cro, r, sizeof(struct class_ro64_t));
4415 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4416 swapStruct(cro);
4417 outs() << " flags " << format("0x%" PRIx32, cro.flags);
4418 if (cro.flags & RO_META)
4419 outs() << " RO_META";
4420 if (cro.flags & RO_ROOT)
4421 outs() << " RO_ROOT";
4422 if (cro.flags & RO_HAS_CXX_STRUCTORS)
4423 outs() << " RO_HAS_CXX_STRUCTORS";
4424 outs() << "\n";
4425 outs() << " instanceStart " << cro.instanceStart << "\n";
4426 outs() << " instanceSize " << cro.instanceSize << "\n";
4427 outs() << " reserved " << format("0x%" PRIx32, cro.reserved)
4428 << "\n";
4429 outs() << " ivarLayout " << format("0x%" PRIx64, cro.ivarLayout)
4430 << "\n";
4431 print_layout_map64(cro.ivarLayout, info);
4432
4433 outs() << " name ";
4434 sym_name = get_symbol_64(offset + offsetof(struct class_ro64_t, name), S,
4435 info, n_value, cro.name);
4436 if (n_value != 0) {
4437 if (info->verbose && sym_name != nullptr)
4438 outs() << sym_name;
4439 else
4440 outs() << format("0x%" PRIx64, n_value);
4441 if (cro.name != 0)
4442 outs() << " + " << format("0x%" PRIx64, cro.name);
4443 } else
4444 outs() << format("0x%" PRIx64, cro.name);
4445 name = get_pointer_64(cro.name + n_value, xoffset, left, xS, info);
4446 if (name != nullptr)
4447 outs() << format(" %.*s", left, name);
4448 outs() << "\n";
4449
4450 outs() << " baseMethods ";
4451 sym_name = get_symbol_64(offset + offsetof(struct class_ro64_t, baseMethods),
4452 S, info, n_value, cro.baseMethods);
4453 if (n_value != 0) {
4454 if (info->verbose && sym_name != nullptr)
4455 outs() << sym_name;
4456 else
4457 outs() << format("0x%" PRIx64, n_value);
4458 if (cro.baseMethods != 0)
4459 outs() << " + " << format("0x%" PRIx64, cro.baseMethods);
4460 } else
4461 outs() << format("0x%" PRIx64, cro.baseMethods);
4462 outs() << " (struct method_list_t *)\n";
4463 if (cro.baseMethods + n_value != 0)
4464 print_method_list64_t(cro.baseMethods + n_value, info, "");
4465
4466 outs() << " baseProtocols ";
4467 sym_name =
4468 get_symbol_64(offset + offsetof(struct class_ro64_t, baseProtocols), S,
4469 info, n_value, cro.baseProtocols);
4470 if (n_value != 0) {
4471 if (info->verbose && sym_name != nullptr)
4472 outs() << sym_name;
4473 else
4474 outs() << format("0x%" PRIx64, n_value);
4475 if (cro.baseProtocols != 0)
4476 outs() << " + " << format("0x%" PRIx64, cro.baseProtocols);
4477 } else
4478 outs() << format("0x%" PRIx64, cro.baseProtocols);
4479 outs() << "\n";
4480 if (cro.baseProtocols + n_value != 0)
4481 print_protocol_list64_t(cro.baseProtocols + n_value, info);
4482
4483 outs() << " ivars ";
4484 sym_name = get_symbol_64(offset + offsetof(struct class_ro64_t, ivars), S,
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004485 info, n_value, cro.ivars);
Kevin Enderby0fc11822015-04-01 20:57:01 +00004486 if (n_value != 0) {
4487 if (info->verbose && sym_name != nullptr)
4488 outs() << sym_name;
4489 else
4490 outs() << format("0x%" PRIx64, n_value);
4491 if (cro.ivars != 0)
4492 outs() << " + " << format("0x%" PRIx64, cro.ivars);
4493 } else
4494 outs() << format("0x%" PRIx64, cro.ivars);
4495 outs() << "\n";
4496 if (cro.ivars + n_value != 0)
4497 print_ivar_list64_t(cro.ivars + n_value, info);
4498
4499 outs() << " weakIvarLayout ";
4500 sym_name =
4501 get_symbol_64(offset + offsetof(struct class_ro64_t, weakIvarLayout), S,
4502 info, n_value, cro.weakIvarLayout);
4503 if (n_value != 0) {
4504 if (info->verbose && sym_name != nullptr)
4505 outs() << sym_name;
4506 else
4507 outs() << format("0x%" PRIx64, n_value);
4508 if (cro.weakIvarLayout != 0)
4509 outs() << " + " << format("0x%" PRIx64, cro.weakIvarLayout);
4510 } else
4511 outs() << format("0x%" PRIx64, cro.weakIvarLayout);
4512 outs() << "\n";
4513 print_layout_map64(cro.weakIvarLayout + n_value, info);
4514
4515 outs() << " baseProperties ";
4516 sym_name =
4517 get_symbol_64(offset + offsetof(struct class_ro64_t, baseProperties), S,
4518 info, n_value, cro.baseProperties);
4519 if (n_value != 0) {
4520 if (info->verbose && sym_name != nullptr)
4521 outs() << sym_name;
4522 else
4523 outs() << format("0x%" PRIx64, n_value);
4524 if (cro.baseProperties != 0)
4525 outs() << " + " << format("0x%" PRIx64, cro.baseProperties);
4526 } else
4527 outs() << format("0x%" PRIx64, cro.baseProperties);
4528 outs() << "\n";
4529 if (cro.baseProperties + n_value != 0)
4530 print_objc_property_list64(cro.baseProperties + n_value, info);
4531
Rafael Espindolab9091322015-10-24 23:19:10 +00004532 is_meta_class = (cro.flags & RO_META) != 0;
Richard Smith81ff44d2015-10-09 22:09:56 +00004533 return true;
Kevin Enderby0fc11822015-04-01 20:57:01 +00004534}
4535
Richard Smith81ff44d2015-10-09 22:09:56 +00004536static bool print_class_ro32_t(uint32_t p, struct DisassembleInfo *info,
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004537 bool &is_meta_class) {
4538 struct class_ro32_t cro;
4539 const char *r;
4540 uint32_t offset, xoffset, left;
4541 SectionRef S, xS;
4542 const char *name;
4543
4544 r = get_pointer_32(p, offset, left, S, info);
4545 if (r == nullptr)
Richard Smith81ff44d2015-10-09 22:09:56 +00004546 return false;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004547 memset(&cro, '\0', sizeof(struct class_ro32_t));
4548 if (left < sizeof(struct class_ro32_t)) {
4549 memcpy(&cro, r, left);
4550 outs() << " (class_ro_t entends past the end of the section)\n";
4551 } else
4552 memcpy(&cro, r, sizeof(struct class_ro32_t));
4553 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4554 swapStruct(cro);
4555 outs() << " flags " << format("0x%" PRIx32, cro.flags);
4556 if (cro.flags & RO_META)
4557 outs() << " RO_META";
4558 if (cro.flags & RO_ROOT)
4559 outs() << " RO_ROOT";
4560 if (cro.flags & RO_HAS_CXX_STRUCTORS)
4561 outs() << " RO_HAS_CXX_STRUCTORS";
4562 outs() << "\n";
4563 outs() << " instanceStart " << cro.instanceStart << "\n";
4564 outs() << " instanceSize " << cro.instanceSize << "\n";
4565 outs() << " ivarLayout " << format("0x%" PRIx32, cro.ivarLayout)
4566 << "\n";
4567 print_layout_map32(cro.ivarLayout, info);
4568
4569 outs() << " name " << format("0x%" PRIx32, cro.name);
4570 name = get_pointer_32(cro.name, xoffset, left, xS, info);
4571 if (name != nullptr)
4572 outs() << format(" %.*s", left, name);
4573 outs() << "\n";
4574
4575 outs() << " baseMethods "
4576 << format("0x%" PRIx32, cro.baseMethods)
4577 << " (struct method_list_t *)\n";
4578 if (cro.baseMethods != 0)
4579 print_method_list32_t(cro.baseMethods, info, "");
4580
4581 outs() << " baseProtocols "
4582 << format("0x%" PRIx32, cro.baseProtocols) << "\n";
4583 if (cro.baseProtocols != 0)
4584 print_protocol_list32_t(cro.baseProtocols, info);
4585 outs() << " ivars " << format("0x%" PRIx32, cro.ivars)
4586 << "\n";
4587 if (cro.ivars != 0)
4588 print_ivar_list32_t(cro.ivars, info);
4589 outs() << " weakIvarLayout "
4590 << format("0x%" PRIx32, cro.weakIvarLayout) << "\n";
4591 print_layout_map32(cro.weakIvarLayout, info);
4592 outs() << " baseProperties "
4593 << format("0x%" PRIx32, cro.baseProperties) << "\n";
4594 if (cro.baseProperties != 0)
4595 print_objc_property_list32(cro.baseProperties, info);
Rafael Espindolab9091322015-10-24 23:19:10 +00004596 is_meta_class = (cro.flags & RO_META) != 0;
Richard Smith81ff44d2015-10-09 22:09:56 +00004597 return true;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004598}
4599
Kevin Enderby0fc11822015-04-01 20:57:01 +00004600static void print_class64_t(uint64_t p, struct DisassembleInfo *info) {
4601 struct class64_t c;
4602 const char *r;
4603 uint32_t offset, left;
4604 SectionRef S;
4605 const char *name;
4606 uint64_t isa_n_value, n_value;
4607
4608 r = get_pointer_64(p, offset, left, S, info);
4609 if (r == nullptr || left < sizeof(struct class64_t))
4610 return;
4611 memset(&c, '\0', sizeof(struct class64_t));
4612 if (left < sizeof(struct class64_t)) {
4613 memcpy(&c, r, left);
4614 outs() << " (class_t entends past the end of the section)\n";
4615 } else
4616 memcpy(&c, r, sizeof(struct class64_t));
4617 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4618 swapStruct(c);
4619
4620 outs() << " isa " << format("0x%" PRIx64, c.isa);
4621 name = get_symbol_64(offset + offsetof(struct class64_t, isa), S, info,
4622 isa_n_value, c.isa);
4623 if (name != nullptr)
4624 outs() << " " << name;
4625 outs() << "\n";
4626
4627 outs() << " superclass " << format("0x%" PRIx64, c.superclass);
4628 name = get_symbol_64(offset + offsetof(struct class64_t, superclass), S, info,
4629 n_value, c.superclass);
4630 if (name != nullptr)
4631 outs() << " " << name;
4632 outs() << "\n";
4633
4634 outs() << " cache " << format("0x%" PRIx64, c.cache);
4635 name = get_symbol_64(offset + offsetof(struct class64_t, cache), S, info,
4636 n_value, c.cache);
4637 if (name != nullptr)
4638 outs() << " " << name;
4639 outs() << "\n";
4640
4641 outs() << " vtable " << format("0x%" PRIx64, c.vtable);
4642 name = get_symbol_64(offset + offsetof(struct class64_t, vtable), S, info,
4643 n_value, c.vtable);
4644 if (name != nullptr)
4645 outs() << " " << name;
4646 outs() << "\n";
4647
4648 name = get_symbol_64(offset + offsetof(struct class64_t, data), S, info,
4649 n_value, c.data);
4650 outs() << " data ";
4651 if (n_value != 0) {
4652 if (info->verbose && name != nullptr)
4653 outs() << name;
4654 else
4655 outs() << format("0x%" PRIx64, n_value);
4656 if (c.data != 0)
4657 outs() << " + " << format("0x%" PRIx64, c.data);
4658 } else
4659 outs() << format("0x%" PRIx64, c.data);
4660 outs() << " (struct class_ro_t *)";
4661
4662 // This is a Swift class if some of the low bits of the pointer are set.
4663 if ((c.data + n_value) & 0x7)
4664 outs() << " Swift class";
4665 outs() << "\n";
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004666 bool is_meta_class;
Richard Smith81ff44d2015-10-09 22:09:56 +00004667 if (!print_class_ro64_t((c.data + n_value) & ~0x7, info, is_meta_class))
4668 return;
Kevin Enderby0fc11822015-04-01 20:57:01 +00004669
Kevin Enderbyaac75382015-10-08 16:56:35 +00004670 if (!is_meta_class &&
4671 c.isa + isa_n_value != p &&
4672 c.isa + isa_n_value != 0 &&
4673 info->depth < 100) {
4674 info->depth++;
4675 outs() << "Meta Class\n";
4676 print_class64_t(c.isa + isa_n_value, info);
Kevin Enderby0fc11822015-04-01 20:57:01 +00004677 }
4678}
4679
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004680static void print_class32_t(uint32_t p, struct DisassembleInfo *info) {
4681 struct class32_t c;
4682 const char *r;
4683 uint32_t offset, left;
4684 SectionRef S;
4685 const char *name;
4686
4687 r = get_pointer_32(p, offset, left, S, info);
4688 if (r == nullptr)
4689 return;
4690 memset(&c, '\0', sizeof(struct class32_t));
4691 if (left < sizeof(struct class32_t)) {
4692 memcpy(&c, r, left);
4693 outs() << " (class_t entends past the end of the section)\n";
4694 } else
4695 memcpy(&c, r, sizeof(struct class32_t));
4696 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4697 swapStruct(c);
4698
4699 outs() << " isa " << format("0x%" PRIx32, c.isa);
4700 name =
4701 get_symbol_32(offset + offsetof(struct class32_t, isa), S, info, c.isa);
4702 if (name != nullptr)
4703 outs() << " " << name;
4704 outs() << "\n";
4705
4706 outs() << " superclass " << format("0x%" PRIx32, c.superclass);
4707 name = get_symbol_32(offset + offsetof(struct class32_t, superclass), S, info,
4708 c.superclass);
4709 if (name != nullptr)
4710 outs() << " " << name;
4711 outs() << "\n";
4712
4713 outs() << " cache " << format("0x%" PRIx32, c.cache);
4714 name = get_symbol_32(offset + offsetof(struct class32_t, cache), S, info,
4715 c.cache);
4716 if (name != nullptr)
4717 outs() << " " << name;
4718 outs() << "\n";
4719
4720 outs() << " vtable " << format("0x%" PRIx32, c.vtable);
4721 name = get_symbol_32(offset + offsetof(struct class32_t, vtable), S, info,
4722 c.vtable);
4723 if (name != nullptr)
4724 outs() << " " << name;
4725 outs() << "\n";
4726
4727 name =
4728 get_symbol_32(offset + offsetof(struct class32_t, data), S, info, c.data);
4729 outs() << " data " << format("0x%" PRIx32, c.data)
4730 << " (struct class_ro_t *)";
4731
4732 // This is a Swift class if some of the low bits of the pointer are set.
4733 if (c.data & 0x3)
4734 outs() << " Swift class";
4735 outs() << "\n";
4736 bool is_meta_class;
Richard Smith81ff44d2015-10-09 22:09:56 +00004737 if (!print_class_ro32_t(c.data & ~0x3, info, is_meta_class))
4738 return;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004739
Hans Wennborgcc9deb42015-09-29 18:02:48 +00004740 if (!is_meta_class) {
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004741 outs() << "Meta Class\n";
4742 print_class32_t(c.isa, info);
4743 }
4744}
4745
Kevin Enderby846c0002015-04-16 17:19:59 +00004746static void print_objc_class_t(struct objc_class_t *objc_class,
4747 struct DisassembleInfo *info) {
4748 uint32_t offset, left, xleft;
4749 const char *name, *p, *ivar_list;
4750 SectionRef S;
4751 int32_t i;
4752 struct objc_ivar_list_t objc_ivar_list;
4753 struct objc_ivar_t ivar;
4754
4755 outs() << "\t\t isa " << format("0x%08" PRIx32, objc_class->isa);
4756 if (info->verbose && CLS_GETINFO(objc_class, CLS_META)) {
4757 name = get_pointer_32(objc_class->isa, offset, left, S, info, true);
4758 if (name != nullptr)
4759 outs() << format(" %.*s", left, name);
4760 else
4761 outs() << " (not in an __OBJC section)";
4762 }
4763 outs() << "\n";
4764
4765 outs() << "\t super_class "
4766 << format("0x%08" PRIx32, objc_class->super_class);
4767 if (info->verbose) {
4768 name = get_pointer_32(objc_class->super_class, offset, left, S, info, true);
4769 if (name != nullptr)
4770 outs() << format(" %.*s", left, name);
4771 else
4772 outs() << " (not in an __OBJC section)";
4773 }
4774 outs() << "\n";
4775
4776 outs() << "\t\t name " << format("0x%08" PRIx32, objc_class->name);
4777 if (info->verbose) {
4778 name = get_pointer_32(objc_class->name, offset, left, S, info, true);
4779 if (name != nullptr)
4780 outs() << format(" %.*s", left, name);
4781 else
4782 outs() << " (not in an __OBJC section)";
4783 }
4784 outs() << "\n";
4785
4786 outs() << "\t\t version " << format("0x%08" PRIx32, objc_class->version)
4787 << "\n";
4788
4789 outs() << "\t\t info " << format("0x%08" PRIx32, objc_class->info);
4790 if (info->verbose) {
4791 if (CLS_GETINFO(objc_class, CLS_CLASS))
4792 outs() << " CLS_CLASS";
4793 else if (CLS_GETINFO(objc_class, CLS_META))
4794 outs() << " CLS_META";
4795 }
4796 outs() << "\n";
4797
4798 outs() << "\t instance_size "
4799 << format("0x%08" PRIx32, objc_class->instance_size) << "\n";
4800
4801 p = get_pointer_32(objc_class->ivars, offset, left, S, info, true);
4802 outs() << "\t\t ivars " << format("0x%08" PRIx32, objc_class->ivars);
4803 if (p != nullptr) {
4804 if (left > sizeof(struct objc_ivar_list_t)) {
4805 outs() << "\n";
4806 memcpy(&objc_ivar_list, p, sizeof(struct objc_ivar_list_t));
4807 } else {
4808 outs() << " (entends past the end of the section)\n";
4809 memset(&objc_ivar_list, '\0', sizeof(struct objc_ivar_list_t));
4810 memcpy(&objc_ivar_list, p, left);
4811 }
4812 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4813 swapStruct(objc_ivar_list);
4814 outs() << "\t\t ivar_count " << objc_ivar_list.ivar_count << "\n";
4815 ivar_list = p + sizeof(struct objc_ivar_list_t);
4816 for (i = 0; i < objc_ivar_list.ivar_count; i++) {
4817 if ((i + 1) * sizeof(struct objc_ivar_t) > left) {
4818 outs() << "\t\t remaining ivar's extend past the of the section\n";
4819 break;
4820 }
4821 memcpy(&ivar, ivar_list + i * sizeof(struct objc_ivar_t),
4822 sizeof(struct objc_ivar_t));
4823 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4824 swapStruct(ivar);
4825
4826 outs() << "\t\t\tivar_name " << format("0x%08" PRIx32, ivar.ivar_name);
4827 if (info->verbose) {
4828 name = get_pointer_32(ivar.ivar_name, offset, xleft, S, info, true);
4829 if (name != nullptr)
4830 outs() << format(" %.*s", xleft, name);
4831 else
4832 outs() << " (not in an __OBJC section)";
4833 }
4834 outs() << "\n";
4835
4836 outs() << "\t\t\tivar_type " << format("0x%08" PRIx32, ivar.ivar_type);
4837 if (info->verbose) {
4838 name = get_pointer_32(ivar.ivar_type, offset, xleft, S, info, true);
4839 if (name != nullptr)
4840 outs() << format(" %.*s", xleft, name);
4841 else
4842 outs() << " (not in an __OBJC section)";
4843 }
4844 outs() << "\n";
4845
4846 outs() << "\t\t ivar_offset "
4847 << format("0x%08" PRIx32, ivar.ivar_offset) << "\n";
4848 }
4849 } else {
4850 outs() << " (not in an __OBJC section)\n";
4851 }
4852
4853 outs() << "\t\t methods " << format("0x%08" PRIx32, objc_class->methodLists);
4854 if (print_method_list(objc_class->methodLists, info))
4855 outs() << " (not in an __OBJC section)\n";
4856
4857 outs() << "\t\t cache " << format("0x%08" PRIx32, objc_class->cache)
4858 << "\n";
4859
4860 outs() << "\t\tprotocols " << format("0x%08" PRIx32, objc_class->protocols);
4861 if (print_protocol_list(objc_class->protocols, 16, info))
4862 outs() << " (not in an __OBJC section)\n";
4863}
4864
4865static void print_objc_objc_category_t(struct objc_category_t *objc_category,
4866 struct DisassembleInfo *info) {
4867 uint32_t offset, left;
4868 const char *name;
4869 SectionRef S;
4870
4871 outs() << "\t category name "
4872 << format("0x%08" PRIx32, objc_category->category_name);
4873 if (info->verbose) {
4874 name = get_pointer_32(objc_category->category_name, offset, left, S, info,
4875 true);
4876 if (name != nullptr)
4877 outs() << format(" %.*s", left, name);
4878 else
4879 outs() << " (not in an __OBJC section)";
4880 }
4881 outs() << "\n";
4882
4883 outs() << "\t\t class name "
4884 << format("0x%08" PRIx32, objc_category->class_name);
4885 if (info->verbose) {
4886 name =
4887 get_pointer_32(objc_category->class_name, offset, left, S, info, true);
4888 if (name != nullptr)
4889 outs() << format(" %.*s", left, name);
4890 else
4891 outs() << " (not in an __OBJC section)";
4892 }
4893 outs() << "\n";
4894
4895 outs() << "\t instance methods "
4896 << format("0x%08" PRIx32, objc_category->instance_methods);
4897 if (print_method_list(objc_category->instance_methods, info))
4898 outs() << " (not in an __OBJC section)\n";
4899
4900 outs() << "\t class methods "
4901 << format("0x%08" PRIx32, objc_category->class_methods);
4902 if (print_method_list(objc_category->class_methods, info))
4903 outs() << " (not in an __OBJC section)\n";
4904}
4905
Kevin Enderby0fc11822015-04-01 20:57:01 +00004906static void print_category64_t(uint64_t p, struct DisassembleInfo *info) {
4907 struct category64_t c;
4908 const char *r;
4909 uint32_t offset, xoffset, left;
4910 SectionRef S, xS;
4911 const char *name, *sym_name;
4912 uint64_t n_value;
4913
4914 r = get_pointer_64(p, offset, left, S, info);
4915 if (r == nullptr)
4916 return;
4917 memset(&c, '\0', sizeof(struct category64_t));
4918 if (left < sizeof(struct category64_t)) {
4919 memcpy(&c, r, left);
4920 outs() << " (category_t entends past the end of the section)\n";
4921 } else
4922 memcpy(&c, r, sizeof(struct category64_t));
4923 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4924 swapStruct(c);
4925
4926 outs() << " name ";
4927 sym_name = get_symbol_64(offset + offsetof(struct category64_t, name), S,
4928 info, n_value, c.name);
4929 if (n_value != 0) {
4930 if (info->verbose && sym_name != nullptr)
4931 outs() << sym_name;
4932 else
4933 outs() << format("0x%" PRIx64, n_value);
4934 if (c.name != 0)
4935 outs() << " + " << format("0x%" PRIx64, c.name);
4936 } else
4937 outs() << format("0x%" PRIx64, c.name);
4938 name = get_pointer_64(c.name + n_value, xoffset, left, xS, info);
4939 if (name != nullptr)
4940 outs() << format(" %.*s", left, name);
4941 outs() << "\n";
4942
4943 outs() << " cls ";
4944 sym_name = get_symbol_64(offset + offsetof(struct category64_t, cls), S, info,
4945 n_value, c.cls);
4946 if (n_value != 0) {
4947 if (info->verbose && sym_name != nullptr)
4948 outs() << sym_name;
4949 else
4950 outs() << format("0x%" PRIx64, n_value);
4951 if (c.cls != 0)
4952 outs() << " + " << format("0x%" PRIx64, c.cls);
4953 } else
4954 outs() << format("0x%" PRIx64, c.cls);
4955 outs() << "\n";
4956 if (c.cls + n_value != 0)
4957 print_class64_t(c.cls + n_value, info);
4958
4959 outs() << " instanceMethods ";
4960 sym_name =
4961 get_symbol_64(offset + offsetof(struct category64_t, instanceMethods), S,
4962 info, n_value, c.instanceMethods);
4963 if (n_value != 0) {
4964 if (info->verbose && sym_name != nullptr)
4965 outs() << sym_name;
4966 else
4967 outs() << format("0x%" PRIx64, n_value);
4968 if (c.instanceMethods != 0)
4969 outs() << " + " << format("0x%" PRIx64, c.instanceMethods);
4970 } else
4971 outs() << format("0x%" PRIx64, c.instanceMethods);
4972 outs() << "\n";
4973 if (c.instanceMethods + n_value != 0)
4974 print_method_list64_t(c.instanceMethods + n_value, info, "");
4975
4976 outs() << " classMethods ";
4977 sym_name = get_symbol_64(offset + offsetof(struct category64_t, classMethods),
4978 S, info, n_value, c.classMethods);
4979 if (n_value != 0) {
4980 if (info->verbose && sym_name != nullptr)
4981 outs() << sym_name;
4982 else
4983 outs() << format("0x%" PRIx64, n_value);
4984 if (c.classMethods != 0)
4985 outs() << " + " << format("0x%" PRIx64, c.classMethods);
4986 } else
4987 outs() << format("0x%" PRIx64, c.classMethods);
4988 outs() << "\n";
4989 if (c.classMethods + n_value != 0)
4990 print_method_list64_t(c.classMethods + n_value, info, "");
4991
4992 outs() << " protocols ";
4993 sym_name = get_symbol_64(offset + offsetof(struct category64_t, protocols), S,
4994 info, n_value, c.protocols);
4995 if (n_value != 0) {
4996 if (info->verbose && sym_name != nullptr)
4997 outs() << sym_name;
4998 else
4999 outs() << format("0x%" PRIx64, n_value);
5000 if (c.protocols != 0)
5001 outs() << " + " << format("0x%" PRIx64, c.protocols);
5002 } else
5003 outs() << format("0x%" PRIx64, c.protocols);
5004 outs() << "\n";
5005 if (c.protocols + n_value != 0)
5006 print_protocol_list64_t(c.protocols + n_value, info);
5007
5008 outs() << "instanceProperties ";
5009 sym_name =
5010 get_symbol_64(offset + offsetof(struct category64_t, instanceProperties),
5011 S, info, n_value, c.instanceProperties);
5012 if (n_value != 0) {
5013 if (info->verbose && sym_name != nullptr)
5014 outs() << sym_name;
5015 else
5016 outs() << format("0x%" PRIx64, n_value);
5017 if (c.instanceProperties != 0)
5018 outs() << " + " << format("0x%" PRIx64, c.instanceProperties);
5019 } else
5020 outs() << format("0x%" PRIx64, c.instanceProperties);
5021 outs() << "\n";
5022 if (c.instanceProperties + n_value != 0)
5023 print_objc_property_list64(c.instanceProperties + n_value, info);
5024}
5025
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005026static void print_category32_t(uint32_t p, struct DisassembleInfo *info) {
5027 struct category32_t c;
5028 const char *r;
5029 uint32_t offset, left;
5030 SectionRef S, xS;
5031 const char *name;
5032
5033 r = get_pointer_32(p, offset, left, S, info);
5034 if (r == nullptr)
5035 return;
5036 memset(&c, '\0', sizeof(struct category32_t));
5037 if (left < sizeof(struct category32_t)) {
5038 memcpy(&c, r, left);
5039 outs() << " (category_t entends past the end of the section)\n";
5040 } else
5041 memcpy(&c, r, sizeof(struct category32_t));
5042 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5043 swapStruct(c);
5044
5045 outs() << " name " << format("0x%" PRIx32, c.name);
5046 name = get_symbol_32(offset + offsetof(struct category32_t, name), S, info,
5047 c.name);
Hans Wennborgcc9deb42015-09-29 18:02:48 +00005048 if (name)
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005049 outs() << " " << name;
5050 outs() << "\n";
5051
5052 outs() << " cls " << format("0x%" PRIx32, c.cls) << "\n";
5053 if (c.cls != 0)
5054 print_class32_t(c.cls, info);
5055 outs() << " instanceMethods " << format("0x%" PRIx32, c.instanceMethods)
5056 << "\n";
5057 if (c.instanceMethods != 0)
5058 print_method_list32_t(c.instanceMethods, info, "");
5059 outs() << " classMethods " << format("0x%" PRIx32, c.classMethods)
5060 << "\n";
5061 if (c.classMethods != 0)
5062 print_method_list32_t(c.classMethods, info, "");
5063 outs() << " protocols " << format("0x%" PRIx32, c.protocols) << "\n";
5064 if (c.protocols != 0)
5065 print_protocol_list32_t(c.protocols, info);
5066 outs() << "instanceProperties " << format("0x%" PRIx32, c.instanceProperties)
5067 << "\n";
5068 if (c.instanceProperties != 0)
5069 print_objc_property_list32(c.instanceProperties, info);
5070}
5071
Kevin Enderby0fc11822015-04-01 20:57:01 +00005072static void print_message_refs64(SectionRef S, struct DisassembleInfo *info) {
5073 uint32_t i, left, offset, xoffset;
5074 uint64_t p, n_value;
5075 struct message_ref64 mr;
5076 const char *name, *sym_name;
5077 const char *r;
5078 SectionRef xS;
5079
5080 if (S == SectionRef())
5081 return;
5082
5083 StringRef SectName;
5084 S.getName(SectName);
5085 DataRefImpl Ref = S.getRawDataRefImpl();
5086 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5087 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5088 offset = 0;
5089 for (i = 0; i < S.getSize(); i += sizeof(struct message_ref64)) {
5090 p = S.getAddress() + i;
5091 r = get_pointer_64(p, offset, left, S, info);
5092 if (r == nullptr)
5093 return;
5094 memset(&mr, '\0', sizeof(struct message_ref64));
5095 if (left < sizeof(struct message_ref64)) {
5096 memcpy(&mr, r, left);
5097 outs() << " (message_ref entends past the end of the section)\n";
5098 } else
5099 memcpy(&mr, r, sizeof(struct message_ref64));
5100 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5101 swapStruct(mr);
5102
5103 outs() << " imp ";
5104 name = get_symbol_64(offset + offsetof(struct message_ref64, imp), S, info,
5105 n_value, mr.imp);
5106 if (n_value != 0) {
5107 outs() << format("0x%" PRIx64, n_value) << " ";
5108 if (mr.imp != 0)
5109 outs() << "+ " << format("0x%" PRIx64, mr.imp) << " ";
5110 } else
5111 outs() << format("0x%" PRIx64, mr.imp) << " ";
5112 if (name != nullptr)
5113 outs() << " " << name;
5114 outs() << "\n";
5115
5116 outs() << " sel ";
5117 sym_name = get_symbol_64(offset + offsetof(struct message_ref64, sel), S,
5118 info, n_value, mr.sel);
5119 if (n_value != 0) {
5120 if (info->verbose && sym_name != nullptr)
5121 outs() << sym_name;
5122 else
5123 outs() << format("0x%" PRIx64, n_value);
5124 if (mr.sel != 0)
5125 outs() << " + " << format("0x%" PRIx64, mr.sel);
5126 } else
5127 outs() << format("0x%" PRIx64, mr.sel);
5128 name = get_pointer_64(mr.sel + n_value, xoffset, left, xS, info);
5129 if (name != nullptr)
5130 outs() << format(" %.*s", left, name);
5131 outs() << "\n";
5132
5133 offset += sizeof(struct message_ref64);
5134 }
5135}
5136
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005137static void print_message_refs32(SectionRef S, struct DisassembleInfo *info) {
5138 uint32_t i, left, offset, xoffset, p;
5139 struct message_ref32 mr;
5140 const char *name, *r;
5141 SectionRef xS;
5142
5143 if (S == SectionRef())
5144 return;
5145
5146 StringRef SectName;
5147 S.getName(SectName);
5148 DataRefImpl Ref = S.getRawDataRefImpl();
5149 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5150 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5151 offset = 0;
5152 for (i = 0; i < S.getSize(); i += sizeof(struct message_ref64)) {
5153 p = S.getAddress() + i;
5154 r = get_pointer_32(p, offset, left, S, info);
5155 if (r == nullptr)
5156 return;
5157 memset(&mr, '\0', sizeof(struct message_ref32));
5158 if (left < sizeof(struct message_ref32)) {
5159 memcpy(&mr, r, left);
5160 outs() << " (message_ref entends past the end of the section)\n";
5161 } else
5162 memcpy(&mr, r, sizeof(struct message_ref32));
5163 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5164 swapStruct(mr);
5165
5166 outs() << " imp " << format("0x%" PRIx32, mr.imp);
5167 name = get_symbol_32(offset + offsetof(struct message_ref32, imp), S, info,
5168 mr.imp);
5169 if (name != nullptr)
5170 outs() << " " << name;
5171 outs() << "\n";
5172
5173 outs() << " sel " << format("0x%" PRIx32, mr.sel);
5174 name = get_pointer_32(mr.sel, xoffset, left, xS, info);
5175 if (name != nullptr)
5176 outs() << " " << name;
5177 outs() << "\n";
5178
5179 offset += sizeof(struct message_ref32);
5180 }
5181}
5182
Kevin Enderby0fc11822015-04-01 20:57:01 +00005183static void print_image_info64(SectionRef S, struct DisassembleInfo *info) {
5184 uint32_t left, offset, swift_version;
5185 uint64_t p;
5186 struct objc_image_info64 o;
5187 const char *r;
5188
Kevin Enderbyaf7c9d02015-10-09 16:48:44 +00005189 if (S == SectionRef())
5190 return;
5191
Kevin Enderby0fc11822015-04-01 20:57:01 +00005192 StringRef SectName;
5193 S.getName(SectName);
5194 DataRefImpl Ref = S.getRawDataRefImpl();
5195 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5196 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5197 p = S.getAddress();
5198 r = get_pointer_64(p, offset, left, S, info);
5199 if (r == nullptr)
5200 return;
5201 memset(&o, '\0', sizeof(struct objc_image_info64));
5202 if (left < sizeof(struct objc_image_info64)) {
5203 memcpy(&o, r, left);
5204 outs() << " (objc_image_info entends past the end of the section)\n";
5205 } else
5206 memcpy(&o, r, sizeof(struct objc_image_info64));
5207 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5208 swapStruct(o);
5209 outs() << " version " << o.version << "\n";
5210 outs() << " flags " << format("0x%" PRIx32, o.flags);
5211 if (o.flags & OBJC_IMAGE_IS_REPLACEMENT)
5212 outs() << " OBJC_IMAGE_IS_REPLACEMENT";
5213 if (o.flags & OBJC_IMAGE_SUPPORTS_GC)
5214 outs() << " OBJC_IMAGE_SUPPORTS_GC";
5215 swift_version = (o.flags >> 8) & 0xff;
5216 if (swift_version != 0) {
5217 if (swift_version == 1)
5218 outs() << " Swift 1.0";
5219 else if (swift_version == 2)
5220 outs() << " Swift 1.1";
5221 else
5222 outs() << " unknown future Swift version (" << swift_version << ")";
5223 }
5224 outs() << "\n";
5225}
5226
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005227static void print_image_info32(SectionRef S, struct DisassembleInfo *info) {
5228 uint32_t left, offset, swift_version, p;
5229 struct objc_image_info32 o;
5230 const char *r;
5231
Kevin Enderby19be2512016-04-21 19:49:29 +00005232 if (S == SectionRef())
5233 return;
5234
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005235 StringRef SectName;
5236 S.getName(SectName);
5237 DataRefImpl Ref = S.getRawDataRefImpl();
5238 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5239 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5240 p = S.getAddress();
5241 r = get_pointer_32(p, offset, left, S, info);
5242 if (r == nullptr)
5243 return;
5244 memset(&o, '\0', sizeof(struct objc_image_info32));
5245 if (left < sizeof(struct objc_image_info32)) {
5246 memcpy(&o, r, left);
5247 outs() << " (objc_image_info entends past the end of the section)\n";
5248 } else
5249 memcpy(&o, r, sizeof(struct objc_image_info32));
5250 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5251 swapStruct(o);
5252 outs() << " version " << o.version << "\n";
5253 outs() << " flags " << format("0x%" PRIx32, o.flags);
5254 if (o.flags & OBJC_IMAGE_IS_REPLACEMENT)
5255 outs() << " OBJC_IMAGE_IS_REPLACEMENT";
5256 if (o.flags & OBJC_IMAGE_SUPPORTS_GC)
5257 outs() << " OBJC_IMAGE_SUPPORTS_GC";
5258 swift_version = (o.flags >> 8) & 0xff;
5259 if (swift_version != 0) {
5260 if (swift_version == 1)
5261 outs() << " Swift 1.0";
5262 else if (swift_version == 2)
5263 outs() << " Swift 1.1";
5264 else
5265 outs() << " unknown future Swift version (" << swift_version << ")";
5266 }
5267 outs() << "\n";
5268}
5269
Kevin Enderby846c0002015-04-16 17:19:59 +00005270static void print_image_info(SectionRef S, struct DisassembleInfo *info) {
5271 uint32_t left, offset, p;
5272 struct imageInfo_t o;
5273 const char *r;
5274
5275 StringRef SectName;
5276 S.getName(SectName);
5277 DataRefImpl Ref = S.getRawDataRefImpl();
5278 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5279 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5280 p = S.getAddress();
5281 r = get_pointer_32(p, offset, left, S, info);
5282 if (r == nullptr)
5283 return;
5284 memset(&o, '\0', sizeof(struct imageInfo_t));
5285 if (left < sizeof(struct imageInfo_t)) {
5286 memcpy(&o, r, left);
5287 outs() << " (imageInfo entends past the end of the section)\n";
5288 } else
5289 memcpy(&o, r, sizeof(struct imageInfo_t));
5290 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5291 swapStruct(o);
5292 outs() << " version " << o.version << "\n";
5293 outs() << " flags " << format("0x%" PRIx32, o.flags);
5294 if (o.flags & 0x1)
5295 outs() << " F&C";
5296 if (o.flags & 0x2)
5297 outs() << " GC";
5298 if (o.flags & 0x4)
5299 outs() << " GC-only";
5300 else
5301 outs() << " RR";
5302 outs() << "\n";
5303}
5304
Kevin Enderby0fc11822015-04-01 20:57:01 +00005305static void printObjc2_64bit_MetaData(MachOObjectFile *O, bool verbose) {
5306 SymbolAddressMap AddrMap;
5307 if (verbose)
5308 CreateSymbolAddressMap(O, &AddrMap);
5309
5310 std::vector<SectionRef> Sections;
5311 for (const SectionRef &Section : O->sections()) {
5312 StringRef SectName;
5313 Section.getName(SectName);
5314 Sections.push_back(Section);
5315 }
5316
5317 struct DisassembleInfo info;
5318 // Set up the block of info used by the Symbolizer call backs.
5319 info.verbose = verbose;
5320 info.O = O;
5321 info.AddrMap = &AddrMap;
5322 info.Sections = &Sections;
5323 info.class_name = nullptr;
5324 info.selector_name = nullptr;
5325 info.method = nullptr;
5326 info.demangled_name = nullptr;
5327 info.bindtable = nullptr;
5328 info.adrp_addr = 0;
5329 info.adrp_inst = 0;
5330
Kevin Enderbyaac75382015-10-08 16:56:35 +00005331 info.depth = 0;
Davide Italiano62507042015-12-11 22:27:59 +00005332 SectionRef CL = get_section(O, "__OBJC2", "__class_list");
5333 if (CL == SectionRef())
5334 CL = get_section(O, "__DATA", "__objc_classlist");
5335 info.S = CL;
5336 walk_pointer_list_64("class", CL, O, &info, print_class64_t);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005337
Davide Italiano62507042015-12-11 22:27:59 +00005338 SectionRef CR = get_section(O, "__OBJC2", "__class_refs");
5339 if (CR == SectionRef())
5340 CR = get_section(O, "__DATA", "__objc_classrefs");
5341 info.S = CR;
5342 walk_pointer_list_64("class refs", CR, O, &info, nullptr);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005343
Davide Italiano62507042015-12-11 22:27:59 +00005344 SectionRef SR = get_section(O, "__OBJC2", "__super_refs");
5345 if (SR == SectionRef())
5346 SR = get_section(O, "__DATA", "__objc_superrefs");
5347 info.S = SR;
5348 walk_pointer_list_64("super refs", SR, O, &info, nullptr);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005349
Davide Italiano62507042015-12-11 22:27:59 +00005350 SectionRef CA = get_section(O, "__OBJC2", "__category_list");
5351 if (CA == SectionRef())
5352 CA = get_section(O, "__DATA", "__objc_catlist");
5353 info.S = CA;
5354 walk_pointer_list_64("category", CA, O, &info, print_category64_t);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005355
Davide Italiano62507042015-12-11 22:27:59 +00005356 SectionRef PL = get_section(O, "__OBJC2", "__protocol_list");
5357 if (PL == SectionRef())
5358 PL = get_section(O, "__DATA", "__objc_protolist");
5359 info.S = PL;
5360 walk_pointer_list_64("protocol", PL, O, &info, nullptr);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005361
Davide Italiano62507042015-12-11 22:27:59 +00005362 SectionRef MR = get_section(O, "__OBJC2", "__message_refs");
5363 if (MR == SectionRef())
5364 MR = get_section(O, "__DATA", "__objc_msgrefs");
5365 info.S = MR;
5366 print_message_refs64(MR, &info);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005367
Davide Italiano62507042015-12-11 22:27:59 +00005368 SectionRef II = get_section(O, "__OBJC2", "__image_info");
5369 if (II == SectionRef())
5370 II = get_section(O, "__DATA", "__objc_imageinfo");
5371 info.S = II;
5372 print_image_info64(II, &info);
Kevin Enderby0bc6ed42015-04-01 21:50:45 +00005373
5374 if (info.bindtable != nullptr)
5375 delete info.bindtable;
Kevin Enderby0fc11822015-04-01 20:57:01 +00005376}
5377
5378static void printObjc2_32bit_MetaData(MachOObjectFile *O, bool verbose) {
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005379 SymbolAddressMap AddrMap;
5380 if (verbose)
5381 CreateSymbolAddressMap(O, &AddrMap);
5382
5383 std::vector<SectionRef> Sections;
5384 for (const SectionRef &Section : O->sections()) {
5385 StringRef SectName;
5386 Section.getName(SectName);
5387 Sections.push_back(Section);
5388 }
5389
5390 struct DisassembleInfo info;
5391 // Set up the block of info used by the Symbolizer call backs.
5392 info.verbose = verbose;
5393 info.O = O;
5394 info.AddrMap = &AddrMap;
5395 info.Sections = &Sections;
5396 info.class_name = nullptr;
5397 info.selector_name = nullptr;
5398 info.method = nullptr;
5399 info.demangled_name = nullptr;
5400 info.bindtable = nullptr;
5401 info.adrp_addr = 0;
5402 info.adrp_inst = 0;
5403
5404 const SectionRef CL = get_section(O, "__OBJC2", "__class_list");
5405 if (CL != SectionRef()) {
5406 info.S = CL;
5407 walk_pointer_list_32("class", CL, O, &info, print_class32_t);
5408 } else {
5409 const SectionRef CL = get_section(O, "__DATA", "__objc_classlist");
5410 info.S = CL;
5411 walk_pointer_list_32("class", CL, O, &info, print_class32_t);
5412 }
5413
5414 const SectionRef CR = get_section(O, "__OBJC2", "__class_refs");
5415 if (CR != SectionRef()) {
5416 info.S = CR;
5417 walk_pointer_list_32("class refs", CR, O, &info, nullptr);
5418 } else {
5419 const SectionRef CR = get_section(O, "__DATA", "__objc_classrefs");
5420 info.S = CR;
5421 walk_pointer_list_32("class refs", CR, O, &info, nullptr);
5422 }
5423
5424 const SectionRef SR = get_section(O, "__OBJC2", "__super_refs");
5425 if (SR != SectionRef()) {
5426 info.S = SR;
5427 walk_pointer_list_32("super refs", SR, O, &info, nullptr);
5428 } else {
5429 const SectionRef SR = get_section(O, "__DATA", "__objc_superrefs");
5430 info.S = SR;
5431 walk_pointer_list_32("super refs", SR, O, &info, nullptr);
5432 }
5433
5434 const SectionRef CA = get_section(O, "__OBJC2", "__category_list");
5435 if (CA != SectionRef()) {
5436 info.S = CA;
5437 walk_pointer_list_32("category", CA, O, &info, print_category32_t);
5438 } else {
5439 const SectionRef CA = get_section(O, "__DATA", "__objc_catlist");
5440 info.S = CA;
5441 walk_pointer_list_32("category", CA, O, &info, print_category32_t);
5442 }
5443
5444 const SectionRef PL = get_section(O, "__OBJC2", "__protocol_list");
5445 if (PL != SectionRef()) {
5446 info.S = PL;
5447 walk_pointer_list_32("protocol", PL, O, &info, nullptr);
5448 } else {
5449 const SectionRef PL = get_section(O, "__DATA", "__objc_protolist");
5450 info.S = PL;
5451 walk_pointer_list_32("protocol", PL, O, &info, nullptr);
5452 }
5453
5454 const SectionRef MR = get_section(O, "__OBJC2", "__message_refs");
5455 if (MR != SectionRef()) {
5456 info.S = MR;
5457 print_message_refs32(MR, &info);
5458 } else {
5459 const SectionRef MR = get_section(O, "__DATA", "__objc_msgrefs");
5460 info.S = MR;
5461 print_message_refs32(MR, &info);
5462 }
5463
5464 const SectionRef II = get_section(O, "__OBJC2", "__image_info");
5465 if (II != SectionRef()) {
5466 info.S = II;
5467 print_image_info32(II, &info);
5468 } else {
5469 const SectionRef II = get_section(O, "__DATA", "__objc_imageinfo");
5470 info.S = II;
5471 print_image_info32(II, &info);
5472 }
Kevin Enderby0fc11822015-04-01 20:57:01 +00005473}
5474
5475static bool printObjc1_32bit_MetaData(MachOObjectFile *O, bool verbose) {
Kevin Enderby846c0002015-04-16 17:19:59 +00005476 uint32_t i, j, p, offset, xoffset, left, defs_left, def;
5477 const char *r, *name, *defs;
5478 struct objc_module_t module;
5479 SectionRef S, xS;
5480 struct objc_symtab_t symtab;
5481 struct objc_class_t objc_class;
5482 struct objc_category_t objc_category;
5483
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005484 outs() << "Objective-C segment\n";
Kevin Enderby846c0002015-04-16 17:19:59 +00005485 S = get_section(O, "__OBJC", "__module_info");
5486 if (S == SectionRef())
5487 return false;
5488
5489 SymbolAddressMap AddrMap;
5490 if (verbose)
5491 CreateSymbolAddressMap(O, &AddrMap);
5492
5493 std::vector<SectionRef> Sections;
5494 for (const SectionRef &Section : O->sections()) {
5495 StringRef SectName;
5496 Section.getName(SectName);
5497 Sections.push_back(Section);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005498 }
Kevin Enderby846c0002015-04-16 17:19:59 +00005499
5500 struct DisassembleInfo info;
5501 // Set up the block of info used by the Symbolizer call backs.
5502 info.verbose = verbose;
5503 info.O = O;
5504 info.AddrMap = &AddrMap;
5505 info.Sections = &Sections;
5506 info.class_name = nullptr;
5507 info.selector_name = nullptr;
5508 info.method = nullptr;
5509 info.demangled_name = nullptr;
5510 info.bindtable = nullptr;
5511 info.adrp_addr = 0;
5512 info.adrp_inst = 0;
5513
5514 for (i = 0; i < S.getSize(); i += sizeof(struct objc_module_t)) {
5515 p = S.getAddress() + i;
5516 r = get_pointer_32(p, offset, left, S, &info, true);
5517 if (r == nullptr)
5518 return true;
5519 memset(&module, '\0', sizeof(struct objc_module_t));
5520 if (left < sizeof(struct objc_module_t)) {
5521 memcpy(&module, r, left);
5522 outs() << " (module extends past end of __module_info section)\n";
5523 } else
5524 memcpy(&module, r, sizeof(struct objc_module_t));
5525 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5526 swapStruct(module);
5527
5528 outs() << "Module " << format("0x%" PRIx32, p) << "\n";
5529 outs() << " version " << module.version << "\n";
5530 outs() << " size " << module.size << "\n";
5531 outs() << " name ";
5532 name = get_pointer_32(module.name, xoffset, left, xS, &info, true);
5533 if (name != nullptr)
5534 outs() << format("%.*s", left, name);
5535 else
5536 outs() << format("0x%08" PRIx32, module.name)
5537 << "(not in an __OBJC section)";
5538 outs() << "\n";
5539
5540 r = get_pointer_32(module.symtab, xoffset, left, xS, &info, true);
5541 if (module.symtab == 0 || r == nullptr) {
5542 outs() << " symtab " << format("0x%08" PRIx32, module.symtab)
5543 << " (not in an __OBJC section)\n";
5544 continue;
5545 }
5546 outs() << " symtab " << format("0x%08" PRIx32, module.symtab) << "\n";
5547 memset(&symtab, '\0', sizeof(struct objc_symtab_t));
5548 defs_left = 0;
5549 defs = nullptr;
5550 if (left < sizeof(struct objc_symtab_t)) {
5551 memcpy(&symtab, r, left);
5552 outs() << "\tsymtab extends past end of an __OBJC section)\n";
5553 } else {
5554 memcpy(&symtab, r, sizeof(struct objc_symtab_t));
5555 if (left > sizeof(struct objc_symtab_t)) {
5556 defs_left = left - sizeof(struct objc_symtab_t);
5557 defs = r + sizeof(struct objc_symtab_t);
5558 }
5559 }
5560 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5561 swapStruct(symtab);
5562
5563 outs() << "\tsel_ref_cnt " << symtab.sel_ref_cnt << "\n";
5564 r = get_pointer_32(symtab.refs, xoffset, left, xS, &info, true);
5565 outs() << "\trefs " << format("0x%08" PRIx32, symtab.refs);
5566 if (r == nullptr)
5567 outs() << " (not in an __OBJC section)";
5568 outs() << "\n";
5569 outs() << "\tcls_def_cnt " << symtab.cls_def_cnt << "\n";
5570 outs() << "\tcat_def_cnt " << symtab.cat_def_cnt << "\n";
5571 if (symtab.cls_def_cnt > 0)
5572 outs() << "\tClass Definitions\n";
5573 for (j = 0; j < symtab.cls_def_cnt; j++) {
5574 if ((j + 1) * sizeof(uint32_t) > defs_left) {
5575 outs() << "\t(remaining class defs entries entends past the end of the "
5576 << "section)\n";
5577 break;
5578 }
5579 memcpy(&def, defs + j * sizeof(uint32_t), sizeof(uint32_t));
5580 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5581 sys::swapByteOrder(def);
5582
5583 r = get_pointer_32(def, xoffset, left, xS, &info, true);
5584 outs() << "\tdefs[" << j << "] " << format("0x%08" PRIx32, def);
5585 if (r != nullptr) {
5586 if (left > sizeof(struct objc_class_t)) {
5587 outs() << "\n";
5588 memcpy(&objc_class, r, sizeof(struct objc_class_t));
5589 } else {
5590 outs() << " (entends past the end of the section)\n";
5591 memset(&objc_class, '\0', sizeof(struct objc_class_t));
5592 memcpy(&objc_class, r, left);
5593 }
5594 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5595 swapStruct(objc_class);
5596 print_objc_class_t(&objc_class, &info);
5597 } else {
5598 outs() << "(not in an __OBJC section)\n";
5599 }
5600
5601 if (CLS_GETINFO(&objc_class, CLS_CLASS)) {
5602 outs() << "\tMeta Class";
5603 r = get_pointer_32(objc_class.isa, xoffset, left, xS, &info, true);
5604 if (r != nullptr) {
5605 if (left > sizeof(struct objc_class_t)) {
5606 outs() << "\n";
5607 memcpy(&objc_class, r, sizeof(struct objc_class_t));
5608 } else {
5609 outs() << " (entends past the end of the section)\n";
5610 memset(&objc_class, '\0', sizeof(struct objc_class_t));
5611 memcpy(&objc_class, r, left);
5612 }
5613 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5614 swapStruct(objc_class);
5615 print_objc_class_t(&objc_class, &info);
5616 } else {
5617 outs() << "(not in an __OBJC section)\n";
5618 }
5619 }
5620 }
5621 if (symtab.cat_def_cnt > 0)
5622 outs() << "\tCategory Definitions\n";
5623 for (j = 0; j < symtab.cat_def_cnt; j++) {
5624 if ((j + symtab.cls_def_cnt + 1) * sizeof(uint32_t) > defs_left) {
5625 outs() << "\t(remaining category defs entries entends past the end of "
5626 << "the section)\n";
5627 break;
5628 }
5629 memcpy(&def, defs + (j + symtab.cls_def_cnt) * sizeof(uint32_t),
5630 sizeof(uint32_t));
5631 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5632 sys::swapByteOrder(def);
5633
5634 r = get_pointer_32(def, xoffset, left, xS, &info, true);
5635 outs() << "\tdefs[" << j + symtab.cls_def_cnt << "] "
5636 << format("0x%08" PRIx32, def);
5637 if (r != nullptr) {
5638 if (left > sizeof(struct objc_category_t)) {
5639 outs() << "\n";
5640 memcpy(&objc_category, r, sizeof(struct objc_category_t));
5641 } else {
5642 outs() << " (entends past the end of the section)\n";
5643 memset(&objc_category, '\0', sizeof(struct objc_category_t));
5644 memcpy(&objc_category, r, left);
5645 }
5646 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5647 swapStruct(objc_category);
5648 print_objc_objc_category_t(&objc_category, &info);
5649 } else {
5650 outs() << "(not in an __OBJC section)\n";
5651 }
5652 }
5653 }
5654 const SectionRef II = get_section(O, "__OBJC", "__image_info");
5655 if (II != SectionRef())
5656 print_image_info(II, &info);
5657
5658 return true;
Kevin Enderby0fc11822015-04-01 20:57:01 +00005659}
5660
Kevin Enderby4ad9bde2015-04-16 22:33:20 +00005661static void DumpProtocolSection(MachOObjectFile *O, const char *sect,
5662 uint32_t size, uint32_t addr) {
5663 SymbolAddressMap AddrMap;
5664 CreateSymbolAddressMap(O, &AddrMap);
5665
5666 std::vector<SectionRef> Sections;
5667 for (const SectionRef &Section : O->sections()) {
5668 StringRef SectName;
5669 Section.getName(SectName);
5670 Sections.push_back(Section);
5671 }
5672
5673 struct DisassembleInfo info;
5674 // Set up the block of info used by the Symbolizer call backs.
5675 info.verbose = true;
5676 info.O = O;
5677 info.AddrMap = &AddrMap;
5678 info.Sections = &Sections;
5679 info.class_name = nullptr;
5680 info.selector_name = nullptr;
5681 info.method = nullptr;
5682 info.demangled_name = nullptr;
5683 info.bindtable = nullptr;
5684 info.adrp_addr = 0;
5685 info.adrp_inst = 0;
5686
5687 const char *p;
5688 struct objc_protocol_t protocol;
5689 uint32_t left, paddr;
5690 for (p = sect; p < sect + size; p += sizeof(struct objc_protocol_t)) {
5691 memset(&protocol, '\0', sizeof(struct objc_protocol_t));
5692 left = size - (p - sect);
5693 if (left < sizeof(struct objc_protocol_t)) {
5694 outs() << "Protocol extends past end of __protocol section\n";
5695 memcpy(&protocol, p, left);
5696 } else
5697 memcpy(&protocol, p, sizeof(struct objc_protocol_t));
5698 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5699 swapStruct(protocol);
5700 paddr = addr + (p - sect);
5701 outs() << "Protocol " << format("0x%" PRIx32, paddr);
5702 if (print_protocol(paddr, 0, &info))
5703 outs() << "(not in an __OBJC section)\n";
5704 }
5705}
5706
Kevin Enderby9873e2c2016-05-23 21:34:12 +00005707#ifdef HAVE_LIBXAR
5708inline void swapStruct(struct xar_header &xar) {
5709 sys::swapByteOrder(xar.magic);
5710 sys::swapByteOrder(xar.size);
5711 sys::swapByteOrder(xar.version);
5712 sys::swapByteOrder(xar.toc_length_compressed);
5713 sys::swapByteOrder(xar.toc_length_uncompressed);
5714 sys::swapByteOrder(xar.cksum_alg);
5715}
5716
5717static void PrintModeVerbose(uint32_t mode) {
5718 switch(mode & S_IFMT){
5719 case S_IFDIR:
5720 outs() << "d";
5721 break;
5722 case S_IFCHR:
5723 outs() << "c";
5724 break;
5725 case S_IFBLK:
5726 outs() << "b";
5727 break;
5728 case S_IFREG:
5729 outs() << "-";
5730 break;
5731 case S_IFLNK:
5732 outs() << "l";
5733 break;
5734 case S_IFSOCK:
5735 outs() << "s";
5736 break;
5737 default:
5738 outs() << "?";
5739 break;
5740 }
5741
5742 /* owner permissions */
5743 if(mode & S_IREAD)
5744 outs() << "r";
5745 else
5746 outs() << "-";
5747 if(mode & S_IWRITE)
5748 outs() << "w";
5749 else
5750 outs() << "-";
5751 if(mode & S_ISUID)
5752 outs() << "s";
5753 else if(mode & S_IEXEC)
5754 outs() << "x";
5755 else
5756 outs() << "-";
5757
5758 /* group permissions */
5759 if(mode & (S_IREAD >> 3))
5760 outs() << "r";
5761 else
5762 outs() << "-";
5763 if(mode & (S_IWRITE >> 3))
5764 outs() << "w";
5765 else
5766 outs() << "-";
5767 if(mode & S_ISGID)
5768 outs() << "s";
5769 else if(mode & (S_IEXEC >> 3))
5770 outs() << "x";
5771 else
5772 outs() << "-";
5773
5774 /* other permissions */
5775 if(mode & (S_IREAD >> 6))
5776 outs() << "r";
5777 else
5778 outs() << "-";
5779 if(mode & (S_IWRITE >> 6))
5780 outs() << "w";
5781 else
5782 outs() << "-";
5783 if(mode & S_ISVTX)
5784 outs() << "t";
5785 else if(mode & (S_IEXEC >> 6))
5786 outs() << "x";
5787 else
5788 outs() << "-";
5789}
5790
5791static void PrintXarFilesSummary(const char *XarFilename, xar_t xar) {
5792 xar_iter_t xi;
5793 xar_file_t xf;
5794 xar_iter_t xp;
5795 const char *key, *type, *mode, *user, *group, *size, *mtime, *name, *m;
5796 char *endp;
5797 uint32_t mode_value;
5798
5799 xi = xar_iter_new();
5800 if (!xi) {
5801 errs() << "Can't obtain an xar iterator for xar archive "
5802 << XarFilename << "\n";
5803 return;
5804 }
5805
5806 // Go through the xar's files.
5807 for (xf = xar_file_first(xar, xi); xf; xf = xar_file_next(xi)) {
5808 xp = xar_iter_new();
5809 if(!xp){
5810 errs() << "Can't obtain an xar iterator for xar archive "
5811 << XarFilename << "\n";
5812 return;
5813 }
5814 type = nullptr;
5815 mode = nullptr;
5816 user = nullptr;
5817 group = nullptr;
5818 size = nullptr;
5819 mtime = nullptr;
5820 name = nullptr;
5821 for(key = xar_prop_first(xf, xp); key; key = xar_prop_next(xp)){
5822 const char *val = nullptr;
5823 xar_prop_get(xf, key, &val);
5824#if 0 // Useful for debugging.
5825 outs() << "key: " << key << " value: " << val << "\n";
5826#endif
5827 if(strcmp(key, "type") == 0)
5828 type = val;
5829 if(strcmp(key, "mode") == 0)
5830 mode = val;
5831 if(strcmp(key, "user") == 0)
5832 user = val;
5833 if(strcmp(key, "group") == 0)
5834 group = val;
5835 if(strcmp(key, "data/size") == 0)
5836 size = val;
5837 if(strcmp(key, "mtime") == 0)
5838 mtime = val;
5839 if(strcmp(key, "name") == 0)
5840 name = val;
5841 }
5842 if(mode != nullptr){
5843 mode_value = strtoul(mode, &endp, 8);
5844 if(*endp != '\0')
5845 outs() << "(mode: \"" << mode << "\" contains non-octal chars) ";
5846 if(strcmp(type, "file") == 0)
5847 mode_value |= S_IFREG;
5848 PrintModeVerbose(mode_value);
5849 outs() << " ";
5850 }
5851 if(user != nullptr)
5852 outs() << format("%10s/", user);
5853 if(group != nullptr)
5854 outs() << format("%-10s ", group);
5855 if(size != nullptr)
5856 outs() << format("%7s ", size);
5857 if(mtime != nullptr){
5858 for(m = mtime; *m != 'T' && *m != '\0'; m++)
5859 outs() << *m;
5860 if(*m == 'T')
5861 m++;
5862 outs() << " ";
5863 for( ; *m != 'Z' && *m != '\0'; m++)
5864 outs() << *m;
5865 outs() << " ";
5866 }
5867 if(name != nullptr)
5868 outs() << name;
5869 outs() << "\n";
5870 }
5871}
5872
5873static void DumpBitcodeSection(MachOObjectFile *O, const char *sect,
5874 uint32_t size, bool verbose,
5875 bool PrintXarHeader, bool PrintXarFileHeaders,
5876 std::string XarMemberName) {
5877 if(size < sizeof(struct xar_header)) {
5878 outs() << "size of (__LLVM,__bundle) section too small (smaller than size "
5879 "of struct xar_header)\n";
5880 return;
5881 }
5882 struct xar_header XarHeader;
5883 memcpy(&XarHeader, sect, sizeof(struct xar_header));
5884 if (sys::IsLittleEndianHost)
5885 swapStruct(XarHeader);
5886 if (PrintXarHeader) {
5887 if (!XarMemberName.empty())
5888 outs() << "In xar member " << XarMemberName << ": ";
5889 else
5890 outs() << "For (__LLVM,__bundle) section: ";
5891 outs() << "xar header\n";
5892 if (XarHeader.magic == XAR_HEADER_MAGIC)
5893 outs() << " magic XAR_HEADER_MAGIC\n";
5894 else
5895 outs() << " magic "
5896 << format_hex(XarHeader.magic, 10, true)
5897 << " (not XAR_HEADER_MAGIC)\n";
5898 outs() << " size " << XarHeader.size << "\n";
5899 outs() << " version " << XarHeader.version << "\n";
5900 outs() << " toc_length_compressed " << XarHeader.toc_length_compressed
5901 << "\n";
5902 outs() << "toc_length_uncompressed " << XarHeader.toc_length_uncompressed
5903 << "\n";
5904 outs() << " cksum_alg ";
5905 switch (XarHeader.cksum_alg) {
5906 case XAR_CKSUM_NONE:
5907 outs() << "XAR_CKSUM_NONE\n";
5908 break;
5909 case XAR_CKSUM_SHA1:
5910 outs() << "XAR_CKSUM_SHA1\n";
5911 break;
5912 case XAR_CKSUM_MD5:
5913 outs() << "XAR_CKSUM_MD5\n";
5914 break;
Kevin Enderby42882282016-05-23 22:18:59 +00005915#ifdef XAR_CKSUM_SHA256
Kevin Enderby9873e2c2016-05-23 21:34:12 +00005916 case XAR_CKSUM_SHA256:
5917 outs() << "XAR_CKSUM_SHA256\n";
5918 break;
Kevin Enderby42882282016-05-23 22:18:59 +00005919#endif
5920#ifdef XAR_CKSUM_SHA512
Kevin Enderby9873e2c2016-05-23 21:34:12 +00005921 case XAR_CKSUM_SHA512:
5922 outs() << "XAR_CKSUM_SHA512\n";
5923 break;
Kevin Enderby42882282016-05-23 22:18:59 +00005924#endif
Kevin Enderby9873e2c2016-05-23 21:34:12 +00005925 default:
5926 outs() << XarHeader.cksum_alg << "\n";
5927 }
5928 }
5929
5930 SmallString<128> XarFilename;
5931 int FD;
5932 std::error_code XarEC =
5933 sys::fs::createTemporaryFile("llvm-objdump", "xar", FD, XarFilename);
5934 if (XarEC) {
5935 errs() << XarEC.message() << "\n";
5936 return;
5937 }
5938 tool_output_file XarFile(XarFilename, FD);
5939 raw_fd_ostream &XarOut = XarFile.os();
5940 StringRef XarContents(sect, size);
5941 XarOut << XarContents;
5942 XarOut.close();
5943 if (XarOut.has_error())
5944 return;
5945
5946 xar_t xar = xar_open(XarFilename.c_str(), READ);
5947 if (!xar) {
5948 errs() << "Can't create temporary xar archive " << XarFilename << "\n";
5949 return;
5950 }
5951
5952 SmallString<128> TocFilename;
5953 std::error_code TocEC =
5954 sys::fs::createTemporaryFile("llvm-objdump", "toc", TocFilename);
5955 if (TocEC) {
5956 errs() << TocEC.message() << "\n";
5957 return;
5958 }
5959 xar_serialize(xar, TocFilename.c_str());
5960
5961 if (PrintXarFileHeaders) {
5962 if (!XarMemberName.empty())
5963 outs() << "In xar member " << XarMemberName << ": ";
5964 else
5965 outs() << "For (__LLVM,__bundle) section: ";
5966 outs() << "xar archive files:\n";
5967 PrintXarFilesSummary(XarFilename.c_str(), xar);
5968 }
5969
5970 ErrorOr<std::unique_ptr<MemoryBuffer>> FileOrErr =
5971 MemoryBuffer::getFileOrSTDIN(TocFilename.c_str());
5972 if (std::error_code EC = FileOrErr.getError()) {
5973 errs() << EC.message() << "\n";
5974 return;
5975 }
5976 std::unique_ptr<MemoryBuffer> &Buffer = FileOrErr.get();
5977
5978 if (!XarMemberName.empty())
5979 outs() << "In xar member " << XarMemberName << ": ";
5980 else
5981 outs() << "For (__LLVM,__bundle) section: ";
5982 outs() << "xar table of contents:\n";
5983 outs() << Buffer->getBuffer() << "\n";
5984
5985 // TODO: Go through the xar's files.
5986 xar_iter_t xi = xar_iter_new();
5987 if(!xi){
5988 errs() << "Can't obtain an xar iterator for xar archive "
5989 << XarFilename.c_str() << "\n";
5990 xar_close(xar);
5991 return;
5992 }
5993 for(xar_file_t xf = xar_file_first(xar, xi); xf; xf = xar_file_next(xi)){
5994 const char *key;
5995 xar_iter_t xp;
5996 const char *member_name, *member_type, *member_size_string;
5997 size_t member_size;
5998
5999 xp = xar_iter_new();
6000 if(!xp){
6001 errs() << "Can't obtain an xar iterator for xar archive "
6002 << XarFilename.c_str() << "\n";
6003 xar_close(xar);
6004 return;
6005 }
6006 member_name = NULL;
6007 member_type = NULL;
6008 member_size_string = NULL;
6009 for(key = xar_prop_first(xf, xp); key; key = xar_prop_next(xp)){
6010 const char *val = nullptr;
6011 xar_prop_get(xf, key, &val);
6012#if 0 // Useful for debugging.
6013 outs() << "key: " << key << " value: " << val << "\n";
6014#endif
6015 if(strcmp(key, "name") == 0)
6016 member_name = val;
6017 if(strcmp(key, "type") == 0)
6018 member_type = val;
6019 if(strcmp(key, "data/size") == 0)
6020 member_size_string = val;
6021 }
6022 /*
6023 * If we find a file with a name, date/size and type properties
6024 * and with the type being "file" see if that is a xar file.
6025 */
6026 if (member_name != NULL && member_type != NULL &&
6027 strcmp(member_type, "file") == 0 &&
6028 member_size_string != NULL){
6029 // Extract the file into a buffer.
6030 char *endptr;
6031 member_size = strtoul(member_size_string, &endptr, 10);
6032 if (*endptr == '\0' && member_size != 0) {
6033 char *buffer = (char *) ::operator new (member_size);
6034 if (xar_extract_tobuffersz(xar, xf, &buffer, &member_size) == 0) {
6035#if 0 // Useful for debugging.
6036 outs() << "xar member: " << member_name << " extracted\n";
6037#endif
6038 // Set the XarMemberName we want to see printed in the header.
6039 std::string OldXarMemberName;
6040 // If XarMemberName is already set this is nested. So
6041 // save the old name and create the nested name.
6042 if (!XarMemberName.empty()) {
6043 OldXarMemberName = XarMemberName;
6044 XarMemberName =
6045 (Twine("[") + XarMemberName + "]" + member_name).str();
6046 } else {
6047 OldXarMemberName = "";
6048 XarMemberName = member_name;
6049 }
6050 // See if this is could be a xar file (nested).
6051 if (member_size >= sizeof(struct xar_header)) {
6052#if 0 // Useful for debugging.
6053 outs() << "could be a xar file: " << member_name << "\n";
6054#endif
6055 memcpy((char *)&XarHeader, buffer, sizeof(struct xar_header));
6056 if (sys::IsLittleEndianHost)
6057 swapStruct(XarHeader);
6058 if(XarHeader.magic == XAR_HEADER_MAGIC)
6059 DumpBitcodeSection(O, buffer, member_size, verbose,
6060 PrintXarHeader, PrintXarFileHeaders,
6061 XarMemberName);
6062 }
6063 XarMemberName = OldXarMemberName;
6064 }
6065 delete buffer;
6066 }
6067 }
6068 xar_iter_free(xp);
6069 }
6070 xar_close(xar);
6071}
6072#endif // defined(HAVE_LIBXAR)
6073
Kevin Enderby0fc11822015-04-01 20:57:01 +00006074static void printObjcMetaData(MachOObjectFile *O, bool verbose) {
6075 if (O->is64Bit())
6076 printObjc2_64bit_MetaData(O, verbose);
6077 else {
6078 MachO::mach_header H;
6079 H = O->getHeader();
6080 if (H.cputype == MachO::CPU_TYPE_ARM)
6081 printObjc2_32bit_MetaData(O, verbose);
6082 else {
6083 // This is the 32-bit non-arm cputype case. Which is normally
6084 // the first Objective-C ABI. But it may be the case of a
6085 // binary for the iOS simulator which is the second Objective-C
6086 // ABI. In that case printObjc1_32bit_MetaData() will determine that
6087 // and return false.
Hans Wennborgcc9deb42015-09-29 18:02:48 +00006088 if (!printObjc1_32bit_MetaData(O, verbose))
Kevin Enderby0fc11822015-04-01 20:57:01 +00006089 printObjc2_32bit_MetaData(O, verbose);
6090 }
6091 }
6092}
6093
Kevin Enderbybf246f52014-09-24 23:08:22 +00006094// GuessLiteralPointer returns a string which for the item in the Mach-O file
6095// for the address passed in as ReferenceValue for printing as a comment with
6096// the instruction and also returns the corresponding type of that item
6097// indirectly through ReferenceType.
6098//
6099// If ReferenceValue is an address of literal cstring then a pointer to the
6100// cstring is returned and ReferenceType is set to
6101// LLVMDisassembler_ReferenceType_Out_LitPool_CstrAddr .
6102//
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006103// If ReferenceValue is an address of an Objective-C CFString, Selector ref or
6104// Class ref that name is returned and the ReferenceType is set accordingly.
6105//
6106// Lastly, literals which are Symbol address in a literal pool are looked for
6107// and if found the symbol name is returned and ReferenceType is set to
6108// LLVMDisassembler_ReferenceType_Out_LitPool_SymAddr .
6109//
6110// If there is no item in the Mach-O file for the address passed in as
6111// ReferenceValue nullptr is returned and ReferenceType is unchanged.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00006112static const char *GuessLiteralPointer(uint64_t ReferenceValue,
6113 uint64_t ReferencePC,
6114 uint64_t *ReferenceType,
6115 struct DisassembleInfo *info) {
Kevin Enderbybf246f52014-09-24 23:08:22 +00006116 // First see if there is an external relocation entry at the ReferencePC.
Kevin Enderbyd90a4172015-10-10 00:05:01 +00006117 if (info->O->getHeader().filetype == MachO::MH_OBJECT) {
6118 uint64_t sect_addr = info->S.getAddress();
6119 uint64_t sect_offset = ReferencePC - sect_addr;
6120 bool reloc_found = false;
6121 DataRefImpl Rel;
6122 MachO::any_relocation_info RE;
6123 bool isExtern = false;
6124 SymbolRef Symbol;
6125 for (const RelocationRef &Reloc : info->S.relocations()) {
6126 uint64_t RelocOffset = Reloc.getOffset();
6127 if (RelocOffset == sect_offset) {
6128 Rel = Reloc.getRawDataRefImpl();
6129 RE = info->O->getRelocation(Rel);
6130 if (info->O->isRelocationScattered(RE))
6131 continue;
6132 isExtern = info->O->getPlainRelocationExternal(RE);
6133 if (isExtern) {
6134 symbol_iterator RelocSym = Reloc.getSymbol();
6135 Symbol = *RelocSym;
6136 }
6137 reloc_found = true;
6138 break;
Kevin Enderbybf246f52014-09-24 23:08:22 +00006139 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00006140 }
Kevin Enderbyd90a4172015-10-10 00:05:01 +00006141 // If there is an external relocation entry for a symbol in a section
6142 // then used that symbol's value for the value of the reference.
6143 if (reloc_found && isExtern) {
6144 if (info->O->getAnyRelocationPCRel(RE)) {
6145 unsigned Type = info->O->getAnyRelocationType(RE);
6146 if (Type == MachO::X86_64_RELOC_SIGNED) {
6147 ReferenceValue = Symbol.getValue();
6148 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00006149 }
6150 }
6151 }
6152
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006153 // Look for literals such as Objective-C CFStrings refs, Selector refs,
6154 // Message refs and Class refs.
6155 bool classref, selref, msgref, cfstring;
6156 uint64_t pointer_value = GuessPointerPointer(ReferenceValue, info, classref,
6157 selref, msgref, cfstring);
David Blaikie33dd45d02015-03-23 18:39:02 +00006158 if (classref && pointer_value == 0) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006159 // Note the ReferenceValue is a pointer into the __objc_classrefs section.
6160 // And the pointer_value in that section is typically zero as it will be
6161 // set by dyld as part of the "bind information".
6162 const char *name = get_dyld_bind_info_symbolname(ReferenceValue, info);
6163 if (name != nullptr) {
6164 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Class_Ref;
Hans Wennborgdb53e302014-10-23 21:59:17 +00006165 const char *class_name = strrchr(name, '$');
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006166 if (class_name != nullptr && class_name[1] == '_' &&
6167 class_name[2] != '\0') {
6168 info->class_name = class_name + 2;
6169 return name;
6170 }
6171 }
6172 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00006173
David Blaikie33dd45d02015-03-23 18:39:02 +00006174 if (classref) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006175 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Class_Ref;
6176 const char *name =
6177 get_objc2_64bit_class_name(pointer_value, ReferenceValue, info);
6178 if (name != nullptr)
6179 info->class_name = name;
6180 else
6181 name = "bad class ref";
Kevin Enderbybf246f52014-09-24 23:08:22 +00006182 return name;
6183 }
6184
David Blaikie33dd45d02015-03-23 18:39:02 +00006185 if (cfstring) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006186 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_CFString_Ref;
6187 const char *name = get_objc2_64bit_cfstring_name(ReferenceValue, info);
6188 return name;
6189 }
6190
David Blaikie33dd45d02015-03-23 18:39:02 +00006191 if (selref && pointer_value == 0)
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006192 pointer_value = get_objc2_64bit_selref(ReferenceValue, info);
6193
6194 if (pointer_value != 0)
6195 ReferenceValue = pointer_value;
6196
6197 const char *name = GuessCstringPointer(ReferenceValue, info);
6198 if (name) {
David Blaikie33dd45d02015-03-23 18:39:02 +00006199 if (pointer_value != 0 && selref) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006200 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Selector_Ref;
6201 info->selector_name = name;
David Blaikie33dd45d02015-03-23 18:39:02 +00006202 } else if (pointer_value != 0 && msgref) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006203 info->class_name = nullptr;
6204 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message_Ref;
6205 info->selector_name = name;
6206 } else
6207 *ReferenceType = LLVMDisassembler_ReferenceType_Out_LitPool_CstrAddr;
6208 return name;
6209 }
6210
6211 // Lastly look for an indirect symbol with this ReferenceValue which is in
6212 // a literal pool. If found return that symbol name.
6213 name = GuessIndirectSymbol(ReferenceValue, info);
6214 if (name) {
6215 *ReferenceType = LLVMDisassembler_ReferenceType_Out_LitPool_SymAddr;
6216 return name;
6217 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00006218
6219 return nullptr;
6220}
6221
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006222// SymbolizerSymbolLookUp is the symbol lookup function passed when creating
Kevin Enderbybf246f52014-09-24 23:08:22 +00006223// the Symbolizer. It looks up the ReferenceValue using the info passed via the
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006224// pointer to the struct DisassembleInfo that was passed when MCSymbolizer
6225// is created and returns the symbol name that matches the ReferenceValue or
6226// nullptr if none. The ReferenceType is passed in for the IN type of
6227// reference the instruction is making from the values in defined in the header
6228// "llvm-c/Disassembler.h". On return the ReferenceType can set to a specific
6229// Out type and the ReferenceName will also be set which is added as a comment
6230// to the disassembled instruction.
6231//
Kevin Enderby04bf6932014-10-28 23:39:46 +00006232#if HAVE_CXXABI_H
6233// If the symbol name is a C++ mangled name then the demangled name is
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006234// returned through ReferenceName and ReferenceType is set to
6235// LLVMDisassembler_ReferenceType_DeMangled_Name .
Kevin Enderby04bf6932014-10-28 23:39:46 +00006236#endif
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006237//
6238// When this is called to get a symbol name for a branch target then the
6239// ReferenceType will be LLVMDisassembler_ReferenceType_In_Branch and then
6240// SymbolValue will be looked for in the indirect symbol table to determine if
6241// it is an address for a symbol stub. If so then the symbol name for that
6242// stub is returned indirectly through ReferenceName and then ReferenceType is
6243// set to LLVMDisassembler_ReferenceType_Out_SymbolStub.
6244//
Kevin Enderbybf246f52014-09-24 23:08:22 +00006245// When this is called with an value loaded via a PC relative load then
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006246// ReferenceType will be LLVMDisassembler_ReferenceType_In_PCrel_Load then the
6247// SymbolValue is checked to be an address of literal pointer, symbol pointer,
6248// or an Objective-C meta data reference. If so the output ReferenceType is
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006249// set to correspond to that as well as setting the ReferenceName.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00006250static const char *SymbolizerSymbolLookUp(void *DisInfo,
6251 uint64_t ReferenceValue,
6252 uint64_t *ReferenceType,
6253 uint64_t ReferencePC,
6254 const char **ReferenceName) {
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006255 struct DisassembleInfo *info = (struct DisassembleInfo *)DisInfo;
Kevin Enderbybf246f52014-09-24 23:08:22 +00006256 // If no verbose symbolic information is wanted then just return nullptr.
David Blaikie33dd45d02015-03-23 18:39:02 +00006257 if (!info->verbose) {
Kevin Enderbybf246f52014-09-24 23:08:22 +00006258 *ReferenceName = nullptr;
6259 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006260 return nullptr;
6261 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00006262
Kevin Enderbyf6d25852015-01-31 00:37:11 +00006263 const char *SymbolName = GuessSymbolName(ReferenceValue, info->AddrMap);
Kevin Enderbybf246f52014-09-24 23:08:22 +00006264
Kevin Enderby85974882014-09-26 22:20:44 +00006265 if (*ReferenceType == LLVMDisassembler_ReferenceType_In_Branch) {
6266 *ReferenceName = GuessIndirectSymbol(ReferenceValue, info);
Kevin Enderby04bf6932014-10-28 23:39:46 +00006267 if (*ReferenceName != nullptr) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006268 method_reference(info, ReferenceType, ReferenceName);
6269 if (*ReferenceType != LLVMDisassembler_ReferenceType_Out_Objc_Message)
6270 *ReferenceType = LLVMDisassembler_ReferenceType_Out_SymbolStub;
6271 } else
Kevin Enderby04bf6932014-10-28 23:39:46 +00006272#if HAVE_CXXABI_H
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006273 if (SymbolName != nullptr && strncmp(SymbolName, "__Z", 3) == 0) {
Kevin Enderby04bf6932014-10-28 23:39:46 +00006274 if (info->demangled_name != nullptr)
6275 free(info->demangled_name);
6276 int status;
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006277 info->demangled_name =
6278 abi::__cxa_demangle(SymbolName + 1, nullptr, nullptr, &status);
Kevin Enderby04bf6932014-10-28 23:39:46 +00006279 if (info->demangled_name != nullptr) {
6280 *ReferenceName = info->demangled_name;
6281 *ReferenceType = LLVMDisassembler_ReferenceType_DeMangled_Name;
6282 } else
6283 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
6284 } else
6285#endif
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006286 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
6287 } else if (*ReferenceType == LLVMDisassembler_ReferenceType_In_PCrel_Load) {
6288 *ReferenceName =
6289 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
Kevin Enderby85974882014-09-26 22:20:44 +00006290 if (*ReferenceName)
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006291 method_reference(info, ReferenceType, ReferenceName);
Kevin Enderby85974882014-09-26 22:20:44 +00006292 else
6293 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
Kevin Enderbyae3c1262014-11-14 21:52:18 +00006294 // If this is arm64 and the reference is an adrp instruction save the
6295 // instruction, passed in ReferenceValue and the address of the instruction
6296 // for use later if we see and add immediate instruction.
6297 } else if (info->O->getArch() == Triple::aarch64 &&
6298 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADRP) {
6299 info->adrp_inst = ReferenceValue;
6300 info->adrp_addr = ReferencePC;
6301 SymbolName = nullptr;
6302 *ReferenceName = nullptr;
6303 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
6304 // If this is arm64 and reference is an add immediate instruction and we
6305 // have
6306 // seen an adrp instruction just before it and the adrp's Xd register
6307 // matches
6308 // this add's Xn register reconstruct the value being referenced and look to
6309 // see if it is a literal pointer. Note the add immediate instruction is
6310 // passed in ReferenceValue.
6311 } else if (info->O->getArch() == Triple::aarch64 &&
6312 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADDXri &&
6313 ReferencePC - 4 == info->adrp_addr &&
6314 (info->adrp_inst & 0x9f000000) == 0x90000000 &&
6315 (info->adrp_inst & 0x1f) == ((ReferenceValue >> 5) & 0x1f)) {
6316 uint32_t addxri_inst;
6317 uint64_t adrp_imm, addxri_imm;
6318
6319 adrp_imm =
6320 ((info->adrp_inst & 0x00ffffe0) >> 3) | ((info->adrp_inst >> 29) & 0x3);
6321 if (info->adrp_inst & 0x0200000)
6322 adrp_imm |= 0xfffffffffc000000LL;
6323
6324 addxri_inst = ReferenceValue;
6325 addxri_imm = (addxri_inst >> 10) & 0xfff;
6326 if (((addxri_inst >> 22) & 0x3) == 1)
6327 addxri_imm <<= 12;
6328
6329 ReferenceValue = (info->adrp_addr & 0xfffffffffffff000LL) +
6330 (adrp_imm << 12) + addxri_imm;
6331
6332 *ReferenceName =
6333 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
6334 if (*ReferenceName == nullptr)
6335 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
6336 // If this is arm64 and the reference is a load register instruction and we
6337 // have seen an adrp instruction just before it and the adrp's Xd register
6338 // matches this add's Xn register reconstruct the value being referenced and
6339 // look to see if it is a literal pointer. Note the load register
6340 // instruction is passed in ReferenceValue.
6341 } else if (info->O->getArch() == Triple::aarch64 &&
6342 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_LDRXui &&
6343 ReferencePC - 4 == info->adrp_addr &&
6344 (info->adrp_inst & 0x9f000000) == 0x90000000 &&
6345 (info->adrp_inst & 0x1f) == ((ReferenceValue >> 5) & 0x1f)) {
6346 uint32_t ldrxui_inst;
6347 uint64_t adrp_imm, ldrxui_imm;
6348
6349 adrp_imm =
6350 ((info->adrp_inst & 0x00ffffe0) >> 3) | ((info->adrp_inst >> 29) & 0x3);
6351 if (info->adrp_inst & 0x0200000)
6352 adrp_imm |= 0xfffffffffc000000LL;
6353
6354 ldrxui_inst = ReferenceValue;
6355 ldrxui_imm = (ldrxui_inst >> 10) & 0xfff;
6356
6357 ReferenceValue = (info->adrp_addr & 0xfffffffffffff000LL) +
6358 (adrp_imm << 12) + (ldrxui_imm << 3);
6359
6360 *ReferenceName =
6361 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
6362 if (*ReferenceName == nullptr)
6363 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
6364 }
6365 // If this arm64 and is an load register (PC-relative) instruction the
6366 // ReferenceValue is the PC plus the immediate value.
6367 else if (info->O->getArch() == Triple::aarch64 &&
6368 (*ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_LDRXl ||
6369 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADR)) {
6370 *ReferenceName =
6371 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
6372 if (*ReferenceName == nullptr)
6373 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
Kevin Enderby85974882014-09-26 22:20:44 +00006374 }
Kevin Enderby04bf6932014-10-28 23:39:46 +00006375#if HAVE_CXXABI_H
6376 else if (SymbolName != nullptr && strncmp(SymbolName, "__Z", 3) == 0) {
6377 if (info->demangled_name != nullptr)
6378 free(info->demangled_name);
6379 int status;
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006380 info->demangled_name =
6381 abi::__cxa_demangle(SymbolName + 1, nullptr, nullptr, &status);
Kevin Enderby04bf6932014-10-28 23:39:46 +00006382 if (info->demangled_name != nullptr) {
6383 *ReferenceName = info->demangled_name;
6384 *ReferenceType = LLVMDisassembler_ReferenceType_DeMangled_Name;
6385 }
6386 }
6387#endif
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006388 else {
Kevin Enderbybf246f52014-09-24 23:08:22 +00006389 *ReferenceName = nullptr;
6390 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
6391 }
6392
6393 return SymbolName;
6394}
6395
Kevin Enderbybf246f52014-09-24 23:08:22 +00006396/// \brief Emits the comments that are stored in the CommentStream.
6397/// Each comment in the CommentStream must end with a newline.
6398static void emitComments(raw_svector_ostream &CommentStream,
6399 SmallString<128> &CommentsToEmit,
6400 formatted_raw_ostream &FormattedOS,
6401 const MCAsmInfo &MAI) {
6402 // Flush the stream before taking its content.
Kevin Enderbybf246f52014-09-24 23:08:22 +00006403 StringRef Comments = CommentsToEmit.str();
6404 // Get the default information for printing a comment.
6405 const char *CommentBegin = MAI.getCommentString();
6406 unsigned CommentColumn = MAI.getCommentColumn();
6407 bool IsFirst = true;
6408 while (!Comments.empty()) {
6409 if (!IsFirst)
6410 FormattedOS << '\n';
6411 // Emit a line of comments.
6412 FormattedOS.PadToColumn(CommentColumn);
6413 size_t Position = Comments.find('\n');
6414 FormattedOS << CommentBegin << ' ' << Comments.substr(0, Position);
6415 // Move after the newline character.
6416 Comments = Comments.substr(Position + 1);
6417 IsFirst = false;
6418 }
6419 FormattedOS.flush();
6420
6421 // Tell the comment stream that the vector changed underneath it.
6422 CommentsToEmit.clear();
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006423}
6424
Kevin Enderby95df54c2015-02-04 01:01:38 +00006425static void DisassembleMachO(StringRef Filename, MachOObjectFile *MachOOF,
6426 StringRef DisSegName, StringRef DisSectName) {
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006427 const char *McpuDefault = nullptr;
6428 const Target *ThumbTarget = nullptr;
6429 const Target *TheTarget = GetTarget(MachOOF, &McpuDefault, &ThumbTarget);
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006430 if (!TheTarget) {
6431 // GetTarget prints out stuff.
6432 return;
6433 }
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006434 if (MCPU.empty() && McpuDefault)
6435 MCPU = McpuDefault;
6436
Ahmed Charles56440fd2014-03-06 05:51:42 +00006437 std::unique_ptr<const MCInstrInfo> InstrInfo(TheTarget->createMCInstrInfo());
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006438 std::unique_ptr<const MCInstrInfo> ThumbInstrInfo;
Kevin Enderbyae3c1262014-11-14 21:52:18 +00006439 if (ThumbTarget)
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006440 ThumbInstrInfo.reset(ThumbTarget->createMCInstrInfo());
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006441
Kevin Enderbyc9595622014-08-06 23:24:41 +00006442 // Package up features to be passed to target/subtarget
6443 std::string FeaturesStr;
6444 if (MAttrs.size()) {
6445 SubtargetFeatures Features;
6446 for (unsigned i = 0; i != MAttrs.size(); ++i)
6447 Features.AddFeature(MAttrs[i]);
6448 FeaturesStr = Features.getString();
6449 }
6450
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006451 // Set up disassembler.
Ahmed Charles56440fd2014-03-06 05:51:42 +00006452 std::unique_ptr<const MCRegisterInfo> MRI(
6453 TheTarget->createMCRegInfo(TripleName));
6454 std::unique_ptr<const MCAsmInfo> AsmInfo(
Rafael Espindola227144c2013-05-13 01:16:13 +00006455 TheTarget->createMCAsmInfo(*MRI, TripleName));
Ahmed Charles56440fd2014-03-06 05:51:42 +00006456 std::unique_ptr<const MCSubtargetInfo> STI(
Kevin Enderbyc9595622014-08-06 23:24:41 +00006457 TheTarget->createMCSubtargetInfo(TripleName, MCPU, FeaturesStr));
Craig Toppere6cb63e2014-04-25 04:24:47 +00006458 MCContext Ctx(AsmInfo.get(), MRI.get(), nullptr);
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006459 std::unique_ptr<MCDisassembler> DisAsm(
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006460 TheTarget->createMCDisassembler(*STI, Ctx));
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006461 std::unique_ptr<MCSymbolizer> Symbolizer;
6462 struct DisassembleInfo SymbolizerInfo;
6463 std::unique_ptr<MCRelocationInfo> RelInfo(
6464 TheTarget->createMCRelocationInfo(TripleName, Ctx));
6465 if (RelInfo) {
6466 Symbolizer.reset(TheTarget->createMCSymbolizer(
6467 TripleName, SymbolizerGetOpInfo, SymbolizerSymbolLookUp,
David Blaikie186db432015-01-18 20:45:48 +00006468 &SymbolizerInfo, &Ctx, std::move(RelInfo)));
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006469 DisAsm->setSymbolizer(std::move(Symbolizer));
6470 }
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006471 int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
Ahmed Charles56440fd2014-03-06 05:51:42 +00006472 std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
Daniel Sanders50f17232015-09-15 16:17:27 +00006473 Triple(TripleName), AsmPrinterVariant, *AsmInfo, *InstrInfo, *MRI));
Kevin Enderbybf246f52014-09-24 23:08:22 +00006474 // Set the display preference for hex vs. decimal immediates.
6475 IP->setPrintImmHex(PrintImmHex);
6476 // Comment stream and backing vector.
6477 SmallString<128> CommentsToEmit;
6478 raw_svector_ostream CommentStream(CommentsToEmit);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00006479 // FIXME: Setting the CommentStream in the InstPrinter is problematic in that
6480 // if it is done then arm64 comments for string literals don't get printed
6481 // and some constant get printed instead and not setting it causes intel
6482 // (32-bit and 64-bit) comments printed with different spacing before the
6483 // comment causing different diffs with the 'C' disassembler library API.
6484 // IP->setCommentStream(CommentStream);
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00006485
Kevin Enderbyae3c1262014-11-14 21:52:18 +00006486 if (!AsmInfo || !STI || !DisAsm || !IP) {
Michael J. Spencerc1363cf2011-10-07 19:25:47 +00006487 errs() << "error: couldn't initialize disassembler for target "
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00006488 << TripleName << '\n';
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006489 return;
6490 }
6491
Tim Northover09ca33e2016-04-22 23:23:31 +00006492 // Set up separate thumb disassembler if needed.
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006493 std::unique_ptr<const MCRegisterInfo> ThumbMRI;
6494 std::unique_ptr<const MCAsmInfo> ThumbAsmInfo;
6495 std::unique_ptr<const MCSubtargetInfo> ThumbSTI;
Kevin Enderby930fdc72014-11-06 19:00:13 +00006496 std::unique_ptr<MCDisassembler> ThumbDisAsm;
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006497 std::unique_ptr<MCInstPrinter> ThumbIP;
6498 std::unique_ptr<MCContext> ThumbCtx;
Kevin Enderby930fdc72014-11-06 19:00:13 +00006499 std::unique_ptr<MCSymbolizer> ThumbSymbolizer;
6500 struct DisassembleInfo ThumbSymbolizerInfo;
6501 std::unique_ptr<MCRelocationInfo> ThumbRelInfo;
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006502 if (ThumbTarget) {
6503 ThumbMRI.reset(ThumbTarget->createMCRegInfo(ThumbTripleName));
6504 ThumbAsmInfo.reset(
6505 ThumbTarget->createMCAsmInfo(*ThumbMRI, ThumbTripleName));
6506 ThumbSTI.reset(
6507 ThumbTarget->createMCSubtargetInfo(ThumbTripleName, MCPU, FeaturesStr));
6508 ThumbCtx.reset(new MCContext(ThumbAsmInfo.get(), ThumbMRI.get(), nullptr));
6509 ThumbDisAsm.reset(ThumbTarget->createMCDisassembler(*ThumbSTI, *ThumbCtx));
Kevin Enderby930fdc72014-11-06 19:00:13 +00006510 MCContext *PtrThumbCtx = ThumbCtx.get();
6511 ThumbRelInfo.reset(
6512 ThumbTarget->createMCRelocationInfo(ThumbTripleName, *PtrThumbCtx));
6513 if (ThumbRelInfo) {
6514 ThumbSymbolizer.reset(ThumbTarget->createMCSymbolizer(
6515 ThumbTripleName, SymbolizerGetOpInfo, SymbolizerSymbolLookUp,
David Blaikie186db432015-01-18 20:45:48 +00006516 &ThumbSymbolizerInfo, PtrThumbCtx, std::move(ThumbRelInfo)));
Kevin Enderby930fdc72014-11-06 19:00:13 +00006517 ThumbDisAsm->setSymbolizer(std::move(ThumbSymbolizer));
6518 }
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006519 int ThumbAsmPrinterVariant = ThumbAsmInfo->getAssemblerDialect();
6520 ThumbIP.reset(ThumbTarget->createMCInstPrinter(
Daniel Sanders50f17232015-09-15 16:17:27 +00006521 Triple(ThumbTripleName), ThumbAsmPrinterVariant, *ThumbAsmInfo,
6522 *ThumbInstrInfo, *ThumbMRI));
Kevin Enderbybf246f52014-09-24 23:08:22 +00006523 // Set the display preference for hex vs. decimal immediates.
6524 ThumbIP->setPrintImmHex(PrintImmHex);
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006525 }
6526
Kevin Enderbyae3c1262014-11-14 21:52:18 +00006527 if (ThumbTarget && (!ThumbAsmInfo || !ThumbSTI || !ThumbDisAsm || !ThumbIP)) {
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006528 errs() << "error: couldn't initialize disassembler for target "
6529 << ThumbTripleName << '\n';
6530 return;
6531 }
6532
Charles Davis8bdfafd2013-09-01 04:28:48 +00006533 MachO::mach_header Header = MachOOF->getHeader();
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006534
Ahmed Bougachaaa790682013-05-24 01:07:04 +00006535 // FIXME: Using the -cfg command line option, this code used to be able to
6536 // annotate relocations with the referenced symbol's name, and if this was
6537 // inside a __[cf]string section, the data it points to. This is now replaced
6538 // by the upcoming MCSymbolizer, which needs the appropriate setup done above.
Owen Andersond9243c42011-10-17 21:37:35 +00006539 std::vector<SectionRef> Sections;
6540 std::vector<SymbolRef> Symbols;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006541 SmallVector<uint64_t, 8> FoundFns;
Kevin Enderby273ae012013-06-06 17:20:50 +00006542 uint64_t BaseSegmentAddress;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006543
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00006544 getSectionsAndSymbols(MachOOF, Sections, Symbols, FoundFns,
Kevin Enderby273ae012013-06-06 17:20:50 +00006545 BaseSegmentAddress);
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006546
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006547 // Sort the symbols by address, just in case they didn't come in that way.
Owen Andersond9243c42011-10-17 21:37:35 +00006548 std::sort(Symbols.begin(), Symbols.end(), SymbolSorter());
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006549
Kevin Enderby273ae012013-06-06 17:20:50 +00006550 // Build a data in code table that is sorted on by the address of each entry.
6551 uint64_t BaseAddress = 0;
Charles Davis8bdfafd2013-09-01 04:28:48 +00006552 if (Header.filetype == MachO::MH_OBJECT)
Rafael Espindola80291272014-10-08 15:28:58 +00006553 BaseAddress = Sections[0].getAddress();
Kevin Enderby273ae012013-06-06 17:20:50 +00006554 else
6555 BaseAddress = BaseSegmentAddress;
6556 DiceTable Dices;
Kevin Enderby273ae012013-06-06 17:20:50 +00006557 for (dice_iterator DI = MachOOF->begin_dices(), DE = MachOOF->end_dices();
Rafael Espindola5e812af2014-01-30 02:49:50 +00006558 DI != DE; ++DI) {
Kevin Enderby273ae012013-06-06 17:20:50 +00006559 uint32_t Offset;
6560 DI->getOffset(Offset);
6561 Dices.push_back(std::make_pair(BaseAddress + Offset, *DI));
6562 }
6563 array_pod_sort(Dices.begin(), Dices.end());
6564
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006565#ifndef NDEBUG
6566 raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls();
6567#else
6568 raw_ostream &DebugOut = nulls();
6569#endif
6570
Ahmed Charles56440fd2014-03-06 05:51:42 +00006571 std::unique_ptr<DIContext> diContext;
Rafael Espindola9b709252013-04-13 01:45:40 +00006572 ObjectFile *DbgObj = MachOOF;
Benjamin Kramer699128e2011-09-21 01:13:19 +00006573 // Try to find debug info and set up the DIContext for it.
6574 if (UseDbg) {
Benjamin Kramer699128e2011-09-21 01:13:19 +00006575 // A separate DSym file path was specified, parse it as a macho file,
6576 // get the sections and supply it to the section name parsing machinery.
6577 if (!DSYMFile.empty()) {
Rafael Espindola48af1c22014-08-19 18:44:46 +00006578 ErrorOr<std::unique_ptr<MemoryBuffer>> BufOrErr =
Rafael Espindolaadf21f22014-07-06 17:43:13 +00006579 MemoryBuffer::getFileOrSTDIN(DSYMFile);
Rafael Espindola48af1c22014-08-19 18:44:46 +00006580 if (std::error_code EC = BufOrErr.getError()) {
Rafael Espindolaadf21f22014-07-06 17:43:13 +00006581 errs() << "llvm-objdump: " << Filename << ": " << EC.message() << '\n';
Benjamin Kramer699128e2011-09-21 01:13:19 +00006582 return;
6583 }
Rafael Espindola48af1c22014-08-19 18:44:46 +00006584 DbgObj =
6585 ObjectFile::createMachOObjectFile(BufOrErr.get()->getMemBufferRef())
6586 .get()
6587 .release();
Benjamin Kramer699128e2011-09-21 01:13:19 +00006588 }
6589
Eric Christopher7370b552012-11-12 21:40:38 +00006590 // Setup the DIContext
Zachary Turner6489d7b2015-04-23 17:37:47 +00006591 diContext.reset(new DWARFContextInMemory(*DbgObj));
Benjamin Kramer699128e2011-09-21 01:13:19 +00006592 }
6593
Colin LeMahieufcc32762015-07-29 19:08:10 +00006594 if (FilterSections.size() == 0)
Kevin Enderby95df54c2015-02-04 01:01:38 +00006595 outs() << "(" << DisSegName << "," << DisSectName << ") section\n";
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00006596
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006597 for (unsigned SectIdx = 0; SectIdx != Sections.size(); SectIdx++) {
Owen Andersond9243c42011-10-17 21:37:35 +00006598 StringRef SectName;
Kevin Enderby95df54c2015-02-04 01:01:38 +00006599 if (Sections[SectIdx].getName(SectName) || SectName != DisSectName)
6600 continue;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006601
Rafael Espindolaa9f810b2012-12-21 03:47:03 +00006602 DataRefImpl DR = Sections[SectIdx].getRawDataRefImpl();
Ahmed Bougachaaa790682013-05-24 01:07:04 +00006603
Rafael Espindolab0f76a42013-04-05 15:15:22 +00006604 StringRef SegmentName = MachOOF->getSectionFinalSegmentName(DR);
Kevin Enderby95df54c2015-02-04 01:01:38 +00006605 if (SegmentName != DisSegName)
Rafael Espindolaa9f810b2012-12-21 03:47:03 +00006606 continue;
6607
Rafael Espindola7fc5b872014-11-12 02:04:27 +00006608 StringRef BytesStr;
6609 Sections[SectIdx].getContents(BytesStr);
Aaron Ballman106fd7b2014-11-12 14:01:17 +00006610 ArrayRef<uint8_t> Bytes(reinterpret_cast<const uint8_t *>(BytesStr.data()),
6611 BytesStr.size());
Rafael Espindola80291272014-10-08 15:28:58 +00006612 uint64_t SectAddress = Sections[SectIdx].getAddress();
Rafael Espindolabd604f22014-11-07 00:52:15 +00006613
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006614 bool symbolTableWorked = false;
6615
Kevin Enderbybf246f52014-09-24 23:08:22 +00006616 // Create a map of symbol addresses to symbol names for use by
6617 // the SymbolizerSymbolLookUp() routine.
6618 SymbolAddressMap AddrMap;
Kevin Enderby6a221752015-03-17 17:10:57 +00006619 bool DisSymNameFound = false;
Kevin Enderbybf246f52014-09-24 23:08:22 +00006620 for (const SymbolRef &Symbol : MachOOF->symbols()) {
Kevin Enderby7bd8d992016-05-02 20:28:12 +00006621 Expected<SymbolRef::Type> STOrErr = Symbol.getType();
6622 if (!STOrErr) {
6623 std::string Buf;
6624 raw_string_ostream OS(Buf);
6625 logAllUnhandledErrors(STOrErr.takeError(), OS, "");
6626 OS.flush();
6627 report_fatal_error(Buf);
6628 }
Kevin Enderby5afbc1c2016-03-23 20:27:00 +00006629 SymbolRef::Type ST = *STOrErr;
Kevin Enderbybf246f52014-09-24 23:08:22 +00006630 if (ST == SymbolRef::ST_Function || ST == SymbolRef::ST_Data ||
6631 ST == SymbolRef::ST_Other) {
Rafael Espindoladea00162015-07-03 17:44:18 +00006632 uint64_t Address = Symbol.getValue();
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00006633 Expected<StringRef> SymNameOrErr = Symbol.getName();
6634 if (!SymNameOrErr) {
6635 std::string Buf;
6636 raw_string_ostream OS(Buf);
6637 logAllUnhandledErrors(SymNameOrErr.takeError(), OS, "");
6638 OS.flush();
6639 report_fatal_error(Buf);
6640 }
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00006641 StringRef SymName = *SymNameOrErr;
Kevin Enderbybf246f52014-09-24 23:08:22 +00006642 AddrMap[Address] = SymName;
Kevin Enderby6a221752015-03-17 17:10:57 +00006643 if (!DisSymName.empty() && DisSymName == SymName)
6644 DisSymNameFound = true;
Kevin Enderbybf246f52014-09-24 23:08:22 +00006645 }
6646 }
David Blaikie33dd45d02015-03-23 18:39:02 +00006647 if (!DisSymName.empty() && !DisSymNameFound) {
Kevin Enderby6a221752015-03-17 17:10:57 +00006648 outs() << "Can't find -dis-symname: " << DisSymName << "\n";
6649 return;
6650 }
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006651 // Set up the block of info used by the Symbolizer call backs.
Kevin Enderby8e29ec92015-03-17 22:26:11 +00006652 SymbolizerInfo.verbose = !NoSymbolicOperands;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006653 SymbolizerInfo.O = MachOOF;
6654 SymbolizerInfo.S = Sections[SectIdx];
Kevin Enderbybf246f52014-09-24 23:08:22 +00006655 SymbolizerInfo.AddrMap = &AddrMap;
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006656 SymbolizerInfo.Sections = &Sections;
6657 SymbolizerInfo.class_name = nullptr;
6658 SymbolizerInfo.selector_name = nullptr;
6659 SymbolizerInfo.method = nullptr;
Kevin Enderby04bf6932014-10-28 23:39:46 +00006660 SymbolizerInfo.demangled_name = nullptr;
Kevin Enderby078be602014-10-23 19:53:12 +00006661 SymbolizerInfo.bindtable = nullptr;
Kevin Enderby10738222014-11-19 20:20:16 +00006662 SymbolizerInfo.adrp_addr = 0;
6663 SymbolizerInfo.adrp_inst = 0;
Kevin Enderby930fdc72014-11-06 19:00:13 +00006664 // Same for the ThumbSymbolizer
Kevin Enderby8e29ec92015-03-17 22:26:11 +00006665 ThumbSymbolizerInfo.verbose = !NoSymbolicOperands;
Kevin Enderby930fdc72014-11-06 19:00:13 +00006666 ThumbSymbolizerInfo.O = MachOOF;
6667 ThumbSymbolizerInfo.S = Sections[SectIdx];
6668 ThumbSymbolizerInfo.AddrMap = &AddrMap;
6669 ThumbSymbolizerInfo.Sections = &Sections;
6670 ThumbSymbolizerInfo.class_name = nullptr;
6671 ThumbSymbolizerInfo.selector_name = nullptr;
6672 ThumbSymbolizerInfo.method = nullptr;
6673 ThumbSymbolizerInfo.demangled_name = nullptr;
6674 ThumbSymbolizerInfo.bindtable = nullptr;
Kevin Enderby10738222014-11-19 20:20:16 +00006675 ThumbSymbolizerInfo.adrp_addr = 0;
6676 ThumbSymbolizerInfo.adrp_inst = 0;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006677
Kevin Enderby4b627be2016-04-28 20:14:13 +00006678 unsigned int Arch = MachOOF->getArch();
6679
Tim Northoverf203ab52016-07-14 22:13:32 +00006680 // Skip all symbols if this is a stubs file.
6681 if (Bytes.size() == 0)
6682 return;
6683
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00006684 // Disassemble symbol by symbol.
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006685 for (unsigned SymIdx = 0; SymIdx != Symbols.size(); SymIdx++) {
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00006686 Expected<StringRef> SymNameOrErr = Symbols[SymIdx].getName();
6687 if (!SymNameOrErr) {
6688 std::string Buf;
6689 raw_string_ostream OS(Buf);
6690 logAllUnhandledErrors(SymNameOrErr.takeError(), OS, "");
6691 OS.flush();
6692 report_fatal_error(Buf);
6693 }
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00006694 StringRef SymName = *SymNameOrErr;
Owen Andersond9243c42011-10-17 21:37:35 +00006695
Kevin Enderby7bd8d992016-05-02 20:28:12 +00006696 Expected<SymbolRef::Type> STOrErr = Symbols[SymIdx].getType();
6697 if (!STOrErr) {
6698 std::string Buf;
6699 raw_string_ostream OS(Buf);
6700 logAllUnhandledErrors(STOrErr.takeError(), OS, "");
6701 OS.flush();
6702 report_fatal_error(Buf);
6703 }
Kevin Enderby5afbc1c2016-03-23 20:27:00 +00006704 SymbolRef::Type ST = *STOrErr;
Kuba Breckade833222015-11-12 09:40:29 +00006705 if (ST != SymbolRef::ST_Function && ST != SymbolRef::ST_Data)
Owen Andersond9243c42011-10-17 21:37:35 +00006706 continue;
6707
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00006708 // Make sure the symbol is defined in this section.
Rafael Espindola80291272014-10-08 15:28:58 +00006709 bool containsSym = Sections[SectIdx].containsSymbol(Symbols[SymIdx]);
Kevin Enderbyd8a6e832016-06-15 21:14:01 +00006710 if (!containsSym) {
6711 if (!DisSymName.empty() && DisSymName == SymName) {
6712 outs() << "-dis-symname: " << DisSymName << " not in the section\n";
6713 return;
6714 }
6715 continue;
6716 }
6717 // The __mh_execute_header is special and we need to deal with that fact
6718 // this symbol is before the start of the (__TEXT,__text) section and at the
6719 // address of the start of the __TEXT segment. This is because this symbol
6720 // is an N_SECT symbol in the (__TEXT,__text) but its address is before the
6721 // start of the section in a standard MH_EXECUTE filetype.
6722 if (!DisSymName.empty() && DisSymName == "__mh_execute_header") {
6723 outs() << "-dis-symname: __mh_execute_header not in any section\n";
6724 return;
6725 }
Tim Northoverfbefee32016-07-14 23:13:03 +00006726 // When this code is trying to disassemble a symbol at a time and in the
6727 // case there is only the __mh_execute_header symbol left as in a stripped
6728 // executable, we need to deal with this by ignoring this symbol so the
6729 // whole section is disassembled and this symbol is then not displayed.
6730 if (SymName == "__mh_execute_header" || SymName == "__mh_dylib_header" ||
6731 SymName == "__mh_bundle_header" || SymName == "__mh_object_header" ||
6732 SymName == "__mh_preload_header" || SymName == "__mh_dylinker_header")
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006733 continue;
6734
Kevin Enderby6a221752015-03-17 17:10:57 +00006735 // If we are only disassembling one symbol see if this is that symbol.
6736 if (!DisSymName.empty() && DisSymName != SymName)
6737 continue;
6738
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00006739 // Start at the address of the symbol relative to the section's address.
Tim Northoverf203ab52016-07-14 22:13:32 +00006740 uint64_t SectSize = Sections[SectIdx].getSize();
Rafael Espindoladea00162015-07-03 17:44:18 +00006741 uint64_t Start = Symbols[SymIdx].getValue();
Rafael Espindola80291272014-10-08 15:28:58 +00006742 uint64_t SectionAddress = Sections[SectIdx].getAddress();
Cameron Zwarich54478a52012-02-03 05:42:17 +00006743 Start -= SectionAddress;
Owen Andersond9243c42011-10-17 21:37:35 +00006744
Tim Northoverf203ab52016-07-14 22:13:32 +00006745 if (Start > SectSize) {
6746 outs() << "section data ends, " << SymName
6747 << " lies outside valid range\n";
6748 return;
6749 }
6750
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00006751 // Stop disassembling either at the beginning of the next symbol or at
6752 // the end of the section.
Kevin Enderbyedd58722012-05-15 18:57:14 +00006753 bool containsNextSym = false;
Owen Andersond9243c42011-10-17 21:37:35 +00006754 uint64_t NextSym = 0;
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006755 uint64_t NextSymIdx = SymIdx + 1;
Owen Andersond9243c42011-10-17 21:37:35 +00006756 while (Symbols.size() > NextSymIdx) {
Kevin Enderby7bd8d992016-05-02 20:28:12 +00006757 Expected<SymbolRef::Type> STOrErr = Symbols[NextSymIdx].getType();
6758 if (!STOrErr) {
6759 std::string Buf;
6760 raw_string_ostream OS(Buf);
6761 logAllUnhandledErrors(STOrErr.takeError(), OS, "");
6762 OS.flush();
6763 report_fatal_error(Buf);
6764 }
Kevin Enderby5afbc1c2016-03-23 20:27:00 +00006765 SymbolRef::Type NextSymType = *STOrErr;
Owen Andersond9243c42011-10-17 21:37:35 +00006766 if (NextSymType == SymbolRef::ST_Function) {
Rafael Espindola80291272014-10-08 15:28:58 +00006767 containsNextSym =
6768 Sections[SectIdx].containsSymbol(Symbols[NextSymIdx]);
Rafael Espindoladea00162015-07-03 17:44:18 +00006769 NextSym = Symbols[NextSymIdx].getValue();
Cameron Zwarich54478a52012-02-03 05:42:17 +00006770 NextSym -= SectionAddress;
Owen Andersond9243c42011-10-17 21:37:35 +00006771 break;
6772 }
6773 ++NextSymIdx;
6774 }
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006775
Tim Northoverf203ab52016-07-14 22:13:32 +00006776 uint64_t End = containsNextSym ? std::min(NextSym, SectSize) : SectSize;
Owen Andersond9243c42011-10-17 21:37:35 +00006777 uint64_t Size;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006778
6779 symbolTableWorked = true;
Rafael Espindolabd604f22014-11-07 00:52:15 +00006780
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006781 DataRefImpl Symb = Symbols[SymIdx].getRawDataRefImpl();
Tim Northover09ca33e2016-04-22 23:23:31 +00006782 bool IsThumb = MachOOF->getSymbolFlags(Symb) & SymbolRef::SF_Thumb;
6783
6784 // We only need the dedicated Thumb target if there's a real choice
6785 // (i.e. we're not targeting M-class) and the function is Thumb.
6786 bool UseThumbTarget = IsThumb && ThumbTarget;
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006787
Ahmed Bougachaaa790682013-05-24 01:07:04 +00006788 outs() << SymName << ":\n";
6789 DILineInfo lastLine;
6790 for (uint64_t Index = Start; Index < End; Index += Size) {
6791 MCInst Inst;
Owen Andersond9243c42011-10-17 21:37:35 +00006792
Kevin Enderbybf246f52014-09-24 23:08:22 +00006793 uint64_t PC = SectAddress + Index;
Kevin Enderbyab5e6c92015-03-17 21:07:39 +00006794 if (!NoLeadingAddr) {
6795 if (FullLeadingAddr) {
6796 if (MachOOF->is64Bit())
6797 outs() << format("%016" PRIx64, PC);
6798 else
6799 outs() << format("%08" PRIx64, PC);
6800 } else {
6801 outs() << format("%8" PRIx64 ":", PC);
6802 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00006803 }
Kevin Enderby4b627be2016-04-28 20:14:13 +00006804 if (!NoShowRawInsn || Arch == Triple::arm)
Kevin Enderbybf246f52014-09-24 23:08:22 +00006805 outs() << "\t";
Kevin Enderby273ae012013-06-06 17:20:50 +00006806
6807 // Check the data in code table here to see if this is data not an
6808 // instruction to be disassembled.
6809 DiceTable Dice;
Kevin Enderbybf246f52014-09-24 23:08:22 +00006810 Dice.push_back(std::make_pair(PC, DiceRef()));
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006811 dice_table_iterator DTI =
6812 std::search(Dices.begin(), Dices.end(), Dice.begin(), Dice.end(),
6813 compareDiceTableEntries);
6814 if (DTI != Dices.end()) {
Kevin Enderby273ae012013-06-06 17:20:50 +00006815 uint16_t Length;
6816 DTI->second.getLength(Length);
Kevin Enderby273ae012013-06-06 17:20:50 +00006817 uint16_t Kind;
6818 DTI->second.getKind(Kind);
Colin LeMahieufc32b1b2015-03-18 19:27:31 +00006819 Size = DumpDataInCode(Bytes.data() + Index, Length, Kind);
Kevin Enderby930fdc72014-11-06 19:00:13 +00006820 if ((Kind == MachO::DICE_KIND_JUMP_TABLE8) &&
6821 (PC == (DTI->first + Length - 1)) && (Length & 1))
6822 Size++;
Kevin Enderby273ae012013-06-06 17:20:50 +00006823 continue;
6824 }
6825
Kevin Enderbybf246f52014-09-24 23:08:22 +00006826 SmallVector<char, 64> AnnotationsBytes;
6827 raw_svector_ostream Annotations(AnnotationsBytes);
6828
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006829 bool gotInst;
Tim Northover09ca33e2016-04-22 23:23:31 +00006830 if (UseThumbTarget)
Rafael Espindola7fc5b872014-11-12 02:04:27 +00006831 gotInst = ThumbDisAsm->getInstruction(Inst, Size, Bytes.slice(Index),
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006832 PC, DebugOut, Annotations);
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006833 else
Rafael Espindola7fc5b872014-11-12 02:04:27 +00006834 gotInst = DisAsm->getInstruction(Inst, Size, Bytes.slice(Index), PC,
Kevin Enderbybf246f52014-09-24 23:08:22 +00006835 DebugOut, Annotations);
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006836 if (gotInst) {
Kevin Enderby4b627be2016-04-28 20:14:13 +00006837 if (!NoShowRawInsn || Arch == Triple::arm) {
Craig Topper0013be12015-09-21 05:32:41 +00006838 dumpBytes(makeArrayRef(Bytes.data() + Index, Size), outs());
Kevin Enderbybf246f52014-09-24 23:08:22 +00006839 }
6840 formatted_raw_ostream FormattedOS(outs());
Kevin Enderbybf246f52014-09-24 23:08:22 +00006841 StringRef AnnotationsStr = Annotations.str();
Tim Northover09ca33e2016-04-22 23:23:31 +00006842 if (UseThumbTarget)
Akira Hatanakab46d0232015-03-27 20:36:02 +00006843 ThumbIP->printInst(&Inst, FormattedOS, AnnotationsStr, *ThumbSTI);
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006844 else
Akira Hatanaka1d079942015-03-28 20:44:05 +00006845 IP->printInst(&Inst, FormattedOS, AnnotationsStr, *STI);
Kevin Enderbybf246f52014-09-24 23:08:22 +00006846 emitComments(CommentStream, CommentsToEmit, FormattedOS, *AsmInfo);
Owen Andersond9243c42011-10-17 21:37:35 +00006847
Ahmed Bougachaaa790682013-05-24 01:07:04 +00006848 // Print debug info.
6849 if (diContext) {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006850 DILineInfo dli = diContext->getLineInfoForAddress(PC);
Ahmed Bougachaaa790682013-05-24 01:07:04 +00006851 // Print valid line info if it changed.
Alexey Samsonovd0109992014-04-18 21:36:39 +00006852 if (dli != lastLine && dli.Line != 0)
6853 outs() << "\t## " << dli.FileName << ':' << dli.Line << ':'
6854 << dli.Column;
Ahmed Bougachaaa790682013-05-24 01:07:04 +00006855 lastLine = dli;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006856 }
Ahmed Bougachaaa790682013-05-24 01:07:04 +00006857 outs() << "\n";
6858 } else {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006859 unsigned int Arch = MachOOF->getArch();
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006860 if (Arch == Triple::x86_64 || Arch == Triple::x86) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006861 outs() << format("\t.byte 0x%02x #bad opcode\n",
6862 *(Bytes.data() + Index) & 0xff);
6863 Size = 1; // skip exactly one illegible byte and move on.
Tim Northover09ca33e2016-04-22 23:23:31 +00006864 } else if (Arch == Triple::aarch64 ||
6865 (Arch == Triple::arm && !IsThumb)) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00006866 uint32_t opcode = (*(Bytes.data() + Index) & 0xff) |
6867 (*(Bytes.data() + Index + 1) & 0xff) << 8 |
6868 (*(Bytes.data() + Index + 2) & 0xff) << 16 |
6869 (*(Bytes.data() + Index + 3) & 0xff) << 24;
6870 outs() << format("\t.long\t0x%08x\n", opcode);
6871 Size = 4;
Tim Northover09ca33e2016-04-22 23:23:31 +00006872 } else if (Arch == Triple::arm) {
6873 assert(IsThumb && "ARM mode should have been dealt with above");
6874 uint32_t opcode = (*(Bytes.data() + Index) & 0xff) |
6875 (*(Bytes.data() + Index + 1) & 0xff) << 8;
6876 outs() << format("\t.short\t0x%04x\n", opcode);
6877 Size = 2;
6878 } else{
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006879 errs() << "llvm-objdump: warning: invalid instruction encoding\n";
6880 if (Size == 0)
6881 Size = 1; // skip illegible bytes
6882 }
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006883 }
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006884 }
6885 }
Ahmed Bougachaaa790682013-05-24 01:07:04 +00006886 if (!symbolTableWorked) {
Rafael Espindola80291272014-10-08 15:28:58 +00006887 // Reading the symbol table didn't work, disassemble the whole section.
6888 uint64_t SectAddress = Sections[SectIdx].getAddress();
6889 uint64_t SectSize = Sections[SectIdx].getSize();
Kevin Enderbybadd1002012-05-18 00:13:56 +00006890 uint64_t InstSize;
6891 for (uint64_t Index = 0; Index < SectSize; Index += InstSize) {
Bill Wendling4e68e062012-07-19 00:17:40 +00006892 MCInst Inst;
Kevin Enderbybadd1002012-05-18 00:13:56 +00006893
Kevin Enderbybf246f52014-09-24 23:08:22 +00006894 uint64_t PC = SectAddress + Index;
Rafael Espindola7fc5b872014-11-12 02:04:27 +00006895 if (DisAsm->getInstruction(Inst, InstSize, Bytes.slice(Index), PC,
6896 DebugOut, nulls())) {
Kevin Enderbyab5e6c92015-03-17 21:07:39 +00006897 if (!NoLeadingAddr) {
6898 if (FullLeadingAddr) {
6899 if (MachOOF->is64Bit())
6900 outs() << format("%016" PRIx64, PC);
6901 else
6902 outs() << format("%08" PRIx64, PC);
6903 } else {
6904 outs() << format("%8" PRIx64 ":", PC);
6905 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00006906 }
Kevin Enderby4b627be2016-04-28 20:14:13 +00006907 if (!NoShowRawInsn || Arch == Triple::arm) {
Kevin Enderbybf246f52014-09-24 23:08:22 +00006908 outs() << "\t";
Craig Topper0013be12015-09-21 05:32:41 +00006909 dumpBytes(makeArrayRef(Bytes.data() + Index, InstSize), outs());
Kevin Enderbybf246f52014-09-24 23:08:22 +00006910 }
Akira Hatanaka1d079942015-03-28 20:44:05 +00006911 IP->printInst(&Inst, outs(), "", *STI);
Bill Wendling4e68e062012-07-19 00:17:40 +00006912 outs() << "\n";
6913 } else {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006914 unsigned int Arch = MachOOF->getArch();
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006915 if (Arch == Triple::x86_64 || Arch == Triple::x86) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006916 outs() << format("\t.byte 0x%02x #bad opcode\n",
6917 *(Bytes.data() + Index) & 0xff);
6918 InstSize = 1; // skip exactly one illegible byte and move on.
6919 } else {
6920 errs() << "llvm-objdump: warning: invalid instruction encoding\n";
6921 if (InstSize == 0)
6922 InstSize = 1; // skip illegible bytes
6923 }
Bill Wendling4e68e062012-07-19 00:17:40 +00006924 }
Kevin Enderbybadd1002012-05-18 00:13:56 +00006925 }
6926 }
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00006927 // The TripleName's need to be reset if we are called again for a different
6928 // archtecture.
6929 TripleName = "";
6930 ThumbTripleName = "";
6931
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006932 if (SymbolizerInfo.method != nullptr)
6933 free(SymbolizerInfo.method);
Kevin Enderby04bf6932014-10-28 23:39:46 +00006934 if (SymbolizerInfo.demangled_name != nullptr)
6935 free(SymbolizerInfo.demangled_name);
Kevin Enderby078be602014-10-23 19:53:12 +00006936 if (SymbolizerInfo.bindtable != nullptr)
6937 delete SymbolizerInfo.bindtable;
Kevin Enderby930fdc72014-11-06 19:00:13 +00006938 if (ThumbSymbolizerInfo.method != nullptr)
6939 free(ThumbSymbolizerInfo.method);
6940 if (ThumbSymbolizerInfo.demangled_name != nullptr)
6941 free(ThumbSymbolizerInfo.demangled_name);
6942 if (ThumbSymbolizerInfo.bindtable != nullptr)
6943 delete ThumbSymbolizerInfo.bindtable;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006944 }
6945}
Tim Northover4bd286a2014-08-01 13:07:19 +00006946
Tim Northover39c70bb2014-08-12 11:52:59 +00006947//===----------------------------------------------------------------------===//
6948// __compact_unwind section dumping
6949//===----------------------------------------------------------------------===//
6950
Tim Northover4bd286a2014-08-01 13:07:19 +00006951namespace {
Tim Northover39c70bb2014-08-12 11:52:59 +00006952
6953template <typename T> static uint64_t readNext(const char *&Buf) {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006954 using llvm::support::little;
6955 using llvm::support::unaligned;
Tim Northover39c70bb2014-08-12 11:52:59 +00006956
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006957 uint64_t Val = support::endian::read<T, little, unaligned>(Buf);
6958 Buf += sizeof(T);
6959 return Val;
6960}
Tim Northover39c70bb2014-08-12 11:52:59 +00006961
Tim Northover4bd286a2014-08-01 13:07:19 +00006962struct CompactUnwindEntry {
6963 uint32_t OffsetInSection;
6964
6965 uint64_t FunctionAddr;
6966 uint32_t Length;
6967 uint32_t CompactEncoding;
6968 uint64_t PersonalityAddr;
6969 uint64_t LSDAAddr;
6970
6971 RelocationRef FunctionReloc;
6972 RelocationRef PersonalityReloc;
6973 RelocationRef LSDAReloc;
6974
6975 CompactUnwindEntry(StringRef Contents, unsigned Offset, bool Is64)
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006976 : OffsetInSection(Offset) {
Tim Northover4bd286a2014-08-01 13:07:19 +00006977 if (Is64)
6978 read<uint64_t>(Contents.data() + Offset);
6979 else
6980 read<uint32_t>(Contents.data() + Offset);
6981 }
6982
6983private:
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006984 template <typename UIntPtr> void read(const char *Buf) {
Tim Northover4bd286a2014-08-01 13:07:19 +00006985 FunctionAddr = readNext<UIntPtr>(Buf);
6986 Length = readNext<uint32_t>(Buf);
6987 CompactEncoding = readNext<uint32_t>(Buf);
6988 PersonalityAddr = readNext<UIntPtr>(Buf);
6989 LSDAAddr = readNext<UIntPtr>(Buf);
6990 }
6991};
6992}
6993
6994/// Given a relocation from __compact_unwind, consisting of the RelocationRef
6995/// and data being relocated, determine the best base Name and Addend to use for
6996/// display purposes.
6997///
6998/// 1. An Extern relocation will directly reference a symbol (and the data is
6999/// then already an addend), so use that.
7000/// 2. Otherwise the data is an offset in the object file's layout; try to find
7001// a symbol before it in the same section, and use the offset from there.
7002/// 3. Finally, if all that fails, fall back to an offset from the start of the
7003/// referenced section.
7004static void findUnwindRelocNameAddend(const MachOObjectFile *Obj,
7005 std::map<uint64_t, SymbolRef> &Symbols,
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007006 const RelocationRef &Reloc, uint64_t Addr,
Tim Northover4bd286a2014-08-01 13:07:19 +00007007 StringRef &Name, uint64_t &Addend) {
7008 if (Reloc.getSymbol() != Obj->symbol_end()) {
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00007009 Expected<StringRef> NameOrErr = Reloc.getSymbol()->getName();
7010 if (!NameOrErr) {
7011 std::string Buf;
7012 raw_string_ostream OS(Buf);
7013 logAllUnhandledErrors(NameOrErr.takeError(), OS, "");
7014 OS.flush();
7015 report_fatal_error(Buf);
7016 }
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00007017 Name = *NameOrErr;
Tim Northover4bd286a2014-08-01 13:07:19 +00007018 Addend = Addr;
7019 return;
7020 }
7021
7022 auto RE = Obj->getRelocation(Reloc.getRawDataRefImpl());
Keno Fischerc780e8e2015-05-21 21:24:32 +00007023 SectionRef RelocSection = Obj->getAnyRelocationSection(RE);
Tim Northover4bd286a2014-08-01 13:07:19 +00007024
Rafael Espindola80291272014-10-08 15:28:58 +00007025 uint64_t SectionAddr = RelocSection.getAddress();
Tim Northover4bd286a2014-08-01 13:07:19 +00007026
7027 auto Sym = Symbols.upper_bound(Addr);
7028 if (Sym == Symbols.begin()) {
7029 // The first symbol in the object is after this reference, the best we can
7030 // do is section-relative notation.
7031 RelocSection.getName(Name);
7032 Addend = Addr - SectionAddr;
7033 return;
7034 }
7035
7036 // Go back one so that SymbolAddress <= Addr.
7037 --Sym;
7038
Kevin Enderby7bd8d992016-05-02 20:28:12 +00007039 auto SectOrErr = Sym->second.getSection();
7040 if (!SectOrErr) {
7041 std::string Buf;
7042 raw_string_ostream OS(Buf);
7043 logAllUnhandledErrors(SectOrErr.takeError(), OS, "");
7044 OS.flush();
7045 report_fatal_error(Buf);
7046 }
7047 section_iterator SymSection = *SectOrErr;
Tim Northover4bd286a2014-08-01 13:07:19 +00007048 if (RelocSection == *SymSection) {
7049 // There's a valid symbol in the same section before this reference.
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00007050 Expected<StringRef> NameOrErr = Sym->second.getName();
7051 if (!NameOrErr) {
7052 std::string Buf;
7053 raw_string_ostream OS(Buf);
7054 logAllUnhandledErrors(NameOrErr.takeError(), OS, "");
7055 OS.flush();
7056 report_fatal_error(Buf);
7057 }
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00007058 Name = *NameOrErr;
Tim Northover4bd286a2014-08-01 13:07:19 +00007059 Addend = Addr - Sym->first;
7060 return;
7061 }
7062
7063 // There is a symbol before this reference, but it's in a different
7064 // section. Probably not helpful to mention it, so use the section name.
7065 RelocSection.getName(Name);
7066 Addend = Addr - SectionAddr;
7067}
7068
7069static void printUnwindRelocDest(const MachOObjectFile *Obj,
7070 std::map<uint64_t, SymbolRef> &Symbols,
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007071 const RelocationRef &Reloc, uint64_t Addr) {
Tim Northover4bd286a2014-08-01 13:07:19 +00007072 StringRef Name;
7073 uint64_t Addend;
7074
Rafael Espindola854038e2015-06-26 14:51:16 +00007075 if (!Reloc.getObject())
Tim Northover0b0add52014-09-09 10:45:06 +00007076 return;
7077
Tim Northover4bd286a2014-08-01 13:07:19 +00007078 findUnwindRelocNameAddend(Obj, Symbols, Reloc, Addr, Name, Addend);
7079
7080 outs() << Name;
7081 if (Addend)
Tim Northover63a25622014-08-11 09:14:06 +00007082 outs() << " + " << format("0x%" PRIx64, Addend);
Tim Northover4bd286a2014-08-01 13:07:19 +00007083}
7084
7085static void
7086printMachOCompactUnwindSection(const MachOObjectFile *Obj,
7087 std::map<uint64_t, SymbolRef> &Symbols,
7088 const SectionRef &CompactUnwind) {
7089
7090 assert(Obj->isLittleEndian() &&
7091 "There should not be a big-endian .o with __compact_unwind");
7092
7093 bool Is64 = Obj->is64Bit();
7094 uint32_t PointerSize = Is64 ? sizeof(uint64_t) : sizeof(uint32_t);
7095 uint32_t EntrySize = 3 * PointerSize + 2 * sizeof(uint32_t);
7096
7097 StringRef Contents;
7098 CompactUnwind.getContents(Contents);
7099
7100 SmallVector<CompactUnwindEntry, 4> CompactUnwinds;
7101
7102 // First populate the initial raw offsets, encodings and so on from the entry.
7103 for (unsigned Offset = 0; Offset < Contents.size(); Offset += EntrySize) {
7104 CompactUnwindEntry Entry(Contents.data(), Offset, Is64);
7105 CompactUnwinds.push_back(Entry);
7106 }
7107
7108 // Next we need to look at the relocations to find out what objects are
7109 // actually being referred to.
7110 for (const RelocationRef &Reloc : CompactUnwind.relocations()) {
Rafael Espindola96d071c2015-06-29 23:29:12 +00007111 uint64_t RelocAddress = Reloc.getOffset();
Tim Northover4bd286a2014-08-01 13:07:19 +00007112
7113 uint32_t EntryIdx = RelocAddress / EntrySize;
7114 uint32_t OffsetInEntry = RelocAddress - EntryIdx * EntrySize;
7115 CompactUnwindEntry &Entry = CompactUnwinds[EntryIdx];
7116
7117 if (OffsetInEntry == 0)
7118 Entry.FunctionReloc = Reloc;
7119 else if (OffsetInEntry == PointerSize + 2 * sizeof(uint32_t))
7120 Entry.PersonalityReloc = Reloc;
7121 else if (OffsetInEntry == 2 * PointerSize + 2 * sizeof(uint32_t))
7122 Entry.LSDAReloc = Reloc;
7123 else
7124 llvm_unreachable("Unexpected relocation in __compact_unwind section");
7125 }
7126
7127 // Finally, we're ready to print the data we've gathered.
7128 outs() << "Contents of __compact_unwind section:\n";
7129 for (auto &Entry : CompactUnwinds) {
Tim Northover06af2602014-08-08 12:08:51 +00007130 outs() << " Entry at offset "
7131 << format("0x%" PRIx32, Entry.OffsetInSection) << ":\n";
Tim Northover4bd286a2014-08-01 13:07:19 +00007132
7133 // 1. Start of the region this entry applies to.
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007134 outs() << " start: " << format("0x%" PRIx64,
7135 Entry.FunctionAddr) << ' ';
7136 printUnwindRelocDest(Obj, Symbols, Entry.FunctionReloc, Entry.FunctionAddr);
Tim Northover4bd286a2014-08-01 13:07:19 +00007137 outs() << '\n';
7138
7139 // 2. Length of the region this entry applies to.
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007140 outs() << " length: " << format("0x%" PRIx32, Entry.Length)
7141 << '\n';
Tim Northover4bd286a2014-08-01 13:07:19 +00007142 // 3. The 32-bit compact encoding.
7143 outs() << " compact encoding: "
Tim Northoverb911bf82014-08-08 12:00:09 +00007144 << format("0x%08" PRIx32, Entry.CompactEncoding) << '\n';
Tim Northover4bd286a2014-08-01 13:07:19 +00007145
7146 // 4. The personality function, if present.
Rafael Espindola854038e2015-06-26 14:51:16 +00007147 if (Entry.PersonalityReloc.getObject()) {
Tim Northover4bd286a2014-08-01 13:07:19 +00007148 outs() << " personality function: "
Tim Northoverb911bf82014-08-08 12:00:09 +00007149 << format("0x%" PRIx64, Entry.PersonalityAddr) << ' ';
Tim Northover4bd286a2014-08-01 13:07:19 +00007150 printUnwindRelocDest(Obj, Symbols, Entry.PersonalityReloc,
7151 Entry.PersonalityAddr);
7152 outs() << '\n';
7153 }
7154
7155 // 5. This entry's language-specific data area.
Rafael Espindola854038e2015-06-26 14:51:16 +00007156 if (Entry.LSDAReloc.getObject()) {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007157 outs() << " LSDA: " << format("0x%" PRIx64,
7158 Entry.LSDAAddr) << ' ';
Tim Northover4bd286a2014-08-01 13:07:19 +00007159 printUnwindRelocDest(Obj, Symbols, Entry.LSDAReloc, Entry.LSDAAddr);
7160 outs() << '\n';
7161 }
7162 }
7163}
7164
Tim Northover39c70bb2014-08-12 11:52:59 +00007165//===----------------------------------------------------------------------===//
7166// __unwind_info section dumping
7167//===----------------------------------------------------------------------===//
7168
7169static void printRegularSecondLevelUnwindPage(const char *PageStart) {
7170 const char *Pos = PageStart;
7171 uint32_t Kind = readNext<uint32_t>(Pos);
7172 (void)Kind;
7173 assert(Kind == 2 && "kind for a regular 2nd level index should be 2");
7174
7175 uint16_t EntriesStart = readNext<uint16_t>(Pos);
7176 uint16_t NumEntries = readNext<uint16_t>(Pos);
7177
7178 Pos = PageStart + EntriesStart;
7179 for (unsigned i = 0; i < NumEntries; ++i) {
7180 uint32_t FunctionOffset = readNext<uint32_t>(Pos);
7181 uint32_t Encoding = readNext<uint32_t>(Pos);
7182
7183 outs() << " [" << i << "]: "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007184 << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
7185 << ", "
7186 << "encoding=" << format("0x%08" PRIx32, Encoding) << '\n';
Tim Northover39c70bb2014-08-12 11:52:59 +00007187 }
7188}
7189
7190static void printCompressedSecondLevelUnwindPage(
7191 const char *PageStart, uint32_t FunctionBase,
7192 const SmallVectorImpl<uint32_t> &CommonEncodings) {
7193 const char *Pos = PageStart;
7194 uint32_t Kind = readNext<uint32_t>(Pos);
7195 (void)Kind;
7196 assert(Kind == 3 && "kind for a compressed 2nd level index should be 3");
7197
7198 uint16_t EntriesStart = readNext<uint16_t>(Pos);
7199 uint16_t NumEntries = readNext<uint16_t>(Pos);
7200
7201 uint16_t EncodingsStart = readNext<uint16_t>(Pos);
7202 readNext<uint16_t>(Pos);
Aaron Ballman80930af2014-08-14 13:53:19 +00007203 const auto *PageEncodings = reinterpret_cast<const support::ulittle32_t *>(
7204 PageStart + EncodingsStart);
Tim Northover39c70bb2014-08-12 11:52:59 +00007205
7206 Pos = PageStart + EntriesStart;
7207 for (unsigned i = 0; i < NumEntries; ++i) {
7208 uint32_t Entry = readNext<uint32_t>(Pos);
7209 uint32_t FunctionOffset = FunctionBase + (Entry & 0xffffff);
7210 uint32_t EncodingIdx = Entry >> 24;
7211
7212 uint32_t Encoding;
7213 if (EncodingIdx < CommonEncodings.size())
7214 Encoding = CommonEncodings[EncodingIdx];
7215 else
7216 Encoding = PageEncodings[EncodingIdx - CommonEncodings.size()];
7217
7218 outs() << " [" << i << "]: "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007219 << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
7220 << ", "
7221 << "encoding[" << EncodingIdx
7222 << "]=" << format("0x%08" PRIx32, Encoding) << '\n';
Tim Northover39c70bb2014-08-12 11:52:59 +00007223 }
7224}
7225
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007226static void printMachOUnwindInfoSection(const MachOObjectFile *Obj,
7227 std::map<uint64_t, SymbolRef> &Symbols,
7228 const SectionRef &UnwindInfo) {
Tim Northover39c70bb2014-08-12 11:52:59 +00007229
7230 assert(Obj->isLittleEndian() &&
7231 "There should not be a big-endian .o with __unwind_info");
7232
7233 outs() << "Contents of __unwind_info section:\n";
7234
7235 StringRef Contents;
7236 UnwindInfo.getContents(Contents);
7237 const char *Pos = Contents.data();
7238
7239 //===----------------------------------
7240 // Section header
7241 //===----------------------------------
7242
7243 uint32_t Version = readNext<uint32_t>(Pos);
7244 outs() << " Version: "
7245 << format("0x%" PRIx32, Version) << '\n';
7246 assert(Version == 1 && "only understand version 1");
7247
7248 uint32_t CommonEncodingsStart = readNext<uint32_t>(Pos);
7249 outs() << " Common encodings array section offset: "
7250 << format("0x%" PRIx32, CommonEncodingsStart) << '\n';
7251 uint32_t NumCommonEncodings = readNext<uint32_t>(Pos);
7252 outs() << " Number of common encodings in array: "
7253 << format("0x%" PRIx32, NumCommonEncodings) << '\n';
7254
7255 uint32_t PersonalitiesStart = readNext<uint32_t>(Pos);
7256 outs() << " Personality function array section offset: "
7257 << format("0x%" PRIx32, PersonalitiesStart) << '\n';
7258 uint32_t NumPersonalities = readNext<uint32_t>(Pos);
7259 outs() << " Number of personality functions in array: "
7260 << format("0x%" PRIx32, NumPersonalities) << '\n';
7261
7262 uint32_t IndicesStart = readNext<uint32_t>(Pos);
7263 outs() << " Index array section offset: "
7264 << format("0x%" PRIx32, IndicesStart) << '\n';
7265 uint32_t NumIndices = readNext<uint32_t>(Pos);
7266 outs() << " Number of indices in array: "
7267 << format("0x%" PRIx32, NumIndices) << '\n';
7268
7269 //===----------------------------------
7270 // A shared list of common encodings
7271 //===----------------------------------
7272
7273 // These occupy indices in the range [0, N] whenever an encoding is referenced
7274 // from a compressed 2nd level index table. In practice the linker only
7275 // creates ~128 of these, so that indices are available to embed encodings in
7276 // the 2nd level index.
7277
7278 SmallVector<uint32_t, 64> CommonEncodings;
7279 outs() << " Common encodings: (count = " << NumCommonEncodings << ")\n";
7280 Pos = Contents.data() + CommonEncodingsStart;
7281 for (unsigned i = 0; i < NumCommonEncodings; ++i) {
7282 uint32_t Encoding = readNext<uint32_t>(Pos);
7283 CommonEncodings.push_back(Encoding);
7284
7285 outs() << " encoding[" << i << "]: " << format("0x%08" PRIx32, Encoding)
7286 << '\n';
7287 }
7288
Tim Northover39c70bb2014-08-12 11:52:59 +00007289 //===----------------------------------
7290 // Personality functions used in this executable
7291 //===----------------------------------
7292
7293 // There should be only a handful of these (one per source language,
7294 // roughly). Particularly since they only get 2 bits in the compact encoding.
7295
7296 outs() << " Personality functions: (count = " << NumPersonalities << ")\n";
7297 Pos = Contents.data() + PersonalitiesStart;
7298 for (unsigned i = 0; i < NumPersonalities; ++i) {
7299 uint32_t PersonalityFn = readNext<uint32_t>(Pos);
7300 outs() << " personality[" << i + 1
7301 << "]: " << format("0x%08" PRIx32, PersonalityFn) << '\n';
7302 }
7303
7304 //===----------------------------------
7305 // The level 1 index entries
7306 //===----------------------------------
7307
7308 // These specify an approximate place to start searching for the more detailed
7309 // information, sorted by PC.
7310
7311 struct IndexEntry {
7312 uint32_t FunctionOffset;
7313 uint32_t SecondLevelPageStart;
7314 uint32_t LSDAStart;
7315 };
7316
7317 SmallVector<IndexEntry, 4> IndexEntries;
7318
7319 outs() << " Top level indices: (count = " << NumIndices << ")\n";
7320 Pos = Contents.data() + IndicesStart;
7321 for (unsigned i = 0; i < NumIndices; ++i) {
7322 IndexEntry Entry;
7323
7324 Entry.FunctionOffset = readNext<uint32_t>(Pos);
7325 Entry.SecondLevelPageStart = readNext<uint32_t>(Pos);
7326 Entry.LSDAStart = readNext<uint32_t>(Pos);
7327 IndexEntries.push_back(Entry);
7328
7329 outs() << " [" << i << "]: "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007330 << "function offset=" << format("0x%08" PRIx32, Entry.FunctionOffset)
7331 << ", "
Tim Northover39c70bb2014-08-12 11:52:59 +00007332 << "2nd level page offset="
7333 << format("0x%08" PRIx32, Entry.SecondLevelPageStart) << ", "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007334 << "LSDA offset=" << format("0x%08" PRIx32, Entry.LSDAStart) << '\n';
Tim Northover39c70bb2014-08-12 11:52:59 +00007335 }
7336
Tim Northover39c70bb2014-08-12 11:52:59 +00007337 //===----------------------------------
7338 // Next come the LSDA tables
7339 //===----------------------------------
7340
7341 // The LSDA layout is rather implicit: it's a contiguous array of entries from
7342 // the first top-level index's LSDAOffset to the last (sentinel).
7343
7344 outs() << " LSDA descriptors:\n";
7345 Pos = Contents.data() + IndexEntries[0].LSDAStart;
7346 int NumLSDAs = (IndexEntries.back().LSDAStart - IndexEntries[0].LSDAStart) /
7347 (2 * sizeof(uint32_t));
7348 for (int i = 0; i < NumLSDAs; ++i) {
7349 uint32_t FunctionOffset = readNext<uint32_t>(Pos);
7350 uint32_t LSDAOffset = readNext<uint32_t>(Pos);
7351 outs() << " [" << i << "]: "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007352 << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
7353 << ", "
7354 << "LSDA offset=" << format("0x%08" PRIx32, LSDAOffset) << '\n';
Tim Northover39c70bb2014-08-12 11:52:59 +00007355 }
7356
7357 //===----------------------------------
7358 // Finally, the 2nd level indices
7359 //===----------------------------------
7360
7361 // Generally these are 4K in size, and have 2 possible forms:
7362 // + Regular stores up to 511 entries with disparate encodings
7363 // + Compressed stores up to 1021 entries if few enough compact encoding
7364 // values are used.
7365 outs() << " Second level indices:\n";
7366 for (unsigned i = 0; i < IndexEntries.size() - 1; ++i) {
7367 // The final sentinel top-level index has no associated 2nd level page
7368 if (IndexEntries[i].SecondLevelPageStart == 0)
7369 break;
7370
7371 outs() << " Second level index[" << i << "]: "
7372 << "offset in section="
7373 << format("0x%08" PRIx32, IndexEntries[i].SecondLevelPageStart)
7374 << ", "
7375 << "base function offset="
7376 << format("0x%08" PRIx32, IndexEntries[i].FunctionOffset) << '\n';
7377
7378 Pos = Contents.data() + IndexEntries[i].SecondLevelPageStart;
Aaron Ballman80930af2014-08-14 13:53:19 +00007379 uint32_t Kind = *reinterpret_cast<const support::ulittle32_t *>(Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007380 if (Kind == 2)
7381 printRegularSecondLevelUnwindPage(Pos);
7382 else if (Kind == 3)
7383 printCompressedSecondLevelUnwindPage(Pos, IndexEntries[i].FunctionOffset,
7384 CommonEncodings);
7385 else
7386 llvm_unreachable("Do not know how to print this kind of 2nd level page");
Tim Northover39c70bb2014-08-12 11:52:59 +00007387 }
7388}
7389
Tim Northover4bd286a2014-08-01 13:07:19 +00007390void llvm::printMachOUnwindInfo(const MachOObjectFile *Obj) {
7391 std::map<uint64_t, SymbolRef> Symbols;
7392 for (const SymbolRef &SymRef : Obj->symbols()) {
7393 // Discard any undefined or absolute symbols. They're not going to take part
7394 // in the convenience lookup for unwind info and just take up resources.
Kevin Enderby7bd8d992016-05-02 20:28:12 +00007395 auto SectOrErr = SymRef.getSection();
7396 if (!SectOrErr) {
7397 // TODO: Actually report errors helpfully.
7398 consumeError(SectOrErr.takeError());
7399 continue;
7400 }
7401 section_iterator Section = *SectOrErr;
Tim Northover4bd286a2014-08-01 13:07:19 +00007402 if (Section == Obj->section_end())
7403 continue;
7404
Rafael Espindoladea00162015-07-03 17:44:18 +00007405 uint64_t Addr = SymRef.getValue();
Tim Northover4bd286a2014-08-01 13:07:19 +00007406 Symbols.insert(std::make_pair(Addr, SymRef));
7407 }
7408
7409 for (const SectionRef &Section : Obj->sections()) {
7410 StringRef SectName;
7411 Section.getName(SectName);
7412 if (SectName == "__compact_unwind")
7413 printMachOCompactUnwindSection(Obj, Symbols, Section);
7414 else if (SectName == "__unwind_info")
Tim Northover39c70bb2014-08-12 11:52:59 +00007415 printMachOUnwindInfoSection(Obj, Symbols, Section);
Tim Northover4bd286a2014-08-01 13:07:19 +00007416 }
7417}
Kevin Enderbyb76d3862014-08-22 20:35:18 +00007418
7419static void PrintMachHeader(uint32_t magic, uint32_t cputype,
7420 uint32_t cpusubtype, uint32_t filetype,
7421 uint32_t ncmds, uint32_t sizeofcmds, uint32_t flags,
7422 bool verbose) {
7423 outs() << "Mach header\n";
7424 outs() << " magic cputype cpusubtype caps filetype ncmds "
7425 "sizeofcmds flags\n";
7426 if (verbose) {
7427 if (magic == MachO::MH_MAGIC)
7428 outs() << " MH_MAGIC";
7429 else if (magic == MachO::MH_MAGIC_64)
7430 outs() << "MH_MAGIC_64";
7431 else
7432 outs() << format(" 0x%08" PRIx32, magic);
7433 switch (cputype) {
7434 case MachO::CPU_TYPE_I386:
7435 outs() << " I386";
7436 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
7437 case MachO::CPU_SUBTYPE_I386_ALL:
7438 outs() << " ALL";
7439 break;
7440 default:
7441 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
7442 break;
7443 }
7444 break;
7445 case MachO::CPU_TYPE_X86_64:
7446 outs() << " X86_64";
Kevin Enderby131d1772015-01-09 19:22:37 +00007447 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
7448 case MachO::CPU_SUBTYPE_X86_64_ALL:
7449 outs() << " ALL";
7450 break;
7451 case MachO::CPU_SUBTYPE_X86_64_H:
7452 outs() << " Haswell";
7453 break;
7454 default:
7455 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
7456 break;
7457 }
Kevin Enderbyb76d3862014-08-22 20:35:18 +00007458 break;
7459 case MachO::CPU_TYPE_ARM:
7460 outs() << " ARM";
7461 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
7462 case MachO::CPU_SUBTYPE_ARM_ALL:
7463 outs() << " ALL";
7464 break;
7465 case MachO::CPU_SUBTYPE_ARM_V4T:
7466 outs() << " V4T";
7467 break;
7468 case MachO::CPU_SUBTYPE_ARM_V5TEJ:
7469 outs() << " V5TEJ";
7470 break;
7471 case MachO::CPU_SUBTYPE_ARM_XSCALE:
7472 outs() << " XSCALE";
7473 break;
7474 case MachO::CPU_SUBTYPE_ARM_V6:
7475 outs() << " V6";
7476 break;
7477 case MachO::CPU_SUBTYPE_ARM_V6M:
7478 outs() << " V6M";
7479 break;
7480 case MachO::CPU_SUBTYPE_ARM_V7:
7481 outs() << " V7";
7482 break;
7483 case MachO::CPU_SUBTYPE_ARM_V7EM:
7484 outs() << " V7EM";
7485 break;
7486 case MachO::CPU_SUBTYPE_ARM_V7K:
7487 outs() << " V7K";
7488 break;
7489 case MachO::CPU_SUBTYPE_ARM_V7M:
7490 outs() << " V7M";
7491 break;
7492 case MachO::CPU_SUBTYPE_ARM_V7S:
7493 outs() << " V7S";
7494 break;
7495 default:
7496 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
7497 break;
7498 }
7499 break;
7500 case MachO::CPU_TYPE_ARM64:
7501 outs() << " ARM64";
7502 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
7503 case MachO::CPU_SUBTYPE_ARM64_ALL:
7504 outs() << " ALL";
7505 break;
7506 default:
7507 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
7508 break;
7509 }
7510 break;
7511 case MachO::CPU_TYPE_POWERPC:
7512 outs() << " PPC";
7513 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
7514 case MachO::CPU_SUBTYPE_POWERPC_ALL:
7515 outs() << " ALL";
7516 break;
7517 default:
7518 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
7519 break;
7520 }
7521 break;
7522 case MachO::CPU_TYPE_POWERPC64:
7523 outs() << " PPC64";
7524 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
7525 case MachO::CPU_SUBTYPE_POWERPC_ALL:
7526 outs() << " ALL";
7527 break;
7528 default:
7529 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
7530 break;
7531 }
7532 break;
Kevin Enderby40fdbf82016-01-26 18:20:49 +00007533 default:
7534 outs() << format(" %7d", cputype);
7535 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
7536 break;
Kevin Enderbyb76d3862014-08-22 20:35:18 +00007537 }
7538 if ((cpusubtype & MachO::CPU_SUBTYPE_MASK) == MachO::CPU_SUBTYPE_LIB64) {
Kevin Enderby8ae63c12014-09-04 16:54:47 +00007539 outs() << " LIB64";
Kevin Enderbyb76d3862014-08-22 20:35:18 +00007540 } else {
7541 outs() << format(" 0x%02" PRIx32,
7542 (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24);
7543 }
7544 switch (filetype) {
7545 case MachO::MH_OBJECT:
7546 outs() << " OBJECT";
7547 break;
7548 case MachO::MH_EXECUTE:
7549 outs() << " EXECUTE";
7550 break;
7551 case MachO::MH_FVMLIB:
7552 outs() << " FVMLIB";
7553 break;
7554 case MachO::MH_CORE:
7555 outs() << " CORE";
7556 break;
7557 case MachO::MH_PRELOAD:
7558 outs() << " PRELOAD";
7559 break;
7560 case MachO::MH_DYLIB:
7561 outs() << " DYLIB";
7562 break;
7563 case MachO::MH_DYLIB_STUB:
7564 outs() << " DYLIB_STUB";
7565 break;
7566 case MachO::MH_DYLINKER:
7567 outs() << " DYLINKER";
7568 break;
7569 case MachO::MH_BUNDLE:
7570 outs() << " BUNDLE";
7571 break;
7572 case MachO::MH_DSYM:
7573 outs() << " DSYM";
7574 break;
7575 case MachO::MH_KEXT_BUNDLE:
7576 outs() << " KEXTBUNDLE";
7577 break;
7578 default:
7579 outs() << format(" %10u", filetype);
7580 break;
7581 }
7582 outs() << format(" %5u", ncmds);
7583 outs() << format(" %10u", sizeofcmds);
7584 uint32_t f = flags;
7585 if (f & MachO::MH_NOUNDEFS) {
7586 outs() << " NOUNDEFS";
7587 f &= ~MachO::MH_NOUNDEFS;
7588 }
7589 if (f & MachO::MH_INCRLINK) {
7590 outs() << " INCRLINK";
7591 f &= ~MachO::MH_INCRLINK;
7592 }
7593 if (f & MachO::MH_DYLDLINK) {
7594 outs() << " DYLDLINK";
7595 f &= ~MachO::MH_DYLDLINK;
7596 }
7597 if (f & MachO::MH_BINDATLOAD) {
7598 outs() << " BINDATLOAD";
7599 f &= ~MachO::MH_BINDATLOAD;
7600 }
7601 if (f & MachO::MH_PREBOUND) {
7602 outs() << " PREBOUND";
7603 f &= ~MachO::MH_PREBOUND;
7604 }
7605 if (f & MachO::MH_SPLIT_SEGS) {
7606 outs() << " SPLIT_SEGS";
7607 f &= ~MachO::MH_SPLIT_SEGS;
7608 }
7609 if (f & MachO::MH_LAZY_INIT) {
7610 outs() << " LAZY_INIT";
7611 f &= ~MachO::MH_LAZY_INIT;
7612 }
7613 if (f & MachO::MH_TWOLEVEL) {
7614 outs() << " TWOLEVEL";
7615 f &= ~MachO::MH_TWOLEVEL;
7616 }
7617 if (f & MachO::MH_FORCE_FLAT) {
7618 outs() << " FORCE_FLAT";
7619 f &= ~MachO::MH_FORCE_FLAT;
7620 }
7621 if (f & MachO::MH_NOMULTIDEFS) {
7622 outs() << " NOMULTIDEFS";
7623 f &= ~MachO::MH_NOMULTIDEFS;
7624 }
7625 if (f & MachO::MH_NOFIXPREBINDING) {
7626 outs() << " NOFIXPREBINDING";
7627 f &= ~MachO::MH_NOFIXPREBINDING;
7628 }
7629 if (f & MachO::MH_PREBINDABLE) {
7630 outs() << " PREBINDABLE";
7631 f &= ~MachO::MH_PREBINDABLE;
7632 }
7633 if (f & MachO::MH_ALLMODSBOUND) {
7634 outs() << " ALLMODSBOUND";
7635 f &= ~MachO::MH_ALLMODSBOUND;
7636 }
7637 if (f & MachO::MH_SUBSECTIONS_VIA_SYMBOLS) {
7638 outs() << " SUBSECTIONS_VIA_SYMBOLS";
7639 f &= ~MachO::MH_SUBSECTIONS_VIA_SYMBOLS;
7640 }
7641 if (f & MachO::MH_CANONICAL) {
7642 outs() << " CANONICAL";
7643 f &= ~MachO::MH_CANONICAL;
7644 }
7645 if (f & MachO::MH_WEAK_DEFINES) {
7646 outs() << " WEAK_DEFINES";
7647 f &= ~MachO::MH_WEAK_DEFINES;
7648 }
7649 if (f & MachO::MH_BINDS_TO_WEAK) {
7650 outs() << " BINDS_TO_WEAK";
7651 f &= ~MachO::MH_BINDS_TO_WEAK;
7652 }
7653 if (f & MachO::MH_ALLOW_STACK_EXECUTION) {
7654 outs() << " ALLOW_STACK_EXECUTION";
7655 f &= ~MachO::MH_ALLOW_STACK_EXECUTION;
7656 }
7657 if (f & MachO::MH_DEAD_STRIPPABLE_DYLIB) {
7658 outs() << " DEAD_STRIPPABLE_DYLIB";
7659 f &= ~MachO::MH_DEAD_STRIPPABLE_DYLIB;
7660 }
7661 if (f & MachO::MH_PIE) {
7662 outs() << " PIE";
7663 f &= ~MachO::MH_PIE;
7664 }
7665 if (f & MachO::MH_NO_REEXPORTED_DYLIBS) {
7666 outs() << " NO_REEXPORTED_DYLIBS";
7667 f &= ~MachO::MH_NO_REEXPORTED_DYLIBS;
7668 }
7669 if (f & MachO::MH_HAS_TLV_DESCRIPTORS) {
7670 outs() << " MH_HAS_TLV_DESCRIPTORS";
7671 f &= ~MachO::MH_HAS_TLV_DESCRIPTORS;
7672 }
7673 if (f & MachO::MH_NO_HEAP_EXECUTION) {
7674 outs() << " MH_NO_HEAP_EXECUTION";
7675 f &= ~MachO::MH_NO_HEAP_EXECUTION;
7676 }
7677 if (f & MachO::MH_APP_EXTENSION_SAFE) {
7678 outs() << " APP_EXTENSION_SAFE";
7679 f &= ~MachO::MH_APP_EXTENSION_SAFE;
7680 }
7681 if (f != 0 || flags == 0)
7682 outs() << format(" 0x%08" PRIx32, f);
7683 } else {
7684 outs() << format(" 0x%08" PRIx32, magic);
7685 outs() << format(" %7d", cputype);
7686 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
7687 outs() << format(" 0x%02" PRIx32,
7688 (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24);
7689 outs() << format(" %10u", filetype);
7690 outs() << format(" %5u", ncmds);
7691 outs() << format(" %10u", sizeofcmds);
7692 outs() << format(" 0x%08" PRIx32, flags);
7693 }
7694 outs() << "\n";
7695}
7696
Kevin Enderby956366c2014-08-29 22:30:52 +00007697static void PrintSegmentCommand(uint32_t cmd, uint32_t cmdsize,
7698 StringRef SegName, uint64_t vmaddr,
7699 uint64_t vmsize, uint64_t fileoff,
7700 uint64_t filesize, uint32_t maxprot,
7701 uint32_t initprot, uint32_t nsects,
7702 uint32_t flags, uint32_t object_size,
7703 bool verbose) {
7704 uint64_t expected_cmdsize;
7705 if (cmd == MachO::LC_SEGMENT) {
7706 outs() << " cmd LC_SEGMENT\n";
7707 expected_cmdsize = nsects;
7708 expected_cmdsize *= sizeof(struct MachO::section);
7709 expected_cmdsize += sizeof(struct MachO::segment_command);
7710 } else {
7711 outs() << " cmd LC_SEGMENT_64\n";
7712 expected_cmdsize = nsects;
7713 expected_cmdsize *= sizeof(struct MachO::section_64);
7714 expected_cmdsize += sizeof(struct MachO::segment_command_64);
7715 }
7716 outs() << " cmdsize " << cmdsize;
7717 if (cmdsize != expected_cmdsize)
7718 outs() << " Inconsistent size\n";
7719 else
7720 outs() << "\n";
7721 outs() << " segname " << SegName << "\n";
7722 if (cmd == MachO::LC_SEGMENT_64) {
7723 outs() << " vmaddr " << format("0x%016" PRIx64, vmaddr) << "\n";
7724 outs() << " vmsize " << format("0x%016" PRIx64, vmsize) << "\n";
7725 } else {
Kevin Enderbyadb7c432014-12-16 18:58:11 +00007726 outs() << " vmaddr " << format("0x%08" PRIx64, vmaddr) << "\n";
7727 outs() << " vmsize " << format("0x%08" PRIx64, vmsize) << "\n";
Kevin Enderby956366c2014-08-29 22:30:52 +00007728 }
7729 outs() << " fileoff " << fileoff;
7730 if (fileoff > object_size)
7731 outs() << " (past end of file)\n";
7732 else
7733 outs() << "\n";
7734 outs() << " filesize " << filesize;
7735 if (fileoff + filesize > object_size)
7736 outs() << " (past end of file)\n";
7737 else
7738 outs() << "\n";
7739 if (verbose) {
7740 if ((maxprot &
7741 ~(MachO::VM_PROT_READ | MachO::VM_PROT_WRITE |
7742 MachO::VM_PROT_EXECUTE)) != 0)
7743 outs() << " maxprot ?" << format("0x%08" PRIx32, maxprot) << "\n";
7744 else {
Davide Italiano37ff06a2015-09-02 16:53:25 +00007745 outs() << " maxprot ";
7746 outs() << ((maxprot & MachO::VM_PROT_READ) ? "r" : "-");
7747 outs() << ((maxprot & MachO::VM_PROT_WRITE) ? "w" : "-");
7748 outs() << ((maxprot & MachO::VM_PROT_EXECUTE) ? "x\n" : "-\n");
Kevin Enderby956366c2014-08-29 22:30:52 +00007749 }
7750 if ((initprot &
7751 ~(MachO::VM_PROT_READ | MachO::VM_PROT_WRITE |
7752 MachO::VM_PROT_EXECUTE)) != 0)
7753 outs() << " initprot ?" << format("0x%08" PRIx32, initprot) << "\n";
7754 else {
Davide Italiano37ff06a2015-09-02 16:53:25 +00007755 outs() << " initprot ";
7756 outs() << ((initprot & MachO::VM_PROT_READ) ? "r" : "-");
7757 outs() << ((initprot & MachO::VM_PROT_WRITE) ? "w" : "-");
7758 outs() << ((initprot & MachO::VM_PROT_EXECUTE) ? "x\n" : "-\n");
Kevin Enderby956366c2014-08-29 22:30:52 +00007759 }
7760 } else {
7761 outs() << " maxprot " << format("0x%08" PRIx32, maxprot) << "\n";
7762 outs() << " initprot " << format("0x%08" PRIx32, initprot) << "\n";
7763 }
7764 outs() << " nsects " << nsects << "\n";
7765 if (verbose) {
7766 outs() << " flags";
7767 if (flags == 0)
7768 outs() << " (none)\n";
7769 else {
7770 if (flags & MachO::SG_HIGHVM) {
7771 outs() << " HIGHVM";
7772 flags &= ~MachO::SG_HIGHVM;
7773 }
7774 if (flags & MachO::SG_FVMLIB) {
7775 outs() << " FVMLIB";
7776 flags &= ~MachO::SG_FVMLIB;
7777 }
7778 if (flags & MachO::SG_NORELOC) {
7779 outs() << " NORELOC";
7780 flags &= ~MachO::SG_NORELOC;
7781 }
7782 if (flags & MachO::SG_PROTECTED_VERSION_1) {
7783 outs() << " PROTECTED_VERSION_1";
7784 flags &= ~MachO::SG_PROTECTED_VERSION_1;
7785 }
7786 if (flags)
7787 outs() << format(" 0x%08" PRIx32, flags) << " (unknown flags)\n";
7788 else
7789 outs() << "\n";
7790 }
7791 } else {
7792 outs() << " flags " << format("0x%" PRIx32, flags) << "\n";
7793 }
7794}
7795
7796static void PrintSection(const char *sectname, const char *segname,
7797 uint64_t addr, uint64_t size, uint32_t offset,
7798 uint32_t align, uint32_t reloff, uint32_t nreloc,
7799 uint32_t flags, uint32_t reserved1, uint32_t reserved2,
7800 uint32_t cmd, const char *sg_segname,
7801 uint32_t filetype, uint32_t object_size,
7802 bool verbose) {
7803 outs() << "Section\n";
7804 outs() << " sectname " << format("%.16s\n", sectname);
7805 outs() << " segname " << format("%.16s", segname);
7806 if (filetype != MachO::MH_OBJECT && strncmp(sg_segname, segname, 16) != 0)
7807 outs() << " (does not match segment)\n";
7808 else
7809 outs() << "\n";
7810 if (cmd == MachO::LC_SEGMENT_64) {
7811 outs() << " addr " << format("0x%016" PRIx64, addr) << "\n";
7812 outs() << " size " << format("0x%016" PRIx64, size);
7813 } else {
Kevin Enderby75594b62014-12-16 21:00:25 +00007814 outs() << " addr " << format("0x%08" PRIx64, addr) << "\n";
7815 outs() << " size " << format("0x%08" PRIx64, size);
Kevin Enderby956366c2014-08-29 22:30:52 +00007816 }
7817 if ((flags & MachO::S_ZEROFILL) != 0 && offset + size > object_size)
7818 outs() << " (past end of file)\n";
7819 else
7820 outs() << "\n";
7821 outs() << " offset " << offset;
7822 if (offset > object_size)
7823 outs() << " (past end of file)\n";
7824 else
7825 outs() << "\n";
7826 uint32_t align_shifted = 1 << align;
7827 outs() << " align 2^" << align << " (" << align_shifted << ")\n";
7828 outs() << " reloff " << reloff;
7829 if (reloff > object_size)
7830 outs() << " (past end of file)\n";
7831 else
7832 outs() << "\n";
7833 outs() << " nreloc " << nreloc;
7834 if (reloff + nreloc * sizeof(struct MachO::relocation_info) > object_size)
7835 outs() << " (past end of file)\n";
7836 else
7837 outs() << "\n";
7838 uint32_t section_type = flags & MachO::SECTION_TYPE;
7839 if (verbose) {
7840 outs() << " type";
7841 if (section_type == MachO::S_REGULAR)
7842 outs() << " S_REGULAR\n";
7843 else if (section_type == MachO::S_ZEROFILL)
7844 outs() << " S_ZEROFILL\n";
7845 else if (section_type == MachO::S_CSTRING_LITERALS)
7846 outs() << " S_CSTRING_LITERALS\n";
7847 else if (section_type == MachO::S_4BYTE_LITERALS)
7848 outs() << " S_4BYTE_LITERALS\n";
7849 else if (section_type == MachO::S_8BYTE_LITERALS)
7850 outs() << " S_8BYTE_LITERALS\n";
7851 else if (section_type == MachO::S_16BYTE_LITERALS)
7852 outs() << " S_16BYTE_LITERALS\n";
7853 else if (section_type == MachO::S_LITERAL_POINTERS)
7854 outs() << " S_LITERAL_POINTERS\n";
7855 else if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS)
7856 outs() << " S_NON_LAZY_SYMBOL_POINTERS\n";
7857 else if (section_type == MachO::S_LAZY_SYMBOL_POINTERS)
7858 outs() << " S_LAZY_SYMBOL_POINTERS\n";
7859 else if (section_type == MachO::S_SYMBOL_STUBS)
7860 outs() << " S_SYMBOL_STUBS\n";
7861 else if (section_type == MachO::S_MOD_INIT_FUNC_POINTERS)
7862 outs() << " S_MOD_INIT_FUNC_POINTERS\n";
7863 else if (section_type == MachO::S_MOD_TERM_FUNC_POINTERS)
7864 outs() << " S_MOD_TERM_FUNC_POINTERS\n";
7865 else if (section_type == MachO::S_COALESCED)
7866 outs() << " S_COALESCED\n";
7867 else if (section_type == MachO::S_INTERPOSING)
7868 outs() << " S_INTERPOSING\n";
7869 else if (section_type == MachO::S_DTRACE_DOF)
7870 outs() << " S_DTRACE_DOF\n";
7871 else if (section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS)
7872 outs() << " S_LAZY_DYLIB_SYMBOL_POINTERS\n";
7873 else if (section_type == MachO::S_THREAD_LOCAL_REGULAR)
7874 outs() << " S_THREAD_LOCAL_REGULAR\n";
7875 else if (section_type == MachO::S_THREAD_LOCAL_ZEROFILL)
7876 outs() << " S_THREAD_LOCAL_ZEROFILL\n";
7877 else if (section_type == MachO::S_THREAD_LOCAL_VARIABLES)
7878 outs() << " S_THREAD_LOCAL_VARIABLES\n";
7879 else if (section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS)
7880 outs() << " S_THREAD_LOCAL_VARIABLE_POINTERS\n";
7881 else if (section_type == MachO::S_THREAD_LOCAL_INIT_FUNCTION_POINTERS)
7882 outs() << " S_THREAD_LOCAL_INIT_FUNCTION_POINTERS\n";
7883 else
7884 outs() << format("0x%08" PRIx32, section_type) << "\n";
7885 outs() << "attributes";
7886 uint32_t section_attributes = flags & MachO::SECTION_ATTRIBUTES;
7887 if (section_attributes & MachO::S_ATTR_PURE_INSTRUCTIONS)
7888 outs() << " PURE_INSTRUCTIONS";
7889 if (section_attributes & MachO::S_ATTR_NO_TOC)
7890 outs() << " NO_TOC";
7891 if (section_attributes & MachO::S_ATTR_STRIP_STATIC_SYMS)
7892 outs() << " STRIP_STATIC_SYMS";
7893 if (section_attributes & MachO::S_ATTR_NO_DEAD_STRIP)
7894 outs() << " NO_DEAD_STRIP";
7895 if (section_attributes & MachO::S_ATTR_LIVE_SUPPORT)
7896 outs() << " LIVE_SUPPORT";
7897 if (section_attributes & MachO::S_ATTR_SELF_MODIFYING_CODE)
7898 outs() << " SELF_MODIFYING_CODE";
7899 if (section_attributes & MachO::S_ATTR_DEBUG)
7900 outs() << " DEBUG";
7901 if (section_attributes & MachO::S_ATTR_SOME_INSTRUCTIONS)
7902 outs() << " SOME_INSTRUCTIONS";
7903 if (section_attributes & MachO::S_ATTR_EXT_RELOC)
7904 outs() << " EXT_RELOC";
7905 if (section_attributes & MachO::S_ATTR_LOC_RELOC)
7906 outs() << " LOC_RELOC";
7907 if (section_attributes == 0)
7908 outs() << " (none)";
7909 outs() << "\n";
7910 } else
7911 outs() << " flags " << format("0x%08" PRIx32, flags) << "\n";
7912 outs() << " reserved1 " << reserved1;
7913 if (section_type == MachO::S_SYMBOL_STUBS ||
7914 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
7915 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
7916 section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
7917 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS)
7918 outs() << " (index into indirect symbol table)\n";
7919 else
7920 outs() << "\n";
7921 outs() << " reserved2 " << reserved2;
7922 if (section_type == MachO::S_SYMBOL_STUBS)
7923 outs() << " (size of stubs)\n";
7924 else
7925 outs() << "\n";
7926}
7927
David Majnemer73cc6ff2014-11-13 19:48:56 +00007928static void PrintSymtabLoadCommand(MachO::symtab_command st, bool Is64Bit,
Kevin Enderby956366c2014-08-29 22:30:52 +00007929 uint32_t object_size) {
7930 outs() << " cmd LC_SYMTAB\n";
7931 outs() << " cmdsize " << st.cmdsize;
7932 if (st.cmdsize != sizeof(struct MachO::symtab_command))
7933 outs() << " Incorrect size\n";
7934 else
7935 outs() << "\n";
7936 outs() << " symoff " << st.symoff;
7937 if (st.symoff > object_size)
7938 outs() << " (past end of file)\n";
7939 else
7940 outs() << "\n";
7941 outs() << " nsyms " << st.nsyms;
7942 uint64_t big_size;
David Majnemer73cc6ff2014-11-13 19:48:56 +00007943 if (Is64Bit) {
Kevin Enderby956366c2014-08-29 22:30:52 +00007944 big_size = st.nsyms;
7945 big_size *= sizeof(struct MachO::nlist_64);
7946 big_size += st.symoff;
7947 if (big_size > object_size)
7948 outs() << " (past end of file)\n";
7949 else
7950 outs() << "\n";
7951 } else {
7952 big_size = st.nsyms;
7953 big_size *= sizeof(struct MachO::nlist);
7954 big_size += st.symoff;
7955 if (big_size > object_size)
7956 outs() << " (past end of file)\n";
7957 else
7958 outs() << "\n";
7959 }
7960 outs() << " stroff " << st.stroff;
7961 if (st.stroff > object_size)
7962 outs() << " (past end of file)\n";
7963 else
7964 outs() << "\n";
7965 outs() << " strsize " << st.strsize;
7966 big_size = st.stroff;
7967 big_size += st.strsize;
7968 if (big_size > object_size)
7969 outs() << " (past end of file)\n";
7970 else
7971 outs() << "\n";
7972}
7973
7974static void PrintDysymtabLoadCommand(MachO::dysymtab_command dyst,
7975 uint32_t nsyms, uint32_t object_size,
David Majnemer73cc6ff2014-11-13 19:48:56 +00007976 bool Is64Bit) {
Kevin Enderby956366c2014-08-29 22:30:52 +00007977 outs() << " cmd LC_DYSYMTAB\n";
7978 outs() << " cmdsize " << dyst.cmdsize;
7979 if (dyst.cmdsize != sizeof(struct MachO::dysymtab_command))
7980 outs() << " Incorrect size\n";
7981 else
7982 outs() << "\n";
7983 outs() << " ilocalsym " << dyst.ilocalsym;
7984 if (dyst.ilocalsym > nsyms)
7985 outs() << " (greater than the number of symbols)\n";
7986 else
7987 outs() << "\n";
7988 outs() << " nlocalsym " << dyst.nlocalsym;
7989 uint64_t big_size;
7990 big_size = dyst.ilocalsym;
7991 big_size += dyst.nlocalsym;
7992 if (big_size > nsyms)
7993 outs() << " (past the end of the symbol table)\n";
7994 else
7995 outs() << "\n";
7996 outs() << " iextdefsym " << dyst.iextdefsym;
7997 if (dyst.iextdefsym > nsyms)
7998 outs() << " (greater than the number of symbols)\n";
7999 else
8000 outs() << "\n";
8001 outs() << " nextdefsym " << dyst.nextdefsym;
8002 big_size = dyst.iextdefsym;
8003 big_size += dyst.nextdefsym;
8004 if (big_size > nsyms)
8005 outs() << " (past the end of the symbol table)\n";
8006 else
8007 outs() << "\n";
8008 outs() << " iundefsym " << dyst.iundefsym;
8009 if (dyst.iundefsym > nsyms)
8010 outs() << " (greater than the number of symbols)\n";
8011 else
8012 outs() << "\n";
8013 outs() << " nundefsym " << dyst.nundefsym;
8014 big_size = dyst.iundefsym;
8015 big_size += dyst.nundefsym;
8016 if (big_size > nsyms)
8017 outs() << " (past the end of the symbol table)\n";
8018 else
8019 outs() << "\n";
8020 outs() << " tocoff " << dyst.tocoff;
8021 if (dyst.tocoff > object_size)
8022 outs() << " (past end of file)\n";
8023 else
8024 outs() << "\n";
8025 outs() << " ntoc " << dyst.ntoc;
8026 big_size = dyst.ntoc;
8027 big_size *= sizeof(struct MachO::dylib_table_of_contents);
8028 big_size += dyst.tocoff;
8029 if (big_size > object_size)
8030 outs() << " (past end of file)\n";
8031 else
8032 outs() << "\n";
8033 outs() << " modtaboff " << dyst.modtaboff;
8034 if (dyst.modtaboff > object_size)
8035 outs() << " (past end of file)\n";
8036 else
8037 outs() << "\n";
8038 outs() << " nmodtab " << dyst.nmodtab;
8039 uint64_t modtabend;
David Majnemer73cc6ff2014-11-13 19:48:56 +00008040 if (Is64Bit) {
Kevin Enderby956366c2014-08-29 22:30:52 +00008041 modtabend = dyst.nmodtab;
8042 modtabend *= sizeof(struct MachO::dylib_module_64);
8043 modtabend += dyst.modtaboff;
8044 } else {
8045 modtabend = dyst.nmodtab;
8046 modtabend *= sizeof(struct MachO::dylib_module);
8047 modtabend += dyst.modtaboff;
8048 }
8049 if (modtabend > object_size)
8050 outs() << " (past end of file)\n";
8051 else
8052 outs() << "\n";
8053 outs() << " extrefsymoff " << dyst.extrefsymoff;
8054 if (dyst.extrefsymoff > object_size)
8055 outs() << " (past end of file)\n";
8056 else
8057 outs() << "\n";
8058 outs() << " nextrefsyms " << dyst.nextrefsyms;
8059 big_size = dyst.nextrefsyms;
8060 big_size *= sizeof(struct MachO::dylib_reference);
8061 big_size += dyst.extrefsymoff;
8062 if (big_size > object_size)
8063 outs() << " (past end of file)\n";
8064 else
8065 outs() << "\n";
8066 outs() << " indirectsymoff " << dyst.indirectsymoff;
8067 if (dyst.indirectsymoff > object_size)
8068 outs() << " (past end of file)\n";
8069 else
8070 outs() << "\n";
8071 outs() << " nindirectsyms " << dyst.nindirectsyms;
8072 big_size = dyst.nindirectsyms;
8073 big_size *= sizeof(uint32_t);
8074 big_size += dyst.indirectsymoff;
8075 if (big_size > object_size)
8076 outs() << " (past end of file)\n";
8077 else
8078 outs() << "\n";
8079 outs() << " extreloff " << dyst.extreloff;
8080 if (dyst.extreloff > object_size)
8081 outs() << " (past end of file)\n";
8082 else
8083 outs() << "\n";
8084 outs() << " nextrel " << dyst.nextrel;
8085 big_size = dyst.nextrel;
8086 big_size *= sizeof(struct MachO::relocation_info);
8087 big_size += dyst.extreloff;
8088 if (big_size > object_size)
8089 outs() << " (past end of file)\n";
8090 else
8091 outs() << "\n";
8092 outs() << " locreloff " << dyst.locreloff;
8093 if (dyst.locreloff > object_size)
8094 outs() << " (past end of file)\n";
8095 else
8096 outs() << "\n";
8097 outs() << " nlocrel " << dyst.nlocrel;
8098 big_size = dyst.nlocrel;
8099 big_size *= sizeof(struct MachO::relocation_info);
8100 big_size += dyst.locreloff;
8101 if (big_size > object_size)
8102 outs() << " (past end of file)\n";
8103 else
8104 outs() << "\n";
8105}
8106
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008107static void PrintDyldInfoLoadCommand(MachO::dyld_info_command dc,
8108 uint32_t object_size) {
8109 if (dc.cmd == MachO::LC_DYLD_INFO)
8110 outs() << " cmd LC_DYLD_INFO\n";
8111 else
8112 outs() << " cmd LC_DYLD_INFO_ONLY\n";
8113 outs() << " cmdsize " << dc.cmdsize;
8114 if (dc.cmdsize != sizeof(struct MachO::dyld_info_command))
8115 outs() << " Incorrect size\n";
8116 else
8117 outs() << "\n";
8118 outs() << " rebase_off " << dc.rebase_off;
8119 if (dc.rebase_off > object_size)
8120 outs() << " (past end of file)\n";
8121 else
8122 outs() << "\n";
8123 outs() << " rebase_size " << dc.rebase_size;
8124 uint64_t big_size;
8125 big_size = dc.rebase_off;
8126 big_size += dc.rebase_size;
8127 if (big_size > object_size)
8128 outs() << " (past end of file)\n";
8129 else
8130 outs() << "\n";
8131 outs() << " bind_off " << dc.bind_off;
8132 if (dc.bind_off > object_size)
8133 outs() << " (past end of file)\n";
8134 else
8135 outs() << "\n";
8136 outs() << " bind_size " << dc.bind_size;
8137 big_size = dc.bind_off;
8138 big_size += dc.bind_size;
8139 if (big_size > object_size)
8140 outs() << " (past end of file)\n";
8141 else
8142 outs() << "\n";
8143 outs() << " weak_bind_off " << dc.weak_bind_off;
8144 if (dc.weak_bind_off > object_size)
8145 outs() << " (past end of file)\n";
8146 else
8147 outs() << "\n";
8148 outs() << " weak_bind_size " << dc.weak_bind_size;
8149 big_size = dc.weak_bind_off;
8150 big_size += dc.weak_bind_size;
8151 if (big_size > object_size)
8152 outs() << " (past end of file)\n";
8153 else
8154 outs() << "\n";
8155 outs() << " lazy_bind_off " << dc.lazy_bind_off;
8156 if (dc.lazy_bind_off > object_size)
8157 outs() << " (past end of file)\n";
8158 else
8159 outs() << "\n";
8160 outs() << " lazy_bind_size " << dc.lazy_bind_size;
8161 big_size = dc.lazy_bind_off;
8162 big_size += dc.lazy_bind_size;
8163 if (big_size > object_size)
8164 outs() << " (past end of file)\n";
8165 else
8166 outs() << "\n";
8167 outs() << " export_off " << dc.export_off;
8168 if (dc.export_off > object_size)
8169 outs() << " (past end of file)\n";
8170 else
8171 outs() << "\n";
8172 outs() << " export_size " << dc.export_size;
8173 big_size = dc.export_off;
8174 big_size += dc.export_size;
8175 if (big_size > object_size)
8176 outs() << " (past end of file)\n";
8177 else
8178 outs() << "\n";
8179}
8180
8181static void PrintDyldLoadCommand(MachO::dylinker_command dyld,
8182 const char *Ptr) {
8183 if (dyld.cmd == MachO::LC_ID_DYLINKER)
8184 outs() << " cmd LC_ID_DYLINKER\n";
8185 else if (dyld.cmd == MachO::LC_LOAD_DYLINKER)
8186 outs() << " cmd LC_LOAD_DYLINKER\n";
8187 else if (dyld.cmd == MachO::LC_DYLD_ENVIRONMENT)
8188 outs() << " cmd LC_DYLD_ENVIRONMENT\n";
8189 else
8190 outs() << " cmd ?(" << dyld.cmd << ")\n";
8191 outs() << " cmdsize " << dyld.cmdsize;
8192 if (dyld.cmdsize < sizeof(struct MachO::dylinker_command))
8193 outs() << " Incorrect size\n";
8194 else
8195 outs() << "\n";
8196 if (dyld.name >= dyld.cmdsize)
8197 outs() << " name ?(bad offset " << dyld.name << ")\n";
8198 else {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00008199 const char *P = (const char *)(Ptr) + dyld.name;
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008200 outs() << " name " << P << " (offset " << dyld.name << ")\n";
8201 }
8202}
8203
8204static void PrintUuidLoadCommand(MachO::uuid_command uuid) {
8205 outs() << " cmd LC_UUID\n";
8206 outs() << " cmdsize " << uuid.cmdsize;
8207 if (uuid.cmdsize != sizeof(struct MachO::uuid_command))
8208 outs() << " Incorrect size\n";
8209 else
8210 outs() << "\n";
8211 outs() << " uuid ";
Davide Italianoc74277a2015-12-07 00:03:28 +00008212 for (int i = 0; i < 16; ++i) {
8213 outs() << format("%02" PRIX32, uuid.uuid[i]);
8214 if (i == 3 || i == 5 || i == 7 || i == 9)
8215 outs() << "-";
8216 }
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008217 outs() << "\n";
8218}
8219
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008220static void PrintRpathLoadCommand(MachO::rpath_command rpath, const char *Ptr) {
Jean-Daniel Dupas00cc1f52014-12-04 07:37:02 +00008221 outs() << " cmd LC_RPATH\n";
8222 outs() << " cmdsize " << rpath.cmdsize;
8223 if (rpath.cmdsize < sizeof(struct MachO::rpath_command))
8224 outs() << " Incorrect size\n";
8225 else
8226 outs() << "\n";
8227 if (rpath.path >= rpath.cmdsize)
8228 outs() << " path ?(bad offset " << rpath.path << ")\n";
8229 else {
8230 const char *P = (const char *)(Ptr) + rpath.path;
8231 outs() << " path " << P << " (offset " << rpath.path << ")\n";
8232 }
8233}
8234
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008235static void PrintVersionMinLoadCommand(MachO::version_min_command vd) {
Tim Northoverbfbfb122015-11-02 21:26:58 +00008236 StringRef LoadCmdName;
8237 switch (vd.cmd) {
8238 case MachO::LC_VERSION_MIN_MACOSX:
8239 LoadCmdName = "LC_VERSION_MIN_MACOSX";
8240 break;
8241 case MachO::LC_VERSION_MIN_IPHONEOS:
8242 LoadCmdName = "LC_VERSION_MIN_IPHONEOS";
8243 break;
8244 case MachO::LC_VERSION_MIN_TVOS:
8245 LoadCmdName = "LC_VERSION_MIN_TVOS";
8246 break;
8247 case MachO::LC_VERSION_MIN_WATCHOS:
8248 LoadCmdName = "LC_VERSION_MIN_WATCHOS";
8249 break;
8250 default:
8251 llvm_unreachable("Unknown version min load command");
8252 }
8253
8254 outs() << " cmd " << LoadCmdName << '\n';
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008255 outs() << " cmdsize " << vd.cmdsize;
8256 if (vd.cmdsize != sizeof(struct MachO::version_min_command))
8257 outs() << " Incorrect size\n";
8258 else
8259 outs() << "\n";
Davide Italiano56baef32015-08-26 12:26:11 +00008260 outs() << " version "
8261 << MachOObjectFile::getVersionMinMajor(vd, false) << "."
8262 << MachOObjectFile::getVersionMinMinor(vd, false);
8263 uint32_t Update = MachOObjectFile::getVersionMinUpdate(vd, false);
8264 if (Update != 0)
8265 outs() << "." << Update;
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008266 outs() << "\n";
8267 if (vd.sdk == 0)
Kevin Enderby57538292014-12-17 01:01:30 +00008268 outs() << " sdk n/a";
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008269 else {
Davide Italiano56baef32015-08-26 12:26:11 +00008270 outs() << " sdk "
8271 << MachOObjectFile::getVersionMinMajor(vd, true) << "."
8272 << MachOObjectFile::getVersionMinMinor(vd, true);
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008273 }
Davide Italiano56baef32015-08-26 12:26:11 +00008274 Update = MachOObjectFile::getVersionMinUpdate(vd, true);
8275 if (Update != 0)
8276 outs() << "." << Update;
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008277 outs() << "\n";
8278}
8279
8280static void PrintSourceVersionCommand(MachO::source_version_command sd) {
8281 outs() << " cmd LC_SOURCE_VERSION\n";
8282 outs() << " cmdsize " << sd.cmdsize;
8283 if (sd.cmdsize != sizeof(struct MachO::source_version_command))
8284 outs() << " Incorrect size\n";
8285 else
8286 outs() << "\n";
8287 uint64_t a = (sd.version >> 40) & 0xffffff;
8288 uint64_t b = (sd.version >> 30) & 0x3ff;
8289 uint64_t c = (sd.version >> 20) & 0x3ff;
8290 uint64_t d = (sd.version >> 10) & 0x3ff;
8291 uint64_t e = sd.version & 0x3ff;
8292 outs() << " version " << a << "." << b;
8293 if (e != 0)
8294 outs() << "." << c << "." << d << "." << e;
8295 else if (d != 0)
8296 outs() << "." << c << "." << d;
8297 else if (c != 0)
8298 outs() << "." << c;
8299 outs() << "\n";
8300}
8301
8302static void PrintEntryPointCommand(MachO::entry_point_command ep) {
8303 outs() << " cmd LC_MAIN\n";
8304 outs() << " cmdsize " << ep.cmdsize;
8305 if (ep.cmdsize != sizeof(struct MachO::entry_point_command))
8306 outs() << " Incorrect size\n";
8307 else
8308 outs() << "\n";
8309 outs() << " entryoff " << ep.entryoff << "\n";
8310 outs() << " stacksize " << ep.stacksize << "\n";
8311}
8312
Kevin Enderby0804f4672014-12-16 23:25:52 +00008313static void PrintEncryptionInfoCommand(MachO::encryption_info_command ec,
8314 uint32_t object_size) {
8315 outs() << " cmd LC_ENCRYPTION_INFO\n";
8316 outs() << " cmdsize " << ec.cmdsize;
8317 if (ec.cmdsize != sizeof(struct MachO::encryption_info_command))
8318 outs() << " Incorrect size\n";
8319 else
8320 outs() << "\n";
8321 outs() << " cryptoff " << ec.cryptoff;
8322 if (ec.cryptoff > object_size)
8323 outs() << " (past end of file)\n";
8324 else
8325 outs() << "\n";
8326 outs() << " cryptsize " << ec.cryptsize;
8327 if (ec.cryptsize > object_size)
8328 outs() << " (past end of file)\n";
8329 else
8330 outs() << "\n";
8331 outs() << " cryptid " << ec.cryptid << "\n";
8332}
8333
Kevin Enderby57538292014-12-17 01:01:30 +00008334static void PrintEncryptionInfoCommand64(MachO::encryption_info_command_64 ec,
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008335 uint32_t object_size) {
Kevin Enderby57538292014-12-17 01:01:30 +00008336 outs() << " cmd LC_ENCRYPTION_INFO_64\n";
8337 outs() << " cmdsize " << ec.cmdsize;
8338 if (ec.cmdsize != sizeof(struct MachO::encryption_info_command_64))
8339 outs() << " Incorrect size\n";
8340 else
8341 outs() << "\n";
8342 outs() << " cryptoff " << ec.cryptoff;
8343 if (ec.cryptoff > object_size)
8344 outs() << " (past end of file)\n";
8345 else
8346 outs() << "\n";
8347 outs() << " cryptsize " << ec.cryptsize;
8348 if (ec.cryptsize > object_size)
8349 outs() << " (past end of file)\n";
8350 else
8351 outs() << "\n";
8352 outs() << " cryptid " << ec.cryptid << "\n";
8353 outs() << " pad " << ec.pad << "\n";
8354}
8355
Kevin Enderbyd0b6b7f2014-12-18 00:53:40 +00008356static void PrintLinkerOptionCommand(MachO::linker_option_command lo,
8357 const char *Ptr) {
8358 outs() << " cmd LC_LINKER_OPTION\n";
8359 outs() << " cmdsize " << lo.cmdsize;
8360 if (lo.cmdsize < sizeof(struct MachO::linker_option_command))
8361 outs() << " Incorrect size\n";
8362 else
8363 outs() << "\n";
8364 outs() << " count " << lo.count << "\n";
8365 const char *string = Ptr + sizeof(struct MachO::linker_option_command);
8366 uint32_t left = lo.cmdsize - sizeof(struct MachO::linker_option_command);
8367 uint32_t i = 0;
8368 while (left > 0) {
8369 while (*string == '\0' && left > 0) {
8370 string++;
8371 left--;
8372 }
8373 if (left > 0) {
8374 i++;
8375 outs() << " string #" << i << " " << format("%.*s\n", left, string);
David Majnemerd4449ed2014-12-20 08:24:43 +00008376 uint32_t NullPos = StringRef(string, left).find('\0');
8377 uint32_t len = std::min(NullPos, left) + 1;
Kevin Enderbyd0b6b7f2014-12-18 00:53:40 +00008378 string += len;
8379 left -= len;
8380 }
8381 }
8382 if (lo.count != i)
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008383 outs() << " count " << lo.count << " does not match number of strings "
8384 << i << "\n";
Kevin Enderbyd0b6b7f2014-12-18 00:53:40 +00008385}
8386
Kevin Enderbyb4b79312014-12-18 19:24:35 +00008387static void PrintSubFrameworkCommand(MachO::sub_framework_command sub,
8388 const char *Ptr) {
8389 outs() << " cmd LC_SUB_FRAMEWORK\n";
8390 outs() << " cmdsize " << sub.cmdsize;
8391 if (sub.cmdsize < sizeof(struct MachO::sub_framework_command))
8392 outs() << " Incorrect size\n";
8393 else
8394 outs() << "\n";
8395 if (sub.umbrella < sub.cmdsize) {
8396 const char *P = Ptr + sub.umbrella;
8397 outs() << " umbrella " << P << " (offset " << sub.umbrella << ")\n";
8398 } else {
8399 outs() << " umbrella ?(bad offset " << sub.umbrella << ")\n";
8400 }
8401}
8402
Kevin Enderbya2bd8d92014-12-18 23:13:26 +00008403static void PrintSubUmbrellaCommand(MachO::sub_umbrella_command sub,
8404 const char *Ptr) {
8405 outs() << " cmd LC_SUB_UMBRELLA\n";
8406 outs() << " cmdsize " << sub.cmdsize;
8407 if (sub.cmdsize < sizeof(struct MachO::sub_umbrella_command))
8408 outs() << " Incorrect size\n";
8409 else
8410 outs() << "\n";
8411 if (sub.sub_umbrella < sub.cmdsize) {
8412 const char *P = Ptr + sub.sub_umbrella;
8413 outs() << " sub_umbrella " << P << " (offset " << sub.sub_umbrella << ")\n";
8414 } else {
8415 outs() << " sub_umbrella ?(bad offset " << sub.sub_umbrella << ")\n";
8416 }
8417}
8418
Kevin Enderby36c8d3a2014-12-19 19:48:16 +00008419static void PrintSubLibraryCommand(MachO::sub_library_command sub,
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008420 const char *Ptr) {
Kevin Enderby36c8d3a2014-12-19 19:48:16 +00008421 outs() << " cmd LC_SUB_LIBRARY\n";
8422 outs() << " cmdsize " << sub.cmdsize;
8423 if (sub.cmdsize < sizeof(struct MachO::sub_library_command))
8424 outs() << " Incorrect size\n";
8425 else
8426 outs() << "\n";
8427 if (sub.sub_library < sub.cmdsize) {
8428 const char *P = Ptr + sub.sub_library;
8429 outs() << " sub_library " << P << " (offset " << sub.sub_library << ")\n";
8430 } else {
8431 outs() << " sub_library ?(bad offset " << sub.sub_library << ")\n";
8432 }
8433}
8434
Kevin Enderby186eac32014-12-19 21:06:24 +00008435static void PrintSubClientCommand(MachO::sub_client_command sub,
8436 const char *Ptr) {
8437 outs() << " cmd LC_SUB_CLIENT\n";
8438 outs() << " cmdsize " << sub.cmdsize;
8439 if (sub.cmdsize < sizeof(struct MachO::sub_client_command))
8440 outs() << " Incorrect size\n";
8441 else
8442 outs() << "\n";
8443 if (sub.client < sub.cmdsize) {
8444 const char *P = Ptr + sub.client;
8445 outs() << " client " << P << " (offset " << sub.client << ")\n";
8446 } else {
8447 outs() << " client ?(bad offset " << sub.client << ")\n";
8448 }
8449}
Kevin Enderby36c8d3a2014-12-19 19:48:16 +00008450
Kevin Enderby52e4ce42014-12-19 22:25:22 +00008451static void PrintRoutinesCommand(MachO::routines_command r) {
8452 outs() << " cmd LC_ROUTINES\n";
8453 outs() << " cmdsize " << r.cmdsize;
8454 if (r.cmdsize != sizeof(struct MachO::routines_command))
8455 outs() << " Incorrect size\n";
8456 else
8457 outs() << "\n";
8458 outs() << " init_address " << format("0x%08" PRIx32, r.init_address) << "\n";
8459 outs() << " init_module " << r.init_module << "\n";
8460 outs() << " reserved1 " << r.reserved1 << "\n";
8461 outs() << " reserved2 " << r.reserved2 << "\n";
8462 outs() << " reserved3 " << r.reserved3 << "\n";
8463 outs() << " reserved4 " << r.reserved4 << "\n";
8464 outs() << " reserved5 " << r.reserved5 << "\n";
8465 outs() << " reserved6 " << r.reserved6 << "\n";
8466}
8467
8468static void PrintRoutinesCommand64(MachO::routines_command_64 r) {
8469 outs() << " cmd LC_ROUTINES_64\n";
8470 outs() << " cmdsize " << r.cmdsize;
8471 if (r.cmdsize != sizeof(struct MachO::routines_command_64))
8472 outs() << " Incorrect size\n";
8473 else
8474 outs() << "\n";
8475 outs() << " init_address " << format("0x%016" PRIx64, r.init_address) << "\n";
8476 outs() << " init_module " << r.init_module << "\n";
8477 outs() << " reserved1 " << r.reserved1 << "\n";
8478 outs() << " reserved2 " << r.reserved2 << "\n";
8479 outs() << " reserved3 " << r.reserved3 << "\n";
8480 outs() << " reserved4 " << r.reserved4 << "\n";
8481 outs() << " reserved5 " << r.reserved5 << "\n";
8482 outs() << " reserved6 " << r.reserved6 << "\n";
8483}
8484
Kevin Enderby48ef5342014-12-23 22:56:39 +00008485static void Print_x86_thread_state64_t(MachO::x86_thread_state64_t &cpu64) {
8486 outs() << " rax " << format("0x%016" PRIx64, cpu64.rax);
8487 outs() << " rbx " << format("0x%016" PRIx64, cpu64.rbx);
8488 outs() << " rcx " << format("0x%016" PRIx64, cpu64.rcx) << "\n";
8489 outs() << " rdx " << format("0x%016" PRIx64, cpu64.rdx);
8490 outs() << " rdi " << format("0x%016" PRIx64, cpu64.rdi);
8491 outs() << " rsi " << format("0x%016" PRIx64, cpu64.rsi) << "\n";
8492 outs() << " rbp " << format("0x%016" PRIx64, cpu64.rbp);
8493 outs() << " rsp " << format("0x%016" PRIx64, cpu64.rsp);
8494 outs() << " r8 " << format("0x%016" PRIx64, cpu64.r8) << "\n";
8495 outs() << " r9 " << format("0x%016" PRIx64, cpu64.r9);
8496 outs() << " r10 " << format("0x%016" PRIx64, cpu64.r10);
8497 outs() << " r11 " << format("0x%016" PRIx64, cpu64.r11) << "\n";
8498 outs() << " r12 " << format("0x%016" PRIx64, cpu64.r12);
8499 outs() << " r13 " << format("0x%016" PRIx64, cpu64.r13);
8500 outs() << " r14 " << format("0x%016" PRIx64, cpu64.r14) << "\n";
8501 outs() << " r15 " << format("0x%016" PRIx64, cpu64.r15);
8502 outs() << " rip " << format("0x%016" PRIx64, cpu64.rip) << "\n";
8503 outs() << "rflags " << format("0x%016" PRIx64, cpu64.rflags);
8504 outs() << " cs " << format("0x%016" PRIx64, cpu64.cs);
8505 outs() << " fs " << format("0x%016" PRIx64, cpu64.fs) << "\n";
8506 outs() << " gs " << format("0x%016" PRIx64, cpu64.gs) << "\n";
8507}
8508
Kevin Enderby227df342014-12-23 23:43:59 +00008509static void Print_mmst_reg(MachO::mmst_reg_t &r) {
Kevin Enderby48ef5342014-12-23 22:56:39 +00008510 uint32_t f;
8511 outs() << "\t mmst_reg ";
8512 for (f = 0; f < 10; f++)
8513 outs() << format("%02" PRIx32, (r.mmst_reg[f] & 0xff)) << " ";
8514 outs() << "\n";
8515 outs() << "\t mmst_rsrv ";
8516 for (f = 0; f < 6; f++)
8517 outs() << format("%02" PRIx32, (r.mmst_rsrv[f] & 0xff)) << " ";
8518 outs() << "\n";
8519}
8520
Kevin Enderbyaefb0032014-12-24 00:16:51 +00008521static void Print_xmm_reg(MachO::xmm_reg_t &r) {
Kevin Enderby48ef5342014-12-23 22:56:39 +00008522 uint32_t f;
8523 outs() << "\t xmm_reg ";
8524 for (f = 0; f < 16; f++)
8525 outs() << format("%02" PRIx32, (r.xmm_reg[f] & 0xff)) << " ";
8526 outs() << "\n";
8527}
8528
8529static void Print_x86_float_state_t(MachO::x86_float_state64_t &fpu) {
8530 outs() << "\t fpu_reserved[0] " << fpu.fpu_reserved[0];
8531 outs() << " fpu_reserved[1] " << fpu.fpu_reserved[1] << "\n";
8532 outs() << "\t control: invalid " << fpu.fpu_fcw.invalid;
8533 outs() << " denorm " << fpu.fpu_fcw.denorm;
8534 outs() << " zdiv " << fpu.fpu_fcw.zdiv;
8535 outs() << " ovrfl " << fpu.fpu_fcw.ovrfl;
8536 outs() << " undfl " << fpu.fpu_fcw.undfl;
8537 outs() << " precis " << fpu.fpu_fcw.precis << "\n";
8538 outs() << "\t\t pc ";
8539 if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_24B)
8540 outs() << "FP_PREC_24B ";
8541 else if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_53B)
8542 outs() << "FP_PREC_53B ";
8543 else if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_64B)
8544 outs() << "FP_PREC_64B ";
8545 else
8546 outs() << fpu.fpu_fcw.pc << " ";
8547 outs() << "rc ";
8548 if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_NEAR)
8549 outs() << "FP_RND_NEAR ";
8550 else if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_DOWN)
8551 outs() << "FP_RND_DOWN ";
8552 else if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_UP)
8553 outs() << "FP_RND_UP ";
8554 else if (fpu.fpu_fcw.rc == MachO::x86_FP_CHOP)
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008555 outs() << "FP_CHOP ";
Kevin Enderby48ef5342014-12-23 22:56:39 +00008556 outs() << "\n";
8557 outs() << "\t status: invalid " << fpu.fpu_fsw.invalid;
8558 outs() << " denorm " << fpu.fpu_fsw.denorm;
8559 outs() << " zdiv " << fpu.fpu_fsw.zdiv;
8560 outs() << " ovrfl " << fpu.fpu_fsw.ovrfl;
8561 outs() << " undfl " << fpu.fpu_fsw.undfl;
8562 outs() << " precis " << fpu.fpu_fsw.precis;
8563 outs() << " stkflt " << fpu.fpu_fsw.stkflt << "\n";
8564 outs() << "\t errsumm " << fpu.fpu_fsw.errsumm;
8565 outs() << " c0 " << fpu.fpu_fsw.c0;
8566 outs() << " c1 " << fpu.fpu_fsw.c1;
8567 outs() << " c2 " << fpu.fpu_fsw.c2;
8568 outs() << " tos " << fpu.fpu_fsw.tos;
8569 outs() << " c3 " << fpu.fpu_fsw.c3;
8570 outs() << " busy " << fpu.fpu_fsw.busy << "\n";
8571 outs() << "\t fpu_ftw " << format("0x%02" PRIx32, fpu.fpu_ftw);
8572 outs() << " fpu_rsrv1 " << format("0x%02" PRIx32, fpu.fpu_rsrv1);
8573 outs() << " fpu_fop " << format("0x%04" PRIx32, fpu.fpu_fop);
8574 outs() << " fpu_ip " << format("0x%08" PRIx32, fpu.fpu_ip) << "\n";
8575 outs() << "\t fpu_cs " << format("0x%04" PRIx32, fpu.fpu_cs);
8576 outs() << " fpu_rsrv2 " << format("0x%04" PRIx32, fpu.fpu_rsrv2);
8577 outs() << " fpu_dp " << format("0x%08" PRIx32, fpu.fpu_dp);
8578 outs() << " fpu_ds " << format("0x%04" PRIx32, fpu.fpu_ds) << "\n";
8579 outs() << "\t fpu_rsrv3 " << format("0x%04" PRIx32, fpu.fpu_rsrv3);
8580 outs() << " fpu_mxcsr " << format("0x%08" PRIx32, fpu.fpu_mxcsr);
8581 outs() << " fpu_mxcsrmask " << format("0x%08" PRIx32, fpu.fpu_mxcsrmask);
8582 outs() << "\n";
8583 outs() << "\t fpu_stmm0:\n";
8584 Print_mmst_reg(fpu.fpu_stmm0);
8585 outs() << "\t fpu_stmm1:\n";
8586 Print_mmst_reg(fpu.fpu_stmm1);
8587 outs() << "\t fpu_stmm2:\n";
8588 Print_mmst_reg(fpu.fpu_stmm2);
8589 outs() << "\t fpu_stmm3:\n";
8590 Print_mmst_reg(fpu.fpu_stmm3);
8591 outs() << "\t fpu_stmm4:\n";
8592 Print_mmst_reg(fpu.fpu_stmm4);
8593 outs() << "\t fpu_stmm5:\n";
8594 Print_mmst_reg(fpu.fpu_stmm5);
8595 outs() << "\t fpu_stmm6:\n";
8596 Print_mmst_reg(fpu.fpu_stmm6);
8597 outs() << "\t fpu_stmm7:\n";
8598 Print_mmst_reg(fpu.fpu_stmm7);
8599 outs() << "\t fpu_xmm0:\n";
8600 Print_xmm_reg(fpu.fpu_xmm0);
8601 outs() << "\t fpu_xmm1:\n";
8602 Print_xmm_reg(fpu.fpu_xmm1);
8603 outs() << "\t fpu_xmm2:\n";
8604 Print_xmm_reg(fpu.fpu_xmm2);
8605 outs() << "\t fpu_xmm3:\n";
8606 Print_xmm_reg(fpu.fpu_xmm3);
8607 outs() << "\t fpu_xmm4:\n";
8608 Print_xmm_reg(fpu.fpu_xmm4);
8609 outs() << "\t fpu_xmm5:\n";
8610 Print_xmm_reg(fpu.fpu_xmm5);
8611 outs() << "\t fpu_xmm6:\n";
8612 Print_xmm_reg(fpu.fpu_xmm6);
8613 outs() << "\t fpu_xmm7:\n";
8614 Print_xmm_reg(fpu.fpu_xmm7);
8615 outs() << "\t fpu_xmm8:\n";
8616 Print_xmm_reg(fpu.fpu_xmm8);
8617 outs() << "\t fpu_xmm9:\n";
8618 Print_xmm_reg(fpu.fpu_xmm9);
8619 outs() << "\t fpu_xmm10:\n";
8620 Print_xmm_reg(fpu.fpu_xmm10);
8621 outs() << "\t fpu_xmm11:\n";
8622 Print_xmm_reg(fpu.fpu_xmm11);
8623 outs() << "\t fpu_xmm12:\n";
8624 Print_xmm_reg(fpu.fpu_xmm12);
8625 outs() << "\t fpu_xmm13:\n";
8626 Print_xmm_reg(fpu.fpu_xmm13);
8627 outs() << "\t fpu_xmm14:\n";
8628 Print_xmm_reg(fpu.fpu_xmm14);
8629 outs() << "\t fpu_xmm15:\n";
8630 Print_xmm_reg(fpu.fpu_xmm15);
8631 outs() << "\t fpu_rsrv4:\n";
8632 for (uint32_t f = 0; f < 6; f++) {
8633 outs() << "\t ";
8634 for (uint32_t g = 0; g < 16; g++)
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008635 outs() << format("%02" PRIx32, fpu.fpu_rsrv4[f * g]) << " ";
Kevin Enderby48ef5342014-12-23 22:56:39 +00008636 outs() << "\n";
8637 }
8638 outs() << "\t fpu_reserved1 " << format("0x%08" PRIx32, fpu.fpu_reserved1);
8639 outs() << "\n";
8640}
8641
8642static void Print_x86_exception_state_t(MachO::x86_exception_state64_t &exc64) {
8643 outs() << "\t trapno " << format("0x%08" PRIx32, exc64.trapno);
8644 outs() << " err " << format("0x%08" PRIx32, exc64.err);
8645 outs() << " faultvaddr " << format("0x%016" PRIx64, exc64.faultvaddr) << "\n";
8646}
8647
8648static void PrintThreadCommand(MachO::thread_command t, const char *Ptr,
8649 bool isLittleEndian, uint32_t cputype) {
8650 if (t.cmd == MachO::LC_THREAD)
8651 outs() << " cmd LC_THREAD\n";
8652 else if (t.cmd == MachO::LC_UNIXTHREAD)
8653 outs() << " cmd LC_UNIXTHREAD\n";
8654 else
8655 outs() << " cmd " << t.cmd << " (unknown)\n";
8656 outs() << " cmdsize " << t.cmdsize;
8657 if (t.cmdsize < sizeof(struct MachO::thread_command) + 2 * sizeof(uint32_t))
8658 outs() << " Incorrect size\n";
8659 else
8660 outs() << "\n";
8661
8662 const char *begin = Ptr + sizeof(struct MachO::thread_command);
8663 const char *end = Ptr + t.cmdsize;
8664 uint32_t flavor, count, left;
8665 if (cputype == MachO::CPU_TYPE_X86_64) {
8666 while (begin < end) {
8667 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
8668 memcpy((char *)&flavor, begin, sizeof(uint32_t));
8669 begin += sizeof(uint32_t);
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008670 } else {
Kevin Enderby48ef5342014-12-23 22:56:39 +00008671 flavor = 0;
8672 begin = end;
8673 }
8674 if (isLittleEndian != sys::IsLittleEndianHost)
8675 sys::swapByteOrder(flavor);
8676 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
8677 memcpy((char *)&count, begin, sizeof(uint32_t));
8678 begin += sizeof(uint32_t);
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008679 } else {
Kevin Enderby48ef5342014-12-23 22:56:39 +00008680 count = 0;
8681 begin = end;
8682 }
8683 if (isLittleEndian != sys::IsLittleEndianHost)
8684 sys::swapByteOrder(count);
8685 if (flavor == MachO::x86_THREAD_STATE64) {
8686 outs() << " flavor x86_THREAD_STATE64\n";
8687 if (count == MachO::x86_THREAD_STATE64_COUNT)
8688 outs() << " count x86_THREAD_STATE64_COUNT\n";
8689 else
8690 outs() << " count " << count
8691 << " (not x86_THREAD_STATE64_COUNT)\n";
8692 MachO::x86_thread_state64_t cpu64;
8693 left = end - begin;
8694 if (left >= sizeof(MachO::x86_thread_state64_t)) {
8695 memcpy(&cpu64, begin, sizeof(MachO::x86_thread_state64_t));
8696 begin += sizeof(MachO::x86_thread_state64_t);
8697 } else {
8698 memset(&cpu64, '\0', sizeof(MachO::x86_thread_state64_t));
8699 memcpy(&cpu64, begin, left);
8700 begin += left;
8701 }
8702 if (isLittleEndian != sys::IsLittleEndianHost)
8703 swapStruct(cpu64);
8704 Print_x86_thread_state64_t(cpu64);
8705 } else if (flavor == MachO::x86_THREAD_STATE) {
8706 outs() << " flavor x86_THREAD_STATE\n";
8707 if (count == MachO::x86_THREAD_STATE_COUNT)
8708 outs() << " count x86_THREAD_STATE_COUNT\n";
8709 else
8710 outs() << " count " << count
8711 << " (not x86_THREAD_STATE_COUNT)\n";
8712 struct MachO::x86_thread_state_t ts;
8713 left = end - begin;
8714 if (left >= sizeof(MachO::x86_thread_state_t)) {
8715 memcpy(&ts, begin, sizeof(MachO::x86_thread_state_t));
8716 begin += sizeof(MachO::x86_thread_state_t);
8717 } else {
8718 memset(&ts, '\0', sizeof(MachO::x86_thread_state_t));
8719 memcpy(&ts, begin, left);
8720 begin += left;
8721 }
8722 if (isLittleEndian != sys::IsLittleEndianHost)
8723 swapStruct(ts);
8724 if (ts.tsh.flavor == MachO::x86_THREAD_STATE64) {
8725 outs() << "\t tsh.flavor x86_THREAD_STATE64 ";
8726 if (ts.tsh.count == MachO::x86_THREAD_STATE64_COUNT)
8727 outs() << "tsh.count x86_THREAD_STATE64_COUNT\n";
8728 else
8729 outs() << "tsh.count " << ts.tsh.count
8730 << " (not x86_THREAD_STATE64_COUNT\n";
8731 Print_x86_thread_state64_t(ts.uts.ts64);
8732 } else {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008733 outs() << "\t tsh.flavor " << ts.tsh.flavor << " tsh.count "
8734 << ts.tsh.count << "\n";
Kevin Enderby48ef5342014-12-23 22:56:39 +00008735 }
8736 } else if (flavor == MachO::x86_FLOAT_STATE) {
8737 outs() << " flavor x86_FLOAT_STATE\n";
8738 if (count == MachO::x86_FLOAT_STATE_COUNT)
8739 outs() << " count x86_FLOAT_STATE_COUNT\n";
8740 else
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008741 outs() << " count " << count << " (not x86_FLOAT_STATE_COUNT)\n";
Kevin Enderby48ef5342014-12-23 22:56:39 +00008742 struct MachO::x86_float_state_t fs;
8743 left = end - begin;
8744 if (left >= sizeof(MachO::x86_float_state_t)) {
8745 memcpy(&fs, begin, sizeof(MachO::x86_float_state_t));
8746 begin += sizeof(MachO::x86_float_state_t);
8747 } else {
8748 memset(&fs, '\0', sizeof(MachO::x86_float_state_t));
8749 memcpy(&fs, begin, left);
8750 begin += left;
8751 }
8752 if (isLittleEndian != sys::IsLittleEndianHost)
8753 swapStruct(fs);
8754 if (fs.fsh.flavor == MachO::x86_FLOAT_STATE64) {
8755 outs() << "\t fsh.flavor x86_FLOAT_STATE64 ";
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008756 if (fs.fsh.count == MachO::x86_FLOAT_STATE64_COUNT)
Kevin Enderby48ef5342014-12-23 22:56:39 +00008757 outs() << "fsh.count x86_FLOAT_STATE64_COUNT\n";
8758 else
8759 outs() << "fsh.count " << fs.fsh.count
8760 << " (not x86_FLOAT_STATE64_COUNT\n";
8761 Print_x86_float_state_t(fs.ufs.fs64);
8762 } else {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008763 outs() << "\t fsh.flavor " << fs.fsh.flavor << " fsh.count "
8764 << fs.fsh.count << "\n";
Kevin Enderby48ef5342014-12-23 22:56:39 +00008765 }
8766 } else if (flavor == MachO::x86_EXCEPTION_STATE) {
8767 outs() << " flavor x86_EXCEPTION_STATE\n";
8768 if (count == MachO::x86_EXCEPTION_STATE_COUNT)
8769 outs() << " count x86_EXCEPTION_STATE_COUNT\n";
8770 else
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008771 outs() << " count " << count
Kevin Enderby48ef5342014-12-23 22:56:39 +00008772 << " (not x86_EXCEPTION_STATE_COUNT)\n";
8773 struct MachO::x86_exception_state_t es;
8774 left = end - begin;
8775 if (left >= sizeof(MachO::x86_exception_state_t)) {
8776 memcpy(&es, begin, sizeof(MachO::x86_exception_state_t));
8777 begin += sizeof(MachO::x86_exception_state_t);
8778 } else {
8779 memset(&es, '\0', sizeof(MachO::x86_exception_state_t));
8780 memcpy(&es, begin, left);
8781 begin += left;
8782 }
8783 if (isLittleEndian != sys::IsLittleEndianHost)
8784 swapStruct(es);
8785 if (es.esh.flavor == MachO::x86_EXCEPTION_STATE64) {
8786 outs() << "\t esh.flavor x86_EXCEPTION_STATE64\n";
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008787 if (es.esh.count == MachO::x86_EXCEPTION_STATE64_COUNT)
Kevin Enderby48ef5342014-12-23 22:56:39 +00008788 outs() << "\t esh.count x86_EXCEPTION_STATE64_COUNT\n";
8789 else
8790 outs() << "\t esh.count " << es.esh.count
8791 << " (not x86_EXCEPTION_STATE64_COUNT\n";
8792 Print_x86_exception_state_t(es.ues.es64);
8793 } else {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008794 outs() << "\t esh.flavor " << es.esh.flavor << " esh.count "
8795 << es.esh.count << "\n";
Kevin Enderby48ef5342014-12-23 22:56:39 +00008796 }
8797 } else {
8798 outs() << " flavor " << flavor << " (unknown)\n";
8799 outs() << " count " << count << "\n";
8800 outs() << " state (unknown)\n";
8801 begin += count * sizeof(uint32_t);
8802 }
8803 }
8804 } else {
8805 while (begin < end) {
8806 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
8807 memcpy((char *)&flavor, begin, sizeof(uint32_t));
8808 begin += sizeof(uint32_t);
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008809 } else {
Kevin Enderby48ef5342014-12-23 22:56:39 +00008810 flavor = 0;
8811 begin = end;
8812 }
8813 if (isLittleEndian != sys::IsLittleEndianHost)
8814 sys::swapByteOrder(flavor);
8815 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
8816 memcpy((char *)&count, begin, sizeof(uint32_t));
8817 begin += sizeof(uint32_t);
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008818 } else {
Kevin Enderby48ef5342014-12-23 22:56:39 +00008819 count = 0;
8820 begin = end;
8821 }
8822 if (isLittleEndian != sys::IsLittleEndianHost)
8823 sys::swapByteOrder(count);
8824 outs() << " flavor " << flavor << "\n";
8825 outs() << " count " << count << "\n";
8826 outs() << " state (Unknown cputype/cpusubtype)\n";
8827 begin += count * sizeof(uint32_t);
8828 }
8829 }
8830}
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008831
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008832static void PrintDylibCommand(MachO::dylib_command dl, const char *Ptr) {
8833 if (dl.cmd == MachO::LC_ID_DYLIB)
8834 outs() << " cmd LC_ID_DYLIB\n";
8835 else if (dl.cmd == MachO::LC_LOAD_DYLIB)
8836 outs() << " cmd LC_LOAD_DYLIB\n";
8837 else if (dl.cmd == MachO::LC_LOAD_WEAK_DYLIB)
8838 outs() << " cmd LC_LOAD_WEAK_DYLIB\n";
8839 else if (dl.cmd == MachO::LC_REEXPORT_DYLIB)
8840 outs() << " cmd LC_REEXPORT_DYLIB\n";
8841 else if (dl.cmd == MachO::LC_LAZY_LOAD_DYLIB)
8842 outs() << " cmd LC_LAZY_LOAD_DYLIB\n";
8843 else if (dl.cmd == MachO::LC_LOAD_UPWARD_DYLIB)
8844 outs() << " cmd LC_LOAD_UPWARD_DYLIB\n";
8845 else
8846 outs() << " cmd " << dl.cmd << " (unknown)\n";
8847 outs() << " cmdsize " << dl.cmdsize;
8848 if (dl.cmdsize < sizeof(struct MachO::dylib_command))
8849 outs() << " Incorrect size\n";
8850 else
8851 outs() << "\n";
8852 if (dl.dylib.name < dl.cmdsize) {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00008853 const char *P = (const char *)(Ptr) + dl.dylib.name;
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008854 outs() << " name " << P << " (offset " << dl.dylib.name << ")\n";
8855 } else {
8856 outs() << " name ?(bad offset " << dl.dylib.name << ")\n";
8857 }
8858 outs() << " time stamp " << dl.dylib.timestamp << " ";
8859 time_t t = dl.dylib.timestamp;
8860 outs() << ctime(&t);
8861 outs() << " current version ";
8862 if (dl.dylib.current_version == 0xffffffff)
8863 outs() << "n/a\n";
8864 else
8865 outs() << ((dl.dylib.current_version >> 16) & 0xffff) << "."
8866 << ((dl.dylib.current_version >> 8) & 0xff) << "."
8867 << (dl.dylib.current_version & 0xff) << "\n";
8868 outs() << "compatibility version ";
8869 if (dl.dylib.compatibility_version == 0xffffffff)
8870 outs() << "n/a\n";
8871 else
8872 outs() << ((dl.dylib.compatibility_version >> 16) & 0xffff) << "."
8873 << ((dl.dylib.compatibility_version >> 8) & 0xff) << "."
8874 << (dl.dylib.compatibility_version & 0xff) << "\n";
8875}
8876
8877static void PrintLinkEditDataCommand(MachO::linkedit_data_command ld,
8878 uint32_t object_size) {
8879 if (ld.cmd == MachO::LC_CODE_SIGNATURE)
Kevin Enderby1be37a32016-04-28 21:07:20 +00008880 outs() << " cmd LC_CODE_SIGNATURE\n";
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008881 else if (ld.cmd == MachO::LC_SEGMENT_SPLIT_INFO)
8882 outs() << " cmd LC_SEGMENT_SPLIT_INFO\n";
8883 else if (ld.cmd == MachO::LC_FUNCTION_STARTS)
8884 outs() << " cmd LC_FUNCTION_STARTS\n";
8885 else if (ld.cmd == MachO::LC_DATA_IN_CODE)
8886 outs() << " cmd LC_DATA_IN_CODE\n";
8887 else if (ld.cmd == MachO::LC_DYLIB_CODE_SIGN_DRS)
8888 outs() << " cmd LC_DYLIB_CODE_SIGN_DRS\n";
8889 else if (ld.cmd == MachO::LC_LINKER_OPTIMIZATION_HINT)
8890 outs() << " cmd LC_LINKER_OPTIMIZATION_HINT\n";
8891 else
8892 outs() << " cmd " << ld.cmd << " (?)\n";
8893 outs() << " cmdsize " << ld.cmdsize;
8894 if (ld.cmdsize != sizeof(struct MachO::linkedit_data_command))
8895 outs() << " Incorrect size\n";
8896 else
8897 outs() << "\n";
8898 outs() << " dataoff " << ld.dataoff;
8899 if (ld.dataoff > object_size)
8900 outs() << " (past end of file)\n";
8901 else
8902 outs() << "\n";
8903 outs() << " datasize " << ld.datasize;
8904 uint64_t big_size = ld.dataoff;
8905 big_size += ld.datasize;
8906 if (big_size > object_size)
8907 outs() << " (past end of file)\n";
8908 else
8909 outs() << "\n";
8910}
8911
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00008912static void PrintLoadCommands(const MachOObjectFile *Obj, uint32_t filetype,
8913 uint32_t cputype, bool verbose) {
Kevin Enderby956366c2014-08-29 22:30:52 +00008914 StringRef Buf = Obj->getData();
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00008915 unsigned Index = 0;
8916 for (const auto &Command : Obj->load_commands()) {
8917 outs() << "Load command " << Index++ << "\n";
Kevin Enderby956366c2014-08-29 22:30:52 +00008918 if (Command.C.cmd == MachO::LC_SEGMENT) {
8919 MachO::segment_command SLC = Obj->getSegmentLoadCommand(Command);
8920 const char *sg_segname = SLC.segname;
8921 PrintSegmentCommand(SLC.cmd, SLC.cmdsize, SLC.segname, SLC.vmaddr,
8922 SLC.vmsize, SLC.fileoff, SLC.filesize, SLC.maxprot,
8923 SLC.initprot, SLC.nsects, SLC.flags, Buf.size(),
8924 verbose);
8925 for (unsigned j = 0; j < SLC.nsects; j++) {
Kevin Enderbyc9713382014-12-16 01:14:45 +00008926 MachO::section S = Obj->getSection(Command, j);
Kevin Enderby956366c2014-08-29 22:30:52 +00008927 PrintSection(S.sectname, S.segname, S.addr, S.size, S.offset, S.align,
8928 S.reloff, S.nreloc, S.flags, S.reserved1, S.reserved2,
8929 SLC.cmd, sg_segname, filetype, Buf.size(), verbose);
8930 }
8931 } else if (Command.C.cmd == MachO::LC_SEGMENT_64) {
8932 MachO::segment_command_64 SLC_64 = Obj->getSegment64LoadCommand(Command);
8933 const char *sg_segname = SLC_64.segname;
8934 PrintSegmentCommand(SLC_64.cmd, SLC_64.cmdsize, SLC_64.segname,
8935 SLC_64.vmaddr, SLC_64.vmsize, SLC_64.fileoff,
8936 SLC_64.filesize, SLC_64.maxprot, SLC_64.initprot,
8937 SLC_64.nsects, SLC_64.flags, Buf.size(), verbose);
8938 for (unsigned j = 0; j < SLC_64.nsects; j++) {
8939 MachO::section_64 S_64 = Obj->getSection64(Command, j);
8940 PrintSection(S_64.sectname, S_64.segname, S_64.addr, S_64.size,
8941 S_64.offset, S_64.align, S_64.reloff, S_64.nreloc,
8942 S_64.flags, S_64.reserved1, S_64.reserved2, SLC_64.cmd,
8943 sg_segname, filetype, Buf.size(), verbose);
8944 }
8945 } else if (Command.C.cmd == MachO::LC_SYMTAB) {
8946 MachO::symtab_command Symtab = Obj->getSymtabLoadCommand();
David Majnemer73cc6ff2014-11-13 19:48:56 +00008947 PrintSymtabLoadCommand(Symtab, Obj->is64Bit(), Buf.size());
Kevin Enderby956366c2014-08-29 22:30:52 +00008948 } else if (Command.C.cmd == MachO::LC_DYSYMTAB) {
8949 MachO::dysymtab_command Dysymtab = Obj->getDysymtabLoadCommand();
8950 MachO::symtab_command Symtab = Obj->getSymtabLoadCommand();
David Majnemer73cc6ff2014-11-13 19:48:56 +00008951 PrintDysymtabLoadCommand(Dysymtab, Symtab.nsyms, Buf.size(),
8952 Obj->is64Bit());
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008953 } else if (Command.C.cmd == MachO::LC_DYLD_INFO ||
8954 Command.C.cmd == MachO::LC_DYLD_INFO_ONLY) {
8955 MachO::dyld_info_command DyldInfo = Obj->getDyldInfoLoadCommand(Command);
8956 PrintDyldInfoLoadCommand(DyldInfo, Buf.size());
8957 } else if (Command.C.cmd == MachO::LC_LOAD_DYLINKER ||
8958 Command.C.cmd == MachO::LC_ID_DYLINKER ||
8959 Command.C.cmd == MachO::LC_DYLD_ENVIRONMENT) {
8960 MachO::dylinker_command Dyld = Obj->getDylinkerCommand(Command);
8961 PrintDyldLoadCommand(Dyld, Command.Ptr);
8962 } else if (Command.C.cmd == MachO::LC_UUID) {
8963 MachO::uuid_command Uuid = Obj->getUuidCommand(Command);
8964 PrintUuidLoadCommand(Uuid);
Jean-Daniel Dupas00cc1f52014-12-04 07:37:02 +00008965 } else if (Command.C.cmd == MachO::LC_RPATH) {
8966 MachO::rpath_command Rpath = Obj->getRpathCommand(Command);
8967 PrintRpathLoadCommand(Rpath, Command.Ptr);
Kevin Enderby1ff0ecc2014-12-16 21:48:27 +00008968 } else if (Command.C.cmd == MachO::LC_VERSION_MIN_MACOSX ||
Tim Northoverbfbfb122015-11-02 21:26:58 +00008969 Command.C.cmd == MachO::LC_VERSION_MIN_IPHONEOS ||
8970 Command.C.cmd == MachO::LC_VERSION_MIN_TVOS ||
8971 Command.C.cmd == MachO::LC_VERSION_MIN_WATCHOS) {
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008972 MachO::version_min_command Vd = Obj->getVersionMinLoadCommand(Command);
8973 PrintVersionMinLoadCommand(Vd);
8974 } else if (Command.C.cmd == MachO::LC_SOURCE_VERSION) {
8975 MachO::source_version_command Sd = Obj->getSourceVersionCommand(Command);
8976 PrintSourceVersionCommand(Sd);
8977 } else if (Command.C.cmd == MachO::LC_MAIN) {
8978 MachO::entry_point_command Ep = Obj->getEntryPointCommand(Command);
8979 PrintEntryPointCommand(Ep);
Kevin Enderby0804f4672014-12-16 23:25:52 +00008980 } else if (Command.C.cmd == MachO::LC_ENCRYPTION_INFO) {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008981 MachO::encryption_info_command Ei =
8982 Obj->getEncryptionInfoCommand(Command);
Kevin Enderby0804f4672014-12-16 23:25:52 +00008983 PrintEncryptionInfoCommand(Ei, Buf.size());
Kevin Enderby57538292014-12-17 01:01:30 +00008984 } else if (Command.C.cmd == MachO::LC_ENCRYPTION_INFO_64) {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008985 MachO::encryption_info_command_64 Ei =
8986 Obj->getEncryptionInfoCommand64(Command);
Kevin Enderby57538292014-12-17 01:01:30 +00008987 PrintEncryptionInfoCommand64(Ei, Buf.size());
Kevin Enderbyd0b6b7f2014-12-18 00:53:40 +00008988 } else if (Command.C.cmd == MachO::LC_LINKER_OPTION) {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008989 MachO::linker_option_command Lo =
8990 Obj->getLinkerOptionLoadCommand(Command);
Kevin Enderbyd0b6b7f2014-12-18 00:53:40 +00008991 PrintLinkerOptionCommand(Lo, Command.Ptr);
Kevin Enderbyb4b79312014-12-18 19:24:35 +00008992 } else if (Command.C.cmd == MachO::LC_SUB_FRAMEWORK) {
8993 MachO::sub_framework_command Sf = Obj->getSubFrameworkCommand(Command);
8994 PrintSubFrameworkCommand(Sf, Command.Ptr);
Kevin Enderbya2bd8d92014-12-18 23:13:26 +00008995 } else if (Command.C.cmd == MachO::LC_SUB_UMBRELLA) {
8996 MachO::sub_umbrella_command Sf = Obj->getSubUmbrellaCommand(Command);
8997 PrintSubUmbrellaCommand(Sf, Command.Ptr);
Kevin Enderby36c8d3a2014-12-19 19:48:16 +00008998 } else if (Command.C.cmd == MachO::LC_SUB_LIBRARY) {
8999 MachO::sub_library_command Sl = Obj->getSubLibraryCommand(Command);
9000 PrintSubLibraryCommand(Sl, Command.Ptr);
Kevin Enderby186eac32014-12-19 21:06:24 +00009001 } else if (Command.C.cmd == MachO::LC_SUB_CLIENT) {
9002 MachO::sub_client_command Sc = Obj->getSubClientCommand(Command);
9003 PrintSubClientCommand(Sc, Command.Ptr);
Kevin Enderby52e4ce42014-12-19 22:25:22 +00009004 } else if (Command.C.cmd == MachO::LC_ROUTINES) {
9005 MachO::routines_command Rc = Obj->getRoutinesCommand(Command);
9006 PrintRoutinesCommand(Rc);
9007 } else if (Command.C.cmd == MachO::LC_ROUTINES_64) {
9008 MachO::routines_command_64 Rc = Obj->getRoutinesCommand64(Command);
9009 PrintRoutinesCommand64(Rc);
Kevin Enderby48ef5342014-12-23 22:56:39 +00009010 } else if (Command.C.cmd == MachO::LC_THREAD ||
9011 Command.C.cmd == MachO::LC_UNIXTHREAD) {
9012 MachO::thread_command Tc = Obj->getThreadCommand(Command);
9013 PrintThreadCommand(Tc, Command.Ptr, Obj->isLittleEndian(), cputype);
Nick Kledzik15558912014-10-16 18:58:20 +00009014 } else if (Command.C.cmd == MachO::LC_LOAD_DYLIB ||
9015 Command.C.cmd == MachO::LC_ID_DYLIB ||
9016 Command.C.cmd == MachO::LC_LOAD_WEAK_DYLIB ||
9017 Command.C.cmd == MachO::LC_REEXPORT_DYLIB ||
9018 Command.C.cmd == MachO::LC_LAZY_LOAD_DYLIB ||
9019 Command.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB) {
Kevin Enderby8ae63c12014-09-04 16:54:47 +00009020 MachO::dylib_command Dl = Obj->getDylibIDLoadCommand(Command);
9021 PrintDylibCommand(Dl, Command.Ptr);
9022 } else if (Command.C.cmd == MachO::LC_CODE_SIGNATURE ||
9023 Command.C.cmd == MachO::LC_SEGMENT_SPLIT_INFO ||
9024 Command.C.cmd == MachO::LC_FUNCTION_STARTS ||
9025 Command.C.cmd == MachO::LC_DATA_IN_CODE ||
9026 Command.C.cmd == MachO::LC_DYLIB_CODE_SIGN_DRS ||
9027 Command.C.cmd == MachO::LC_LINKER_OPTIMIZATION_HINT) {
9028 MachO::linkedit_data_command Ld =
9029 Obj->getLinkeditDataLoadCommand(Command);
9030 PrintLinkEditDataCommand(Ld, Buf.size());
Kevin Enderby956366c2014-08-29 22:30:52 +00009031 } else {
9032 outs() << " cmd ?(" << format("0x%08" PRIx32, Command.C.cmd)
9033 << ")\n";
9034 outs() << " cmdsize " << Command.C.cmdsize << "\n";
9035 // TODO: get and print the raw bytes of the load command.
9036 }
9037 // TODO: print all the other kinds of load commands.
Kevin Enderby956366c2014-08-29 22:30:52 +00009038 }
9039}
9040
Kevin Enderby0ae163f2016-01-13 00:25:36 +00009041static void PrintMachHeader(const MachOObjectFile *Obj, bool verbose) {
Kevin Enderbyb76d3862014-08-22 20:35:18 +00009042 if (Obj->is64Bit()) {
9043 MachO::mach_header_64 H_64;
9044 H_64 = Obj->getHeader64();
9045 PrintMachHeader(H_64.magic, H_64.cputype, H_64.cpusubtype, H_64.filetype,
9046 H_64.ncmds, H_64.sizeofcmds, H_64.flags, verbose);
9047 } else {
9048 MachO::mach_header H;
9049 H = Obj->getHeader();
9050 PrintMachHeader(H.magic, H.cputype, H.cpusubtype, H.filetype, H.ncmds,
9051 H.sizeofcmds, H.flags, verbose);
9052 }
9053}
9054
9055void llvm::printMachOFileHeader(const object::ObjectFile *Obj) {
9056 const MachOObjectFile *file = dyn_cast<const MachOObjectFile>(Obj);
Kevin Enderby0ae163f2016-01-13 00:25:36 +00009057 PrintMachHeader(file, !NonVerbose);
9058}
9059
9060void llvm::printMachOLoadCommands(const object::ObjectFile *Obj) {
9061 const MachOObjectFile *file = dyn_cast<const MachOObjectFile>(Obj);
Kevin Enderby956366c2014-08-29 22:30:52 +00009062 uint32_t filetype = 0;
9063 uint32_t cputype = 0;
Kevin Enderby0ae163f2016-01-13 00:25:36 +00009064 if (file->is64Bit()) {
9065 MachO::mach_header_64 H_64;
9066 H_64 = file->getHeader64();
9067 filetype = H_64.filetype;
9068 cputype = H_64.cputype;
9069 } else {
9070 MachO::mach_header H;
9071 H = file->getHeader();
9072 filetype = H.filetype;
9073 cputype = H.cputype;
9074 }
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00009075 PrintLoadCommands(file, filetype, cputype, !NonVerbose);
Kevin Enderbyb76d3862014-08-22 20:35:18 +00009076}
Nick Kledzikd04bc352014-08-30 00:20:14 +00009077
9078//===----------------------------------------------------------------------===//
9079// export trie dumping
9080//===----------------------------------------------------------------------===//
9081
9082void llvm::printMachOExportsTrie(const object::MachOObjectFile *Obj) {
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00009083 for (const llvm::object::ExportEntry &Entry : Obj->exports()) {
9084 uint64_t Flags = Entry.flags();
Nick Kledzikd04bc352014-08-30 00:20:14 +00009085 bool ReExport = (Flags & MachO::EXPORT_SYMBOL_FLAGS_REEXPORT);
9086 bool WeakDef = (Flags & MachO::EXPORT_SYMBOL_FLAGS_WEAK_DEFINITION);
9087 bool ThreadLocal = ((Flags & MachO::EXPORT_SYMBOL_FLAGS_KIND_MASK) ==
9088 MachO::EXPORT_SYMBOL_FLAGS_KIND_THREAD_LOCAL);
9089 bool Abs = ((Flags & MachO::EXPORT_SYMBOL_FLAGS_KIND_MASK) ==
9090 MachO::EXPORT_SYMBOL_FLAGS_KIND_ABSOLUTE);
9091 bool Resolver = (Flags & MachO::EXPORT_SYMBOL_FLAGS_STUB_AND_RESOLVER);
9092 if (ReExport)
9093 outs() << "[re-export] ";
9094 else
Kevin Enderbyb28ed012014-10-29 21:28:24 +00009095 outs() << format("0x%08llX ",
9096 Entry.address()); // FIXME:add in base address
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00009097 outs() << Entry.name();
Nick Kledzikd04bc352014-08-30 00:20:14 +00009098 if (WeakDef || ThreadLocal || Resolver || Abs) {
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00009099 bool NeedsComma = false;
Nick Kledzik1d1ac4b2014-09-03 01:12:52 +00009100 outs() << " [";
Nick Kledzikd04bc352014-08-30 00:20:14 +00009101 if (WeakDef) {
9102 outs() << "weak_def";
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00009103 NeedsComma = true;
Nick Kledzikd04bc352014-08-30 00:20:14 +00009104 }
9105 if (ThreadLocal) {
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00009106 if (NeedsComma)
Nick Kledzikd04bc352014-08-30 00:20:14 +00009107 outs() << ", ";
9108 outs() << "per-thread";
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00009109 NeedsComma = true;
Nick Kledzikd04bc352014-08-30 00:20:14 +00009110 }
9111 if (Abs) {
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00009112 if (NeedsComma)
Nick Kledzikd04bc352014-08-30 00:20:14 +00009113 outs() << ", ";
9114 outs() << "absolute";
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00009115 NeedsComma = true;
Nick Kledzikd04bc352014-08-30 00:20:14 +00009116 }
9117 if (Resolver) {
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00009118 if (NeedsComma)
Nick Kledzikd04bc352014-08-30 00:20:14 +00009119 outs() << ", ";
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00009120 outs() << format("resolver=0x%08llX", Entry.other());
9121 NeedsComma = true;
Nick Kledzikd04bc352014-08-30 00:20:14 +00009122 }
9123 outs() << "]";
9124 }
9125 if (ReExport) {
9126 StringRef DylibName = "unknown";
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00009127 int Ordinal = Entry.other() - 1;
9128 Obj->getLibraryShortNameByIndex(Ordinal, DylibName);
9129 if (Entry.otherName().empty())
Nick Kledzikd04bc352014-08-30 00:20:14 +00009130 outs() << " (from " << DylibName << ")";
9131 else
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00009132 outs() << " (" << Entry.otherName() << " from " << DylibName << ")";
Nick Kledzikd04bc352014-08-30 00:20:14 +00009133 }
9134 outs() << "\n";
9135 }
9136}
Nick Kledzikac431442014-09-12 21:34:15 +00009137
Nick Kledzikac431442014-09-12 21:34:15 +00009138//===----------------------------------------------------------------------===//
9139// rebase table dumping
9140//===----------------------------------------------------------------------===//
9141
9142namespace {
9143class SegInfo {
9144public:
9145 SegInfo(const object::MachOObjectFile *Obj);
9146
9147 StringRef segmentName(uint32_t SegIndex);
9148 StringRef sectionName(uint32_t SegIndex, uint64_t SegOffset);
9149 uint64_t address(uint32_t SegIndex, uint64_t SegOffset);
Kevin Enderbyaf7c9d02015-10-09 16:48:44 +00009150 bool isValidSegIndexAndOffset(uint32_t SegIndex, uint64_t SegOffset);
Nick Kledzikac431442014-09-12 21:34:15 +00009151
9152private:
9153 struct SectionInfo {
9154 uint64_t Address;
9155 uint64_t Size;
9156 StringRef SectionName;
9157 StringRef SegmentName;
9158 uint64_t OffsetInSegment;
9159 uint64_t SegmentStartAddress;
9160 uint32_t SegmentIndex;
9161 };
9162 const SectionInfo &findSection(uint32_t SegIndex, uint64_t SegOffset);
9163 SmallVector<SectionInfo, 32> Sections;
9164};
9165}
9166
9167SegInfo::SegInfo(const object::MachOObjectFile *Obj) {
9168 // Build table of sections so segIndex/offset pairs can be translated.
Nick Kledzik56ebef42014-09-16 01:41:51 +00009169 uint32_t CurSegIndex = Obj->hasPageZeroSegment() ? 1 : 0;
Nick Kledzikac431442014-09-12 21:34:15 +00009170 StringRef CurSegName;
9171 uint64_t CurSegAddress;
9172 for (const SectionRef &Section : Obj->sections()) {
9173 SectionInfo Info;
Davide Italianoccd53fe2015-08-05 07:18:31 +00009174 error(Section.getName(Info.SectionName));
Rafael Espindola80291272014-10-08 15:28:58 +00009175 Info.Address = Section.getAddress();
9176 Info.Size = Section.getSize();
Nick Kledzikac431442014-09-12 21:34:15 +00009177 Info.SegmentName =
9178 Obj->getSectionFinalSegmentName(Section.getRawDataRefImpl());
9179 if (!Info.SegmentName.equals(CurSegName)) {
9180 ++CurSegIndex;
9181 CurSegName = Info.SegmentName;
9182 CurSegAddress = Info.Address;
9183 }
9184 Info.SegmentIndex = CurSegIndex - 1;
9185 Info.OffsetInSegment = Info.Address - CurSegAddress;
9186 Info.SegmentStartAddress = CurSegAddress;
9187 Sections.push_back(Info);
9188 }
9189}
9190
9191StringRef SegInfo::segmentName(uint32_t SegIndex) {
9192 for (const SectionInfo &SI : Sections) {
9193 if (SI.SegmentIndex == SegIndex)
9194 return SI.SegmentName;
9195 }
9196 llvm_unreachable("invalid segIndex");
9197}
9198
Kevin Enderbyaf7c9d02015-10-09 16:48:44 +00009199bool SegInfo::isValidSegIndexAndOffset(uint32_t SegIndex,
9200 uint64_t OffsetInSeg) {
9201 for (const SectionInfo &SI : Sections) {
9202 if (SI.SegmentIndex != SegIndex)
9203 continue;
9204 if (SI.OffsetInSegment > OffsetInSeg)
9205 continue;
9206 if (OffsetInSeg >= (SI.OffsetInSegment + SI.Size))
9207 continue;
9208 return true;
9209 }
9210 return false;
9211}
9212
Nick Kledzikac431442014-09-12 21:34:15 +00009213const SegInfo::SectionInfo &SegInfo::findSection(uint32_t SegIndex,
9214 uint64_t OffsetInSeg) {
9215 for (const SectionInfo &SI : Sections) {
9216 if (SI.SegmentIndex != SegIndex)
9217 continue;
9218 if (SI.OffsetInSegment > OffsetInSeg)
9219 continue;
9220 if (OffsetInSeg >= (SI.OffsetInSegment + SI.Size))
9221 continue;
9222 return SI;
9223 }
9224 llvm_unreachable("segIndex and offset not in any section");
9225}
9226
9227StringRef SegInfo::sectionName(uint32_t SegIndex, uint64_t OffsetInSeg) {
9228 return findSection(SegIndex, OffsetInSeg).SectionName;
9229}
9230
9231uint64_t SegInfo::address(uint32_t SegIndex, uint64_t OffsetInSeg) {
9232 const SectionInfo &SI = findSection(SegIndex, OffsetInSeg);
9233 return SI.SegmentStartAddress + OffsetInSeg;
9234}
9235
9236void llvm::printMachORebaseTable(const object::MachOObjectFile *Obj) {
9237 // Build table of sections so names can used in final output.
9238 SegInfo sectionTable(Obj);
9239
9240 outs() << "segment section address type\n";
9241 for (const llvm::object::MachORebaseEntry &Entry : Obj->rebaseTable()) {
9242 uint32_t SegIndex = Entry.segmentIndex();
9243 uint64_t OffsetInSeg = Entry.segmentOffset();
9244 StringRef SegmentName = sectionTable.segmentName(SegIndex);
9245 StringRef SectionName = sectionTable.sectionName(SegIndex, OffsetInSeg);
9246 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
9247
9248 // Table lines look like: __DATA __nl_symbol_ptr 0x0000F00C pointer
Kevin Enderbyb28ed012014-10-29 21:28:24 +00009249 outs() << format("%-8s %-18s 0x%08" PRIX64 " %s\n",
9250 SegmentName.str().c_str(), SectionName.str().c_str(),
9251 Address, Entry.typeName().str().c_str());
Nick Kledzikac431442014-09-12 21:34:15 +00009252 }
9253}
Nick Kledzik56ebef42014-09-16 01:41:51 +00009254
9255static StringRef ordinalName(const object::MachOObjectFile *Obj, int Ordinal) {
9256 StringRef DylibName;
9257 switch (Ordinal) {
9258 case MachO::BIND_SPECIAL_DYLIB_SELF:
9259 return "this-image";
9260 case MachO::BIND_SPECIAL_DYLIB_MAIN_EXECUTABLE:
9261 return "main-executable";
9262 case MachO::BIND_SPECIAL_DYLIB_FLAT_LOOKUP:
9263 return "flat-namespace";
9264 default:
Nick Kledzikabd29872014-09-16 22:03:13 +00009265 if (Ordinal > 0) {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00009266 std::error_code EC =
9267 Obj->getLibraryShortNameByIndex(Ordinal - 1, DylibName);
Nick Kledzikabd29872014-09-16 22:03:13 +00009268 if (EC)
Nick Kledzik51d2c2b2014-10-14 23:29:38 +00009269 return "<<bad library ordinal>>";
Nick Kledzikabd29872014-09-16 22:03:13 +00009270 return DylibName;
9271 }
Nick Kledzik56ebef42014-09-16 01:41:51 +00009272 }
Nick Kledzikabd29872014-09-16 22:03:13 +00009273 return "<<unknown special ordinal>>";
Nick Kledzik56ebef42014-09-16 01:41:51 +00009274}
9275
9276//===----------------------------------------------------------------------===//
9277// bind table dumping
9278//===----------------------------------------------------------------------===//
9279
9280void llvm::printMachOBindTable(const object::MachOObjectFile *Obj) {
9281 // Build table of sections so names can used in final output.
9282 SegInfo sectionTable(Obj);
9283
Nick Kledzik5ffacc12014-09-30 00:19:58 +00009284 outs() << "segment section address type "
9285 "addend dylib symbol\n";
Nick Kledzik56ebef42014-09-16 01:41:51 +00009286 for (const llvm::object::MachOBindEntry &Entry : Obj->bindTable()) {
9287 uint32_t SegIndex = Entry.segmentIndex();
9288 uint64_t OffsetInSeg = Entry.segmentOffset();
9289 StringRef SegmentName = sectionTable.segmentName(SegIndex);
9290 StringRef SectionName = sectionTable.sectionName(SegIndex, OffsetInSeg);
9291 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
9292
9293 // Table lines look like:
9294 // __DATA __got 0x00012010 pointer 0 libSystem ___stack_chk_guard
Nick Kledzik5ffacc12014-09-30 00:19:58 +00009295 StringRef Attr;
Nick Kledzik56ebef42014-09-16 01:41:51 +00009296 if (Entry.flags() & MachO::BIND_SYMBOL_FLAGS_WEAK_IMPORT)
Nick Kledzik5ffacc12014-09-30 00:19:58 +00009297 Attr = " (weak_import)";
Kevin Enderbyb28ed012014-10-29 21:28:24 +00009298 outs() << left_justify(SegmentName, 8) << " "
Nick Kledzik5ffacc12014-09-30 00:19:58 +00009299 << left_justify(SectionName, 18) << " "
9300 << format_hex(Address, 10, true) << " "
9301 << left_justify(Entry.typeName(), 8) << " "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00009302 << format_decimal(Entry.addend(), 8) << " "
Nick Kledzik5ffacc12014-09-30 00:19:58 +00009303 << left_justify(ordinalName(Obj, Entry.ordinal()), 16) << " "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00009304 << Entry.symbolName() << Attr << "\n";
Nick Kledzik56ebef42014-09-16 01:41:51 +00009305 }
9306}
9307
9308//===----------------------------------------------------------------------===//
9309// lazy bind table dumping
9310//===----------------------------------------------------------------------===//
9311
9312void llvm::printMachOLazyBindTable(const object::MachOObjectFile *Obj) {
9313 // Build table of sections so names can used in final output.
9314 SegInfo sectionTable(Obj);
9315
Nick Kledzik5ffacc12014-09-30 00:19:58 +00009316 outs() << "segment section address "
9317 "dylib symbol\n";
Nick Kledzik56ebef42014-09-16 01:41:51 +00009318 for (const llvm::object::MachOBindEntry &Entry : Obj->lazyBindTable()) {
9319 uint32_t SegIndex = Entry.segmentIndex();
9320 uint64_t OffsetInSeg = Entry.segmentOffset();
9321 StringRef SegmentName = sectionTable.segmentName(SegIndex);
9322 StringRef SectionName = sectionTable.sectionName(SegIndex, OffsetInSeg);
9323 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
9324
9325 // Table lines look like:
9326 // __DATA __got 0x00012010 libSystem ___stack_chk_guard
Kevin Enderbyb28ed012014-10-29 21:28:24 +00009327 outs() << left_justify(SegmentName, 8) << " "
Nick Kledzik5ffacc12014-09-30 00:19:58 +00009328 << left_justify(SectionName, 18) << " "
9329 << format_hex(Address, 10, true) << " "
9330 << left_justify(ordinalName(Obj, Entry.ordinal()), 16) << " "
Nick Kledzik56ebef42014-09-16 01:41:51 +00009331 << Entry.symbolName() << "\n";
9332 }
9333}
9334
Nick Kledzik56ebef42014-09-16 01:41:51 +00009335//===----------------------------------------------------------------------===//
9336// weak bind table dumping
9337//===----------------------------------------------------------------------===//
9338
9339void llvm::printMachOWeakBindTable(const object::MachOObjectFile *Obj) {
9340 // Build table of sections so names can used in final output.
9341 SegInfo sectionTable(Obj);
9342
Nick Kledzik5ffacc12014-09-30 00:19:58 +00009343 outs() << "segment section address "
9344 "type addend symbol\n";
Nick Kledzik56ebef42014-09-16 01:41:51 +00009345 for (const llvm::object::MachOBindEntry &Entry : Obj->weakBindTable()) {
9346 // Strong symbols don't have a location to update.
9347 if (Entry.flags() & MachO::BIND_SYMBOL_FLAGS_NON_WEAK_DEFINITION) {
Nick Kledzik5ffacc12014-09-30 00:19:58 +00009348 outs() << " strong "
Nick Kledzik56ebef42014-09-16 01:41:51 +00009349 << Entry.symbolName() << "\n";
9350 continue;
9351 }
9352 uint32_t SegIndex = Entry.segmentIndex();
9353 uint64_t OffsetInSeg = Entry.segmentOffset();
9354 StringRef SegmentName = sectionTable.segmentName(SegIndex);
9355 StringRef SectionName = sectionTable.sectionName(SegIndex, OffsetInSeg);
9356 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
9357
9358 // Table lines look like:
9359 // __DATA __data 0x00001000 pointer 0 _foo
Kevin Enderbyb28ed012014-10-29 21:28:24 +00009360 outs() << left_justify(SegmentName, 8) << " "
Nick Kledzik5ffacc12014-09-30 00:19:58 +00009361 << left_justify(SectionName, 18) << " "
9362 << format_hex(Address, 10, true) << " "
9363 << left_justify(Entry.typeName(), 8) << " "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00009364 << format_decimal(Entry.addend(), 8) << " " << Entry.symbolName()
9365 << "\n";
Nick Kledzik56ebef42014-09-16 01:41:51 +00009366 }
9367}
9368
Kevin Enderby6f326ce2014-10-23 19:37:31 +00009369// get_dyld_bind_info_symbolname() is used for disassembly and passed an
9370// address, ReferenceValue, in the Mach-O file and looks in the dyld bind
9371// information for that address. If the address is found its binding symbol
9372// name is returned. If not nullptr is returned.
9373static const char *get_dyld_bind_info_symbolname(uint64_t ReferenceValue,
9374 struct DisassembleInfo *info) {
Kevin Enderby078be602014-10-23 19:53:12 +00009375 if (info->bindtable == nullptr) {
9376 info->bindtable = new (BindTable);
Kevin Enderby6f326ce2014-10-23 19:37:31 +00009377 SegInfo sectionTable(info->O);
9378 for (const llvm::object::MachOBindEntry &Entry : info->O->bindTable()) {
9379 uint32_t SegIndex = Entry.segmentIndex();
9380 uint64_t OffsetInSeg = Entry.segmentOffset();
Kevin Enderbyaf7c9d02015-10-09 16:48:44 +00009381 if (!sectionTable.isValidSegIndexAndOffset(SegIndex, OffsetInSeg))
9382 continue;
Kevin Enderby6f326ce2014-10-23 19:37:31 +00009383 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
9384 const char *SymbolName = nullptr;
9385 StringRef name = Entry.symbolName();
9386 if (!name.empty())
9387 SymbolName = name.data();
Kevin Enderby078be602014-10-23 19:53:12 +00009388 info->bindtable->push_back(std::make_pair(Address, SymbolName));
Kevin Enderby6f326ce2014-10-23 19:37:31 +00009389 }
9390 }
Kevin Enderby078be602014-10-23 19:53:12 +00009391 for (bind_table_iterator BI = info->bindtable->begin(),
9392 BE = info->bindtable->end();
Kevin Enderby6f326ce2014-10-23 19:37:31 +00009393 BI != BE; ++BI) {
9394 uint64_t Address = BI->first;
9395 if (ReferenceValue == Address) {
9396 const char *SymbolName = BI->second;
9397 return SymbolName;
9398 }
9399 }
9400 return nullptr;
9401}