blob: 960ef6be4146c4dc3f59047790d07f7ed8ed50ba [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
14#include "llvm-objdump.h"
Kevin Enderby98c9acc2014-09-16 18:00:57 +000015#include "llvm-c/Disassembler.h"
Benjamin Kramer43a772e2011-09-19 17:56:04 +000016#include "llvm/ADT/STLExtras.h"
Ahmed Bougachaaa790682013-05-24 01:07:04 +000017#include "llvm/ADT/StringExtras.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000018#include "llvm/ADT/Triple.h"
Zachary Turner264b5d92017-06-07 03:48:56 +000019#include "llvm/BinaryFormat/MachO.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"
Rafael Espindolab940b662016-09-06 19:16:48 +000023#include "llvm/Demangle/Demangle.h"
Benjamin Kramer43a772e2011-09-19 17:56:04 +000024#include "llvm/MC/MCAsmInfo.h"
Lang Hamesa1bc0f52014-04-15 04:40:56 +000025#include "llvm/MC/MCContext.h"
Benjamin Kramerf57c1972016-01-26 16:44:37 +000026#include "llvm/MC/MCDisassembler/MCDisassembler.h"
Benjamin Kramer43a772e2011-09-19 17:56:04 +000027#include "llvm/MC/MCInst.h"
28#include "llvm/MC/MCInstPrinter.h"
Benjamin Kramer43a772e2011-09-19 17:56:04 +000029#include "llvm/MC/MCInstrDesc.h"
30#include "llvm/MC/MCInstrInfo.h"
Jim Grosbachfd93a592012-03-05 19:33:20 +000031#include "llvm/MC/MCRegisterInfo.h"
Benjamin Kramer43a772e2011-09-19 17:56:04 +000032#include "llvm/MC/MCSubtargetInfo.h"
Zachary Turner264b5d92017-06-07 03:48:56 +000033#include "llvm/Object/MachO.h"
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +000034#include "llvm/Object/MachOUniversal.h"
Rafael Espindola9b709252013-04-13 01:45:40 +000035#include "llvm/Support/Casting.h"
Benjamin Kramer43a772e2011-09-19 17:56:04 +000036#include "llvm/Support/CommandLine.h"
37#include "llvm/Support/Debug.h"
Tim Northover4bd286a2014-08-01 13:07:19 +000038#include "llvm/Support/Endian.h"
Benjamin Kramer43a772e2011-09-19 17:56:04 +000039#include "llvm/Support/Format.h"
Chandler Carruthd9903882015-01-14 11:23:27 +000040#include "llvm/Support/FormattedStream.h"
Benjamin Kramer43a772e2011-09-19 17:56:04 +000041#include "llvm/Support/GraphWriter.h"
Kevin Enderby9a509442015-01-27 21:28:24 +000042#include "llvm/Support/LEB128.h"
Benjamin Kramer43a772e2011-09-19 17:56:04 +000043#include "llvm/Support/MemoryBuffer.h"
44#include "llvm/Support/TargetRegistry.h"
45#include "llvm/Support/TargetSelect.h"
Kevin Enderby9873e2c2016-05-23 21:34:12 +000046#include "llvm/Support/ToolOutputFile.h"
Benjamin Kramer43a772e2011-09-19 17:56:04 +000047#include "llvm/Support/raw_ostream.h"
Benjamin Kramer43a772e2011-09-19 17:56:04 +000048#include <algorithm>
49#include <cstring>
Rafael Espindolaa6e9c3e2014-06-12 17:38:55 +000050#include <system_error>
Kevin Enderby04bf6932014-10-28 23:39:46 +000051
Kevin Enderby9873e2c2016-05-23 21:34:12 +000052#ifdef HAVE_LIBXAR
53extern "C" {
54#include <xar/xar.h>
55}
56#endif
57
Benjamin Kramer43a772e2011-09-19 17:56:04 +000058using namespace llvm;
59using namespace object;
60
61static cl::opt<bool>
Kevin Enderbyb28ed012014-10-29 21:28:24 +000062 UseDbg("g",
63 cl::desc("Print line information from debug info if available"));
Benjamin Kramer699128e2011-09-21 01:13:19 +000064
Kevin Enderbyb28ed012014-10-29 21:28:24 +000065static cl::opt<std::string> DSYMFile("dsym",
66 cl::desc("Use .dSYM file for debug info"));
Benjamin Kramer699128e2011-09-21 01:13:19 +000067
Kevin Enderbyb28ed012014-10-29 21:28:24 +000068static cl::opt<bool> FullLeadingAddr("full-leading-addr",
69 cl::desc("Print full leading address"));
Kevin Enderbybf246f52014-09-24 23:08:22 +000070
Kevin Enderbyf9d60f02016-11-29 21:43:40 +000071static cl::opt<bool> NoLeadingHeaders("no-leading-headers",
72 cl::desc("Print no leading headers"));
73
Kevin Enderby13023a12015-01-15 23:19:11 +000074cl::opt<bool> llvm::UniversalHeaders("universal-headers",
75 cl::desc("Print Mach-O universal headers "
76 "(requires -macho)"));
77
Kevin Enderby131d1772015-01-09 19:22:37 +000078cl::opt<bool>
Kevin Enderby13023a12015-01-15 23:19:11 +000079 llvm::ArchiveHeaders("archive-headers",
80 cl::desc("Print archive headers for Mach-O archives "
81 "(requires -macho)"));
Kevin Enderby131d1772015-01-09 19:22:37 +000082
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +000083cl::opt<bool>
Kevin Enderby8972e482015-04-30 20:30:42 +000084 ArchiveMemberOffsets("archive-member-offsets",
85 cl::desc("Print the offset to each archive member for "
86 "Mach-O archives (requires -macho and "
87 "-archive-headers)"));
88
89cl::opt<bool>
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +000090 llvm::IndirectSymbols("indirect-symbols",
91 cl::desc("Print indirect symbol table for Mach-O "
92 "objects (requires -macho)"));
93
Kevin Enderby69fe98d2015-01-23 18:52:17 +000094cl::opt<bool>
95 llvm::DataInCode("data-in-code",
96 cl::desc("Print the data in code table for Mach-O objects "
97 "(requires -macho)"));
98
Kevin Enderby9a509442015-01-27 21:28:24 +000099cl::opt<bool>
100 llvm::LinkOptHints("link-opt-hints",
101 cl::desc("Print the linker optimization hints for "
102 "Mach-O objects (requires -macho)"));
103
Kevin Enderbycd66be52015-03-11 22:06:32 +0000104cl::opt<bool>
105 llvm::InfoPlist("info-plist",
106 cl::desc("Print the info plist section as strings for "
107 "Mach-O objects (requires -macho)"));
108
Kevin Enderbyf0640752015-03-13 17:56:32 +0000109cl::opt<bool>
Kevin Enderbybc847fa2015-03-16 20:08:09 +0000110 llvm::DylibsUsed("dylibs-used",
111 cl::desc("Print the shared libraries used for linked "
112 "Mach-O files (requires -macho)"));
113
114cl::opt<bool>
115 llvm::DylibId("dylib-id",
116 cl::desc("Print the shared library's id for the dylib Mach-O "
117 "file (requires -macho)"));
118
119cl::opt<bool>
Kevin Enderbyf0640752015-03-13 17:56:32 +0000120 llvm::NonVerbose("non-verbose",
121 cl::desc("Print the info for Mach-O objects in "
122 "non-verbose or numeric form (requires -macho)"));
123
Kevin Enderby0fc11822015-04-01 20:57:01 +0000124cl::opt<bool>
125 llvm::ObjcMetaData("objc-meta-data",
126 cl::desc("Print the Objective-C runtime meta data for "
127 "Mach-O files (requires -macho)"));
128
Kevin Enderby6a221752015-03-17 17:10:57 +0000129cl::opt<std::string> llvm::DisSymName(
130 "dis-symname",
Saleem Abdulrasoolec6a7742016-09-08 23:17:34 +0000131 cl::desc("disassemble just this symbol's instructions (requires -macho)"));
Kevin Enderby6a221752015-03-17 17:10:57 +0000132
Kevin Enderby8e29ec92015-03-17 22:26:11 +0000133static cl::opt<bool> NoSymbolicOperands(
134 "no-symbolic-operands",
135 cl::desc("do not symbolic operands when disassembling (requires -macho)"));
136
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +0000137static cl::list<std::string>
138 ArchFlags("arch", cl::desc("architecture(s) from a Mach-O file to dump"),
139 cl::ZeroOrMore);
Hans Wennborgcc9deb42015-09-29 18:02:48 +0000140
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +0000141bool ArchAll = false;
142
Kevin Enderbyec5ca032014-08-18 20:21:02 +0000143static std::string ThumbTripleName;
144
145static const Target *GetTarget(const MachOObjectFile *MachOObj,
146 const char **McpuDefault,
147 const Target **ThumbTarget) {
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000148 // Figure out the target triple.
Tim Northover9e8eb412016-04-22 23:21:13 +0000149 llvm::Triple TT(TripleName);
Cameron Zwarich88cc16a2012-02-03 06:35:22 +0000150 if (TripleName.empty()) {
Tim Northover9e8eb412016-04-22 23:21:13 +0000151 TT = MachOObj->getArchTriple(McpuDefault);
Cameron Zwarich88cc16a2012-02-03 06:35:22 +0000152 TripleName = TT.str();
Tim Northover9e8eb412016-04-22 23:21:13 +0000153 }
154
155 if (TT.getArch() == Triple::arm) {
156 // We've inferred a 32-bit ARM target from the object file. All MachO CPUs
157 // that support ARM are also capable of Thumb mode.
158 llvm::Triple ThumbTriple = TT;
159 std::string ThumbName = (Twine("thumb") + TT.getArchName().substr(3)).str();
160 ThumbTriple.setArchName(ThumbName);
Kevin Enderbyec5ca032014-08-18 20:21:02 +0000161 ThumbTripleName = ThumbTriple.str();
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000162 }
163
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000164 // Get the target specific parser.
165 std::string Error;
166 const Target *TheTarget = TargetRegistry::lookupTarget(TripleName, Error);
Kevin Enderbyec5ca032014-08-18 20:21:02 +0000167 if (TheTarget && ThumbTripleName.empty())
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000168 return TheTarget;
169
Kevin Enderbyec5ca032014-08-18 20:21:02 +0000170 *ThumbTarget = TargetRegistry::lookupTarget(ThumbTripleName, Error);
171 if (*ThumbTarget)
172 return TheTarget;
173
174 errs() << "llvm-objdump: error: unable to get target for '";
175 if (!TheTarget)
176 errs() << TripleName;
177 else
178 errs() << ThumbTripleName;
179 errs() << "', see --version and --triple.\n";
Craig Toppere6cb63e2014-04-25 04:24:47 +0000180 return nullptr;
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000181}
182
Owen Andersond9243c42011-10-17 21:37:35 +0000183struct SymbolSorter {
184 bool operator()(const SymbolRef &A, const SymbolRef &B) {
Kevin Enderby7bd8d992016-05-02 20:28:12 +0000185 Expected<SymbolRef::Type> ATypeOrErr = A.getType();
Kevin Enderby844c4ac2016-11-15 23:07:41 +0000186 if (!ATypeOrErr)
187 report_error(A.getObject()->getFileName(), ATypeOrErr.takeError());
Kevin Enderby5afbc1c2016-03-23 20:27:00 +0000188 SymbolRef::Type AType = *ATypeOrErr;
Kevin Enderby7bd8d992016-05-02 20:28:12 +0000189 Expected<SymbolRef::Type> BTypeOrErr = B.getType();
Kevin Enderby844c4ac2016-11-15 23:07:41 +0000190 if (!BTypeOrErr)
191 report_error(B.getObject()->getFileName(), BTypeOrErr.takeError());
Kevin Enderby74f58d42016-03-23 21:45:21 +0000192 SymbolRef::Type BType = *BTypeOrErr;
Kevin Enderby5afbc1c2016-03-23 20:27:00 +0000193 uint64_t AAddr = (AType != SymbolRef::ST_Function) ? 0 : A.getValue();
194 uint64_t BAddr = (BType != SymbolRef::ST_Function) ? 0 : B.getValue();
Owen Andersond9243c42011-10-17 21:37:35 +0000195 return AAddr < BAddr;
196 }
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000197};
198
Kevin Enderby273ae012013-06-06 17:20:50 +0000199// Types for the storted data in code table that is built before disassembly
200// and the predicate function to sort them.
201typedef std::pair<uint64_t, DiceRef> DiceTableEntry;
202typedef std::vector<DiceTableEntry> DiceTable;
203typedef DiceTable::iterator dice_table_iterator;
204
Kevin Enderby930fdc72014-11-06 19:00:13 +0000205// This is used to search for a data in code table entry for the PC being
206// disassembled. The j parameter has the PC in j.first. A single data in code
207// table entry can cover many bytes for each of its Kind's. So if the offset,
208// aka the i.first value, of the data in code table entry plus its Length
209// covers the PC being searched for this will return true. If not it will
210// return false.
David Majnemerea9b8ee2014-11-04 08:41:48 +0000211static bool compareDiceTableEntries(const DiceTableEntry &i,
212 const DiceTableEntry &j) {
Kevin Enderby930fdc72014-11-06 19:00:13 +0000213 uint16_t Length;
214 i.second.getLength(Length);
215
216 return j.first >= i.first && j.first < i.first + Length;
Kevin Enderby273ae012013-06-06 17:20:50 +0000217}
218
Colin LeMahieufc32b1b2015-03-18 19:27:31 +0000219static uint64_t DumpDataInCode(const uint8_t *bytes, uint64_t Length,
Kevin Enderby930fdc72014-11-06 19:00:13 +0000220 unsigned short Kind) {
221 uint32_t Value, Size = 1;
Kevin Enderby273ae012013-06-06 17:20:50 +0000222
223 switch (Kind) {
Kevin Enderby930fdc72014-11-06 19:00:13 +0000224 default:
Charles Davis8bdfafd2013-09-01 04:28:48 +0000225 case MachO::DICE_KIND_DATA:
Kevin Enderby930fdc72014-11-06 19:00:13 +0000226 if (Length >= 4) {
227 if (!NoShowRawInsn)
Craig Topper0013be12015-09-21 05:32:41 +0000228 dumpBytes(makeArrayRef(bytes, 4), outs());
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000229 Value = bytes[3] << 24 | bytes[2] << 16 | bytes[1] << 8 | bytes[0];
Kevin Enderby273ae012013-06-06 17:20:50 +0000230 outs() << "\t.long " << Value;
Kevin Enderby930fdc72014-11-06 19:00:13 +0000231 Size = 4;
232 } else if (Length >= 2) {
233 if (!NoShowRawInsn)
Craig Topper0013be12015-09-21 05:32:41 +0000234 dumpBytes(makeArrayRef(bytes, 2), outs());
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000235 Value = bytes[1] << 8 | bytes[0];
Kevin Enderby273ae012013-06-06 17:20:50 +0000236 outs() << "\t.short " << Value;
Kevin Enderby930fdc72014-11-06 19:00:13 +0000237 Size = 2;
238 } else {
239 if (!NoShowRawInsn)
Craig Topper0013be12015-09-21 05:32:41 +0000240 dumpBytes(makeArrayRef(bytes, 2), outs());
Kevin Enderby273ae012013-06-06 17:20:50 +0000241 Value = bytes[0];
242 outs() << "\t.byte " << Value;
Kevin Enderby930fdc72014-11-06 19:00:13 +0000243 Size = 1;
Kevin Enderby273ae012013-06-06 17:20:50 +0000244 }
Kevin Enderby930fdc72014-11-06 19:00:13 +0000245 if (Kind == MachO::DICE_KIND_DATA)
246 outs() << "\t@ KIND_DATA\n";
247 else
248 outs() << "\t@ data in code kind = " << Kind << "\n";
Kevin Enderby273ae012013-06-06 17:20:50 +0000249 break;
Charles Davis8bdfafd2013-09-01 04:28:48 +0000250 case MachO::DICE_KIND_JUMP_TABLE8:
Kevin Enderby930fdc72014-11-06 19:00:13 +0000251 if (!NoShowRawInsn)
Craig Topper0013be12015-09-21 05:32:41 +0000252 dumpBytes(makeArrayRef(bytes, 1), outs());
Kevin Enderby273ae012013-06-06 17:20:50 +0000253 Value = bytes[0];
Kevin Enderby930fdc72014-11-06 19:00:13 +0000254 outs() << "\t.byte " << format("%3u", Value) << "\t@ KIND_JUMP_TABLE8\n";
255 Size = 1;
Kevin Enderby273ae012013-06-06 17:20:50 +0000256 break;
Charles Davis8bdfafd2013-09-01 04:28:48 +0000257 case MachO::DICE_KIND_JUMP_TABLE16:
Kevin Enderby930fdc72014-11-06 19:00:13 +0000258 if (!NoShowRawInsn)
Craig Topper0013be12015-09-21 05:32:41 +0000259 dumpBytes(makeArrayRef(bytes, 2), outs());
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000260 Value = bytes[1] << 8 | bytes[0];
Kevin Enderby930fdc72014-11-06 19:00:13 +0000261 outs() << "\t.short " << format("%5u", Value & 0xffff)
262 << "\t@ KIND_JUMP_TABLE16\n";
263 Size = 2;
Kevin Enderby273ae012013-06-06 17:20:50 +0000264 break;
Charles Davis8bdfafd2013-09-01 04:28:48 +0000265 case MachO::DICE_KIND_JUMP_TABLE32:
Kevin Enderby930fdc72014-11-06 19:00:13 +0000266 case MachO::DICE_KIND_ABS_JUMP_TABLE32:
267 if (!NoShowRawInsn)
Craig Topper0013be12015-09-21 05:32:41 +0000268 dumpBytes(makeArrayRef(bytes, 4), outs());
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000269 Value = bytes[3] << 24 | bytes[2] << 16 | bytes[1] << 8 | bytes[0];
Kevin Enderby930fdc72014-11-06 19:00:13 +0000270 outs() << "\t.long " << Value;
271 if (Kind == MachO::DICE_KIND_JUMP_TABLE32)
272 outs() << "\t@ KIND_JUMP_TABLE32\n";
273 else
274 outs() << "\t@ KIND_ABS_JUMP_TABLE32\n";
275 Size = 4;
Kevin Enderby273ae012013-06-06 17:20:50 +0000276 break;
277 }
Kevin Enderby930fdc72014-11-06 19:00:13 +0000278 return Size;
Kevin Enderby273ae012013-06-06 17:20:50 +0000279}
280
Alexey Samsonovd319c4f2015-06-03 22:19:36 +0000281static void getSectionsAndSymbols(MachOObjectFile *MachOObj,
Alexey Samsonov464d2e42014-03-17 07:28:19 +0000282 std::vector<SectionRef> &Sections,
283 std::vector<SymbolRef> &Symbols,
284 SmallVectorImpl<uint64_t> &FoundFns,
285 uint64_t &BaseSegmentAddress) {
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +0000286 for (const SymbolRef &Symbol : MachOObj->symbols()) {
Kevin Enderby81e8b7d2016-04-20 21:24:34 +0000287 Expected<StringRef> SymName = Symbol.getName();
Kevin Enderby844c4ac2016-11-15 23:07:41 +0000288 if (!SymName)
289 report_error(MachOObj->getFileName(), SymName.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +0000290 if (!SymName->startswith("ltmp"))
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +0000291 Symbols.push_back(Symbol);
292 }
Owen Andersond9243c42011-10-17 21:37:35 +0000293
Alexey Samsonov48803e52014-03-13 14:37:36 +0000294 for (const SectionRef &Section : MachOObj->sections()) {
Owen Andersond9243c42011-10-17 21:37:35 +0000295 StringRef SectName;
Alexey Samsonov48803e52014-03-13 14:37:36 +0000296 Section.getName(SectName);
297 Sections.push_back(Section);
Owen Andersond9243c42011-10-17 21:37:35 +0000298 }
299
Kevin Enderby273ae012013-06-06 17:20:50 +0000300 bool BaseSegmentAddressSet = false;
Alexey Samsonovd319c4f2015-06-03 22:19:36 +0000301 for (const auto &Command : MachOObj->load_commands()) {
Charles Davis8bdfafd2013-09-01 04:28:48 +0000302 if (Command.C.cmd == MachO::LC_FUNCTION_STARTS) {
Benjamin Kramer699128e2011-09-21 01:13:19 +0000303 // We found a function starts segment, parse the addresses for later
304 // consumption.
Charles Davis8bdfafd2013-09-01 04:28:48 +0000305 MachO::linkedit_data_command LLC =
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000306 MachOObj->getLinkeditDataLoadCommand(Command);
Benjamin Kramer699128e2011-09-21 01:13:19 +0000307
Charles Davis8bdfafd2013-09-01 04:28:48 +0000308 MachOObj->ReadULEB128s(LLC.dataoff, FoundFns);
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000309 } else if (Command.C.cmd == MachO::LC_SEGMENT) {
310 MachO::segment_command SLC = MachOObj->getSegmentLoadCommand(Command);
Charles Davis8bdfafd2013-09-01 04:28:48 +0000311 StringRef SegName = SLC.segname;
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000312 if (!BaseSegmentAddressSet && SegName != "__PAGEZERO") {
Kevin Enderby273ae012013-06-06 17:20:50 +0000313 BaseSegmentAddressSet = true;
Charles Davis8bdfafd2013-09-01 04:28:48 +0000314 BaseSegmentAddress = SLC.vmaddr;
Kevin Enderby273ae012013-06-06 17:20:50 +0000315 }
316 }
Benjamin Kramer8a529dc2011-09-21 22:16:43 +0000317 }
Benjamin Kramer699128e2011-09-21 01:13:19 +0000318}
319
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +0000320static void PrintIndirectSymbolTable(MachOObjectFile *O, bool verbose,
321 uint32_t n, uint32_t count,
322 uint32_t stride, uint64_t addr) {
323 MachO::dysymtab_command Dysymtab = O->getDysymtabLoadCommand();
324 uint32_t nindirectsyms = Dysymtab.nindirectsyms;
325 if (n > nindirectsyms)
326 outs() << " (entries start past the end of the indirect symbol "
327 "table) (reserved1 field greater than the table size)";
328 else if (n + count > nindirectsyms)
329 outs() << " (entries extends past the end of the indirect symbol "
330 "table)";
331 outs() << "\n";
332 uint32_t cputype = O->getHeader().cputype;
333 if (cputype & MachO::CPU_ARCH_ABI64)
334 outs() << "address index";
335 else
336 outs() << "address index";
337 if (verbose)
338 outs() << " name\n";
339 else
340 outs() << "\n";
341 for (uint32_t j = 0; j < count && n + j < nindirectsyms; j++) {
342 if (cputype & MachO::CPU_ARCH_ABI64)
343 outs() << format("0x%016" PRIx64, addr + j * stride) << " ";
344 else
Tim Northover43978372016-04-26 18:29:16 +0000345 outs() << format("0x%08" PRIx32, (uint32_t)addr + j * stride) << " ";
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +0000346 MachO::dysymtab_command Dysymtab = O->getDysymtabLoadCommand();
347 uint32_t indirect_symbol = O->getIndirectSymbolTableEntry(Dysymtab, n + j);
348 if (indirect_symbol == MachO::INDIRECT_SYMBOL_LOCAL) {
349 outs() << "LOCAL\n";
350 continue;
351 }
352 if (indirect_symbol ==
353 (MachO::INDIRECT_SYMBOL_LOCAL | MachO::INDIRECT_SYMBOL_ABS)) {
354 outs() << "LOCAL ABSOLUTE\n";
355 continue;
356 }
357 if (indirect_symbol == MachO::INDIRECT_SYMBOL_ABS) {
358 outs() << "ABSOLUTE\n";
359 continue;
360 }
361 outs() << format("%5u ", indirect_symbol);
Kevin Enderbyf0640752015-03-13 17:56:32 +0000362 if (verbose) {
363 MachO::symtab_command Symtab = O->getSymtabLoadCommand();
364 if (indirect_symbol < Symtab.nsyms) {
365 symbol_iterator Sym = O->getSymbolByIndex(indirect_symbol);
366 SymbolRef Symbol = *Sym;
Kevin Enderby81e8b7d2016-04-20 21:24:34 +0000367 Expected<StringRef> SymName = Symbol.getName();
Kevin Enderby844c4ac2016-11-15 23:07:41 +0000368 if (!SymName)
369 report_error(O->getFileName(), SymName.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +0000370 outs() << *SymName;
Kevin Enderbyf0640752015-03-13 17:56:32 +0000371 } else {
372 outs() << "?";
373 }
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +0000374 }
375 outs() << "\n";
376 }
377}
378
379static void PrintIndirectSymbols(MachOObjectFile *O, bool verbose) {
Alexey Samsonovd319c4f2015-06-03 22:19:36 +0000380 for (const auto &Load : O->load_commands()) {
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +0000381 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
382 MachO::segment_command_64 Seg = O->getSegment64LoadCommand(Load);
383 for (unsigned J = 0; J < Seg.nsects; ++J) {
384 MachO::section_64 Sec = O->getSection64(Load, J);
385 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
386 if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
387 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
388 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
389 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
390 section_type == MachO::S_SYMBOL_STUBS) {
391 uint32_t stride;
392 if (section_type == MachO::S_SYMBOL_STUBS)
393 stride = Sec.reserved2;
394 else
395 stride = 8;
396 if (stride == 0) {
397 outs() << "Can't print indirect symbols for (" << Sec.segname << ","
398 << Sec.sectname << ") "
399 << "(size of stubs in reserved2 field is zero)\n";
400 continue;
401 }
402 uint32_t count = Sec.size / stride;
403 outs() << "Indirect symbols for (" << Sec.segname << ","
404 << Sec.sectname << ") " << count << " entries";
405 uint32_t n = Sec.reserved1;
406 PrintIndirectSymbolTable(O, verbose, n, count, stride, Sec.addr);
407 }
408 }
409 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
410 MachO::segment_command Seg = O->getSegmentLoadCommand(Load);
411 for (unsigned J = 0; J < Seg.nsects; ++J) {
412 MachO::section Sec = O->getSection(Load, J);
413 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
414 if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
415 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
416 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
417 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
418 section_type == MachO::S_SYMBOL_STUBS) {
419 uint32_t stride;
420 if (section_type == MachO::S_SYMBOL_STUBS)
421 stride = Sec.reserved2;
422 else
423 stride = 4;
424 if (stride == 0) {
425 outs() << "Can't print indirect symbols for (" << Sec.segname << ","
426 << Sec.sectname << ") "
427 << "(size of stubs in reserved2 field is zero)\n";
428 continue;
429 }
430 uint32_t count = Sec.size / stride;
431 outs() << "Indirect symbols for (" << Sec.segname << ","
432 << Sec.sectname << ") " << count << " entries";
433 uint32_t n = Sec.reserved1;
434 PrintIndirectSymbolTable(O, verbose, n, count, stride, Sec.addr);
435 }
436 }
437 }
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +0000438 }
439}
440
Kevin Enderby69fe98d2015-01-23 18:52:17 +0000441static void PrintDataInCodeTable(MachOObjectFile *O, bool verbose) {
442 MachO::linkedit_data_command DIC = O->getDataInCodeLoadCommand();
443 uint32_t nentries = DIC.datasize / sizeof(struct MachO::data_in_code_entry);
444 outs() << "Data in code table (" << nentries << " entries)\n";
445 outs() << "offset length kind\n";
446 for (dice_iterator DI = O->begin_dices(), DE = O->end_dices(); DI != DE;
447 ++DI) {
448 uint32_t Offset;
449 DI->getOffset(Offset);
450 outs() << format("0x%08" PRIx32, Offset) << " ";
451 uint16_t Length;
452 DI->getLength(Length);
453 outs() << format("%6u", Length) << " ";
454 uint16_t Kind;
455 DI->getKind(Kind);
456 if (verbose) {
457 switch (Kind) {
458 case MachO::DICE_KIND_DATA:
459 outs() << "DATA";
460 break;
461 case MachO::DICE_KIND_JUMP_TABLE8:
462 outs() << "JUMP_TABLE8";
463 break;
464 case MachO::DICE_KIND_JUMP_TABLE16:
465 outs() << "JUMP_TABLE16";
466 break;
467 case MachO::DICE_KIND_JUMP_TABLE32:
468 outs() << "JUMP_TABLE32";
469 break;
470 case MachO::DICE_KIND_ABS_JUMP_TABLE32:
471 outs() << "ABS_JUMP_TABLE32";
472 break;
473 default:
474 outs() << format("0x%04" PRIx32, Kind);
475 break;
476 }
477 } else
478 outs() << format("0x%04" PRIx32, Kind);
479 outs() << "\n";
480 }
481}
482
Kevin Enderby9a509442015-01-27 21:28:24 +0000483static void PrintLinkOptHints(MachOObjectFile *O) {
484 MachO::linkedit_data_command LohLC = O->getLinkOptHintsLoadCommand();
485 const char *loh = O->getData().substr(LohLC.dataoff, 1).data();
486 uint32_t nloh = LohLC.datasize;
487 outs() << "Linker optimiztion hints (" << nloh << " total bytes)\n";
488 for (uint32_t i = 0; i < nloh;) {
489 unsigned n;
490 uint64_t identifier = decodeULEB128((const uint8_t *)(loh + i), &n);
491 i += n;
492 outs() << " identifier " << identifier << " ";
493 if (i >= nloh)
494 return;
495 switch (identifier) {
496 case 1:
497 outs() << "AdrpAdrp\n";
498 break;
499 case 2:
500 outs() << "AdrpLdr\n";
501 break;
502 case 3:
503 outs() << "AdrpAddLdr\n";
504 break;
505 case 4:
506 outs() << "AdrpLdrGotLdr\n";
507 break;
508 case 5:
509 outs() << "AdrpAddStr\n";
510 break;
511 case 6:
512 outs() << "AdrpLdrGotStr\n";
513 break;
514 case 7:
515 outs() << "AdrpAdd\n";
516 break;
517 case 8:
518 outs() << "AdrpLdrGot\n";
519 break;
520 default:
521 outs() << "Unknown identifier value\n";
522 break;
523 }
524 uint64_t narguments = decodeULEB128((const uint8_t *)(loh + i), &n);
525 i += n;
526 outs() << " narguments " << narguments << "\n";
527 if (i >= nloh)
528 return;
529
530 for (uint32_t j = 0; j < narguments; j++) {
531 uint64_t value = decodeULEB128((const uint8_t *)(loh + i), &n);
532 i += n;
533 outs() << "\tvalue " << format("0x%" PRIx64, value) << "\n";
534 if (i >= nloh)
535 return;
536 }
537 }
538}
539
Kevin Enderbybc847fa2015-03-16 20:08:09 +0000540static void PrintDylibs(MachOObjectFile *O, bool JustId) {
Alexey Samsonovd319c4f2015-06-03 22:19:36 +0000541 unsigned Index = 0;
542 for (const auto &Load : O->load_commands()) {
Kevin Enderbybc847fa2015-03-16 20:08:09 +0000543 if ((JustId && Load.C.cmd == MachO::LC_ID_DYLIB) ||
544 (!JustId && (Load.C.cmd == MachO::LC_ID_DYLIB ||
545 Load.C.cmd == MachO::LC_LOAD_DYLIB ||
546 Load.C.cmd == MachO::LC_LOAD_WEAK_DYLIB ||
547 Load.C.cmd == MachO::LC_REEXPORT_DYLIB ||
548 Load.C.cmd == MachO::LC_LAZY_LOAD_DYLIB ||
549 Load.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB))) {
550 MachO::dylib_command dl = O->getDylibIDLoadCommand(Load);
551 if (dl.dylib.name < dl.cmdsize) {
552 const char *p = (const char *)(Load.Ptr) + dl.dylib.name;
553 if (JustId)
554 outs() << p << "\n";
555 else {
556 outs() << "\t" << p;
557 outs() << " (compatibility version "
558 << ((dl.dylib.compatibility_version >> 16) & 0xffff) << "."
559 << ((dl.dylib.compatibility_version >> 8) & 0xff) << "."
560 << (dl.dylib.compatibility_version & 0xff) << ",";
561 outs() << " current version "
562 << ((dl.dylib.current_version >> 16) & 0xffff) << "."
563 << ((dl.dylib.current_version >> 8) & 0xff) << "."
564 << (dl.dylib.current_version & 0xff) << ")\n";
565 }
566 } else {
567 outs() << "\tBad offset (" << dl.dylib.name << ") for name of ";
568 if (Load.C.cmd == MachO::LC_ID_DYLIB)
569 outs() << "LC_ID_DYLIB ";
570 else if (Load.C.cmd == MachO::LC_LOAD_DYLIB)
571 outs() << "LC_LOAD_DYLIB ";
572 else if (Load.C.cmd == MachO::LC_LOAD_WEAK_DYLIB)
573 outs() << "LC_LOAD_WEAK_DYLIB ";
574 else if (Load.C.cmd == MachO::LC_LAZY_LOAD_DYLIB)
575 outs() << "LC_LAZY_LOAD_DYLIB ";
576 else if (Load.C.cmd == MachO::LC_REEXPORT_DYLIB)
577 outs() << "LC_REEXPORT_DYLIB ";
578 else if (Load.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB)
579 outs() << "LC_LOAD_UPWARD_DYLIB ";
580 else
581 outs() << "LC_??? ";
Alexey Samsonovd319c4f2015-06-03 22:19:36 +0000582 outs() << "command " << Index++ << "\n";
Kevin Enderbybc847fa2015-03-16 20:08:09 +0000583 }
584 }
Kevin Enderbybc847fa2015-03-16 20:08:09 +0000585 }
586}
587
Kevin Enderbyf6d25852015-01-31 00:37:11 +0000588typedef DenseMap<uint64_t, StringRef> SymbolAddressMap;
589
590static void CreateSymbolAddressMap(MachOObjectFile *O,
591 SymbolAddressMap *AddrMap) {
592 // Create a map of symbol addresses to symbol names.
593 for (const SymbolRef &Symbol : O->symbols()) {
Kevin Enderby7bd8d992016-05-02 20:28:12 +0000594 Expected<SymbolRef::Type> STOrErr = Symbol.getType();
Kevin Enderby844c4ac2016-11-15 23:07:41 +0000595 if (!STOrErr)
596 report_error(O->getFileName(), STOrErr.takeError());
Kevin Enderby5afbc1c2016-03-23 20:27:00 +0000597 SymbolRef::Type ST = *STOrErr;
Kevin Enderbyf6d25852015-01-31 00:37:11 +0000598 if (ST == SymbolRef::ST_Function || ST == SymbolRef::ST_Data ||
599 ST == SymbolRef::ST_Other) {
Rafael Espindoladea00162015-07-03 17:44:18 +0000600 uint64_t Address = Symbol.getValue();
Kevin Enderby81e8b7d2016-04-20 21:24:34 +0000601 Expected<StringRef> SymNameOrErr = Symbol.getName();
Kevin Enderby844c4ac2016-11-15 23:07:41 +0000602 if (!SymNameOrErr)
603 report_error(O->getFileName(), SymNameOrErr.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +0000604 StringRef SymName = *SymNameOrErr;
Kevin Enderby846c0002015-04-16 17:19:59 +0000605 if (!SymName.startswith(".objc"))
606 (*AddrMap)[Address] = SymName;
Kevin Enderbyf6d25852015-01-31 00:37:11 +0000607 }
608 }
609}
610
611// GuessSymbolName is passed the address of what might be a symbol and a
612// pointer to the SymbolAddressMap. It returns the name of a symbol
613// with that address or nullptr if no symbol is found with that address.
614static const char *GuessSymbolName(uint64_t value, SymbolAddressMap *AddrMap) {
615 const char *SymbolName = nullptr;
616 // A DenseMap can't lookup up some values.
617 if (value != 0xffffffffffffffffULL && value != 0xfffffffffffffffeULL) {
618 StringRef name = AddrMap->lookup(value);
619 if (!name.empty())
620 SymbolName = name.data();
621 }
622 return SymbolName;
623}
624
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000625static void DumpCstringChar(const char c) {
626 char p[2];
627 p[0] = c;
628 p[1] = '\0';
629 outs().write_escaped(p);
630}
631
Kevin Enderby10ba0412015-02-04 21:38:42 +0000632static void DumpCstringSection(MachOObjectFile *O, const char *sect,
633 uint32_t sect_size, uint64_t sect_addr,
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000634 bool print_addresses) {
Kevin Enderby10ba0412015-02-04 21:38:42 +0000635 for (uint32_t i = 0; i < sect_size; i++) {
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000636 if (print_addresses) {
637 if (O->is64Bit())
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000638 outs() << format("%016" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000639 else
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000640 outs() << format("%08" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000641 }
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000642 for (; i < sect_size && sect[i] != '\0'; i++)
643 DumpCstringChar(sect[i]);
Kevin Enderby10ba0412015-02-04 21:38:42 +0000644 if (i < sect_size && sect[i] == '\0')
645 outs() << "\n";
646 }
647}
648
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000649static void DumpLiteral4(uint32_t l, float f) {
650 outs() << format("0x%08" PRIx32, l);
651 if ((l & 0x7f800000) != 0x7f800000)
652 outs() << format(" (%.16e)\n", f);
653 else {
654 if (l == 0x7f800000)
655 outs() << " (+Infinity)\n";
656 else if (l == 0xff800000)
657 outs() << " (-Infinity)\n";
658 else if ((l & 0x00400000) == 0x00400000)
659 outs() << " (non-signaling Not-a-Number)\n";
660 else
661 outs() << " (signaling Not-a-Number)\n";
662 }
663}
664
665static void DumpLiteral4Section(MachOObjectFile *O, const char *sect,
666 uint32_t sect_size, uint64_t sect_addr,
667 bool print_addresses) {
668 for (uint32_t i = 0; i < sect_size; i += sizeof(float)) {
669 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 }
675 float f;
676 memcpy(&f, sect + i, sizeof(float));
677 if (O->isLittleEndian() != sys::IsLittleEndianHost)
678 sys::swapByteOrder(f);
679 uint32_t l;
680 memcpy(&l, sect + i, sizeof(uint32_t));
681 if (O->isLittleEndian() != sys::IsLittleEndianHost)
682 sys::swapByteOrder(l);
683 DumpLiteral4(l, f);
684 }
685}
686
687static void DumpLiteral8(MachOObjectFile *O, uint32_t l0, uint32_t l1,
688 double d) {
689 outs() << format("0x%08" PRIx32, l0) << " " << format("0x%08" PRIx32, l1);
690 uint32_t Hi, Lo;
Davide Italianob627d9f2015-12-12 21:50:11 +0000691 Hi = (O->isLittleEndian()) ? l1 : l0;
692 Lo = (O->isLittleEndian()) ? l0 : l1;
693
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000694 // Hi is the high word, so this is equivalent to if(isfinite(d))
695 if ((Hi & 0x7ff00000) != 0x7ff00000)
696 outs() << format(" (%.16e)\n", d);
697 else {
698 if (Hi == 0x7ff00000 && Lo == 0)
699 outs() << " (+Infinity)\n";
700 else if (Hi == 0xfff00000 && Lo == 0)
701 outs() << " (-Infinity)\n";
702 else if ((Hi & 0x00080000) == 0x00080000)
703 outs() << " (non-signaling Not-a-Number)\n";
704 else
705 outs() << " (signaling Not-a-Number)\n";
706 }
707}
708
709static void DumpLiteral8Section(MachOObjectFile *O, const char *sect,
710 uint32_t sect_size, uint64_t sect_addr,
711 bool print_addresses) {
712 for (uint32_t i = 0; i < sect_size; i += sizeof(double)) {
713 if (print_addresses) {
714 if (O->is64Bit())
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000715 outs() << format("%016" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000716 else
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000717 outs() << format("%08" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000718 }
719 double d;
720 memcpy(&d, sect + i, sizeof(double));
721 if (O->isLittleEndian() != sys::IsLittleEndianHost)
722 sys::swapByteOrder(d);
723 uint32_t l0, l1;
724 memcpy(&l0, sect + i, sizeof(uint32_t));
725 memcpy(&l1, sect + i + sizeof(uint32_t), sizeof(uint32_t));
726 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
727 sys::swapByteOrder(l0);
728 sys::swapByteOrder(l1);
729 }
730 DumpLiteral8(O, l0, l1, d);
731 }
732}
733
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000734static void DumpLiteral16(uint32_t l0, uint32_t l1, uint32_t l2, uint32_t l3) {
735 outs() << format("0x%08" PRIx32, l0) << " ";
736 outs() << format("0x%08" PRIx32, l1) << " ";
737 outs() << format("0x%08" PRIx32, l2) << " ";
738 outs() << format("0x%08" PRIx32, l3) << "\n";
739}
740
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000741static void DumpLiteral16Section(MachOObjectFile *O, const char *sect,
742 uint32_t sect_size, uint64_t sect_addr,
743 bool print_addresses) {
744 for (uint32_t i = 0; i < sect_size; i += 16) {
745 if (print_addresses) {
746 if (O->is64Bit())
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000747 outs() << format("%016" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000748 else
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000749 outs() << format("%08" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000750 }
751 uint32_t l0, l1, l2, l3;
752 memcpy(&l0, sect + i, sizeof(uint32_t));
753 memcpy(&l1, sect + i + sizeof(uint32_t), sizeof(uint32_t));
754 memcpy(&l2, sect + i + 2 * sizeof(uint32_t), sizeof(uint32_t));
755 memcpy(&l3, sect + i + 3 * sizeof(uint32_t), sizeof(uint32_t));
756 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
757 sys::swapByteOrder(l0);
758 sys::swapByteOrder(l1);
759 sys::swapByteOrder(l2);
760 sys::swapByteOrder(l3);
761 }
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000762 DumpLiteral16(l0, l1, l2, l3);
763 }
764}
765
766static void DumpLiteralPointerSection(MachOObjectFile *O,
767 const SectionRef &Section,
768 const char *sect, uint32_t sect_size,
769 uint64_t sect_addr,
770 bool print_addresses) {
771 // Collect the literal sections in this Mach-O file.
772 std::vector<SectionRef> LiteralSections;
773 for (const SectionRef &Section : O->sections()) {
774 DataRefImpl Ref = Section.getRawDataRefImpl();
775 uint32_t section_type;
776 if (O->is64Bit()) {
777 const MachO::section_64 Sec = O->getSection64(Ref);
778 section_type = Sec.flags & MachO::SECTION_TYPE;
779 } else {
780 const MachO::section Sec = O->getSection(Ref);
781 section_type = Sec.flags & MachO::SECTION_TYPE;
782 }
783 if (section_type == MachO::S_CSTRING_LITERALS ||
784 section_type == MachO::S_4BYTE_LITERALS ||
785 section_type == MachO::S_8BYTE_LITERALS ||
786 section_type == MachO::S_16BYTE_LITERALS)
787 LiteralSections.push_back(Section);
788 }
789
790 // Set the size of the literal pointer.
791 uint32_t lp_size = O->is64Bit() ? 8 : 4;
792
Eric Christopher572e03a2015-06-19 01:53:21 +0000793 // Collect the external relocation symbols for the literal pointers.
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000794 std::vector<std::pair<uint64_t, SymbolRef>> Relocs;
795 for (const RelocationRef &Reloc : Section.relocations()) {
796 DataRefImpl Rel;
797 MachO::any_relocation_info RE;
798 bool isExtern = false;
799 Rel = Reloc.getRawDataRefImpl();
800 RE = O->getRelocation(Rel);
801 isExtern = O->getPlainRelocationExternal(RE);
802 if (isExtern) {
Rafael Espindola96d071c2015-06-29 23:29:12 +0000803 uint64_t RelocOffset = Reloc.getOffset();
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000804 symbol_iterator RelocSym = Reloc.getSymbol();
805 Relocs.push_back(std::make_pair(RelocOffset, *RelocSym));
806 }
807 }
808 array_pod_sort(Relocs.begin(), Relocs.end());
809
810 // Dump each literal pointer.
811 for (uint32_t i = 0; i < sect_size; i += lp_size) {
812 if (print_addresses) {
813 if (O->is64Bit())
814 outs() << format("%016" PRIx64, sect_addr + i) << " ";
815 else
816 outs() << format("%08" PRIx64, sect_addr + i) << " ";
817 }
818 uint64_t lp;
819 if (O->is64Bit()) {
820 memcpy(&lp, sect + i, sizeof(uint64_t));
821 if (O->isLittleEndian() != sys::IsLittleEndianHost)
822 sys::swapByteOrder(lp);
823 } else {
824 uint32_t li;
825 memcpy(&li, sect + i, sizeof(uint32_t));
826 if (O->isLittleEndian() != sys::IsLittleEndianHost)
827 sys::swapByteOrder(li);
828 lp = li;
829 }
830
831 // First look for an external relocation entry for this literal pointer.
David Majnemer42531262016-08-12 03:55:06 +0000832 auto Reloc = find_if(Relocs, [&](const std::pair<uint64_t, SymbolRef> &P) {
833 return P.first == i;
834 });
David Blaikie33dd45d02015-03-23 18:39:02 +0000835 if (Reloc != Relocs.end()) {
836 symbol_iterator RelocSym = Reloc->second;
Kevin Enderby81e8b7d2016-04-20 21:24:34 +0000837 Expected<StringRef> SymName = RelocSym->getName();
Kevin Enderby844c4ac2016-11-15 23:07:41 +0000838 if (!SymName)
839 report_error(O->getFileName(), SymName.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +0000840 outs() << "external relocation entry for symbol:" << *SymName << "\n";
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000841 continue;
David Blaikie33dd45d02015-03-23 18:39:02 +0000842 }
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000843
844 // For local references see what the section the literal pointer points to.
David Majnemer562e8292016-08-12 00:18:03 +0000845 auto Sect = find_if(LiteralSections, [&](const SectionRef &R) {
846 return lp >= R.getAddress() && lp < R.getAddress() + R.getSize();
847 });
David Blaikie33dd45d02015-03-23 18:39:02 +0000848 if (Sect == LiteralSections.end()) {
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000849 outs() << format("0x%" PRIx64, lp) << " (not in a literal section)\n";
David Blaikie33dd45d02015-03-23 18:39:02 +0000850 continue;
851 }
852
853 uint64_t SectAddress = Sect->getAddress();
854 uint64_t SectSize = Sect->getSize();
855
856 StringRef SectName;
857 Sect->getName(SectName);
858 DataRefImpl Ref = Sect->getRawDataRefImpl();
859 StringRef SegmentName = O->getSectionFinalSegmentName(Ref);
860 outs() << SegmentName << ":" << SectName << ":";
861
862 uint32_t section_type;
863 if (O->is64Bit()) {
864 const MachO::section_64 Sec = O->getSection64(Ref);
865 section_type = Sec.flags & MachO::SECTION_TYPE;
866 } else {
867 const MachO::section Sec = O->getSection(Ref);
868 section_type = Sec.flags & MachO::SECTION_TYPE;
869 }
870
871 StringRef BytesStr;
872 Sect->getContents(BytesStr);
873 const char *Contents = reinterpret_cast<const char *>(BytesStr.data());
874
875 switch (section_type) {
876 case MachO::S_CSTRING_LITERALS:
877 for (uint64_t i = lp - SectAddress; i < SectSize && Contents[i] != '\0';
878 i++) {
879 DumpCstringChar(Contents[i]);
880 }
881 outs() << "\n";
882 break;
883 case MachO::S_4BYTE_LITERALS:
884 float f;
885 memcpy(&f, Contents + (lp - SectAddress), sizeof(float));
886 uint32_t l;
887 memcpy(&l, Contents + (lp - SectAddress), sizeof(uint32_t));
888 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
889 sys::swapByteOrder(f);
890 sys::swapByteOrder(l);
891 }
892 DumpLiteral4(l, f);
893 break;
894 case MachO::S_8BYTE_LITERALS: {
895 double d;
896 memcpy(&d, Contents + (lp - SectAddress), sizeof(double));
897 uint32_t l0, l1;
898 memcpy(&l0, Contents + (lp - SectAddress), sizeof(uint32_t));
899 memcpy(&l1, Contents + (lp - SectAddress) + sizeof(uint32_t),
900 sizeof(uint32_t));
901 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
902 sys::swapByteOrder(f);
903 sys::swapByteOrder(l0);
904 sys::swapByteOrder(l1);
905 }
906 DumpLiteral8(O, l0, l1, d);
907 break;
908 }
909 case MachO::S_16BYTE_LITERALS: {
910 uint32_t l0, l1, l2, l3;
911 memcpy(&l0, Contents + (lp - SectAddress), sizeof(uint32_t));
912 memcpy(&l1, Contents + (lp - SectAddress) + sizeof(uint32_t),
913 sizeof(uint32_t));
914 memcpy(&l2, Contents + (lp - SectAddress) + 2 * sizeof(uint32_t),
915 sizeof(uint32_t));
916 memcpy(&l3, Contents + (lp - SectAddress) + 3 * sizeof(uint32_t),
917 sizeof(uint32_t));
918 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
919 sys::swapByteOrder(l0);
920 sys::swapByteOrder(l1);
921 sys::swapByteOrder(l2);
922 sys::swapByteOrder(l3);
923 }
924 DumpLiteral16(l0, l1, l2, l3);
925 break;
926 }
927 }
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000928 }
929}
930
Kevin Enderbyf6d25852015-01-31 00:37:11 +0000931static void DumpInitTermPointerSection(MachOObjectFile *O, const char *sect,
932 uint32_t sect_size, uint64_t sect_addr,
933 SymbolAddressMap *AddrMap,
934 bool verbose) {
935 uint32_t stride;
Davide Italiano3eb47e22015-12-15 23:14:21 +0000936 stride = (O->is64Bit()) ? sizeof(uint64_t) : sizeof(uint32_t);
Kevin Enderbyf6d25852015-01-31 00:37:11 +0000937 for (uint32_t i = 0; i < sect_size; i += stride) {
938 const char *SymbolName = nullptr;
939 if (O->is64Bit()) {
940 outs() << format("0x%016" PRIx64, sect_addr + i * stride) << " ";
941 uint64_t pointer_value;
942 memcpy(&pointer_value, sect + i, stride);
943 if (O->isLittleEndian() != sys::IsLittleEndianHost)
944 sys::swapByteOrder(pointer_value);
945 outs() << format("0x%016" PRIx64, pointer_value);
946 if (verbose)
947 SymbolName = GuessSymbolName(pointer_value, AddrMap);
948 } else {
949 outs() << format("0x%08" PRIx64, sect_addr + i * stride) << " ";
950 uint32_t pointer_value;
951 memcpy(&pointer_value, sect + i, stride);
952 if (O->isLittleEndian() != sys::IsLittleEndianHost)
953 sys::swapByteOrder(pointer_value);
954 outs() << format("0x%08" PRIx32, pointer_value);
955 if (verbose)
956 SymbolName = GuessSymbolName(pointer_value, AddrMap);
957 }
958 if (SymbolName)
959 outs() << " " << SymbolName;
960 outs() << "\n";
961 }
962}
963
964static void DumpRawSectionContents(MachOObjectFile *O, const char *sect,
965 uint32_t size, uint64_t addr) {
966 uint32_t cputype = O->getHeader().cputype;
967 if (cputype == MachO::CPU_TYPE_I386 || cputype == MachO::CPU_TYPE_X86_64) {
968 uint32_t j;
969 for (uint32_t i = 0; i < size; i += j, addr += j) {
970 if (O->is64Bit())
971 outs() << format("%016" PRIx64, addr) << "\t";
972 else
Kevin Enderbyf0640752015-03-13 17:56:32 +0000973 outs() << format("%08" PRIx64, addr) << "\t";
Kevin Enderbyf6d25852015-01-31 00:37:11 +0000974 for (j = 0; j < 16 && i + j < size; j++) {
975 uint8_t byte_word = *(sect + i + j);
976 outs() << format("%02" PRIx32, (uint32_t)byte_word) << " ";
977 }
978 outs() << "\n";
979 }
980 } else {
981 uint32_t j;
982 for (uint32_t i = 0; i < size; i += j, addr += j) {
983 if (O->is64Bit())
984 outs() << format("%016" PRIx64, addr) << "\t";
985 else
Kevin Enderbyc4930852016-04-27 22:36:18 +0000986 outs() << format("%08" PRIx64, addr) << "\t";
Kevin Enderbyf6d25852015-01-31 00:37:11 +0000987 for (j = 0; j < 4 * sizeof(int32_t) && i + j < size;
988 j += sizeof(int32_t)) {
Kevin Enderby8eccdad2016-04-27 23:43:00 +0000989 if (i + j + sizeof(int32_t) <= size) {
Kevin Enderbyf6d25852015-01-31 00:37:11 +0000990 uint32_t long_word;
991 memcpy(&long_word, sect + i + j, sizeof(int32_t));
992 if (O->isLittleEndian() != sys::IsLittleEndianHost)
993 sys::swapByteOrder(long_word);
994 outs() << format("%08" PRIx32, long_word) << " ";
995 } else {
996 for (uint32_t k = 0; i + j + k < size; k++) {
Kevin Enderby8eccdad2016-04-27 23:43:00 +0000997 uint8_t byte_word = *(sect + i + j + k);
Kevin Enderbyf6d25852015-01-31 00:37:11 +0000998 outs() << format("%02" PRIx32, (uint32_t)byte_word) << " ";
999 }
1000 }
1001 }
1002 outs() << "\n";
1003 }
1004 }
1005}
1006
Kevin Enderby95df54c2015-02-04 01:01:38 +00001007static void DisassembleMachO(StringRef Filename, MachOObjectFile *MachOOF,
1008 StringRef DisSegName, StringRef DisSectName);
Kevin Enderby4ad9bde2015-04-16 22:33:20 +00001009static void DumpProtocolSection(MachOObjectFile *O, const char *sect,
1010 uint32_t size, uint32_t addr);
Kevin Enderby9873e2c2016-05-23 21:34:12 +00001011#ifdef HAVE_LIBXAR
1012static void DumpBitcodeSection(MachOObjectFile *O, const char *sect,
1013 uint32_t size, bool verbose,
1014 bool PrintXarHeader, bool PrintXarFileHeaders,
1015 std::string XarMemberName);
1016#endif // defined(HAVE_LIBXAR)
Kevin Enderby95df54c2015-02-04 01:01:38 +00001017
1018static void DumpSectionContents(StringRef Filename, MachOObjectFile *O,
1019 bool verbose) {
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001020 SymbolAddressMap AddrMap;
1021 if (verbose)
1022 CreateSymbolAddressMap(O, &AddrMap);
1023
Colin LeMahieufcc32762015-07-29 19:08:10 +00001024 for (unsigned i = 0; i < FilterSections.size(); ++i) {
1025 StringRef DumpSection = FilterSections[i];
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001026 std::pair<StringRef, StringRef> DumpSegSectName;
1027 DumpSegSectName = DumpSection.split(',');
1028 StringRef DumpSegName, DumpSectName;
1029 if (DumpSegSectName.second.size()) {
1030 DumpSegName = DumpSegSectName.first;
1031 DumpSectName = DumpSegSectName.second;
1032 } else {
1033 DumpSegName = "";
1034 DumpSectName = DumpSegSectName.first;
1035 }
1036 for (const SectionRef &Section : O->sections()) {
1037 StringRef SectName;
1038 Section.getName(SectName);
1039 DataRefImpl Ref = Section.getRawDataRefImpl();
1040 StringRef SegName = O->getSectionFinalSegmentName(Ref);
1041 if ((DumpSegName.empty() || SegName == DumpSegName) &&
1042 (SectName == DumpSectName)) {
Adrian Prantlc2401dd2015-03-27 17:31:15 +00001043
Kevin Enderby95df54c2015-02-04 01:01:38 +00001044 uint32_t section_flags;
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001045 if (O->is64Bit()) {
1046 const MachO::section_64 Sec = O->getSection64(Ref);
Kevin Enderby95df54c2015-02-04 01:01:38 +00001047 section_flags = Sec.flags;
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001048
1049 } else {
1050 const MachO::section Sec = O->getSection(Ref);
Kevin Enderby95df54c2015-02-04 01:01:38 +00001051 section_flags = Sec.flags;
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001052 }
Kevin Enderby95df54c2015-02-04 01:01:38 +00001053 uint32_t section_type = section_flags & MachO::SECTION_TYPE;
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001054
1055 StringRef BytesStr;
1056 Section.getContents(BytesStr);
1057 const char *sect = reinterpret_cast<const char *>(BytesStr.data());
1058 uint32_t sect_size = BytesStr.size();
1059 uint64_t sect_addr = Section.getAddress();
1060
Adrian Prantlc2401dd2015-03-27 17:31:15 +00001061 outs() << "Contents of (" << SegName << "," << SectName
1062 << ") section\n";
1063
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001064 if (verbose) {
Kevin Enderby95df54c2015-02-04 01:01:38 +00001065 if ((section_flags & MachO::S_ATTR_PURE_INSTRUCTIONS) ||
1066 (section_flags & MachO::S_ATTR_SOME_INSTRUCTIONS)) {
1067 DisassembleMachO(Filename, O, SegName, SectName);
1068 continue;
1069 }
Kevin Enderbycd66be52015-03-11 22:06:32 +00001070 if (SegName == "__TEXT" && SectName == "__info_plist") {
1071 outs() << sect;
1072 continue;
1073 }
Kevin Enderby4ad9bde2015-04-16 22:33:20 +00001074 if (SegName == "__OBJC" && SectName == "__protocol") {
1075 DumpProtocolSection(O, sect, sect_size, sect_addr);
1076 continue;
1077 }
Kevin Enderby9873e2c2016-05-23 21:34:12 +00001078#ifdef HAVE_LIBXAR
1079 if (SegName == "__LLVM" && SectName == "__bundle") {
1080 DumpBitcodeSection(O, sect, sect_size, verbose, !NoSymbolicOperands,
1081 ArchiveHeaders, "");
1082 continue;
1083 }
1084#endif // defined(HAVE_LIBXAR)
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001085 switch (section_type) {
1086 case MachO::S_REGULAR:
1087 DumpRawSectionContents(O, sect, sect_size, sect_addr);
1088 break;
1089 case MachO::S_ZEROFILL:
1090 outs() << "zerofill section and has no contents in the file\n";
1091 break;
Kevin Enderby10ba0412015-02-04 21:38:42 +00001092 case MachO::S_CSTRING_LITERALS:
Kevin Enderbyab5e6c92015-03-17 21:07:39 +00001093 DumpCstringSection(O, sect, sect_size, sect_addr, !NoLeadingAddr);
Kevin Enderby10ba0412015-02-04 21:38:42 +00001094 break;
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001095 case MachO::S_4BYTE_LITERALS:
Kevin Enderbyab5e6c92015-03-17 21:07:39 +00001096 DumpLiteral4Section(O, sect, sect_size, sect_addr, !NoLeadingAddr);
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001097 break;
1098 case MachO::S_8BYTE_LITERALS:
Kevin Enderbyab5e6c92015-03-17 21:07:39 +00001099 DumpLiteral8Section(O, sect, sect_size, sect_addr, !NoLeadingAddr);
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001100 break;
1101 case MachO::S_16BYTE_LITERALS:
Kevin Enderby0fc11822015-04-01 20:57:01 +00001102 DumpLiteral16Section(O, sect, sect_size, sect_addr, !NoLeadingAddr);
1103 break;
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001104 case MachO::S_LITERAL_POINTERS:
1105 DumpLiteralPointerSection(O, Section, sect, sect_size, sect_addr,
Kevin Enderbyab5e6c92015-03-17 21:07:39 +00001106 !NoLeadingAddr);
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001107 break;
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001108 case MachO::S_MOD_INIT_FUNC_POINTERS:
1109 case MachO::S_MOD_TERM_FUNC_POINTERS:
1110 DumpInitTermPointerSection(O, sect, sect_size, sect_addr, &AddrMap,
1111 verbose);
1112 break;
1113 default:
1114 outs() << "Unknown section type ("
1115 << format("0x%08" PRIx32, section_type) << ")\n";
1116 DumpRawSectionContents(O, sect, sect_size, sect_addr);
1117 break;
1118 }
1119 } else {
1120 if (section_type == MachO::S_ZEROFILL)
1121 outs() << "zerofill section and has no contents in the file\n";
1122 else
1123 DumpRawSectionContents(O, sect, sect_size, sect_addr);
1124 }
1125 }
1126 }
1127 }
1128}
1129
Kevin Enderbycd66be52015-03-11 22:06:32 +00001130static void DumpInfoPlistSectionContents(StringRef Filename,
1131 MachOObjectFile *O) {
1132 for (const SectionRef &Section : O->sections()) {
1133 StringRef SectName;
1134 Section.getName(SectName);
1135 DataRefImpl Ref = Section.getRawDataRefImpl();
1136 StringRef SegName = O->getSectionFinalSegmentName(Ref);
1137 if (SegName == "__TEXT" && SectName == "__info_plist") {
Kevin Enderby30cf2e82017-06-20 21:00:25 +00001138 if (!NoLeadingHeaders)
1139 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
Kevin Enderbycd66be52015-03-11 22:06:32 +00001140 StringRef BytesStr;
1141 Section.getContents(BytesStr);
1142 const char *sect = reinterpret_cast<const char *>(BytesStr.data());
Kevin Enderby418659f2017-02-06 21:01:08 +00001143 outs() << format("%.*s", BytesStr.size(), sect) << "\n";
Kevin Enderbycd66be52015-03-11 22:06:32 +00001144 return;
1145 }
1146 }
1147}
1148
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001149// checkMachOAndArchFlags() checks to see if the ObjectFile is a Mach-O file
1150// and if it is and there is a list of architecture flags is specified then
1151// check to make sure this Mach-O file is one of those architectures or all
1152// architectures were specified. If not then an error is generated and this
1153// routine returns false. Else it returns true.
1154static bool checkMachOAndArchFlags(ObjectFile *O, StringRef Filename) {
David Majnemer91160d82016-10-31 17:11:31 +00001155 auto *MachO = dyn_cast<MachOObjectFile>(O);
1156
1157 if (!MachO || ArchAll || ArchFlags.empty())
1158 return true;
1159
1160 MachO::mach_header H;
1161 MachO::mach_header_64 H_64;
1162 Triple T;
Kevin Enderby59343a92016-12-16 22:54:02 +00001163 const char *McpuDefault, *ArchFlag;
David Majnemer91160d82016-10-31 17:11:31 +00001164 if (MachO->is64Bit()) {
1165 H_64 = MachO->MachOObjectFile::getHeader64();
Kevin Enderby59343a92016-12-16 22:54:02 +00001166 T = MachOObjectFile::getArchTriple(H_64.cputype, H_64.cpusubtype,
1167 &McpuDefault, &ArchFlag);
David Majnemer91160d82016-10-31 17:11:31 +00001168 } else {
1169 H = MachO->MachOObjectFile::getHeader();
Kevin Enderby59343a92016-12-16 22:54:02 +00001170 T = MachOObjectFile::getArchTriple(H.cputype, H.cpusubtype,
1171 &McpuDefault, &ArchFlag);
David Majnemer91160d82016-10-31 17:11:31 +00001172 }
Kevin Enderby59343a92016-12-16 22:54:02 +00001173 const std::string ArchFlagName(ArchFlag);
David Majnemer91160d82016-10-31 17:11:31 +00001174 if (none_of(ArchFlags, [&](const std::string &Name) {
Kevin Enderby59343a92016-12-16 22:54:02 +00001175 return Name == ArchFlagName;
David Majnemer91160d82016-10-31 17:11:31 +00001176 })) {
1177 errs() << "llvm-objdump: " + Filename + ": No architecture specified.\n";
1178 return false;
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001179 }
1180 return true;
1181}
1182
Kevin Enderby0fc11822015-04-01 20:57:01 +00001183static void printObjcMetaData(MachOObjectFile *O, bool verbose);
1184
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001185// ProcessMachO() is passed a single opened Mach-O file, which may be an
1186// archive member and or in a slice of a universal file. It prints the
1187// the file name and header info and then processes it according to the
1188// command line options.
Kevin Enderby844c4ac2016-11-15 23:07:41 +00001189static void ProcessMachO(StringRef Name, MachOObjectFile *MachOOF,
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001190 StringRef ArchiveMemberName = StringRef(),
1191 StringRef ArchitectureName = StringRef()) {
Kevin Enderby131d1772015-01-09 19:22:37 +00001192 // If we are doing some processing here on the Mach-O file print the header
1193 // info. And don't print it otherwise like in the case of printing the
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +00001194 // UniversalHeaders or ArchiveHeaders.
Kevin Enderbyac9e1552016-05-17 17:10:12 +00001195 if (Disassemble || PrivateHeaders || ExportsTrie || Rebase || Bind || SymbolTable ||
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001196 LazyBind || WeakBind || IndirectSymbols || DataInCode || LinkOptHints ||
Colin LeMahieufcc32762015-07-29 19:08:10 +00001197 DylibsUsed || DylibId || ObjcMetaData || (FilterSections.size() != 0)) {
Kevin Enderbyf9d60f02016-11-29 21:43:40 +00001198 if (!NoLeadingHeaders) {
1199 outs() << Name;
1200 if (!ArchiveMemberName.empty())
1201 outs() << '(' << ArchiveMemberName << ')';
1202 if (!ArchitectureName.empty())
1203 outs() << " (architecture " << ArchitectureName << ")";
1204 outs() << ":\n";
1205 }
Kevin Enderby131d1772015-01-09 19:22:37 +00001206 }
Kevin Enderby844c4ac2016-11-15 23:07:41 +00001207 // To use the report_error() form with an ArchiveName and FileName set
1208 // these up based on what is passed for Name and ArchiveMemberName.
1209 StringRef ArchiveName;
1210 StringRef FileName;
1211 if (!ArchiveMemberName.empty()) {
1212 ArchiveName = Name;
1213 FileName = ArchiveMemberName;
1214 } else {
1215 ArchiveName = StringRef();
1216 FileName = Name;
1217 }
1218
1219 // If we need the symbol table to do the operation then check it here to
1220 // produce a good error message as to where the Mach-O file comes from in
1221 // the error message.
1222 if (Disassemble || IndirectSymbols || FilterSections.size() != 0 ||
1223 UnwindInfo)
1224 if (Error Err = MachOOF->checkSymbolTable())
1225 report_error(ArchiveName, FileName, std::move(Err), ArchitectureName);
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001226
1227 if (Disassemble)
Kevin Enderby844c4ac2016-11-15 23:07:41 +00001228 DisassembleMachO(FileName, MachOOF, "__TEXT", "__text");
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +00001229 if (IndirectSymbols)
Kevin Enderbyf0640752015-03-13 17:56:32 +00001230 PrintIndirectSymbols(MachOOF, !NonVerbose);
Kevin Enderby69fe98d2015-01-23 18:52:17 +00001231 if (DataInCode)
Kevin Enderbyf0640752015-03-13 17:56:32 +00001232 PrintDataInCodeTable(MachOOF, !NonVerbose);
Kevin Enderby9a509442015-01-27 21:28:24 +00001233 if (LinkOptHints)
1234 PrintLinkOptHints(MachOOF);
Kevin Enderby98da6132015-01-20 21:47:46 +00001235 if (Relocations)
1236 PrintRelocations(MachOOF);
1237 if (SectionHeaders)
1238 PrintSectionHeaders(MachOOF);
1239 if (SectionContents)
1240 PrintSectionContents(MachOOF);
Colin LeMahieufcc32762015-07-29 19:08:10 +00001241 if (FilterSections.size() != 0)
Kevin Enderby844c4ac2016-11-15 23:07:41 +00001242 DumpSectionContents(FileName, MachOOF, !NonVerbose);
Kevin Enderbycd66be52015-03-11 22:06:32 +00001243 if (InfoPlist)
Kevin Enderby844c4ac2016-11-15 23:07:41 +00001244 DumpInfoPlistSectionContents(FileName, MachOOF);
Kevin Enderbybc847fa2015-03-16 20:08:09 +00001245 if (DylibsUsed)
1246 PrintDylibs(MachOOF, false);
1247 if (DylibId)
1248 PrintDylibs(MachOOF, true);
Kevin Enderby844c4ac2016-11-15 23:07:41 +00001249 if (SymbolTable)
Kevin Enderby9acb1092016-05-31 20:35:34 +00001250 PrintSymbolTable(MachOOF, ArchiveName, ArchitectureName);
Kevin Enderby98da6132015-01-20 21:47:46 +00001251 if (UnwindInfo)
1252 printMachOUnwindInfo(MachOOF);
Kevin Enderby0ae163f2016-01-13 00:25:36 +00001253 if (PrivateHeaders) {
1254 printMachOFileHeader(MachOOF);
1255 printMachOLoadCommands(MachOOF);
1256 }
1257 if (FirstPrivateHeader)
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001258 printMachOFileHeader(MachOOF);
Kevin Enderby0fc11822015-04-01 20:57:01 +00001259 if (ObjcMetaData)
1260 printObjcMetaData(MachOOF, !NonVerbose);
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001261 if (ExportsTrie)
1262 printExportsTrie(MachOOF);
1263 if (Rebase)
1264 printRebaseTable(MachOOF);
1265 if (Bind)
1266 printBindTable(MachOOF);
1267 if (LazyBind)
1268 printLazyBindTable(MachOOF);
1269 if (WeakBind)
1270 printWeakBindTable(MachOOF);
Igor Laevsky03a670c2016-01-26 15:09:42 +00001271
1272 if (DwarfDumpType != DIDT_Null) {
1273 std::unique_ptr<DIContext> DICtx(new DWARFContextInMemory(*MachOOF));
1274 // Dump the complete DWARF structure.
Adrian Prantlf4bc1f72017-06-01 18:18:23 +00001275 DIDumpOptions DumpOpts;
1276 DumpOpts.DumpType = DwarfDumpType;
1277 DumpOpts.DumpEH = true;
1278 DICtx->dump(outs(), DumpOpts);
Igor Laevsky03a670c2016-01-26 15:09:42 +00001279 }
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001280}
1281
Kevin Enderby131d1772015-01-09 19:22:37 +00001282// printUnknownCPUType() helps print_fat_headers for unknown CPU's.
1283static void printUnknownCPUType(uint32_t cputype, uint32_t cpusubtype) {
1284 outs() << " cputype (" << cputype << ")\n";
1285 outs() << " cpusubtype (" << cpusubtype << ")\n";
1286}
1287
1288// printCPUType() helps print_fat_headers by printing the cputype and
1289// pusubtype (symbolically for the one's it knows about).
1290static void printCPUType(uint32_t cputype, uint32_t cpusubtype) {
1291 switch (cputype) {
1292 case MachO::CPU_TYPE_I386:
1293 switch (cpusubtype) {
1294 case MachO::CPU_SUBTYPE_I386_ALL:
1295 outs() << " cputype CPU_TYPE_I386\n";
1296 outs() << " cpusubtype CPU_SUBTYPE_I386_ALL\n";
1297 break;
1298 default:
1299 printUnknownCPUType(cputype, cpusubtype);
1300 break;
1301 }
1302 break;
1303 case MachO::CPU_TYPE_X86_64:
1304 switch (cpusubtype) {
1305 case MachO::CPU_SUBTYPE_X86_64_ALL:
1306 outs() << " cputype CPU_TYPE_X86_64\n";
1307 outs() << " cpusubtype CPU_SUBTYPE_X86_64_ALL\n";
1308 break;
1309 case MachO::CPU_SUBTYPE_X86_64_H:
1310 outs() << " cputype CPU_TYPE_X86_64\n";
1311 outs() << " cpusubtype CPU_SUBTYPE_X86_64_H\n";
1312 break;
1313 default:
1314 printUnknownCPUType(cputype, cpusubtype);
1315 break;
1316 }
1317 break;
1318 case MachO::CPU_TYPE_ARM:
1319 switch (cpusubtype) {
1320 case MachO::CPU_SUBTYPE_ARM_ALL:
1321 outs() << " cputype CPU_TYPE_ARM\n";
1322 outs() << " cpusubtype CPU_SUBTYPE_ARM_ALL\n";
1323 break;
1324 case MachO::CPU_SUBTYPE_ARM_V4T:
1325 outs() << " cputype CPU_TYPE_ARM\n";
1326 outs() << " cpusubtype CPU_SUBTYPE_ARM_V4T\n";
1327 break;
1328 case MachO::CPU_SUBTYPE_ARM_V5TEJ:
1329 outs() << " cputype CPU_TYPE_ARM\n";
1330 outs() << " cpusubtype CPU_SUBTYPE_ARM_V5TEJ\n";
1331 break;
1332 case MachO::CPU_SUBTYPE_ARM_XSCALE:
1333 outs() << " cputype CPU_TYPE_ARM\n";
1334 outs() << " cpusubtype CPU_SUBTYPE_ARM_XSCALE\n";
1335 break;
1336 case MachO::CPU_SUBTYPE_ARM_V6:
1337 outs() << " cputype CPU_TYPE_ARM\n";
1338 outs() << " cpusubtype CPU_SUBTYPE_ARM_V6\n";
1339 break;
1340 case MachO::CPU_SUBTYPE_ARM_V6M:
1341 outs() << " cputype CPU_TYPE_ARM\n";
1342 outs() << " cpusubtype CPU_SUBTYPE_ARM_V6M\n";
1343 break;
1344 case MachO::CPU_SUBTYPE_ARM_V7:
1345 outs() << " cputype CPU_TYPE_ARM\n";
1346 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7\n";
1347 break;
1348 case MachO::CPU_SUBTYPE_ARM_V7EM:
1349 outs() << " cputype CPU_TYPE_ARM\n";
1350 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7EM\n";
1351 break;
1352 case MachO::CPU_SUBTYPE_ARM_V7K:
1353 outs() << " cputype CPU_TYPE_ARM\n";
1354 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7K\n";
1355 break;
1356 case MachO::CPU_SUBTYPE_ARM_V7M:
1357 outs() << " cputype CPU_TYPE_ARM\n";
1358 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7M\n";
1359 break;
1360 case MachO::CPU_SUBTYPE_ARM_V7S:
1361 outs() << " cputype CPU_TYPE_ARM\n";
1362 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7S\n";
1363 break;
1364 default:
1365 printUnknownCPUType(cputype, cpusubtype);
1366 break;
1367 }
1368 break;
1369 case MachO::CPU_TYPE_ARM64:
1370 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
1371 case MachO::CPU_SUBTYPE_ARM64_ALL:
1372 outs() << " cputype CPU_TYPE_ARM64\n";
1373 outs() << " cpusubtype CPU_SUBTYPE_ARM64_ALL\n";
1374 break;
1375 default:
1376 printUnknownCPUType(cputype, cpusubtype);
1377 break;
1378 }
1379 break;
1380 default:
1381 printUnknownCPUType(cputype, cpusubtype);
1382 break;
1383 }
1384}
1385
1386static void printMachOUniversalHeaders(const object::MachOUniversalBinary *UB,
1387 bool verbose) {
1388 outs() << "Fat headers\n";
Kevin Enderby606a3382016-06-21 21:55:01 +00001389 if (verbose) {
1390 if (UB->getMagic() == MachO::FAT_MAGIC)
1391 outs() << "fat_magic FAT_MAGIC\n";
1392 else // UB->getMagic() == MachO::FAT_MAGIC_64
1393 outs() << "fat_magic FAT_MAGIC_64\n";
1394 } else
Kevin Enderby131d1772015-01-09 19:22:37 +00001395 outs() << "fat_magic " << format("0x%" PRIx32, MachO::FAT_MAGIC) << "\n";
1396
1397 uint32_t nfat_arch = UB->getNumberOfObjects();
1398 StringRef Buf = UB->getData();
1399 uint64_t size = Buf.size();
1400 uint64_t big_size = sizeof(struct MachO::fat_header) +
1401 nfat_arch * sizeof(struct MachO::fat_arch);
1402 outs() << "nfat_arch " << UB->getNumberOfObjects();
1403 if (nfat_arch == 0)
1404 outs() << " (malformed, contains zero architecture types)\n";
1405 else if (big_size > size)
1406 outs() << " (malformed, architectures past end of file)\n";
1407 else
1408 outs() << "\n";
1409
1410 for (uint32_t i = 0; i < nfat_arch; ++i) {
1411 MachOUniversalBinary::ObjectForArch OFA(UB, i);
1412 uint32_t cputype = OFA.getCPUType();
1413 uint32_t cpusubtype = OFA.getCPUSubType();
1414 outs() << "architecture ";
1415 for (uint32_t j = 0; i != 0 && j <= i - 1; j++) {
1416 MachOUniversalBinary::ObjectForArch other_OFA(UB, j);
1417 uint32_t other_cputype = other_OFA.getCPUType();
1418 uint32_t other_cpusubtype = other_OFA.getCPUSubType();
Kevin Enderby0512bd72015-01-09 21:55:03 +00001419 if (cputype != 0 && cpusubtype != 0 && cputype == other_cputype &&
Kevin Enderby131d1772015-01-09 19:22:37 +00001420 (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) ==
Kevin Enderby0512bd72015-01-09 21:55:03 +00001421 (other_cpusubtype & ~MachO::CPU_SUBTYPE_MASK)) {
Kevin Enderby131d1772015-01-09 19:22:37 +00001422 outs() << "(illegal duplicate architecture) ";
1423 break;
Kevin Enderby0512bd72015-01-09 21:55:03 +00001424 }
Kevin Enderby131d1772015-01-09 19:22:37 +00001425 }
1426 if (verbose) {
Kevin Enderby59343a92016-12-16 22:54:02 +00001427 outs() << OFA.getArchFlagName() << "\n";
Kevin Enderby131d1772015-01-09 19:22:37 +00001428 printCPUType(cputype, cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
1429 } else {
1430 outs() << i << "\n";
1431 outs() << " cputype " << cputype << "\n";
1432 outs() << " cpusubtype " << (cpusubtype & ~MachO::CPU_SUBTYPE_MASK)
1433 << "\n";
1434 }
1435 if (verbose &&
1436 (cpusubtype & MachO::CPU_SUBTYPE_MASK) == MachO::CPU_SUBTYPE_LIB64)
1437 outs() << " capabilities CPU_SUBTYPE_LIB64\n";
1438 else
1439 outs() << " capabilities "
1440 << format("0x%" PRIx32,
1441 (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24) << "\n";
1442 outs() << " offset " << OFA.getOffset();
1443 if (OFA.getOffset() > size)
1444 outs() << " (past end of file)";
1445 if (OFA.getOffset() % (1 << OFA.getAlign()) != 0)
1446 outs() << " (not aligned on it's alignment (2^" << OFA.getAlign() << ")";
1447 outs() << "\n";
1448 outs() << " size " << OFA.getSize();
1449 big_size = OFA.getOffset() + OFA.getSize();
1450 if (big_size > size)
1451 outs() << " (past end of file)";
1452 outs() << "\n";
1453 outs() << " align 2^" << OFA.getAlign() << " (" << (1 << OFA.getAlign())
1454 << ")\n";
1455 }
1456}
1457
Kevin Enderby6524bd82016-07-19 20:47:07 +00001458static void printArchiveChild(StringRef Filename, const Archive::Child &C,
1459 bool verbose, bool print_offset,
1460 StringRef ArchitectureName = StringRef()) {
Kevin Enderby13023a12015-01-15 23:19:11 +00001461 if (print_offset)
1462 outs() << C.getChildOffset() << "\t";
Vedant Kumar4031d9f2016-08-03 19:02:50 +00001463 Expected<sys::fs::perms> ModeOrErr = C.getAccessMode();
1464 if (!ModeOrErr)
1465 report_error(Filename, C, ModeOrErr.takeError(), ArchitectureName);
1466 sys::fs::perms Mode = ModeOrErr.get();
Kevin Enderby13023a12015-01-15 23:19:11 +00001467 if (verbose) {
1468 // FIXME: this first dash, "-", is for (Mode & S_IFMT) == S_IFREG.
1469 // But there is nothing in sys::fs::perms for S_IFMT or S_IFREG.
1470 outs() << "-";
Davide Italianobb9a6cc2015-09-07 20:47:03 +00001471 outs() << ((Mode & sys::fs::owner_read) ? "r" : "-");
1472 outs() << ((Mode & sys::fs::owner_write) ? "w" : "-");
1473 outs() << ((Mode & sys::fs::owner_exe) ? "x" : "-");
1474 outs() << ((Mode & sys::fs::group_read) ? "r" : "-");
1475 outs() << ((Mode & sys::fs::group_write) ? "w" : "-");
1476 outs() << ((Mode & sys::fs::group_exe) ? "x" : "-");
1477 outs() << ((Mode & sys::fs::others_read) ? "r" : "-");
1478 outs() << ((Mode & sys::fs::others_write) ? "w" : "-");
1479 outs() << ((Mode & sys::fs::others_exe) ? "x" : "-");
Kevin Enderby13023a12015-01-15 23:19:11 +00001480 } else {
1481 outs() << format("0%o ", Mode);
1482 }
1483
Vedant Kumar4031d9f2016-08-03 19:02:50 +00001484 Expected<unsigned> UIDOrErr = C.getUID();
1485 if (!UIDOrErr)
1486 report_error(Filename, C, UIDOrErr.takeError(), ArchitectureName);
1487 unsigned UID = UIDOrErr.get();
Kevin Enderby13023a12015-01-15 23:19:11 +00001488 outs() << format("%3d/", UID);
Vedant Kumar4031d9f2016-08-03 19:02:50 +00001489 Expected<unsigned> GIDOrErr = C.getGID();
1490 if (!GIDOrErr)
1491 report_error(Filename, C, GIDOrErr.takeError(), ArchitectureName);
1492 unsigned GID = GIDOrErr.get();
Kevin Enderby13023a12015-01-15 23:19:11 +00001493 outs() << format("%-3d ", GID);
Kevin Enderby6524bd82016-07-19 20:47:07 +00001494 Expected<uint64_t> Size = C.getRawSize();
1495 if (!Size)
1496 report_error(Filename, C, Size.takeError(), ArchitectureName);
Kevin Enderby7a969422015-11-05 19:24:56 +00001497 outs() << format("%5" PRId64, Size.get()) << " ";
Kevin Enderby13023a12015-01-15 23:19:11 +00001498
1499 StringRef RawLastModified = C.getRawLastModified();
1500 if (verbose) {
1501 unsigned Seconds;
1502 if (RawLastModified.getAsInteger(10, Seconds))
Vedant Kumar4031d9f2016-08-03 19:02:50 +00001503 outs() << "(date: \"" << RawLastModified
1504 << "\" contains non-decimal chars) ";
Kevin Enderby13023a12015-01-15 23:19:11 +00001505 else {
1506 // Since cime(3) returns a 26 character string of the form:
1507 // "Sun Sep 16 01:03:52 1973\n\0"
1508 // just print 24 characters.
1509 time_t t = Seconds;
1510 outs() << format("%.24s ", ctime(&t));
1511 }
1512 } else {
1513 outs() << RawLastModified << " ";
1514 }
1515
1516 if (verbose) {
Kevin Enderbyf4586032016-07-29 17:44:13 +00001517 Expected<StringRef> NameOrErr = C.getName();
1518 if (!NameOrErr) {
1519 consumeError(NameOrErr.takeError());
1520 Expected<StringRef> NameOrErr = C.getRawName();
1521 if (!NameOrErr)
1522 report_error(Filename, C, NameOrErr.takeError(), ArchitectureName);
1523 StringRef RawName = NameOrErr.get();
Kevin Enderby13023a12015-01-15 23:19:11 +00001524 outs() << RawName << "\n";
1525 } else {
1526 StringRef Name = NameOrErr.get();
1527 outs() << Name << "\n";
1528 }
1529 } else {
Kevin Enderbyf4586032016-07-29 17:44:13 +00001530 Expected<StringRef> NameOrErr = C.getRawName();
1531 if (!NameOrErr)
1532 report_error(Filename, C, NameOrErr.takeError(), ArchitectureName);
1533 StringRef RawName = NameOrErr.get();
Kevin Enderby13023a12015-01-15 23:19:11 +00001534 outs() << RawName << "\n";
1535 }
1536}
1537
Kevin Enderby6524bd82016-07-19 20:47:07 +00001538static void printArchiveHeaders(StringRef Filename, Archive *A, bool verbose,
1539 bool print_offset,
1540 StringRef ArchitectureName = StringRef()) {
Mehdi Amini41af4302016-11-11 04:28:40 +00001541 Error Err = Error::success();
1542 ;
Lang Hamesfc209622016-07-14 02:24:01 +00001543 for (const auto &C : A->children(Err, false))
Kevin Enderby6524bd82016-07-19 20:47:07 +00001544 printArchiveChild(Filename, C, verbose, print_offset, ArchitectureName);
1545
Lang Hamesfc209622016-07-14 02:24:01 +00001546 if (Err)
Kevin Enderby844c4ac2016-11-15 23:07:41 +00001547 report_error(StringRef(), Filename, std::move(Err), ArchitectureName);
Kevin Enderby13023a12015-01-15 23:19:11 +00001548}
1549
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001550// ParseInputMachO() parses the named Mach-O file in Filename and handles the
1551// -arch flags selecting just those slices as specified by them and also parses
1552// archive files. Then for each individual Mach-O file ProcessMachO() is
1553// called to process the file based on the command line options.
1554void llvm::ParseInputMachO(StringRef Filename) {
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001555 // Check for -arch all and verifiy the -arch flags are valid.
1556 for (unsigned i = 0; i < ArchFlags.size(); ++i) {
1557 if (ArchFlags[i] == "all") {
1558 ArchAll = true;
1559 } else {
1560 if (!MachOObjectFile::isValidArch(ArchFlags[i])) {
1561 errs() << "llvm-objdump: Unknown architecture named '" + ArchFlags[i] +
1562 "'for the -arch option\n";
1563 return;
1564 }
1565 }
1566 }
1567
1568 // Attempt to open the binary.
Kevin Enderby3fcdf6a2016-04-06 22:14:09 +00001569 Expected<OwningBinary<Binary>> BinaryOrErr = createBinary(Filename);
Kevin Enderby98898f22017-01-30 20:53:17 +00001570 if (!BinaryOrErr) {
1571 if (auto E = isNotObjectErrorInvalidFileType(BinaryOrErr.takeError()))
1572 report_error(Filename, std::move(E));
1573 else
1574 outs() << Filename << ": is not an object file\n";
1575 return;
1576 }
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001577 Binary &Bin = *BinaryOrErr.get().getBinary();
Kevin Enderby3f0ffab2014-12-03 22:29:40 +00001578
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001579 if (Archive *A = dyn_cast<Archive>(&Bin)) {
1580 outs() << "Archive : " << Filename << "\n";
Kevin Enderby13023a12015-01-15 23:19:11 +00001581 if (ArchiveHeaders)
Kevin Enderby6524bd82016-07-19 20:47:07 +00001582 printArchiveHeaders(Filename, A, !NonVerbose, ArchiveMemberOffsets);
1583
Mehdi Amini41af4302016-11-11 04:28:40 +00001584 Error Err = Error::success();
Lang Hamesfc209622016-07-14 02:24:01 +00001585 for (auto &C : A->children(Err)) {
Kevin Enderbyac9e1552016-05-17 17:10:12 +00001586 Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
1587 if (!ChildOrErr) {
1588 if (auto E = isNotObjectErrorInvalidFileType(ChildOrErr.takeError()))
1589 report_error(Filename, C, std::move(E));
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001590 continue;
Kevin Enderbyac9e1552016-05-17 17:10:12 +00001591 }
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001592 if (MachOObjectFile *O = dyn_cast<MachOObjectFile>(&*ChildOrErr.get())) {
1593 if (!checkMachOAndArchFlags(O, Filename))
1594 return;
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001595 ProcessMachO(Filename, O, O->getFileName());
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001596 }
1597 }
Lang Hamesfc209622016-07-14 02:24:01 +00001598 if (Err)
1599 report_error(Filename, std::move(Err));
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001600 return;
1601 }
Kevin Enderby131d1772015-01-09 19:22:37 +00001602 if (UniversalHeaders) {
1603 if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(&Bin))
Kevin Enderbyf0640752015-03-13 17:56:32 +00001604 printMachOUniversalHeaders(UB, !NonVerbose);
Kevin Enderby131d1772015-01-09 19:22:37 +00001605 }
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001606 if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(&Bin)) {
1607 // If we have a list of architecture flags specified dump only those.
1608 if (!ArchAll && ArchFlags.size() != 0) {
1609 // Look for a slice in the universal binary that matches each ArchFlag.
1610 bool ArchFound;
1611 for (unsigned i = 0; i < ArchFlags.size(); ++i) {
1612 ArchFound = false;
1613 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
1614 E = UB->end_objects();
1615 I != E; ++I) {
Kevin Enderby59343a92016-12-16 22:54:02 +00001616 if (ArchFlags[i] == I->getArchFlagName()) {
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001617 ArchFound = true;
Kevin Enderby9acb1092016-05-31 20:35:34 +00001618 Expected<std::unique_ptr<ObjectFile>> ObjOrErr =
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001619 I->getAsObjectFile();
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001620 std::string ArchitectureName = "";
1621 if (ArchFlags.size() > 1)
Kevin Enderby59343a92016-12-16 22:54:02 +00001622 ArchitectureName = I->getArchFlagName();
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001623 if (ObjOrErr) {
1624 ObjectFile &O = *ObjOrErr.get();
1625 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&O))
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001626 ProcessMachO(Filename, MachOOF, "", ArchitectureName);
Kevin Enderby9acb1092016-05-31 20:35:34 +00001627 } else if (auto E = isNotObjectErrorInvalidFileType(
1628 ObjOrErr.takeError())) {
1629 report_error(Filename, StringRef(), std::move(E),
1630 ArchitectureName);
1631 continue;
Kevin Enderby42398052016-06-28 23:16:13 +00001632 } else if (Expected<std::unique_ptr<Archive>> AOrErr =
Rafael Espindola0bfe8282014-12-09 21:05:36 +00001633 I->getAsArchive()) {
1634 std::unique_ptr<Archive> &A = *AOrErr;
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001635 outs() << "Archive : " << Filename;
1636 if (!ArchitectureName.empty())
1637 outs() << " (architecture " << ArchitectureName << ")";
1638 outs() << "\n";
Kevin Enderby13023a12015-01-15 23:19:11 +00001639 if (ArchiveHeaders)
Kevin Enderby6524bd82016-07-19 20:47:07 +00001640 printArchiveHeaders(Filename, A.get(), !NonVerbose,
1641 ArchiveMemberOffsets, ArchitectureName);
Mehdi Amini41af4302016-11-11 04:28:40 +00001642 Error Err = Error::success();
Lang Hamesfc209622016-07-14 02:24:01 +00001643 for (auto &C : A->children(Err)) {
Kevin Enderbyac9e1552016-05-17 17:10:12 +00001644 Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
1645 if (!ChildOrErr) {
1646 if (auto E = isNotObjectErrorInvalidFileType(ChildOrErr.takeError()))
Kevin Enderby9acb1092016-05-31 20:35:34 +00001647 report_error(Filename, C, std::move(E), ArchitectureName);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001648 continue;
Kevin Enderbyac9e1552016-05-17 17:10:12 +00001649 }
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001650 if (MachOObjectFile *O =
1651 dyn_cast<MachOObjectFile>(&*ChildOrErr.get()))
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001652 ProcessMachO(Filename, O, O->getFileName(), ArchitectureName);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001653 }
Lang Hamesfc209622016-07-14 02:24:01 +00001654 if (Err)
1655 report_error(Filename, std::move(Err));
Kevin Enderby42398052016-06-28 23:16:13 +00001656 } else {
1657 consumeError(AOrErr.takeError());
1658 error("Mach-O universal file: " + Filename + " for " +
Kevin Enderby59343a92016-12-16 22:54:02 +00001659 "architecture " + StringRef(I->getArchFlagName()) +
Kevin Enderby42398052016-06-28 23:16:13 +00001660 " is not a Mach-O file or an archive file");
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001661 }
1662 }
1663 }
1664 if (!ArchFound) {
1665 errs() << "llvm-objdump: file: " + Filename + " does not contain "
1666 << "architecture: " + ArchFlags[i] + "\n";
1667 return;
1668 }
1669 }
1670 return;
1671 }
1672 // No architecture flags were specified so if this contains a slice that
1673 // matches the host architecture dump only that.
1674 if (!ArchAll) {
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001675 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
1676 E = UB->end_objects();
1677 I != E; ++I) {
Kevin Enderby0512bd72015-01-09 21:55:03 +00001678 if (MachOObjectFile::getHostArch().getArchName() ==
Kevin Enderby59343a92016-12-16 22:54:02 +00001679 I->getArchFlagName()) {
Kevin Enderby9acb1092016-05-31 20:35:34 +00001680 Expected<std::unique_ptr<ObjectFile>> ObjOrErr = I->getAsObjectFile();
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001681 std::string ArchiveName;
1682 ArchiveName.clear();
1683 if (ObjOrErr) {
1684 ObjectFile &O = *ObjOrErr.get();
1685 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&O))
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001686 ProcessMachO(Filename, MachOOF);
Kevin Enderby9acb1092016-05-31 20:35:34 +00001687 } else if (auto E = isNotObjectErrorInvalidFileType(
1688 ObjOrErr.takeError())) {
1689 report_error(Filename, std::move(E));
1690 continue;
Kevin Enderby42398052016-06-28 23:16:13 +00001691 } else if (Expected<std::unique_ptr<Archive>> AOrErr =
Rafael Espindola0bfe8282014-12-09 21:05:36 +00001692 I->getAsArchive()) {
1693 std::unique_ptr<Archive> &A = *AOrErr;
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001694 outs() << "Archive : " << Filename << "\n";
Kevin Enderby13023a12015-01-15 23:19:11 +00001695 if (ArchiveHeaders)
Kevin Enderby6524bd82016-07-19 20:47:07 +00001696 printArchiveHeaders(Filename, A.get(), !NonVerbose,
1697 ArchiveMemberOffsets);
Mehdi Amini41af4302016-11-11 04:28:40 +00001698 Error Err = Error::success();
Lang Hamesfc209622016-07-14 02:24:01 +00001699 for (auto &C : A->children(Err)) {
Kevin Enderbyac9e1552016-05-17 17:10:12 +00001700 Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
1701 if (!ChildOrErr) {
1702 if (auto E = isNotObjectErrorInvalidFileType(ChildOrErr.takeError()))
1703 report_error(Filename, C, std::move(E));
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001704 continue;
Kevin Enderbyac9e1552016-05-17 17:10:12 +00001705 }
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001706 if (MachOObjectFile *O =
1707 dyn_cast<MachOObjectFile>(&*ChildOrErr.get()))
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001708 ProcessMachO(Filename, O, O->getFileName());
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001709 }
Lang Hamesfc209622016-07-14 02:24:01 +00001710 if (Err)
1711 report_error(Filename, std::move(Err));
Kevin Enderby42398052016-06-28 23:16:13 +00001712 } else {
1713 consumeError(AOrErr.takeError());
1714 error("Mach-O universal file: " + Filename + " for architecture " +
Kevin Enderby59343a92016-12-16 22:54:02 +00001715 StringRef(I->getArchFlagName()) +
Kevin Enderby42398052016-06-28 23:16:13 +00001716 " is not a Mach-O file or an archive file");
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001717 }
1718 return;
1719 }
1720 }
1721 }
1722 // Either all architectures have been specified or none have been specified
1723 // and this does not contain the host architecture so dump all the slices.
1724 bool moreThanOneArch = UB->getNumberOfObjects() > 1;
1725 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
1726 E = UB->end_objects();
1727 I != E; ++I) {
Kevin Enderby9acb1092016-05-31 20:35:34 +00001728 Expected<std::unique_ptr<ObjectFile>> ObjOrErr = I->getAsObjectFile();
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001729 std::string ArchitectureName = "";
1730 if (moreThanOneArch)
Kevin Enderby59343a92016-12-16 22:54:02 +00001731 ArchitectureName = I->getArchFlagName();
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001732 if (ObjOrErr) {
1733 ObjectFile &Obj = *ObjOrErr.get();
1734 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&Obj))
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001735 ProcessMachO(Filename, MachOOF, "", ArchitectureName);
Kevin Enderby9acb1092016-05-31 20:35:34 +00001736 } else if (auto E = isNotObjectErrorInvalidFileType(
1737 ObjOrErr.takeError())) {
1738 report_error(StringRef(), Filename, std::move(E), ArchitectureName);
1739 continue;
Kevin Enderby42398052016-06-28 23:16:13 +00001740 } else if (Expected<std::unique_ptr<Archive>> AOrErr =
1741 I->getAsArchive()) {
Rafael Espindola0bfe8282014-12-09 21:05:36 +00001742 std::unique_ptr<Archive> &A = *AOrErr;
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001743 outs() << "Archive : " << Filename;
1744 if (!ArchitectureName.empty())
1745 outs() << " (architecture " << ArchitectureName << ")";
1746 outs() << "\n";
Kevin Enderby13023a12015-01-15 23:19:11 +00001747 if (ArchiveHeaders)
Kevin Enderby6524bd82016-07-19 20:47:07 +00001748 printArchiveHeaders(Filename, A.get(), !NonVerbose,
1749 ArchiveMemberOffsets, ArchitectureName);
Mehdi Amini41af4302016-11-11 04:28:40 +00001750 Error Err = Error::success();
Lang Hamesfc209622016-07-14 02:24:01 +00001751 for (auto &C : A->children(Err)) {
Kevin Enderbyac9e1552016-05-17 17:10:12 +00001752 Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
1753 if (!ChildOrErr) {
1754 if (auto E = isNotObjectErrorInvalidFileType(ChildOrErr.takeError()))
Kevin Enderby9acb1092016-05-31 20:35:34 +00001755 report_error(Filename, C, std::move(E), ArchitectureName);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001756 continue;
Kevin Enderbyac9e1552016-05-17 17:10:12 +00001757 }
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001758 if (MachOObjectFile *O =
1759 dyn_cast<MachOObjectFile>(&*ChildOrErr.get())) {
1760 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(O))
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001761 ProcessMachO(Filename, MachOOF, MachOOF->getFileName(),
1762 ArchitectureName);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001763 }
1764 }
Lang Hamesfc209622016-07-14 02:24:01 +00001765 if (Err)
1766 report_error(Filename, std::move(Err));
Kevin Enderby42398052016-06-28 23:16:13 +00001767 } else {
1768 consumeError(AOrErr.takeError());
1769 error("Mach-O universal file: " + Filename + " for architecture " +
Kevin Enderby59343a92016-12-16 22:54:02 +00001770 StringRef(I->getArchFlagName()) +
Kevin Enderby42398052016-06-28 23:16:13 +00001771 " is not a Mach-O file or an archive file");
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001772 }
1773 }
1774 return;
1775 }
1776 if (ObjectFile *O = dyn_cast<ObjectFile>(&Bin)) {
1777 if (!checkMachOAndArchFlags(O, Filename))
1778 return;
1779 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&*O)) {
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001780 ProcessMachO(Filename, MachOOF);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001781 } else
1782 errs() << "llvm-objdump: '" << Filename << "': "
1783 << "Object is not a Mach-O file type.\n";
Davide Italiano25d84582016-01-13 04:11:36 +00001784 return;
1785 }
1786 llvm_unreachable("Input object can't be invalid at this point");
Rafael Espindola9b709252013-04-13 01:45:40 +00001787}
1788
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001789// The block of info used by the Symbolizer call backs.
1790struct DisassembleInfo {
1791 bool verbose;
1792 MachOObjectFile *O;
1793 SectionRef S;
Kevin Enderbybf246f52014-09-24 23:08:22 +00001794 SymbolAddressMap *AddrMap;
Kevin Enderby6f326ce2014-10-23 19:37:31 +00001795 std::vector<SectionRef> *Sections;
1796 const char *class_name;
1797 const char *selector_name;
1798 char *method;
Kevin Enderby04bf6932014-10-28 23:39:46 +00001799 char *demangled_name;
Kevin Enderbyae3c1262014-11-14 21:52:18 +00001800 uint64_t adrp_addr;
1801 uint32_t adrp_inst;
Saleem Abdulrasool1d84d9a2017-01-08 19:14:15 +00001802 std::unique_ptr<SymbolAddressMap> bindtable;
Kevin Enderbyaac75382015-10-08 16:56:35 +00001803 uint32_t depth;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001804};
1805
1806// SymbolizerGetOpInfo() is the operand information call back function.
1807// This is called to get the symbolic information for operand(s) of an
1808// instruction when it is being done. This routine does this from
1809// the relocation information, symbol table, etc. That block of information
1810// is a pointer to the struct DisassembleInfo that was passed when the
1811// disassembler context was created and passed to back to here when
1812// called back by the disassembler for instruction operands that could have
1813// relocation information. The address of the instruction containing operand is
1814// at the Pc parameter. The immediate value the operand has is passed in
1815// op_info->Value and is at Offset past the start of the instruction and has a
1816// byte Size of 1, 2 or 4. The symbolc information is returned in TagBuf is the
1817// LLVMOpInfo1 struct defined in the header "llvm-c/Disassembler.h" as symbol
1818// names and addends of the symbolic expression to add for the operand. The
1819// value of TagType is currently 1 (for the LLVMOpInfo1 struct). If symbolic
1820// information is returned then this function returns 1 else it returns 0.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00001821static int SymbolizerGetOpInfo(void *DisInfo, uint64_t Pc, uint64_t Offset,
1822 uint64_t Size, int TagType, void *TagBuf) {
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001823 struct DisassembleInfo *info = (struct DisassembleInfo *)DisInfo;
1824 struct LLVMOpInfo1 *op_info = (struct LLVMOpInfo1 *)TagBuf;
Kevin Enderbyae3c1262014-11-14 21:52:18 +00001825 uint64_t value = op_info->Value;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001826
1827 // Make sure all fields returned are zero if we don't set them.
1828 memset((void *)op_info, '\0', sizeof(struct LLVMOpInfo1));
1829 op_info->Value = value;
1830
1831 // If the TagType is not the value 1 which it code knows about or if no
1832 // verbose symbolic information is wanted then just return 0, indicating no
1833 // information is being returned.
David Blaikie33dd45d02015-03-23 18:39:02 +00001834 if (TagType != 1 || !info->verbose)
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001835 return 0;
1836
1837 unsigned int Arch = info->O->getArch();
1838 if (Arch == Triple::x86) {
Kevin Enderby9907d0a2014-11-04 00:43:16 +00001839 if (Size != 1 && Size != 2 && Size != 4 && Size != 0)
1840 return 0;
Kevin Enderbyd90a4172015-10-10 00:05:01 +00001841 if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
1842 // TODO:
1843 // Search the external relocation entries of a fully linked image
1844 // (if any) for an entry that matches this segment offset.
1845 // uint32_t seg_offset = (Pc + Offset);
1846 return 0;
1847 }
1848 // In MH_OBJECT filetypes search the section's relocation entries (if any)
1849 // for an entry for this section offset.
Kevin Enderby9907d0a2014-11-04 00:43:16 +00001850 uint32_t sect_addr = info->S.getAddress();
1851 uint32_t sect_offset = (Pc + Offset) - sect_addr;
1852 bool reloc_found = false;
1853 DataRefImpl Rel;
1854 MachO::any_relocation_info RE;
1855 bool isExtern = false;
1856 SymbolRef Symbol;
1857 bool r_scattered = false;
1858 uint32_t r_value, pair_r_value, r_type;
1859 for (const RelocationRef &Reloc : info->S.relocations()) {
Rafael Espindola96d071c2015-06-29 23:29:12 +00001860 uint64_t RelocOffset = Reloc.getOffset();
Kevin Enderby9907d0a2014-11-04 00:43:16 +00001861 if (RelocOffset == sect_offset) {
1862 Rel = Reloc.getRawDataRefImpl();
1863 RE = info->O->getRelocation(Rel);
Kevin Enderby3eb73e12014-11-11 19:16:45 +00001864 r_type = info->O->getAnyRelocationType(RE);
Kevin Enderby9907d0a2014-11-04 00:43:16 +00001865 r_scattered = info->O->isRelocationScattered(RE);
1866 if (r_scattered) {
1867 r_value = info->O->getScatteredRelocationValue(RE);
Kevin Enderby9907d0a2014-11-04 00:43:16 +00001868 if (r_type == MachO::GENERIC_RELOC_SECTDIFF ||
1869 r_type == MachO::GENERIC_RELOC_LOCAL_SECTDIFF) {
1870 DataRefImpl RelNext = Rel;
1871 info->O->moveRelocationNext(RelNext);
1872 MachO::any_relocation_info RENext;
1873 RENext = info->O->getRelocation(RelNext);
1874 if (info->O->isRelocationScattered(RENext))
Kevin Enderby930fdc72014-11-06 19:00:13 +00001875 pair_r_value = info->O->getScatteredRelocationValue(RENext);
Kevin Enderby9907d0a2014-11-04 00:43:16 +00001876 else
1877 return 0;
1878 }
1879 } else {
1880 isExtern = info->O->getPlainRelocationExternal(RE);
1881 if (isExtern) {
1882 symbol_iterator RelocSym = Reloc.getSymbol();
1883 Symbol = *RelocSym;
1884 }
1885 }
1886 reloc_found = true;
1887 break;
1888 }
1889 }
1890 if (reloc_found && isExtern) {
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00001891 Expected<StringRef> SymName = Symbol.getName();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00001892 if (!SymName)
1893 report_error(info->O->getFileName(), SymName.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00001894 const char *name = SymName->data();
Kevin Enderby9907d0a2014-11-04 00:43:16 +00001895 op_info->AddSymbol.Present = 1;
1896 op_info->AddSymbol.Name = name;
1897 // For i386 extern relocation entries the value in the instruction is
1898 // the offset from the symbol, and value is already set in op_info->Value.
1899 return 1;
1900 }
1901 if (reloc_found && (r_type == MachO::GENERIC_RELOC_SECTDIFF ||
1902 r_type == MachO::GENERIC_RELOC_LOCAL_SECTDIFF)) {
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001903 const char *add = GuessSymbolName(r_value, info->AddrMap);
1904 const char *sub = GuessSymbolName(pair_r_value, info->AddrMap);
Kevin Enderby9907d0a2014-11-04 00:43:16 +00001905 uint32_t offset = value - (r_value - pair_r_value);
1906 op_info->AddSymbol.Present = 1;
1907 if (add != nullptr)
1908 op_info->AddSymbol.Name = add;
1909 else
1910 op_info->AddSymbol.Value = r_value;
1911 op_info->SubtractSymbol.Present = 1;
1912 if (sub != nullptr)
1913 op_info->SubtractSymbol.Name = sub;
1914 else
1915 op_info->SubtractSymbol.Value = pair_r_value;
1916 op_info->Value = offset;
1917 return 1;
1918 }
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001919 return 0;
David Blaikie33dd45d02015-03-23 18:39:02 +00001920 }
1921 if (Arch == Triple::x86_64) {
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001922 if (Size != 1 && Size != 2 && Size != 4 && Size != 0)
1923 return 0;
Kevin Enderbyd90a4172015-10-10 00:05:01 +00001924 if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
1925 // TODO:
1926 // Search the external relocation entries of a fully linked image
1927 // (if any) for an entry that matches this segment offset.
1928 // uint64_t seg_offset = (Pc + Offset);
1929 return 0;
1930 }
1931 // In MH_OBJECT filetypes search the section's relocation entries (if any)
1932 // for an entry for this section offset.
Rafael Espindola80291272014-10-08 15:28:58 +00001933 uint64_t sect_addr = info->S.getAddress();
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001934 uint64_t sect_offset = (Pc + Offset) - sect_addr;
1935 bool reloc_found = false;
1936 DataRefImpl Rel;
1937 MachO::any_relocation_info RE;
1938 bool isExtern = false;
1939 SymbolRef Symbol;
1940 for (const RelocationRef &Reloc : info->S.relocations()) {
Rafael Espindola96d071c2015-06-29 23:29:12 +00001941 uint64_t RelocOffset = Reloc.getOffset();
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001942 if (RelocOffset == sect_offset) {
1943 Rel = Reloc.getRawDataRefImpl();
1944 RE = info->O->getRelocation(Rel);
1945 // NOTE: Scattered relocations don't exist on x86_64.
1946 isExtern = info->O->getPlainRelocationExternal(RE);
1947 if (isExtern) {
1948 symbol_iterator RelocSym = Reloc.getSymbol();
1949 Symbol = *RelocSym;
1950 }
1951 reloc_found = true;
1952 break;
1953 }
1954 }
1955 if (reloc_found && isExtern) {
1956 // The Value passed in will be adjusted by the Pc if the instruction
1957 // adds the Pc. But for x86_64 external relocation entries the Value
1958 // is the offset from the external symbol.
1959 if (info->O->getAnyRelocationPCRel(RE))
1960 op_info->Value -= Pc + Offset + Size;
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00001961 Expected<StringRef> SymName = Symbol.getName();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00001962 if (!SymName)
1963 report_error(info->O->getFileName(), SymName.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00001964 const char *name = SymName->data();
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001965 unsigned Type = info->O->getAnyRelocationType(RE);
1966 if (Type == MachO::X86_64_RELOC_SUBTRACTOR) {
1967 DataRefImpl RelNext = Rel;
1968 info->O->moveRelocationNext(RelNext);
1969 MachO::any_relocation_info RENext = info->O->getRelocation(RelNext);
1970 unsigned TypeNext = info->O->getAnyRelocationType(RENext);
1971 bool isExternNext = info->O->getPlainRelocationExternal(RENext);
1972 unsigned SymbolNum = info->O->getPlainRelocationSymbolNum(RENext);
1973 if (TypeNext == MachO::X86_64_RELOC_UNSIGNED && isExternNext) {
1974 op_info->SubtractSymbol.Present = 1;
1975 op_info->SubtractSymbol.Name = name;
1976 symbol_iterator RelocSymNext = info->O->getSymbolByIndex(SymbolNum);
1977 Symbol = *RelocSymNext;
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00001978 Expected<StringRef> SymNameNext = Symbol.getName();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00001979 if (!SymNameNext)
1980 report_error(info->O->getFileName(), SymNameNext.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00001981 name = SymNameNext->data();
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001982 }
1983 }
1984 // TODO: add the VariantKinds to op_info->VariantKind for relocation types
1985 // like: X86_64_RELOC_TLV, X86_64_RELOC_GOT_LOAD and X86_64_RELOC_GOT.
1986 op_info->AddSymbol.Present = 1;
1987 op_info->AddSymbol.Name = name;
1988 return 1;
1989 }
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001990 return 0;
David Blaikie33dd45d02015-03-23 18:39:02 +00001991 }
1992 if (Arch == Triple::arm) {
Kevin Enderby930fdc72014-11-06 19:00:13 +00001993 if (Offset != 0 || (Size != 4 && Size != 2))
1994 return 0;
Kevin Enderbyd90a4172015-10-10 00:05:01 +00001995 if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
1996 // TODO:
1997 // Search the external relocation entries of a fully linked image
1998 // (if any) for an entry that matches this segment offset.
1999 // uint32_t seg_offset = (Pc + Offset);
2000 return 0;
2001 }
2002 // In MH_OBJECT filetypes search the section's relocation entries (if any)
2003 // for an entry for this section offset.
Kevin Enderby930fdc72014-11-06 19:00:13 +00002004 uint32_t sect_addr = info->S.getAddress();
2005 uint32_t sect_offset = (Pc + Offset) - sect_addr;
Kevin Enderby930fdc72014-11-06 19:00:13 +00002006 DataRefImpl Rel;
2007 MachO::any_relocation_info RE;
2008 bool isExtern = false;
2009 SymbolRef Symbol;
2010 bool r_scattered = false;
2011 uint32_t r_value, pair_r_value, r_type, r_length, other_half;
David Blaikie33dd45d02015-03-23 18:39:02 +00002012 auto Reloc =
David Majnemer562e8292016-08-12 00:18:03 +00002013 find_if(info->S.relocations(), [&](const RelocationRef &Reloc) {
2014 uint64_t RelocOffset = Reloc.getOffset();
2015 return RelocOffset == sect_offset;
2016 });
David Blaikie33dd45d02015-03-23 18:39:02 +00002017
2018 if (Reloc == info->S.relocations().end())
2019 return 0;
2020
2021 Rel = Reloc->getRawDataRefImpl();
2022 RE = info->O->getRelocation(Rel);
2023 r_length = info->O->getAnyRelocationLength(RE);
2024 r_scattered = info->O->isRelocationScattered(RE);
2025 if (r_scattered) {
2026 r_value = info->O->getScatteredRelocationValue(RE);
2027 r_type = info->O->getScatteredRelocationType(RE);
2028 } else {
2029 r_type = info->O->getAnyRelocationType(RE);
2030 isExtern = info->O->getPlainRelocationExternal(RE);
2031 if (isExtern) {
2032 symbol_iterator RelocSym = Reloc->getSymbol();
2033 Symbol = *RelocSym;
Kevin Enderby930fdc72014-11-06 19:00:13 +00002034 }
2035 }
David Blaikie33dd45d02015-03-23 18:39:02 +00002036 if (r_type == MachO::ARM_RELOC_HALF ||
2037 r_type == MachO::ARM_RELOC_SECTDIFF ||
2038 r_type == MachO::ARM_RELOC_LOCAL_SECTDIFF ||
2039 r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
2040 DataRefImpl RelNext = Rel;
2041 info->O->moveRelocationNext(RelNext);
2042 MachO::any_relocation_info RENext;
2043 RENext = info->O->getRelocation(RelNext);
2044 other_half = info->O->getAnyRelocationAddress(RENext) & 0xffff;
2045 if (info->O->isRelocationScattered(RENext))
2046 pair_r_value = info->O->getScatteredRelocationValue(RENext);
2047 }
2048
2049 if (isExtern) {
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00002050 Expected<StringRef> SymName = Symbol.getName();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00002051 if (!SymName)
2052 report_error(info->O->getFileName(), SymName.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00002053 const char *name = SymName->data();
Kevin Enderby930fdc72014-11-06 19:00:13 +00002054 op_info->AddSymbol.Present = 1;
2055 op_info->AddSymbol.Name = name;
Sylvestre Ledru648cced2015-02-05 17:00:23 +00002056 switch (r_type) {
2057 case MachO::ARM_RELOC_HALF:
2058 if ((r_length & 0x1) == 1) {
2059 op_info->Value = value << 16 | other_half;
2060 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
2061 } else {
2062 op_info->Value = other_half << 16 | value;
2063 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
Sylvestre Ledrufe0c7ad2015-02-05 16:35:44 +00002064 }
Sylvestre Ledru648cced2015-02-05 17:00:23 +00002065 break;
2066 default:
2067 break;
Kevin Enderby930fdc72014-11-06 19:00:13 +00002068 }
2069 return 1;
2070 }
2071 // If we have a branch that is not an external relocation entry then
2072 // return 0 so the code in tryAddingSymbolicOperand() can use the
2073 // SymbolLookUp call back with the branch target address to look up the
Simon Pilgrimdae11f72016-11-20 13:31:13 +00002074 // symbol and possibility add an annotation for a symbol stub.
David Blaikie33dd45d02015-03-23 18:39:02 +00002075 if (isExtern == 0 && (r_type == MachO::ARM_RELOC_BR24 ||
2076 r_type == MachO::ARM_THUMB_RELOC_BR22))
Kevin Enderby930fdc72014-11-06 19:00:13 +00002077 return 0;
2078
2079 uint32_t offset = 0;
David Blaikie33dd45d02015-03-23 18:39:02 +00002080 if (r_type == MachO::ARM_RELOC_HALF ||
2081 r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
2082 if ((r_length & 0x1) == 1)
2083 value = value << 16 | other_half;
2084 else
2085 value = other_half << 16 | value;
2086 }
2087 if (r_scattered && (r_type != MachO::ARM_RELOC_HALF &&
2088 r_type != MachO::ARM_RELOC_HALF_SECTDIFF)) {
2089 offset = value - r_value;
2090 value = r_value;
Kevin Enderby930fdc72014-11-06 19:00:13 +00002091 }
2092
David Blaikie33dd45d02015-03-23 18:39:02 +00002093 if (r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
Kevin Enderby930fdc72014-11-06 19:00:13 +00002094 if ((r_length & 0x1) == 1)
2095 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
2096 else
2097 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
Kevin Enderbyf6d25852015-01-31 00:37:11 +00002098 const char *add = GuessSymbolName(r_value, info->AddrMap);
2099 const char *sub = GuessSymbolName(pair_r_value, info->AddrMap);
Kevin Enderby930fdc72014-11-06 19:00:13 +00002100 int32_t offset = value - (r_value - pair_r_value);
2101 op_info->AddSymbol.Present = 1;
2102 if (add != nullptr)
2103 op_info->AddSymbol.Name = add;
2104 else
2105 op_info->AddSymbol.Value = r_value;
2106 op_info->SubtractSymbol.Present = 1;
2107 if (sub != nullptr)
2108 op_info->SubtractSymbol.Name = sub;
2109 else
2110 op_info->SubtractSymbol.Value = pair_r_value;
2111 op_info->Value = offset;
2112 return 1;
2113 }
2114
Kevin Enderby930fdc72014-11-06 19:00:13 +00002115 op_info->AddSymbol.Present = 1;
2116 op_info->Value = offset;
David Blaikie33dd45d02015-03-23 18:39:02 +00002117 if (r_type == MachO::ARM_RELOC_HALF) {
2118 if ((r_length & 0x1) == 1)
2119 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
2120 else
2121 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
Kevin Enderby930fdc72014-11-06 19:00:13 +00002122 }
Kevin Enderbyf6d25852015-01-31 00:37:11 +00002123 const char *add = GuessSymbolName(value, info->AddrMap);
Kevin Enderby930fdc72014-11-06 19:00:13 +00002124 if (add != nullptr) {
2125 op_info->AddSymbol.Name = add;
2126 return 1;
2127 }
2128 op_info->AddSymbol.Value = value;
2129 return 1;
David Blaikie33dd45d02015-03-23 18:39:02 +00002130 }
2131 if (Arch == Triple::aarch64) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002132 if (Offset != 0 || Size != 4)
2133 return 0;
Kevin Enderbyd90a4172015-10-10 00:05:01 +00002134 if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
2135 // TODO:
2136 // Search the external relocation entries of a fully linked image
2137 // (if any) for an entry that matches this segment offset.
2138 // uint64_t seg_offset = (Pc + Offset);
2139 return 0;
2140 }
2141 // In MH_OBJECT filetypes search the section's relocation entries (if any)
2142 // for an entry for this section offset.
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002143 uint64_t sect_addr = info->S.getAddress();
2144 uint64_t sect_offset = (Pc + Offset) - sect_addr;
David Blaikie33dd45d02015-03-23 18:39:02 +00002145 auto Reloc =
David Majnemer562e8292016-08-12 00:18:03 +00002146 find_if(info->S.relocations(), [&](const RelocationRef &Reloc) {
2147 uint64_t RelocOffset = Reloc.getOffset();
2148 return RelocOffset == sect_offset;
2149 });
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002150
David Blaikie33dd45d02015-03-23 18:39:02 +00002151 if (Reloc == info->S.relocations().end())
2152 return 0;
2153
2154 DataRefImpl Rel = Reloc->getRawDataRefImpl();
2155 MachO::any_relocation_info RE = info->O->getRelocation(Rel);
2156 uint32_t r_type = info->O->getAnyRelocationType(RE);
2157 if (r_type == MachO::ARM64_RELOC_ADDEND) {
2158 DataRefImpl RelNext = Rel;
2159 info->O->moveRelocationNext(RelNext);
2160 MachO::any_relocation_info RENext = info->O->getRelocation(RelNext);
2161 if (value == 0) {
2162 value = info->O->getPlainRelocationSymbolNum(RENext);
2163 op_info->Value = value;
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002164 }
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002165 }
David Blaikie33dd45d02015-03-23 18:39:02 +00002166 // NOTE: Scattered relocations don't exist on arm64.
2167 if (!info->O->getPlainRelocationExternal(RE))
2168 return 0;
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00002169 Expected<StringRef> SymName = Reloc->getSymbol()->getName();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00002170 if (!SymName)
2171 report_error(info->O->getFileName(), SymName.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00002172 const char *name = SymName->data();
David Blaikie33dd45d02015-03-23 18:39:02 +00002173 op_info->AddSymbol.Present = 1;
2174 op_info->AddSymbol.Name = name;
2175
2176 switch (r_type) {
2177 case MachO::ARM64_RELOC_PAGE21:
2178 /* @page */
2179 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_PAGE;
2180 break;
2181 case MachO::ARM64_RELOC_PAGEOFF12:
2182 /* @pageoff */
2183 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_PAGEOFF;
2184 break;
2185 case MachO::ARM64_RELOC_GOT_LOAD_PAGE21:
2186 /* @gotpage */
2187 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_GOTPAGE;
2188 break;
2189 case MachO::ARM64_RELOC_GOT_LOAD_PAGEOFF12:
2190 /* @gotpageoff */
2191 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_GOTPAGEOFF;
2192 break;
2193 case MachO::ARM64_RELOC_TLVP_LOAD_PAGE21:
2194 /* @tvlppage is not implemented in llvm-mc */
2195 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_TLVP;
2196 break;
2197 case MachO::ARM64_RELOC_TLVP_LOAD_PAGEOFF12:
2198 /* @tvlppageoff is not implemented in llvm-mc */
2199 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_TLVOFF;
2200 break;
2201 default:
2202 case MachO::ARM64_RELOC_BRANCH26:
2203 op_info->VariantKind = LLVMDisassembler_VariantKind_None;
2204 break;
2205 }
2206 return 1;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002207 }
David Blaikie33dd45d02015-03-23 18:39:02 +00002208 return 0;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002209}
2210
Kevin Enderbybf246f52014-09-24 23:08:22 +00002211// GuessCstringPointer is passed the address of what might be a pointer to a
2212// literal string in a cstring section. If that address is in a cstring section
2213// it returns a pointer to that string. Else it returns nullptr.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00002214static const char *GuessCstringPointer(uint64_t ReferenceValue,
2215 struct DisassembleInfo *info) {
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00002216 for (const auto &Load : info->O->load_commands()) {
Kevin Enderbybf246f52014-09-24 23:08:22 +00002217 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
2218 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
2219 for (unsigned J = 0; J < Seg.nsects; ++J) {
2220 MachO::section_64 Sec = info->O->getSection64(Load, J);
2221 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
2222 if (section_type == MachO::S_CSTRING_LITERALS &&
2223 ReferenceValue >= Sec.addr &&
2224 ReferenceValue < Sec.addr + Sec.size) {
2225 uint64_t sect_offset = ReferenceValue - Sec.addr;
2226 uint64_t object_offset = Sec.offset + sect_offset;
2227 StringRef MachOContents = info->O->getData();
2228 uint64_t object_size = MachOContents.size();
2229 const char *object_addr = (const char *)MachOContents.data();
2230 if (object_offset < object_size) {
2231 const char *name = object_addr + object_offset;
2232 return name;
2233 } else {
2234 return nullptr;
2235 }
2236 }
2237 }
2238 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
2239 MachO::segment_command Seg = info->O->getSegmentLoadCommand(Load);
2240 for (unsigned J = 0; J < Seg.nsects; ++J) {
2241 MachO::section Sec = info->O->getSection(Load, J);
2242 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
2243 if (section_type == MachO::S_CSTRING_LITERALS &&
2244 ReferenceValue >= Sec.addr &&
2245 ReferenceValue < Sec.addr + Sec.size) {
2246 uint64_t sect_offset = ReferenceValue - Sec.addr;
2247 uint64_t object_offset = Sec.offset + sect_offset;
2248 StringRef MachOContents = info->O->getData();
2249 uint64_t object_size = MachOContents.size();
2250 const char *object_addr = (const char *)MachOContents.data();
2251 if (object_offset < object_size) {
2252 const char *name = object_addr + object_offset;
2253 return name;
2254 } else {
2255 return nullptr;
2256 }
2257 }
2258 }
2259 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00002260 }
2261 return nullptr;
2262}
2263
Kevin Enderby85974882014-09-26 22:20:44 +00002264// GuessIndirectSymbol returns the name of the indirect symbol for the
2265// ReferenceValue passed in or nullptr. This is used when ReferenceValue maybe
2266// an address of a symbol stub or a lazy or non-lazy pointer to associate the
2267// symbol name being referenced by the stub or pointer.
2268static const char *GuessIndirectSymbol(uint64_t ReferenceValue,
2269 struct DisassembleInfo *info) {
Kevin Enderby85974882014-09-26 22:20:44 +00002270 MachO::dysymtab_command Dysymtab = info->O->getDysymtabLoadCommand();
2271 MachO::symtab_command Symtab = info->O->getSymtabLoadCommand();
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00002272 for (const auto &Load : info->O->load_commands()) {
Kevin Enderby85974882014-09-26 22:20:44 +00002273 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
2274 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
2275 for (unsigned J = 0; J < Seg.nsects; ++J) {
2276 MachO::section_64 Sec = info->O->getSection64(Load, J);
2277 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
2278 if ((section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
2279 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
2280 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
2281 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
2282 section_type == MachO::S_SYMBOL_STUBS) &&
2283 ReferenceValue >= Sec.addr &&
2284 ReferenceValue < Sec.addr + Sec.size) {
2285 uint32_t stride;
2286 if (section_type == MachO::S_SYMBOL_STUBS)
2287 stride = Sec.reserved2;
2288 else
2289 stride = 8;
2290 if (stride == 0)
2291 return nullptr;
2292 uint32_t index = Sec.reserved1 + (ReferenceValue - Sec.addr) / stride;
2293 if (index < Dysymtab.nindirectsyms) {
2294 uint32_t indirect_symbol =
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002295 info->O->getIndirectSymbolTableEntry(Dysymtab, index);
Kevin Enderby85974882014-09-26 22:20:44 +00002296 if (indirect_symbol < Symtab.nsyms) {
2297 symbol_iterator Sym = info->O->getSymbolByIndex(indirect_symbol);
2298 SymbolRef Symbol = *Sym;
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00002299 Expected<StringRef> SymName = Symbol.getName();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00002300 if (!SymName)
2301 report_error(info->O->getFileName(), SymName.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00002302 const char *name = SymName->data();
Kevin Enderby85974882014-09-26 22:20:44 +00002303 return name;
2304 }
2305 }
2306 }
2307 }
2308 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
2309 MachO::segment_command Seg = info->O->getSegmentLoadCommand(Load);
2310 for (unsigned J = 0; J < Seg.nsects; ++J) {
2311 MachO::section Sec = info->O->getSection(Load, J);
2312 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
2313 if ((section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
2314 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
2315 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
2316 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
2317 section_type == MachO::S_SYMBOL_STUBS) &&
2318 ReferenceValue >= Sec.addr &&
2319 ReferenceValue < Sec.addr + Sec.size) {
2320 uint32_t stride;
2321 if (section_type == MachO::S_SYMBOL_STUBS)
2322 stride = Sec.reserved2;
2323 else
2324 stride = 4;
2325 if (stride == 0)
2326 return nullptr;
2327 uint32_t index = Sec.reserved1 + (ReferenceValue - Sec.addr) / stride;
2328 if (index < Dysymtab.nindirectsyms) {
2329 uint32_t indirect_symbol =
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002330 info->O->getIndirectSymbolTableEntry(Dysymtab, index);
Kevin Enderby85974882014-09-26 22:20:44 +00002331 if (indirect_symbol < Symtab.nsyms) {
2332 symbol_iterator Sym = info->O->getSymbolByIndex(indirect_symbol);
2333 SymbolRef Symbol = *Sym;
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00002334 Expected<StringRef> SymName = Symbol.getName();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00002335 if (!SymName)
2336 report_error(info->O->getFileName(), SymName.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00002337 const char *name = SymName->data();
Kevin Enderby85974882014-09-26 22:20:44 +00002338 return name;
2339 }
2340 }
2341 }
2342 }
2343 }
Kevin Enderby85974882014-09-26 22:20:44 +00002344 }
2345 return nullptr;
2346}
2347
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002348// method_reference() is called passing it the ReferenceName that might be
2349// a reference it to an Objective-C method call. If so then it allocates and
2350// assembles a method call string with the values last seen and saved in
2351// the DisassembleInfo's class_name and selector_name fields. This is saved
2352// into the method field of the info and any previous string is free'ed.
2353// Then the class_name field in the info is set to nullptr. The method call
2354// string is set into ReferenceName and ReferenceType is set to
2355// LLVMDisassembler_ReferenceType_Out_Objc_Message. If this not a method call
2356// then both ReferenceType and ReferenceName are left unchanged.
2357static void method_reference(struct DisassembleInfo *info,
2358 uint64_t *ReferenceType,
2359 const char **ReferenceName) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002360 unsigned int Arch = info->O->getArch();
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002361 if (*ReferenceName != nullptr) {
2362 if (strcmp(*ReferenceName, "_objc_msgSend") == 0) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002363 if (info->selector_name != nullptr) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002364 if (info->method != nullptr)
2365 free(info->method);
2366 if (info->class_name != nullptr) {
2367 info->method = (char *)malloc(5 + strlen(info->class_name) +
2368 strlen(info->selector_name));
2369 if (info->method != nullptr) {
2370 strcpy(info->method, "+[");
2371 strcat(info->method, info->class_name);
2372 strcat(info->method, " ");
2373 strcat(info->method, info->selector_name);
2374 strcat(info->method, "]");
2375 *ReferenceName = info->method;
2376 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
2377 }
2378 } else {
2379 info->method = (char *)malloc(9 + strlen(info->selector_name));
2380 if (info->method != nullptr) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002381 if (Arch == Triple::x86_64)
2382 strcpy(info->method, "-[%rdi ");
2383 else if (Arch == Triple::aarch64)
2384 strcpy(info->method, "-[x0 ");
2385 else
2386 strcpy(info->method, "-[r? ");
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002387 strcat(info->method, info->selector_name);
2388 strcat(info->method, "]");
2389 *ReferenceName = info->method;
2390 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
2391 }
2392 }
2393 info->class_name = nullptr;
2394 }
2395 } else if (strcmp(*ReferenceName, "_objc_msgSendSuper2") == 0) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002396 if (info->selector_name != nullptr) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002397 if (info->method != nullptr)
2398 free(info->method);
2399 info->method = (char *)malloc(17 + strlen(info->selector_name));
2400 if (info->method != nullptr) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002401 if (Arch == Triple::x86_64)
2402 strcpy(info->method, "-[[%rdi super] ");
2403 else if (Arch == Triple::aarch64)
2404 strcpy(info->method, "-[[x0 super] ");
2405 else
2406 strcpy(info->method, "-[[r? super] ");
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002407 strcat(info->method, info->selector_name);
2408 strcat(info->method, "]");
2409 *ReferenceName = info->method;
2410 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
2411 }
2412 info->class_name = nullptr;
2413 }
2414 }
2415 }
2416}
2417
2418// GuessPointerPointer() is passed the address of what might be a pointer to
2419// a reference to an Objective-C class, selector, message ref or cfstring.
2420// If so the value of the pointer is returned and one of the booleans are set
2421// to true. If not zero is returned and all the booleans are set to false.
2422static uint64_t GuessPointerPointer(uint64_t ReferenceValue,
2423 struct DisassembleInfo *info,
2424 bool &classref, bool &selref, bool &msgref,
2425 bool &cfstring) {
2426 classref = false;
2427 selref = false;
2428 msgref = false;
2429 cfstring = false;
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00002430 for (const auto &Load : info->O->load_commands()) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002431 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
2432 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
2433 for (unsigned J = 0; J < Seg.nsects; ++J) {
2434 MachO::section_64 Sec = info->O->getSection64(Load, J);
2435 if ((strncmp(Sec.sectname, "__objc_selrefs", 16) == 0 ||
2436 strncmp(Sec.sectname, "__objc_classrefs", 16) == 0 ||
2437 strncmp(Sec.sectname, "__objc_superrefs", 16) == 0 ||
2438 strncmp(Sec.sectname, "__objc_msgrefs", 16) == 0 ||
2439 strncmp(Sec.sectname, "__cfstring", 16) == 0) &&
2440 ReferenceValue >= Sec.addr &&
2441 ReferenceValue < Sec.addr + Sec.size) {
2442 uint64_t sect_offset = ReferenceValue - Sec.addr;
2443 uint64_t object_offset = Sec.offset + sect_offset;
2444 StringRef MachOContents = info->O->getData();
2445 uint64_t object_size = MachOContents.size();
2446 const char *object_addr = (const char *)MachOContents.data();
2447 if (object_offset < object_size) {
2448 uint64_t pointer_value;
2449 memcpy(&pointer_value, object_addr + object_offset,
2450 sizeof(uint64_t));
2451 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
2452 sys::swapByteOrder(pointer_value);
2453 if (strncmp(Sec.sectname, "__objc_selrefs", 16) == 0)
2454 selref = true;
2455 else if (strncmp(Sec.sectname, "__objc_classrefs", 16) == 0 ||
2456 strncmp(Sec.sectname, "__objc_superrefs", 16) == 0)
2457 classref = true;
2458 else if (strncmp(Sec.sectname, "__objc_msgrefs", 16) == 0 &&
2459 ReferenceValue + 8 < Sec.addr + Sec.size) {
2460 msgref = true;
2461 memcpy(&pointer_value, object_addr + object_offset + 8,
2462 sizeof(uint64_t));
2463 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
2464 sys::swapByteOrder(pointer_value);
2465 } else if (strncmp(Sec.sectname, "__cfstring", 16) == 0)
2466 cfstring = true;
2467 return pointer_value;
2468 } else {
2469 return 0;
2470 }
2471 }
2472 }
2473 }
2474 // TODO: Look for LC_SEGMENT for 32-bit Mach-O files.
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002475 }
2476 return 0;
2477}
2478
2479// get_pointer_64 returns a pointer to the bytes in the object file at the
2480// Address from a section in the Mach-O file. And indirectly returns the
2481// offset into the section, number of bytes left in the section past the offset
2482// and which section is was being referenced. If the Address is not in a
2483// section nullptr is returned.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00002484static const char *get_pointer_64(uint64_t Address, uint32_t &offset,
2485 uint32_t &left, SectionRef &S,
Kevin Enderby846c0002015-04-16 17:19:59 +00002486 DisassembleInfo *info,
2487 bool objc_only = false) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002488 offset = 0;
2489 left = 0;
2490 S = SectionRef();
2491 for (unsigned SectIdx = 0; SectIdx != info->Sections->size(); SectIdx++) {
2492 uint64_t SectAddress = ((*(info->Sections))[SectIdx]).getAddress();
2493 uint64_t SectSize = ((*(info->Sections))[SectIdx]).getSize();
Kevin Enderby46e642f2015-10-08 22:50:55 +00002494 if (SectSize == 0)
2495 continue;
Kevin Enderby846c0002015-04-16 17:19:59 +00002496 if (objc_only) {
2497 StringRef SectName;
2498 ((*(info->Sections))[SectIdx]).getName(SectName);
2499 DataRefImpl Ref = ((*(info->Sections))[SectIdx]).getRawDataRefImpl();
2500 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
2501 if (SegName != "__OBJC" && SectName != "__cstring")
2502 continue;
2503 }
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002504 if (Address >= SectAddress && Address < SectAddress + SectSize) {
2505 S = (*(info->Sections))[SectIdx];
2506 offset = Address - SectAddress;
2507 left = SectSize - offset;
2508 StringRef SectContents;
2509 ((*(info->Sections))[SectIdx]).getContents(SectContents);
2510 return SectContents.data() + offset;
2511 }
2512 }
2513 return nullptr;
2514}
2515
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002516static const char *get_pointer_32(uint32_t Address, uint32_t &offset,
2517 uint32_t &left, SectionRef &S,
Kevin Enderby846c0002015-04-16 17:19:59 +00002518 DisassembleInfo *info,
2519 bool objc_only = false) {
2520 return get_pointer_64(Address, offset, left, S, info, objc_only);
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002521}
2522
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002523// get_symbol_64() returns the name of a symbol (or nullptr) and the address of
2524// the symbol indirectly through n_value. Based on the relocation information
2525// for the specified section offset in the specified section reference.
Kevin Enderby0fc11822015-04-01 20:57:01 +00002526// If no relocation information is found and a non-zero ReferenceValue for the
2527// symbol is passed, look up that address in the info's AddrMap.
Rafael Espindolad7a32ea2015-06-24 10:20:30 +00002528static const char *get_symbol_64(uint32_t sect_offset, SectionRef S,
2529 DisassembleInfo *info, uint64_t &n_value,
Rafael Espindolabe8b0ea2015-07-07 17:12:59 +00002530 uint64_t ReferenceValue = 0) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002531 n_value = 0;
David Blaikie33dd45d02015-03-23 18:39:02 +00002532 if (!info->verbose)
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002533 return nullptr;
2534
2535 // See if there is an external relocation entry at the sect_offset.
2536 bool reloc_found = false;
2537 DataRefImpl Rel;
2538 MachO::any_relocation_info RE;
2539 bool isExtern = false;
2540 SymbolRef Symbol;
2541 for (const RelocationRef &Reloc : S.relocations()) {
Rafael Espindola96d071c2015-06-29 23:29:12 +00002542 uint64_t RelocOffset = Reloc.getOffset();
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002543 if (RelocOffset == sect_offset) {
2544 Rel = Reloc.getRawDataRefImpl();
2545 RE = info->O->getRelocation(Rel);
2546 if (info->O->isRelocationScattered(RE))
2547 continue;
2548 isExtern = info->O->getPlainRelocationExternal(RE);
2549 if (isExtern) {
2550 symbol_iterator RelocSym = Reloc.getSymbol();
2551 Symbol = *RelocSym;
2552 }
2553 reloc_found = true;
2554 break;
2555 }
2556 }
2557 // If there is an external relocation entry for a symbol in this section
2558 // at this section_offset then use that symbol's value for the n_value
2559 // and return its name.
2560 const char *SymbolName = nullptr;
2561 if (reloc_found && isExtern) {
Rafael Espindoladea00162015-07-03 17:44:18 +00002562 n_value = Symbol.getValue();
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00002563 Expected<StringRef> NameOrError = Symbol.getName();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00002564 if (!NameOrError)
2565 report_error(info->O->getFileName(), NameOrError.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00002566 StringRef Name = *NameOrError;
2567 if (!Name.empty()) {
2568 SymbolName = Name.data();
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002569 return SymbolName;
2570 }
2571 }
2572
2573 // TODO: For fully linked images, look through the external relocation
2574 // entries off the dynamic symtab command. For these the r_offset is from the
2575 // start of the first writeable segment in the Mach-O file. So the offset
2576 // to this section from that segment is passed to this routine by the caller,
2577 // as the database_offset. Which is the difference of the section's starting
2578 // address and the first writable segment.
2579 //
2580 // NOTE: need add passing the database_offset to this routine.
2581
Kevin Enderby0fc11822015-04-01 20:57:01 +00002582 // We did not find an external relocation entry so look up the ReferenceValue
2583 // as an address of a symbol and if found return that symbol's name.
Rafael Espindolabe8b0ea2015-07-07 17:12:59 +00002584 SymbolName = GuessSymbolName(ReferenceValue, info->AddrMap);
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002585
2586 return SymbolName;
2587}
2588
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002589static const char *get_symbol_32(uint32_t sect_offset, SectionRef S,
2590 DisassembleInfo *info,
2591 uint32_t ReferenceValue) {
2592 uint64_t n_value64;
2593 return get_symbol_64(sect_offset, S, info, n_value64, ReferenceValue);
2594}
2595
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002596// These are structs in the Objective-C meta data and read to produce the
2597// comments for disassembly. While these are part of the ABI they are no
Zachary Turner264b5d92017-06-07 03:48:56 +00002598// public defintions. So the are here not in include/llvm/BinaryFormat/MachO.h
2599// .
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002600
2601// The cfstring object in a 64-bit Mach-O file.
2602struct cfstring64_t {
2603 uint64_t isa; // class64_t * (64-bit pointer)
2604 uint64_t flags; // flag bits
2605 uint64_t characters; // char * (64-bit pointer)
2606 uint64_t length; // number of non-NULL characters in above
2607};
2608
2609// The class object in a 64-bit Mach-O file.
2610struct class64_t {
2611 uint64_t isa; // class64_t * (64-bit pointer)
2612 uint64_t superclass; // class64_t * (64-bit pointer)
2613 uint64_t cache; // Cache (64-bit pointer)
2614 uint64_t vtable; // IMP * (64-bit pointer)
2615 uint64_t data; // class_ro64_t * (64-bit pointer)
2616};
2617
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002618struct class32_t {
2619 uint32_t isa; /* class32_t * (32-bit pointer) */
2620 uint32_t superclass; /* class32_t * (32-bit pointer) */
2621 uint32_t cache; /* Cache (32-bit pointer) */
2622 uint32_t vtable; /* IMP * (32-bit pointer) */
2623 uint32_t data; /* class_ro32_t * (32-bit pointer) */
2624};
2625
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002626struct class_ro64_t {
2627 uint32_t flags;
2628 uint32_t instanceStart;
2629 uint32_t instanceSize;
2630 uint32_t reserved;
2631 uint64_t ivarLayout; // const uint8_t * (64-bit pointer)
2632 uint64_t name; // const char * (64-bit pointer)
2633 uint64_t baseMethods; // const method_list_t * (64-bit pointer)
2634 uint64_t baseProtocols; // const protocol_list_t * (64-bit pointer)
2635 uint64_t ivars; // const ivar_list_t * (64-bit pointer)
2636 uint64_t weakIvarLayout; // const uint8_t * (64-bit pointer)
2637 uint64_t baseProperties; // const struct objc_property_list (64-bit pointer)
2638};
2639
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002640struct class_ro32_t {
2641 uint32_t flags;
2642 uint32_t instanceStart;
2643 uint32_t instanceSize;
2644 uint32_t ivarLayout; /* const uint8_t * (32-bit pointer) */
2645 uint32_t name; /* const char * (32-bit pointer) */
2646 uint32_t baseMethods; /* const method_list_t * (32-bit pointer) */
2647 uint32_t baseProtocols; /* const protocol_list_t * (32-bit pointer) */
2648 uint32_t ivars; /* const ivar_list_t * (32-bit pointer) */
2649 uint32_t weakIvarLayout; /* const uint8_t * (32-bit pointer) */
2650 uint32_t baseProperties; /* const struct objc_property_list *
2651 (32-bit pointer) */
2652};
2653
2654/* Values for class_ro{64,32}_t->flags */
Kevin Enderby0fc11822015-04-01 20:57:01 +00002655#define RO_META (1 << 0)
2656#define RO_ROOT (1 << 1)
2657#define RO_HAS_CXX_STRUCTORS (1 << 2)
2658
2659struct method_list64_t {
2660 uint32_t entsize;
2661 uint32_t count;
2662 /* struct method64_t first; These structures follow inline */
2663};
2664
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002665struct method_list32_t {
2666 uint32_t entsize;
2667 uint32_t count;
2668 /* struct method32_t first; These structures follow inline */
2669};
2670
Kevin Enderby0fc11822015-04-01 20:57:01 +00002671struct method64_t {
2672 uint64_t name; /* SEL (64-bit pointer) */
2673 uint64_t types; /* const char * (64-bit pointer) */
2674 uint64_t imp; /* IMP (64-bit pointer) */
2675};
2676
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002677struct method32_t {
2678 uint32_t name; /* SEL (32-bit pointer) */
2679 uint32_t types; /* const char * (32-bit pointer) */
2680 uint32_t imp; /* IMP (32-bit pointer) */
2681};
2682
Kevin Enderby0fc11822015-04-01 20:57:01 +00002683struct protocol_list64_t {
2684 uint64_t count; /* uintptr_t (a 64-bit value) */
2685 /* struct protocol64_t * list[0]; These pointers follow inline */
2686};
2687
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002688struct protocol_list32_t {
2689 uint32_t count; /* uintptr_t (a 32-bit value) */
2690 /* struct protocol32_t * list[0]; These pointers follow inline */
2691};
2692
Kevin Enderby0fc11822015-04-01 20:57:01 +00002693struct protocol64_t {
2694 uint64_t isa; /* id * (64-bit pointer) */
2695 uint64_t name; /* const char * (64-bit pointer) */
2696 uint64_t protocols; /* struct protocol_list64_t *
2697 (64-bit pointer) */
2698 uint64_t instanceMethods; /* method_list_t * (64-bit pointer) */
2699 uint64_t classMethods; /* method_list_t * (64-bit pointer) */
2700 uint64_t optionalInstanceMethods; /* method_list_t * (64-bit pointer) */
2701 uint64_t optionalClassMethods; /* method_list_t * (64-bit pointer) */
2702 uint64_t instanceProperties; /* struct objc_property_list *
2703 (64-bit pointer) */
2704};
2705
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002706struct protocol32_t {
2707 uint32_t isa; /* id * (32-bit pointer) */
2708 uint32_t name; /* const char * (32-bit pointer) */
2709 uint32_t protocols; /* struct protocol_list_t *
2710 (32-bit pointer) */
2711 uint32_t instanceMethods; /* method_list_t * (32-bit pointer) */
2712 uint32_t classMethods; /* method_list_t * (32-bit pointer) */
2713 uint32_t optionalInstanceMethods; /* method_list_t * (32-bit pointer) */
2714 uint32_t optionalClassMethods; /* method_list_t * (32-bit pointer) */
2715 uint32_t instanceProperties; /* struct objc_property_list *
2716 (32-bit pointer) */
2717};
2718
Kevin Enderby0fc11822015-04-01 20:57:01 +00002719struct ivar_list64_t {
2720 uint32_t entsize;
2721 uint32_t count;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002722 /* struct ivar64_t first; These structures follow inline */
2723};
2724
2725struct ivar_list32_t {
2726 uint32_t entsize;
2727 uint32_t count;
2728 /* struct ivar32_t first; These structures follow inline */
Kevin Enderby0fc11822015-04-01 20:57:01 +00002729};
2730
2731struct ivar64_t {
2732 uint64_t offset; /* uintptr_t * (64-bit pointer) */
2733 uint64_t name; /* const char * (64-bit pointer) */
2734 uint64_t type; /* const char * (64-bit pointer) */
2735 uint32_t alignment;
2736 uint32_t size;
2737};
2738
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002739struct ivar32_t {
2740 uint32_t offset; /* uintptr_t * (32-bit pointer) */
2741 uint32_t name; /* const char * (32-bit pointer) */
2742 uint32_t type; /* const char * (32-bit pointer) */
2743 uint32_t alignment;
2744 uint32_t size;
2745};
2746
Kevin Enderby0fc11822015-04-01 20:57:01 +00002747struct objc_property_list64 {
2748 uint32_t entsize;
2749 uint32_t count;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002750 /* struct objc_property64 first; These structures follow inline */
2751};
2752
2753struct objc_property_list32 {
2754 uint32_t entsize;
2755 uint32_t count;
2756 /* struct objc_property32 first; These structures follow inline */
Kevin Enderby0fc11822015-04-01 20:57:01 +00002757};
2758
2759struct objc_property64 {
2760 uint64_t name; /* const char * (64-bit pointer) */
2761 uint64_t attributes; /* const char * (64-bit pointer) */
2762};
2763
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002764struct objc_property32 {
2765 uint32_t name; /* const char * (32-bit pointer) */
2766 uint32_t attributes; /* const char * (32-bit pointer) */
2767};
2768
Kevin Enderby0fc11822015-04-01 20:57:01 +00002769struct category64_t {
2770 uint64_t name; /* const char * (64-bit pointer) */
2771 uint64_t cls; /* struct class_t * (64-bit pointer) */
2772 uint64_t instanceMethods; /* struct method_list_t * (64-bit pointer) */
2773 uint64_t classMethods; /* struct method_list_t * (64-bit pointer) */
2774 uint64_t protocols; /* struct protocol_list_t * (64-bit pointer) */
2775 uint64_t instanceProperties; /* struct objc_property_list *
2776 (64-bit pointer) */
2777};
2778
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002779struct category32_t {
2780 uint32_t name; /* const char * (32-bit pointer) */
2781 uint32_t cls; /* struct class_t * (32-bit pointer) */
2782 uint32_t instanceMethods; /* struct method_list_t * (32-bit pointer) */
2783 uint32_t classMethods; /* struct method_list_t * (32-bit pointer) */
2784 uint32_t protocols; /* struct protocol_list_t * (32-bit pointer) */
2785 uint32_t instanceProperties; /* struct objc_property_list *
2786 (32-bit pointer) */
2787};
2788
Kevin Enderby0fc11822015-04-01 20:57:01 +00002789struct objc_image_info64 {
2790 uint32_t version;
2791 uint32_t flags;
2792};
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002793struct objc_image_info32 {
2794 uint32_t version;
2795 uint32_t flags;
2796};
Kevin Enderby846c0002015-04-16 17:19:59 +00002797struct imageInfo_t {
2798 uint32_t version;
2799 uint32_t flags;
2800};
Kevin Enderby0fc11822015-04-01 20:57:01 +00002801/* masks for objc_image_info.flags */
2802#define OBJC_IMAGE_IS_REPLACEMENT (1 << 0)
2803#define OBJC_IMAGE_SUPPORTS_GC (1 << 1)
2804
2805struct message_ref64 {
2806 uint64_t imp; /* IMP (64-bit pointer) */
2807 uint64_t sel; /* SEL (64-bit pointer) */
2808};
2809
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002810struct message_ref32 {
2811 uint32_t imp; /* IMP (32-bit pointer) */
2812 uint32_t sel; /* SEL (32-bit pointer) */
2813};
2814
Kevin Enderby846c0002015-04-16 17:19:59 +00002815// Objective-C 1 (32-bit only) meta data structs.
2816
2817struct objc_module_t {
2818 uint32_t version;
2819 uint32_t size;
2820 uint32_t name; /* char * (32-bit pointer) */
2821 uint32_t symtab; /* struct objc_symtab * (32-bit pointer) */
2822};
2823
2824struct objc_symtab_t {
2825 uint32_t sel_ref_cnt;
2826 uint32_t refs; /* SEL * (32-bit pointer) */
2827 uint16_t cls_def_cnt;
2828 uint16_t cat_def_cnt;
2829 // uint32_t defs[1]; /* void * (32-bit pointer) variable size */
2830};
2831
2832struct objc_class_t {
2833 uint32_t isa; /* struct objc_class * (32-bit pointer) */
2834 uint32_t super_class; /* struct objc_class * (32-bit pointer) */
2835 uint32_t name; /* const char * (32-bit pointer) */
2836 int32_t version;
2837 int32_t info;
2838 int32_t instance_size;
2839 uint32_t ivars; /* struct objc_ivar_list * (32-bit pointer) */
2840 uint32_t methodLists; /* struct objc_method_list ** (32-bit pointer) */
2841 uint32_t cache; /* struct objc_cache * (32-bit pointer) */
2842 uint32_t protocols; /* struct objc_protocol_list * (32-bit pointer) */
2843};
2844
2845#define CLS_GETINFO(cls, infomask) ((cls)->info & (infomask))
2846// class is not a metaclass
2847#define CLS_CLASS 0x1
2848// class is a metaclass
2849#define CLS_META 0x2
2850
2851struct objc_category_t {
2852 uint32_t category_name; /* char * (32-bit pointer) */
2853 uint32_t class_name; /* char * (32-bit pointer) */
2854 uint32_t instance_methods; /* struct objc_method_list * (32-bit pointer) */
2855 uint32_t class_methods; /* struct objc_method_list * (32-bit pointer) */
2856 uint32_t protocols; /* struct objc_protocol_list * (32-bit ptr) */
2857};
2858
2859struct objc_ivar_t {
2860 uint32_t ivar_name; /* char * (32-bit pointer) */
2861 uint32_t ivar_type; /* char * (32-bit pointer) */
2862 int32_t ivar_offset;
2863};
2864
2865struct objc_ivar_list_t {
2866 int32_t ivar_count;
2867 // struct objc_ivar_t ivar_list[1]; /* variable length structure */
2868};
2869
2870struct objc_method_list_t {
2871 uint32_t obsolete; /* struct objc_method_list * (32-bit pointer) */
2872 int32_t method_count;
2873 // struct objc_method_t method_list[1]; /* variable length structure */
2874};
2875
2876struct objc_method_t {
2877 uint32_t method_name; /* SEL, aka struct objc_selector * (32-bit pointer) */
2878 uint32_t method_types; /* char * (32-bit pointer) */
2879 uint32_t method_imp; /* IMP, aka function pointer, (*IMP)(id, SEL, ...)
2880 (32-bit pointer) */
2881};
2882
2883struct objc_protocol_list_t {
2884 uint32_t next; /* struct objc_protocol_list * (32-bit pointer) */
2885 int32_t count;
2886 // uint32_t list[1]; /* Protocol *, aka struct objc_protocol_t *
2887 // (32-bit pointer) */
2888};
2889
2890struct objc_protocol_t {
2891 uint32_t isa; /* struct objc_class * (32-bit pointer) */
2892 uint32_t protocol_name; /* char * (32-bit pointer) */
2893 uint32_t protocol_list; /* struct objc_protocol_list * (32-bit pointer) */
2894 uint32_t instance_methods; /* struct objc_method_description_list *
2895 (32-bit pointer) */
2896 uint32_t class_methods; /* struct objc_method_description_list *
2897 (32-bit pointer) */
2898};
2899
2900struct objc_method_description_list_t {
2901 int32_t count;
2902 // struct objc_method_description_t list[1];
2903};
2904
2905struct objc_method_description_t {
2906 uint32_t name; /* SEL, aka struct objc_selector * (32-bit pointer) */
2907 uint32_t types; /* char * (32-bit pointer) */
2908};
2909
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002910inline void swapStruct(struct cfstring64_t &cfs) {
2911 sys::swapByteOrder(cfs.isa);
2912 sys::swapByteOrder(cfs.flags);
2913 sys::swapByteOrder(cfs.characters);
2914 sys::swapByteOrder(cfs.length);
2915}
2916
2917inline void swapStruct(struct class64_t &c) {
2918 sys::swapByteOrder(c.isa);
2919 sys::swapByteOrder(c.superclass);
2920 sys::swapByteOrder(c.cache);
2921 sys::swapByteOrder(c.vtable);
2922 sys::swapByteOrder(c.data);
2923}
2924
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002925inline void swapStruct(struct class32_t &c) {
2926 sys::swapByteOrder(c.isa);
2927 sys::swapByteOrder(c.superclass);
2928 sys::swapByteOrder(c.cache);
2929 sys::swapByteOrder(c.vtable);
2930 sys::swapByteOrder(c.data);
2931}
2932
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002933inline void swapStruct(struct class_ro64_t &cro) {
2934 sys::swapByteOrder(cro.flags);
2935 sys::swapByteOrder(cro.instanceStart);
2936 sys::swapByteOrder(cro.instanceSize);
2937 sys::swapByteOrder(cro.reserved);
2938 sys::swapByteOrder(cro.ivarLayout);
2939 sys::swapByteOrder(cro.name);
2940 sys::swapByteOrder(cro.baseMethods);
2941 sys::swapByteOrder(cro.baseProtocols);
2942 sys::swapByteOrder(cro.ivars);
2943 sys::swapByteOrder(cro.weakIvarLayout);
2944 sys::swapByteOrder(cro.baseProperties);
2945}
2946
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002947inline void swapStruct(struct class_ro32_t &cro) {
2948 sys::swapByteOrder(cro.flags);
2949 sys::swapByteOrder(cro.instanceStart);
2950 sys::swapByteOrder(cro.instanceSize);
2951 sys::swapByteOrder(cro.ivarLayout);
2952 sys::swapByteOrder(cro.name);
2953 sys::swapByteOrder(cro.baseMethods);
2954 sys::swapByteOrder(cro.baseProtocols);
2955 sys::swapByteOrder(cro.ivars);
2956 sys::swapByteOrder(cro.weakIvarLayout);
2957 sys::swapByteOrder(cro.baseProperties);
2958}
2959
Kevin Enderby0fc11822015-04-01 20:57:01 +00002960inline void swapStruct(struct method_list64_t &ml) {
2961 sys::swapByteOrder(ml.entsize);
2962 sys::swapByteOrder(ml.count);
2963}
2964
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002965inline void swapStruct(struct method_list32_t &ml) {
2966 sys::swapByteOrder(ml.entsize);
2967 sys::swapByteOrder(ml.count);
2968}
2969
Kevin Enderby0fc11822015-04-01 20:57:01 +00002970inline void swapStruct(struct method64_t &m) {
2971 sys::swapByteOrder(m.name);
2972 sys::swapByteOrder(m.types);
2973 sys::swapByteOrder(m.imp);
2974}
2975
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002976inline void swapStruct(struct method32_t &m) {
2977 sys::swapByteOrder(m.name);
2978 sys::swapByteOrder(m.types);
2979 sys::swapByteOrder(m.imp);
2980}
2981
Kevin Enderby0fc11822015-04-01 20:57:01 +00002982inline void swapStruct(struct protocol_list64_t &pl) {
2983 sys::swapByteOrder(pl.count);
2984}
2985
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002986inline void swapStruct(struct protocol_list32_t &pl) {
2987 sys::swapByteOrder(pl.count);
2988}
2989
Kevin Enderby0fc11822015-04-01 20:57:01 +00002990inline void swapStruct(struct protocol64_t &p) {
2991 sys::swapByteOrder(p.isa);
2992 sys::swapByteOrder(p.name);
2993 sys::swapByteOrder(p.protocols);
2994 sys::swapByteOrder(p.instanceMethods);
2995 sys::swapByteOrder(p.classMethods);
2996 sys::swapByteOrder(p.optionalInstanceMethods);
2997 sys::swapByteOrder(p.optionalClassMethods);
2998 sys::swapByteOrder(p.instanceProperties);
2999}
3000
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003001inline void swapStruct(struct protocol32_t &p) {
3002 sys::swapByteOrder(p.isa);
3003 sys::swapByteOrder(p.name);
3004 sys::swapByteOrder(p.protocols);
3005 sys::swapByteOrder(p.instanceMethods);
3006 sys::swapByteOrder(p.classMethods);
3007 sys::swapByteOrder(p.optionalInstanceMethods);
3008 sys::swapByteOrder(p.optionalClassMethods);
3009 sys::swapByteOrder(p.instanceProperties);
3010}
3011
Kevin Enderby0fc11822015-04-01 20:57:01 +00003012inline void swapStruct(struct ivar_list64_t &il) {
3013 sys::swapByteOrder(il.entsize);
3014 sys::swapByteOrder(il.count);
3015}
3016
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003017inline void swapStruct(struct ivar_list32_t &il) {
3018 sys::swapByteOrder(il.entsize);
3019 sys::swapByteOrder(il.count);
3020}
3021
Kevin Enderby0fc11822015-04-01 20:57:01 +00003022inline void swapStruct(struct ivar64_t &i) {
3023 sys::swapByteOrder(i.offset);
3024 sys::swapByteOrder(i.name);
3025 sys::swapByteOrder(i.type);
3026 sys::swapByteOrder(i.alignment);
3027 sys::swapByteOrder(i.size);
3028}
3029
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003030inline void swapStruct(struct ivar32_t &i) {
3031 sys::swapByteOrder(i.offset);
3032 sys::swapByteOrder(i.name);
3033 sys::swapByteOrder(i.type);
3034 sys::swapByteOrder(i.alignment);
3035 sys::swapByteOrder(i.size);
3036}
3037
Kevin Enderby0fc11822015-04-01 20:57:01 +00003038inline void swapStruct(struct objc_property_list64 &pl) {
3039 sys::swapByteOrder(pl.entsize);
3040 sys::swapByteOrder(pl.count);
3041}
3042
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003043inline void swapStruct(struct objc_property_list32 &pl) {
3044 sys::swapByteOrder(pl.entsize);
3045 sys::swapByteOrder(pl.count);
3046}
3047
Kevin Enderby0fc11822015-04-01 20:57:01 +00003048inline void swapStruct(struct objc_property64 &op) {
3049 sys::swapByteOrder(op.name);
3050 sys::swapByteOrder(op.attributes);
3051}
3052
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003053inline void swapStruct(struct objc_property32 &op) {
3054 sys::swapByteOrder(op.name);
3055 sys::swapByteOrder(op.attributes);
3056}
3057
Kevin Enderby0fc11822015-04-01 20:57:01 +00003058inline void swapStruct(struct category64_t &c) {
3059 sys::swapByteOrder(c.name);
3060 sys::swapByteOrder(c.cls);
3061 sys::swapByteOrder(c.instanceMethods);
3062 sys::swapByteOrder(c.classMethods);
3063 sys::swapByteOrder(c.protocols);
3064 sys::swapByteOrder(c.instanceProperties);
3065}
3066
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003067inline void swapStruct(struct category32_t &c) {
3068 sys::swapByteOrder(c.name);
3069 sys::swapByteOrder(c.cls);
3070 sys::swapByteOrder(c.instanceMethods);
3071 sys::swapByteOrder(c.classMethods);
3072 sys::swapByteOrder(c.protocols);
3073 sys::swapByteOrder(c.instanceProperties);
3074}
3075
Kevin Enderby0fc11822015-04-01 20:57:01 +00003076inline void swapStruct(struct objc_image_info64 &o) {
3077 sys::swapByteOrder(o.version);
3078 sys::swapByteOrder(o.flags);
3079}
3080
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003081inline void swapStruct(struct objc_image_info32 &o) {
3082 sys::swapByteOrder(o.version);
3083 sys::swapByteOrder(o.flags);
3084}
3085
Kevin Enderby846c0002015-04-16 17:19:59 +00003086inline void swapStruct(struct imageInfo_t &o) {
3087 sys::swapByteOrder(o.version);
3088 sys::swapByteOrder(o.flags);
3089}
3090
Kevin Enderby0fc11822015-04-01 20:57:01 +00003091inline void swapStruct(struct message_ref64 &mr) {
3092 sys::swapByteOrder(mr.imp);
3093 sys::swapByteOrder(mr.sel);
3094}
3095
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003096inline void swapStruct(struct message_ref32 &mr) {
3097 sys::swapByteOrder(mr.imp);
3098 sys::swapByteOrder(mr.sel);
3099}
3100
Kevin Enderby846c0002015-04-16 17:19:59 +00003101inline void swapStruct(struct objc_module_t &module) {
3102 sys::swapByteOrder(module.version);
3103 sys::swapByteOrder(module.size);
3104 sys::swapByteOrder(module.name);
3105 sys::swapByteOrder(module.symtab);
Jingyue Wufedecc42015-04-16 18:43:44 +00003106}
Kevin Enderby846c0002015-04-16 17:19:59 +00003107
3108inline void swapStruct(struct objc_symtab_t &symtab) {
3109 sys::swapByteOrder(symtab.sel_ref_cnt);
3110 sys::swapByteOrder(symtab.refs);
3111 sys::swapByteOrder(symtab.cls_def_cnt);
3112 sys::swapByteOrder(symtab.cat_def_cnt);
Jingyue Wufedecc42015-04-16 18:43:44 +00003113}
Kevin Enderby846c0002015-04-16 17:19:59 +00003114
3115inline void swapStruct(struct objc_class_t &objc_class) {
3116 sys::swapByteOrder(objc_class.isa);
3117 sys::swapByteOrder(objc_class.super_class);
3118 sys::swapByteOrder(objc_class.name);
3119 sys::swapByteOrder(objc_class.version);
3120 sys::swapByteOrder(objc_class.info);
3121 sys::swapByteOrder(objc_class.instance_size);
3122 sys::swapByteOrder(objc_class.ivars);
3123 sys::swapByteOrder(objc_class.methodLists);
3124 sys::swapByteOrder(objc_class.cache);
3125 sys::swapByteOrder(objc_class.protocols);
Jingyue Wufedecc42015-04-16 18:43:44 +00003126}
Kevin Enderby846c0002015-04-16 17:19:59 +00003127
3128inline void swapStruct(struct objc_category_t &objc_category) {
3129 sys::swapByteOrder(objc_category.category_name);
3130 sys::swapByteOrder(objc_category.class_name);
3131 sys::swapByteOrder(objc_category.instance_methods);
3132 sys::swapByteOrder(objc_category.class_methods);
3133 sys::swapByteOrder(objc_category.protocols);
3134}
3135
3136inline void swapStruct(struct objc_ivar_list_t &objc_ivar_list) {
3137 sys::swapByteOrder(objc_ivar_list.ivar_count);
3138}
3139
3140inline void swapStruct(struct objc_ivar_t &objc_ivar) {
3141 sys::swapByteOrder(objc_ivar.ivar_name);
3142 sys::swapByteOrder(objc_ivar.ivar_type);
3143 sys::swapByteOrder(objc_ivar.ivar_offset);
Jingyue Wufedecc42015-04-16 18:43:44 +00003144}
Kevin Enderby846c0002015-04-16 17:19:59 +00003145
3146inline void swapStruct(struct objc_method_list_t &method_list) {
3147 sys::swapByteOrder(method_list.obsolete);
3148 sys::swapByteOrder(method_list.method_count);
3149}
3150
3151inline void swapStruct(struct objc_method_t &method) {
3152 sys::swapByteOrder(method.method_name);
3153 sys::swapByteOrder(method.method_types);
3154 sys::swapByteOrder(method.method_imp);
3155}
3156
3157inline void swapStruct(struct objc_protocol_list_t &protocol_list) {
3158 sys::swapByteOrder(protocol_list.next);
3159 sys::swapByteOrder(protocol_list.count);
3160}
3161
3162inline void swapStruct(struct objc_protocol_t &protocol) {
3163 sys::swapByteOrder(protocol.isa);
3164 sys::swapByteOrder(protocol.protocol_name);
3165 sys::swapByteOrder(protocol.protocol_list);
3166 sys::swapByteOrder(protocol.instance_methods);
3167 sys::swapByteOrder(protocol.class_methods);
3168}
3169
3170inline void swapStruct(struct objc_method_description_list_t &mdl) {
3171 sys::swapByteOrder(mdl.count);
3172}
3173
3174inline void swapStruct(struct objc_method_description_t &md) {
3175 sys::swapByteOrder(md.name);
3176 sys::swapByteOrder(md.types);
3177}
3178
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003179static const char *get_dyld_bind_info_symbolname(uint64_t ReferenceValue,
3180 struct DisassembleInfo *info);
3181
3182// get_objc2_64bit_class_name() is used for disassembly and is passed a pointer
3183// to an Objective-C class and returns the class name. It is also passed the
3184// address of the pointer, so when the pointer is zero as it can be in an .o
3185// file, that is used to look for an external relocation entry with a symbol
3186// name.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00003187static const char *get_objc2_64bit_class_name(uint64_t pointer_value,
3188 uint64_t ReferenceValue,
3189 struct DisassembleInfo *info) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003190 const char *r;
3191 uint32_t offset, left;
3192 SectionRef S;
3193
3194 // The pointer_value can be 0 in an object file and have a relocation
3195 // entry for the class symbol at the ReferenceValue (the address of the
3196 // pointer).
3197 if (pointer_value == 0) {
3198 r = get_pointer_64(ReferenceValue, offset, left, S, info);
3199 if (r == nullptr || left < sizeof(uint64_t))
3200 return nullptr;
3201 uint64_t n_value;
3202 const char *symbol_name = get_symbol_64(offset, S, info, n_value);
3203 if (symbol_name == nullptr)
3204 return nullptr;
Hans Wennborgdb53e302014-10-23 21:59:17 +00003205 const char *class_name = strrchr(symbol_name, '$');
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003206 if (class_name != nullptr && class_name[1] == '_' && class_name[2] != '\0')
3207 return class_name + 2;
3208 else
3209 return nullptr;
3210 }
3211
3212 // The case were the pointer_value is non-zero and points to a class defined
3213 // in this Mach-O file.
3214 r = get_pointer_64(pointer_value, offset, left, S, info);
3215 if (r == nullptr || left < sizeof(struct class64_t))
3216 return nullptr;
3217 struct class64_t c;
3218 memcpy(&c, r, sizeof(struct class64_t));
3219 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3220 swapStruct(c);
3221 if (c.data == 0)
3222 return nullptr;
3223 r = get_pointer_64(c.data, offset, left, S, info);
3224 if (r == nullptr || left < sizeof(struct class_ro64_t))
3225 return nullptr;
3226 struct class_ro64_t cro;
3227 memcpy(&cro, r, sizeof(struct class_ro64_t));
3228 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3229 swapStruct(cro);
3230 if (cro.name == 0)
3231 return nullptr;
3232 const char *name = get_pointer_64(cro.name, offset, left, S, info);
3233 return name;
3234}
3235
3236// get_objc2_64bit_cfstring_name is used for disassembly and is passed a
3237// pointer to a cfstring and returns its name or nullptr.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00003238static const char *get_objc2_64bit_cfstring_name(uint64_t ReferenceValue,
3239 struct DisassembleInfo *info) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003240 const char *r, *name;
3241 uint32_t offset, left;
3242 SectionRef S;
3243 struct cfstring64_t cfs;
3244 uint64_t cfs_characters;
3245
3246 r = get_pointer_64(ReferenceValue, offset, left, S, info);
3247 if (r == nullptr || left < sizeof(struct cfstring64_t))
3248 return nullptr;
3249 memcpy(&cfs, r, sizeof(struct cfstring64_t));
3250 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3251 swapStruct(cfs);
3252 if (cfs.characters == 0) {
3253 uint64_t n_value;
3254 const char *symbol_name = get_symbol_64(
3255 offset + offsetof(struct cfstring64_t, characters), S, info, n_value);
3256 if (symbol_name == nullptr)
3257 return nullptr;
3258 cfs_characters = n_value;
3259 } else
3260 cfs_characters = cfs.characters;
3261 name = get_pointer_64(cfs_characters, offset, left, S, info);
3262
3263 return name;
3264}
3265
3266// get_objc2_64bit_selref() is used for disassembly and is passed a the address
3267// of a pointer to an Objective-C selector reference when the pointer value is
3268// zero as in a .o file and is likely to have a external relocation entry with
3269// who's symbol's n_value is the real pointer to the selector name. If that is
3270// the case the real pointer to the selector name is returned else 0 is
3271// returned
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00003272static uint64_t get_objc2_64bit_selref(uint64_t ReferenceValue,
3273 struct DisassembleInfo *info) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003274 uint32_t offset, left;
3275 SectionRef S;
3276
3277 const char *r = get_pointer_64(ReferenceValue, offset, left, S, info);
3278 if (r == nullptr || left < sizeof(uint64_t))
3279 return 0;
3280 uint64_t n_value;
3281 const char *symbol_name = get_symbol_64(offset, S, info, n_value);
3282 if (symbol_name == nullptr)
3283 return 0;
3284 return n_value;
3285}
3286
Kevin Enderby0fc11822015-04-01 20:57:01 +00003287static const SectionRef get_section(MachOObjectFile *O, const char *segname,
3288 const char *sectname) {
3289 for (const SectionRef &Section : O->sections()) {
3290 StringRef SectName;
3291 Section.getName(SectName);
3292 DataRefImpl Ref = Section.getRawDataRefImpl();
3293 StringRef SegName = O->getSectionFinalSegmentName(Ref);
3294 if (SegName == segname && SectName == sectname)
3295 return Section;
3296 }
3297 return SectionRef();
3298}
3299
3300static void
3301walk_pointer_list_64(const char *listname, const SectionRef S,
3302 MachOObjectFile *O, struct DisassembleInfo *info,
3303 void (*func)(uint64_t, struct DisassembleInfo *info)) {
3304 if (S == SectionRef())
3305 return;
3306
3307 StringRef SectName;
3308 S.getName(SectName);
3309 DataRefImpl Ref = S.getRawDataRefImpl();
3310 StringRef SegName = O->getSectionFinalSegmentName(Ref);
3311 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
3312
3313 StringRef BytesStr;
3314 S.getContents(BytesStr);
3315 const char *Contents = reinterpret_cast<const char *>(BytesStr.data());
3316
3317 for (uint32_t i = 0; i < S.getSize(); i += sizeof(uint64_t)) {
3318 uint32_t left = S.getSize() - i;
3319 uint32_t size = left < sizeof(uint64_t) ? left : sizeof(uint64_t);
3320 uint64_t p = 0;
3321 memcpy(&p, Contents + i, size);
3322 if (i + sizeof(uint64_t) > S.getSize())
3323 outs() << listname << " list pointer extends past end of (" << SegName
3324 << "," << SectName << ") section\n";
3325 outs() << format("%016" PRIx64, S.getAddress() + i) << " ";
3326
3327 if (O->isLittleEndian() != sys::IsLittleEndianHost)
3328 sys::swapByteOrder(p);
3329
3330 uint64_t n_value = 0;
3331 const char *name = get_symbol_64(i, S, info, n_value, p);
3332 if (name == nullptr)
3333 name = get_dyld_bind_info_symbolname(S.getAddress() + i, info);
3334
3335 if (n_value != 0) {
3336 outs() << format("0x%" PRIx64, n_value);
3337 if (p != 0)
3338 outs() << " + " << format("0x%" PRIx64, p);
3339 } else
3340 outs() << format("0x%" PRIx64, p);
3341 if (name != nullptr)
3342 outs() << " " << name;
3343 outs() << "\n";
3344
3345 p += n_value;
3346 if (func)
3347 func(p, info);
3348 }
3349}
3350
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003351static void
3352walk_pointer_list_32(const char *listname, const SectionRef S,
3353 MachOObjectFile *O, struct DisassembleInfo *info,
3354 void (*func)(uint32_t, struct DisassembleInfo *info)) {
3355 if (S == SectionRef())
3356 return;
3357
3358 StringRef SectName;
3359 S.getName(SectName);
3360 DataRefImpl Ref = S.getRawDataRefImpl();
3361 StringRef SegName = O->getSectionFinalSegmentName(Ref);
3362 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
3363
3364 StringRef BytesStr;
3365 S.getContents(BytesStr);
3366 const char *Contents = reinterpret_cast<const char *>(BytesStr.data());
3367
3368 for (uint32_t i = 0; i < S.getSize(); i += sizeof(uint32_t)) {
3369 uint32_t left = S.getSize() - i;
3370 uint32_t size = left < sizeof(uint32_t) ? left : sizeof(uint32_t);
3371 uint32_t p = 0;
3372 memcpy(&p, Contents + i, size);
3373 if (i + sizeof(uint32_t) > S.getSize())
3374 outs() << listname << " list pointer extends past end of (" << SegName
3375 << "," << SectName << ") section\n";
Kevin Enderbycf261312015-04-06 22:33:43 +00003376 uint32_t Address = S.getAddress() + i;
3377 outs() << format("%08" PRIx32, Address) << " ";
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003378
3379 if (O->isLittleEndian() != sys::IsLittleEndianHost)
3380 sys::swapByteOrder(p);
3381 outs() << format("0x%" PRIx32, p);
3382
3383 const char *name = get_symbol_32(i, S, info, p);
3384 if (name != nullptr)
3385 outs() << " " << name;
3386 outs() << "\n";
3387
3388 if (func)
3389 func(p, info);
3390 }
3391}
3392
3393static void print_layout_map(const char *layout_map, uint32_t left) {
Kevin Enderbya59824a2015-10-06 22:27:08 +00003394 if (layout_map == nullptr)
3395 return;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003396 outs() << " layout map: ";
3397 do {
3398 outs() << format("0x%02" PRIx32, (*layout_map) & 0xff) << " ";
3399 left--;
3400 layout_map++;
3401 } while (*layout_map != '\0' && left != 0);
3402 outs() << "\n";
3403}
3404
Kevin Enderby0fc11822015-04-01 20:57:01 +00003405static void print_layout_map64(uint64_t p, struct DisassembleInfo *info) {
3406 uint32_t offset, left;
3407 SectionRef S;
3408 const char *layout_map;
3409
3410 if (p == 0)
3411 return;
3412 layout_map = get_pointer_64(p, offset, left, S, info);
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003413 print_layout_map(layout_map, left);
3414}
3415
3416static void print_layout_map32(uint32_t p, struct DisassembleInfo *info) {
3417 uint32_t offset, left;
3418 SectionRef S;
3419 const char *layout_map;
3420
3421 if (p == 0)
3422 return;
3423 layout_map = get_pointer_32(p, offset, left, S, info);
3424 print_layout_map(layout_map, left);
Kevin Enderby0fc11822015-04-01 20:57:01 +00003425}
3426
3427static void print_method_list64_t(uint64_t p, struct DisassembleInfo *info,
3428 const char *indent) {
3429 struct method_list64_t ml;
3430 struct method64_t m;
3431 const char *r;
3432 uint32_t offset, xoffset, left, i;
3433 SectionRef S, xS;
3434 const char *name, *sym_name;
3435 uint64_t n_value;
3436
3437 r = get_pointer_64(p, offset, left, S, info);
3438 if (r == nullptr)
3439 return;
3440 memset(&ml, '\0', sizeof(struct method_list64_t));
3441 if (left < sizeof(struct method_list64_t)) {
3442 memcpy(&ml, r, left);
3443 outs() << " (method_list_t entends past the end of the section)\n";
3444 } else
3445 memcpy(&ml, r, sizeof(struct method_list64_t));
3446 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3447 swapStruct(ml);
3448 outs() << indent << "\t\t entsize " << ml.entsize << "\n";
3449 outs() << indent << "\t\t count " << ml.count << "\n";
3450
3451 p += sizeof(struct method_list64_t);
3452 offset += sizeof(struct method_list64_t);
3453 for (i = 0; i < ml.count; i++) {
3454 r = get_pointer_64(p, offset, left, S, info);
3455 if (r == nullptr)
3456 return;
3457 memset(&m, '\0', sizeof(struct method64_t));
3458 if (left < sizeof(struct method64_t)) {
Kevin Enderbya59824a2015-10-06 22:27:08 +00003459 memcpy(&m, r, left);
3460 outs() << indent << " (method_t extends past the end of the section)\n";
Kevin Enderby0fc11822015-04-01 20:57:01 +00003461 } else
3462 memcpy(&m, r, sizeof(struct method64_t));
3463 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3464 swapStruct(m);
3465
3466 outs() << indent << "\t\t name ";
3467 sym_name = get_symbol_64(offset + offsetof(struct method64_t, name), S,
3468 info, n_value, m.name);
3469 if (n_value != 0) {
3470 if (info->verbose && sym_name != nullptr)
3471 outs() << sym_name;
3472 else
3473 outs() << format("0x%" PRIx64, n_value);
3474 if (m.name != 0)
3475 outs() << " + " << format("0x%" PRIx64, m.name);
3476 } else
3477 outs() << format("0x%" PRIx64, m.name);
3478 name = get_pointer_64(m.name + n_value, xoffset, left, xS, info);
3479 if (name != nullptr)
3480 outs() << format(" %.*s", left, name);
3481 outs() << "\n";
3482
3483 outs() << indent << "\t\t types ";
3484 sym_name = get_symbol_64(offset + offsetof(struct method64_t, types), S,
3485 info, n_value, m.types);
3486 if (n_value != 0) {
3487 if (info->verbose && sym_name != nullptr)
3488 outs() << sym_name;
3489 else
3490 outs() << format("0x%" PRIx64, n_value);
3491 if (m.types != 0)
3492 outs() << " + " << format("0x%" PRIx64, m.types);
3493 } else
3494 outs() << format("0x%" PRIx64, m.types);
3495 name = get_pointer_64(m.types + n_value, xoffset, left, xS, info);
3496 if (name != nullptr)
3497 outs() << format(" %.*s", left, name);
3498 outs() << "\n";
3499
3500 outs() << indent << "\t\t imp ";
3501 name = get_symbol_64(offset + offsetof(struct method64_t, imp), S, info,
3502 n_value, m.imp);
3503 if (info->verbose && name == nullptr) {
3504 if (n_value != 0) {
3505 outs() << format("0x%" PRIx64, n_value) << " ";
3506 if (m.imp != 0)
3507 outs() << "+ " << format("0x%" PRIx64, m.imp) << " ";
3508 } else
3509 outs() << format("0x%" PRIx64, m.imp) << " ";
3510 }
3511 if (name != nullptr)
3512 outs() << name;
3513 outs() << "\n";
3514
3515 p += sizeof(struct method64_t);
3516 offset += sizeof(struct method64_t);
3517 }
3518}
3519
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003520static void print_method_list32_t(uint64_t p, struct DisassembleInfo *info,
3521 const char *indent) {
3522 struct method_list32_t ml;
3523 struct method32_t m;
Kevin Enderby846c0002015-04-16 17:19:59 +00003524 const char *r, *name;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003525 uint32_t offset, xoffset, left, i;
3526 SectionRef S, xS;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003527
3528 r = get_pointer_32(p, offset, left, S, info);
3529 if (r == nullptr)
3530 return;
3531 memset(&ml, '\0', sizeof(struct method_list32_t));
3532 if (left < sizeof(struct method_list32_t)) {
3533 memcpy(&ml, r, left);
3534 outs() << " (method_list_t entends past the end of the section)\n";
3535 } else
3536 memcpy(&ml, r, sizeof(struct method_list32_t));
3537 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3538 swapStruct(ml);
3539 outs() << indent << "\t\t entsize " << ml.entsize << "\n";
3540 outs() << indent << "\t\t count " << ml.count << "\n";
3541
3542 p += sizeof(struct method_list32_t);
3543 offset += sizeof(struct method_list32_t);
3544 for (i = 0; i < ml.count; i++) {
3545 r = get_pointer_32(p, offset, left, S, info);
3546 if (r == nullptr)
3547 return;
3548 memset(&m, '\0', sizeof(struct method32_t));
3549 if (left < sizeof(struct method32_t)) {
3550 memcpy(&ml, r, left);
3551 outs() << indent << " (method_t entends past the end of the section)\n";
3552 } else
3553 memcpy(&m, r, sizeof(struct method32_t));
3554 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3555 swapStruct(m);
3556
3557 outs() << indent << "\t\t name " << format("0x%" PRIx32, m.name);
3558 name = get_pointer_32(m.name, xoffset, left, xS, info);
3559 if (name != nullptr)
3560 outs() << format(" %.*s", left, name);
3561 outs() << "\n";
3562
3563 outs() << indent << "\t\t types " << format("0x%" PRIx32, m.types);
3564 name = get_pointer_32(m.types, xoffset, left, xS, info);
3565 if (name != nullptr)
3566 outs() << format(" %.*s", left, name);
3567 outs() << "\n";
3568
3569 outs() << indent << "\t\t imp " << format("0x%" PRIx32, m.imp);
3570 name = get_symbol_32(offset + offsetof(struct method32_t, imp), S, info,
3571 m.imp);
3572 if (name != nullptr)
3573 outs() << " " << name;
3574 outs() << "\n";
3575
3576 p += sizeof(struct method32_t);
3577 offset += sizeof(struct method32_t);
3578 }
3579}
3580
Kevin Enderby846c0002015-04-16 17:19:59 +00003581static bool print_method_list(uint32_t p, struct DisassembleInfo *info) {
3582 uint32_t offset, left, xleft;
3583 SectionRef S;
3584 struct objc_method_list_t method_list;
3585 struct objc_method_t method;
3586 const char *r, *methods, *name, *SymbolName;
3587 int32_t i;
3588
3589 r = get_pointer_32(p, offset, left, S, info, true);
3590 if (r == nullptr)
3591 return true;
3592
3593 outs() << "\n";
3594 if (left > sizeof(struct objc_method_list_t)) {
3595 memcpy(&method_list, r, sizeof(struct objc_method_list_t));
3596 } else {
3597 outs() << "\t\t objc_method_list extends past end of the section\n";
3598 memset(&method_list, '\0', sizeof(struct objc_method_list_t));
3599 memcpy(&method_list, r, left);
3600 }
3601 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3602 swapStruct(method_list);
3603
3604 outs() << "\t\t obsolete "
3605 << format("0x%08" PRIx32, method_list.obsolete) << "\n";
3606 outs() << "\t\t method_count " << method_list.method_count << "\n";
3607
3608 methods = r + sizeof(struct objc_method_list_t);
3609 for (i = 0; i < method_list.method_count; i++) {
3610 if ((i + 1) * sizeof(struct objc_method_t) > left) {
3611 outs() << "\t\t remaining method's extend past the of the section\n";
3612 break;
3613 }
3614 memcpy(&method, methods + i * sizeof(struct objc_method_t),
3615 sizeof(struct objc_method_t));
3616 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3617 swapStruct(method);
3618
3619 outs() << "\t\t method_name "
3620 << format("0x%08" PRIx32, method.method_name);
3621 if (info->verbose) {
3622 name = get_pointer_32(method.method_name, offset, xleft, S, info, true);
3623 if (name != nullptr)
3624 outs() << format(" %.*s", xleft, name);
3625 else
3626 outs() << " (not in an __OBJC section)";
3627 }
3628 outs() << "\n";
3629
3630 outs() << "\t\t method_types "
3631 << format("0x%08" PRIx32, method.method_types);
3632 if (info->verbose) {
3633 name = get_pointer_32(method.method_types, offset, xleft, S, info, true);
3634 if (name != nullptr)
3635 outs() << format(" %.*s", xleft, name);
3636 else
3637 outs() << " (not in an __OBJC section)";
3638 }
3639 outs() << "\n";
3640
3641 outs() << "\t\t method_imp "
3642 << format("0x%08" PRIx32, method.method_imp) << " ";
3643 if (info->verbose) {
3644 SymbolName = GuessSymbolName(method.method_imp, info->AddrMap);
3645 if (SymbolName != nullptr)
3646 outs() << SymbolName;
3647 }
3648 outs() << "\n";
3649 }
3650 return false;
3651}
3652
Kevin Enderby0fc11822015-04-01 20:57:01 +00003653static void print_protocol_list64_t(uint64_t p, struct DisassembleInfo *info) {
3654 struct protocol_list64_t pl;
3655 uint64_t q, n_value;
3656 struct protocol64_t pc;
3657 const char *r;
3658 uint32_t offset, xoffset, left, i;
3659 SectionRef S, xS;
3660 const char *name, *sym_name;
3661
3662 r = get_pointer_64(p, offset, left, S, info);
3663 if (r == nullptr)
3664 return;
3665 memset(&pl, '\0', sizeof(struct protocol_list64_t));
3666 if (left < sizeof(struct protocol_list64_t)) {
3667 memcpy(&pl, r, left);
3668 outs() << " (protocol_list_t entends past the end of the section)\n";
3669 } else
3670 memcpy(&pl, r, sizeof(struct protocol_list64_t));
3671 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3672 swapStruct(pl);
3673 outs() << " count " << pl.count << "\n";
3674
3675 p += sizeof(struct protocol_list64_t);
3676 offset += sizeof(struct protocol_list64_t);
3677 for (i = 0; i < pl.count; i++) {
3678 r = get_pointer_64(p, offset, left, S, info);
3679 if (r == nullptr)
3680 return;
3681 q = 0;
3682 if (left < sizeof(uint64_t)) {
3683 memcpy(&q, r, left);
3684 outs() << " (protocol_t * entends past the end of the section)\n";
3685 } else
3686 memcpy(&q, r, sizeof(uint64_t));
3687 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3688 sys::swapByteOrder(q);
3689
3690 outs() << "\t\t list[" << i << "] ";
3691 sym_name = get_symbol_64(offset, S, info, n_value, q);
3692 if (n_value != 0) {
3693 if (info->verbose && sym_name != nullptr)
3694 outs() << sym_name;
3695 else
3696 outs() << format("0x%" PRIx64, n_value);
3697 if (q != 0)
3698 outs() << " + " << format("0x%" PRIx64, q);
3699 } else
3700 outs() << format("0x%" PRIx64, q);
3701 outs() << " (struct protocol_t *)\n";
3702
3703 r = get_pointer_64(q + n_value, offset, left, S, info);
3704 if (r == nullptr)
3705 return;
3706 memset(&pc, '\0', sizeof(struct protocol64_t));
3707 if (left < sizeof(struct protocol64_t)) {
3708 memcpy(&pc, r, left);
3709 outs() << " (protocol_t entends past the end of the section)\n";
3710 } else
3711 memcpy(&pc, r, sizeof(struct protocol64_t));
3712 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3713 swapStruct(pc);
3714
3715 outs() << "\t\t\t isa " << format("0x%" PRIx64, pc.isa) << "\n";
3716
3717 outs() << "\t\t\t name ";
3718 sym_name = get_symbol_64(offset + offsetof(struct protocol64_t, name), S,
3719 info, n_value, pc.name);
3720 if (n_value != 0) {
3721 if (info->verbose && sym_name != nullptr)
3722 outs() << sym_name;
3723 else
3724 outs() << format("0x%" PRIx64, n_value);
3725 if (pc.name != 0)
3726 outs() << " + " << format("0x%" PRIx64, pc.name);
3727 } else
3728 outs() << format("0x%" PRIx64, pc.name);
3729 name = get_pointer_64(pc.name + n_value, xoffset, left, xS, info);
3730 if (name != nullptr)
3731 outs() << format(" %.*s", left, name);
3732 outs() << "\n";
3733
3734 outs() << "\t\t\tprotocols " << format("0x%" PRIx64, pc.protocols) << "\n";
3735
3736 outs() << "\t\t instanceMethods ";
3737 sym_name =
3738 get_symbol_64(offset + offsetof(struct protocol64_t, instanceMethods),
3739 S, info, n_value, pc.instanceMethods);
3740 if (n_value != 0) {
3741 if (info->verbose && sym_name != nullptr)
3742 outs() << sym_name;
3743 else
3744 outs() << format("0x%" PRIx64, n_value);
3745 if (pc.instanceMethods != 0)
3746 outs() << " + " << format("0x%" PRIx64, pc.instanceMethods);
3747 } else
3748 outs() << format("0x%" PRIx64, pc.instanceMethods);
3749 outs() << " (struct method_list_t *)\n";
3750 if (pc.instanceMethods + n_value != 0)
3751 print_method_list64_t(pc.instanceMethods + n_value, info, "\t");
3752
3753 outs() << "\t\t classMethods ";
3754 sym_name =
3755 get_symbol_64(offset + offsetof(struct protocol64_t, classMethods), S,
3756 info, n_value, pc.classMethods);
3757 if (n_value != 0) {
3758 if (info->verbose && sym_name != nullptr)
3759 outs() << sym_name;
3760 else
3761 outs() << format("0x%" PRIx64, n_value);
3762 if (pc.classMethods != 0)
3763 outs() << " + " << format("0x%" PRIx64, pc.classMethods);
3764 } else
3765 outs() << format("0x%" PRIx64, pc.classMethods);
3766 outs() << " (struct method_list_t *)\n";
3767 if (pc.classMethods + n_value != 0)
3768 print_method_list64_t(pc.classMethods + n_value, info, "\t");
3769
3770 outs() << "\t optionalInstanceMethods "
3771 << format("0x%" PRIx64, pc.optionalInstanceMethods) << "\n";
3772 outs() << "\t optionalClassMethods "
3773 << format("0x%" PRIx64, pc.optionalClassMethods) << "\n";
3774 outs() << "\t instanceProperties "
3775 << format("0x%" PRIx64, pc.instanceProperties) << "\n";
3776
3777 p += sizeof(uint64_t);
3778 offset += sizeof(uint64_t);
3779 }
3780}
3781
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003782static void print_protocol_list32_t(uint32_t p, struct DisassembleInfo *info) {
3783 struct protocol_list32_t pl;
3784 uint32_t q;
3785 struct protocol32_t pc;
3786 const char *r;
3787 uint32_t offset, xoffset, left, i;
3788 SectionRef S, xS;
3789 const char *name;
3790
3791 r = get_pointer_32(p, offset, left, S, info);
3792 if (r == nullptr)
3793 return;
3794 memset(&pl, '\0', sizeof(struct protocol_list32_t));
3795 if (left < sizeof(struct protocol_list32_t)) {
3796 memcpy(&pl, r, left);
3797 outs() << " (protocol_list_t entends past the end of the section)\n";
3798 } else
3799 memcpy(&pl, r, sizeof(struct protocol_list32_t));
3800 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3801 swapStruct(pl);
3802 outs() << " count " << pl.count << "\n";
3803
3804 p += sizeof(struct protocol_list32_t);
3805 offset += sizeof(struct protocol_list32_t);
3806 for (i = 0; i < pl.count; i++) {
3807 r = get_pointer_32(p, offset, left, S, info);
3808 if (r == nullptr)
3809 return;
3810 q = 0;
3811 if (left < sizeof(uint32_t)) {
3812 memcpy(&q, r, left);
3813 outs() << " (protocol_t * entends past the end of the section)\n";
3814 } else
3815 memcpy(&q, r, sizeof(uint32_t));
3816 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3817 sys::swapByteOrder(q);
3818 outs() << "\t\t list[" << i << "] " << format("0x%" PRIx32, q)
3819 << " (struct protocol_t *)\n";
3820 r = get_pointer_32(q, offset, left, S, info);
3821 if (r == nullptr)
3822 return;
3823 memset(&pc, '\0', sizeof(struct protocol32_t));
3824 if (left < sizeof(struct protocol32_t)) {
3825 memcpy(&pc, r, left);
3826 outs() << " (protocol_t entends past the end of the section)\n";
3827 } else
3828 memcpy(&pc, r, sizeof(struct protocol32_t));
3829 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3830 swapStruct(pc);
3831 outs() << "\t\t\t isa " << format("0x%" PRIx32, pc.isa) << "\n";
3832 outs() << "\t\t\t name " << format("0x%" PRIx32, pc.name);
3833 name = get_pointer_32(pc.name, xoffset, left, xS, info);
3834 if (name != nullptr)
3835 outs() << format(" %.*s", left, name);
3836 outs() << "\n";
3837 outs() << "\t\t\tprotocols " << format("0x%" PRIx32, pc.protocols) << "\n";
3838 outs() << "\t\t instanceMethods "
3839 << format("0x%" PRIx32, pc.instanceMethods)
3840 << " (struct method_list_t *)\n";
3841 if (pc.instanceMethods != 0)
3842 print_method_list32_t(pc.instanceMethods, info, "\t");
3843 outs() << "\t\t classMethods " << format("0x%" PRIx32, pc.classMethods)
3844 << " (struct method_list_t *)\n";
3845 if (pc.classMethods != 0)
3846 print_method_list32_t(pc.classMethods, info, "\t");
3847 outs() << "\t optionalInstanceMethods "
3848 << format("0x%" PRIx32, pc.optionalInstanceMethods) << "\n";
3849 outs() << "\t optionalClassMethods "
3850 << format("0x%" PRIx32, pc.optionalClassMethods) << "\n";
3851 outs() << "\t instanceProperties "
3852 << format("0x%" PRIx32, pc.instanceProperties) << "\n";
3853 p += sizeof(uint32_t);
3854 offset += sizeof(uint32_t);
3855 }
3856}
3857
Kevin Enderby846c0002015-04-16 17:19:59 +00003858static void print_indent(uint32_t indent) {
3859 for (uint32_t i = 0; i < indent;) {
3860 if (indent - i >= 8) {
3861 outs() << "\t";
3862 i += 8;
3863 } else {
3864 for (uint32_t j = i; j < indent; j++)
3865 outs() << " ";
3866 return;
3867 }
3868 }
3869}
3870
3871static bool print_method_description_list(uint32_t p, uint32_t indent,
3872 struct DisassembleInfo *info) {
3873 uint32_t offset, left, xleft;
3874 SectionRef S;
3875 struct objc_method_description_list_t mdl;
3876 struct objc_method_description_t md;
3877 const char *r, *list, *name;
3878 int32_t i;
3879
3880 r = get_pointer_32(p, offset, left, S, info, true);
3881 if (r == nullptr)
3882 return true;
3883
3884 outs() << "\n";
3885 if (left > sizeof(struct objc_method_description_list_t)) {
3886 memcpy(&mdl, r, sizeof(struct objc_method_description_list_t));
3887 } else {
3888 print_indent(indent);
3889 outs() << " objc_method_description_list extends past end of the section\n";
3890 memset(&mdl, '\0', sizeof(struct objc_method_description_list_t));
3891 memcpy(&mdl, r, left);
3892 }
3893 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3894 swapStruct(mdl);
3895
3896 print_indent(indent);
3897 outs() << " count " << mdl.count << "\n";
3898
3899 list = r + sizeof(struct objc_method_description_list_t);
3900 for (i = 0; i < mdl.count; i++) {
3901 if ((i + 1) * sizeof(struct objc_method_description_t) > left) {
3902 print_indent(indent);
3903 outs() << " remaining list entries extend past the of the section\n";
3904 break;
3905 }
3906 print_indent(indent);
3907 outs() << " list[" << i << "]\n";
3908 memcpy(&md, list + i * sizeof(struct objc_method_description_t),
3909 sizeof(struct objc_method_description_t));
3910 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3911 swapStruct(md);
3912
3913 print_indent(indent);
3914 outs() << " name " << format("0x%08" PRIx32, md.name);
3915 if (info->verbose) {
3916 name = get_pointer_32(md.name, offset, xleft, S, info, true);
3917 if (name != nullptr)
3918 outs() << format(" %.*s", xleft, name);
3919 else
3920 outs() << " (not in an __OBJC section)";
3921 }
3922 outs() << "\n";
3923
3924 print_indent(indent);
3925 outs() << " types " << format("0x%08" PRIx32, md.types);
3926 if (info->verbose) {
3927 name = get_pointer_32(md.types, offset, xleft, S, info, true);
3928 if (name != nullptr)
3929 outs() << format(" %.*s", xleft, name);
3930 else
3931 outs() << " (not in an __OBJC section)";
3932 }
3933 outs() << "\n";
3934 }
3935 return false;
3936}
3937
3938static bool print_protocol_list(uint32_t p, uint32_t indent,
3939 struct DisassembleInfo *info);
3940
3941static bool print_protocol(uint32_t p, uint32_t indent,
3942 struct DisassembleInfo *info) {
3943 uint32_t offset, left;
3944 SectionRef S;
3945 struct objc_protocol_t protocol;
3946 const char *r, *name;
3947
3948 r = get_pointer_32(p, offset, left, S, info, true);
3949 if (r == nullptr)
3950 return true;
3951
3952 outs() << "\n";
3953 if (left >= sizeof(struct objc_protocol_t)) {
3954 memcpy(&protocol, r, sizeof(struct objc_protocol_t));
3955 } else {
3956 print_indent(indent);
3957 outs() << " Protocol extends past end of the section\n";
3958 memset(&protocol, '\0', sizeof(struct objc_protocol_t));
3959 memcpy(&protocol, r, left);
3960 }
3961 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3962 swapStruct(protocol);
3963
3964 print_indent(indent);
3965 outs() << " isa " << format("0x%08" PRIx32, protocol.isa)
3966 << "\n";
3967
3968 print_indent(indent);
3969 outs() << " protocol_name "
3970 << format("0x%08" PRIx32, protocol.protocol_name);
3971 if (info->verbose) {
3972 name = get_pointer_32(protocol.protocol_name, offset, left, S, info, true);
3973 if (name != nullptr)
3974 outs() << format(" %.*s", left, name);
3975 else
3976 outs() << " (not in an __OBJC section)";
3977 }
3978 outs() << "\n";
3979
3980 print_indent(indent);
3981 outs() << " protocol_list "
3982 << format("0x%08" PRIx32, protocol.protocol_list);
3983 if (print_protocol_list(protocol.protocol_list, indent + 4, info))
3984 outs() << " (not in an __OBJC section)\n";
3985
3986 print_indent(indent);
3987 outs() << " instance_methods "
3988 << format("0x%08" PRIx32, protocol.instance_methods);
3989 if (print_method_description_list(protocol.instance_methods, indent, info))
3990 outs() << " (not in an __OBJC section)\n";
3991
3992 print_indent(indent);
3993 outs() << " class_methods "
3994 << format("0x%08" PRIx32, protocol.class_methods);
3995 if (print_method_description_list(protocol.class_methods, indent, info))
3996 outs() << " (not in an __OBJC section)\n";
3997
3998 return false;
3999}
4000
4001static bool print_protocol_list(uint32_t p, uint32_t indent,
4002 struct DisassembleInfo *info) {
4003 uint32_t offset, left, l;
4004 SectionRef S;
4005 struct objc_protocol_list_t protocol_list;
4006 const char *r, *list;
4007 int32_t i;
4008
4009 r = get_pointer_32(p, offset, left, S, info, true);
4010 if (r == nullptr)
4011 return true;
4012
4013 outs() << "\n";
4014 if (left > sizeof(struct objc_protocol_list_t)) {
4015 memcpy(&protocol_list, r, sizeof(struct objc_protocol_list_t));
4016 } else {
4017 outs() << "\t\t objc_protocol_list_t extends past end of the section\n";
4018 memset(&protocol_list, '\0', sizeof(struct objc_protocol_list_t));
4019 memcpy(&protocol_list, r, left);
4020 }
4021 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4022 swapStruct(protocol_list);
4023
4024 print_indent(indent);
4025 outs() << " next " << format("0x%08" PRIx32, protocol_list.next)
4026 << "\n";
4027 print_indent(indent);
4028 outs() << " count " << protocol_list.count << "\n";
4029
4030 list = r + sizeof(struct objc_protocol_list_t);
4031 for (i = 0; i < protocol_list.count; i++) {
4032 if ((i + 1) * sizeof(uint32_t) > left) {
4033 outs() << "\t\t remaining list entries extend past the of the section\n";
4034 break;
4035 }
4036 memcpy(&l, list + i * sizeof(uint32_t), sizeof(uint32_t));
4037 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4038 sys::swapByteOrder(l);
4039
4040 print_indent(indent);
4041 outs() << " list[" << i << "] " << format("0x%08" PRIx32, l);
4042 if (print_protocol(l, indent, info))
4043 outs() << "(not in an __OBJC section)\n";
4044 }
4045 return false;
4046}
4047
Kevin Enderby0fc11822015-04-01 20:57:01 +00004048static void print_ivar_list64_t(uint64_t p, struct DisassembleInfo *info) {
4049 struct ivar_list64_t il;
4050 struct ivar64_t i;
4051 const char *r;
4052 uint32_t offset, xoffset, left, j;
4053 SectionRef S, xS;
4054 const char *name, *sym_name, *ivar_offset_p;
4055 uint64_t ivar_offset, n_value;
4056
4057 r = get_pointer_64(p, offset, left, S, info);
4058 if (r == nullptr)
4059 return;
4060 memset(&il, '\0', sizeof(struct ivar_list64_t));
4061 if (left < sizeof(struct ivar_list64_t)) {
4062 memcpy(&il, r, left);
4063 outs() << " (ivar_list_t entends past the end of the section)\n";
4064 } else
4065 memcpy(&il, r, sizeof(struct ivar_list64_t));
4066 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4067 swapStruct(il);
4068 outs() << " entsize " << il.entsize << "\n";
4069 outs() << " count " << il.count << "\n";
4070
4071 p += sizeof(struct ivar_list64_t);
4072 offset += sizeof(struct ivar_list64_t);
4073 for (j = 0; j < il.count; j++) {
4074 r = get_pointer_64(p, offset, left, S, info);
4075 if (r == nullptr)
4076 return;
4077 memset(&i, '\0', sizeof(struct ivar64_t));
4078 if (left < sizeof(struct ivar64_t)) {
4079 memcpy(&i, r, left);
4080 outs() << " (ivar_t entends past the end of the section)\n";
4081 } else
4082 memcpy(&i, r, sizeof(struct ivar64_t));
4083 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4084 swapStruct(i);
4085
4086 outs() << "\t\t\t offset ";
4087 sym_name = get_symbol_64(offset + offsetof(struct ivar64_t, offset), S,
4088 info, n_value, i.offset);
4089 if (n_value != 0) {
4090 if (info->verbose && sym_name != nullptr)
4091 outs() << sym_name;
4092 else
4093 outs() << format("0x%" PRIx64, n_value);
4094 if (i.offset != 0)
4095 outs() << " + " << format("0x%" PRIx64, i.offset);
4096 } else
4097 outs() << format("0x%" PRIx64, i.offset);
4098 ivar_offset_p = get_pointer_64(i.offset + n_value, xoffset, left, xS, info);
4099 if (ivar_offset_p != nullptr && left >= sizeof(*ivar_offset_p)) {
4100 memcpy(&ivar_offset, ivar_offset_p, sizeof(ivar_offset));
4101 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4102 sys::swapByteOrder(ivar_offset);
4103 outs() << " " << ivar_offset << "\n";
4104 } else
4105 outs() << "\n";
4106
4107 outs() << "\t\t\t name ";
4108 sym_name = get_symbol_64(offset + offsetof(struct ivar64_t, name), S, info,
4109 n_value, i.name);
4110 if (n_value != 0) {
4111 if (info->verbose && sym_name != nullptr)
4112 outs() << sym_name;
4113 else
4114 outs() << format("0x%" PRIx64, n_value);
4115 if (i.name != 0)
4116 outs() << " + " << format("0x%" PRIx64, i.name);
4117 } else
4118 outs() << format("0x%" PRIx64, i.name);
4119 name = get_pointer_64(i.name + n_value, xoffset, left, xS, info);
4120 if (name != nullptr)
4121 outs() << format(" %.*s", left, name);
4122 outs() << "\n";
4123
4124 outs() << "\t\t\t type ";
4125 sym_name = get_symbol_64(offset + offsetof(struct ivar64_t, type), S, info,
4126 n_value, i.name);
4127 name = get_pointer_64(i.type + n_value, xoffset, left, xS, info);
4128 if (n_value != 0) {
4129 if (info->verbose && sym_name != nullptr)
4130 outs() << sym_name;
4131 else
4132 outs() << format("0x%" PRIx64, n_value);
4133 if (i.type != 0)
4134 outs() << " + " << format("0x%" PRIx64, i.type);
4135 } else
4136 outs() << format("0x%" PRIx64, i.type);
4137 if (name != nullptr)
4138 outs() << format(" %.*s", left, name);
4139 outs() << "\n";
4140
4141 outs() << "\t\t\talignment " << i.alignment << "\n";
4142 outs() << "\t\t\t size " << i.size << "\n";
4143
4144 p += sizeof(struct ivar64_t);
4145 offset += sizeof(struct ivar64_t);
4146 }
4147}
4148
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004149static void print_ivar_list32_t(uint32_t p, struct DisassembleInfo *info) {
4150 struct ivar_list32_t il;
4151 struct ivar32_t i;
4152 const char *r;
4153 uint32_t offset, xoffset, left, j;
4154 SectionRef S, xS;
4155 const char *name, *ivar_offset_p;
4156 uint32_t ivar_offset;
4157
4158 r = get_pointer_32(p, offset, left, S, info);
4159 if (r == nullptr)
4160 return;
4161 memset(&il, '\0', sizeof(struct ivar_list32_t));
4162 if (left < sizeof(struct ivar_list32_t)) {
4163 memcpy(&il, r, left);
4164 outs() << " (ivar_list_t entends past the end of the section)\n";
4165 } else
4166 memcpy(&il, r, sizeof(struct ivar_list32_t));
4167 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4168 swapStruct(il);
4169 outs() << " entsize " << il.entsize << "\n";
4170 outs() << " count " << il.count << "\n";
4171
4172 p += sizeof(struct ivar_list32_t);
4173 offset += sizeof(struct ivar_list32_t);
4174 for (j = 0; j < il.count; j++) {
4175 r = get_pointer_32(p, offset, left, S, info);
4176 if (r == nullptr)
4177 return;
4178 memset(&i, '\0', sizeof(struct ivar32_t));
4179 if (left < sizeof(struct ivar32_t)) {
4180 memcpy(&i, r, left);
4181 outs() << " (ivar_t entends past the end of the section)\n";
4182 } else
4183 memcpy(&i, r, sizeof(struct ivar32_t));
4184 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4185 swapStruct(i);
4186
4187 outs() << "\t\t\t offset " << format("0x%" PRIx32, i.offset);
4188 ivar_offset_p = get_pointer_32(i.offset, xoffset, left, xS, info);
4189 if (ivar_offset_p != nullptr && left >= sizeof(*ivar_offset_p)) {
4190 memcpy(&ivar_offset, ivar_offset_p, sizeof(ivar_offset));
4191 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4192 sys::swapByteOrder(ivar_offset);
4193 outs() << " " << ivar_offset << "\n";
4194 } else
4195 outs() << "\n";
4196
4197 outs() << "\t\t\t name " << format("0x%" PRIx32, i.name);
4198 name = get_pointer_32(i.name, xoffset, left, xS, info);
4199 if (name != nullptr)
4200 outs() << format(" %.*s", left, name);
4201 outs() << "\n";
4202
4203 outs() << "\t\t\t type " << format("0x%" PRIx32, i.type);
4204 name = get_pointer_32(i.type, xoffset, left, xS, info);
4205 if (name != nullptr)
4206 outs() << format(" %.*s", left, name);
4207 outs() << "\n";
4208
4209 outs() << "\t\t\talignment " << i.alignment << "\n";
4210 outs() << "\t\t\t size " << i.size << "\n";
4211
4212 p += sizeof(struct ivar32_t);
4213 offset += sizeof(struct ivar32_t);
4214 }
4215}
4216
Kevin Enderby0fc11822015-04-01 20:57:01 +00004217static void print_objc_property_list64(uint64_t p,
4218 struct DisassembleInfo *info) {
4219 struct objc_property_list64 opl;
4220 struct objc_property64 op;
4221 const char *r;
4222 uint32_t offset, xoffset, left, j;
4223 SectionRef S, xS;
4224 const char *name, *sym_name;
4225 uint64_t n_value;
4226
4227 r = get_pointer_64(p, offset, left, S, info);
4228 if (r == nullptr)
4229 return;
4230 memset(&opl, '\0', sizeof(struct objc_property_list64));
4231 if (left < sizeof(struct objc_property_list64)) {
4232 memcpy(&opl, r, left);
4233 outs() << " (objc_property_list entends past the end of the section)\n";
4234 } else
4235 memcpy(&opl, r, sizeof(struct objc_property_list64));
4236 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4237 swapStruct(opl);
4238 outs() << " entsize " << opl.entsize << "\n";
4239 outs() << " count " << opl.count << "\n";
4240
4241 p += sizeof(struct objc_property_list64);
4242 offset += sizeof(struct objc_property_list64);
4243 for (j = 0; j < opl.count; j++) {
4244 r = get_pointer_64(p, offset, left, S, info);
4245 if (r == nullptr)
4246 return;
4247 memset(&op, '\0', sizeof(struct objc_property64));
4248 if (left < sizeof(struct objc_property64)) {
4249 memcpy(&op, r, left);
4250 outs() << " (objc_property entends past the end of the section)\n";
4251 } else
4252 memcpy(&op, r, sizeof(struct objc_property64));
4253 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4254 swapStruct(op);
4255
4256 outs() << "\t\t\t name ";
4257 sym_name = get_symbol_64(offset + offsetof(struct objc_property64, name), S,
4258 info, n_value, op.name);
4259 if (n_value != 0) {
4260 if (info->verbose && sym_name != nullptr)
4261 outs() << sym_name;
4262 else
4263 outs() << format("0x%" PRIx64, n_value);
4264 if (op.name != 0)
4265 outs() << " + " << format("0x%" PRIx64, op.name);
4266 } else
4267 outs() << format("0x%" PRIx64, op.name);
4268 name = get_pointer_64(op.name + n_value, xoffset, left, xS, info);
4269 if (name != nullptr)
4270 outs() << format(" %.*s", left, name);
4271 outs() << "\n";
4272
4273 outs() << "\t\t\tattributes ";
4274 sym_name =
4275 get_symbol_64(offset + offsetof(struct objc_property64, attributes), S,
4276 info, n_value, op.attributes);
4277 if (n_value != 0) {
4278 if (info->verbose && sym_name != nullptr)
4279 outs() << sym_name;
4280 else
4281 outs() << format("0x%" PRIx64, n_value);
4282 if (op.attributes != 0)
4283 outs() << " + " << format("0x%" PRIx64, op.attributes);
4284 } else
4285 outs() << format("0x%" PRIx64, op.attributes);
4286 name = get_pointer_64(op.attributes + n_value, xoffset, left, xS, info);
4287 if (name != nullptr)
4288 outs() << format(" %.*s", left, name);
4289 outs() << "\n";
4290
4291 p += sizeof(struct objc_property64);
4292 offset += sizeof(struct objc_property64);
4293 }
4294}
4295
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004296static void print_objc_property_list32(uint32_t p,
4297 struct DisassembleInfo *info) {
4298 struct objc_property_list32 opl;
4299 struct objc_property32 op;
4300 const char *r;
4301 uint32_t offset, xoffset, left, j;
4302 SectionRef S, xS;
4303 const char *name;
4304
4305 r = get_pointer_32(p, offset, left, S, info);
4306 if (r == nullptr)
4307 return;
4308 memset(&opl, '\0', sizeof(struct objc_property_list32));
4309 if (left < sizeof(struct objc_property_list32)) {
4310 memcpy(&opl, r, left);
4311 outs() << " (objc_property_list entends past the end of the section)\n";
4312 } else
4313 memcpy(&opl, r, sizeof(struct objc_property_list32));
4314 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4315 swapStruct(opl);
4316 outs() << " entsize " << opl.entsize << "\n";
4317 outs() << " count " << opl.count << "\n";
4318
4319 p += sizeof(struct objc_property_list32);
4320 offset += sizeof(struct objc_property_list32);
4321 for (j = 0; j < opl.count; j++) {
4322 r = get_pointer_32(p, offset, left, S, info);
4323 if (r == nullptr)
4324 return;
4325 memset(&op, '\0', sizeof(struct objc_property32));
4326 if (left < sizeof(struct objc_property32)) {
4327 memcpy(&op, r, left);
4328 outs() << " (objc_property entends past the end of the section)\n";
4329 } else
4330 memcpy(&op, r, sizeof(struct objc_property32));
4331 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4332 swapStruct(op);
4333
4334 outs() << "\t\t\t name " << format("0x%" PRIx32, op.name);
4335 name = get_pointer_32(op.name, xoffset, left, xS, info);
4336 if (name != nullptr)
4337 outs() << format(" %.*s", left, name);
4338 outs() << "\n";
4339
4340 outs() << "\t\t\tattributes " << format("0x%" PRIx32, op.attributes);
4341 name = get_pointer_32(op.attributes, xoffset, left, xS, info);
4342 if (name != nullptr)
4343 outs() << format(" %.*s", left, name);
4344 outs() << "\n";
4345
4346 p += sizeof(struct objc_property32);
4347 offset += sizeof(struct objc_property32);
4348 }
4349}
4350
Richard Smith81ff44d2015-10-09 22:09:56 +00004351static bool print_class_ro64_t(uint64_t p, struct DisassembleInfo *info,
Kevin Enderby0fc11822015-04-01 20:57:01 +00004352 bool &is_meta_class) {
4353 struct class_ro64_t cro;
4354 const char *r;
4355 uint32_t offset, xoffset, left;
4356 SectionRef S, xS;
4357 const char *name, *sym_name;
4358 uint64_t n_value;
4359
4360 r = get_pointer_64(p, offset, left, S, info);
4361 if (r == nullptr || left < sizeof(struct class_ro64_t))
Richard Smith81ff44d2015-10-09 22:09:56 +00004362 return false;
Chandler Carruth33e58902016-11-04 07:10:24 +00004363 memcpy(&cro, r, sizeof(struct class_ro64_t));
Kevin Enderby0fc11822015-04-01 20:57:01 +00004364 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4365 swapStruct(cro);
4366 outs() << " flags " << format("0x%" PRIx32, cro.flags);
4367 if (cro.flags & RO_META)
4368 outs() << " RO_META";
4369 if (cro.flags & RO_ROOT)
4370 outs() << " RO_ROOT";
4371 if (cro.flags & RO_HAS_CXX_STRUCTORS)
4372 outs() << " RO_HAS_CXX_STRUCTORS";
4373 outs() << "\n";
4374 outs() << " instanceStart " << cro.instanceStart << "\n";
4375 outs() << " instanceSize " << cro.instanceSize << "\n";
4376 outs() << " reserved " << format("0x%" PRIx32, cro.reserved)
4377 << "\n";
4378 outs() << " ivarLayout " << format("0x%" PRIx64, cro.ivarLayout)
4379 << "\n";
4380 print_layout_map64(cro.ivarLayout, info);
4381
4382 outs() << " name ";
4383 sym_name = get_symbol_64(offset + offsetof(struct class_ro64_t, name), S,
4384 info, n_value, cro.name);
4385 if (n_value != 0) {
4386 if (info->verbose && sym_name != nullptr)
4387 outs() << sym_name;
4388 else
4389 outs() << format("0x%" PRIx64, n_value);
4390 if (cro.name != 0)
4391 outs() << " + " << format("0x%" PRIx64, cro.name);
4392 } else
4393 outs() << format("0x%" PRIx64, cro.name);
4394 name = get_pointer_64(cro.name + n_value, xoffset, left, xS, info);
4395 if (name != nullptr)
4396 outs() << format(" %.*s", left, name);
4397 outs() << "\n";
4398
4399 outs() << " baseMethods ";
4400 sym_name = get_symbol_64(offset + offsetof(struct class_ro64_t, baseMethods),
4401 S, info, n_value, cro.baseMethods);
4402 if (n_value != 0) {
4403 if (info->verbose && sym_name != nullptr)
4404 outs() << sym_name;
4405 else
4406 outs() << format("0x%" PRIx64, n_value);
4407 if (cro.baseMethods != 0)
4408 outs() << " + " << format("0x%" PRIx64, cro.baseMethods);
4409 } else
4410 outs() << format("0x%" PRIx64, cro.baseMethods);
4411 outs() << " (struct method_list_t *)\n";
4412 if (cro.baseMethods + n_value != 0)
4413 print_method_list64_t(cro.baseMethods + n_value, info, "");
4414
4415 outs() << " baseProtocols ";
4416 sym_name =
4417 get_symbol_64(offset + offsetof(struct class_ro64_t, baseProtocols), S,
4418 info, n_value, cro.baseProtocols);
4419 if (n_value != 0) {
4420 if (info->verbose && sym_name != nullptr)
4421 outs() << sym_name;
4422 else
4423 outs() << format("0x%" PRIx64, n_value);
4424 if (cro.baseProtocols != 0)
4425 outs() << " + " << format("0x%" PRIx64, cro.baseProtocols);
4426 } else
4427 outs() << format("0x%" PRIx64, cro.baseProtocols);
4428 outs() << "\n";
4429 if (cro.baseProtocols + n_value != 0)
4430 print_protocol_list64_t(cro.baseProtocols + n_value, info);
4431
4432 outs() << " ivars ";
4433 sym_name = get_symbol_64(offset + offsetof(struct class_ro64_t, ivars), S,
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004434 info, n_value, cro.ivars);
Kevin Enderby0fc11822015-04-01 20:57:01 +00004435 if (n_value != 0) {
4436 if (info->verbose && sym_name != nullptr)
4437 outs() << sym_name;
4438 else
4439 outs() << format("0x%" PRIx64, n_value);
4440 if (cro.ivars != 0)
4441 outs() << " + " << format("0x%" PRIx64, cro.ivars);
4442 } else
4443 outs() << format("0x%" PRIx64, cro.ivars);
4444 outs() << "\n";
4445 if (cro.ivars + n_value != 0)
4446 print_ivar_list64_t(cro.ivars + n_value, info);
4447
4448 outs() << " weakIvarLayout ";
4449 sym_name =
4450 get_symbol_64(offset + offsetof(struct class_ro64_t, weakIvarLayout), S,
4451 info, n_value, cro.weakIvarLayout);
4452 if (n_value != 0) {
4453 if (info->verbose && sym_name != nullptr)
4454 outs() << sym_name;
4455 else
4456 outs() << format("0x%" PRIx64, n_value);
4457 if (cro.weakIvarLayout != 0)
4458 outs() << " + " << format("0x%" PRIx64, cro.weakIvarLayout);
4459 } else
4460 outs() << format("0x%" PRIx64, cro.weakIvarLayout);
4461 outs() << "\n";
4462 print_layout_map64(cro.weakIvarLayout + n_value, info);
4463
4464 outs() << " baseProperties ";
4465 sym_name =
4466 get_symbol_64(offset + offsetof(struct class_ro64_t, baseProperties), S,
4467 info, n_value, cro.baseProperties);
4468 if (n_value != 0) {
4469 if (info->verbose && sym_name != nullptr)
4470 outs() << sym_name;
4471 else
4472 outs() << format("0x%" PRIx64, n_value);
4473 if (cro.baseProperties != 0)
4474 outs() << " + " << format("0x%" PRIx64, cro.baseProperties);
4475 } else
4476 outs() << format("0x%" PRIx64, cro.baseProperties);
4477 outs() << "\n";
4478 if (cro.baseProperties + n_value != 0)
4479 print_objc_property_list64(cro.baseProperties + n_value, info);
4480
Rafael Espindolab9091322015-10-24 23:19:10 +00004481 is_meta_class = (cro.flags & RO_META) != 0;
Richard Smith81ff44d2015-10-09 22:09:56 +00004482 return true;
Kevin Enderby0fc11822015-04-01 20:57:01 +00004483}
4484
Richard Smith81ff44d2015-10-09 22:09:56 +00004485static bool print_class_ro32_t(uint32_t p, struct DisassembleInfo *info,
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004486 bool &is_meta_class) {
4487 struct class_ro32_t cro;
4488 const char *r;
4489 uint32_t offset, xoffset, left;
4490 SectionRef S, xS;
4491 const char *name;
4492
4493 r = get_pointer_32(p, offset, left, S, info);
4494 if (r == nullptr)
Richard Smith81ff44d2015-10-09 22:09:56 +00004495 return false;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004496 memset(&cro, '\0', sizeof(struct class_ro32_t));
4497 if (left < sizeof(struct class_ro32_t)) {
4498 memcpy(&cro, r, left);
4499 outs() << " (class_ro_t entends past the end of the section)\n";
4500 } else
4501 memcpy(&cro, r, sizeof(struct class_ro32_t));
4502 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4503 swapStruct(cro);
4504 outs() << " flags " << format("0x%" PRIx32, cro.flags);
4505 if (cro.flags & RO_META)
4506 outs() << " RO_META";
4507 if (cro.flags & RO_ROOT)
4508 outs() << " RO_ROOT";
4509 if (cro.flags & RO_HAS_CXX_STRUCTORS)
4510 outs() << " RO_HAS_CXX_STRUCTORS";
4511 outs() << "\n";
4512 outs() << " instanceStart " << cro.instanceStart << "\n";
4513 outs() << " instanceSize " << cro.instanceSize << "\n";
4514 outs() << " ivarLayout " << format("0x%" PRIx32, cro.ivarLayout)
4515 << "\n";
4516 print_layout_map32(cro.ivarLayout, info);
4517
4518 outs() << " name " << format("0x%" PRIx32, cro.name);
4519 name = get_pointer_32(cro.name, xoffset, left, xS, info);
4520 if (name != nullptr)
4521 outs() << format(" %.*s", left, name);
4522 outs() << "\n";
4523
4524 outs() << " baseMethods "
4525 << format("0x%" PRIx32, cro.baseMethods)
4526 << " (struct method_list_t *)\n";
4527 if (cro.baseMethods != 0)
4528 print_method_list32_t(cro.baseMethods, info, "");
4529
4530 outs() << " baseProtocols "
4531 << format("0x%" PRIx32, cro.baseProtocols) << "\n";
4532 if (cro.baseProtocols != 0)
4533 print_protocol_list32_t(cro.baseProtocols, info);
4534 outs() << " ivars " << format("0x%" PRIx32, cro.ivars)
4535 << "\n";
4536 if (cro.ivars != 0)
4537 print_ivar_list32_t(cro.ivars, info);
4538 outs() << " weakIvarLayout "
4539 << format("0x%" PRIx32, cro.weakIvarLayout) << "\n";
4540 print_layout_map32(cro.weakIvarLayout, info);
4541 outs() << " baseProperties "
4542 << format("0x%" PRIx32, cro.baseProperties) << "\n";
4543 if (cro.baseProperties != 0)
4544 print_objc_property_list32(cro.baseProperties, info);
Rafael Espindolab9091322015-10-24 23:19:10 +00004545 is_meta_class = (cro.flags & RO_META) != 0;
Richard Smith81ff44d2015-10-09 22:09:56 +00004546 return true;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004547}
4548
Kevin Enderby0fc11822015-04-01 20:57:01 +00004549static void print_class64_t(uint64_t p, struct DisassembleInfo *info) {
4550 struct class64_t c;
4551 const char *r;
4552 uint32_t offset, left;
4553 SectionRef S;
4554 const char *name;
4555 uint64_t isa_n_value, n_value;
4556
4557 r = get_pointer_64(p, offset, left, S, info);
4558 if (r == nullptr || left < sizeof(struct class64_t))
4559 return;
Chandler Carruth33e58902016-11-04 07:10:24 +00004560 memcpy(&c, r, sizeof(struct class64_t));
Kevin Enderby0fc11822015-04-01 20:57:01 +00004561 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4562 swapStruct(c);
4563
4564 outs() << " isa " << format("0x%" PRIx64, c.isa);
4565 name = get_symbol_64(offset + offsetof(struct class64_t, isa), S, info,
4566 isa_n_value, c.isa);
4567 if (name != nullptr)
4568 outs() << " " << name;
4569 outs() << "\n";
4570
4571 outs() << " superclass " << format("0x%" PRIx64, c.superclass);
4572 name = get_symbol_64(offset + offsetof(struct class64_t, superclass), S, info,
4573 n_value, c.superclass);
4574 if (name != nullptr)
4575 outs() << " " << name;
Kevin Enderby1ce38582017-06-20 22:55:11 +00004576 else {
4577 name = get_dyld_bind_info_symbolname(S.getAddress() +
4578 offset + offsetof(struct class64_t, superclass), info);
4579 if (name != nullptr)
4580 outs() << " " << name;
4581 }
Kevin Enderby0fc11822015-04-01 20:57:01 +00004582 outs() << "\n";
4583
4584 outs() << " cache " << format("0x%" PRIx64, c.cache);
4585 name = get_symbol_64(offset + offsetof(struct class64_t, cache), S, info,
4586 n_value, c.cache);
4587 if (name != nullptr)
4588 outs() << " " << name;
4589 outs() << "\n";
4590
4591 outs() << " vtable " << format("0x%" PRIx64, c.vtable);
4592 name = get_symbol_64(offset + offsetof(struct class64_t, vtable), S, info,
4593 n_value, c.vtable);
4594 if (name != nullptr)
4595 outs() << " " << name;
4596 outs() << "\n";
4597
4598 name = get_symbol_64(offset + offsetof(struct class64_t, data), S, info,
4599 n_value, c.data);
4600 outs() << " data ";
4601 if (n_value != 0) {
4602 if (info->verbose && name != nullptr)
4603 outs() << name;
4604 else
4605 outs() << format("0x%" PRIx64, n_value);
4606 if (c.data != 0)
4607 outs() << " + " << format("0x%" PRIx64, c.data);
4608 } else
4609 outs() << format("0x%" PRIx64, c.data);
4610 outs() << " (struct class_ro_t *)";
4611
4612 // This is a Swift class if some of the low bits of the pointer are set.
4613 if ((c.data + n_value) & 0x7)
4614 outs() << " Swift class";
4615 outs() << "\n";
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004616 bool is_meta_class;
Richard Smith81ff44d2015-10-09 22:09:56 +00004617 if (!print_class_ro64_t((c.data + n_value) & ~0x7, info, is_meta_class))
4618 return;
Kevin Enderby0fc11822015-04-01 20:57:01 +00004619
Kevin Enderbyaac75382015-10-08 16:56:35 +00004620 if (!is_meta_class &&
4621 c.isa + isa_n_value != p &&
4622 c.isa + isa_n_value != 0 &&
4623 info->depth < 100) {
4624 info->depth++;
4625 outs() << "Meta Class\n";
4626 print_class64_t(c.isa + isa_n_value, info);
Kevin Enderby0fc11822015-04-01 20:57:01 +00004627 }
4628}
4629
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004630static void print_class32_t(uint32_t p, struct DisassembleInfo *info) {
4631 struct class32_t c;
4632 const char *r;
4633 uint32_t offset, left;
4634 SectionRef S;
4635 const char *name;
4636
4637 r = get_pointer_32(p, offset, left, S, info);
4638 if (r == nullptr)
4639 return;
4640 memset(&c, '\0', sizeof(struct class32_t));
4641 if (left < sizeof(struct class32_t)) {
4642 memcpy(&c, r, left);
4643 outs() << " (class_t entends past the end of the section)\n";
4644 } else
4645 memcpy(&c, r, sizeof(struct class32_t));
4646 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4647 swapStruct(c);
4648
4649 outs() << " isa " << format("0x%" PRIx32, c.isa);
4650 name =
4651 get_symbol_32(offset + offsetof(struct class32_t, isa), S, info, c.isa);
4652 if (name != nullptr)
4653 outs() << " " << name;
4654 outs() << "\n";
4655
4656 outs() << " superclass " << format("0x%" PRIx32, c.superclass);
4657 name = get_symbol_32(offset + offsetof(struct class32_t, superclass), S, info,
4658 c.superclass);
4659 if (name != nullptr)
4660 outs() << " " << name;
4661 outs() << "\n";
4662
4663 outs() << " cache " << format("0x%" PRIx32, c.cache);
4664 name = get_symbol_32(offset + offsetof(struct class32_t, cache), S, info,
4665 c.cache);
4666 if (name != nullptr)
4667 outs() << " " << name;
4668 outs() << "\n";
4669
4670 outs() << " vtable " << format("0x%" PRIx32, c.vtable);
4671 name = get_symbol_32(offset + offsetof(struct class32_t, vtable), S, info,
4672 c.vtable);
4673 if (name != nullptr)
4674 outs() << " " << name;
4675 outs() << "\n";
4676
4677 name =
4678 get_symbol_32(offset + offsetof(struct class32_t, data), S, info, c.data);
4679 outs() << " data " << format("0x%" PRIx32, c.data)
4680 << " (struct class_ro_t *)";
4681
4682 // This is a Swift class if some of the low bits of the pointer are set.
4683 if (c.data & 0x3)
4684 outs() << " Swift class";
4685 outs() << "\n";
4686 bool is_meta_class;
Richard Smith81ff44d2015-10-09 22:09:56 +00004687 if (!print_class_ro32_t(c.data & ~0x3, info, is_meta_class))
4688 return;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004689
Hans Wennborgcc9deb42015-09-29 18:02:48 +00004690 if (!is_meta_class) {
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004691 outs() << "Meta Class\n";
4692 print_class32_t(c.isa, info);
4693 }
4694}
4695
Kevin Enderby846c0002015-04-16 17:19:59 +00004696static void print_objc_class_t(struct objc_class_t *objc_class,
4697 struct DisassembleInfo *info) {
4698 uint32_t offset, left, xleft;
4699 const char *name, *p, *ivar_list;
4700 SectionRef S;
4701 int32_t i;
4702 struct objc_ivar_list_t objc_ivar_list;
4703 struct objc_ivar_t ivar;
4704
4705 outs() << "\t\t isa " << format("0x%08" PRIx32, objc_class->isa);
4706 if (info->verbose && CLS_GETINFO(objc_class, CLS_META)) {
4707 name = get_pointer_32(objc_class->isa, offset, left, S, info, true);
4708 if (name != nullptr)
4709 outs() << format(" %.*s", left, name);
4710 else
4711 outs() << " (not in an __OBJC section)";
4712 }
4713 outs() << "\n";
4714
4715 outs() << "\t super_class "
4716 << format("0x%08" PRIx32, objc_class->super_class);
4717 if (info->verbose) {
4718 name = get_pointer_32(objc_class->super_class, offset, left, S, info, true);
4719 if (name != nullptr)
4720 outs() << format(" %.*s", left, name);
4721 else
4722 outs() << " (not in an __OBJC section)";
4723 }
4724 outs() << "\n";
4725
4726 outs() << "\t\t name " << format("0x%08" PRIx32, objc_class->name);
4727 if (info->verbose) {
4728 name = get_pointer_32(objc_class->name, offset, left, S, info, true);
4729 if (name != nullptr)
4730 outs() << format(" %.*s", left, name);
4731 else
4732 outs() << " (not in an __OBJC section)";
4733 }
4734 outs() << "\n";
4735
4736 outs() << "\t\t version " << format("0x%08" PRIx32, objc_class->version)
4737 << "\n";
4738
4739 outs() << "\t\t info " << format("0x%08" PRIx32, objc_class->info);
4740 if (info->verbose) {
4741 if (CLS_GETINFO(objc_class, CLS_CLASS))
4742 outs() << " CLS_CLASS";
4743 else if (CLS_GETINFO(objc_class, CLS_META))
4744 outs() << " CLS_META";
4745 }
4746 outs() << "\n";
4747
4748 outs() << "\t instance_size "
4749 << format("0x%08" PRIx32, objc_class->instance_size) << "\n";
4750
4751 p = get_pointer_32(objc_class->ivars, offset, left, S, info, true);
4752 outs() << "\t\t ivars " << format("0x%08" PRIx32, objc_class->ivars);
4753 if (p != nullptr) {
4754 if (left > sizeof(struct objc_ivar_list_t)) {
4755 outs() << "\n";
4756 memcpy(&objc_ivar_list, p, sizeof(struct objc_ivar_list_t));
4757 } else {
4758 outs() << " (entends past the end of the section)\n";
4759 memset(&objc_ivar_list, '\0', sizeof(struct objc_ivar_list_t));
4760 memcpy(&objc_ivar_list, p, left);
4761 }
4762 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4763 swapStruct(objc_ivar_list);
4764 outs() << "\t\t ivar_count " << objc_ivar_list.ivar_count << "\n";
4765 ivar_list = p + sizeof(struct objc_ivar_list_t);
4766 for (i = 0; i < objc_ivar_list.ivar_count; i++) {
4767 if ((i + 1) * sizeof(struct objc_ivar_t) > left) {
4768 outs() << "\t\t remaining ivar's extend past the of the section\n";
4769 break;
4770 }
4771 memcpy(&ivar, ivar_list + i * sizeof(struct objc_ivar_t),
4772 sizeof(struct objc_ivar_t));
4773 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4774 swapStruct(ivar);
4775
4776 outs() << "\t\t\tivar_name " << format("0x%08" PRIx32, ivar.ivar_name);
4777 if (info->verbose) {
4778 name = get_pointer_32(ivar.ivar_name, offset, xleft, S, info, true);
4779 if (name != nullptr)
4780 outs() << format(" %.*s", xleft, name);
4781 else
4782 outs() << " (not in an __OBJC section)";
4783 }
4784 outs() << "\n";
4785
4786 outs() << "\t\t\tivar_type " << format("0x%08" PRIx32, ivar.ivar_type);
4787 if (info->verbose) {
4788 name = get_pointer_32(ivar.ivar_type, offset, xleft, S, info, true);
4789 if (name != nullptr)
4790 outs() << format(" %.*s", xleft, name);
4791 else
4792 outs() << " (not in an __OBJC section)";
4793 }
4794 outs() << "\n";
4795
4796 outs() << "\t\t ivar_offset "
4797 << format("0x%08" PRIx32, ivar.ivar_offset) << "\n";
4798 }
4799 } else {
4800 outs() << " (not in an __OBJC section)\n";
4801 }
4802
4803 outs() << "\t\t methods " << format("0x%08" PRIx32, objc_class->methodLists);
4804 if (print_method_list(objc_class->methodLists, info))
4805 outs() << " (not in an __OBJC section)\n";
4806
4807 outs() << "\t\t cache " << format("0x%08" PRIx32, objc_class->cache)
4808 << "\n";
4809
4810 outs() << "\t\tprotocols " << format("0x%08" PRIx32, objc_class->protocols);
4811 if (print_protocol_list(objc_class->protocols, 16, info))
4812 outs() << " (not in an __OBJC section)\n";
4813}
4814
4815static void print_objc_objc_category_t(struct objc_category_t *objc_category,
4816 struct DisassembleInfo *info) {
4817 uint32_t offset, left;
4818 const char *name;
4819 SectionRef S;
4820
4821 outs() << "\t category name "
4822 << format("0x%08" PRIx32, objc_category->category_name);
4823 if (info->verbose) {
4824 name = get_pointer_32(objc_category->category_name, offset, left, S, info,
4825 true);
4826 if (name != nullptr)
4827 outs() << format(" %.*s", left, name);
4828 else
4829 outs() << " (not in an __OBJC section)";
4830 }
4831 outs() << "\n";
4832
4833 outs() << "\t\t class name "
4834 << format("0x%08" PRIx32, objc_category->class_name);
4835 if (info->verbose) {
4836 name =
4837 get_pointer_32(objc_category->class_name, offset, left, S, info, true);
4838 if (name != nullptr)
4839 outs() << format(" %.*s", left, name);
4840 else
4841 outs() << " (not in an __OBJC section)";
4842 }
4843 outs() << "\n";
4844
4845 outs() << "\t instance methods "
4846 << format("0x%08" PRIx32, objc_category->instance_methods);
4847 if (print_method_list(objc_category->instance_methods, info))
4848 outs() << " (not in an __OBJC section)\n";
4849
4850 outs() << "\t class methods "
4851 << format("0x%08" PRIx32, objc_category->class_methods);
4852 if (print_method_list(objc_category->class_methods, info))
4853 outs() << " (not in an __OBJC section)\n";
4854}
4855
Kevin Enderby0fc11822015-04-01 20:57:01 +00004856static void print_category64_t(uint64_t p, struct DisassembleInfo *info) {
4857 struct category64_t c;
4858 const char *r;
4859 uint32_t offset, xoffset, left;
4860 SectionRef S, xS;
4861 const char *name, *sym_name;
4862 uint64_t n_value;
4863
4864 r = get_pointer_64(p, offset, left, S, info);
4865 if (r == nullptr)
4866 return;
4867 memset(&c, '\0', sizeof(struct category64_t));
4868 if (left < sizeof(struct category64_t)) {
4869 memcpy(&c, r, left);
4870 outs() << " (category_t entends past the end of the section)\n";
4871 } else
4872 memcpy(&c, r, sizeof(struct category64_t));
4873 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4874 swapStruct(c);
4875
4876 outs() << " name ";
4877 sym_name = get_symbol_64(offset + offsetof(struct category64_t, name), S,
4878 info, n_value, c.name);
4879 if (n_value != 0) {
4880 if (info->verbose && sym_name != nullptr)
4881 outs() << sym_name;
4882 else
4883 outs() << format("0x%" PRIx64, n_value);
4884 if (c.name != 0)
4885 outs() << " + " << format("0x%" PRIx64, c.name);
4886 } else
4887 outs() << format("0x%" PRIx64, c.name);
4888 name = get_pointer_64(c.name + n_value, xoffset, left, xS, info);
4889 if (name != nullptr)
4890 outs() << format(" %.*s", left, name);
4891 outs() << "\n";
4892
4893 outs() << " cls ";
4894 sym_name = get_symbol_64(offset + offsetof(struct category64_t, cls), S, info,
4895 n_value, c.cls);
4896 if (n_value != 0) {
4897 if (info->verbose && sym_name != nullptr)
4898 outs() << sym_name;
4899 else
4900 outs() << format("0x%" PRIx64, n_value);
4901 if (c.cls != 0)
4902 outs() << " + " << format("0x%" PRIx64, c.cls);
4903 } else
4904 outs() << format("0x%" PRIx64, c.cls);
4905 outs() << "\n";
4906 if (c.cls + n_value != 0)
4907 print_class64_t(c.cls + n_value, info);
4908
4909 outs() << " instanceMethods ";
4910 sym_name =
4911 get_symbol_64(offset + offsetof(struct category64_t, instanceMethods), S,
4912 info, n_value, c.instanceMethods);
4913 if (n_value != 0) {
4914 if (info->verbose && sym_name != nullptr)
4915 outs() << sym_name;
4916 else
4917 outs() << format("0x%" PRIx64, n_value);
4918 if (c.instanceMethods != 0)
4919 outs() << " + " << format("0x%" PRIx64, c.instanceMethods);
4920 } else
4921 outs() << format("0x%" PRIx64, c.instanceMethods);
4922 outs() << "\n";
4923 if (c.instanceMethods + n_value != 0)
4924 print_method_list64_t(c.instanceMethods + n_value, info, "");
4925
4926 outs() << " classMethods ";
4927 sym_name = get_symbol_64(offset + offsetof(struct category64_t, classMethods),
4928 S, info, n_value, c.classMethods);
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.classMethods != 0)
4935 outs() << " + " << format("0x%" PRIx64, c.classMethods);
4936 } else
4937 outs() << format("0x%" PRIx64, c.classMethods);
4938 outs() << "\n";
4939 if (c.classMethods + n_value != 0)
4940 print_method_list64_t(c.classMethods + n_value, info, "");
4941
4942 outs() << " protocols ";
4943 sym_name = get_symbol_64(offset + offsetof(struct category64_t, protocols), S,
4944 info, n_value, c.protocols);
4945 if (n_value != 0) {
4946 if (info->verbose && sym_name != nullptr)
4947 outs() << sym_name;
4948 else
4949 outs() << format("0x%" PRIx64, n_value);
4950 if (c.protocols != 0)
4951 outs() << " + " << format("0x%" PRIx64, c.protocols);
4952 } else
4953 outs() << format("0x%" PRIx64, c.protocols);
4954 outs() << "\n";
4955 if (c.protocols + n_value != 0)
4956 print_protocol_list64_t(c.protocols + n_value, info);
4957
4958 outs() << "instanceProperties ";
4959 sym_name =
4960 get_symbol_64(offset + offsetof(struct category64_t, instanceProperties),
4961 S, info, n_value, c.instanceProperties);
4962 if (n_value != 0) {
4963 if (info->verbose && sym_name != nullptr)
4964 outs() << sym_name;
4965 else
4966 outs() << format("0x%" PRIx64, n_value);
4967 if (c.instanceProperties != 0)
4968 outs() << " + " << format("0x%" PRIx64, c.instanceProperties);
4969 } else
4970 outs() << format("0x%" PRIx64, c.instanceProperties);
4971 outs() << "\n";
4972 if (c.instanceProperties + n_value != 0)
4973 print_objc_property_list64(c.instanceProperties + n_value, info);
4974}
4975
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004976static void print_category32_t(uint32_t p, struct DisassembleInfo *info) {
4977 struct category32_t c;
4978 const char *r;
4979 uint32_t offset, left;
4980 SectionRef S, xS;
4981 const char *name;
4982
4983 r = get_pointer_32(p, offset, left, S, info);
4984 if (r == nullptr)
4985 return;
4986 memset(&c, '\0', sizeof(struct category32_t));
4987 if (left < sizeof(struct category32_t)) {
4988 memcpy(&c, r, left);
4989 outs() << " (category_t entends past the end of the section)\n";
4990 } else
4991 memcpy(&c, r, sizeof(struct category32_t));
4992 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4993 swapStruct(c);
4994
4995 outs() << " name " << format("0x%" PRIx32, c.name);
4996 name = get_symbol_32(offset + offsetof(struct category32_t, name), S, info,
4997 c.name);
Hans Wennborgcc9deb42015-09-29 18:02:48 +00004998 if (name)
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004999 outs() << " " << name;
5000 outs() << "\n";
5001
5002 outs() << " cls " << format("0x%" PRIx32, c.cls) << "\n";
5003 if (c.cls != 0)
5004 print_class32_t(c.cls, info);
5005 outs() << " instanceMethods " << format("0x%" PRIx32, c.instanceMethods)
5006 << "\n";
5007 if (c.instanceMethods != 0)
5008 print_method_list32_t(c.instanceMethods, info, "");
5009 outs() << " classMethods " << format("0x%" PRIx32, c.classMethods)
5010 << "\n";
5011 if (c.classMethods != 0)
5012 print_method_list32_t(c.classMethods, info, "");
5013 outs() << " protocols " << format("0x%" PRIx32, c.protocols) << "\n";
5014 if (c.protocols != 0)
5015 print_protocol_list32_t(c.protocols, info);
5016 outs() << "instanceProperties " << format("0x%" PRIx32, c.instanceProperties)
5017 << "\n";
5018 if (c.instanceProperties != 0)
5019 print_objc_property_list32(c.instanceProperties, info);
5020}
5021
Kevin Enderby0fc11822015-04-01 20:57:01 +00005022static void print_message_refs64(SectionRef S, struct DisassembleInfo *info) {
5023 uint32_t i, left, offset, xoffset;
5024 uint64_t p, n_value;
5025 struct message_ref64 mr;
5026 const char *name, *sym_name;
5027 const char *r;
5028 SectionRef xS;
5029
5030 if (S == SectionRef())
5031 return;
5032
5033 StringRef SectName;
5034 S.getName(SectName);
5035 DataRefImpl Ref = S.getRawDataRefImpl();
5036 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5037 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5038 offset = 0;
5039 for (i = 0; i < S.getSize(); i += sizeof(struct message_ref64)) {
5040 p = S.getAddress() + i;
5041 r = get_pointer_64(p, offset, left, S, info);
5042 if (r == nullptr)
5043 return;
5044 memset(&mr, '\0', sizeof(struct message_ref64));
5045 if (left < sizeof(struct message_ref64)) {
5046 memcpy(&mr, r, left);
5047 outs() << " (message_ref entends past the end of the section)\n";
5048 } else
5049 memcpy(&mr, r, sizeof(struct message_ref64));
5050 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5051 swapStruct(mr);
5052
5053 outs() << " imp ";
5054 name = get_symbol_64(offset + offsetof(struct message_ref64, imp), S, info,
5055 n_value, mr.imp);
5056 if (n_value != 0) {
5057 outs() << format("0x%" PRIx64, n_value) << " ";
5058 if (mr.imp != 0)
5059 outs() << "+ " << format("0x%" PRIx64, mr.imp) << " ";
5060 } else
5061 outs() << format("0x%" PRIx64, mr.imp) << " ";
5062 if (name != nullptr)
5063 outs() << " " << name;
5064 outs() << "\n";
5065
5066 outs() << " sel ";
5067 sym_name = get_symbol_64(offset + offsetof(struct message_ref64, sel), S,
5068 info, n_value, mr.sel);
5069 if (n_value != 0) {
5070 if (info->verbose && sym_name != nullptr)
5071 outs() << sym_name;
5072 else
5073 outs() << format("0x%" PRIx64, n_value);
5074 if (mr.sel != 0)
5075 outs() << " + " << format("0x%" PRIx64, mr.sel);
5076 } else
5077 outs() << format("0x%" PRIx64, mr.sel);
5078 name = get_pointer_64(mr.sel + n_value, xoffset, left, xS, info);
5079 if (name != nullptr)
5080 outs() << format(" %.*s", left, name);
5081 outs() << "\n";
5082
5083 offset += sizeof(struct message_ref64);
5084 }
5085}
5086
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005087static void print_message_refs32(SectionRef S, struct DisassembleInfo *info) {
5088 uint32_t i, left, offset, xoffset, p;
5089 struct message_ref32 mr;
5090 const char *name, *r;
5091 SectionRef xS;
5092
5093 if (S == SectionRef())
5094 return;
5095
5096 StringRef SectName;
5097 S.getName(SectName);
5098 DataRefImpl Ref = S.getRawDataRefImpl();
5099 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5100 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5101 offset = 0;
5102 for (i = 0; i < S.getSize(); i += sizeof(struct message_ref64)) {
5103 p = S.getAddress() + i;
5104 r = get_pointer_32(p, offset, left, S, info);
5105 if (r == nullptr)
5106 return;
5107 memset(&mr, '\0', sizeof(struct message_ref32));
5108 if (left < sizeof(struct message_ref32)) {
5109 memcpy(&mr, r, left);
5110 outs() << " (message_ref entends past the end of the section)\n";
5111 } else
5112 memcpy(&mr, r, sizeof(struct message_ref32));
5113 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5114 swapStruct(mr);
5115
5116 outs() << " imp " << format("0x%" PRIx32, mr.imp);
5117 name = get_symbol_32(offset + offsetof(struct message_ref32, imp), S, info,
5118 mr.imp);
5119 if (name != nullptr)
5120 outs() << " " << name;
5121 outs() << "\n";
5122
5123 outs() << " sel " << format("0x%" PRIx32, mr.sel);
5124 name = get_pointer_32(mr.sel, xoffset, left, xS, info);
5125 if (name != nullptr)
5126 outs() << " " << name;
5127 outs() << "\n";
5128
5129 offset += sizeof(struct message_ref32);
5130 }
5131}
5132
Kevin Enderby0fc11822015-04-01 20:57:01 +00005133static void print_image_info64(SectionRef S, struct DisassembleInfo *info) {
5134 uint32_t left, offset, swift_version;
5135 uint64_t p;
5136 struct objc_image_info64 o;
5137 const char *r;
5138
Kevin Enderbyaf7c9d02015-10-09 16:48:44 +00005139 if (S == SectionRef())
5140 return;
5141
Kevin Enderby0fc11822015-04-01 20:57:01 +00005142 StringRef SectName;
5143 S.getName(SectName);
5144 DataRefImpl Ref = S.getRawDataRefImpl();
5145 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5146 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5147 p = S.getAddress();
5148 r = get_pointer_64(p, offset, left, S, info);
5149 if (r == nullptr)
5150 return;
5151 memset(&o, '\0', sizeof(struct objc_image_info64));
5152 if (left < sizeof(struct objc_image_info64)) {
5153 memcpy(&o, r, left);
5154 outs() << " (objc_image_info entends past the end of the section)\n";
5155 } else
5156 memcpy(&o, r, sizeof(struct objc_image_info64));
5157 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5158 swapStruct(o);
5159 outs() << " version " << o.version << "\n";
5160 outs() << " flags " << format("0x%" PRIx32, o.flags);
5161 if (o.flags & OBJC_IMAGE_IS_REPLACEMENT)
5162 outs() << " OBJC_IMAGE_IS_REPLACEMENT";
5163 if (o.flags & OBJC_IMAGE_SUPPORTS_GC)
5164 outs() << " OBJC_IMAGE_SUPPORTS_GC";
5165 swift_version = (o.flags >> 8) & 0xff;
5166 if (swift_version != 0) {
5167 if (swift_version == 1)
5168 outs() << " Swift 1.0";
5169 else if (swift_version == 2)
5170 outs() << " Swift 1.1";
5171 else
5172 outs() << " unknown future Swift version (" << swift_version << ")";
5173 }
5174 outs() << "\n";
5175}
5176
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005177static void print_image_info32(SectionRef S, struct DisassembleInfo *info) {
5178 uint32_t left, offset, swift_version, p;
5179 struct objc_image_info32 o;
5180 const char *r;
5181
Kevin Enderby19be2512016-04-21 19:49:29 +00005182 if (S == SectionRef())
5183 return;
5184
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005185 StringRef SectName;
5186 S.getName(SectName);
5187 DataRefImpl Ref = S.getRawDataRefImpl();
5188 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5189 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5190 p = S.getAddress();
5191 r = get_pointer_32(p, offset, left, S, info);
5192 if (r == nullptr)
5193 return;
5194 memset(&o, '\0', sizeof(struct objc_image_info32));
5195 if (left < sizeof(struct objc_image_info32)) {
5196 memcpy(&o, r, left);
5197 outs() << " (objc_image_info entends past the end of the section)\n";
5198 } else
5199 memcpy(&o, r, sizeof(struct objc_image_info32));
5200 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5201 swapStruct(o);
5202 outs() << " version " << o.version << "\n";
5203 outs() << " flags " << format("0x%" PRIx32, o.flags);
5204 if (o.flags & OBJC_IMAGE_IS_REPLACEMENT)
5205 outs() << " OBJC_IMAGE_IS_REPLACEMENT";
5206 if (o.flags & OBJC_IMAGE_SUPPORTS_GC)
5207 outs() << " OBJC_IMAGE_SUPPORTS_GC";
5208 swift_version = (o.flags >> 8) & 0xff;
5209 if (swift_version != 0) {
5210 if (swift_version == 1)
5211 outs() << " Swift 1.0";
5212 else if (swift_version == 2)
5213 outs() << " Swift 1.1";
5214 else
5215 outs() << " unknown future Swift version (" << swift_version << ")";
5216 }
5217 outs() << "\n";
5218}
5219
Kevin Enderby846c0002015-04-16 17:19:59 +00005220static void print_image_info(SectionRef S, struct DisassembleInfo *info) {
5221 uint32_t left, offset, p;
5222 struct imageInfo_t o;
5223 const char *r;
5224
5225 StringRef SectName;
5226 S.getName(SectName);
5227 DataRefImpl Ref = S.getRawDataRefImpl();
5228 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5229 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5230 p = S.getAddress();
5231 r = get_pointer_32(p, offset, left, S, info);
5232 if (r == nullptr)
5233 return;
5234 memset(&o, '\0', sizeof(struct imageInfo_t));
5235 if (left < sizeof(struct imageInfo_t)) {
5236 memcpy(&o, r, left);
5237 outs() << " (imageInfo entends past the end of the section)\n";
5238 } else
5239 memcpy(&o, r, sizeof(struct imageInfo_t));
5240 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5241 swapStruct(o);
5242 outs() << " version " << o.version << "\n";
5243 outs() << " flags " << format("0x%" PRIx32, o.flags);
5244 if (o.flags & 0x1)
5245 outs() << " F&C";
5246 if (o.flags & 0x2)
5247 outs() << " GC";
5248 if (o.flags & 0x4)
5249 outs() << " GC-only";
5250 else
5251 outs() << " RR";
5252 outs() << "\n";
5253}
5254
Kevin Enderby0fc11822015-04-01 20:57:01 +00005255static void printObjc2_64bit_MetaData(MachOObjectFile *O, bool verbose) {
5256 SymbolAddressMap AddrMap;
5257 if (verbose)
5258 CreateSymbolAddressMap(O, &AddrMap);
5259
5260 std::vector<SectionRef> Sections;
5261 for (const SectionRef &Section : O->sections()) {
5262 StringRef SectName;
5263 Section.getName(SectName);
5264 Sections.push_back(Section);
5265 }
5266
5267 struct DisassembleInfo info;
5268 // Set up the block of info used by the Symbolizer call backs.
5269 info.verbose = verbose;
5270 info.O = O;
5271 info.AddrMap = &AddrMap;
5272 info.Sections = &Sections;
5273 info.class_name = nullptr;
5274 info.selector_name = nullptr;
5275 info.method = nullptr;
5276 info.demangled_name = nullptr;
5277 info.bindtable = nullptr;
5278 info.adrp_addr = 0;
5279 info.adrp_inst = 0;
5280
Kevin Enderbyaac75382015-10-08 16:56:35 +00005281 info.depth = 0;
Davide Italiano62507042015-12-11 22:27:59 +00005282 SectionRef CL = get_section(O, "__OBJC2", "__class_list");
5283 if (CL == SectionRef())
5284 CL = get_section(O, "__DATA", "__objc_classlist");
Kevin Enderby5879a482017-02-09 17:56:26 +00005285 if (CL == SectionRef())
5286 CL = get_section(O, "__DATA_CONST", "__objc_classlist");
5287 if (CL == SectionRef())
5288 CL = get_section(O, "__DATA_DIRTY", "__objc_classlist");
Davide Italiano62507042015-12-11 22:27:59 +00005289 info.S = CL;
5290 walk_pointer_list_64("class", CL, O, &info, print_class64_t);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005291
Davide Italiano62507042015-12-11 22:27:59 +00005292 SectionRef CR = get_section(O, "__OBJC2", "__class_refs");
5293 if (CR == SectionRef())
5294 CR = get_section(O, "__DATA", "__objc_classrefs");
Kevin Enderby5879a482017-02-09 17:56:26 +00005295 if (CR == SectionRef())
5296 CR = get_section(O, "__DATA_CONST", "__objc_classrefs");
5297 if (CR == SectionRef())
5298 CR = get_section(O, "__DATA_DIRTY", "__objc_classrefs");
Davide Italiano62507042015-12-11 22:27:59 +00005299 info.S = CR;
5300 walk_pointer_list_64("class refs", CR, O, &info, nullptr);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005301
Davide Italiano62507042015-12-11 22:27:59 +00005302 SectionRef SR = get_section(O, "__OBJC2", "__super_refs");
5303 if (SR == SectionRef())
5304 SR = get_section(O, "__DATA", "__objc_superrefs");
Kevin Enderby5879a482017-02-09 17:56:26 +00005305 if (SR == SectionRef())
5306 SR = get_section(O, "__DATA_CONST", "__objc_superrefs");
5307 if (SR == SectionRef())
5308 SR = get_section(O, "__DATA_DIRTY", "__objc_superrefs");
Davide Italiano62507042015-12-11 22:27:59 +00005309 info.S = SR;
5310 walk_pointer_list_64("super refs", SR, O, &info, nullptr);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005311
Davide Italiano62507042015-12-11 22:27:59 +00005312 SectionRef CA = get_section(O, "__OBJC2", "__category_list");
5313 if (CA == SectionRef())
5314 CA = get_section(O, "__DATA", "__objc_catlist");
Kevin Enderby5879a482017-02-09 17:56:26 +00005315 if (CA == SectionRef())
5316 CA = get_section(O, "__DATA_CONST", "__objc_catlist");
5317 if (CA == SectionRef())
5318 CA = get_section(O, "__DATA_DIRTY", "__objc_catlist");
Davide Italiano62507042015-12-11 22:27:59 +00005319 info.S = CA;
5320 walk_pointer_list_64("category", CA, O, &info, print_category64_t);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005321
Davide Italiano62507042015-12-11 22:27:59 +00005322 SectionRef PL = get_section(O, "__OBJC2", "__protocol_list");
5323 if (PL == SectionRef())
5324 PL = get_section(O, "__DATA", "__objc_protolist");
Kevin Enderby5879a482017-02-09 17:56:26 +00005325 if (PL == SectionRef())
5326 PL = get_section(O, "__DATA_CONST", "__objc_protolist");
5327 if (PL == SectionRef())
5328 PL = get_section(O, "__DATA_DIRTY", "__objc_protolist");
Davide Italiano62507042015-12-11 22:27:59 +00005329 info.S = PL;
5330 walk_pointer_list_64("protocol", PL, O, &info, nullptr);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005331
Davide Italiano62507042015-12-11 22:27:59 +00005332 SectionRef MR = get_section(O, "__OBJC2", "__message_refs");
5333 if (MR == SectionRef())
5334 MR = get_section(O, "__DATA", "__objc_msgrefs");
Kevin Enderby5879a482017-02-09 17:56:26 +00005335 if (MR == SectionRef())
5336 MR = get_section(O, "__DATA_CONST", "__objc_msgrefs");
5337 if (MR == SectionRef())
5338 MR = get_section(O, "__DATA_DIRTY", "__objc_msgrefs");
Davide Italiano62507042015-12-11 22:27:59 +00005339 info.S = MR;
5340 print_message_refs64(MR, &info);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005341
Davide Italiano62507042015-12-11 22:27:59 +00005342 SectionRef II = get_section(O, "__OBJC2", "__image_info");
5343 if (II == SectionRef())
5344 II = get_section(O, "__DATA", "__objc_imageinfo");
Kevin Enderby5879a482017-02-09 17:56:26 +00005345 if (II == SectionRef())
5346 II = get_section(O, "__DATA_CONST", "__objc_imageinfo");
5347 if (II == SectionRef())
5348 II = get_section(O, "__DATA_DIRTY", "__objc_imageinfo");
Davide Italiano62507042015-12-11 22:27:59 +00005349 info.S = II;
5350 print_image_info64(II, &info);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005351}
5352
5353static void printObjc2_32bit_MetaData(MachOObjectFile *O, bool verbose) {
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005354 SymbolAddressMap AddrMap;
5355 if (verbose)
5356 CreateSymbolAddressMap(O, &AddrMap);
5357
5358 std::vector<SectionRef> Sections;
5359 for (const SectionRef &Section : O->sections()) {
5360 StringRef SectName;
5361 Section.getName(SectName);
5362 Sections.push_back(Section);
5363 }
5364
5365 struct DisassembleInfo info;
5366 // Set up the block of info used by the Symbolizer call backs.
5367 info.verbose = verbose;
5368 info.O = O;
5369 info.AddrMap = &AddrMap;
5370 info.Sections = &Sections;
5371 info.class_name = nullptr;
5372 info.selector_name = nullptr;
5373 info.method = nullptr;
5374 info.demangled_name = nullptr;
5375 info.bindtable = nullptr;
5376 info.adrp_addr = 0;
5377 info.adrp_inst = 0;
5378
Kevin Enderby5879a482017-02-09 17:56:26 +00005379 SectionRef CL = get_section(O, "__OBJC2", "__class_list");
5380 if (CL == SectionRef())
5381 CL = get_section(O, "__DATA", "__objc_classlist");
5382 if (CL == SectionRef())
5383 CL = get_section(O, "__DATA_CONST", "__objc_classlist");
5384 if (CL == SectionRef())
5385 CL = get_section(O, "__DATA_DIRTY", "__objc_classlist");
5386 info.S = CL;
5387 walk_pointer_list_32("class", CL, O, &info, print_class32_t);
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005388
Kevin Enderby5879a482017-02-09 17:56:26 +00005389 SectionRef CR = get_section(O, "__OBJC2", "__class_refs");
5390 if (CR == SectionRef())
5391 CR = get_section(O, "__DATA", "__objc_classrefs");
5392 if (CR == SectionRef())
5393 CR = get_section(O, "__DATA_CONST", "__objc_classrefs");
5394 if (CR == SectionRef())
5395 CR = get_section(O, "__DATA_DIRTY", "__objc_classrefs");
5396 info.S = CR;
5397 walk_pointer_list_32("class refs", CR, O, &info, nullptr);
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005398
Kevin Enderby5879a482017-02-09 17:56:26 +00005399 SectionRef SR = get_section(O, "__OBJC2", "__super_refs");
5400 if (SR == SectionRef())
5401 SR = get_section(O, "__DATA", "__objc_superrefs");
5402 if (SR == SectionRef())
5403 SR = get_section(O, "__DATA_CONST", "__objc_superrefs");
5404 if (SR == SectionRef())
5405 SR = get_section(O, "__DATA_DIRTY", "__objc_superrefs");
5406 info.S = SR;
5407 walk_pointer_list_32("super refs", SR, O, &info, nullptr);
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005408
Kevin Enderby5879a482017-02-09 17:56:26 +00005409 SectionRef CA = get_section(O, "__OBJC2", "__category_list");
5410 if (CA == SectionRef())
5411 CA = get_section(O, "__DATA", "__objc_catlist");
5412 if (CA == SectionRef())
5413 CA = get_section(O, "__DATA_CONST", "__objc_catlist");
5414 if (CA == SectionRef())
5415 CA = get_section(O, "__DATA_DIRTY", "__objc_catlist");
5416 info.S = CA;
5417 walk_pointer_list_32("category", CA, O, &info, print_category32_t);
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005418
Kevin Enderby5879a482017-02-09 17:56:26 +00005419 SectionRef PL = get_section(O, "__OBJC2", "__protocol_list");
5420 if (PL == SectionRef())
5421 PL = get_section(O, "__DATA", "__objc_protolist");
5422 if (PL == SectionRef())
5423 PL = get_section(O, "__DATA_CONST", "__objc_protolist");
5424 if (PL == SectionRef())
5425 PL = get_section(O, "__DATA_DIRTY", "__objc_protolist");
5426 info.S = PL;
5427 walk_pointer_list_32("protocol", PL, O, &info, nullptr);
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005428
Kevin Enderby5879a482017-02-09 17:56:26 +00005429 SectionRef MR = get_section(O, "__OBJC2", "__message_refs");
5430 if (MR == SectionRef())
5431 MR = get_section(O, "__DATA", "__objc_msgrefs");
5432 if (MR == SectionRef())
5433 MR = get_section(O, "__DATA_CONST", "__objc_msgrefs");
5434 if (MR == SectionRef())
5435 MR = get_section(O, "__DATA_DIRTY", "__objc_msgrefs");
5436 info.S = MR;
5437 print_message_refs32(MR, &info);
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005438
Kevin Enderby5879a482017-02-09 17:56:26 +00005439 SectionRef II = get_section(O, "__OBJC2", "__image_info");
5440 if (II == SectionRef())
5441 II = get_section(O, "__DATA", "__objc_imageinfo");
5442 if (II == SectionRef())
5443 II = get_section(O, "__DATA_CONST", "__objc_imageinfo");
5444 if (II == SectionRef())
5445 II = get_section(O, "__DATA_DIRTY", "__objc_imageinfo");
5446 info.S = II;
5447 print_image_info32(II, &info);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005448}
5449
5450static bool printObjc1_32bit_MetaData(MachOObjectFile *O, bool verbose) {
Kevin Enderby846c0002015-04-16 17:19:59 +00005451 uint32_t i, j, p, offset, xoffset, left, defs_left, def;
5452 const char *r, *name, *defs;
5453 struct objc_module_t module;
5454 SectionRef S, xS;
5455 struct objc_symtab_t symtab;
5456 struct objc_class_t objc_class;
5457 struct objc_category_t objc_category;
5458
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005459 outs() << "Objective-C segment\n";
Kevin Enderby846c0002015-04-16 17:19:59 +00005460 S = get_section(O, "__OBJC", "__module_info");
5461 if (S == SectionRef())
5462 return false;
5463
5464 SymbolAddressMap AddrMap;
5465 if (verbose)
5466 CreateSymbolAddressMap(O, &AddrMap);
5467
5468 std::vector<SectionRef> Sections;
5469 for (const SectionRef &Section : O->sections()) {
5470 StringRef SectName;
5471 Section.getName(SectName);
5472 Sections.push_back(Section);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005473 }
Kevin Enderby846c0002015-04-16 17:19:59 +00005474
5475 struct DisassembleInfo info;
5476 // Set up the block of info used by the Symbolizer call backs.
5477 info.verbose = verbose;
5478 info.O = O;
5479 info.AddrMap = &AddrMap;
5480 info.Sections = &Sections;
5481 info.class_name = nullptr;
5482 info.selector_name = nullptr;
5483 info.method = nullptr;
5484 info.demangled_name = nullptr;
5485 info.bindtable = nullptr;
5486 info.adrp_addr = 0;
5487 info.adrp_inst = 0;
5488
5489 for (i = 0; i < S.getSize(); i += sizeof(struct objc_module_t)) {
5490 p = S.getAddress() + i;
5491 r = get_pointer_32(p, offset, left, S, &info, true);
5492 if (r == nullptr)
5493 return true;
5494 memset(&module, '\0', sizeof(struct objc_module_t));
5495 if (left < sizeof(struct objc_module_t)) {
5496 memcpy(&module, r, left);
5497 outs() << " (module extends past end of __module_info section)\n";
5498 } else
5499 memcpy(&module, r, sizeof(struct objc_module_t));
5500 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5501 swapStruct(module);
5502
5503 outs() << "Module " << format("0x%" PRIx32, p) << "\n";
5504 outs() << " version " << module.version << "\n";
5505 outs() << " size " << module.size << "\n";
5506 outs() << " name ";
5507 name = get_pointer_32(module.name, xoffset, left, xS, &info, true);
5508 if (name != nullptr)
5509 outs() << format("%.*s", left, name);
5510 else
5511 outs() << format("0x%08" PRIx32, module.name)
5512 << "(not in an __OBJC section)";
5513 outs() << "\n";
5514
5515 r = get_pointer_32(module.symtab, xoffset, left, xS, &info, true);
5516 if (module.symtab == 0 || r == nullptr) {
5517 outs() << " symtab " << format("0x%08" PRIx32, module.symtab)
5518 << " (not in an __OBJC section)\n";
5519 continue;
5520 }
5521 outs() << " symtab " << format("0x%08" PRIx32, module.symtab) << "\n";
5522 memset(&symtab, '\0', sizeof(struct objc_symtab_t));
5523 defs_left = 0;
5524 defs = nullptr;
5525 if (left < sizeof(struct objc_symtab_t)) {
5526 memcpy(&symtab, r, left);
5527 outs() << "\tsymtab extends past end of an __OBJC section)\n";
5528 } else {
5529 memcpy(&symtab, r, sizeof(struct objc_symtab_t));
5530 if (left > sizeof(struct objc_symtab_t)) {
5531 defs_left = left - sizeof(struct objc_symtab_t);
5532 defs = r + sizeof(struct objc_symtab_t);
5533 }
5534 }
5535 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5536 swapStruct(symtab);
5537
5538 outs() << "\tsel_ref_cnt " << symtab.sel_ref_cnt << "\n";
5539 r = get_pointer_32(symtab.refs, xoffset, left, xS, &info, true);
5540 outs() << "\trefs " << format("0x%08" PRIx32, symtab.refs);
5541 if (r == nullptr)
5542 outs() << " (not in an __OBJC section)";
5543 outs() << "\n";
5544 outs() << "\tcls_def_cnt " << symtab.cls_def_cnt << "\n";
5545 outs() << "\tcat_def_cnt " << symtab.cat_def_cnt << "\n";
5546 if (symtab.cls_def_cnt > 0)
5547 outs() << "\tClass Definitions\n";
5548 for (j = 0; j < symtab.cls_def_cnt; j++) {
5549 if ((j + 1) * sizeof(uint32_t) > defs_left) {
5550 outs() << "\t(remaining class defs entries entends past the end of the "
5551 << "section)\n";
5552 break;
5553 }
5554 memcpy(&def, defs + j * sizeof(uint32_t), sizeof(uint32_t));
5555 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5556 sys::swapByteOrder(def);
5557
5558 r = get_pointer_32(def, xoffset, left, xS, &info, true);
5559 outs() << "\tdefs[" << j << "] " << format("0x%08" PRIx32, def);
5560 if (r != nullptr) {
5561 if (left > sizeof(struct objc_class_t)) {
5562 outs() << "\n";
5563 memcpy(&objc_class, r, sizeof(struct objc_class_t));
5564 } else {
5565 outs() << " (entends past the end of the section)\n";
5566 memset(&objc_class, '\0', sizeof(struct objc_class_t));
5567 memcpy(&objc_class, r, left);
5568 }
5569 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5570 swapStruct(objc_class);
5571 print_objc_class_t(&objc_class, &info);
5572 } else {
5573 outs() << "(not in an __OBJC section)\n";
5574 }
5575
5576 if (CLS_GETINFO(&objc_class, CLS_CLASS)) {
5577 outs() << "\tMeta Class";
5578 r = get_pointer_32(objc_class.isa, xoffset, left, xS, &info, true);
5579 if (r != nullptr) {
5580 if (left > sizeof(struct objc_class_t)) {
5581 outs() << "\n";
5582 memcpy(&objc_class, r, sizeof(struct objc_class_t));
5583 } else {
5584 outs() << " (entends past the end of the section)\n";
5585 memset(&objc_class, '\0', sizeof(struct objc_class_t));
5586 memcpy(&objc_class, r, left);
5587 }
5588 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5589 swapStruct(objc_class);
5590 print_objc_class_t(&objc_class, &info);
5591 } else {
5592 outs() << "(not in an __OBJC section)\n";
5593 }
5594 }
5595 }
5596 if (symtab.cat_def_cnt > 0)
5597 outs() << "\tCategory Definitions\n";
5598 for (j = 0; j < symtab.cat_def_cnt; j++) {
5599 if ((j + symtab.cls_def_cnt + 1) * sizeof(uint32_t) > defs_left) {
5600 outs() << "\t(remaining category defs entries entends past the end of "
5601 << "the section)\n";
5602 break;
5603 }
5604 memcpy(&def, defs + (j + symtab.cls_def_cnt) * sizeof(uint32_t),
5605 sizeof(uint32_t));
5606 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5607 sys::swapByteOrder(def);
5608
5609 r = get_pointer_32(def, xoffset, left, xS, &info, true);
5610 outs() << "\tdefs[" << j + symtab.cls_def_cnt << "] "
5611 << format("0x%08" PRIx32, def);
5612 if (r != nullptr) {
5613 if (left > sizeof(struct objc_category_t)) {
5614 outs() << "\n";
5615 memcpy(&objc_category, r, sizeof(struct objc_category_t));
5616 } else {
5617 outs() << " (entends past the end of the section)\n";
5618 memset(&objc_category, '\0', sizeof(struct objc_category_t));
5619 memcpy(&objc_category, r, left);
5620 }
5621 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5622 swapStruct(objc_category);
5623 print_objc_objc_category_t(&objc_category, &info);
5624 } else {
5625 outs() << "(not in an __OBJC section)\n";
5626 }
5627 }
5628 }
5629 const SectionRef II = get_section(O, "__OBJC", "__image_info");
5630 if (II != SectionRef())
5631 print_image_info(II, &info);
5632
5633 return true;
Kevin Enderby0fc11822015-04-01 20:57:01 +00005634}
5635
Kevin Enderby4ad9bde2015-04-16 22:33:20 +00005636static void DumpProtocolSection(MachOObjectFile *O, const char *sect,
5637 uint32_t size, uint32_t addr) {
5638 SymbolAddressMap AddrMap;
5639 CreateSymbolAddressMap(O, &AddrMap);
5640
5641 std::vector<SectionRef> Sections;
5642 for (const SectionRef &Section : O->sections()) {
5643 StringRef SectName;
5644 Section.getName(SectName);
5645 Sections.push_back(Section);
5646 }
5647
5648 struct DisassembleInfo info;
5649 // Set up the block of info used by the Symbolizer call backs.
5650 info.verbose = true;
5651 info.O = O;
5652 info.AddrMap = &AddrMap;
5653 info.Sections = &Sections;
5654 info.class_name = nullptr;
5655 info.selector_name = nullptr;
5656 info.method = nullptr;
5657 info.demangled_name = nullptr;
5658 info.bindtable = nullptr;
5659 info.adrp_addr = 0;
5660 info.adrp_inst = 0;
5661
5662 const char *p;
5663 struct objc_protocol_t protocol;
5664 uint32_t left, paddr;
5665 for (p = sect; p < sect + size; p += sizeof(struct objc_protocol_t)) {
5666 memset(&protocol, '\0', sizeof(struct objc_protocol_t));
5667 left = size - (p - sect);
5668 if (left < sizeof(struct objc_protocol_t)) {
5669 outs() << "Protocol extends past end of __protocol section\n";
5670 memcpy(&protocol, p, left);
5671 } else
5672 memcpy(&protocol, p, sizeof(struct objc_protocol_t));
5673 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5674 swapStruct(protocol);
5675 paddr = addr + (p - sect);
5676 outs() << "Protocol " << format("0x%" PRIx32, paddr);
5677 if (print_protocol(paddr, 0, &info))
5678 outs() << "(not in an __OBJC section)\n";
5679 }
5680}
5681
Kevin Enderby9873e2c2016-05-23 21:34:12 +00005682#ifdef HAVE_LIBXAR
5683inline void swapStruct(struct xar_header &xar) {
5684 sys::swapByteOrder(xar.magic);
5685 sys::swapByteOrder(xar.size);
5686 sys::swapByteOrder(xar.version);
5687 sys::swapByteOrder(xar.toc_length_compressed);
5688 sys::swapByteOrder(xar.toc_length_uncompressed);
5689 sys::swapByteOrder(xar.cksum_alg);
5690}
5691
5692static void PrintModeVerbose(uint32_t mode) {
5693 switch(mode & S_IFMT){
5694 case S_IFDIR:
5695 outs() << "d";
5696 break;
5697 case S_IFCHR:
5698 outs() << "c";
5699 break;
5700 case S_IFBLK:
5701 outs() << "b";
5702 break;
5703 case S_IFREG:
5704 outs() << "-";
5705 break;
5706 case S_IFLNK:
5707 outs() << "l";
5708 break;
5709 case S_IFSOCK:
5710 outs() << "s";
5711 break;
5712 default:
5713 outs() << "?";
5714 break;
5715 }
5716
5717 /* owner permissions */
5718 if(mode & S_IREAD)
5719 outs() << "r";
5720 else
5721 outs() << "-";
5722 if(mode & S_IWRITE)
5723 outs() << "w";
5724 else
5725 outs() << "-";
5726 if(mode & S_ISUID)
5727 outs() << "s";
5728 else if(mode & S_IEXEC)
5729 outs() << "x";
5730 else
5731 outs() << "-";
5732
5733 /* group permissions */
5734 if(mode & (S_IREAD >> 3))
5735 outs() << "r";
5736 else
5737 outs() << "-";
5738 if(mode & (S_IWRITE >> 3))
5739 outs() << "w";
5740 else
5741 outs() << "-";
5742 if(mode & S_ISGID)
5743 outs() << "s";
5744 else if(mode & (S_IEXEC >> 3))
5745 outs() << "x";
5746 else
5747 outs() << "-";
5748
5749 /* other permissions */
5750 if(mode & (S_IREAD >> 6))
5751 outs() << "r";
5752 else
5753 outs() << "-";
5754 if(mode & (S_IWRITE >> 6))
5755 outs() << "w";
5756 else
5757 outs() << "-";
5758 if(mode & S_ISVTX)
5759 outs() << "t";
5760 else if(mode & (S_IEXEC >> 6))
5761 outs() << "x";
5762 else
5763 outs() << "-";
5764}
5765
5766static void PrintXarFilesSummary(const char *XarFilename, xar_t xar) {
5767 xar_iter_t xi;
5768 xar_file_t xf;
5769 xar_iter_t xp;
5770 const char *key, *type, *mode, *user, *group, *size, *mtime, *name, *m;
5771 char *endp;
5772 uint32_t mode_value;
5773
5774 xi = xar_iter_new();
5775 if (!xi) {
5776 errs() << "Can't obtain an xar iterator for xar archive "
5777 << XarFilename << "\n";
5778 return;
5779 }
5780
5781 // Go through the xar's files.
5782 for (xf = xar_file_first(xar, xi); xf; xf = xar_file_next(xi)) {
5783 xp = xar_iter_new();
5784 if(!xp){
5785 errs() << "Can't obtain an xar iterator for xar archive "
5786 << XarFilename << "\n";
5787 return;
5788 }
5789 type = nullptr;
5790 mode = nullptr;
5791 user = nullptr;
5792 group = nullptr;
5793 size = nullptr;
5794 mtime = nullptr;
5795 name = nullptr;
5796 for(key = xar_prop_first(xf, xp); key; key = xar_prop_next(xp)){
5797 const char *val = nullptr;
5798 xar_prop_get(xf, key, &val);
5799#if 0 // Useful for debugging.
5800 outs() << "key: " << key << " value: " << val << "\n";
5801#endif
5802 if(strcmp(key, "type") == 0)
5803 type = val;
5804 if(strcmp(key, "mode") == 0)
5805 mode = val;
5806 if(strcmp(key, "user") == 0)
5807 user = val;
5808 if(strcmp(key, "group") == 0)
5809 group = val;
5810 if(strcmp(key, "data/size") == 0)
5811 size = val;
5812 if(strcmp(key, "mtime") == 0)
5813 mtime = val;
5814 if(strcmp(key, "name") == 0)
5815 name = val;
5816 }
5817 if(mode != nullptr){
5818 mode_value = strtoul(mode, &endp, 8);
5819 if(*endp != '\0')
5820 outs() << "(mode: \"" << mode << "\" contains non-octal chars) ";
5821 if(strcmp(type, "file") == 0)
5822 mode_value |= S_IFREG;
5823 PrintModeVerbose(mode_value);
5824 outs() << " ";
5825 }
5826 if(user != nullptr)
5827 outs() << format("%10s/", user);
5828 if(group != nullptr)
5829 outs() << format("%-10s ", group);
5830 if(size != nullptr)
5831 outs() << format("%7s ", size);
5832 if(mtime != nullptr){
5833 for(m = mtime; *m != 'T' && *m != '\0'; m++)
5834 outs() << *m;
5835 if(*m == 'T')
5836 m++;
5837 outs() << " ";
5838 for( ; *m != 'Z' && *m != '\0'; m++)
5839 outs() << *m;
5840 outs() << " ";
5841 }
5842 if(name != nullptr)
5843 outs() << name;
5844 outs() << "\n";
5845 }
5846}
5847
5848static void DumpBitcodeSection(MachOObjectFile *O, const char *sect,
5849 uint32_t size, bool verbose,
5850 bool PrintXarHeader, bool PrintXarFileHeaders,
5851 std::string XarMemberName) {
5852 if(size < sizeof(struct xar_header)) {
5853 outs() << "size of (__LLVM,__bundle) section too small (smaller than size "
5854 "of struct xar_header)\n";
5855 return;
5856 }
5857 struct xar_header XarHeader;
5858 memcpy(&XarHeader, sect, sizeof(struct xar_header));
5859 if (sys::IsLittleEndianHost)
5860 swapStruct(XarHeader);
5861 if (PrintXarHeader) {
5862 if (!XarMemberName.empty())
5863 outs() << "In xar member " << XarMemberName << ": ";
5864 else
5865 outs() << "For (__LLVM,__bundle) section: ";
5866 outs() << "xar header\n";
5867 if (XarHeader.magic == XAR_HEADER_MAGIC)
5868 outs() << " magic XAR_HEADER_MAGIC\n";
5869 else
5870 outs() << " magic "
5871 << format_hex(XarHeader.magic, 10, true)
5872 << " (not XAR_HEADER_MAGIC)\n";
5873 outs() << " size " << XarHeader.size << "\n";
5874 outs() << " version " << XarHeader.version << "\n";
5875 outs() << " toc_length_compressed " << XarHeader.toc_length_compressed
5876 << "\n";
5877 outs() << "toc_length_uncompressed " << XarHeader.toc_length_uncompressed
5878 << "\n";
5879 outs() << " cksum_alg ";
5880 switch (XarHeader.cksum_alg) {
5881 case XAR_CKSUM_NONE:
5882 outs() << "XAR_CKSUM_NONE\n";
5883 break;
5884 case XAR_CKSUM_SHA1:
5885 outs() << "XAR_CKSUM_SHA1\n";
5886 break;
5887 case XAR_CKSUM_MD5:
5888 outs() << "XAR_CKSUM_MD5\n";
5889 break;
Kevin Enderby42882282016-05-23 22:18:59 +00005890#ifdef XAR_CKSUM_SHA256
Kevin Enderby9873e2c2016-05-23 21:34:12 +00005891 case XAR_CKSUM_SHA256:
5892 outs() << "XAR_CKSUM_SHA256\n";
5893 break;
Kevin Enderby42882282016-05-23 22:18:59 +00005894#endif
5895#ifdef XAR_CKSUM_SHA512
Kevin Enderby9873e2c2016-05-23 21:34:12 +00005896 case XAR_CKSUM_SHA512:
5897 outs() << "XAR_CKSUM_SHA512\n";
5898 break;
Kevin Enderby42882282016-05-23 22:18:59 +00005899#endif
Kevin Enderby9873e2c2016-05-23 21:34:12 +00005900 default:
5901 outs() << XarHeader.cksum_alg << "\n";
5902 }
5903 }
5904
5905 SmallString<128> XarFilename;
5906 int FD;
5907 std::error_code XarEC =
5908 sys::fs::createTemporaryFile("llvm-objdump", "xar", FD, XarFilename);
5909 if (XarEC) {
5910 errs() << XarEC.message() << "\n";
5911 return;
5912 }
5913 tool_output_file XarFile(XarFilename, FD);
5914 raw_fd_ostream &XarOut = XarFile.os();
5915 StringRef XarContents(sect, size);
5916 XarOut << XarContents;
5917 XarOut.close();
5918 if (XarOut.has_error())
5919 return;
5920
5921 xar_t xar = xar_open(XarFilename.c_str(), READ);
5922 if (!xar) {
5923 errs() << "Can't create temporary xar archive " << XarFilename << "\n";
5924 return;
5925 }
5926
5927 SmallString<128> TocFilename;
5928 std::error_code TocEC =
5929 sys::fs::createTemporaryFile("llvm-objdump", "toc", TocFilename);
5930 if (TocEC) {
5931 errs() << TocEC.message() << "\n";
5932 return;
5933 }
5934 xar_serialize(xar, TocFilename.c_str());
5935
5936 if (PrintXarFileHeaders) {
5937 if (!XarMemberName.empty())
5938 outs() << "In xar member " << XarMemberName << ": ";
5939 else
5940 outs() << "For (__LLVM,__bundle) section: ";
5941 outs() << "xar archive files:\n";
5942 PrintXarFilesSummary(XarFilename.c_str(), xar);
5943 }
5944
5945 ErrorOr<std::unique_ptr<MemoryBuffer>> FileOrErr =
5946 MemoryBuffer::getFileOrSTDIN(TocFilename.c_str());
5947 if (std::error_code EC = FileOrErr.getError()) {
5948 errs() << EC.message() << "\n";
5949 return;
5950 }
5951 std::unique_ptr<MemoryBuffer> &Buffer = FileOrErr.get();
5952
5953 if (!XarMemberName.empty())
5954 outs() << "In xar member " << XarMemberName << ": ";
5955 else
5956 outs() << "For (__LLVM,__bundle) section: ";
5957 outs() << "xar table of contents:\n";
5958 outs() << Buffer->getBuffer() << "\n";
5959
5960 // TODO: Go through the xar's files.
5961 xar_iter_t xi = xar_iter_new();
5962 if(!xi){
5963 errs() << "Can't obtain an xar iterator for xar archive "
5964 << XarFilename.c_str() << "\n";
5965 xar_close(xar);
5966 return;
5967 }
5968 for(xar_file_t xf = xar_file_first(xar, xi); xf; xf = xar_file_next(xi)){
5969 const char *key;
5970 xar_iter_t xp;
5971 const char *member_name, *member_type, *member_size_string;
5972 size_t member_size;
5973
5974 xp = xar_iter_new();
5975 if(!xp){
5976 errs() << "Can't obtain an xar iterator for xar archive "
5977 << XarFilename.c_str() << "\n";
5978 xar_close(xar);
5979 return;
5980 }
5981 member_name = NULL;
5982 member_type = NULL;
5983 member_size_string = NULL;
5984 for(key = xar_prop_first(xf, xp); key; key = xar_prop_next(xp)){
5985 const char *val = nullptr;
5986 xar_prop_get(xf, key, &val);
5987#if 0 // Useful for debugging.
5988 outs() << "key: " << key << " value: " << val << "\n";
5989#endif
5990 if(strcmp(key, "name") == 0)
5991 member_name = val;
5992 if(strcmp(key, "type") == 0)
5993 member_type = val;
5994 if(strcmp(key, "data/size") == 0)
5995 member_size_string = val;
5996 }
5997 /*
5998 * If we find a file with a name, date/size and type properties
5999 * and with the type being "file" see if that is a xar file.
6000 */
6001 if (member_name != NULL && member_type != NULL &&
6002 strcmp(member_type, "file") == 0 &&
6003 member_size_string != NULL){
6004 // Extract the file into a buffer.
6005 char *endptr;
6006 member_size = strtoul(member_size_string, &endptr, 10);
6007 if (*endptr == '\0' && member_size != 0) {
6008 char *buffer = (char *) ::operator new (member_size);
6009 if (xar_extract_tobuffersz(xar, xf, &buffer, &member_size) == 0) {
6010#if 0 // Useful for debugging.
6011 outs() << "xar member: " << member_name << " extracted\n";
6012#endif
6013 // Set the XarMemberName we want to see printed in the header.
6014 std::string OldXarMemberName;
6015 // If XarMemberName is already set this is nested. So
6016 // save the old name and create the nested name.
6017 if (!XarMemberName.empty()) {
6018 OldXarMemberName = XarMemberName;
6019 XarMemberName =
6020 (Twine("[") + XarMemberName + "]" + member_name).str();
6021 } else {
6022 OldXarMemberName = "";
6023 XarMemberName = member_name;
6024 }
6025 // See if this is could be a xar file (nested).
6026 if (member_size >= sizeof(struct xar_header)) {
6027#if 0 // Useful for debugging.
6028 outs() << "could be a xar file: " << member_name << "\n";
6029#endif
6030 memcpy((char *)&XarHeader, buffer, sizeof(struct xar_header));
6031 if (sys::IsLittleEndianHost)
6032 swapStruct(XarHeader);
6033 if(XarHeader.magic == XAR_HEADER_MAGIC)
6034 DumpBitcodeSection(O, buffer, member_size, verbose,
6035 PrintXarHeader, PrintXarFileHeaders,
6036 XarMemberName);
6037 }
6038 XarMemberName = OldXarMemberName;
6039 }
6040 delete buffer;
6041 }
6042 }
6043 xar_iter_free(xp);
6044 }
6045 xar_close(xar);
6046}
6047#endif // defined(HAVE_LIBXAR)
6048
Kevin Enderby0fc11822015-04-01 20:57:01 +00006049static void printObjcMetaData(MachOObjectFile *O, bool verbose) {
6050 if (O->is64Bit())
6051 printObjc2_64bit_MetaData(O, verbose);
6052 else {
6053 MachO::mach_header H;
6054 H = O->getHeader();
6055 if (H.cputype == MachO::CPU_TYPE_ARM)
6056 printObjc2_32bit_MetaData(O, verbose);
6057 else {
6058 // This is the 32-bit non-arm cputype case. Which is normally
6059 // the first Objective-C ABI. But it may be the case of a
6060 // binary for the iOS simulator which is the second Objective-C
6061 // ABI. In that case printObjc1_32bit_MetaData() will determine that
6062 // and return false.
Hans Wennborgcc9deb42015-09-29 18:02:48 +00006063 if (!printObjc1_32bit_MetaData(O, verbose))
Kevin Enderby0fc11822015-04-01 20:57:01 +00006064 printObjc2_32bit_MetaData(O, verbose);
6065 }
6066 }
6067}
6068
Kevin Enderbybf246f52014-09-24 23:08:22 +00006069// GuessLiteralPointer returns a string which for the item in the Mach-O file
6070// for the address passed in as ReferenceValue for printing as a comment with
6071// the instruction and also returns the corresponding type of that item
6072// indirectly through ReferenceType.
6073//
6074// If ReferenceValue is an address of literal cstring then a pointer to the
6075// cstring is returned and ReferenceType is set to
6076// LLVMDisassembler_ReferenceType_Out_LitPool_CstrAddr .
6077//
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006078// If ReferenceValue is an address of an Objective-C CFString, Selector ref or
6079// Class ref that name is returned and the ReferenceType is set accordingly.
6080//
6081// Lastly, literals which are Symbol address in a literal pool are looked for
6082// and if found the symbol name is returned and ReferenceType is set to
6083// LLVMDisassembler_ReferenceType_Out_LitPool_SymAddr .
6084//
6085// If there is no item in the Mach-O file for the address passed in as
6086// ReferenceValue nullptr is returned and ReferenceType is unchanged.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00006087static const char *GuessLiteralPointer(uint64_t ReferenceValue,
6088 uint64_t ReferencePC,
6089 uint64_t *ReferenceType,
6090 struct DisassembleInfo *info) {
Kevin Enderbybf246f52014-09-24 23:08:22 +00006091 // First see if there is an external relocation entry at the ReferencePC.
Kevin Enderbyd90a4172015-10-10 00:05:01 +00006092 if (info->O->getHeader().filetype == MachO::MH_OBJECT) {
6093 uint64_t sect_addr = info->S.getAddress();
6094 uint64_t sect_offset = ReferencePC - sect_addr;
6095 bool reloc_found = false;
6096 DataRefImpl Rel;
6097 MachO::any_relocation_info RE;
6098 bool isExtern = false;
6099 SymbolRef Symbol;
6100 for (const RelocationRef &Reloc : info->S.relocations()) {
6101 uint64_t RelocOffset = Reloc.getOffset();
6102 if (RelocOffset == sect_offset) {
6103 Rel = Reloc.getRawDataRefImpl();
6104 RE = info->O->getRelocation(Rel);
6105 if (info->O->isRelocationScattered(RE))
6106 continue;
6107 isExtern = info->O->getPlainRelocationExternal(RE);
6108 if (isExtern) {
6109 symbol_iterator RelocSym = Reloc.getSymbol();
6110 Symbol = *RelocSym;
6111 }
6112 reloc_found = true;
6113 break;
Kevin Enderbybf246f52014-09-24 23:08:22 +00006114 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00006115 }
Kevin Enderbyd90a4172015-10-10 00:05:01 +00006116 // If there is an external relocation entry for a symbol in a section
6117 // then used that symbol's value for the value of the reference.
6118 if (reloc_found && isExtern) {
6119 if (info->O->getAnyRelocationPCRel(RE)) {
6120 unsigned Type = info->O->getAnyRelocationType(RE);
6121 if (Type == MachO::X86_64_RELOC_SIGNED) {
6122 ReferenceValue = Symbol.getValue();
6123 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00006124 }
6125 }
6126 }
6127
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006128 // Look for literals such as Objective-C CFStrings refs, Selector refs,
6129 // Message refs and Class refs.
6130 bool classref, selref, msgref, cfstring;
6131 uint64_t pointer_value = GuessPointerPointer(ReferenceValue, info, classref,
6132 selref, msgref, cfstring);
David Blaikie33dd45d02015-03-23 18:39:02 +00006133 if (classref && pointer_value == 0) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006134 // Note the ReferenceValue is a pointer into the __objc_classrefs section.
6135 // And the pointer_value in that section is typically zero as it will be
6136 // set by dyld as part of the "bind information".
6137 const char *name = get_dyld_bind_info_symbolname(ReferenceValue, info);
6138 if (name != nullptr) {
6139 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Class_Ref;
Hans Wennborgdb53e302014-10-23 21:59:17 +00006140 const char *class_name = strrchr(name, '$');
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006141 if (class_name != nullptr && class_name[1] == '_' &&
6142 class_name[2] != '\0') {
6143 info->class_name = class_name + 2;
6144 return name;
6145 }
6146 }
6147 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00006148
David Blaikie33dd45d02015-03-23 18:39:02 +00006149 if (classref) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006150 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Class_Ref;
6151 const char *name =
6152 get_objc2_64bit_class_name(pointer_value, ReferenceValue, info);
6153 if (name != nullptr)
6154 info->class_name = name;
6155 else
6156 name = "bad class ref";
Kevin Enderbybf246f52014-09-24 23:08:22 +00006157 return name;
6158 }
6159
David Blaikie33dd45d02015-03-23 18:39:02 +00006160 if (cfstring) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006161 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_CFString_Ref;
6162 const char *name = get_objc2_64bit_cfstring_name(ReferenceValue, info);
6163 return name;
6164 }
6165
David Blaikie33dd45d02015-03-23 18:39:02 +00006166 if (selref && pointer_value == 0)
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006167 pointer_value = get_objc2_64bit_selref(ReferenceValue, info);
6168
6169 if (pointer_value != 0)
6170 ReferenceValue = pointer_value;
6171
6172 const char *name = GuessCstringPointer(ReferenceValue, info);
6173 if (name) {
David Blaikie33dd45d02015-03-23 18:39:02 +00006174 if (pointer_value != 0 && selref) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006175 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Selector_Ref;
6176 info->selector_name = name;
David Blaikie33dd45d02015-03-23 18:39:02 +00006177 } else if (pointer_value != 0 && msgref) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006178 info->class_name = nullptr;
6179 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message_Ref;
6180 info->selector_name = name;
6181 } else
6182 *ReferenceType = LLVMDisassembler_ReferenceType_Out_LitPool_CstrAddr;
6183 return name;
6184 }
6185
6186 // Lastly look for an indirect symbol with this ReferenceValue which is in
6187 // a literal pool. If found return that symbol name.
6188 name = GuessIndirectSymbol(ReferenceValue, info);
6189 if (name) {
6190 *ReferenceType = LLVMDisassembler_ReferenceType_Out_LitPool_SymAddr;
6191 return name;
6192 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00006193
6194 return nullptr;
6195}
6196
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006197// SymbolizerSymbolLookUp is the symbol lookup function passed when creating
Kevin Enderbybf246f52014-09-24 23:08:22 +00006198// the Symbolizer. It looks up the ReferenceValue using the info passed via the
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006199// pointer to the struct DisassembleInfo that was passed when MCSymbolizer
6200// is created and returns the symbol name that matches the ReferenceValue or
6201// nullptr if none. The ReferenceType is passed in for the IN type of
6202// reference the instruction is making from the values in defined in the header
6203// "llvm-c/Disassembler.h". On return the ReferenceType can set to a specific
6204// Out type and the ReferenceName will also be set which is added as a comment
6205// to the disassembled instruction.
6206//
Kevin Enderby04bf6932014-10-28 23:39:46 +00006207// If the symbol name is a C++ mangled name then the demangled name is
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006208// returned through ReferenceName and ReferenceType is set to
6209// LLVMDisassembler_ReferenceType_DeMangled_Name .
6210//
6211// When this is called to get a symbol name for a branch target then the
6212// ReferenceType will be LLVMDisassembler_ReferenceType_In_Branch and then
6213// SymbolValue will be looked for in the indirect symbol table to determine if
6214// it is an address for a symbol stub. If so then the symbol name for that
6215// stub is returned indirectly through ReferenceName and then ReferenceType is
6216// set to LLVMDisassembler_ReferenceType_Out_SymbolStub.
6217//
Kevin Enderbybf246f52014-09-24 23:08:22 +00006218// When this is called with an value loaded via a PC relative load then
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006219// ReferenceType will be LLVMDisassembler_ReferenceType_In_PCrel_Load then the
6220// SymbolValue is checked to be an address of literal pointer, symbol pointer,
6221// or an Objective-C meta data reference. If so the output ReferenceType is
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006222// set to correspond to that as well as setting the ReferenceName.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00006223static const char *SymbolizerSymbolLookUp(void *DisInfo,
6224 uint64_t ReferenceValue,
6225 uint64_t *ReferenceType,
6226 uint64_t ReferencePC,
6227 const char **ReferenceName) {
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006228 struct DisassembleInfo *info = (struct DisassembleInfo *)DisInfo;
Kevin Enderbybf246f52014-09-24 23:08:22 +00006229 // If no verbose symbolic information is wanted then just return nullptr.
David Blaikie33dd45d02015-03-23 18:39:02 +00006230 if (!info->verbose) {
Kevin Enderbybf246f52014-09-24 23:08:22 +00006231 *ReferenceName = nullptr;
6232 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006233 return nullptr;
6234 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00006235
Kevin Enderbyf6d25852015-01-31 00:37:11 +00006236 const char *SymbolName = GuessSymbolName(ReferenceValue, info->AddrMap);
Kevin Enderbybf246f52014-09-24 23:08:22 +00006237
Kevin Enderby85974882014-09-26 22:20:44 +00006238 if (*ReferenceType == LLVMDisassembler_ReferenceType_In_Branch) {
6239 *ReferenceName = GuessIndirectSymbol(ReferenceValue, info);
Kevin Enderby04bf6932014-10-28 23:39:46 +00006240 if (*ReferenceName != nullptr) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006241 method_reference(info, ReferenceType, ReferenceName);
6242 if (*ReferenceType != LLVMDisassembler_ReferenceType_Out_Objc_Message)
6243 *ReferenceType = LLVMDisassembler_ReferenceType_Out_SymbolStub;
Rafael Espindolab940b662016-09-06 19:16:48 +00006244 } else if (SymbolName != nullptr && strncmp(SymbolName, "__Z", 3) == 0) {
Kevin Enderby04bf6932014-10-28 23:39:46 +00006245 if (info->demangled_name != nullptr)
6246 free(info->demangled_name);
6247 int status;
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006248 info->demangled_name =
Rafael Espindolab940b662016-09-06 19:16:48 +00006249 itaniumDemangle(SymbolName + 1, nullptr, nullptr, &status);
Kevin Enderby04bf6932014-10-28 23:39:46 +00006250 if (info->demangled_name != nullptr) {
6251 *ReferenceName = info->demangled_name;
6252 *ReferenceType = LLVMDisassembler_ReferenceType_DeMangled_Name;
6253 } else
6254 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
6255 } else
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006256 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
6257 } else if (*ReferenceType == LLVMDisassembler_ReferenceType_In_PCrel_Load) {
6258 *ReferenceName =
6259 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
Kevin Enderby85974882014-09-26 22:20:44 +00006260 if (*ReferenceName)
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006261 method_reference(info, ReferenceType, ReferenceName);
Kevin Enderby85974882014-09-26 22:20:44 +00006262 else
6263 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
Kevin Enderbyae3c1262014-11-14 21:52:18 +00006264 // If this is arm64 and the reference is an adrp instruction save the
6265 // instruction, passed in ReferenceValue and the address of the instruction
6266 // for use later if we see and add immediate instruction.
6267 } else if (info->O->getArch() == Triple::aarch64 &&
6268 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADRP) {
6269 info->adrp_inst = ReferenceValue;
6270 info->adrp_addr = ReferencePC;
6271 SymbolName = nullptr;
6272 *ReferenceName = nullptr;
6273 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
6274 // If this is arm64 and reference is an add immediate instruction and we
6275 // have
6276 // seen an adrp instruction just before it and the adrp's Xd register
6277 // matches
6278 // this add's Xn register reconstruct the value being referenced and look to
6279 // see if it is a literal pointer. Note the add immediate instruction is
6280 // passed in ReferenceValue.
6281 } else if (info->O->getArch() == Triple::aarch64 &&
6282 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADDXri &&
6283 ReferencePC - 4 == info->adrp_addr &&
6284 (info->adrp_inst & 0x9f000000) == 0x90000000 &&
6285 (info->adrp_inst & 0x1f) == ((ReferenceValue >> 5) & 0x1f)) {
6286 uint32_t addxri_inst;
6287 uint64_t adrp_imm, addxri_imm;
6288
6289 adrp_imm =
6290 ((info->adrp_inst & 0x00ffffe0) >> 3) | ((info->adrp_inst >> 29) & 0x3);
6291 if (info->adrp_inst & 0x0200000)
6292 adrp_imm |= 0xfffffffffc000000LL;
6293
6294 addxri_inst = ReferenceValue;
6295 addxri_imm = (addxri_inst >> 10) & 0xfff;
6296 if (((addxri_inst >> 22) & 0x3) == 1)
6297 addxri_imm <<= 12;
6298
6299 ReferenceValue = (info->adrp_addr & 0xfffffffffffff000LL) +
6300 (adrp_imm << 12) + addxri_imm;
6301
6302 *ReferenceName =
6303 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
6304 if (*ReferenceName == nullptr)
6305 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
6306 // If this is arm64 and the reference is a load register instruction and we
6307 // have seen an adrp instruction just before it and the adrp's Xd register
6308 // matches this add's Xn register reconstruct the value being referenced and
6309 // look to see if it is a literal pointer. Note the load register
6310 // instruction is passed in ReferenceValue.
6311 } else if (info->O->getArch() == Triple::aarch64 &&
6312 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_LDRXui &&
6313 ReferencePC - 4 == info->adrp_addr &&
6314 (info->adrp_inst & 0x9f000000) == 0x90000000 &&
6315 (info->adrp_inst & 0x1f) == ((ReferenceValue >> 5) & 0x1f)) {
6316 uint32_t ldrxui_inst;
6317 uint64_t adrp_imm, ldrxui_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 ldrxui_inst = ReferenceValue;
6325 ldrxui_imm = (ldrxui_inst >> 10) & 0xfff;
6326
6327 ReferenceValue = (info->adrp_addr & 0xfffffffffffff000LL) +
6328 (adrp_imm << 12) + (ldrxui_imm << 3);
6329
6330 *ReferenceName =
6331 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
6332 if (*ReferenceName == nullptr)
6333 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
6334 }
6335 // If this arm64 and is an load register (PC-relative) instruction the
6336 // ReferenceValue is the PC plus the immediate value.
6337 else if (info->O->getArch() == Triple::aarch64 &&
6338 (*ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_LDRXl ||
6339 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADR)) {
6340 *ReferenceName =
6341 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
6342 if (*ReferenceName == nullptr)
6343 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
Rafael Espindolab940b662016-09-06 19:16:48 +00006344 } else if (SymbolName != nullptr && strncmp(SymbolName, "__Z", 3) == 0) {
Kevin Enderby04bf6932014-10-28 23:39:46 +00006345 if (info->demangled_name != nullptr)
6346 free(info->demangled_name);
6347 int status;
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006348 info->demangled_name =
Rafael Espindolab940b662016-09-06 19:16:48 +00006349 itaniumDemangle(SymbolName + 1, nullptr, nullptr, &status);
Kevin Enderby04bf6932014-10-28 23:39:46 +00006350 if (info->demangled_name != nullptr) {
6351 *ReferenceName = info->demangled_name;
6352 *ReferenceType = LLVMDisassembler_ReferenceType_DeMangled_Name;
6353 }
6354 }
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006355 else {
Kevin Enderbybf246f52014-09-24 23:08:22 +00006356 *ReferenceName = nullptr;
6357 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
6358 }
6359
6360 return SymbolName;
6361}
6362
Kevin Enderbybf246f52014-09-24 23:08:22 +00006363/// \brief Emits the comments that are stored in the CommentStream.
6364/// Each comment in the CommentStream must end with a newline.
6365static void emitComments(raw_svector_ostream &CommentStream,
6366 SmallString<128> &CommentsToEmit,
6367 formatted_raw_ostream &FormattedOS,
6368 const MCAsmInfo &MAI) {
6369 // Flush the stream before taking its content.
Kevin Enderbybf246f52014-09-24 23:08:22 +00006370 StringRef Comments = CommentsToEmit.str();
6371 // Get the default information for printing a comment.
Mehdi Amini36d33fc2016-10-01 06:46:33 +00006372 StringRef CommentBegin = MAI.getCommentString();
Kevin Enderbybf246f52014-09-24 23:08:22 +00006373 unsigned CommentColumn = MAI.getCommentColumn();
6374 bool IsFirst = true;
6375 while (!Comments.empty()) {
6376 if (!IsFirst)
6377 FormattedOS << '\n';
6378 // Emit a line of comments.
6379 FormattedOS.PadToColumn(CommentColumn);
6380 size_t Position = Comments.find('\n');
6381 FormattedOS << CommentBegin << ' ' << Comments.substr(0, Position);
6382 // Move after the newline character.
6383 Comments = Comments.substr(Position + 1);
6384 IsFirst = false;
6385 }
6386 FormattedOS.flush();
6387
6388 // Tell the comment stream that the vector changed underneath it.
6389 CommentsToEmit.clear();
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006390}
6391
Kevin Enderby95df54c2015-02-04 01:01:38 +00006392static void DisassembleMachO(StringRef Filename, MachOObjectFile *MachOOF,
6393 StringRef DisSegName, StringRef DisSectName) {
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006394 const char *McpuDefault = nullptr;
6395 const Target *ThumbTarget = nullptr;
6396 const Target *TheTarget = GetTarget(MachOOF, &McpuDefault, &ThumbTarget);
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006397 if (!TheTarget) {
6398 // GetTarget prints out stuff.
6399 return;
6400 }
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006401 if (MCPU.empty() && McpuDefault)
6402 MCPU = McpuDefault;
6403
Ahmed Charles56440fd2014-03-06 05:51:42 +00006404 std::unique_ptr<const MCInstrInfo> InstrInfo(TheTarget->createMCInstrInfo());
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006405 std::unique_ptr<const MCInstrInfo> ThumbInstrInfo;
Kevin Enderbyae3c1262014-11-14 21:52:18 +00006406 if (ThumbTarget)
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006407 ThumbInstrInfo.reset(ThumbTarget->createMCInstrInfo());
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006408
Kevin Enderbyc9595622014-08-06 23:24:41 +00006409 // Package up features to be passed to target/subtarget
6410 std::string FeaturesStr;
6411 if (MAttrs.size()) {
6412 SubtargetFeatures Features;
6413 for (unsigned i = 0; i != MAttrs.size(); ++i)
6414 Features.AddFeature(MAttrs[i]);
6415 FeaturesStr = Features.getString();
6416 }
6417
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006418 // Set up disassembler.
Ahmed Charles56440fd2014-03-06 05:51:42 +00006419 std::unique_ptr<const MCRegisterInfo> MRI(
6420 TheTarget->createMCRegInfo(TripleName));
6421 std::unique_ptr<const MCAsmInfo> AsmInfo(
Rafael Espindola227144c2013-05-13 01:16:13 +00006422 TheTarget->createMCAsmInfo(*MRI, TripleName));
Ahmed Charles56440fd2014-03-06 05:51:42 +00006423 std::unique_ptr<const MCSubtargetInfo> STI(
Kevin Enderbyc9595622014-08-06 23:24:41 +00006424 TheTarget->createMCSubtargetInfo(TripleName, MCPU, FeaturesStr));
Craig Toppere6cb63e2014-04-25 04:24:47 +00006425 MCContext Ctx(AsmInfo.get(), MRI.get(), nullptr);
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006426 std::unique_ptr<MCDisassembler> DisAsm(
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006427 TheTarget->createMCDisassembler(*STI, Ctx));
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006428 std::unique_ptr<MCSymbolizer> Symbolizer;
6429 struct DisassembleInfo SymbolizerInfo;
6430 std::unique_ptr<MCRelocationInfo> RelInfo(
6431 TheTarget->createMCRelocationInfo(TripleName, Ctx));
6432 if (RelInfo) {
6433 Symbolizer.reset(TheTarget->createMCSymbolizer(
6434 TripleName, SymbolizerGetOpInfo, SymbolizerSymbolLookUp,
David Blaikie186db432015-01-18 20:45:48 +00006435 &SymbolizerInfo, &Ctx, std::move(RelInfo)));
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006436 DisAsm->setSymbolizer(std::move(Symbolizer));
6437 }
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006438 int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
Ahmed Charles56440fd2014-03-06 05:51:42 +00006439 std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
Daniel Sanders50f17232015-09-15 16:17:27 +00006440 Triple(TripleName), AsmPrinterVariant, *AsmInfo, *InstrInfo, *MRI));
Kevin Enderbybf246f52014-09-24 23:08:22 +00006441 // Set the display preference for hex vs. decimal immediates.
6442 IP->setPrintImmHex(PrintImmHex);
6443 // Comment stream and backing vector.
6444 SmallString<128> CommentsToEmit;
6445 raw_svector_ostream CommentStream(CommentsToEmit);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00006446 // FIXME: Setting the CommentStream in the InstPrinter is problematic in that
6447 // if it is done then arm64 comments for string literals don't get printed
6448 // and some constant get printed instead and not setting it causes intel
6449 // (32-bit and 64-bit) comments printed with different spacing before the
6450 // comment causing different diffs with the 'C' disassembler library API.
6451 // IP->setCommentStream(CommentStream);
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00006452
Kevin Enderbyae3c1262014-11-14 21:52:18 +00006453 if (!AsmInfo || !STI || !DisAsm || !IP) {
Michael J. Spencerc1363cf2011-10-07 19:25:47 +00006454 errs() << "error: couldn't initialize disassembler for target "
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00006455 << TripleName << '\n';
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006456 return;
6457 }
6458
Tim Northover09ca33e2016-04-22 23:23:31 +00006459 // Set up separate thumb disassembler if needed.
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006460 std::unique_ptr<const MCRegisterInfo> ThumbMRI;
6461 std::unique_ptr<const MCAsmInfo> ThumbAsmInfo;
6462 std::unique_ptr<const MCSubtargetInfo> ThumbSTI;
Kevin Enderby930fdc72014-11-06 19:00:13 +00006463 std::unique_ptr<MCDisassembler> ThumbDisAsm;
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006464 std::unique_ptr<MCInstPrinter> ThumbIP;
6465 std::unique_ptr<MCContext> ThumbCtx;
Kevin Enderby930fdc72014-11-06 19:00:13 +00006466 std::unique_ptr<MCSymbolizer> ThumbSymbolizer;
6467 struct DisassembleInfo ThumbSymbolizerInfo;
6468 std::unique_ptr<MCRelocationInfo> ThumbRelInfo;
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006469 if (ThumbTarget) {
6470 ThumbMRI.reset(ThumbTarget->createMCRegInfo(ThumbTripleName));
6471 ThumbAsmInfo.reset(
6472 ThumbTarget->createMCAsmInfo(*ThumbMRI, ThumbTripleName));
6473 ThumbSTI.reset(
6474 ThumbTarget->createMCSubtargetInfo(ThumbTripleName, MCPU, FeaturesStr));
6475 ThumbCtx.reset(new MCContext(ThumbAsmInfo.get(), ThumbMRI.get(), nullptr));
6476 ThumbDisAsm.reset(ThumbTarget->createMCDisassembler(*ThumbSTI, *ThumbCtx));
Kevin Enderby930fdc72014-11-06 19:00:13 +00006477 MCContext *PtrThumbCtx = ThumbCtx.get();
6478 ThumbRelInfo.reset(
6479 ThumbTarget->createMCRelocationInfo(ThumbTripleName, *PtrThumbCtx));
6480 if (ThumbRelInfo) {
6481 ThumbSymbolizer.reset(ThumbTarget->createMCSymbolizer(
6482 ThumbTripleName, SymbolizerGetOpInfo, SymbolizerSymbolLookUp,
David Blaikie186db432015-01-18 20:45:48 +00006483 &ThumbSymbolizerInfo, PtrThumbCtx, std::move(ThumbRelInfo)));
Kevin Enderby930fdc72014-11-06 19:00:13 +00006484 ThumbDisAsm->setSymbolizer(std::move(ThumbSymbolizer));
6485 }
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006486 int ThumbAsmPrinterVariant = ThumbAsmInfo->getAssemblerDialect();
6487 ThumbIP.reset(ThumbTarget->createMCInstPrinter(
Daniel Sanders50f17232015-09-15 16:17:27 +00006488 Triple(ThumbTripleName), ThumbAsmPrinterVariant, *ThumbAsmInfo,
6489 *ThumbInstrInfo, *ThumbMRI));
Kevin Enderbybf246f52014-09-24 23:08:22 +00006490 // Set the display preference for hex vs. decimal immediates.
6491 ThumbIP->setPrintImmHex(PrintImmHex);
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006492 }
6493
Kevin Enderbyae3c1262014-11-14 21:52:18 +00006494 if (ThumbTarget && (!ThumbAsmInfo || !ThumbSTI || !ThumbDisAsm || !ThumbIP)) {
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006495 errs() << "error: couldn't initialize disassembler for target "
6496 << ThumbTripleName << '\n';
6497 return;
6498 }
6499
Charles Davis8bdfafd2013-09-01 04:28:48 +00006500 MachO::mach_header Header = MachOOF->getHeader();
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006501
Ahmed Bougachaaa790682013-05-24 01:07:04 +00006502 // FIXME: Using the -cfg command line option, this code used to be able to
6503 // annotate relocations with the referenced symbol's name, and if this was
6504 // inside a __[cf]string section, the data it points to. This is now replaced
6505 // by the upcoming MCSymbolizer, which needs the appropriate setup done above.
Owen Andersond9243c42011-10-17 21:37:35 +00006506 std::vector<SectionRef> Sections;
6507 std::vector<SymbolRef> Symbols;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006508 SmallVector<uint64_t, 8> FoundFns;
Kevin Enderby273ae012013-06-06 17:20:50 +00006509 uint64_t BaseSegmentAddress;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006510
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00006511 getSectionsAndSymbols(MachOOF, Sections, Symbols, FoundFns,
Kevin Enderby273ae012013-06-06 17:20:50 +00006512 BaseSegmentAddress);
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006513
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006514 // Sort the symbols by address, just in case they didn't come in that way.
Owen Andersond9243c42011-10-17 21:37:35 +00006515 std::sort(Symbols.begin(), Symbols.end(), SymbolSorter());
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006516
Kevin Enderby273ae012013-06-06 17:20:50 +00006517 // Build a data in code table that is sorted on by the address of each entry.
6518 uint64_t BaseAddress = 0;
Charles Davis8bdfafd2013-09-01 04:28:48 +00006519 if (Header.filetype == MachO::MH_OBJECT)
Rafael Espindola80291272014-10-08 15:28:58 +00006520 BaseAddress = Sections[0].getAddress();
Kevin Enderby273ae012013-06-06 17:20:50 +00006521 else
6522 BaseAddress = BaseSegmentAddress;
6523 DiceTable Dices;
Kevin Enderby273ae012013-06-06 17:20:50 +00006524 for (dice_iterator DI = MachOOF->begin_dices(), DE = MachOOF->end_dices();
Rafael Espindola5e812af2014-01-30 02:49:50 +00006525 DI != DE; ++DI) {
Kevin Enderby273ae012013-06-06 17:20:50 +00006526 uint32_t Offset;
6527 DI->getOffset(Offset);
6528 Dices.push_back(std::make_pair(BaseAddress + Offset, *DI));
6529 }
6530 array_pod_sort(Dices.begin(), Dices.end());
6531
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006532#ifndef NDEBUG
6533 raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls();
6534#else
6535 raw_ostream &DebugOut = nulls();
6536#endif
6537
Ahmed Charles56440fd2014-03-06 05:51:42 +00006538 std::unique_ptr<DIContext> diContext;
Rafael Espindola9b709252013-04-13 01:45:40 +00006539 ObjectFile *DbgObj = MachOOF;
Benjamin Kramer699128e2011-09-21 01:13:19 +00006540 // Try to find debug info and set up the DIContext for it.
6541 if (UseDbg) {
Benjamin Kramer699128e2011-09-21 01:13:19 +00006542 // A separate DSym file path was specified, parse it as a macho file,
6543 // get the sections and supply it to the section name parsing machinery.
6544 if (!DSYMFile.empty()) {
Rafael Espindola48af1c22014-08-19 18:44:46 +00006545 ErrorOr<std::unique_ptr<MemoryBuffer>> BufOrErr =
Rafael Espindolaadf21f22014-07-06 17:43:13 +00006546 MemoryBuffer::getFileOrSTDIN(DSYMFile);
Rafael Espindola48af1c22014-08-19 18:44:46 +00006547 if (std::error_code EC = BufOrErr.getError()) {
Rafael Espindolaadf21f22014-07-06 17:43:13 +00006548 errs() << "llvm-objdump: " << Filename << ": " << EC.message() << '\n';
Benjamin Kramer699128e2011-09-21 01:13:19 +00006549 return;
6550 }
Rafael Espindola48af1c22014-08-19 18:44:46 +00006551 DbgObj =
6552 ObjectFile::createMachOObjectFile(BufOrErr.get()->getMemBufferRef())
6553 .get()
6554 .release();
Benjamin Kramer699128e2011-09-21 01:13:19 +00006555 }
6556
Eric Christopher7370b552012-11-12 21:40:38 +00006557 // Setup the DIContext
Zachary Turner6489d7b2015-04-23 17:37:47 +00006558 diContext.reset(new DWARFContextInMemory(*DbgObj));
Benjamin Kramer699128e2011-09-21 01:13:19 +00006559 }
6560
Colin LeMahieufcc32762015-07-29 19:08:10 +00006561 if (FilterSections.size() == 0)
Kevin Enderby95df54c2015-02-04 01:01:38 +00006562 outs() << "(" << DisSegName << "," << DisSectName << ") section\n";
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00006563
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006564 for (unsigned SectIdx = 0; SectIdx != Sections.size(); SectIdx++) {
Owen Andersond9243c42011-10-17 21:37:35 +00006565 StringRef SectName;
Kevin Enderby95df54c2015-02-04 01:01:38 +00006566 if (Sections[SectIdx].getName(SectName) || SectName != DisSectName)
6567 continue;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006568
Rafael Espindolaa9f810b2012-12-21 03:47:03 +00006569 DataRefImpl DR = Sections[SectIdx].getRawDataRefImpl();
Ahmed Bougachaaa790682013-05-24 01:07:04 +00006570
Rafael Espindolab0f76a42013-04-05 15:15:22 +00006571 StringRef SegmentName = MachOOF->getSectionFinalSegmentName(DR);
Kevin Enderby95df54c2015-02-04 01:01:38 +00006572 if (SegmentName != DisSegName)
Rafael Espindolaa9f810b2012-12-21 03:47:03 +00006573 continue;
6574
Rafael Espindola7fc5b872014-11-12 02:04:27 +00006575 StringRef BytesStr;
6576 Sections[SectIdx].getContents(BytesStr);
Aaron Ballman106fd7b2014-11-12 14:01:17 +00006577 ArrayRef<uint8_t> Bytes(reinterpret_cast<const uint8_t *>(BytesStr.data()),
6578 BytesStr.size());
Rafael Espindola80291272014-10-08 15:28:58 +00006579 uint64_t SectAddress = Sections[SectIdx].getAddress();
Rafael Espindolabd604f22014-11-07 00:52:15 +00006580
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006581 bool symbolTableWorked = false;
6582
Kevin Enderbybf246f52014-09-24 23:08:22 +00006583 // Create a map of symbol addresses to symbol names for use by
6584 // the SymbolizerSymbolLookUp() routine.
6585 SymbolAddressMap AddrMap;
Kevin Enderby6a221752015-03-17 17:10:57 +00006586 bool DisSymNameFound = false;
Kevin Enderbybf246f52014-09-24 23:08:22 +00006587 for (const SymbolRef &Symbol : MachOOF->symbols()) {
Kevin Enderby7bd8d992016-05-02 20:28:12 +00006588 Expected<SymbolRef::Type> STOrErr = Symbol.getType();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00006589 if (!STOrErr)
6590 report_error(MachOOF->getFileName(), STOrErr.takeError());
Kevin Enderby5afbc1c2016-03-23 20:27:00 +00006591 SymbolRef::Type ST = *STOrErr;
Kevin Enderbybf246f52014-09-24 23:08:22 +00006592 if (ST == SymbolRef::ST_Function || ST == SymbolRef::ST_Data ||
6593 ST == SymbolRef::ST_Other) {
Rafael Espindoladea00162015-07-03 17:44:18 +00006594 uint64_t Address = Symbol.getValue();
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00006595 Expected<StringRef> SymNameOrErr = Symbol.getName();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00006596 if (!SymNameOrErr)
6597 report_error(MachOOF->getFileName(), SymNameOrErr.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00006598 StringRef SymName = *SymNameOrErr;
Kevin Enderbybf246f52014-09-24 23:08:22 +00006599 AddrMap[Address] = SymName;
Kevin Enderby6a221752015-03-17 17:10:57 +00006600 if (!DisSymName.empty() && DisSymName == SymName)
6601 DisSymNameFound = true;
Kevin Enderbybf246f52014-09-24 23:08:22 +00006602 }
6603 }
David Blaikie33dd45d02015-03-23 18:39:02 +00006604 if (!DisSymName.empty() && !DisSymNameFound) {
Kevin Enderby6a221752015-03-17 17:10:57 +00006605 outs() << "Can't find -dis-symname: " << DisSymName << "\n";
6606 return;
6607 }
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006608 // Set up the block of info used by the Symbolizer call backs.
Kevin Enderby8e29ec92015-03-17 22:26:11 +00006609 SymbolizerInfo.verbose = !NoSymbolicOperands;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006610 SymbolizerInfo.O = MachOOF;
6611 SymbolizerInfo.S = Sections[SectIdx];
Kevin Enderbybf246f52014-09-24 23:08:22 +00006612 SymbolizerInfo.AddrMap = &AddrMap;
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006613 SymbolizerInfo.Sections = &Sections;
6614 SymbolizerInfo.class_name = nullptr;
6615 SymbolizerInfo.selector_name = nullptr;
6616 SymbolizerInfo.method = nullptr;
Kevin Enderby04bf6932014-10-28 23:39:46 +00006617 SymbolizerInfo.demangled_name = nullptr;
Kevin Enderby078be602014-10-23 19:53:12 +00006618 SymbolizerInfo.bindtable = nullptr;
Kevin Enderby10738222014-11-19 20:20:16 +00006619 SymbolizerInfo.adrp_addr = 0;
6620 SymbolizerInfo.adrp_inst = 0;
Kevin Enderby930fdc72014-11-06 19:00:13 +00006621 // Same for the ThumbSymbolizer
Kevin Enderby8e29ec92015-03-17 22:26:11 +00006622 ThumbSymbolizerInfo.verbose = !NoSymbolicOperands;
Kevin Enderby930fdc72014-11-06 19:00:13 +00006623 ThumbSymbolizerInfo.O = MachOOF;
6624 ThumbSymbolizerInfo.S = Sections[SectIdx];
6625 ThumbSymbolizerInfo.AddrMap = &AddrMap;
6626 ThumbSymbolizerInfo.Sections = &Sections;
6627 ThumbSymbolizerInfo.class_name = nullptr;
6628 ThumbSymbolizerInfo.selector_name = nullptr;
6629 ThumbSymbolizerInfo.method = nullptr;
6630 ThumbSymbolizerInfo.demangled_name = nullptr;
6631 ThumbSymbolizerInfo.bindtable = nullptr;
Kevin Enderby10738222014-11-19 20:20:16 +00006632 ThumbSymbolizerInfo.adrp_addr = 0;
6633 ThumbSymbolizerInfo.adrp_inst = 0;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006634
Kevin Enderby4b627be2016-04-28 20:14:13 +00006635 unsigned int Arch = MachOOF->getArch();
6636
Tim Northoverf203ab52016-07-14 22:13:32 +00006637 // Skip all symbols if this is a stubs file.
6638 if (Bytes.size() == 0)
6639 return;
6640
Kevin Enderbyc138da32017-02-06 18:43:18 +00006641 // If the section has symbols but no symbol at the start of the section
6642 // these are used to make sure the bytes before the first symbol are
6643 // disassembled.
6644 bool FirstSymbol = true;
6645 bool FirstSymbolAtSectionStart = true;
6646
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00006647 // Disassemble symbol by symbol.
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006648 for (unsigned SymIdx = 0; SymIdx != Symbols.size(); SymIdx++) {
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00006649 Expected<StringRef> SymNameOrErr = Symbols[SymIdx].getName();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00006650 if (!SymNameOrErr)
6651 report_error(MachOOF->getFileName(), SymNameOrErr.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00006652 StringRef SymName = *SymNameOrErr;
Owen Andersond9243c42011-10-17 21:37:35 +00006653
Kevin Enderby7bd8d992016-05-02 20:28:12 +00006654 Expected<SymbolRef::Type> STOrErr = Symbols[SymIdx].getType();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00006655 if (!STOrErr)
6656 report_error(MachOOF->getFileName(), STOrErr.takeError());
Kevin Enderby5afbc1c2016-03-23 20:27:00 +00006657 SymbolRef::Type ST = *STOrErr;
Kuba Breckade833222015-11-12 09:40:29 +00006658 if (ST != SymbolRef::ST_Function && ST != SymbolRef::ST_Data)
Owen Andersond9243c42011-10-17 21:37:35 +00006659 continue;
6660
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00006661 // Make sure the symbol is defined in this section.
Rafael Espindola80291272014-10-08 15:28:58 +00006662 bool containsSym = Sections[SectIdx].containsSymbol(Symbols[SymIdx]);
Kevin Enderbyd8a6e832016-06-15 21:14:01 +00006663 if (!containsSym) {
6664 if (!DisSymName.empty() && DisSymName == SymName) {
6665 outs() << "-dis-symname: " << DisSymName << " not in the section\n";
6666 return;
6667 }
6668 continue;
6669 }
6670 // The __mh_execute_header is special and we need to deal with that fact
6671 // this symbol is before the start of the (__TEXT,__text) section and at the
6672 // address of the start of the __TEXT segment. This is because this symbol
6673 // is an N_SECT symbol in the (__TEXT,__text) but its address is before the
6674 // start of the section in a standard MH_EXECUTE filetype.
6675 if (!DisSymName.empty() && DisSymName == "__mh_execute_header") {
6676 outs() << "-dis-symname: __mh_execute_header not in any section\n";
6677 return;
6678 }
Tim Northoverfbefee32016-07-14 23:13:03 +00006679 // When this code is trying to disassemble a symbol at a time and in the
6680 // case there is only the __mh_execute_header symbol left as in a stripped
6681 // executable, we need to deal with this by ignoring this symbol so the
6682 // whole section is disassembled and this symbol is then not displayed.
6683 if (SymName == "__mh_execute_header" || SymName == "__mh_dylib_header" ||
6684 SymName == "__mh_bundle_header" || SymName == "__mh_object_header" ||
6685 SymName == "__mh_preload_header" || SymName == "__mh_dylinker_header")
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006686 continue;
6687
Kevin Enderby6a221752015-03-17 17:10:57 +00006688 // If we are only disassembling one symbol see if this is that symbol.
6689 if (!DisSymName.empty() && DisSymName != SymName)
6690 continue;
6691
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00006692 // Start at the address of the symbol relative to the section's address.
Tim Northoverf203ab52016-07-14 22:13:32 +00006693 uint64_t SectSize = Sections[SectIdx].getSize();
Rafael Espindoladea00162015-07-03 17:44:18 +00006694 uint64_t Start = Symbols[SymIdx].getValue();
Rafael Espindola80291272014-10-08 15:28:58 +00006695 uint64_t SectionAddress = Sections[SectIdx].getAddress();
Cameron Zwarich54478a52012-02-03 05:42:17 +00006696 Start -= SectionAddress;
Owen Andersond9243c42011-10-17 21:37:35 +00006697
Tim Northoverf203ab52016-07-14 22:13:32 +00006698 if (Start > SectSize) {
6699 outs() << "section data ends, " << SymName
6700 << " lies outside valid range\n";
6701 return;
6702 }
6703
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00006704 // Stop disassembling either at the beginning of the next symbol or at
6705 // the end of the section.
Kevin Enderbyedd58722012-05-15 18:57:14 +00006706 bool containsNextSym = false;
Owen Andersond9243c42011-10-17 21:37:35 +00006707 uint64_t NextSym = 0;
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006708 uint64_t NextSymIdx = SymIdx + 1;
Owen Andersond9243c42011-10-17 21:37:35 +00006709 while (Symbols.size() > NextSymIdx) {
Kevin Enderby7bd8d992016-05-02 20:28:12 +00006710 Expected<SymbolRef::Type> STOrErr = Symbols[NextSymIdx].getType();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00006711 if (!STOrErr)
6712 report_error(MachOOF->getFileName(), STOrErr.takeError());
Kevin Enderby5afbc1c2016-03-23 20:27:00 +00006713 SymbolRef::Type NextSymType = *STOrErr;
Owen Andersond9243c42011-10-17 21:37:35 +00006714 if (NextSymType == SymbolRef::ST_Function) {
Rafael Espindola80291272014-10-08 15:28:58 +00006715 containsNextSym =
6716 Sections[SectIdx].containsSymbol(Symbols[NextSymIdx]);
Rafael Espindoladea00162015-07-03 17:44:18 +00006717 NextSym = Symbols[NextSymIdx].getValue();
Cameron Zwarich54478a52012-02-03 05:42:17 +00006718 NextSym -= SectionAddress;
Owen Andersond9243c42011-10-17 21:37:35 +00006719 break;
6720 }
6721 ++NextSymIdx;
6722 }
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006723
Tim Northoverf203ab52016-07-14 22:13:32 +00006724 uint64_t End = containsNextSym ? std::min(NextSym, SectSize) : SectSize;
Owen Andersond9243c42011-10-17 21:37:35 +00006725 uint64_t Size;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006726
6727 symbolTableWorked = true;
Rafael Espindolabd604f22014-11-07 00:52:15 +00006728
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006729 DataRefImpl Symb = Symbols[SymIdx].getRawDataRefImpl();
Tim Northover09ca33e2016-04-22 23:23:31 +00006730 bool IsThumb = MachOOF->getSymbolFlags(Symb) & SymbolRef::SF_Thumb;
6731
6732 // We only need the dedicated Thumb target if there's a real choice
6733 // (i.e. we're not targeting M-class) and the function is Thumb.
6734 bool UseThumbTarget = IsThumb && ThumbTarget;
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006735
Kevin Enderbyc138da32017-02-06 18:43:18 +00006736 // If we are not specifying a symbol to start disassembly with and this
6737 // is the first symbol in the section but not at the start of the section
6738 // then move the disassembly index to the start of the section and
6739 // don't print the symbol name just yet. This is so the bytes before the
6740 // first symbol are disassembled.
6741 uint64_t SymbolStart = Start;
6742 if (DisSymName.empty() && FirstSymbol && Start != 0) {
6743 FirstSymbolAtSectionStart = false;
6744 Start = 0;
6745 }
6746 else
6747 outs() << SymName << ":\n";
6748
Ahmed Bougachaaa790682013-05-24 01:07:04 +00006749 DILineInfo lastLine;
6750 for (uint64_t Index = Start; Index < End; Index += Size) {
6751 MCInst Inst;
Owen Andersond9243c42011-10-17 21:37:35 +00006752
Kevin Enderbyc138da32017-02-06 18:43:18 +00006753 // If this is the first symbol in the section and it was not at the
6754 // start of the section, see if we are at its Index now and if so print
6755 // the symbol name.
6756 if (FirstSymbol && !FirstSymbolAtSectionStart && Index == SymbolStart)
6757 outs() << SymName << ":\n";
6758
Kevin Enderbybf246f52014-09-24 23:08:22 +00006759 uint64_t PC = SectAddress + Index;
Kevin Enderbyab5e6c92015-03-17 21:07:39 +00006760 if (!NoLeadingAddr) {
6761 if (FullLeadingAddr) {
6762 if (MachOOF->is64Bit())
6763 outs() << format("%016" PRIx64, PC);
6764 else
6765 outs() << format("%08" PRIx64, PC);
6766 } else {
6767 outs() << format("%8" PRIx64 ":", PC);
6768 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00006769 }
Kevin Enderby4b627be2016-04-28 20:14:13 +00006770 if (!NoShowRawInsn || Arch == Triple::arm)
Kevin Enderbybf246f52014-09-24 23:08:22 +00006771 outs() << "\t";
Kevin Enderby273ae012013-06-06 17:20:50 +00006772
6773 // Check the data in code table here to see if this is data not an
6774 // instruction to be disassembled.
6775 DiceTable Dice;
Kevin Enderbybf246f52014-09-24 23:08:22 +00006776 Dice.push_back(std::make_pair(PC, DiceRef()));
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006777 dice_table_iterator DTI =
6778 std::search(Dices.begin(), Dices.end(), Dice.begin(), Dice.end(),
6779 compareDiceTableEntries);
6780 if (DTI != Dices.end()) {
Kevin Enderby273ae012013-06-06 17:20:50 +00006781 uint16_t Length;
6782 DTI->second.getLength(Length);
Kevin Enderby273ae012013-06-06 17:20:50 +00006783 uint16_t Kind;
6784 DTI->second.getKind(Kind);
Colin LeMahieufc32b1b2015-03-18 19:27:31 +00006785 Size = DumpDataInCode(Bytes.data() + Index, Length, Kind);
Kevin Enderby930fdc72014-11-06 19:00:13 +00006786 if ((Kind == MachO::DICE_KIND_JUMP_TABLE8) &&
6787 (PC == (DTI->first + Length - 1)) && (Length & 1))
6788 Size++;
Kevin Enderby273ae012013-06-06 17:20:50 +00006789 continue;
6790 }
6791
Kevin Enderbybf246f52014-09-24 23:08:22 +00006792 SmallVector<char, 64> AnnotationsBytes;
6793 raw_svector_ostream Annotations(AnnotationsBytes);
6794
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006795 bool gotInst;
Tim Northover09ca33e2016-04-22 23:23:31 +00006796 if (UseThumbTarget)
Rafael Espindola7fc5b872014-11-12 02:04:27 +00006797 gotInst = ThumbDisAsm->getInstruction(Inst, Size, Bytes.slice(Index),
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006798 PC, DebugOut, Annotations);
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006799 else
Rafael Espindola7fc5b872014-11-12 02:04:27 +00006800 gotInst = DisAsm->getInstruction(Inst, Size, Bytes.slice(Index), PC,
Kevin Enderbybf246f52014-09-24 23:08:22 +00006801 DebugOut, Annotations);
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006802 if (gotInst) {
Kevin Enderby4b627be2016-04-28 20:14:13 +00006803 if (!NoShowRawInsn || Arch == Triple::arm) {
Craig Topper0013be12015-09-21 05:32:41 +00006804 dumpBytes(makeArrayRef(Bytes.data() + Index, Size), outs());
Kevin Enderbybf246f52014-09-24 23:08:22 +00006805 }
6806 formatted_raw_ostream FormattedOS(outs());
Kevin Enderbybf246f52014-09-24 23:08:22 +00006807 StringRef AnnotationsStr = Annotations.str();
Tim Northover09ca33e2016-04-22 23:23:31 +00006808 if (UseThumbTarget)
Akira Hatanakab46d0232015-03-27 20:36:02 +00006809 ThumbIP->printInst(&Inst, FormattedOS, AnnotationsStr, *ThumbSTI);
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006810 else
Akira Hatanaka1d079942015-03-28 20:44:05 +00006811 IP->printInst(&Inst, FormattedOS, AnnotationsStr, *STI);
Kevin Enderbybf246f52014-09-24 23:08:22 +00006812 emitComments(CommentStream, CommentsToEmit, FormattedOS, *AsmInfo);
Owen Andersond9243c42011-10-17 21:37:35 +00006813
Ahmed Bougachaaa790682013-05-24 01:07:04 +00006814 // Print debug info.
6815 if (diContext) {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006816 DILineInfo dli = diContext->getLineInfoForAddress(PC);
Ahmed Bougachaaa790682013-05-24 01:07:04 +00006817 // Print valid line info if it changed.
Alexey Samsonovd0109992014-04-18 21:36:39 +00006818 if (dli != lastLine && dli.Line != 0)
6819 outs() << "\t## " << dli.FileName << ':' << dli.Line << ':'
6820 << dli.Column;
Ahmed Bougachaaa790682013-05-24 01:07:04 +00006821 lastLine = dli;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006822 }
Ahmed Bougachaaa790682013-05-24 01:07:04 +00006823 outs() << "\n";
6824 } else {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006825 unsigned int Arch = MachOOF->getArch();
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006826 if (Arch == Triple::x86_64 || Arch == Triple::x86) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006827 outs() << format("\t.byte 0x%02x #bad opcode\n",
6828 *(Bytes.data() + Index) & 0xff);
6829 Size = 1; // skip exactly one illegible byte and move on.
Tim Northover09ca33e2016-04-22 23:23:31 +00006830 } else if (Arch == Triple::aarch64 ||
6831 (Arch == Triple::arm && !IsThumb)) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00006832 uint32_t opcode = (*(Bytes.data() + Index) & 0xff) |
6833 (*(Bytes.data() + Index + 1) & 0xff) << 8 |
6834 (*(Bytes.data() + Index + 2) & 0xff) << 16 |
6835 (*(Bytes.data() + Index + 3) & 0xff) << 24;
6836 outs() << format("\t.long\t0x%08x\n", opcode);
6837 Size = 4;
Tim Northover09ca33e2016-04-22 23:23:31 +00006838 } else if (Arch == Triple::arm) {
6839 assert(IsThumb && "ARM mode should have been dealt with above");
6840 uint32_t opcode = (*(Bytes.data() + Index) & 0xff) |
6841 (*(Bytes.data() + Index + 1) & 0xff) << 8;
6842 outs() << format("\t.short\t0x%04x\n", opcode);
6843 Size = 2;
6844 } else{
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006845 errs() << "llvm-objdump: warning: invalid instruction encoding\n";
6846 if (Size == 0)
6847 Size = 1; // skip illegible bytes
6848 }
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006849 }
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006850 }
Kevin Enderbyc138da32017-02-06 18:43:18 +00006851 // Now that we are done disassembled the first symbol set the bool that
6852 // were doing this to false.
6853 FirstSymbol = false;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006854 }
Ahmed Bougachaaa790682013-05-24 01:07:04 +00006855 if (!symbolTableWorked) {
Rafael Espindola80291272014-10-08 15:28:58 +00006856 // Reading the symbol table didn't work, disassemble the whole section.
6857 uint64_t SectAddress = Sections[SectIdx].getAddress();
6858 uint64_t SectSize = Sections[SectIdx].getSize();
Kevin Enderbybadd1002012-05-18 00:13:56 +00006859 uint64_t InstSize;
6860 for (uint64_t Index = 0; Index < SectSize; Index += InstSize) {
Bill Wendling4e68e062012-07-19 00:17:40 +00006861 MCInst Inst;
Kevin Enderbybadd1002012-05-18 00:13:56 +00006862
Kevin Enderbybf246f52014-09-24 23:08:22 +00006863 uint64_t PC = SectAddress + Index;
Kevin Enderby02d3a372017-01-31 18:09:10 +00006864 SmallVector<char, 64> AnnotationsBytes;
6865 raw_svector_ostream Annotations(AnnotationsBytes);
Rafael Espindola7fc5b872014-11-12 02:04:27 +00006866 if (DisAsm->getInstruction(Inst, InstSize, Bytes.slice(Index), PC,
Kevin Enderby02d3a372017-01-31 18:09:10 +00006867 DebugOut, Annotations)) {
Kevin Enderbyab5e6c92015-03-17 21:07:39 +00006868 if (!NoLeadingAddr) {
6869 if (FullLeadingAddr) {
6870 if (MachOOF->is64Bit())
6871 outs() << format("%016" PRIx64, PC);
6872 else
6873 outs() << format("%08" PRIx64, PC);
6874 } else {
6875 outs() << format("%8" PRIx64 ":", PC);
6876 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00006877 }
Kevin Enderby4b627be2016-04-28 20:14:13 +00006878 if (!NoShowRawInsn || Arch == Triple::arm) {
Kevin Enderbybf246f52014-09-24 23:08:22 +00006879 outs() << "\t";
Craig Topper0013be12015-09-21 05:32:41 +00006880 dumpBytes(makeArrayRef(Bytes.data() + Index, InstSize), outs());
Kevin Enderbybf246f52014-09-24 23:08:22 +00006881 }
Kevin Enderby02d3a372017-01-31 18:09:10 +00006882 StringRef AnnotationsStr = Annotations.str();
6883 IP->printInst(&Inst, outs(), AnnotationsStr, *STI);
Bill Wendling4e68e062012-07-19 00:17:40 +00006884 outs() << "\n";
6885 } else {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006886 unsigned int Arch = MachOOF->getArch();
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006887 if (Arch == Triple::x86_64 || Arch == Triple::x86) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006888 outs() << format("\t.byte 0x%02x #bad opcode\n",
6889 *(Bytes.data() + Index) & 0xff);
6890 InstSize = 1; // skip exactly one illegible byte and move on.
6891 } else {
6892 errs() << "llvm-objdump: warning: invalid instruction encoding\n";
6893 if (InstSize == 0)
6894 InstSize = 1; // skip illegible bytes
6895 }
Bill Wendling4e68e062012-07-19 00:17:40 +00006896 }
Kevin Enderbybadd1002012-05-18 00:13:56 +00006897 }
6898 }
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00006899 // The TripleName's need to be reset if we are called again for a different
6900 // archtecture.
6901 TripleName = "";
6902 ThumbTripleName = "";
6903
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006904 if (SymbolizerInfo.method != nullptr)
6905 free(SymbolizerInfo.method);
Kevin Enderby04bf6932014-10-28 23:39:46 +00006906 if (SymbolizerInfo.demangled_name != nullptr)
6907 free(SymbolizerInfo.demangled_name);
Kevin Enderby930fdc72014-11-06 19:00:13 +00006908 if (ThumbSymbolizerInfo.method != nullptr)
6909 free(ThumbSymbolizerInfo.method);
6910 if (ThumbSymbolizerInfo.demangled_name != nullptr)
6911 free(ThumbSymbolizerInfo.demangled_name);
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006912 }
6913}
Tim Northover4bd286a2014-08-01 13:07:19 +00006914
Tim Northover39c70bb2014-08-12 11:52:59 +00006915//===----------------------------------------------------------------------===//
6916// __compact_unwind section dumping
6917//===----------------------------------------------------------------------===//
6918
Tim Northover4bd286a2014-08-01 13:07:19 +00006919namespace {
Tim Northover39c70bb2014-08-12 11:52:59 +00006920
6921template <typename T> static uint64_t readNext(const char *&Buf) {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006922 using llvm::support::little;
6923 using llvm::support::unaligned;
Tim Northover39c70bb2014-08-12 11:52:59 +00006924
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006925 uint64_t Val = support::endian::read<T, little, unaligned>(Buf);
6926 Buf += sizeof(T);
6927 return Val;
6928}
Tim Northover39c70bb2014-08-12 11:52:59 +00006929
Tim Northover4bd286a2014-08-01 13:07:19 +00006930struct CompactUnwindEntry {
6931 uint32_t OffsetInSection;
6932
6933 uint64_t FunctionAddr;
6934 uint32_t Length;
6935 uint32_t CompactEncoding;
6936 uint64_t PersonalityAddr;
6937 uint64_t LSDAAddr;
6938
6939 RelocationRef FunctionReloc;
6940 RelocationRef PersonalityReloc;
6941 RelocationRef LSDAReloc;
6942
6943 CompactUnwindEntry(StringRef Contents, unsigned Offset, bool Is64)
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006944 : OffsetInSection(Offset) {
Tim Northover4bd286a2014-08-01 13:07:19 +00006945 if (Is64)
6946 read<uint64_t>(Contents.data() + Offset);
6947 else
6948 read<uint32_t>(Contents.data() + Offset);
6949 }
6950
6951private:
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006952 template <typename UIntPtr> void read(const char *Buf) {
Tim Northover4bd286a2014-08-01 13:07:19 +00006953 FunctionAddr = readNext<UIntPtr>(Buf);
6954 Length = readNext<uint32_t>(Buf);
6955 CompactEncoding = readNext<uint32_t>(Buf);
6956 PersonalityAddr = readNext<UIntPtr>(Buf);
6957 LSDAAddr = readNext<UIntPtr>(Buf);
6958 }
6959};
6960}
6961
6962/// Given a relocation from __compact_unwind, consisting of the RelocationRef
6963/// and data being relocated, determine the best base Name and Addend to use for
6964/// display purposes.
6965///
6966/// 1. An Extern relocation will directly reference a symbol (and the data is
6967/// then already an addend), so use that.
6968/// 2. Otherwise the data is an offset in the object file's layout; try to find
6969// a symbol before it in the same section, and use the offset from there.
6970/// 3. Finally, if all that fails, fall back to an offset from the start of the
6971/// referenced section.
6972static void findUnwindRelocNameAddend(const MachOObjectFile *Obj,
6973 std::map<uint64_t, SymbolRef> &Symbols,
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006974 const RelocationRef &Reloc, uint64_t Addr,
Tim Northover4bd286a2014-08-01 13:07:19 +00006975 StringRef &Name, uint64_t &Addend) {
6976 if (Reloc.getSymbol() != Obj->symbol_end()) {
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00006977 Expected<StringRef> NameOrErr = Reloc.getSymbol()->getName();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00006978 if (!NameOrErr)
6979 report_error(Obj->getFileName(), NameOrErr.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00006980 Name = *NameOrErr;
Tim Northover4bd286a2014-08-01 13:07:19 +00006981 Addend = Addr;
6982 return;
6983 }
6984
6985 auto RE = Obj->getRelocation(Reloc.getRawDataRefImpl());
Keno Fischerc780e8e2015-05-21 21:24:32 +00006986 SectionRef RelocSection = Obj->getAnyRelocationSection(RE);
Tim Northover4bd286a2014-08-01 13:07:19 +00006987
Rafael Espindola80291272014-10-08 15:28:58 +00006988 uint64_t SectionAddr = RelocSection.getAddress();
Tim Northover4bd286a2014-08-01 13:07:19 +00006989
6990 auto Sym = Symbols.upper_bound(Addr);
6991 if (Sym == Symbols.begin()) {
6992 // The first symbol in the object is after this reference, the best we can
6993 // do is section-relative notation.
6994 RelocSection.getName(Name);
6995 Addend = Addr - SectionAddr;
6996 return;
6997 }
6998
6999 // Go back one so that SymbolAddress <= Addr.
7000 --Sym;
7001
Kevin Enderby7bd8d992016-05-02 20:28:12 +00007002 auto SectOrErr = Sym->second.getSection();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00007003 if (!SectOrErr)
7004 report_error(Obj->getFileName(), SectOrErr.takeError());
Kevin Enderby7bd8d992016-05-02 20:28:12 +00007005 section_iterator SymSection = *SectOrErr;
Tim Northover4bd286a2014-08-01 13:07:19 +00007006 if (RelocSection == *SymSection) {
7007 // There's a valid symbol in the same section before this reference.
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00007008 Expected<StringRef> NameOrErr = Sym->second.getName();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00007009 if (!NameOrErr)
7010 report_error(Obj->getFileName(), NameOrErr.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00007011 Name = *NameOrErr;
Tim Northover4bd286a2014-08-01 13:07:19 +00007012 Addend = Addr - Sym->first;
7013 return;
7014 }
7015
7016 // There is a symbol before this reference, but it's in a different
7017 // section. Probably not helpful to mention it, so use the section name.
7018 RelocSection.getName(Name);
7019 Addend = Addr - SectionAddr;
7020}
7021
7022static void printUnwindRelocDest(const MachOObjectFile *Obj,
7023 std::map<uint64_t, SymbolRef> &Symbols,
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007024 const RelocationRef &Reloc, uint64_t Addr) {
Tim Northover4bd286a2014-08-01 13:07:19 +00007025 StringRef Name;
7026 uint64_t Addend;
7027
Rafael Espindola854038e2015-06-26 14:51:16 +00007028 if (!Reloc.getObject())
Tim Northover0b0add52014-09-09 10:45:06 +00007029 return;
7030
Tim Northover4bd286a2014-08-01 13:07:19 +00007031 findUnwindRelocNameAddend(Obj, Symbols, Reloc, Addr, Name, Addend);
7032
7033 outs() << Name;
7034 if (Addend)
Tim Northover63a25622014-08-11 09:14:06 +00007035 outs() << " + " << format("0x%" PRIx64, Addend);
Tim Northover4bd286a2014-08-01 13:07:19 +00007036}
7037
7038static void
7039printMachOCompactUnwindSection(const MachOObjectFile *Obj,
7040 std::map<uint64_t, SymbolRef> &Symbols,
7041 const SectionRef &CompactUnwind) {
7042
Tim Northoverbf55f7e2016-11-15 20:26:01 +00007043 if (!Obj->isLittleEndian()) {
7044 outs() << "Skipping big-endian __compact_unwind section\n";
7045 return;
7046 }
Tim Northover4bd286a2014-08-01 13:07:19 +00007047
7048 bool Is64 = Obj->is64Bit();
7049 uint32_t PointerSize = Is64 ? sizeof(uint64_t) : sizeof(uint32_t);
7050 uint32_t EntrySize = 3 * PointerSize + 2 * sizeof(uint32_t);
7051
7052 StringRef Contents;
7053 CompactUnwind.getContents(Contents);
7054
7055 SmallVector<CompactUnwindEntry, 4> CompactUnwinds;
7056
7057 // First populate the initial raw offsets, encodings and so on from the entry.
7058 for (unsigned Offset = 0; Offset < Contents.size(); Offset += EntrySize) {
7059 CompactUnwindEntry Entry(Contents.data(), Offset, Is64);
7060 CompactUnwinds.push_back(Entry);
7061 }
7062
7063 // Next we need to look at the relocations to find out what objects are
7064 // actually being referred to.
7065 for (const RelocationRef &Reloc : CompactUnwind.relocations()) {
Rafael Espindola96d071c2015-06-29 23:29:12 +00007066 uint64_t RelocAddress = Reloc.getOffset();
Tim Northover4bd286a2014-08-01 13:07:19 +00007067
7068 uint32_t EntryIdx = RelocAddress / EntrySize;
7069 uint32_t OffsetInEntry = RelocAddress - EntryIdx * EntrySize;
7070 CompactUnwindEntry &Entry = CompactUnwinds[EntryIdx];
7071
7072 if (OffsetInEntry == 0)
7073 Entry.FunctionReloc = Reloc;
7074 else if (OffsetInEntry == PointerSize + 2 * sizeof(uint32_t))
7075 Entry.PersonalityReloc = Reloc;
7076 else if (OffsetInEntry == 2 * PointerSize + 2 * sizeof(uint32_t))
7077 Entry.LSDAReloc = Reloc;
Tim Northoverbf55f7e2016-11-15 20:26:01 +00007078 else {
7079 outs() << "Invalid relocation in __compact_unwind section\n";
7080 return;
7081 }
Tim Northover4bd286a2014-08-01 13:07:19 +00007082 }
7083
7084 // Finally, we're ready to print the data we've gathered.
7085 outs() << "Contents of __compact_unwind section:\n";
7086 for (auto &Entry : CompactUnwinds) {
Tim Northover06af2602014-08-08 12:08:51 +00007087 outs() << " Entry at offset "
7088 << format("0x%" PRIx32, Entry.OffsetInSection) << ":\n";
Tim Northover4bd286a2014-08-01 13:07:19 +00007089
7090 // 1. Start of the region this entry applies to.
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007091 outs() << " start: " << format("0x%" PRIx64,
7092 Entry.FunctionAddr) << ' ';
7093 printUnwindRelocDest(Obj, Symbols, Entry.FunctionReloc, Entry.FunctionAddr);
Tim Northover4bd286a2014-08-01 13:07:19 +00007094 outs() << '\n';
7095
7096 // 2. Length of the region this entry applies to.
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007097 outs() << " length: " << format("0x%" PRIx32, Entry.Length)
7098 << '\n';
Tim Northover4bd286a2014-08-01 13:07:19 +00007099 // 3. The 32-bit compact encoding.
7100 outs() << " compact encoding: "
Tim Northoverb911bf82014-08-08 12:00:09 +00007101 << format("0x%08" PRIx32, Entry.CompactEncoding) << '\n';
Tim Northover4bd286a2014-08-01 13:07:19 +00007102
7103 // 4. The personality function, if present.
Rafael Espindola854038e2015-06-26 14:51:16 +00007104 if (Entry.PersonalityReloc.getObject()) {
Tim Northover4bd286a2014-08-01 13:07:19 +00007105 outs() << " personality function: "
Tim Northoverb911bf82014-08-08 12:00:09 +00007106 << format("0x%" PRIx64, Entry.PersonalityAddr) << ' ';
Tim Northover4bd286a2014-08-01 13:07:19 +00007107 printUnwindRelocDest(Obj, Symbols, Entry.PersonalityReloc,
7108 Entry.PersonalityAddr);
7109 outs() << '\n';
7110 }
7111
7112 // 5. This entry's language-specific data area.
Rafael Espindola854038e2015-06-26 14:51:16 +00007113 if (Entry.LSDAReloc.getObject()) {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007114 outs() << " LSDA: " << format("0x%" PRIx64,
7115 Entry.LSDAAddr) << ' ';
Tim Northover4bd286a2014-08-01 13:07:19 +00007116 printUnwindRelocDest(Obj, Symbols, Entry.LSDAReloc, Entry.LSDAAddr);
7117 outs() << '\n';
7118 }
7119 }
7120}
7121
Tim Northover39c70bb2014-08-12 11:52:59 +00007122//===----------------------------------------------------------------------===//
7123// __unwind_info section dumping
7124//===----------------------------------------------------------------------===//
7125
7126static void printRegularSecondLevelUnwindPage(const char *PageStart) {
7127 const char *Pos = PageStart;
7128 uint32_t Kind = readNext<uint32_t>(Pos);
7129 (void)Kind;
7130 assert(Kind == 2 && "kind for a regular 2nd level index should be 2");
7131
7132 uint16_t EntriesStart = readNext<uint16_t>(Pos);
7133 uint16_t NumEntries = readNext<uint16_t>(Pos);
7134
7135 Pos = PageStart + EntriesStart;
7136 for (unsigned i = 0; i < NumEntries; ++i) {
7137 uint32_t FunctionOffset = readNext<uint32_t>(Pos);
7138 uint32_t Encoding = readNext<uint32_t>(Pos);
7139
7140 outs() << " [" << i << "]: "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007141 << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
7142 << ", "
7143 << "encoding=" << format("0x%08" PRIx32, Encoding) << '\n';
Tim Northover39c70bb2014-08-12 11:52:59 +00007144 }
7145}
7146
7147static void printCompressedSecondLevelUnwindPage(
7148 const char *PageStart, uint32_t FunctionBase,
7149 const SmallVectorImpl<uint32_t> &CommonEncodings) {
7150 const char *Pos = PageStart;
7151 uint32_t Kind = readNext<uint32_t>(Pos);
7152 (void)Kind;
7153 assert(Kind == 3 && "kind for a compressed 2nd level index should be 3");
7154
7155 uint16_t EntriesStart = readNext<uint16_t>(Pos);
7156 uint16_t NumEntries = readNext<uint16_t>(Pos);
7157
7158 uint16_t EncodingsStart = readNext<uint16_t>(Pos);
7159 readNext<uint16_t>(Pos);
Aaron Ballman80930af2014-08-14 13:53:19 +00007160 const auto *PageEncodings = reinterpret_cast<const support::ulittle32_t *>(
7161 PageStart + EncodingsStart);
Tim Northover39c70bb2014-08-12 11:52:59 +00007162
7163 Pos = PageStart + EntriesStart;
7164 for (unsigned i = 0; i < NumEntries; ++i) {
7165 uint32_t Entry = readNext<uint32_t>(Pos);
7166 uint32_t FunctionOffset = FunctionBase + (Entry & 0xffffff);
7167 uint32_t EncodingIdx = Entry >> 24;
7168
7169 uint32_t Encoding;
7170 if (EncodingIdx < CommonEncodings.size())
7171 Encoding = CommonEncodings[EncodingIdx];
7172 else
7173 Encoding = PageEncodings[EncodingIdx - CommonEncodings.size()];
7174
7175 outs() << " [" << i << "]: "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007176 << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
7177 << ", "
7178 << "encoding[" << EncodingIdx
7179 << "]=" << format("0x%08" PRIx32, Encoding) << '\n';
Tim Northover39c70bb2014-08-12 11:52:59 +00007180 }
7181}
7182
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007183static void printMachOUnwindInfoSection(const MachOObjectFile *Obj,
7184 std::map<uint64_t, SymbolRef> &Symbols,
7185 const SectionRef &UnwindInfo) {
Tim Northover39c70bb2014-08-12 11:52:59 +00007186
Tim Northoverbf55f7e2016-11-15 20:26:01 +00007187 if (!Obj->isLittleEndian()) {
7188 outs() << "Skipping big-endian __unwind_info section\n";
7189 return;
7190 }
Tim Northover39c70bb2014-08-12 11:52:59 +00007191
7192 outs() << "Contents of __unwind_info section:\n";
7193
7194 StringRef Contents;
7195 UnwindInfo.getContents(Contents);
7196 const char *Pos = Contents.data();
7197
7198 //===----------------------------------
7199 // Section header
7200 //===----------------------------------
7201
7202 uint32_t Version = readNext<uint32_t>(Pos);
7203 outs() << " Version: "
7204 << format("0x%" PRIx32, Version) << '\n';
Tim Northoverbf55f7e2016-11-15 20:26:01 +00007205 if (Version != 1) {
7206 outs() << " Skipping section with unknown version\n";
7207 return;
7208 }
Tim Northover39c70bb2014-08-12 11:52:59 +00007209
7210 uint32_t CommonEncodingsStart = readNext<uint32_t>(Pos);
7211 outs() << " Common encodings array section offset: "
7212 << format("0x%" PRIx32, CommonEncodingsStart) << '\n';
7213 uint32_t NumCommonEncodings = readNext<uint32_t>(Pos);
7214 outs() << " Number of common encodings in array: "
7215 << format("0x%" PRIx32, NumCommonEncodings) << '\n';
7216
7217 uint32_t PersonalitiesStart = readNext<uint32_t>(Pos);
7218 outs() << " Personality function array section offset: "
7219 << format("0x%" PRIx32, PersonalitiesStart) << '\n';
7220 uint32_t NumPersonalities = readNext<uint32_t>(Pos);
7221 outs() << " Number of personality functions in array: "
7222 << format("0x%" PRIx32, NumPersonalities) << '\n';
7223
7224 uint32_t IndicesStart = readNext<uint32_t>(Pos);
7225 outs() << " Index array section offset: "
7226 << format("0x%" PRIx32, IndicesStart) << '\n';
7227 uint32_t NumIndices = readNext<uint32_t>(Pos);
7228 outs() << " Number of indices in array: "
7229 << format("0x%" PRIx32, NumIndices) << '\n';
7230
7231 //===----------------------------------
7232 // A shared list of common encodings
7233 //===----------------------------------
7234
7235 // These occupy indices in the range [0, N] whenever an encoding is referenced
7236 // from a compressed 2nd level index table. In practice the linker only
7237 // creates ~128 of these, so that indices are available to embed encodings in
7238 // the 2nd level index.
7239
7240 SmallVector<uint32_t, 64> CommonEncodings;
7241 outs() << " Common encodings: (count = " << NumCommonEncodings << ")\n";
7242 Pos = Contents.data() + CommonEncodingsStart;
7243 for (unsigned i = 0; i < NumCommonEncodings; ++i) {
7244 uint32_t Encoding = readNext<uint32_t>(Pos);
7245 CommonEncodings.push_back(Encoding);
7246
7247 outs() << " encoding[" << i << "]: " << format("0x%08" PRIx32, Encoding)
7248 << '\n';
7249 }
7250
Tim Northover39c70bb2014-08-12 11:52:59 +00007251 //===----------------------------------
7252 // Personality functions used in this executable
7253 //===----------------------------------
7254
7255 // There should be only a handful of these (one per source language,
7256 // roughly). Particularly since they only get 2 bits in the compact encoding.
7257
7258 outs() << " Personality functions: (count = " << NumPersonalities << ")\n";
7259 Pos = Contents.data() + PersonalitiesStart;
7260 for (unsigned i = 0; i < NumPersonalities; ++i) {
7261 uint32_t PersonalityFn = readNext<uint32_t>(Pos);
7262 outs() << " personality[" << i + 1
7263 << "]: " << format("0x%08" PRIx32, PersonalityFn) << '\n';
7264 }
7265
7266 //===----------------------------------
7267 // The level 1 index entries
7268 //===----------------------------------
7269
7270 // These specify an approximate place to start searching for the more detailed
7271 // information, sorted by PC.
7272
7273 struct IndexEntry {
7274 uint32_t FunctionOffset;
7275 uint32_t SecondLevelPageStart;
7276 uint32_t LSDAStart;
7277 };
7278
7279 SmallVector<IndexEntry, 4> IndexEntries;
7280
7281 outs() << " Top level indices: (count = " << NumIndices << ")\n";
7282 Pos = Contents.data() + IndicesStart;
7283 for (unsigned i = 0; i < NumIndices; ++i) {
7284 IndexEntry Entry;
7285
7286 Entry.FunctionOffset = readNext<uint32_t>(Pos);
7287 Entry.SecondLevelPageStart = readNext<uint32_t>(Pos);
7288 Entry.LSDAStart = readNext<uint32_t>(Pos);
7289 IndexEntries.push_back(Entry);
7290
7291 outs() << " [" << i << "]: "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007292 << "function offset=" << format("0x%08" PRIx32, Entry.FunctionOffset)
7293 << ", "
Tim Northover39c70bb2014-08-12 11:52:59 +00007294 << "2nd level page offset="
7295 << format("0x%08" PRIx32, Entry.SecondLevelPageStart) << ", "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007296 << "LSDA offset=" << format("0x%08" PRIx32, Entry.LSDAStart) << '\n';
Tim Northover39c70bb2014-08-12 11:52:59 +00007297 }
7298
Tim Northover39c70bb2014-08-12 11:52:59 +00007299 //===----------------------------------
7300 // Next come the LSDA tables
7301 //===----------------------------------
7302
7303 // The LSDA layout is rather implicit: it's a contiguous array of entries from
7304 // the first top-level index's LSDAOffset to the last (sentinel).
7305
7306 outs() << " LSDA descriptors:\n";
7307 Pos = Contents.data() + IndexEntries[0].LSDAStart;
7308 int NumLSDAs = (IndexEntries.back().LSDAStart - IndexEntries[0].LSDAStart) /
7309 (2 * sizeof(uint32_t));
7310 for (int i = 0; i < NumLSDAs; ++i) {
7311 uint32_t FunctionOffset = readNext<uint32_t>(Pos);
7312 uint32_t LSDAOffset = readNext<uint32_t>(Pos);
7313 outs() << " [" << i << "]: "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007314 << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
7315 << ", "
7316 << "LSDA offset=" << format("0x%08" PRIx32, LSDAOffset) << '\n';
Tim Northover39c70bb2014-08-12 11:52:59 +00007317 }
7318
7319 //===----------------------------------
7320 // Finally, the 2nd level indices
7321 //===----------------------------------
7322
7323 // Generally these are 4K in size, and have 2 possible forms:
7324 // + Regular stores up to 511 entries with disparate encodings
7325 // + Compressed stores up to 1021 entries if few enough compact encoding
7326 // values are used.
7327 outs() << " Second level indices:\n";
7328 for (unsigned i = 0; i < IndexEntries.size() - 1; ++i) {
7329 // The final sentinel top-level index has no associated 2nd level page
7330 if (IndexEntries[i].SecondLevelPageStart == 0)
7331 break;
7332
7333 outs() << " Second level index[" << i << "]: "
7334 << "offset in section="
7335 << format("0x%08" PRIx32, IndexEntries[i].SecondLevelPageStart)
7336 << ", "
7337 << "base function offset="
7338 << format("0x%08" PRIx32, IndexEntries[i].FunctionOffset) << '\n';
7339
7340 Pos = Contents.data() + IndexEntries[i].SecondLevelPageStart;
Aaron Ballman80930af2014-08-14 13:53:19 +00007341 uint32_t Kind = *reinterpret_cast<const support::ulittle32_t *>(Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007342 if (Kind == 2)
7343 printRegularSecondLevelUnwindPage(Pos);
7344 else if (Kind == 3)
7345 printCompressedSecondLevelUnwindPage(Pos, IndexEntries[i].FunctionOffset,
7346 CommonEncodings);
7347 else
Tim Northoverbf55f7e2016-11-15 20:26:01 +00007348 outs() << " Skipping 2nd level page with unknown kind " << Kind
7349 << '\n';
Tim Northover39c70bb2014-08-12 11:52:59 +00007350 }
7351}
7352
Tim Northover4bd286a2014-08-01 13:07:19 +00007353void llvm::printMachOUnwindInfo(const MachOObjectFile *Obj) {
7354 std::map<uint64_t, SymbolRef> Symbols;
7355 for (const SymbolRef &SymRef : Obj->symbols()) {
7356 // Discard any undefined or absolute symbols. They're not going to take part
7357 // in the convenience lookup for unwind info and just take up resources.
Kevin Enderby7bd8d992016-05-02 20:28:12 +00007358 auto SectOrErr = SymRef.getSection();
7359 if (!SectOrErr) {
7360 // TODO: Actually report errors helpfully.
7361 consumeError(SectOrErr.takeError());
7362 continue;
7363 }
7364 section_iterator Section = *SectOrErr;
Tim Northover4bd286a2014-08-01 13:07:19 +00007365 if (Section == Obj->section_end())
7366 continue;
7367
Rafael Espindoladea00162015-07-03 17:44:18 +00007368 uint64_t Addr = SymRef.getValue();
Tim Northover4bd286a2014-08-01 13:07:19 +00007369 Symbols.insert(std::make_pair(Addr, SymRef));
7370 }
7371
7372 for (const SectionRef &Section : Obj->sections()) {
7373 StringRef SectName;
7374 Section.getName(SectName);
7375 if (SectName == "__compact_unwind")
7376 printMachOCompactUnwindSection(Obj, Symbols, Section);
7377 else if (SectName == "__unwind_info")
Tim Northover39c70bb2014-08-12 11:52:59 +00007378 printMachOUnwindInfoSection(Obj, Symbols, Section);
Tim Northover4bd286a2014-08-01 13:07:19 +00007379 }
7380}
Kevin Enderbyb76d3862014-08-22 20:35:18 +00007381
7382static void PrintMachHeader(uint32_t magic, uint32_t cputype,
7383 uint32_t cpusubtype, uint32_t filetype,
7384 uint32_t ncmds, uint32_t sizeofcmds, uint32_t flags,
7385 bool verbose) {
7386 outs() << "Mach header\n";
7387 outs() << " magic cputype cpusubtype caps filetype ncmds "
7388 "sizeofcmds flags\n";
7389 if (verbose) {
7390 if (magic == MachO::MH_MAGIC)
7391 outs() << " MH_MAGIC";
7392 else if (magic == MachO::MH_MAGIC_64)
7393 outs() << "MH_MAGIC_64";
7394 else
7395 outs() << format(" 0x%08" PRIx32, magic);
7396 switch (cputype) {
7397 case MachO::CPU_TYPE_I386:
7398 outs() << " I386";
7399 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
7400 case MachO::CPU_SUBTYPE_I386_ALL:
7401 outs() << " ALL";
7402 break;
7403 default:
7404 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
7405 break;
7406 }
7407 break;
7408 case MachO::CPU_TYPE_X86_64:
7409 outs() << " X86_64";
Kevin Enderby131d1772015-01-09 19:22:37 +00007410 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
7411 case MachO::CPU_SUBTYPE_X86_64_ALL:
7412 outs() << " ALL";
7413 break;
7414 case MachO::CPU_SUBTYPE_X86_64_H:
7415 outs() << " Haswell";
7416 break;
7417 default:
7418 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
7419 break;
7420 }
Kevin Enderbyb76d3862014-08-22 20:35:18 +00007421 break;
7422 case MachO::CPU_TYPE_ARM:
7423 outs() << " ARM";
7424 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
7425 case MachO::CPU_SUBTYPE_ARM_ALL:
7426 outs() << " ALL";
7427 break;
7428 case MachO::CPU_SUBTYPE_ARM_V4T:
7429 outs() << " V4T";
7430 break;
7431 case MachO::CPU_SUBTYPE_ARM_V5TEJ:
7432 outs() << " V5TEJ";
7433 break;
7434 case MachO::CPU_SUBTYPE_ARM_XSCALE:
7435 outs() << " XSCALE";
7436 break;
7437 case MachO::CPU_SUBTYPE_ARM_V6:
7438 outs() << " V6";
7439 break;
7440 case MachO::CPU_SUBTYPE_ARM_V6M:
7441 outs() << " V6M";
7442 break;
7443 case MachO::CPU_SUBTYPE_ARM_V7:
7444 outs() << " V7";
7445 break;
7446 case MachO::CPU_SUBTYPE_ARM_V7EM:
7447 outs() << " V7EM";
7448 break;
7449 case MachO::CPU_SUBTYPE_ARM_V7K:
7450 outs() << " V7K";
7451 break;
7452 case MachO::CPU_SUBTYPE_ARM_V7M:
7453 outs() << " V7M";
7454 break;
7455 case MachO::CPU_SUBTYPE_ARM_V7S:
7456 outs() << " V7S";
7457 break;
7458 default:
7459 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
7460 break;
7461 }
7462 break;
7463 case MachO::CPU_TYPE_ARM64:
7464 outs() << " ARM64";
7465 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
7466 case MachO::CPU_SUBTYPE_ARM64_ALL:
7467 outs() << " ALL";
7468 break;
7469 default:
7470 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
7471 break;
7472 }
7473 break;
7474 case MachO::CPU_TYPE_POWERPC:
7475 outs() << " PPC";
7476 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
7477 case MachO::CPU_SUBTYPE_POWERPC_ALL:
7478 outs() << " ALL";
7479 break;
7480 default:
7481 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
7482 break;
7483 }
7484 break;
7485 case MachO::CPU_TYPE_POWERPC64:
7486 outs() << " PPC64";
7487 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
7488 case MachO::CPU_SUBTYPE_POWERPC_ALL:
7489 outs() << " ALL";
7490 break;
7491 default:
7492 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
7493 break;
7494 }
7495 break;
Kevin Enderby40fdbf82016-01-26 18:20:49 +00007496 default:
7497 outs() << format(" %7d", cputype);
7498 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
7499 break;
Kevin Enderbyb76d3862014-08-22 20:35:18 +00007500 }
7501 if ((cpusubtype & MachO::CPU_SUBTYPE_MASK) == MachO::CPU_SUBTYPE_LIB64) {
Kevin Enderby8ae63c12014-09-04 16:54:47 +00007502 outs() << " LIB64";
Kevin Enderbyb76d3862014-08-22 20:35:18 +00007503 } else {
7504 outs() << format(" 0x%02" PRIx32,
7505 (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24);
7506 }
7507 switch (filetype) {
7508 case MachO::MH_OBJECT:
7509 outs() << " OBJECT";
7510 break;
7511 case MachO::MH_EXECUTE:
7512 outs() << " EXECUTE";
7513 break;
7514 case MachO::MH_FVMLIB:
7515 outs() << " FVMLIB";
7516 break;
7517 case MachO::MH_CORE:
7518 outs() << " CORE";
7519 break;
7520 case MachO::MH_PRELOAD:
7521 outs() << " PRELOAD";
7522 break;
7523 case MachO::MH_DYLIB:
7524 outs() << " DYLIB";
7525 break;
7526 case MachO::MH_DYLIB_STUB:
7527 outs() << " DYLIB_STUB";
7528 break;
7529 case MachO::MH_DYLINKER:
7530 outs() << " DYLINKER";
7531 break;
7532 case MachO::MH_BUNDLE:
7533 outs() << " BUNDLE";
7534 break;
7535 case MachO::MH_DSYM:
7536 outs() << " DSYM";
7537 break;
7538 case MachO::MH_KEXT_BUNDLE:
7539 outs() << " KEXTBUNDLE";
7540 break;
7541 default:
7542 outs() << format(" %10u", filetype);
7543 break;
7544 }
7545 outs() << format(" %5u", ncmds);
7546 outs() << format(" %10u", sizeofcmds);
7547 uint32_t f = flags;
7548 if (f & MachO::MH_NOUNDEFS) {
7549 outs() << " NOUNDEFS";
7550 f &= ~MachO::MH_NOUNDEFS;
7551 }
7552 if (f & MachO::MH_INCRLINK) {
7553 outs() << " INCRLINK";
7554 f &= ~MachO::MH_INCRLINK;
7555 }
7556 if (f & MachO::MH_DYLDLINK) {
7557 outs() << " DYLDLINK";
7558 f &= ~MachO::MH_DYLDLINK;
7559 }
7560 if (f & MachO::MH_BINDATLOAD) {
7561 outs() << " BINDATLOAD";
7562 f &= ~MachO::MH_BINDATLOAD;
7563 }
7564 if (f & MachO::MH_PREBOUND) {
7565 outs() << " PREBOUND";
7566 f &= ~MachO::MH_PREBOUND;
7567 }
7568 if (f & MachO::MH_SPLIT_SEGS) {
7569 outs() << " SPLIT_SEGS";
7570 f &= ~MachO::MH_SPLIT_SEGS;
7571 }
7572 if (f & MachO::MH_LAZY_INIT) {
7573 outs() << " LAZY_INIT";
7574 f &= ~MachO::MH_LAZY_INIT;
7575 }
7576 if (f & MachO::MH_TWOLEVEL) {
7577 outs() << " TWOLEVEL";
7578 f &= ~MachO::MH_TWOLEVEL;
7579 }
7580 if (f & MachO::MH_FORCE_FLAT) {
7581 outs() << " FORCE_FLAT";
7582 f &= ~MachO::MH_FORCE_FLAT;
7583 }
7584 if (f & MachO::MH_NOMULTIDEFS) {
7585 outs() << " NOMULTIDEFS";
7586 f &= ~MachO::MH_NOMULTIDEFS;
7587 }
7588 if (f & MachO::MH_NOFIXPREBINDING) {
7589 outs() << " NOFIXPREBINDING";
7590 f &= ~MachO::MH_NOFIXPREBINDING;
7591 }
7592 if (f & MachO::MH_PREBINDABLE) {
7593 outs() << " PREBINDABLE";
7594 f &= ~MachO::MH_PREBINDABLE;
7595 }
7596 if (f & MachO::MH_ALLMODSBOUND) {
7597 outs() << " ALLMODSBOUND";
7598 f &= ~MachO::MH_ALLMODSBOUND;
7599 }
7600 if (f & MachO::MH_SUBSECTIONS_VIA_SYMBOLS) {
7601 outs() << " SUBSECTIONS_VIA_SYMBOLS";
7602 f &= ~MachO::MH_SUBSECTIONS_VIA_SYMBOLS;
7603 }
7604 if (f & MachO::MH_CANONICAL) {
7605 outs() << " CANONICAL";
7606 f &= ~MachO::MH_CANONICAL;
7607 }
7608 if (f & MachO::MH_WEAK_DEFINES) {
7609 outs() << " WEAK_DEFINES";
7610 f &= ~MachO::MH_WEAK_DEFINES;
7611 }
7612 if (f & MachO::MH_BINDS_TO_WEAK) {
7613 outs() << " BINDS_TO_WEAK";
7614 f &= ~MachO::MH_BINDS_TO_WEAK;
7615 }
7616 if (f & MachO::MH_ALLOW_STACK_EXECUTION) {
7617 outs() << " ALLOW_STACK_EXECUTION";
7618 f &= ~MachO::MH_ALLOW_STACK_EXECUTION;
7619 }
7620 if (f & MachO::MH_DEAD_STRIPPABLE_DYLIB) {
7621 outs() << " DEAD_STRIPPABLE_DYLIB";
7622 f &= ~MachO::MH_DEAD_STRIPPABLE_DYLIB;
7623 }
7624 if (f & MachO::MH_PIE) {
7625 outs() << " PIE";
7626 f &= ~MachO::MH_PIE;
7627 }
7628 if (f & MachO::MH_NO_REEXPORTED_DYLIBS) {
7629 outs() << " NO_REEXPORTED_DYLIBS";
7630 f &= ~MachO::MH_NO_REEXPORTED_DYLIBS;
7631 }
7632 if (f & MachO::MH_HAS_TLV_DESCRIPTORS) {
7633 outs() << " MH_HAS_TLV_DESCRIPTORS";
7634 f &= ~MachO::MH_HAS_TLV_DESCRIPTORS;
7635 }
7636 if (f & MachO::MH_NO_HEAP_EXECUTION) {
7637 outs() << " MH_NO_HEAP_EXECUTION";
7638 f &= ~MachO::MH_NO_HEAP_EXECUTION;
7639 }
7640 if (f & MachO::MH_APP_EXTENSION_SAFE) {
7641 outs() << " APP_EXTENSION_SAFE";
7642 f &= ~MachO::MH_APP_EXTENSION_SAFE;
7643 }
Kevin Enderbydf0d6da2017-06-19 19:38:22 +00007644 if (f & MachO::MH_NLIST_OUTOFSYNC_WITH_DYLDINFO) {
7645 outs() << " NLIST_OUTOFSYNC_WITH_DYLDINFO";
7646 f &= ~MachO::MH_NLIST_OUTOFSYNC_WITH_DYLDINFO;
7647 }
Kevin Enderbyb76d3862014-08-22 20:35:18 +00007648 if (f != 0 || flags == 0)
7649 outs() << format(" 0x%08" PRIx32, f);
7650 } else {
7651 outs() << format(" 0x%08" PRIx32, magic);
7652 outs() << format(" %7d", cputype);
7653 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
7654 outs() << format(" 0x%02" PRIx32,
7655 (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24);
7656 outs() << format(" %10u", filetype);
7657 outs() << format(" %5u", ncmds);
7658 outs() << format(" %10u", sizeofcmds);
7659 outs() << format(" 0x%08" PRIx32, flags);
7660 }
7661 outs() << "\n";
7662}
7663
Kevin Enderby956366c2014-08-29 22:30:52 +00007664static void PrintSegmentCommand(uint32_t cmd, uint32_t cmdsize,
7665 StringRef SegName, uint64_t vmaddr,
7666 uint64_t vmsize, uint64_t fileoff,
7667 uint64_t filesize, uint32_t maxprot,
7668 uint32_t initprot, uint32_t nsects,
7669 uint32_t flags, uint32_t object_size,
7670 bool verbose) {
7671 uint64_t expected_cmdsize;
7672 if (cmd == MachO::LC_SEGMENT) {
7673 outs() << " cmd LC_SEGMENT\n";
7674 expected_cmdsize = nsects;
7675 expected_cmdsize *= sizeof(struct MachO::section);
7676 expected_cmdsize += sizeof(struct MachO::segment_command);
7677 } else {
7678 outs() << " cmd LC_SEGMENT_64\n";
7679 expected_cmdsize = nsects;
7680 expected_cmdsize *= sizeof(struct MachO::section_64);
7681 expected_cmdsize += sizeof(struct MachO::segment_command_64);
7682 }
7683 outs() << " cmdsize " << cmdsize;
7684 if (cmdsize != expected_cmdsize)
7685 outs() << " Inconsistent size\n";
7686 else
7687 outs() << "\n";
7688 outs() << " segname " << SegName << "\n";
7689 if (cmd == MachO::LC_SEGMENT_64) {
7690 outs() << " vmaddr " << format("0x%016" PRIx64, vmaddr) << "\n";
7691 outs() << " vmsize " << format("0x%016" PRIx64, vmsize) << "\n";
7692 } else {
Kevin Enderbyadb7c432014-12-16 18:58:11 +00007693 outs() << " vmaddr " << format("0x%08" PRIx64, vmaddr) << "\n";
7694 outs() << " vmsize " << format("0x%08" PRIx64, vmsize) << "\n";
Kevin Enderby956366c2014-08-29 22:30:52 +00007695 }
7696 outs() << " fileoff " << fileoff;
7697 if (fileoff > object_size)
7698 outs() << " (past end of file)\n";
7699 else
7700 outs() << "\n";
7701 outs() << " filesize " << filesize;
7702 if (fileoff + filesize > object_size)
7703 outs() << " (past end of file)\n";
7704 else
7705 outs() << "\n";
7706 if (verbose) {
7707 if ((maxprot &
7708 ~(MachO::VM_PROT_READ | MachO::VM_PROT_WRITE |
7709 MachO::VM_PROT_EXECUTE)) != 0)
7710 outs() << " maxprot ?" << format("0x%08" PRIx32, maxprot) << "\n";
7711 else {
Davide Italiano37ff06a2015-09-02 16:53:25 +00007712 outs() << " maxprot ";
7713 outs() << ((maxprot & MachO::VM_PROT_READ) ? "r" : "-");
7714 outs() << ((maxprot & MachO::VM_PROT_WRITE) ? "w" : "-");
7715 outs() << ((maxprot & MachO::VM_PROT_EXECUTE) ? "x\n" : "-\n");
Kevin Enderby956366c2014-08-29 22:30:52 +00007716 }
7717 if ((initprot &
7718 ~(MachO::VM_PROT_READ | MachO::VM_PROT_WRITE |
7719 MachO::VM_PROT_EXECUTE)) != 0)
Kevin Enderby41c9c002016-10-21 18:22:35 +00007720 outs() << " initprot ?" << format("0x%08" PRIx32, initprot) << "\n";
Kevin Enderby956366c2014-08-29 22:30:52 +00007721 else {
Kevin Enderby41c9c002016-10-21 18:22:35 +00007722 outs() << " initprot ";
Davide Italiano37ff06a2015-09-02 16:53:25 +00007723 outs() << ((initprot & MachO::VM_PROT_READ) ? "r" : "-");
7724 outs() << ((initprot & MachO::VM_PROT_WRITE) ? "w" : "-");
7725 outs() << ((initprot & MachO::VM_PROT_EXECUTE) ? "x\n" : "-\n");
Kevin Enderby956366c2014-08-29 22:30:52 +00007726 }
7727 } else {
7728 outs() << " maxprot " << format("0x%08" PRIx32, maxprot) << "\n";
7729 outs() << " initprot " << format("0x%08" PRIx32, initprot) << "\n";
7730 }
7731 outs() << " nsects " << nsects << "\n";
7732 if (verbose) {
7733 outs() << " flags";
7734 if (flags == 0)
7735 outs() << " (none)\n";
7736 else {
7737 if (flags & MachO::SG_HIGHVM) {
7738 outs() << " HIGHVM";
7739 flags &= ~MachO::SG_HIGHVM;
7740 }
7741 if (flags & MachO::SG_FVMLIB) {
7742 outs() << " FVMLIB";
7743 flags &= ~MachO::SG_FVMLIB;
7744 }
7745 if (flags & MachO::SG_NORELOC) {
7746 outs() << " NORELOC";
7747 flags &= ~MachO::SG_NORELOC;
7748 }
7749 if (flags & MachO::SG_PROTECTED_VERSION_1) {
7750 outs() << " PROTECTED_VERSION_1";
7751 flags &= ~MachO::SG_PROTECTED_VERSION_1;
7752 }
7753 if (flags)
7754 outs() << format(" 0x%08" PRIx32, flags) << " (unknown flags)\n";
7755 else
7756 outs() << "\n";
7757 }
7758 } else {
7759 outs() << " flags " << format("0x%" PRIx32, flags) << "\n";
7760 }
7761}
7762
7763static void PrintSection(const char *sectname, const char *segname,
7764 uint64_t addr, uint64_t size, uint32_t offset,
7765 uint32_t align, uint32_t reloff, uint32_t nreloc,
7766 uint32_t flags, uint32_t reserved1, uint32_t reserved2,
7767 uint32_t cmd, const char *sg_segname,
7768 uint32_t filetype, uint32_t object_size,
7769 bool verbose) {
7770 outs() << "Section\n";
7771 outs() << " sectname " << format("%.16s\n", sectname);
7772 outs() << " segname " << format("%.16s", segname);
7773 if (filetype != MachO::MH_OBJECT && strncmp(sg_segname, segname, 16) != 0)
7774 outs() << " (does not match segment)\n";
7775 else
7776 outs() << "\n";
7777 if (cmd == MachO::LC_SEGMENT_64) {
7778 outs() << " addr " << format("0x%016" PRIx64, addr) << "\n";
7779 outs() << " size " << format("0x%016" PRIx64, size);
7780 } else {
Kevin Enderby75594b62014-12-16 21:00:25 +00007781 outs() << " addr " << format("0x%08" PRIx64, addr) << "\n";
7782 outs() << " size " << format("0x%08" PRIx64, size);
Kevin Enderby956366c2014-08-29 22:30:52 +00007783 }
7784 if ((flags & MachO::S_ZEROFILL) != 0 && offset + size > object_size)
7785 outs() << " (past end of file)\n";
7786 else
7787 outs() << "\n";
7788 outs() << " offset " << offset;
7789 if (offset > object_size)
7790 outs() << " (past end of file)\n";
7791 else
7792 outs() << "\n";
7793 uint32_t align_shifted = 1 << align;
7794 outs() << " align 2^" << align << " (" << align_shifted << ")\n";
7795 outs() << " reloff " << reloff;
7796 if (reloff > object_size)
7797 outs() << " (past end of file)\n";
7798 else
7799 outs() << "\n";
7800 outs() << " nreloc " << nreloc;
7801 if (reloff + nreloc * sizeof(struct MachO::relocation_info) > object_size)
7802 outs() << " (past end of file)\n";
7803 else
7804 outs() << "\n";
7805 uint32_t section_type = flags & MachO::SECTION_TYPE;
7806 if (verbose) {
7807 outs() << " type";
7808 if (section_type == MachO::S_REGULAR)
7809 outs() << " S_REGULAR\n";
7810 else if (section_type == MachO::S_ZEROFILL)
7811 outs() << " S_ZEROFILL\n";
7812 else if (section_type == MachO::S_CSTRING_LITERALS)
7813 outs() << " S_CSTRING_LITERALS\n";
7814 else if (section_type == MachO::S_4BYTE_LITERALS)
7815 outs() << " S_4BYTE_LITERALS\n";
7816 else if (section_type == MachO::S_8BYTE_LITERALS)
7817 outs() << " S_8BYTE_LITERALS\n";
7818 else if (section_type == MachO::S_16BYTE_LITERALS)
7819 outs() << " S_16BYTE_LITERALS\n";
7820 else if (section_type == MachO::S_LITERAL_POINTERS)
7821 outs() << " S_LITERAL_POINTERS\n";
7822 else if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS)
7823 outs() << " S_NON_LAZY_SYMBOL_POINTERS\n";
7824 else if (section_type == MachO::S_LAZY_SYMBOL_POINTERS)
7825 outs() << " S_LAZY_SYMBOL_POINTERS\n";
7826 else if (section_type == MachO::S_SYMBOL_STUBS)
7827 outs() << " S_SYMBOL_STUBS\n";
7828 else if (section_type == MachO::S_MOD_INIT_FUNC_POINTERS)
7829 outs() << " S_MOD_INIT_FUNC_POINTERS\n";
7830 else if (section_type == MachO::S_MOD_TERM_FUNC_POINTERS)
7831 outs() << " S_MOD_TERM_FUNC_POINTERS\n";
7832 else if (section_type == MachO::S_COALESCED)
7833 outs() << " S_COALESCED\n";
7834 else if (section_type == MachO::S_INTERPOSING)
7835 outs() << " S_INTERPOSING\n";
7836 else if (section_type == MachO::S_DTRACE_DOF)
7837 outs() << " S_DTRACE_DOF\n";
7838 else if (section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS)
7839 outs() << " S_LAZY_DYLIB_SYMBOL_POINTERS\n";
7840 else if (section_type == MachO::S_THREAD_LOCAL_REGULAR)
7841 outs() << " S_THREAD_LOCAL_REGULAR\n";
7842 else if (section_type == MachO::S_THREAD_LOCAL_ZEROFILL)
7843 outs() << " S_THREAD_LOCAL_ZEROFILL\n";
7844 else if (section_type == MachO::S_THREAD_LOCAL_VARIABLES)
7845 outs() << " S_THREAD_LOCAL_VARIABLES\n";
7846 else if (section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS)
7847 outs() << " S_THREAD_LOCAL_VARIABLE_POINTERS\n";
7848 else if (section_type == MachO::S_THREAD_LOCAL_INIT_FUNCTION_POINTERS)
7849 outs() << " S_THREAD_LOCAL_INIT_FUNCTION_POINTERS\n";
7850 else
7851 outs() << format("0x%08" PRIx32, section_type) << "\n";
7852 outs() << "attributes";
7853 uint32_t section_attributes = flags & MachO::SECTION_ATTRIBUTES;
7854 if (section_attributes & MachO::S_ATTR_PURE_INSTRUCTIONS)
7855 outs() << " PURE_INSTRUCTIONS";
7856 if (section_attributes & MachO::S_ATTR_NO_TOC)
7857 outs() << " NO_TOC";
7858 if (section_attributes & MachO::S_ATTR_STRIP_STATIC_SYMS)
7859 outs() << " STRIP_STATIC_SYMS";
7860 if (section_attributes & MachO::S_ATTR_NO_DEAD_STRIP)
7861 outs() << " NO_DEAD_STRIP";
7862 if (section_attributes & MachO::S_ATTR_LIVE_SUPPORT)
7863 outs() << " LIVE_SUPPORT";
7864 if (section_attributes & MachO::S_ATTR_SELF_MODIFYING_CODE)
7865 outs() << " SELF_MODIFYING_CODE";
7866 if (section_attributes & MachO::S_ATTR_DEBUG)
7867 outs() << " DEBUG";
7868 if (section_attributes & MachO::S_ATTR_SOME_INSTRUCTIONS)
7869 outs() << " SOME_INSTRUCTIONS";
7870 if (section_attributes & MachO::S_ATTR_EXT_RELOC)
7871 outs() << " EXT_RELOC";
7872 if (section_attributes & MachO::S_ATTR_LOC_RELOC)
7873 outs() << " LOC_RELOC";
7874 if (section_attributes == 0)
7875 outs() << " (none)";
7876 outs() << "\n";
7877 } else
7878 outs() << " flags " << format("0x%08" PRIx32, flags) << "\n";
7879 outs() << " reserved1 " << reserved1;
7880 if (section_type == MachO::S_SYMBOL_STUBS ||
7881 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
7882 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
7883 section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
7884 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS)
7885 outs() << " (index into indirect symbol table)\n";
7886 else
7887 outs() << "\n";
7888 outs() << " reserved2 " << reserved2;
7889 if (section_type == MachO::S_SYMBOL_STUBS)
7890 outs() << " (size of stubs)\n";
7891 else
7892 outs() << "\n";
7893}
7894
David Majnemer73cc6ff2014-11-13 19:48:56 +00007895static void PrintSymtabLoadCommand(MachO::symtab_command st, bool Is64Bit,
Kevin Enderby956366c2014-08-29 22:30:52 +00007896 uint32_t object_size) {
7897 outs() << " cmd LC_SYMTAB\n";
7898 outs() << " cmdsize " << st.cmdsize;
7899 if (st.cmdsize != sizeof(struct MachO::symtab_command))
7900 outs() << " Incorrect size\n";
7901 else
7902 outs() << "\n";
7903 outs() << " symoff " << st.symoff;
7904 if (st.symoff > object_size)
7905 outs() << " (past end of file)\n";
7906 else
7907 outs() << "\n";
7908 outs() << " nsyms " << st.nsyms;
7909 uint64_t big_size;
David Majnemer73cc6ff2014-11-13 19:48:56 +00007910 if (Is64Bit) {
Kevin Enderby956366c2014-08-29 22:30:52 +00007911 big_size = st.nsyms;
7912 big_size *= sizeof(struct MachO::nlist_64);
7913 big_size += st.symoff;
7914 if (big_size > object_size)
7915 outs() << " (past end of file)\n";
7916 else
7917 outs() << "\n";
7918 } else {
7919 big_size = st.nsyms;
7920 big_size *= sizeof(struct MachO::nlist);
7921 big_size += st.symoff;
7922 if (big_size > object_size)
7923 outs() << " (past end of file)\n";
7924 else
7925 outs() << "\n";
7926 }
7927 outs() << " stroff " << st.stroff;
7928 if (st.stroff > object_size)
7929 outs() << " (past end of file)\n";
7930 else
7931 outs() << "\n";
7932 outs() << " strsize " << st.strsize;
7933 big_size = st.stroff;
7934 big_size += st.strsize;
7935 if (big_size > object_size)
7936 outs() << " (past end of file)\n";
7937 else
7938 outs() << "\n";
7939}
7940
7941static void PrintDysymtabLoadCommand(MachO::dysymtab_command dyst,
7942 uint32_t nsyms, uint32_t object_size,
David Majnemer73cc6ff2014-11-13 19:48:56 +00007943 bool Is64Bit) {
Kevin Enderby956366c2014-08-29 22:30:52 +00007944 outs() << " cmd LC_DYSYMTAB\n";
7945 outs() << " cmdsize " << dyst.cmdsize;
7946 if (dyst.cmdsize != sizeof(struct MachO::dysymtab_command))
7947 outs() << " Incorrect size\n";
7948 else
7949 outs() << "\n";
7950 outs() << " ilocalsym " << dyst.ilocalsym;
7951 if (dyst.ilocalsym > nsyms)
7952 outs() << " (greater than the number of symbols)\n";
7953 else
7954 outs() << "\n";
7955 outs() << " nlocalsym " << dyst.nlocalsym;
7956 uint64_t big_size;
7957 big_size = dyst.ilocalsym;
7958 big_size += dyst.nlocalsym;
7959 if (big_size > nsyms)
7960 outs() << " (past the end of the symbol table)\n";
7961 else
7962 outs() << "\n";
7963 outs() << " iextdefsym " << dyst.iextdefsym;
7964 if (dyst.iextdefsym > nsyms)
7965 outs() << " (greater than the number of symbols)\n";
7966 else
7967 outs() << "\n";
7968 outs() << " nextdefsym " << dyst.nextdefsym;
7969 big_size = dyst.iextdefsym;
7970 big_size += dyst.nextdefsym;
7971 if (big_size > nsyms)
7972 outs() << " (past the end of the symbol table)\n";
7973 else
7974 outs() << "\n";
7975 outs() << " iundefsym " << dyst.iundefsym;
7976 if (dyst.iundefsym > nsyms)
7977 outs() << " (greater than the number of symbols)\n";
7978 else
7979 outs() << "\n";
7980 outs() << " nundefsym " << dyst.nundefsym;
7981 big_size = dyst.iundefsym;
7982 big_size += dyst.nundefsym;
7983 if (big_size > nsyms)
7984 outs() << " (past the end of the symbol table)\n";
7985 else
7986 outs() << "\n";
7987 outs() << " tocoff " << dyst.tocoff;
7988 if (dyst.tocoff > object_size)
7989 outs() << " (past end of file)\n";
7990 else
7991 outs() << "\n";
7992 outs() << " ntoc " << dyst.ntoc;
7993 big_size = dyst.ntoc;
7994 big_size *= sizeof(struct MachO::dylib_table_of_contents);
7995 big_size += dyst.tocoff;
7996 if (big_size > object_size)
7997 outs() << " (past end of file)\n";
7998 else
7999 outs() << "\n";
8000 outs() << " modtaboff " << dyst.modtaboff;
8001 if (dyst.modtaboff > object_size)
8002 outs() << " (past end of file)\n";
8003 else
8004 outs() << "\n";
8005 outs() << " nmodtab " << dyst.nmodtab;
8006 uint64_t modtabend;
David Majnemer73cc6ff2014-11-13 19:48:56 +00008007 if (Is64Bit) {
Kevin Enderby956366c2014-08-29 22:30:52 +00008008 modtabend = dyst.nmodtab;
8009 modtabend *= sizeof(struct MachO::dylib_module_64);
8010 modtabend += dyst.modtaboff;
8011 } else {
8012 modtabend = dyst.nmodtab;
8013 modtabend *= sizeof(struct MachO::dylib_module);
8014 modtabend += dyst.modtaboff;
8015 }
8016 if (modtabend > object_size)
8017 outs() << " (past end of file)\n";
8018 else
8019 outs() << "\n";
8020 outs() << " extrefsymoff " << dyst.extrefsymoff;
8021 if (dyst.extrefsymoff > object_size)
8022 outs() << " (past end of file)\n";
8023 else
8024 outs() << "\n";
8025 outs() << " nextrefsyms " << dyst.nextrefsyms;
8026 big_size = dyst.nextrefsyms;
8027 big_size *= sizeof(struct MachO::dylib_reference);
8028 big_size += dyst.extrefsymoff;
8029 if (big_size > object_size)
8030 outs() << " (past end of file)\n";
8031 else
8032 outs() << "\n";
8033 outs() << " indirectsymoff " << dyst.indirectsymoff;
8034 if (dyst.indirectsymoff > object_size)
8035 outs() << " (past end of file)\n";
8036 else
8037 outs() << "\n";
8038 outs() << " nindirectsyms " << dyst.nindirectsyms;
8039 big_size = dyst.nindirectsyms;
8040 big_size *= sizeof(uint32_t);
8041 big_size += dyst.indirectsymoff;
8042 if (big_size > object_size)
8043 outs() << " (past end of file)\n";
8044 else
8045 outs() << "\n";
8046 outs() << " extreloff " << dyst.extreloff;
8047 if (dyst.extreloff > object_size)
8048 outs() << " (past end of file)\n";
8049 else
8050 outs() << "\n";
8051 outs() << " nextrel " << dyst.nextrel;
8052 big_size = dyst.nextrel;
8053 big_size *= sizeof(struct MachO::relocation_info);
8054 big_size += dyst.extreloff;
8055 if (big_size > object_size)
8056 outs() << " (past end of file)\n";
8057 else
8058 outs() << "\n";
8059 outs() << " locreloff " << dyst.locreloff;
8060 if (dyst.locreloff > object_size)
8061 outs() << " (past end of file)\n";
8062 else
8063 outs() << "\n";
8064 outs() << " nlocrel " << dyst.nlocrel;
8065 big_size = dyst.nlocrel;
8066 big_size *= sizeof(struct MachO::relocation_info);
8067 big_size += dyst.locreloff;
8068 if (big_size > object_size)
8069 outs() << " (past end of file)\n";
8070 else
8071 outs() << "\n";
8072}
8073
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008074static void PrintDyldInfoLoadCommand(MachO::dyld_info_command dc,
8075 uint32_t object_size) {
8076 if (dc.cmd == MachO::LC_DYLD_INFO)
8077 outs() << " cmd LC_DYLD_INFO\n";
8078 else
8079 outs() << " cmd LC_DYLD_INFO_ONLY\n";
8080 outs() << " cmdsize " << dc.cmdsize;
8081 if (dc.cmdsize != sizeof(struct MachO::dyld_info_command))
8082 outs() << " Incorrect size\n";
8083 else
8084 outs() << "\n";
8085 outs() << " rebase_off " << dc.rebase_off;
8086 if (dc.rebase_off > object_size)
8087 outs() << " (past end of file)\n";
8088 else
8089 outs() << "\n";
8090 outs() << " rebase_size " << dc.rebase_size;
8091 uint64_t big_size;
8092 big_size = dc.rebase_off;
8093 big_size += dc.rebase_size;
8094 if (big_size > object_size)
8095 outs() << " (past end of file)\n";
8096 else
8097 outs() << "\n";
8098 outs() << " bind_off " << dc.bind_off;
8099 if (dc.bind_off > object_size)
8100 outs() << " (past end of file)\n";
8101 else
8102 outs() << "\n";
8103 outs() << " bind_size " << dc.bind_size;
8104 big_size = dc.bind_off;
8105 big_size += dc.bind_size;
8106 if (big_size > object_size)
8107 outs() << " (past end of file)\n";
8108 else
8109 outs() << "\n";
8110 outs() << " weak_bind_off " << dc.weak_bind_off;
8111 if (dc.weak_bind_off > object_size)
8112 outs() << " (past end of file)\n";
8113 else
8114 outs() << "\n";
8115 outs() << " weak_bind_size " << dc.weak_bind_size;
8116 big_size = dc.weak_bind_off;
8117 big_size += dc.weak_bind_size;
8118 if (big_size > object_size)
8119 outs() << " (past end of file)\n";
8120 else
8121 outs() << "\n";
8122 outs() << " lazy_bind_off " << dc.lazy_bind_off;
8123 if (dc.lazy_bind_off > object_size)
8124 outs() << " (past end of file)\n";
8125 else
8126 outs() << "\n";
8127 outs() << " lazy_bind_size " << dc.lazy_bind_size;
8128 big_size = dc.lazy_bind_off;
8129 big_size += dc.lazy_bind_size;
8130 if (big_size > object_size)
8131 outs() << " (past end of file)\n";
8132 else
8133 outs() << "\n";
8134 outs() << " export_off " << dc.export_off;
8135 if (dc.export_off > object_size)
8136 outs() << " (past end of file)\n";
8137 else
8138 outs() << "\n";
8139 outs() << " export_size " << dc.export_size;
8140 big_size = dc.export_off;
8141 big_size += dc.export_size;
8142 if (big_size > object_size)
8143 outs() << " (past end of file)\n";
8144 else
8145 outs() << "\n";
8146}
8147
8148static void PrintDyldLoadCommand(MachO::dylinker_command dyld,
8149 const char *Ptr) {
8150 if (dyld.cmd == MachO::LC_ID_DYLINKER)
8151 outs() << " cmd LC_ID_DYLINKER\n";
8152 else if (dyld.cmd == MachO::LC_LOAD_DYLINKER)
8153 outs() << " cmd LC_LOAD_DYLINKER\n";
8154 else if (dyld.cmd == MachO::LC_DYLD_ENVIRONMENT)
8155 outs() << " cmd LC_DYLD_ENVIRONMENT\n";
8156 else
8157 outs() << " cmd ?(" << dyld.cmd << ")\n";
8158 outs() << " cmdsize " << dyld.cmdsize;
8159 if (dyld.cmdsize < sizeof(struct MachO::dylinker_command))
8160 outs() << " Incorrect size\n";
8161 else
8162 outs() << "\n";
8163 if (dyld.name >= dyld.cmdsize)
8164 outs() << " name ?(bad offset " << dyld.name << ")\n";
8165 else {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00008166 const char *P = (const char *)(Ptr) + dyld.name;
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008167 outs() << " name " << P << " (offset " << dyld.name << ")\n";
8168 }
8169}
8170
8171static void PrintUuidLoadCommand(MachO::uuid_command uuid) {
8172 outs() << " cmd LC_UUID\n";
8173 outs() << " cmdsize " << uuid.cmdsize;
8174 if (uuid.cmdsize != sizeof(struct MachO::uuid_command))
8175 outs() << " Incorrect size\n";
8176 else
8177 outs() << "\n";
8178 outs() << " uuid ";
Davide Italianoc74277a2015-12-07 00:03:28 +00008179 for (int i = 0; i < 16; ++i) {
8180 outs() << format("%02" PRIX32, uuid.uuid[i]);
8181 if (i == 3 || i == 5 || i == 7 || i == 9)
8182 outs() << "-";
8183 }
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008184 outs() << "\n";
8185}
8186
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008187static void PrintRpathLoadCommand(MachO::rpath_command rpath, const char *Ptr) {
Jean-Daniel Dupas00cc1f52014-12-04 07:37:02 +00008188 outs() << " cmd LC_RPATH\n";
8189 outs() << " cmdsize " << rpath.cmdsize;
8190 if (rpath.cmdsize < sizeof(struct MachO::rpath_command))
8191 outs() << " Incorrect size\n";
8192 else
8193 outs() << "\n";
8194 if (rpath.path >= rpath.cmdsize)
8195 outs() << " path ?(bad offset " << rpath.path << ")\n";
8196 else {
8197 const char *P = (const char *)(Ptr) + rpath.path;
8198 outs() << " path " << P << " (offset " << rpath.path << ")\n";
8199 }
8200}
8201
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008202static void PrintVersionMinLoadCommand(MachO::version_min_command vd) {
Tim Northoverbfbfb122015-11-02 21:26:58 +00008203 StringRef LoadCmdName;
8204 switch (vd.cmd) {
8205 case MachO::LC_VERSION_MIN_MACOSX:
8206 LoadCmdName = "LC_VERSION_MIN_MACOSX";
8207 break;
8208 case MachO::LC_VERSION_MIN_IPHONEOS:
8209 LoadCmdName = "LC_VERSION_MIN_IPHONEOS";
8210 break;
8211 case MachO::LC_VERSION_MIN_TVOS:
8212 LoadCmdName = "LC_VERSION_MIN_TVOS";
8213 break;
8214 case MachO::LC_VERSION_MIN_WATCHOS:
8215 LoadCmdName = "LC_VERSION_MIN_WATCHOS";
8216 break;
8217 default:
8218 llvm_unreachable("Unknown version min load command");
8219 }
8220
8221 outs() << " cmd " << LoadCmdName << '\n';
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008222 outs() << " cmdsize " << vd.cmdsize;
8223 if (vd.cmdsize != sizeof(struct MachO::version_min_command))
8224 outs() << " Incorrect size\n";
8225 else
8226 outs() << "\n";
Davide Italiano56baef32015-08-26 12:26:11 +00008227 outs() << " version "
8228 << MachOObjectFile::getVersionMinMajor(vd, false) << "."
8229 << MachOObjectFile::getVersionMinMinor(vd, false);
8230 uint32_t Update = MachOObjectFile::getVersionMinUpdate(vd, false);
8231 if (Update != 0)
8232 outs() << "." << Update;
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008233 outs() << "\n";
8234 if (vd.sdk == 0)
Kevin Enderby57538292014-12-17 01:01:30 +00008235 outs() << " sdk n/a";
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008236 else {
Davide Italiano56baef32015-08-26 12:26:11 +00008237 outs() << " sdk "
8238 << MachOObjectFile::getVersionMinMajor(vd, true) << "."
8239 << MachOObjectFile::getVersionMinMinor(vd, true);
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008240 }
Davide Italiano56baef32015-08-26 12:26:11 +00008241 Update = MachOObjectFile::getVersionMinUpdate(vd, true);
8242 if (Update != 0)
8243 outs() << "." << Update;
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008244 outs() << "\n";
8245}
8246
Kevin Enderbya4579c42017-01-19 17:36:31 +00008247static void PrintNoteLoadCommand(MachO::note_command Nt) {
8248 outs() << " cmd LC_NOTE\n";
8249 outs() << " cmdsize " << Nt.cmdsize;
8250 if (Nt.cmdsize != sizeof(struct MachO::note_command))
8251 outs() << " Incorrect size\n";
8252 else
8253 outs() << "\n";
8254 const char *d = Nt.data_owner;
8255 outs() << "data_owner " << format("%.16s\n", d);
8256 outs() << " offset " << Nt.offset << "\n";
8257 outs() << " size " << Nt.size << "\n";
8258}
8259
Steven Wu5b54a422017-01-23 20:07:55 +00008260static void PrintBuildToolVersion(MachO::build_tool_version bv) {
8261 outs() << " tool " << MachOObjectFile::getBuildTool(bv.tool) << "\n";
8262 outs() << " version " << MachOObjectFile::getVersionString(bv.version)
8263 << "\n";
8264}
8265
8266static void PrintBuildVersionLoadCommand(const MachOObjectFile *obj,
8267 MachO::build_version_command bd) {
8268 outs() << " cmd LC_BUILD_VERSION\n";
8269 outs() << " cmdsize " << bd.cmdsize;
8270 if (bd.cmdsize !=
8271 sizeof(struct MachO::build_version_command) +
8272 bd.ntools * sizeof(struct MachO::build_tool_version))
8273 outs() << " Incorrect size\n";
8274 else
8275 outs() << "\n";
8276 outs() << " platform " << MachOObjectFile::getBuildPlatform(bd.platform)
8277 << "\n";
8278 if (bd.sdk)
8279 outs() << " sdk " << MachOObjectFile::getVersionString(bd.sdk)
8280 << "\n";
8281 else
8282 outs() << " sdk n/a\n";
8283 outs() << " minos " << MachOObjectFile::getVersionString(bd.minos)
8284 << "\n";
8285 outs() << " ntools " << bd.ntools << "\n";
8286 for (unsigned i = 0; i < bd.ntools; ++i) {
8287 MachO::build_tool_version bv = obj->getBuildToolVersion(i);
8288 PrintBuildToolVersion(bv);
8289 }
8290}
8291
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008292static void PrintSourceVersionCommand(MachO::source_version_command sd) {
8293 outs() << " cmd LC_SOURCE_VERSION\n";
8294 outs() << " cmdsize " << sd.cmdsize;
8295 if (sd.cmdsize != sizeof(struct MachO::source_version_command))
8296 outs() << " Incorrect size\n";
8297 else
8298 outs() << "\n";
8299 uint64_t a = (sd.version >> 40) & 0xffffff;
8300 uint64_t b = (sd.version >> 30) & 0x3ff;
8301 uint64_t c = (sd.version >> 20) & 0x3ff;
8302 uint64_t d = (sd.version >> 10) & 0x3ff;
8303 uint64_t e = sd.version & 0x3ff;
8304 outs() << " version " << a << "." << b;
8305 if (e != 0)
8306 outs() << "." << c << "." << d << "." << e;
8307 else if (d != 0)
8308 outs() << "." << c << "." << d;
8309 else if (c != 0)
8310 outs() << "." << c;
8311 outs() << "\n";
8312}
8313
8314static void PrintEntryPointCommand(MachO::entry_point_command ep) {
8315 outs() << " cmd LC_MAIN\n";
8316 outs() << " cmdsize " << ep.cmdsize;
8317 if (ep.cmdsize != sizeof(struct MachO::entry_point_command))
8318 outs() << " Incorrect size\n";
8319 else
8320 outs() << "\n";
8321 outs() << " entryoff " << ep.entryoff << "\n";
8322 outs() << " stacksize " << ep.stacksize << "\n";
8323}
8324
Kevin Enderby0804f4672014-12-16 23:25:52 +00008325static void PrintEncryptionInfoCommand(MachO::encryption_info_command ec,
8326 uint32_t object_size) {
8327 outs() << " cmd LC_ENCRYPTION_INFO\n";
8328 outs() << " cmdsize " << ec.cmdsize;
8329 if (ec.cmdsize != sizeof(struct MachO::encryption_info_command))
8330 outs() << " Incorrect size\n";
8331 else
8332 outs() << "\n";
8333 outs() << " cryptoff " << ec.cryptoff;
8334 if (ec.cryptoff > object_size)
8335 outs() << " (past end of file)\n";
8336 else
8337 outs() << "\n";
8338 outs() << " cryptsize " << ec.cryptsize;
8339 if (ec.cryptsize > object_size)
8340 outs() << " (past end of file)\n";
8341 else
8342 outs() << "\n";
8343 outs() << " cryptid " << ec.cryptid << "\n";
8344}
8345
Kevin Enderby57538292014-12-17 01:01:30 +00008346static void PrintEncryptionInfoCommand64(MachO::encryption_info_command_64 ec,
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008347 uint32_t object_size) {
Kevin Enderby57538292014-12-17 01:01:30 +00008348 outs() << " cmd LC_ENCRYPTION_INFO_64\n";
8349 outs() << " cmdsize " << ec.cmdsize;
8350 if (ec.cmdsize != sizeof(struct MachO::encryption_info_command_64))
8351 outs() << " Incorrect size\n";
8352 else
8353 outs() << "\n";
8354 outs() << " cryptoff " << ec.cryptoff;
8355 if (ec.cryptoff > object_size)
8356 outs() << " (past end of file)\n";
8357 else
8358 outs() << "\n";
8359 outs() << " cryptsize " << ec.cryptsize;
8360 if (ec.cryptsize > object_size)
8361 outs() << " (past end of file)\n";
8362 else
8363 outs() << "\n";
8364 outs() << " cryptid " << ec.cryptid << "\n";
8365 outs() << " pad " << ec.pad << "\n";
8366}
8367
Kevin Enderbyd0b6b7f2014-12-18 00:53:40 +00008368static void PrintLinkerOptionCommand(MachO::linker_option_command lo,
8369 const char *Ptr) {
8370 outs() << " cmd LC_LINKER_OPTION\n";
8371 outs() << " cmdsize " << lo.cmdsize;
8372 if (lo.cmdsize < sizeof(struct MachO::linker_option_command))
8373 outs() << " Incorrect size\n";
8374 else
8375 outs() << "\n";
8376 outs() << " count " << lo.count << "\n";
8377 const char *string = Ptr + sizeof(struct MachO::linker_option_command);
8378 uint32_t left = lo.cmdsize - sizeof(struct MachO::linker_option_command);
8379 uint32_t i = 0;
8380 while (left > 0) {
8381 while (*string == '\0' && left > 0) {
8382 string++;
8383 left--;
8384 }
8385 if (left > 0) {
8386 i++;
8387 outs() << " string #" << i << " " << format("%.*s\n", left, string);
David Majnemerd4449ed2014-12-20 08:24:43 +00008388 uint32_t NullPos = StringRef(string, left).find('\0');
8389 uint32_t len = std::min(NullPos, left) + 1;
Kevin Enderbyd0b6b7f2014-12-18 00:53:40 +00008390 string += len;
8391 left -= len;
8392 }
8393 }
8394 if (lo.count != i)
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008395 outs() << " count " << lo.count << " does not match number of strings "
8396 << i << "\n";
Kevin Enderbyd0b6b7f2014-12-18 00:53:40 +00008397}
8398
Kevin Enderbyb4b79312014-12-18 19:24:35 +00008399static void PrintSubFrameworkCommand(MachO::sub_framework_command sub,
8400 const char *Ptr) {
8401 outs() << " cmd LC_SUB_FRAMEWORK\n";
8402 outs() << " cmdsize " << sub.cmdsize;
8403 if (sub.cmdsize < sizeof(struct MachO::sub_framework_command))
8404 outs() << " Incorrect size\n";
8405 else
8406 outs() << "\n";
8407 if (sub.umbrella < sub.cmdsize) {
8408 const char *P = Ptr + sub.umbrella;
8409 outs() << " umbrella " << P << " (offset " << sub.umbrella << ")\n";
8410 } else {
8411 outs() << " umbrella ?(bad offset " << sub.umbrella << ")\n";
8412 }
8413}
8414
Kevin Enderbya2bd8d92014-12-18 23:13:26 +00008415static void PrintSubUmbrellaCommand(MachO::sub_umbrella_command sub,
8416 const char *Ptr) {
8417 outs() << " cmd LC_SUB_UMBRELLA\n";
8418 outs() << " cmdsize " << sub.cmdsize;
8419 if (sub.cmdsize < sizeof(struct MachO::sub_umbrella_command))
8420 outs() << " Incorrect size\n";
8421 else
8422 outs() << "\n";
8423 if (sub.sub_umbrella < sub.cmdsize) {
8424 const char *P = Ptr + sub.sub_umbrella;
8425 outs() << " sub_umbrella " << P << " (offset " << sub.sub_umbrella << ")\n";
8426 } else {
8427 outs() << " sub_umbrella ?(bad offset " << sub.sub_umbrella << ")\n";
8428 }
8429}
8430
Kevin Enderby36c8d3a2014-12-19 19:48:16 +00008431static void PrintSubLibraryCommand(MachO::sub_library_command sub,
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008432 const char *Ptr) {
Kevin Enderby36c8d3a2014-12-19 19:48:16 +00008433 outs() << " cmd LC_SUB_LIBRARY\n";
8434 outs() << " cmdsize " << sub.cmdsize;
8435 if (sub.cmdsize < sizeof(struct MachO::sub_library_command))
8436 outs() << " Incorrect size\n";
8437 else
8438 outs() << "\n";
8439 if (sub.sub_library < sub.cmdsize) {
8440 const char *P = Ptr + sub.sub_library;
8441 outs() << " sub_library " << P << " (offset " << sub.sub_library << ")\n";
8442 } else {
8443 outs() << " sub_library ?(bad offset " << sub.sub_library << ")\n";
8444 }
8445}
8446
Kevin Enderby186eac32014-12-19 21:06:24 +00008447static void PrintSubClientCommand(MachO::sub_client_command sub,
8448 const char *Ptr) {
8449 outs() << " cmd LC_SUB_CLIENT\n";
8450 outs() << " cmdsize " << sub.cmdsize;
8451 if (sub.cmdsize < sizeof(struct MachO::sub_client_command))
8452 outs() << " Incorrect size\n";
8453 else
8454 outs() << "\n";
8455 if (sub.client < sub.cmdsize) {
8456 const char *P = Ptr + sub.client;
8457 outs() << " client " << P << " (offset " << sub.client << ")\n";
8458 } else {
8459 outs() << " client ?(bad offset " << sub.client << ")\n";
8460 }
8461}
Kevin Enderby36c8d3a2014-12-19 19:48:16 +00008462
Kevin Enderby52e4ce42014-12-19 22:25:22 +00008463static void PrintRoutinesCommand(MachO::routines_command r) {
8464 outs() << " cmd LC_ROUTINES\n";
8465 outs() << " cmdsize " << r.cmdsize;
8466 if (r.cmdsize != sizeof(struct MachO::routines_command))
8467 outs() << " Incorrect size\n";
8468 else
8469 outs() << "\n";
8470 outs() << " init_address " << format("0x%08" PRIx32, r.init_address) << "\n";
8471 outs() << " init_module " << r.init_module << "\n";
8472 outs() << " reserved1 " << r.reserved1 << "\n";
8473 outs() << " reserved2 " << r.reserved2 << "\n";
8474 outs() << " reserved3 " << r.reserved3 << "\n";
8475 outs() << " reserved4 " << r.reserved4 << "\n";
8476 outs() << " reserved5 " << r.reserved5 << "\n";
8477 outs() << " reserved6 " << r.reserved6 << "\n";
8478}
8479
8480static void PrintRoutinesCommand64(MachO::routines_command_64 r) {
8481 outs() << " cmd LC_ROUTINES_64\n";
8482 outs() << " cmdsize " << r.cmdsize;
8483 if (r.cmdsize != sizeof(struct MachO::routines_command_64))
8484 outs() << " Incorrect size\n";
8485 else
8486 outs() << "\n";
8487 outs() << " init_address " << format("0x%016" PRIx64, r.init_address) << "\n";
8488 outs() << " init_module " << r.init_module << "\n";
8489 outs() << " reserved1 " << r.reserved1 << "\n";
8490 outs() << " reserved2 " << r.reserved2 << "\n";
8491 outs() << " reserved3 " << r.reserved3 << "\n";
8492 outs() << " reserved4 " << r.reserved4 << "\n";
8493 outs() << " reserved5 " << r.reserved5 << "\n";
8494 outs() << " reserved6 " << r.reserved6 << "\n";
8495}
8496
Kevin Enderbyc3a035d2017-01-23 21:13:29 +00008497static void Print_x86_thread_state32_t(MachO::x86_thread_state32_t &cpu32) {
8498 outs() << "\t eax " << format("0x%08" PRIx32, cpu32.eax);
8499 outs() << " ebx " << format("0x%08" PRIx32, cpu32.ebx);
8500 outs() << " ecx " << format("0x%08" PRIx32, cpu32.ecx);
8501 outs() << " edx " << format("0x%08" PRIx32, cpu32.edx) << "\n";
8502 outs() << "\t edi " << format("0x%08" PRIx32, cpu32.edi);
8503 outs() << " esi " << format("0x%08" PRIx32, cpu32.esi);
8504 outs() << " ebp " << format("0x%08" PRIx32, cpu32.ebp);
8505 outs() << " esp " << format("0x%08" PRIx32, cpu32.esp) << "\n";
8506 outs() << "\t ss " << format("0x%08" PRIx32, cpu32.ss);
8507 outs() << " eflags " << format("0x%08" PRIx32, cpu32.eflags);
8508 outs() << " eip " << format("0x%08" PRIx32, cpu32.eip);
8509 outs() << " cs " << format("0x%08" PRIx32, cpu32.cs) << "\n";
8510 outs() << "\t ds " << format("0x%08" PRIx32, cpu32.ds);
8511 outs() << " es " << format("0x%08" PRIx32, cpu32.es);
8512 outs() << " fs " << format("0x%08" PRIx32, cpu32.fs);
8513 outs() << " gs " << format("0x%08" PRIx32, cpu32.gs) << "\n";
8514}
8515
Kevin Enderby48ef5342014-12-23 22:56:39 +00008516static void Print_x86_thread_state64_t(MachO::x86_thread_state64_t &cpu64) {
8517 outs() << " rax " << format("0x%016" PRIx64, cpu64.rax);
8518 outs() << " rbx " << format("0x%016" PRIx64, cpu64.rbx);
8519 outs() << " rcx " << format("0x%016" PRIx64, cpu64.rcx) << "\n";
8520 outs() << " rdx " << format("0x%016" PRIx64, cpu64.rdx);
8521 outs() << " rdi " << format("0x%016" PRIx64, cpu64.rdi);
8522 outs() << " rsi " << format("0x%016" PRIx64, cpu64.rsi) << "\n";
8523 outs() << " rbp " << format("0x%016" PRIx64, cpu64.rbp);
8524 outs() << " rsp " << format("0x%016" PRIx64, cpu64.rsp);
8525 outs() << " r8 " << format("0x%016" PRIx64, cpu64.r8) << "\n";
8526 outs() << " r9 " << format("0x%016" PRIx64, cpu64.r9);
8527 outs() << " r10 " << format("0x%016" PRIx64, cpu64.r10);
8528 outs() << " r11 " << format("0x%016" PRIx64, cpu64.r11) << "\n";
8529 outs() << " r12 " << format("0x%016" PRIx64, cpu64.r12);
8530 outs() << " r13 " << format("0x%016" PRIx64, cpu64.r13);
8531 outs() << " r14 " << format("0x%016" PRIx64, cpu64.r14) << "\n";
8532 outs() << " r15 " << format("0x%016" PRIx64, cpu64.r15);
8533 outs() << " rip " << format("0x%016" PRIx64, cpu64.rip) << "\n";
8534 outs() << "rflags " << format("0x%016" PRIx64, cpu64.rflags);
8535 outs() << " cs " << format("0x%016" PRIx64, cpu64.cs);
8536 outs() << " fs " << format("0x%016" PRIx64, cpu64.fs) << "\n";
8537 outs() << " gs " << format("0x%016" PRIx64, cpu64.gs) << "\n";
8538}
8539
Kevin Enderby227df342014-12-23 23:43:59 +00008540static void Print_mmst_reg(MachO::mmst_reg_t &r) {
Kevin Enderby48ef5342014-12-23 22:56:39 +00008541 uint32_t f;
8542 outs() << "\t mmst_reg ";
8543 for (f = 0; f < 10; f++)
8544 outs() << format("%02" PRIx32, (r.mmst_reg[f] & 0xff)) << " ";
8545 outs() << "\n";
8546 outs() << "\t mmst_rsrv ";
8547 for (f = 0; f < 6; f++)
8548 outs() << format("%02" PRIx32, (r.mmst_rsrv[f] & 0xff)) << " ";
8549 outs() << "\n";
8550}
8551
Kevin Enderbyaefb0032014-12-24 00:16:51 +00008552static void Print_xmm_reg(MachO::xmm_reg_t &r) {
Kevin Enderby48ef5342014-12-23 22:56:39 +00008553 uint32_t f;
8554 outs() << "\t xmm_reg ";
8555 for (f = 0; f < 16; f++)
8556 outs() << format("%02" PRIx32, (r.xmm_reg[f] & 0xff)) << " ";
8557 outs() << "\n";
8558}
8559
8560static void Print_x86_float_state_t(MachO::x86_float_state64_t &fpu) {
8561 outs() << "\t fpu_reserved[0] " << fpu.fpu_reserved[0];
8562 outs() << " fpu_reserved[1] " << fpu.fpu_reserved[1] << "\n";
8563 outs() << "\t control: invalid " << fpu.fpu_fcw.invalid;
8564 outs() << " denorm " << fpu.fpu_fcw.denorm;
8565 outs() << " zdiv " << fpu.fpu_fcw.zdiv;
8566 outs() << " ovrfl " << fpu.fpu_fcw.ovrfl;
8567 outs() << " undfl " << fpu.fpu_fcw.undfl;
8568 outs() << " precis " << fpu.fpu_fcw.precis << "\n";
8569 outs() << "\t\t pc ";
8570 if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_24B)
8571 outs() << "FP_PREC_24B ";
8572 else if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_53B)
8573 outs() << "FP_PREC_53B ";
8574 else if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_64B)
8575 outs() << "FP_PREC_64B ";
8576 else
8577 outs() << fpu.fpu_fcw.pc << " ";
8578 outs() << "rc ";
8579 if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_NEAR)
8580 outs() << "FP_RND_NEAR ";
8581 else if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_DOWN)
8582 outs() << "FP_RND_DOWN ";
8583 else if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_UP)
8584 outs() << "FP_RND_UP ";
8585 else if (fpu.fpu_fcw.rc == MachO::x86_FP_CHOP)
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008586 outs() << "FP_CHOP ";
Kevin Enderby48ef5342014-12-23 22:56:39 +00008587 outs() << "\n";
8588 outs() << "\t status: invalid " << fpu.fpu_fsw.invalid;
8589 outs() << " denorm " << fpu.fpu_fsw.denorm;
8590 outs() << " zdiv " << fpu.fpu_fsw.zdiv;
8591 outs() << " ovrfl " << fpu.fpu_fsw.ovrfl;
8592 outs() << " undfl " << fpu.fpu_fsw.undfl;
8593 outs() << " precis " << fpu.fpu_fsw.precis;
8594 outs() << " stkflt " << fpu.fpu_fsw.stkflt << "\n";
8595 outs() << "\t errsumm " << fpu.fpu_fsw.errsumm;
8596 outs() << " c0 " << fpu.fpu_fsw.c0;
8597 outs() << " c1 " << fpu.fpu_fsw.c1;
8598 outs() << " c2 " << fpu.fpu_fsw.c2;
8599 outs() << " tos " << fpu.fpu_fsw.tos;
8600 outs() << " c3 " << fpu.fpu_fsw.c3;
8601 outs() << " busy " << fpu.fpu_fsw.busy << "\n";
8602 outs() << "\t fpu_ftw " << format("0x%02" PRIx32, fpu.fpu_ftw);
8603 outs() << " fpu_rsrv1 " << format("0x%02" PRIx32, fpu.fpu_rsrv1);
8604 outs() << " fpu_fop " << format("0x%04" PRIx32, fpu.fpu_fop);
8605 outs() << " fpu_ip " << format("0x%08" PRIx32, fpu.fpu_ip) << "\n";
8606 outs() << "\t fpu_cs " << format("0x%04" PRIx32, fpu.fpu_cs);
8607 outs() << " fpu_rsrv2 " << format("0x%04" PRIx32, fpu.fpu_rsrv2);
8608 outs() << " fpu_dp " << format("0x%08" PRIx32, fpu.fpu_dp);
8609 outs() << " fpu_ds " << format("0x%04" PRIx32, fpu.fpu_ds) << "\n";
8610 outs() << "\t fpu_rsrv3 " << format("0x%04" PRIx32, fpu.fpu_rsrv3);
8611 outs() << " fpu_mxcsr " << format("0x%08" PRIx32, fpu.fpu_mxcsr);
8612 outs() << " fpu_mxcsrmask " << format("0x%08" PRIx32, fpu.fpu_mxcsrmask);
8613 outs() << "\n";
8614 outs() << "\t fpu_stmm0:\n";
8615 Print_mmst_reg(fpu.fpu_stmm0);
8616 outs() << "\t fpu_stmm1:\n";
8617 Print_mmst_reg(fpu.fpu_stmm1);
8618 outs() << "\t fpu_stmm2:\n";
8619 Print_mmst_reg(fpu.fpu_stmm2);
8620 outs() << "\t fpu_stmm3:\n";
8621 Print_mmst_reg(fpu.fpu_stmm3);
8622 outs() << "\t fpu_stmm4:\n";
8623 Print_mmst_reg(fpu.fpu_stmm4);
8624 outs() << "\t fpu_stmm5:\n";
8625 Print_mmst_reg(fpu.fpu_stmm5);
8626 outs() << "\t fpu_stmm6:\n";
8627 Print_mmst_reg(fpu.fpu_stmm6);
8628 outs() << "\t fpu_stmm7:\n";
8629 Print_mmst_reg(fpu.fpu_stmm7);
8630 outs() << "\t fpu_xmm0:\n";
8631 Print_xmm_reg(fpu.fpu_xmm0);
8632 outs() << "\t fpu_xmm1:\n";
8633 Print_xmm_reg(fpu.fpu_xmm1);
8634 outs() << "\t fpu_xmm2:\n";
8635 Print_xmm_reg(fpu.fpu_xmm2);
8636 outs() << "\t fpu_xmm3:\n";
8637 Print_xmm_reg(fpu.fpu_xmm3);
8638 outs() << "\t fpu_xmm4:\n";
8639 Print_xmm_reg(fpu.fpu_xmm4);
8640 outs() << "\t fpu_xmm5:\n";
8641 Print_xmm_reg(fpu.fpu_xmm5);
8642 outs() << "\t fpu_xmm6:\n";
8643 Print_xmm_reg(fpu.fpu_xmm6);
8644 outs() << "\t fpu_xmm7:\n";
8645 Print_xmm_reg(fpu.fpu_xmm7);
8646 outs() << "\t fpu_xmm8:\n";
8647 Print_xmm_reg(fpu.fpu_xmm8);
8648 outs() << "\t fpu_xmm9:\n";
8649 Print_xmm_reg(fpu.fpu_xmm9);
8650 outs() << "\t fpu_xmm10:\n";
8651 Print_xmm_reg(fpu.fpu_xmm10);
8652 outs() << "\t fpu_xmm11:\n";
8653 Print_xmm_reg(fpu.fpu_xmm11);
8654 outs() << "\t fpu_xmm12:\n";
8655 Print_xmm_reg(fpu.fpu_xmm12);
8656 outs() << "\t fpu_xmm13:\n";
8657 Print_xmm_reg(fpu.fpu_xmm13);
8658 outs() << "\t fpu_xmm14:\n";
8659 Print_xmm_reg(fpu.fpu_xmm14);
8660 outs() << "\t fpu_xmm15:\n";
8661 Print_xmm_reg(fpu.fpu_xmm15);
8662 outs() << "\t fpu_rsrv4:\n";
8663 for (uint32_t f = 0; f < 6; f++) {
8664 outs() << "\t ";
8665 for (uint32_t g = 0; g < 16; g++)
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008666 outs() << format("%02" PRIx32, fpu.fpu_rsrv4[f * g]) << " ";
Kevin Enderby48ef5342014-12-23 22:56:39 +00008667 outs() << "\n";
8668 }
8669 outs() << "\t fpu_reserved1 " << format("0x%08" PRIx32, fpu.fpu_reserved1);
8670 outs() << "\n";
8671}
8672
8673static void Print_x86_exception_state_t(MachO::x86_exception_state64_t &exc64) {
8674 outs() << "\t trapno " << format("0x%08" PRIx32, exc64.trapno);
8675 outs() << " err " << format("0x%08" PRIx32, exc64.err);
8676 outs() << " faultvaddr " << format("0x%016" PRIx64, exc64.faultvaddr) << "\n";
8677}
8678
Kevin Enderby41c9c002016-10-21 18:22:35 +00008679static void Print_arm_thread_state32_t(MachO::arm_thread_state32_t &cpu32) {
8680 outs() << "\t r0 " << format("0x%08" PRIx32, cpu32.r[0]);
8681 outs() << " r1 " << format("0x%08" PRIx32, cpu32.r[1]);
8682 outs() << " r2 " << format("0x%08" PRIx32, cpu32.r[2]);
8683 outs() << " r3 " << format("0x%08" PRIx32, cpu32.r[3]) << "\n";
8684 outs() << "\t r4 " << format("0x%08" PRIx32, cpu32.r[4]);
8685 outs() << " r5 " << format("0x%08" PRIx32, cpu32.r[5]);
8686 outs() << " r6 " << format("0x%08" PRIx32, cpu32.r[6]);
8687 outs() << " r7 " << format("0x%08" PRIx32, cpu32.r[7]) << "\n";
8688 outs() << "\t r8 " << format("0x%08" PRIx32, cpu32.r[8]);
8689 outs() << " r9 " << format("0x%08" PRIx32, cpu32.r[9]);
8690 outs() << " r10 " << format("0x%08" PRIx32, cpu32.r[10]);
8691 outs() << " r11 " << format("0x%08" PRIx32, cpu32.r[11]) << "\n";
8692 outs() << "\t r12 " << format("0x%08" PRIx32, cpu32.r[12]);
8693 outs() << " sp " << format("0x%08" PRIx32, cpu32.sp);
8694 outs() << " lr " << format("0x%08" PRIx32, cpu32.lr);
8695 outs() << " pc " << format("0x%08" PRIx32, cpu32.pc) << "\n";
8696 outs() << "\t cpsr " << format("0x%08" PRIx32, cpu32.cpsr) << "\n";
8697}
8698
Kevin Enderby7747cb52016-11-03 20:51:28 +00008699static void Print_arm_thread_state64_t(MachO::arm_thread_state64_t &cpu64) {
8700 outs() << "\t x0 " << format("0x%016" PRIx64, cpu64.x[0]);
8701 outs() << " x1 " << format("0x%016" PRIx64, cpu64.x[1]);
8702 outs() << " x2 " << format("0x%016" PRIx64, cpu64.x[2]) << "\n";
8703 outs() << "\t x3 " << format("0x%016" PRIx64, cpu64.x[3]);
8704 outs() << " x4 " << format("0x%016" PRIx64, cpu64.x[4]);
8705 outs() << " x5 " << format("0x%016" PRIx64, cpu64.x[5]) << "\n";
8706 outs() << "\t x6 " << format("0x%016" PRIx64, cpu64.x[6]);
8707 outs() << " x7 " << format("0x%016" PRIx64, cpu64.x[7]);
8708 outs() << " x8 " << format("0x%016" PRIx64, cpu64.x[8]) << "\n";
8709 outs() << "\t x9 " << format("0x%016" PRIx64, cpu64.x[9]);
8710 outs() << " x10 " << format("0x%016" PRIx64, cpu64.x[10]);
8711 outs() << " x11 " << format("0x%016" PRIx64, cpu64.x[11]) << "\n";
8712 outs() << "\t x12 " << format("0x%016" PRIx64, cpu64.x[12]);
8713 outs() << " x13 " << format("0x%016" PRIx64, cpu64.x[13]);
8714 outs() << " x14 " << format("0x%016" PRIx64, cpu64.x[14]) << "\n";
8715 outs() << "\t x15 " << format("0x%016" PRIx64, cpu64.x[15]);
8716 outs() << " x16 " << format("0x%016" PRIx64, cpu64.x[16]);
8717 outs() << " x17 " << format("0x%016" PRIx64, cpu64.x[17]) << "\n";
8718 outs() << "\t x18 " << format("0x%016" PRIx64, cpu64.x[18]);
8719 outs() << " x19 " << format("0x%016" PRIx64, cpu64.x[19]);
8720 outs() << " x20 " << format("0x%016" PRIx64, cpu64.x[20]) << "\n";
8721 outs() << "\t x21 " << format("0x%016" PRIx64, cpu64.x[21]);
8722 outs() << " x22 " << format("0x%016" PRIx64, cpu64.x[22]);
8723 outs() << " x23 " << format("0x%016" PRIx64, cpu64.x[23]) << "\n";
8724 outs() << "\t x24 " << format("0x%016" PRIx64, cpu64.x[24]);
8725 outs() << " x25 " << format("0x%016" PRIx64, cpu64.x[25]);
8726 outs() << " x26 " << format("0x%016" PRIx64, cpu64.x[26]) << "\n";
8727 outs() << "\t x27 " << format("0x%016" PRIx64, cpu64.x[27]);
8728 outs() << " x28 " << format("0x%016" PRIx64, cpu64.x[28]);
8729 outs() << " fp " << format("0x%016" PRIx64, cpu64.fp) << "\n";
8730 outs() << "\t lr " << format("0x%016" PRIx64, cpu64.lr);
8731 outs() << " sp " << format("0x%016" PRIx64, cpu64.sp);
8732 outs() << " pc " << format("0x%016" PRIx64, cpu64.pc) << "\n";
8733 outs() << "\t cpsr " << format("0x%08" PRIx32, cpu64.cpsr) << "\n";
8734}
8735
Kevin Enderby48ef5342014-12-23 22:56:39 +00008736static void PrintThreadCommand(MachO::thread_command t, const char *Ptr,
8737 bool isLittleEndian, uint32_t cputype) {
8738 if (t.cmd == MachO::LC_THREAD)
8739 outs() << " cmd LC_THREAD\n";
8740 else if (t.cmd == MachO::LC_UNIXTHREAD)
8741 outs() << " cmd LC_UNIXTHREAD\n";
8742 else
8743 outs() << " cmd " << t.cmd << " (unknown)\n";
8744 outs() << " cmdsize " << t.cmdsize;
8745 if (t.cmdsize < sizeof(struct MachO::thread_command) + 2 * sizeof(uint32_t))
8746 outs() << " Incorrect size\n";
8747 else
8748 outs() << "\n";
8749
8750 const char *begin = Ptr + sizeof(struct MachO::thread_command);
8751 const char *end = Ptr + t.cmdsize;
8752 uint32_t flavor, count, left;
Kevin Enderbyc3a035d2017-01-23 21:13:29 +00008753 if (cputype == MachO::CPU_TYPE_I386) {
8754 while (begin < end) {
8755 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
8756 memcpy((char *)&flavor, begin, sizeof(uint32_t));
8757 begin += sizeof(uint32_t);
8758 } else {
8759 flavor = 0;
8760 begin = end;
8761 }
8762 if (isLittleEndian != sys::IsLittleEndianHost)
8763 sys::swapByteOrder(flavor);
8764 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
8765 memcpy((char *)&count, begin, sizeof(uint32_t));
8766 begin += sizeof(uint32_t);
8767 } else {
8768 count = 0;
8769 begin = end;
8770 }
8771 if (isLittleEndian != sys::IsLittleEndianHost)
8772 sys::swapByteOrder(count);
8773 if (flavor == MachO::x86_THREAD_STATE32) {
8774 outs() << " flavor i386_THREAD_STATE\n";
8775 if (count == MachO::x86_THREAD_STATE32_COUNT)
8776 outs() << " count i386_THREAD_STATE_COUNT\n";
8777 else
8778 outs() << " count " << count
8779 << " (not x86_THREAD_STATE32_COUNT)\n";
8780 MachO::x86_thread_state32_t cpu32;
8781 left = end - begin;
8782 if (left >= sizeof(MachO::x86_thread_state32_t)) {
8783 memcpy(&cpu32, begin, sizeof(MachO::x86_thread_state32_t));
8784 begin += sizeof(MachO::x86_thread_state32_t);
8785 } else {
8786 memset(&cpu32, '\0', sizeof(MachO::x86_thread_state32_t));
8787 memcpy(&cpu32, begin, left);
8788 begin += left;
8789 }
8790 if (isLittleEndian != sys::IsLittleEndianHost)
8791 swapStruct(cpu32);
8792 Print_x86_thread_state32_t(cpu32);
8793 } else if (flavor == MachO::x86_THREAD_STATE) {
8794 outs() << " flavor x86_THREAD_STATE\n";
8795 if (count == MachO::x86_THREAD_STATE_COUNT)
8796 outs() << " count x86_THREAD_STATE_COUNT\n";
8797 else
8798 outs() << " count " << count
8799 << " (not x86_THREAD_STATE_COUNT)\n";
8800 struct MachO::x86_thread_state_t ts;
8801 left = end - begin;
8802 if (left >= sizeof(MachO::x86_thread_state_t)) {
8803 memcpy(&ts, begin, sizeof(MachO::x86_thread_state_t));
8804 begin += sizeof(MachO::x86_thread_state_t);
8805 } else {
8806 memset(&ts, '\0', sizeof(MachO::x86_thread_state_t));
8807 memcpy(&ts, begin, left);
8808 begin += left;
8809 }
8810 if (isLittleEndian != sys::IsLittleEndianHost)
8811 swapStruct(ts);
8812 if (ts.tsh.flavor == MachO::x86_THREAD_STATE32) {
8813 outs() << "\t tsh.flavor x86_THREAD_STATE32 ";
8814 if (ts.tsh.count == MachO::x86_THREAD_STATE32_COUNT)
8815 outs() << "tsh.count x86_THREAD_STATE32_COUNT\n";
8816 else
8817 outs() << "tsh.count " << ts.tsh.count
8818 << " (not x86_THREAD_STATE32_COUNT\n";
8819 Print_x86_thread_state32_t(ts.uts.ts32);
8820 } else {
8821 outs() << "\t tsh.flavor " << ts.tsh.flavor << " tsh.count "
8822 << ts.tsh.count << "\n";
8823 }
8824 } else {
8825 outs() << " flavor " << flavor << " (unknown)\n";
8826 outs() << " count " << count << "\n";
8827 outs() << " state (unknown)\n";
8828 begin += count * sizeof(uint32_t);
8829 }
8830 }
8831 } else if (cputype == MachO::CPU_TYPE_X86_64) {
Kevin Enderby48ef5342014-12-23 22:56:39 +00008832 while (begin < end) {
8833 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
8834 memcpy((char *)&flavor, begin, sizeof(uint32_t));
8835 begin += sizeof(uint32_t);
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008836 } else {
Kevin Enderby48ef5342014-12-23 22:56:39 +00008837 flavor = 0;
8838 begin = end;
8839 }
8840 if (isLittleEndian != sys::IsLittleEndianHost)
8841 sys::swapByteOrder(flavor);
8842 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
8843 memcpy((char *)&count, begin, sizeof(uint32_t));
8844 begin += sizeof(uint32_t);
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008845 } else {
Kevin Enderby48ef5342014-12-23 22:56:39 +00008846 count = 0;
8847 begin = end;
8848 }
8849 if (isLittleEndian != sys::IsLittleEndianHost)
8850 sys::swapByteOrder(count);
8851 if (flavor == MachO::x86_THREAD_STATE64) {
8852 outs() << " flavor x86_THREAD_STATE64\n";
8853 if (count == MachO::x86_THREAD_STATE64_COUNT)
8854 outs() << " count x86_THREAD_STATE64_COUNT\n";
8855 else
8856 outs() << " count " << count
8857 << " (not x86_THREAD_STATE64_COUNT)\n";
8858 MachO::x86_thread_state64_t cpu64;
8859 left = end - begin;
8860 if (left >= sizeof(MachO::x86_thread_state64_t)) {
8861 memcpy(&cpu64, begin, sizeof(MachO::x86_thread_state64_t));
8862 begin += sizeof(MachO::x86_thread_state64_t);
8863 } else {
8864 memset(&cpu64, '\0', sizeof(MachO::x86_thread_state64_t));
8865 memcpy(&cpu64, begin, left);
8866 begin += left;
8867 }
8868 if (isLittleEndian != sys::IsLittleEndianHost)
8869 swapStruct(cpu64);
8870 Print_x86_thread_state64_t(cpu64);
8871 } else if (flavor == MachO::x86_THREAD_STATE) {
8872 outs() << " flavor x86_THREAD_STATE\n";
8873 if (count == MachO::x86_THREAD_STATE_COUNT)
8874 outs() << " count x86_THREAD_STATE_COUNT\n";
8875 else
8876 outs() << " count " << count
8877 << " (not x86_THREAD_STATE_COUNT)\n";
8878 struct MachO::x86_thread_state_t ts;
8879 left = end - begin;
8880 if (left >= sizeof(MachO::x86_thread_state_t)) {
8881 memcpy(&ts, begin, sizeof(MachO::x86_thread_state_t));
8882 begin += sizeof(MachO::x86_thread_state_t);
8883 } else {
8884 memset(&ts, '\0', sizeof(MachO::x86_thread_state_t));
8885 memcpy(&ts, begin, left);
8886 begin += left;
8887 }
8888 if (isLittleEndian != sys::IsLittleEndianHost)
8889 swapStruct(ts);
8890 if (ts.tsh.flavor == MachO::x86_THREAD_STATE64) {
8891 outs() << "\t tsh.flavor x86_THREAD_STATE64 ";
8892 if (ts.tsh.count == MachO::x86_THREAD_STATE64_COUNT)
8893 outs() << "tsh.count x86_THREAD_STATE64_COUNT\n";
8894 else
8895 outs() << "tsh.count " << ts.tsh.count
8896 << " (not x86_THREAD_STATE64_COUNT\n";
8897 Print_x86_thread_state64_t(ts.uts.ts64);
8898 } else {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008899 outs() << "\t tsh.flavor " << ts.tsh.flavor << " tsh.count "
8900 << ts.tsh.count << "\n";
Kevin Enderby48ef5342014-12-23 22:56:39 +00008901 }
8902 } else if (flavor == MachO::x86_FLOAT_STATE) {
8903 outs() << " flavor x86_FLOAT_STATE\n";
8904 if (count == MachO::x86_FLOAT_STATE_COUNT)
8905 outs() << " count x86_FLOAT_STATE_COUNT\n";
8906 else
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008907 outs() << " count " << count << " (not x86_FLOAT_STATE_COUNT)\n";
Kevin Enderby48ef5342014-12-23 22:56:39 +00008908 struct MachO::x86_float_state_t fs;
8909 left = end - begin;
8910 if (left >= sizeof(MachO::x86_float_state_t)) {
8911 memcpy(&fs, begin, sizeof(MachO::x86_float_state_t));
8912 begin += sizeof(MachO::x86_float_state_t);
8913 } else {
8914 memset(&fs, '\0', sizeof(MachO::x86_float_state_t));
8915 memcpy(&fs, begin, left);
8916 begin += left;
8917 }
8918 if (isLittleEndian != sys::IsLittleEndianHost)
8919 swapStruct(fs);
8920 if (fs.fsh.flavor == MachO::x86_FLOAT_STATE64) {
8921 outs() << "\t fsh.flavor x86_FLOAT_STATE64 ";
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008922 if (fs.fsh.count == MachO::x86_FLOAT_STATE64_COUNT)
Kevin Enderby48ef5342014-12-23 22:56:39 +00008923 outs() << "fsh.count x86_FLOAT_STATE64_COUNT\n";
8924 else
8925 outs() << "fsh.count " << fs.fsh.count
8926 << " (not x86_FLOAT_STATE64_COUNT\n";
8927 Print_x86_float_state_t(fs.ufs.fs64);
8928 } else {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008929 outs() << "\t fsh.flavor " << fs.fsh.flavor << " fsh.count "
8930 << fs.fsh.count << "\n";
Kevin Enderby48ef5342014-12-23 22:56:39 +00008931 }
8932 } else if (flavor == MachO::x86_EXCEPTION_STATE) {
8933 outs() << " flavor x86_EXCEPTION_STATE\n";
8934 if (count == MachO::x86_EXCEPTION_STATE_COUNT)
8935 outs() << " count x86_EXCEPTION_STATE_COUNT\n";
8936 else
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008937 outs() << " count " << count
Kevin Enderby48ef5342014-12-23 22:56:39 +00008938 << " (not x86_EXCEPTION_STATE_COUNT)\n";
8939 struct MachO::x86_exception_state_t es;
8940 left = end - begin;
8941 if (left >= sizeof(MachO::x86_exception_state_t)) {
8942 memcpy(&es, begin, sizeof(MachO::x86_exception_state_t));
8943 begin += sizeof(MachO::x86_exception_state_t);
8944 } else {
8945 memset(&es, '\0', sizeof(MachO::x86_exception_state_t));
8946 memcpy(&es, begin, left);
8947 begin += left;
8948 }
8949 if (isLittleEndian != sys::IsLittleEndianHost)
8950 swapStruct(es);
8951 if (es.esh.flavor == MachO::x86_EXCEPTION_STATE64) {
8952 outs() << "\t esh.flavor x86_EXCEPTION_STATE64\n";
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008953 if (es.esh.count == MachO::x86_EXCEPTION_STATE64_COUNT)
Kevin Enderby48ef5342014-12-23 22:56:39 +00008954 outs() << "\t esh.count x86_EXCEPTION_STATE64_COUNT\n";
8955 else
8956 outs() << "\t esh.count " << es.esh.count
8957 << " (not x86_EXCEPTION_STATE64_COUNT\n";
8958 Print_x86_exception_state_t(es.ues.es64);
8959 } else {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008960 outs() << "\t esh.flavor " << es.esh.flavor << " esh.count "
8961 << es.esh.count << "\n";
Kevin Enderby48ef5342014-12-23 22:56:39 +00008962 }
8963 } else {
8964 outs() << " flavor " << flavor << " (unknown)\n";
8965 outs() << " count " << count << "\n";
8966 outs() << " state (unknown)\n";
8967 begin += count * sizeof(uint32_t);
8968 }
8969 }
Kevin Enderby41c9c002016-10-21 18:22:35 +00008970 } else if (cputype == MachO::CPU_TYPE_ARM) {
8971 while (begin < end) {
8972 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
8973 memcpy((char *)&flavor, begin, sizeof(uint32_t));
8974 begin += sizeof(uint32_t);
8975 } else {
8976 flavor = 0;
8977 begin = end;
8978 }
8979 if (isLittleEndian != sys::IsLittleEndianHost)
8980 sys::swapByteOrder(flavor);
8981 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
8982 memcpy((char *)&count, begin, sizeof(uint32_t));
8983 begin += sizeof(uint32_t);
8984 } else {
8985 count = 0;
8986 begin = end;
8987 }
8988 if (isLittleEndian != sys::IsLittleEndianHost)
8989 sys::swapByteOrder(count);
8990 if (flavor == MachO::ARM_THREAD_STATE) {
8991 outs() << " flavor ARM_THREAD_STATE\n";
8992 if (count == MachO::ARM_THREAD_STATE_COUNT)
8993 outs() << " count ARM_THREAD_STATE_COUNT\n";
8994 else
8995 outs() << " count " << count
8996 << " (not ARM_THREAD_STATE_COUNT)\n";
8997 MachO::arm_thread_state32_t cpu32;
8998 left = end - begin;
8999 if (left >= sizeof(MachO::arm_thread_state32_t)) {
9000 memcpy(&cpu32, begin, sizeof(MachO::arm_thread_state32_t));
9001 begin += sizeof(MachO::arm_thread_state32_t);
9002 } else {
9003 memset(&cpu32, '\0', sizeof(MachO::arm_thread_state32_t));
9004 memcpy(&cpu32, begin, left);
9005 begin += left;
9006 }
9007 if (isLittleEndian != sys::IsLittleEndianHost)
9008 swapStruct(cpu32);
9009 Print_arm_thread_state32_t(cpu32);
9010 } else {
9011 outs() << " flavor " << flavor << " (unknown)\n";
9012 outs() << " count " << count << "\n";
9013 outs() << " state (unknown)\n";
9014 begin += count * sizeof(uint32_t);
9015 }
9016 }
Kevin Enderby7747cb52016-11-03 20:51:28 +00009017 } else if (cputype == MachO::CPU_TYPE_ARM64) {
9018 while (begin < end) {
9019 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9020 memcpy((char *)&flavor, begin, sizeof(uint32_t));
9021 begin += sizeof(uint32_t);
9022 } else {
9023 flavor = 0;
9024 begin = end;
9025 }
9026 if (isLittleEndian != sys::IsLittleEndianHost)
9027 sys::swapByteOrder(flavor);
9028 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9029 memcpy((char *)&count, begin, sizeof(uint32_t));
9030 begin += sizeof(uint32_t);
9031 } else {
9032 count = 0;
9033 begin = end;
9034 }
9035 if (isLittleEndian != sys::IsLittleEndianHost)
9036 sys::swapByteOrder(count);
9037 if (flavor == MachO::ARM_THREAD_STATE64) {
9038 outs() << " flavor ARM_THREAD_STATE64\n";
9039 if (count == MachO::ARM_THREAD_STATE64_COUNT)
9040 outs() << " count ARM_THREAD_STATE64_COUNT\n";
9041 else
9042 outs() << " count " << count
9043 << " (not ARM_THREAD_STATE64_COUNT)\n";
9044 MachO::arm_thread_state64_t cpu64;
9045 left = end - begin;
9046 if (left >= sizeof(MachO::arm_thread_state64_t)) {
9047 memcpy(&cpu64, begin, sizeof(MachO::arm_thread_state64_t));
9048 begin += sizeof(MachO::arm_thread_state64_t);
9049 } else {
9050 memset(&cpu64, '\0', sizeof(MachO::arm_thread_state64_t));
9051 memcpy(&cpu64, begin, left);
9052 begin += left;
9053 }
9054 if (isLittleEndian != sys::IsLittleEndianHost)
9055 swapStruct(cpu64);
9056 Print_arm_thread_state64_t(cpu64);
9057 } else {
9058 outs() << " flavor " << flavor << " (unknown)\n";
9059 outs() << " count " << count << "\n";
9060 outs() << " state (unknown)\n";
9061 begin += count * sizeof(uint32_t);
9062 }
9063 }
Kevin Enderby48ef5342014-12-23 22:56:39 +00009064 } else {
9065 while (begin < end) {
9066 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9067 memcpy((char *)&flavor, begin, sizeof(uint32_t));
9068 begin += sizeof(uint32_t);
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009069 } else {
Kevin Enderby48ef5342014-12-23 22:56:39 +00009070 flavor = 0;
9071 begin = end;
9072 }
9073 if (isLittleEndian != sys::IsLittleEndianHost)
9074 sys::swapByteOrder(flavor);
9075 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9076 memcpy((char *)&count, begin, sizeof(uint32_t));
9077 begin += sizeof(uint32_t);
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009078 } else {
Kevin Enderby48ef5342014-12-23 22:56:39 +00009079 count = 0;
9080 begin = end;
9081 }
9082 if (isLittleEndian != sys::IsLittleEndianHost)
9083 sys::swapByteOrder(count);
9084 outs() << " flavor " << flavor << "\n";
9085 outs() << " count " << count << "\n";
9086 outs() << " state (Unknown cputype/cpusubtype)\n";
9087 begin += count * sizeof(uint32_t);
9088 }
9089 }
9090}
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009091
Kevin Enderby8ae63c12014-09-04 16:54:47 +00009092static void PrintDylibCommand(MachO::dylib_command dl, const char *Ptr) {
9093 if (dl.cmd == MachO::LC_ID_DYLIB)
9094 outs() << " cmd LC_ID_DYLIB\n";
9095 else if (dl.cmd == MachO::LC_LOAD_DYLIB)
9096 outs() << " cmd LC_LOAD_DYLIB\n";
9097 else if (dl.cmd == MachO::LC_LOAD_WEAK_DYLIB)
9098 outs() << " cmd LC_LOAD_WEAK_DYLIB\n";
9099 else if (dl.cmd == MachO::LC_REEXPORT_DYLIB)
9100 outs() << " cmd LC_REEXPORT_DYLIB\n";
9101 else if (dl.cmd == MachO::LC_LAZY_LOAD_DYLIB)
9102 outs() << " cmd LC_LAZY_LOAD_DYLIB\n";
9103 else if (dl.cmd == MachO::LC_LOAD_UPWARD_DYLIB)
9104 outs() << " cmd LC_LOAD_UPWARD_DYLIB\n";
9105 else
9106 outs() << " cmd " << dl.cmd << " (unknown)\n";
9107 outs() << " cmdsize " << dl.cmdsize;
9108 if (dl.cmdsize < sizeof(struct MachO::dylib_command))
9109 outs() << " Incorrect size\n";
9110 else
9111 outs() << "\n";
9112 if (dl.dylib.name < dl.cmdsize) {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00009113 const char *P = (const char *)(Ptr) + dl.dylib.name;
Kevin Enderby8ae63c12014-09-04 16:54:47 +00009114 outs() << " name " << P << " (offset " << dl.dylib.name << ")\n";
9115 } else {
9116 outs() << " name ?(bad offset " << dl.dylib.name << ")\n";
9117 }
9118 outs() << " time stamp " << dl.dylib.timestamp << " ";
9119 time_t t = dl.dylib.timestamp;
9120 outs() << ctime(&t);
9121 outs() << " current version ";
9122 if (dl.dylib.current_version == 0xffffffff)
9123 outs() << "n/a\n";
9124 else
9125 outs() << ((dl.dylib.current_version >> 16) & 0xffff) << "."
9126 << ((dl.dylib.current_version >> 8) & 0xff) << "."
9127 << (dl.dylib.current_version & 0xff) << "\n";
9128 outs() << "compatibility version ";
9129 if (dl.dylib.compatibility_version == 0xffffffff)
9130 outs() << "n/a\n";
9131 else
9132 outs() << ((dl.dylib.compatibility_version >> 16) & 0xffff) << "."
9133 << ((dl.dylib.compatibility_version >> 8) & 0xff) << "."
9134 << (dl.dylib.compatibility_version & 0xff) << "\n";
9135}
9136
9137static void PrintLinkEditDataCommand(MachO::linkedit_data_command ld,
9138 uint32_t object_size) {
9139 if (ld.cmd == MachO::LC_CODE_SIGNATURE)
Kevin Enderby1be37a32016-04-28 21:07:20 +00009140 outs() << " cmd LC_CODE_SIGNATURE\n";
Kevin Enderby8ae63c12014-09-04 16:54:47 +00009141 else if (ld.cmd == MachO::LC_SEGMENT_SPLIT_INFO)
9142 outs() << " cmd LC_SEGMENT_SPLIT_INFO\n";
9143 else if (ld.cmd == MachO::LC_FUNCTION_STARTS)
9144 outs() << " cmd LC_FUNCTION_STARTS\n";
9145 else if (ld.cmd == MachO::LC_DATA_IN_CODE)
9146 outs() << " cmd LC_DATA_IN_CODE\n";
9147 else if (ld.cmd == MachO::LC_DYLIB_CODE_SIGN_DRS)
9148 outs() << " cmd LC_DYLIB_CODE_SIGN_DRS\n";
9149 else if (ld.cmd == MachO::LC_LINKER_OPTIMIZATION_HINT)
9150 outs() << " cmd LC_LINKER_OPTIMIZATION_HINT\n";
9151 else
9152 outs() << " cmd " << ld.cmd << " (?)\n";
9153 outs() << " cmdsize " << ld.cmdsize;
9154 if (ld.cmdsize != sizeof(struct MachO::linkedit_data_command))
9155 outs() << " Incorrect size\n";
9156 else
9157 outs() << "\n";
9158 outs() << " dataoff " << ld.dataoff;
9159 if (ld.dataoff > object_size)
9160 outs() << " (past end of file)\n";
9161 else
9162 outs() << "\n";
9163 outs() << " datasize " << ld.datasize;
9164 uint64_t big_size = ld.dataoff;
9165 big_size += ld.datasize;
9166 if (big_size > object_size)
9167 outs() << " (past end of file)\n";
9168 else
9169 outs() << "\n";
9170}
9171
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00009172static void PrintLoadCommands(const MachOObjectFile *Obj, uint32_t filetype,
9173 uint32_t cputype, bool verbose) {
Kevin Enderby956366c2014-08-29 22:30:52 +00009174 StringRef Buf = Obj->getData();
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00009175 unsigned Index = 0;
9176 for (const auto &Command : Obj->load_commands()) {
9177 outs() << "Load command " << Index++ << "\n";
Kevin Enderby956366c2014-08-29 22:30:52 +00009178 if (Command.C.cmd == MachO::LC_SEGMENT) {
9179 MachO::segment_command SLC = Obj->getSegmentLoadCommand(Command);
9180 const char *sg_segname = SLC.segname;
9181 PrintSegmentCommand(SLC.cmd, SLC.cmdsize, SLC.segname, SLC.vmaddr,
9182 SLC.vmsize, SLC.fileoff, SLC.filesize, SLC.maxprot,
9183 SLC.initprot, SLC.nsects, SLC.flags, Buf.size(),
9184 verbose);
9185 for (unsigned j = 0; j < SLC.nsects; j++) {
Kevin Enderbyc9713382014-12-16 01:14:45 +00009186 MachO::section S = Obj->getSection(Command, j);
Kevin Enderby956366c2014-08-29 22:30:52 +00009187 PrintSection(S.sectname, S.segname, S.addr, S.size, S.offset, S.align,
9188 S.reloff, S.nreloc, S.flags, S.reserved1, S.reserved2,
9189 SLC.cmd, sg_segname, filetype, Buf.size(), verbose);
9190 }
9191 } else if (Command.C.cmd == MachO::LC_SEGMENT_64) {
9192 MachO::segment_command_64 SLC_64 = Obj->getSegment64LoadCommand(Command);
9193 const char *sg_segname = SLC_64.segname;
9194 PrintSegmentCommand(SLC_64.cmd, SLC_64.cmdsize, SLC_64.segname,
9195 SLC_64.vmaddr, SLC_64.vmsize, SLC_64.fileoff,
9196 SLC_64.filesize, SLC_64.maxprot, SLC_64.initprot,
9197 SLC_64.nsects, SLC_64.flags, Buf.size(), verbose);
9198 for (unsigned j = 0; j < SLC_64.nsects; j++) {
9199 MachO::section_64 S_64 = Obj->getSection64(Command, j);
9200 PrintSection(S_64.sectname, S_64.segname, S_64.addr, S_64.size,
9201 S_64.offset, S_64.align, S_64.reloff, S_64.nreloc,
9202 S_64.flags, S_64.reserved1, S_64.reserved2, SLC_64.cmd,
9203 sg_segname, filetype, Buf.size(), verbose);
9204 }
9205 } else if (Command.C.cmd == MachO::LC_SYMTAB) {
9206 MachO::symtab_command Symtab = Obj->getSymtabLoadCommand();
David Majnemer73cc6ff2014-11-13 19:48:56 +00009207 PrintSymtabLoadCommand(Symtab, Obj->is64Bit(), Buf.size());
Kevin Enderby956366c2014-08-29 22:30:52 +00009208 } else if (Command.C.cmd == MachO::LC_DYSYMTAB) {
9209 MachO::dysymtab_command Dysymtab = Obj->getDysymtabLoadCommand();
9210 MachO::symtab_command Symtab = Obj->getSymtabLoadCommand();
David Majnemer73cc6ff2014-11-13 19:48:56 +00009211 PrintDysymtabLoadCommand(Dysymtab, Symtab.nsyms, Buf.size(),
9212 Obj->is64Bit());
Kevin Enderby8ae63c12014-09-04 16:54:47 +00009213 } else if (Command.C.cmd == MachO::LC_DYLD_INFO ||
9214 Command.C.cmd == MachO::LC_DYLD_INFO_ONLY) {
9215 MachO::dyld_info_command DyldInfo = Obj->getDyldInfoLoadCommand(Command);
9216 PrintDyldInfoLoadCommand(DyldInfo, Buf.size());
9217 } else if (Command.C.cmd == MachO::LC_LOAD_DYLINKER ||
9218 Command.C.cmd == MachO::LC_ID_DYLINKER ||
9219 Command.C.cmd == MachO::LC_DYLD_ENVIRONMENT) {
9220 MachO::dylinker_command Dyld = Obj->getDylinkerCommand(Command);
9221 PrintDyldLoadCommand(Dyld, Command.Ptr);
9222 } else if (Command.C.cmd == MachO::LC_UUID) {
9223 MachO::uuid_command Uuid = Obj->getUuidCommand(Command);
9224 PrintUuidLoadCommand(Uuid);
Jean-Daniel Dupas00cc1f52014-12-04 07:37:02 +00009225 } else if (Command.C.cmd == MachO::LC_RPATH) {
9226 MachO::rpath_command Rpath = Obj->getRpathCommand(Command);
9227 PrintRpathLoadCommand(Rpath, Command.Ptr);
Kevin Enderby1ff0ecc2014-12-16 21:48:27 +00009228 } else if (Command.C.cmd == MachO::LC_VERSION_MIN_MACOSX ||
Tim Northoverbfbfb122015-11-02 21:26:58 +00009229 Command.C.cmd == MachO::LC_VERSION_MIN_IPHONEOS ||
9230 Command.C.cmd == MachO::LC_VERSION_MIN_TVOS ||
9231 Command.C.cmd == MachO::LC_VERSION_MIN_WATCHOS) {
Kevin Enderby8ae63c12014-09-04 16:54:47 +00009232 MachO::version_min_command Vd = Obj->getVersionMinLoadCommand(Command);
9233 PrintVersionMinLoadCommand(Vd);
Kevin Enderbya4579c42017-01-19 17:36:31 +00009234 } else if (Command.C.cmd == MachO::LC_NOTE) {
9235 MachO::note_command Nt = Obj->getNoteLoadCommand(Command);
9236 PrintNoteLoadCommand(Nt);
Steven Wu5b54a422017-01-23 20:07:55 +00009237 } else if (Command.C.cmd == MachO::LC_BUILD_VERSION) {
9238 MachO::build_version_command Bv =
9239 Obj->getBuildVersionLoadCommand(Command);
9240 PrintBuildVersionLoadCommand(Obj, Bv);
Kevin Enderby8ae63c12014-09-04 16:54:47 +00009241 } else if (Command.C.cmd == MachO::LC_SOURCE_VERSION) {
9242 MachO::source_version_command Sd = Obj->getSourceVersionCommand(Command);
9243 PrintSourceVersionCommand(Sd);
9244 } else if (Command.C.cmd == MachO::LC_MAIN) {
9245 MachO::entry_point_command Ep = Obj->getEntryPointCommand(Command);
9246 PrintEntryPointCommand(Ep);
Kevin Enderby0804f4672014-12-16 23:25:52 +00009247 } else if (Command.C.cmd == MachO::LC_ENCRYPTION_INFO) {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009248 MachO::encryption_info_command Ei =
9249 Obj->getEncryptionInfoCommand(Command);
Kevin Enderby0804f4672014-12-16 23:25:52 +00009250 PrintEncryptionInfoCommand(Ei, Buf.size());
Kevin Enderby57538292014-12-17 01:01:30 +00009251 } else if (Command.C.cmd == MachO::LC_ENCRYPTION_INFO_64) {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009252 MachO::encryption_info_command_64 Ei =
9253 Obj->getEncryptionInfoCommand64(Command);
Kevin Enderby57538292014-12-17 01:01:30 +00009254 PrintEncryptionInfoCommand64(Ei, Buf.size());
Kevin Enderbyd0b6b7f2014-12-18 00:53:40 +00009255 } else if (Command.C.cmd == MachO::LC_LINKER_OPTION) {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009256 MachO::linker_option_command Lo =
9257 Obj->getLinkerOptionLoadCommand(Command);
Kevin Enderbyd0b6b7f2014-12-18 00:53:40 +00009258 PrintLinkerOptionCommand(Lo, Command.Ptr);
Kevin Enderbyb4b79312014-12-18 19:24:35 +00009259 } else if (Command.C.cmd == MachO::LC_SUB_FRAMEWORK) {
9260 MachO::sub_framework_command Sf = Obj->getSubFrameworkCommand(Command);
9261 PrintSubFrameworkCommand(Sf, Command.Ptr);
Kevin Enderbya2bd8d92014-12-18 23:13:26 +00009262 } else if (Command.C.cmd == MachO::LC_SUB_UMBRELLA) {
9263 MachO::sub_umbrella_command Sf = Obj->getSubUmbrellaCommand(Command);
9264 PrintSubUmbrellaCommand(Sf, Command.Ptr);
Kevin Enderby36c8d3a2014-12-19 19:48:16 +00009265 } else if (Command.C.cmd == MachO::LC_SUB_LIBRARY) {
9266 MachO::sub_library_command Sl = Obj->getSubLibraryCommand(Command);
9267 PrintSubLibraryCommand(Sl, Command.Ptr);
Kevin Enderby186eac32014-12-19 21:06:24 +00009268 } else if (Command.C.cmd == MachO::LC_SUB_CLIENT) {
9269 MachO::sub_client_command Sc = Obj->getSubClientCommand(Command);
9270 PrintSubClientCommand(Sc, Command.Ptr);
Kevin Enderby52e4ce42014-12-19 22:25:22 +00009271 } else if (Command.C.cmd == MachO::LC_ROUTINES) {
9272 MachO::routines_command Rc = Obj->getRoutinesCommand(Command);
9273 PrintRoutinesCommand(Rc);
9274 } else if (Command.C.cmd == MachO::LC_ROUTINES_64) {
9275 MachO::routines_command_64 Rc = Obj->getRoutinesCommand64(Command);
9276 PrintRoutinesCommand64(Rc);
Kevin Enderby48ef5342014-12-23 22:56:39 +00009277 } else if (Command.C.cmd == MachO::LC_THREAD ||
9278 Command.C.cmd == MachO::LC_UNIXTHREAD) {
9279 MachO::thread_command Tc = Obj->getThreadCommand(Command);
9280 PrintThreadCommand(Tc, Command.Ptr, Obj->isLittleEndian(), cputype);
Nick Kledzik15558912014-10-16 18:58:20 +00009281 } else if (Command.C.cmd == MachO::LC_LOAD_DYLIB ||
9282 Command.C.cmd == MachO::LC_ID_DYLIB ||
9283 Command.C.cmd == MachO::LC_LOAD_WEAK_DYLIB ||
9284 Command.C.cmd == MachO::LC_REEXPORT_DYLIB ||
9285 Command.C.cmd == MachO::LC_LAZY_LOAD_DYLIB ||
9286 Command.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB) {
Kevin Enderby8ae63c12014-09-04 16:54:47 +00009287 MachO::dylib_command Dl = Obj->getDylibIDLoadCommand(Command);
9288 PrintDylibCommand(Dl, Command.Ptr);
9289 } else if (Command.C.cmd == MachO::LC_CODE_SIGNATURE ||
9290 Command.C.cmd == MachO::LC_SEGMENT_SPLIT_INFO ||
9291 Command.C.cmd == MachO::LC_FUNCTION_STARTS ||
9292 Command.C.cmd == MachO::LC_DATA_IN_CODE ||
9293 Command.C.cmd == MachO::LC_DYLIB_CODE_SIGN_DRS ||
9294 Command.C.cmd == MachO::LC_LINKER_OPTIMIZATION_HINT) {
9295 MachO::linkedit_data_command Ld =
9296 Obj->getLinkeditDataLoadCommand(Command);
9297 PrintLinkEditDataCommand(Ld, Buf.size());
Kevin Enderby956366c2014-08-29 22:30:52 +00009298 } else {
9299 outs() << " cmd ?(" << format("0x%08" PRIx32, Command.C.cmd)
9300 << ")\n";
9301 outs() << " cmdsize " << Command.C.cmdsize << "\n";
9302 // TODO: get and print the raw bytes of the load command.
9303 }
9304 // TODO: print all the other kinds of load commands.
Kevin Enderby956366c2014-08-29 22:30:52 +00009305 }
9306}
9307
Kevin Enderby0ae163f2016-01-13 00:25:36 +00009308static void PrintMachHeader(const MachOObjectFile *Obj, bool verbose) {
Kevin Enderbyb76d3862014-08-22 20:35:18 +00009309 if (Obj->is64Bit()) {
9310 MachO::mach_header_64 H_64;
9311 H_64 = Obj->getHeader64();
9312 PrintMachHeader(H_64.magic, H_64.cputype, H_64.cpusubtype, H_64.filetype,
9313 H_64.ncmds, H_64.sizeofcmds, H_64.flags, verbose);
9314 } else {
9315 MachO::mach_header H;
9316 H = Obj->getHeader();
9317 PrintMachHeader(H.magic, H.cputype, H.cpusubtype, H.filetype, H.ncmds,
9318 H.sizeofcmds, H.flags, verbose);
9319 }
9320}
9321
9322void llvm::printMachOFileHeader(const object::ObjectFile *Obj) {
9323 const MachOObjectFile *file = dyn_cast<const MachOObjectFile>(Obj);
Kevin Enderby0ae163f2016-01-13 00:25:36 +00009324 PrintMachHeader(file, !NonVerbose);
9325}
9326
9327void llvm::printMachOLoadCommands(const object::ObjectFile *Obj) {
9328 const MachOObjectFile *file = dyn_cast<const MachOObjectFile>(Obj);
Kevin Enderby956366c2014-08-29 22:30:52 +00009329 uint32_t filetype = 0;
9330 uint32_t cputype = 0;
Kevin Enderby0ae163f2016-01-13 00:25:36 +00009331 if (file->is64Bit()) {
9332 MachO::mach_header_64 H_64;
9333 H_64 = file->getHeader64();
9334 filetype = H_64.filetype;
9335 cputype = H_64.cputype;
9336 } else {
9337 MachO::mach_header H;
9338 H = file->getHeader();
9339 filetype = H.filetype;
9340 cputype = H.cputype;
9341 }
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00009342 PrintLoadCommands(file, filetype, cputype, !NonVerbose);
Kevin Enderbyb76d3862014-08-22 20:35:18 +00009343}
Nick Kledzikd04bc352014-08-30 00:20:14 +00009344
9345//===----------------------------------------------------------------------===//
9346// export trie dumping
9347//===----------------------------------------------------------------------===//
9348
9349void llvm::printMachOExportsTrie(const object::MachOObjectFile *Obj) {
Kevin Enderby0d5ec112017-06-19 21:23:07 +00009350 uint64_t BaseSegmentAddress = 0;
9351 for (const auto &Command : Obj->load_commands()) {
9352 if (Command.C.cmd == MachO::LC_SEGMENT) {
9353 MachO::segment_command Seg = Obj->getSegmentLoadCommand(Command);
9354 if (Seg.fileoff == 0 && Seg.filesize != 0) {
9355 BaseSegmentAddress = Seg.vmaddr;
9356 break;
9357 }
9358 } else if (Command.C.cmd == MachO::LC_SEGMENT_64) {
9359 MachO::segment_command_64 Seg = Obj->getSegment64LoadCommand(Command);
9360 if (Seg.fileoff == 0 && Seg.filesize != 0) {
9361 BaseSegmentAddress = Seg.vmaddr;
9362 break;
9363 }
9364 }
9365 }
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00009366 for (const llvm::object::ExportEntry &Entry : Obj->exports()) {
9367 uint64_t Flags = Entry.flags();
Nick Kledzikd04bc352014-08-30 00:20:14 +00009368 bool ReExport = (Flags & MachO::EXPORT_SYMBOL_FLAGS_REEXPORT);
9369 bool WeakDef = (Flags & MachO::EXPORT_SYMBOL_FLAGS_WEAK_DEFINITION);
9370 bool ThreadLocal = ((Flags & MachO::EXPORT_SYMBOL_FLAGS_KIND_MASK) ==
9371 MachO::EXPORT_SYMBOL_FLAGS_KIND_THREAD_LOCAL);
9372 bool Abs = ((Flags & MachO::EXPORT_SYMBOL_FLAGS_KIND_MASK) ==
9373 MachO::EXPORT_SYMBOL_FLAGS_KIND_ABSOLUTE);
9374 bool Resolver = (Flags & MachO::EXPORT_SYMBOL_FLAGS_STUB_AND_RESOLVER);
9375 if (ReExport)
9376 outs() << "[re-export] ";
9377 else
Kevin Enderbyb28ed012014-10-29 21:28:24 +00009378 outs() << format("0x%08llX ",
Kevin Enderby0d5ec112017-06-19 21:23:07 +00009379 Entry.address() + BaseSegmentAddress);
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00009380 outs() << Entry.name();
Nick Kledzikd04bc352014-08-30 00:20:14 +00009381 if (WeakDef || ThreadLocal || Resolver || Abs) {
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00009382 bool NeedsComma = false;
Nick Kledzik1d1ac4b2014-09-03 01:12:52 +00009383 outs() << " [";
Nick Kledzikd04bc352014-08-30 00:20:14 +00009384 if (WeakDef) {
9385 outs() << "weak_def";
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00009386 NeedsComma = true;
Nick Kledzikd04bc352014-08-30 00:20:14 +00009387 }
9388 if (ThreadLocal) {
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00009389 if (NeedsComma)
Nick Kledzikd04bc352014-08-30 00:20:14 +00009390 outs() << ", ";
9391 outs() << "per-thread";
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00009392 NeedsComma = true;
Nick Kledzikd04bc352014-08-30 00:20:14 +00009393 }
9394 if (Abs) {
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00009395 if (NeedsComma)
Nick Kledzikd04bc352014-08-30 00:20:14 +00009396 outs() << ", ";
9397 outs() << "absolute";
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00009398 NeedsComma = true;
Nick Kledzikd04bc352014-08-30 00:20:14 +00009399 }
9400 if (Resolver) {
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00009401 if (NeedsComma)
Nick Kledzikd04bc352014-08-30 00:20:14 +00009402 outs() << ", ";
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00009403 outs() << format("resolver=0x%08llX", Entry.other());
9404 NeedsComma = true;
Nick Kledzikd04bc352014-08-30 00:20:14 +00009405 }
9406 outs() << "]";
9407 }
9408 if (ReExport) {
9409 StringRef DylibName = "unknown";
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00009410 int Ordinal = Entry.other() - 1;
9411 Obj->getLibraryShortNameByIndex(Ordinal, DylibName);
9412 if (Entry.otherName().empty())
Nick Kledzikd04bc352014-08-30 00:20:14 +00009413 outs() << " (from " << DylibName << ")";
9414 else
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00009415 outs() << " (" << Entry.otherName() << " from " << DylibName << ")";
Nick Kledzikd04bc352014-08-30 00:20:14 +00009416 }
9417 outs() << "\n";
9418 }
9419}
Nick Kledzikac431442014-09-12 21:34:15 +00009420
Nick Kledzikac431442014-09-12 21:34:15 +00009421//===----------------------------------------------------------------------===//
9422// rebase table dumping
9423//===----------------------------------------------------------------------===//
9424
Kevin Enderbya8d256c2017-03-20 19:46:55 +00009425void llvm::printMachORebaseTable(object::MachOObjectFile *Obj) {
Nick Kledzikac431442014-09-12 21:34:15 +00009426 outs() << "segment section address type\n";
Kevin Enderbya8d256c2017-03-20 19:46:55 +00009427 Error Err = Error::success();
9428 for (const llvm::object::MachORebaseEntry &Entry : Obj->rebaseTable(Err)) {
9429 StringRef SegmentName = Entry.segmentName();
9430 StringRef SectionName = Entry.sectionName();
9431 uint64_t Address = Entry.address();
Nick Kledzikac431442014-09-12 21:34:15 +00009432
9433 // Table lines look like: __DATA __nl_symbol_ptr 0x0000F00C pointer
Kevin Enderbyb28ed012014-10-29 21:28:24 +00009434 outs() << format("%-8s %-18s 0x%08" PRIX64 " %s\n",
9435 SegmentName.str().c_str(), SectionName.str().c_str(),
9436 Address, Entry.typeName().str().c_str());
Nick Kledzikac431442014-09-12 21:34:15 +00009437 }
Kevin Enderbya8d256c2017-03-20 19:46:55 +00009438 if (Err)
9439 report_error(Obj->getFileName(), std::move(Err));
Nick Kledzikac431442014-09-12 21:34:15 +00009440}
Nick Kledzik56ebef42014-09-16 01:41:51 +00009441
9442static StringRef ordinalName(const object::MachOObjectFile *Obj, int Ordinal) {
9443 StringRef DylibName;
9444 switch (Ordinal) {
9445 case MachO::BIND_SPECIAL_DYLIB_SELF:
9446 return "this-image";
9447 case MachO::BIND_SPECIAL_DYLIB_MAIN_EXECUTABLE:
9448 return "main-executable";
9449 case MachO::BIND_SPECIAL_DYLIB_FLAT_LOOKUP:
9450 return "flat-namespace";
9451 default:
Nick Kledzikabd29872014-09-16 22:03:13 +00009452 if (Ordinal > 0) {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00009453 std::error_code EC =
9454 Obj->getLibraryShortNameByIndex(Ordinal - 1, DylibName);
Nick Kledzikabd29872014-09-16 22:03:13 +00009455 if (EC)
Nick Kledzik51d2c2b2014-10-14 23:29:38 +00009456 return "<<bad library ordinal>>";
Nick Kledzikabd29872014-09-16 22:03:13 +00009457 return DylibName;
9458 }
Nick Kledzik56ebef42014-09-16 01:41:51 +00009459 }
Nick Kledzikabd29872014-09-16 22:03:13 +00009460 return "<<unknown special ordinal>>";
Nick Kledzik56ebef42014-09-16 01:41:51 +00009461}
9462
9463//===----------------------------------------------------------------------===//
9464// bind table dumping
9465//===----------------------------------------------------------------------===//
9466
Kevin Enderbya8d256c2017-03-20 19:46:55 +00009467void llvm::printMachOBindTable(object::MachOObjectFile *Obj) {
Nick Kledzik56ebef42014-09-16 01:41:51 +00009468 // Build table of sections so names can used in final output.
Nick Kledzik5ffacc12014-09-30 00:19:58 +00009469 outs() << "segment section address type "
9470 "addend dylib symbol\n";
Kevin Enderbyfeb63b92017-02-28 21:47:07 +00009471 Error Err = Error::success();
9472 for (const llvm::object::MachOBindEntry &Entry : Obj->bindTable(Err)) {
Kevin Enderbya8d256c2017-03-20 19:46:55 +00009473 StringRef SegmentName = Entry.segmentName();
9474 StringRef SectionName = Entry.sectionName();
9475 uint64_t Address = Entry.address();
Nick Kledzik56ebef42014-09-16 01:41:51 +00009476
9477 // Table lines look like:
9478 // __DATA __got 0x00012010 pointer 0 libSystem ___stack_chk_guard
Nick Kledzik5ffacc12014-09-30 00:19:58 +00009479 StringRef Attr;
Nick Kledzik56ebef42014-09-16 01:41:51 +00009480 if (Entry.flags() & MachO::BIND_SYMBOL_FLAGS_WEAK_IMPORT)
Nick Kledzik5ffacc12014-09-30 00:19:58 +00009481 Attr = " (weak_import)";
Kevin Enderbyb28ed012014-10-29 21:28:24 +00009482 outs() << left_justify(SegmentName, 8) << " "
Nick Kledzik5ffacc12014-09-30 00:19:58 +00009483 << left_justify(SectionName, 18) << " "
9484 << format_hex(Address, 10, true) << " "
9485 << left_justify(Entry.typeName(), 8) << " "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00009486 << format_decimal(Entry.addend(), 8) << " "
Nick Kledzik5ffacc12014-09-30 00:19:58 +00009487 << left_justify(ordinalName(Obj, Entry.ordinal()), 16) << " "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00009488 << Entry.symbolName() << Attr << "\n";
Nick Kledzik56ebef42014-09-16 01:41:51 +00009489 }
Kevin Enderbyfeb63b92017-02-28 21:47:07 +00009490 if (Err)
9491 report_error(Obj->getFileName(), std::move(Err));
Nick Kledzik56ebef42014-09-16 01:41:51 +00009492}
9493
9494//===----------------------------------------------------------------------===//
9495// lazy bind table dumping
9496//===----------------------------------------------------------------------===//
9497
Kevin Enderbya8d256c2017-03-20 19:46:55 +00009498void llvm::printMachOLazyBindTable(object::MachOObjectFile *Obj) {
Nick Kledzik5ffacc12014-09-30 00:19:58 +00009499 outs() << "segment section address "
9500 "dylib symbol\n";
Kevin Enderbyfeb63b92017-02-28 21:47:07 +00009501 Error Err = Error::success();
9502 for (const llvm::object::MachOBindEntry &Entry : Obj->lazyBindTable(Err)) {
Kevin Enderbya8d256c2017-03-20 19:46:55 +00009503 StringRef SegmentName = Entry.segmentName();
9504 StringRef SectionName = Entry.sectionName();
9505 uint64_t Address = Entry.address();
Nick Kledzik56ebef42014-09-16 01:41:51 +00009506
9507 // Table lines look like:
9508 // __DATA __got 0x00012010 libSystem ___stack_chk_guard
Kevin Enderbyb28ed012014-10-29 21:28:24 +00009509 outs() << left_justify(SegmentName, 8) << " "
Nick Kledzik5ffacc12014-09-30 00:19:58 +00009510 << left_justify(SectionName, 18) << " "
9511 << format_hex(Address, 10, true) << " "
9512 << left_justify(ordinalName(Obj, Entry.ordinal()), 16) << " "
Nick Kledzik56ebef42014-09-16 01:41:51 +00009513 << Entry.symbolName() << "\n";
9514 }
Kevin Enderbyfeb63b92017-02-28 21:47:07 +00009515 if (Err)
9516 report_error(Obj->getFileName(), std::move(Err));
Nick Kledzik56ebef42014-09-16 01:41:51 +00009517}
9518
Nick Kledzik56ebef42014-09-16 01:41:51 +00009519//===----------------------------------------------------------------------===//
9520// weak bind table dumping
9521//===----------------------------------------------------------------------===//
9522
Kevin Enderbya8d256c2017-03-20 19:46:55 +00009523void llvm::printMachOWeakBindTable(object::MachOObjectFile *Obj) {
Nick Kledzik5ffacc12014-09-30 00:19:58 +00009524 outs() << "segment section address "
9525 "type addend symbol\n";
Kevin Enderbyfeb63b92017-02-28 21:47:07 +00009526 Error Err = Error::success();
9527 for (const llvm::object::MachOBindEntry &Entry : Obj->weakBindTable(Err)) {
Nick Kledzik56ebef42014-09-16 01:41:51 +00009528 // Strong symbols don't have a location to update.
9529 if (Entry.flags() & MachO::BIND_SYMBOL_FLAGS_NON_WEAK_DEFINITION) {
Nick Kledzik5ffacc12014-09-30 00:19:58 +00009530 outs() << " strong "
Nick Kledzik56ebef42014-09-16 01:41:51 +00009531 << Entry.symbolName() << "\n";
9532 continue;
9533 }
Kevin Enderbya8d256c2017-03-20 19:46:55 +00009534 StringRef SegmentName = Entry.segmentName();
9535 StringRef SectionName = Entry.sectionName();
9536 uint64_t Address = Entry.address();
Nick Kledzik56ebef42014-09-16 01:41:51 +00009537
9538 // Table lines look like:
9539 // __DATA __data 0x00001000 pointer 0 _foo
Kevin Enderbyb28ed012014-10-29 21:28:24 +00009540 outs() << left_justify(SegmentName, 8) << " "
Nick Kledzik5ffacc12014-09-30 00:19:58 +00009541 << left_justify(SectionName, 18) << " "
9542 << format_hex(Address, 10, true) << " "
9543 << left_justify(Entry.typeName(), 8) << " "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00009544 << format_decimal(Entry.addend(), 8) << " " << Entry.symbolName()
9545 << "\n";
Nick Kledzik56ebef42014-09-16 01:41:51 +00009546 }
Kevin Enderbyfeb63b92017-02-28 21:47:07 +00009547 if (Err)
9548 report_error(Obj->getFileName(), std::move(Err));
Nick Kledzik56ebef42014-09-16 01:41:51 +00009549}
9550
Kevin Enderby6f326ce2014-10-23 19:37:31 +00009551// get_dyld_bind_info_symbolname() is used for disassembly and passed an
9552// address, ReferenceValue, in the Mach-O file and looks in the dyld bind
9553// information for that address. If the address is found its binding symbol
9554// name is returned. If not nullptr is returned.
9555static const char *get_dyld_bind_info_symbolname(uint64_t ReferenceValue,
9556 struct DisassembleInfo *info) {
Kevin Enderby078be602014-10-23 19:53:12 +00009557 if (info->bindtable == nullptr) {
Saleem Abdulrasool1d84d9a2017-01-08 19:14:15 +00009558 info->bindtable = llvm::make_unique<SymbolAddressMap>();
Kevin Enderbyfeb63b92017-02-28 21:47:07 +00009559 Error Err = Error::success();
9560 for (const llvm::object::MachOBindEntry &Entry : info->O->bindTable(Err)) {
Kevin Enderbya8d256c2017-03-20 19:46:55 +00009561 uint64_t Address = Entry.address();
Kevin Enderby6f326ce2014-10-23 19:37:31 +00009562 StringRef name = Entry.symbolName();
9563 if (!name.empty())
Saleem Abdulrasool1d84d9a2017-01-08 19:14:15 +00009564 (*info->bindtable)[Address] = name;
Kevin Enderby6f326ce2014-10-23 19:37:31 +00009565 }
Kevin Enderbyfeb63b92017-02-28 21:47:07 +00009566 if (Err)
9567 report_error(info->O->getFileName(), std::move(Err));
Kevin Enderby6f326ce2014-10-23 19:37:31 +00009568 }
Saleem Abdulrasool1d84d9a2017-01-08 19:14:15 +00009569 auto name = info->bindtable->lookup(ReferenceValue);
9570 return !name.empty() ? name.data() : nullptr;
Kevin Enderby6f326ce2014-10-23 19:37:31 +00009571}