blob: 4e5241c5c502b20df50f8173ba217f64d4eea423 [file] [log] [blame]
Benjamin Kramer43a772e2011-09-19 17:56:04 +00001//===-- MachODump.cpp - Object file dumping utility for llvm --------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the MachO-specific dumper for llvm-objdump.
11//
12//===----------------------------------------------------------------------===//
13
Mehdi Aminib550cb12016-04-18 09:17:29 +000014#include "llvm/Object/MachO.h"
Benjamin Kramer43a772e2011-09-19 17:56:04 +000015#include "llvm-objdump.h"
Kevin Enderby98c9acc2014-09-16 18:00:57 +000016#include "llvm-c/Disassembler.h"
Benjamin Kramer43a772e2011-09-19 17:56:04 +000017#include "llvm/ADT/STLExtras.h"
Ahmed Bougachaaa790682013-05-24 01:07:04 +000018#include "llvm/ADT/StringExtras.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000019#include "llvm/ADT/Triple.h"
Kevin Enderby04bf6932014-10-28 23:39:46 +000020#include "llvm/Config/config.h"
Zachary Turner6489d7b2015-04-23 17:37:47 +000021#include "llvm/DebugInfo/DIContext.h"
22#include "llvm/DebugInfo/DWARF/DWARFContext.h"
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"
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +000033#include "llvm/Object/MachOUniversal.h"
Rafael Espindola9b709252013-04-13 01:45:40 +000034#include "llvm/Support/Casting.h"
Benjamin Kramer43a772e2011-09-19 17:56:04 +000035#include "llvm/Support/CommandLine.h"
36#include "llvm/Support/Debug.h"
Tim Northover4bd286a2014-08-01 13:07:19 +000037#include "llvm/Support/Endian.h"
Benjamin Kramer43a772e2011-09-19 17:56:04 +000038#include "llvm/Support/Format.h"
Chandler Carruthd9903882015-01-14 11:23:27 +000039#include "llvm/Support/FormattedStream.h"
Benjamin Kramer43a772e2011-09-19 17:56:04 +000040#include "llvm/Support/GraphWriter.h"
Kevin Enderby9a509442015-01-27 21:28:24 +000041#include "llvm/Support/LEB128.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000042#include "llvm/Support/MachO.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 Enderbyab5e6c92015-03-17 21:07:39 +000071static cl::opt<bool> NoLeadingAddr("no-leading-addr",
72 cl::desc("Print no leading address"));
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") {
1138 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
1139 StringRef BytesStr;
1140 Section.getContents(BytesStr);
1141 const char *sect = reinterpret_cast<const char *>(BytesStr.data());
1142 outs() << sect;
1143 return;
1144 }
1145 }
1146}
1147
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001148// checkMachOAndArchFlags() checks to see if the ObjectFile is a Mach-O file
1149// and if it is and there is a list of architecture flags is specified then
1150// check to make sure this Mach-O file is one of those architectures or all
1151// architectures were specified. If not then an error is generated and this
1152// routine returns false. Else it returns true.
1153static bool checkMachOAndArchFlags(ObjectFile *O, StringRef Filename) {
David Majnemer91160d82016-10-31 17:11:31 +00001154 auto *MachO = dyn_cast<MachOObjectFile>(O);
1155
1156 if (!MachO || ArchAll || ArchFlags.empty())
1157 return true;
1158
1159 MachO::mach_header H;
1160 MachO::mach_header_64 H_64;
1161 Triple T;
1162 if (MachO->is64Bit()) {
1163 H_64 = MachO->MachOObjectFile::getHeader64();
1164 T = MachOObjectFile::getArchTriple(H_64.cputype, H_64.cpusubtype);
1165 } else {
1166 H = MachO->MachOObjectFile::getHeader();
1167 T = MachOObjectFile::getArchTriple(H.cputype, H.cpusubtype);
1168 }
1169 if (none_of(ArchFlags, [&](const std::string &Name) {
1170 return Name == T.getArchName();
1171 })) {
1172 errs() << "llvm-objdump: " + Filename + ": No architecture specified.\n";
1173 return false;
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001174 }
1175 return true;
1176}
1177
Kevin Enderby0fc11822015-04-01 20:57:01 +00001178static void printObjcMetaData(MachOObjectFile *O, bool verbose);
1179
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001180// ProcessMachO() is passed a single opened Mach-O file, which may be an
1181// archive member and or in a slice of a universal file. It prints the
1182// the file name and header info and then processes it according to the
1183// command line options.
Kevin Enderby844c4ac2016-11-15 23:07:41 +00001184static void ProcessMachO(StringRef Name, MachOObjectFile *MachOOF,
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001185 StringRef ArchiveMemberName = StringRef(),
1186 StringRef ArchitectureName = StringRef()) {
Kevin Enderby131d1772015-01-09 19:22:37 +00001187 // If we are doing some processing here on the Mach-O file print the header
1188 // info. And don't print it otherwise like in the case of printing the
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +00001189 // UniversalHeaders or ArchiveHeaders.
Kevin Enderbyac9e1552016-05-17 17:10:12 +00001190 if (Disassemble || PrivateHeaders || ExportsTrie || Rebase || Bind || SymbolTable ||
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001191 LazyBind || WeakBind || IndirectSymbols || DataInCode || LinkOptHints ||
Colin LeMahieufcc32762015-07-29 19:08:10 +00001192 DylibsUsed || DylibId || ObjcMetaData || (FilterSections.size() != 0)) {
Kevin Enderby844c4ac2016-11-15 23:07:41 +00001193 outs() << Name;
Kevin Enderby131d1772015-01-09 19:22:37 +00001194 if (!ArchiveMemberName.empty())
1195 outs() << '(' << ArchiveMemberName << ')';
1196 if (!ArchitectureName.empty())
1197 outs() << " (architecture " << ArchitectureName << ")";
1198 outs() << ":\n";
1199 }
Kevin Enderby844c4ac2016-11-15 23:07:41 +00001200 // To use the report_error() form with an ArchiveName and FileName set
1201 // these up based on what is passed for Name and ArchiveMemberName.
1202 StringRef ArchiveName;
1203 StringRef FileName;
1204 if (!ArchiveMemberName.empty()) {
1205 ArchiveName = Name;
1206 FileName = ArchiveMemberName;
1207 } else {
1208 ArchiveName = StringRef();
1209 FileName = Name;
1210 }
1211
1212 // If we need the symbol table to do the operation then check it here to
1213 // produce a good error message as to where the Mach-O file comes from in
1214 // the error message.
1215 if (Disassemble || IndirectSymbols || FilterSections.size() != 0 ||
1216 UnwindInfo)
1217 if (Error Err = MachOOF->checkSymbolTable())
1218 report_error(ArchiveName, FileName, std::move(Err), ArchitectureName);
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001219
1220 if (Disassemble)
Kevin Enderby844c4ac2016-11-15 23:07:41 +00001221 DisassembleMachO(FileName, MachOOF, "__TEXT", "__text");
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +00001222 if (IndirectSymbols)
Kevin Enderbyf0640752015-03-13 17:56:32 +00001223 PrintIndirectSymbols(MachOOF, !NonVerbose);
Kevin Enderby69fe98d2015-01-23 18:52:17 +00001224 if (DataInCode)
Kevin Enderbyf0640752015-03-13 17:56:32 +00001225 PrintDataInCodeTable(MachOOF, !NonVerbose);
Kevin Enderby9a509442015-01-27 21:28:24 +00001226 if (LinkOptHints)
1227 PrintLinkOptHints(MachOOF);
Kevin Enderby98da6132015-01-20 21:47:46 +00001228 if (Relocations)
1229 PrintRelocations(MachOOF);
1230 if (SectionHeaders)
1231 PrintSectionHeaders(MachOOF);
1232 if (SectionContents)
1233 PrintSectionContents(MachOOF);
Colin LeMahieufcc32762015-07-29 19:08:10 +00001234 if (FilterSections.size() != 0)
Kevin Enderby844c4ac2016-11-15 23:07:41 +00001235 DumpSectionContents(FileName, MachOOF, !NonVerbose);
Kevin Enderbycd66be52015-03-11 22:06:32 +00001236 if (InfoPlist)
Kevin Enderby844c4ac2016-11-15 23:07:41 +00001237 DumpInfoPlistSectionContents(FileName, MachOOF);
Kevin Enderbybc847fa2015-03-16 20:08:09 +00001238 if (DylibsUsed)
1239 PrintDylibs(MachOOF, false);
1240 if (DylibId)
1241 PrintDylibs(MachOOF, true);
Kevin Enderby844c4ac2016-11-15 23:07:41 +00001242 if (SymbolTable)
Kevin Enderby9acb1092016-05-31 20:35:34 +00001243 PrintSymbolTable(MachOOF, ArchiveName, ArchitectureName);
Kevin Enderby98da6132015-01-20 21:47:46 +00001244 if (UnwindInfo)
1245 printMachOUnwindInfo(MachOOF);
Kevin Enderby0ae163f2016-01-13 00:25:36 +00001246 if (PrivateHeaders) {
1247 printMachOFileHeader(MachOOF);
1248 printMachOLoadCommands(MachOOF);
1249 }
1250 if (FirstPrivateHeader)
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001251 printMachOFileHeader(MachOOF);
Kevin Enderby0fc11822015-04-01 20:57:01 +00001252 if (ObjcMetaData)
1253 printObjcMetaData(MachOOF, !NonVerbose);
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001254 if (ExportsTrie)
1255 printExportsTrie(MachOOF);
1256 if (Rebase)
1257 printRebaseTable(MachOOF);
1258 if (Bind)
1259 printBindTable(MachOOF);
1260 if (LazyBind)
1261 printLazyBindTable(MachOOF);
1262 if (WeakBind)
1263 printWeakBindTable(MachOOF);
Igor Laevsky03a670c2016-01-26 15:09:42 +00001264
1265 if (DwarfDumpType != DIDT_Null) {
1266 std::unique_ptr<DIContext> DICtx(new DWARFContextInMemory(*MachOOF));
1267 // Dump the complete DWARF structure.
1268 DICtx->dump(outs(), DwarfDumpType, true /* DumpEH */);
1269 }
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001270}
1271
Kevin Enderby131d1772015-01-09 19:22:37 +00001272// printUnknownCPUType() helps print_fat_headers for unknown CPU's.
1273static void printUnknownCPUType(uint32_t cputype, uint32_t cpusubtype) {
1274 outs() << " cputype (" << cputype << ")\n";
1275 outs() << " cpusubtype (" << cpusubtype << ")\n";
1276}
1277
1278// printCPUType() helps print_fat_headers by printing the cputype and
1279// pusubtype (symbolically for the one's it knows about).
1280static void printCPUType(uint32_t cputype, uint32_t cpusubtype) {
1281 switch (cputype) {
1282 case MachO::CPU_TYPE_I386:
1283 switch (cpusubtype) {
1284 case MachO::CPU_SUBTYPE_I386_ALL:
1285 outs() << " cputype CPU_TYPE_I386\n";
1286 outs() << " cpusubtype CPU_SUBTYPE_I386_ALL\n";
1287 break;
1288 default:
1289 printUnknownCPUType(cputype, cpusubtype);
1290 break;
1291 }
1292 break;
1293 case MachO::CPU_TYPE_X86_64:
1294 switch (cpusubtype) {
1295 case MachO::CPU_SUBTYPE_X86_64_ALL:
1296 outs() << " cputype CPU_TYPE_X86_64\n";
1297 outs() << " cpusubtype CPU_SUBTYPE_X86_64_ALL\n";
1298 break;
1299 case MachO::CPU_SUBTYPE_X86_64_H:
1300 outs() << " cputype CPU_TYPE_X86_64\n";
1301 outs() << " cpusubtype CPU_SUBTYPE_X86_64_H\n";
1302 break;
1303 default:
1304 printUnknownCPUType(cputype, cpusubtype);
1305 break;
1306 }
1307 break;
1308 case MachO::CPU_TYPE_ARM:
1309 switch (cpusubtype) {
1310 case MachO::CPU_SUBTYPE_ARM_ALL:
1311 outs() << " cputype CPU_TYPE_ARM\n";
1312 outs() << " cpusubtype CPU_SUBTYPE_ARM_ALL\n";
1313 break;
1314 case MachO::CPU_SUBTYPE_ARM_V4T:
1315 outs() << " cputype CPU_TYPE_ARM\n";
1316 outs() << " cpusubtype CPU_SUBTYPE_ARM_V4T\n";
1317 break;
1318 case MachO::CPU_SUBTYPE_ARM_V5TEJ:
1319 outs() << " cputype CPU_TYPE_ARM\n";
1320 outs() << " cpusubtype CPU_SUBTYPE_ARM_V5TEJ\n";
1321 break;
1322 case MachO::CPU_SUBTYPE_ARM_XSCALE:
1323 outs() << " cputype CPU_TYPE_ARM\n";
1324 outs() << " cpusubtype CPU_SUBTYPE_ARM_XSCALE\n";
1325 break;
1326 case MachO::CPU_SUBTYPE_ARM_V6:
1327 outs() << " cputype CPU_TYPE_ARM\n";
1328 outs() << " cpusubtype CPU_SUBTYPE_ARM_V6\n";
1329 break;
1330 case MachO::CPU_SUBTYPE_ARM_V6M:
1331 outs() << " cputype CPU_TYPE_ARM\n";
1332 outs() << " cpusubtype CPU_SUBTYPE_ARM_V6M\n";
1333 break;
1334 case MachO::CPU_SUBTYPE_ARM_V7:
1335 outs() << " cputype CPU_TYPE_ARM\n";
1336 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7\n";
1337 break;
1338 case MachO::CPU_SUBTYPE_ARM_V7EM:
1339 outs() << " cputype CPU_TYPE_ARM\n";
1340 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7EM\n";
1341 break;
1342 case MachO::CPU_SUBTYPE_ARM_V7K:
1343 outs() << " cputype CPU_TYPE_ARM\n";
1344 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7K\n";
1345 break;
1346 case MachO::CPU_SUBTYPE_ARM_V7M:
1347 outs() << " cputype CPU_TYPE_ARM\n";
1348 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7M\n";
1349 break;
1350 case MachO::CPU_SUBTYPE_ARM_V7S:
1351 outs() << " cputype CPU_TYPE_ARM\n";
1352 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7S\n";
1353 break;
1354 default:
1355 printUnknownCPUType(cputype, cpusubtype);
1356 break;
1357 }
1358 break;
1359 case MachO::CPU_TYPE_ARM64:
1360 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
1361 case MachO::CPU_SUBTYPE_ARM64_ALL:
1362 outs() << " cputype CPU_TYPE_ARM64\n";
1363 outs() << " cpusubtype CPU_SUBTYPE_ARM64_ALL\n";
1364 break;
1365 default:
1366 printUnknownCPUType(cputype, cpusubtype);
1367 break;
1368 }
1369 break;
1370 default:
1371 printUnknownCPUType(cputype, cpusubtype);
1372 break;
1373 }
1374}
1375
1376static void printMachOUniversalHeaders(const object::MachOUniversalBinary *UB,
1377 bool verbose) {
1378 outs() << "Fat headers\n";
Kevin Enderby606a3382016-06-21 21:55:01 +00001379 if (verbose) {
1380 if (UB->getMagic() == MachO::FAT_MAGIC)
1381 outs() << "fat_magic FAT_MAGIC\n";
1382 else // UB->getMagic() == MachO::FAT_MAGIC_64
1383 outs() << "fat_magic FAT_MAGIC_64\n";
1384 } else
Kevin Enderby131d1772015-01-09 19:22:37 +00001385 outs() << "fat_magic " << format("0x%" PRIx32, MachO::FAT_MAGIC) << "\n";
1386
1387 uint32_t nfat_arch = UB->getNumberOfObjects();
1388 StringRef Buf = UB->getData();
1389 uint64_t size = Buf.size();
1390 uint64_t big_size = sizeof(struct MachO::fat_header) +
1391 nfat_arch * sizeof(struct MachO::fat_arch);
1392 outs() << "nfat_arch " << UB->getNumberOfObjects();
1393 if (nfat_arch == 0)
1394 outs() << " (malformed, contains zero architecture types)\n";
1395 else if (big_size > size)
1396 outs() << " (malformed, architectures past end of file)\n";
1397 else
1398 outs() << "\n";
1399
1400 for (uint32_t i = 0; i < nfat_arch; ++i) {
1401 MachOUniversalBinary::ObjectForArch OFA(UB, i);
1402 uint32_t cputype = OFA.getCPUType();
1403 uint32_t cpusubtype = OFA.getCPUSubType();
1404 outs() << "architecture ";
1405 for (uint32_t j = 0; i != 0 && j <= i - 1; j++) {
1406 MachOUniversalBinary::ObjectForArch other_OFA(UB, j);
1407 uint32_t other_cputype = other_OFA.getCPUType();
1408 uint32_t other_cpusubtype = other_OFA.getCPUSubType();
Kevin Enderby0512bd72015-01-09 21:55:03 +00001409 if (cputype != 0 && cpusubtype != 0 && cputype == other_cputype &&
Kevin Enderby131d1772015-01-09 19:22:37 +00001410 (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) ==
Kevin Enderby0512bd72015-01-09 21:55:03 +00001411 (other_cpusubtype & ~MachO::CPU_SUBTYPE_MASK)) {
Kevin Enderby131d1772015-01-09 19:22:37 +00001412 outs() << "(illegal duplicate architecture) ";
1413 break;
Kevin Enderby0512bd72015-01-09 21:55:03 +00001414 }
Kevin Enderby131d1772015-01-09 19:22:37 +00001415 }
1416 if (verbose) {
1417 outs() << OFA.getArchTypeName() << "\n";
1418 printCPUType(cputype, cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
1419 } else {
1420 outs() << i << "\n";
1421 outs() << " cputype " << cputype << "\n";
1422 outs() << " cpusubtype " << (cpusubtype & ~MachO::CPU_SUBTYPE_MASK)
1423 << "\n";
1424 }
1425 if (verbose &&
1426 (cpusubtype & MachO::CPU_SUBTYPE_MASK) == MachO::CPU_SUBTYPE_LIB64)
1427 outs() << " capabilities CPU_SUBTYPE_LIB64\n";
1428 else
1429 outs() << " capabilities "
1430 << format("0x%" PRIx32,
1431 (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24) << "\n";
1432 outs() << " offset " << OFA.getOffset();
1433 if (OFA.getOffset() > size)
1434 outs() << " (past end of file)";
1435 if (OFA.getOffset() % (1 << OFA.getAlign()) != 0)
1436 outs() << " (not aligned on it's alignment (2^" << OFA.getAlign() << ")";
1437 outs() << "\n";
1438 outs() << " size " << OFA.getSize();
1439 big_size = OFA.getOffset() + OFA.getSize();
1440 if (big_size > size)
1441 outs() << " (past end of file)";
1442 outs() << "\n";
1443 outs() << " align 2^" << OFA.getAlign() << " (" << (1 << OFA.getAlign())
1444 << ")\n";
1445 }
1446}
1447
Kevin Enderby6524bd82016-07-19 20:47:07 +00001448static void printArchiveChild(StringRef Filename, const Archive::Child &C,
1449 bool verbose, bool print_offset,
1450 StringRef ArchitectureName = StringRef()) {
Kevin Enderby13023a12015-01-15 23:19:11 +00001451 if (print_offset)
1452 outs() << C.getChildOffset() << "\t";
Vedant Kumar4031d9f2016-08-03 19:02:50 +00001453 Expected<sys::fs::perms> ModeOrErr = C.getAccessMode();
1454 if (!ModeOrErr)
1455 report_error(Filename, C, ModeOrErr.takeError(), ArchitectureName);
1456 sys::fs::perms Mode = ModeOrErr.get();
Kevin Enderby13023a12015-01-15 23:19:11 +00001457 if (verbose) {
1458 // FIXME: this first dash, "-", is for (Mode & S_IFMT) == S_IFREG.
1459 // But there is nothing in sys::fs::perms for S_IFMT or S_IFREG.
1460 outs() << "-";
Davide Italianobb9a6cc2015-09-07 20:47:03 +00001461 outs() << ((Mode & sys::fs::owner_read) ? "r" : "-");
1462 outs() << ((Mode & sys::fs::owner_write) ? "w" : "-");
1463 outs() << ((Mode & sys::fs::owner_exe) ? "x" : "-");
1464 outs() << ((Mode & sys::fs::group_read) ? "r" : "-");
1465 outs() << ((Mode & sys::fs::group_write) ? "w" : "-");
1466 outs() << ((Mode & sys::fs::group_exe) ? "x" : "-");
1467 outs() << ((Mode & sys::fs::others_read) ? "r" : "-");
1468 outs() << ((Mode & sys::fs::others_write) ? "w" : "-");
1469 outs() << ((Mode & sys::fs::others_exe) ? "x" : "-");
Kevin Enderby13023a12015-01-15 23:19:11 +00001470 } else {
1471 outs() << format("0%o ", Mode);
1472 }
1473
Vedant Kumar4031d9f2016-08-03 19:02:50 +00001474 Expected<unsigned> UIDOrErr = C.getUID();
1475 if (!UIDOrErr)
1476 report_error(Filename, C, UIDOrErr.takeError(), ArchitectureName);
1477 unsigned UID = UIDOrErr.get();
Kevin Enderby13023a12015-01-15 23:19:11 +00001478 outs() << format("%3d/", UID);
Vedant Kumar4031d9f2016-08-03 19:02:50 +00001479 Expected<unsigned> GIDOrErr = C.getGID();
1480 if (!GIDOrErr)
1481 report_error(Filename, C, GIDOrErr.takeError(), ArchitectureName);
1482 unsigned GID = GIDOrErr.get();
Kevin Enderby13023a12015-01-15 23:19:11 +00001483 outs() << format("%-3d ", GID);
Kevin Enderby6524bd82016-07-19 20:47:07 +00001484 Expected<uint64_t> Size = C.getRawSize();
1485 if (!Size)
1486 report_error(Filename, C, Size.takeError(), ArchitectureName);
Kevin Enderby7a969422015-11-05 19:24:56 +00001487 outs() << format("%5" PRId64, Size.get()) << " ";
Kevin Enderby13023a12015-01-15 23:19:11 +00001488
1489 StringRef RawLastModified = C.getRawLastModified();
1490 if (verbose) {
1491 unsigned Seconds;
1492 if (RawLastModified.getAsInteger(10, Seconds))
Vedant Kumar4031d9f2016-08-03 19:02:50 +00001493 outs() << "(date: \"" << RawLastModified
1494 << "\" contains non-decimal chars) ";
Kevin Enderby13023a12015-01-15 23:19:11 +00001495 else {
1496 // Since cime(3) returns a 26 character string of the form:
1497 // "Sun Sep 16 01:03:52 1973\n\0"
1498 // just print 24 characters.
1499 time_t t = Seconds;
1500 outs() << format("%.24s ", ctime(&t));
1501 }
1502 } else {
1503 outs() << RawLastModified << " ";
1504 }
1505
1506 if (verbose) {
Kevin Enderbyf4586032016-07-29 17:44:13 +00001507 Expected<StringRef> NameOrErr = C.getName();
1508 if (!NameOrErr) {
1509 consumeError(NameOrErr.takeError());
1510 Expected<StringRef> NameOrErr = C.getRawName();
1511 if (!NameOrErr)
1512 report_error(Filename, C, NameOrErr.takeError(), ArchitectureName);
1513 StringRef RawName = NameOrErr.get();
Kevin Enderby13023a12015-01-15 23:19:11 +00001514 outs() << RawName << "\n";
1515 } else {
1516 StringRef Name = NameOrErr.get();
1517 outs() << Name << "\n";
1518 }
1519 } else {
Kevin Enderbyf4586032016-07-29 17:44:13 +00001520 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 }
1526}
1527
Kevin Enderby6524bd82016-07-19 20:47:07 +00001528static void printArchiveHeaders(StringRef Filename, Archive *A, bool verbose,
1529 bool print_offset,
1530 StringRef ArchitectureName = StringRef()) {
Mehdi Amini41af4302016-11-11 04:28:40 +00001531 Error Err = Error::success();
1532 ;
Lang Hamesfc209622016-07-14 02:24:01 +00001533 for (const auto &C : A->children(Err, false))
Kevin Enderby6524bd82016-07-19 20:47:07 +00001534 printArchiveChild(Filename, C, verbose, print_offset, ArchitectureName);
1535
Lang Hamesfc209622016-07-14 02:24:01 +00001536 if (Err)
Kevin Enderby844c4ac2016-11-15 23:07:41 +00001537 report_error(StringRef(), Filename, std::move(Err), ArchitectureName);
Kevin Enderby13023a12015-01-15 23:19:11 +00001538}
1539
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001540// ParseInputMachO() parses the named Mach-O file in Filename and handles the
1541// -arch flags selecting just those slices as specified by them and also parses
1542// archive files. Then for each individual Mach-O file ProcessMachO() is
1543// called to process the file based on the command line options.
1544void llvm::ParseInputMachO(StringRef Filename) {
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001545 // Check for -arch all and verifiy the -arch flags are valid.
1546 for (unsigned i = 0; i < ArchFlags.size(); ++i) {
1547 if (ArchFlags[i] == "all") {
1548 ArchAll = true;
1549 } else {
1550 if (!MachOObjectFile::isValidArch(ArchFlags[i])) {
1551 errs() << "llvm-objdump: Unknown architecture named '" + ArchFlags[i] +
1552 "'for the -arch option\n";
1553 return;
1554 }
1555 }
1556 }
1557
1558 // Attempt to open the binary.
Kevin Enderby3fcdf6a2016-04-06 22:14:09 +00001559 Expected<OwningBinary<Binary>> BinaryOrErr = createBinary(Filename);
1560 if (!BinaryOrErr)
1561 report_error(Filename, BinaryOrErr.takeError());
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001562 Binary &Bin = *BinaryOrErr.get().getBinary();
Kevin Enderby3f0ffab2014-12-03 22:29:40 +00001563
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001564 if (Archive *A = dyn_cast<Archive>(&Bin)) {
1565 outs() << "Archive : " << Filename << "\n";
Kevin Enderby13023a12015-01-15 23:19:11 +00001566 if (ArchiveHeaders)
Kevin Enderby6524bd82016-07-19 20:47:07 +00001567 printArchiveHeaders(Filename, A, !NonVerbose, ArchiveMemberOffsets);
1568
Mehdi Amini41af4302016-11-11 04:28:40 +00001569 Error Err = Error::success();
Lang Hamesfc209622016-07-14 02:24:01 +00001570 for (auto &C : A->children(Err)) {
Kevin Enderbyac9e1552016-05-17 17:10:12 +00001571 Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
1572 if (!ChildOrErr) {
1573 if (auto E = isNotObjectErrorInvalidFileType(ChildOrErr.takeError()))
1574 report_error(Filename, C, std::move(E));
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001575 continue;
Kevin Enderbyac9e1552016-05-17 17:10:12 +00001576 }
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001577 if (MachOObjectFile *O = dyn_cast<MachOObjectFile>(&*ChildOrErr.get())) {
1578 if (!checkMachOAndArchFlags(O, Filename))
1579 return;
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001580 ProcessMachO(Filename, O, O->getFileName());
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001581 }
1582 }
Lang Hamesfc209622016-07-14 02:24:01 +00001583 if (Err)
1584 report_error(Filename, std::move(Err));
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001585 return;
1586 }
Kevin Enderby131d1772015-01-09 19:22:37 +00001587 if (UniversalHeaders) {
1588 if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(&Bin))
Kevin Enderbyf0640752015-03-13 17:56:32 +00001589 printMachOUniversalHeaders(UB, !NonVerbose);
Kevin Enderby131d1772015-01-09 19:22:37 +00001590 }
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001591 if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(&Bin)) {
1592 // If we have a list of architecture flags specified dump only those.
1593 if (!ArchAll && ArchFlags.size() != 0) {
1594 // Look for a slice in the universal binary that matches each ArchFlag.
1595 bool ArchFound;
1596 for (unsigned i = 0; i < ArchFlags.size(); ++i) {
1597 ArchFound = false;
1598 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
1599 E = UB->end_objects();
1600 I != E; ++I) {
1601 if (ArchFlags[i] == I->getArchTypeName()) {
1602 ArchFound = true;
Kevin Enderby9acb1092016-05-31 20:35:34 +00001603 Expected<std::unique_ptr<ObjectFile>> ObjOrErr =
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001604 I->getAsObjectFile();
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001605 std::string ArchitectureName = "";
1606 if (ArchFlags.size() > 1)
1607 ArchitectureName = I->getArchTypeName();
1608 if (ObjOrErr) {
1609 ObjectFile &O = *ObjOrErr.get();
1610 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&O))
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001611 ProcessMachO(Filename, MachOOF, "", ArchitectureName);
Kevin Enderby9acb1092016-05-31 20:35:34 +00001612 } else if (auto E = isNotObjectErrorInvalidFileType(
1613 ObjOrErr.takeError())) {
1614 report_error(Filename, StringRef(), std::move(E),
1615 ArchitectureName);
1616 continue;
Kevin Enderby42398052016-06-28 23:16:13 +00001617 } else if (Expected<std::unique_ptr<Archive>> AOrErr =
Rafael Espindola0bfe8282014-12-09 21:05:36 +00001618 I->getAsArchive()) {
1619 std::unique_ptr<Archive> &A = *AOrErr;
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001620 outs() << "Archive : " << Filename;
1621 if (!ArchitectureName.empty())
1622 outs() << " (architecture " << ArchitectureName << ")";
1623 outs() << "\n";
Kevin Enderby13023a12015-01-15 23:19:11 +00001624 if (ArchiveHeaders)
Kevin Enderby6524bd82016-07-19 20:47:07 +00001625 printArchiveHeaders(Filename, A.get(), !NonVerbose,
1626 ArchiveMemberOffsets, ArchitectureName);
Mehdi Amini41af4302016-11-11 04:28:40 +00001627 Error Err = Error::success();
Lang Hamesfc209622016-07-14 02:24:01 +00001628 for (auto &C : A->children(Err)) {
Kevin Enderbyac9e1552016-05-17 17:10:12 +00001629 Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
1630 if (!ChildOrErr) {
1631 if (auto E = isNotObjectErrorInvalidFileType(ChildOrErr.takeError()))
Kevin Enderby9acb1092016-05-31 20:35:34 +00001632 report_error(Filename, C, std::move(E), ArchitectureName);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001633 continue;
Kevin Enderbyac9e1552016-05-17 17:10:12 +00001634 }
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001635 if (MachOObjectFile *O =
1636 dyn_cast<MachOObjectFile>(&*ChildOrErr.get()))
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001637 ProcessMachO(Filename, O, O->getFileName(), ArchitectureName);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001638 }
Lang Hamesfc209622016-07-14 02:24:01 +00001639 if (Err)
1640 report_error(Filename, std::move(Err));
Kevin Enderby42398052016-06-28 23:16:13 +00001641 } else {
1642 consumeError(AOrErr.takeError());
1643 error("Mach-O universal file: " + Filename + " for " +
1644 "architecture " + StringRef(I->getArchTypeName()) +
1645 " is not a Mach-O file or an archive file");
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001646 }
1647 }
1648 }
1649 if (!ArchFound) {
1650 errs() << "llvm-objdump: file: " + Filename + " does not contain "
1651 << "architecture: " + ArchFlags[i] + "\n";
1652 return;
1653 }
1654 }
1655 return;
1656 }
1657 // No architecture flags were specified so if this contains a slice that
1658 // matches the host architecture dump only that.
1659 if (!ArchAll) {
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001660 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
1661 E = UB->end_objects();
1662 I != E; ++I) {
Kevin Enderby0512bd72015-01-09 21:55:03 +00001663 if (MachOObjectFile::getHostArch().getArchName() ==
1664 I->getArchTypeName()) {
Kevin Enderby9acb1092016-05-31 20:35:34 +00001665 Expected<std::unique_ptr<ObjectFile>> ObjOrErr = I->getAsObjectFile();
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001666 std::string ArchiveName;
1667 ArchiveName.clear();
1668 if (ObjOrErr) {
1669 ObjectFile &O = *ObjOrErr.get();
1670 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&O))
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001671 ProcessMachO(Filename, MachOOF);
Kevin Enderby9acb1092016-05-31 20:35:34 +00001672 } else if (auto E = isNotObjectErrorInvalidFileType(
1673 ObjOrErr.takeError())) {
1674 report_error(Filename, std::move(E));
1675 continue;
Kevin Enderby42398052016-06-28 23:16:13 +00001676 } else if (Expected<std::unique_ptr<Archive>> AOrErr =
Rafael Espindola0bfe8282014-12-09 21:05:36 +00001677 I->getAsArchive()) {
1678 std::unique_ptr<Archive> &A = *AOrErr;
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001679 outs() << "Archive : " << Filename << "\n";
Kevin Enderby13023a12015-01-15 23:19:11 +00001680 if (ArchiveHeaders)
Kevin Enderby6524bd82016-07-19 20:47:07 +00001681 printArchiveHeaders(Filename, A.get(), !NonVerbose,
1682 ArchiveMemberOffsets);
Mehdi Amini41af4302016-11-11 04:28:40 +00001683 Error Err = Error::success();
Lang Hamesfc209622016-07-14 02:24:01 +00001684 for (auto &C : A->children(Err)) {
Kevin Enderbyac9e1552016-05-17 17:10:12 +00001685 Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
1686 if (!ChildOrErr) {
1687 if (auto E = isNotObjectErrorInvalidFileType(ChildOrErr.takeError()))
1688 report_error(Filename, C, std::move(E));
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001689 continue;
Kevin Enderbyac9e1552016-05-17 17:10:12 +00001690 }
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001691 if (MachOObjectFile *O =
1692 dyn_cast<MachOObjectFile>(&*ChildOrErr.get()))
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001693 ProcessMachO(Filename, O, O->getFileName());
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001694 }
Lang Hamesfc209622016-07-14 02:24:01 +00001695 if (Err)
1696 report_error(Filename, std::move(Err));
Kevin Enderby42398052016-06-28 23:16:13 +00001697 } else {
1698 consumeError(AOrErr.takeError());
1699 error("Mach-O universal file: " + Filename + " for architecture " +
1700 StringRef(I->getArchTypeName()) +
1701 " is not a Mach-O file or an archive file");
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001702 }
1703 return;
1704 }
1705 }
1706 }
1707 // Either all architectures have been specified or none have been specified
1708 // and this does not contain the host architecture so dump all the slices.
1709 bool moreThanOneArch = UB->getNumberOfObjects() > 1;
1710 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
1711 E = UB->end_objects();
1712 I != E; ++I) {
Kevin Enderby9acb1092016-05-31 20:35:34 +00001713 Expected<std::unique_ptr<ObjectFile>> ObjOrErr = I->getAsObjectFile();
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001714 std::string ArchitectureName = "";
1715 if (moreThanOneArch)
1716 ArchitectureName = I->getArchTypeName();
1717 if (ObjOrErr) {
1718 ObjectFile &Obj = *ObjOrErr.get();
1719 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&Obj))
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001720 ProcessMachO(Filename, MachOOF, "", ArchitectureName);
Kevin Enderby9acb1092016-05-31 20:35:34 +00001721 } else if (auto E = isNotObjectErrorInvalidFileType(
1722 ObjOrErr.takeError())) {
1723 report_error(StringRef(), Filename, std::move(E), ArchitectureName);
1724 continue;
Kevin Enderby42398052016-06-28 23:16:13 +00001725 } else if (Expected<std::unique_ptr<Archive>> AOrErr =
1726 I->getAsArchive()) {
Rafael Espindola0bfe8282014-12-09 21:05:36 +00001727 std::unique_ptr<Archive> &A = *AOrErr;
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001728 outs() << "Archive : " << Filename;
1729 if (!ArchitectureName.empty())
1730 outs() << " (architecture " << ArchitectureName << ")";
1731 outs() << "\n";
Kevin Enderby13023a12015-01-15 23:19:11 +00001732 if (ArchiveHeaders)
Kevin Enderby6524bd82016-07-19 20:47:07 +00001733 printArchiveHeaders(Filename, A.get(), !NonVerbose,
1734 ArchiveMemberOffsets, ArchitectureName);
Mehdi Amini41af4302016-11-11 04:28:40 +00001735 Error Err = Error::success();
Lang Hamesfc209622016-07-14 02:24:01 +00001736 for (auto &C : A->children(Err)) {
Kevin Enderbyac9e1552016-05-17 17:10:12 +00001737 Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
1738 if (!ChildOrErr) {
1739 if (auto E = isNotObjectErrorInvalidFileType(ChildOrErr.takeError()))
Kevin Enderby9acb1092016-05-31 20:35:34 +00001740 report_error(Filename, C, std::move(E), ArchitectureName);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001741 continue;
Kevin Enderbyac9e1552016-05-17 17:10:12 +00001742 }
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001743 if (MachOObjectFile *O =
1744 dyn_cast<MachOObjectFile>(&*ChildOrErr.get())) {
1745 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(O))
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001746 ProcessMachO(Filename, MachOOF, MachOOF->getFileName(),
1747 ArchitectureName);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001748 }
1749 }
Lang Hamesfc209622016-07-14 02:24:01 +00001750 if (Err)
1751 report_error(Filename, std::move(Err));
Kevin Enderby42398052016-06-28 23:16:13 +00001752 } else {
1753 consumeError(AOrErr.takeError());
1754 error("Mach-O universal file: " + Filename + " for architecture " +
1755 StringRef(I->getArchTypeName()) +
1756 " is not a Mach-O file or an archive file");
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001757 }
1758 }
1759 return;
1760 }
1761 if (ObjectFile *O = dyn_cast<ObjectFile>(&Bin)) {
1762 if (!checkMachOAndArchFlags(O, Filename))
1763 return;
1764 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&*O)) {
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001765 ProcessMachO(Filename, MachOOF);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001766 } else
1767 errs() << "llvm-objdump: '" << Filename << "': "
1768 << "Object is not a Mach-O file type.\n";
Davide Italiano25d84582016-01-13 04:11:36 +00001769 return;
1770 }
1771 llvm_unreachable("Input object can't be invalid at this point");
Rafael Espindola9b709252013-04-13 01:45:40 +00001772}
1773
Kevin Enderby6f326ce2014-10-23 19:37:31 +00001774typedef std::pair<uint64_t, const char *> BindInfoEntry;
1775typedef std::vector<BindInfoEntry> BindTable;
1776typedef BindTable::iterator bind_table_iterator;
Kevin Enderbybf246f52014-09-24 23:08:22 +00001777
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001778// The block of info used by the Symbolizer call backs.
1779struct DisassembleInfo {
1780 bool verbose;
1781 MachOObjectFile *O;
1782 SectionRef S;
Kevin Enderbybf246f52014-09-24 23:08:22 +00001783 SymbolAddressMap *AddrMap;
Kevin Enderby6f326ce2014-10-23 19:37:31 +00001784 std::vector<SectionRef> *Sections;
1785 const char *class_name;
1786 const char *selector_name;
1787 char *method;
Kevin Enderby04bf6932014-10-28 23:39:46 +00001788 char *demangled_name;
Kevin Enderbyae3c1262014-11-14 21:52:18 +00001789 uint64_t adrp_addr;
1790 uint32_t adrp_inst;
Kevin Enderby078be602014-10-23 19:53:12 +00001791 BindTable *bindtable;
Kevin Enderbyaac75382015-10-08 16:56:35 +00001792 uint32_t depth;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001793};
1794
1795// SymbolizerGetOpInfo() is the operand information call back function.
1796// This is called to get the symbolic information for operand(s) of an
1797// instruction when it is being done. This routine does this from
1798// the relocation information, symbol table, etc. That block of information
1799// is a pointer to the struct DisassembleInfo that was passed when the
1800// disassembler context was created and passed to back to here when
1801// called back by the disassembler for instruction operands that could have
1802// relocation information. The address of the instruction containing operand is
1803// at the Pc parameter. The immediate value the operand has is passed in
1804// op_info->Value and is at Offset past the start of the instruction and has a
1805// byte Size of 1, 2 or 4. The symbolc information is returned in TagBuf is the
1806// LLVMOpInfo1 struct defined in the header "llvm-c/Disassembler.h" as symbol
1807// names and addends of the symbolic expression to add for the operand. The
1808// value of TagType is currently 1 (for the LLVMOpInfo1 struct). If symbolic
1809// information is returned then this function returns 1 else it returns 0.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00001810static int SymbolizerGetOpInfo(void *DisInfo, uint64_t Pc, uint64_t Offset,
1811 uint64_t Size, int TagType, void *TagBuf) {
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001812 struct DisassembleInfo *info = (struct DisassembleInfo *)DisInfo;
1813 struct LLVMOpInfo1 *op_info = (struct LLVMOpInfo1 *)TagBuf;
Kevin Enderbyae3c1262014-11-14 21:52:18 +00001814 uint64_t value = op_info->Value;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001815
1816 // Make sure all fields returned are zero if we don't set them.
1817 memset((void *)op_info, '\0', sizeof(struct LLVMOpInfo1));
1818 op_info->Value = value;
1819
1820 // If the TagType is not the value 1 which it code knows about or if no
1821 // verbose symbolic information is wanted then just return 0, indicating no
1822 // information is being returned.
David Blaikie33dd45d02015-03-23 18:39:02 +00001823 if (TagType != 1 || !info->verbose)
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001824 return 0;
1825
1826 unsigned int Arch = info->O->getArch();
1827 if (Arch == Triple::x86) {
Kevin Enderby9907d0a2014-11-04 00:43:16 +00001828 if (Size != 1 && Size != 2 && Size != 4 && Size != 0)
1829 return 0;
Kevin Enderbyd90a4172015-10-10 00:05:01 +00001830 if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
1831 // TODO:
1832 // Search the external relocation entries of a fully linked image
1833 // (if any) for an entry that matches this segment offset.
1834 // uint32_t seg_offset = (Pc + Offset);
1835 return 0;
1836 }
1837 // In MH_OBJECT filetypes search the section's relocation entries (if any)
1838 // for an entry for this section offset.
Kevin Enderby9907d0a2014-11-04 00:43:16 +00001839 uint32_t sect_addr = info->S.getAddress();
1840 uint32_t sect_offset = (Pc + Offset) - sect_addr;
1841 bool reloc_found = false;
1842 DataRefImpl Rel;
1843 MachO::any_relocation_info RE;
1844 bool isExtern = false;
1845 SymbolRef Symbol;
1846 bool r_scattered = false;
1847 uint32_t r_value, pair_r_value, r_type;
1848 for (const RelocationRef &Reloc : info->S.relocations()) {
Rafael Espindola96d071c2015-06-29 23:29:12 +00001849 uint64_t RelocOffset = Reloc.getOffset();
Kevin Enderby9907d0a2014-11-04 00:43:16 +00001850 if (RelocOffset == sect_offset) {
1851 Rel = Reloc.getRawDataRefImpl();
1852 RE = info->O->getRelocation(Rel);
Kevin Enderby3eb73e12014-11-11 19:16:45 +00001853 r_type = info->O->getAnyRelocationType(RE);
Kevin Enderby9907d0a2014-11-04 00:43:16 +00001854 r_scattered = info->O->isRelocationScattered(RE);
1855 if (r_scattered) {
1856 r_value = info->O->getScatteredRelocationValue(RE);
Kevin Enderby9907d0a2014-11-04 00:43:16 +00001857 if (r_type == MachO::GENERIC_RELOC_SECTDIFF ||
1858 r_type == MachO::GENERIC_RELOC_LOCAL_SECTDIFF) {
1859 DataRefImpl RelNext = Rel;
1860 info->O->moveRelocationNext(RelNext);
1861 MachO::any_relocation_info RENext;
1862 RENext = info->O->getRelocation(RelNext);
1863 if (info->O->isRelocationScattered(RENext))
Kevin Enderby930fdc72014-11-06 19:00:13 +00001864 pair_r_value = info->O->getScatteredRelocationValue(RENext);
Kevin Enderby9907d0a2014-11-04 00:43:16 +00001865 else
1866 return 0;
1867 }
1868 } else {
1869 isExtern = info->O->getPlainRelocationExternal(RE);
1870 if (isExtern) {
1871 symbol_iterator RelocSym = Reloc.getSymbol();
1872 Symbol = *RelocSym;
1873 }
1874 }
1875 reloc_found = true;
1876 break;
1877 }
1878 }
1879 if (reloc_found && isExtern) {
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00001880 Expected<StringRef> SymName = Symbol.getName();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00001881 if (!SymName)
1882 report_error(info->O->getFileName(), SymName.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00001883 const char *name = SymName->data();
Kevin Enderby9907d0a2014-11-04 00:43:16 +00001884 op_info->AddSymbol.Present = 1;
1885 op_info->AddSymbol.Name = name;
1886 // For i386 extern relocation entries the value in the instruction is
1887 // the offset from the symbol, and value is already set in op_info->Value.
1888 return 1;
1889 }
1890 if (reloc_found && (r_type == MachO::GENERIC_RELOC_SECTDIFF ||
1891 r_type == MachO::GENERIC_RELOC_LOCAL_SECTDIFF)) {
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001892 const char *add = GuessSymbolName(r_value, info->AddrMap);
1893 const char *sub = GuessSymbolName(pair_r_value, info->AddrMap);
Kevin Enderby9907d0a2014-11-04 00:43:16 +00001894 uint32_t offset = value - (r_value - pair_r_value);
1895 op_info->AddSymbol.Present = 1;
1896 if (add != nullptr)
1897 op_info->AddSymbol.Name = add;
1898 else
1899 op_info->AddSymbol.Value = r_value;
1900 op_info->SubtractSymbol.Present = 1;
1901 if (sub != nullptr)
1902 op_info->SubtractSymbol.Name = sub;
1903 else
1904 op_info->SubtractSymbol.Value = pair_r_value;
1905 op_info->Value = offset;
1906 return 1;
1907 }
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001908 return 0;
David Blaikie33dd45d02015-03-23 18:39:02 +00001909 }
1910 if (Arch == Triple::x86_64) {
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001911 if (Size != 1 && Size != 2 && Size != 4 && Size != 0)
1912 return 0;
Kevin Enderbyd90a4172015-10-10 00:05:01 +00001913 if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
1914 // TODO:
1915 // Search the external relocation entries of a fully linked image
1916 // (if any) for an entry that matches this segment offset.
1917 // uint64_t seg_offset = (Pc + Offset);
1918 return 0;
1919 }
1920 // In MH_OBJECT filetypes search the section's relocation entries (if any)
1921 // for an entry for this section offset.
Rafael Espindola80291272014-10-08 15:28:58 +00001922 uint64_t sect_addr = info->S.getAddress();
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001923 uint64_t sect_offset = (Pc + Offset) - sect_addr;
1924 bool reloc_found = false;
1925 DataRefImpl Rel;
1926 MachO::any_relocation_info RE;
1927 bool isExtern = false;
1928 SymbolRef Symbol;
1929 for (const RelocationRef &Reloc : info->S.relocations()) {
Rafael Espindola96d071c2015-06-29 23:29:12 +00001930 uint64_t RelocOffset = Reloc.getOffset();
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001931 if (RelocOffset == sect_offset) {
1932 Rel = Reloc.getRawDataRefImpl();
1933 RE = info->O->getRelocation(Rel);
1934 // NOTE: Scattered relocations don't exist on x86_64.
1935 isExtern = info->O->getPlainRelocationExternal(RE);
1936 if (isExtern) {
1937 symbol_iterator RelocSym = Reloc.getSymbol();
1938 Symbol = *RelocSym;
1939 }
1940 reloc_found = true;
1941 break;
1942 }
1943 }
1944 if (reloc_found && isExtern) {
1945 // The Value passed in will be adjusted by the Pc if the instruction
1946 // adds the Pc. But for x86_64 external relocation entries the Value
1947 // is the offset from the external symbol.
1948 if (info->O->getAnyRelocationPCRel(RE))
1949 op_info->Value -= Pc + Offset + Size;
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00001950 Expected<StringRef> SymName = Symbol.getName();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00001951 if (!SymName)
1952 report_error(info->O->getFileName(), SymName.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00001953 const char *name = SymName->data();
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001954 unsigned Type = info->O->getAnyRelocationType(RE);
1955 if (Type == MachO::X86_64_RELOC_SUBTRACTOR) {
1956 DataRefImpl RelNext = Rel;
1957 info->O->moveRelocationNext(RelNext);
1958 MachO::any_relocation_info RENext = info->O->getRelocation(RelNext);
1959 unsigned TypeNext = info->O->getAnyRelocationType(RENext);
1960 bool isExternNext = info->O->getPlainRelocationExternal(RENext);
1961 unsigned SymbolNum = info->O->getPlainRelocationSymbolNum(RENext);
1962 if (TypeNext == MachO::X86_64_RELOC_UNSIGNED && isExternNext) {
1963 op_info->SubtractSymbol.Present = 1;
1964 op_info->SubtractSymbol.Name = name;
1965 symbol_iterator RelocSymNext = info->O->getSymbolByIndex(SymbolNum);
1966 Symbol = *RelocSymNext;
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00001967 Expected<StringRef> SymNameNext = Symbol.getName();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00001968 if (!SymNameNext)
1969 report_error(info->O->getFileName(), SymNameNext.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00001970 name = SymNameNext->data();
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001971 }
1972 }
1973 // TODO: add the VariantKinds to op_info->VariantKind for relocation types
1974 // like: X86_64_RELOC_TLV, X86_64_RELOC_GOT_LOAD and X86_64_RELOC_GOT.
1975 op_info->AddSymbol.Present = 1;
1976 op_info->AddSymbol.Name = name;
1977 return 1;
1978 }
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001979 return 0;
David Blaikie33dd45d02015-03-23 18:39:02 +00001980 }
1981 if (Arch == Triple::arm) {
Kevin Enderby930fdc72014-11-06 19:00:13 +00001982 if (Offset != 0 || (Size != 4 && Size != 2))
1983 return 0;
Kevin Enderbyd90a4172015-10-10 00:05:01 +00001984 if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
1985 // TODO:
1986 // Search the external relocation entries of a fully linked image
1987 // (if any) for an entry that matches this segment offset.
1988 // uint32_t seg_offset = (Pc + Offset);
1989 return 0;
1990 }
1991 // In MH_OBJECT filetypes search the section's relocation entries (if any)
1992 // for an entry for this section offset.
Kevin Enderby930fdc72014-11-06 19:00:13 +00001993 uint32_t sect_addr = info->S.getAddress();
1994 uint32_t sect_offset = (Pc + Offset) - sect_addr;
Kevin Enderby930fdc72014-11-06 19:00:13 +00001995 DataRefImpl Rel;
1996 MachO::any_relocation_info RE;
1997 bool isExtern = false;
1998 SymbolRef Symbol;
1999 bool r_scattered = false;
2000 uint32_t r_value, pair_r_value, r_type, r_length, other_half;
David Blaikie33dd45d02015-03-23 18:39:02 +00002001 auto Reloc =
David Majnemer562e8292016-08-12 00:18:03 +00002002 find_if(info->S.relocations(), [&](const RelocationRef &Reloc) {
2003 uint64_t RelocOffset = Reloc.getOffset();
2004 return RelocOffset == sect_offset;
2005 });
David Blaikie33dd45d02015-03-23 18:39:02 +00002006
2007 if (Reloc == info->S.relocations().end())
2008 return 0;
2009
2010 Rel = Reloc->getRawDataRefImpl();
2011 RE = info->O->getRelocation(Rel);
2012 r_length = info->O->getAnyRelocationLength(RE);
2013 r_scattered = info->O->isRelocationScattered(RE);
2014 if (r_scattered) {
2015 r_value = info->O->getScatteredRelocationValue(RE);
2016 r_type = info->O->getScatteredRelocationType(RE);
2017 } else {
2018 r_type = info->O->getAnyRelocationType(RE);
2019 isExtern = info->O->getPlainRelocationExternal(RE);
2020 if (isExtern) {
2021 symbol_iterator RelocSym = Reloc->getSymbol();
2022 Symbol = *RelocSym;
Kevin Enderby930fdc72014-11-06 19:00:13 +00002023 }
2024 }
David Blaikie33dd45d02015-03-23 18:39:02 +00002025 if (r_type == MachO::ARM_RELOC_HALF ||
2026 r_type == MachO::ARM_RELOC_SECTDIFF ||
2027 r_type == MachO::ARM_RELOC_LOCAL_SECTDIFF ||
2028 r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
2029 DataRefImpl RelNext = Rel;
2030 info->O->moveRelocationNext(RelNext);
2031 MachO::any_relocation_info RENext;
2032 RENext = info->O->getRelocation(RelNext);
2033 other_half = info->O->getAnyRelocationAddress(RENext) & 0xffff;
2034 if (info->O->isRelocationScattered(RENext))
2035 pair_r_value = info->O->getScatteredRelocationValue(RENext);
2036 }
2037
2038 if (isExtern) {
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00002039 Expected<StringRef> SymName = Symbol.getName();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00002040 if (!SymName)
2041 report_error(info->O->getFileName(), SymName.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00002042 const char *name = SymName->data();
Kevin Enderby930fdc72014-11-06 19:00:13 +00002043 op_info->AddSymbol.Present = 1;
2044 op_info->AddSymbol.Name = name;
Sylvestre Ledru648cced2015-02-05 17:00:23 +00002045 switch (r_type) {
2046 case MachO::ARM_RELOC_HALF:
2047 if ((r_length & 0x1) == 1) {
2048 op_info->Value = value << 16 | other_half;
2049 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
2050 } else {
2051 op_info->Value = other_half << 16 | value;
2052 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
Sylvestre Ledrufe0c7ad2015-02-05 16:35:44 +00002053 }
Sylvestre Ledru648cced2015-02-05 17:00:23 +00002054 break;
2055 default:
2056 break;
Kevin Enderby930fdc72014-11-06 19:00:13 +00002057 }
2058 return 1;
2059 }
2060 // If we have a branch that is not an external relocation entry then
2061 // return 0 so the code in tryAddingSymbolicOperand() can use the
2062 // SymbolLookUp call back with the branch target address to look up the
Simon Pilgrimdae11f72016-11-20 13:31:13 +00002063 // symbol and possibility add an annotation for a symbol stub.
David Blaikie33dd45d02015-03-23 18:39:02 +00002064 if (isExtern == 0 && (r_type == MachO::ARM_RELOC_BR24 ||
2065 r_type == MachO::ARM_THUMB_RELOC_BR22))
Kevin Enderby930fdc72014-11-06 19:00:13 +00002066 return 0;
2067
2068 uint32_t offset = 0;
David Blaikie33dd45d02015-03-23 18:39:02 +00002069 if (r_type == MachO::ARM_RELOC_HALF ||
2070 r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
2071 if ((r_length & 0x1) == 1)
2072 value = value << 16 | other_half;
2073 else
2074 value = other_half << 16 | value;
2075 }
2076 if (r_scattered && (r_type != MachO::ARM_RELOC_HALF &&
2077 r_type != MachO::ARM_RELOC_HALF_SECTDIFF)) {
2078 offset = value - r_value;
2079 value = r_value;
Kevin Enderby930fdc72014-11-06 19:00:13 +00002080 }
2081
David Blaikie33dd45d02015-03-23 18:39:02 +00002082 if (r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
Kevin Enderby930fdc72014-11-06 19:00:13 +00002083 if ((r_length & 0x1) == 1)
2084 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
2085 else
2086 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
Kevin Enderbyf6d25852015-01-31 00:37:11 +00002087 const char *add = GuessSymbolName(r_value, info->AddrMap);
2088 const char *sub = GuessSymbolName(pair_r_value, info->AddrMap);
Kevin Enderby930fdc72014-11-06 19:00:13 +00002089 int32_t offset = value - (r_value - pair_r_value);
2090 op_info->AddSymbol.Present = 1;
2091 if (add != nullptr)
2092 op_info->AddSymbol.Name = add;
2093 else
2094 op_info->AddSymbol.Value = r_value;
2095 op_info->SubtractSymbol.Present = 1;
2096 if (sub != nullptr)
2097 op_info->SubtractSymbol.Name = sub;
2098 else
2099 op_info->SubtractSymbol.Value = pair_r_value;
2100 op_info->Value = offset;
2101 return 1;
2102 }
2103
Kevin Enderby930fdc72014-11-06 19:00:13 +00002104 op_info->AddSymbol.Present = 1;
2105 op_info->Value = offset;
David Blaikie33dd45d02015-03-23 18:39:02 +00002106 if (r_type == MachO::ARM_RELOC_HALF) {
2107 if ((r_length & 0x1) == 1)
2108 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
2109 else
2110 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
Kevin Enderby930fdc72014-11-06 19:00:13 +00002111 }
Kevin Enderbyf6d25852015-01-31 00:37:11 +00002112 const char *add = GuessSymbolName(value, info->AddrMap);
Kevin Enderby930fdc72014-11-06 19:00:13 +00002113 if (add != nullptr) {
2114 op_info->AddSymbol.Name = add;
2115 return 1;
2116 }
2117 op_info->AddSymbol.Value = value;
2118 return 1;
David Blaikie33dd45d02015-03-23 18:39:02 +00002119 }
2120 if (Arch == Triple::aarch64) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002121 if (Offset != 0 || Size != 4)
2122 return 0;
Kevin Enderbyd90a4172015-10-10 00:05:01 +00002123 if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
2124 // TODO:
2125 // Search the external relocation entries of a fully linked image
2126 // (if any) for an entry that matches this segment offset.
2127 // uint64_t seg_offset = (Pc + Offset);
2128 return 0;
2129 }
2130 // In MH_OBJECT filetypes search the section's relocation entries (if any)
2131 // for an entry for this section offset.
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002132 uint64_t sect_addr = info->S.getAddress();
2133 uint64_t sect_offset = (Pc + Offset) - sect_addr;
David Blaikie33dd45d02015-03-23 18:39:02 +00002134 auto Reloc =
David Majnemer562e8292016-08-12 00:18:03 +00002135 find_if(info->S.relocations(), [&](const RelocationRef &Reloc) {
2136 uint64_t RelocOffset = Reloc.getOffset();
2137 return RelocOffset == sect_offset;
2138 });
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002139
David Blaikie33dd45d02015-03-23 18:39:02 +00002140 if (Reloc == info->S.relocations().end())
2141 return 0;
2142
2143 DataRefImpl Rel = Reloc->getRawDataRefImpl();
2144 MachO::any_relocation_info RE = info->O->getRelocation(Rel);
2145 uint32_t r_type = info->O->getAnyRelocationType(RE);
2146 if (r_type == MachO::ARM64_RELOC_ADDEND) {
2147 DataRefImpl RelNext = Rel;
2148 info->O->moveRelocationNext(RelNext);
2149 MachO::any_relocation_info RENext = info->O->getRelocation(RelNext);
2150 if (value == 0) {
2151 value = info->O->getPlainRelocationSymbolNum(RENext);
2152 op_info->Value = value;
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002153 }
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002154 }
David Blaikie33dd45d02015-03-23 18:39:02 +00002155 // NOTE: Scattered relocations don't exist on arm64.
2156 if (!info->O->getPlainRelocationExternal(RE))
2157 return 0;
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00002158 Expected<StringRef> SymName = Reloc->getSymbol()->getName();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00002159 if (!SymName)
2160 report_error(info->O->getFileName(), SymName.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00002161 const char *name = SymName->data();
David Blaikie33dd45d02015-03-23 18:39:02 +00002162 op_info->AddSymbol.Present = 1;
2163 op_info->AddSymbol.Name = name;
2164
2165 switch (r_type) {
2166 case MachO::ARM64_RELOC_PAGE21:
2167 /* @page */
2168 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_PAGE;
2169 break;
2170 case MachO::ARM64_RELOC_PAGEOFF12:
2171 /* @pageoff */
2172 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_PAGEOFF;
2173 break;
2174 case MachO::ARM64_RELOC_GOT_LOAD_PAGE21:
2175 /* @gotpage */
2176 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_GOTPAGE;
2177 break;
2178 case MachO::ARM64_RELOC_GOT_LOAD_PAGEOFF12:
2179 /* @gotpageoff */
2180 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_GOTPAGEOFF;
2181 break;
2182 case MachO::ARM64_RELOC_TLVP_LOAD_PAGE21:
2183 /* @tvlppage is not implemented in llvm-mc */
2184 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_TLVP;
2185 break;
2186 case MachO::ARM64_RELOC_TLVP_LOAD_PAGEOFF12:
2187 /* @tvlppageoff is not implemented in llvm-mc */
2188 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_TLVOFF;
2189 break;
2190 default:
2191 case MachO::ARM64_RELOC_BRANCH26:
2192 op_info->VariantKind = LLVMDisassembler_VariantKind_None;
2193 break;
2194 }
2195 return 1;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002196 }
David Blaikie33dd45d02015-03-23 18:39:02 +00002197 return 0;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002198}
2199
Kevin Enderbybf246f52014-09-24 23:08:22 +00002200// GuessCstringPointer is passed the address of what might be a pointer to a
2201// literal string in a cstring section. If that address is in a cstring section
2202// it returns a pointer to that string. Else it returns nullptr.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00002203static const char *GuessCstringPointer(uint64_t ReferenceValue,
2204 struct DisassembleInfo *info) {
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00002205 for (const auto &Load : info->O->load_commands()) {
Kevin Enderbybf246f52014-09-24 23:08:22 +00002206 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
2207 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
2208 for (unsigned J = 0; J < Seg.nsects; ++J) {
2209 MachO::section_64 Sec = info->O->getSection64(Load, J);
2210 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
2211 if (section_type == MachO::S_CSTRING_LITERALS &&
2212 ReferenceValue >= Sec.addr &&
2213 ReferenceValue < Sec.addr + Sec.size) {
2214 uint64_t sect_offset = ReferenceValue - Sec.addr;
2215 uint64_t object_offset = Sec.offset + sect_offset;
2216 StringRef MachOContents = info->O->getData();
2217 uint64_t object_size = MachOContents.size();
2218 const char *object_addr = (const char *)MachOContents.data();
2219 if (object_offset < object_size) {
2220 const char *name = object_addr + object_offset;
2221 return name;
2222 } else {
2223 return nullptr;
2224 }
2225 }
2226 }
2227 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
2228 MachO::segment_command Seg = info->O->getSegmentLoadCommand(Load);
2229 for (unsigned J = 0; J < Seg.nsects; ++J) {
2230 MachO::section Sec = info->O->getSection(Load, J);
2231 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
2232 if (section_type == MachO::S_CSTRING_LITERALS &&
2233 ReferenceValue >= Sec.addr &&
2234 ReferenceValue < Sec.addr + Sec.size) {
2235 uint64_t sect_offset = ReferenceValue - Sec.addr;
2236 uint64_t object_offset = Sec.offset + sect_offset;
2237 StringRef MachOContents = info->O->getData();
2238 uint64_t object_size = MachOContents.size();
2239 const char *object_addr = (const char *)MachOContents.data();
2240 if (object_offset < object_size) {
2241 const char *name = object_addr + object_offset;
2242 return name;
2243 } else {
2244 return nullptr;
2245 }
2246 }
2247 }
2248 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00002249 }
2250 return nullptr;
2251}
2252
Kevin Enderby85974882014-09-26 22:20:44 +00002253// GuessIndirectSymbol returns the name of the indirect symbol for the
2254// ReferenceValue passed in or nullptr. This is used when ReferenceValue maybe
2255// an address of a symbol stub or a lazy or non-lazy pointer to associate the
2256// symbol name being referenced by the stub or pointer.
2257static const char *GuessIndirectSymbol(uint64_t ReferenceValue,
2258 struct DisassembleInfo *info) {
Kevin Enderby85974882014-09-26 22:20:44 +00002259 MachO::dysymtab_command Dysymtab = info->O->getDysymtabLoadCommand();
2260 MachO::symtab_command Symtab = info->O->getSymtabLoadCommand();
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00002261 for (const auto &Load : info->O->load_commands()) {
Kevin Enderby85974882014-09-26 22:20:44 +00002262 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
2263 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
2264 for (unsigned J = 0; J < Seg.nsects; ++J) {
2265 MachO::section_64 Sec = info->O->getSection64(Load, J);
2266 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
2267 if ((section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
2268 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
2269 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
2270 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
2271 section_type == MachO::S_SYMBOL_STUBS) &&
2272 ReferenceValue >= Sec.addr &&
2273 ReferenceValue < Sec.addr + Sec.size) {
2274 uint32_t stride;
2275 if (section_type == MachO::S_SYMBOL_STUBS)
2276 stride = Sec.reserved2;
2277 else
2278 stride = 8;
2279 if (stride == 0)
2280 return nullptr;
2281 uint32_t index = Sec.reserved1 + (ReferenceValue - Sec.addr) / stride;
2282 if (index < Dysymtab.nindirectsyms) {
2283 uint32_t indirect_symbol =
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002284 info->O->getIndirectSymbolTableEntry(Dysymtab, index);
Kevin Enderby85974882014-09-26 22:20:44 +00002285 if (indirect_symbol < Symtab.nsyms) {
2286 symbol_iterator Sym = info->O->getSymbolByIndex(indirect_symbol);
2287 SymbolRef Symbol = *Sym;
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00002288 Expected<StringRef> SymName = Symbol.getName();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00002289 if (!SymName)
2290 report_error(info->O->getFileName(), SymName.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00002291 const char *name = SymName->data();
Kevin Enderby85974882014-09-26 22:20:44 +00002292 return name;
2293 }
2294 }
2295 }
2296 }
2297 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
2298 MachO::segment_command Seg = info->O->getSegmentLoadCommand(Load);
2299 for (unsigned J = 0; J < Seg.nsects; ++J) {
2300 MachO::section Sec = info->O->getSection(Load, J);
2301 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
2302 if ((section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
2303 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
2304 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
2305 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
2306 section_type == MachO::S_SYMBOL_STUBS) &&
2307 ReferenceValue >= Sec.addr &&
2308 ReferenceValue < Sec.addr + Sec.size) {
2309 uint32_t stride;
2310 if (section_type == MachO::S_SYMBOL_STUBS)
2311 stride = Sec.reserved2;
2312 else
2313 stride = 4;
2314 if (stride == 0)
2315 return nullptr;
2316 uint32_t index = Sec.reserved1 + (ReferenceValue - Sec.addr) / stride;
2317 if (index < Dysymtab.nindirectsyms) {
2318 uint32_t indirect_symbol =
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002319 info->O->getIndirectSymbolTableEntry(Dysymtab, index);
Kevin Enderby85974882014-09-26 22:20:44 +00002320 if (indirect_symbol < Symtab.nsyms) {
2321 symbol_iterator Sym = info->O->getSymbolByIndex(indirect_symbol);
2322 SymbolRef Symbol = *Sym;
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00002323 Expected<StringRef> SymName = Symbol.getName();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00002324 if (!SymName)
2325 report_error(info->O->getFileName(), SymName.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00002326 const char *name = SymName->data();
Kevin Enderby85974882014-09-26 22:20:44 +00002327 return name;
2328 }
2329 }
2330 }
2331 }
2332 }
Kevin Enderby85974882014-09-26 22:20:44 +00002333 }
2334 return nullptr;
2335}
2336
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002337// method_reference() is called passing it the ReferenceName that might be
2338// a reference it to an Objective-C method call. If so then it allocates and
2339// assembles a method call string with the values last seen and saved in
2340// the DisassembleInfo's class_name and selector_name fields. This is saved
2341// into the method field of the info and any previous string is free'ed.
2342// Then the class_name field in the info is set to nullptr. The method call
2343// string is set into ReferenceName and ReferenceType is set to
2344// LLVMDisassembler_ReferenceType_Out_Objc_Message. If this not a method call
2345// then both ReferenceType and ReferenceName are left unchanged.
2346static void method_reference(struct DisassembleInfo *info,
2347 uint64_t *ReferenceType,
2348 const char **ReferenceName) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002349 unsigned int Arch = info->O->getArch();
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002350 if (*ReferenceName != nullptr) {
2351 if (strcmp(*ReferenceName, "_objc_msgSend") == 0) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002352 if (info->selector_name != nullptr) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002353 if (info->method != nullptr)
2354 free(info->method);
2355 if (info->class_name != nullptr) {
2356 info->method = (char *)malloc(5 + strlen(info->class_name) +
2357 strlen(info->selector_name));
2358 if (info->method != nullptr) {
2359 strcpy(info->method, "+[");
2360 strcat(info->method, info->class_name);
2361 strcat(info->method, " ");
2362 strcat(info->method, info->selector_name);
2363 strcat(info->method, "]");
2364 *ReferenceName = info->method;
2365 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
2366 }
2367 } else {
2368 info->method = (char *)malloc(9 + strlen(info->selector_name));
2369 if (info->method != nullptr) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002370 if (Arch == Triple::x86_64)
2371 strcpy(info->method, "-[%rdi ");
2372 else if (Arch == Triple::aarch64)
2373 strcpy(info->method, "-[x0 ");
2374 else
2375 strcpy(info->method, "-[r? ");
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002376 strcat(info->method, info->selector_name);
2377 strcat(info->method, "]");
2378 *ReferenceName = info->method;
2379 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
2380 }
2381 }
2382 info->class_name = nullptr;
2383 }
2384 } else if (strcmp(*ReferenceName, "_objc_msgSendSuper2") == 0) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002385 if (info->selector_name != nullptr) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002386 if (info->method != nullptr)
2387 free(info->method);
2388 info->method = (char *)malloc(17 + strlen(info->selector_name));
2389 if (info->method != nullptr) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002390 if (Arch == Triple::x86_64)
2391 strcpy(info->method, "-[[%rdi super] ");
2392 else if (Arch == Triple::aarch64)
2393 strcpy(info->method, "-[[x0 super] ");
2394 else
2395 strcpy(info->method, "-[[r? super] ");
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002396 strcat(info->method, info->selector_name);
2397 strcat(info->method, "]");
2398 *ReferenceName = info->method;
2399 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
2400 }
2401 info->class_name = nullptr;
2402 }
2403 }
2404 }
2405}
2406
2407// GuessPointerPointer() is passed the address of what might be a pointer to
2408// a reference to an Objective-C class, selector, message ref or cfstring.
2409// If so the value of the pointer is returned and one of the booleans are set
2410// to true. If not zero is returned and all the booleans are set to false.
2411static uint64_t GuessPointerPointer(uint64_t ReferenceValue,
2412 struct DisassembleInfo *info,
2413 bool &classref, bool &selref, bool &msgref,
2414 bool &cfstring) {
2415 classref = false;
2416 selref = false;
2417 msgref = false;
2418 cfstring = false;
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00002419 for (const auto &Load : info->O->load_commands()) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002420 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
2421 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
2422 for (unsigned J = 0; J < Seg.nsects; ++J) {
2423 MachO::section_64 Sec = info->O->getSection64(Load, J);
2424 if ((strncmp(Sec.sectname, "__objc_selrefs", 16) == 0 ||
2425 strncmp(Sec.sectname, "__objc_classrefs", 16) == 0 ||
2426 strncmp(Sec.sectname, "__objc_superrefs", 16) == 0 ||
2427 strncmp(Sec.sectname, "__objc_msgrefs", 16) == 0 ||
2428 strncmp(Sec.sectname, "__cfstring", 16) == 0) &&
2429 ReferenceValue >= Sec.addr &&
2430 ReferenceValue < Sec.addr + Sec.size) {
2431 uint64_t sect_offset = ReferenceValue - Sec.addr;
2432 uint64_t object_offset = Sec.offset + sect_offset;
2433 StringRef MachOContents = info->O->getData();
2434 uint64_t object_size = MachOContents.size();
2435 const char *object_addr = (const char *)MachOContents.data();
2436 if (object_offset < object_size) {
2437 uint64_t pointer_value;
2438 memcpy(&pointer_value, object_addr + object_offset,
2439 sizeof(uint64_t));
2440 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
2441 sys::swapByteOrder(pointer_value);
2442 if (strncmp(Sec.sectname, "__objc_selrefs", 16) == 0)
2443 selref = true;
2444 else if (strncmp(Sec.sectname, "__objc_classrefs", 16) == 0 ||
2445 strncmp(Sec.sectname, "__objc_superrefs", 16) == 0)
2446 classref = true;
2447 else if (strncmp(Sec.sectname, "__objc_msgrefs", 16) == 0 &&
2448 ReferenceValue + 8 < Sec.addr + Sec.size) {
2449 msgref = true;
2450 memcpy(&pointer_value, object_addr + object_offset + 8,
2451 sizeof(uint64_t));
2452 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
2453 sys::swapByteOrder(pointer_value);
2454 } else if (strncmp(Sec.sectname, "__cfstring", 16) == 0)
2455 cfstring = true;
2456 return pointer_value;
2457 } else {
2458 return 0;
2459 }
2460 }
2461 }
2462 }
2463 // TODO: Look for LC_SEGMENT for 32-bit Mach-O files.
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002464 }
2465 return 0;
2466}
2467
2468// get_pointer_64 returns a pointer to the bytes in the object file at the
2469// Address from a section in the Mach-O file. And indirectly returns the
2470// offset into the section, number of bytes left in the section past the offset
2471// and which section is was being referenced. If the Address is not in a
2472// section nullptr is returned.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00002473static const char *get_pointer_64(uint64_t Address, uint32_t &offset,
2474 uint32_t &left, SectionRef &S,
Kevin Enderby846c0002015-04-16 17:19:59 +00002475 DisassembleInfo *info,
2476 bool objc_only = false) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002477 offset = 0;
2478 left = 0;
2479 S = SectionRef();
2480 for (unsigned SectIdx = 0; SectIdx != info->Sections->size(); SectIdx++) {
2481 uint64_t SectAddress = ((*(info->Sections))[SectIdx]).getAddress();
2482 uint64_t SectSize = ((*(info->Sections))[SectIdx]).getSize();
Kevin Enderby46e642f2015-10-08 22:50:55 +00002483 if (SectSize == 0)
2484 continue;
Kevin Enderby846c0002015-04-16 17:19:59 +00002485 if (objc_only) {
2486 StringRef SectName;
2487 ((*(info->Sections))[SectIdx]).getName(SectName);
2488 DataRefImpl Ref = ((*(info->Sections))[SectIdx]).getRawDataRefImpl();
2489 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
2490 if (SegName != "__OBJC" && SectName != "__cstring")
2491 continue;
2492 }
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002493 if (Address >= SectAddress && Address < SectAddress + SectSize) {
2494 S = (*(info->Sections))[SectIdx];
2495 offset = Address - SectAddress;
2496 left = SectSize - offset;
2497 StringRef SectContents;
2498 ((*(info->Sections))[SectIdx]).getContents(SectContents);
2499 return SectContents.data() + offset;
2500 }
2501 }
2502 return nullptr;
2503}
2504
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002505static const char *get_pointer_32(uint32_t Address, uint32_t &offset,
2506 uint32_t &left, SectionRef &S,
Kevin Enderby846c0002015-04-16 17:19:59 +00002507 DisassembleInfo *info,
2508 bool objc_only = false) {
2509 return get_pointer_64(Address, offset, left, S, info, objc_only);
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002510}
2511
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002512// get_symbol_64() returns the name of a symbol (or nullptr) and the address of
2513// the symbol indirectly through n_value. Based on the relocation information
2514// for the specified section offset in the specified section reference.
Kevin Enderby0fc11822015-04-01 20:57:01 +00002515// If no relocation information is found and a non-zero ReferenceValue for the
2516// symbol is passed, look up that address in the info's AddrMap.
Rafael Espindolad7a32ea2015-06-24 10:20:30 +00002517static const char *get_symbol_64(uint32_t sect_offset, SectionRef S,
2518 DisassembleInfo *info, uint64_t &n_value,
Rafael Espindolabe8b0ea2015-07-07 17:12:59 +00002519 uint64_t ReferenceValue = 0) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002520 n_value = 0;
David Blaikie33dd45d02015-03-23 18:39:02 +00002521 if (!info->verbose)
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002522 return nullptr;
2523
2524 // See if there is an external relocation entry at the sect_offset.
2525 bool reloc_found = false;
2526 DataRefImpl Rel;
2527 MachO::any_relocation_info RE;
2528 bool isExtern = false;
2529 SymbolRef Symbol;
2530 for (const RelocationRef &Reloc : S.relocations()) {
Rafael Espindola96d071c2015-06-29 23:29:12 +00002531 uint64_t RelocOffset = Reloc.getOffset();
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002532 if (RelocOffset == sect_offset) {
2533 Rel = Reloc.getRawDataRefImpl();
2534 RE = info->O->getRelocation(Rel);
2535 if (info->O->isRelocationScattered(RE))
2536 continue;
2537 isExtern = info->O->getPlainRelocationExternal(RE);
2538 if (isExtern) {
2539 symbol_iterator RelocSym = Reloc.getSymbol();
2540 Symbol = *RelocSym;
2541 }
2542 reloc_found = true;
2543 break;
2544 }
2545 }
2546 // If there is an external relocation entry for a symbol in this section
2547 // at this section_offset then use that symbol's value for the n_value
2548 // and return its name.
2549 const char *SymbolName = nullptr;
2550 if (reloc_found && isExtern) {
Rafael Espindoladea00162015-07-03 17:44:18 +00002551 n_value = Symbol.getValue();
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00002552 Expected<StringRef> NameOrError = Symbol.getName();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00002553 if (!NameOrError)
2554 report_error(info->O->getFileName(), NameOrError.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00002555 StringRef Name = *NameOrError;
2556 if (!Name.empty()) {
2557 SymbolName = Name.data();
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002558 return SymbolName;
2559 }
2560 }
2561
2562 // TODO: For fully linked images, look through the external relocation
2563 // entries off the dynamic symtab command. For these the r_offset is from the
2564 // start of the first writeable segment in the Mach-O file. So the offset
2565 // to this section from that segment is passed to this routine by the caller,
2566 // as the database_offset. Which is the difference of the section's starting
2567 // address and the first writable segment.
2568 //
2569 // NOTE: need add passing the database_offset to this routine.
2570
Kevin Enderby0fc11822015-04-01 20:57:01 +00002571 // We did not find an external relocation entry so look up the ReferenceValue
2572 // as an address of a symbol and if found return that symbol's name.
Rafael Espindolabe8b0ea2015-07-07 17:12:59 +00002573 SymbolName = GuessSymbolName(ReferenceValue, info->AddrMap);
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002574
2575 return SymbolName;
2576}
2577
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002578static const char *get_symbol_32(uint32_t sect_offset, SectionRef S,
2579 DisassembleInfo *info,
2580 uint32_t ReferenceValue) {
2581 uint64_t n_value64;
2582 return get_symbol_64(sect_offset, S, info, n_value64, ReferenceValue);
2583}
2584
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002585// These are structs in the Objective-C meta data and read to produce the
2586// comments for disassembly. While these are part of the ABI they are no
2587// public defintions. So the are here not in include/llvm/Support/MachO.h .
2588
2589// The cfstring object in a 64-bit Mach-O file.
2590struct cfstring64_t {
2591 uint64_t isa; // class64_t * (64-bit pointer)
2592 uint64_t flags; // flag bits
2593 uint64_t characters; // char * (64-bit pointer)
2594 uint64_t length; // number of non-NULL characters in above
2595};
2596
2597// The class object in a 64-bit Mach-O file.
2598struct class64_t {
2599 uint64_t isa; // class64_t * (64-bit pointer)
2600 uint64_t superclass; // class64_t * (64-bit pointer)
2601 uint64_t cache; // Cache (64-bit pointer)
2602 uint64_t vtable; // IMP * (64-bit pointer)
2603 uint64_t data; // class_ro64_t * (64-bit pointer)
2604};
2605
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002606struct class32_t {
2607 uint32_t isa; /* class32_t * (32-bit pointer) */
2608 uint32_t superclass; /* class32_t * (32-bit pointer) */
2609 uint32_t cache; /* Cache (32-bit pointer) */
2610 uint32_t vtable; /* IMP * (32-bit pointer) */
2611 uint32_t data; /* class_ro32_t * (32-bit pointer) */
2612};
2613
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002614struct class_ro64_t {
2615 uint32_t flags;
2616 uint32_t instanceStart;
2617 uint32_t instanceSize;
2618 uint32_t reserved;
2619 uint64_t ivarLayout; // const uint8_t * (64-bit pointer)
2620 uint64_t name; // const char * (64-bit pointer)
2621 uint64_t baseMethods; // const method_list_t * (64-bit pointer)
2622 uint64_t baseProtocols; // const protocol_list_t * (64-bit pointer)
2623 uint64_t ivars; // const ivar_list_t * (64-bit pointer)
2624 uint64_t weakIvarLayout; // const uint8_t * (64-bit pointer)
2625 uint64_t baseProperties; // const struct objc_property_list (64-bit pointer)
2626};
2627
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002628struct class_ro32_t {
2629 uint32_t flags;
2630 uint32_t instanceStart;
2631 uint32_t instanceSize;
2632 uint32_t ivarLayout; /* const uint8_t * (32-bit pointer) */
2633 uint32_t name; /* const char * (32-bit pointer) */
2634 uint32_t baseMethods; /* const method_list_t * (32-bit pointer) */
2635 uint32_t baseProtocols; /* const protocol_list_t * (32-bit pointer) */
2636 uint32_t ivars; /* const ivar_list_t * (32-bit pointer) */
2637 uint32_t weakIvarLayout; /* const uint8_t * (32-bit pointer) */
2638 uint32_t baseProperties; /* const struct objc_property_list *
2639 (32-bit pointer) */
2640};
2641
2642/* Values for class_ro{64,32}_t->flags */
Kevin Enderby0fc11822015-04-01 20:57:01 +00002643#define RO_META (1 << 0)
2644#define RO_ROOT (1 << 1)
2645#define RO_HAS_CXX_STRUCTORS (1 << 2)
2646
2647struct method_list64_t {
2648 uint32_t entsize;
2649 uint32_t count;
2650 /* struct method64_t first; These structures follow inline */
2651};
2652
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002653struct method_list32_t {
2654 uint32_t entsize;
2655 uint32_t count;
2656 /* struct method32_t first; These structures follow inline */
2657};
2658
Kevin Enderby0fc11822015-04-01 20:57:01 +00002659struct method64_t {
2660 uint64_t name; /* SEL (64-bit pointer) */
2661 uint64_t types; /* const char * (64-bit pointer) */
2662 uint64_t imp; /* IMP (64-bit pointer) */
2663};
2664
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002665struct method32_t {
2666 uint32_t name; /* SEL (32-bit pointer) */
2667 uint32_t types; /* const char * (32-bit pointer) */
2668 uint32_t imp; /* IMP (32-bit pointer) */
2669};
2670
Kevin Enderby0fc11822015-04-01 20:57:01 +00002671struct protocol_list64_t {
2672 uint64_t count; /* uintptr_t (a 64-bit value) */
2673 /* struct protocol64_t * list[0]; These pointers follow inline */
2674};
2675
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002676struct protocol_list32_t {
2677 uint32_t count; /* uintptr_t (a 32-bit value) */
2678 /* struct protocol32_t * list[0]; These pointers follow inline */
2679};
2680
Kevin Enderby0fc11822015-04-01 20:57:01 +00002681struct protocol64_t {
2682 uint64_t isa; /* id * (64-bit pointer) */
2683 uint64_t name; /* const char * (64-bit pointer) */
2684 uint64_t protocols; /* struct protocol_list64_t *
2685 (64-bit pointer) */
2686 uint64_t instanceMethods; /* method_list_t * (64-bit pointer) */
2687 uint64_t classMethods; /* method_list_t * (64-bit pointer) */
2688 uint64_t optionalInstanceMethods; /* method_list_t * (64-bit pointer) */
2689 uint64_t optionalClassMethods; /* method_list_t * (64-bit pointer) */
2690 uint64_t instanceProperties; /* struct objc_property_list *
2691 (64-bit pointer) */
2692};
2693
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002694struct protocol32_t {
2695 uint32_t isa; /* id * (32-bit pointer) */
2696 uint32_t name; /* const char * (32-bit pointer) */
2697 uint32_t protocols; /* struct protocol_list_t *
2698 (32-bit pointer) */
2699 uint32_t instanceMethods; /* method_list_t * (32-bit pointer) */
2700 uint32_t classMethods; /* method_list_t * (32-bit pointer) */
2701 uint32_t optionalInstanceMethods; /* method_list_t * (32-bit pointer) */
2702 uint32_t optionalClassMethods; /* method_list_t * (32-bit pointer) */
2703 uint32_t instanceProperties; /* struct objc_property_list *
2704 (32-bit pointer) */
2705};
2706
Kevin Enderby0fc11822015-04-01 20:57:01 +00002707struct ivar_list64_t {
2708 uint32_t entsize;
2709 uint32_t count;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002710 /* struct ivar64_t first; These structures follow inline */
2711};
2712
2713struct ivar_list32_t {
2714 uint32_t entsize;
2715 uint32_t count;
2716 /* struct ivar32_t first; These structures follow inline */
Kevin Enderby0fc11822015-04-01 20:57:01 +00002717};
2718
2719struct ivar64_t {
2720 uint64_t offset; /* uintptr_t * (64-bit pointer) */
2721 uint64_t name; /* const char * (64-bit pointer) */
2722 uint64_t type; /* const char * (64-bit pointer) */
2723 uint32_t alignment;
2724 uint32_t size;
2725};
2726
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002727struct ivar32_t {
2728 uint32_t offset; /* uintptr_t * (32-bit pointer) */
2729 uint32_t name; /* const char * (32-bit pointer) */
2730 uint32_t type; /* const char * (32-bit pointer) */
2731 uint32_t alignment;
2732 uint32_t size;
2733};
2734
Kevin Enderby0fc11822015-04-01 20:57:01 +00002735struct objc_property_list64 {
2736 uint32_t entsize;
2737 uint32_t count;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002738 /* struct objc_property64 first; These structures follow inline */
2739};
2740
2741struct objc_property_list32 {
2742 uint32_t entsize;
2743 uint32_t count;
2744 /* struct objc_property32 first; These structures follow inline */
Kevin Enderby0fc11822015-04-01 20:57:01 +00002745};
2746
2747struct objc_property64 {
2748 uint64_t name; /* const char * (64-bit pointer) */
2749 uint64_t attributes; /* const char * (64-bit pointer) */
2750};
2751
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002752struct objc_property32 {
2753 uint32_t name; /* const char * (32-bit pointer) */
2754 uint32_t attributes; /* const char * (32-bit pointer) */
2755};
2756
Kevin Enderby0fc11822015-04-01 20:57:01 +00002757struct category64_t {
2758 uint64_t name; /* const char * (64-bit pointer) */
2759 uint64_t cls; /* struct class_t * (64-bit pointer) */
2760 uint64_t instanceMethods; /* struct method_list_t * (64-bit pointer) */
2761 uint64_t classMethods; /* struct method_list_t * (64-bit pointer) */
2762 uint64_t protocols; /* struct protocol_list_t * (64-bit pointer) */
2763 uint64_t instanceProperties; /* struct objc_property_list *
2764 (64-bit pointer) */
2765};
2766
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002767struct category32_t {
2768 uint32_t name; /* const char * (32-bit pointer) */
2769 uint32_t cls; /* struct class_t * (32-bit pointer) */
2770 uint32_t instanceMethods; /* struct method_list_t * (32-bit pointer) */
2771 uint32_t classMethods; /* struct method_list_t * (32-bit pointer) */
2772 uint32_t protocols; /* struct protocol_list_t * (32-bit pointer) */
2773 uint32_t instanceProperties; /* struct objc_property_list *
2774 (32-bit pointer) */
2775};
2776
Kevin Enderby0fc11822015-04-01 20:57:01 +00002777struct objc_image_info64 {
2778 uint32_t version;
2779 uint32_t flags;
2780};
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002781struct objc_image_info32 {
2782 uint32_t version;
2783 uint32_t flags;
2784};
Kevin Enderby846c0002015-04-16 17:19:59 +00002785struct imageInfo_t {
2786 uint32_t version;
2787 uint32_t flags;
2788};
Kevin Enderby0fc11822015-04-01 20:57:01 +00002789/* masks for objc_image_info.flags */
2790#define OBJC_IMAGE_IS_REPLACEMENT (1 << 0)
2791#define OBJC_IMAGE_SUPPORTS_GC (1 << 1)
2792
2793struct message_ref64 {
2794 uint64_t imp; /* IMP (64-bit pointer) */
2795 uint64_t sel; /* SEL (64-bit pointer) */
2796};
2797
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002798struct message_ref32 {
2799 uint32_t imp; /* IMP (32-bit pointer) */
2800 uint32_t sel; /* SEL (32-bit pointer) */
2801};
2802
Kevin Enderby846c0002015-04-16 17:19:59 +00002803// Objective-C 1 (32-bit only) meta data structs.
2804
2805struct objc_module_t {
2806 uint32_t version;
2807 uint32_t size;
2808 uint32_t name; /* char * (32-bit pointer) */
2809 uint32_t symtab; /* struct objc_symtab * (32-bit pointer) */
2810};
2811
2812struct objc_symtab_t {
2813 uint32_t sel_ref_cnt;
2814 uint32_t refs; /* SEL * (32-bit pointer) */
2815 uint16_t cls_def_cnt;
2816 uint16_t cat_def_cnt;
2817 // uint32_t defs[1]; /* void * (32-bit pointer) variable size */
2818};
2819
2820struct objc_class_t {
2821 uint32_t isa; /* struct objc_class * (32-bit pointer) */
2822 uint32_t super_class; /* struct objc_class * (32-bit pointer) */
2823 uint32_t name; /* const char * (32-bit pointer) */
2824 int32_t version;
2825 int32_t info;
2826 int32_t instance_size;
2827 uint32_t ivars; /* struct objc_ivar_list * (32-bit pointer) */
2828 uint32_t methodLists; /* struct objc_method_list ** (32-bit pointer) */
2829 uint32_t cache; /* struct objc_cache * (32-bit pointer) */
2830 uint32_t protocols; /* struct objc_protocol_list * (32-bit pointer) */
2831};
2832
2833#define CLS_GETINFO(cls, infomask) ((cls)->info & (infomask))
2834// class is not a metaclass
2835#define CLS_CLASS 0x1
2836// class is a metaclass
2837#define CLS_META 0x2
2838
2839struct objc_category_t {
2840 uint32_t category_name; /* char * (32-bit pointer) */
2841 uint32_t class_name; /* char * (32-bit pointer) */
2842 uint32_t instance_methods; /* struct objc_method_list * (32-bit pointer) */
2843 uint32_t class_methods; /* struct objc_method_list * (32-bit pointer) */
2844 uint32_t protocols; /* struct objc_protocol_list * (32-bit ptr) */
2845};
2846
2847struct objc_ivar_t {
2848 uint32_t ivar_name; /* char * (32-bit pointer) */
2849 uint32_t ivar_type; /* char * (32-bit pointer) */
2850 int32_t ivar_offset;
2851};
2852
2853struct objc_ivar_list_t {
2854 int32_t ivar_count;
2855 // struct objc_ivar_t ivar_list[1]; /* variable length structure */
2856};
2857
2858struct objc_method_list_t {
2859 uint32_t obsolete; /* struct objc_method_list * (32-bit pointer) */
2860 int32_t method_count;
2861 // struct objc_method_t method_list[1]; /* variable length structure */
2862};
2863
2864struct objc_method_t {
2865 uint32_t method_name; /* SEL, aka struct objc_selector * (32-bit pointer) */
2866 uint32_t method_types; /* char * (32-bit pointer) */
2867 uint32_t method_imp; /* IMP, aka function pointer, (*IMP)(id, SEL, ...)
2868 (32-bit pointer) */
2869};
2870
2871struct objc_protocol_list_t {
2872 uint32_t next; /* struct objc_protocol_list * (32-bit pointer) */
2873 int32_t count;
2874 // uint32_t list[1]; /* Protocol *, aka struct objc_protocol_t *
2875 // (32-bit pointer) */
2876};
2877
2878struct objc_protocol_t {
2879 uint32_t isa; /* struct objc_class * (32-bit pointer) */
2880 uint32_t protocol_name; /* char * (32-bit pointer) */
2881 uint32_t protocol_list; /* struct objc_protocol_list * (32-bit pointer) */
2882 uint32_t instance_methods; /* struct objc_method_description_list *
2883 (32-bit pointer) */
2884 uint32_t class_methods; /* struct objc_method_description_list *
2885 (32-bit pointer) */
2886};
2887
2888struct objc_method_description_list_t {
2889 int32_t count;
2890 // struct objc_method_description_t list[1];
2891};
2892
2893struct objc_method_description_t {
2894 uint32_t name; /* SEL, aka struct objc_selector * (32-bit pointer) */
2895 uint32_t types; /* char * (32-bit pointer) */
2896};
2897
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002898inline void swapStruct(struct cfstring64_t &cfs) {
2899 sys::swapByteOrder(cfs.isa);
2900 sys::swapByteOrder(cfs.flags);
2901 sys::swapByteOrder(cfs.characters);
2902 sys::swapByteOrder(cfs.length);
2903}
2904
2905inline void swapStruct(struct class64_t &c) {
2906 sys::swapByteOrder(c.isa);
2907 sys::swapByteOrder(c.superclass);
2908 sys::swapByteOrder(c.cache);
2909 sys::swapByteOrder(c.vtable);
2910 sys::swapByteOrder(c.data);
2911}
2912
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002913inline void swapStruct(struct class32_t &c) {
2914 sys::swapByteOrder(c.isa);
2915 sys::swapByteOrder(c.superclass);
2916 sys::swapByteOrder(c.cache);
2917 sys::swapByteOrder(c.vtable);
2918 sys::swapByteOrder(c.data);
2919}
2920
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002921inline void swapStruct(struct class_ro64_t &cro) {
2922 sys::swapByteOrder(cro.flags);
2923 sys::swapByteOrder(cro.instanceStart);
2924 sys::swapByteOrder(cro.instanceSize);
2925 sys::swapByteOrder(cro.reserved);
2926 sys::swapByteOrder(cro.ivarLayout);
2927 sys::swapByteOrder(cro.name);
2928 sys::swapByteOrder(cro.baseMethods);
2929 sys::swapByteOrder(cro.baseProtocols);
2930 sys::swapByteOrder(cro.ivars);
2931 sys::swapByteOrder(cro.weakIvarLayout);
2932 sys::swapByteOrder(cro.baseProperties);
2933}
2934
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002935inline void swapStruct(struct class_ro32_t &cro) {
2936 sys::swapByteOrder(cro.flags);
2937 sys::swapByteOrder(cro.instanceStart);
2938 sys::swapByteOrder(cro.instanceSize);
2939 sys::swapByteOrder(cro.ivarLayout);
2940 sys::swapByteOrder(cro.name);
2941 sys::swapByteOrder(cro.baseMethods);
2942 sys::swapByteOrder(cro.baseProtocols);
2943 sys::swapByteOrder(cro.ivars);
2944 sys::swapByteOrder(cro.weakIvarLayout);
2945 sys::swapByteOrder(cro.baseProperties);
2946}
2947
Kevin Enderby0fc11822015-04-01 20:57:01 +00002948inline void swapStruct(struct method_list64_t &ml) {
2949 sys::swapByteOrder(ml.entsize);
2950 sys::swapByteOrder(ml.count);
2951}
2952
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002953inline void swapStruct(struct method_list32_t &ml) {
2954 sys::swapByteOrder(ml.entsize);
2955 sys::swapByteOrder(ml.count);
2956}
2957
Kevin Enderby0fc11822015-04-01 20:57:01 +00002958inline void swapStruct(struct method64_t &m) {
2959 sys::swapByteOrder(m.name);
2960 sys::swapByteOrder(m.types);
2961 sys::swapByteOrder(m.imp);
2962}
2963
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002964inline void swapStruct(struct method32_t &m) {
2965 sys::swapByteOrder(m.name);
2966 sys::swapByteOrder(m.types);
2967 sys::swapByteOrder(m.imp);
2968}
2969
Kevin Enderby0fc11822015-04-01 20:57:01 +00002970inline void swapStruct(struct protocol_list64_t &pl) {
2971 sys::swapByteOrder(pl.count);
2972}
2973
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002974inline void swapStruct(struct protocol_list32_t &pl) {
2975 sys::swapByteOrder(pl.count);
2976}
2977
Kevin Enderby0fc11822015-04-01 20:57:01 +00002978inline void swapStruct(struct protocol64_t &p) {
2979 sys::swapByteOrder(p.isa);
2980 sys::swapByteOrder(p.name);
2981 sys::swapByteOrder(p.protocols);
2982 sys::swapByteOrder(p.instanceMethods);
2983 sys::swapByteOrder(p.classMethods);
2984 sys::swapByteOrder(p.optionalInstanceMethods);
2985 sys::swapByteOrder(p.optionalClassMethods);
2986 sys::swapByteOrder(p.instanceProperties);
2987}
2988
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002989inline void swapStruct(struct protocol32_t &p) {
2990 sys::swapByteOrder(p.isa);
2991 sys::swapByteOrder(p.name);
2992 sys::swapByteOrder(p.protocols);
2993 sys::swapByteOrder(p.instanceMethods);
2994 sys::swapByteOrder(p.classMethods);
2995 sys::swapByteOrder(p.optionalInstanceMethods);
2996 sys::swapByteOrder(p.optionalClassMethods);
2997 sys::swapByteOrder(p.instanceProperties);
2998}
2999
Kevin Enderby0fc11822015-04-01 20:57:01 +00003000inline void swapStruct(struct ivar_list64_t &il) {
3001 sys::swapByteOrder(il.entsize);
3002 sys::swapByteOrder(il.count);
3003}
3004
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003005inline void swapStruct(struct ivar_list32_t &il) {
3006 sys::swapByteOrder(il.entsize);
3007 sys::swapByteOrder(il.count);
3008}
3009
Kevin Enderby0fc11822015-04-01 20:57:01 +00003010inline void swapStruct(struct ivar64_t &i) {
3011 sys::swapByteOrder(i.offset);
3012 sys::swapByteOrder(i.name);
3013 sys::swapByteOrder(i.type);
3014 sys::swapByteOrder(i.alignment);
3015 sys::swapByteOrder(i.size);
3016}
3017
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003018inline void swapStruct(struct ivar32_t &i) {
3019 sys::swapByteOrder(i.offset);
3020 sys::swapByteOrder(i.name);
3021 sys::swapByteOrder(i.type);
3022 sys::swapByteOrder(i.alignment);
3023 sys::swapByteOrder(i.size);
3024}
3025
Kevin Enderby0fc11822015-04-01 20:57:01 +00003026inline void swapStruct(struct objc_property_list64 &pl) {
3027 sys::swapByteOrder(pl.entsize);
3028 sys::swapByteOrder(pl.count);
3029}
3030
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003031inline void swapStruct(struct objc_property_list32 &pl) {
3032 sys::swapByteOrder(pl.entsize);
3033 sys::swapByteOrder(pl.count);
3034}
3035
Kevin Enderby0fc11822015-04-01 20:57:01 +00003036inline void swapStruct(struct objc_property64 &op) {
3037 sys::swapByteOrder(op.name);
3038 sys::swapByteOrder(op.attributes);
3039}
3040
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003041inline void swapStruct(struct objc_property32 &op) {
3042 sys::swapByteOrder(op.name);
3043 sys::swapByteOrder(op.attributes);
3044}
3045
Kevin Enderby0fc11822015-04-01 20:57:01 +00003046inline void swapStruct(struct category64_t &c) {
3047 sys::swapByteOrder(c.name);
3048 sys::swapByteOrder(c.cls);
3049 sys::swapByteOrder(c.instanceMethods);
3050 sys::swapByteOrder(c.classMethods);
3051 sys::swapByteOrder(c.protocols);
3052 sys::swapByteOrder(c.instanceProperties);
3053}
3054
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003055inline void swapStruct(struct category32_t &c) {
3056 sys::swapByteOrder(c.name);
3057 sys::swapByteOrder(c.cls);
3058 sys::swapByteOrder(c.instanceMethods);
3059 sys::swapByteOrder(c.classMethods);
3060 sys::swapByteOrder(c.protocols);
3061 sys::swapByteOrder(c.instanceProperties);
3062}
3063
Kevin Enderby0fc11822015-04-01 20:57:01 +00003064inline void swapStruct(struct objc_image_info64 &o) {
3065 sys::swapByteOrder(o.version);
3066 sys::swapByteOrder(o.flags);
3067}
3068
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003069inline void swapStruct(struct objc_image_info32 &o) {
3070 sys::swapByteOrder(o.version);
3071 sys::swapByteOrder(o.flags);
3072}
3073
Kevin Enderby846c0002015-04-16 17:19:59 +00003074inline void swapStruct(struct imageInfo_t &o) {
3075 sys::swapByteOrder(o.version);
3076 sys::swapByteOrder(o.flags);
3077}
3078
Kevin Enderby0fc11822015-04-01 20:57:01 +00003079inline void swapStruct(struct message_ref64 &mr) {
3080 sys::swapByteOrder(mr.imp);
3081 sys::swapByteOrder(mr.sel);
3082}
3083
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003084inline void swapStruct(struct message_ref32 &mr) {
3085 sys::swapByteOrder(mr.imp);
3086 sys::swapByteOrder(mr.sel);
3087}
3088
Kevin Enderby846c0002015-04-16 17:19:59 +00003089inline void swapStruct(struct objc_module_t &module) {
3090 sys::swapByteOrder(module.version);
3091 sys::swapByteOrder(module.size);
3092 sys::swapByteOrder(module.name);
3093 sys::swapByteOrder(module.symtab);
Jingyue Wufedecc42015-04-16 18:43:44 +00003094}
Kevin Enderby846c0002015-04-16 17:19:59 +00003095
3096inline void swapStruct(struct objc_symtab_t &symtab) {
3097 sys::swapByteOrder(symtab.sel_ref_cnt);
3098 sys::swapByteOrder(symtab.refs);
3099 sys::swapByteOrder(symtab.cls_def_cnt);
3100 sys::swapByteOrder(symtab.cat_def_cnt);
Jingyue Wufedecc42015-04-16 18:43:44 +00003101}
Kevin Enderby846c0002015-04-16 17:19:59 +00003102
3103inline void swapStruct(struct objc_class_t &objc_class) {
3104 sys::swapByteOrder(objc_class.isa);
3105 sys::swapByteOrder(objc_class.super_class);
3106 sys::swapByteOrder(objc_class.name);
3107 sys::swapByteOrder(objc_class.version);
3108 sys::swapByteOrder(objc_class.info);
3109 sys::swapByteOrder(objc_class.instance_size);
3110 sys::swapByteOrder(objc_class.ivars);
3111 sys::swapByteOrder(objc_class.methodLists);
3112 sys::swapByteOrder(objc_class.cache);
3113 sys::swapByteOrder(objc_class.protocols);
Jingyue Wufedecc42015-04-16 18:43:44 +00003114}
Kevin Enderby846c0002015-04-16 17:19:59 +00003115
3116inline void swapStruct(struct objc_category_t &objc_category) {
3117 sys::swapByteOrder(objc_category.category_name);
3118 sys::swapByteOrder(objc_category.class_name);
3119 sys::swapByteOrder(objc_category.instance_methods);
3120 sys::swapByteOrder(objc_category.class_methods);
3121 sys::swapByteOrder(objc_category.protocols);
3122}
3123
3124inline void swapStruct(struct objc_ivar_list_t &objc_ivar_list) {
3125 sys::swapByteOrder(objc_ivar_list.ivar_count);
3126}
3127
3128inline void swapStruct(struct objc_ivar_t &objc_ivar) {
3129 sys::swapByteOrder(objc_ivar.ivar_name);
3130 sys::swapByteOrder(objc_ivar.ivar_type);
3131 sys::swapByteOrder(objc_ivar.ivar_offset);
Jingyue Wufedecc42015-04-16 18:43:44 +00003132}
Kevin Enderby846c0002015-04-16 17:19:59 +00003133
3134inline void swapStruct(struct objc_method_list_t &method_list) {
3135 sys::swapByteOrder(method_list.obsolete);
3136 sys::swapByteOrder(method_list.method_count);
3137}
3138
3139inline void swapStruct(struct objc_method_t &method) {
3140 sys::swapByteOrder(method.method_name);
3141 sys::swapByteOrder(method.method_types);
3142 sys::swapByteOrder(method.method_imp);
3143}
3144
3145inline void swapStruct(struct objc_protocol_list_t &protocol_list) {
3146 sys::swapByteOrder(protocol_list.next);
3147 sys::swapByteOrder(protocol_list.count);
3148}
3149
3150inline void swapStruct(struct objc_protocol_t &protocol) {
3151 sys::swapByteOrder(protocol.isa);
3152 sys::swapByteOrder(protocol.protocol_name);
3153 sys::swapByteOrder(protocol.protocol_list);
3154 sys::swapByteOrder(protocol.instance_methods);
3155 sys::swapByteOrder(protocol.class_methods);
3156}
3157
3158inline void swapStruct(struct objc_method_description_list_t &mdl) {
3159 sys::swapByteOrder(mdl.count);
3160}
3161
3162inline void swapStruct(struct objc_method_description_t &md) {
3163 sys::swapByteOrder(md.name);
3164 sys::swapByteOrder(md.types);
3165}
3166
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003167static const char *get_dyld_bind_info_symbolname(uint64_t ReferenceValue,
3168 struct DisassembleInfo *info);
3169
3170// get_objc2_64bit_class_name() is used for disassembly and is passed a pointer
3171// to an Objective-C class and returns the class name. It is also passed the
3172// address of the pointer, so when the pointer is zero as it can be in an .o
3173// file, that is used to look for an external relocation entry with a symbol
3174// name.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00003175static const char *get_objc2_64bit_class_name(uint64_t pointer_value,
3176 uint64_t ReferenceValue,
3177 struct DisassembleInfo *info) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003178 const char *r;
3179 uint32_t offset, left;
3180 SectionRef S;
3181
3182 // The pointer_value can be 0 in an object file and have a relocation
3183 // entry for the class symbol at the ReferenceValue (the address of the
3184 // pointer).
3185 if (pointer_value == 0) {
3186 r = get_pointer_64(ReferenceValue, offset, left, S, info);
3187 if (r == nullptr || left < sizeof(uint64_t))
3188 return nullptr;
3189 uint64_t n_value;
3190 const char *symbol_name = get_symbol_64(offset, S, info, n_value);
3191 if (symbol_name == nullptr)
3192 return nullptr;
Hans Wennborgdb53e302014-10-23 21:59:17 +00003193 const char *class_name = strrchr(symbol_name, '$');
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003194 if (class_name != nullptr && class_name[1] == '_' && class_name[2] != '\0')
3195 return class_name + 2;
3196 else
3197 return nullptr;
3198 }
3199
3200 // The case were the pointer_value is non-zero and points to a class defined
3201 // in this Mach-O file.
3202 r = get_pointer_64(pointer_value, offset, left, S, info);
3203 if (r == nullptr || left < sizeof(struct class64_t))
3204 return nullptr;
3205 struct class64_t c;
3206 memcpy(&c, r, sizeof(struct class64_t));
3207 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3208 swapStruct(c);
3209 if (c.data == 0)
3210 return nullptr;
3211 r = get_pointer_64(c.data, offset, left, S, info);
3212 if (r == nullptr || left < sizeof(struct class_ro64_t))
3213 return nullptr;
3214 struct class_ro64_t cro;
3215 memcpy(&cro, r, sizeof(struct class_ro64_t));
3216 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3217 swapStruct(cro);
3218 if (cro.name == 0)
3219 return nullptr;
3220 const char *name = get_pointer_64(cro.name, offset, left, S, info);
3221 return name;
3222}
3223
3224// get_objc2_64bit_cfstring_name is used for disassembly and is passed a
3225// pointer to a cfstring and returns its name or nullptr.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00003226static const char *get_objc2_64bit_cfstring_name(uint64_t ReferenceValue,
3227 struct DisassembleInfo *info) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003228 const char *r, *name;
3229 uint32_t offset, left;
3230 SectionRef S;
3231 struct cfstring64_t cfs;
3232 uint64_t cfs_characters;
3233
3234 r = get_pointer_64(ReferenceValue, offset, left, S, info);
3235 if (r == nullptr || left < sizeof(struct cfstring64_t))
3236 return nullptr;
3237 memcpy(&cfs, r, sizeof(struct cfstring64_t));
3238 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3239 swapStruct(cfs);
3240 if (cfs.characters == 0) {
3241 uint64_t n_value;
3242 const char *symbol_name = get_symbol_64(
3243 offset + offsetof(struct cfstring64_t, characters), S, info, n_value);
3244 if (symbol_name == nullptr)
3245 return nullptr;
3246 cfs_characters = n_value;
3247 } else
3248 cfs_characters = cfs.characters;
3249 name = get_pointer_64(cfs_characters, offset, left, S, info);
3250
3251 return name;
3252}
3253
3254// get_objc2_64bit_selref() is used for disassembly and is passed a the address
3255// of a pointer to an Objective-C selector reference when the pointer value is
3256// zero as in a .o file and is likely to have a external relocation entry with
3257// who's symbol's n_value is the real pointer to the selector name. If that is
3258// the case the real pointer to the selector name is returned else 0 is
3259// returned
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00003260static uint64_t get_objc2_64bit_selref(uint64_t ReferenceValue,
3261 struct DisassembleInfo *info) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003262 uint32_t offset, left;
3263 SectionRef S;
3264
3265 const char *r = get_pointer_64(ReferenceValue, offset, left, S, info);
3266 if (r == nullptr || left < sizeof(uint64_t))
3267 return 0;
3268 uint64_t n_value;
3269 const char *symbol_name = get_symbol_64(offset, S, info, n_value);
3270 if (symbol_name == nullptr)
3271 return 0;
3272 return n_value;
3273}
3274
Kevin Enderby0fc11822015-04-01 20:57:01 +00003275static const SectionRef get_section(MachOObjectFile *O, const char *segname,
3276 const char *sectname) {
3277 for (const SectionRef &Section : O->sections()) {
3278 StringRef SectName;
3279 Section.getName(SectName);
3280 DataRefImpl Ref = Section.getRawDataRefImpl();
3281 StringRef SegName = O->getSectionFinalSegmentName(Ref);
3282 if (SegName == segname && SectName == sectname)
3283 return Section;
3284 }
3285 return SectionRef();
3286}
3287
3288static void
3289walk_pointer_list_64(const char *listname, const SectionRef S,
3290 MachOObjectFile *O, struct DisassembleInfo *info,
3291 void (*func)(uint64_t, struct DisassembleInfo *info)) {
3292 if (S == SectionRef())
3293 return;
3294
3295 StringRef SectName;
3296 S.getName(SectName);
3297 DataRefImpl Ref = S.getRawDataRefImpl();
3298 StringRef SegName = O->getSectionFinalSegmentName(Ref);
3299 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
3300
3301 StringRef BytesStr;
3302 S.getContents(BytesStr);
3303 const char *Contents = reinterpret_cast<const char *>(BytesStr.data());
3304
3305 for (uint32_t i = 0; i < S.getSize(); i += sizeof(uint64_t)) {
3306 uint32_t left = S.getSize() - i;
3307 uint32_t size = left < sizeof(uint64_t) ? left : sizeof(uint64_t);
3308 uint64_t p = 0;
3309 memcpy(&p, Contents + i, size);
3310 if (i + sizeof(uint64_t) > S.getSize())
3311 outs() << listname << " list pointer extends past end of (" << SegName
3312 << "," << SectName << ") section\n";
3313 outs() << format("%016" PRIx64, S.getAddress() + i) << " ";
3314
3315 if (O->isLittleEndian() != sys::IsLittleEndianHost)
3316 sys::swapByteOrder(p);
3317
3318 uint64_t n_value = 0;
3319 const char *name = get_symbol_64(i, S, info, n_value, p);
3320 if (name == nullptr)
3321 name = get_dyld_bind_info_symbolname(S.getAddress() + i, info);
3322
3323 if (n_value != 0) {
3324 outs() << format("0x%" PRIx64, n_value);
3325 if (p != 0)
3326 outs() << " + " << format("0x%" PRIx64, p);
3327 } else
3328 outs() << format("0x%" PRIx64, p);
3329 if (name != nullptr)
3330 outs() << " " << name;
3331 outs() << "\n";
3332
3333 p += n_value;
3334 if (func)
3335 func(p, info);
3336 }
3337}
3338
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003339static void
3340walk_pointer_list_32(const char *listname, const SectionRef S,
3341 MachOObjectFile *O, struct DisassembleInfo *info,
3342 void (*func)(uint32_t, struct DisassembleInfo *info)) {
3343 if (S == SectionRef())
3344 return;
3345
3346 StringRef SectName;
3347 S.getName(SectName);
3348 DataRefImpl Ref = S.getRawDataRefImpl();
3349 StringRef SegName = O->getSectionFinalSegmentName(Ref);
3350 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
3351
3352 StringRef BytesStr;
3353 S.getContents(BytesStr);
3354 const char *Contents = reinterpret_cast<const char *>(BytesStr.data());
3355
3356 for (uint32_t i = 0; i < S.getSize(); i += sizeof(uint32_t)) {
3357 uint32_t left = S.getSize() - i;
3358 uint32_t size = left < sizeof(uint32_t) ? left : sizeof(uint32_t);
3359 uint32_t p = 0;
3360 memcpy(&p, Contents + i, size);
3361 if (i + sizeof(uint32_t) > S.getSize())
3362 outs() << listname << " list pointer extends past end of (" << SegName
3363 << "," << SectName << ") section\n";
Kevin Enderbycf261312015-04-06 22:33:43 +00003364 uint32_t Address = S.getAddress() + i;
3365 outs() << format("%08" PRIx32, Address) << " ";
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003366
3367 if (O->isLittleEndian() != sys::IsLittleEndianHost)
3368 sys::swapByteOrder(p);
3369 outs() << format("0x%" PRIx32, p);
3370
3371 const char *name = get_symbol_32(i, S, info, p);
3372 if (name != nullptr)
3373 outs() << " " << name;
3374 outs() << "\n";
3375
3376 if (func)
3377 func(p, info);
3378 }
3379}
3380
3381static void print_layout_map(const char *layout_map, uint32_t left) {
Kevin Enderbya59824a2015-10-06 22:27:08 +00003382 if (layout_map == nullptr)
3383 return;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003384 outs() << " layout map: ";
3385 do {
3386 outs() << format("0x%02" PRIx32, (*layout_map) & 0xff) << " ";
3387 left--;
3388 layout_map++;
3389 } while (*layout_map != '\0' && left != 0);
3390 outs() << "\n";
3391}
3392
Kevin Enderby0fc11822015-04-01 20:57:01 +00003393static void print_layout_map64(uint64_t p, struct DisassembleInfo *info) {
3394 uint32_t offset, left;
3395 SectionRef S;
3396 const char *layout_map;
3397
3398 if (p == 0)
3399 return;
3400 layout_map = get_pointer_64(p, offset, left, S, info);
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003401 print_layout_map(layout_map, left);
3402}
3403
3404static void print_layout_map32(uint32_t p, struct DisassembleInfo *info) {
3405 uint32_t offset, left;
3406 SectionRef S;
3407 const char *layout_map;
3408
3409 if (p == 0)
3410 return;
3411 layout_map = get_pointer_32(p, offset, left, S, info);
3412 print_layout_map(layout_map, left);
Kevin Enderby0fc11822015-04-01 20:57:01 +00003413}
3414
3415static void print_method_list64_t(uint64_t p, struct DisassembleInfo *info,
3416 const char *indent) {
3417 struct method_list64_t ml;
3418 struct method64_t m;
3419 const char *r;
3420 uint32_t offset, xoffset, left, i;
3421 SectionRef S, xS;
3422 const char *name, *sym_name;
3423 uint64_t n_value;
3424
3425 r = get_pointer_64(p, offset, left, S, info);
3426 if (r == nullptr)
3427 return;
3428 memset(&ml, '\0', sizeof(struct method_list64_t));
3429 if (left < sizeof(struct method_list64_t)) {
3430 memcpy(&ml, r, left);
3431 outs() << " (method_list_t entends past the end of the section)\n";
3432 } else
3433 memcpy(&ml, r, sizeof(struct method_list64_t));
3434 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3435 swapStruct(ml);
3436 outs() << indent << "\t\t entsize " << ml.entsize << "\n";
3437 outs() << indent << "\t\t count " << ml.count << "\n";
3438
3439 p += sizeof(struct method_list64_t);
3440 offset += sizeof(struct method_list64_t);
3441 for (i = 0; i < ml.count; i++) {
3442 r = get_pointer_64(p, offset, left, S, info);
3443 if (r == nullptr)
3444 return;
3445 memset(&m, '\0', sizeof(struct method64_t));
3446 if (left < sizeof(struct method64_t)) {
Kevin Enderbya59824a2015-10-06 22:27:08 +00003447 memcpy(&m, r, left);
3448 outs() << indent << " (method_t extends past the end of the section)\n";
Kevin Enderby0fc11822015-04-01 20:57:01 +00003449 } else
3450 memcpy(&m, r, sizeof(struct method64_t));
3451 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3452 swapStruct(m);
3453
3454 outs() << indent << "\t\t name ";
3455 sym_name = get_symbol_64(offset + offsetof(struct method64_t, name), S,
3456 info, n_value, m.name);
3457 if (n_value != 0) {
3458 if (info->verbose && sym_name != nullptr)
3459 outs() << sym_name;
3460 else
3461 outs() << format("0x%" PRIx64, n_value);
3462 if (m.name != 0)
3463 outs() << " + " << format("0x%" PRIx64, m.name);
3464 } else
3465 outs() << format("0x%" PRIx64, m.name);
3466 name = get_pointer_64(m.name + n_value, xoffset, left, xS, info);
3467 if (name != nullptr)
3468 outs() << format(" %.*s", left, name);
3469 outs() << "\n";
3470
3471 outs() << indent << "\t\t types ";
3472 sym_name = get_symbol_64(offset + offsetof(struct method64_t, types), S,
3473 info, n_value, m.types);
3474 if (n_value != 0) {
3475 if (info->verbose && sym_name != nullptr)
3476 outs() << sym_name;
3477 else
3478 outs() << format("0x%" PRIx64, n_value);
3479 if (m.types != 0)
3480 outs() << " + " << format("0x%" PRIx64, m.types);
3481 } else
3482 outs() << format("0x%" PRIx64, m.types);
3483 name = get_pointer_64(m.types + n_value, xoffset, left, xS, info);
3484 if (name != nullptr)
3485 outs() << format(" %.*s", left, name);
3486 outs() << "\n";
3487
3488 outs() << indent << "\t\t imp ";
3489 name = get_symbol_64(offset + offsetof(struct method64_t, imp), S, info,
3490 n_value, m.imp);
3491 if (info->verbose && name == nullptr) {
3492 if (n_value != 0) {
3493 outs() << format("0x%" PRIx64, n_value) << " ";
3494 if (m.imp != 0)
3495 outs() << "+ " << format("0x%" PRIx64, m.imp) << " ";
3496 } else
3497 outs() << format("0x%" PRIx64, m.imp) << " ";
3498 }
3499 if (name != nullptr)
3500 outs() << name;
3501 outs() << "\n";
3502
3503 p += sizeof(struct method64_t);
3504 offset += sizeof(struct method64_t);
3505 }
3506}
3507
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003508static void print_method_list32_t(uint64_t p, struct DisassembleInfo *info,
3509 const char *indent) {
3510 struct method_list32_t ml;
3511 struct method32_t m;
Kevin Enderby846c0002015-04-16 17:19:59 +00003512 const char *r, *name;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003513 uint32_t offset, xoffset, left, i;
3514 SectionRef S, xS;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003515
3516 r = get_pointer_32(p, offset, left, S, info);
3517 if (r == nullptr)
3518 return;
3519 memset(&ml, '\0', sizeof(struct method_list32_t));
3520 if (left < sizeof(struct method_list32_t)) {
3521 memcpy(&ml, r, left);
3522 outs() << " (method_list_t entends past the end of the section)\n";
3523 } else
3524 memcpy(&ml, r, sizeof(struct method_list32_t));
3525 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3526 swapStruct(ml);
3527 outs() << indent << "\t\t entsize " << ml.entsize << "\n";
3528 outs() << indent << "\t\t count " << ml.count << "\n";
3529
3530 p += sizeof(struct method_list32_t);
3531 offset += sizeof(struct method_list32_t);
3532 for (i = 0; i < ml.count; i++) {
3533 r = get_pointer_32(p, offset, left, S, info);
3534 if (r == nullptr)
3535 return;
3536 memset(&m, '\0', sizeof(struct method32_t));
3537 if (left < sizeof(struct method32_t)) {
3538 memcpy(&ml, r, left);
3539 outs() << indent << " (method_t entends past the end of the section)\n";
3540 } else
3541 memcpy(&m, r, sizeof(struct method32_t));
3542 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3543 swapStruct(m);
3544
3545 outs() << indent << "\t\t name " << format("0x%" PRIx32, m.name);
3546 name = get_pointer_32(m.name, xoffset, left, xS, info);
3547 if (name != nullptr)
3548 outs() << format(" %.*s", left, name);
3549 outs() << "\n";
3550
3551 outs() << indent << "\t\t types " << format("0x%" PRIx32, m.types);
3552 name = get_pointer_32(m.types, xoffset, left, xS, info);
3553 if (name != nullptr)
3554 outs() << format(" %.*s", left, name);
3555 outs() << "\n";
3556
3557 outs() << indent << "\t\t imp " << format("0x%" PRIx32, m.imp);
3558 name = get_symbol_32(offset + offsetof(struct method32_t, imp), S, info,
3559 m.imp);
3560 if (name != nullptr)
3561 outs() << " " << name;
3562 outs() << "\n";
3563
3564 p += sizeof(struct method32_t);
3565 offset += sizeof(struct method32_t);
3566 }
3567}
3568
Kevin Enderby846c0002015-04-16 17:19:59 +00003569static bool print_method_list(uint32_t p, struct DisassembleInfo *info) {
3570 uint32_t offset, left, xleft;
3571 SectionRef S;
3572 struct objc_method_list_t method_list;
3573 struct objc_method_t method;
3574 const char *r, *methods, *name, *SymbolName;
3575 int32_t i;
3576
3577 r = get_pointer_32(p, offset, left, S, info, true);
3578 if (r == nullptr)
3579 return true;
3580
3581 outs() << "\n";
3582 if (left > sizeof(struct objc_method_list_t)) {
3583 memcpy(&method_list, r, sizeof(struct objc_method_list_t));
3584 } else {
3585 outs() << "\t\t objc_method_list extends past end of the section\n";
3586 memset(&method_list, '\0', sizeof(struct objc_method_list_t));
3587 memcpy(&method_list, r, left);
3588 }
3589 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3590 swapStruct(method_list);
3591
3592 outs() << "\t\t obsolete "
3593 << format("0x%08" PRIx32, method_list.obsolete) << "\n";
3594 outs() << "\t\t method_count " << method_list.method_count << "\n";
3595
3596 methods = r + sizeof(struct objc_method_list_t);
3597 for (i = 0; i < method_list.method_count; i++) {
3598 if ((i + 1) * sizeof(struct objc_method_t) > left) {
3599 outs() << "\t\t remaining method's extend past the of the section\n";
3600 break;
3601 }
3602 memcpy(&method, methods + i * sizeof(struct objc_method_t),
3603 sizeof(struct objc_method_t));
3604 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3605 swapStruct(method);
3606
3607 outs() << "\t\t method_name "
3608 << format("0x%08" PRIx32, method.method_name);
3609 if (info->verbose) {
3610 name = get_pointer_32(method.method_name, offset, xleft, S, info, true);
3611 if (name != nullptr)
3612 outs() << format(" %.*s", xleft, name);
3613 else
3614 outs() << " (not in an __OBJC section)";
3615 }
3616 outs() << "\n";
3617
3618 outs() << "\t\t method_types "
3619 << format("0x%08" PRIx32, method.method_types);
3620 if (info->verbose) {
3621 name = get_pointer_32(method.method_types, offset, xleft, S, info, true);
3622 if (name != nullptr)
3623 outs() << format(" %.*s", xleft, name);
3624 else
3625 outs() << " (not in an __OBJC section)";
3626 }
3627 outs() << "\n";
3628
3629 outs() << "\t\t method_imp "
3630 << format("0x%08" PRIx32, method.method_imp) << " ";
3631 if (info->verbose) {
3632 SymbolName = GuessSymbolName(method.method_imp, info->AddrMap);
3633 if (SymbolName != nullptr)
3634 outs() << SymbolName;
3635 }
3636 outs() << "\n";
3637 }
3638 return false;
3639}
3640
Kevin Enderby0fc11822015-04-01 20:57:01 +00003641static void print_protocol_list64_t(uint64_t p, struct DisassembleInfo *info) {
3642 struct protocol_list64_t pl;
3643 uint64_t q, n_value;
3644 struct protocol64_t pc;
3645 const char *r;
3646 uint32_t offset, xoffset, left, i;
3647 SectionRef S, xS;
3648 const char *name, *sym_name;
3649
3650 r = get_pointer_64(p, offset, left, S, info);
3651 if (r == nullptr)
3652 return;
3653 memset(&pl, '\0', sizeof(struct protocol_list64_t));
3654 if (left < sizeof(struct protocol_list64_t)) {
3655 memcpy(&pl, r, left);
3656 outs() << " (protocol_list_t entends past the end of the section)\n";
3657 } else
3658 memcpy(&pl, r, sizeof(struct protocol_list64_t));
3659 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3660 swapStruct(pl);
3661 outs() << " count " << pl.count << "\n";
3662
3663 p += sizeof(struct protocol_list64_t);
3664 offset += sizeof(struct protocol_list64_t);
3665 for (i = 0; i < pl.count; i++) {
3666 r = get_pointer_64(p, offset, left, S, info);
3667 if (r == nullptr)
3668 return;
3669 q = 0;
3670 if (left < sizeof(uint64_t)) {
3671 memcpy(&q, r, left);
3672 outs() << " (protocol_t * entends past the end of the section)\n";
3673 } else
3674 memcpy(&q, r, sizeof(uint64_t));
3675 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3676 sys::swapByteOrder(q);
3677
3678 outs() << "\t\t list[" << i << "] ";
3679 sym_name = get_symbol_64(offset, S, info, n_value, q);
3680 if (n_value != 0) {
3681 if (info->verbose && sym_name != nullptr)
3682 outs() << sym_name;
3683 else
3684 outs() << format("0x%" PRIx64, n_value);
3685 if (q != 0)
3686 outs() << " + " << format("0x%" PRIx64, q);
3687 } else
3688 outs() << format("0x%" PRIx64, q);
3689 outs() << " (struct protocol_t *)\n";
3690
3691 r = get_pointer_64(q + n_value, offset, left, S, info);
3692 if (r == nullptr)
3693 return;
3694 memset(&pc, '\0', sizeof(struct protocol64_t));
3695 if (left < sizeof(struct protocol64_t)) {
3696 memcpy(&pc, r, left);
3697 outs() << " (protocol_t entends past the end of the section)\n";
3698 } else
3699 memcpy(&pc, r, sizeof(struct protocol64_t));
3700 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3701 swapStruct(pc);
3702
3703 outs() << "\t\t\t isa " << format("0x%" PRIx64, pc.isa) << "\n";
3704
3705 outs() << "\t\t\t name ";
3706 sym_name = get_symbol_64(offset + offsetof(struct protocol64_t, name), S,
3707 info, n_value, pc.name);
3708 if (n_value != 0) {
3709 if (info->verbose && sym_name != nullptr)
3710 outs() << sym_name;
3711 else
3712 outs() << format("0x%" PRIx64, n_value);
3713 if (pc.name != 0)
3714 outs() << " + " << format("0x%" PRIx64, pc.name);
3715 } else
3716 outs() << format("0x%" PRIx64, pc.name);
3717 name = get_pointer_64(pc.name + n_value, xoffset, left, xS, info);
3718 if (name != nullptr)
3719 outs() << format(" %.*s", left, name);
3720 outs() << "\n";
3721
3722 outs() << "\t\t\tprotocols " << format("0x%" PRIx64, pc.protocols) << "\n";
3723
3724 outs() << "\t\t instanceMethods ";
3725 sym_name =
3726 get_symbol_64(offset + offsetof(struct protocol64_t, instanceMethods),
3727 S, info, n_value, pc.instanceMethods);
3728 if (n_value != 0) {
3729 if (info->verbose && sym_name != nullptr)
3730 outs() << sym_name;
3731 else
3732 outs() << format("0x%" PRIx64, n_value);
3733 if (pc.instanceMethods != 0)
3734 outs() << " + " << format("0x%" PRIx64, pc.instanceMethods);
3735 } else
3736 outs() << format("0x%" PRIx64, pc.instanceMethods);
3737 outs() << " (struct method_list_t *)\n";
3738 if (pc.instanceMethods + n_value != 0)
3739 print_method_list64_t(pc.instanceMethods + n_value, info, "\t");
3740
3741 outs() << "\t\t classMethods ";
3742 sym_name =
3743 get_symbol_64(offset + offsetof(struct protocol64_t, classMethods), S,
3744 info, n_value, pc.classMethods);
3745 if (n_value != 0) {
3746 if (info->verbose && sym_name != nullptr)
3747 outs() << sym_name;
3748 else
3749 outs() << format("0x%" PRIx64, n_value);
3750 if (pc.classMethods != 0)
3751 outs() << " + " << format("0x%" PRIx64, pc.classMethods);
3752 } else
3753 outs() << format("0x%" PRIx64, pc.classMethods);
3754 outs() << " (struct method_list_t *)\n";
3755 if (pc.classMethods + n_value != 0)
3756 print_method_list64_t(pc.classMethods + n_value, info, "\t");
3757
3758 outs() << "\t optionalInstanceMethods "
3759 << format("0x%" PRIx64, pc.optionalInstanceMethods) << "\n";
3760 outs() << "\t optionalClassMethods "
3761 << format("0x%" PRIx64, pc.optionalClassMethods) << "\n";
3762 outs() << "\t instanceProperties "
3763 << format("0x%" PRIx64, pc.instanceProperties) << "\n";
3764
3765 p += sizeof(uint64_t);
3766 offset += sizeof(uint64_t);
3767 }
3768}
3769
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003770static void print_protocol_list32_t(uint32_t p, struct DisassembleInfo *info) {
3771 struct protocol_list32_t pl;
3772 uint32_t q;
3773 struct protocol32_t pc;
3774 const char *r;
3775 uint32_t offset, xoffset, left, i;
3776 SectionRef S, xS;
3777 const char *name;
3778
3779 r = get_pointer_32(p, offset, left, S, info);
3780 if (r == nullptr)
3781 return;
3782 memset(&pl, '\0', sizeof(struct protocol_list32_t));
3783 if (left < sizeof(struct protocol_list32_t)) {
3784 memcpy(&pl, r, left);
3785 outs() << " (protocol_list_t entends past the end of the section)\n";
3786 } else
3787 memcpy(&pl, r, sizeof(struct protocol_list32_t));
3788 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3789 swapStruct(pl);
3790 outs() << " count " << pl.count << "\n";
3791
3792 p += sizeof(struct protocol_list32_t);
3793 offset += sizeof(struct protocol_list32_t);
3794 for (i = 0; i < pl.count; i++) {
3795 r = get_pointer_32(p, offset, left, S, info);
3796 if (r == nullptr)
3797 return;
3798 q = 0;
3799 if (left < sizeof(uint32_t)) {
3800 memcpy(&q, r, left);
3801 outs() << " (protocol_t * entends past the end of the section)\n";
3802 } else
3803 memcpy(&q, r, sizeof(uint32_t));
3804 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3805 sys::swapByteOrder(q);
3806 outs() << "\t\t list[" << i << "] " << format("0x%" PRIx32, q)
3807 << " (struct protocol_t *)\n";
3808 r = get_pointer_32(q, offset, left, S, info);
3809 if (r == nullptr)
3810 return;
3811 memset(&pc, '\0', sizeof(struct protocol32_t));
3812 if (left < sizeof(struct protocol32_t)) {
3813 memcpy(&pc, r, left);
3814 outs() << " (protocol_t entends past the end of the section)\n";
3815 } else
3816 memcpy(&pc, r, sizeof(struct protocol32_t));
3817 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3818 swapStruct(pc);
3819 outs() << "\t\t\t isa " << format("0x%" PRIx32, pc.isa) << "\n";
3820 outs() << "\t\t\t name " << format("0x%" PRIx32, pc.name);
3821 name = get_pointer_32(pc.name, xoffset, left, xS, info);
3822 if (name != nullptr)
3823 outs() << format(" %.*s", left, name);
3824 outs() << "\n";
3825 outs() << "\t\t\tprotocols " << format("0x%" PRIx32, pc.protocols) << "\n";
3826 outs() << "\t\t instanceMethods "
3827 << format("0x%" PRIx32, pc.instanceMethods)
3828 << " (struct method_list_t *)\n";
3829 if (pc.instanceMethods != 0)
3830 print_method_list32_t(pc.instanceMethods, info, "\t");
3831 outs() << "\t\t classMethods " << format("0x%" PRIx32, pc.classMethods)
3832 << " (struct method_list_t *)\n";
3833 if (pc.classMethods != 0)
3834 print_method_list32_t(pc.classMethods, info, "\t");
3835 outs() << "\t optionalInstanceMethods "
3836 << format("0x%" PRIx32, pc.optionalInstanceMethods) << "\n";
3837 outs() << "\t optionalClassMethods "
3838 << format("0x%" PRIx32, pc.optionalClassMethods) << "\n";
3839 outs() << "\t instanceProperties "
3840 << format("0x%" PRIx32, pc.instanceProperties) << "\n";
3841 p += sizeof(uint32_t);
3842 offset += sizeof(uint32_t);
3843 }
3844}
3845
Kevin Enderby846c0002015-04-16 17:19:59 +00003846static void print_indent(uint32_t indent) {
3847 for (uint32_t i = 0; i < indent;) {
3848 if (indent - i >= 8) {
3849 outs() << "\t";
3850 i += 8;
3851 } else {
3852 for (uint32_t j = i; j < indent; j++)
3853 outs() << " ";
3854 return;
3855 }
3856 }
3857}
3858
3859static bool print_method_description_list(uint32_t p, uint32_t indent,
3860 struct DisassembleInfo *info) {
3861 uint32_t offset, left, xleft;
3862 SectionRef S;
3863 struct objc_method_description_list_t mdl;
3864 struct objc_method_description_t md;
3865 const char *r, *list, *name;
3866 int32_t i;
3867
3868 r = get_pointer_32(p, offset, left, S, info, true);
3869 if (r == nullptr)
3870 return true;
3871
3872 outs() << "\n";
3873 if (left > sizeof(struct objc_method_description_list_t)) {
3874 memcpy(&mdl, r, sizeof(struct objc_method_description_list_t));
3875 } else {
3876 print_indent(indent);
3877 outs() << " objc_method_description_list extends past end of the section\n";
3878 memset(&mdl, '\0', sizeof(struct objc_method_description_list_t));
3879 memcpy(&mdl, r, left);
3880 }
3881 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3882 swapStruct(mdl);
3883
3884 print_indent(indent);
3885 outs() << " count " << mdl.count << "\n";
3886
3887 list = r + sizeof(struct objc_method_description_list_t);
3888 for (i = 0; i < mdl.count; i++) {
3889 if ((i + 1) * sizeof(struct objc_method_description_t) > left) {
3890 print_indent(indent);
3891 outs() << " remaining list entries extend past the of the section\n";
3892 break;
3893 }
3894 print_indent(indent);
3895 outs() << " list[" << i << "]\n";
3896 memcpy(&md, list + i * sizeof(struct objc_method_description_t),
3897 sizeof(struct objc_method_description_t));
3898 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3899 swapStruct(md);
3900
3901 print_indent(indent);
3902 outs() << " name " << format("0x%08" PRIx32, md.name);
3903 if (info->verbose) {
3904 name = get_pointer_32(md.name, offset, xleft, S, info, true);
3905 if (name != nullptr)
3906 outs() << format(" %.*s", xleft, name);
3907 else
3908 outs() << " (not in an __OBJC section)";
3909 }
3910 outs() << "\n";
3911
3912 print_indent(indent);
3913 outs() << " types " << format("0x%08" PRIx32, md.types);
3914 if (info->verbose) {
3915 name = get_pointer_32(md.types, offset, xleft, S, info, true);
3916 if (name != nullptr)
3917 outs() << format(" %.*s", xleft, name);
3918 else
3919 outs() << " (not in an __OBJC section)";
3920 }
3921 outs() << "\n";
3922 }
3923 return false;
3924}
3925
3926static bool print_protocol_list(uint32_t p, uint32_t indent,
3927 struct DisassembleInfo *info);
3928
3929static bool print_protocol(uint32_t p, uint32_t indent,
3930 struct DisassembleInfo *info) {
3931 uint32_t offset, left;
3932 SectionRef S;
3933 struct objc_protocol_t protocol;
3934 const char *r, *name;
3935
3936 r = get_pointer_32(p, offset, left, S, info, true);
3937 if (r == nullptr)
3938 return true;
3939
3940 outs() << "\n";
3941 if (left >= sizeof(struct objc_protocol_t)) {
3942 memcpy(&protocol, r, sizeof(struct objc_protocol_t));
3943 } else {
3944 print_indent(indent);
3945 outs() << " Protocol extends past end of the section\n";
3946 memset(&protocol, '\0', sizeof(struct objc_protocol_t));
3947 memcpy(&protocol, r, left);
3948 }
3949 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3950 swapStruct(protocol);
3951
3952 print_indent(indent);
3953 outs() << " isa " << format("0x%08" PRIx32, protocol.isa)
3954 << "\n";
3955
3956 print_indent(indent);
3957 outs() << " protocol_name "
3958 << format("0x%08" PRIx32, protocol.protocol_name);
3959 if (info->verbose) {
3960 name = get_pointer_32(protocol.protocol_name, offset, left, S, info, true);
3961 if (name != nullptr)
3962 outs() << format(" %.*s", left, name);
3963 else
3964 outs() << " (not in an __OBJC section)";
3965 }
3966 outs() << "\n";
3967
3968 print_indent(indent);
3969 outs() << " protocol_list "
3970 << format("0x%08" PRIx32, protocol.protocol_list);
3971 if (print_protocol_list(protocol.protocol_list, indent + 4, info))
3972 outs() << " (not in an __OBJC section)\n";
3973
3974 print_indent(indent);
3975 outs() << " instance_methods "
3976 << format("0x%08" PRIx32, protocol.instance_methods);
3977 if (print_method_description_list(protocol.instance_methods, indent, info))
3978 outs() << " (not in an __OBJC section)\n";
3979
3980 print_indent(indent);
3981 outs() << " class_methods "
3982 << format("0x%08" PRIx32, protocol.class_methods);
3983 if (print_method_description_list(protocol.class_methods, indent, info))
3984 outs() << " (not in an __OBJC section)\n";
3985
3986 return false;
3987}
3988
3989static bool print_protocol_list(uint32_t p, uint32_t indent,
3990 struct DisassembleInfo *info) {
3991 uint32_t offset, left, l;
3992 SectionRef S;
3993 struct objc_protocol_list_t protocol_list;
3994 const char *r, *list;
3995 int32_t i;
3996
3997 r = get_pointer_32(p, offset, left, S, info, true);
3998 if (r == nullptr)
3999 return true;
4000
4001 outs() << "\n";
4002 if (left > sizeof(struct objc_protocol_list_t)) {
4003 memcpy(&protocol_list, r, sizeof(struct objc_protocol_list_t));
4004 } else {
4005 outs() << "\t\t objc_protocol_list_t extends past end of the section\n";
4006 memset(&protocol_list, '\0', sizeof(struct objc_protocol_list_t));
4007 memcpy(&protocol_list, r, left);
4008 }
4009 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4010 swapStruct(protocol_list);
4011
4012 print_indent(indent);
4013 outs() << " next " << format("0x%08" PRIx32, protocol_list.next)
4014 << "\n";
4015 print_indent(indent);
4016 outs() << " count " << protocol_list.count << "\n";
4017
4018 list = r + sizeof(struct objc_protocol_list_t);
4019 for (i = 0; i < protocol_list.count; i++) {
4020 if ((i + 1) * sizeof(uint32_t) > left) {
4021 outs() << "\t\t remaining list entries extend past the of the section\n";
4022 break;
4023 }
4024 memcpy(&l, list + i * sizeof(uint32_t), sizeof(uint32_t));
4025 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4026 sys::swapByteOrder(l);
4027
4028 print_indent(indent);
4029 outs() << " list[" << i << "] " << format("0x%08" PRIx32, l);
4030 if (print_protocol(l, indent, info))
4031 outs() << "(not in an __OBJC section)\n";
4032 }
4033 return false;
4034}
4035
Kevin Enderby0fc11822015-04-01 20:57:01 +00004036static void print_ivar_list64_t(uint64_t p, struct DisassembleInfo *info) {
4037 struct ivar_list64_t il;
4038 struct ivar64_t i;
4039 const char *r;
4040 uint32_t offset, xoffset, left, j;
4041 SectionRef S, xS;
4042 const char *name, *sym_name, *ivar_offset_p;
4043 uint64_t ivar_offset, n_value;
4044
4045 r = get_pointer_64(p, offset, left, S, info);
4046 if (r == nullptr)
4047 return;
4048 memset(&il, '\0', sizeof(struct ivar_list64_t));
4049 if (left < sizeof(struct ivar_list64_t)) {
4050 memcpy(&il, r, left);
4051 outs() << " (ivar_list_t entends past the end of the section)\n";
4052 } else
4053 memcpy(&il, r, sizeof(struct ivar_list64_t));
4054 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4055 swapStruct(il);
4056 outs() << " entsize " << il.entsize << "\n";
4057 outs() << " count " << il.count << "\n";
4058
4059 p += sizeof(struct ivar_list64_t);
4060 offset += sizeof(struct ivar_list64_t);
4061 for (j = 0; j < il.count; j++) {
4062 r = get_pointer_64(p, offset, left, S, info);
4063 if (r == nullptr)
4064 return;
4065 memset(&i, '\0', sizeof(struct ivar64_t));
4066 if (left < sizeof(struct ivar64_t)) {
4067 memcpy(&i, r, left);
4068 outs() << " (ivar_t entends past the end of the section)\n";
4069 } else
4070 memcpy(&i, r, sizeof(struct ivar64_t));
4071 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4072 swapStruct(i);
4073
4074 outs() << "\t\t\t offset ";
4075 sym_name = get_symbol_64(offset + offsetof(struct ivar64_t, offset), S,
4076 info, n_value, i.offset);
4077 if (n_value != 0) {
4078 if (info->verbose && sym_name != nullptr)
4079 outs() << sym_name;
4080 else
4081 outs() << format("0x%" PRIx64, n_value);
4082 if (i.offset != 0)
4083 outs() << " + " << format("0x%" PRIx64, i.offset);
4084 } else
4085 outs() << format("0x%" PRIx64, i.offset);
4086 ivar_offset_p = get_pointer_64(i.offset + n_value, xoffset, left, xS, info);
4087 if (ivar_offset_p != nullptr && left >= sizeof(*ivar_offset_p)) {
4088 memcpy(&ivar_offset, ivar_offset_p, sizeof(ivar_offset));
4089 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4090 sys::swapByteOrder(ivar_offset);
4091 outs() << " " << ivar_offset << "\n";
4092 } else
4093 outs() << "\n";
4094
4095 outs() << "\t\t\t name ";
4096 sym_name = get_symbol_64(offset + offsetof(struct ivar64_t, name), S, info,
4097 n_value, i.name);
4098 if (n_value != 0) {
4099 if (info->verbose && sym_name != nullptr)
4100 outs() << sym_name;
4101 else
4102 outs() << format("0x%" PRIx64, n_value);
4103 if (i.name != 0)
4104 outs() << " + " << format("0x%" PRIx64, i.name);
4105 } else
4106 outs() << format("0x%" PRIx64, i.name);
4107 name = get_pointer_64(i.name + n_value, xoffset, left, xS, info);
4108 if (name != nullptr)
4109 outs() << format(" %.*s", left, name);
4110 outs() << "\n";
4111
4112 outs() << "\t\t\t type ";
4113 sym_name = get_symbol_64(offset + offsetof(struct ivar64_t, type), S, info,
4114 n_value, i.name);
4115 name = get_pointer_64(i.type + n_value, xoffset, left, xS, info);
4116 if (n_value != 0) {
4117 if (info->verbose && sym_name != nullptr)
4118 outs() << sym_name;
4119 else
4120 outs() << format("0x%" PRIx64, n_value);
4121 if (i.type != 0)
4122 outs() << " + " << format("0x%" PRIx64, i.type);
4123 } else
4124 outs() << format("0x%" PRIx64, i.type);
4125 if (name != nullptr)
4126 outs() << format(" %.*s", left, name);
4127 outs() << "\n";
4128
4129 outs() << "\t\t\talignment " << i.alignment << "\n";
4130 outs() << "\t\t\t size " << i.size << "\n";
4131
4132 p += sizeof(struct ivar64_t);
4133 offset += sizeof(struct ivar64_t);
4134 }
4135}
4136
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004137static void print_ivar_list32_t(uint32_t p, struct DisassembleInfo *info) {
4138 struct ivar_list32_t il;
4139 struct ivar32_t i;
4140 const char *r;
4141 uint32_t offset, xoffset, left, j;
4142 SectionRef S, xS;
4143 const char *name, *ivar_offset_p;
4144 uint32_t ivar_offset;
4145
4146 r = get_pointer_32(p, offset, left, S, info);
4147 if (r == nullptr)
4148 return;
4149 memset(&il, '\0', sizeof(struct ivar_list32_t));
4150 if (left < sizeof(struct ivar_list32_t)) {
4151 memcpy(&il, r, left);
4152 outs() << " (ivar_list_t entends past the end of the section)\n";
4153 } else
4154 memcpy(&il, r, sizeof(struct ivar_list32_t));
4155 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4156 swapStruct(il);
4157 outs() << " entsize " << il.entsize << "\n";
4158 outs() << " count " << il.count << "\n";
4159
4160 p += sizeof(struct ivar_list32_t);
4161 offset += sizeof(struct ivar_list32_t);
4162 for (j = 0; j < il.count; j++) {
4163 r = get_pointer_32(p, offset, left, S, info);
4164 if (r == nullptr)
4165 return;
4166 memset(&i, '\0', sizeof(struct ivar32_t));
4167 if (left < sizeof(struct ivar32_t)) {
4168 memcpy(&i, r, left);
4169 outs() << " (ivar_t entends past the end of the section)\n";
4170 } else
4171 memcpy(&i, r, sizeof(struct ivar32_t));
4172 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4173 swapStruct(i);
4174
4175 outs() << "\t\t\t offset " << format("0x%" PRIx32, i.offset);
4176 ivar_offset_p = get_pointer_32(i.offset, xoffset, left, xS, info);
4177 if (ivar_offset_p != nullptr && left >= sizeof(*ivar_offset_p)) {
4178 memcpy(&ivar_offset, ivar_offset_p, sizeof(ivar_offset));
4179 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4180 sys::swapByteOrder(ivar_offset);
4181 outs() << " " << ivar_offset << "\n";
4182 } else
4183 outs() << "\n";
4184
4185 outs() << "\t\t\t name " << format("0x%" PRIx32, i.name);
4186 name = get_pointer_32(i.name, xoffset, left, xS, info);
4187 if (name != nullptr)
4188 outs() << format(" %.*s", left, name);
4189 outs() << "\n";
4190
4191 outs() << "\t\t\t type " << format("0x%" PRIx32, i.type);
4192 name = get_pointer_32(i.type, xoffset, left, xS, info);
4193 if (name != nullptr)
4194 outs() << format(" %.*s", left, name);
4195 outs() << "\n";
4196
4197 outs() << "\t\t\talignment " << i.alignment << "\n";
4198 outs() << "\t\t\t size " << i.size << "\n";
4199
4200 p += sizeof(struct ivar32_t);
4201 offset += sizeof(struct ivar32_t);
4202 }
4203}
4204
Kevin Enderby0fc11822015-04-01 20:57:01 +00004205static void print_objc_property_list64(uint64_t p,
4206 struct DisassembleInfo *info) {
4207 struct objc_property_list64 opl;
4208 struct objc_property64 op;
4209 const char *r;
4210 uint32_t offset, xoffset, left, j;
4211 SectionRef S, xS;
4212 const char *name, *sym_name;
4213 uint64_t n_value;
4214
4215 r = get_pointer_64(p, offset, left, S, info);
4216 if (r == nullptr)
4217 return;
4218 memset(&opl, '\0', sizeof(struct objc_property_list64));
4219 if (left < sizeof(struct objc_property_list64)) {
4220 memcpy(&opl, r, left);
4221 outs() << " (objc_property_list entends past the end of the section)\n";
4222 } else
4223 memcpy(&opl, r, sizeof(struct objc_property_list64));
4224 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4225 swapStruct(opl);
4226 outs() << " entsize " << opl.entsize << "\n";
4227 outs() << " count " << opl.count << "\n";
4228
4229 p += sizeof(struct objc_property_list64);
4230 offset += sizeof(struct objc_property_list64);
4231 for (j = 0; j < opl.count; j++) {
4232 r = get_pointer_64(p, offset, left, S, info);
4233 if (r == nullptr)
4234 return;
4235 memset(&op, '\0', sizeof(struct objc_property64));
4236 if (left < sizeof(struct objc_property64)) {
4237 memcpy(&op, r, left);
4238 outs() << " (objc_property entends past the end of the section)\n";
4239 } else
4240 memcpy(&op, r, sizeof(struct objc_property64));
4241 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4242 swapStruct(op);
4243
4244 outs() << "\t\t\t name ";
4245 sym_name = get_symbol_64(offset + offsetof(struct objc_property64, name), S,
4246 info, n_value, op.name);
4247 if (n_value != 0) {
4248 if (info->verbose && sym_name != nullptr)
4249 outs() << sym_name;
4250 else
4251 outs() << format("0x%" PRIx64, n_value);
4252 if (op.name != 0)
4253 outs() << " + " << format("0x%" PRIx64, op.name);
4254 } else
4255 outs() << format("0x%" PRIx64, op.name);
4256 name = get_pointer_64(op.name + n_value, xoffset, left, xS, info);
4257 if (name != nullptr)
4258 outs() << format(" %.*s", left, name);
4259 outs() << "\n";
4260
4261 outs() << "\t\t\tattributes ";
4262 sym_name =
4263 get_symbol_64(offset + offsetof(struct objc_property64, attributes), S,
4264 info, n_value, op.attributes);
4265 if (n_value != 0) {
4266 if (info->verbose && sym_name != nullptr)
4267 outs() << sym_name;
4268 else
4269 outs() << format("0x%" PRIx64, n_value);
4270 if (op.attributes != 0)
4271 outs() << " + " << format("0x%" PRIx64, op.attributes);
4272 } else
4273 outs() << format("0x%" PRIx64, op.attributes);
4274 name = get_pointer_64(op.attributes + n_value, xoffset, left, xS, info);
4275 if (name != nullptr)
4276 outs() << format(" %.*s", left, name);
4277 outs() << "\n";
4278
4279 p += sizeof(struct objc_property64);
4280 offset += sizeof(struct objc_property64);
4281 }
4282}
4283
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004284static void print_objc_property_list32(uint32_t p,
4285 struct DisassembleInfo *info) {
4286 struct objc_property_list32 opl;
4287 struct objc_property32 op;
4288 const char *r;
4289 uint32_t offset, xoffset, left, j;
4290 SectionRef S, xS;
4291 const char *name;
4292
4293 r = get_pointer_32(p, offset, left, S, info);
4294 if (r == nullptr)
4295 return;
4296 memset(&opl, '\0', sizeof(struct objc_property_list32));
4297 if (left < sizeof(struct objc_property_list32)) {
4298 memcpy(&opl, r, left);
4299 outs() << " (objc_property_list entends past the end of the section)\n";
4300 } else
4301 memcpy(&opl, r, sizeof(struct objc_property_list32));
4302 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4303 swapStruct(opl);
4304 outs() << " entsize " << opl.entsize << "\n";
4305 outs() << " count " << opl.count << "\n";
4306
4307 p += sizeof(struct objc_property_list32);
4308 offset += sizeof(struct objc_property_list32);
4309 for (j = 0; j < opl.count; j++) {
4310 r = get_pointer_32(p, offset, left, S, info);
4311 if (r == nullptr)
4312 return;
4313 memset(&op, '\0', sizeof(struct objc_property32));
4314 if (left < sizeof(struct objc_property32)) {
4315 memcpy(&op, r, left);
4316 outs() << " (objc_property entends past the end of the section)\n";
4317 } else
4318 memcpy(&op, r, sizeof(struct objc_property32));
4319 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4320 swapStruct(op);
4321
4322 outs() << "\t\t\t name " << format("0x%" PRIx32, op.name);
4323 name = get_pointer_32(op.name, xoffset, left, xS, info);
4324 if (name != nullptr)
4325 outs() << format(" %.*s", left, name);
4326 outs() << "\n";
4327
4328 outs() << "\t\t\tattributes " << format("0x%" PRIx32, op.attributes);
4329 name = get_pointer_32(op.attributes, xoffset, left, xS, info);
4330 if (name != nullptr)
4331 outs() << format(" %.*s", left, name);
4332 outs() << "\n";
4333
4334 p += sizeof(struct objc_property32);
4335 offset += sizeof(struct objc_property32);
4336 }
4337}
4338
Richard Smith81ff44d2015-10-09 22:09:56 +00004339static bool print_class_ro64_t(uint64_t p, struct DisassembleInfo *info,
Kevin Enderby0fc11822015-04-01 20:57:01 +00004340 bool &is_meta_class) {
4341 struct class_ro64_t cro;
4342 const char *r;
4343 uint32_t offset, xoffset, left;
4344 SectionRef S, xS;
4345 const char *name, *sym_name;
4346 uint64_t n_value;
4347
4348 r = get_pointer_64(p, offset, left, S, info);
4349 if (r == nullptr || left < sizeof(struct class_ro64_t))
Richard Smith81ff44d2015-10-09 22:09:56 +00004350 return false;
Chandler Carruth33e58902016-11-04 07:10:24 +00004351 memcpy(&cro, r, sizeof(struct class_ro64_t));
Kevin Enderby0fc11822015-04-01 20:57:01 +00004352 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4353 swapStruct(cro);
4354 outs() << " flags " << format("0x%" PRIx32, cro.flags);
4355 if (cro.flags & RO_META)
4356 outs() << " RO_META";
4357 if (cro.flags & RO_ROOT)
4358 outs() << " RO_ROOT";
4359 if (cro.flags & RO_HAS_CXX_STRUCTORS)
4360 outs() << " RO_HAS_CXX_STRUCTORS";
4361 outs() << "\n";
4362 outs() << " instanceStart " << cro.instanceStart << "\n";
4363 outs() << " instanceSize " << cro.instanceSize << "\n";
4364 outs() << " reserved " << format("0x%" PRIx32, cro.reserved)
4365 << "\n";
4366 outs() << " ivarLayout " << format("0x%" PRIx64, cro.ivarLayout)
4367 << "\n";
4368 print_layout_map64(cro.ivarLayout, info);
4369
4370 outs() << " name ";
4371 sym_name = get_symbol_64(offset + offsetof(struct class_ro64_t, name), S,
4372 info, n_value, cro.name);
4373 if (n_value != 0) {
4374 if (info->verbose && sym_name != nullptr)
4375 outs() << sym_name;
4376 else
4377 outs() << format("0x%" PRIx64, n_value);
4378 if (cro.name != 0)
4379 outs() << " + " << format("0x%" PRIx64, cro.name);
4380 } else
4381 outs() << format("0x%" PRIx64, cro.name);
4382 name = get_pointer_64(cro.name + n_value, xoffset, left, xS, info);
4383 if (name != nullptr)
4384 outs() << format(" %.*s", left, name);
4385 outs() << "\n";
4386
4387 outs() << " baseMethods ";
4388 sym_name = get_symbol_64(offset + offsetof(struct class_ro64_t, baseMethods),
4389 S, info, n_value, cro.baseMethods);
4390 if (n_value != 0) {
4391 if (info->verbose && sym_name != nullptr)
4392 outs() << sym_name;
4393 else
4394 outs() << format("0x%" PRIx64, n_value);
4395 if (cro.baseMethods != 0)
4396 outs() << " + " << format("0x%" PRIx64, cro.baseMethods);
4397 } else
4398 outs() << format("0x%" PRIx64, cro.baseMethods);
4399 outs() << " (struct method_list_t *)\n";
4400 if (cro.baseMethods + n_value != 0)
4401 print_method_list64_t(cro.baseMethods + n_value, info, "");
4402
4403 outs() << " baseProtocols ";
4404 sym_name =
4405 get_symbol_64(offset + offsetof(struct class_ro64_t, baseProtocols), S,
4406 info, n_value, cro.baseProtocols);
4407 if (n_value != 0) {
4408 if (info->verbose && sym_name != nullptr)
4409 outs() << sym_name;
4410 else
4411 outs() << format("0x%" PRIx64, n_value);
4412 if (cro.baseProtocols != 0)
4413 outs() << " + " << format("0x%" PRIx64, cro.baseProtocols);
4414 } else
4415 outs() << format("0x%" PRIx64, cro.baseProtocols);
4416 outs() << "\n";
4417 if (cro.baseProtocols + n_value != 0)
4418 print_protocol_list64_t(cro.baseProtocols + n_value, info);
4419
4420 outs() << " ivars ";
4421 sym_name = get_symbol_64(offset + offsetof(struct class_ro64_t, ivars), S,
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004422 info, n_value, cro.ivars);
Kevin Enderby0fc11822015-04-01 20:57:01 +00004423 if (n_value != 0) {
4424 if (info->verbose && sym_name != nullptr)
4425 outs() << sym_name;
4426 else
4427 outs() << format("0x%" PRIx64, n_value);
4428 if (cro.ivars != 0)
4429 outs() << " + " << format("0x%" PRIx64, cro.ivars);
4430 } else
4431 outs() << format("0x%" PRIx64, cro.ivars);
4432 outs() << "\n";
4433 if (cro.ivars + n_value != 0)
4434 print_ivar_list64_t(cro.ivars + n_value, info);
4435
4436 outs() << " weakIvarLayout ";
4437 sym_name =
4438 get_symbol_64(offset + offsetof(struct class_ro64_t, weakIvarLayout), S,
4439 info, n_value, cro.weakIvarLayout);
4440 if (n_value != 0) {
4441 if (info->verbose && sym_name != nullptr)
4442 outs() << sym_name;
4443 else
4444 outs() << format("0x%" PRIx64, n_value);
4445 if (cro.weakIvarLayout != 0)
4446 outs() << " + " << format("0x%" PRIx64, cro.weakIvarLayout);
4447 } else
4448 outs() << format("0x%" PRIx64, cro.weakIvarLayout);
4449 outs() << "\n";
4450 print_layout_map64(cro.weakIvarLayout + n_value, info);
4451
4452 outs() << " baseProperties ";
4453 sym_name =
4454 get_symbol_64(offset + offsetof(struct class_ro64_t, baseProperties), S,
4455 info, n_value, cro.baseProperties);
4456 if (n_value != 0) {
4457 if (info->verbose && sym_name != nullptr)
4458 outs() << sym_name;
4459 else
4460 outs() << format("0x%" PRIx64, n_value);
4461 if (cro.baseProperties != 0)
4462 outs() << " + " << format("0x%" PRIx64, cro.baseProperties);
4463 } else
4464 outs() << format("0x%" PRIx64, cro.baseProperties);
4465 outs() << "\n";
4466 if (cro.baseProperties + n_value != 0)
4467 print_objc_property_list64(cro.baseProperties + n_value, info);
4468
Rafael Espindolab9091322015-10-24 23:19:10 +00004469 is_meta_class = (cro.flags & RO_META) != 0;
Richard Smith81ff44d2015-10-09 22:09:56 +00004470 return true;
Kevin Enderby0fc11822015-04-01 20:57:01 +00004471}
4472
Richard Smith81ff44d2015-10-09 22:09:56 +00004473static bool print_class_ro32_t(uint32_t p, struct DisassembleInfo *info,
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004474 bool &is_meta_class) {
4475 struct class_ro32_t cro;
4476 const char *r;
4477 uint32_t offset, xoffset, left;
4478 SectionRef S, xS;
4479 const char *name;
4480
4481 r = get_pointer_32(p, offset, left, S, info);
4482 if (r == nullptr)
Richard Smith81ff44d2015-10-09 22:09:56 +00004483 return false;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004484 memset(&cro, '\0', sizeof(struct class_ro32_t));
4485 if (left < sizeof(struct class_ro32_t)) {
4486 memcpy(&cro, r, left);
4487 outs() << " (class_ro_t entends past the end of the section)\n";
4488 } else
4489 memcpy(&cro, r, sizeof(struct class_ro32_t));
4490 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4491 swapStruct(cro);
4492 outs() << " flags " << format("0x%" PRIx32, cro.flags);
4493 if (cro.flags & RO_META)
4494 outs() << " RO_META";
4495 if (cro.flags & RO_ROOT)
4496 outs() << " RO_ROOT";
4497 if (cro.flags & RO_HAS_CXX_STRUCTORS)
4498 outs() << " RO_HAS_CXX_STRUCTORS";
4499 outs() << "\n";
4500 outs() << " instanceStart " << cro.instanceStart << "\n";
4501 outs() << " instanceSize " << cro.instanceSize << "\n";
4502 outs() << " ivarLayout " << format("0x%" PRIx32, cro.ivarLayout)
4503 << "\n";
4504 print_layout_map32(cro.ivarLayout, info);
4505
4506 outs() << " name " << format("0x%" PRIx32, cro.name);
4507 name = get_pointer_32(cro.name, xoffset, left, xS, info);
4508 if (name != nullptr)
4509 outs() << format(" %.*s", left, name);
4510 outs() << "\n";
4511
4512 outs() << " baseMethods "
4513 << format("0x%" PRIx32, cro.baseMethods)
4514 << " (struct method_list_t *)\n";
4515 if (cro.baseMethods != 0)
4516 print_method_list32_t(cro.baseMethods, info, "");
4517
4518 outs() << " baseProtocols "
4519 << format("0x%" PRIx32, cro.baseProtocols) << "\n";
4520 if (cro.baseProtocols != 0)
4521 print_protocol_list32_t(cro.baseProtocols, info);
4522 outs() << " ivars " << format("0x%" PRIx32, cro.ivars)
4523 << "\n";
4524 if (cro.ivars != 0)
4525 print_ivar_list32_t(cro.ivars, info);
4526 outs() << " weakIvarLayout "
4527 << format("0x%" PRIx32, cro.weakIvarLayout) << "\n";
4528 print_layout_map32(cro.weakIvarLayout, info);
4529 outs() << " baseProperties "
4530 << format("0x%" PRIx32, cro.baseProperties) << "\n";
4531 if (cro.baseProperties != 0)
4532 print_objc_property_list32(cro.baseProperties, info);
Rafael Espindolab9091322015-10-24 23:19:10 +00004533 is_meta_class = (cro.flags & RO_META) != 0;
Richard Smith81ff44d2015-10-09 22:09:56 +00004534 return true;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004535}
4536
Kevin Enderby0fc11822015-04-01 20:57:01 +00004537static void print_class64_t(uint64_t p, struct DisassembleInfo *info) {
4538 struct class64_t c;
4539 const char *r;
4540 uint32_t offset, left;
4541 SectionRef S;
4542 const char *name;
4543 uint64_t isa_n_value, n_value;
4544
4545 r = get_pointer_64(p, offset, left, S, info);
4546 if (r == nullptr || left < sizeof(struct class64_t))
4547 return;
Chandler Carruth33e58902016-11-04 07:10:24 +00004548 memcpy(&c, r, sizeof(struct class64_t));
Kevin Enderby0fc11822015-04-01 20:57:01 +00004549 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4550 swapStruct(c);
4551
4552 outs() << " isa " << format("0x%" PRIx64, c.isa);
4553 name = get_symbol_64(offset + offsetof(struct class64_t, isa), S, info,
4554 isa_n_value, c.isa);
4555 if (name != nullptr)
4556 outs() << " " << name;
4557 outs() << "\n";
4558
4559 outs() << " superclass " << format("0x%" PRIx64, c.superclass);
4560 name = get_symbol_64(offset + offsetof(struct class64_t, superclass), S, info,
4561 n_value, c.superclass);
4562 if (name != nullptr)
4563 outs() << " " << name;
4564 outs() << "\n";
4565
4566 outs() << " cache " << format("0x%" PRIx64, c.cache);
4567 name = get_symbol_64(offset + offsetof(struct class64_t, cache), S, info,
4568 n_value, c.cache);
4569 if (name != nullptr)
4570 outs() << " " << name;
4571 outs() << "\n";
4572
4573 outs() << " vtable " << format("0x%" PRIx64, c.vtable);
4574 name = get_symbol_64(offset + offsetof(struct class64_t, vtable), S, info,
4575 n_value, c.vtable);
4576 if (name != nullptr)
4577 outs() << " " << name;
4578 outs() << "\n";
4579
4580 name = get_symbol_64(offset + offsetof(struct class64_t, data), S, info,
4581 n_value, c.data);
4582 outs() << " data ";
4583 if (n_value != 0) {
4584 if (info->verbose && name != nullptr)
4585 outs() << name;
4586 else
4587 outs() << format("0x%" PRIx64, n_value);
4588 if (c.data != 0)
4589 outs() << " + " << format("0x%" PRIx64, c.data);
4590 } else
4591 outs() << format("0x%" PRIx64, c.data);
4592 outs() << " (struct class_ro_t *)";
4593
4594 // This is a Swift class if some of the low bits of the pointer are set.
4595 if ((c.data + n_value) & 0x7)
4596 outs() << " Swift class";
4597 outs() << "\n";
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004598 bool is_meta_class;
Richard Smith81ff44d2015-10-09 22:09:56 +00004599 if (!print_class_ro64_t((c.data + n_value) & ~0x7, info, is_meta_class))
4600 return;
Kevin Enderby0fc11822015-04-01 20:57:01 +00004601
Kevin Enderbyaac75382015-10-08 16:56:35 +00004602 if (!is_meta_class &&
4603 c.isa + isa_n_value != p &&
4604 c.isa + isa_n_value != 0 &&
4605 info->depth < 100) {
4606 info->depth++;
4607 outs() << "Meta Class\n";
4608 print_class64_t(c.isa + isa_n_value, info);
Kevin Enderby0fc11822015-04-01 20:57:01 +00004609 }
4610}
4611
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004612static void print_class32_t(uint32_t p, struct DisassembleInfo *info) {
4613 struct class32_t c;
4614 const char *r;
4615 uint32_t offset, left;
4616 SectionRef S;
4617 const char *name;
4618
4619 r = get_pointer_32(p, offset, left, S, info);
4620 if (r == nullptr)
4621 return;
4622 memset(&c, '\0', sizeof(struct class32_t));
4623 if (left < sizeof(struct class32_t)) {
4624 memcpy(&c, r, left);
4625 outs() << " (class_t entends past the end of the section)\n";
4626 } else
4627 memcpy(&c, r, sizeof(struct class32_t));
4628 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4629 swapStruct(c);
4630
4631 outs() << " isa " << format("0x%" PRIx32, c.isa);
4632 name =
4633 get_symbol_32(offset + offsetof(struct class32_t, isa), S, info, c.isa);
4634 if (name != nullptr)
4635 outs() << " " << name;
4636 outs() << "\n";
4637
4638 outs() << " superclass " << format("0x%" PRIx32, c.superclass);
4639 name = get_symbol_32(offset + offsetof(struct class32_t, superclass), S, info,
4640 c.superclass);
4641 if (name != nullptr)
4642 outs() << " " << name;
4643 outs() << "\n";
4644
4645 outs() << " cache " << format("0x%" PRIx32, c.cache);
4646 name = get_symbol_32(offset + offsetof(struct class32_t, cache), S, info,
4647 c.cache);
4648 if (name != nullptr)
4649 outs() << " " << name;
4650 outs() << "\n";
4651
4652 outs() << " vtable " << format("0x%" PRIx32, c.vtable);
4653 name = get_symbol_32(offset + offsetof(struct class32_t, vtable), S, info,
4654 c.vtable);
4655 if (name != nullptr)
4656 outs() << " " << name;
4657 outs() << "\n";
4658
4659 name =
4660 get_symbol_32(offset + offsetof(struct class32_t, data), S, info, c.data);
4661 outs() << " data " << format("0x%" PRIx32, c.data)
4662 << " (struct class_ro_t *)";
4663
4664 // This is a Swift class if some of the low bits of the pointer are set.
4665 if (c.data & 0x3)
4666 outs() << " Swift class";
4667 outs() << "\n";
4668 bool is_meta_class;
Richard Smith81ff44d2015-10-09 22:09:56 +00004669 if (!print_class_ro32_t(c.data & ~0x3, info, is_meta_class))
4670 return;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004671
Hans Wennborgcc9deb42015-09-29 18:02:48 +00004672 if (!is_meta_class) {
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004673 outs() << "Meta Class\n";
4674 print_class32_t(c.isa, info);
4675 }
4676}
4677
Kevin Enderby846c0002015-04-16 17:19:59 +00004678static void print_objc_class_t(struct objc_class_t *objc_class,
4679 struct DisassembleInfo *info) {
4680 uint32_t offset, left, xleft;
4681 const char *name, *p, *ivar_list;
4682 SectionRef S;
4683 int32_t i;
4684 struct objc_ivar_list_t objc_ivar_list;
4685 struct objc_ivar_t ivar;
4686
4687 outs() << "\t\t isa " << format("0x%08" PRIx32, objc_class->isa);
4688 if (info->verbose && CLS_GETINFO(objc_class, CLS_META)) {
4689 name = get_pointer_32(objc_class->isa, offset, left, S, info, true);
4690 if (name != nullptr)
4691 outs() << format(" %.*s", left, name);
4692 else
4693 outs() << " (not in an __OBJC section)";
4694 }
4695 outs() << "\n";
4696
4697 outs() << "\t super_class "
4698 << format("0x%08" PRIx32, objc_class->super_class);
4699 if (info->verbose) {
4700 name = get_pointer_32(objc_class->super_class, offset, left, S, info, true);
4701 if (name != nullptr)
4702 outs() << format(" %.*s", left, name);
4703 else
4704 outs() << " (not in an __OBJC section)";
4705 }
4706 outs() << "\n";
4707
4708 outs() << "\t\t name " << format("0x%08" PRIx32, objc_class->name);
4709 if (info->verbose) {
4710 name = get_pointer_32(objc_class->name, offset, left, S, info, true);
4711 if (name != nullptr)
4712 outs() << format(" %.*s", left, name);
4713 else
4714 outs() << " (not in an __OBJC section)";
4715 }
4716 outs() << "\n";
4717
4718 outs() << "\t\t version " << format("0x%08" PRIx32, objc_class->version)
4719 << "\n";
4720
4721 outs() << "\t\t info " << format("0x%08" PRIx32, objc_class->info);
4722 if (info->verbose) {
4723 if (CLS_GETINFO(objc_class, CLS_CLASS))
4724 outs() << " CLS_CLASS";
4725 else if (CLS_GETINFO(objc_class, CLS_META))
4726 outs() << " CLS_META";
4727 }
4728 outs() << "\n";
4729
4730 outs() << "\t instance_size "
4731 << format("0x%08" PRIx32, objc_class->instance_size) << "\n";
4732
4733 p = get_pointer_32(objc_class->ivars, offset, left, S, info, true);
4734 outs() << "\t\t ivars " << format("0x%08" PRIx32, objc_class->ivars);
4735 if (p != nullptr) {
4736 if (left > sizeof(struct objc_ivar_list_t)) {
4737 outs() << "\n";
4738 memcpy(&objc_ivar_list, p, sizeof(struct objc_ivar_list_t));
4739 } else {
4740 outs() << " (entends past the end of the section)\n";
4741 memset(&objc_ivar_list, '\0', sizeof(struct objc_ivar_list_t));
4742 memcpy(&objc_ivar_list, p, left);
4743 }
4744 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4745 swapStruct(objc_ivar_list);
4746 outs() << "\t\t ivar_count " << objc_ivar_list.ivar_count << "\n";
4747 ivar_list = p + sizeof(struct objc_ivar_list_t);
4748 for (i = 0; i < objc_ivar_list.ivar_count; i++) {
4749 if ((i + 1) * sizeof(struct objc_ivar_t) > left) {
4750 outs() << "\t\t remaining ivar's extend past the of the section\n";
4751 break;
4752 }
4753 memcpy(&ivar, ivar_list + i * sizeof(struct objc_ivar_t),
4754 sizeof(struct objc_ivar_t));
4755 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4756 swapStruct(ivar);
4757
4758 outs() << "\t\t\tivar_name " << format("0x%08" PRIx32, ivar.ivar_name);
4759 if (info->verbose) {
4760 name = get_pointer_32(ivar.ivar_name, offset, xleft, S, info, true);
4761 if (name != nullptr)
4762 outs() << format(" %.*s", xleft, name);
4763 else
4764 outs() << " (not in an __OBJC section)";
4765 }
4766 outs() << "\n";
4767
4768 outs() << "\t\t\tivar_type " << format("0x%08" PRIx32, ivar.ivar_type);
4769 if (info->verbose) {
4770 name = get_pointer_32(ivar.ivar_type, offset, xleft, S, info, true);
4771 if (name != nullptr)
4772 outs() << format(" %.*s", xleft, name);
4773 else
4774 outs() << " (not in an __OBJC section)";
4775 }
4776 outs() << "\n";
4777
4778 outs() << "\t\t ivar_offset "
4779 << format("0x%08" PRIx32, ivar.ivar_offset) << "\n";
4780 }
4781 } else {
4782 outs() << " (not in an __OBJC section)\n";
4783 }
4784
4785 outs() << "\t\t methods " << format("0x%08" PRIx32, objc_class->methodLists);
4786 if (print_method_list(objc_class->methodLists, info))
4787 outs() << " (not in an __OBJC section)\n";
4788
4789 outs() << "\t\t cache " << format("0x%08" PRIx32, objc_class->cache)
4790 << "\n";
4791
4792 outs() << "\t\tprotocols " << format("0x%08" PRIx32, objc_class->protocols);
4793 if (print_protocol_list(objc_class->protocols, 16, info))
4794 outs() << " (not in an __OBJC section)\n";
4795}
4796
4797static void print_objc_objc_category_t(struct objc_category_t *objc_category,
4798 struct DisassembleInfo *info) {
4799 uint32_t offset, left;
4800 const char *name;
4801 SectionRef S;
4802
4803 outs() << "\t category name "
4804 << format("0x%08" PRIx32, objc_category->category_name);
4805 if (info->verbose) {
4806 name = get_pointer_32(objc_category->category_name, offset, left, S, info,
4807 true);
4808 if (name != nullptr)
4809 outs() << format(" %.*s", left, name);
4810 else
4811 outs() << " (not in an __OBJC section)";
4812 }
4813 outs() << "\n";
4814
4815 outs() << "\t\t class name "
4816 << format("0x%08" PRIx32, objc_category->class_name);
4817 if (info->verbose) {
4818 name =
4819 get_pointer_32(objc_category->class_name, offset, left, S, info, true);
4820 if (name != nullptr)
4821 outs() << format(" %.*s", left, name);
4822 else
4823 outs() << " (not in an __OBJC section)";
4824 }
4825 outs() << "\n";
4826
4827 outs() << "\t instance methods "
4828 << format("0x%08" PRIx32, objc_category->instance_methods);
4829 if (print_method_list(objc_category->instance_methods, info))
4830 outs() << " (not in an __OBJC section)\n";
4831
4832 outs() << "\t class methods "
4833 << format("0x%08" PRIx32, objc_category->class_methods);
4834 if (print_method_list(objc_category->class_methods, info))
4835 outs() << " (not in an __OBJC section)\n";
4836}
4837
Kevin Enderby0fc11822015-04-01 20:57:01 +00004838static void print_category64_t(uint64_t p, struct DisassembleInfo *info) {
4839 struct category64_t c;
4840 const char *r;
4841 uint32_t offset, xoffset, left;
4842 SectionRef S, xS;
4843 const char *name, *sym_name;
4844 uint64_t n_value;
4845
4846 r = get_pointer_64(p, offset, left, S, info);
4847 if (r == nullptr)
4848 return;
4849 memset(&c, '\0', sizeof(struct category64_t));
4850 if (left < sizeof(struct category64_t)) {
4851 memcpy(&c, r, left);
4852 outs() << " (category_t entends past the end of the section)\n";
4853 } else
4854 memcpy(&c, r, sizeof(struct category64_t));
4855 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4856 swapStruct(c);
4857
4858 outs() << " name ";
4859 sym_name = get_symbol_64(offset + offsetof(struct category64_t, name), S,
4860 info, n_value, c.name);
4861 if (n_value != 0) {
4862 if (info->verbose && sym_name != nullptr)
4863 outs() << sym_name;
4864 else
4865 outs() << format("0x%" PRIx64, n_value);
4866 if (c.name != 0)
4867 outs() << " + " << format("0x%" PRIx64, c.name);
4868 } else
4869 outs() << format("0x%" PRIx64, c.name);
4870 name = get_pointer_64(c.name + n_value, xoffset, left, xS, info);
4871 if (name != nullptr)
4872 outs() << format(" %.*s", left, name);
4873 outs() << "\n";
4874
4875 outs() << " cls ";
4876 sym_name = get_symbol_64(offset + offsetof(struct category64_t, cls), S, info,
4877 n_value, c.cls);
4878 if (n_value != 0) {
4879 if (info->verbose && sym_name != nullptr)
4880 outs() << sym_name;
4881 else
4882 outs() << format("0x%" PRIx64, n_value);
4883 if (c.cls != 0)
4884 outs() << " + " << format("0x%" PRIx64, c.cls);
4885 } else
4886 outs() << format("0x%" PRIx64, c.cls);
4887 outs() << "\n";
4888 if (c.cls + n_value != 0)
4889 print_class64_t(c.cls + n_value, info);
4890
4891 outs() << " instanceMethods ";
4892 sym_name =
4893 get_symbol_64(offset + offsetof(struct category64_t, instanceMethods), S,
4894 info, n_value, c.instanceMethods);
4895 if (n_value != 0) {
4896 if (info->verbose && sym_name != nullptr)
4897 outs() << sym_name;
4898 else
4899 outs() << format("0x%" PRIx64, n_value);
4900 if (c.instanceMethods != 0)
4901 outs() << " + " << format("0x%" PRIx64, c.instanceMethods);
4902 } else
4903 outs() << format("0x%" PRIx64, c.instanceMethods);
4904 outs() << "\n";
4905 if (c.instanceMethods + n_value != 0)
4906 print_method_list64_t(c.instanceMethods + n_value, info, "");
4907
4908 outs() << " classMethods ";
4909 sym_name = get_symbol_64(offset + offsetof(struct category64_t, classMethods),
4910 S, info, n_value, c.classMethods);
4911 if (n_value != 0) {
4912 if (info->verbose && sym_name != nullptr)
4913 outs() << sym_name;
4914 else
4915 outs() << format("0x%" PRIx64, n_value);
4916 if (c.classMethods != 0)
4917 outs() << " + " << format("0x%" PRIx64, c.classMethods);
4918 } else
4919 outs() << format("0x%" PRIx64, c.classMethods);
4920 outs() << "\n";
4921 if (c.classMethods + n_value != 0)
4922 print_method_list64_t(c.classMethods + n_value, info, "");
4923
4924 outs() << " protocols ";
4925 sym_name = get_symbol_64(offset + offsetof(struct category64_t, protocols), S,
4926 info, n_value, c.protocols);
4927 if (n_value != 0) {
4928 if (info->verbose && sym_name != nullptr)
4929 outs() << sym_name;
4930 else
4931 outs() << format("0x%" PRIx64, n_value);
4932 if (c.protocols != 0)
4933 outs() << " + " << format("0x%" PRIx64, c.protocols);
4934 } else
4935 outs() << format("0x%" PRIx64, c.protocols);
4936 outs() << "\n";
4937 if (c.protocols + n_value != 0)
4938 print_protocol_list64_t(c.protocols + n_value, info);
4939
4940 outs() << "instanceProperties ";
4941 sym_name =
4942 get_symbol_64(offset + offsetof(struct category64_t, instanceProperties),
4943 S, info, n_value, c.instanceProperties);
4944 if (n_value != 0) {
4945 if (info->verbose && sym_name != nullptr)
4946 outs() << sym_name;
4947 else
4948 outs() << format("0x%" PRIx64, n_value);
4949 if (c.instanceProperties != 0)
4950 outs() << " + " << format("0x%" PRIx64, c.instanceProperties);
4951 } else
4952 outs() << format("0x%" PRIx64, c.instanceProperties);
4953 outs() << "\n";
4954 if (c.instanceProperties + n_value != 0)
4955 print_objc_property_list64(c.instanceProperties + n_value, info);
4956}
4957
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004958static void print_category32_t(uint32_t p, struct DisassembleInfo *info) {
4959 struct category32_t c;
4960 const char *r;
4961 uint32_t offset, left;
4962 SectionRef S, xS;
4963 const char *name;
4964
4965 r = get_pointer_32(p, offset, left, S, info);
4966 if (r == nullptr)
4967 return;
4968 memset(&c, '\0', sizeof(struct category32_t));
4969 if (left < sizeof(struct category32_t)) {
4970 memcpy(&c, r, left);
4971 outs() << " (category_t entends past the end of the section)\n";
4972 } else
4973 memcpy(&c, r, sizeof(struct category32_t));
4974 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4975 swapStruct(c);
4976
4977 outs() << " name " << format("0x%" PRIx32, c.name);
4978 name = get_symbol_32(offset + offsetof(struct category32_t, name), S, info,
4979 c.name);
Hans Wennborgcc9deb42015-09-29 18:02:48 +00004980 if (name)
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004981 outs() << " " << name;
4982 outs() << "\n";
4983
4984 outs() << " cls " << format("0x%" PRIx32, c.cls) << "\n";
4985 if (c.cls != 0)
4986 print_class32_t(c.cls, info);
4987 outs() << " instanceMethods " << format("0x%" PRIx32, c.instanceMethods)
4988 << "\n";
4989 if (c.instanceMethods != 0)
4990 print_method_list32_t(c.instanceMethods, info, "");
4991 outs() << " classMethods " << format("0x%" PRIx32, c.classMethods)
4992 << "\n";
4993 if (c.classMethods != 0)
4994 print_method_list32_t(c.classMethods, info, "");
4995 outs() << " protocols " << format("0x%" PRIx32, c.protocols) << "\n";
4996 if (c.protocols != 0)
4997 print_protocol_list32_t(c.protocols, info);
4998 outs() << "instanceProperties " << format("0x%" PRIx32, c.instanceProperties)
4999 << "\n";
5000 if (c.instanceProperties != 0)
5001 print_objc_property_list32(c.instanceProperties, info);
5002}
5003
Kevin Enderby0fc11822015-04-01 20:57:01 +00005004static void print_message_refs64(SectionRef S, struct DisassembleInfo *info) {
5005 uint32_t i, left, offset, xoffset;
5006 uint64_t p, n_value;
5007 struct message_ref64 mr;
5008 const char *name, *sym_name;
5009 const char *r;
5010 SectionRef xS;
5011
5012 if (S == SectionRef())
5013 return;
5014
5015 StringRef SectName;
5016 S.getName(SectName);
5017 DataRefImpl Ref = S.getRawDataRefImpl();
5018 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5019 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5020 offset = 0;
5021 for (i = 0; i < S.getSize(); i += sizeof(struct message_ref64)) {
5022 p = S.getAddress() + i;
5023 r = get_pointer_64(p, offset, left, S, info);
5024 if (r == nullptr)
5025 return;
5026 memset(&mr, '\0', sizeof(struct message_ref64));
5027 if (left < sizeof(struct message_ref64)) {
5028 memcpy(&mr, r, left);
5029 outs() << " (message_ref entends past the end of the section)\n";
5030 } else
5031 memcpy(&mr, r, sizeof(struct message_ref64));
5032 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5033 swapStruct(mr);
5034
5035 outs() << " imp ";
5036 name = get_symbol_64(offset + offsetof(struct message_ref64, imp), S, info,
5037 n_value, mr.imp);
5038 if (n_value != 0) {
5039 outs() << format("0x%" PRIx64, n_value) << " ";
5040 if (mr.imp != 0)
5041 outs() << "+ " << format("0x%" PRIx64, mr.imp) << " ";
5042 } else
5043 outs() << format("0x%" PRIx64, mr.imp) << " ";
5044 if (name != nullptr)
5045 outs() << " " << name;
5046 outs() << "\n";
5047
5048 outs() << " sel ";
5049 sym_name = get_symbol_64(offset + offsetof(struct message_ref64, sel), S,
5050 info, n_value, mr.sel);
5051 if (n_value != 0) {
5052 if (info->verbose && sym_name != nullptr)
5053 outs() << sym_name;
5054 else
5055 outs() << format("0x%" PRIx64, n_value);
5056 if (mr.sel != 0)
5057 outs() << " + " << format("0x%" PRIx64, mr.sel);
5058 } else
5059 outs() << format("0x%" PRIx64, mr.sel);
5060 name = get_pointer_64(mr.sel + n_value, xoffset, left, xS, info);
5061 if (name != nullptr)
5062 outs() << format(" %.*s", left, name);
5063 outs() << "\n";
5064
5065 offset += sizeof(struct message_ref64);
5066 }
5067}
5068
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005069static void print_message_refs32(SectionRef S, struct DisassembleInfo *info) {
5070 uint32_t i, left, offset, xoffset, p;
5071 struct message_ref32 mr;
5072 const char *name, *r;
5073 SectionRef xS;
5074
5075 if (S == SectionRef())
5076 return;
5077
5078 StringRef SectName;
5079 S.getName(SectName);
5080 DataRefImpl Ref = S.getRawDataRefImpl();
5081 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5082 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5083 offset = 0;
5084 for (i = 0; i < S.getSize(); i += sizeof(struct message_ref64)) {
5085 p = S.getAddress() + i;
5086 r = get_pointer_32(p, offset, left, S, info);
5087 if (r == nullptr)
5088 return;
5089 memset(&mr, '\0', sizeof(struct message_ref32));
5090 if (left < sizeof(struct message_ref32)) {
5091 memcpy(&mr, r, left);
5092 outs() << " (message_ref entends past the end of the section)\n";
5093 } else
5094 memcpy(&mr, r, sizeof(struct message_ref32));
5095 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5096 swapStruct(mr);
5097
5098 outs() << " imp " << format("0x%" PRIx32, mr.imp);
5099 name = get_symbol_32(offset + offsetof(struct message_ref32, imp), S, info,
5100 mr.imp);
5101 if (name != nullptr)
5102 outs() << " " << name;
5103 outs() << "\n";
5104
5105 outs() << " sel " << format("0x%" PRIx32, mr.sel);
5106 name = get_pointer_32(mr.sel, xoffset, left, xS, info);
5107 if (name != nullptr)
5108 outs() << " " << name;
5109 outs() << "\n";
5110
5111 offset += sizeof(struct message_ref32);
5112 }
5113}
5114
Kevin Enderby0fc11822015-04-01 20:57:01 +00005115static void print_image_info64(SectionRef S, struct DisassembleInfo *info) {
5116 uint32_t left, offset, swift_version;
5117 uint64_t p;
5118 struct objc_image_info64 o;
5119 const char *r;
5120
Kevin Enderbyaf7c9d02015-10-09 16:48:44 +00005121 if (S == SectionRef())
5122 return;
5123
Kevin Enderby0fc11822015-04-01 20:57:01 +00005124 StringRef SectName;
5125 S.getName(SectName);
5126 DataRefImpl Ref = S.getRawDataRefImpl();
5127 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5128 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5129 p = S.getAddress();
5130 r = get_pointer_64(p, offset, left, S, info);
5131 if (r == nullptr)
5132 return;
5133 memset(&o, '\0', sizeof(struct objc_image_info64));
5134 if (left < sizeof(struct objc_image_info64)) {
5135 memcpy(&o, r, left);
5136 outs() << " (objc_image_info entends past the end of the section)\n";
5137 } else
5138 memcpy(&o, r, sizeof(struct objc_image_info64));
5139 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5140 swapStruct(o);
5141 outs() << " version " << o.version << "\n";
5142 outs() << " flags " << format("0x%" PRIx32, o.flags);
5143 if (o.flags & OBJC_IMAGE_IS_REPLACEMENT)
5144 outs() << " OBJC_IMAGE_IS_REPLACEMENT";
5145 if (o.flags & OBJC_IMAGE_SUPPORTS_GC)
5146 outs() << " OBJC_IMAGE_SUPPORTS_GC";
5147 swift_version = (o.flags >> 8) & 0xff;
5148 if (swift_version != 0) {
5149 if (swift_version == 1)
5150 outs() << " Swift 1.0";
5151 else if (swift_version == 2)
5152 outs() << " Swift 1.1";
5153 else
5154 outs() << " unknown future Swift version (" << swift_version << ")";
5155 }
5156 outs() << "\n";
5157}
5158
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005159static void print_image_info32(SectionRef S, struct DisassembleInfo *info) {
5160 uint32_t left, offset, swift_version, p;
5161 struct objc_image_info32 o;
5162 const char *r;
5163
Kevin Enderby19be2512016-04-21 19:49:29 +00005164 if (S == SectionRef())
5165 return;
5166
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005167 StringRef SectName;
5168 S.getName(SectName);
5169 DataRefImpl Ref = S.getRawDataRefImpl();
5170 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5171 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5172 p = S.getAddress();
5173 r = get_pointer_32(p, offset, left, S, info);
5174 if (r == nullptr)
5175 return;
5176 memset(&o, '\0', sizeof(struct objc_image_info32));
5177 if (left < sizeof(struct objc_image_info32)) {
5178 memcpy(&o, r, left);
5179 outs() << " (objc_image_info entends past the end of the section)\n";
5180 } else
5181 memcpy(&o, r, sizeof(struct objc_image_info32));
5182 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5183 swapStruct(o);
5184 outs() << " version " << o.version << "\n";
5185 outs() << " flags " << format("0x%" PRIx32, o.flags);
5186 if (o.flags & OBJC_IMAGE_IS_REPLACEMENT)
5187 outs() << " OBJC_IMAGE_IS_REPLACEMENT";
5188 if (o.flags & OBJC_IMAGE_SUPPORTS_GC)
5189 outs() << " OBJC_IMAGE_SUPPORTS_GC";
5190 swift_version = (o.flags >> 8) & 0xff;
5191 if (swift_version != 0) {
5192 if (swift_version == 1)
5193 outs() << " Swift 1.0";
5194 else if (swift_version == 2)
5195 outs() << " Swift 1.1";
5196 else
5197 outs() << " unknown future Swift version (" << swift_version << ")";
5198 }
5199 outs() << "\n";
5200}
5201
Kevin Enderby846c0002015-04-16 17:19:59 +00005202static void print_image_info(SectionRef S, struct DisassembleInfo *info) {
5203 uint32_t left, offset, p;
5204 struct imageInfo_t o;
5205 const char *r;
5206
5207 StringRef SectName;
5208 S.getName(SectName);
5209 DataRefImpl Ref = S.getRawDataRefImpl();
5210 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5211 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5212 p = S.getAddress();
5213 r = get_pointer_32(p, offset, left, S, info);
5214 if (r == nullptr)
5215 return;
5216 memset(&o, '\0', sizeof(struct imageInfo_t));
5217 if (left < sizeof(struct imageInfo_t)) {
5218 memcpy(&o, r, left);
5219 outs() << " (imageInfo entends past the end of the section)\n";
5220 } else
5221 memcpy(&o, r, sizeof(struct imageInfo_t));
5222 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5223 swapStruct(o);
5224 outs() << " version " << o.version << "\n";
5225 outs() << " flags " << format("0x%" PRIx32, o.flags);
5226 if (o.flags & 0x1)
5227 outs() << " F&C";
5228 if (o.flags & 0x2)
5229 outs() << " GC";
5230 if (o.flags & 0x4)
5231 outs() << " GC-only";
5232 else
5233 outs() << " RR";
5234 outs() << "\n";
5235}
5236
Kevin Enderby0fc11822015-04-01 20:57:01 +00005237static void printObjc2_64bit_MetaData(MachOObjectFile *O, bool verbose) {
5238 SymbolAddressMap AddrMap;
5239 if (verbose)
5240 CreateSymbolAddressMap(O, &AddrMap);
5241
5242 std::vector<SectionRef> Sections;
5243 for (const SectionRef &Section : O->sections()) {
5244 StringRef SectName;
5245 Section.getName(SectName);
5246 Sections.push_back(Section);
5247 }
5248
5249 struct DisassembleInfo info;
5250 // Set up the block of info used by the Symbolizer call backs.
5251 info.verbose = verbose;
5252 info.O = O;
5253 info.AddrMap = &AddrMap;
5254 info.Sections = &Sections;
5255 info.class_name = nullptr;
5256 info.selector_name = nullptr;
5257 info.method = nullptr;
5258 info.demangled_name = nullptr;
5259 info.bindtable = nullptr;
5260 info.adrp_addr = 0;
5261 info.adrp_inst = 0;
5262
Kevin Enderbyaac75382015-10-08 16:56:35 +00005263 info.depth = 0;
Davide Italiano62507042015-12-11 22:27:59 +00005264 SectionRef CL = get_section(O, "__OBJC2", "__class_list");
5265 if (CL == SectionRef())
5266 CL = get_section(O, "__DATA", "__objc_classlist");
5267 info.S = CL;
5268 walk_pointer_list_64("class", CL, O, &info, print_class64_t);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005269
Davide Italiano62507042015-12-11 22:27:59 +00005270 SectionRef CR = get_section(O, "__OBJC2", "__class_refs");
5271 if (CR == SectionRef())
5272 CR = get_section(O, "__DATA", "__objc_classrefs");
5273 info.S = CR;
5274 walk_pointer_list_64("class refs", CR, O, &info, nullptr);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005275
Davide Italiano62507042015-12-11 22:27:59 +00005276 SectionRef SR = get_section(O, "__OBJC2", "__super_refs");
5277 if (SR == SectionRef())
5278 SR = get_section(O, "__DATA", "__objc_superrefs");
5279 info.S = SR;
5280 walk_pointer_list_64("super refs", SR, O, &info, nullptr);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005281
Davide Italiano62507042015-12-11 22:27:59 +00005282 SectionRef CA = get_section(O, "__OBJC2", "__category_list");
5283 if (CA == SectionRef())
5284 CA = get_section(O, "__DATA", "__objc_catlist");
5285 info.S = CA;
5286 walk_pointer_list_64("category", CA, O, &info, print_category64_t);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005287
Davide Italiano62507042015-12-11 22:27:59 +00005288 SectionRef PL = get_section(O, "__OBJC2", "__protocol_list");
5289 if (PL == SectionRef())
5290 PL = get_section(O, "__DATA", "__objc_protolist");
5291 info.S = PL;
5292 walk_pointer_list_64("protocol", PL, O, &info, nullptr);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005293
Davide Italiano62507042015-12-11 22:27:59 +00005294 SectionRef MR = get_section(O, "__OBJC2", "__message_refs");
5295 if (MR == SectionRef())
5296 MR = get_section(O, "__DATA", "__objc_msgrefs");
5297 info.S = MR;
5298 print_message_refs64(MR, &info);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005299
Davide Italiano62507042015-12-11 22:27:59 +00005300 SectionRef II = get_section(O, "__OBJC2", "__image_info");
5301 if (II == SectionRef())
5302 II = get_section(O, "__DATA", "__objc_imageinfo");
5303 info.S = II;
5304 print_image_info64(II, &info);
Kevin Enderby0bc6ed42015-04-01 21:50:45 +00005305
5306 if (info.bindtable != nullptr)
5307 delete info.bindtable;
Kevin Enderby0fc11822015-04-01 20:57:01 +00005308}
5309
5310static void printObjc2_32bit_MetaData(MachOObjectFile *O, bool verbose) {
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005311 SymbolAddressMap AddrMap;
5312 if (verbose)
5313 CreateSymbolAddressMap(O, &AddrMap);
5314
5315 std::vector<SectionRef> Sections;
5316 for (const SectionRef &Section : O->sections()) {
5317 StringRef SectName;
5318 Section.getName(SectName);
5319 Sections.push_back(Section);
5320 }
5321
5322 struct DisassembleInfo info;
5323 // Set up the block of info used by the Symbolizer call backs.
5324 info.verbose = verbose;
5325 info.O = O;
5326 info.AddrMap = &AddrMap;
5327 info.Sections = &Sections;
5328 info.class_name = nullptr;
5329 info.selector_name = nullptr;
5330 info.method = nullptr;
5331 info.demangled_name = nullptr;
5332 info.bindtable = nullptr;
5333 info.adrp_addr = 0;
5334 info.adrp_inst = 0;
5335
5336 const SectionRef CL = get_section(O, "__OBJC2", "__class_list");
5337 if (CL != SectionRef()) {
5338 info.S = CL;
5339 walk_pointer_list_32("class", CL, O, &info, print_class32_t);
5340 } else {
5341 const SectionRef CL = get_section(O, "__DATA", "__objc_classlist");
5342 info.S = CL;
5343 walk_pointer_list_32("class", CL, O, &info, print_class32_t);
5344 }
5345
5346 const SectionRef CR = get_section(O, "__OBJC2", "__class_refs");
5347 if (CR != SectionRef()) {
5348 info.S = CR;
5349 walk_pointer_list_32("class refs", CR, O, &info, nullptr);
5350 } else {
5351 const SectionRef CR = get_section(O, "__DATA", "__objc_classrefs");
5352 info.S = CR;
5353 walk_pointer_list_32("class refs", CR, O, &info, nullptr);
5354 }
5355
5356 const SectionRef SR = get_section(O, "__OBJC2", "__super_refs");
5357 if (SR != SectionRef()) {
5358 info.S = SR;
5359 walk_pointer_list_32("super refs", SR, O, &info, nullptr);
5360 } else {
5361 const SectionRef SR = get_section(O, "__DATA", "__objc_superrefs");
5362 info.S = SR;
5363 walk_pointer_list_32("super refs", SR, O, &info, nullptr);
5364 }
5365
5366 const SectionRef CA = get_section(O, "__OBJC2", "__category_list");
5367 if (CA != SectionRef()) {
5368 info.S = CA;
5369 walk_pointer_list_32("category", CA, O, &info, print_category32_t);
5370 } else {
5371 const SectionRef CA = get_section(O, "__DATA", "__objc_catlist");
5372 info.S = CA;
5373 walk_pointer_list_32("category", CA, O, &info, print_category32_t);
5374 }
5375
5376 const SectionRef PL = get_section(O, "__OBJC2", "__protocol_list");
5377 if (PL != SectionRef()) {
5378 info.S = PL;
5379 walk_pointer_list_32("protocol", PL, O, &info, nullptr);
5380 } else {
5381 const SectionRef PL = get_section(O, "__DATA", "__objc_protolist");
5382 info.S = PL;
5383 walk_pointer_list_32("protocol", PL, O, &info, nullptr);
5384 }
5385
5386 const SectionRef MR = get_section(O, "__OBJC2", "__message_refs");
5387 if (MR != SectionRef()) {
5388 info.S = MR;
5389 print_message_refs32(MR, &info);
5390 } else {
5391 const SectionRef MR = get_section(O, "__DATA", "__objc_msgrefs");
5392 info.S = MR;
5393 print_message_refs32(MR, &info);
5394 }
5395
5396 const SectionRef II = get_section(O, "__OBJC2", "__image_info");
5397 if (II != SectionRef()) {
5398 info.S = II;
5399 print_image_info32(II, &info);
5400 } else {
5401 const SectionRef II = get_section(O, "__DATA", "__objc_imageinfo");
5402 info.S = II;
5403 print_image_info32(II, &info);
5404 }
Kevin Enderby0fc11822015-04-01 20:57:01 +00005405}
5406
5407static bool printObjc1_32bit_MetaData(MachOObjectFile *O, bool verbose) {
Kevin Enderby846c0002015-04-16 17:19:59 +00005408 uint32_t i, j, p, offset, xoffset, left, defs_left, def;
5409 const char *r, *name, *defs;
5410 struct objc_module_t module;
5411 SectionRef S, xS;
5412 struct objc_symtab_t symtab;
5413 struct objc_class_t objc_class;
5414 struct objc_category_t objc_category;
5415
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005416 outs() << "Objective-C segment\n";
Kevin Enderby846c0002015-04-16 17:19:59 +00005417 S = get_section(O, "__OBJC", "__module_info");
5418 if (S == SectionRef())
5419 return false;
5420
5421 SymbolAddressMap AddrMap;
5422 if (verbose)
5423 CreateSymbolAddressMap(O, &AddrMap);
5424
5425 std::vector<SectionRef> Sections;
5426 for (const SectionRef &Section : O->sections()) {
5427 StringRef SectName;
5428 Section.getName(SectName);
5429 Sections.push_back(Section);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005430 }
Kevin Enderby846c0002015-04-16 17:19:59 +00005431
5432 struct DisassembleInfo info;
5433 // Set up the block of info used by the Symbolizer call backs.
5434 info.verbose = verbose;
5435 info.O = O;
5436 info.AddrMap = &AddrMap;
5437 info.Sections = &Sections;
5438 info.class_name = nullptr;
5439 info.selector_name = nullptr;
5440 info.method = nullptr;
5441 info.demangled_name = nullptr;
5442 info.bindtable = nullptr;
5443 info.adrp_addr = 0;
5444 info.adrp_inst = 0;
5445
5446 for (i = 0; i < S.getSize(); i += sizeof(struct objc_module_t)) {
5447 p = S.getAddress() + i;
5448 r = get_pointer_32(p, offset, left, S, &info, true);
5449 if (r == nullptr)
5450 return true;
5451 memset(&module, '\0', sizeof(struct objc_module_t));
5452 if (left < sizeof(struct objc_module_t)) {
5453 memcpy(&module, r, left);
5454 outs() << " (module extends past end of __module_info section)\n";
5455 } else
5456 memcpy(&module, r, sizeof(struct objc_module_t));
5457 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5458 swapStruct(module);
5459
5460 outs() << "Module " << format("0x%" PRIx32, p) << "\n";
5461 outs() << " version " << module.version << "\n";
5462 outs() << " size " << module.size << "\n";
5463 outs() << " name ";
5464 name = get_pointer_32(module.name, xoffset, left, xS, &info, true);
5465 if (name != nullptr)
5466 outs() << format("%.*s", left, name);
5467 else
5468 outs() << format("0x%08" PRIx32, module.name)
5469 << "(not in an __OBJC section)";
5470 outs() << "\n";
5471
5472 r = get_pointer_32(module.symtab, xoffset, left, xS, &info, true);
5473 if (module.symtab == 0 || r == nullptr) {
5474 outs() << " symtab " << format("0x%08" PRIx32, module.symtab)
5475 << " (not in an __OBJC section)\n";
5476 continue;
5477 }
5478 outs() << " symtab " << format("0x%08" PRIx32, module.symtab) << "\n";
5479 memset(&symtab, '\0', sizeof(struct objc_symtab_t));
5480 defs_left = 0;
5481 defs = nullptr;
5482 if (left < sizeof(struct objc_symtab_t)) {
5483 memcpy(&symtab, r, left);
5484 outs() << "\tsymtab extends past end of an __OBJC section)\n";
5485 } else {
5486 memcpy(&symtab, r, sizeof(struct objc_symtab_t));
5487 if (left > sizeof(struct objc_symtab_t)) {
5488 defs_left = left - sizeof(struct objc_symtab_t);
5489 defs = r + sizeof(struct objc_symtab_t);
5490 }
5491 }
5492 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5493 swapStruct(symtab);
5494
5495 outs() << "\tsel_ref_cnt " << symtab.sel_ref_cnt << "\n";
5496 r = get_pointer_32(symtab.refs, xoffset, left, xS, &info, true);
5497 outs() << "\trefs " << format("0x%08" PRIx32, symtab.refs);
5498 if (r == nullptr)
5499 outs() << " (not in an __OBJC section)";
5500 outs() << "\n";
5501 outs() << "\tcls_def_cnt " << symtab.cls_def_cnt << "\n";
5502 outs() << "\tcat_def_cnt " << symtab.cat_def_cnt << "\n";
5503 if (symtab.cls_def_cnt > 0)
5504 outs() << "\tClass Definitions\n";
5505 for (j = 0; j < symtab.cls_def_cnt; j++) {
5506 if ((j + 1) * sizeof(uint32_t) > defs_left) {
5507 outs() << "\t(remaining class defs entries entends past the end of the "
5508 << "section)\n";
5509 break;
5510 }
5511 memcpy(&def, defs + j * sizeof(uint32_t), sizeof(uint32_t));
5512 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5513 sys::swapByteOrder(def);
5514
5515 r = get_pointer_32(def, xoffset, left, xS, &info, true);
5516 outs() << "\tdefs[" << j << "] " << format("0x%08" PRIx32, def);
5517 if (r != nullptr) {
5518 if (left > sizeof(struct objc_class_t)) {
5519 outs() << "\n";
5520 memcpy(&objc_class, r, sizeof(struct objc_class_t));
5521 } else {
5522 outs() << " (entends past the end of the section)\n";
5523 memset(&objc_class, '\0', sizeof(struct objc_class_t));
5524 memcpy(&objc_class, r, left);
5525 }
5526 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5527 swapStruct(objc_class);
5528 print_objc_class_t(&objc_class, &info);
5529 } else {
5530 outs() << "(not in an __OBJC section)\n";
5531 }
5532
5533 if (CLS_GETINFO(&objc_class, CLS_CLASS)) {
5534 outs() << "\tMeta Class";
5535 r = get_pointer_32(objc_class.isa, xoffset, left, xS, &info, true);
5536 if (r != nullptr) {
5537 if (left > sizeof(struct objc_class_t)) {
5538 outs() << "\n";
5539 memcpy(&objc_class, r, sizeof(struct objc_class_t));
5540 } else {
5541 outs() << " (entends past the end of the section)\n";
5542 memset(&objc_class, '\0', sizeof(struct objc_class_t));
5543 memcpy(&objc_class, r, left);
5544 }
5545 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5546 swapStruct(objc_class);
5547 print_objc_class_t(&objc_class, &info);
5548 } else {
5549 outs() << "(not in an __OBJC section)\n";
5550 }
5551 }
5552 }
5553 if (symtab.cat_def_cnt > 0)
5554 outs() << "\tCategory Definitions\n";
5555 for (j = 0; j < symtab.cat_def_cnt; j++) {
5556 if ((j + symtab.cls_def_cnt + 1) * sizeof(uint32_t) > defs_left) {
5557 outs() << "\t(remaining category defs entries entends past the end of "
5558 << "the section)\n";
5559 break;
5560 }
5561 memcpy(&def, defs + (j + symtab.cls_def_cnt) * sizeof(uint32_t),
5562 sizeof(uint32_t));
5563 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5564 sys::swapByteOrder(def);
5565
5566 r = get_pointer_32(def, xoffset, left, xS, &info, true);
5567 outs() << "\tdefs[" << j + symtab.cls_def_cnt << "] "
5568 << format("0x%08" PRIx32, def);
5569 if (r != nullptr) {
5570 if (left > sizeof(struct objc_category_t)) {
5571 outs() << "\n";
5572 memcpy(&objc_category, r, sizeof(struct objc_category_t));
5573 } else {
5574 outs() << " (entends past the end of the section)\n";
5575 memset(&objc_category, '\0', sizeof(struct objc_category_t));
5576 memcpy(&objc_category, r, left);
5577 }
5578 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5579 swapStruct(objc_category);
5580 print_objc_objc_category_t(&objc_category, &info);
5581 } else {
5582 outs() << "(not in an __OBJC section)\n";
5583 }
5584 }
5585 }
5586 const SectionRef II = get_section(O, "__OBJC", "__image_info");
5587 if (II != SectionRef())
5588 print_image_info(II, &info);
5589
5590 return true;
Kevin Enderby0fc11822015-04-01 20:57:01 +00005591}
5592
Kevin Enderby4ad9bde2015-04-16 22:33:20 +00005593static void DumpProtocolSection(MachOObjectFile *O, const char *sect,
5594 uint32_t size, uint32_t addr) {
5595 SymbolAddressMap AddrMap;
5596 CreateSymbolAddressMap(O, &AddrMap);
5597
5598 std::vector<SectionRef> Sections;
5599 for (const SectionRef &Section : O->sections()) {
5600 StringRef SectName;
5601 Section.getName(SectName);
5602 Sections.push_back(Section);
5603 }
5604
5605 struct DisassembleInfo info;
5606 // Set up the block of info used by the Symbolizer call backs.
5607 info.verbose = true;
5608 info.O = O;
5609 info.AddrMap = &AddrMap;
5610 info.Sections = &Sections;
5611 info.class_name = nullptr;
5612 info.selector_name = nullptr;
5613 info.method = nullptr;
5614 info.demangled_name = nullptr;
5615 info.bindtable = nullptr;
5616 info.adrp_addr = 0;
5617 info.adrp_inst = 0;
5618
5619 const char *p;
5620 struct objc_protocol_t protocol;
5621 uint32_t left, paddr;
5622 for (p = sect; p < sect + size; p += sizeof(struct objc_protocol_t)) {
5623 memset(&protocol, '\0', sizeof(struct objc_protocol_t));
5624 left = size - (p - sect);
5625 if (left < sizeof(struct objc_protocol_t)) {
5626 outs() << "Protocol extends past end of __protocol section\n";
5627 memcpy(&protocol, p, left);
5628 } else
5629 memcpy(&protocol, p, sizeof(struct objc_protocol_t));
5630 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5631 swapStruct(protocol);
5632 paddr = addr + (p - sect);
5633 outs() << "Protocol " << format("0x%" PRIx32, paddr);
5634 if (print_protocol(paddr, 0, &info))
5635 outs() << "(not in an __OBJC section)\n";
5636 }
5637}
5638
Kevin Enderby9873e2c2016-05-23 21:34:12 +00005639#ifdef HAVE_LIBXAR
5640inline void swapStruct(struct xar_header &xar) {
5641 sys::swapByteOrder(xar.magic);
5642 sys::swapByteOrder(xar.size);
5643 sys::swapByteOrder(xar.version);
5644 sys::swapByteOrder(xar.toc_length_compressed);
5645 sys::swapByteOrder(xar.toc_length_uncompressed);
5646 sys::swapByteOrder(xar.cksum_alg);
5647}
5648
5649static void PrintModeVerbose(uint32_t mode) {
5650 switch(mode & S_IFMT){
5651 case S_IFDIR:
5652 outs() << "d";
5653 break;
5654 case S_IFCHR:
5655 outs() << "c";
5656 break;
5657 case S_IFBLK:
5658 outs() << "b";
5659 break;
5660 case S_IFREG:
5661 outs() << "-";
5662 break;
5663 case S_IFLNK:
5664 outs() << "l";
5665 break;
5666 case S_IFSOCK:
5667 outs() << "s";
5668 break;
5669 default:
5670 outs() << "?";
5671 break;
5672 }
5673
5674 /* owner permissions */
5675 if(mode & S_IREAD)
5676 outs() << "r";
5677 else
5678 outs() << "-";
5679 if(mode & S_IWRITE)
5680 outs() << "w";
5681 else
5682 outs() << "-";
5683 if(mode & S_ISUID)
5684 outs() << "s";
5685 else if(mode & S_IEXEC)
5686 outs() << "x";
5687 else
5688 outs() << "-";
5689
5690 /* group permissions */
5691 if(mode & (S_IREAD >> 3))
5692 outs() << "r";
5693 else
5694 outs() << "-";
5695 if(mode & (S_IWRITE >> 3))
5696 outs() << "w";
5697 else
5698 outs() << "-";
5699 if(mode & S_ISGID)
5700 outs() << "s";
5701 else if(mode & (S_IEXEC >> 3))
5702 outs() << "x";
5703 else
5704 outs() << "-";
5705
5706 /* other permissions */
5707 if(mode & (S_IREAD >> 6))
5708 outs() << "r";
5709 else
5710 outs() << "-";
5711 if(mode & (S_IWRITE >> 6))
5712 outs() << "w";
5713 else
5714 outs() << "-";
5715 if(mode & S_ISVTX)
5716 outs() << "t";
5717 else if(mode & (S_IEXEC >> 6))
5718 outs() << "x";
5719 else
5720 outs() << "-";
5721}
5722
5723static void PrintXarFilesSummary(const char *XarFilename, xar_t xar) {
5724 xar_iter_t xi;
5725 xar_file_t xf;
5726 xar_iter_t xp;
5727 const char *key, *type, *mode, *user, *group, *size, *mtime, *name, *m;
5728 char *endp;
5729 uint32_t mode_value;
5730
5731 xi = xar_iter_new();
5732 if (!xi) {
5733 errs() << "Can't obtain an xar iterator for xar archive "
5734 << XarFilename << "\n";
5735 return;
5736 }
5737
5738 // Go through the xar's files.
5739 for (xf = xar_file_first(xar, xi); xf; xf = xar_file_next(xi)) {
5740 xp = xar_iter_new();
5741 if(!xp){
5742 errs() << "Can't obtain an xar iterator for xar archive "
5743 << XarFilename << "\n";
5744 return;
5745 }
5746 type = nullptr;
5747 mode = nullptr;
5748 user = nullptr;
5749 group = nullptr;
5750 size = nullptr;
5751 mtime = nullptr;
5752 name = nullptr;
5753 for(key = xar_prop_first(xf, xp); key; key = xar_prop_next(xp)){
5754 const char *val = nullptr;
5755 xar_prop_get(xf, key, &val);
5756#if 0 // Useful for debugging.
5757 outs() << "key: " << key << " value: " << val << "\n";
5758#endif
5759 if(strcmp(key, "type") == 0)
5760 type = val;
5761 if(strcmp(key, "mode") == 0)
5762 mode = val;
5763 if(strcmp(key, "user") == 0)
5764 user = val;
5765 if(strcmp(key, "group") == 0)
5766 group = val;
5767 if(strcmp(key, "data/size") == 0)
5768 size = val;
5769 if(strcmp(key, "mtime") == 0)
5770 mtime = val;
5771 if(strcmp(key, "name") == 0)
5772 name = val;
5773 }
5774 if(mode != nullptr){
5775 mode_value = strtoul(mode, &endp, 8);
5776 if(*endp != '\0')
5777 outs() << "(mode: \"" << mode << "\" contains non-octal chars) ";
5778 if(strcmp(type, "file") == 0)
5779 mode_value |= S_IFREG;
5780 PrintModeVerbose(mode_value);
5781 outs() << " ";
5782 }
5783 if(user != nullptr)
5784 outs() << format("%10s/", user);
5785 if(group != nullptr)
5786 outs() << format("%-10s ", group);
5787 if(size != nullptr)
5788 outs() << format("%7s ", size);
5789 if(mtime != nullptr){
5790 for(m = mtime; *m != 'T' && *m != '\0'; m++)
5791 outs() << *m;
5792 if(*m == 'T')
5793 m++;
5794 outs() << " ";
5795 for( ; *m != 'Z' && *m != '\0'; m++)
5796 outs() << *m;
5797 outs() << " ";
5798 }
5799 if(name != nullptr)
5800 outs() << name;
5801 outs() << "\n";
5802 }
5803}
5804
5805static void DumpBitcodeSection(MachOObjectFile *O, const char *sect,
5806 uint32_t size, bool verbose,
5807 bool PrintXarHeader, bool PrintXarFileHeaders,
5808 std::string XarMemberName) {
5809 if(size < sizeof(struct xar_header)) {
5810 outs() << "size of (__LLVM,__bundle) section too small (smaller than size "
5811 "of struct xar_header)\n";
5812 return;
5813 }
5814 struct xar_header XarHeader;
5815 memcpy(&XarHeader, sect, sizeof(struct xar_header));
5816 if (sys::IsLittleEndianHost)
5817 swapStruct(XarHeader);
5818 if (PrintXarHeader) {
5819 if (!XarMemberName.empty())
5820 outs() << "In xar member " << XarMemberName << ": ";
5821 else
5822 outs() << "For (__LLVM,__bundle) section: ";
5823 outs() << "xar header\n";
5824 if (XarHeader.magic == XAR_HEADER_MAGIC)
5825 outs() << " magic XAR_HEADER_MAGIC\n";
5826 else
5827 outs() << " magic "
5828 << format_hex(XarHeader.magic, 10, true)
5829 << " (not XAR_HEADER_MAGIC)\n";
5830 outs() << " size " << XarHeader.size << "\n";
5831 outs() << " version " << XarHeader.version << "\n";
5832 outs() << " toc_length_compressed " << XarHeader.toc_length_compressed
5833 << "\n";
5834 outs() << "toc_length_uncompressed " << XarHeader.toc_length_uncompressed
5835 << "\n";
5836 outs() << " cksum_alg ";
5837 switch (XarHeader.cksum_alg) {
5838 case XAR_CKSUM_NONE:
5839 outs() << "XAR_CKSUM_NONE\n";
5840 break;
5841 case XAR_CKSUM_SHA1:
5842 outs() << "XAR_CKSUM_SHA1\n";
5843 break;
5844 case XAR_CKSUM_MD5:
5845 outs() << "XAR_CKSUM_MD5\n";
5846 break;
Kevin Enderby42882282016-05-23 22:18:59 +00005847#ifdef XAR_CKSUM_SHA256
Kevin Enderby9873e2c2016-05-23 21:34:12 +00005848 case XAR_CKSUM_SHA256:
5849 outs() << "XAR_CKSUM_SHA256\n";
5850 break;
Kevin Enderby42882282016-05-23 22:18:59 +00005851#endif
5852#ifdef XAR_CKSUM_SHA512
Kevin Enderby9873e2c2016-05-23 21:34:12 +00005853 case XAR_CKSUM_SHA512:
5854 outs() << "XAR_CKSUM_SHA512\n";
5855 break;
Kevin Enderby42882282016-05-23 22:18:59 +00005856#endif
Kevin Enderby9873e2c2016-05-23 21:34:12 +00005857 default:
5858 outs() << XarHeader.cksum_alg << "\n";
5859 }
5860 }
5861
5862 SmallString<128> XarFilename;
5863 int FD;
5864 std::error_code XarEC =
5865 sys::fs::createTemporaryFile("llvm-objdump", "xar", FD, XarFilename);
5866 if (XarEC) {
5867 errs() << XarEC.message() << "\n";
5868 return;
5869 }
5870 tool_output_file XarFile(XarFilename, FD);
5871 raw_fd_ostream &XarOut = XarFile.os();
5872 StringRef XarContents(sect, size);
5873 XarOut << XarContents;
5874 XarOut.close();
5875 if (XarOut.has_error())
5876 return;
5877
5878 xar_t xar = xar_open(XarFilename.c_str(), READ);
5879 if (!xar) {
5880 errs() << "Can't create temporary xar archive " << XarFilename << "\n";
5881 return;
5882 }
5883
5884 SmallString<128> TocFilename;
5885 std::error_code TocEC =
5886 sys::fs::createTemporaryFile("llvm-objdump", "toc", TocFilename);
5887 if (TocEC) {
5888 errs() << TocEC.message() << "\n";
5889 return;
5890 }
5891 xar_serialize(xar, TocFilename.c_str());
5892
5893 if (PrintXarFileHeaders) {
5894 if (!XarMemberName.empty())
5895 outs() << "In xar member " << XarMemberName << ": ";
5896 else
5897 outs() << "For (__LLVM,__bundle) section: ";
5898 outs() << "xar archive files:\n";
5899 PrintXarFilesSummary(XarFilename.c_str(), xar);
5900 }
5901
5902 ErrorOr<std::unique_ptr<MemoryBuffer>> FileOrErr =
5903 MemoryBuffer::getFileOrSTDIN(TocFilename.c_str());
5904 if (std::error_code EC = FileOrErr.getError()) {
5905 errs() << EC.message() << "\n";
5906 return;
5907 }
5908 std::unique_ptr<MemoryBuffer> &Buffer = FileOrErr.get();
5909
5910 if (!XarMemberName.empty())
5911 outs() << "In xar member " << XarMemberName << ": ";
5912 else
5913 outs() << "For (__LLVM,__bundle) section: ";
5914 outs() << "xar table of contents:\n";
5915 outs() << Buffer->getBuffer() << "\n";
5916
5917 // TODO: Go through the xar's files.
5918 xar_iter_t xi = xar_iter_new();
5919 if(!xi){
5920 errs() << "Can't obtain an xar iterator for xar archive "
5921 << XarFilename.c_str() << "\n";
5922 xar_close(xar);
5923 return;
5924 }
5925 for(xar_file_t xf = xar_file_first(xar, xi); xf; xf = xar_file_next(xi)){
5926 const char *key;
5927 xar_iter_t xp;
5928 const char *member_name, *member_type, *member_size_string;
5929 size_t member_size;
5930
5931 xp = xar_iter_new();
5932 if(!xp){
5933 errs() << "Can't obtain an xar iterator for xar archive "
5934 << XarFilename.c_str() << "\n";
5935 xar_close(xar);
5936 return;
5937 }
5938 member_name = NULL;
5939 member_type = NULL;
5940 member_size_string = NULL;
5941 for(key = xar_prop_first(xf, xp); key; key = xar_prop_next(xp)){
5942 const char *val = nullptr;
5943 xar_prop_get(xf, key, &val);
5944#if 0 // Useful for debugging.
5945 outs() << "key: " << key << " value: " << val << "\n";
5946#endif
5947 if(strcmp(key, "name") == 0)
5948 member_name = val;
5949 if(strcmp(key, "type") == 0)
5950 member_type = val;
5951 if(strcmp(key, "data/size") == 0)
5952 member_size_string = val;
5953 }
5954 /*
5955 * If we find a file with a name, date/size and type properties
5956 * and with the type being "file" see if that is a xar file.
5957 */
5958 if (member_name != NULL && member_type != NULL &&
5959 strcmp(member_type, "file") == 0 &&
5960 member_size_string != NULL){
5961 // Extract the file into a buffer.
5962 char *endptr;
5963 member_size = strtoul(member_size_string, &endptr, 10);
5964 if (*endptr == '\0' && member_size != 0) {
5965 char *buffer = (char *) ::operator new (member_size);
5966 if (xar_extract_tobuffersz(xar, xf, &buffer, &member_size) == 0) {
5967#if 0 // Useful for debugging.
5968 outs() << "xar member: " << member_name << " extracted\n";
5969#endif
5970 // Set the XarMemberName we want to see printed in the header.
5971 std::string OldXarMemberName;
5972 // If XarMemberName is already set this is nested. So
5973 // save the old name and create the nested name.
5974 if (!XarMemberName.empty()) {
5975 OldXarMemberName = XarMemberName;
5976 XarMemberName =
5977 (Twine("[") + XarMemberName + "]" + member_name).str();
5978 } else {
5979 OldXarMemberName = "";
5980 XarMemberName = member_name;
5981 }
5982 // See if this is could be a xar file (nested).
5983 if (member_size >= sizeof(struct xar_header)) {
5984#if 0 // Useful for debugging.
5985 outs() << "could be a xar file: " << member_name << "\n";
5986#endif
5987 memcpy((char *)&XarHeader, buffer, sizeof(struct xar_header));
5988 if (sys::IsLittleEndianHost)
5989 swapStruct(XarHeader);
5990 if(XarHeader.magic == XAR_HEADER_MAGIC)
5991 DumpBitcodeSection(O, buffer, member_size, verbose,
5992 PrintXarHeader, PrintXarFileHeaders,
5993 XarMemberName);
5994 }
5995 XarMemberName = OldXarMemberName;
5996 }
5997 delete buffer;
5998 }
5999 }
6000 xar_iter_free(xp);
6001 }
6002 xar_close(xar);
6003}
6004#endif // defined(HAVE_LIBXAR)
6005
Kevin Enderby0fc11822015-04-01 20:57:01 +00006006static void printObjcMetaData(MachOObjectFile *O, bool verbose) {
6007 if (O->is64Bit())
6008 printObjc2_64bit_MetaData(O, verbose);
6009 else {
6010 MachO::mach_header H;
6011 H = O->getHeader();
6012 if (H.cputype == MachO::CPU_TYPE_ARM)
6013 printObjc2_32bit_MetaData(O, verbose);
6014 else {
6015 // This is the 32-bit non-arm cputype case. Which is normally
6016 // the first Objective-C ABI. But it may be the case of a
6017 // binary for the iOS simulator which is the second Objective-C
6018 // ABI. In that case printObjc1_32bit_MetaData() will determine that
6019 // and return false.
Hans Wennborgcc9deb42015-09-29 18:02:48 +00006020 if (!printObjc1_32bit_MetaData(O, verbose))
Kevin Enderby0fc11822015-04-01 20:57:01 +00006021 printObjc2_32bit_MetaData(O, verbose);
6022 }
6023 }
6024}
6025
Kevin Enderbybf246f52014-09-24 23:08:22 +00006026// GuessLiteralPointer returns a string which for the item in the Mach-O file
6027// for the address passed in as ReferenceValue for printing as a comment with
6028// the instruction and also returns the corresponding type of that item
6029// indirectly through ReferenceType.
6030//
6031// If ReferenceValue is an address of literal cstring then a pointer to the
6032// cstring is returned and ReferenceType is set to
6033// LLVMDisassembler_ReferenceType_Out_LitPool_CstrAddr .
6034//
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006035// If ReferenceValue is an address of an Objective-C CFString, Selector ref or
6036// Class ref that name is returned and the ReferenceType is set accordingly.
6037//
6038// Lastly, literals which are Symbol address in a literal pool are looked for
6039// and if found the symbol name is returned and ReferenceType is set to
6040// LLVMDisassembler_ReferenceType_Out_LitPool_SymAddr .
6041//
6042// If there is no item in the Mach-O file for the address passed in as
6043// ReferenceValue nullptr is returned and ReferenceType is unchanged.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00006044static const char *GuessLiteralPointer(uint64_t ReferenceValue,
6045 uint64_t ReferencePC,
6046 uint64_t *ReferenceType,
6047 struct DisassembleInfo *info) {
Kevin Enderbybf246f52014-09-24 23:08:22 +00006048 // First see if there is an external relocation entry at the ReferencePC.
Kevin Enderbyd90a4172015-10-10 00:05:01 +00006049 if (info->O->getHeader().filetype == MachO::MH_OBJECT) {
6050 uint64_t sect_addr = info->S.getAddress();
6051 uint64_t sect_offset = ReferencePC - sect_addr;
6052 bool reloc_found = false;
6053 DataRefImpl Rel;
6054 MachO::any_relocation_info RE;
6055 bool isExtern = false;
6056 SymbolRef Symbol;
6057 for (const RelocationRef &Reloc : info->S.relocations()) {
6058 uint64_t RelocOffset = Reloc.getOffset();
6059 if (RelocOffset == sect_offset) {
6060 Rel = Reloc.getRawDataRefImpl();
6061 RE = info->O->getRelocation(Rel);
6062 if (info->O->isRelocationScattered(RE))
6063 continue;
6064 isExtern = info->O->getPlainRelocationExternal(RE);
6065 if (isExtern) {
6066 symbol_iterator RelocSym = Reloc.getSymbol();
6067 Symbol = *RelocSym;
6068 }
6069 reloc_found = true;
6070 break;
Kevin Enderbybf246f52014-09-24 23:08:22 +00006071 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00006072 }
Kevin Enderbyd90a4172015-10-10 00:05:01 +00006073 // If there is an external relocation entry for a symbol in a section
6074 // then used that symbol's value for the value of the reference.
6075 if (reloc_found && isExtern) {
6076 if (info->O->getAnyRelocationPCRel(RE)) {
6077 unsigned Type = info->O->getAnyRelocationType(RE);
6078 if (Type == MachO::X86_64_RELOC_SIGNED) {
6079 ReferenceValue = Symbol.getValue();
6080 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00006081 }
6082 }
6083 }
6084
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006085 // Look for literals such as Objective-C CFStrings refs, Selector refs,
6086 // Message refs and Class refs.
6087 bool classref, selref, msgref, cfstring;
6088 uint64_t pointer_value = GuessPointerPointer(ReferenceValue, info, classref,
6089 selref, msgref, cfstring);
David Blaikie33dd45d02015-03-23 18:39:02 +00006090 if (classref && pointer_value == 0) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006091 // Note the ReferenceValue is a pointer into the __objc_classrefs section.
6092 // And the pointer_value in that section is typically zero as it will be
6093 // set by dyld as part of the "bind information".
6094 const char *name = get_dyld_bind_info_symbolname(ReferenceValue, info);
6095 if (name != nullptr) {
6096 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Class_Ref;
Hans Wennborgdb53e302014-10-23 21:59:17 +00006097 const char *class_name = strrchr(name, '$');
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006098 if (class_name != nullptr && class_name[1] == '_' &&
6099 class_name[2] != '\0') {
6100 info->class_name = class_name + 2;
6101 return name;
6102 }
6103 }
6104 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00006105
David Blaikie33dd45d02015-03-23 18:39:02 +00006106 if (classref) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006107 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Class_Ref;
6108 const char *name =
6109 get_objc2_64bit_class_name(pointer_value, ReferenceValue, info);
6110 if (name != nullptr)
6111 info->class_name = name;
6112 else
6113 name = "bad class ref";
Kevin Enderbybf246f52014-09-24 23:08:22 +00006114 return name;
6115 }
6116
David Blaikie33dd45d02015-03-23 18:39:02 +00006117 if (cfstring) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006118 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_CFString_Ref;
6119 const char *name = get_objc2_64bit_cfstring_name(ReferenceValue, info);
6120 return name;
6121 }
6122
David Blaikie33dd45d02015-03-23 18:39:02 +00006123 if (selref && pointer_value == 0)
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006124 pointer_value = get_objc2_64bit_selref(ReferenceValue, info);
6125
6126 if (pointer_value != 0)
6127 ReferenceValue = pointer_value;
6128
6129 const char *name = GuessCstringPointer(ReferenceValue, info);
6130 if (name) {
David Blaikie33dd45d02015-03-23 18:39:02 +00006131 if (pointer_value != 0 && selref) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006132 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Selector_Ref;
6133 info->selector_name = name;
David Blaikie33dd45d02015-03-23 18:39:02 +00006134 } else if (pointer_value != 0 && msgref) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006135 info->class_name = nullptr;
6136 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message_Ref;
6137 info->selector_name = name;
6138 } else
6139 *ReferenceType = LLVMDisassembler_ReferenceType_Out_LitPool_CstrAddr;
6140 return name;
6141 }
6142
6143 // Lastly look for an indirect symbol with this ReferenceValue which is in
6144 // a literal pool. If found return that symbol name.
6145 name = GuessIndirectSymbol(ReferenceValue, info);
6146 if (name) {
6147 *ReferenceType = LLVMDisassembler_ReferenceType_Out_LitPool_SymAddr;
6148 return name;
6149 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00006150
6151 return nullptr;
6152}
6153
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006154// SymbolizerSymbolLookUp is the symbol lookup function passed when creating
Kevin Enderbybf246f52014-09-24 23:08:22 +00006155// the Symbolizer. It looks up the ReferenceValue using the info passed via the
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006156// pointer to the struct DisassembleInfo that was passed when MCSymbolizer
6157// is created and returns the symbol name that matches the ReferenceValue or
6158// nullptr if none. The ReferenceType is passed in for the IN type of
6159// reference the instruction is making from the values in defined in the header
6160// "llvm-c/Disassembler.h". On return the ReferenceType can set to a specific
6161// Out type and the ReferenceName will also be set which is added as a comment
6162// to the disassembled instruction.
6163//
Kevin Enderby04bf6932014-10-28 23:39:46 +00006164// If the symbol name is a C++ mangled name then the demangled name is
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006165// returned through ReferenceName and ReferenceType is set to
6166// LLVMDisassembler_ReferenceType_DeMangled_Name .
6167//
6168// When this is called to get a symbol name for a branch target then the
6169// ReferenceType will be LLVMDisassembler_ReferenceType_In_Branch and then
6170// SymbolValue will be looked for in the indirect symbol table to determine if
6171// it is an address for a symbol stub. If so then the symbol name for that
6172// stub is returned indirectly through ReferenceName and then ReferenceType is
6173// set to LLVMDisassembler_ReferenceType_Out_SymbolStub.
6174//
Kevin Enderbybf246f52014-09-24 23:08:22 +00006175// When this is called with an value loaded via a PC relative load then
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006176// ReferenceType will be LLVMDisassembler_ReferenceType_In_PCrel_Load then the
6177// SymbolValue is checked to be an address of literal pointer, symbol pointer,
6178// or an Objective-C meta data reference. If so the output ReferenceType is
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006179// set to correspond to that as well as setting the ReferenceName.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00006180static const char *SymbolizerSymbolLookUp(void *DisInfo,
6181 uint64_t ReferenceValue,
6182 uint64_t *ReferenceType,
6183 uint64_t ReferencePC,
6184 const char **ReferenceName) {
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006185 struct DisassembleInfo *info = (struct DisassembleInfo *)DisInfo;
Kevin Enderbybf246f52014-09-24 23:08:22 +00006186 // If no verbose symbolic information is wanted then just return nullptr.
David Blaikie33dd45d02015-03-23 18:39:02 +00006187 if (!info->verbose) {
Kevin Enderbybf246f52014-09-24 23:08:22 +00006188 *ReferenceName = nullptr;
6189 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006190 return nullptr;
6191 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00006192
Kevin Enderbyf6d25852015-01-31 00:37:11 +00006193 const char *SymbolName = GuessSymbolName(ReferenceValue, info->AddrMap);
Kevin Enderbybf246f52014-09-24 23:08:22 +00006194
Kevin Enderby85974882014-09-26 22:20:44 +00006195 if (*ReferenceType == LLVMDisassembler_ReferenceType_In_Branch) {
6196 *ReferenceName = GuessIndirectSymbol(ReferenceValue, info);
Kevin Enderby04bf6932014-10-28 23:39:46 +00006197 if (*ReferenceName != nullptr) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006198 method_reference(info, ReferenceType, ReferenceName);
6199 if (*ReferenceType != LLVMDisassembler_ReferenceType_Out_Objc_Message)
6200 *ReferenceType = LLVMDisassembler_ReferenceType_Out_SymbolStub;
Rafael Espindolab940b662016-09-06 19:16:48 +00006201 } else if (SymbolName != nullptr && strncmp(SymbolName, "__Z", 3) == 0) {
Kevin Enderby04bf6932014-10-28 23:39:46 +00006202 if (info->demangled_name != nullptr)
6203 free(info->demangled_name);
6204 int status;
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006205 info->demangled_name =
Rafael Espindolab940b662016-09-06 19:16:48 +00006206 itaniumDemangle(SymbolName + 1, nullptr, nullptr, &status);
Kevin Enderby04bf6932014-10-28 23:39:46 +00006207 if (info->demangled_name != nullptr) {
6208 *ReferenceName = info->demangled_name;
6209 *ReferenceType = LLVMDisassembler_ReferenceType_DeMangled_Name;
6210 } else
6211 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
6212 } else
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006213 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
6214 } else if (*ReferenceType == LLVMDisassembler_ReferenceType_In_PCrel_Load) {
6215 *ReferenceName =
6216 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
Kevin Enderby85974882014-09-26 22:20:44 +00006217 if (*ReferenceName)
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006218 method_reference(info, ReferenceType, ReferenceName);
Kevin Enderby85974882014-09-26 22:20:44 +00006219 else
6220 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
Kevin Enderbyae3c1262014-11-14 21:52:18 +00006221 // If this is arm64 and the reference is an adrp instruction save the
6222 // instruction, passed in ReferenceValue and the address of the instruction
6223 // for use later if we see and add immediate instruction.
6224 } else if (info->O->getArch() == Triple::aarch64 &&
6225 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADRP) {
6226 info->adrp_inst = ReferenceValue;
6227 info->adrp_addr = ReferencePC;
6228 SymbolName = nullptr;
6229 *ReferenceName = nullptr;
6230 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
6231 // If this is arm64 and reference is an add immediate instruction and we
6232 // have
6233 // seen an adrp instruction just before it and the adrp's Xd register
6234 // matches
6235 // this add's Xn register reconstruct the value being referenced and look to
6236 // see if it is a literal pointer. Note the add immediate instruction is
6237 // passed in ReferenceValue.
6238 } else if (info->O->getArch() == Triple::aarch64 &&
6239 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADDXri &&
6240 ReferencePC - 4 == info->adrp_addr &&
6241 (info->adrp_inst & 0x9f000000) == 0x90000000 &&
6242 (info->adrp_inst & 0x1f) == ((ReferenceValue >> 5) & 0x1f)) {
6243 uint32_t addxri_inst;
6244 uint64_t adrp_imm, addxri_imm;
6245
6246 adrp_imm =
6247 ((info->adrp_inst & 0x00ffffe0) >> 3) | ((info->adrp_inst >> 29) & 0x3);
6248 if (info->adrp_inst & 0x0200000)
6249 adrp_imm |= 0xfffffffffc000000LL;
6250
6251 addxri_inst = ReferenceValue;
6252 addxri_imm = (addxri_inst >> 10) & 0xfff;
6253 if (((addxri_inst >> 22) & 0x3) == 1)
6254 addxri_imm <<= 12;
6255
6256 ReferenceValue = (info->adrp_addr & 0xfffffffffffff000LL) +
6257 (adrp_imm << 12) + addxri_imm;
6258
6259 *ReferenceName =
6260 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
6261 if (*ReferenceName == nullptr)
6262 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
6263 // If this is arm64 and the reference is a load register instruction and we
6264 // have seen an adrp instruction just before it and the adrp's Xd register
6265 // matches this add's Xn register reconstruct the value being referenced and
6266 // look to see if it is a literal pointer. Note the load register
6267 // instruction is passed in ReferenceValue.
6268 } else if (info->O->getArch() == Triple::aarch64 &&
6269 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_LDRXui &&
6270 ReferencePC - 4 == info->adrp_addr &&
6271 (info->adrp_inst & 0x9f000000) == 0x90000000 &&
6272 (info->adrp_inst & 0x1f) == ((ReferenceValue >> 5) & 0x1f)) {
6273 uint32_t ldrxui_inst;
6274 uint64_t adrp_imm, ldrxui_imm;
6275
6276 adrp_imm =
6277 ((info->adrp_inst & 0x00ffffe0) >> 3) | ((info->adrp_inst >> 29) & 0x3);
6278 if (info->adrp_inst & 0x0200000)
6279 adrp_imm |= 0xfffffffffc000000LL;
6280
6281 ldrxui_inst = ReferenceValue;
6282 ldrxui_imm = (ldrxui_inst >> 10) & 0xfff;
6283
6284 ReferenceValue = (info->adrp_addr & 0xfffffffffffff000LL) +
6285 (adrp_imm << 12) + (ldrxui_imm << 3);
6286
6287 *ReferenceName =
6288 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
6289 if (*ReferenceName == nullptr)
6290 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
6291 }
6292 // If this arm64 and is an load register (PC-relative) instruction the
6293 // ReferenceValue is the PC plus the immediate value.
6294 else if (info->O->getArch() == Triple::aarch64 &&
6295 (*ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_LDRXl ||
6296 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADR)) {
6297 *ReferenceName =
6298 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
6299 if (*ReferenceName == nullptr)
6300 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
Rafael Espindolab940b662016-09-06 19:16:48 +00006301 } else if (SymbolName != nullptr && strncmp(SymbolName, "__Z", 3) == 0) {
Kevin Enderby04bf6932014-10-28 23:39:46 +00006302 if (info->demangled_name != nullptr)
6303 free(info->demangled_name);
6304 int status;
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006305 info->demangled_name =
Rafael Espindolab940b662016-09-06 19:16:48 +00006306 itaniumDemangle(SymbolName + 1, nullptr, nullptr, &status);
Kevin Enderby04bf6932014-10-28 23:39:46 +00006307 if (info->demangled_name != nullptr) {
6308 *ReferenceName = info->demangled_name;
6309 *ReferenceType = LLVMDisassembler_ReferenceType_DeMangled_Name;
6310 }
6311 }
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006312 else {
Kevin Enderbybf246f52014-09-24 23:08:22 +00006313 *ReferenceName = nullptr;
6314 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
6315 }
6316
6317 return SymbolName;
6318}
6319
Kevin Enderbybf246f52014-09-24 23:08:22 +00006320/// \brief Emits the comments that are stored in the CommentStream.
6321/// Each comment in the CommentStream must end with a newline.
6322static void emitComments(raw_svector_ostream &CommentStream,
6323 SmallString<128> &CommentsToEmit,
6324 formatted_raw_ostream &FormattedOS,
6325 const MCAsmInfo &MAI) {
6326 // Flush the stream before taking its content.
Kevin Enderbybf246f52014-09-24 23:08:22 +00006327 StringRef Comments = CommentsToEmit.str();
6328 // Get the default information for printing a comment.
Mehdi Amini36d33fc2016-10-01 06:46:33 +00006329 StringRef CommentBegin = MAI.getCommentString();
Kevin Enderbybf246f52014-09-24 23:08:22 +00006330 unsigned CommentColumn = MAI.getCommentColumn();
6331 bool IsFirst = true;
6332 while (!Comments.empty()) {
6333 if (!IsFirst)
6334 FormattedOS << '\n';
6335 // Emit a line of comments.
6336 FormattedOS.PadToColumn(CommentColumn);
6337 size_t Position = Comments.find('\n');
6338 FormattedOS << CommentBegin << ' ' << Comments.substr(0, Position);
6339 // Move after the newline character.
6340 Comments = Comments.substr(Position + 1);
6341 IsFirst = false;
6342 }
6343 FormattedOS.flush();
6344
6345 // Tell the comment stream that the vector changed underneath it.
6346 CommentsToEmit.clear();
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006347}
6348
Kevin Enderby95df54c2015-02-04 01:01:38 +00006349static void DisassembleMachO(StringRef Filename, MachOObjectFile *MachOOF,
6350 StringRef DisSegName, StringRef DisSectName) {
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006351 const char *McpuDefault = nullptr;
6352 const Target *ThumbTarget = nullptr;
6353 const Target *TheTarget = GetTarget(MachOOF, &McpuDefault, &ThumbTarget);
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006354 if (!TheTarget) {
6355 // GetTarget prints out stuff.
6356 return;
6357 }
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006358 if (MCPU.empty() && McpuDefault)
6359 MCPU = McpuDefault;
6360
Ahmed Charles56440fd2014-03-06 05:51:42 +00006361 std::unique_ptr<const MCInstrInfo> InstrInfo(TheTarget->createMCInstrInfo());
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006362 std::unique_ptr<const MCInstrInfo> ThumbInstrInfo;
Kevin Enderbyae3c1262014-11-14 21:52:18 +00006363 if (ThumbTarget)
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006364 ThumbInstrInfo.reset(ThumbTarget->createMCInstrInfo());
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006365
Kevin Enderbyc9595622014-08-06 23:24:41 +00006366 // Package up features to be passed to target/subtarget
6367 std::string FeaturesStr;
6368 if (MAttrs.size()) {
6369 SubtargetFeatures Features;
6370 for (unsigned i = 0; i != MAttrs.size(); ++i)
6371 Features.AddFeature(MAttrs[i]);
6372 FeaturesStr = Features.getString();
6373 }
6374
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006375 // Set up disassembler.
Ahmed Charles56440fd2014-03-06 05:51:42 +00006376 std::unique_ptr<const MCRegisterInfo> MRI(
6377 TheTarget->createMCRegInfo(TripleName));
6378 std::unique_ptr<const MCAsmInfo> AsmInfo(
Rafael Espindola227144c2013-05-13 01:16:13 +00006379 TheTarget->createMCAsmInfo(*MRI, TripleName));
Ahmed Charles56440fd2014-03-06 05:51:42 +00006380 std::unique_ptr<const MCSubtargetInfo> STI(
Kevin Enderbyc9595622014-08-06 23:24:41 +00006381 TheTarget->createMCSubtargetInfo(TripleName, MCPU, FeaturesStr));
Craig Toppere6cb63e2014-04-25 04:24:47 +00006382 MCContext Ctx(AsmInfo.get(), MRI.get(), nullptr);
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006383 std::unique_ptr<MCDisassembler> DisAsm(
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006384 TheTarget->createMCDisassembler(*STI, Ctx));
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006385 std::unique_ptr<MCSymbolizer> Symbolizer;
6386 struct DisassembleInfo SymbolizerInfo;
6387 std::unique_ptr<MCRelocationInfo> RelInfo(
6388 TheTarget->createMCRelocationInfo(TripleName, Ctx));
6389 if (RelInfo) {
6390 Symbolizer.reset(TheTarget->createMCSymbolizer(
6391 TripleName, SymbolizerGetOpInfo, SymbolizerSymbolLookUp,
David Blaikie186db432015-01-18 20:45:48 +00006392 &SymbolizerInfo, &Ctx, std::move(RelInfo)));
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006393 DisAsm->setSymbolizer(std::move(Symbolizer));
6394 }
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006395 int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
Ahmed Charles56440fd2014-03-06 05:51:42 +00006396 std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
Daniel Sanders50f17232015-09-15 16:17:27 +00006397 Triple(TripleName), AsmPrinterVariant, *AsmInfo, *InstrInfo, *MRI));
Kevin Enderbybf246f52014-09-24 23:08:22 +00006398 // Set the display preference for hex vs. decimal immediates.
6399 IP->setPrintImmHex(PrintImmHex);
6400 // Comment stream and backing vector.
6401 SmallString<128> CommentsToEmit;
6402 raw_svector_ostream CommentStream(CommentsToEmit);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00006403 // FIXME: Setting the CommentStream in the InstPrinter is problematic in that
6404 // if it is done then arm64 comments for string literals don't get printed
6405 // and some constant get printed instead and not setting it causes intel
6406 // (32-bit and 64-bit) comments printed with different spacing before the
6407 // comment causing different diffs with the 'C' disassembler library API.
6408 // IP->setCommentStream(CommentStream);
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00006409
Kevin Enderbyae3c1262014-11-14 21:52:18 +00006410 if (!AsmInfo || !STI || !DisAsm || !IP) {
Michael J. Spencerc1363cf2011-10-07 19:25:47 +00006411 errs() << "error: couldn't initialize disassembler for target "
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00006412 << TripleName << '\n';
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006413 return;
6414 }
6415
Tim Northover09ca33e2016-04-22 23:23:31 +00006416 // Set up separate thumb disassembler if needed.
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006417 std::unique_ptr<const MCRegisterInfo> ThumbMRI;
6418 std::unique_ptr<const MCAsmInfo> ThumbAsmInfo;
6419 std::unique_ptr<const MCSubtargetInfo> ThumbSTI;
Kevin Enderby930fdc72014-11-06 19:00:13 +00006420 std::unique_ptr<MCDisassembler> ThumbDisAsm;
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006421 std::unique_ptr<MCInstPrinter> ThumbIP;
6422 std::unique_ptr<MCContext> ThumbCtx;
Kevin Enderby930fdc72014-11-06 19:00:13 +00006423 std::unique_ptr<MCSymbolizer> ThumbSymbolizer;
6424 struct DisassembleInfo ThumbSymbolizerInfo;
6425 std::unique_ptr<MCRelocationInfo> ThumbRelInfo;
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006426 if (ThumbTarget) {
6427 ThumbMRI.reset(ThumbTarget->createMCRegInfo(ThumbTripleName));
6428 ThumbAsmInfo.reset(
6429 ThumbTarget->createMCAsmInfo(*ThumbMRI, ThumbTripleName));
6430 ThumbSTI.reset(
6431 ThumbTarget->createMCSubtargetInfo(ThumbTripleName, MCPU, FeaturesStr));
6432 ThumbCtx.reset(new MCContext(ThumbAsmInfo.get(), ThumbMRI.get(), nullptr));
6433 ThumbDisAsm.reset(ThumbTarget->createMCDisassembler(*ThumbSTI, *ThumbCtx));
Kevin Enderby930fdc72014-11-06 19:00:13 +00006434 MCContext *PtrThumbCtx = ThumbCtx.get();
6435 ThumbRelInfo.reset(
6436 ThumbTarget->createMCRelocationInfo(ThumbTripleName, *PtrThumbCtx));
6437 if (ThumbRelInfo) {
6438 ThumbSymbolizer.reset(ThumbTarget->createMCSymbolizer(
6439 ThumbTripleName, SymbolizerGetOpInfo, SymbolizerSymbolLookUp,
David Blaikie186db432015-01-18 20:45:48 +00006440 &ThumbSymbolizerInfo, PtrThumbCtx, std::move(ThumbRelInfo)));
Kevin Enderby930fdc72014-11-06 19:00:13 +00006441 ThumbDisAsm->setSymbolizer(std::move(ThumbSymbolizer));
6442 }
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006443 int ThumbAsmPrinterVariant = ThumbAsmInfo->getAssemblerDialect();
6444 ThumbIP.reset(ThumbTarget->createMCInstPrinter(
Daniel Sanders50f17232015-09-15 16:17:27 +00006445 Triple(ThumbTripleName), ThumbAsmPrinterVariant, *ThumbAsmInfo,
6446 *ThumbInstrInfo, *ThumbMRI));
Kevin Enderbybf246f52014-09-24 23:08:22 +00006447 // Set the display preference for hex vs. decimal immediates.
6448 ThumbIP->setPrintImmHex(PrintImmHex);
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006449 }
6450
Kevin Enderbyae3c1262014-11-14 21:52:18 +00006451 if (ThumbTarget && (!ThumbAsmInfo || !ThumbSTI || !ThumbDisAsm || !ThumbIP)) {
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006452 errs() << "error: couldn't initialize disassembler for target "
6453 << ThumbTripleName << '\n';
6454 return;
6455 }
6456
Charles Davis8bdfafd2013-09-01 04:28:48 +00006457 MachO::mach_header Header = MachOOF->getHeader();
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006458
Ahmed Bougachaaa790682013-05-24 01:07:04 +00006459 // FIXME: Using the -cfg command line option, this code used to be able to
6460 // annotate relocations with the referenced symbol's name, and if this was
6461 // inside a __[cf]string section, the data it points to. This is now replaced
6462 // by the upcoming MCSymbolizer, which needs the appropriate setup done above.
Owen Andersond9243c42011-10-17 21:37:35 +00006463 std::vector<SectionRef> Sections;
6464 std::vector<SymbolRef> Symbols;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006465 SmallVector<uint64_t, 8> FoundFns;
Kevin Enderby273ae012013-06-06 17:20:50 +00006466 uint64_t BaseSegmentAddress;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006467
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00006468 getSectionsAndSymbols(MachOOF, Sections, Symbols, FoundFns,
Kevin Enderby273ae012013-06-06 17:20:50 +00006469 BaseSegmentAddress);
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006470
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006471 // Sort the symbols by address, just in case they didn't come in that way.
Owen Andersond9243c42011-10-17 21:37:35 +00006472 std::sort(Symbols.begin(), Symbols.end(), SymbolSorter());
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006473
Kevin Enderby273ae012013-06-06 17:20:50 +00006474 // Build a data in code table that is sorted on by the address of each entry.
6475 uint64_t BaseAddress = 0;
Charles Davis8bdfafd2013-09-01 04:28:48 +00006476 if (Header.filetype == MachO::MH_OBJECT)
Rafael Espindola80291272014-10-08 15:28:58 +00006477 BaseAddress = Sections[0].getAddress();
Kevin Enderby273ae012013-06-06 17:20:50 +00006478 else
6479 BaseAddress = BaseSegmentAddress;
6480 DiceTable Dices;
Kevin Enderby273ae012013-06-06 17:20:50 +00006481 for (dice_iterator DI = MachOOF->begin_dices(), DE = MachOOF->end_dices();
Rafael Espindola5e812af2014-01-30 02:49:50 +00006482 DI != DE; ++DI) {
Kevin Enderby273ae012013-06-06 17:20:50 +00006483 uint32_t Offset;
6484 DI->getOffset(Offset);
6485 Dices.push_back(std::make_pair(BaseAddress + Offset, *DI));
6486 }
6487 array_pod_sort(Dices.begin(), Dices.end());
6488
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006489#ifndef NDEBUG
6490 raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls();
6491#else
6492 raw_ostream &DebugOut = nulls();
6493#endif
6494
Ahmed Charles56440fd2014-03-06 05:51:42 +00006495 std::unique_ptr<DIContext> diContext;
Rafael Espindola9b709252013-04-13 01:45:40 +00006496 ObjectFile *DbgObj = MachOOF;
Benjamin Kramer699128e2011-09-21 01:13:19 +00006497 // Try to find debug info and set up the DIContext for it.
6498 if (UseDbg) {
Benjamin Kramer699128e2011-09-21 01:13:19 +00006499 // A separate DSym file path was specified, parse it as a macho file,
6500 // get the sections and supply it to the section name parsing machinery.
6501 if (!DSYMFile.empty()) {
Rafael Espindola48af1c22014-08-19 18:44:46 +00006502 ErrorOr<std::unique_ptr<MemoryBuffer>> BufOrErr =
Rafael Espindolaadf21f22014-07-06 17:43:13 +00006503 MemoryBuffer::getFileOrSTDIN(DSYMFile);
Rafael Espindola48af1c22014-08-19 18:44:46 +00006504 if (std::error_code EC = BufOrErr.getError()) {
Rafael Espindolaadf21f22014-07-06 17:43:13 +00006505 errs() << "llvm-objdump: " << Filename << ": " << EC.message() << '\n';
Benjamin Kramer699128e2011-09-21 01:13:19 +00006506 return;
6507 }
Rafael Espindola48af1c22014-08-19 18:44:46 +00006508 DbgObj =
6509 ObjectFile::createMachOObjectFile(BufOrErr.get()->getMemBufferRef())
6510 .get()
6511 .release();
Benjamin Kramer699128e2011-09-21 01:13:19 +00006512 }
6513
Eric Christopher7370b552012-11-12 21:40:38 +00006514 // Setup the DIContext
Zachary Turner6489d7b2015-04-23 17:37:47 +00006515 diContext.reset(new DWARFContextInMemory(*DbgObj));
Benjamin Kramer699128e2011-09-21 01:13:19 +00006516 }
6517
Colin LeMahieufcc32762015-07-29 19:08:10 +00006518 if (FilterSections.size() == 0)
Kevin Enderby95df54c2015-02-04 01:01:38 +00006519 outs() << "(" << DisSegName << "," << DisSectName << ") section\n";
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00006520
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006521 for (unsigned SectIdx = 0; SectIdx != Sections.size(); SectIdx++) {
Owen Andersond9243c42011-10-17 21:37:35 +00006522 StringRef SectName;
Kevin Enderby95df54c2015-02-04 01:01:38 +00006523 if (Sections[SectIdx].getName(SectName) || SectName != DisSectName)
6524 continue;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006525
Rafael Espindolaa9f810b2012-12-21 03:47:03 +00006526 DataRefImpl DR = Sections[SectIdx].getRawDataRefImpl();
Ahmed Bougachaaa790682013-05-24 01:07:04 +00006527
Rafael Espindolab0f76a42013-04-05 15:15:22 +00006528 StringRef SegmentName = MachOOF->getSectionFinalSegmentName(DR);
Kevin Enderby95df54c2015-02-04 01:01:38 +00006529 if (SegmentName != DisSegName)
Rafael Espindolaa9f810b2012-12-21 03:47:03 +00006530 continue;
6531
Rafael Espindola7fc5b872014-11-12 02:04:27 +00006532 StringRef BytesStr;
6533 Sections[SectIdx].getContents(BytesStr);
Aaron Ballman106fd7b2014-11-12 14:01:17 +00006534 ArrayRef<uint8_t> Bytes(reinterpret_cast<const uint8_t *>(BytesStr.data()),
6535 BytesStr.size());
Rafael Espindola80291272014-10-08 15:28:58 +00006536 uint64_t SectAddress = Sections[SectIdx].getAddress();
Rafael Espindolabd604f22014-11-07 00:52:15 +00006537
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006538 bool symbolTableWorked = false;
6539
Kevin Enderbybf246f52014-09-24 23:08:22 +00006540 // Create a map of symbol addresses to symbol names for use by
6541 // the SymbolizerSymbolLookUp() routine.
6542 SymbolAddressMap AddrMap;
Kevin Enderby6a221752015-03-17 17:10:57 +00006543 bool DisSymNameFound = false;
Kevin Enderbybf246f52014-09-24 23:08:22 +00006544 for (const SymbolRef &Symbol : MachOOF->symbols()) {
Kevin Enderby7bd8d992016-05-02 20:28:12 +00006545 Expected<SymbolRef::Type> STOrErr = Symbol.getType();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00006546 if (!STOrErr)
6547 report_error(MachOOF->getFileName(), STOrErr.takeError());
Kevin Enderby5afbc1c2016-03-23 20:27:00 +00006548 SymbolRef::Type ST = *STOrErr;
Kevin Enderbybf246f52014-09-24 23:08:22 +00006549 if (ST == SymbolRef::ST_Function || ST == SymbolRef::ST_Data ||
6550 ST == SymbolRef::ST_Other) {
Rafael Espindoladea00162015-07-03 17:44:18 +00006551 uint64_t Address = Symbol.getValue();
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00006552 Expected<StringRef> SymNameOrErr = Symbol.getName();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00006553 if (!SymNameOrErr)
6554 report_error(MachOOF->getFileName(), SymNameOrErr.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00006555 StringRef SymName = *SymNameOrErr;
Kevin Enderbybf246f52014-09-24 23:08:22 +00006556 AddrMap[Address] = SymName;
Kevin Enderby6a221752015-03-17 17:10:57 +00006557 if (!DisSymName.empty() && DisSymName == SymName)
6558 DisSymNameFound = true;
Kevin Enderbybf246f52014-09-24 23:08:22 +00006559 }
6560 }
David Blaikie33dd45d02015-03-23 18:39:02 +00006561 if (!DisSymName.empty() && !DisSymNameFound) {
Kevin Enderby6a221752015-03-17 17:10:57 +00006562 outs() << "Can't find -dis-symname: " << DisSymName << "\n";
6563 return;
6564 }
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006565 // Set up the block of info used by the Symbolizer call backs.
Kevin Enderby8e29ec92015-03-17 22:26:11 +00006566 SymbolizerInfo.verbose = !NoSymbolicOperands;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006567 SymbolizerInfo.O = MachOOF;
6568 SymbolizerInfo.S = Sections[SectIdx];
Kevin Enderbybf246f52014-09-24 23:08:22 +00006569 SymbolizerInfo.AddrMap = &AddrMap;
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006570 SymbolizerInfo.Sections = &Sections;
6571 SymbolizerInfo.class_name = nullptr;
6572 SymbolizerInfo.selector_name = nullptr;
6573 SymbolizerInfo.method = nullptr;
Kevin Enderby04bf6932014-10-28 23:39:46 +00006574 SymbolizerInfo.demangled_name = nullptr;
Kevin Enderby078be602014-10-23 19:53:12 +00006575 SymbolizerInfo.bindtable = nullptr;
Kevin Enderby10738222014-11-19 20:20:16 +00006576 SymbolizerInfo.adrp_addr = 0;
6577 SymbolizerInfo.adrp_inst = 0;
Kevin Enderby930fdc72014-11-06 19:00:13 +00006578 // Same for the ThumbSymbolizer
Kevin Enderby8e29ec92015-03-17 22:26:11 +00006579 ThumbSymbolizerInfo.verbose = !NoSymbolicOperands;
Kevin Enderby930fdc72014-11-06 19:00:13 +00006580 ThumbSymbolizerInfo.O = MachOOF;
6581 ThumbSymbolizerInfo.S = Sections[SectIdx];
6582 ThumbSymbolizerInfo.AddrMap = &AddrMap;
6583 ThumbSymbolizerInfo.Sections = &Sections;
6584 ThumbSymbolizerInfo.class_name = nullptr;
6585 ThumbSymbolizerInfo.selector_name = nullptr;
6586 ThumbSymbolizerInfo.method = nullptr;
6587 ThumbSymbolizerInfo.demangled_name = nullptr;
6588 ThumbSymbolizerInfo.bindtable = nullptr;
Kevin Enderby10738222014-11-19 20:20:16 +00006589 ThumbSymbolizerInfo.adrp_addr = 0;
6590 ThumbSymbolizerInfo.adrp_inst = 0;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006591
Kevin Enderby4b627be2016-04-28 20:14:13 +00006592 unsigned int Arch = MachOOF->getArch();
6593
Tim Northoverf203ab52016-07-14 22:13:32 +00006594 // Skip all symbols if this is a stubs file.
6595 if (Bytes.size() == 0)
6596 return;
6597
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00006598 // Disassemble symbol by symbol.
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006599 for (unsigned SymIdx = 0; SymIdx != Symbols.size(); SymIdx++) {
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00006600 Expected<StringRef> SymNameOrErr = Symbols[SymIdx].getName();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00006601 if (!SymNameOrErr)
6602 report_error(MachOOF->getFileName(), SymNameOrErr.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00006603 StringRef SymName = *SymNameOrErr;
Owen Andersond9243c42011-10-17 21:37:35 +00006604
Kevin Enderby7bd8d992016-05-02 20:28:12 +00006605 Expected<SymbolRef::Type> STOrErr = Symbols[SymIdx].getType();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00006606 if (!STOrErr)
6607 report_error(MachOOF->getFileName(), STOrErr.takeError());
Kevin Enderby5afbc1c2016-03-23 20:27:00 +00006608 SymbolRef::Type ST = *STOrErr;
Kuba Breckade833222015-11-12 09:40:29 +00006609 if (ST != SymbolRef::ST_Function && ST != SymbolRef::ST_Data)
Owen Andersond9243c42011-10-17 21:37:35 +00006610 continue;
6611
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00006612 // Make sure the symbol is defined in this section.
Rafael Espindola80291272014-10-08 15:28:58 +00006613 bool containsSym = Sections[SectIdx].containsSymbol(Symbols[SymIdx]);
Kevin Enderbyd8a6e832016-06-15 21:14:01 +00006614 if (!containsSym) {
6615 if (!DisSymName.empty() && DisSymName == SymName) {
6616 outs() << "-dis-symname: " << DisSymName << " not in the section\n";
6617 return;
6618 }
6619 continue;
6620 }
6621 // The __mh_execute_header is special and we need to deal with that fact
6622 // this symbol is before the start of the (__TEXT,__text) section and at the
6623 // address of the start of the __TEXT segment. This is because this symbol
6624 // is an N_SECT symbol in the (__TEXT,__text) but its address is before the
6625 // start of the section in a standard MH_EXECUTE filetype.
6626 if (!DisSymName.empty() && DisSymName == "__mh_execute_header") {
6627 outs() << "-dis-symname: __mh_execute_header not in any section\n";
6628 return;
6629 }
Tim Northoverfbefee32016-07-14 23:13:03 +00006630 // When this code is trying to disassemble a symbol at a time and in the
6631 // case there is only the __mh_execute_header symbol left as in a stripped
6632 // executable, we need to deal with this by ignoring this symbol so the
6633 // whole section is disassembled and this symbol is then not displayed.
6634 if (SymName == "__mh_execute_header" || SymName == "__mh_dylib_header" ||
6635 SymName == "__mh_bundle_header" || SymName == "__mh_object_header" ||
6636 SymName == "__mh_preload_header" || SymName == "__mh_dylinker_header")
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006637 continue;
6638
Kevin Enderby6a221752015-03-17 17:10:57 +00006639 // If we are only disassembling one symbol see if this is that symbol.
6640 if (!DisSymName.empty() && DisSymName != SymName)
6641 continue;
6642
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00006643 // Start at the address of the symbol relative to the section's address.
Tim Northoverf203ab52016-07-14 22:13:32 +00006644 uint64_t SectSize = Sections[SectIdx].getSize();
Rafael Espindoladea00162015-07-03 17:44:18 +00006645 uint64_t Start = Symbols[SymIdx].getValue();
Rafael Espindola80291272014-10-08 15:28:58 +00006646 uint64_t SectionAddress = Sections[SectIdx].getAddress();
Cameron Zwarich54478a52012-02-03 05:42:17 +00006647 Start -= SectionAddress;
Owen Andersond9243c42011-10-17 21:37:35 +00006648
Tim Northoverf203ab52016-07-14 22:13:32 +00006649 if (Start > SectSize) {
6650 outs() << "section data ends, " << SymName
6651 << " lies outside valid range\n";
6652 return;
6653 }
6654
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00006655 // Stop disassembling either at the beginning of the next symbol or at
6656 // the end of the section.
Kevin Enderbyedd58722012-05-15 18:57:14 +00006657 bool containsNextSym = false;
Owen Andersond9243c42011-10-17 21:37:35 +00006658 uint64_t NextSym = 0;
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006659 uint64_t NextSymIdx = SymIdx + 1;
Owen Andersond9243c42011-10-17 21:37:35 +00006660 while (Symbols.size() > NextSymIdx) {
Kevin Enderby7bd8d992016-05-02 20:28:12 +00006661 Expected<SymbolRef::Type> STOrErr = Symbols[NextSymIdx].getType();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00006662 if (!STOrErr)
6663 report_error(MachOOF->getFileName(), STOrErr.takeError());
Kevin Enderby5afbc1c2016-03-23 20:27:00 +00006664 SymbolRef::Type NextSymType = *STOrErr;
Owen Andersond9243c42011-10-17 21:37:35 +00006665 if (NextSymType == SymbolRef::ST_Function) {
Rafael Espindola80291272014-10-08 15:28:58 +00006666 containsNextSym =
6667 Sections[SectIdx].containsSymbol(Symbols[NextSymIdx]);
Rafael Espindoladea00162015-07-03 17:44:18 +00006668 NextSym = Symbols[NextSymIdx].getValue();
Cameron Zwarich54478a52012-02-03 05:42:17 +00006669 NextSym -= SectionAddress;
Owen Andersond9243c42011-10-17 21:37:35 +00006670 break;
6671 }
6672 ++NextSymIdx;
6673 }
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006674
Tim Northoverf203ab52016-07-14 22:13:32 +00006675 uint64_t End = containsNextSym ? std::min(NextSym, SectSize) : SectSize;
Owen Andersond9243c42011-10-17 21:37:35 +00006676 uint64_t Size;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006677
6678 symbolTableWorked = true;
Rafael Espindolabd604f22014-11-07 00:52:15 +00006679
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006680 DataRefImpl Symb = Symbols[SymIdx].getRawDataRefImpl();
Tim Northover09ca33e2016-04-22 23:23:31 +00006681 bool IsThumb = MachOOF->getSymbolFlags(Symb) & SymbolRef::SF_Thumb;
6682
6683 // We only need the dedicated Thumb target if there's a real choice
6684 // (i.e. we're not targeting M-class) and the function is Thumb.
6685 bool UseThumbTarget = IsThumb && ThumbTarget;
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006686
Ahmed Bougachaaa790682013-05-24 01:07:04 +00006687 outs() << SymName << ":\n";
6688 DILineInfo lastLine;
6689 for (uint64_t Index = Start; Index < End; Index += Size) {
6690 MCInst Inst;
Owen Andersond9243c42011-10-17 21:37:35 +00006691
Kevin Enderbybf246f52014-09-24 23:08:22 +00006692 uint64_t PC = SectAddress + Index;
Kevin Enderbyab5e6c92015-03-17 21:07:39 +00006693 if (!NoLeadingAddr) {
6694 if (FullLeadingAddr) {
6695 if (MachOOF->is64Bit())
6696 outs() << format("%016" PRIx64, PC);
6697 else
6698 outs() << format("%08" PRIx64, PC);
6699 } else {
6700 outs() << format("%8" PRIx64 ":", PC);
6701 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00006702 }
Kevin Enderby4b627be2016-04-28 20:14:13 +00006703 if (!NoShowRawInsn || Arch == Triple::arm)
Kevin Enderbybf246f52014-09-24 23:08:22 +00006704 outs() << "\t";
Kevin Enderby273ae012013-06-06 17:20:50 +00006705
6706 // Check the data in code table here to see if this is data not an
6707 // instruction to be disassembled.
6708 DiceTable Dice;
Kevin Enderbybf246f52014-09-24 23:08:22 +00006709 Dice.push_back(std::make_pair(PC, DiceRef()));
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006710 dice_table_iterator DTI =
6711 std::search(Dices.begin(), Dices.end(), Dice.begin(), Dice.end(),
6712 compareDiceTableEntries);
6713 if (DTI != Dices.end()) {
Kevin Enderby273ae012013-06-06 17:20:50 +00006714 uint16_t Length;
6715 DTI->second.getLength(Length);
Kevin Enderby273ae012013-06-06 17:20:50 +00006716 uint16_t Kind;
6717 DTI->second.getKind(Kind);
Colin LeMahieufc32b1b2015-03-18 19:27:31 +00006718 Size = DumpDataInCode(Bytes.data() + Index, Length, Kind);
Kevin Enderby930fdc72014-11-06 19:00:13 +00006719 if ((Kind == MachO::DICE_KIND_JUMP_TABLE8) &&
6720 (PC == (DTI->first + Length - 1)) && (Length & 1))
6721 Size++;
Kevin Enderby273ae012013-06-06 17:20:50 +00006722 continue;
6723 }
6724
Kevin Enderbybf246f52014-09-24 23:08:22 +00006725 SmallVector<char, 64> AnnotationsBytes;
6726 raw_svector_ostream Annotations(AnnotationsBytes);
6727
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006728 bool gotInst;
Tim Northover09ca33e2016-04-22 23:23:31 +00006729 if (UseThumbTarget)
Rafael Espindola7fc5b872014-11-12 02:04:27 +00006730 gotInst = ThumbDisAsm->getInstruction(Inst, Size, Bytes.slice(Index),
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006731 PC, DebugOut, Annotations);
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006732 else
Rafael Espindola7fc5b872014-11-12 02:04:27 +00006733 gotInst = DisAsm->getInstruction(Inst, Size, Bytes.slice(Index), PC,
Kevin Enderbybf246f52014-09-24 23:08:22 +00006734 DebugOut, Annotations);
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006735 if (gotInst) {
Kevin Enderby4b627be2016-04-28 20:14:13 +00006736 if (!NoShowRawInsn || Arch == Triple::arm) {
Craig Topper0013be12015-09-21 05:32:41 +00006737 dumpBytes(makeArrayRef(Bytes.data() + Index, Size), outs());
Kevin Enderbybf246f52014-09-24 23:08:22 +00006738 }
6739 formatted_raw_ostream FormattedOS(outs());
Kevin Enderbybf246f52014-09-24 23:08:22 +00006740 StringRef AnnotationsStr = Annotations.str();
Tim Northover09ca33e2016-04-22 23:23:31 +00006741 if (UseThumbTarget)
Akira Hatanakab46d0232015-03-27 20:36:02 +00006742 ThumbIP->printInst(&Inst, FormattedOS, AnnotationsStr, *ThumbSTI);
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006743 else
Akira Hatanaka1d079942015-03-28 20:44:05 +00006744 IP->printInst(&Inst, FormattedOS, AnnotationsStr, *STI);
Kevin Enderbybf246f52014-09-24 23:08:22 +00006745 emitComments(CommentStream, CommentsToEmit, FormattedOS, *AsmInfo);
Owen Andersond9243c42011-10-17 21:37:35 +00006746
Ahmed Bougachaaa790682013-05-24 01:07:04 +00006747 // Print debug info.
6748 if (diContext) {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006749 DILineInfo dli = diContext->getLineInfoForAddress(PC);
Ahmed Bougachaaa790682013-05-24 01:07:04 +00006750 // Print valid line info if it changed.
Alexey Samsonovd0109992014-04-18 21:36:39 +00006751 if (dli != lastLine && dli.Line != 0)
6752 outs() << "\t## " << dli.FileName << ':' << dli.Line << ':'
6753 << dli.Column;
Ahmed Bougachaaa790682013-05-24 01:07:04 +00006754 lastLine = dli;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006755 }
Ahmed Bougachaaa790682013-05-24 01:07:04 +00006756 outs() << "\n";
6757 } else {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006758 unsigned int Arch = MachOOF->getArch();
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006759 if (Arch == Triple::x86_64 || Arch == Triple::x86) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006760 outs() << format("\t.byte 0x%02x #bad opcode\n",
6761 *(Bytes.data() + Index) & 0xff);
6762 Size = 1; // skip exactly one illegible byte and move on.
Tim Northover09ca33e2016-04-22 23:23:31 +00006763 } else if (Arch == Triple::aarch64 ||
6764 (Arch == Triple::arm && !IsThumb)) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00006765 uint32_t opcode = (*(Bytes.data() + Index) & 0xff) |
6766 (*(Bytes.data() + Index + 1) & 0xff) << 8 |
6767 (*(Bytes.data() + Index + 2) & 0xff) << 16 |
6768 (*(Bytes.data() + Index + 3) & 0xff) << 24;
6769 outs() << format("\t.long\t0x%08x\n", opcode);
6770 Size = 4;
Tim Northover09ca33e2016-04-22 23:23:31 +00006771 } else if (Arch == Triple::arm) {
6772 assert(IsThumb && "ARM mode should have been dealt with above");
6773 uint32_t opcode = (*(Bytes.data() + Index) & 0xff) |
6774 (*(Bytes.data() + Index + 1) & 0xff) << 8;
6775 outs() << format("\t.short\t0x%04x\n", opcode);
6776 Size = 2;
6777 } else{
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006778 errs() << "llvm-objdump: warning: invalid instruction encoding\n";
6779 if (Size == 0)
6780 Size = 1; // skip illegible bytes
6781 }
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006782 }
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006783 }
6784 }
Ahmed Bougachaaa790682013-05-24 01:07:04 +00006785 if (!symbolTableWorked) {
Rafael Espindola80291272014-10-08 15:28:58 +00006786 // Reading the symbol table didn't work, disassemble the whole section.
6787 uint64_t SectAddress = Sections[SectIdx].getAddress();
6788 uint64_t SectSize = Sections[SectIdx].getSize();
Kevin Enderbybadd1002012-05-18 00:13:56 +00006789 uint64_t InstSize;
6790 for (uint64_t Index = 0; Index < SectSize; Index += InstSize) {
Bill Wendling4e68e062012-07-19 00:17:40 +00006791 MCInst Inst;
Kevin Enderbybadd1002012-05-18 00:13:56 +00006792
Kevin Enderbybf246f52014-09-24 23:08:22 +00006793 uint64_t PC = SectAddress + Index;
Rafael Espindola7fc5b872014-11-12 02:04:27 +00006794 if (DisAsm->getInstruction(Inst, InstSize, Bytes.slice(Index), PC,
6795 DebugOut, nulls())) {
Kevin Enderbyab5e6c92015-03-17 21:07:39 +00006796 if (!NoLeadingAddr) {
6797 if (FullLeadingAddr) {
6798 if (MachOOF->is64Bit())
6799 outs() << format("%016" PRIx64, PC);
6800 else
6801 outs() << format("%08" PRIx64, PC);
6802 } else {
6803 outs() << format("%8" PRIx64 ":", PC);
6804 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00006805 }
Kevin Enderby4b627be2016-04-28 20:14:13 +00006806 if (!NoShowRawInsn || Arch == Triple::arm) {
Kevin Enderbybf246f52014-09-24 23:08:22 +00006807 outs() << "\t";
Craig Topper0013be12015-09-21 05:32:41 +00006808 dumpBytes(makeArrayRef(Bytes.data() + Index, InstSize), outs());
Kevin Enderbybf246f52014-09-24 23:08:22 +00006809 }
Akira Hatanaka1d079942015-03-28 20:44:05 +00006810 IP->printInst(&Inst, outs(), "", *STI);
Bill Wendling4e68e062012-07-19 00:17:40 +00006811 outs() << "\n";
6812 } else {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006813 unsigned int Arch = MachOOF->getArch();
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006814 if (Arch == Triple::x86_64 || Arch == Triple::x86) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006815 outs() << format("\t.byte 0x%02x #bad opcode\n",
6816 *(Bytes.data() + Index) & 0xff);
6817 InstSize = 1; // skip exactly one illegible byte and move on.
6818 } else {
6819 errs() << "llvm-objdump: warning: invalid instruction encoding\n";
6820 if (InstSize == 0)
6821 InstSize = 1; // skip illegible bytes
6822 }
Bill Wendling4e68e062012-07-19 00:17:40 +00006823 }
Kevin Enderbybadd1002012-05-18 00:13:56 +00006824 }
6825 }
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00006826 // The TripleName's need to be reset if we are called again for a different
6827 // archtecture.
6828 TripleName = "";
6829 ThumbTripleName = "";
6830
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006831 if (SymbolizerInfo.method != nullptr)
6832 free(SymbolizerInfo.method);
Kevin Enderby04bf6932014-10-28 23:39:46 +00006833 if (SymbolizerInfo.demangled_name != nullptr)
6834 free(SymbolizerInfo.demangled_name);
Kevin Enderby078be602014-10-23 19:53:12 +00006835 if (SymbolizerInfo.bindtable != nullptr)
6836 delete SymbolizerInfo.bindtable;
Kevin Enderby930fdc72014-11-06 19:00:13 +00006837 if (ThumbSymbolizerInfo.method != nullptr)
6838 free(ThumbSymbolizerInfo.method);
6839 if (ThumbSymbolizerInfo.demangled_name != nullptr)
6840 free(ThumbSymbolizerInfo.demangled_name);
6841 if (ThumbSymbolizerInfo.bindtable != nullptr)
6842 delete ThumbSymbolizerInfo.bindtable;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006843 }
6844}
Tim Northover4bd286a2014-08-01 13:07:19 +00006845
Tim Northover39c70bb2014-08-12 11:52:59 +00006846//===----------------------------------------------------------------------===//
6847// __compact_unwind section dumping
6848//===----------------------------------------------------------------------===//
6849
Tim Northover4bd286a2014-08-01 13:07:19 +00006850namespace {
Tim Northover39c70bb2014-08-12 11:52:59 +00006851
6852template <typename T> static uint64_t readNext(const char *&Buf) {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006853 using llvm::support::little;
6854 using llvm::support::unaligned;
Tim Northover39c70bb2014-08-12 11:52:59 +00006855
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006856 uint64_t Val = support::endian::read<T, little, unaligned>(Buf);
6857 Buf += sizeof(T);
6858 return Val;
6859}
Tim Northover39c70bb2014-08-12 11:52:59 +00006860
Tim Northover4bd286a2014-08-01 13:07:19 +00006861struct CompactUnwindEntry {
6862 uint32_t OffsetInSection;
6863
6864 uint64_t FunctionAddr;
6865 uint32_t Length;
6866 uint32_t CompactEncoding;
6867 uint64_t PersonalityAddr;
6868 uint64_t LSDAAddr;
6869
6870 RelocationRef FunctionReloc;
6871 RelocationRef PersonalityReloc;
6872 RelocationRef LSDAReloc;
6873
6874 CompactUnwindEntry(StringRef Contents, unsigned Offset, bool Is64)
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006875 : OffsetInSection(Offset) {
Tim Northover4bd286a2014-08-01 13:07:19 +00006876 if (Is64)
6877 read<uint64_t>(Contents.data() + Offset);
6878 else
6879 read<uint32_t>(Contents.data() + Offset);
6880 }
6881
6882private:
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006883 template <typename UIntPtr> void read(const char *Buf) {
Tim Northover4bd286a2014-08-01 13:07:19 +00006884 FunctionAddr = readNext<UIntPtr>(Buf);
6885 Length = readNext<uint32_t>(Buf);
6886 CompactEncoding = readNext<uint32_t>(Buf);
6887 PersonalityAddr = readNext<UIntPtr>(Buf);
6888 LSDAAddr = readNext<UIntPtr>(Buf);
6889 }
6890};
6891}
6892
6893/// Given a relocation from __compact_unwind, consisting of the RelocationRef
6894/// and data being relocated, determine the best base Name and Addend to use for
6895/// display purposes.
6896///
6897/// 1. An Extern relocation will directly reference a symbol (and the data is
6898/// then already an addend), so use that.
6899/// 2. Otherwise the data is an offset in the object file's layout; try to find
6900// a symbol before it in the same section, and use the offset from there.
6901/// 3. Finally, if all that fails, fall back to an offset from the start of the
6902/// referenced section.
6903static void findUnwindRelocNameAddend(const MachOObjectFile *Obj,
6904 std::map<uint64_t, SymbolRef> &Symbols,
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006905 const RelocationRef &Reloc, uint64_t Addr,
Tim Northover4bd286a2014-08-01 13:07:19 +00006906 StringRef &Name, uint64_t &Addend) {
6907 if (Reloc.getSymbol() != Obj->symbol_end()) {
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00006908 Expected<StringRef> NameOrErr = Reloc.getSymbol()->getName();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00006909 if (!NameOrErr)
6910 report_error(Obj->getFileName(), NameOrErr.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00006911 Name = *NameOrErr;
Tim Northover4bd286a2014-08-01 13:07:19 +00006912 Addend = Addr;
6913 return;
6914 }
6915
6916 auto RE = Obj->getRelocation(Reloc.getRawDataRefImpl());
Keno Fischerc780e8e2015-05-21 21:24:32 +00006917 SectionRef RelocSection = Obj->getAnyRelocationSection(RE);
Tim Northover4bd286a2014-08-01 13:07:19 +00006918
Rafael Espindola80291272014-10-08 15:28:58 +00006919 uint64_t SectionAddr = RelocSection.getAddress();
Tim Northover4bd286a2014-08-01 13:07:19 +00006920
6921 auto Sym = Symbols.upper_bound(Addr);
6922 if (Sym == Symbols.begin()) {
6923 // The first symbol in the object is after this reference, the best we can
6924 // do is section-relative notation.
6925 RelocSection.getName(Name);
6926 Addend = Addr - SectionAddr;
6927 return;
6928 }
6929
6930 // Go back one so that SymbolAddress <= Addr.
6931 --Sym;
6932
Kevin Enderby7bd8d992016-05-02 20:28:12 +00006933 auto SectOrErr = Sym->second.getSection();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00006934 if (!SectOrErr)
6935 report_error(Obj->getFileName(), SectOrErr.takeError());
Kevin Enderby7bd8d992016-05-02 20:28:12 +00006936 section_iterator SymSection = *SectOrErr;
Tim Northover4bd286a2014-08-01 13:07:19 +00006937 if (RelocSection == *SymSection) {
6938 // There's a valid symbol in the same section before this reference.
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00006939 Expected<StringRef> NameOrErr = Sym->second.getName();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00006940 if (!NameOrErr)
6941 report_error(Obj->getFileName(), NameOrErr.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00006942 Name = *NameOrErr;
Tim Northover4bd286a2014-08-01 13:07:19 +00006943 Addend = Addr - Sym->first;
6944 return;
6945 }
6946
6947 // There is a symbol before this reference, but it's in a different
6948 // section. Probably not helpful to mention it, so use the section name.
6949 RelocSection.getName(Name);
6950 Addend = Addr - SectionAddr;
6951}
6952
6953static void printUnwindRelocDest(const MachOObjectFile *Obj,
6954 std::map<uint64_t, SymbolRef> &Symbols,
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006955 const RelocationRef &Reloc, uint64_t Addr) {
Tim Northover4bd286a2014-08-01 13:07:19 +00006956 StringRef Name;
6957 uint64_t Addend;
6958
Rafael Espindola854038e2015-06-26 14:51:16 +00006959 if (!Reloc.getObject())
Tim Northover0b0add52014-09-09 10:45:06 +00006960 return;
6961
Tim Northover4bd286a2014-08-01 13:07:19 +00006962 findUnwindRelocNameAddend(Obj, Symbols, Reloc, Addr, Name, Addend);
6963
6964 outs() << Name;
6965 if (Addend)
Tim Northover63a25622014-08-11 09:14:06 +00006966 outs() << " + " << format("0x%" PRIx64, Addend);
Tim Northover4bd286a2014-08-01 13:07:19 +00006967}
6968
6969static void
6970printMachOCompactUnwindSection(const MachOObjectFile *Obj,
6971 std::map<uint64_t, SymbolRef> &Symbols,
6972 const SectionRef &CompactUnwind) {
6973
Tim Northoverbf55f7e2016-11-15 20:26:01 +00006974 if (!Obj->isLittleEndian()) {
6975 outs() << "Skipping big-endian __compact_unwind section\n";
6976 return;
6977 }
Tim Northover4bd286a2014-08-01 13:07:19 +00006978
6979 bool Is64 = Obj->is64Bit();
6980 uint32_t PointerSize = Is64 ? sizeof(uint64_t) : sizeof(uint32_t);
6981 uint32_t EntrySize = 3 * PointerSize + 2 * sizeof(uint32_t);
6982
6983 StringRef Contents;
6984 CompactUnwind.getContents(Contents);
6985
6986 SmallVector<CompactUnwindEntry, 4> CompactUnwinds;
6987
6988 // First populate the initial raw offsets, encodings and so on from the entry.
6989 for (unsigned Offset = 0; Offset < Contents.size(); Offset += EntrySize) {
6990 CompactUnwindEntry Entry(Contents.data(), Offset, Is64);
6991 CompactUnwinds.push_back(Entry);
6992 }
6993
6994 // Next we need to look at the relocations to find out what objects are
6995 // actually being referred to.
6996 for (const RelocationRef &Reloc : CompactUnwind.relocations()) {
Rafael Espindola96d071c2015-06-29 23:29:12 +00006997 uint64_t RelocAddress = Reloc.getOffset();
Tim Northover4bd286a2014-08-01 13:07:19 +00006998
6999 uint32_t EntryIdx = RelocAddress / EntrySize;
7000 uint32_t OffsetInEntry = RelocAddress - EntryIdx * EntrySize;
7001 CompactUnwindEntry &Entry = CompactUnwinds[EntryIdx];
7002
7003 if (OffsetInEntry == 0)
7004 Entry.FunctionReloc = Reloc;
7005 else if (OffsetInEntry == PointerSize + 2 * sizeof(uint32_t))
7006 Entry.PersonalityReloc = Reloc;
7007 else if (OffsetInEntry == 2 * PointerSize + 2 * sizeof(uint32_t))
7008 Entry.LSDAReloc = Reloc;
Tim Northoverbf55f7e2016-11-15 20:26:01 +00007009 else {
7010 outs() << "Invalid relocation in __compact_unwind section\n";
7011 return;
7012 }
Tim Northover4bd286a2014-08-01 13:07:19 +00007013 }
7014
7015 // Finally, we're ready to print the data we've gathered.
7016 outs() << "Contents of __compact_unwind section:\n";
7017 for (auto &Entry : CompactUnwinds) {
Tim Northover06af2602014-08-08 12:08:51 +00007018 outs() << " Entry at offset "
7019 << format("0x%" PRIx32, Entry.OffsetInSection) << ":\n";
Tim Northover4bd286a2014-08-01 13:07:19 +00007020
7021 // 1. Start of the region this entry applies to.
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007022 outs() << " start: " << format("0x%" PRIx64,
7023 Entry.FunctionAddr) << ' ';
7024 printUnwindRelocDest(Obj, Symbols, Entry.FunctionReloc, Entry.FunctionAddr);
Tim Northover4bd286a2014-08-01 13:07:19 +00007025 outs() << '\n';
7026
7027 // 2. Length of the region this entry applies to.
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007028 outs() << " length: " << format("0x%" PRIx32, Entry.Length)
7029 << '\n';
Tim Northover4bd286a2014-08-01 13:07:19 +00007030 // 3. The 32-bit compact encoding.
7031 outs() << " compact encoding: "
Tim Northoverb911bf82014-08-08 12:00:09 +00007032 << format("0x%08" PRIx32, Entry.CompactEncoding) << '\n';
Tim Northover4bd286a2014-08-01 13:07:19 +00007033
7034 // 4. The personality function, if present.
Rafael Espindola854038e2015-06-26 14:51:16 +00007035 if (Entry.PersonalityReloc.getObject()) {
Tim Northover4bd286a2014-08-01 13:07:19 +00007036 outs() << " personality function: "
Tim Northoverb911bf82014-08-08 12:00:09 +00007037 << format("0x%" PRIx64, Entry.PersonalityAddr) << ' ';
Tim Northover4bd286a2014-08-01 13:07:19 +00007038 printUnwindRelocDest(Obj, Symbols, Entry.PersonalityReloc,
7039 Entry.PersonalityAddr);
7040 outs() << '\n';
7041 }
7042
7043 // 5. This entry's language-specific data area.
Rafael Espindola854038e2015-06-26 14:51:16 +00007044 if (Entry.LSDAReloc.getObject()) {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007045 outs() << " LSDA: " << format("0x%" PRIx64,
7046 Entry.LSDAAddr) << ' ';
Tim Northover4bd286a2014-08-01 13:07:19 +00007047 printUnwindRelocDest(Obj, Symbols, Entry.LSDAReloc, Entry.LSDAAddr);
7048 outs() << '\n';
7049 }
7050 }
7051}
7052
Tim Northover39c70bb2014-08-12 11:52:59 +00007053//===----------------------------------------------------------------------===//
7054// __unwind_info section dumping
7055//===----------------------------------------------------------------------===//
7056
7057static void printRegularSecondLevelUnwindPage(const char *PageStart) {
7058 const char *Pos = PageStart;
7059 uint32_t Kind = readNext<uint32_t>(Pos);
7060 (void)Kind;
7061 assert(Kind == 2 && "kind for a regular 2nd level index should be 2");
7062
7063 uint16_t EntriesStart = readNext<uint16_t>(Pos);
7064 uint16_t NumEntries = readNext<uint16_t>(Pos);
7065
7066 Pos = PageStart + EntriesStart;
7067 for (unsigned i = 0; i < NumEntries; ++i) {
7068 uint32_t FunctionOffset = readNext<uint32_t>(Pos);
7069 uint32_t Encoding = readNext<uint32_t>(Pos);
7070
7071 outs() << " [" << i << "]: "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007072 << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
7073 << ", "
7074 << "encoding=" << format("0x%08" PRIx32, Encoding) << '\n';
Tim Northover39c70bb2014-08-12 11:52:59 +00007075 }
7076}
7077
7078static void printCompressedSecondLevelUnwindPage(
7079 const char *PageStart, uint32_t FunctionBase,
7080 const SmallVectorImpl<uint32_t> &CommonEncodings) {
7081 const char *Pos = PageStart;
7082 uint32_t Kind = readNext<uint32_t>(Pos);
7083 (void)Kind;
7084 assert(Kind == 3 && "kind for a compressed 2nd level index should be 3");
7085
7086 uint16_t EntriesStart = readNext<uint16_t>(Pos);
7087 uint16_t NumEntries = readNext<uint16_t>(Pos);
7088
7089 uint16_t EncodingsStart = readNext<uint16_t>(Pos);
7090 readNext<uint16_t>(Pos);
Aaron Ballman80930af2014-08-14 13:53:19 +00007091 const auto *PageEncodings = reinterpret_cast<const support::ulittle32_t *>(
7092 PageStart + EncodingsStart);
Tim Northover39c70bb2014-08-12 11:52:59 +00007093
7094 Pos = PageStart + EntriesStart;
7095 for (unsigned i = 0; i < NumEntries; ++i) {
7096 uint32_t Entry = readNext<uint32_t>(Pos);
7097 uint32_t FunctionOffset = FunctionBase + (Entry & 0xffffff);
7098 uint32_t EncodingIdx = Entry >> 24;
7099
7100 uint32_t Encoding;
7101 if (EncodingIdx < CommonEncodings.size())
7102 Encoding = CommonEncodings[EncodingIdx];
7103 else
7104 Encoding = PageEncodings[EncodingIdx - CommonEncodings.size()];
7105
7106 outs() << " [" << i << "]: "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007107 << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
7108 << ", "
7109 << "encoding[" << EncodingIdx
7110 << "]=" << format("0x%08" PRIx32, Encoding) << '\n';
Tim Northover39c70bb2014-08-12 11:52:59 +00007111 }
7112}
7113
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007114static void printMachOUnwindInfoSection(const MachOObjectFile *Obj,
7115 std::map<uint64_t, SymbolRef> &Symbols,
7116 const SectionRef &UnwindInfo) {
Tim Northover39c70bb2014-08-12 11:52:59 +00007117
Tim Northoverbf55f7e2016-11-15 20:26:01 +00007118 if (!Obj->isLittleEndian()) {
7119 outs() << "Skipping big-endian __unwind_info section\n";
7120 return;
7121 }
Tim Northover39c70bb2014-08-12 11:52:59 +00007122
7123 outs() << "Contents of __unwind_info section:\n";
7124
7125 StringRef Contents;
7126 UnwindInfo.getContents(Contents);
7127 const char *Pos = Contents.data();
7128
7129 //===----------------------------------
7130 // Section header
7131 //===----------------------------------
7132
7133 uint32_t Version = readNext<uint32_t>(Pos);
7134 outs() << " Version: "
7135 << format("0x%" PRIx32, Version) << '\n';
Tim Northoverbf55f7e2016-11-15 20:26:01 +00007136 if (Version != 1) {
7137 outs() << " Skipping section with unknown version\n";
7138 return;
7139 }
Tim Northover39c70bb2014-08-12 11:52:59 +00007140
7141 uint32_t CommonEncodingsStart = readNext<uint32_t>(Pos);
7142 outs() << " Common encodings array section offset: "
7143 << format("0x%" PRIx32, CommonEncodingsStart) << '\n';
7144 uint32_t NumCommonEncodings = readNext<uint32_t>(Pos);
7145 outs() << " Number of common encodings in array: "
7146 << format("0x%" PRIx32, NumCommonEncodings) << '\n';
7147
7148 uint32_t PersonalitiesStart = readNext<uint32_t>(Pos);
7149 outs() << " Personality function array section offset: "
7150 << format("0x%" PRIx32, PersonalitiesStart) << '\n';
7151 uint32_t NumPersonalities = readNext<uint32_t>(Pos);
7152 outs() << " Number of personality functions in array: "
7153 << format("0x%" PRIx32, NumPersonalities) << '\n';
7154
7155 uint32_t IndicesStart = readNext<uint32_t>(Pos);
7156 outs() << " Index array section offset: "
7157 << format("0x%" PRIx32, IndicesStart) << '\n';
7158 uint32_t NumIndices = readNext<uint32_t>(Pos);
7159 outs() << " Number of indices in array: "
7160 << format("0x%" PRIx32, NumIndices) << '\n';
7161
7162 //===----------------------------------
7163 // A shared list of common encodings
7164 //===----------------------------------
7165
7166 // These occupy indices in the range [0, N] whenever an encoding is referenced
7167 // from a compressed 2nd level index table. In practice the linker only
7168 // creates ~128 of these, so that indices are available to embed encodings in
7169 // the 2nd level index.
7170
7171 SmallVector<uint32_t, 64> CommonEncodings;
7172 outs() << " Common encodings: (count = " << NumCommonEncodings << ")\n";
7173 Pos = Contents.data() + CommonEncodingsStart;
7174 for (unsigned i = 0; i < NumCommonEncodings; ++i) {
7175 uint32_t Encoding = readNext<uint32_t>(Pos);
7176 CommonEncodings.push_back(Encoding);
7177
7178 outs() << " encoding[" << i << "]: " << format("0x%08" PRIx32, Encoding)
7179 << '\n';
7180 }
7181
Tim Northover39c70bb2014-08-12 11:52:59 +00007182 //===----------------------------------
7183 // Personality functions used in this executable
7184 //===----------------------------------
7185
7186 // There should be only a handful of these (one per source language,
7187 // roughly). Particularly since they only get 2 bits in the compact encoding.
7188
7189 outs() << " Personality functions: (count = " << NumPersonalities << ")\n";
7190 Pos = Contents.data() + PersonalitiesStart;
7191 for (unsigned i = 0; i < NumPersonalities; ++i) {
7192 uint32_t PersonalityFn = readNext<uint32_t>(Pos);
7193 outs() << " personality[" << i + 1
7194 << "]: " << format("0x%08" PRIx32, PersonalityFn) << '\n';
7195 }
7196
7197 //===----------------------------------
7198 // The level 1 index entries
7199 //===----------------------------------
7200
7201 // These specify an approximate place to start searching for the more detailed
7202 // information, sorted by PC.
7203
7204 struct IndexEntry {
7205 uint32_t FunctionOffset;
7206 uint32_t SecondLevelPageStart;
7207 uint32_t LSDAStart;
7208 };
7209
7210 SmallVector<IndexEntry, 4> IndexEntries;
7211
7212 outs() << " Top level indices: (count = " << NumIndices << ")\n";
7213 Pos = Contents.data() + IndicesStart;
7214 for (unsigned i = 0; i < NumIndices; ++i) {
7215 IndexEntry Entry;
7216
7217 Entry.FunctionOffset = readNext<uint32_t>(Pos);
7218 Entry.SecondLevelPageStart = readNext<uint32_t>(Pos);
7219 Entry.LSDAStart = readNext<uint32_t>(Pos);
7220 IndexEntries.push_back(Entry);
7221
7222 outs() << " [" << i << "]: "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007223 << "function offset=" << format("0x%08" PRIx32, Entry.FunctionOffset)
7224 << ", "
Tim Northover39c70bb2014-08-12 11:52:59 +00007225 << "2nd level page offset="
7226 << format("0x%08" PRIx32, Entry.SecondLevelPageStart) << ", "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007227 << "LSDA offset=" << format("0x%08" PRIx32, Entry.LSDAStart) << '\n';
Tim Northover39c70bb2014-08-12 11:52:59 +00007228 }
7229
Tim Northover39c70bb2014-08-12 11:52:59 +00007230 //===----------------------------------
7231 // Next come the LSDA tables
7232 //===----------------------------------
7233
7234 // The LSDA layout is rather implicit: it's a contiguous array of entries from
7235 // the first top-level index's LSDAOffset to the last (sentinel).
7236
7237 outs() << " LSDA descriptors:\n";
7238 Pos = Contents.data() + IndexEntries[0].LSDAStart;
7239 int NumLSDAs = (IndexEntries.back().LSDAStart - IndexEntries[0].LSDAStart) /
7240 (2 * sizeof(uint32_t));
7241 for (int i = 0; i < NumLSDAs; ++i) {
7242 uint32_t FunctionOffset = readNext<uint32_t>(Pos);
7243 uint32_t LSDAOffset = readNext<uint32_t>(Pos);
7244 outs() << " [" << i << "]: "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007245 << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
7246 << ", "
7247 << "LSDA offset=" << format("0x%08" PRIx32, LSDAOffset) << '\n';
Tim Northover39c70bb2014-08-12 11:52:59 +00007248 }
7249
7250 //===----------------------------------
7251 // Finally, the 2nd level indices
7252 //===----------------------------------
7253
7254 // Generally these are 4K in size, and have 2 possible forms:
7255 // + Regular stores up to 511 entries with disparate encodings
7256 // + Compressed stores up to 1021 entries if few enough compact encoding
7257 // values are used.
7258 outs() << " Second level indices:\n";
7259 for (unsigned i = 0; i < IndexEntries.size() - 1; ++i) {
7260 // The final sentinel top-level index has no associated 2nd level page
7261 if (IndexEntries[i].SecondLevelPageStart == 0)
7262 break;
7263
7264 outs() << " Second level index[" << i << "]: "
7265 << "offset in section="
7266 << format("0x%08" PRIx32, IndexEntries[i].SecondLevelPageStart)
7267 << ", "
7268 << "base function offset="
7269 << format("0x%08" PRIx32, IndexEntries[i].FunctionOffset) << '\n';
7270
7271 Pos = Contents.data() + IndexEntries[i].SecondLevelPageStart;
Aaron Ballman80930af2014-08-14 13:53:19 +00007272 uint32_t Kind = *reinterpret_cast<const support::ulittle32_t *>(Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007273 if (Kind == 2)
7274 printRegularSecondLevelUnwindPage(Pos);
7275 else if (Kind == 3)
7276 printCompressedSecondLevelUnwindPage(Pos, IndexEntries[i].FunctionOffset,
7277 CommonEncodings);
7278 else
Tim Northoverbf55f7e2016-11-15 20:26:01 +00007279 outs() << " Skipping 2nd level page with unknown kind " << Kind
7280 << '\n';
Tim Northover39c70bb2014-08-12 11:52:59 +00007281 }
7282}
7283
Tim Northover4bd286a2014-08-01 13:07:19 +00007284void llvm::printMachOUnwindInfo(const MachOObjectFile *Obj) {
7285 std::map<uint64_t, SymbolRef> Symbols;
7286 for (const SymbolRef &SymRef : Obj->symbols()) {
7287 // Discard any undefined or absolute symbols. They're not going to take part
7288 // in the convenience lookup for unwind info and just take up resources.
Kevin Enderby7bd8d992016-05-02 20:28:12 +00007289 auto SectOrErr = SymRef.getSection();
7290 if (!SectOrErr) {
7291 // TODO: Actually report errors helpfully.
7292 consumeError(SectOrErr.takeError());
7293 continue;
7294 }
7295 section_iterator Section = *SectOrErr;
Tim Northover4bd286a2014-08-01 13:07:19 +00007296 if (Section == Obj->section_end())
7297 continue;
7298
Rafael Espindoladea00162015-07-03 17:44:18 +00007299 uint64_t Addr = SymRef.getValue();
Tim Northover4bd286a2014-08-01 13:07:19 +00007300 Symbols.insert(std::make_pair(Addr, SymRef));
7301 }
7302
7303 for (const SectionRef &Section : Obj->sections()) {
7304 StringRef SectName;
7305 Section.getName(SectName);
7306 if (SectName == "__compact_unwind")
7307 printMachOCompactUnwindSection(Obj, Symbols, Section);
7308 else if (SectName == "__unwind_info")
Tim Northover39c70bb2014-08-12 11:52:59 +00007309 printMachOUnwindInfoSection(Obj, Symbols, Section);
Tim Northover4bd286a2014-08-01 13:07:19 +00007310 }
7311}
Kevin Enderbyb76d3862014-08-22 20:35:18 +00007312
7313static void PrintMachHeader(uint32_t magic, uint32_t cputype,
7314 uint32_t cpusubtype, uint32_t filetype,
7315 uint32_t ncmds, uint32_t sizeofcmds, uint32_t flags,
7316 bool verbose) {
7317 outs() << "Mach header\n";
7318 outs() << " magic cputype cpusubtype caps filetype ncmds "
7319 "sizeofcmds flags\n";
7320 if (verbose) {
7321 if (magic == MachO::MH_MAGIC)
7322 outs() << " MH_MAGIC";
7323 else if (magic == MachO::MH_MAGIC_64)
7324 outs() << "MH_MAGIC_64";
7325 else
7326 outs() << format(" 0x%08" PRIx32, magic);
7327 switch (cputype) {
7328 case MachO::CPU_TYPE_I386:
7329 outs() << " I386";
7330 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
7331 case MachO::CPU_SUBTYPE_I386_ALL:
7332 outs() << " ALL";
7333 break;
7334 default:
7335 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
7336 break;
7337 }
7338 break;
7339 case MachO::CPU_TYPE_X86_64:
7340 outs() << " X86_64";
Kevin Enderby131d1772015-01-09 19:22:37 +00007341 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
7342 case MachO::CPU_SUBTYPE_X86_64_ALL:
7343 outs() << " ALL";
7344 break;
7345 case MachO::CPU_SUBTYPE_X86_64_H:
7346 outs() << " Haswell";
7347 break;
7348 default:
7349 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
7350 break;
7351 }
Kevin Enderbyb76d3862014-08-22 20:35:18 +00007352 break;
7353 case MachO::CPU_TYPE_ARM:
7354 outs() << " ARM";
7355 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
7356 case MachO::CPU_SUBTYPE_ARM_ALL:
7357 outs() << " ALL";
7358 break;
7359 case MachO::CPU_SUBTYPE_ARM_V4T:
7360 outs() << " V4T";
7361 break;
7362 case MachO::CPU_SUBTYPE_ARM_V5TEJ:
7363 outs() << " V5TEJ";
7364 break;
7365 case MachO::CPU_SUBTYPE_ARM_XSCALE:
7366 outs() << " XSCALE";
7367 break;
7368 case MachO::CPU_SUBTYPE_ARM_V6:
7369 outs() << " V6";
7370 break;
7371 case MachO::CPU_SUBTYPE_ARM_V6M:
7372 outs() << " V6M";
7373 break;
7374 case MachO::CPU_SUBTYPE_ARM_V7:
7375 outs() << " V7";
7376 break;
7377 case MachO::CPU_SUBTYPE_ARM_V7EM:
7378 outs() << " V7EM";
7379 break;
7380 case MachO::CPU_SUBTYPE_ARM_V7K:
7381 outs() << " V7K";
7382 break;
7383 case MachO::CPU_SUBTYPE_ARM_V7M:
7384 outs() << " V7M";
7385 break;
7386 case MachO::CPU_SUBTYPE_ARM_V7S:
7387 outs() << " V7S";
7388 break;
7389 default:
7390 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
7391 break;
7392 }
7393 break;
7394 case MachO::CPU_TYPE_ARM64:
7395 outs() << " ARM64";
7396 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
7397 case MachO::CPU_SUBTYPE_ARM64_ALL:
7398 outs() << " ALL";
7399 break;
7400 default:
7401 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
7402 break;
7403 }
7404 break;
7405 case MachO::CPU_TYPE_POWERPC:
7406 outs() << " PPC";
7407 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
7408 case MachO::CPU_SUBTYPE_POWERPC_ALL:
7409 outs() << " ALL";
7410 break;
7411 default:
7412 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
7413 break;
7414 }
7415 break;
7416 case MachO::CPU_TYPE_POWERPC64:
7417 outs() << " PPC64";
7418 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
7419 case MachO::CPU_SUBTYPE_POWERPC_ALL:
7420 outs() << " ALL";
7421 break;
7422 default:
7423 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
7424 break;
7425 }
7426 break;
Kevin Enderby40fdbf82016-01-26 18:20:49 +00007427 default:
7428 outs() << format(" %7d", cputype);
7429 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
7430 break;
Kevin Enderbyb76d3862014-08-22 20:35:18 +00007431 }
7432 if ((cpusubtype & MachO::CPU_SUBTYPE_MASK) == MachO::CPU_SUBTYPE_LIB64) {
Kevin Enderby8ae63c12014-09-04 16:54:47 +00007433 outs() << " LIB64";
Kevin Enderbyb76d3862014-08-22 20:35:18 +00007434 } else {
7435 outs() << format(" 0x%02" PRIx32,
7436 (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24);
7437 }
7438 switch (filetype) {
7439 case MachO::MH_OBJECT:
7440 outs() << " OBJECT";
7441 break;
7442 case MachO::MH_EXECUTE:
7443 outs() << " EXECUTE";
7444 break;
7445 case MachO::MH_FVMLIB:
7446 outs() << " FVMLIB";
7447 break;
7448 case MachO::MH_CORE:
7449 outs() << " CORE";
7450 break;
7451 case MachO::MH_PRELOAD:
7452 outs() << " PRELOAD";
7453 break;
7454 case MachO::MH_DYLIB:
7455 outs() << " DYLIB";
7456 break;
7457 case MachO::MH_DYLIB_STUB:
7458 outs() << " DYLIB_STUB";
7459 break;
7460 case MachO::MH_DYLINKER:
7461 outs() << " DYLINKER";
7462 break;
7463 case MachO::MH_BUNDLE:
7464 outs() << " BUNDLE";
7465 break;
7466 case MachO::MH_DSYM:
7467 outs() << " DSYM";
7468 break;
7469 case MachO::MH_KEXT_BUNDLE:
7470 outs() << " KEXTBUNDLE";
7471 break;
7472 default:
7473 outs() << format(" %10u", filetype);
7474 break;
7475 }
7476 outs() << format(" %5u", ncmds);
7477 outs() << format(" %10u", sizeofcmds);
7478 uint32_t f = flags;
7479 if (f & MachO::MH_NOUNDEFS) {
7480 outs() << " NOUNDEFS";
7481 f &= ~MachO::MH_NOUNDEFS;
7482 }
7483 if (f & MachO::MH_INCRLINK) {
7484 outs() << " INCRLINK";
7485 f &= ~MachO::MH_INCRLINK;
7486 }
7487 if (f & MachO::MH_DYLDLINK) {
7488 outs() << " DYLDLINK";
7489 f &= ~MachO::MH_DYLDLINK;
7490 }
7491 if (f & MachO::MH_BINDATLOAD) {
7492 outs() << " BINDATLOAD";
7493 f &= ~MachO::MH_BINDATLOAD;
7494 }
7495 if (f & MachO::MH_PREBOUND) {
7496 outs() << " PREBOUND";
7497 f &= ~MachO::MH_PREBOUND;
7498 }
7499 if (f & MachO::MH_SPLIT_SEGS) {
7500 outs() << " SPLIT_SEGS";
7501 f &= ~MachO::MH_SPLIT_SEGS;
7502 }
7503 if (f & MachO::MH_LAZY_INIT) {
7504 outs() << " LAZY_INIT";
7505 f &= ~MachO::MH_LAZY_INIT;
7506 }
7507 if (f & MachO::MH_TWOLEVEL) {
7508 outs() << " TWOLEVEL";
7509 f &= ~MachO::MH_TWOLEVEL;
7510 }
7511 if (f & MachO::MH_FORCE_FLAT) {
7512 outs() << " FORCE_FLAT";
7513 f &= ~MachO::MH_FORCE_FLAT;
7514 }
7515 if (f & MachO::MH_NOMULTIDEFS) {
7516 outs() << " NOMULTIDEFS";
7517 f &= ~MachO::MH_NOMULTIDEFS;
7518 }
7519 if (f & MachO::MH_NOFIXPREBINDING) {
7520 outs() << " NOFIXPREBINDING";
7521 f &= ~MachO::MH_NOFIXPREBINDING;
7522 }
7523 if (f & MachO::MH_PREBINDABLE) {
7524 outs() << " PREBINDABLE";
7525 f &= ~MachO::MH_PREBINDABLE;
7526 }
7527 if (f & MachO::MH_ALLMODSBOUND) {
7528 outs() << " ALLMODSBOUND";
7529 f &= ~MachO::MH_ALLMODSBOUND;
7530 }
7531 if (f & MachO::MH_SUBSECTIONS_VIA_SYMBOLS) {
7532 outs() << " SUBSECTIONS_VIA_SYMBOLS";
7533 f &= ~MachO::MH_SUBSECTIONS_VIA_SYMBOLS;
7534 }
7535 if (f & MachO::MH_CANONICAL) {
7536 outs() << " CANONICAL";
7537 f &= ~MachO::MH_CANONICAL;
7538 }
7539 if (f & MachO::MH_WEAK_DEFINES) {
7540 outs() << " WEAK_DEFINES";
7541 f &= ~MachO::MH_WEAK_DEFINES;
7542 }
7543 if (f & MachO::MH_BINDS_TO_WEAK) {
7544 outs() << " BINDS_TO_WEAK";
7545 f &= ~MachO::MH_BINDS_TO_WEAK;
7546 }
7547 if (f & MachO::MH_ALLOW_STACK_EXECUTION) {
7548 outs() << " ALLOW_STACK_EXECUTION";
7549 f &= ~MachO::MH_ALLOW_STACK_EXECUTION;
7550 }
7551 if (f & MachO::MH_DEAD_STRIPPABLE_DYLIB) {
7552 outs() << " DEAD_STRIPPABLE_DYLIB";
7553 f &= ~MachO::MH_DEAD_STRIPPABLE_DYLIB;
7554 }
7555 if (f & MachO::MH_PIE) {
7556 outs() << " PIE";
7557 f &= ~MachO::MH_PIE;
7558 }
7559 if (f & MachO::MH_NO_REEXPORTED_DYLIBS) {
7560 outs() << " NO_REEXPORTED_DYLIBS";
7561 f &= ~MachO::MH_NO_REEXPORTED_DYLIBS;
7562 }
7563 if (f & MachO::MH_HAS_TLV_DESCRIPTORS) {
7564 outs() << " MH_HAS_TLV_DESCRIPTORS";
7565 f &= ~MachO::MH_HAS_TLV_DESCRIPTORS;
7566 }
7567 if (f & MachO::MH_NO_HEAP_EXECUTION) {
7568 outs() << " MH_NO_HEAP_EXECUTION";
7569 f &= ~MachO::MH_NO_HEAP_EXECUTION;
7570 }
7571 if (f & MachO::MH_APP_EXTENSION_SAFE) {
7572 outs() << " APP_EXTENSION_SAFE";
7573 f &= ~MachO::MH_APP_EXTENSION_SAFE;
7574 }
7575 if (f != 0 || flags == 0)
7576 outs() << format(" 0x%08" PRIx32, f);
7577 } else {
7578 outs() << format(" 0x%08" PRIx32, magic);
7579 outs() << format(" %7d", cputype);
7580 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
7581 outs() << format(" 0x%02" PRIx32,
7582 (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24);
7583 outs() << format(" %10u", filetype);
7584 outs() << format(" %5u", ncmds);
7585 outs() << format(" %10u", sizeofcmds);
7586 outs() << format(" 0x%08" PRIx32, flags);
7587 }
7588 outs() << "\n";
7589}
7590
Kevin Enderby956366c2014-08-29 22:30:52 +00007591static void PrintSegmentCommand(uint32_t cmd, uint32_t cmdsize,
7592 StringRef SegName, uint64_t vmaddr,
7593 uint64_t vmsize, uint64_t fileoff,
7594 uint64_t filesize, uint32_t maxprot,
7595 uint32_t initprot, uint32_t nsects,
7596 uint32_t flags, uint32_t object_size,
7597 bool verbose) {
7598 uint64_t expected_cmdsize;
7599 if (cmd == MachO::LC_SEGMENT) {
7600 outs() << " cmd LC_SEGMENT\n";
7601 expected_cmdsize = nsects;
7602 expected_cmdsize *= sizeof(struct MachO::section);
7603 expected_cmdsize += sizeof(struct MachO::segment_command);
7604 } else {
7605 outs() << " cmd LC_SEGMENT_64\n";
7606 expected_cmdsize = nsects;
7607 expected_cmdsize *= sizeof(struct MachO::section_64);
7608 expected_cmdsize += sizeof(struct MachO::segment_command_64);
7609 }
7610 outs() << " cmdsize " << cmdsize;
7611 if (cmdsize != expected_cmdsize)
7612 outs() << " Inconsistent size\n";
7613 else
7614 outs() << "\n";
7615 outs() << " segname " << SegName << "\n";
7616 if (cmd == MachO::LC_SEGMENT_64) {
7617 outs() << " vmaddr " << format("0x%016" PRIx64, vmaddr) << "\n";
7618 outs() << " vmsize " << format("0x%016" PRIx64, vmsize) << "\n";
7619 } else {
Kevin Enderbyadb7c432014-12-16 18:58:11 +00007620 outs() << " vmaddr " << format("0x%08" PRIx64, vmaddr) << "\n";
7621 outs() << " vmsize " << format("0x%08" PRIx64, vmsize) << "\n";
Kevin Enderby956366c2014-08-29 22:30:52 +00007622 }
7623 outs() << " fileoff " << fileoff;
7624 if (fileoff > object_size)
7625 outs() << " (past end of file)\n";
7626 else
7627 outs() << "\n";
7628 outs() << " filesize " << filesize;
7629 if (fileoff + filesize > object_size)
7630 outs() << " (past end of file)\n";
7631 else
7632 outs() << "\n";
7633 if (verbose) {
7634 if ((maxprot &
7635 ~(MachO::VM_PROT_READ | MachO::VM_PROT_WRITE |
7636 MachO::VM_PROT_EXECUTE)) != 0)
7637 outs() << " maxprot ?" << format("0x%08" PRIx32, maxprot) << "\n";
7638 else {
Davide Italiano37ff06a2015-09-02 16:53:25 +00007639 outs() << " maxprot ";
7640 outs() << ((maxprot & MachO::VM_PROT_READ) ? "r" : "-");
7641 outs() << ((maxprot & MachO::VM_PROT_WRITE) ? "w" : "-");
7642 outs() << ((maxprot & MachO::VM_PROT_EXECUTE) ? "x\n" : "-\n");
Kevin Enderby956366c2014-08-29 22:30:52 +00007643 }
7644 if ((initprot &
7645 ~(MachO::VM_PROT_READ | MachO::VM_PROT_WRITE |
7646 MachO::VM_PROT_EXECUTE)) != 0)
Kevin Enderby41c9c002016-10-21 18:22:35 +00007647 outs() << " initprot ?" << format("0x%08" PRIx32, initprot) << "\n";
Kevin Enderby956366c2014-08-29 22:30:52 +00007648 else {
Kevin Enderby41c9c002016-10-21 18:22:35 +00007649 outs() << " initprot ";
Davide Italiano37ff06a2015-09-02 16:53:25 +00007650 outs() << ((initprot & MachO::VM_PROT_READ) ? "r" : "-");
7651 outs() << ((initprot & MachO::VM_PROT_WRITE) ? "w" : "-");
7652 outs() << ((initprot & MachO::VM_PROT_EXECUTE) ? "x\n" : "-\n");
Kevin Enderby956366c2014-08-29 22:30:52 +00007653 }
7654 } else {
7655 outs() << " maxprot " << format("0x%08" PRIx32, maxprot) << "\n";
7656 outs() << " initprot " << format("0x%08" PRIx32, initprot) << "\n";
7657 }
7658 outs() << " nsects " << nsects << "\n";
7659 if (verbose) {
7660 outs() << " flags";
7661 if (flags == 0)
7662 outs() << " (none)\n";
7663 else {
7664 if (flags & MachO::SG_HIGHVM) {
7665 outs() << " HIGHVM";
7666 flags &= ~MachO::SG_HIGHVM;
7667 }
7668 if (flags & MachO::SG_FVMLIB) {
7669 outs() << " FVMLIB";
7670 flags &= ~MachO::SG_FVMLIB;
7671 }
7672 if (flags & MachO::SG_NORELOC) {
7673 outs() << " NORELOC";
7674 flags &= ~MachO::SG_NORELOC;
7675 }
7676 if (flags & MachO::SG_PROTECTED_VERSION_1) {
7677 outs() << " PROTECTED_VERSION_1";
7678 flags &= ~MachO::SG_PROTECTED_VERSION_1;
7679 }
7680 if (flags)
7681 outs() << format(" 0x%08" PRIx32, flags) << " (unknown flags)\n";
7682 else
7683 outs() << "\n";
7684 }
7685 } else {
7686 outs() << " flags " << format("0x%" PRIx32, flags) << "\n";
7687 }
7688}
7689
7690static void PrintSection(const char *sectname, const char *segname,
7691 uint64_t addr, uint64_t size, uint32_t offset,
7692 uint32_t align, uint32_t reloff, uint32_t nreloc,
7693 uint32_t flags, uint32_t reserved1, uint32_t reserved2,
7694 uint32_t cmd, const char *sg_segname,
7695 uint32_t filetype, uint32_t object_size,
7696 bool verbose) {
7697 outs() << "Section\n";
7698 outs() << " sectname " << format("%.16s\n", sectname);
7699 outs() << " segname " << format("%.16s", segname);
7700 if (filetype != MachO::MH_OBJECT && strncmp(sg_segname, segname, 16) != 0)
7701 outs() << " (does not match segment)\n";
7702 else
7703 outs() << "\n";
7704 if (cmd == MachO::LC_SEGMENT_64) {
7705 outs() << " addr " << format("0x%016" PRIx64, addr) << "\n";
7706 outs() << " size " << format("0x%016" PRIx64, size);
7707 } else {
Kevin Enderby75594b62014-12-16 21:00:25 +00007708 outs() << " addr " << format("0x%08" PRIx64, addr) << "\n";
7709 outs() << " size " << format("0x%08" PRIx64, size);
Kevin Enderby956366c2014-08-29 22:30:52 +00007710 }
7711 if ((flags & MachO::S_ZEROFILL) != 0 && offset + size > object_size)
7712 outs() << " (past end of file)\n";
7713 else
7714 outs() << "\n";
7715 outs() << " offset " << offset;
7716 if (offset > object_size)
7717 outs() << " (past end of file)\n";
7718 else
7719 outs() << "\n";
7720 uint32_t align_shifted = 1 << align;
7721 outs() << " align 2^" << align << " (" << align_shifted << ")\n";
7722 outs() << " reloff " << reloff;
7723 if (reloff > object_size)
7724 outs() << " (past end of file)\n";
7725 else
7726 outs() << "\n";
7727 outs() << " nreloc " << nreloc;
7728 if (reloff + nreloc * sizeof(struct MachO::relocation_info) > object_size)
7729 outs() << " (past end of file)\n";
7730 else
7731 outs() << "\n";
7732 uint32_t section_type = flags & MachO::SECTION_TYPE;
7733 if (verbose) {
7734 outs() << " type";
7735 if (section_type == MachO::S_REGULAR)
7736 outs() << " S_REGULAR\n";
7737 else if (section_type == MachO::S_ZEROFILL)
7738 outs() << " S_ZEROFILL\n";
7739 else if (section_type == MachO::S_CSTRING_LITERALS)
7740 outs() << " S_CSTRING_LITERALS\n";
7741 else if (section_type == MachO::S_4BYTE_LITERALS)
7742 outs() << " S_4BYTE_LITERALS\n";
7743 else if (section_type == MachO::S_8BYTE_LITERALS)
7744 outs() << " S_8BYTE_LITERALS\n";
7745 else if (section_type == MachO::S_16BYTE_LITERALS)
7746 outs() << " S_16BYTE_LITERALS\n";
7747 else if (section_type == MachO::S_LITERAL_POINTERS)
7748 outs() << " S_LITERAL_POINTERS\n";
7749 else if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS)
7750 outs() << " S_NON_LAZY_SYMBOL_POINTERS\n";
7751 else if (section_type == MachO::S_LAZY_SYMBOL_POINTERS)
7752 outs() << " S_LAZY_SYMBOL_POINTERS\n";
7753 else if (section_type == MachO::S_SYMBOL_STUBS)
7754 outs() << " S_SYMBOL_STUBS\n";
7755 else if (section_type == MachO::S_MOD_INIT_FUNC_POINTERS)
7756 outs() << " S_MOD_INIT_FUNC_POINTERS\n";
7757 else if (section_type == MachO::S_MOD_TERM_FUNC_POINTERS)
7758 outs() << " S_MOD_TERM_FUNC_POINTERS\n";
7759 else if (section_type == MachO::S_COALESCED)
7760 outs() << " S_COALESCED\n";
7761 else if (section_type == MachO::S_INTERPOSING)
7762 outs() << " S_INTERPOSING\n";
7763 else if (section_type == MachO::S_DTRACE_DOF)
7764 outs() << " S_DTRACE_DOF\n";
7765 else if (section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS)
7766 outs() << " S_LAZY_DYLIB_SYMBOL_POINTERS\n";
7767 else if (section_type == MachO::S_THREAD_LOCAL_REGULAR)
7768 outs() << " S_THREAD_LOCAL_REGULAR\n";
7769 else if (section_type == MachO::S_THREAD_LOCAL_ZEROFILL)
7770 outs() << " S_THREAD_LOCAL_ZEROFILL\n";
7771 else if (section_type == MachO::S_THREAD_LOCAL_VARIABLES)
7772 outs() << " S_THREAD_LOCAL_VARIABLES\n";
7773 else if (section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS)
7774 outs() << " S_THREAD_LOCAL_VARIABLE_POINTERS\n";
7775 else if (section_type == MachO::S_THREAD_LOCAL_INIT_FUNCTION_POINTERS)
7776 outs() << " S_THREAD_LOCAL_INIT_FUNCTION_POINTERS\n";
7777 else
7778 outs() << format("0x%08" PRIx32, section_type) << "\n";
7779 outs() << "attributes";
7780 uint32_t section_attributes = flags & MachO::SECTION_ATTRIBUTES;
7781 if (section_attributes & MachO::S_ATTR_PURE_INSTRUCTIONS)
7782 outs() << " PURE_INSTRUCTIONS";
7783 if (section_attributes & MachO::S_ATTR_NO_TOC)
7784 outs() << " NO_TOC";
7785 if (section_attributes & MachO::S_ATTR_STRIP_STATIC_SYMS)
7786 outs() << " STRIP_STATIC_SYMS";
7787 if (section_attributes & MachO::S_ATTR_NO_DEAD_STRIP)
7788 outs() << " NO_DEAD_STRIP";
7789 if (section_attributes & MachO::S_ATTR_LIVE_SUPPORT)
7790 outs() << " LIVE_SUPPORT";
7791 if (section_attributes & MachO::S_ATTR_SELF_MODIFYING_CODE)
7792 outs() << " SELF_MODIFYING_CODE";
7793 if (section_attributes & MachO::S_ATTR_DEBUG)
7794 outs() << " DEBUG";
7795 if (section_attributes & MachO::S_ATTR_SOME_INSTRUCTIONS)
7796 outs() << " SOME_INSTRUCTIONS";
7797 if (section_attributes & MachO::S_ATTR_EXT_RELOC)
7798 outs() << " EXT_RELOC";
7799 if (section_attributes & MachO::S_ATTR_LOC_RELOC)
7800 outs() << " LOC_RELOC";
7801 if (section_attributes == 0)
7802 outs() << " (none)";
7803 outs() << "\n";
7804 } else
7805 outs() << " flags " << format("0x%08" PRIx32, flags) << "\n";
7806 outs() << " reserved1 " << reserved1;
7807 if (section_type == MachO::S_SYMBOL_STUBS ||
7808 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
7809 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
7810 section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
7811 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS)
7812 outs() << " (index into indirect symbol table)\n";
7813 else
7814 outs() << "\n";
7815 outs() << " reserved2 " << reserved2;
7816 if (section_type == MachO::S_SYMBOL_STUBS)
7817 outs() << " (size of stubs)\n";
7818 else
7819 outs() << "\n";
7820}
7821
David Majnemer73cc6ff2014-11-13 19:48:56 +00007822static void PrintSymtabLoadCommand(MachO::symtab_command st, bool Is64Bit,
Kevin Enderby956366c2014-08-29 22:30:52 +00007823 uint32_t object_size) {
7824 outs() << " cmd LC_SYMTAB\n";
7825 outs() << " cmdsize " << st.cmdsize;
7826 if (st.cmdsize != sizeof(struct MachO::symtab_command))
7827 outs() << " Incorrect size\n";
7828 else
7829 outs() << "\n";
7830 outs() << " symoff " << st.symoff;
7831 if (st.symoff > object_size)
7832 outs() << " (past end of file)\n";
7833 else
7834 outs() << "\n";
7835 outs() << " nsyms " << st.nsyms;
7836 uint64_t big_size;
David Majnemer73cc6ff2014-11-13 19:48:56 +00007837 if (Is64Bit) {
Kevin Enderby956366c2014-08-29 22:30:52 +00007838 big_size = st.nsyms;
7839 big_size *= sizeof(struct MachO::nlist_64);
7840 big_size += st.symoff;
7841 if (big_size > object_size)
7842 outs() << " (past end of file)\n";
7843 else
7844 outs() << "\n";
7845 } else {
7846 big_size = st.nsyms;
7847 big_size *= sizeof(struct MachO::nlist);
7848 big_size += st.symoff;
7849 if (big_size > object_size)
7850 outs() << " (past end of file)\n";
7851 else
7852 outs() << "\n";
7853 }
7854 outs() << " stroff " << st.stroff;
7855 if (st.stroff > object_size)
7856 outs() << " (past end of file)\n";
7857 else
7858 outs() << "\n";
7859 outs() << " strsize " << st.strsize;
7860 big_size = st.stroff;
7861 big_size += st.strsize;
7862 if (big_size > object_size)
7863 outs() << " (past end of file)\n";
7864 else
7865 outs() << "\n";
7866}
7867
7868static void PrintDysymtabLoadCommand(MachO::dysymtab_command dyst,
7869 uint32_t nsyms, uint32_t object_size,
David Majnemer73cc6ff2014-11-13 19:48:56 +00007870 bool Is64Bit) {
Kevin Enderby956366c2014-08-29 22:30:52 +00007871 outs() << " cmd LC_DYSYMTAB\n";
7872 outs() << " cmdsize " << dyst.cmdsize;
7873 if (dyst.cmdsize != sizeof(struct MachO::dysymtab_command))
7874 outs() << " Incorrect size\n";
7875 else
7876 outs() << "\n";
7877 outs() << " ilocalsym " << dyst.ilocalsym;
7878 if (dyst.ilocalsym > nsyms)
7879 outs() << " (greater than the number of symbols)\n";
7880 else
7881 outs() << "\n";
7882 outs() << " nlocalsym " << dyst.nlocalsym;
7883 uint64_t big_size;
7884 big_size = dyst.ilocalsym;
7885 big_size += dyst.nlocalsym;
7886 if (big_size > nsyms)
7887 outs() << " (past the end of the symbol table)\n";
7888 else
7889 outs() << "\n";
7890 outs() << " iextdefsym " << dyst.iextdefsym;
7891 if (dyst.iextdefsym > nsyms)
7892 outs() << " (greater than the number of symbols)\n";
7893 else
7894 outs() << "\n";
7895 outs() << " nextdefsym " << dyst.nextdefsym;
7896 big_size = dyst.iextdefsym;
7897 big_size += dyst.nextdefsym;
7898 if (big_size > nsyms)
7899 outs() << " (past the end of the symbol table)\n";
7900 else
7901 outs() << "\n";
7902 outs() << " iundefsym " << dyst.iundefsym;
7903 if (dyst.iundefsym > nsyms)
7904 outs() << " (greater than the number of symbols)\n";
7905 else
7906 outs() << "\n";
7907 outs() << " nundefsym " << dyst.nundefsym;
7908 big_size = dyst.iundefsym;
7909 big_size += dyst.nundefsym;
7910 if (big_size > nsyms)
7911 outs() << " (past the end of the symbol table)\n";
7912 else
7913 outs() << "\n";
7914 outs() << " tocoff " << dyst.tocoff;
7915 if (dyst.tocoff > object_size)
7916 outs() << " (past end of file)\n";
7917 else
7918 outs() << "\n";
7919 outs() << " ntoc " << dyst.ntoc;
7920 big_size = dyst.ntoc;
7921 big_size *= sizeof(struct MachO::dylib_table_of_contents);
7922 big_size += dyst.tocoff;
7923 if (big_size > object_size)
7924 outs() << " (past end of file)\n";
7925 else
7926 outs() << "\n";
7927 outs() << " modtaboff " << dyst.modtaboff;
7928 if (dyst.modtaboff > object_size)
7929 outs() << " (past end of file)\n";
7930 else
7931 outs() << "\n";
7932 outs() << " nmodtab " << dyst.nmodtab;
7933 uint64_t modtabend;
David Majnemer73cc6ff2014-11-13 19:48:56 +00007934 if (Is64Bit) {
Kevin Enderby956366c2014-08-29 22:30:52 +00007935 modtabend = dyst.nmodtab;
7936 modtabend *= sizeof(struct MachO::dylib_module_64);
7937 modtabend += dyst.modtaboff;
7938 } else {
7939 modtabend = dyst.nmodtab;
7940 modtabend *= sizeof(struct MachO::dylib_module);
7941 modtabend += dyst.modtaboff;
7942 }
7943 if (modtabend > object_size)
7944 outs() << " (past end of file)\n";
7945 else
7946 outs() << "\n";
7947 outs() << " extrefsymoff " << dyst.extrefsymoff;
7948 if (dyst.extrefsymoff > object_size)
7949 outs() << " (past end of file)\n";
7950 else
7951 outs() << "\n";
7952 outs() << " nextrefsyms " << dyst.nextrefsyms;
7953 big_size = dyst.nextrefsyms;
7954 big_size *= sizeof(struct MachO::dylib_reference);
7955 big_size += dyst.extrefsymoff;
7956 if (big_size > object_size)
7957 outs() << " (past end of file)\n";
7958 else
7959 outs() << "\n";
7960 outs() << " indirectsymoff " << dyst.indirectsymoff;
7961 if (dyst.indirectsymoff > object_size)
7962 outs() << " (past end of file)\n";
7963 else
7964 outs() << "\n";
7965 outs() << " nindirectsyms " << dyst.nindirectsyms;
7966 big_size = dyst.nindirectsyms;
7967 big_size *= sizeof(uint32_t);
7968 big_size += dyst.indirectsymoff;
7969 if (big_size > object_size)
7970 outs() << " (past end of file)\n";
7971 else
7972 outs() << "\n";
7973 outs() << " extreloff " << dyst.extreloff;
7974 if (dyst.extreloff > object_size)
7975 outs() << " (past end of file)\n";
7976 else
7977 outs() << "\n";
7978 outs() << " nextrel " << dyst.nextrel;
7979 big_size = dyst.nextrel;
7980 big_size *= sizeof(struct MachO::relocation_info);
7981 big_size += dyst.extreloff;
7982 if (big_size > object_size)
7983 outs() << " (past end of file)\n";
7984 else
7985 outs() << "\n";
7986 outs() << " locreloff " << dyst.locreloff;
7987 if (dyst.locreloff > object_size)
7988 outs() << " (past end of file)\n";
7989 else
7990 outs() << "\n";
7991 outs() << " nlocrel " << dyst.nlocrel;
7992 big_size = dyst.nlocrel;
7993 big_size *= sizeof(struct MachO::relocation_info);
7994 big_size += dyst.locreloff;
7995 if (big_size > object_size)
7996 outs() << " (past end of file)\n";
7997 else
7998 outs() << "\n";
7999}
8000
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008001static void PrintDyldInfoLoadCommand(MachO::dyld_info_command dc,
8002 uint32_t object_size) {
8003 if (dc.cmd == MachO::LC_DYLD_INFO)
8004 outs() << " cmd LC_DYLD_INFO\n";
8005 else
8006 outs() << " cmd LC_DYLD_INFO_ONLY\n";
8007 outs() << " cmdsize " << dc.cmdsize;
8008 if (dc.cmdsize != sizeof(struct MachO::dyld_info_command))
8009 outs() << " Incorrect size\n";
8010 else
8011 outs() << "\n";
8012 outs() << " rebase_off " << dc.rebase_off;
8013 if (dc.rebase_off > object_size)
8014 outs() << " (past end of file)\n";
8015 else
8016 outs() << "\n";
8017 outs() << " rebase_size " << dc.rebase_size;
8018 uint64_t big_size;
8019 big_size = dc.rebase_off;
8020 big_size += dc.rebase_size;
8021 if (big_size > object_size)
8022 outs() << " (past end of file)\n";
8023 else
8024 outs() << "\n";
8025 outs() << " bind_off " << dc.bind_off;
8026 if (dc.bind_off > object_size)
8027 outs() << " (past end of file)\n";
8028 else
8029 outs() << "\n";
8030 outs() << " bind_size " << dc.bind_size;
8031 big_size = dc.bind_off;
8032 big_size += dc.bind_size;
8033 if (big_size > object_size)
8034 outs() << " (past end of file)\n";
8035 else
8036 outs() << "\n";
8037 outs() << " weak_bind_off " << dc.weak_bind_off;
8038 if (dc.weak_bind_off > object_size)
8039 outs() << " (past end of file)\n";
8040 else
8041 outs() << "\n";
8042 outs() << " weak_bind_size " << dc.weak_bind_size;
8043 big_size = dc.weak_bind_off;
8044 big_size += dc.weak_bind_size;
8045 if (big_size > object_size)
8046 outs() << " (past end of file)\n";
8047 else
8048 outs() << "\n";
8049 outs() << " lazy_bind_off " << dc.lazy_bind_off;
8050 if (dc.lazy_bind_off > object_size)
8051 outs() << " (past end of file)\n";
8052 else
8053 outs() << "\n";
8054 outs() << " lazy_bind_size " << dc.lazy_bind_size;
8055 big_size = dc.lazy_bind_off;
8056 big_size += dc.lazy_bind_size;
8057 if (big_size > object_size)
8058 outs() << " (past end of file)\n";
8059 else
8060 outs() << "\n";
8061 outs() << " export_off " << dc.export_off;
8062 if (dc.export_off > object_size)
8063 outs() << " (past end of file)\n";
8064 else
8065 outs() << "\n";
8066 outs() << " export_size " << dc.export_size;
8067 big_size = dc.export_off;
8068 big_size += dc.export_size;
8069 if (big_size > object_size)
8070 outs() << " (past end of file)\n";
8071 else
8072 outs() << "\n";
8073}
8074
8075static void PrintDyldLoadCommand(MachO::dylinker_command dyld,
8076 const char *Ptr) {
8077 if (dyld.cmd == MachO::LC_ID_DYLINKER)
8078 outs() << " cmd LC_ID_DYLINKER\n";
8079 else if (dyld.cmd == MachO::LC_LOAD_DYLINKER)
8080 outs() << " cmd LC_LOAD_DYLINKER\n";
8081 else if (dyld.cmd == MachO::LC_DYLD_ENVIRONMENT)
8082 outs() << " cmd LC_DYLD_ENVIRONMENT\n";
8083 else
8084 outs() << " cmd ?(" << dyld.cmd << ")\n";
8085 outs() << " cmdsize " << dyld.cmdsize;
8086 if (dyld.cmdsize < sizeof(struct MachO::dylinker_command))
8087 outs() << " Incorrect size\n";
8088 else
8089 outs() << "\n";
8090 if (dyld.name >= dyld.cmdsize)
8091 outs() << " name ?(bad offset " << dyld.name << ")\n";
8092 else {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00008093 const char *P = (const char *)(Ptr) + dyld.name;
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008094 outs() << " name " << P << " (offset " << dyld.name << ")\n";
8095 }
8096}
8097
8098static void PrintUuidLoadCommand(MachO::uuid_command uuid) {
8099 outs() << " cmd LC_UUID\n";
8100 outs() << " cmdsize " << uuid.cmdsize;
8101 if (uuid.cmdsize != sizeof(struct MachO::uuid_command))
8102 outs() << " Incorrect size\n";
8103 else
8104 outs() << "\n";
8105 outs() << " uuid ";
Davide Italianoc74277a2015-12-07 00:03:28 +00008106 for (int i = 0; i < 16; ++i) {
8107 outs() << format("%02" PRIX32, uuid.uuid[i]);
8108 if (i == 3 || i == 5 || i == 7 || i == 9)
8109 outs() << "-";
8110 }
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008111 outs() << "\n";
8112}
8113
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008114static void PrintRpathLoadCommand(MachO::rpath_command rpath, const char *Ptr) {
Jean-Daniel Dupas00cc1f52014-12-04 07:37:02 +00008115 outs() << " cmd LC_RPATH\n";
8116 outs() << " cmdsize " << rpath.cmdsize;
8117 if (rpath.cmdsize < sizeof(struct MachO::rpath_command))
8118 outs() << " Incorrect size\n";
8119 else
8120 outs() << "\n";
8121 if (rpath.path >= rpath.cmdsize)
8122 outs() << " path ?(bad offset " << rpath.path << ")\n";
8123 else {
8124 const char *P = (const char *)(Ptr) + rpath.path;
8125 outs() << " path " << P << " (offset " << rpath.path << ")\n";
8126 }
8127}
8128
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008129static void PrintVersionMinLoadCommand(MachO::version_min_command vd) {
Tim Northoverbfbfb122015-11-02 21:26:58 +00008130 StringRef LoadCmdName;
8131 switch (vd.cmd) {
8132 case MachO::LC_VERSION_MIN_MACOSX:
8133 LoadCmdName = "LC_VERSION_MIN_MACOSX";
8134 break;
8135 case MachO::LC_VERSION_MIN_IPHONEOS:
8136 LoadCmdName = "LC_VERSION_MIN_IPHONEOS";
8137 break;
8138 case MachO::LC_VERSION_MIN_TVOS:
8139 LoadCmdName = "LC_VERSION_MIN_TVOS";
8140 break;
8141 case MachO::LC_VERSION_MIN_WATCHOS:
8142 LoadCmdName = "LC_VERSION_MIN_WATCHOS";
8143 break;
8144 default:
8145 llvm_unreachable("Unknown version min load command");
8146 }
8147
8148 outs() << " cmd " << LoadCmdName << '\n';
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008149 outs() << " cmdsize " << vd.cmdsize;
8150 if (vd.cmdsize != sizeof(struct MachO::version_min_command))
8151 outs() << " Incorrect size\n";
8152 else
8153 outs() << "\n";
Davide Italiano56baef32015-08-26 12:26:11 +00008154 outs() << " version "
8155 << MachOObjectFile::getVersionMinMajor(vd, false) << "."
8156 << MachOObjectFile::getVersionMinMinor(vd, false);
8157 uint32_t Update = MachOObjectFile::getVersionMinUpdate(vd, false);
8158 if (Update != 0)
8159 outs() << "." << Update;
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008160 outs() << "\n";
8161 if (vd.sdk == 0)
Kevin Enderby57538292014-12-17 01:01:30 +00008162 outs() << " sdk n/a";
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008163 else {
Davide Italiano56baef32015-08-26 12:26:11 +00008164 outs() << " sdk "
8165 << MachOObjectFile::getVersionMinMajor(vd, true) << "."
8166 << MachOObjectFile::getVersionMinMinor(vd, true);
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008167 }
Davide Italiano56baef32015-08-26 12:26:11 +00008168 Update = MachOObjectFile::getVersionMinUpdate(vd, true);
8169 if (Update != 0)
8170 outs() << "." << Update;
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008171 outs() << "\n";
8172}
8173
8174static void PrintSourceVersionCommand(MachO::source_version_command sd) {
8175 outs() << " cmd LC_SOURCE_VERSION\n";
8176 outs() << " cmdsize " << sd.cmdsize;
8177 if (sd.cmdsize != sizeof(struct MachO::source_version_command))
8178 outs() << " Incorrect size\n";
8179 else
8180 outs() << "\n";
8181 uint64_t a = (sd.version >> 40) & 0xffffff;
8182 uint64_t b = (sd.version >> 30) & 0x3ff;
8183 uint64_t c = (sd.version >> 20) & 0x3ff;
8184 uint64_t d = (sd.version >> 10) & 0x3ff;
8185 uint64_t e = sd.version & 0x3ff;
8186 outs() << " version " << a << "." << b;
8187 if (e != 0)
8188 outs() << "." << c << "." << d << "." << e;
8189 else if (d != 0)
8190 outs() << "." << c << "." << d;
8191 else if (c != 0)
8192 outs() << "." << c;
8193 outs() << "\n";
8194}
8195
8196static void PrintEntryPointCommand(MachO::entry_point_command ep) {
8197 outs() << " cmd LC_MAIN\n";
8198 outs() << " cmdsize " << ep.cmdsize;
8199 if (ep.cmdsize != sizeof(struct MachO::entry_point_command))
8200 outs() << " Incorrect size\n";
8201 else
8202 outs() << "\n";
8203 outs() << " entryoff " << ep.entryoff << "\n";
8204 outs() << " stacksize " << ep.stacksize << "\n";
8205}
8206
Kevin Enderby0804f4672014-12-16 23:25:52 +00008207static void PrintEncryptionInfoCommand(MachO::encryption_info_command ec,
8208 uint32_t object_size) {
8209 outs() << " cmd LC_ENCRYPTION_INFO\n";
8210 outs() << " cmdsize " << ec.cmdsize;
8211 if (ec.cmdsize != sizeof(struct MachO::encryption_info_command))
8212 outs() << " Incorrect size\n";
8213 else
8214 outs() << "\n";
8215 outs() << " cryptoff " << ec.cryptoff;
8216 if (ec.cryptoff > object_size)
8217 outs() << " (past end of file)\n";
8218 else
8219 outs() << "\n";
8220 outs() << " cryptsize " << ec.cryptsize;
8221 if (ec.cryptsize > object_size)
8222 outs() << " (past end of file)\n";
8223 else
8224 outs() << "\n";
8225 outs() << " cryptid " << ec.cryptid << "\n";
8226}
8227
Kevin Enderby57538292014-12-17 01:01:30 +00008228static void PrintEncryptionInfoCommand64(MachO::encryption_info_command_64 ec,
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008229 uint32_t object_size) {
Kevin Enderby57538292014-12-17 01:01:30 +00008230 outs() << " cmd LC_ENCRYPTION_INFO_64\n";
8231 outs() << " cmdsize " << ec.cmdsize;
8232 if (ec.cmdsize != sizeof(struct MachO::encryption_info_command_64))
8233 outs() << " Incorrect size\n";
8234 else
8235 outs() << "\n";
8236 outs() << " cryptoff " << ec.cryptoff;
8237 if (ec.cryptoff > object_size)
8238 outs() << " (past end of file)\n";
8239 else
8240 outs() << "\n";
8241 outs() << " cryptsize " << ec.cryptsize;
8242 if (ec.cryptsize > object_size)
8243 outs() << " (past end of file)\n";
8244 else
8245 outs() << "\n";
8246 outs() << " cryptid " << ec.cryptid << "\n";
8247 outs() << " pad " << ec.pad << "\n";
8248}
8249
Kevin Enderbyd0b6b7f2014-12-18 00:53:40 +00008250static void PrintLinkerOptionCommand(MachO::linker_option_command lo,
8251 const char *Ptr) {
8252 outs() << " cmd LC_LINKER_OPTION\n";
8253 outs() << " cmdsize " << lo.cmdsize;
8254 if (lo.cmdsize < sizeof(struct MachO::linker_option_command))
8255 outs() << " Incorrect size\n";
8256 else
8257 outs() << "\n";
8258 outs() << " count " << lo.count << "\n";
8259 const char *string = Ptr + sizeof(struct MachO::linker_option_command);
8260 uint32_t left = lo.cmdsize - sizeof(struct MachO::linker_option_command);
8261 uint32_t i = 0;
8262 while (left > 0) {
8263 while (*string == '\0' && left > 0) {
8264 string++;
8265 left--;
8266 }
8267 if (left > 0) {
8268 i++;
8269 outs() << " string #" << i << " " << format("%.*s\n", left, string);
David Majnemerd4449ed2014-12-20 08:24:43 +00008270 uint32_t NullPos = StringRef(string, left).find('\0');
8271 uint32_t len = std::min(NullPos, left) + 1;
Kevin Enderbyd0b6b7f2014-12-18 00:53:40 +00008272 string += len;
8273 left -= len;
8274 }
8275 }
8276 if (lo.count != i)
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008277 outs() << " count " << lo.count << " does not match number of strings "
8278 << i << "\n";
Kevin Enderbyd0b6b7f2014-12-18 00:53:40 +00008279}
8280
Kevin Enderbyb4b79312014-12-18 19:24:35 +00008281static void PrintSubFrameworkCommand(MachO::sub_framework_command sub,
8282 const char *Ptr) {
8283 outs() << " cmd LC_SUB_FRAMEWORK\n";
8284 outs() << " cmdsize " << sub.cmdsize;
8285 if (sub.cmdsize < sizeof(struct MachO::sub_framework_command))
8286 outs() << " Incorrect size\n";
8287 else
8288 outs() << "\n";
8289 if (sub.umbrella < sub.cmdsize) {
8290 const char *P = Ptr + sub.umbrella;
8291 outs() << " umbrella " << P << " (offset " << sub.umbrella << ")\n";
8292 } else {
8293 outs() << " umbrella ?(bad offset " << sub.umbrella << ")\n";
8294 }
8295}
8296
Kevin Enderbya2bd8d92014-12-18 23:13:26 +00008297static void PrintSubUmbrellaCommand(MachO::sub_umbrella_command sub,
8298 const char *Ptr) {
8299 outs() << " cmd LC_SUB_UMBRELLA\n";
8300 outs() << " cmdsize " << sub.cmdsize;
8301 if (sub.cmdsize < sizeof(struct MachO::sub_umbrella_command))
8302 outs() << " Incorrect size\n";
8303 else
8304 outs() << "\n";
8305 if (sub.sub_umbrella < sub.cmdsize) {
8306 const char *P = Ptr + sub.sub_umbrella;
8307 outs() << " sub_umbrella " << P << " (offset " << sub.sub_umbrella << ")\n";
8308 } else {
8309 outs() << " sub_umbrella ?(bad offset " << sub.sub_umbrella << ")\n";
8310 }
8311}
8312
Kevin Enderby36c8d3a2014-12-19 19:48:16 +00008313static void PrintSubLibraryCommand(MachO::sub_library_command sub,
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008314 const char *Ptr) {
Kevin Enderby36c8d3a2014-12-19 19:48:16 +00008315 outs() << " cmd LC_SUB_LIBRARY\n";
8316 outs() << " cmdsize " << sub.cmdsize;
8317 if (sub.cmdsize < sizeof(struct MachO::sub_library_command))
8318 outs() << " Incorrect size\n";
8319 else
8320 outs() << "\n";
8321 if (sub.sub_library < sub.cmdsize) {
8322 const char *P = Ptr + sub.sub_library;
8323 outs() << " sub_library " << P << " (offset " << sub.sub_library << ")\n";
8324 } else {
8325 outs() << " sub_library ?(bad offset " << sub.sub_library << ")\n";
8326 }
8327}
8328
Kevin Enderby186eac32014-12-19 21:06:24 +00008329static void PrintSubClientCommand(MachO::sub_client_command sub,
8330 const char *Ptr) {
8331 outs() << " cmd LC_SUB_CLIENT\n";
8332 outs() << " cmdsize " << sub.cmdsize;
8333 if (sub.cmdsize < sizeof(struct MachO::sub_client_command))
8334 outs() << " Incorrect size\n";
8335 else
8336 outs() << "\n";
8337 if (sub.client < sub.cmdsize) {
8338 const char *P = Ptr + sub.client;
8339 outs() << " client " << P << " (offset " << sub.client << ")\n";
8340 } else {
8341 outs() << " client ?(bad offset " << sub.client << ")\n";
8342 }
8343}
Kevin Enderby36c8d3a2014-12-19 19:48:16 +00008344
Kevin Enderby52e4ce42014-12-19 22:25:22 +00008345static void PrintRoutinesCommand(MachO::routines_command r) {
8346 outs() << " cmd LC_ROUTINES\n";
8347 outs() << " cmdsize " << r.cmdsize;
8348 if (r.cmdsize != sizeof(struct MachO::routines_command))
8349 outs() << " Incorrect size\n";
8350 else
8351 outs() << "\n";
8352 outs() << " init_address " << format("0x%08" PRIx32, r.init_address) << "\n";
8353 outs() << " init_module " << r.init_module << "\n";
8354 outs() << " reserved1 " << r.reserved1 << "\n";
8355 outs() << " reserved2 " << r.reserved2 << "\n";
8356 outs() << " reserved3 " << r.reserved3 << "\n";
8357 outs() << " reserved4 " << r.reserved4 << "\n";
8358 outs() << " reserved5 " << r.reserved5 << "\n";
8359 outs() << " reserved6 " << r.reserved6 << "\n";
8360}
8361
8362static void PrintRoutinesCommand64(MachO::routines_command_64 r) {
8363 outs() << " cmd LC_ROUTINES_64\n";
8364 outs() << " cmdsize " << r.cmdsize;
8365 if (r.cmdsize != sizeof(struct MachO::routines_command_64))
8366 outs() << " Incorrect size\n";
8367 else
8368 outs() << "\n";
8369 outs() << " init_address " << format("0x%016" PRIx64, r.init_address) << "\n";
8370 outs() << " init_module " << r.init_module << "\n";
8371 outs() << " reserved1 " << r.reserved1 << "\n";
8372 outs() << " reserved2 " << r.reserved2 << "\n";
8373 outs() << " reserved3 " << r.reserved3 << "\n";
8374 outs() << " reserved4 " << r.reserved4 << "\n";
8375 outs() << " reserved5 " << r.reserved5 << "\n";
8376 outs() << " reserved6 " << r.reserved6 << "\n";
8377}
8378
Kevin Enderby48ef5342014-12-23 22:56:39 +00008379static void Print_x86_thread_state64_t(MachO::x86_thread_state64_t &cpu64) {
8380 outs() << " rax " << format("0x%016" PRIx64, cpu64.rax);
8381 outs() << " rbx " << format("0x%016" PRIx64, cpu64.rbx);
8382 outs() << " rcx " << format("0x%016" PRIx64, cpu64.rcx) << "\n";
8383 outs() << " rdx " << format("0x%016" PRIx64, cpu64.rdx);
8384 outs() << " rdi " << format("0x%016" PRIx64, cpu64.rdi);
8385 outs() << " rsi " << format("0x%016" PRIx64, cpu64.rsi) << "\n";
8386 outs() << " rbp " << format("0x%016" PRIx64, cpu64.rbp);
8387 outs() << " rsp " << format("0x%016" PRIx64, cpu64.rsp);
8388 outs() << " r8 " << format("0x%016" PRIx64, cpu64.r8) << "\n";
8389 outs() << " r9 " << format("0x%016" PRIx64, cpu64.r9);
8390 outs() << " r10 " << format("0x%016" PRIx64, cpu64.r10);
8391 outs() << " r11 " << format("0x%016" PRIx64, cpu64.r11) << "\n";
8392 outs() << " r12 " << format("0x%016" PRIx64, cpu64.r12);
8393 outs() << " r13 " << format("0x%016" PRIx64, cpu64.r13);
8394 outs() << " r14 " << format("0x%016" PRIx64, cpu64.r14) << "\n";
8395 outs() << " r15 " << format("0x%016" PRIx64, cpu64.r15);
8396 outs() << " rip " << format("0x%016" PRIx64, cpu64.rip) << "\n";
8397 outs() << "rflags " << format("0x%016" PRIx64, cpu64.rflags);
8398 outs() << " cs " << format("0x%016" PRIx64, cpu64.cs);
8399 outs() << " fs " << format("0x%016" PRIx64, cpu64.fs) << "\n";
8400 outs() << " gs " << format("0x%016" PRIx64, cpu64.gs) << "\n";
8401}
8402
Kevin Enderby227df342014-12-23 23:43:59 +00008403static void Print_mmst_reg(MachO::mmst_reg_t &r) {
Kevin Enderby48ef5342014-12-23 22:56:39 +00008404 uint32_t f;
8405 outs() << "\t mmst_reg ";
8406 for (f = 0; f < 10; f++)
8407 outs() << format("%02" PRIx32, (r.mmst_reg[f] & 0xff)) << " ";
8408 outs() << "\n";
8409 outs() << "\t mmst_rsrv ";
8410 for (f = 0; f < 6; f++)
8411 outs() << format("%02" PRIx32, (r.mmst_rsrv[f] & 0xff)) << " ";
8412 outs() << "\n";
8413}
8414
Kevin Enderbyaefb0032014-12-24 00:16:51 +00008415static void Print_xmm_reg(MachO::xmm_reg_t &r) {
Kevin Enderby48ef5342014-12-23 22:56:39 +00008416 uint32_t f;
8417 outs() << "\t xmm_reg ";
8418 for (f = 0; f < 16; f++)
8419 outs() << format("%02" PRIx32, (r.xmm_reg[f] & 0xff)) << " ";
8420 outs() << "\n";
8421}
8422
8423static void Print_x86_float_state_t(MachO::x86_float_state64_t &fpu) {
8424 outs() << "\t fpu_reserved[0] " << fpu.fpu_reserved[0];
8425 outs() << " fpu_reserved[1] " << fpu.fpu_reserved[1] << "\n";
8426 outs() << "\t control: invalid " << fpu.fpu_fcw.invalid;
8427 outs() << " denorm " << fpu.fpu_fcw.denorm;
8428 outs() << " zdiv " << fpu.fpu_fcw.zdiv;
8429 outs() << " ovrfl " << fpu.fpu_fcw.ovrfl;
8430 outs() << " undfl " << fpu.fpu_fcw.undfl;
8431 outs() << " precis " << fpu.fpu_fcw.precis << "\n";
8432 outs() << "\t\t pc ";
8433 if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_24B)
8434 outs() << "FP_PREC_24B ";
8435 else if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_53B)
8436 outs() << "FP_PREC_53B ";
8437 else if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_64B)
8438 outs() << "FP_PREC_64B ";
8439 else
8440 outs() << fpu.fpu_fcw.pc << " ";
8441 outs() << "rc ";
8442 if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_NEAR)
8443 outs() << "FP_RND_NEAR ";
8444 else if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_DOWN)
8445 outs() << "FP_RND_DOWN ";
8446 else if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_UP)
8447 outs() << "FP_RND_UP ";
8448 else if (fpu.fpu_fcw.rc == MachO::x86_FP_CHOP)
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008449 outs() << "FP_CHOP ";
Kevin Enderby48ef5342014-12-23 22:56:39 +00008450 outs() << "\n";
8451 outs() << "\t status: invalid " << fpu.fpu_fsw.invalid;
8452 outs() << " denorm " << fpu.fpu_fsw.denorm;
8453 outs() << " zdiv " << fpu.fpu_fsw.zdiv;
8454 outs() << " ovrfl " << fpu.fpu_fsw.ovrfl;
8455 outs() << " undfl " << fpu.fpu_fsw.undfl;
8456 outs() << " precis " << fpu.fpu_fsw.precis;
8457 outs() << " stkflt " << fpu.fpu_fsw.stkflt << "\n";
8458 outs() << "\t errsumm " << fpu.fpu_fsw.errsumm;
8459 outs() << " c0 " << fpu.fpu_fsw.c0;
8460 outs() << " c1 " << fpu.fpu_fsw.c1;
8461 outs() << " c2 " << fpu.fpu_fsw.c2;
8462 outs() << " tos " << fpu.fpu_fsw.tos;
8463 outs() << " c3 " << fpu.fpu_fsw.c3;
8464 outs() << " busy " << fpu.fpu_fsw.busy << "\n";
8465 outs() << "\t fpu_ftw " << format("0x%02" PRIx32, fpu.fpu_ftw);
8466 outs() << " fpu_rsrv1 " << format("0x%02" PRIx32, fpu.fpu_rsrv1);
8467 outs() << " fpu_fop " << format("0x%04" PRIx32, fpu.fpu_fop);
8468 outs() << " fpu_ip " << format("0x%08" PRIx32, fpu.fpu_ip) << "\n";
8469 outs() << "\t fpu_cs " << format("0x%04" PRIx32, fpu.fpu_cs);
8470 outs() << " fpu_rsrv2 " << format("0x%04" PRIx32, fpu.fpu_rsrv2);
8471 outs() << " fpu_dp " << format("0x%08" PRIx32, fpu.fpu_dp);
8472 outs() << " fpu_ds " << format("0x%04" PRIx32, fpu.fpu_ds) << "\n";
8473 outs() << "\t fpu_rsrv3 " << format("0x%04" PRIx32, fpu.fpu_rsrv3);
8474 outs() << " fpu_mxcsr " << format("0x%08" PRIx32, fpu.fpu_mxcsr);
8475 outs() << " fpu_mxcsrmask " << format("0x%08" PRIx32, fpu.fpu_mxcsrmask);
8476 outs() << "\n";
8477 outs() << "\t fpu_stmm0:\n";
8478 Print_mmst_reg(fpu.fpu_stmm0);
8479 outs() << "\t fpu_stmm1:\n";
8480 Print_mmst_reg(fpu.fpu_stmm1);
8481 outs() << "\t fpu_stmm2:\n";
8482 Print_mmst_reg(fpu.fpu_stmm2);
8483 outs() << "\t fpu_stmm3:\n";
8484 Print_mmst_reg(fpu.fpu_stmm3);
8485 outs() << "\t fpu_stmm4:\n";
8486 Print_mmst_reg(fpu.fpu_stmm4);
8487 outs() << "\t fpu_stmm5:\n";
8488 Print_mmst_reg(fpu.fpu_stmm5);
8489 outs() << "\t fpu_stmm6:\n";
8490 Print_mmst_reg(fpu.fpu_stmm6);
8491 outs() << "\t fpu_stmm7:\n";
8492 Print_mmst_reg(fpu.fpu_stmm7);
8493 outs() << "\t fpu_xmm0:\n";
8494 Print_xmm_reg(fpu.fpu_xmm0);
8495 outs() << "\t fpu_xmm1:\n";
8496 Print_xmm_reg(fpu.fpu_xmm1);
8497 outs() << "\t fpu_xmm2:\n";
8498 Print_xmm_reg(fpu.fpu_xmm2);
8499 outs() << "\t fpu_xmm3:\n";
8500 Print_xmm_reg(fpu.fpu_xmm3);
8501 outs() << "\t fpu_xmm4:\n";
8502 Print_xmm_reg(fpu.fpu_xmm4);
8503 outs() << "\t fpu_xmm5:\n";
8504 Print_xmm_reg(fpu.fpu_xmm5);
8505 outs() << "\t fpu_xmm6:\n";
8506 Print_xmm_reg(fpu.fpu_xmm6);
8507 outs() << "\t fpu_xmm7:\n";
8508 Print_xmm_reg(fpu.fpu_xmm7);
8509 outs() << "\t fpu_xmm8:\n";
8510 Print_xmm_reg(fpu.fpu_xmm8);
8511 outs() << "\t fpu_xmm9:\n";
8512 Print_xmm_reg(fpu.fpu_xmm9);
8513 outs() << "\t fpu_xmm10:\n";
8514 Print_xmm_reg(fpu.fpu_xmm10);
8515 outs() << "\t fpu_xmm11:\n";
8516 Print_xmm_reg(fpu.fpu_xmm11);
8517 outs() << "\t fpu_xmm12:\n";
8518 Print_xmm_reg(fpu.fpu_xmm12);
8519 outs() << "\t fpu_xmm13:\n";
8520 Print_xmm_reg(fpu.fpu_xmm13);
8521 outs() << "\t fpu_xmm14:\n";
8522 Print_xmm_reg(fpu.fpu_xmm14);
8523 outs() << "\t fpu_xmm15:\n";
8524 Print_xmm_reg(fpu.fpu_xmm15);
8525 outs() << "\t fpu_rsrv4:\n";
8526 for (uint32_t f = 0; f < 6; f++) {
8527 outs() << "\t ";
8528 for (uint32_t g = 0; g < 16; g++)
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008529 outs() << format("%02" PRIx32, fpu.fpu_rsrv4[f * g]) << " ";
Kevin Enderby48ef5342014-12-23 22:56:39 +00008530 outs() << "\n";
8531 }
8532 outs() << "\t fpu_reserved1 " << format("0x%08" PRIx32, fpu.fpu_reserved1);
8533 outs() << "\n";
8534}
8535
8536static void Print_x86_exception_state_t(MachO::x86_exception_state64_t &exc64) {
8537 outs() << "\t trapno " << format("0x%08" PRIx32, exc64.trapno);
8538 outs() << " err " << format("0x%08" PRIx32, exc64.err);
8539 outs() << " faultvaddr " << format("0x%016" PRIx64, exc64.faultvaddr) << "\n";
8540}
8541
Kevin Enderby41c9c002016-10-21 18:22:35 +00008542static void Print_arm_thread_state32_t(MachO::arm_thread_state32_t &cpu32) {
8543 outs() << "\t r0 " << format("0x%08" PRIx32, cpu32.r[0]);
8544 outs() << " r1 " << format("0x%08" PRIx32, cpu32.r[1]);
8545 outs() << " r2 " << format("0x%08" PRIx32, cpu32.r[2]);
8546 outs() << " r3 " << format("0x%08" PRIx32, cpu32.r[3]) << "\n";
8547 outs() << "\t r4 " << format("0x%08" PRIx32, cpu32.r[4]);
8548 outs() << " r5 " << format("0x%08" PRIx32, cpu32.r[5]);
8549 outs() << " r6 " << format("0x%08" PRIx32, cpu32.r[6]);
8550 outs() << " r7 " << format("0x%08" PRIx32, cpu32.r[7]) << "\n";
8551 outs() << "\t r8 " << format("0x%08" PRIx32, cpu32.r[8]);
8552 outs() << " r9 " << format("0x%08" PRIx32, cpu32.r[9]);
8553 outs() << " r10 " << format("0x%08" PRIx32, cpu32.r[10]);
8554 outs() << " r11 " << format("0x%08" PRIx32, cpu32.r[11]) << "\n";
8555 outs() << "\t r12 " << format("0x%08" PRIx32, cpu32.r[12]);
8556 outs() << " sp " << format("0x%08" PRIx32, cpu32.sp);
8557 outs() << " lr " << format("0x%08" PRIx32, cpu32.lr);
8558 outs() << " pc " << format("0x%08" PRIx32, cpu32.pc) << "\n";
8559 outs() << "\t cpsr " << format("0x%08" PRIx32, cpu32.cpsr) << "\n";
8560}
8561
Kevin Enderby7747cb52016-11-03 20:51:28 +00008562static void Print_arm_thread_state64_t(MachO::arm_thread_state64_t &cpu64) {
8563 outs() << "\t x0 " << format("0x%016" PRIx64, cpu64.x[0]);
8564 outs() << " x1 " << format("0x%016" PRIx64, cpu64.x[1]);
8565 outs() << " x2 " << format("0x%016" PRIx64, cpu64.x[2]) << "\n";
8566 outs() << "\t x3 " << format("0x%016" PRIx64, cpu64.x[3]);
8567 outs() << " x4 " << format("0x%016" PRIx64, cpu64.x[4]);
8568 outs() << " x5 " << format("0x%016" PRIx64, cpu64.x[5]) << "\n";
8569 outs() << "\t x6 " << format("0x%016" PRIx64, cpu64.x[6]);
8570 outs() << " x7 " << format("0x%016" PRIx64, cpu64.x[7]);
8571 outs() << " x8 " << format("0x%016" PRIx64, cpu64.x[8]) << "\n";
8572 outs() << "\t x9 " << format("0x%016" PRIx64, cpu64.x[9]);
8573 outs() << " x10 " << format("0x%016" PRIx64, cpu64.x[10]);
8574 outs() << " x11 " << format("0x%016" PRIx64, cpu64.x[11]) << "\n";
8575 outs() << "\t x12 " << format("0x%016" PRIx64, cpu64.x[12]);
8576 outs() << " x13 " << format("0x%016" PRIx64, cpu64.x[13]);
8577 outs() << " x14 " << format("0x%016" PRIx64, cpu64.x[14]) << "\n";
8578 outs() << "\t x15 " << format("0x%016" PRIx64, cpu64.x[15]);
8579 outs() << " x16 " << format("0x%016" PRIx64, cpu64.x[16]);
8580 outs() << " x17 " << format("0x%016" PRIx64, cpu64.x[17]) << "\n";
8581 outs() << "\t x18 " << format("0x%016" PRIx64, cpu64.x[18]);
8582 outs() << " x19 " << format("0x%016" PRIx64, cpu64.x[19]);
8583 outs() << " x20 " << format("0x%016" PRIx64, cpu64.x[20]) << "\n";
8584 outs() << "\t x21 " << format("0x%016" PRIx64, cpu64.x[21]);
8585 outs() << " x22 " << format("0x%016" PRIx64, cpu64.x[22]);
8586 outs() << " x23 " << format("0x%016" PRIx64, cpu64.x[23]) << "\n";
8587 outs() << "\t x24 " << format("0x%016" PRIx64, cpu64.x[24]);
8588 outs() << " x25 " << format("0x%016" PRIx64, cpu64.x[25]);
8589 outs() << " x26 " << format("0x%016" PRIx64, cpu64.x[26]) << "\n";
8590 outs() << "\t x27 " << format("0x%016" PRIx64, cpu64.x[27]);
8591 outs() << " x28 " << format("0x%016" PRIx64, cpu64.x[28]);
8592 outs() << " fp " << format("0x%016" PRIx64, cpu64.fp) << "\n";
8593 outs() << "\t lr " << format("0x%016" PRIx64, cpu64.lr);
8594 outs() << " sp " << format("0x%016" PRIx64, cpu64.sp);
8595 outs() << " pc " << format("0x%016" PRIx64, cpu64.pc) << "\n";
8596 outs() << "\t cpsr " << format("0x%08" PRIx32, cpu64.cpsr) << "\n";
8597}
8598
Kevin Enderby48ef5342014-12-23 22:56:39 +00008599static void PrintThreadCommand(MachO::thread_command t, const char *Ptr,
8600 bool isLittleEndian, uint32_t cputype) {
8601 if (t.cmd == MachO::LC_THREAD)
8602 outs() << " cmd LC_THREAD\n";
8603 else if (t.cmd == MachO::LC_UNIXTHREAD)
8604 outs() << " cmd LC_UNIXTHREAD\n";
8605 else
8606 outs() << " cmd " << t.cmd << " (unknown)\n";
8607 outs() << " cmdsize " << t.cmdsize;
8608 if (t.cmdsize < sizeof(struct MachO::thread_command) + 2 * sizeof(uint32_t))
8609 outs() << " Incorrect size\n";
8610 else
8611 outs() << "\n";
8612
8613 const char *begin = Ptr + sizeof(struct MachO::thread_command);
8614 const char *end = Ptr + t.cmdsize;
8615 uint32_t flavor, count, left;
8616 if (cputype == MachO::CPU_TYPE_X86_64) {
8617 while (begin < end) {
8618 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
8619 memcpy((char *)&flavor, begin, sizeof(uint32_t));
8620 begin += sizeof(uint32_t);
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008621 } else {
Kevin Enderby48ef5342014-12-23 22:56:39 +00008622 flavor = 0;
8623 begin = end;
8624 }
8625 if (isLittleEndian != sys::IsLittleEndianHost)
8626 sys::swapByteOrder(flavor);
8627 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
8628 memcpy((char *)&count, begin, sizeof(uint32_t));
8629 begin += sizeof(uint32_t);
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008630 } else {
Kevin Enderby48ef5342014-12-23 22:56:39 +00008631 count = 0;
8632 begin = end;
8633 }
8634 if (isLittleEndian != sys::IsLittleEndianHost)
8635 sys::swapByteOrder(count);
8636 if (flavor == MachO::x86_THREAD_STATE64) {
8637 outs() << " flavor x86_THREAD_STATE64\n";
8638 if (count == MachO::x86_THREAD_STATE64_COUNT)
8639 outs() << " count x86_THREAD_STATE64_COUNT\n";
8640 else
8641 outs() << " count " << count
8642 << " (not x86_THREAD_STATE64_COUNT)\n";
8643 MachO::x86_thread_state64_t cpu64;
8644 left = end - begin;
8645 if (left >= sizeof(MachO::x86_thread_state64_t)) {
8646 memcpy(&cpu64, begin, sizeof(MachO::x86_thread_state64_t));
8647 begin += sizeof(MachO::x86_thread_state64_t);
8648 } else {
8649 memset(&cpu64, '\0', sizeof(MachO::x86_thread_state64_t));
8650 memcpy(&cpu64, begin, left);
8651 begin += left;
8652 }
8653 if (isLittleEndian != sys::IsLittleEndianHost)
8654 swapStruct(cpu64);
8655 Print_x86_thread_state64_t(cpu64);
8656 } else if (flavor == MachO::x86_THREAD_STATE) {
8657 outs() << " flavor x86_THREAD_STATE\n";
8658 if (count == MachO::x86_THREAD_STATE_COUNT)
8659 outs() << " count x86_THREAD_STATE_COUNT\n";
8660 else
8661 outs() << " count " << count
8662 << " (not x86_THREAD_STATE_COUNT)\n";
8663 struct MachO::x86_thread_state_t ts;
8664 left = end - begin;
8665 if (left >= sizeof(MachO::x86_thread_state_t)) {
8666 memcpy(&ts, begin, sizeof(MachO::x86_thread_state_t));
8667 begin += sizeof(MachO::x86_thread_state_t);
8668 } else {
8669 memset(&ts, '\0', sizeof(MachO::x86_thread_state_t));
8670 memcpy(&ts, begin, left);
8671 begin += left;
8672 }
8673 if (isLittleEndian != sys::IsLittleEndianHost)
8674 swapStruct(ts);
8675 if (ts.tsh.flavor == MachO::x86_THREAD_STATE64) {
8676 outs() << "\t tsh.flavor x86_THREAD_STATE64 ";
8677 if (ts.tsh.count == MachO::x86_THREAD_STATE64_COUNT)
8678 outs() << "tsh.count x86_THREAD_STATE64_COUNT\n";
8679 else
8680 outs() << "tsh.count " << ts.tsh.count
8681 << " (not x86_THREAD_STATE64_COUNT\n";
8682 Print_x86_thread_state64_t(ts.uts.ts64);
8683 } else {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008684 outs() << "\t tsh.flavor " << ts.tsh.flavor << " tsh.count "
8685 << ts.tsh.count << "\n";
Kevin Enderby48ef5342014-12-23 22:56:39 +00008686 }
8687 } else if (flavor == MachO::x86_FLOAT_STATE) {
8688 outs() << " flavor x86_FLOAT_STATE\n";
8689 if (count == MachO::x86_FLOAT_STATE_COUNT)
8690 outs() << " count x86_FLOAT_STATE_COUNT\n";
8691 else
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008692 outs() << " count " << count << " (not x86_FLOAT_STATE_COUNT)\n";
Kevin Enderby48ef5342014-12-23 22:56:39 +00008693 struct MachO::x86_float_state_t fs;
8694 left = end - begin;
8695 if (left >= sizeof(MachO::x86_float_state_t)) {
8696 memcpy(&fs, begin, sizeof(MachO::x86_float_state_t));
8697 begin += sizeof(MachO::x86_float_state_t);
8698 } else {
8699 memset(&fs, '\0', sizeof(MachO::x86_float_state_t));
8700 memcpy(&fs, begin, left);
8701 begin += left;
8702 }
8703 if (isLittleEndian != sys::IsLittleEndianHost)
8704 swapStruct(fs);
8705 if (fs.fsh.flavor == MachO::x86_FLOAT_STATE64) {
8706 outs() << "\t fsh.flavor x86_FLOAT_STATE64 ";
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008707 if (fs.fsh.count == MachO::x86_FLOAT_STATE64_COUNT)
Kevin Enderby48ef5342014-12-23 22:56:39 +00008708 outs() << "fsh.count x86_FLOAT_STATE64_COUNT\n";
8709 else
8710 outs() << "fsh.count " << fs.fsh.count
8711 << " (not x86_FLOAT_STATE64_COUNT\n";
8712 Print_x86_float_state_t(fs.ufs.fs64);
8713 } else {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008714 outs() << "\t fsh.flavor " << fs.fsh.flavor << " fsh.count "
8715 << fs.fsh.count << "\n";
Kevin Enderby48ef5342014-12-23 22:56:39 +00008716 }
8717 } else if (flavor == MachO::x86_EXCEPTION_STATE) {
8718 outs() << " flavor x86_EXCEPTION_STATE\n";
8719 if (count == MachO::x86_EXCEPTION_STATE_COUNT)
8720 outs() << " count x86_EXCEPTION_STATE_COUNT\n";
8721 else
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008722 outs() << " count " << count
Kevin Enderby48ef5342014-12-23 22:56:39 +00008723 << " (not x86_EXCEPTION_STATE_COUNT)\n";
8724 struct MachO::x86_exception_state_t es;
8725 left = end - begin;
8726 if (left >= sizeof(MachO::x86_exception_state_t)) {
8727 memcpy(&es, begin, sizeof(MachO::x86_exception_state_t));
8728 begin += sizeof(MachO::x86_exception_state_t);
8729 } else {
8730 memset(&es, '\0', sizeof(MachO::x86_exception_state_t));
8731 memcpy(&es, begin, left);
8732 begin += left;
8733 }
8734 if (isLittleEndian != sys::IsLittleEndianHost)
8735 swapStruct(es);
8736 if (es.esh.flavor == MachO::x86_EXCEPTION_STATE64) {
8737 outs() << "\t esh.flavor x86_EXCEPTION_STATE64\n";
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008738 if (es.esh.count == MachO::x86_EXCEPTION_STATE64_COUNT)
Kevin Enderby48ef5342014-12-23 22:56:39 +00008739 outs() << "\t esh.count x86_EXCEPTION_STATE64_COUNT\n";
8740 else
8741 outs() << "\t esh.count " << es.esh.count
8742 << " (not x86_EXCEPTION_STATE64_COUNT\n";
8743 Print_x86_exception_state_t(es.ues.es64);
8744 } else {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008745 outs() << "\t esh.flavor " << es.esh.flavor << " esh.count "
8746 << es.esh.count << "\n";
Kevin Enderby48ef5342014-12-23 22:56:39 +00008747 }
8748 } else {
8749 outs() << " flavor " << flavor << " (unknown)\n";
8750 outs() << " count " << count << "\n";
8751 outs() << " state (unknown)\n";
8752 begin += count * sizeof(uint32_t);
8753 }
8754 }
Kevin Enderby41c9c002016-10-21 18:22:35 +00008755 } else if (cputype == MachO::CPU_TYPE_ARM) {
8756 while (begin < end) {
8757 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
8758 memcpy((char *)&flavor, begin, sizeof(uint32_t));
8759 begin += sizeof(uint32_t);
8760 } else {
8761 flavor = 0;
8762 begin = end;
8763 }
8764 if (isLittleEndian != sys::IsLittleEndianHost)
8765 sys::swapByteOrder(flavor);
8766 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
8767 memcpy((char *)&count, begin, sizeof(uint32_t));
8768 begin += sizeof(uint32_t);
8769 } else {
8770 count = 0;
8771 begin = end;
8772 }
8773 if (isLittleEndian != sys::IsLittleEndianHost)
8774 sys::swapByteOrder(count);
8775 if (flavor == MachO::ARM_THREAD_STATE) {
8776 outs() << " flavor ARM_THREAD_STATE\n";
8777 if (count == MachO::ARM_THREAD_STATE_COUNT)
8778 outs() << " count ARM_THREAD_STATE_COUNT\n";
8779 else
8780 outs() << " count " << count
8781 << " (not ARM_THREAD_STATE_COUNT)\n";
8782 MachO::arm_thread_state32_t cpu32;
8783 left = end - begin;
8784 if (left >= sizeof(MachO::arm_thread_state32_t)) {
8785 memcpy(&cpu32, begin, sizeof(MachO::arm_thread_state32_t));
8786 begin += sizeof(MachO::arm_thread_state32_t);
8787 } else {
8788 memset(&cpu32, '\0', sizeof(MachO::arm_thread_state32_t));
8789 memcpy(&cpu32, begin, left);
8790 begin += left;
8791 }
8792 if (isLittleEndian != sys::IsLittleEndianHost)
8793 swapStruct(cpu32);
8794 Print_arm_thread_state32_t(cpu32);
8795 } else {
8796 outs() << " flavor " << flavor << " (unknown)\n";
8797 outs() << " count " << count << "\n";
8798 outs() << " state (unknown)\n";
8799 begin += count * sizeof(uint32_t);
8800 }
8801 }
Kevin Enderby7747cb52016-11-03 20:51:28 +00008802 } else if (cputype == MachO::CPU_TYPE_ARM64) {
8803 while (begin < end) {
8804 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
8805 memcpy((char *)&flavor, begin, sizeof(uint32_t));
8806 begin += sizeof(uint32_t);
8807 } else {
8808 flavor = 0;
8809 begin = end;
8810 }
8811 if (isLittleEndian != sys::IsLittleEndianHost)
8812 sys::swapByteOrder(flavor);
8813 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
8814 memcpy((char *)&count, begin, sizeof(uint32_t));
8815 begin += sizeof(uint32_t);
8816 } else {
8817 count = 0;
8818 begin = end;
8819 }
8820 if (isLittleEndian != sys::IsLittleEndianHost)
8821 sys::swapByteOrder(count);
8822 if (flavor == MachO::ARM_THREAD_STATE64) {
8823 outs() << " flavor ARM_THREAD_STATE64\n";
8824 if (count == MachO::ARM_THREAD_STATE64_COUNT)
8825 outs() << " count ARM_THREAD_STATE64_COUNT\n";
8826 else
8827 outs() << " count " << count
8828 << " (not ARM_THREAD_STATE64_COUNT)\n";
8829 MachO::arm_thread_state64_t cpu64;
8830 left = end - begin;
8831 if (left >= sizeof(MachO::arm_thread_state64_t)) {
8832 memcpy(&cpu64, begin, sizeof(MachO::arm_thread_state64_t));
8833 begin += sizeof(MachO::arm_thread_state64_t);
8834 } else {
8835 memset(&cpu64, '\0', sizeof(MachO::arm_thread_state64_t));
8836 memcpy(&cpu64, begin, left);
8837 begin += left;
8838 }
8839 if (isLittleEndian != sys::IsLittleEndianHost)
8840 swapStruct(cpu64);
8841 Print_arm_thread_state64_t(cpu64);
8842 } else {
8843 outs() << " flavor " << flavor << " (unknown)\n";
8844 outs() << " count " << count << "\n";
8845 outs() << " state (unknown)\n";
8846 begin += count * sizeof(uint32_t);
8847 }
8848 }
Kevin Enderby48ef5342014-12-23 22:56:39 +00008849 } else {
8850 while (begin < end) {
8851 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
8852 memcpy((char *)&flavor, begin, sizeof(uint32_t));
8853 begin += sizeof(uint32_t);
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008854 } else {
Kevin Enderby48ef5342014-12-23 22:56:39 +00008855 flavor = 0;
8856 begin = end;
8857 }
8858 if (isLittleEndian != sys::IsLittleEndianHost)
8859 sys::swapByteOrder(flavor);
8860 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
8861 memcpy((char *)&count, begin, sizeof(uint32_t));
8862 begin += sizeof(uint32_t);
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008863 } else {
Kevin Enderby48ef5342014-12-23 22:56:39 +00008864 count = 0;
8865 begin = end;
8866 }
8867 if (isLittleEndian != sys::IsLittleEndianHost)
8868 sys::swapByteOrder(count);
8869 outs() << " flavor " << flavor << "\n";
8870 outs() << " count " << count << "\n";
8871 outs() << " state (Unknown cputype/cpusubtype)\n";
8872 begin += count * sizeof(uint32_t);
8873 }
8874 }
8875}
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008876
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008877static void PrintDylibCommand(MachO::dylib_command dl, const char *Ptr) {
8878 if (dl.cmd == MachO::LC_ID_DYLIB)
8879 outs() << " cmd LC_ID_DYLIB\n";
8880 else if (dl.cmd == MachO::LC_LOAD_DYLIB)
8881 outs() << " cmd LC_LOAD_DYLIB\n";
8882 else if (dl.cmd == MachO::LC_LOAD_WEAK_DYLIB)
8883 outs() << " cmd LC_LOAD_WEAK_DYLIB\n";
8884 else if (dl.cmd == MachO::LC_REEXPORT_DYLIB)
8885 outs() << " cmd LC_REEXPORT_DYLIB\n";
8886 else if (dl.cmd == MachO::LC_LAZY_LOAD_DYLIB)
8887 outs() << " cmd LC_LAZY_LOAD_DYLIB\n";
8888 else if (dl.cmd == MachO::LC_LOAD_UPWARD_DYLIB)
8889 outs() << " cmd LC_LOAD_UPWARD_DYLIB\n";
8890 else
8891 outs() << " cmd " << dl.cmd << " (unknown)\n";
8892 outs() << " cmdsize " << dl.cmdsize;
8893 if (dl.cmdsize < sizeof(struct MachO::dylib_command))
8894 outs() << " Incorrect size\n";
8895 else
8896 outs() << "\n";
8897 if (dl.dylib.name < dl.cmdsize) {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00008898 const char *P = (const char *)(Ptr) + dl.dylib.name;
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008899 outs() << " name " << P << " (offset " << dl.dylib.name << ")\n";
8900 } else {
8901 outs() << " name ?(bad offset " << dl.dylib.name << ")\n";
8902 }
8903 outs() << " time stamp " << dl.dylib.timestamp << " ";
8904 time_t t = dl.dylib.timestamp;
8905 outs() << ctime(&t);
8906 outs() << " current version ";
8907 if (dl.dylib.current_version == 0xffffffff)
8908 outs() << "n/a\n";
8909 else
8910 outs() << ((dl.dylib.current_version >> 16) & 0xffff) << "."
8911 << ((dl.dylib.current_version >> 8) & 0xff) << "."
8912 << (dl.dylib.current_version & 0xff) << "\n";
8913 outs() << "compatibility version ";
8914 if (dl.dylib.compatibility_version == 0xffffffff)
8915 outs() << "n/a\n";
8916 else
8917 outs() << ((dl.dylib.compatibility_version >> 16) & 0xffff) << "."
8918 << ((dl.dylib.compatibility_version >> 8) & 0xff) << "."
8919 << (dl.dylib.compatibility_version & 0xff) << "\n";
8920}
8921
8922static void PrintLinkEditDataCommand(MachO::linkedit_data_command ld,
8923 uint32_t object_size) {
8924 if (ld.cmd == MachO::LC_CODE_SIGNATURE)
Kevin Enderby1be37a32016-04-28 21:07:20 +00008925 outs() << " cmd LC_CODE_SIGNATURE\n";
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008926 else if (ld.cmd == MachO::LC_SEGMENT_SPLIT_INFO)
8927 outs() << " cmd LC_SEGMENT_SPLIT_INFO\n";
8928 else if (ld.cmd == MachO::LC_FUNCTION_STARTS)
8929 outs() << " cmd LC_FUNCTION_STARTS\n";
8930 else if (ld.cmd == MachO::LC_DATA_IN_CODE)
8931 outs() << " cmd LC_DATA_IN_CODE\n";
8932 else if (ld.cmd == MachO::LC_DYLIB_CODE_SIGN_DRS)
8933 outs() << " cmd LC_DYLIB_CODE_SIGN_DRS\n";
8934 else if (ld.cmd == MachO::LC_LINKER_OPTIMIZATION_HINT)
8935 outs() << " cmd LC_LINKER_OPTIMIZATION_HINT\n";
8936 else
8937 outs() << " cmd " << ld.cmd << " (?)\n";
8938 outs() << " cmdsize " << ld.cmdsize;
8939 if (ld.cmdsize != sizeof(struct MachO::linkedit_data_command))
8940 outs() << " Incorrect size\n";
8941 else
8942 outs() << "\n";
8943 outs() << " dataoff " << ld.dataoff;
8944 if (ld.dataoff > object_size)
8945 outs() << " (past end of file)\n";
8946 else
8947 outs() << "\n";
8948 outs() << " datasize " << ld.datasize;
8949 uint64_t big_size = ld.dataoff;
8950 big_size += ld.datasize;
8951 if (big_size > object_size)
8952 outs() << " (past end of file)\n";
8953 else
8954 outs() << "\n";
8955}
8956
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00008957static void PrintLoadCommands(const MachOObjectFile *Obj, uint32_t filetype,
8958 uint32_t cputype, bool verbose) {
Kevin Enderby956366c2014-08-29 22:30:52 +00008959 StringRef Buf = Obj->getData();
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00008960 unsigned Index = 0;
8961 for (const auto &Command : Obj->load_commands()) {
8962 outs() << "Load command " << Index++ << "\n";
Kevin Enderby956366c2014-08-29 22:30:52 +00008963 if (Command.C.cmd == MachO::LC_SEGMENT) {
8964 MachO::segment_command SLC = Obj->getSegmentLoadCommand(Command);
8965 const char *sg_segname = SLC.segname;
8966 PrintSegmentCommand(SLC.cmd, SLC.cmdsize, SLC.segname, SLC.vmaddr,
8967 SLC.vmsize, SLC.fileoff, SLC.filesize, SLC.maxprot,
8968 SLC.initprot, SLC.nsects, SLC.flags, Buf.size(),
8969 verbose);
8970 for (unsigned j = 0; j < SLC.nsects; j++) {
Kevin Enderbyc9713382014-12-16 01:14:45 +00008971 MachO::section S = Obj->getSection(Command, j);
Kevin Enderby956366c2014-08-29 22:30:52 +00008972 PrintSection(S.sectname, S.segname, S.addr, S.size, S.offset, S.align,
8973 S.reloff, S.nreloc, S.flags, S.reserved1, S.reserved2,
8974 SLC.cmd, sg_segname, filetype, Buf.size(), verbose);
8975 }
8976 } else if (Command.C.cmd == MachO::LC_SEGMENT_64) {
8977 MachO::segment_command_64 SLC_64 = Obj->getSegment64LoadCommand(Command);
8978 const char *sg_segname = SLC_64.segname;
8979 PrintSegmentCommand(SLC_64.cmd, SLC_64.cmdsize, SLC_64.segname,
8980 SLC_64.vmaddr, SLC_64.vmsize, SLC_64.fileoff,
8981 SLC_64.filesize, SLC_64.maxprot, SLC_64.initprot,
8982 SLC_64.nsects, SLC_64.flags, Buf.size(), verbose);
8983 for (unsigned j = 0; j < SLC_64.nsects; j++) {
8984 MachO::section_64 S_64 = Obj->getSection64(Command, j);
8985 PrintSection(S_64.sectname, S_64.segname, S_64.addr, S_64.size,
8986 S_64.offset, S_64.align, S_64.reloff, S_64.nreloc,
8987 S_64.flags, S_64.reserved1, S_64.reserved2, SLC_64.cmd,
8988 sg_segname, filetype, Buf.size(), verbose);
8989 }
8990 } else if (Command.C.cmd == MachO::LC_SYMTAB) {
8991 MachO::symtab_command Symtab = Obj->getSymtabLoadCommand();
David Majnemer73cc6ff2014-11-13 19:48:56 +00008992 PrintSymtabLoadCommand(Symtab, Obj->is64Bit(), Buf.size());
Kevin Enderby956366c2014-08-29 22:30:52 +00008993 } else if (Command.C.cmd == MachO::LC_DYSYMTAB) {
8994 MachO::dysymtab_command Dysymtab = Obj->getDysymtabLoadCommand();
8995 MachO::symtab_command Symtab = Obj->getSymtabLoadCommand();
David Majnemer73cc6ff2014-11-13 19:48:56 +00008996 PrintDysymtabLoadCommand(Dysymtab, Symtab.nsyms, Buf.size(),
8997 Obj->is64Bit());
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008998 } else if (Command.C.cmd == MachO::LC_DYLD_INFO ||
8999 Command.C.cmd == MachO::LC_DYLD_INFO_ONLY) {
9000 MachO::dyld_info_command DyldInfo = Obj->getDyldInfoLoadCommand(Command);
9001 PrintDyldInfoLoadCommand(DyldInfo, Buf.size());
9002 } else if (Command.C.cmd == MachO::LC_LOAD_DYLINKER ||
9003 Command.C.cmd == MachO::LC_ID_DYLINKER ||
9004 Command.C.cmd == MachO::LC_DYLD_ENVIRONMENT) {
9005 MachO::dylinker_command Dyld = Obj->getDylinkerCommand(Command);
9006 PrintDyldLoadCommand(Dyld, Command.Ptr);
9007 } else if (Command.C.cmd == MachO::LC_UUID) {
9008 MachO::uuid_command Uuid = Obj->getUuidCommand(Command);
9009 PrintUuidLoadCommand(Uuid);
Jean-Daniel Dupas00cc1f52014-12-04 07:37:02 +00009010 } else if (Command.C.cmd == MachO::LC_RPATH) {
9011 MachO::rpath_command Rpath = Obj->getRpathCommand(Command);
9012 PrintRpathLoadCommand(Rpath, Command.Ptr);
Kevin Enderby1ff0ecc2014-12-16 21:48:27 +00009013 } else if (Command.C.cmd == MachO::LC_VERSION_MIN_MACOSX ||
Tim Northoverbfbfb122015-11-02 21:26:58 +00009014 Command.C.cmd == MachO::LC_VERSION_MIN_IPHONEOS ||
9015 Command.C.cmd == MachO::LC_VERSION_MIN_TVOS ||
9016 Command.C.cmd == MachO::LC_VERSION_MIN_WATCHOS) {
Kevin Enderby8ae63c12014-09-04 16:54:47 +00009017 MachO::version_min_command Vd = Obj->getVersionMinLoadCommand(Command);
9018 PrintVersionMinLoadCommand(Vd);
9019 } else if (Command.C.cmd == MachO::LC_SOURCE_VERSION) {
9020 MachO::source_version_command Sd = Obj->getSourceVersionCommand(Command);
9021 PrintSourceVersionCommand(Sd);
9022 } else if (Command.C.cmd == MachO::LC_MAIN) {
9023 MachO::entry_point_command Ep = Obj->getEntryPointCommand(Command);
9024 PrintEntryPointCommand(Ep);
Kevin Enderby0804f4672014-12-16 23:25:52 +00009025 } else if (Command.C.cmd == MachO::LC_ENCRYPTION_INFO) {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009026 MachO::encryption_info_command Ei =
9027 Obj->getEncryptionInfoCommand(Command);
Kevin Enderby0804f4672014-12-16 23:25:52 +00009028 PrintEncryptionInfoCommand(Ei, Buf.size());
Kevin Enderby57538292014-12-17 01:01:30 +00009029 } else if (Command.C.cmd == MachO::LC_ENCRYPTION_INFO_64) {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009030 MachO::encryption_info_command_64 Ei =
9031 Obj->getEncryptionInfoCommand64(Command);
Kevin Enderby57538292014-12-17 01:01:30 +00009032 PrintEncryptionInfoCommand64(Ei, Buf.size());
Kevin Enderbyd0b6b7f2014-12-18 00:53:40 +00009033 } else if (Command.C.cmd == MachO::LC_LINKER_OPTION) {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009034 MachO::linker_option_command Lo =
9035 Obj->getLinkerOptionLoadCommand(Command);
Kevin Enderbyd0b6b7f2014-12-18 00:53:40 +00009036 PrintLinkerOptionCommand(Lo, Command.Ptr);
Kevin Enderbyb4b79312014-12-18 19:24:35 +00009037 } else if (Command.C.cmd == MachO::LC_SUB_FRAMEWORK) {
9038 MachO::sub_framework_command Sf = Obj->getSubFrameworkCommand(Command);
9039 PrintSubFrameworkCommand(Sf, Command.Ptr);
Kevin Enderbya2bd8d92014-12-18 23:13:26 +00009040 } else if (Command.C.cmd == MachO::LC_SUB_UMBRELLA) {
9041 MachO::sub_umbrella_command Sf = Obj->getSubUmbrellaCommand(Command);
9042 PrintSubUmbrellaCommand(Sf, Command.Ptr);
Kevin Enderby36c8d3a2014-12-19 19:48:16 +00009043 } else if (Command.C.cmd == MachO::LC_SUB_LIBRARY) {
9044 MachO::sub_library_command Sl = Obj->getSubLibraryCommand(Command);
9045 PrintSubLibraryCommand(Sl, Command.Ptr);
Kevin Enderby186eac32014-12-19 21:06:24 +00009046 } else if (Command.C.cmd == MachO::LC_SUB_CLIENT) {
9047 MachO::sub_client_command Sc = Obj->getSubClientCommand(Command);
9048 PrintSubClientCommand(Sc, Command.Ptr);
Kevin Enderby52e4ce42014-12-19 22:25:22 +00009049 } else if (Command.C.cmd == MachO::LC_ROUTINES) {
9050 MachO::routines_command Rc = Obj->getRoutinesCommand(Command);
9051 PrintRoutinesCommand(Rc);
9052 } else if (Command.C.cmd == MachO::LC_ROUTINES_64) {
9053 MachO::routines_command_64 Rc = Obj->getRoutinesCommand64(Command);
9054 PrintRoutinesCommand64(Rc);
Kevin Enderby48ef5342014-12-23 22:56:39 +00009055 } else if (Command.C.cmd == MachO::LC_THREAD ||
9056 Command.C.cmd == MachO::LC_UNIXTHREAD) {
9057 MachO::thread_command Tc = Obj->getThreadCommand(Command);
9058 PrintThreadCommand(Tc, Command.Ptr, Obj->isLittleEndian(), cputype);
Nick Kledzik15558912014-10-16 18:58:20 +00009059 } else if (Command.C.cmd == MachO::LC_LOAD_DYLIB ||
9060 Command.C.cmd == MachO::LC_ID_DYLIB ||
9061 Command.C.cmd == MachO::LC_LOAD_WEAK_DYLIB ||
9062 Command.C.cmd == MachO::LC_REEXPORT_DYLIB ||
9063 Command.C.cmd == MachO::LC_LAZY_LOAD_DYLIB ||
9064 Command.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB) {
Kevin Enderby8ae63c12014-09-04 16:54:47 +00009065 MachO::dylib_command Dl = Obj->getDylibIDLoadCommand(Command);
9066 PrintDylibCommand(Dl, Command.Ptr);
9067 } else if (Command.C.cmd == MachO::LC_CODE_SIGNATURE ||
9068 Command.C.cmd == MachO::LC_SEGMENT_SPLIT_INFO ||
9069 Command.C.cmd == MachO::LC_FUNCTION_STARTS ||
9070 Command.C.cmd == MachO::LC_DATA_IN_CODE ||
9071 Command.C.cmd == MachO::LC_DYLIB_CODE_SIGN_DRS ||
9072 Command.C.cmd == MachO::LC_LINKER_OPTIMIZATION_HINT) {
9073 MachO::linkedit_data_command Ld =
9074 Obj->getLinkeditDataLoadCommand(Command);
9075 PrintLinkEditDataCommand(Ld, Buf.size());
Kevin Enderby956366c2014-08-29 22:30:52 +00009076 } else {
9077 outs() << " cmd ?(" << format("0x%08" PRIx32, Command.C.cmd)
9078 << ")\n";
9079 outs() << " cmdsize " << Command.C.cmdsize << "\n";
9080 // TODO: get and print the raw bytes of the load command.
9081 }
9082 // TODO: print all the other kinds of load commands.
Kevin Enderby956366c2014-08-29 22:30:52 +00009083 }
9084}
9085
Kevin Enderby0ae163f2016-01-13 00:25:36 +00009086static void PrintMachHeader(const MachOObjectFile *Obj, bool verbose) {
Kevin Enderbyb76d3862014-08-22 20:35:18 +00009087 if (Obj->is64Bit()) {
9088 MachO::mach_header_64 H_64;
9089 H_64 = Obj->getHeader64();
9090 PrintMachHeader(H_64.magic, H_64.cputype, H_64.cpusubtype, H_64.filetype,
9091 H_64.ncmds, H_64.sizeofcmds, H_64.flags, verbose);
9092 } else {
9093 MachO::mach_header H;
9094 H = Obj->getHeader();
9095 PrintMachHeader(H.magic, H.cputype, H.cpusubtype, H.filetype, H.ncmds,
9096 H.sizeofcmds, H.flags, verbose);
9097 }
9098}
9099
9100void llvm::printMachOFileHeader(const object::ObjectFile *Obj) {
9101 const MachOObjectFile *file = dyn_cast<const MachOObjectFile>(Obj);
Kevin Enderby0ae163f2016-01-13 00:25:36 +00009102 PrintMachHeader(file, !NonVerbose);
9103}
9104
9105void llvm::printMachOLoadCommands(const object::ObjectFile *Obj) {
9106 const MachOObjectFile *file = dyn_cast<const MachOObjectFile>(Obj);
Kevin Enderby956366c2014-08-29 22:30:52 +00009107 uint32_t filetype = 0;
9108 uint32_t cputype = 0;
Kevin Enderby0ae163f2016-01-13 00:25:36 +00009109 if (file->is64Bit()) {
9110 MachO::mach_header_64 H_64;
9111 H_64 = file->getHeader64();
9112 filetype = H_64.filetype;
9113 cputype = H_64.cputype;
9114 } else {
9115 MachO::mach_header H;
9116 H = file->getHeader();
9117 filetype = H.filetype;
9118 cputype = H.cputype;
9119 }
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00009120 PrintLoadCommands(file, filetype, cputype, !NonVerbose);
Kevin Enderbyb76d3862014-08-22 20:35:18 +00009121}
Nick Kledzikd04bc352014-08-30 00:20:14 +00009122
9123//===----------------------------------------------------------------------===//
9124// export trie dumping
9125//===----------------------------------------------------------------------===//
9126
9127void llvm::printMachOExportsTrie(const object::MachOObjectFile *Obj) {
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00009128 for (const llvm::object::ExportEntry &Entry : Obj->exports()) {
9129 uint64_t Flags = Entry.flags();
Nick Kledzikd04bc352014-08-30 00:20:14 +00009130 bool ReExport = (Flags & MachO::EXPORT_SYMBOL_FLAGS_REEXPORT);
9131 bool WeakDef = (Flags & MachO::EXPORT_SYMBOL_FLAGS_WEAK_DEFINITION);
9132 bool ThreadLocal = ((Flags & MachO::EXPORT_SYMBOL_FLAGS_KIND_MASK) ==
9133 MachO::EXPORT_SYMBOL_FLAGS_KIND_THREAD_LOCAL);
9134 bool Abs = ((Flags & MachO::EXPORT_SYMBOL_FLAGS_KIND_MASK) ==
9135 MachO::EXPORT_SYMBOL_FLAGS_KIND_ABSOLUTE);
9136 bool Resolver = (Flags & MachO::EXPORT_SYMBOL_FLAGS_STUB_AND_RESOLVER);
9137 if (ReExport)
9138 outs() << "[re-export] ";
9139 else
Kevin Enderbyb28ed012014-10-29 21:28:24 +00009140 outs() << format("0x%08llX ",
9141 Entry.address()); // FIXME:add in base address
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00009142 outs() << Entry.name();
Nick Kledzikd04bc352014-08-30 00:20:14 +00009143 if (WeakDef || ThreadLocal || Resolver || Abs) {
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00009144 bool NeedsComma = false;
Nick Kledzik1d1ac4b2014-09-03 01:12:52 +00009145 outs() << " [";
Nick Kledzikd04bc352014-08-30 00:20:14 +00009146 if (WeakDef) {
9147 outs() << "weak_def";
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00009148 NeedsComma = true;
Nick Kledzikd04bc352014-08-30 00:20:14 +00009149 }
9150 if (ThreadLocal) {
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00009151 if (NeedsComma)
Nick Kledzikd04bc352014-08-30 00:20:14 +00009152 outs() << ", ";
9153 outs() << "per-thread";
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00009154 NeedsComma = true;
Nick Kledzikd04bc352014-08-30 00:20:14 +00009155 }
9156 if (Abs) {
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00009157 if (NeedsComma)
Nick Kledzikd04bc352014-08-30 00:20:14 +00009158 outs() << ", ";
9159 outs() << "absolute";
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00009160 NeedsComma = true;
Nick Kledzikd04bc352014-08-30 00:20:14 +00009161 }
9162 if (Resolver) {
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00009163 if (NeedsComma)
Nick Kledzikd04bc352014-08-30 00:20:14 +00009164 outs() << ", ";
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00009165 outs() << format("resolver=0x%08llX", Entry.other());
9166 NeedsComma = true;
Nick Kledzikd04bc352014-08-30 00:20:14 +00009167 }
9168 outs() << "]";
9169 }
9170 if (ReExport) {
9171 StringRef DylibName = "unknown";
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00009172 int Ordinal = Entry.other() - 1;
9173 Obj->getLibraryShortNameByIndex(Ordinal, DylibName);
9174 if (Entry.otherName().empty())
Nick Kledzikd04bc352014-08-30 00:20:14 +00009175 outs() << " (from " << DylibName << ")";
9176 else
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00009177 outs() << " (" << Entry.otherName() << " from " << DylibName << ")";
Nick Kledzikd04bc352014-08-30 00:20:14 +00009178 }
9179 outs() << "\n";
9180 }
9181}
Nick Kledzikac431442014-09-12 21:34:15 +00009182
Nick Kledzikac431442014-09-12 21:34:15 +00009183//===----------------------------------------------------------------------===//
9184// rebase table dumping
9185//===----------------------------------------------------------------------===//
9186
9187namespace {
9188class SegInfo {
9189public:
9190 SegInfo(const object::MachOObjectFile *Obj);
9191
9192 StringRef segmentName(uint32_t SegIndex);
9193 StringRef sectionName(uint32_t SegIndex, uint64_t SegOffset);
9194 uint64_t address(uint32_t SegIndex, uint64_t SegOffset);
Kevin Enderbyaf7c9d02015-10-09 16:48:44 +00009195 bool isValidSegIndexAndOffset(uint32_t SegIndex, uint64_t SegOffset);
Nick Kledzikac431442014-09-12 21:34:15 +00009196
9197private:
9198 struct SectionInfo {
9199 uint64_t Address;
9200 uint64_t Size;
9201 StringRef SectionName;
9202 StringRef SegmentName;
9203 uint64_t OffsetInSegment;
9204 uint64_t SegmentStartAddress;
9205 uint32_t SegmentIndex;
9206 };
9207 const SectionInfo &findSection(uint32_t SegIndex, uint64_t SegOffset);
9208 SmallVector<SectionInfo, 32> Sections;
9209};
9210}
9211
9212SegInfo::SegInfo(const object::MachOObjectFile *Obj) {
9213 // Build table of sections so segIndex/offset pairs can be translated.
Nick Kledzik56ebef42014-09-16 01:41:51 +00009214 uint32_t CurSegIndex = Obj->hasPageZeroSegment() ? 1 : 0;
Nick Kledzikac431442014-09-12 21:34:15 +00009215 StringRef CurSegName;
9216 uint64_t CurSegAddress;
9217 for (const SectionRef &Section : Obj->sections()) {
9218 SectionInfo Info;
Davide Italianoccd53fe2015-08-05 07:18:31 +00009219 error(Section.getName(Info.SectionName));
Rafael Espindola80291272014-10-08 15:28:58 +00009220 Info.Address = Section.getAddress();
9221 Info.Size = Section.getSize();
Nick Kledzikac431442014-09-12 21:34:15 +00009222 Info.SegmentName =
9223 Obj->getSectionFinalSegmentName(Section.getRawDataRefImpl());
9224 if (!Info.SegmentName.equals(CurSegName)) {
9225 ++CurSegIndex;
9226 CurSegName = Info.SegmentName;
9227 CurSegAddress = Info.Address;
9228 }
9229 Info.SegmentIndex = CurSegIndex - 1;
9230 Info.OffsetInSegment = Info.Address - CurSegAddress;
9231 Info.SegmentStartAddress = CurSegAddress;
9232 Sections.push_back(Info);
9233 }
9234}
9235
9236StringRef SegInfo::segmentName(uint32_t SegIndex) {
9237 for (const SectionInfo &SI : Sections) {
9238 if (SI.SegmentIndex == SegIndex)
9239 return SI.SegmentName;
9240 }
9241 llvm_unreachable("invalid segIndex");
9242}
9243
Kevin Enderbyaf7c9d02015-10-09 16:48:44 +00009244bool SegInfo::isValidSegIndexAndOffset(uint32_t SegIndex,
9245 uint64_t OffsetInSeg) {
9246 for (const SectionInfo &SI : Sections) {
9247 if (SI.SegmentIndex != SegIndex)
9248 continue;
9249 if (SI.OffsetInSegment > OffsetInSeg)
9250 continue;
9251 if (OffsetInSeg >= (SI.OffsetInSegment + SI.Size))
9252 continue;
9253 return true;
9254 }
9255 return false;
9256}
9257
Nick Kledzikac431442014-09-12 21:34:15 +00009258const SegInfo::SectionInfo &SegInfo::findSection(uint32_t SegIndex,
9259 uint64_t OffsetInSeg) {
9260 for (const SectionInfo &SI : Sections) {
9261 if (SI.SegmentIndex != SegIndex)
9262 continue;
9263 if (SI.OffsetInSegment > OffsetInSeg)
9264 continue;
9265 if (OffsetInSeg >= (SI.OffsetInSegment + SI.Size))
9266 continue;
9267 return SI;
9268 }
9269 llvm_unreachable("segIndex and offset not in any section");
9270}
9271
9272StringRef SegInfo::sectionName(uint32_t SegIndex, uint64_t OffsetInSeg) {
9273 return findSection(SegIndex, OffsetInSeg).SectionName;
9274}
9275
9276uint64_t SegInfo::address(uint32_t SegIndex, uint64_t OffsetInSeg) {
9277 const SectionInfo &SI = findSection(SegIndex, OffsetInSeg);
9278 return SI.SegmentStartAddress + OffsetInSeg;
9279}
9280
9281void llvm::printMachORebaseTable(const object::MachOObjectFile *Obj) {
9282 // Build table of sections so names can used in final output.
9283 SegInfo sectionTable(Obj);
9284
9285 outs() << "segment section address type\n";
9286 for (const llvm::object::MachORebaseEntry &Entry : Obj->rebaseTable()) {
9287 uint32_t SegIndex = Entry.segmentIndex();
9288 uint64_t OffsetInSeg = Entry.segmentOffset();
9289 StringRef SegmentName = sectionTable.segmentName(SegIndex);
9290 StringRef SectionName = sectionTable.sectionName(SegIndex, OffsetInSeg);
9291 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
9292
9293 // Table lines look like: __DATA __nl_symbol_ptr 0x0000F00C pointer
Kevin Enderbyb28ed012014-10-29 21:28:24 +00009294 outs() << format("%-8s %-18s 0x%08" PRIX64 " %s\n",
9295 SegmentName.str().c_str(), SectionName.str().c_str(),
9296 Address, Entry.typeName().str().c_str());
Nick Kledzikac431442014-09-12 21:34:15 +00009297 }
9298}
Nick Kledzik56ebef42014-09-16 01:41:51 +00009299
9300static StringRef ordinalName(const object::MachOObjectFile *Obj, int Ordinal) {
9301 StringRef DylibName;
9302 switch (Ordinal) {
9303 case MachO::BIND_SPECIAL_DYLIB_SELF:
9304 return "this-image";
9305 case MachO::BIND_SPECIAL_DYLIB_MAIN_EXECUTABLE:
9306 return "main-executable";
9307 case MachO::BIND_SPECIAL_DYLIB_FLAT_LOOKUP:
9308 return "flat-namespace";
9309 default:
Nick Kledzikabd29872014-09-16 22:03:13 +00009310 if (Ordinal > 0) {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00009311 std::error_code EC =
9312 Obj->getLibraryShortNameByIndex(Ordinal - 1, DylibName);
Nick Kledzikabd29872014-09-16 22:03:13 +00009313 if (EC)
Nick Kledzik51d2c2b2014-10-14 23:29:38 +00009314 return "<<bad library ordinal>>";
Nick Kledzikabd29872014-09-16 22:03:13 +00009315 return DylibName;
9316 }
Nick Kledzik56ebef42014-09-16 01:41:51 +00009317 }
Nick Kledzikabd29872014-09-16 22:03:13 +00009318 return "<<unknown special ordinal>>";
Nick Kledzik56ebef42014-09-16 01:41:51 +00009319}
9320
9321//===----------------------------------------------------------------------===//
9322// bind table dumping
9323//===----------------------------------------------------------------------===//
9324
9325void llvm::printMachOBindTable(const object::MachOObjectFile *Obj) {
9326 // Build table of sections so names can used in final output.
9327 SegInfo sectionTable(Obj);
9328
Nick Kledzik5ffacc12014-09-30 00:19:58 +00009329 outs() << "segment section address type "
9330 "addend dylib symbol\n";
Nick Kledzik56ebef42014-09-16 01:41:51 +00009331 for (const llvm::object::MachOBindEntry &Entry : Obj->bindTable()) {
9332 uint32_t SegIndex = Entry.segmentIndex();
9333 uint64_t OffsetInSeg = Entry.segmentOffset();
9334 StringRef SegmentName = sectionTable.segmentName(SegIndex);
9335 StringRef SectionName = sectionTable.sectionName(SegIndex, OffsetInSeg);
9336 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
9337
9338 // Table lines look like:
9339 // __DATA __got 0x00012010 pointer 0 libSystem ___stack_chk_guard
Nick Kledzik5ffacc12014-09-30 00:19:58 +00009340 StringRef Attr;
Nick Kledzik56ebef42014-09-16 01:41:51 +00009341 if (Entry.flags() & MachO::BIND_SYMBOL_FLAGS_WEAK_IMPORT)
Nick Kledzik5ffacc12014-09-30 00:19:58 +00009342 Attr = " (weak_import)";
Kevin Enderbyb28ed012014-10-29 21:28:24 +00009343 outs() << left_justify(SegmentName, 8) << " "
Nick Kledzik5ffacc12014-09-30 00:19:58 +00009344 << left_justify(SectionName, 18) << " "
9345 << format_hex(Address, 10, true) << " "
9346 << left_justify(Entry.typeName(), 8) << " "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00009347 << format_decimal(Entry.addend(), 8) << " "
Nick Kledzik5ffacc12014-09-30 00:19:58 +00009348 << left_justify(ordinalName(Obj, Entry.ordinal()), 16) << " "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00009349 << Entry.symbolName() << Attr << "\n";
Nick Kledzik56ebef42014-09-16 01:41:51 +00009350 }
9351}
9352
9353//===----------------------------------------------------------------------===//
9354// lazy bind table dumping
9355//===----------------------------------------------------------------------===//
9356
9357void llvm::printMachOLazyBindTable(const object::MachOObjectFile *Obj) {
9358 // Build table of sections so names can used in final output.
9359 SegInfo sectionTable(Obj);
9360
Nick Kledzik5ffacc12014-09-30 00:19:58 +00009361 outs() << "segment section address "
9362 "dylib symbol\n";
Nick Kledzik56ebef42014-09-16 01:41:51 +00009363 for (const llvm::object::MachOBindEntry &Entry : Obj->lazyBindTable()) {
9364 uint32_t SegIndex = Entry.segmentIndex();
9365 uint64_t OffsetInSeg = Entry.segmentOffset();
9366 StringRef SegmentName = sectionTable.segmentName(SegIndex);
9367 StringRef SectionName = sectionTable.sectionName(SegIndex, OffsetInSeg);
9368 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
9369
9370 // Table lines look like:
9371 // __DATA __got 0x00012010 libSystem ___stack_chk_guard
Kevin Enderbyb28ed012014-10-29 21:28:24 +00009372 outs() << left_justify(SegmentName, 8) << " "
Nick Kledzik5ffacc12014-09-30 00:19:58 +00009373 << left_justify(SectionName, 18) << " "
9374 << format_hex(Address, 10, true) << " "
9375 << left_justify(ordinalName(Obj, Entry.ordinal()), 16) << " "
Nick Kledzik56ebef42014-09-16 01:41:51 +00009376 << Entry.symbolName() << "\n";
9377 }
9378}
9379
Nick Kledzik56ebef42014-09-16 01:41:51 +00009380//===----------------------------------------------------------------------===//
9381// weak bind table dumping
9382//===----------------------------------------------------------------------===//
9383
9384void llvm::printMachOWeakBindTable(const object::MachOObjectFile *Obj) {
9385 // Build table of sections so names can used in final output.
9386 SegInfo sectionTable(Obj);
9387
Nick Kledzik5ffacc12014-09-30 00:19:58 +00009388 outs() << "segment section address "
9389 "type addend symbol\n";
Nick Kledzik56ebef42014-09-16 01:41:51 +00009390 for (const llvm::object::MachOBindEntry &Entry : Obj->weakBindTable()) {
9391 // Strong symbols don't have a location to update.
9392 if (Entry.flags() & MachO::BIND_SYMBOL_FLAGS_NON_WEAK_DEFINITION) {
Nick Kledzik5ffacc12014-09-30 00:19:58 +00009393 outs() << " strong "
Nick Kledzik56ebef42014-09-16 01:41:51 +00009394 << Entry.symbolName() << "\n";
9395 continue;
9396 }
9397 uint32_t SegIndex = Entry.segmentIndex();
9398 uint64_t OffsetInSeg = Entry.segmentOffset();
9399 StringRef SegmentName = sectionTable.segmentName(SegIndex);
9400 StringRef SectionName = sectionTable.sectionName(SegIndex, OffsetInSeg);
9401 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
9402
9403 // Table lines look like:
9404 // __DATA __data 0x00001000 pointer 0 _foo
Kevin Enderbyb28ed012014-10-29 21:28:24 +00009405 outs() << left_justify(SegmentName, 8) << " "
Nick Kledzik5ffacc12014-09-30 00:19:58 +00009406 << left_justify(SectionName, 18) << " "
9407 << format_hex(Address, 10, true) << " "
9408 << left_justify(Entry.typeName(), 8) << " "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00009409 << format_decimal(Entry.addend(), 8) << " " << Entry.symbolName()
9410 << "\n";
Nick Kledzik56ebef42014-09-16 01:41:51 +00009411 }
9412}
9413
Kevin Enderby6f326ce2014-10-23 19:37:31 +00009414// get_dyld_bind_info_symbolname() is used for disassembly and passed an
9415// address, ReferenceValue, in the Mach-O file and looks in the dyld bind
9416// information for that address. If the address is found its binding symbol
9417// name is returned. If not nullptr is returned.
9418static const char *get_dyld_bind_info_symbolname(uint64_t ReferenceValue,
9419 struct DisassembleInfo *info) {
Kevin Enderby078be602014-10-23 19:53:12 +00009420 if (info->bindtable == nullptr) {
9421 info->bindtable = new (BindTable);
Kevin Enderby6f326ce2014-10-23 19:37:31 +00009422 SegInfo sectionTable(info->O);
9423 for (const llvm::object::MachOBindEntry &Entry : info->O->bindTable()) {
9424 uint32_t SegIndex = Entry.segmentIndex();
9425 uint64_t OffsetInSeg = Entry.segmentOffset();
Kevin Enderbyaf7c9d02015-10-09 16:48:44 +00009426 if (!sectionTable.isValidSegIndexAndOffset(SegIndex, OffsetInSeg))
9427 continue;
Kevin Enderby6f326ce2014-10-23 19:37:31 +00009428 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
9429 const char *SymbolName = nullptr;
9430 StringRef name = Entry.symbolName();
9431 if (!name.empty())
9432 SymbolName = name.data();
Kevin Enderby078be602014-10-23 19:53:12 +00009433 info->bindtable->push_back(std::make_pair(Address, SymbolName));
Kevin Enderby6f326ce2014-10-23 19:37:31 +00009434 }
9435 }
Kevin Enderby078be602014-10-23 19:53:12 +00009436 for (bind_table_iterator BI = info->bindtable->begin(),
9437 BE = info->bindtable->end();
Kevin Enderby6f326ce2014-10-23 19:37:31 +00009438 BI != BE; ++BI) {
9439 uint64_t Address = BI->first;
9440 if (ReferenceValue == Address) {
9441 const char *SymbolName = BI->second;
9442 return SymbolName;
9443 }
9444 }
9445 return nullptr;
9446}