blob: 6d4beb4378e003251db11535069c91593c5f92d3 [file] [log] [blame]
Benjamin Kramer43a772e2011-09-19 17:56:04 +00001//===-- MachODump.cpp - Object file dumping utility for llvm --------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the MachO-specific dumper for llvm-objdump.
11//
12//===----------------------------------------------------------------------===//
13
14#include "llvm-objdump.h"
Kevin Enderby98c9acc2014-09-16 18:00:57 +000015#include "llvm-c/Disassembler.h"
Benjamin Kramer43a772e2011-09-19 17:56:04 +000016#include "llvm/ADT/STLExtras.h"
Ahmed Bougachaaa790682013-05-24 01:07:04 +000017#include "llvm/ADT/StringExtras.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000018#include "llvm/ADT/Triple.h"
Zachary Turner264b5d92017-06-07 03:48:56 +000019#include "llvm/BinaryFormat/MachO.h"
Kevin Enderby04bf6932014-10-28 23:39:46 +000020#include "llvm/Config/config.h"
Zachary Turner6489d7b2015-04-23 17:37:47 +000021#include "llvm/DebugInfo/DIContext.h"
22#include "llvm/DebugInfo/DWARF/DWARFContext.h"
Rafael Espindolab940b662016-09-06 19:16:48 +000023#include "llvm/Demangle/Demangle.h"
Benjamin Kramer43a772e2011-09-19 17:56:04 +000024#include "llvm/MC/MCAsmInfo.h"
Lang Hamesa1bc0f52014-04-15 04:40:56 +000025#include "llvm/MC/MCContext.h"
Benjamin Kramerf57c1972016-01-26 16:44:37 +000026#include "llvm/MC/MCDisassembler/MCDisassembler.h"
Benjamin Kramer43a772e2011-09-19 17:56:04 +000027#include "llvm/MC/MCInst.h"
28#include "llvm/MC/MCInstPrinter.h"
Benjamin Kramer43a772e2011-09-19 17:56:04 +000029#include "llvm/MC/MCInstrDesc.h"
30#include "llvm/MC/MCInstrInfo.h"
Jim Grosbachfd93a592012-03-05 19:33:20 +000031#include "llvm/MC/MCRegisterInfo.h"
Benjamin Kramer43a772e2011-09-19 17:56:04 +000032#include "llvm/MC/MCSubtargetInfo.h"
Zachary Turner264b5d92017-06-07 03:48:56 +000033#include "llvm/Object/MachO.h"
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +000034#include "llvm/Object/MachOUniversal.h"
Rafael Espindola9b709252013-04-13 01:45:40 +000035#include "llvm/Support/Casting.h"
Benjamin Kramer43a772e2011-09-19 17:56:04 +000036#include "llvm/Support/CommandLine.h"
37#include "llvm/Support/Debug.h"
Tim Northover4bd286a2014-08-01 13:07:19 +000038#include "llvm/Support/Endian.h"
Benjamin Kramer43a772e2011-09-19 17:56:04 +000039#include "llvm/Support/Format.h"
Chandler Carruthd9903882015-01-14 11:23:27 +000040#include "llvm/Support/FormattedStream.h"
Benjamin Kramer43a772e2011-09-19 17:56:04 +000041#include "llvm/Support/GraphWriter.h"
Kevin Enderby9a509442015-01-27 21:28:24 +000042#include "llvm/Support/LEB128.h"
Benjamin Kramer43a772e2011-09-19 17:56:04 +000043#include "llvm/Support/MemoryBuffer.h"
44#include "llvm/Support/TargetRegistry.h"
45#include "llvm/Support/TargetSelect.h"
Kevin Enderby9873e2c2016-05-23 21:34:12 +000046#include "llvm/Support/ToolOutputFile.h"
Jonas Devliegheree787efd2018-11-11 22:12:04 +000047#include "llvm/Support/WithColor.h"
Benjamin Kramer43a772e2011-09-19 17:56:04 +000048#include "llvm/Support/raw_ostream.h"
Benjamin Kramer43a772e2011-09-19 17:56:04 +000049#include <algorithm>
50#include <cstring>
Rafael Espindolaa6e9c3e2014-06-12 17:38:55 +000051#include <system_error>
Kevin Enderby04bf6932014-10-28 23:39:46 +000052
Kevin Enderby9873e2c2016-05-23 21:34:12 +000053#ifdef HAVE_LIBXAR
54extern "C" {
55#include <xar/xar.h>
56}
57#endif
58
Benjamin Kramer43a772e2011-09-19 17:56:04 +000059using namespace llvm;
60using namespace object;
61
62static cl::opt<bool>
Kevin Enderbyb28ed012014-10-29 21:28:24 +000063 UseDbg("g",
64 cl::desc("Print line information from debug info if available"));
Benjamin Kramer699128e2011-09-21 01:13:19 +000065
Kevin Enderbyb28ed012014-10-29 21:28:24 +000066static cl::opt<std::string> DSYMFile("dsym",
67 cl::desc("Use .dSYM file for debug info"));
Benjamin Kramer699128e2011-09-21 01:13:19 +000068
Kevin Enderbyb28ed012014-10-29 21:28:24 +000069static cl::opt<bool> FullLeadingAddr("full-leading-addr",
70 cl::desc("Print full leading address"));
Kevin Enderbybf246f52014-09-24 23:08:22 +000071
Kevin Enderbyf9d60f02016-11-29 21:43:40 +000072static cl::opt<bool> NoLeadingHeaders("no-leading-headers",
73 cl::desc("Print no leading headers"));
74
Kevin Enderby13023a12015-01-15 23:19:11 +000075cl::opt<bool> llvm::UniversalHeaders("universal-headers",
76 cl::desc("Print Mach-O universal headers "
77 "(requires -macho)"));
78
Kevin Enderby131d1772015-01-09 19:22:37 +000079cl::opt<bool>
Kevin Enderby8972e482015-04-30 20:30:42 +000080 ArchiveMemberOffsets("archive-member-offsets",
81 cl::desc("Print the offset to each archive member for "
82 "Mach-O archives (requires -macho and "
83 "-archive-headers)"));
84
85cl::opt<bool>
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +000086 llvm::IndirectSymbols("indirect-symbols",
87 cl::desc("Print indirect symbol table for Mach-O "
88 "objects (requires -macho)"));
89
Kevin Enderby69fe98d2015-01-23 18:52:17 +000090cl::opt<bool>
91 llvm::DataInCode("data-in-code",
92 cl::desc("Print the data in code table for Mach-O objects "
93 "(requires -macho)"));
94
Kevin Enderby9a509442015-01-27 21:28:24 +000095cl::opt<bool>
96 llvm::LinkOptHints("link-opt-hints",
97 cl::desc("Print the linker optimization hints for "
98 "Mach-O objects (requires -macho)"));
99
Kevin Enderbycd66be52015-03-11 22:06:32 +0000100cl::opt<bool>
101 llvm::InfoPlist("info-plist",
102 cl::desc("Print the info plist section as strings for "
103 "Mach-O objects (requires -macho)"));
104
Kevin Enderbyf0640752015-03-13 17:56:32 +0000105cl::opt<bool>
Kevin Enderbybc847fa2015-03-16 20:08:09 +0000106 llvm::DylibsUsed("dylibs-used",
107 cl::desc("Print the shared libraries used for linked "
108 "Mach-O files (requires -macho)"));
109
110cl::opt<bool>
111 llvm::DylibId("dylib-id",
112 cl::desc("Print the shared library's id for the dylib Mach-O "
113 "file (requires -macho)"));
114
115cl::opt<bool>
Kevin Enderbyf0640752015-03-13 17:56:32 +0000116 llvm::NonVerbose("non-verbose",
117 cl::desc("Print the info for Mach-O objects in "
118 "non-verbose or numeric form (requires -macho)"));
119
Kevin Enderby0fc11822015-04-01 20:57:01 +0000120cl::opt<bool>
121 llvm::ObjcMetaData("objc-meta-data",
122 cl::desc("Print the Objective-C runtime meta data for "
123 "Mach-O files (requires -macho)"));
124
Kevin Enderby6a221752015-03-17 17:10:57 +0000125cl::opt<std::string> llvm::DisSymName(
126 "dis-symname",
Saleem Abdulrasoolec6a7742016-09-08 23:17:34 +0000127 cl::desc("disassemble just this symbol's instructions (requires -macho)"));
Kevin Enderby6a221752015-03-17 17:10:57 +0000128
Kevin Enderby8e29ec92015-03-17 22:26:11 +0000129static cl::opt<bool> NoSymbolicOperands(
130 "no-symbolic-operands",
131 cl::desc("do not symbolic operands when disassembling (requires -macho)"));
132
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +0000133static cl::list<std::string>
134 ArchFlags("arch", cl::desc("architecture(s) from a Mach-O file to dump"),
135 cl::ZeroOrMore);
Hans Wennborgcc9deb42015-09-29 18:02:48 +0000136
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +0000137bool ArchAll = false;
138
Kevin Enderbyec5ca032014-08-18 20:21:02 +0000139static std::string ThumbTripleName;
140
141static const Target *GetTarget(const MachOObjectFile *MachOObj,
142 const char **McpuDefault,
143 const Target **ThumbTarget) {
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000144 // Figure out the target triple.
Tim Northover9e8eb412016-04-22 23:21:13 +0000145 llvm::Triple TT(TripleName);
Cameron Zwarich88cc16a2012-02-03 06:35:22 +0000146 if (TripleName.empty()) {
Tim Northover9e8eb412016-04-22 23:21:13 +0000147 TT = MachOObj->getArchTriple(McpuDefault);
Cameron Zwarich88cc16a2012-02-03 06:35:22 +0000148 TripleName = TT.str();
Tim Northover9e8eb412016-04-22 23:21:13 +0000149 }
150
151 if (TT.getArch() == Triple::arm) {
152 // We've inferred a 32-bit ARM target from the object file. All MachO CPUs
153 // that support ARM are also capable of Thumb mode.
154 llvm::Triple ThumbTriple = TT;
155 std::string ThumbName = (Twine("thumb") + TT.getArchName().substr(3)).str();
156 ThumbTriple.setArchName(ThumbName);
Kevin Enderbyec5ca032014-08-18 20:21:02 +0000157 ThumbTripleName = ThumbTriple.str();
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000158 }
159
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000160 // Get the target specific parser.
161 std::string Error;
162 const Target *TheTarget = TargetRegistry::lookupTarget(TripleName, Error);
Kevin Enderbyec5ca032014-08-18 20:21:02 +0000163 if (TheTarget && ThumbTripleName.empty())
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000164 return TheTarget;
165
Kevin Enderbyec5ca032014-08-18 20:21:02 +0000166 *ThumbTarget = TargetRegistry::lookupTarget(ThumbTripleName, Error);
167 if (*ThumbTarget)
168 return TheTarget;
169
Jonas Devliegheree787efd2018-11-11 22:12:04 +0000170 WithColor::error(errs(), "llvm-objdump") << "unable to get target for '";
Kevin Enderbyec5ca032014-08-18 20:21:02 +0000171 if (!TheTarget)
172 errs() << TripleName;
173 else
174 errs() << ThumbTripleName;
175 errs() << "', see --version and --triple.\n";
Craig Toppere6cb63e2014-04-25 04:24:47 +0000176 return nullptr;
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000177}
178
Owen Andersond9243c42011-10-17 21:37:35 +0000179struct SymbolSorter {
180 bool operator()(const SymbolRef &A, const SymbolRef &B) {
Kevin Enderby7bd8d992016-05-02 20:28:12 +0000181 Expected<SymbolRef::Type> ATypeOrErr = A.getType();
Kevin Enderby844c4ac2016-11-15 23:07:41 +0000182 if (!ATypeOrErr)
183 report_error(A.getObject()->getFileName(), ATypeOrErr.takeError());
Kevin Enderby5afbc1c2016-03-23 20:27:00 +0000184 SymbolRef::Type AType = *ATypeOrErr;
Kevin Enderby7bd8d992016-05-02 20:28:12 +0000185 Expected<SymbolRef::Type> BTypeOrErr = B.getType();
Kevin Enderby844c4ac2016-11-15 23:07:41 +0000186 if (!BTypeOrErr)
187 report_error(B.getObject()->getFileName(), BTypeOrErr.takeError());
Kevin Enderby74f58d42016-03-23 21:45:21 +0000188 SymbolRef::Type BType = *BTypeOrErr;
Kevin Enderby5afbc1c2016-03-23 20:27:00 +0000189 uint64_t AAddr = (AType != SymbolRef::ST_Function) ? 0 : A.getValue();
190 uint64_t BAddr = (BType != SymbolRef::ST_Function) ? 0 : B.getValue();
Owen Andersond9243c42011-10-17 21:37:35 +0000191 return AAddr < BAddr;
192 }
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000193};
194
Kevin Enderby273ae012013-06-06 17:20:50 +0000195// Types for the storted data in code table that is built before disassembly
196// and the predicate function to sort them.
197typedef std::pair<uint64_t, DiceRef> DiceTableEntry;
198typedef std::vector<DiceTableEntry> DiceTable;
199typedef DiceTable::iterator dice_table_iterator;
200
Francis Ricci195a66f2017-10-06 15:54:20 +0000201#ifdef HAVE_LIBXAR
Francis Ricci6f942972017-10-06 15:33:28 +0000202namespace {
203struct ScopedXarFile {
204 xar_t xar;
Francis Ricci57d84522017-10-09 20:27:14 +0000205 ScopedXarFile(const char *filename, int32_t flags)
206 : xar(xar_open(filename, flags)) {}
Francis Ricci6f942972017-10-06 15:33:28 +0000207 ~ScopedXarFile() {
208 if (xar)
209 xar_close(xar);
210 }
211 ScopedXarFile(const ScopedXarFile &) = delete;
212 ScopedXarFile &operator=(const ScopedXarFile &) = delete;
213 operator xar_t() { return xar; }
214};
215
216struct ScopedXarIter {
217 xar_iter_t iter;
Francis Ricci57d84522017-10-09 20:27:14 +0000218 ScopedXarIter() : iter(xar_iter_new()) {}
Francis Ricci6f942972017-10-06 15:33:28 +0000219 ~ScopedXarIter() {
220 if (iter)
221 xar_iter_free(iter);
222 }
223 ScopedXarIter(const ScopedXarIter &) = delete;
224 ScopedXarIter &operator=(const ScopedXarIter &) = delete;
225 operator xar_iter_t() { return iter; }
226};
227} // namespace
Francis Ricci195a66f2017-10-06 15:54:20 +0000228#endif // defined(HAVE_LIBXAR)
Francis Ricci6f942972017-10-06 15:33:28 +0000229
Kevin Enderby930fdc72014-11-06 19:00:13 +0000230// This is used to search for a data in code table entry for the PC being
231// disassembled. The j parameter has the PC in j.first. A single data in code
232// table entry can cover many bytes for each of its Kind's. So if the offset,
233// aka the i.first value, of the data in code table entry plus its Length
234// covers the PC being searched for this will return true. If not it will
235// return false.
David Majnemerea9b8ee2014-11-04 08:41:48 +0000236static bool compareDiceTableEntries(const DiceTableEntry &i,
237 const DiceTableEntry &j) {
Kevin Enderby930fdc72014-11-06 19:00:13 +0000238 uint16_t Length;
239 i.second.getLength(Length);
240
241 return j.first >= i.first && j.first < i.first + Length;
Kevin Enderby273ae012013-06-06 17:20:50 +0000242}
243
Colin LeMahieufc32b1b2015-03-18 19:27:31 +0000244static uint64_t DumpDataInCode(const uint8_t *bytes, uint64_t Length,
Kevin Enderby930fdc72014-11-06 19:00:13 +0000245 unsigned short Kind) {
246 uint32_t Value, Size = 1;
Kevin Enderby273ae012013-06-06 17:20:50 +0000247
248 switch (Kind) {
Kevin Enderby930fdc72014-11-06 19:00:13 +0000249 default:
Charles Davis8bdfafd2013-09-01 04:28:48 +0000250 case MachO::DICE_KIND_DATA:
Kevin Enderby930fdc72014-11-06 19:00:13 +0000251 if (Length >= 4) {
252 if (!NoShowRawInsn)
Craig Topper0013be12015-09-21 05:32:41 +0000253 dumpBytes(makeArrayRef(bytes, 4), outs());
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000254 Value = bytes[3] << 24 | bytes[2] << 16 | bytes[1] << 8 | bytes[0];
Kevin Enderby273ae012013-06-06 17:20:50 +0000255 outs() << "\t.long " << Value;
Kevin Enderby930fdc72014-11-06 19:00:13 +0000256 Size = 4;
257 } else if (Length >= 2) {
258 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 Enderby273ae012013-06-06 17:20:50 +0000261 outs() << "\t.short " << Value;
Kevin Enderby930fdc72014-11-06 19:00:13 +0000262 Size = 2;
263 } else {
264 if (!NoShowRawInsn)
Craig Topper0013be12015-09-21 05:32:41 +0000265 dumpBytes(makeArrayRef(bytes, 2), outs());
Kevin Enderby273ae012013-06-06 17:20:50 +0000266 Value = bytes[0];
267 outs() << "\t.byte " << Value;
Kevin Enderby930fdc72014-11-06 19:00:13 +0000268 Size = 1;
Kevin Enderby273ae012013-06-06 17:20:50 +0000269 }
Kevin Enderby930fdc72014-11-06 19:00:13 +0000270 if (Kind == MachO::DICE_KIND_DATA)
271 outs() << "\t@ KIND_DATA\n";
272 else
273 outs() << "\t@ data in code kind = " << Kind << "\n";
Kevin Enderby273ae012013-06-06 17:20:50 +0000274 break;
Charles Davis8bdfafd2013-09-01 04:28:48 +0000275 case MachO::DICE_KIND_JUMP_TABLE8:
Kevin Enderby930fdc72014-11-06 19:00:13 +0000276 if (!NoShowRawInsn)
Craig Topper0013be12015-09-21 05:32:41 +0000277 dumpBytes(makeArrayRef(bytes, 1), outs());
Kevin Enderby273ae012013-06-06 17:20:50 +0000278 Value = bytes[0];
Kevin Enderby930fdc72014-11-06 19:00:13 +0000279 outs() << "\t.byte " << format("%3u", Value) << "\t@ KIND_JUMP_TABLE8\n";
280 Size = 1;
Kevin Enderby273ae012013-06-06 17:20:50 +0000281 break;
Charles Davis8bdfafd2013-09-01 04:28:48 +0000282 case MachO::DICE_KIND_JUMP_TABLE16:
Kevin Enderby930fdc72014-11-06 19:00:13 +0000283 if (!NoShowRawInsn)
Craig Topper0013be12015-09-21 05:32:41 +0000284 dumpBytes(makeArrayRef(bytes, 2), outs());
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000285 Value = bytes[1] << 8 | bytes[0];
Kevin Enderby930fdc72014-11-06 19:00:13 +0000286 outs() << "\t.short " << format("%5u", Value & 0xffff)
287 << "\t@ KIND_JUMP_TABLE16\n";
288 Size = 2;
Kevin Enderby273ae012013-06-06 17:20:50 +0000289 break;
Charles Davis8bdfafd2013-09-01 04:28:48 +0000290 case MachO::DICE_KIND_JUMP_TABLE32:
Kevin Enderby930fdc72014-11-06 19:00:13 +0000291 case MachO::DICE_KIND_ABS_JUMP_TABLE32:
292 if (!NoShowRawInsn)
Craig Topper0013be12015-09-21 05:32:41 +0000293 dumpBytes(makeArrayRef(bytes, 4), outs());
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000294 Value = bytes[3] << 24 | bytes[2] << 16 | bytes[1] << 8 | bytes[0];
Kevin Enderby930fdc72014-11-06 19:00:13 +0000295 outs() << "\t.long " << Value;
296 if (Kind == MachO::DICE_KIND_JUMP_TABLE32)
297 outs() << "\t@ KIND_JUMP_TABLE32\n";
298 else
299 outs() << "\t@ KIND_ABS_JUMP_TABLE32\n";
300 Size = 4;
Kevin Enderby273ae012013-06-06 17:20:50 +0000301 break;
302 }
Kevin Enderby930fdc72014-11-06 19:00:13 +0000303 return Size;
Kevin Enderby273ae012013-06-06 17:20:50 +0000304}
305
Alexey Samsonovd319c4f2015-06-03 22:19:36 +0000306static void getSectionsAndSymbols(MachOObjectFile *MachOObj,
Alexey Samsonov464d2e42014-03-17 07:28:19 +0000307 std::vector<SectionRef> &Sections,
308 std::vector<SymbolRef> &Symbols,
309 SmallVectorImpl<uint64_t> &FoundFns,
310 uint64_t &BaseSegmentAddress) {
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +0000311 for (const SymbolRef &Symbol : MachOObj->symbols()) {
Kevin Enderby81e8b7d2016-04-20 21:24:34 +0000312 Expected<StringRef> SymName = Symbol.getName();
Kevin Enderby844c4ac2016-11-15 23:07:41 +0000313 if (!SymName)
314 report_error(MachOObj->getFileName(), SymName.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +0000315 if (!SymName->startswith("ltmp"))
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +0000316 Symbols.push_back(Symbol);
317 }
Owen Andersond9243c42011-10-17 21:37:35 +0000318
Alexey Samsonov48803e52014-03-13 14:37:36 +0000319 for (const SectionRef &Section : MachOObj->sections()) {
Owen Andersond9243c42011-10-17 21:37:35 +0000320 StringRef SectName;
Alexey Samsonov48803e52014-03-13 14:37:36 +0000321 Section.getName(SectName);
322 Sections.push_back(Section);
Owen Andersond9243c42011-10-17 21:37:35 +0000323 }
324
Kevin Enderby273ae012013-06-06 17:20:50 +0000325 bool BaseSegmentAddressSet = false;
Alexey Samsonovd319c4f2015-06-03 22:19:36 +0000326 for (const auto &Command : MachOObj->load_commands()) {
Charles Davis8bdfafd2013-09-01 04:28:48 +0000327 if (Command.C.cmd == MachO::LC_FUNCTION_STARTS) {
Benjamin Kramer699128e2011-09-21 01:13:19 +0000328 // We found a function starts segment, parse the addresses for later
329 // consumption.
Charles Davis8bdfafd2013-09-01 04:28:48 +0000330 MachO::linkedit_data_command LLC =
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000331 MachOObj->getLinkeditDataLoadCommand(Command);
Benjamin Kramer699128e2011-09-21 01:13:19 +0000332
Charles Davis8bdfafd2013-09-01 04:28:48 +0000333 MachOObj->ReadULEB128s(LLC.dataoff, FoundFns);
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000334 } else if (Command.C.cmd == MachO::LC_SEGMENT) {
335 MachO::segment_command SLC = MachOObj->getSegmentLoadCommand(Command);
Charles Davis8bdfafd2013-09-01 04:28:48 +0000336 StringRef SegName = SLC.segname;
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000337 if (!BaseSegmentAddressSet && SegName != "__PAGEZERO") {
Kevin Enderby273ae012013-06-06 17:20:50 +0000338 BaseSegmentAddressSet = true;
Charles Davis8bdfafd2013-09-01 04:28:48 +0000339 BaseSegmentAddress = SLC.vmaddr;
Kevin Enderby273ae012013-06-06 17:20:50 +0000340 }
341 }
Benjamin Kramer8a529dc2011-09-21 22:16:43 +0000342 }
Benjamin Kramer699128e2011-09-21 01:13:19 +0000343}
344
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +0000345static void PrintIndirectSymbolTable(MachOObjectFile *O, bool verbose,
346 uint32_t n, uint32_t count,
347 uint32_t stride, uint64_t addr) {
348 MachO::dysymtab_command Dysymtab = O->getDysymtabLoadCommand();
349 uint32_t nindirectsyms = Dysymtab.nindirectsyms;
350 if (n > nindirectsyms)
351 outs() << " (entries start past the end of the indirect symbol "
352 "table) (reserved1 field greater than the table size)";
353 else if (n + count > nindirectsyms)
354 outs() << " (entries extends past the end of the indirect symbol "
355 "table)";
356 outs() << "\n";
357 uint32_t cputype = O->getHeader().cputype;
358 if (cputype & MachO::CPU_ARCH_ABI64)
359 outs() << "address index";
360 else
361 outs() << "address index";
362 if (verbose)
363 outs() << " name\n";
364 else
365 outs() << "\n";
366 for (uint32_t j = 0; j < count && n + j < nindirectsyms; j++) {
367 if (cputype & MachO::CPU_ARCH_ABI64)
368 outs() << format("0x%016" PRIx64, addr + j * stride) << " ";
369 else
Tim Northover43978372016-04-26 18:29:16 +0000370 outs() << format("0x%08" PRIx32, (uint32_t)addr + j * stride) << " ";
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +0000371 MachO::dysymtab_command Dysymtab = O->getDysymtabLoadCommand();
372 uint32_t indirect_symbol = O->getIndirectSymbolTableEntry(Dysymtab, n + j);
373 if (indirect_symbol == MachO::INDIRECT_SYMBOL_LOCAL) {
374 outs() << "LOCAL\n";
375 continue;
376 }
377 if (indirect_symbol ==
378 (MachO::INDIRECT_SYMBOL_LOCAL | MachO::INDIRECT_SYMBOL_ABS)) {
379 outs() << "LOCAL ABSOLUTE\n";
380 continue;
381 }
382 if (indirect_symbol == MachO::INDIRECT_SYMBOL_ABS) {
383 outs() << "ABSOLUTE\n";
384 continue;
385 }
386 outs() << format("%5u ", indirect_symbol);
Kevin Enderbyf0640752015-03-13 17:56:32 +0000387 if (verbose) {
388 MachO::symtab_command Symtab = O->getSymtabLoadCommand();
389 if (indirect_symbol < Symtab.nsyms) {
390 symbol_iterator Sym = O->getSymbolByIndex(indirect_symbol);
391 SymbolRef Symbol = *Sym;
Kevin Enderby81e8b7d2016-04-20 21:24:34 +0000392 Expected<StringRef> SymName = Symbol.getName();
Kevin Enderby844c4ac2016-11-15 23:07:41 +0000393 if (!SymName)
394 report_error(O->getFileName(), SymName.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +0000395 outs() << *SymName;
Kevin Enderbyf0640752015-03-13 17:56:32 +0000396 } else {
397 outs() << "?";
398 }
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +0000399 }
400 outs() << "\n";
401 }
402}
403
404static void PrintIndirectSymbols(MachOObjectFile *O, bool verbose) {
Alexey Samsonovd319c4f2015-06-03 22:19:36 +0000405 for (const auto &Load : O->load_commands()) {
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +0000406 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
407 MachO::segment_command_64 Seg = O->getSegment64LoadCommand(Load);
408 for (unsigned J = 0; J < Seg.nsects; ++J) {
409 MachO::section_64 Sec = O->getSection64(Load, J);
410 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
411 if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
412 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
413 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
414 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
415 section_type == MachO::S_SYMBOL_STUBS) {
416 uint32_t stride;
417 if (section_type == MachO::S_SYMBOL_STUBS)
418 stride = Sec.reserved2;
419 else
420 stride = 8;
421 if (stride == 0) {
422 outs() << "Can't print indirect symbols for (" << Sec.segname << ","
423 << Sec.sectname << ") "
424 << "(size of stubs in reserved2 field is zero)\n";
425 continue;
426 }
427 uint32_t count = Sec.size / stride;
428 outs() << "Indirect symbols for (" << Sec.segname << ","
429 << Sec.sectname << ") " << count << " entries";
430 uint32_t n = Sec.reserved1;
431 PrintIndirectSymbolTable(O, verbose, n, count, stride, Sec.addr);
432 }
433 }
434 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
435 MachO::segment_command Seg = O->getSegmentLoadCommand(Load);
436 for (unsigned J = 0; J < Seg.nsects; ++J) {
437 MachO::section Sec = O->getSection(Load, J);
438 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
439 if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
440 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
441 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
442 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
443 section_type == MachO::S_SYMBOL_STUBS) {
444 uint32_t stride;
445 if (section_type == MachO::S_SYMBOL_STUBS)
446 stride = Sec.reserved2;
447 else
448 stride = 4;
449 if (stride == 0) {
450 outs() << "Can't print indirect symbols for (" << Sec.segname << ","
451 << Sec.sectname << ") "
452 << "(size of stubs in reserved2 field is zero)\n";
453 continue;
454 }
455 uint32_t count = Sec.size / stride;
456 outs() << "Indirect symbols for (" << Sec.segname << ","
457 << Sec.sectname << ") " << count << " entries";
458 uint32_t n = Sec.reserved1;
459 PrintIndirectSymbolTable(O, verbose, n, count, stride, Sec.addr);
460 }
461 }
462 }
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +0000463 }
464}
465
Michael Trenta1703b12017-12-15 17:57:40 +0000466static void PrintRType(const uint64_t cputype, const unsigned r_type) {
467 static char const *generic_r_types[] = {
468 "VANILLA ", "PAIR ", "SECTDIF ", "PBLAPTR ", "LOCSDIF ", "TLV ",
469 " 6 (?) ", " 7 (?) ", " 8 (?) ", " 9 (?) ", " 10 (?) ", " 11 (?) ",
470 " 12 (?) ", " 13 (?) ", " 14 (?) ", " 15 (?) "
471 };
472 static char const *x86_64_r_types[] = {
473 "UNSIGND ", "SIGNED ", "BRANCH ", "GOT_LD ", "GOT ", "SUB ",
474 "SIGNED1 ", "SIGNED2 ", "SIGNED4 ", "TLV ", " 10 (?) ", " 11 (?) ",
475 " 12 (?) ", " 13 (?) ", " 14 (?) ", " 15 (?) "
476 };
477 static char const *arm_r_types[] = {
478 "VANILLA ", "PAIR ", "SECTDIFF", "LOCSDIF ", "PBLAPTR ",
479 "BR24 ", "T_BR22 ", "T_BR32 ", "HALF ", "HALFDIF ",
480 " 10 (?) ", " 11 (?) ", " 12 (?) ", " 13 (?) ", " 14 (?) ", " 15 (?) "
481 };
482 static char const *arm64_r_types[] = {
483 "UNSIGND ", "SUB ", "BR26 ", "PAGE21 ", "PAGOF12 ",
484 "GOTLDP ", "GOTLDPOF", "PTRTGOT ", "TLVLDP ", "TLVLDPOF",
485 "ADDEND ", " 11 (?) ", " 12 (?) ", " 13 (?) ", " 14 (?) ", " 15 (?) "
486 };
Jonas Devliegheree787efd2018-11-11 22:12:04 +0000487
Michael Trenta1703b12017-12-15 17:57:40 +0000488 if (r_type > 0xf){
489 outs() << format("%-7u", r_type) << " ";
490 return;
491 }
492 switch (cputype) {
493 case MachO::CPU_TYPE_I386:
494 outs() << generic_r_types[r_type];
495 break;
496 case MachO::CPU_TYPE_X86_64:
497 outs() << x86_64_r_types[r_type];
498 break;
499 case MachO::CPU_TYPE_ARM:
500 outs() << arm_r_types[r_type];
501 break;
502 case MachO::CPU_TYPE_ARM64:
503 outs() << arm64_r_types[r_type];
504 break;
505 default:
506 outs() << format("%-7u ", r_type);
507 }
508}
509
510static void PrintRLength(const uint64_t cputype, const unsigned r_type,
511 const unsigned r_length, const bool previous_arm_half){
512 if (cputype == MachO::CPU_TYPE_ARM &&
513 (r_type == llvm::MachO::ARM_RELOC_HALF ||
514 r_type == llvm::MachO::ARM_RELOC_HALF_SECTDIFF ||
515 previous_arm_half == true)) {
516 if ((r_length & 0x1) == 0)
517 outs() << "lo/";
518 else
519 outs() << "hi/";
520 if ((r_length & 0x1) == 0)
521 outs() << "arm ";
522 else
523 outs() << "thm ";
524 } else {
525 switch (r_length) {
526 case 0:
527 outs() << "byte ";
528 break;
529 case 1:
530 outs() << "word ";
531 break;
532 case 2:
533 outs() << "long ";
534 break;
535 case 3:
536 if (cputype == MachO::CPU_TYPE_X86_64)
537 outs() << "quad ";
538 else
539 outs() << format("?(%2d) ", r_length);
540 break;
541 default:
542 outs() << format("?(%2d) ", r_length);
543 }
544 }
545}
546
547static void PrintRelocationEntries(const MachOObjectFile *O,
548 const relocation_iterator Begin,
549 const relocation_iterator End,
550 const uint64_t cputype,
551 const bool verbose) {
552 const MachO::symtab_command Symtab = O->getSymtabLoadCommand();
553 bool previous_arm_half = false;
554 bool previous_sectdiff = false;
555 uint32_t sectdiff_r_type = 0;
Jonas Devliegheree787efd2018-11-11 22:12:04 +0000556
Michael Trenta1703b12017-12-15 17:57:40 +0000557 for (relocation_iterator Reloc = Begin; Reloc != End; ++Reloc) {
558 const DataRefImpl Rel = Reloc->getRawDataRefImpl();
559 const MachO::any_relocation_info RE = O->getRelocation(Rel);
560 const unsigned r_type = O->getAnyRelocationType(RE);
561 const bool r_scattered = O->isRelocationScattered(RE);
562 const unsigned r_pcrel = O->getAnyRelocationPCRel(RE);
563 const unsigned r_length = O->getAnyRelocationLength(RE);
564 const unsigned r_address = O->getAnyRelocationAddress(RE);
565 const bool r_extern = (r_scattered ? false :
566 O->getPlainRelocationExternal(RE));
567 const uint32_t r_value = (r_scattered ?
568 O->getScatteredRelocationValue(RE) : 0);
569 const unsigned r_symbolnum = (r_scattered ? 0 :
570 O->getPlainRelocationSymbolNum(RE));
Jonas Devliegheree787efd2018-11-11 22:12:04 +0000571
Michael Trenta1703b12017-12-15 17:57:40 +0000572 if (r_scattered && cputype != MachO::CPU_TYPE_X86_64) {
573 if (verbose) {
574 // scattered: address
575 if ((cputype == MachO::CPU_TYPE_I386 &&
576 r_type == llvm::MachO::GENERIC_RELOC_PAIR) ||
577 (cputype == MachO::CPU_TYPE_ARM &&
578 r_type == llvm::MachO::ARM_RELOC_PAIR))
579 outs() << " ";
580 else
581 outs() << format("%08x ", (unsigned int)r_address);
Jonas Devliegheree787efd2018-11-11 22:12:04 +0000582
Michael Trenta1703b12017-12-15 17:57:40 +0000583 // scattered: pcrel
584 if (r_pcrel)
585 outs() << "True ";
586 else
587 outs() << "False ";
Jonas Devliegheree787efd2018-11-11 22:12:04 +0000588
Michael Trenta1703b12017-12-15 17:57:40 +0000589 // scattered: length
590 PrintRLength(cputype, r_type, r_length, previous_arm_half);
Jonas Devliegheree787efd2018-11-11 22:12:04 +0000591
Michael Trenta1703b12017-12-15 17:57:40 +0000592 // scattered: extern & type
593 outs() << "n/a ";
594 PrintRType(cputype, r_type);
Jonas Devliegheree787efd2018-11-11 22:12:04 +0000595
Michael Trenta1703b12017-12-15 17:57:40 +0000596 // scattered: scattered & value
597 outs() << format("True 0x%08x", (unsigned int)r_value);
598 if (previous_sectdiff == false) {
599 if ((cputype == MachO::CPU_TYPE_ARM &&
600 r_type == llvm::MachO::ARM_RELOC_PAIR))
601 outs() << format(" half = 0x%04x ", (unsigned int)r_address);
602 }
603 else if (cputype == MachO::CPU_TYPE_ARM &&
604 sectdiff_r_type == llvm::MachO::ARM_RELOC_HALF_SECTDIFF)
605 outs() << format(" other_half = 0x%04x ", (unsigned int)r_address);
606 if ((cputype == MachO::CPU_TYPE_I386 &&
607 (r_type == llvm::MachO::GENERIC_RELOC_SECTDIFF ||
608 r_type == llvm::MachO::GENERIC_RELOC_LOCAL_SECTDIFF)) ||
609 (cputype == MachO::CPU_TYPE_ARM &&
610 (sectdiff_r_type == llvm::MachO::ARM_RELOC_SECTDIFF ||
611 sectdiff_r_type == llvm::MachO::ARM_RELOC_LOCAL_SECTDIFF ||
612 sectdiff_r_type == llvm::MachO::ARM_RELOC_HALF_SECTDIFF))) {
613 previous_sectdiff = true;
614 sectdiff_r_type = r_type;
615 }
616 else {
617 previous_sectdiff = false;
618 sectdiff_r_type = 0;
619 }
620 if (cputype == MachO::CPU_TYPE_ARM &&
621 (r_type == llvm::MachO::ARM_RELOC_HALF ||
622 r_type == llvm::MachO::ARM_RELOC_HALF_SECTDIFF))
623 previous_arm_half = true;
624 else
625 previous_arm_half = false;
626 outs() << "\n";
627 }
628 else {
629 // scattered: address pcrel length extern type scattered value
630 outs() << format("%08x %1d %-2d n/a %-7d 1 0x%08x\n",
631 (unsigned int)r_address, r_pcrel, r_length, r_type,
632 (unsigned int)r_value);
633 }
634 }
635 else {
636 if (verbose) {
637 // plain: address
638 if (cputype == MachO::CPU_TYPE_ARM &&
639 r_type == llvm::MachO::ARM_RELOC_PAIR)
640 outs() << " ";
641 else
642 outs() << format("%08x ", (unsigned int)r_address);
Jonas Devliegheree787efd2018-11-11 22:12:04 +0000643
Michael Trenta1703b12017-12-15 17:57:40 +0000644 // plain: pcrel
645 if (r_pcrel)
646 outs() << "True ";
647 else
648 outs() << "False ";
Jonas Devliegheree787efd2018-11-11 22:12:04 +0000649
Michael Trenta1703b12017-12-15 17:57:40 +0000650 // plain: length
651 PrintRLength(cputype, r_type, r_length, previous_arm_half);
Jonas Devliegheree787efd2018-11-11 22:12:04 +0000652
Michael Trenta1703b12017-12-15 17:57:40 +0000653 if (r_extern) {
654 // plain: extern & type & scattered
655 outs() << "True ";
656 PrintRType(cputype, r_type);
657 outs() << "False ";
Jonas Devliegheree787efd2018-11-11 22:12:04 +0000658
Michael Trenta1703b12017-12-15 17:57:40 +0000659 // plain: symbolnum/value
660 if (r_symbolnum > Symtab.nsyms)
661 outs() << format("?(%d)\n", r_symbolnum);
662 else {
663 SymbolRef Symbol = *O->getSymbolByIndex(r_symbolnum);
664 Expected<StringRef> SymNameNext = Symbol.getName();
665 const char *name = NULL;
666 if (SymNameNext)
667 name = SymNameNext->data();
668 if (name == NULL)
669 outs() << format("?(%d)\n", r_symbolnum);
670 else
671 outs() << name << "\n";
672 }
673 }
674 else {
675 // plain: extern & type & scattered
676 outs() << "False ";
677 PrintRType(cputype, r_type);
678 outs() << "False ";
Jonas Devliegheree787efd2018-11-11 22:12:04 +0000679
Michael Trenta1703b12017-12-15 17:57:40 +0000680 // plain: symbolnum/value
681 if (cputype == MachO::CPU_TYPE_ARM &&
682 r_type == llvm::MachO::ARM_RELOC_PAIR)
683 outs() << format("other_half = 0x%04x\n", (unsigned int)r_address);
684 else if (cputype == MachO::CPU_TYPE_ARM64 &&
685 r_type == llvm::MachO::ARM64_RELOC_ADDEND)
686 outs() << format("addend = 0x%06x\n", (unsigned int)r_symbolnum);
687 else {
688 outs() << format("%d ", r_symbolnum);
689 if (r_symbolnum == llvm::MachO::R_ABS)
690 outs() << "R_ABS\n";
691 else {
692 // in this case, r_symbolnum is actually a 1-based section number
693 uint32_t nsects = O->section_end()->getRawDataRefImpl().d.a;
694 if (r_symbolnum > 0 && r_symbolnum <= nsects) {
695 llvm::object::DataRefImpl DRI;
696 DRI.d.a = r_symbolnum-1;
697 StringRef SegName = O->getSectionFinalSegmentName(DRI);
698 StringRef SectName;
699 if (O->getSectionName(DRI, SectName))
700 outs() << "(?,?)\n";
701 else
702 outs() << "(" << SegName << "," << SectName << ")\n";
703 }
704 else {
705 outs() << "(?,?)\n";
706 }
707 }
708 }
709 }
710 if (cputype == MachO::CPU_TYPE_ARM &&
711 (r_type == llvm::MachO::ARM_RELOC_HALF ||
712 r_type == llvm::MachO::ARM_RELOC_HALF_SECTDIFF))
713 previous_arm_half = true;
714 else
715 previous_arm_half = false;
716 }
717 else {
718 // plain: address pcrel length extern type scattered symbolnum/section
719 outs() << format("%08x %1d %-2d %1d %-7d 0 %d\n",
720 (unsigned int)r_address, r_pcrel, r_length, r_extern,
721 r_type, r_symbolnum);
722 }
723 }
724 }
725}
726
727static void PrintRelocations(const MachOObjectFile *O, const bool verbose) {
728 const uint64_t cputype = O->getHeader().cputype;
729 const MachO::dysymtab_command Dysymtab = O->getDysymtabLoadCommand();
730 if (Dysymtab.nextrel != 0) {
731 outs() << "External relocation information " << Dysymtab.nextrel
732 << " entries";
733 outs() << "\naddress pcrel length extern type scattered "
734 "symbolnum/value\n";
735 PrintRelocationEntries(O, O->extrel_begin(), O->extrel_end(), cputype,
736 verbose);
737 }
738 if (Dysymtab.nlocrel != 0) {
739 outs() << format("Local relocation information %u entries",
740 Dysymtab.nlocrel);
741 outs() << "\naddress pcrel length extern type scattered "
742 "symbolnum/value\n";
743 PrintRelocationEntries(O, O->locrel_begin(), O->locrel_end(), cputype,
744 verbose);
745 }
746 for (const auto &Load : O->load_commands()) {
747 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
748 const MachO::segment_command_64 Seg = O->getSegment64LoadCommand(Load);
749 for (unsigned J = 0; J < Seg.nsects; ++J) {
750 const MachO::section_64 Sec = O->getSection64(Load, J);
751 if (Sec.nreloc != 0) {
752 DataRefImpl DRI;
753 DRI.d.a = J;
754 const StringRef SegName = O->getSectionFinalSegmentName(DRI);
755 StringRef SectName;
756 if (O->getSectionName(DRI, SectName))
757 outs() << "Relocation information (" << SegName << ",?) "
758 << format("%u entries", Sec.nreloc);
759 else
760 outs() << "Relocation information (" << SegName << ","
761 << SectName << format(") %u entries", Sec.nreloc);
762 outs() << "\naddress pcrel length extern type scattered "
763 "symbolnum/value\n";
764 PrintRelocationEntries(O, O->section_rel_begin(DRI),
765 O->section_rel_end(DRI), cputype, verbose);
766 }
767 }
768 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
769 const MachO::segment_command Seg = O->getSegmentLoadCommand(Load);
770 for (unsigned J = 0; J < Seg.nsects; ++J) {
771 const MachO::section Sec = O->getSection(Load, J);
772 if (Sec.nreloc != 0) {
773 DataRefImpl DRI;
774 DRI.d.a = J;
775 const StringRef SegName = O->getSectionFinalSegmentName(DRI);
776 StringRef SectName;
777 if (O->getSectionName(DRI, SectName))
778 outs() << "Relocation information (" << SegName << ",?) "
779 << format("%u entries", Sec.nreloc);
780 else
781 outs() << "Relocation information (" << SegName << ","
782 << SectName << format(") %u entries", Sec.nreloc);
783 outs() << "\naddress pcrel length extern type scattered "
784 "symbolnum/value\n";
785 PrintRelocationEntries(O, O->section_rel_begin(DRI),
786 O->section_rel_end(DRI), cputype, verbose);
787 }
788 }
789 }
790 }
791}
792
Kevin Enderby69fe98d2015-01-23 18:52:17 +0000793static void PrintDataInCodeTable(MachOObjectFile *O, bool verbose) {
794 MachO::linkedit_data_command DIC = O->getDataInCodeLoadCommand();
795 uint32_t nentries = DIC.datasize / sizeof(struct MachO::data_in_code_entry);
796 outs() << "Data in code table (" << nentries << " entries)\n";
797 outs() << "offset length kind\n";
798 for (dice_iterator DI = O->begin_dices(), DE = O->end_dices(); DI != DE;
799 ++DI) {
800 uint32_t Offset;
801 DI->getOffset(Offset);
802 outs() << format("0x%08" PRIx32, Offset) << " ";
803 uint16_t Length;
804 DI->getLength(Length);
805 outs() << format("%6u", Length) << " ";
806 uint16_t Kind;
807 DI->getKind(Kind);
808 if (verbose) {
809 switch (Kind) {
810 case MachO::DICE_KIND_DATA:
811 outs() << "DATA";
812 break;
813 case MachO::DICE_KIND_JUMP_TABLE8:
814 outs() << "JUMP_TABLE8";
815 break;
816 case MachO::DICE_KIND_JUMP_TABLE16:
817 outs() << "JUMP_TABLE16";
818 break;
819 case MachO::DICE_KIND_JUMP_TABLE32:
820 outs() << "JUMP_TABLE32";
821 break;
822 case MachO::DICE_KIND_ABS_JUMP_TABLE32:
823 outs() << "ABS_JUMP_TABLE32";
824 break;
825 default:
826 outs() << format("0x%04" PRIx32, Kind);
827 break;
828 }
829 } else
830 outs() << format("0x%04" PRIx32, Kind);
831 outs() << "\n";
832 }
833}
834
Kevin Enderby9a509442015-01-27 21:28:24 +0000835static void PrintLinkOptHints(MachOObjectFile *O) {
836 MachO::linkedit_data_command LohLC = O->getLinkOptHintsLoadCommand();
837 const char *loh = O->getData().substr(LohLC.dataoff, 1).data();
838 uint32_t nloh = LohLC.datasize;
839 outs() << "Linker optimiztion hints (" << nloh << " total bytes)\n";
840 for (uint32_t i = 0; i < nloh;) {
841 unsigned n;
842 uint64_t identifier = decodeULEB128((const uint8_t *)(loh + i), &n);
843 i += n;
844 outs() << " identifier " << identifier << " ";
845 if (i >= nloh)
846 return;
847 switch (identifier) {
848 case 1:
849 outs() << "AdrpAdrp\n";
850 break;
851 case 2:
852 outs() << "AdrpLdr\n";
853 break;
854 case 3:
855 outs() << "AdrpAddLdr\n";
856 break;
857 case 4:
858 outs() << "AdrpLdrGotLdr\n";
859 break;
860 case 5:
861 outs() << "AdrpAddStr\n";
862 break;
863 case 6:
864 outs() << "AdrpLdrGotStr\n";
865 break;
866 case 7:
867 outs() << "AdrpAdd\n";
868 break;
869 case 8:
870 outs() << "AdrpLdrGot\n";
871 break;
872 default:
873 outs() << "Unknown identifier value\n";
874 break;
875 }
876 uint64_t narguments = decodeULEB128((const uint8_t *)(loh + i), &n);
877 i += n;
878 outs() << " narguments " << narguments << "\n";
879 if (i >= nloh)
880 return;
881
882 for (uint32_t j = 0; j < narguments; j++) {
883 uint64_t value = decodeULEB128((const uint8_t *)(loh + i), &n);
884 i += n;
885 outs() << "\tvalue " << format("0x%" PRIx64, value) << "\n";
886 if (i >= nloh)
887 return;
888 }
889 }
890}
891
Kevin Enderbybc847fa2015-03-16 20:08:09 +0000892static void PrintDylibs(MachOObjectFile *O, bool JustId) {
Alexey Samsonovd319c4f2015-06-03 22:19:36 +0000893 unsigned Index = 0;
894 for (const auto &Load : O->load_commands()) {
Kevin Enderbybc847fa2015-03-16 20:08:09 +0000895 if ((JustId && Load.C.cmd == MachO::LC_ID_DYLIB) ||
896 (!JustId && (Load.C.cmd == MachO::LC_ID_DYLIB ||
897 Load.C.cmd == MachO::LC_LOAD_DYLIB ||
898 Load.C.cmd == MachO::LC_LOAD_WEAK_DYLIB ||
899 Load.C.cmd == MachO::LC_REEXPORT_DYLIB ||
900 Load.C.cmd == MachO::LC_LAZY_LOAD_DYLIB ||
901 Load.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB))) {
902 MachO::dylib_command dl = O->getDylibIDLoadCommand(Load);
903 if (dl.dylib.name < dl.cmdsize) {
904 const char *p = (const char *)(Load.Ptr) + dl.dylib.name;
905 if (JustId)
906 outs() << p << "\n";
907 else {
908 outs() << "\t" << p;
909 outs() << " (compatibility version "
910 << ((dl.dylib.compatibility_version >> 16) & 0xffff) << "."
911 << ((dl.dylib.compatibility_version >> 8) & 0xff) << "."
912 << (dl.dylib.compatibility_version & 0xff) << ",";
913 outs() << " current version "
914 << ((dl.dylib.current_version >> 16) & 0xffff) << "."
915 << ((dl.dylib.current_version >> 8) & 0xff) << "."
916 << (dl.dylib.current_version & 0xff) << ")\n";
917 }
918 } else {
919 outs() << "\tBad offset (" << dl.dylib.name << ") for name of ";
920 if (Load.C.cmd == MachO::LC_ID_DYLIB)
921 outs() << "LC_ID_DYLIB ";
922 else if (Load.C.cmd == MachO::LC_LOAD_DYLIB)
923 outs() << "LC_LOAD_DYLIB ";
924 else if (Load.C.cmd == MachO::LC_LOAD_WEAK_DYLIB)
925 outs() << "LC_LOAD_WEAK_DYLIB ";
926 else if (Load.C.cmd == MachO::LC_LAZY_LOAD_DYLIB)
927 outs() << "LC_LAZY_LOAD_DYLIB ";
928 else if (Load.C.cmd == MachO::LC_REEXPORT_DYLIB)
929 outs() << "LC_REEXPORT_DYLIB ";
930 else if (Load.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB)
931 outs() << "LC_LOAD_UPWARD_DYLIB ";
932 else
933 outs() << "LC_??? ";
Alexey Samsonovd319c4f2015-06-03 22:19:36 +0000934 outs() << "command " << Index++ << "\n";
Kevin Enderbybc847fa2015-03-16 20:08:09 +0000935 }
936 }
Kevin Enderbybc847fa2015-03-16 20:08:09 +0000937 }
938}
939
Kevin Enderbyf6d25852015-01-31 00:37:11 +0000940typedef DenseMap<uint64_t, StringRef> SymbolAddressMap;
941
942static void CreateSymbolAddressMap(MachOObjectFile *O,
943 SymbolAddressMap *AddrMap) {
944 // Create a map of symbol addresses to symbol names.
945 for (const SymbolRef &Symbol : O->symbols()) {
Kevin Enderby7bd8d992016-05-02 20:28:12 +0000946 Expected<SymbolRef::Type> STOrErr = Symbol.getType();
Kevin Enderby844c4ac2016-11-15 23:07:41 +0000947 if (!STOrErr)
948 report_error(O->getFileName(), STOrErr.takeError());
Kevin Enderby5afbc1c2016-03-23 20:27:00 +0000949 SymbolRef::Type ST = *STOrErr;
Kevin Enderbyf6d25852015-01-31 00:37:11 +0000950 if (ST == SymbolRef::ST_Function || ST == SymbolRef::ST_Data ||
951 ST == SymbolRef::ST_Other) {
Rafael Espindoladea00162015-07-03 17:44:18 +0000952 uint64_t Address = Symbol.getValue();
Kevin Enderby81e8b7d2016-04-20 21:24:34 +0000953 Expected<StringRef> SymNameOrErr = Symbol.getName();
Kevin Enderby844c4ac2016-11-15 23:07:41 +0000954 if (!SymNameOrErr)
955 report_error(O->getFileName(), SymNameOrErr.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +0000956 StringRef SymName = *SymNameOrErr;
Kevin Enderby846c0002015-04-16 17:19:59 +0000957 if (!SymName.startswith(".objc"))
958 (*AddrMap)[Address] = SymName;
Kevin Enderbyf6d25852015-01-31 00:37:11 +0000959 }
960 }
961}
962
963// GuessSymbolName is passed the address of what might be a symbol and a
964// pointer to the SymbolAddressMap. It returns the name of a symbol
965// with that address or nullptr if no symbol is found with that address.
966static const char *GuessSymbolName(uint64_t value, SymbolAddressMap *AddrMap) {
967 const char *SymbolName = nullptr;
968 // A DenseMap can't lookup up some values.
969 if (value != 0xffffffffffffffffULL && value != 0xfffffffffffffffeULL) {
970 StringRef name = AddrMap->lookup(value);
971 if (!name.empty())
972 SymbolName = name.data();
973 }
974 return SymbolName;
975}
976
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000977static void DumpCstringChar(const char c) {
978 char p[2];
979 p[0] = c;
980 p[1] = '\0';
981 outs().write_escaped(p);
982}
983
Kevin Enderby10ba0412015-02-04 21:38:42 +0000984static void DumpCstringSection(MachOObjectFile *O, const char *sect,
985 uint32_t sect_size, uint64_t sect_addr,
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000986 bool print_addresses) {
Kevin Enderby10ba0412015-02-04 21:38:42 +0000987 for (uint32_t i = 0; i < sect_size; i++) {
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000988 if (print_addresses) {
989 if (O->is64Bit())
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000990 outs() << format("%016" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000991 else
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000992 outs() << format("%08" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +0000993 }
Kevin Enderby578fe5a2015-02-17 21:35:48 +0000994 for (; i < sect_size && sect[i] != '\0'; i++)
995 DumpCstringChar(sect[i]);
Kevin Enderby10ba0412015-02-04 21:38:42 +0000996 if (i < sect_size && sect[i] == '\0')
997 outs() << "\n";
998 }
999}
1000
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001001static void DumpLiteral4(uint32_t l, float f) {
1002 outs() << format("0x%08" PRIx32, l);
1003 if ((l & 0x7f800000) != 0x7f800000)
1004 outs() << format(" (%.16e)\n", f);
1005 else {
1006 if (l == 0x7f800000)
1007 outs() << " (+Infinity)\n";
1008 else if (l == 0xff800000)
1009 outs() << " (-Infinity)\n";
1010 else if ((l & 0x00400000) == 0x00400000)
1011 outs() << " (non-signaling Not-a-Number)\n";
1012 else
1013 outs() << " (signaling Not-a-Number)\n";
1014 }
1015}
1016
1017static void DumpLiteral4Section(MachOObjectFile *O, const char *sect,
1018 uint32_t sect_size, uint64_t sect_addr,
1019 bool print_addresses) {
1020 for (uint32_t i = 0; i < sect_size; i += sizeof(float)) {
1021 if (print_addresses) {
1022 if (O->is64Bit())
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001023 outs() << format("%016" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001024 else
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001025 outs() << format("%08" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001026 }
1027 float f;
1028 memcpy(&f, sect + i, sizeof(float));
1029 if (O->isLittleEndian() != sys::IsLittleEndianHost)
1030 sys::swapByteOrder(f);
1031 uint32_t l;
1032 memcpy(&l, sect + i, sizeof(uint32_t));
1033 if (O->isLittleEndian() != sys::IsLittleEndianHost)
1034 sys::swapByteOrder(l);
1035 DumpLiteral4(l, f);
1036 }
1037}
1038
1039static void DumpLiteral8(MachOObjectFile *O, uint32_t l0, uint32_t l1,
1040 double d) {
1041 outs() << format("0x%08" PRIx32, l0) << " " << format("0x%08" PRIx32, l1);
1042 uint32_t Hi, Lo;
Davide Italianob627d9f2015-12-12 21:50:11 +00001043 Hi = (O->isLittleEndian()) ? l1 : l0;
1044 Lo = (O->isLittleEndian()) ? l0 : l1;
1045
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001046 // Hi is the high word, so this is equivalent to if(isfinite(d))
1047 if ((Hi & 0x7ff00000) != 0x7ff00000)
1048 outs() << format(" (%.16e)\n", d);
1049 else {
1050 if (Hi == 0x7ff00000 && Lo == 0)
1051 outs() << " (+Infinity)\n";
1052 else if (Hi == 0xfff00000 && Lo == 0)
1053 outs() << " (-Infinity)\n";
1054 else if ((Hi & 0x00080000) == 0x00080000)
1055 outs() << " (non-signaling Not-a-Number)\n";
1056 else
1057 outs() << " (signaling Not-a-Number)\n";
1058 }
1059}
1060
1061static void DumpLiteral8Section(MachOObjectFile *O, const char *sect,
1062 uint32_t sect_size, uint64_t sect_addr,
1063 bool print_addresses) {
1064 for (uint32_t i = 0; i < sect_size; i += sizeof(double)) {
1065 if (print_addresses) {
1066 if (O->is64Bit())
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001067 outs() << format("%016" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001068 else
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001069 outs() << format("%08" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001070 }
1071 double d;
1072 memcpy(&d, sect + i, sizeof(double));
1073 if (O->isLittleEndian() != sys::IsLittleEndianHost)
1074 sys::swapByteOrder(d);
1075 uint32_t l0, l1;
1076 memcpy(&l0, sect + i, sizeof(uint32_t));
1077 memcpy(&l1, sect + i + sizeof(uint32_t), sizeof(uint32_t));
1078 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
1079 sys::swapByteOrder(l0);
1080 sys::swapByteOrder(l1);
1081 }
1082 DumpLiteral8(O, l0, l1, d);
1083 }
1084}
1085
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001086static void DumpLiteral16(uint32_t l0, uint32_t l1, uint32_t l2, uint32_t l3) {
1087 outs() << format("0x%08" PRIx32, l0) << " ";
1088 outs() << format("0x%08" PRIx32, l1) << " ";
1089 outs() << format("0x%08" PRIx32, l2) << " ";
1090 outs() << format("0x%08" PRIx32, l3) << "\n";
1091}
1092
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001093static void DumpLiteral16Section(MachOObjectFile *O, const char *sect,
1094 uint32_t sect_size, uint64_t sect_addr,
1095 bool print_addresses) {
1096 for (uint32_t i = 0; i < sect_size; i += 16) {
1097 if (print_addresses) {
1098 if (O->is64Bit())
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001099 outs() << format("%016" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001100 else
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001101 outs() << format("%08" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001102 }
1103 uint32_t l0, l1, l2, l3;
1104 memcpy(&l0, sect + i, sizeof(uint32_t));
1105 memcpy(&l1, sect + i + sizeof(uint32_t), sizeof(uint32_t));
1106 memcpy(&l2, sect + i + 2 * sizeof(uint32_t), sizeof(uint32_t));
1107 memcpy(&l3, sect + i + 3 * sizeof(uint32_t), sizeof(uint32_t));
1108 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
1109 sys::swapByteOrder(l0);
1110 sys::swapByteOrder(l1);
1111 sys::swapByteOrder(l2);
1112 sys::swapByteOrder(l3);
1113 }
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001114 DumpLiteral16(l0, l1, l2, l3);
1115 }
1116}
1117
1118static void DumpLiteralPointerSection(MachOObjectFile *O,
1119 const SectionRef &Section,
1120 const char *sect, uint32_t sect_size,
1121 uint64_t sect_addr,
1122 bool print_addresses) {
1123 // Collect the literal sections in this Mach-O file.
1124 std::vector<SectionRef> LiteralSections;
1125 for (const SectionRef &Section : O->sections()) {
1126 DataRefImpl Ref = Section.getRawDataRefImpl();
1127 uint32_t section_type;
1128 if (O->is64Bit()) {
1129 const MachO::section_64 Sec = O->getSection64(Ref);
1130 section_type = Sec.flags & MachO::SECTION_TYPE;
1131 } else {
1132 const MachO::section Sec = O->getSection(Ref);
1133 section_type = Sec.flags & MachO::SECTION_TYPE;
1134 }
1135 if (section_type == MachO::S_CSTRING_LITERALS ||
1136 section_type == MachO::S_4BYTE_LITERALS ||
1137 section_type == MachO::S_8BYTE_LITERALS ||
1138 section_type == MachO::S_16BYTE_LITERALS)
1139 LiteralSections.push_back(Section);
1140 }
1141
1142 // Set the size of the literal pointer.
1143 uint32_t lp_size = O->is64Bit() ? 8 : 4;
1144
Eric Christopher572e03a2015-06-19 01:53:21 +00001145 // Collect the external relocation symbols for the literal pointers.
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001146 std::vector<std::pair<uint64_t, SymbolRef>> Relocs;
1147 for (const RelocationRef &Reloc : Section.relocations()) {
1148 DataRefImpl Rel;
1149 MachO::any_relocation_info RE;
1150 bool isExtern = false;
1151 Rel = Reloc.getRawDataRefImpl();
1152 RE = O->getRelocation(Rel);
1153 isExtern = O->getPlainRelocationExternal(RE);
1154 if (isExtern) {
Rafael Espindola96d071c2015-06-29 23:29:12 +00001155 uint64_t RelocOffset = Reloc.getOffset();
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001156 symbol_iterator RelocSym = Reloc.getSymbol();
1157 Relocs.push_back(std::make_pair(RelocOffset, *RelocSym));
1158 }
1159 }
1160 array_pod_sort(Relocs.begin(), Relocs.end());
1161
1162 // Dump each literal pointer.
1163 for (uint32_t i = 0; i < sect_size; i += lp_size) {
1164 if (print_addresses) {
1165 if (O->is64Bit())
1166 outs() << format("%016" PRIx64, sect_addr + i) << " ";
1167 else
1168 outs() << format("%08" PRIx64, sect_addr + i) << " ";
1169 }
1170 uint64_t lp;
1171 if (O->is64Bit()) {
1172 memcpy(&lp, sect + i, sizeof(uint64_t));
1173 if (O->isLittleEndian() != sys::IsLittleEndianHost)
1174 sys::swapByteOrder(lp);
1175 } else {
1176 uint32_t li;
1177 memcpy(&li, sect + i, sizeof(uint32_t));
1178 if (O->isLittleEndian() != sys::IsLittleEndianHost)
1179 sys::swapByteOrder(li);
1180 lp = li;
1181 }
1182
1183 // First look for an external relocation entry for this literal pointer.
David Majnemer42531262016-08-12 03:55:06 +00001184 auto Reloc = find_if(Relocs, [&](const std::pair<uint64_t, SymbolRef> &P) {
1185 return P.first == i;
1186 });
David Blaikie33dd45d02015-03-23 18:39:02 +00001187 if (Reloc != Relocs.end()) {
1188 symbol_iterator RelocSym = Reloc->second;
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00001189 Expected<StringRef> SymName = RelocSym->getName();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00001190 if (!SymName)
1191 report_error(O->getFileName(), SymName.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00001192 outs() << "external relocation entry for symbol:" << *SymName << "\n";
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001193 continue;
David Blaikie33dd45d02015-03-23 18:39:02 +00001194 }
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001195
1196 // For local references see what the section the literal pointer points to.
David Majnemer562e8292016-08-12 00:18:03 +00001197 auto Sect = find_if(LiteralSections, [&](const SectionRef &R) {
1198 return lp >= R.getAddress() && lp < R.getAddress() + R.getSize();
1199 });
David Blaikie33dd45d02015-03-23 18:39:02 +00001200 if (Sect == LiteralSections.end()) {
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001201 outs() << format("0x%" PRIx64, lp) << " (not in a literal section)\n";
David Blaikie33dd45d02015-03-23 18:39:02 +00001202 continue;
1203 }
1204
1205 uint64_t SectAddress = Sect->getAddress();
1206 uint64_t SectSize = Sect->getSize();
1207
1208 StringRef SectName;
1209 Sect->getName(SectName);
1210 DataRefImpl Ref = Sect->getRawDataRefImpl();
1211 StringRef SegmentName = O->getSectionFinalSegmentName(Ref);
1212 outs() << SegmentName << ":" << SectName << ":";
1213
1214 uint32_t section_type;
1215 if (O->is64Bit()) {
1216 const MachO::section_64 Sec = O->getSection64(Ref);
1217 section_type = Sec.flags & MachO::SECTION_TYPE;
1218 } else {
1219 const MachO::section Sec = O->getSection(Ref);
1220 section_type = Sec.flags & MachO::SECTION_TYPE;
1221 }
1222
1223 StringRef BytesStr;
1224 Sect->getContents(BytesStr);
1225 const char *Contents = reinterpret_cast<const char *>(BytesStr.data());
1226
1227 switch (section_type) {
1228 case MachO::S_CSTRING_LITERALS:
1229 for (uint64_t i = lp - SectAddress; i < SectSize && Contents[i] != '\0';
1230 i++) {
1231 DumpCstringChar(Contents[i]);
1232 }
1233 outs() << "\n";
1234 break;
1235 case MachO::S_4BYTE_LITERALS:
1236 float f;
1237 memcpy(&f, Contents + (lp - SectAddress), sizeof(float));
1238 uint32_t l;
1239 memcpy(&l, Contents + (lp - SectAddress), sizeof(uint32_t));
1240 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
1241 sys::swapByteOrder(f);
1242 sys::swapByteOrder(l);
1243 }
1244 DumpLiteral4(l, f);
1245 break;
1246 case MachO::S_8BYTE_LITERALS: {
1247 double d;
1248 memcpy(&d, Contents + (lp - SectAddress), sizeof(double));
1249 uint32_t l0, l1;
1250 memcpy(&l0, Contents + (lp - SectAddress), sizeof(uint32_t));
1251 memcpy(&l1, Contents + (lp - SectAddress) + sizeof(uint32_t),
1252 sizeof(uint32_t));
1253 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
1254 sys::swapByteOrder(f);
1255 sys::swapByteOrder(l0);
1256 sys::swapByteOrder(l1);
1257 }
1258 DumpLiteral8(O, l0, l1, d);
1259 break;
1260 }
1261 case MachO::S_16BYTE_LITERALS: {
1262 uint32_t l0, l1, l2, l3;
1263 memcpy(&l0, Contents + (lp - SectAddress), sizeof(uint32_t));
1264 memcpy(&l1, Contents + (lp - SectAddress) + sizeof(uint32_t),
1265 sizeof(uint32_t));
1266 memcpy(&l2, Contents + (lp - SectAddress) + 2 * sizeof(uint32_t),
1267 sizeof(uint32_t));
1268 memcpy(&l3, Contents + (lp - SectAddress) + 3 * sizeof(uint32_t),
1269 sizeof(uint32_t));
1270 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
1271 sys::swapByteOrder(l0);
1272 sys::swapByteOrder(l1);
1273 sys::swapByteOrder(l2);
1274 sys::swapByteOrder(l3);
1275 }
1276 DumpLiteral16(l0, l1, l2, l3);
1277 break;
1278 }
1279 }
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001280 }
1281}
1282
Kevin Enderby85b7a662018-03-20 20:29:52 +00001283static void DumpInitTermPointerSection(MachOObjectFile *O,
1284 const SectionRef &Section,
1285 const char *sect,
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001286 uint32_t sect_size, uint64_t sect_addr,
1287 SymbolAddressMap *AddrMap,
1288 bool verbose) {
1289 uint32_t stride;
Davide Italiano3eb47e22015-12-15 23:14:21 +00001290 stride = (O->is64Bit()) ? sizeof(uint64_t) : sizeof(uint32_t);
Kevin Enderby85b7a662018-03-20 20:29:52 +00001291
1292 // Collect the external relocation symbols for the pointers.
1293 std::vector<std::pair<uint64_t, SymbolRef>> Relocs;
1294 for (const RelocationRef &Reloc : Section.relocations()) {
1295 DataRefImpl Rel;
1296 MachO::any_relocation_info RE;
1297 bool isExtern = false;
1298 Rel = Reloc.getRawDataRefImpl();
1299 RE = O->getRelocation(Rel);
1300 isExtern = O->getPlainRelocationExternal(RE);
1301 if (isExtern) {
1302 uint64_t RelocOffset = Reloc.getOffset();
1303 symbol_iterator RelocSym = Reloc.getSymbol();
1304 Relocs.push_back(std::make_pair(RelocOffset, *RelocSym));
1305 }
1306 }
1307 array_pod_sort(Relocs.begin(), Relocs.end());
1308
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001309 for (uint32_t i = 0; i < sect_size; i += stride) {
1310 const char *SymbolName = nullptr;
Kevin Enderby85b7a662018-03-20 20:29:52 +00001311 uint64_t p;
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001312 if (O->is64Bit()) {
1313 outs() << format("0x%016" PRIx64, sect_addr + i * stride) << " ";
1314 uint64_t pointer_value;
1315 memcpy(&pointer_value, sect + i, stride);
1316 if (O->isLittleEndian() != sys::IsLittleEndianHost)
1317 sys::swapByteOrder(pointer_value);
1318 outs() << format("0x%016" PRIx64, pointer_value);
Kevin Enderby85b7a662018-03-20 20:29:52 +00001319 p = pointer_value;
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001320 } else {
1321 outs() << format("0x%08" PRIx64, sect_addr + i * stride) << " ";
1322 uint32_t pointer_value;
1323 memcpy(&pointer_value, sect + i, stride);
1324 if (O->isLittleEndian() != sys::IsLittleEndianHost)
1325 sys::swapByteOrder(pointer_value);
1326 outs() << format("0x%08" PRIx32, pointer_value);
Kevin Enderby85b7a662018-03-20 20:29:52 +00001327 p = pointer_value;
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001328 }
Kevin Enderby85b7a662018-03-20 20:29:52 +00001329 if (verbose) {
1330 // First look for an external relocation entry for this pointer.
1331 auto Reloc = find_if(Relocs, [&](const std::pair<uint64_t, SymbolRef> &P) {
1332 return P.first == i;
1333 });
1334 if (Reloc != Relocs.end()) {
1335 symbol_iterator RelocSym = Reloc->second;
1336 Expected<StringRef> SymName = RelocSym->getName();
1337 if (!SymName)
1338 report_error(O->getFileName(), SymName.takeError());
1339 outs() << " " << *SymName;
1340 } else {
1341 SymbolName = GuessSymbolName(p, AddrMap);
1342 if (SymbolName)
1343 outs() << " " << SymbolName;
1344 }
1345 }
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001346 outs() << "\n";
1347 }
1348}
1349
1350static void DumpRawSectionContents(MachOObjectFile *O, const char *sect,
1351 uint32_t size, uint64_t addr) {
1352 uint32_t cputype = O->getHeader().cputype;
1353 if (cputype == MachO::CPU_TYPE_I386 || cputype == MachO::CPU_TYPE_X86_64) {
1354 uint32_t j;
1355 for (uint32_t i = 0; i < size; i += j, addr += j) {
1356 if (O->is64Bit())
1357 outs() << format("%016" PRIx64, addr) << "\t";
1358 else
Kevin Enderbyf0640752015-03-13 17:56:32 +00001359 outs() << format("%08" PRIx64, addr) << "\t";
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001360 for (j = 0; j < 16 && i + j < size; j++) {
1361 uint8_t byte_word = *(sect + i + j);
1362 outs() << format("%02" PRIx32, (uint32_t)byte_word) << " ";
1363 }
1364 outs() << "\n";
1365 }
1366 } else {
1367 uint32_t j;
1368 for (uint32_t i = 0; i < size; i += j, addr += j) {
1369 if (O->is64Bit())
1370 outs() << format("%016" PRIx64, addr) << "\t";
1371 else
Kevin Enderbyc4930852016-04-27 22:36:18 +00001372 outs() << format("%08" PRIx64, addr) << "\t";
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001373 for (j = 0; j < 4 * sizeof(int32_t) && i + j < size;
1374 j += sizeof(int32_t)) {
Kevin Enderby8eccdad2016-04-27 23:43:00 +00001375 if (i + j + sizeof(int32_t) <= size) {
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001376 uint32_t long_word;
1377 memcpy(&long_word, sect + i + j, sizeof(int32_t));
1378 if (O->isLittleEndian() != sys::IsLittleEndianHost)
1379 sys::swapByteOrder(long_word);
1380 outs() << format("%08" PRIx32, long_word) << " ";
1381 } else {
1382 for (uint32_t k = 0; i + j + k < size; k++) {
Kevin Enderby8eccdad2016-04-27 23:43:00 +00001383 uint8_t byte_word = *(sect + i + j + k);
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001384 outs() << format("%02" PRIx32, (uint32_t)byte_word) << " ";
1385 }
1386 }
1387 }
1388 outs() << "\n";
1389 }
1390 }
1391}
1392
Kevin Enderby95df54c2015-02-04 01:01:38 +00001393static void DisassembleMachO(StringRef Filename, MachOObjectFile *MachOOF,
1394 StringRef DisSegName, StringRef DisSectName);
Kevin Enderby4ad9bde2015-04-16 22:33:20 +00001395static void DumpProtocolSection(MachOObjectFile *O, const char *sect,
1396 uint32_t size, uint32_t addr);
Kevin Enderby9873e2c2016-05-23 21:34:12 +00001397#ifdef HAVE_LIBXAR
1398static void DumpBitcodeSection(MachOObjectFile *O, const char *sect,
1399 uint32_t size, bool verbose,
1400 bool PrintXarHeader, bool PrintXarFileHeaders,
1401 std::string XarMemberName);
1402#endif // defined(HAVE_LIBXAR)
Kevin Enderby95df54c2015-02-04 01:01:38 +00001403
1404static void DumpSectionContents(StringRef Filename, MachOObjectFile *O,
1405 bool verbose) {
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001406 SymbolAddressMap AddrMap;
1407 if (verbose)
1408 CreateSymbolAddressMap(O, &AddrMap);
1409
Colin LeMahieufcc32762015-07-29 19:08:10 +00001410 for (unsigned i = 0; i < FilterSections.size(); ++i) {
1411 StringRef DumpSection = FilterSections[i];
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001412 std::pair<StringRef, StringRef> DumpSegSectName;
1413 DumpSegSectName = DumpSection.split(',');
1414 StringRef DumpSegName, DumpSectName;
1415 if (DumpSegSectName.second.size()) {
1416 DumpSegName = DumpSegSectName.first;
1417 DumpSectName = DumpSegSectName.second;
1418 } else {
1419 DumpSegName = "";
1420 DumpSectName = DumpSegSectName.first;
1421 }
1422 for (const SectionRef &Section : O->sections()) {
1423 StringRef SectName;
1424 Section.getName(SectName);
1425 DataRefImpl Ref = Section.getRawDataRefImpl();
1426 StringRef SegName = O->getSectionFinalSegmentName(Ref);
1427 if ((DumpSegName.empty() || SegName == DumpSegName) &&
1428 (SectName == DumpSectName)) {
Adrian Prantlc2401dd2015-03-27 17:31:15 +00001429
Kevin Enderby95df54c2015-02-04 01:01:38 +00001430 uint32_t section_flags;
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001431 if (O->is64Bit()) {
1432 const MachO::section_64 Sec = O->getSection64(Ref);
Kevin Enderby95df54c2015-02-04 01:01:38 +00001433 section_flags = Sec.flags;
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001434
1435 } else {
1436 const MachO::section Sec = O->getSection(Ref);
Kevin Enderby95df54c2015-02-04 01:01:38 +00001437 section_flags = Sec.flags;
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001438 }
Kevin Enderby95df54c2015-02-04 01:01:38 +00001439 uint32_t section_type = section_flags & MachO::SECTION_TYPE;
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001440
1441 StringRef BytesStr;
1442 Section.getContents(BytesStr);
1443 const char *sect = reinterpret_cast<const char *>(BytesStr.data());
1444 uint32_t sect_size = BytesStr.size();
1445 uint64_t sect_addr = Section.getAddress();
1446
Adrian Prantlc2401dd2015-03-27 17:31:15 +00001447 outs() << "Contents of (" << SegName << "," << SectName
1448 << ") section\n";
1449
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001450 if (verbose) {
Kevin Enderby95df54c2015-02-04 01:01:38 +00001451 if ((section_flags & MachO::S_ATTR_PURE_INSTRUCTIONS) ||
1452 (section_flags & MachO::S_ATTR_SOME_INSTRUCTIONS)) {
1453 DisassembleMachO(Filename, O, SegName, SectName);
1454 continue;
1455 }
Kevin Enderbycd66be52015-03-11 22:06:32 +00001456 if (SegName == "__TEXT" && SectName == "__info_plist") {
1457 outs() << sect;
1458 continue;
1459 }
Kevin Enderby4ad9bde2015-04-16 22:33:20 +00001460 if (SegName == "__OBJC" && SectName == "__protocol") {
1461 DumpProtocolSection(O, sect, sect_size, sect_addr);
1462 continue;
1463 }
Kevin Enderby9873e2c2016-05-23 21:34:12 +00001464#ifdef HAVE_LIBXAR
1465 if (SegName == "__LLVM" && SectName == "__bundle") {
1466 DumpBitcodeSection(O, sect, sect_size, verbose, !NoSymbolicOperands,
1467 ArchiveHeaders, "");
1468 continue;
1469 }
1470#endif // defined(HAVE_LIBXAR)
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001471 switch (section_type) {
1472 case MachO::S_REGULAR:
1473 DumpRawSectionContents(O, sect, sect_size, sect_addr);
1474 break;
1475 case MachO::S_ZEROFILL:
1476 outs() << "zerofill section and has no contents in the file\n";
1477 break;
Kevin Enderby10ba0412015-02-04 21:38:42 +00001478 case MachO::S_CSTRING_LITERALS:
Kevin Enderbyab5e6c92015-03-17 21:07:39 +00001479 DumpCstringSection(O, sect, sect_size, sect_addr, !NoLeadingAddr);
Kevin Enderby10ba0412015-02-04 21:38:42 +00001480 break;
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001481 case MachO::S_4BYTE_LITERALS:
Kevin Enderbyab5e6c92015-03-17 21:07:39 +00001482 DumpLiteral4Section(O, sect, sect_size, sect_addr, !NoLeadingAddr);
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001483 break;
1484 case MachO::S_8BYTE_LITERALS:
Kevin Enderbyab5e6c92015-03-17 21:07:39 +00001485 DumpLiteral8Section(O, sect, sect_size, sect_addr, !NoLeadingAddr);
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001486 break;
1487 case MachO::S_16BYTE_LITERALS:
Kevin Enderby0fc11822015-04-01 20:57:01 +00001488 DumpLiteral16Section(O, sect, sect_size, sect_addr, !NoLeadingAddr);
1489 break;
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001490 case MachO::S_LITERAL_POINTERS:
1491 DumpLiteralPointerSection(O, Section, sect, sect_size, sect_addr,
Kevin Enderbyab5e6c92015-03-17 21:07:39 +00001492 !NoLeadingAddr);
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001493 break;
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001494 case MachO::S_MOD_INIT_FUNC_POINTERS:
1495 case MachO::S_MOD_TERM_FUNC_POINTERS:
Kevin Enderby85b7a662018-03-20 20:29:52 +00001496 DumpInitTermPointerSection(O, Section, sect, sect_size, sect_addr,
1497 &AddrMap, verbose);
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001498 break;
1499 default:
1500 outs() << "Unknown section type ("
1501 << format("0x%08" PRIx32, section_type) << ")\n";
1502 DumpRawSectionContents(O, sect, sect_size, sect_addr);
1503 break;
1504 }
1505 } else {
1506 if (section_type == MachO::S_ZEROFILL)
1507 outs() << "zerofill section and has no contents in the file\n";
1508 else
1509 DumpRawSectionContents(O, sect, sect_size, sect_addr);
1510 }
1511 }
1512 }
1513 }
1514}
1515
Kevin Enderbycd66be52015-03-11 22:06:32 +00001516static void DumpInfoPlistSectionContents(StringRef Filename,
1517 MachOObjectFile *O) {
1518 for (const SectionRef &Section : O->sections()) {
1519 StringRef SectName;
1520 Section.getName(SectName);
1521 DataRefImpl Ref = Section.getRawDataRefImpl();
1522 StringRef SegName = O->getSectionFinalSegmentName(Ref);
1523 if (SegName == "__TEXT" && SectName == "__info_plist") {
Kevin Enderby30cf2e82017-06-20 21:00:25 +00001524 if (!NoLeadingHeaders)
1525 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
Kevin Enderbycd66be52015-03-11 22:06:32 +00001526 StringRef BytesStr;
1527 Section.getContents(BytesStr);
1528 const char *sect = reinterpret_cast<const char *>(BytesStr.data());
Kevin Enderby418659f2017-02-06 21:01:08 +00001529 outs() << format("%.*s", BytesStr.size(), sect) << "\n";
Kevin Enderbycd66be52015-03-11 22:06:32 +00001530 return;
1531 }
1532 }
1533}
1534
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001535// checkMachOAndArchFlags() checks to see if the ObjectFile is a Mach-O file
1536// and if it is and there is a list of architecture flags is specified then
1537// check to make sure this Mach-O file is one of those architectures or all
1538// architectures were specified. If not then an error is generated and this
1539// routine returns false. Else it returns true.
1540static bool checkMachOAndArchFlags(ObjectFile *O, StringRef Filename) {
David Majnemer91160d82016-10-31 17:11:31 +00001541 auto *MachO = dyn_cast<MachOObjectFile>(O);
1542
1543 if (!MachO || ArchAll || ArchFlags.empty())
1544 return true;
1545
1546 MachO::mach_header H;
1547 MachO::mach_header_64 H_64;
1548 Triple T;
Kevin Enderby59343a92016-12-16 22:54:02 +00001549 const char *McpuDefault, *ArchFlag;
David Majnemer91160d82016-10-31 17:11:31 +00001550 if (MachO->is64Bit()) {
1551 H_64 = MachO->MachOObjectFile::getHeader64();
Kevin Enderby59343a92016-12-16 22:54:02 +00001552 T = MachOObjectFile::getArchTriple(H_64.cputype, H_64.cpusubtype,
1553 &McpuDefault, &ArchFlag);
David Majnemer91160d82016-10-31 17:11:31 +00001554 } else {
1555 H = MachO->MachOObjectFile::getHeader();
Kevin Enderby59343a92016-12-16 22:54:02 +00001556 T = MachOObjectFile::getArchTriple(H.cputype, H.cpusubtype,
1557 &McpuDefault, &ArchFlag);
David Majnemer91160d82016-10-31 17:11:31 +00001558 }
Kevin Enderby59343a92016-12-16 22:54:02 +00001559 const std::string ArchFlagName(ArchFlag);
David Majnemer91160d82016-10-31 17:11:31 +00001560 if (none_of(ArchFlags, [&](const std::string &Name) {
Kevin Enderby59343a92016-12-16 22:54:02 +00001561 return Name == ArchFlagName;
David Majnemer91160d82016-10-31 17:11:31 +00001562 })) {
Jonas Devliegheree787efd2018-11-11 22:12:04 +00001563 WithColor::error(errs(), "llvm-objdump")
1564 << Filename << ": no architecture specified.\n";
David Majnemer91160d82016-10-31 17:11:31 +00001565 return false;
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001566 }
1567 return true;
1568}
1569
Kevin Enderby0fc11822015-04-01 20:57:01 +00001570static void printObjcMetaData(MachOObjectFile *O, bool verbose);
1571
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001572// ProcessMachO() is passed a single opened Mach-O file, which may be an
1573// archive member and or in a slice of a universal file. It prints the
1574// the file name and header info and then processes it according to the
1575// command line options.
Kevin Enderby844c4ac2016-11-15 23:07:41 +00001576static void ProcessMachO(StringRef Name, MachOObjectFile *MachOOF,
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001577 StringRef ArchiveMemberName = StringRef(),
1578 StringRef ArchitectureName = StringRef()) {
Kevin Enderby131d1772015-01-09 19:22:37 +00001579 // If we are doing some processing here on the Mach-O file print the header
1580 // info. And don't print it otherwise like in the case of printing the
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +00001581 // UniversalHeaders or ArchiveHeaders.
Michael Trenta1703b12017-12-15 17:57:40 +00001582 if (Disassemble || Relocations || PrivateHeaders || ExportsTrie || Rebase ||
1583 Bind || SymbolTable || LazyBind || WeakBind || IndirectSymbols ||
1584 DataInCode || LinkOptHints || DylibsUsed || DylibId || ObjcMetaData ||
1585 (FilterSections.size() != 0)) {
Kevin Enderbyf9d60f02016-11-29 21:43:40 +00001586 if (!NoLeadingHeaders) {
1587 outs() << Name;
1588 if (!ArchiveMemberName.empty())
1589 outs() << '(' << ArchiveMemberName << ')';
1590 if (!ArchitectureName.empty())
1591 outs() << " (architecture " << ArchitectureName << ")";
1592 outs() << ":\n";
1593 }
Kevin Enderby131d1772015-01-09 19:22:37 +00001594 }
Kevin Enderby844c4ac2016-11-15 23:07:41 +00001595 // To use the report_error() form with an ArchiveName and FileName set
1596 // these up based on what is passed for Name and ArchiveMemberName.
1597 StringRef ArchiveName;
1598 StringRef FileName;
1599 if (!ArchiveMemberName.empty()) {
1600 ArchiveName = Name;
1601 FileName = ArchiveMemberName;
1602 } else {
1603 ArchiveName = StringRef();
1604 FileName = Name;
1605 }
1606
1607 // If we need the symbol table to do the operation then check it here to
1608 // produce a good error message as to where the Mach-O file comes from in
1609 // the error message.
1610 if (Disassemble || IndirectSymbols || FilterSections.size() != 0 ||
1611 UnwindInfo)
1612 if (Error Err = MachOOF->checkSymbolTable())
1613 report_error(ArchiveName, FileName, std::move(Err), ArchitectureName);
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001614
Kevin Enderbyaf2999a2017-06-22 19:50:56 +00001615 if (Disassemble) {
1616 if (MachOOF->getHeader().filetype == MachO::MH_KEXT_BUNDLE &&
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +00001617 MachOOF->getHeader().cputype == MachO::CPU_TYPE_ARM64)
Kevin Enderbyaf2999a2017-06-22 19:50:56 +00001618 DisassembleMachO(FileName, MachOOF, "__TEXT_EXEC", "__text");
1619 else
1620 DisassembleMachO(FileName, MachOOF, "__TEXT", "__text");
1621 }
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +00001622 if (IndirectSymbols)
Kevin Enderbyf0640752015-03-13 17:56:32 +00001623 PrintIndirectSymbols(MachOOF, !NonVerbose);
Kevin Enderby69fe98d2015-01-23 18:52:17 +00001624 if (DataInCode)
Kevin Enderbyf0640752015-03-13 17:56:32 +00001625 PrintDataInCodeTable(MachOOF, !NonVerbose);
Kevin Enderby9a509442015-01-27 21:28:24 +00001626 if (LinkOptHints)
1627 PrintLinkOptHints(MachOOF);
Kevin Enderby98da6132015-01-20 21:47:46 +00001628 if (Relocations)
Michael Trenta1703b12017-12-15 17:57:40 +00001629 PrintRelocations(MachOOF, !NonVerbose);
Kevin Enderby98da6132015-01-20 21:47:46 +00001630 if (SectionHeaders)
1631 PrintSectionHeaders(MachOOF);
1632 if (SectionContents)
1633 PrintSectionContents(MachOOF);
Colin LeMahieufcc32762015-07-29 19:08:10 +00001634 if (FilterSections.size() != 0)
Kevin Enderby844c4ac2016-11-15 23:07:41 +00001635 DumpSectionContents(FileName, MachOOF, !NonVerbose);
Kevin Enderbycd66be52015-03-11 22:06:32 +00001636 if (InfoPlist)
Kevin Enderby844c4ac2016-11-15 23:07:41 +00001637 DumpInfoPlistSectionContents(FileName, MachOOF);
Kevin Enderbybc847fa2015-03-16 20:08:09 +00001638 if (DylibsUsed)
1639 PrintDylibs(MachOOF, false);
1640 if (DylibId)
1641 PrintDylibs(MachOOF, true);
Kevin Enderby844c4ac2016-11-15 23:07:41 +00001642 if (SymbolTable)
Kevin Enderby9acb1092016-05-31 20:35:34 +00001643 PrintSymbolTable(MachOOF, ArchiveName, ArchitectureName);
Kevin Enderby98da6132015-01-20 21:47:46 +00001644 if (UnwindInfo)
1645 printMachOUnwindInfo(MachOOF);
Kevin Enderby0ae163f2016-01-13 00:25:36 +00001646 if (PrivateHeaders) {
1647 printMachOFileHeader(MachOOF);
1648 printMachOLoadCommands(MachOOF);
1649 }
1650 if (FirstPrivateHeader)
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001651 printMachOFileHeader(MachOOF);
Kevin Enderby0fc11822015-04-01 20:57:01 +00001652 if (ObjcMetaData)
1653 printObjcMetaData(MachOOF, !NonVerbose);
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001654 if (ExportsTrie)
1655 printExportsTrie(MachOOF);
1656 if (Rebase)
1657 printRebaseTable(MachOOF);
1658 if (Bind)
1659 printBindTable(MachOOF);
1660 if (LazyBind)
1661 printLazyBindTable(MachOOF);
1662 if (WeakBind)
1663 printWeakBindTable(MachOOF);
Igor Laevsky03a670c2016-01-26 15:09:42 +00001664
1665 if (DwarfDumpType != DIDT_Null) {
Rafael Espindolac398e672017-07-19 22:27:28 +00001666 std::unique_ptr<DIContext> DICtx = DWARFContext::create(*MachOOF);
Igor Laevsky03a670c2016-01-26 15:09:42 +00001667 // Dump the complete DWARF structure.
Adrian Prantlf4bc1f72017-06-01 18:18:23 +00001668 DIDumpOptions DumpOpts;
1669 DumpOpts.DumpType = DwarfDumpType;
Adrian Prantlf4bc1f72017-06-01 18:18:23 +00001670 DICtx->dump(outs(), DumpOpts);
Igor Laevsky03a670c2016-01-26 15:09:42 +00001671 }
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001672}
1673
Kevin Enderby131d1772015-01-09 19:22:37 +00001674// printUnknownCPUType() helps print_fat_headers for unknown CPU's.
1675static void printUnknownCPUType(uint32_t cputype, uint32_t cpusubtype) {
1676 outs() << " cputype (" << cputype << ")\n";
1677 outs() << " cpusubtype (" << cpusubtype << ")\n";
1678}
1679
1680// printCPUType() helps print_fat_headers by printing the cputype and
1681// pusubtype (symbolically for the one's it knows about).
1682static void printCPUType(uint32_t cputype, uint32_t cpusubtype) {
1683 switch (cputype) {
1684 case MachO::CPU_TYPE_I386:
1685 switch (cpusubtype) {
1686 case MachO::CPU_SUBTYPE_I386_ALL:
1687 outs() << " cputype CPU_TYPE_I386\n";
1688 outs() << " cpusubtype CPU_SUBTYPE_I386_ALL\n";
1689 break;
1690 default:
1691 printUnknownCPUType(cputype, cpusubtype);
1692 break;
1693 }
1694 break;
1695 case MachO::CPU_TYPE_X86_64:
1696 switch (cpusubtype) {
1697 case MachO::CPU_SUBTYPE_X86_64_ALL:
1698 outs() << " cputype CPU_TYPE_X86_64\n";
1699 outs() << " cpusubtype CPU_SUBTYPE_X86_64_ALL\n";
1700 break;
1701 case MachO::CPU_SUBTYPE_X86_64_H:
1702 outs() << " cputype CPU_TYPE_X86_64\n";
1703 outs() << " cpusubtype CPU_SUBTYPE_X86_64_H\n";
1704 break;
1705 default:
1706 printUnknownCPUType(cputype, cpusubtype);
1707 break;
1708 }
1709 break;
1710 case MachO::CPU_TYPE_ARM:
1711 switch (cpusubtype) {
1712 case MachO::CPU_SUBTYPE_ARM_ALL:
1713 outs() << " cputype CPU_TYPE_ARM\n";
1714 outs() << " cpusubtype CPU_SUBTYPE_ARM_ALL\n";
1715 break;
1716 case MachO::CPU_SUBTYPE_ARM_V4T:
1717 outs() << " cputype CPU_TYPE_ARM\n";
1718 outs() << " cpusubtype CPU_SUBTYPE_ARM_V4T\n";
1719 break;
1720 case MachO::CPU_SUBTYPE_ARM_V5TEJ:
1721 outs() << " cputype CPU_TYPE_ARM\n";
1722 outs() << " cpusubtype CPU_SUBTYPE_ARM_V5TEJ\n";
1723 break;
1724 case MachO::CPU_SUBTYPE_ARM_XSCALE:
1725 outs() << " cputype CPU_TYPE_ARM\n";
1726 outs() << " cpusubtype CPU_SUBTYPE_ARM_XSCALE\n";
1727 break;
1728 case MachO::CPU_SUBTYPE_ARM_V6:
1729 outs() << " cputype CPU_TYPE_ARM\n";
1730 outs() << " cpusubtype CPU_SUBTYPE_ARM_V6\n";
1731 break;
1732 case MachO::CPU_SUBTYPE_ARM_V6M:
1733 outs() << " cputype CPU_TYPE_ARM\n";
1734 outs() << " cpusubtype CPU_SUBTYPE_ARM_V6M\n";
1735 break;
1736 case MachO::CPU_SUBTYPE_ARM_V7:
1737 outs() << " cputype CPU_TYPE_ARM\n";
1738 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7\n";
1739 break;
1740 case MachO::CPU_SUBTYPE_ARM_V7EM:
1741 outs() << " cputype CPU_TYPE_ARM\n";
1742 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7EM\n";
1743 break;
1744 case MachO::CPU_SUBTYPE_ARM_V7K:
1745 outs() << " cputype CPU_TYPE_ARM\n";
1746 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7K\n";
1747 break;
1748 case MachO::CPU_SUBTYPE_ARM_V7M:
1749 outs() << " cputype CPU_TYPE_ARM\n";
1750 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7M\n";
1751 break;
1752 case MachO::CPU_SUBTYPE_ARM_V7S:
1753 outs() << " cputype CPU_TYPE_ARM\n";
1754 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7S\n";
1755 break;
1756 default:
1757 printUnknownCPUType(cputype, cpusubtype);
1758 break;
1759 }
1760 break;
1761 case MachO::CPU_TYPE_ARM64:
1762 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
1763 case MachO::CPU_SUBTYPE_ARM64_ALL:
1764 outs() << " cputype CPU_TYPE_ARM64\n";
1765 outs() << " cpusubtype CPU_SUBTYPE_ARM64_ALL\n";
1766 break;
1767 default:
1768 printUnknownCPUType(cputype, cpusubtype);
1769 break;
1770 }
1771 break;
1772 default:
1773 printUnknownCPUType(cputype, cpusubtype);
1774 break;
1775 }
1776}
1777
1778static void printMachOUniversalHeaders(const object::MachOUniversalBinary *UB,
1779 bool verbose) {
1780 outs() << "Fat headers\n";
Kevin Enderby606a3382016-06-21 21:55:01 +00001781 if (verbose) {
1782 if (UB->getMagic() == MachO::FAT_MAGIC)
1783 outs() << "fat_magic FAT_MAGIC\n";
1784 else // UB->getMagic() == MachO::FAT_MAGIC_64
1785 outs() << "fat_magic FAT_MAGIC_64\n";
1786 } else
Kevin Enderby131d1772015-01-09 19:22:37 +00001787 outs() << "fat_magic " << format("0x%" PRIx32, MachO::FAT_MAGIC) << "\n";
1788
1789 uint32_t nfat_arch = UB->getNumberOfObjects();
1790 StringRef Buf = UB->getData();
1791 uint64_t size = Buf.size();
1792 uint64_t big_size = sizeof(struct MachO::fat_header) +
1793 nfat_arch * sizeof(struct MachO::fat_arch);
1794 outs() << "nfat_arch " << UB->getNumberOfObjects();
1795 if (nfat_arch == 0)
1796 outs() << " (malformed, contains zero architecture types)\n";
1797 else if (big_size > size)
1798 outs() << " (malformed, architectures past end of file)\n";
1799 else
1800 outs() << "\n";
1801
1802 for (uint32_t i = 0; i < nfat_arch; ++i) {
1803 MachOUniversalBinary::ObjectForArch OFA(UB, i);
1804 uint32_t cputype = OFA.getCPUType();
1805 uint32_t cpusubtype = OFA.getCPUSubType();
1806 outs() << "architecture ";
1807 for (uint32_t j = 0; i != 0 && j <= i - 1; j++) {
1808 MachOUniversalBinary::ObjectForArch other_OFA(UB, j);
1809 uint32_t other_cputype = other_OFA.getCPUType();
1810 uint32_t other_cpusubtype = other_OFA.getCPUSubType();
Kevin Enderby0512bd72015-01-09 21:55:03 +00001811 if (cputype != 0 && cpusubtype != 0 && cputype == other_cputype &&
Kevin Enderby131d1772015-01-09 19:22:37 +00001812 (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) ==
Kevin Enderby0512bd72015-01-09 21:55:03 +00001813 (other_cpusubtype & ~MachO::CPU_SUBTYPE_MASK)) {
Kevin Enderby131d1772015-01-09 19:22:37 +00001814 outs() << "(illegal duplicate architecture) ";
1815 break;
Kevin Enderby0512bd72015-01-09 21:55:03 +00001816 }
Kevin Enderby131d1772015-01-09 19:22:37 +00001817 }
1818 if (verbose) {
Kevin Enderby59343a92016-12-16 22:54:02 +00001819 outs() << OFA.getArchFlagName() << "\n";
Kevin Enderby131d1772015-01-09 19:22:37 +00001820 printCPUType(cputype, cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
1821 } else {
1822 outs() << i << "\n";
1823 outs() << " cputype " << cputype << "\n";
1824 outs() << " cpusubtype " << (cpusubtype & ~MachO::CPU_SUBTYPE_MASK)
1825 << "\n";
1826 }
1827 if (verbose &&
1828 (cpusubtype & MachO::CPU_SUBTYPE_MASK) == MachO::CPU_SUBTYPE_LIB64)
1829 outs() << " capabilities CPU_SUBTYPE_LIB64\n";
1830 else
1831 outs() << " capabilities "
1832 << format("0x%" PRIx32,
1833 (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24) << "\n";
1834 outs() << " offset " << OFA.getOffset();
1835 if (OFA.getOffset() > size)
1836 outs() << " (past end of file)";
1837 if (OFA.getOffset() % (1 << OFA.getAlign()) != 0)
1838 outs() << " (not aligned on it's alignment (2^" << OFA.getAlign() << ")";
1839 outs() << "\n";
1840 outs() << " size " << OFA.getSize();
1841 big_size = OFA.getOffset() + OFA.getSize();
1842 if (big_size > size)
1843 outs() << " (past end of file)";
1844 outs() << "\n";
1845 outs() << " align 2^" << OFA.getAlign() << " (" << (1 << OFA.getAlign())
1846 << ")\n";
1847 }
1848}
1849
Kevin Enderby6524bd82016-07-19 20:47:07 +00001850static void printArchiveChild(StringRef Filename, const Archive::Child &C,
1851 bool verbose, bool print_offset,
1852 StringRef ArchitectureName = StringRef()) {
Kevin Enderby13023a12015-01-15 23:19:11 +00001853 if (print_offset)
1854 outs() << C.getChildOffset() << "\t";
Vedant Kumar4031d9f2016-08-03 19:02:50 +00001855 Expected<sys::fs::perms> ModeOrErr = C.getAccessMode();
1856 if (!ModeOrErr)
1857 report_error(Filename, C, ModeOrErr.takeError(), ArchitectureName);
1858 sys::fs::perms Mode = ModeOrErr.get();
Kevin Enderby13023a12015-01-15 23:19:11 +00001859 if (verbose) {
1860 // FIXME: this first dash, "-", is for (Mode & S_IFMT) == S_IFREG.
1861 // But there is nothing in sys::fs::perms for S_IFMT or S_IFREG.
1862 outs() << "-";
Davide Italianobb9a6cc2015-09-07 20:47:03 +00001863 outs() << ((Mode & sys::fs::owner_read) ? "r" : "-");
1864 outs() << ((Mode & sys::fs::owner_write) ? "w" : "-");
1865 outs() << ((Mode & sys::fs::owner_exe) ? "x" : "-");
1866 outs() << ((Mode & sys::fs::group_read) ? "r" : "-");
1867 outs() << ((Mode & sys::fs::group_write) ? "w" : "-");
1868 outs() << ((Mode & sys::fs::group_exe) ? "x" : "-");
1869 outs() << ((Mode & sys::fs::others_read) ? "r" : "-");
1870 outs() << ((Mode & sys::fs::others_write) ? "w" : "-");
1871 outs() << ((Mode & sys::fs::others_exe) ? "x" : "-");
Kevin Enderby13023a12015-01-15 23:19:11 +00001872 } else {
1873 outs() << format("0%o ", Mode);
1874 }
1875
Vedant Kumar4031d9f2016-08-03 19:02:50 +00001876 Expected<unsigned> UIDOrErr = C.getUID();
1877 if (!UIDOrErr)
1878 report_error(Filename, C, UIDOrErr.takeError(), ArchitectureName);
1879 unsigned UID = UIDOrErr.get();
Kevin Enderby13023a12015-01-15 23:19:11 +00001880 outs() << format("%3d/", UID);
Vedant Kumar4031d9f2016-08-03 19:02:50 +00001881 Expected<unsigned> GIDOrErr = C.getGID();
1882 if (!GIDOrErr)
1883 report_error(Filename, C, GIDOrErr.takeError(), ArchitectureName);
1884 unsigned GID = GIDOrErr.get();
Kevin Enderby13023a12015-01-15 23:19:11 +00001885 outs() << format("%-3d ", GID);
Kevin Enderby6524bd82016-07-19 20:47:07 +00001886 Expected<uint64_t> Size = C.getRawSize();
1887 if (!Size)
1888 report_error(Filename, C, Size.takeError(), ArchitectureName);
Kevin Enderby7a969422015-11-05 19:24:56 +00001889 outs() << format("%5" PRId64, Size.get()) << " ";
Kevin Enderby13023a12015-01-15 23:19:11 +00001890
1891 StringRef RawLastModified = C.getRawLastModified();
1892 if (verbose) {
1893 unsigned Seconds;
1894 if (RawLastModified.getAsInteger(10, Seconds))
Vedant Kumar4031d9f2016-08-03 19:02:50 +00001895 outs() << "(date: \"" << RawLastModified
1896 << "\" contains non-decimal chars) ";
Kevin Enderby13023a12015-01-15 23:19:11 +00001897 else {
1898 // Since cime(3) returns a 26 character string of the form:
1899 // "Sun Sep 16 01:03:52 1973\n\0"
1900 // just print 24 characters.
1901 time_t t = Seconds;
1902 outs() << format("%.24s ", ctime(&t));
1903 }
1904 } else {
1905 outs() << RawLastModified << " ";
1906 }
1907
1908 if (verbose) {
Kevin Enderbyf4586032016-07-29 17:44:13 +00001909 Expected<StringRef> NameOrErr = C.getName();
1910 if (!NameOrErr) {
1911 consumeError(NameOrErr.takeError());
1912 Expected<StringRef> NameOrErr = C.getRawName();
1913 if (!NameOrErr)
1914 report_error(Filename, C, NameOrErr.takeError(), ArchitectureName);
1915 StringRef RawName = NameOrErr.get();
Kevin Enderby13023a12015-01-15 23:19:11 +00001916 outs() << RawName << "\n";
1917 } else {
1918 StringRef Name = NameOrErr.get();
1919 outs() << Name << "\n";
1920 }
1921 } else {
Kevin Enderbyf4586032016-07-29 17:44:13 +00001922 Expected<StringRef> NameOrErr = C.getRawName();
1923 if (!NameOrErr)
1924 report_error(Filename, C, NameOrErr.takeError(), ArchitectureName);
1925 StringRef RawName = NameOrErr.get();
Kevin Enderby13023a12015-01-15 23:19:11 +00001926 outs() << RawName << "\n";
1927 }
1928}
1929
Kevin Enderby6524bd82016-07-19 20:47:07 +00001930static void printArchiveHeaders(StringRef Filename, Archive *A, bool verbose,
1931 bool print_offset,
1932 StringRef ArchitectureName = StringRef()) {
Mehdi Amini41af4302016-11-11 04:28:40 +00001933 Error Err = Error::success();
1934 ;
Lang Hamesfc209622016-07-14 02:24:01 +00001935 for (const auto &C : A->children(Err, false))
Kevin Enderby6524bd82016-07-19 20:47:07 +00001936 printArchiveChild(Filename, C, verbose, print_offset, ArchitectureName);
1937
Lang Hamesfc209622016-07-14 02:24:01 +00001938 if (Err)
Kevin Enderby844c4ac2016-11-15 23:07:41 +00001939 report_error(StringRef(), Filename, std::move(Err), ArchitectureName);
Kevin Enderby13023a12015-01-15 23:19:11 +00001940}
1941
Dave Lee3fb120f2018-08-03 00:06:38 +00001942static bool ValidateArchFlags() {
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001943 // Check for -arch all and verifiy the -arch flags are valid.
1944 for (unsigned i = 0; i < ArchFlags.size(); ++i) {
1945 if (ArchFlags[i] == "all") {
1946 ArchAll = true;
1947 } else {
1948 if (!MachOObjectFile::isValidArch(ArchFlags[i])) {
Jonas Devliegheree787efd2018-11-11 22:12:04 +00001949 WithColor::error(errs(), "llvm-objdump")
1950 << "unknown architecture named '" + ArchFlags[i] +
1951 "'for the -arch option\n";
Dave Lee3fb120f2018-08-03 00:06:38 +00001952 return false;
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001953 }
1954 }
1955 }
Dave Lee3fb120f2018-08-03 00:06:38 +00001956 return true;
1957}
1958
1959// ParseInputMachO() parses the named Mach-O file in Filename and handles the
1960// -arch flags selecting just those slices as specified by them and also parses
1961// archive files. Then for each individual Mach-O file ProcessMachO() is
1962// called to process the file based on the command line options.
1963void llvm::ParseInputMachO(StringRef Filename) {
1964 if (!ValidateArchFlags())
1965 return;
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001966
1967 // Attempt to open the binary.
Kevin Enderby3fcdf6a2016-04-06 22:14:09 +00001968 Expected<OwningBinary<Binary>> BinaryOrErr = createBinary(Filename);
Kevin Enderby98898f22017-01-30 20:53:17 +00001969 if (!BinaryOrErr) {
1970 if (auto E = isNotObjectErrorInvalidFileType(BinaryOrErr.takeError()))
1971 report_error(Filename, std::move(E));
1972 else
1973 outs() << Filename << ": is not an object file\n";
1974 return;
1975 }
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001976 Binary &Bin = *BinaryOrErr.get().getBinary();
Kevin Enderby3f0ffab2014-12-03 22:29:40 +00001977
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001978 if (Archive *A = dyn_cast<Archive>(&Bin)) {
1979 outs() << "Archive : " << Filename << "\n";
Kevin Enderby13023a12015-01-15 23:19:11 +00001980 if (ArchiveHeaders)
Kevin Enderby6524bd82016-07-19 20:47:07 +00001981 printArchiveHeaders(Filename, A, !NonVerbose, ArchiveMemberOffsets);
1982
Mehdi Amini41af4302016-11-11 04:28:40 +00001983 Error Err = Error::success();
Lang Hamesfc209622016-07-14 02:24:01 +00001984 for (auto &C : A->children(Err)) {
Kevin Enderbyac9e1552016-05-17 17:10:12 +00001985 Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
1986 if (!ChildOrErr) {
1987 if (auto E = isNotObjectErrorInvalidFileType(ChildOrErr.takeError()))
1988 report_error(Filename, C, std::move(E));
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001989 continue;
Kevin Enderbyac9e1552016-05-17 17:10:12 +00001990 }
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001991 if (MachOObjectFile *O = dyn_cast<MachOObjectFile>(&*ChildOrErr.get())) {
1992 if (!checkMachOAndArchFlags(O, Filename))
1993 return;
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001994 ProcessMachO(Filename, O, O->getFileName());
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001995 }
1996 }
Lang Hamesfc209622016-07-14 02:24:01 +00001997 if (Err)
1998 report_error(Filename, std::move(Err));
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001999 return;
2000 }
2001 if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(&Bin)) {
Dave Lee3fb120f2018-08-03 00:06:38 +00002002 ParseInputMachO(UB);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00002003 return;
2004 }
2005 if (ObjectFile *O = dyn_cast<ObjectFile>(&Bin)) {
2006 if (!checkMachOAndArchFlags(O, Filename))
2007 return;
Dave Lee3fb120f2018-08-03 00:06:38 +00002008 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&*O))
Kevin Enderbye2297dd2015-01-07 21:02:18 +00002009 ProcessMachO(Filename, MachOOF);
Dave Lee3fb120f2018-08-03 00:06:38 +00002010 else
Jonas Devliegheree787efd2018-11-11 22:12:04 +00002011 WithColor::error(errs(), "llvm-objdump")
2012 << Filename << "': "
2013 << "object is not a Mach-O file type.\n";
Davide Italiano25d84582016-01-13 04:11:36 +00002014 return;
2015 }
2016 llvm_unreachable("Input object can't be invalid at this point");
Rafael Espindola9b709252013-04-13 01:45:40 +00002017}
2018
Dave Lee3fb120f2018-08-03 00:06:38 +00002019void llvm::ParseInputMachO(MachOUniversalBinary *UB) {
2020 if (!ValidateArchFlags())
2021 return;
2022
2023 auto Filename = UB->getFileName();
2024
2025 if (UniversalHeaders)
2026 printMachOUniversalHeaders(UB, !NonVerbose);
2027
2028 // If we have a list of architecture flags specified dump only those.
2029 if (!ArchAll && ArchFlags.size() != 0) {
2030 // Look for a slice in the universal binary that matches each ArchFlag.
2031 bool ArchFound;
2032 for (unsigned i = 0; i < ArchFlags.size(); ++i) {
2033 ArchFound = false;
2034 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
2035 E = UB->end_objects();
2036 I != E; ++I) {
2037 if (ArchFlags[i] == I->getArchFlagName()) {
2038 ArchFound = true;
2039 Expected<std::unique_ptr<ObjectFile>> ObjOrErr =
2040 I->getAsObjectFile();
2041 std::string ArchitectureName = "";
2042 if (ArchFlags.size() > 1)
2043 ArchitectureName = I->getArchFlagName();
2044 if (ObjOrErr) {
2045 ObjectFile &O = *ObjOrErr.get();
2046 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&O))
2047 ProcessMachO(Filename, MachOOF, "", ArchitectureName);
2048 } else if (auto E = isNotObjectErrorInvalidFileType(
2049 ObjOrErr.takeError())) {
2050 report_error(Filename, StringRef(), std::move(E),
2051 ArchitectureName);
2052 continue;
2053 } else if (Expected<std::unique_ptr<Archive>> AOrErr =
2054 I->getAsArchive()) {
2055 std::unique_ptr<Archive> &A = *AOrErr;
2056 outs() << "Archive : " << Filename;
2057 if (!ArchitectureName.empty())
2058 outs() << " (architecture " << ArchitectureName << ")";
2059 outs() << "\n";
2060 if (ArchiveHeaders)
2061 printArchiveHeaders(Filename, A.get(), !NonVerbose,
2062 ArchiveMemberOffsets, ArchitectureName);
2063 Error Err = Error::success();
2064 for (auto &C : A->children(Err)) {
2065 Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
2066 if (!ChildOrErr) {
2067 if (auto E = isNotObjectErrorInvalidFileType(ChildOrErr.takeError()))
2068 report_error(Filename, C, std::move(E), ArchitectureName);
2069 continue;
2070 }
2071 if (MachOObjectFile *O =
2072 dyn_cast<MachOObjectFile>(&*ChildOrErr.get()))
2073 ProcessMachO(Filename, O, O->getFileName(), ArchitectureName);
2074 }
2075 if (Err)
2076 report_error(Filename, std::move(Err));
2077 } else {
2078 consumeError(AOrErr.takeError());
2079 error("Mach-O universal file: " + Filename + " for " +
2080 "architecture " + StringRef(I->getArchFlagName()) +
2081 " is not a Mach-O file or an archive file");
2082 }
2083 }
2084 }
2085 if (!ArchFound) {
Jonas Devliegheree787efd2018-11-11 22:12:04 +00002086 WithColor::error(errs(), "llvm-objdump")
2087 << "file: " + Filename + " does not contain "
2088 << "architecture: " + ArchFlags[i] + "\n";
Dave Lee3fb120f2018-08-03 00:06:38 +00002089 return;
2090 }
2091 }
2092 return;
2093 }
2094 // No architecture flags were specified so if this contains a slice that
2095 // matches the host architecture dump only that.
2096 if (!ArchAll) {
2097 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
2098 E = UB->end_objects();
2099 I != E; ++I) {
2100 if (MachOObjectFile::getHostArch().getArchName() ==
2101 I->getArchFlagName()) {
2102 Expected<std::unique_ptr<ObjectFile>> ObjOrErr = I->getAsObjectFile();
2103 std::string ArchiveName;
2104 ArchiveName.clear();
2105 if (ObjOrErr) {
2106 ObjectFile &O = *ObjOrErr.get();
2107 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&O))
2108 ProcessMachO(Filename, MachOOF);
2109 } else if (auto E = isNotObjectErrorInvalidFileType(
2110 ObjOrErr.takeError())) {
2111 report_error(Filename, std::move(E));
Dave Lee3fb120f2018-08-03 00:06:38 +00002112 } else if (Expected<std::unique_ptr<Archive>> AOrErr =
2113 I->getAsArchive()) {
2114 std::unique_ptr<Archive> &A = *AOrErr;
2115 outs() << "Archive : " << Filename << "\n";
2116 if (ArchiveHeaders)
2117 printArchiveHeaders(Filename, A.get(), !NonVerbose,
2118 ArchiveMemberOffsets);
2119 Error Err = Error::success();
2120 for (auto &C : A->children(Err)) {
2121 Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
2122 if (!ChildOrErr) {
2123 if (auto E = isNotObjectErrorInvalidFileType(ChildOrErr.takeError()))
2124 report_error(Filename, C, std::move(E));
2125 continue;
2126 }
2127 if (MachOObjectFile *O =
2128 dyn_cast<MachOObjectFile>(&*ChildOrErr.get()))
2129 ProcessMachO(Filename, O, O->getFileName());
2130 }
2131 if (Err)
2132 report_error(Filename, std::move(Err));
2133 } else {
2134 consumeError(AOrErr.takeError());
2135 error("Mach-O universal file: " + Filename + " for architecture " +
2136 StringRef(I->getArchFlagName()) +
2137 " is not a Mach-O file or an archive file");
2138 }
2139 return;
2140 }
2141 }
2142 }
2143 // Either all architectures have been specified or none have been specified
2144 // and this does not contain the host architecture so dump all the slices.
2145 bool moreThanOneArch = UB->getNumberOfObjects() > 1;
2146 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
2147 E = UB->end_objects();
2148 I != E; ++I) {
2149 Expected<std::unique_ptr<ObjectFile>> ObjOrErr = I->getAsObjectFile();
2150 std::string ArchitectureName = "";
2151 if (moreThanOneArch)
2152 ArchitectureName = I->getArchFlagName();
2153 if (ObjOrErr) {
2154 ObjectFile &Obj = *ObjOrErr.get();
2155 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&Obj))
2156 ProcessMachO(Filename, MachOOF, "", ArchitectureName);
2157 } else if (auto E = isNotObjectErrorInvalidFileType(
2158 ObjOrErr.takeError())) {
2159 report_error(StringRef(), Filename, std::move(E), ArchitectureName);
Dave Lee3fb120f2018-08-03 00:06:38 +00002160 } else if (Expected<std::unique_ptr<Archive>> AOrErr =
2161 I->getAsArchive()) {
2162 std::unique_ptr<Archive> &A = *AOrErr;
2163 outs() << "Archive : " << Filename;
2164 if (!ArchitectureName.empty())
2165 outs() << " (architecture " << ArchitectureName << ")";
2166 outs() << "\n";
2167 if (ArchiveHeaders)
2168 printArchiveHeaders(Filename, A.get(), !NonVerbose,
2169 ArchiveMemberOffsets, ArchitectureName);
2170 Error Err = Error::success();
2171 for (auto &C : A->children(Err)) {
2172 Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
2173 if (!ChildOrErr) {
2174 if (auto E = isNotObjectErrorInvalidFileType(ChildOrErr.takeError()))
2175 report_error(Filename, C, std::move(E), ArchitectureName);
2176 continue;
2177 }
2178 if (MachOObjectFile *O =
2179 dyn_cast<MachOObjectFile>(&*ChildOrErr.get())) {
2180 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(O))
2181 ProcessMachO(Filename, MachOOF, MachOOF->getFileName(),
2182 ArchitectureName);
2183 }
2184 }
2185 if (Err)
2186 report_error(Filename, std::move(Err));
2187 } else {
2188 consumeError(AOrErr.takeError());
2189 error("Mach-O universal file: " + Filename + " for architecture " +
2190 StringRef(I->getArchFlagName()) +
2191 " is not a Mach-O file or an archive file");
2192 }
2193 }
2194}
2195
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002196// The block of info used by the Symbolizer call backs.
2197struct DisassembleInfo {
Serge Pavlove4e9a1f2018-02-14 03:26:27 +00002198 DisassembleInfo(MachOObjectFile *O, SymbolAddressMap *AddrMap,
2199 std::vector<SectionRef> *Sections, bool verbose)
2200 : verbose(verbose), O(O), AddrMap(AddrMap), Sections(Sections) {}
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002201 bool verbose;
2202 MachOObjectFile *O;
2203 SectionRef S;
Kevin Enderbybf246f52014-09-24 23:08:22 +00002204 SymbolAddressMap *AddrMap;
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002205 std::vector<SectionRef> *Sections;
Serge Pavlove4e9a1f2018-02-14 03:26:27 +00002206 const char *class_name = nullptr;
2207 const char *selector_name = nullptr;
David Blaikie0e550682018-02-20 18:48:51 +00002208 std::unique_ptr<char[]> method = nullptr;
Serge Pavlove4e9a1f2018-02-14 03:26:27 +00002209 char *demangled_name = nullptr;
2210 uint64_t adrp_addr = 0;
2211 uint32_t adrp_inst = 0;
Saleem Abdulrasool1d84d9a2017-01-08 19:14:15 +00002212 std::unique_ptr<SymbolAddressMap> bindtable;
Serge Pavlove4e9a1f2018-02-14 03:26:27 +00002213 uint32_t depth = 0;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002214};
2215
2216// SymbolizerGetOpInfo() is the operand information call back function.
2217// This is called to get the symbolic information for operand(s) of an
2218// instruction when it is being done. This routine does this from
2219// the relocation information, symbol table, etc. That block of information
2220// is a pointer to the struct DisassembleInfo that was passed when the
2221// disassembler context was created and passed to back to here when
2222// called back by the disassembler for instruction operands that could have
2223// relocation information. The address of the instruction containing operand is
2224// at the Pc parameter. The immediate value the operand has is passed in
2225// op_info->Value and is at Offset past the start of the instruction and has a
2226// byte Size of 1, 2 or 4. The symbolc information is returned in TagBuf is the
2227// LLVMOpInfo1 struct defined in the header "llvm-c/Disassembler.h" as symbol
2228// names and addends of the symbolic expression to add for the operand. The
2229// value of TagType is currently 1 (for the LLVMOpInfo1 struct). If symbolic
2230// information is returned then this function returns 1 else it returns 0.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00002231static int SymbolizerGetOpInfo(void *DisInfo, uint64_t Pc, uint64_t Offset,
2232 uint64_t Size, int TagType, void *TagBuf) {
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002233 struct DisassembleInfo *info = (struct DisassembleInfo *)DisInfo;
2234 struct LLVMOpInfo1 *op_info = (struct LLVMOpInfo1 *)TagBuf;
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002235 uint64_t value = op_info->Value;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002236
2237 // Make sure all fields returned are zero if we don't set them.
2238 memset((void *)op_info, '\0', sizeof(struct LLVMOpInfo1));
2239 op_info->Value = value;
2240
2241 // If the TagType is not the value 1 which it code knows about or if no
2242 // verbose symbolic information is wanted then just return 0, indicating no
2243 // information is being returned.
David Blaikie33dd45d02015-03-23 18:39:02 +00002244 if (TagType != 1 || !info->verbose)
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002245 return 0;
2246
2247 unsigned int Arch = info->O->getArch();
2248 if (Arch == Triple::x86) {
Kevin Enderby9907d0a2014-11-04 00:43:16 +00002249 if (Size != 1 && Size != 2 && Size != 4 && Size != 0)
2250 return 0;
Kevin Enderbyd90a4172015-10-10 00:05:01 +00002251 if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
2252 // TODO:
2253 // Search the external relocation entries of a fully linked image
2254 // (if any) for an entry that matches this segment offset.
2255 // uint32_t seg_offset = (Pc + Offset);
2256 return 0;
2257 }
2258 // In MH_OBJECT filetypes search the section's relocation entries (if any)
2259 // for an entry for this section offset.
Kevin Enderby9907d0a2014-11-04 00:43:16 +00002260 uint32_t sect_addr = info->S.getAddress();
2261 uint32_t sect_offset = (Pc + Offset) - sect_addr;
2262 bool reloc_found = false;
2263 DataRefImpl Rel;
2264 MachO::any_relocation_info RE;
2265 bool isExtern = false;
2266 SymbolRef Symbol;
2267 bool r_scattered = false;
2268 uint32_t r_value, pair_r_value, r_type;
2269 for (const RelocationRef &Reloc : info->S.relocations()) {
Rafael Espindola96d071c2015-06-29 23:29:12 +00002270 uint64_t RelocOffset = Reloc.getOffset();
Kevin Enderby9907d0a2014-11-04 00:43:16 +00002271 if (RelocOffset == sect_offset) {
2272 Rel = Reloc.getRawDataRefImpl();
2273 RE = info->O->getRelocation(Rel);
Kevin Enderby3eb73e12014-11-11 19:16:45 +00002274 r_type = info->O->getAnyRelocationType(RE);
Kevin Enderby9907d0a2014-11-04 00:43:16 +00002275 r_scattered = info->O->isRelocationScattered(RE);
2276 if (r_scattered) {
2277 r_value = info->O->getScatteredRelocationValue(RE);
Kevin Enderby9907d0a2014-11-04 00:43:16 +00002278 if (r_type == MachO::GENERIC_RELOC_SECTDIFF ||
2279 r_type == MachO::GENERIC_RELOC_LOCAL_SECTDIFF) {
2280 DataRefImpl RelNext = Rel;
2281 info->O->moveRelocationNext(RelNext);
2282 MachO::any_relocation_info RENext;
2283 RENext = info->O->getRelocation(RelNext);
2284 if (info->O->isRelocationScattered(RENext))
Kevin Enderby930fdc72014-11-06 19:00:13 +00002285 pair_r_value = info->O->getScatteredRelocationValue(RENext);
Kevin Enderby9907d0a2014-11-04 00:43:16 +00002286 else
2287 return 0;
2288 }
2289 } else {
2290 isExtern = info->O->getPlainRelocationExternal(RE);
2291 if (isExtern) {
2292 symbol_iterator RelocSym = Reloc.getSymbol();
2293 Symbol = *RelocSym;
2294 }
2295 }
2296 reloc_found = true;
2297 break;
2298 }
2299 }
2300 if (reloc_found && isExtern) {
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00002301 Expected<StringRef> SymName = Symbol.getName();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00002302 if (!SymName)
2303 report_error(info->O->getFileName(), SymName.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00002304 const char *name = SymName->data();
Kevin Enderby9907d0a2014-11-04 00:43:16 +00002305 op_info->AddSymbol.Present = 1;
2306 op_info->AddSymbol.Name = name;
2307 // For i386 extern relocation entries the value in the instruction is
2308 // the offset from the symbol, and value is already set in op_info->Value.
2309 return 1;
2310 }
2311 if (reloc_found && (r_type == MachO::GENERIC_RELOC_SECTDIFF ||
2312 r_type == MachO::GENERIC_RELOC_LOCAL_SECTDIFF)) {
Kevin Enderbyf6d25852015-01-31 00:37:11 +00002313 const char *add = GuessSymbolName(r_value, info->AddrMap);
2314 const char *sub = GuessSymbolName(pair_r_value, info->AddrMap);
Kevin Enderby9907d0a2014-11-04 00:43:16 +00002315 uint32_t offset = value - (r_value - pair_r_value);
2316 op_info->AddSymbol.Present = 1;
2317 if (add != nullptr)
2318 op_info->AddSymbol.Name = add;
2319 else
2320 op_info->AddSymbol.Value = r_value;
2321 op_info->SubtractSymbol.Present = 1;
2322 if (sub != nullptr)
2323 op_info->SubtractSymbol.Name = sub;
2324 else
2325 op_info->SubtractSymbol.Value = pair_r_value;
2326 op_info->Value = offset;
2327 return 1;
2328 }
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002329 return 0;
David Blaikie33dd45d02015-03-23 18:39:02 +00002330 }
2331 if (Arch == Triple::x86_64) {
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002332 if (Size != 1 && Size != 2 && Size != 4 && Size != 0)
2333 return 0;
Kevin Enderbyabf10f22017-06-22 17:41:22 +00002334 // For non MH_OBJECT types, like MH_KEXT_BUNDLE, Search the external
2335 // relocation entries of a linked image (if any) for an entry that matches
2336 // this segment offset.
Kevin Enderbyd90a4172015-10-10 00:05:01 +00002337 if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
Kevin Enderbyabf10f22017-06-22 17:41:22 +00002338 uint64_t seg_offset = Pc + Offset;
2339 bool reloc_found = false;
2340 DataRefImpl Rel;
2341 MachO::any_relocation_info RE;
2342 bool isExtern = false;
2343 SymbolRef Symbol;
2344 for (const RelocationRef &Reloc : info->O->external_relocations()) {
2345 uint64_t RelocOffset = Reloc.getOffset();
2346 if (RelocOffset == seg_offset) {
2347 Rel = Reloc.getRawDataRefImpl();
2348 RE = info->O->getRelocation(Rel);
2349 // external relocation entries should always be external.
2350 isExtern = info->O->getPlainRelocationExternal(RE);
2351 if (isExtern) {
2352 symbol_iterator RelocSym = Reloc.getSymbol();
2353 Symbol = *RelocSym;
2354 }
2355 reloc_found = true;
2356 break;
2357 }
2358 }
2359 if (reloc_found && isExtern) {
2360 // The Value passed in will be adjusted by the Pc if the instruction
2361 // adds the Pc. But for x86_64 external relocation entries the Value
2362 // is the offset from the external symbol.
2363 if (info->O->getAnyRelocationPCRel(RE))
2364 op_info->Value -= Pc + Offset + Size;
2365 Expected<StringRef> SymName = Symbol.getName();
2366 if (!SymName)
2367 report_error(info->O->getFileName(), SymName.takeError());
2368 const char *name = SymName->data();
2369 op_info->AddSymbol.Present = 1;
2370 op_info->AddSymbol.Name = name;
2371 return 1;
2372 }
Kevin Enderbyd90a4172015-10-10 00:05:01 +00002373 return 0;
2374 }
2375 // In MH_OBJECT filetypes search the section's relocation entries (if any)
2376 // for an entry for this section offset.
Rafael Espindola80291272014-10-08 15:28:58 +00002377 uint64_t sect_addr = info->S.getAddress();
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002378 uint64_t sect_offset = (Pc + Offset) - sect_addr;
2379 bool reloc_found = false;
2380 DataRefImpl Rel;
2381 MachO::any_relocation_info RE;
2382 bool isExtern = false;
2383 SymbolRef Symbol;
2384 for (const RelocationRef &Reloc : info->S.relocations()) {
Rafael Espindola96d071c2015-06-29 23:29:12 +00002385 uint64_t RelocOffset = Reloc.getOffset();
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002386 if (RelocOffset == sect_offset) {
2387 Rel = Reloc.getRawDataRefImpl();
2388 RE = info->O->getRelocation(Rel);
2389 // NOTE: Scattered relocations don't exist on x86_64.
2390 isExtern = info->O->getPlainRelocationExternal(RE);
2391 if (isExtern) {
2392 symbol_iterator RelocSym = Reloc.getSymbol();
2393 Symbol = *RelocSym;
2394 }
2395 reloc_found = true;
2396 break;
2397 }
2398 }
2399 if (reloc_found && isExtern) {
2400 // The Value passed in will be adjusted by the Pc if the instruction
2401 // adds the Pc. But for x86_64 external relocation entries the Value
2402 // is the offset from the external symbol.
2403 if (info->O->getAnyRelocationPCRel(RE))
2404 op_info->Value -= Pc + Offset + Size;
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00002405 Expected<StringRef> SymName = Symbol.getName();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00002406 if (!SymName)
2407 report_error(info->O->getFileName(), SymName.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00002408 const char *name = SymName->data();
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002409 unsigned Type = info->O->getAnyRelocationType(RE);
2410 if (Type == MachO::X86_64_RELOC_SUBTRACTOR) {
2411 DataRefImpl RelNext = Rel;
2412 info->O->moveRelocationNext(RelNext);
2413 MachO::any_relocation_info RENext = info->O->getRelocation(RelNext);
2414 unsigned TypeNext = info->O->getAnyRelocationType(RENext);
2415 bool isExternNext = info->O->getPlainRelocationExternal(RENext);
2416 unsigned SymbolNum = info->O->getPlainRelocationSymbolNum(RENext);
2417 if (TypeNext == MachO::X86_64_RELOC_UNSIGNED && isExternNext) {
2418 op_info->SubtractSymbol.Present = 1;
2419 op_info->SubtractSymbol.Name = name;
2420 symbol_iterator RelocSymNext = info->O->getSymbolByIndex(SymbolNum);
2421 Symbol = *RelocSymNext;
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00002422 Expected<StringRef> SymNameNext = Symbol.getName();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00002423 if (!SymNameNext)
2424 report_error(info->O->getFileName(), SymNameNext.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00002425 name = SymNameNext->data();
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002426 }
2427 }
2428 // TODO: add the VariantKinds to op_info->VariantKind for relocation types
2429 // like: X86_64_RELOC_TLV, X86_64_RELOC_GOT_LOAD and X86_64_RELOC_GOT.
2430 op_info->AddSymbol.Present = 1;
2431 op_info->AddSymbol.Name = name;
2432 return 1;
2433 }
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002434 return 0;
David Blaikie33dd45d02015-03-23 18:39:02 +00002435 }
2436 if (Arch == Triple::arm) {
Kevin Enderby930fdc72014-11-06 19:00:13 +00002437 if (Offset != 0 || (Size != 4 && Size != 2))
2438 return 0;
Kevin Enderbyd90a4172015-10-10 00:05:01 +00002439 if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
2440 // TODO:
2441 // Search the external relocation entries of a fully linked image
2442 // (if any) for an entry that matches this segment offset.
2443 // uint32_t seg_offset = (Pc + Offset);
2444 return 0;
2445 }
2446 // In MH_OBJECT filetypes search the section's relocation entries (if any)
2447 // for an entry for this section offset.
Kevin Enderby930fdc72014-11-06 19:00:13 +00002448 uint32_t sect_addr = info->S.getAddress();
2449 uint32_t sect_offset = (Pc + Offset) - sect_addr;
Kevin Enderby930fdc72014-11-06 19:00:13 +00002450 DataRefImpl Rel;
2451 MachO::any_relocation_info RE;
2452 bool isExtern = false;
2453 SymbolRef Symbol;
2454 bool r_scattered = false;
2455 uint32_t r_value, pair_r_value, r_type, r_length, other_half;
David Blaikie33dd45d02015-03-23 18:39:02 +00002456 auto Reloc =
David Majnemer562e8292016-08-12 00:18:03 +00002457 find_if(info->S.relocations(), [&](const RelocationRef &Reloc) {
2458 uint64_t RelocOffset = Reloc.getOffset();
2459 return RelocOffset == sect_offset;
2460 });
David Blaikie33dd45d02015-03-23 18:39:02 +00002461
2462 if (Reloc == info->S.relocations().end())
2463 return 0;
2464
2465 Rel = Reloc->getRawDataRefImpl();
2466 RE = info->O->getRelocation(Rel);
2467 r_length = info->O->getAnyRelocationLength(RE);
2468 r_scattered = info->O->isRelocationScattered(RE);
2469 if (r_scattered) {
2470 r_value = info->O->getScatteredRelocationValue(RE);
2471 r_type = info->O->getScatteredRelocationType(RE);
2472 } else {
2473 r_type = info->O->getAnyRelocationType(RE);
2474 isExtern = info->O->getPlainRelocationExternal(RE);
2475 if (isExtern) {
2476 symbol_iterator RelocSym = Reloc->getSymbol();
2477 Symbol = *RelocSym;
Kevin Enderby930fdc72014-11-06 19:00:13 +00002478 }
2479 }
David Blaikie33dd45d02015-03-23 18:39:02 +00002480 if (r_type == MachO::ARM_RELOC_HALF ||
2481 r_type == MachO::ARM_RELOC_SECTDIFF ||
2482 r_type == MachO::ARM_RELOC_LOCAL_SECTDIFF ||
2483 r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
2484 DataRefImpl RelNext = Rel;
2485 info->O->moveRelocationNext(RelNext);
2486 MachO::any_relocation_info RENext;
2487 RENext = info->O->getRelocation(RelNext);
2488 other_half = info->O->getAnyRelocationAddress(RENext) & 0xffff;
2489 if (info->O->isRelocationScattered(RENext))
2490 pair_r_value = info->O->getScatteredRelocationValue(RENext);
2491 }
2492
2493 if (isExtern) {
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00002494 Expected<StringRef> SymName = Symbol.getName();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00002495 if (!SymName)
2496 report_error(info->O->getFileName(), SymName.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00002497 const char *name = SymName->data();
Kevin Enderby930fdc72014-11-06 19:00:13 +00002498 op_info->AddSymbol.Present = 1;
2499 op_info->AddSymbol.Name = name;
Sylvestre Ledru648cced2015-02-05 17:00:23 +00002500 switch (r_type) {
2501 case MachO::ARM_RELOC_HALF:
2502 if ((r_length & 0x1) == 1) {
2503 op_info->Value = value << 16 | other_half;
2504 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
2505 } else {
2506 op_info->Value = other_half << 16 | value;
2507 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
Sylvestre Ledrufe0c7ad2015-02-05 16:35:44 +00002508 }
Sylvestre Ledru648cced2015-02-05 17:00:23 +00002509 break;
2510 default:
2511 break;
Kevin Enderby930fdc72014-11-06 19:00:13 +00002512 }
2513 return 1;
2514 }
2515 // If we have a branch that is not an external relocation entry then
2516 // return 0 so the code in tryAddingSymbolicOperand() can use the
2517 // SymbolLookUp call back with the branch target address to look up the
Simon Pilgrimdae11f72016-11-20 13:31:13 +00002518 // symbol and possibility add an annotation for a symbol stub.
David Blaikie33dd45d02015-03-23 18:39:02 +00002519 if (isExtern == 0 && (r_type == MachO::ARM_RELOC_BR24 ||
2520 r_type == MachO::ARM_THUMB_RELOC_BR22))
Kevin Enderby930fdc72014-11-06 19:00:13 +00002521 return 0;
2522
2523 uint32_t offset = 0;
David Blaikie33dd45d02015-03-23 18:39:02 +00002524 if (r_type == MachO::ARM_RELOC_HALF ||
2525 r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
2526 if ((r_length & 0x1) == 1)
2527 value = value << 16 | other_half;
2528 else
2529 value = other_half << 16 | value;
2530 }
2531 if (r_scattered && (r_type != MachO::ARM_RELOC_HALF &&
2532 r_type != MachO::ARM_RELOC_HALF_SECTDIFF)) {
2533 offset = value - r_value;
2534 value = r_value;
Kevin Enderby930fdc72014-11-06 19:00:13 +00002535 }
2536
David Blaikie33dd45d02015-03-23 18:39:02 +00002537 if (r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
Kevin Enderby930fdc72014-11-06 19:00:13 +00002538 if ((r_length & 0x1) == 1)
2539 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
2540 else
2541 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
Kevin Enderbyf6d25852015-01-31 00:37:11 +00002542 const char *add = GuessSymbolName(r_value, info->AddrMap);
2543 const char *sub = GuessSymbolName(pair_r_value, info->AddrMap);
Kevin Enderby930fdc72014-11-06 19:00:13 +00002544 int32_t offset = value - (r_value - pair_r_value);
2545 op_info->AddSymbol.Present = 1;
2546 if (add != nullptr)
2547 op_info->AddSymbol.Name = add;
2548 else
2549 op_info->AddSymbol.Value = r_value;
2550 op_info->SubtractSymbol.Present = 1;
2551 if (sub != nullptr)
2552 op_info->SubtractSymbol.Name = sub;
2553 else
2554 op_info->SubtractSymbol.Value = pair_r_value;
2555 op_info->Value = offset;
2556 return 1;
2557 }
2558
Kevin Enderby930fdc72014-11-06 19:00:13 +00002559 op_info->AddSymbol.Present = 1;
2560 op_info->Value = offset;
David Blaikie33dd45d02015-03-23 18:39:02 +00002561 if (r_type == MachO::ARM_RELOC_HALF) {
2562 if ((r_length & 0x1) == 1)
2563 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
2564 else
2565 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
Kevin Enderby930fdc72014-11-06 19:00:13 +00002566 }
Kevin Enderbyf6d25852015-01-31 00:37:11 +00002567 const char *add = GuessSymbolName(value, info->AddrMap);
Kevin Enderby930fdc72014-11-06 19:00:13 +00002568 if (add != nullptr) {
2569 op_info->AddSymbol.Name = add;
2570 return 1;
2571 }
2572 op_info->AddSymbol.Value = value;
2573 return 1;
David Blaikie33dd45d02015-03-23 18:39:02 +00002574 }
2575 if (Arch == Triple::aarch64) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002576 if (Offset != 0 || Size != 4)
2577 return 0;
Kevin Enderbyd90a4172015-10-10 00:05:01 +00002578 if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
2579 // TODO:
2580 // Search the external relocation entries of a fully linked image
2581 // (if any) for an entry that matches this segment offset.
2582 // uint64_t seg_offset = (Pc + Offset);
2583 return 0;
2584 }
2585 // In MH_OBJECT filetypes search the section's relocation entries (if any)
2586 // for an entry for this section offset.
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002587 uint64_t sect_addr = info->S.getAddress();
2588 uint64_t sect_offset = (Pc + Offset) - sect_addr;
David Blaikie33dd45d02015-03-23 18:39:02 +00002589 auto Reloc =
David Majnemer562e8292016-08-12 00:18:03 +00002590 find_if(info->S.relocations(), [&](const RelocationRef &Reloc) {
2591 uint64_t RelocOffset = Reloc.getOffset();
2592 return RelocOffset == sect_offset;
2593 });
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002594
David Blaikie33dd45d02015-03-23 18:39:02 +00002595 if (Reloc == info->S.relocations().end())
2596 return 0;
2597
2598 DataRefImpl Rel = Reloc->getRawDataRefImpl();
2599 MachO::any_relocation_info RE = info->O->getRelocation(Rel);
2600 uint32_t r_type = info->O->getAnyRelocationType(RE);
2601 if (r_type == MachO::ARM64_RELOC_ADDEND) {
2602 DataRefImpl RelNext = Rel;
2603 info->O->moveRelocationNext(RelNext);
2604 MachO::any_relocation_info RENext = info->O->getRelocation(RelNext);
2605 if (value == 0) {
2606 value = info->O->getPlainRelocationSymbolNum(RENext);
2607 op_info->Value = value;
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002608 }
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002609 }
David Blaikie33dd45d02015-03-23 18:39:02 +00002610 // NOTE: Scattered relocations don't exist on arm64.
2611 if (!info->O->getPlainRelocationExternal(RE))
2612 return 0;
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00002613 Expected<StringRef> SymName = Reloc->getSymbol()->getName();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00002614 if (!SymName)
2615 report_error(info->O->getFileName(), SymName.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00002616 const char *name = SymName->data();
David Blaikie33dd45d02015-03-23 18:39:02 +00002617 op_info->AddSymbol.Present = 1;
2618 op_info->AddSymbol.Name = name;
2619
2620 switch (r_type) {
2621 case MachO::ARM64_RELOC_PAGE21:
2622 /* @page */
2623 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_PAGE;
2624 break;
2625 case MachO::ARM64_RELOC_PAGEOFF12:
2626 /* @pageoff */
2627 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_PAGEOFF;
2628 break;
2629 case MachO::ARM64_RELOC_GOT_LOAD_PAGE21:
2630 /* @gotpage */
2631 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_GOTPAGE;
2632 break;
2633 case MachO::ARM64_RELOC_GOT_LOAD_PAGEOFF12:
2634 /* @gotpageoff */
2635 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_GOTPAGEOFF;
2636 break;
2637 case MachO::ARM64_RELOC_TLVP_LOAD_PAGE21:
2638 /* @tvlppage is not implemented in llvm-mc */
2639 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_TLVP;
2640 break;
2641 case MachO::ARM64_RELOC_TLVP_LOAD_PAGEOFF12:
2642 /* @tvlppageoff is not implemented in llvm-mc */
2643 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_TLVOFF;
2644 break;
2645 default:
2646 case MachO::ARM64_RELOC_BRANCH26:
2647 op_info->VariantKind = LLVMDisassembler_VariantKind_None;
2648 break;
2649 }
2650 return 1;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002651 }
David Blaikie33dd45d02015-03-23 18:39:02 +00002652 return 0;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002653}
2654
Kevin Enderbybf246f52014-09-24 23:08:22 +00002655// GuessCstringPointer is passed the address of what might be a pointer to a
2656// literal string in a cstring section. If that address is in a cstring section
2657// it returns a pointer to that string. Else it returns nullptr.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00002658static const char *GuessCstringPointer(uint64_t ReferenceValue,
2659 struct DisassembleInfo *info) {
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00002660 for (const auto &Load : info->O->load_commands()) {
Kevin Enderbybf246f52014-09-24 23:08:22 +00002661 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
2662 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
2663 for (unsigned J = 0; J < Seg.nsects; ++J) {
2664 MachO::section_64 Sec = info->O->getSection64(Load, J);
2665 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
2666 if (section_type == MachO::S_CSTRING_LITERALS &&
2667 ReferenceValue >= Sec.addr &&
2668 ReferenceValue < Sec.addr + Sec.size) {
2669 uint64_t sect_offset = ReferenceValue - Sec.addr;
2670 uint64_t object_offset = Sec.offset + sect_offset;
2671 StringRef MachOContents = info->O->getData();
2672 uint64_t object_size = MachOContents.size();
2673 const char *object_addr = (const char *)MachOContents.data();
2674 if (object_offset < object_size) {
2675 const char *name = object_addr + object_offset;
2676 return name;
2677 } else {
2678 return nullptr;
2679 }
2680 }
2681 }
2682 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
2683 MachO::segment_command Seg = info->O->getSegmentLoadCommand(Load);
2684 for (unsigned J = 0; J < Seg.nsects; ++J) {
2685 MachO::section Sec = info->O->getSection(Load, J);
2686 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
2687 if (section_type == MachO::S_CSTRING_LITERALS &&
2688 ReferenceValue >= Sec.addr &&
2689 ReferenceValue < Sec.addr + Sec.size) {
2690 uint64_t sect_offset = ReferenceValue - Sec.addr;
2691 uint64_t object_offset = Sec.offset + sect_offset;
2692 StringRef MachOContents = info->O->getData();
2693 uint64_t object_size = MachOContents.size();
2694 const char *object_addr = (const char *)MachOContents.data();
2695 if (object_offset < object_size) {
2696 const char *name = object_addr + object_offset;
2697 return name;
2698 } else {
2699 return nullptr;
2700 }
2701 }
2702 }
2703 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00002704 }
2705 return nullptr;
2706}
2707
Kevin Enderby85974882014-09-26 22:20:44 +00002708// GuessIndirectSymbol returns the name of the indirect symbol for the
2709// ReferenceValue passed in or nullptr. This is used when ReferenceValue maybe
2710// an address of a symbol stub or a lazy or non-lazy pointer to associate the
2711// symbol name being referenced by the stub or pointer.
2712static const char *GuessIndirectSymbol(uint64_t ReferenceValue,
2713 struct DisassembleInfo *info) {
Kevin Enderby85974882014-09-26 22:20:44 +00002714 MachO::dysymtab_command Dysymtab = info->O->getDysymtabLoadCommand();
2715 MachO::symtab_command Symtab = info->O->getSymtabLoadCommand();
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00002716 for (const auto &Load : info->O->load_commands()) {
Kevin Enderby85974882014-09-26 22:20:44 +00002717 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
2718 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
2719 for (unsigned J = 0; J < Seg.nsects; ++J) {
2720 MachO::section_64 Sec = info->O->getSection64(Load, J);
2721 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
2722 if ((section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
2723 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
2724 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
2725 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
2726 section_type == MachO::S_SYMBOL_STUBS) &&
2727 ReferenceValue >= Sec.addr &&
2728 ReferenceValue < Sec.addr + Sec.size) {
2729 uint32_t stride;
2730 if (section_type == MachO::S_SYMBOL_STUBS)
2731 stride = Sec.reserved2;
2732 else
2733 stride = 8;
2734 if (stride == 0)
2735 return nullptr;
2736 uint32_t index = Sec.reserved1 + (ReferenceValue - Sec.addr) / stride;
2737 if (index < Dysymtab.nindirectsyms) {
2738 uint32_t indirect_symbol =
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002739 info->O->getIndirectSymbolTableEntry(Dysymtab, index);
Kevin Enderby85974882014-09-26 22:20:44 +00002740 if (indirect_symbol < Symtab.nsyms) {
2741 symbol_iterator Sym = info->O->getSymbolByIndex(indirect_symbol);
2742 SymbolRef Symbol = *Sym;
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00002743 Expected<StringRef> SymName = Symbol.getName();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00002744 if (!SymName)
2745 report_error(info->O->getFileName(), SymName.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00002746 const char *name = SymName->data();
Kevin Enderby85974882014-09-26 22:20:44 +00002747 return name;
2748 }
2749 }
2750 }
2751 }
2752 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
2753 MachO::segment_command Seg = info->O->getSegmentLoadCommand(Load);
2754 for (unsigned J = 0; J < Seg.nsects; ++J) {
2755 MachO::section Sec = info->O->getSection(Load, J);
2756 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
2757 if ((section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
2758 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
2759 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
2760 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
2761 section_type == MachO::S_SYMBOL_STUBS) &&
2762 ReferenceValue >= Sec.addr &&
2763 ReferenceValue < Sec.addr + Sec.size) {
2764 uint32_t stride;
2765 if (section_type == MachO::S_SYMBOL_STUBS)
2766 stride = Sec.reserved2;
2767 else
2768 stride = 4;
2769 if (stride == 0)
2770 return nullptr;
2771 uint32_t index = Sec.reserved1 + (ReferenceValue - Sec.addr) / stride;
2772 if (index < Dysymtab.nindirectsyms) {
2773 uint32_t indirect_symbol =
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002774 info->O->getIndirectSymbolTableEntry(Dysymtab, index);
Kevin Enderby85974882014-09-26 22:20:44 +00002775 if (indirect_symbol < Symtab.nsyms) {
2776 symbol_iterator Sym = info->O->getSymbolByIndex(indirect_symbol);
2777 SymbolRef Symbol = *Sym;
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00002778 Expected<StringRef> SymName = Symbol.getName();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00002779 if (!SymName)
2780 report_error(info->O->getFileName(), SymName.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00002781 const char *name = SymName->data();
Kevin Enderby85974882014-09-26 22:20:44 +00002782 return name;
2783 }
2784 }
2785 }
2786 }
2787 }
Kevin Enderby85974882014-09-26 22:20:44 +00002788 }
2789 return nullptr;
2790}
2791
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002792// method_reference() is called passing it the ReferenceName that might be
2793// a reference it to an Objective-C method call. If so then it allocates and
2794// assembles a method call string with the values last seen and saved in
2795// the DisassembleInfo's class_name and selector_name fields. This is saved
2796// into the method field of the info and any previous string is free'ed.
2797// Then the class_name field in the info is set to nullptr. The method call
2798// string is set into ReferenceName and ReferenceType is set to
2799// LLVMDisassembler_ReferenceType_Out_Objc_Message. If this not a method call
2800// then both ReferenceType and ReferenceName are left unchanged.
2801static void method_reference(struct DisassembleInfo *info,
2802 uint64_t *ReferenceType,
2803 const char **ReferenceName) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002804 unsigned int Arch = info->O->getArch();
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002805 if (*ReferenceName != nullptr) {
2806 if (strcmp(*ReferenceName, "_objc_msgSend") == 0) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002807 if (info->selector_name != nullptr) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002808 if (info->class_name != nullptr) {
David Blaikie0e550682018-02-20 18:48:51 +00002809 info->method = llvm::make_unique<char[]>(
2810 5 + strlen(info->class_name) + strlen(info->selector_name));
2811 char *method = info->method.get();
2812 if (method != nullptr) {
2813 strcpy(method, "+[");
2814 strcat(method, info->class_name);
2815 strcat(method, " ");
2816 strcat(method, info->selector_name);
2817 strcat(method, "]");
2818 *ReferenceName = method;
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002819 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
2820 }
2821 } else {
David Blaikie0e550682018-02-20 18:48:51 +00002822 info->method =
2823 llvm::make_unique<char[]>(9 + strlen(info->selector_name));
2824 char *method = info->method.get();
2825 if (method != nullptr) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002826 if (Arch == Triple::x86_64)
David Blaikie0e550682018-02-20 18:48:51 +00002827 strcpy(method, "-[%rdi ");
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002828 else if (Arch == Triple::aarch64)
David Blaikie0e550682018-02-20 18:48:51 +00002829 strcpy(method, "-[x0 ");
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002830 else
David Blaikie0e550682018-02-20 18:48:51 +00002831 strcpy(method, "-[r? ");
2832 strcat(method, info->selector_name);
2833 strcat(method, "]");
2834 *ReferenceName = method;
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002835 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
2836 }
2837 }
2838 info->class_name = nullptr;
2839 }
2840 } else if (strcmp(*ReferenceName, "_objc_msgSendSuper2") == 0) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002841 if (info->selector_name != nullptr) {
David Blaikie0e550682018-02-20 18:48:51 +00002842 info->method =
2843 llvm::make_unique<char[]>(17 + strlen(info->selector_name));
2844 char *method = info->method.get();
2845 if (method != nullptr) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002846 if (Arch == Triple::x86_64)
David Blaikie0e550682018-02-20 18:48:51 +00002847 strcpy(method, "-[[%rdi super] ");
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002848 else if (Arch == Triple::aarch64)
David Blaikie0e550682018-02-20 18:48:51 +00002849 strcpy(method, "-[[x0 super] ");
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002850 else
David Blaikie0e550682018-02-20 18:48:51 +00002851 strcpy(method, "-[[r? super] ");
2852 strcat(method, info->selector_name);
2853 strcat(method, "]");
2854 *ReferenceName = method;
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002855 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
2856 }
2857 info->class_name = nullptr;
2858 }
2859 }
2860 }
2861}
2862
2863// GuessPointerPointer() is passed the address of what might be a pointer to
2864// a reference to an Objective-C class, selector, message ref or cfstring.
2865// If so the value of the pointer is returned and one of the booleans are set
2866// to true. If not zero is returned and all the booleans are set to false.
2867static uint64_t GuessPointerPointer(uint64_t ReferenceValue,
2868 struct DisassembleInfo *info,
2869 bool &classref, bool &selref, bool &msgref,
2870 bool &cfstring) {
2871 classref = false;
2872 selref = false;
2873 msgref = false;
2874 cfstring = false;
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00002875 for (const auto &Load : info->O->load_commands()) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002876 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
2877 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
2878 for (unsigned J = 0; J < Seg.nsects; ++J) {
2879 MachO::section_64 Sec = info->O->getSection64(Load, J);
2880 if ((strncmp(Sec.sectname, "__objc_selrefs", 16) == 0 ||
2881 strncmp(Sec.sectname, "__objc_classrefs", 16) == 0 ||
2882 strncmp(Sec.sectname, "__objc_superrefs", 16) == 0 ||
2883 strncmp(Sec.sectname, "__objc_msgrefs", 16) == 0 ||
2884 strncmp(Sec.sectname, "__cfstring", 16) == 0) &&
2885 ReferenceValue >= Sec.addr &&
2886 ReferenceValue < Sec.addr + Sec.size) {
2887 uint64_t sect_offset = ReferenceValue - Sec.addr;
2888 uint64_t object_offset = Sec.offset + sect_offset;
2889 StringRef MachOContents = info->O->getData();
2890 uint64_t object_size = MachOContents.size();
2891 const char *object_addr = (const char *)MachOContents.data();
2892 if (object_offset < object_size) {
2893 uint64_t pointer_value;
2894 memcpy(&pointer_value, object_addr + object_offset,
2895 sizeof(uint64_t));
2896 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
2897 sys::swapByteOrder(pointer_value);
2898 if (strncmp(Sec.sectname, "__objc_selrefs", 16) == 0)
2899 selref = true;
2900 else if (strncmp(Sec.sectname, "__objc_classrefs", 16) == 0 ||
2901 strncmp(Sec.sectname, "__objc_superrefs", 16) == 0)
2902 classref = true;
2903 else if (strncmp(Sec.sectname, "__objc_msgrefs", 16) == 0 &&
2904 ReferenceValue + 8 < Sec.addr + Sec.size) {
2905 msgref = true;
2906 memcpy(&pointer_value, object_addr + object_offset + 8,
2907 sizeof(uint64_t));
2908 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
2909 sys::swapByteOrder(pointer_value);
2910 } else if (strncmp(Sec.sectname, "__cfstring", 16) == 0)
2911 cfstring = true;
2912 return pointer_value;
2913 } else {
2914 return 0;
2915 }
2916 }
2917 }
2918 }
2919 // TODO: Look for LC_SEGMENT for 32-bit Mach-O files.
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002920 }
2921 return 0;
2922}
2923
2924// get_pointer_64 returns a pointer to the bytes in the object file at the
2925// Address from a section in the Mach-O file. And indirectly returns the
2926// offset into the section, number of bytes left in the section past the offset
2927// and which section is was being referenced. If the Address is not in a
2928// section nullptr is returned.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00002929static const char *get_pointer_64(uint64_t Address, uint32_t &offset,
2930 uint32_t &left, SectionRef &S,
Kevin Enderby846c0002015-04-16 17:19:59 +00002931 DisassembleInfo *info,
2932 bool objc_only = false) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002933 offset = 0;
2934 left = 0;
2935 S = SectionRef();
2936 for (unsigned SectIdx = 0; SectIdx != info->Sections->size(); SectIdx++) {
2937 uint64_t SectAddress = ((*(info->Sections))[SectIdx]).getAddress();
2938 uint64_t SectSize = ((*(info->Sections))[SectIdx]).getSize();
Kevin Enderby46e642f2015-10-08 22:50:55 +00002939 if (SectSize == 0)
2940 continue;
Kevin Enderby846c0002015-04-16 17:19:59 +00002941 if (objc_only) {
2942 StringRef SectName;
2943 ((*(info->Sections))[SectIdx]).getName(SectName);
2944 DataRefImpl Ref = ((*(info->Sections))[SectIdx]).getRawDataRefImpl();
2945 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
2946 if (SegName != "__OBJC" && SectName != "__cstring")
2947 continue;
2948 }
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002949 if (Address >= SectAddress && Address < SectAddress + SectSize) {
2950 S = (*(info->Sections))[SectIdx];
2951 offset = Address - SectAddress;
2952 left = SectSize - offset;
2953 StringRef SectContents;
2954 ((*(info->Sections))[SectIdx]).getContents(SectContents);
2955 return SectContents.data() + offset;
2956 }
2957 }
2958 return nullptr;
2959}
2960
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002961static const char *get_pointer_32(uint32_t Address, uint32_t &offset,
2962 uint32_t &left, SectionRef &S,
Kevin Enderby846c0002015-04-16 17:19:59 +00002963 DisassembleInfo *info,
2964 bool objc_only = false) {
2965 return get_pointer_64(Address, offset, left, S, info, objc_only);
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002966}
2967
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002968// get_symbol_64() returns the name of a symbol (or nullptr) and the address of
2969// the symbol indirectly through n_value. Based on the relocation information
2970// for the specified section offset in the specified section reference.
Kevin Enderby0fc11822015-04-01 20:57:01 +00002971// If no relocation information is found and a non-zero ReferenceValue for the
2972// symbol is passed, look up that address in the info's AddrMap.
Rafael Espindolad7a32ea2015-06-24 10:20:30 +00002973static const char *get_symbol_64(uint32_t sect_offset, SectionRef S,
2974 DisassembleInfo *info, uint64_t &n_value,
Rafael Espindolabe8b0ea2015-07-07 17:12:59 +00002975 uint64_t ReferenceValue = 0) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002976 n_value = 0;
David Blaikie33dd45d02015-03-23 18:39:02 +00002977 if (!info->verbose)
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002978 return nullptr;
2979
2980 // See if there is an external relocation entry at the sect_offset.
2981 bool reloc_found = false;
2982 DataRefImpl Rel;
2983 MachO::any_relocation_info RE;
2984 bool isExtern = false;
2985 SymbolRef Symbol;
2986 for (const RelocationRef &Reloc : S.relocations()) {
Rafael Espindola96d071c2015-06-29 23:29:12 +00002987 uint64_t RelocOffset = Reloc.getOffset();
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002988 if (RelocOffset == sect_offset) {
2989 Rel = Reloc.getRawDataRefImpl();
2990 RE = info->O->getRelocation(Rel);
2991 if (info->O->isRelocationScattered(RE))
2992 continue;
2993 isExtern = info->O->getPlainRelocationExternal(RE);
2994 if (isExtern) {
2995 symbol_iterator RelocSym = Reloc.getSymbol();
2996 Symbol = *RelocSym;
2997 }
2998 reloc_found = true;
2999 break;
3000 }
3001 }
3002 // If there is an external relocation entry for a symbol in this section
3003 // at this section_offset then use that symbol's value for the n_value
3004 // and return its name.
3005 const char *SymbolName = nullptr;
3006 if (reloc_found && isExtern) {
Rafael Espindoladea00162015-07-03 17:44:18 +00003007 n_value = Symbol.getValue();
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00003008 Expected<StringRef> NameOrError = Symbol.getName();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00003009 if (!NameOrError)
3010 report_error(info->O->getFileName(), NameOrError.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00003011 StringRef Name = *NameOrError;
3012 if (!Name.empty()) {
3013 SymbolName = Name.data();
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003014 return SymbolName;
3015 }
3016 }
3017
3018 // TODO: For fully linked images, look through the external relocation
3019 // entries off the dynamic symtab command. For these the r_offset is from the
3020 // start of the first writeable segment in the Mach-O file. So the offset
3021 // to this section from that segment is passed to this routine by the caller,
3022 // as the database_offset. Which is the difference of the section's starting
3023 // address and the first writable segment.
3024 //
3025 // NOTE: need add passing the database_offset to this routine.
3026
Kevin Enderby0fc11822015-04-01 20:57:01 +00003027 // We did not find an external relocation entry so look up the ReferenceValue
3028 // as an address of a symbol and if found return that symbol's name.
Rafael Espindolabe8b0ea2015-07-07 17:12:59 +00003029 SymbolName = GuessSymbolName(ReferenceValue, info->AddrMap);
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003030
3031 return SymbolName;
3032}
3033
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003034static const char *get_symbol_32(uint32_t sect_offset, SectionRef S,
3035 DisassembleInfo *info,
3036 uint32_t ReferenceValue) {
3037 uint64_t n_value64;
3038 return get_symbol_64(sect_offset, S, info, n_value64, ReferenceValue);
3039}
3040
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003041// These are structs in the Objective-C meta data and read to produce the
3042// comments for disassembly. While these are part of the ABI they are no
Zachary Turner264b5d92017-06-07 03:48:56 +00003043// public defintions. So the are here not in include/llvm/BinaryFormat/MachO.h
3044// .
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003045
3046// The cfstring object in a 64-bit Mach-O file.
3047struct cfstring64_t {
3048 uint64_t isa; // class64_t * (64-bit pointer)
3049 uint64_t flags; // flag bits
3050 uint64_t characters; // char * (64-bit pointer)
3051 uint64_t length; // number of non-NULL characters in above
3052};
3053
3054// The class object in a 64-bit Mach-O file.
3055struct class64_t {
3056 uint64_t isa; // class64_t * (64-bit pointer)
3057 uint64_t superclass; // class64_t * (64-bit pointer)
3058 uint64_t cache; // Cache (64-bit pointer)
3059 uint64_t vtable; // IMP * (64-bit pointer)
3060 uint64_t data; // class_ro64_t * (64-bit pointer)
3061};
3062
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003063struct class32_t {
3064 uint32_t isa; /* class32_t * (32-bit pointer) */
3065 uint32_t superclass; /* class32_t * (32-bit pointer) */
3066 uint32_t cache; /* Cache (32-bit pointer) */
3067 uint32_t vtable; /* IMP * (32-bit pointer) */
3068 uint32_t data; /* class_ro32_t * (32-bit pointer) */
3069};
3070
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003071struct class_ro64_t {
3072 uint32_t flags;
3073 uint32_t instanceStart;
3074 uint32_t instanceSize;
3075 uint32_t reserved;
3076 uint64_t ivarLayout; // const uint8_t * (64-bit pointer)
3077 uint64_t name; // const char * (64-bit pointer)
3078 uint64_t baseMethods; // const method_list_t * (64-bit pointer)
3079 uint64_t baseProtocols; // const protocol_list_t * (64-bit pointer)
3080 uint64_t ivars; // const ivar_list_t * (64-bit pointer)
3081 uint64_t weakIvarLayout; // const uint8_t * (64-bit pointer)
3082 uint64_t baseProperties; // const struct objc_property_list (64-bit pointer)
3083};
3084
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003085struct class_ro32_t {
3086 uint32_t flags;
3087 uint32_t instanceStart;
3088 uint32_t instanceSize;
3089 uint32_t ivarLayout; /* const uint8_t * (32-bit pointer) */
3090 uint32_t name; /* const char * (32-bit pointer) */
3091 uint32_t baseMethods; /* const method_list_t * (32-bit pointer) */
3092 uint32_t baseProtocols; /* const protocol_list_t * (32-bit pointer) */
3093 uint32_t ivars; /* const ivar_list_t * (32-bit pointer) */
3094 uint32_t weakIvarLayout; /* const uint8_t * (32-bit pointer) */
3095 uint32_t baseProperties; /* const struct objc_property_list *
3096 (32-bit pointer) */
3097};
3098
3099/* Values for class_ro{64,32}_t->flags */
Kevin Enderby0fc11822015-04-01 20:57:01 +00003100#define RO_META (1 << 0)
3101#define RO_ROOT (1 << 1)
3102#define RO_HAS_CXX_STRUCTORS (1 << 2)
3103
3104struct method_list64_t {
3105 uint32_t entsize;
3106 uint32_t count;
3107 /* struct method64_t first; These structures follow inline */
3108};
3109
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003110struct method_list32_t {
3111 uint32_t entsize;
3112 uint32_t count;
3113 /* struct method32_t first; These structures follow inline */
3114};
3115
Kevin Enderby0fc11822015-04-01 20:57:01 +00003116struct method64_t {
3117 uint64_t name; /* SEL (64-bit pointer) */
3118 uint64_t types; /* const char * (64-bit pointer) */
3119 uint64_t imp; /* IMP (64-bit pointer) */
3120};
3121
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003122struct method32_t {
3123 uint32_t name; /* SEL (32-bit pointer) */
3124 uint32_t types; /* const char * (32-bit pointer) */
3125 uint32_t imp; /* IMP (32-bit pointer) */
3126};
3127
Kevin Enderby0fc11822015-04-01 20:57:01 +00003128struct protocol_list64_t {
3129 uint64_t count; /* uintptr_t (a 64-bit value) */
3130 /* struct protocol64_t * list[0]; These pointers follow inline */
3131};
3132
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003133struct protocol_list32_t {
3134 uint32_t count; /* uintptr_t (a 32-bit value) */
3135 /* struct protocol32_t * list[0]; These pointers follow inline */
3136};
3137
Kevin Enderby0fc11822015-04-01 20:57:01 +00003138struct protocol64_t {
3139 uint64_t isa; /* id * (64-bit pointer) */
3140 uint64_t name; /* const char * (64-bit pointer) */
3141 uint64_t protocols; /* struct protocol_list64_t *
3142 (64-bit pointer) */
3143 uint64_t instanceMethods; /* method_list_t * (64-bit pointer) */
3144 uint64_t classMethods; /* method_list_t * (64-bit pointer) */
3145 uint64_t optionalInstanceMethods; /* method_list_t * (64-bit pointer) */
3146 uint64_t optionalClassMethods; /* method_list_t * (64-bit pointer) */
3147 uint64_t instanceProperties; /* struct objc_property_list *
3148 (64-bit pointer) */
3149};
3150
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003151struct protocol32_t {
3152 uint32_t isa; /* id * (32-bit pointer) */
3153 uint32_t name; /* const char * (32-bit pointer) */
3154 uint32_t protocols; /* struct protocol_list_t *
3155 (32-bit pointer) */
3156 uint32_t instanceMethods; /* method_list_t * (32-bit pointer) */
3157 uint32_t classMethods; /* method_list_t * (32-bit pointer) */
3158 uint32_t optionalInstanceMethods; /* method_list_t * (32-bit pointer) */
3159 uint32_t optionalClassMethods; /* method_list_t * (32-bit pointer) */
3160 uint32_t instanceProperties; /* struct objc_property_list *
3161 (32-bit pointer) */
3162};
3163
Kevin Enderby0fc11822015-04-01 20:57:01 +00003164struct ivar_list64_t {
3165 uint32_t entsize;
3166 uint32_t count;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003167 /* struct ivar64_t first; These structures follow inline */
3168};
3169
3170struct ivar_list32_t {
3171 uint32_t entsize;
3172 uint32_t count;
3173 /* struct ivar32_t first; These structures follow inline */
Kevin Enderby0fc11822015-04-01 20:57:01 +00003174};
3175
3176struct ivar64_t {
3177 uint64_t offset; /* uintptr_t * (64-bit pointer) */
3178 uint64_t name; /* const char * (64-bit pointer) */
3179 uint64_t type; /* const char * (64-bit pointer) */
3180 uint32_t alignment;
3181 uint32_t size;
3182};
3183
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003184struct ivar32_t {
3185 uint32_t offset; /* uintptr_t * (32-bit pointer) */
3186 uint32_t name; /* const char * (32-bit pointer) */
3187 uint32_t type; /* const char * (32-bit pointer) */
3188 uint32_t alignment;
3189 uint32_t size;
3190};
3191
Kevin Enderby0fc11822015-04-01 20:57:01 +00003192struct objc_property_list64 {
3193 uint32_t entsize;
3194 uint32_t count;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003195 /* struct objc_property64 first; These structures follow inline */
3196};
3197
3198struct objc_property_list32 {
3199 uint32_t entsize;
3200 uint32_t count;
3201 /* struct objc_property32 first; These structures follow inline */
Kevin Enderby0fc11822015-04-01 20:57:01 +00003202};
3203
3204struct objc_property64 {
3205 uint64_t name; /* const char * (64-bit pointer) */
3206 uint64_t attributes; /* const char * (64-bit pointer) */
3207};
3208
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003209struct objc_property32 {
3210 uint32_t name; /* const char * (32-bit pointer) */
3211 uint32_t attributes; /* const char * (32-bit pointer) */
3212};
3213
Kevin Enderby0fc11822015-04-01 20:57:01 +00003214struct category64_t {
3215 uint64_t name; /* const char * (64-bit pointer) */
3216 uint64_t cls; /* struct class_t * (64-bit pointer) */
3217 uint64_t instanceMethods; /* struct method_list_t * (64-bit pointer) */
3218 uint64_t classMethods; /* struct method_list_t * (64-bit pointer) */
3219 uint64_t protocols; /* struct protocol_list_t * (64-bit pointer) */
3220 uint64_t instanceProperties; /* struct objc_property_list *
3221 (64-bit pointer) */
3222};
3223
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003224struct category32_t {
3225 uint32_t name; /* const char * (32-bit pointer) */
3226 uint32_t cls; /* struct class_t * (32-bit pointer) */
3227 uint32_t instanceMethods; /* struct method_list_t * (32-bit pointer) */
3228 uint32_t classMethods; /* struct method_list_t * (32-bit pointer) */
3229 uint32_t protocols; /* struct protocol_list_t * (32-bit pointer) */
3230 uint32_t instanceProperties; /* struct objc_property_list *
3231 (32-bit pointer) */
3232};
3233
Kevin Enderby0fc11822015-04-01 20:57:01 +00003234struct objc_image_info64 {
3235 uint32_t version;
3236 uint32_t flags;
3237};
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003238struct objc_image_info32 {
3239 uint32_t version;
3240 uint32_t flags;
3241};
Kevin Enderby846c0002015-04-16 17:19:59 +00003242struct imageInfo_t {
3243 uint32_t version;
3244 uint32_t flags;
3245};
Kevin Enderby0fc11822015-04-01 20:57:01 +00003246/* masks for objc_image_info.flags */
3247#define OBJC_IMAGE_IS_REPLACEMENT (1 << 0)
3248#define OBJC_IMAGE_SUPPORTS_GC (1 << 1)
Dave Lee390abe42018-07-06 05:11:35 +00003249#define OBJC_IMAGE_IS_SIMULATED (1 << 5)
3250#define OBJC_IMAGE_HAS_CATEGORY_CLASS_PROPERTIES (1 << 6)
Kevin Enderby0fc11822015-04-01 20:57:01 +00003251
3252struct message_ref64 {
3253 uint64_t imp; /* IMP (64-bit pointer) */
3254 uint64_t sel; /* SEL (64-bit pointer) */
3255};
3256
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003257struct message_ref32 {
3258 uint32_t imp; /* IMP (32-bit pointer) */
3259 uint32_t sel; /* SEL (32-bit pointer) */
3260};
3261
Kevin Enderby846c0002015-04-16 17:19:59 +00003262// Objective-C 1 (32-bit only) meta data structs.
3263
3264struct objc_module_t {
3265 uint32_t version;
3266 uint32_t size;
3267 uint32_t name; /* char * (32-bit pointer) */
3268 uint32_t symtab; /* struct objc_symtab * (32-bit pointer) */
3269};
3270
3271struct objc_symtab_t {
3272 uint32_t sel_ref_cnt;
3273 uint32_t refs; /* SEL * (32-bit pointer) */
3274 uint16_t cls_def_cnt;
3275 uint16_t cat_def_cnt;
3276 // uint32_t defs[1]; /* void * (32-bit pointer) variable size */
3277};
3278
3279struct objc_class_t {
3280 uint32_t isa; /* struct objc_class * (32-bit pointer) */
3281 uint32_t super_class; /* struct objc_class * (32-bit pointer) */
3282 uint32_t name; /* const char * (32-bit pointer) */
3283 int32_t version;
3284 int32_t info;
3285 int32_t instance_size;
3286 uint32_t ivars; /* struct objc_ivar_list * (32-bit pointer) */
3287 uint32_t methodLists; /* struct objc_method_list ** (32-bit pointer) */
3288 uint32_t cache; /* struct objc_cache * (32-bit pointer) */
3289 uint32_t protocols; /* struct objc_protocol_list * (32-bit pointer) */
3290};
3291
3292#define CLS_GETINFO(cls, infomask) ((cls)->info & (infomask))
3293// class is not a metaclass
3294#define CLS_CLASS 0x1
3295// class is a metaclass
3296#define CLS_META 0x2
3297
3298struct objc_category_t {
3299 uint32_t category_name; /* char * (32-bit pointer) */
3300 uint32_t class_name; /* char * (32-bit pointer) */
3301 uint32_t instance_methods; /* struct objc_method_list * (32-bit pointer) */
3302 uint32_t class_methods; /* struct objc_method_list * (32-bit pointer) */
3303 uint32_t protocols; /* struct objc_protocol_list * (32-bit ptr) */
3304};
3305
3306struct objc_ivar_t {
3307 uint32_t ivar_name; /* char * (32-bit pointer) */
3308 uint32_t ivar_type; /* char * (32-bit pointer) */
3309 int32_t ivar_offset;
3310};
3311
3312struct objc_ivar_list_t {
3313 int32_t ivar_count;
3314 // struct objc_ivar_t ivar_list[1]; /* variable length structure */
3315};
3316
3317struct objc_method_list_t {
3318 uint32_t obsolete; /* struct objc_method_list * (32-bit pointer) */
3319 int32_t method_count;
3320 // struct objc_method_t method_list[1]; /* variable length structure */
3321};
3322
3323struct objc_method_t {
3324 uint32_t method_name; /* SEL, aka struct objc_selector * (32-bit pointer) */
3325 uint32_t method_types; /* char * (32-bit pointer) */
3326 uint32_t method_imp; /* IMP, aka function pointer, (*IMP)(id, SEL, ...)
3327 (32-bit pointer) */
3328};
3329
3330struct objc_protocol_list_t {
3331 uint32_t next; /* struct objc_protocol_list * (32-bit pointer) */
3332 int32_t count;
3333 // uint32_t list[1]; /* Protocol *, aka struct objc_protocol_t *
3334 // (32-bit pointer) */
3335};
3336
3337struct objc_protocol_t {
3338 uint32_t isa; /* struct objc_class * (32-bit pointer) */
3339 uint32_t protocol_name; /* char * (32-bit pointer) */
3340 uint32_t protocol_list; /* struct objc_protocol_list * (32-bit pointer) */
3341 uint32_t instance_methods; /* struct objc_method_description_list *
3342 (32-bit pointer) */
3343 uint32_t class_methods; /* struct objc_method_description_list *
3344 (32-bit pointer) */
3345};
3346
3347struct objc_method_description_list_t {
3348 int32_t count;
3349 // struct objc_method_description_t list[1];
3350};
3351
3352struct objc_method_description_t {
3353 uint32_t name; /* SEL, aka struct objc_selector * (32-bit pointer) */
3354 uint32_t types; /* char * (32-bit pointer) */
3355};
3356
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003357inline void swapStruct(struct cfstring64_t &cfs) {
3358 sys::swapByteOrder(cfs.isa);
3359 sys::swapByteOrder(cfs.flags);
3360 sys::swapByteOrder(cfs.characters);
3361 sys::swapByteOrder(cfs.length);
3362}
3363
3364inline void swapStruct(struct class64_t &c) {
3365 sys::swapByteOrder(c.isa);
3366 sys::swapByteOrder(c.superclass);
3367 sys::swapByteOrder(c.cache);
3368 sys::swapByteOrder(c.vtable);
3369 sys::swapByteOrder(c.data);
3370}
3371
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003372inline void swapStruct(struct class32_t &c) {
3373 sys::swapByteOrder(c.isa);
3374 sys::swapByteOrder(c.superclass);
3375 sys::swapByteOrder(c.cache);
3376 sys::swapByteOrder(c.vtable);
3377 sys::swapByteOrder(c.data);
3378}
3379
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003380inline void swapStruct(struct class_ro64_t &cro) {
3381 sys::swapByteOrder(cro.flags);
3382 sys::swapByteOrder(cro.instanceStart);
3383 sys::swapByteOrder(cro.instanceSize);
3384 sys::swapByteOrder(cro.reserved);
3385 sys::swapByteOrder(cro.ivarLayout);
3386 sys::swapByteOrder(cro.name);
3387 sys::swapByteOrder(cro.baseMethods);
3388 sys::swapByteOrder(cro.baseProtocols);
3389 sys::swapByteOrder(cro.ivars);
3390 sys::swapByteOrder(cro.weakIvarLayout);
3391 sys::swapByteOrder(cro.baseProperties);
3392}
3393
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003394inline void swapStruct(struct class_ro32_t &cro) {
3395 sys::swapByteOrder(cro.flags);
3396 sys::swapByteOrder(cro.instanceStart);
3397 sys::swapByteOrder(cro.instanceSize);
3398 sys::swapByteOrder(cro.ivarLayout);
3399 sys::swapByteOrder(cro.name);
3400 sys::swapByteOrder(cro.baseMethods);
3401 sys::swapByteOrder(cro.baseProtocols);
3402 sys::swapByteOrder(cro.ivars);
3403 sys::swapByteOrder(cro.weakIvarLayout);
3404 sys::swapByteOrder(cro.baseProperties);
3405}
3406
Kevin Enderby0fc11822015-04-01 20:57:01 +00003407inline void swapStruct(struct method_list64_t &ml) {
3408 sys::swapByteOrder(ml.entsize);
3409 sys::swapByteOrder(ml.count);
3410}
3411
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003412inline void swapStruct(struct method_list32_t &ml) {
3413 sys::swapByteOrder(ml.entsize);
3414 sys::swapByteOrder(ml.count);
3415}
3416
Kevin Enderby0fc11822015-04-01 20:57:01 +00003417inline void swapStruct(struct method64_t &m) {
3418 sys::swapByteOrder(m.name);
3419 sys::swapByteOrder(m.types);
3420 sys::swapByteOrder(m.imp);
3421}
3422
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003423inline void swapStruct(struct method32_t &m) {
3424 sys::swapByteOrder(m.name);
3425 sys::swapByteOrder(m.types);
3426 sys::swapByteOrder(m.imp);
3427}
3428
Kevin Enderby0fc11822015-04-01 20:57:01 +00003429inline void swapStruct(struct protocol_list64_t &pl) {
3430 sys::swapByteOrder(pl.count);
3431}
3432
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003433inline void swapStruct(struct protocol_list32_t &pl) {
3434 sys::swapByteOrder(pl.count);
3435}
3436
Kevin Enderby0fc11822015-04-01 20:57:01 +00003437inline void swapStruct(struct protocol64_t &p) {
3438 sys::swapByteOrder(p.isa);
3439 sys::swapByteOrder(p.name);
3440 sys::swapByteOrder(p.protocols);
3441 sys::swapByteOrder(p.instanceMethods);
3442 sys::swapByteOrder(p.classMethods);
3443 sys::swapByteOrder(p.optionalInstanceMethods);
3444 sys::swapByteOrder(p.optionalClassMethods);
3445 sys::swapByteOrder(p.instanceProperties);
3446}
3447
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003448inline void swapStruct(struct protocol32_t &p) {
3449 sys::swapByteOrder(p.isa);
3450 sys::swapByteOrder(p.name);
3451 sys::swapByteOrder(p.protocols);
3452 sys::swapByteOrder(p.instanceMethods);
3453 sys::swapByteOrder(p.classMethods);
3454 sys::swapByteOrder(p.optionalInstanceMethods);
3455 sys::swapByteOrder(p.optionalClassMethods);
3456 sys::swapByteOrder(p.instanceProperties);
3457}
3458
Kevin Enderby0fc11822015-04-01 20:57:01 +00003459inline void swapStruct(struct ivar_list64_t &il) {
3460 sys::swapByteOrder(il.entsize);
3461 sys::swapByteOrder(il.count);
3462}
3463
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003464inline void swapStruct(struct ivar_list32_t &il) {
3465 sys::swapByteOrder(il.entsize);
3466 sys::swapByteOrder(il.count);
3467}
3468
Kevin Enderby0fc11822015-04-01 20:57:01 +00003469inline void swapStruct(struct ivar64_t &i) {
3470 sys::swapByteOrder(i.offset);
3471 sys::swapByteOrder(i.name);
3472 sys::swapByteOrder(i.type);
3473 sys::swapByteOrder(i.alignment);
3474 sys::swapByteOrder(i.size);
3475}
3476
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003477inline void swapStruct(struct ivar32_t &i) {
3478 sys::swapByteOrder(i.offset);
3479 sys::swapByteOrder(i.name);
3480 sys::swapByteOrder(i.type);
3481 sys::swapByteOrder(i.alignment);
3482 sys::swapByteOrder(i.size);
3483}
3484
Kevin Enderby0fc11822015-04-01 20:57:01 +00003485inline void swapStruct(struct objc_property_list64 &pl) {
3486 sys::swapByteOrder(pl.entsize);
3487 sys::swapByteOrder(pl.count);
3488}
3489
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003490inline void swapStruct(struct objc_property_list32 &pl) {
3491 sys::swapByteOrder(pl.entsize);
3492 sys::swapByteOrder(pl.count);
3493}
3494
Kevin Enderby0fc11822015-04-01 20:57:01 +00003495inline void swapStruct(struct objc_property64 &op) {
3496 sys::swapByteOrder(op.name);
3497 sys::swapByteOrder(op.attributes);
3498}
3499
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003500inline void swapStruct(struct objc_property32 &op) {
3501 sys::swapByteOrder(op.name);
3502 sys::swapByteOrder(op.attributes);
3503}
3504
Kevin Enderby0fc11822015-04-01 20:57:01 +00003505inline void swapStruct(struct category64_t &c) {
3506 sys::swapByteOrder(c.name);
3507 sys::swapByteOrder(c.cls);
3508 sys::swapByteOrder(c.instanceMethods);
3509 sys::swapByteOrder(c.classMethods);
3510 sys::swapByteOrder(c.protocols);
3511 sys::swapByteOrder(c.instanceProperties);
3512}
3513
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003514inline void swapStruct(struct category32_t &c) {
3515 sys::swapByteOrder(c.name);
3516 sys::swapByteOrder(c.cls);
3517 sys::swapByteOrder(c.instanceMethods);
3518 sys::swapByteOrder(c.classMethods);
3519 sys::swapByteOrder(c.protocols);
3520 sys::swapByteOrder(c.instanceProperties);
3521}
3522
Kevin Enderby0fc11822015-04-01 20:57:01 +00003523inline void swapStruct(struct objc_image_info64 &o) {
3524 sys::swapByteOrder(o.version);
3525 sys::swapByteOrder(o.flags);
3526}
3527
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003528inline void swapStruct(struct objc_image_info32 &o) {
3529 sys::swapByteOrder(o.version);
3530 sys::swapByteOrder(o.flags);
3531}
3532
Kevin Enderby846c0002015-04-16 17:19:59 +00003533inline void swapStruct(struct imageInfo_t &o) {
3534 sys::swapByteOrder(o.version);
3535 sys::swapByteOrder(o.flags);
3536}
3537
Kevin Enderby0fc11822015-04-01 20:57:01 +00003538inline void swapStruct(struct message_ref64 &mr) {
3539 sys::swapByteOrder(mr.imp);
3540 sys::swapByteOrder(mr.sel);
3541}
3542
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003543inline void swapStruct(struct message_ref32 &mr) {
3544 sys::swapByteOrder(mr.imp);
3545 sys::swapByteOrder(mr.sel);
3546}
3547
Kevin Enderby846c0002015-04-16 17:19:59 +00003548inline void swapStruct(struct objc_module_t &module) {
3549 sys::swapByteOrder(module.version);
3550 sys::swapByteOrder(module.size);
3551 sys::swapByteOrder(module.name);
3552 sys::swapByteOrder(module.symtab);
Jingyue Wufedecc42015-04-16 18:43:44 +00003553}
Kevin Enderby846c0002015-04-16 17:19:59 +00003554
3555inline void swapStruct(struct objc_symtab_t &symtab) {
3556 sys::swapByteOrder(symtab.sel_ref_cnt);
3557 sys::swapByteOrder(symtab.refs);
3558 sys::swapByteOrder(symtab.cls_def_cnt);
3559 sys::swapByteOrder(symtab.cat_def_cnt);
Jingyue Wufedecc42015-04-16 18:43:44 +00003560}
Kevin Enderby846c0002015-04-16 17:19:59 +00003561
3562inline void swapStruct(struct objc_class_t &objc_class) {
3563 sys::swapByteOrder(objc_class.isa);
3564 sys::swapByteOrder(objc_class.super_class);
3565 sys::swapByteOrder(objc_class.name);
3566 sys::swapByteOrder(objc_class.version);
3567 sys::swapByteOrder(objc_class.info);
3568 sys::swapByteOrder(objc_class.instance_size);
3569 sys::swapByteOrder(objc_class.ivars);
3570 sys::swapByteOrder(objc_class.methodLists);
3571 sys::swapByteOrder(objc_class.cache);
3572 sys::swapByteOrder(objc_class.protocols);
Jingyue Wufedecc42015-04-16 18:43:44 +00003573}
Kevin Enderby846c0002015-04-16 17:19:59 +00003574
3575inline void swapStruct(struct objc_category_t &objc_category) {
3576 sys::swapByteOrder(objc_category.category_name);
3577 sys::swapByteOrder(objc_category.class_name);
3578 sys::swapByteOrder(objc_category.instance_methods);
3579 sys::swapByteOrder(objc_category.class_methods);
3580 sys::swapByteOrder(objc_category.protocols);
3581}
3582
3583inline void swapStruct(struct objc_ivar_list_t &objc_ivar_list) {
3584 sys::swapByteOrder(objc_ivar_list.ivar_count);
3585}
3586
3587inline void swapStruct(struct objc_ivar_t &objc_ivar) {
3588 sys::swapByteOrder(objc_ivar.ivar_name);
3589 sys::swapByteOrder(objc_ivar.ivar_type);
3590 sys::swapByteOrder(objc_ivar.ivar_offset);
Jingyue Wufedecc42015-04-16 18:43:44 +00003591}
Kevin Enderby846c0002015-04-16 17:19:59 +00003592
3593inline void swapStruct(struct objc_method_list_t &method_list) {
3594 sys::swapByteOrder(method_list.obsolete);
3595 sys::swapByteOrder(method_list.method_count);
3596}
3597
3598inline void swapStruct(struct objc_method_t &method) {
3599 sys::swapByteOrder(method.method_name);
3600 sys::swapByteOrder(method.method_types);
3601 sys::swapByteOrder(method.method_imp);
3602}
3603
3604inline void swapStruct(struct objc_protocol_list_t &protocol_list) {
3605 sys::swapByteOrder(protocol_list.next);
3606 sys::swapByteOrder(protocol_list.count);
3607}
3608
3609inline void swapStruct(struct objc_protocol_t &protocol) {
3610 sys::swapByteOrder(protocol.isa);
3611 sys::swapByteOrder(protocol.protocol_name);
3612 sys::swapByteOrder(protocol.protocol_list);
3613 sys::swapByteOrder(protocol.instance_methods);
3614 sys::swapByteOrder(protocol.class_methods);
3615}
3616
3617inline void swapStruct(struct objc_method_description_list_t &mdl) {
3618 sys::swapByteOrder(mdl.count);
3619}
3620
3621inline void swapStruct(struct objc_method_description_t &md) {
3622 sys::swapByteOrder(md.name);
3623 sys::swapByteOrder(md.types);
3624}
3625
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003626static const char *get_dyld_bind_info_symbolname(uint64_t ReferenceValue,
3627 struct DisassembleInfo *info);
3628
3629// get_objc2_64bit_class_name() is used for disassembly and is passed a pointer
3630// to an Objective-C class and returns the class name. It is also passed the
3631// address of the pointer, so when the pointer is zero as it can be in an .o
3632// file, that is used to look for an external relocation entry with a symbol
3633// name.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00003634static const char *get_objc2_64bit_class_name(uint64_t pointer_value,
3635 uint64_t ReferenceValue,
3636 struct DisassembleInfo *info) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003637 const char *r;
3638 uint32_t offset, left;
3639 SectionRef S;
3640
3641 // The pointer_value can be 0 in an object file and have a relocation
3642 // entry for the class symbol at the ReferenceValue (the address of the
3643 // pointer).
3644 if (pointer_value == 0) {
3645 r = get_pointer_64(ReferenceValue, offset, left, S, info);
3646 if (r == nullptr || left < sizeof(uint64_t))
3647 return nullptr;
3648 uint64_t n_value;
3649 const char *symbol_name = get_symbol_64(offset, S, info, n_value);
3650 if (symbol_name == nullptr)
3651 return nullptr;
Hans Wennborgdb53e302014-10-23 21:59:17 +00003652 const char *class_name = strrchr(symbol_name, '$');
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003653 if (class_name != nullptr && class_name[1] == '_' && class_name[2] != '\0')
3654 return class_name + 2;
3655 else
3656 return nullptr;
3657 }
3658
3659 // The case were the pointer_value is non-zero and points to a class defined
3660 // in this Mach-O file.
3661 r = get_pointer_64(pointer_value, offset, left, S, info);
3662 if (r == nullptr || left < sizeof(struct class64_t))
3663 return nullptr;
3664 struct class64_t c;
3665 memcpy(&c, r, sizeof(struct class64_t));
3666 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3667 swapStruct(c);
3668 if (c.data == 0)
3669 return nullptr;
3670 r = get_pointer_64(c.data, offset, left, S, info);
3671 if (r == nullptr || left < sizeof(struct class_ro64_t))
3672 return nullptr;
3673 struct class_ro64_t cro;
3674 memcpy(&cro, r, sizeof(struct class_ro64_t));
3675 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3676 swapStruct(cro);
3677 if (cro.name == 0)
3678 return nullptr;
3679 const char *name = get_pointer_64(cro.name, offset, left, S, info);
3680 return name;
3681}
3682
3683// get_objc2_64bit_cfstring_name is used for disassembly and is passed a
3684// pointer to a cfstring and returns its name or nullptr.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00003685static const char *get_objc2_64bit_cfstring_name(uint64_t ReferenceValue,
3686 struct DisassembleInfo *info) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003687 const char *r, *name;
3688 uint32_t offset, left;
3689 SectionRef S;
3690 struct cfstring64_t cfs;
3691 uint64_t cfs_characters;
3692
3693 r = get_pointer_64(ReferenceValue, offset, left, S, info);
3694 if (r == nullptr || left < sizeof(struct cfstring64_t))
3695 return nullptr;
3696 memcpy(&cfs, r, sizeof(struct cfstring64_t));
3697 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3698 swapStruct(cfs);
3699 if (cfs.characters == 0) {
3700 uint64_t n_value;
3701 const char *symbol_name = get_symbol_64(
3702 offset + offsetof(struct cfstring64_t, characters), S, info, n_value);
3703 if (symbol_name == nullptr)
3704 return nullptr;
3705 cfs_characters = n_value;
3706 } else
3707 cfs_characters = cfs.characters;
3708 name = get_pointer_64(cfs_characters, offset, left, S, info);
3709
3710 return name;
3711}
3712
3713// get_objc2_64bit_selref() is used for disassembly and is passed a the address
3714// of a pointer to an Objective-C selector reference when the pointer value is
3715// zero as in a .o file and is likely to have a external relocation entry with
3716// who's symbol's n_value is the real pointer to the selector name. If that is
3717// the case the real pointer to the selector name is returned else 0 is
3718// returned
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00003719static uint64_t get_objc2_64bit_selref(uint64_t ReferenceValue,
3720 struct DisassembleInfo *info) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003721 uint32_t offset, left;
3722 SectionRef S;
3723
3724 const char *r = get_pointer_64(ReferenceValue, offset, left, S, info);
3725 if (r == nullptr || left < sizeof(uint64_t))
3726 return 0;
3727 uint64_t n_value;
3728 const char *symbol_name = get_symbol_64(offset, S, info, n_value);
3729 if (symbol_name == nullptr)
3730 return 0;
3731 return n_value;
3732}
3733
Kevin Enderby0fc11822015-04-01 20:57:01 +00003734static const SectionRef get_section(MachOObjectFile *O, const char *segname,
3735 const char *sectname) {
3736 for (const SectionRef &Section : O->sections()) {
3737 StringRef SectName;
3738 Section.getName(SectName);
3739 DataRefImpl Ref = Section.getRawDataRefImpl();
3740 StringRef SegName = O->getSectionFinalSegmentName(Ref);
3741 if (SegName == segname && SectName == sectname)
3742 return Section;
3743 }
3744 return SectionRef();
3745}
3746
3747static void
3748walk_pointer_list_64(const char *listname, const SectionRef S,
3749 MachOObjectFile *O, struct DisassembleInfo *info,
3750 void (*func)(uint64_t, struct DisassembleInfo *info)) {
3751 if (S == SectionRef())
3752 return;
3753
3754 StringRef SectName;
3755 S.getName(SectName);
3756 DataRefImpl Ref = S.getRawDataRefImpl();
3757 StringRef SegName = O->getSectionFinalSegmentName(Ref);
3758 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
3759
3760 StringRef BytesStr;
3761 S.getContents(BytesStr);
3762 const char *Contents = reinterpret_cast<const char *>(BytesStr.data());
3763
3764 for (uint32_t i = 0; i < S.getSize(); i += sizeof(uint64_t)) {
3765 uint32_t left = S.getSize() - i;
3766 uint32_t size = left < sizeof(uint64_t) ? left : sizeof(uint64_t);
3767 uint64_t p = 0;
3768 memcpy(&p, Contents + i, size);
3769 if (i + sizeof(uint64_t) > S.getSize())
3770 outs() << listname << " list pointer extends past end of (" << SegName
3771 << "," << SectName << ") section\n";
3772 outs() << format("%016" PRIx64, S.getAddress() + i) << " ";
3773
3774 if (O->isLittleEndian() != sys::IsLittleEndianHost)
3775 sys::swapByteOrder(p);
3776
3777 uint64_t n_value = 0;
3778 const char *name = get_symbol_64(i, S, info, n_value, p);
3779 if (name == nullptr)
3780 name = get_dyld_bind_info_symbolname(S.getAddress() + i, info);
3781
3782 if (n_value != 0) {
3783 outs() << format("0x%" PRIx64, n_value);
3784 if (p != 0)
3785 outs() << " + " << format("0x%" PRIx64, p);
3786 } else
3787 outs() << format("0x%" PRIx64, p);
3788 if (name != nullptr)
3789 outs() << " " << name;
3790 outs() << "\n";
3791
3792 p += n_value;
3793 if (func)
3794 func(p, info);
3795 }
3796}
3797
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003798static void
3799walk_pointer_list_32(const char *listname, const SectionRef S,
3800 MachOObjectFile *O, struct DisassembleInfo *info,
3801 void (*func)(uint32_t, struct DisassembleInfo *info)) {
3802 if (S == SectionRef())
3803 return;
3804
3805 StringRef SectName;
3806 S.getName(SectName);
3807 DataRefImpl Ref = S.getRawDataRefImpl();
3808 StringRef SegName = O->getSectionFinalSegmentName(Ref);
3809 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
3810
3811 StringRef BytesStr;
3812 S.getContents(BytesStr);
3813 const char *Contents = reinterpret_cast<const char *>(BytesStr.data());
3814
3815 for (uint32_t i = 0; i < S.getSize(); i += sizeof(uint32_t)) {
3816 uint32_t left = S.getSize() - i;
3817 uint32_t size = left < sizeof(uint32_t) ? left : sizeof(uint32_t);
3818 uint32_t p = 0;
3819 memcpy(&p, Contents + i, size);
3820 if (i + sizeof(uint32_t) > S.getSize())
3821 outs() << listname << " list pointer extends past end of (" << SegName
3822 << "," << SectName << ") section\n";
Kevin Enderbycf261312015-04-06 22:33:43 +00003823 uint32_t Address = S.getAddress() + i;
3824 outs() << format("%08" PRIx32, Address) << " ";
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003825
3826 if (O->isLittleEndian() != sys::IsLittleEndianHost)
3827 sys::swapByteOrder(p);
3828 outs() << format("0x%" PRIx32, p);
3829
3830 const char *name = get_symbol_32(i, S, info, p);
3831 if (name != nullptr)
3832 outs() << " " << name;
3833 outs() << "\n";
3834
3835 if (func)
3836 func(p, info);
3837 }
3838}
3839
3840static void print_layout_map(const char *layout_map, uint32_t left) {
Kevin Enderbya59824a2015-10-06 22:27:08 +00003841 if (layout_map == nullptr)
3842 return;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003843 outs() << " layout map: ";
3844 do {
3845 outs() << format("0x%02" PRIx32, (*layout_map) & 0xff) << " ";
3846 left--;
3847 layout_map++;
3848 } while (*layout_map != '\0' && left != 0);
3849 outs() << "\n";
3850}
3851
Kevin Enderby0fc11822015-04-01 20:57:01 +00003852static void print_layout_map64(uint64_t p, struct DisassembleInfo *info) {
3853 uint32_t offset, left;
3854 SectionRef S;
3855 const char *layout_map;
3856
3857 if (p == 0)
3858 return;
3859 layout_map = get_pointer_64(p, offset, left, S, info);
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003860 print_layout_map(layout_map, left);
3861}
3862
3863static void print_layout_map32(uint32_t p, struct DisassembleInfo *info) {
3864 uint32_t offset, left;
3865 SectionRef S;
3866 const char *layout_map;
3867
3868 if (p == 0)
3869 return;
3870 layout_map = get_pointer_32(p, offset, left, S, info);
3871 print_layout_map(layout_map, left);
Kevin Enderby0fc11822015-04-01 20:57:01 +00003872}
3873
3874static void print_method_list64_t(uint64_t p, struct DisassembleInfo *info,
3875 const char *indent) {
3876 struct method_list64_t ml;
3877 struct method64_t m;
3878 const char *r;
3879 uint32_t offset, xoffset, left, i;
3880 SectionRef S, xS;
3881 const char *name, *sym_name;
3882 uint64_t n_value;
3883
3884 r = get_pointer_64(p, offset, left, S, info);
3885 if (r == nullptr)
3886 return;
3887 memset(&ml, '\0', sizeof(struct method_list64_t));
3888 if (left < sizeof(struct method_list64_t)) {
3889 memcpy(&ml, r, left);
3890 outs() << " (method_list_t entends past the end of the section)\n";
3891 } else
3892 memcpy(&ml, r, sizeof(struct method_list64_t));
3893 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3894 swapStruct(ml);
3895 outs() << indent << "\t\t entsize " << ml.entsize << "\n";
3896 outs() << indent << "\t\t count " << ml.count << "\n";
3897
3898 p += sizeof(struct method_list64_t);
3899 offset += sizeof(struct method_list64_t);
3900 for (i = 0; i < ml.count; i++) {
3901 r = get_pointer_64(p, offset, left, S, info);
3902 if (r == nullptr)
3903 return;
3904 memset(&m, '\0', sizeof(struct method64_t));
3905 if (left < sizeof(struct method64_t)) {
Kevin Enderbya59824a2015-10-06 22:27:08 +00003906 memcpy(&m, r, left);
3907 outs() << indent << " (method_t extends past the end of the section)\n";
Kevin Enderby0fc11822015-04-01 20:57:01 +00003908 } else
3909 memcpy(&m, r, sizeof(struct method64_t));
3910 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3911 swapStruct(m);
3912
3913 outs() << indent << "\t\t name ";
3914 sym_name = get_symbol_64(offset + offsetof(struct method64_t, name), S,
3915 info, n_value, m.name);
3916 if (n_value != 0) {
3917 if (info->verbose && sym_name != nullptr)
3918 outs() << sym_name;
3919 else
3920 outs() << format("0x%" PRIx64, n_value);
3921 if (m.name != 0)
3922 outs() << " + " << format("0x%" PRIx64, m.name);
3923 } else
3924 outs() << format("0x%" PRIx64, m.name);
3925 name = get_pointer_64(m.name + n_value, xoffset, left, xS, info);
3926 if (name != nullptr)
3927 outs() << format(" %.*s", left, name);
3928 outs() << "\n";
3929
3930 outs() << indent << "\t\t types ";
3931 sym_name = get_symbol_64(offset + offsetof(struct method64_t, types), S,
3932 info, n_value, m.types);
3933 if (n_value != 0) {
3934 if (info->verbose && sym_name != nullptr)
3935 outs() << sym_name;
3936 else
3937 outs() << format("0x%" PRIx64, n_value);
3938 if (m.types != 0)
3939 outs() << " + " << format("0x%" PRIx64, m.types);
3940 } else
3941 outs() << format("0x%" PRIx64, m.types);
3942 name = get_pointer_64(m.types + n_value, xoffset, left, xS, info);
3943 if (name != nullptr)
3944 outs() << format(" %.*s", left, name);
3945 outs() << "\n";
3946
3947 outs() << indent << "\t\t imp ";
3948 name = get_symbol_64(offset + offsetof(struct method64_t, imp), S, info,
3949 n_value, m.imp);
3950 if (info->verbose && name == nullptr) {
3951 if (n_value != 0) {
3952 outs() << format("0x%" PRIx64, n_value) << " ";
3953 if (m.imp != 0)
3954 outs() << "+ " << format("0x%" PRIx64, m.imp) << " ";
3955 } else
3956 outs() << format("0x%" PRIx64, m.imp) << " ";
3957 }
3958 if (name != nullptr)
3959 outs() << name;
3960 outs() << "\n";
3961
3962 p += sizeof(struct method64_t);
3963 offset += sizeof(struct method64_t);
3964 }
3965}
3966
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003967static void print_method_list32_t(uint64_t p, struct DisassembleInfo *info,
3968 const char *indent) {
3969 struct method_list32_t ml;
3970 struct method32_t m;
Kevin Enderby846c0002015-04-16 17:19:59 +00003971 const char *r, *name;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003972 uint32_t offset, xoffset, left, i;
3973 SectionRef S, xS;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003974
3975 r = get_pointer_32(p, offset, left, S, info);
3976 if (r == nullptr)
3977 return;
3978 memset(&ml, '\0', sizeof(struct method_list32_t));
3979 if (left < sizeof(struct method_list32_t)) {
3980 memcpy(&ml, r, left);
3981 outs() << " (method_list_t entends past the end of the section)\n";
3982 } else
3983 memcpy(&ml, r, sizeof(struct method_list32_t));
3984 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3985 swapStruct(ml);
3986 outs() << indent << "\t\t entsize " << ml.entsize << "\n";
3987 outs() << indent << "\t\t count " << ml.count << "\n";
3988
3989 p += sizeof(struct method_list32_t);
3990 offset += sizeof(struct method_list32_t);
3991 for (i = 0; i < ml.count; i++) {
3992 r = get_pointer_32(p, offset, left, S, info);
3993 if (r == nullptr)
3994 return;
3995 memset(&m, '\0', sizeof(struct method32_t));
3996 if (left < sizeof(struct method32_t)) {
3997 memcpy(&ml, r, left);
3998 outs() << indent << " (method_t entends past the end of the section)\n";
3999 } else
4000 memcpy(&m, r, sizeof(struct method32_t));
4001 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4002 swapStruct(m);
4003
4004 outs() << indent << "\t\t name " << format("0x%" PRIx32, m.name);
4005 name = get_pointer_32(m.name, xoffset, left, xS, info);
4006 if (name != nullptr)
4007 outs() << format(" %.*s", left, name);
4008 outs() << "\n";
4009
4010 outs() << indent << "\t\t types " << format("0x%" PRIx32, m.types);
4011 name = get_pointer_32(m.types, xoffset, left, xS, info);
4012 if (name != nullptr)
4013 outs() << format(" %.*s", left, name);
4014 outs() << "\n";
4015
4016 outs() << indent << "\t\t imp " << format("0x%" PRIx32, m.imp);
4017 name = get_symbol_32(offset + offsetof(struct method32_t, imp), S, info,
4018 m.imp);
4019 if (name != nullptr)
4020 outs() << " " << name;
4021 outs() << "\n";
4022
4023 p += sizeof(struct method32_t);
4024 offset += sizeof(struct method32_t);
4025 }
4026}
4027
Kevin Enderby846c0002015-04-16 17:19:59 +00004028static bool print_method_list(uint32_t p, struct DisassembleInfo *info) {
4029 uint32_t offset, left, xleft;
4030 SectionRef S;
4031 struct objc_method_list_t method_list;
4032 struct objc_method_t method;
4033 const char *r, *methods, *name, *SymbolName;
4034 int32_t i;
4035
4036 r = get_pointer_32(p, offset, left, S, info, true);
4037 if (r == nullptr)
4038 return true;
4039
4040 outs() << "\n";
4041 if (left > sizeof(struct objc_method_list_t)) {
4042 memcpy(&method_list, r, sizeof(struct objc_method_list_t));
4043 } else {
4044 outs() << "\t\t objc_method_list extends past end of the section\n";
4045 memset(&method_list, '\0', sizeof(struct objc_method_list_t));
4046 memcpy(&method_list, r, left);
4047 }
4048 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4049 swapStruct(method_list);
4050
4051 outs() << "\t\t obsolete "
4052 << format("0x%08" PRIx32, method_list.obsolete) << "\n";
4053 outs() << "\t\t method_count " << method_list.method_count << "\n";
4054
4055 methods = r + sizeof(struct objc_method_list_t);
4056 for (i = 0; i < method_list.method_count; i++) {
4057 if ((i + 1) * sizeof(struct objc_method_t) > left) {
4058 outs() << "\t\t remaining method's extend past the of the section\n";
4059 break;
4060 }
4061 memcpy(&method, methods + i * sizeof(struct objc_method_t),
4062 sizeof(struct objc_method_t));
4063 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4064 swapStruct(method);
4065
4066 outs() << "\t\t method_name "
4067 << format("0x%08" PRIx32, method.method_name);
4068 if (info->verbose) {
4069 name = get_pointer_32(method.method_name, offset, xleft, S, info, true);
4070 if (name != nullptr)
4071 outs() << format(" %.*s", xleft, name);
4072 else
4073 outs() << " (not in an __OBJC section)";
4074 }
4075 outs() << "\n";
4076
4077 outs() << "\t\t method_types "
4078 << format("0x%08" PRIx32, method.method_types);
4079 if (info->verbose) {
4080 name = get_pointer_32(method.method_types, offset, xleft, S, info, true);
4081 if (name != nullptr)
4082 outs() << format(" %.*s", xleft, name);
4083 else
4084 outs() << " (not in an __OBJC section)";
4085 }
4086 outs() << "\n";
4087
4088 outs() << "\t\t method_imp "
4089 << format("0x%08" PRIx32, method.method_imp) << " ";
4090 if (info->verbose) {
4091 SymbolName = GuessSymbolName(method.method_imp, info->AddrMap);
4092 if (SymbolName != nullptr)
4093 outs() << SymbolName;
4094 }
4095 outs() << "\n";
4096 }
4097 return false;
4098}
4099
Kevin Enderby0fc11822015-04-01 20:57:01 +00004100static void print_protocol_list64_t(uint64_t p, struct DisassembleInfo *info) {
4101 struct protocol_list64_t pl;
4102 uint64_t q, n_value;
4103 struct protocol64_t pc;
4104 const char *r;
4105 uint32_t offset, xoffset, left, i;
4106 SectionRef S, xS;
4107 const char *name, *sym_name;
4108
4109 r = get_pointer_64(p, offset, left, S, info);
4110 if (r == nullptr)
4111 return;
4112 memset(&pl, '\0', sizeof(struct protocol_list64_t));
4113 if (left < sizeof(struct protocol_list64_t)) {
4114 memcpy(&pl, r, left);
4115 outs() << " (protocol_list_t entends past the end of the section)\n";
4116 } else
4117 memcpy(&pl, r, sizeof(struct protocol_list64_t));
4118 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4119 swapStruct(pl);
4120 outs() << " count " << pl.count << "\n";
4121
4122 p += sizeof(struct protocol_list64_t);
4123 offset += sizeof(struct protocol_list64_t);
4124 for (i = 0; i < pl.count; i++) {
4125 r = get_pointer_64(p, offset, left, S, info);
4126 if (r == nullptr)
4127 return;
4128 q = 0;
4129 if (left < sizeof(uint64_t)) {
4130 memcpy(&q, r, left);
4131 outs() << " (protocol_t * entends past the end of the section)\n";
4132 } else
4133 memcpy(&q, r, sizeof(uint64_t));
4134 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4135 sys::swapByteOrder(q);
4136
4137 outs() << "\t\t list[" << i << "] ";
4138 sym_name = get_symbol_64(offset, S, info, n_value, q);
4139 if (n_value != 0) {
4140 if (info->verbose && sym_name != nullptr)
4141 outs() << sym_name;
4142 else
4143 outs() << format("0x%" PRIx64, n_value);
4144 if (q != 0)
4145 outs() << " + " << format("0x%" PRIx64, q);
4146 } else
4147 outs() << format("0x%" PRIx64, q);
4148 outs() << " (struct protocol_t *)\n";
4149
4150 r = get_pointer_64(q + n_value, offset, left, S, info);
4151 if (r == nullptr)
4152 return;
4153 memset(&pc, '\0', sizeof(struct protocol64_t));
4154 if (left < sizeof(struct protocol64_t)) {
4155 memcpy(&pc, r, left);
4156 outs() << " (protocol_t entends past the end of the section)\n";
4157 } else
4158 memcpy(&pc, r, sizeof(struct protocol64_t));
4159 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4160 swapStruct(pc);
4161
4162 outs() << "\t\t\t isa " << format("0x%" PRIx64, pc.isa) << "\n";
4163
4164 outs() << "\t\t\t name ";
4165 sym_name = get_symbol_64(offset + offsetof(struct protocol64_t, name), S,
4166 info, n_value, pc.name);
4167 if (n_value != 0) {
4168 if (info->verbose && sym_name != nullptr)
4169 outs() << sym_name;
4170 else
4171 outs() << format("0x%" PRIx64, n_value);
4172 if (pc.name != 0)
4173 outs() << " + " << format("0x%" PRIx64, pc.name);
4174 } else
4175 outs() << format("0x%" PRIx64, pc.name);
4176 name = get_pointer_64(pc.name + n_value, xoffset, left, xS, info);
4177 if (name != nullptr)
4178 outs() << format(" %.*s", left, name);
4179 outs() << "\n";
4180
4181 outs() << "\t\t\tprotocols " << format("0x%" PRIx64, pc.protocols) << "\n";
4182
4183 outs() << "\t\t instanceMethods ";
4184 sym_name =
4185 get_symbol_64(offset + offsetof(struct protocol64_t, instanceMethods),
4186 S, info, n_value, pc.instanceMethods);
4187 if (n_value != 0) {
4188 if (info->verbose && sym_name != nullptr)
4189 outs() << sym_name;
4190 else
4191 outs() << format("0x%" PRIx64, n_value);
4192 if (pc.instanceMethods != 0)
4193 outs() << " + " << format("0x%" PRIx64, pc.instanceMethods);
4194 } else
4195 outs() << format("0x%" PRIx64, pc.instanceMethods);
4196 outs() << " (struct method_list_t *)\n";
4197 if (pc.instanceMethods + n_value != 0)
4198 print_method_list64_t(pc.instanceMethods + n_value, info, "\t");
4199
4200 outs() << "\t\t classMethods ";
4201 sym_name =
4202 get_symbol_64(offset + offsetof(struct protocol64_t, classMethods), S,
4203 info, n_value, pc.classMethods);
4204 if (n_value != 0) {
4205 if (info->verbose && sym_name != nullptr)
4206 outs() << sym_name;
4207 else
4208 outs() << format("0x%" PRIx64, n_value);
4209 if (pc.classMethods != 0)
4210 outs() << " + " << format("0x%" PRIx64, pc.classMethods);
4211 } else
4212 outs() << format("0x%" PRIx64, pc.classMethods);
4213 outs() << " (struct method_list_t *)\n";
4214 if (pc.classMethods + n_value != 0)
4215 print_method_list64_t(pc.classMethods + n_value, info, "\t");
4216
4217 outs() << "\t optionalInstanceMethods "
4218 << format("0x%" PRIx64, pc.optionalInstanceMethods) << "\n";
4219 outs() << "\t optionalClassMethods "
4220 << format("0x%" PRIx64, pc.optionalClassMethods) << "\n";
4221 outs() << "\t instanceProperties "
4222 << format("0x%" PRIx64, pc.instanceProperties) << "\n";
4223
4224 p += sizeof(uint64_t);
4225 offset += sizeof(uint64_t);
4226 }
4227}
4228
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004229static void print_protocol_list32_t(uint32_t p, struct DisassembleInfo *info) {
4230 struct protocol_list32_t pl;
4231 uint32_t q;
4232 struct protocol32_t pc;
4233 const char *r;
4234 uint32_t offset, xoffset, left, i;
4235 SectionRef S, xS;
4236 const char *name;
4237
4238 r = get_pointer_32(p, offset, left, S, info);
4239 if (r == nullptr)
4240 return;
4241 memset(&pl, '\0', sizeof(struct protocol_list32_t));
4242 if (left < sizeof(struct protocol_list32_t)) {
4243 memcpy(&pl, r, left);
4244 outs() << " (protocol_list_t entends past the end of the section)\n";
4245 } else
4246 memcpy(&pl, r, sizeof(struct protocol_list32_t));
4247 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4248 swapStruct(pl);
4249 outs() << " count " << pl.count << "\n";
4250
4251 p += sizeof(struct protocol_list32_t);
4252 offset += sizeof(struct protocol_list32_t);
4253 for (i = 0; i < pl.count; i++) {
4254 r = get_pointer_32(p, offset, left, S, info);
4255 if (r == nullptr)
4256 return;
4257 q = 0;
4258 if (left < sizeof(uint32_t)) {
4259 memcpy(&q, r, left);
4260 outs() << " (protocol_t * entends past the end of the section)\n";
4261 } else
4262 memcpy(&q, r, sizeof(uint32_t));
4263 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4264 sys::swapByteOrder(q);
4265 outs() << "\t\t list[" << i << "] " << format("0x%" PRIx32, q)
4266 << " (struct protocol_t *)\n";
4267 r = get_pointer_32(q, offset, left, S, info);
4268 if (r == nullptr)
4269 return;
4270 memset(&pc, '\0', sizeof(struct protocol32_t));
4271 if (left < sizeof(struct protocol32_t)) {
4272 memcpy(&pc, r, left);
4273 outs() << " (protocol_t entends past the end of the section)\n";
4274 } else
4275 memcpy(&pc, r, sizeof(struct protocol32_t));
4276 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4277 swapStruct(pc);
4278 outs() << "\t\t\t isa " << format("0x%" PRIx32, pc.isa) << "\n";
4279 outs() << "\t\t\t name " << format("0x%" PRIx32, pc.name);
4280 name = get_pointer_32(pc.name, xoffset, left, xS, info);
4281 if (name != nullptr)
4282 outs() << format(" %.*s", left, name);
4283 outs() << "\n";
4284 outs() << "\t\t\tprotocols " << format("0x%" PRIx32, pc.protocols) << "\n";
4285 outs() << "\t\t instanceMethods "
4286 << format("0x%" PRIx32, pc.instanceMethods)
4287 << " (struct method_list_t *)\n";
4288 if (pc.instanceMethods != 0)
4289 print_method_list32_t(pc.instanceMethods, info, "\t");
4290 outs() << "\t\t classMethods " << format("0x%" PRIx32, pc.classMethods)
4291 << " (struct method_list_t *)\n";
4292 if (pc.classMethods != 0)
4293 print_method_list32_t(pc.classMethods, info, "\t");
4294 outs() << "\t optionalInstanceMethods "
4295 << format("0x%" PRIx32, pc.optionalInstanceMethods) << "\n";
4296 outs() << "\t optionalClassMethods "
4297 << format("0x%" PRIx32, pc.optionalClassMethods) << "\n";
4298 outs() << "\t instanceProperties "
4299 << format("0x%" PRIx32, pc.instanceProperties) << "\n";
4300 p += sizeof(uint32_t);
4301 offset += sizeof(uint32_t);
4302 }
4303}
4304
Kevin Enderby846c0002015-04-16 17:19:59 +00004305static void print_indent(uint32_t indent) {
4306 for (uint32_t i = 0; i < indent;) {
4307 if (indent - i >= 8) {
4308 outs() << "\t";
4309 i += 8;
4310 } else {
4311 for (uint32_t j = i; j < indent; j++)
4312 outs() << " ";
4313 return;
4314 }
4315 }
4316}
4317
4318static bool print_method_description_list(uint32_t p, uint32_t indent,
4319 struct DisassembleInfo *info) {
4320 uint32_t offset, left, xleft;
4321 SectionRef S;
4322 struct objc_method_description_list_t mdl;
4323 struct objc_method_description_t md;
4324 const char *r, *list, *name;
4325 int32_t i;
4326
4327 r = get_pointer_32(p, offset, left, S, info, true);
4328 if (r == nullptr)
4329 return true;
4330
4331 outs() << "\n";
4332 if (left > sizeof(struct objc_method_description_list_t)) {
4333 memcpy(&mdl, r, sizeof(struct objc_method_description_list_t));
4334 } else {
4335 print_indent(indent);
4336 outs() << " objc_method_description_list extends past end of the section\n";
4337 memset(&mdl, '\0', sizeof(struct objc_method_description_list_t));
4338 memcpy(&mdl, r, left);
4339 }
4340 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4341 swapStruct(mdl);
4342
4343 print_indent(indent);
4344 outs() << " count " << mdl.count << "\n";
4345
4346 list = r + sizeof(struct objc_method_description_list_t);
4347 for (i = 0; i < mdl.count; i++) {
4348 if ((i + 1) * sizeof(struct objc_method_description_t) > left) {
4349 print_indent(indent);
4350 outs() << " remaining list entries extend past the of the section\n";
4351 break;
4352 }
4353 print_indent(indent);
4354 outs() << " list[" << i << "]\n";
4355 memcpy(&md, list + i * sizeof(struct objc_method_description_t),
4356 sizeof(struct objc_method_description_t));
4357 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4358 swapStruct(md);
4359
4360 print_indent(indent);
4361 outs() << " name " << format("0x%08" PRIx32, md.name);
4362 if (info->verbose) {
4363 name = get_pointer_32(md.name, offset, xleft, S, info, true);
4364 if (name != nullptr)
4365 outs() << format(" %.*s", xleft, name);
4366 else
4367 outs() << " (not in an __OBJC section)";
4368 }
4369 outs() << "\n";
4370
4371 print_indent(indent);
4372 outs() << " types " << format("0x%08" PRIx32, md.types);
4373 if (info->verbose) {
4374 name = get_pointer_32(md.types, offset, xleft, S, info, true);
4375 if (name != nullptr)
4376 outs() << format(" %.*s", xleft, name);
4377 else
4378 outs() << " (not in an __OBJC section)";
4379 }
4380 outs() << "\n";
4381 }
4382 return false;
4383}
4384
4385static bool print_protocol_list(uint32_t p, uint32_t indent,
4386 struct DisassembleInfo *info);
4387
4388static bool print_protocol(uint32_t p, uint32_t indent,
4389 struct DisassembleInfo *info) {
4390 uint32_t offset, left;
4391 SectionRef S;
4392 struct objc_protocol_t protocol;
4393 const char *r, *name;
4394
4395 r = get_pointer_32(p, offset, left, S, info, true);
4396 if (r == nullptr)
4397 return true;
4398
4399 outs() << "\n";
4400 if (left >= sizeof(struct objc_protocol_t)) {
4401 memcpy(&protocol, r, sizeof(struct objc_protocol_t));
4402 } else {
4403 print_indent(indent);
4404 outs() << " Protocol extends past end of the section\n";
4405 memset(&protocol, '\0', sizeof(struct objc_protocol_t));
4406 memcpy(&protocol, r, left);
4407 }
4408 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4409 swapStruct(protocol);
4410
4411 print_indent(indent);
4412 outs() << " isa " << format("0x%08" PRIx32, protocol.isa)
4413 << "\n";
4414
4415 print_indent(indent);
4416 outs() << " protocol_name "
4417 << format("0x%08" PRIx32, protocol.protocol_name);
4418 if (info->verbose) {
4419 name = get_pointer_32(protocol.protocol_name, offset, left, S, info, true);
4420 if (name != nullptr)
4421 outs() << format(" %.*s", left, name);
4422 else
4423 outs() << " (not in an __OBJC section)";
4424 }
4425 outs() << "\n";
4426
4427 print_indent(indent);
4428 outs() << " protocol_list "
4429 << format("0x%08" PRIx32, protocol.protocol_list);
4430 if (print_protocol_list(protocol.protocol_list, indent + 4, info))
4431 outs() << " (not in an __OBJC section)\n";
4432
4433 print_indent(indent);
4434 outs() << " instance_methods "
4435 << format("0x%08" PRIx32, protocol.instance_methods);
4436 if (print_method_description_list(protocol.instance_methods, indent, info))
4437 outs() << " (not in an __OBJC section)\n";
4438
4439 print_indent(indent);
4440 outs() << " class_methods "
4441 << format("0x%08" PRIx32, protocol.class_methods);
4442 if (print_method_description_list(protocol.class_methods, indent, info))
4443 outs() << " (not in an __OBJC section)\n";
4444
4445 return false;
4446}
4447
4448static bool print_protocol_list(uint32_t p, uint32_t indent,
4449 struct DisassembleInfo *info) {
4450 uint32_t offset, left, l;
4451 SectionRef S;
4452 struct objc_protocol_list_t protocol_list;
4453 const char *r, *list;
4454 int32_t i;
4455
4456 r = get_pointer_32(p, offset, left, S, info, true);
4457 if (r == nullptr)
4458 return true;
4459
4460 outs() << "\n";
4461 if (left > sizeof(struct objc_protocol_list_t)) {
4462 memcpy(&protocol_list, r, sizeof(struct objc_protocol_list_t));
4463 } else {
4464 outs() << "\t\t objc_protocol_list_t extends past end of the section\n";
4465 memset(&protocol_list, '\0', sizeof(struct objc_protocol_list_t));
4466 memcpy(&protocol_list, r, left);
4467 }
4468 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4469 swapStruct(protocol_list);
4470
4471 print_indent(indent);
4472 outs() << " next " << format("0x%08" PRIx32, protocol_list.next)
4473 << "\n";
4474 print_indent(indent);
4475 outs() << " count " << protocol_list.count << "\n";
4476
4477 list = r + sizeof(struct objc_protocol_list_t);
4478 for (i = 0; i < protocol_list.count; i++) {
4479 if ((i + 1) * sizeof(uint32_t) > left) {
4480 outs() << "\t\t remaining list entries extend past the of the section\n";
4481 break;
4482 }
4483 memcpy(&l, list + i * sizeof(uint32_t), sizeof(uint32_t));
4484 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4485 sys::swapByteOrder(l);
4486
4487 print_indent(indent);
4488 outs() << " list[" << i << "] " << format("0x%08" PRIx32, l);
4489 if (print_protocol(l, indent, info))
4490 outs() << "(not in an __OBJC section)\n";
4491 }
4492 return false;
4493}
4494
Kevin Enderby0fc11822015-04-01 20:57:01 +00004495static void print_ivar_list64_t(uint64_t p, struct DisassembleInfo *info) {
4496 struct ivar_list64_t il;
4497 struct ivar64_t i;
4498 const char *r;
4499 uint32_t offset, xoffset, left, j;
4500 SectionRef S, xS;
4501 const char *name, *sym_name, *ivar_offset_p;
4502 uint64_t ivar_offset, n_value;
4503
4504 r = get_pointer_64(p, offset, left, S, info);
4505 if (r == nullptr)
4506 return;
4507 memset(&il, '\0', sizeof(struct ivar_list64_t));
4508 if (left < sizeof(struct ivar_list64_t)) {
4509 memcpy(&il, r, left);
4510 outs() << " (ivar_list_t entends past the end of the section)\n";
4511 } else
4512 memcpy(&il, r, sizeof(struct ivar_list64_t));
4513 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4514 swapStruct(il);
4515 outs() << " entsize " << il.entsize << "\n";
4516 outs() << " count " << il.count << "\n";
4517
4518 p += sizeof(struct ivar_list64_t);
4519 offset += sizeof(struct ivar_list64_t);
4520 for (j = 0; j < il.count; j++) {
4521 r = get_pointer_64(p, offset, left, S, info);
4522 if (r == nullptr)
4523 return;
4524 memset(&i, '\0', sizeof(struct ivar64_t));
4525 if (left < sizeof(struct ivar64_t)) {
4526 memcpy(&i, r, left);
4527 outs() << " (ivar_t entends past the end of the section)\n";
4528 } else
4529 memcpy(&i, r, sizeof(struct ivar64_t));
4530 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4531 swapStruct(i);
4532
4533 outs() << "\t\t\t offset ";
4534 sym_name = get_symbol_64(offset + offsetof(struct ivar64_t, offset), S,
4535 info, n_value, i.offset);
4536 if (n_value != 0) {
4537 if (info->verbose && sym_name != nullptr)
4538 outs() << sym_name;
4539 else
4540 outs() << format("0x%" PRIx64, n_value);
4541 if (i.offset != 0)
4542 outs() << " + " << format("0x%" PRIx64, i.offset);
4543 } else
4544 outs() << format("0x%" PRIx64, i.offset);
4545 ivar_offset_p = get_pointer_64(i.offset + n_value, xoffset, left, xS, info);
4546 if (ivar_offset_p != nullptr && left >= sizeof(*ivar_offset_p)) {
4547 memcpy(&ivar_offset, ivar_offset_p, sizeof(ivar_offset));
4548 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4549 sys::swapByteOrder(ivar_offset);
4550 outs() << " " << ivar_offset << "\n";
4551 } else
4552 outs() << "\n";
4553
4554 outs() << "\t\t\t name ";
4555 sym_name = get_symbol_64(offset + offsetof(struct ivar64_t, name), S, info,
4556 n_value, i.name);
4557 if (n_value != 0) {
4558 if (info->verbose && sym_name != nullptr)
4559 outs() << sym_name;
4560 else
4561 outs() << format("0x%" PRIx64, n_value);
4562 if (i.name != 0)
4563 outs() << " + " << format("0x%" PRIx64, i.name);
4564 } else
4565 outs() << format("0x%" PRIx64, i.name);
4566 name = get_pointer_64(i.name + n_value, xoffset, left, xS, info);
4567 if (name != nullptr)
4568 outs() << format(" %.*s", left, name);
4569 outs() << "\n";
4570
4571 outs() << "\t\t\t type ";
4572 sym_name = get_symbol_64(offset + offsetof(struct ivar64_t, type), S, info,
4573 n_value, i.name);
4574 name = get_pointer_64(i.type + n_value, xoffset, left, xS, info);
4575 if (n_value != 0) {
4576 if (info->verbose && sym_name != nullptr)
4577 outs() << sym_name;
4578 else
4579 outs() << format("0x%" PRIx64, n_value);
4580 if (i.type != 0)
4581 outs() << " + " << format("0x%" PRIx64, i.type);
4582 } else
4583 outs() << format("0x%" PRIx64, i.type);
4584 if (name != nullptr)
4585 outs() << format(" %.*s", left, name);
4586 outs() << "\n";
4587
4588 outs() << "\t\t\talignment " << i.alignment << "\n";
4589 outs() << "\t\t\t size " << i.size << "\n";
4590
4591 p += sizeof(struct ivar64_t);
4592 offset += sizeof(struct ivar64_t);
4593 }
4594}
4595
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004596static void print_ivar_list32_t(uint32_t p, struct DisassembleInfo *info) {
4597 struct ivar_list32_t il;
4598 struct ivar32_t i;
4599 const char *r;
4600 uint32_t offset, xoffset, left, j;
4601 SectionRef S, xS;
4602 const char *name, *ivar_offset_p;
4603 uint32_t ivar_offset;
4604
4605 r = get_pointer_32(p, offset, left, S, info);
4606 if (r == nullptr)
4607 return;
4608 memset(&il, '\0', sizeof(struct ivar_list32_t));
4609 if (left < sizeof(struct ivar_list32_t)) {
4610 memcpy(&il, r, left);
4611 outs() << " (ivar_list_t entends past the end of the section)\n";
4612 } else
4613 memcpy(&il, r, sizeof(struct ivar_list32_t));
4614 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4615 swapStruct(il);
4616 outs() << " entsize " << il.entsize << "\n";
4617 outs() << " count " << il.count << "\n";
4618
4619 p += sizeof(struct ivar_list32_t);
4620 offset += sizeof(struct ivar_list32_t);
4621 for (j = 0; j < il.count; j++) {
4622 r = get_pointer_32(p, offset, left, S, info);
4623 if (r == nullptr)
4624 return;
4625 memset(&i, '\0', sizeof(struct ivar32_t));
4626 if (left < sizeof(struct ivar32_t)) {
4627 memcpy(&i, r, left);
4628 outs() << " (ivar_t entends past the end of the section)\n";
4629 } else
4630 memcpy(&i, r, sizeof(struct ivar32_t));
4631 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4632 swapStruct(i);
4633
4634 outs() << "\t\t\t offset " << format("0x%" PRIx32, i.offset);
4635 ivar_offset_p = get_pointer_32(i.offset, xoffset, left, xS, info);
4636 if (ivar_offset_p != nullptr && left >= sizeof(*ivar_offset_p)) {
4637 memcpy(&ivar_offset, ivar_offset_p, sizeof(ivar_offset));
4638 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4639 sys::swapByteOrder(ivar_offset);
4640 outs() << " " << ivar_offset << "\n";
4641 } else
4642 outs() << "\n";
4643
4644 outs() << "\t\t\t name " << format("0x%" PRIx32, i.name);
4645 name = get_pointer_32(i.name, xoffset, left, xS, info);
4646 if (name != nullptr)
4647 outs() << format(" %.*s", left, name);
4648 outs() << "\n";
4649
4650 outs() << "\t\t\t type " << format("0x%" PRIx32, i.type);
4651 name = get_pointer_32(i.type, xoffset, left, xS, info);
4652 if (name != nullptr)
4653 outs() << format(" %.*s", left, name);
4654 outs() << "\n";
4655
4656 outs() << "\t\t\talignment " << i.alignment << "\n";
4657 outs() << "\t\t\t size " << i.size << "\n";
4658
4659 p += sizeof(struct ivar32_t);
4660 offset += sizeof(struct ivar32_t);
4661 }
4662}
4663
Kevin Enderby0fc11822015-04-01 20:57:01 +00004664static void print_objc_property_list64(uint64_t p,
4665 struct DisassembleInfo *info) {
4666 struct objc_property_list64 opl;
4667 struct objc_property64 op;
4668 const char *r;
4669 uint32_t offset, xoffset, left, j;
4670 SectionRef S, xS;
4671 const char *name, *sym_name;
4672 uint64_t n_value;
4673
4674 r = get_pointer_64(p, offset, left, S, info);
4675 if (r == nullptr)
4676 return;
4677 memset(&opl, '\0', sizeof(struct objc_property_list64));
4678 if (left < sizeof(struct objc_property_list64)) {
4679 memcpy(&opl, r, left);
4680 outs() << " (objc_property_list entends past the end of the section)\n";
4681 } else
4682 memcpy(&opl, r, sizeof(struct objc_property_list64));
4683 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4684 swapStruct(opl);
4685 outs() << " entsize " << opl.entsize << "\n";
4686 outs() << " count " << opl.count << "\n";
4687
4688 p += sizeof(struct objc_property_list64);
4689 offset += sizeof(struct objc_property_list64);
4690 for (j = 0; j < opl.count; j++) {
4691 r = get_pointer_64(p, offset, left, S, info);
4692 if (r == nullptr)
4693 return;
4694 memset(&op, '\0', sizeof(struct objc_property64));
4695 if (left < sizeof(struct objc_property64)) {
4696 memcpy(&op, r, left);
4697 outs() << " (objc_property entends past the end of the section)\n";
4698 } else
4699 memcpy(&op, r, sizeof(struct objc_property64));
4700 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4701 swapStruct(op);
4702
4703 outs() << "\t\t\t name ";
4704 sym_name = get_symbol_64(offset + offsetof(struct objc_property64, name), S,
4705 info, n_value, op.name);
4706 if (n_value != 0) {
4707 if (info->verbose && sym_name != nullptr)
4708 outs() << sym_name;
4709 else
4710 outs() << format("0x%" PRIx64, n_value);
4711 if (op.name != 0)
4712 outs() << " + " << format("0x%" PRIx64, op.name);
4713 } else
4714 outs() << format("0x%" PRIx64, op.name);
4715 name = get_pointer_64(op.name + n_value, xoffset, left, xS, info);
4716 if (name != nullptr)
4717 outs() << format(" %.*s", left, name);
4718 outs() << "\n";
4719
4720 outs() << "\t\t\tattributes ";
4721 sym_name =
4722 get_symbol_64(offset + offsetof(struct objc_property64, attributes), S,
4723 info, n_value, op.attributes);
4724 if (n_value != 0) {
4725 if (info->verbose && sym_name != nullptr)
4726 outs() << sym_name;
4727 else
4728 outs() << format("0x%" PRIx64, n_value);
4729 if (op.attributes != 0)
4730 outs() << " + " << format("0x%" PRIx64, op.attributes);
4731 } else
4732 outs() << format("0x%" PRIx64, op.attributes);
4733 name = get_pointer_64(op.attributes + n_value, xoffset, left, xS, info);
4734 if (name != nullptr)
4735 outs() << format(" %.*s", left, name);
4736 outs() << "\n";
4737
4738 p += sizeof(struct objc_property64);
4739 offset += sizeof(struct objc_property64);
4740 }
4741}
4742
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004743static void print_objc_property_list32(uint32_t p,
4744 struct DisassembleInfo *info) {
4745 struct objc_property_list32 opl;
4746 struct objc_property32 op;
4747 const char *r;
4748 uint32_t offset, xoffset, left, j;
4749 SectionRef S, xS;
4750 const char *name;
4751
4752 r = get_pointer_32(p, offset, left, S, info);
4753 if (r == nullptr)
4754 return;
4755 memset(&opl, '\0', sizeof(struct objc_property_list32));
4756 if (left < sizeof(struct objc_property_list32)) {
4757 memcpy(&opl, r, left);
4758 outs() << " (objc_property_list entends past the end of the section)\n";
4759 } else
4760 memcpy(&opl, r, sizeof(struct objc_property_list32));
4761 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4762 swapStruct(opl);
4763 outs() << " entsize " << opl.entsize << "\n";
4764 outs() << " count " << opl.count << "\n";
4765
4766 p += sizeof(struct objc_property_list32);
4767 offset += sizeof(struct objc_property_list32);
4768 for (j = 0; j < opl.count; j++) {
4769 r = get_pointer_32(p, offset, left, S, info);
4770 if (r == nullptr)
4771 return;
4772 memset(&op, '\0', sizeof(struct objc_property32));
4773 if (left < sizeof(struct objc_property32)) {
4774 memcpy(&op, r, left);
4775 outs() << " (objc_property entends past the end of the section)\n";
4776 } else
4777 memcpy(&op, r, sizeof(struct objc_property32));
4778 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4779 swapStruct(op);
4780
4781 outs() << "\t\t\t name " << format("0x%" PRIx32, op.name);
4782 name = get_pointer_32(op.name, xoffset, left, xS, info);
4783 if (name != nullptr)
4784 outs() << format(" %.*s", left, name);
4785 outs() << "\n";
4786
4787 outs() << "\t\t\tattributes " << format("0x%" PRIx32, op.attributes);
4788 name = get_pointer_32(op.attributes, xoffset, left, xS, info);
4789 if (name != nullptr)
4790 outs() << format(" %.*s", left, name);
4791 outs() << "\n";
4792
4793 p += sizeof(struct objc_property32);
4794 offset += sizeof(struct objc_property32);
4795 }
4796}
4797
Richard Smith81ff44d2015-10-09 22:09:56 +00004798static bool print_class_ro64_t(uint64_t p, struct DisassembleInfo *info,
Kevin Enderby0fc11822015-04-01 20:57:01 +00004799 bool &is_meta_class) {
4800 struct class_ro64_t cro;
4801 const char *r;
4802 uint32_t offset, xoffset, left;
4803 SectionRef S, xS;
4804 const char *name, *sym_name;
4805 uint64_t n_value;
4806
4807 r = get_pointer_64(p, offset, left, S, info);
4808 if (r == nullptr || left < sizeof(struct class_ro64_t))
Richard Smith81ff44d2015-10-09 22:09:56 +00004809 return false;
Chandler Carruth33e58902016-11-04 07:10:24 +00004810 memcpy(&cro, r, sizeof(struct class_ro64_t));
Kevin Enderby0fc11822015-04-01 20:57:01 +00004811 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4812 swapStruct(cro);
4813 outs() << " flags " << format("0x%" PRIx32, cro.flags);
4814 if (cro.flags & RO_META)
4815 outs() << " RO_META";
4816 if (cro.flags & RO_ROOT)
4817 outs() << " RO_ROOT";
4818 if (cro.flags & RO_HAS_CXX_STRUCTORS)
4819 outs() << " RO_HAS_CXX_STRUCTORS";
4820 outs() << "\n";
4821 outs() << " instanceStart " << cro.instanceStart << "\n";
4822 outs() << " instanceSize " << cro.instanceSize << "\n";
4823 outs() << " reserved " << format("0x%" PRIx32, cro.reserved)
4824 << "\n";
4825 outs() << " ivarLayout " << format("0x%" PRIx64, cro.ivarLayout)
4826 << "\n";
4827 print_layout_map64(cro.ivarLayout, info);
4828
4829 outs() << " name ";
4830 sym_name = get_symbol_64(offset + offsetof(struct class_ro64_t, name), S,
4831 info, n_value, cro.name);
4832 if (n_value != 0) {
4833 if (info->verbose && sym_name != nullptr)
4834 outs() << sym_name;
4835 else
4836 outs() << format("0x%" PRIx64, n_value);
4837 if (cro.name != 0)
4838 outs() << " + " << format("0x%" PRIx64, cro.name);
4839 } else
4840 outs() << format("0x%" PRIx64, cro.name);
4841 name = get_pointer_64(cro.name + n_value, xoffset, left, xS, info);
4842 if (name != nullptr)
4843 outs() << format(" %.*s", left, name);
4844 outs() << "\n";
4845
4846 outs() << " baseMethods ";
4847 sym_name = get_symbol_64(offset + offsetof(struct class_ro64_t, baseMethods),
4848 S, info, n_value, cro.baseMethods);
4849 if (n_value != 0) {
4850 if (info->verbose && sym_name != nullptr)
4851 outs() << sym_name;
4852 else
4853 outs() << format("0x%" PRIx64, n_value);
4854 if (cro.baseMethods != 0)
4855 outs() << " + " << format("0x%" PRIx64, cro.baseMethods);
4856 } else
4857 outs() << format("0x%" PRIx64, cro.baseMethods);
4858 outs() << " (struct method_list_t *)\n";
4859 if (cro.baseMethods + n_value != 0)
4860 print_method_list64_t(cro.baseMethods + n_value, info, "");
4861
4862 outs() << " baseProtocols ";
4863 sym_name =
4864 get_symbol_64(offset + offsetof(struct class_ro64_t, baseProtocols), S,
4865 info, n_value, cro.baseProtocols);
4866 if (n_value != 0) {
4867 if (info->verbose && sym_name != nullptr)
4868 outs() << sym_name;
4869 else
4870 outs() << format("0x%" PRIx64, n_value);
4871 if (cro.baseProtocols != 0)
4872 outs() << " + " << format("0x%" PRIx64, cro.baseProtocols);
4873 } else
4874 outs() << format("0x%" PRIx64, cro.baseProtocols);
4875 outs() << "\n";
4876 if (cro.baseProtocols + n_value != 0)
4877 print_protocol_list64_t(cro.baseProtocols + n_value, info);
4878
4879 outs() << " ivars ";
4880 sym_name = get_symbol_64(offset + offsetof(struct class_ro64_t, ivars), S,
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004881 info, n_value, cro.ivars);
Kevin Enderby0fc11822015-04-01 20:57:01 +00004882 if (n_value != 0) {
4883 if (info->verbose && sym_name != nullptr)
4884 outs() << sym_name;
4885 else
4886 outs() << format("0x%" PRIx64, n_value);
4887 if (cro.ivars != 0)
4888 outs() << " + " << format("0x%" PRIx64, cro.ivars);
4889 } else
4890 outs() << format("0x%" PRIx64, cro.ivars);
4891 outs() << "\n";
4892 if (cro.ivars + n_value != 0)
4893 print_ivar_list64_t(cro.ivars + n_value, info);
4894
4895 outs() << " weakIvarLayout ";
4896 sym_name =
4897 get_symbol_64(offset + offsetof(struct class_ro64_t, weakIvarLayout), S,
4898 info, n_value, cro.weakIvarLayout);
4899 if (n_value != 0) {
4900 if (info->verbose && sym_name != nullptr)
4901 outs() << sym_name;
4902 else
4903 outs() << format("0x%" PRIx64, n_value);
4904 if (cro.weakIvarLayout != 0)
4905 outs() << " + " << format("0x%" PRIx64, cro.weakIvarLayout);
4906 } else
4907 outs() << format("0x%" PRIx64, cro.weakIvarLayout);
4908 outs() << "\n";
4909 print_layout_map64(cro.weakIvarLayout + n_value, info);
4910
4911 outs() << " baseProperties ";
4912 sym_name =
4913 get_symbol_64(offset + offsetof(struct class_ro64_t, baseProperties), S,
4914 info, n_value, cro.baseProperties);
4915 if (n_value != 0) {
4916 if (info->verbose && sym_name != nullptr)
4917 outs() << sym_name;
4918 else
4919 outs() << format("0x%" PRIx64, n_value);
4920 if (cro.baseProperties != 0)
4921 outs() << " + " << format("0x%" PRIx64, cro.baseProperties);
4922 } else
4923 outs() << format("0x%" PRIx64, cro.baseProperties);
4924 outs() << "\n";
4925 if (cro.baseProperties + n_value != 0)
4926 print_objc_property_list64(cro.baseProperties + n_value, info);
4927
Rafael Espindolab9091322015-10-24 23:19:10 +00004928 is_meta_class = (cro.flags & RO_META) != 0;
Richard Smith81ff44d2015-10-09 22:09:56 +00004929 return true;
Kevin Enderby0fc11822015-04-01 20:57:01 +00004930}
4931
Richard Smith81ff44d2015-10-09 22:09:56 +00004932static bool print_class_ro32_t(uint32_t p, struct DisassembleInfo *info,
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004933 bool &is_meta_class) {
4934 struct class_ro32_t cro;
4935 const char *r;
4936 uint32_t offset, xoffset, left;
4937 SectionRef S, xS;
4938 const char *name;
4939
4940 r = get_pointer_32(p, offset, left, S, info);
4941 if (r == nullptr)
Richard Smith81ff44d2015-10-09 22:09:56 +00004942 return false;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004943 memset(&cro, '\0', sizeof(struct class_ro32_t));
4944 if (left < sizeof(struct class_ro32_t)) {
4945 memcpy(&cro, r, left);
4946 outs() << " (class_ro_t entends past the end of the section)\n";
4947 } else
4948 memcpy(&cro, r, sizeof(struct class_ro32_t));
4949 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4950 swapStruct(cro);
4951 outs() << " flags " << format("0x%" PRIx32, cro.flags);
4952 if (cro.flags & RO_META)
4953 outs() << " RO_META";
4954 if (cro.flags & RO_ROOT)
4955 outs() << " RO_ROOT";
4956 if (cro.flags & RO_HAS_CXX_STRUCTORS)
4957 outs() << " RO_HAS_CXX_STRUCTORS";
4958 outs() << "\n";
4959 outs() << " instanceStart " << cro.instanceStart << "\n";
4960 outs() << " instanceSize " << cro.instanceSize << "\n";
4961 outs() << " ivarLayout " << format("0x%" PRIx32, cro.ivarLayout)
4962 << "\n";
4963 print_layout_map32(cro.ivarLayout, info);
4964
4965 outs() << " name " << format("0x%" PRIx32, cro.name);
4966 name = get_pointer_32(cro.name, xoffset, left, xS, info);
4967 if (name != nullptr)
4968 outs() << format(" %.*s", left, name);
4969 outs() << "\n";
4970
4971 outs() << " baseMethods "
4972 << format("0x%" PRIx32, cro.baseMethods)
4973 << " (struct method_list_t *)\n";
4974 if (cro.baseMethods != 0)
4975 print_method_list32_t(cro.baseMethods, info, "");
4976
4977 outs() << " baseProtocols "
4978 << format("0x%" PRIx32, cro.baseProtocols) << "\n";
4979 if (cro.baseProtocols != 0)
4980 print_protocol_list32_t(cro.baseProtocols, info);
4981 outs() << " ivars " << format("0x%" PRIx32, cro.ivars)
4982 << "\n";
4983 if (cro.ivars != 0)
4984 print_ivar_list32_t(cro.ivars, info);
4985 outs() << " weakIvarLayout "
4986 << format("0x%" PRIx32, cro.weakIvarLayout) << "\n";
4987 print_layout_map32(cro.weakIvarLayout, info);
4988 outs() << " baseProperties "
4989 << format("0x%" PRIx32, cro.baseProperties) << "\n";
4990 if (cro.baseProperties != 0)
4991 print_objc_property_list32(cro.baseProperties, info);
Rafael Espindolab9091322015-10-24 23:19:10 +00004992 is_meta_class = (cro.flags & RO_META) != 0;
Richard Smith81ff44d2015-10-09 22:09:56 +00004993 return true;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004994}
4995
Kevin Enderby0fc11822015-04-01 20:57:01 +00004996static void print_class64_t(uint64_t p, struct DisassembleInfo *info) {
4997 struct class64_t c;
4998 const char *r;
4999 uint32_t offset, left;
5000 SectionRef S;
5001 const char *name;
5002 uint64_t isa_n_value, n_value;
5003
5004 r = get_pointer_64(p, offset, left, S, info);
5005 if (r == nullptr || left < sizeof(struct class64_t))
5006 return;
Chandler Carruth33e58902016-11-04 07:10:24 +00005007 memcpy(&c, r, sizeof(struct class64_t));
Kevin Enderby0fc11822015-04-01 20:57:01 +00005008 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5009 swapStruct(c);
5010
5011 outs() << " isa " << format("0x%" PRIx64, c.isa);
5012 name = get_symbol_64(offset + offsetof(struct class64_t, isa), S, info,
5013 isa_n_value, c.isa);
5014 if (name != nullptr)
5015 outs() << " " << name;
5016 outs() << "\n";
5017
5018 outs() << " superclass " << format("0x%" PRIx64, c.superclass);
5019 name = get_symbol_64(offset + offsetof(struct class64_t, superclass), S, info,
5020 n_value, c.superclass);
5021 if (name != nullptr)
5022 outs() << " " << name;
Kevin Enderby1ce38582017-06-20 22:55:11 +00005023 else {
5024 name = get_dyld_bind_info_symbolname(S.getAddress() +
5025 offset + offsetof(struct class64_t, superclass), info);
5026 if (name != nullptr)
5027 outs() << " " << name;
5028 }
Kevin Enderby0fc11822015-04-01 20:57:01 +00005029 outs() << "\n";
5030
5031 outs() << " cache " << format("0x%" PRIx64, c.cache);
5032 name = get_symbol_64(offset + offsetof(struct class64_t, cache), S, info,
5033 n_value, c.cache);
5034 if (name != nullptr)
5035 outs() << " " << name;
5036 outs() << "\n";
5037
5038 outs() << " vtable " << format("0x%" PRIx64, c.vtable);
5039 name = get_symbol_64(offset + offsetof(struct class64_t, vtable), S, info,
5040 n_value, c.vtable);
5041 if (name != nullptr)
5042 outs() << " " << name;
5043 outs() << "\n";
5044
5045 name = get_symbol_64(offset + offsetof(struct class64_t, data), S, info,
5046 n_value, c.data);
5047 outs() << " data ";
5048 if (n_value != 0) {
5049 if (info->verbose && name != nullptr)
5050 outs() << name;
5051 else
5052 outs() << format("0x%" PRIx64, n_value);
5053 if (c.data != 0)
5054 outs() << " + " << format("0x%" PRIx64, c.data);
5055 } else
5056 outs() << format("0x%" PRIx64, c.data);
5057 outs() << " (struct class_ro_t *)";
5058
5059 // This is a Swift class if some of the low bits of the pointer are set.
5060 if ((c.data + n_value) & 0x7)
5061 outs() << " Swift class";
5062 outs() << "\n";
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005063 bool is_meta_class;
Richard Smith81ff44d2015-10-09 22:09:56 +00005064 if (!print_class_ro64_t((c.data + n_value) & ~0x7, info, is_meta_class))
5065 return;
Kevin Enderby0fc11822015-04-01 20:57:01 +00005066
Kevin Enderbyaac75382015-10-08 16:56:35 +00005067 if (!is_meta_class &&
5068 c.isa + isa_n_value != p &&
5069 c.isa + isa_n_value != 0 &&
5070 info->depth < 100) {
5071 info->depth++;
5072 outs() << "Meta Class\n";
5073 print_class64_t(c.isa + isa_n_value, info);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005074 }
5075}
5076
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005077static void print_class32_t(uint32_t p, struct DisassembleInfo *info) {
5078 struct class32_t c;
5079 const char *r;
5080 uint32_t offset, left;
5081 SectionRef S;
5082 const char *name;
5083
5084 r = get_pointer_32(p, offset, left, S, info);
5085 if (r == nullptr)
5086 return;
5087 memset(&c, '\0', sizeof(struct class32_t));
5088 if (left < sizeof(struct class32_t)) {
5089 memcpy(&c, r, left);
5090 outs() << " (class_t entends past the end of the section)\n";
5091 } else
5092 memcpy(&c, r, sizeof(struct class32_t));
5093 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5094 swapStruct(c);
5095
5096 outs() << " isa " << format("0x%" PRIx32, c.isa);
5097 name =
5098 get_symbol_32(offset + offsetof(struct class32_t, isa), S, info, c.isa);
5099 if (name != nullptr)
5100 outs() << " " << name;
5101 outs() << "\n";
5102
5103 outs() << " superclass " << format("0x%" PRIx32, c.superclass);
5104 name = get_symbol_32(offset + offsetof(struct class32_t, superclass), S, info,
5105 c.superclass);
5106 if (name != nullptr)
5107 outs() << " " << name;
5108 outs() << "\n";
5109
5110 outs() << " cache " << format("0x%" PRIx32, c.cache);
5111 name = get_symbol_32(offset + offsetof(struct class32_t, cache), S, info,
5112 c.cache);
5113 if (name != nullptr)
5114 outs() << " " << name;
5115 outs() << "\n";
5116
5117 outs() << " vtable " << format("0x%" PRIx32, c.vtable);
5118 name = get_symbol_32(offset + offsetof(struct class32_t, vtable), S, info,
5119 c.vtable);
5120 if (name != nullptr)
5121 outs() << " " << name;
5122 outs() << "\n";
5123
5124 name =
5125 get_symbol_32(offset + offsetof(struct class32_t, data), S, info, c.data);
5126 outs() << " data " << format("0x%" PRIx32, c.data)
5127 << " (struct class_ro_t *)";
5128
5129 // This is a Swift class if some of the low bits of the pointer are set.
5130 if (c.data & 0x3)
5131 outs() << " Swift class";
5132 outs() << "\n";
5133 bool is_meta_class;
Richard Smith81ff44d2015-10-09 22:09:56 +00005134 if (!print_class_ro32_t(c.data & ~0x3, info, is_meta_class))
5135 return;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005136
Hans Wennborgcc9deb42015-09-29 18:02:48 +00005137 if (!is_meta_class) {
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005138 outs() << "Meta Class\n";
5139 print_class32_t(c.isa, info);
5140 }
5141}
5142
Kevin Enderby846c0002015-04-16 17:19:59 +00005143static void print_objc_class_t(struct objc_class_t *objc_class,
5144 struct DisassembleInfo *info) {
5145 uint32_t offset, left, xleft;
5146 const char *name, *p, *ivar_list;
5147 SectionRef S;
5148 int32_t i;
5149 struct objc_ivar_list_t objc_ivar_list;
5150 struct objc_ivar_t ivar;
5151
5152 outs() << "\t\t isa " << format("0x%08" PRIx32, objc_class->isa);
5153 if (info->verbose && CLS_GETINFO(objc_class, CLS_META)) {
5154 name = get_pointer_32(objc_class->isa, offset, left, S, info, true);
5155 if (name != nullptr)
5156 outs() << format(" %.*s", left, name);
5157 else
5158 outs() << " (not in an __OBJC section)";
5159 }
5160 outs() << "\n";
5161
5162 outs() << "\t super_class "
5163 << format("0x%08" PRIx32, objc_class->super_class);
5164 if (info->verbose) {
5165 name = get_pointer_32(objc_class->super_class, offset, left, S, info, true);
5166 if (name != nullptr)
5167 outs() << format(" %.*s", left, name);
5168 else
5169 outs() << " (not in an __OBJC section)";
5170 }
5171 outs() << "\n";
5172
5173 outs() << "\t\t name " << format("0x%08" PRIx32, objc_class->name);
5174 if (info->verbose) {
5175 name = get_pointer_32(objc_class->name, offset, left, S, info, true);
5176 if (name != nullptr)
5177 outs() << format(" %.*s", left, name);
5178 else
5179 outs() << " (not in an __OBJC section)";
5180 }
5181 outs() << "\n";
5182
5183 outs() << "\t\t version " << format("0x%08" PRIx32, objc_class->version)
5184 << "\n";
5185
5186 outs() << "\t\t info " << format("0x%08" PRIx32, objc_class->info);
5187 if (info->verbose) {
5188 if (CLS_GETINFO(objc_class, CLS_CLASS))
5189 outs() << " CLS_CLASS";
5190 else if (CLS_GETINFO(objc_class, CLS_META))
5191 outs() << " CLS_META";
5192 }
5193 outs() << "\n";
5194
5195 outs() << "\t instance_size "
5196 << format("0x%08" PRIx32, objc_class->instance_size) << "\n";
5197
5198 p = get_pointer_32(objc_class->ivars, offset, left, S, info, true);
5199 outs() << "\t\t ivars " << format("0x%08" PRIx32, objc_class->ivars);
5200 if (p != nullptr) {
5201 if (left > sizeof(struct objc_ivar_list_t)) {
5202 outs() << "\n";
5203 memcpy(&objc_ivar_list, p, sizeof(struct objc_ivar_list_t));
5204 } else {
5205 outs() << " (entends past the end of the section)\n";
5206 memset(&objc_ivar_list, '\0', sizeof(struct objc_ivar_list_t));
5207 memcpy(&objc_ivar_list, p, left);
5208 }
5209 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5210 swapStruct(objc_ivar_list);
5211 outs() << "\t\t ivar_count " << objc_ivar_list.ivar_count << "\n";
5212 ivar_list = p + sizeof(struct objc_ivar_list_t);
5213 for (i = 0; i < objc_ivar_list.ivar_count; i++) {
5214 if ((i + 1) * sizeof(struct objc_ivar_t) > left) {
5215 outs() << "\t\t remaining ivar's extend past the of the section\n";
5216 break;
5217 }
5218 memcpy(&ivar, ivar_list + i * sizeof(struct objc_ivar_t),
5219 sizeof(struct objc_ivar_t));
5220 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5221 swapStruct(ivar);
5222
5223 outs() << "\t\t\tivar_name " << format("0x%08" PRIx32, ivar.ivar_name);
5224 if (info->verbose) {
5225 name = get_pointer_32(ivar.ivar_name, offset, xleft, S, info, true);
5226 if (name != nullptr)
5227 outs() << format(" %.*s", xleft, name);
5228 else
5229 outs() << " (not in an __OBJC section)";
5230 }
5231 outs() << "\n";
5232
5233 outs() << "\t\t\tivar_type " << format("0x%08" PRIx32, ivar.ivar_type);
5234 if (info->verbose) {
5235 name = get_pointer_32(ivar.ivar_type, offset, xleft, S, info, true);
5236 if (name != nullptr)
5237 outs() << format(" %.*s", xleft, name);
5238 else
5239 outs() << " (not in an __OBJC section)";
5240 }
5241 outs() << "\n";
5242
5243 outs() << "\t\t ivar_offset "
5244 << format("0x%08" PRIx32, ivar.ivar_offset) << "\n";
5245 }
5246 } else {
5247 outs() << " (not in an __OBJC section)\n";
5248 }
5249
5250 outs() << "\t\t methods " << format("0x%08" PRIx32, objc_class->methodLists);
5251 if (print_method_list(objc_class->methodLists, info))
5252 outs() << " (not in an __OBJC section)\n";
5253
5254 outs() << "\t\t cache " << format("0x%08" PRIx32, objc_class->cache)
5255 << "\n";
5256
5257 outs() << "\t\tprotocols " << format("0x%08" PRIx32, objc_class->protocols);
5258 if (print_protocol_list(objc_class->protocols, 16, info))
5259 outs() << " (not in an __OBJC section)\n";
5260}
5261
5262static void print_objc_objc_category_t(struct objc_category_t *objc_category,
5263 struct DisassembleInfo *info) {
5264 uint32_t offset, left;
5265 const char *name;
5266 SectionRef S;
5267
5268 outs() << "\t category name "
5269 << format("0x%08" PRIx32, objc_category->category_name);
5270 if (info->verbose) {
5271 name = get_pointer_32(objc_category->category_name, offset, left, S, info,
5272 true);
5273 if (name != nullptr)
5274 outs() << format(" %.*s", left, name);
5275 else
5276 outs() << " (not in an __OBJC section)";
5277 }
5278 outs() << "\n";
5279
5280 outs() << "\t\t class name "
5281 << format("0x%08" PRIx32, objc_category->class_name);
5282 if (info->verbose) {
5283 name =
5284 get_pointer_32(objc_category->class_name, offset, left, S, info, true);
5285 if (name != nullptr)
5286 outs() << format(" %.*s", left, name);
5287 else
5288 outs() << " (not in an __OBJC section)";
5289 }
5290 outs() << "\n";
5291
5292 outs() << "\t instance methods "
5293 << format("0x%08" PRIx32, objc_category->instance_methods);
5294 if (print_method_list(objc_category->instance_methods, info))
5295 outs() << " (not in an __OBJC section)\n";
5296
5297 outs() << "\t class methods "
5298 << format("0x%08" PRIx32, objc_category->class_methods);
5299 if (print_method_list(objc_category->class_methods, info))
5300 outs() << " (not in an __OBJC section)\n";
5301}
5302
Kevin Enderby0fc11822015-04-01 20:57:01 +00005303static void print_category64_t(uint64_t p, struct DisassembleInfo *info) {
5304 struct category64_t c;
5305 const char *r;
5306 uint32_t offset, xoffset, left;
5307 SectionRef S, xS;
5308 const char *name, *sym_name;
5309 uint64_t n_value;
5310
5311 r = get_pointer_64(p, offset, left, S, info);
5312 if (r == nullptr)
5313 return;
5314 memset(&c, '\0', sizeof(struct category64_t));
5315 if (left < sizeof(struct category64_t)) {
5316 memcpy(&c, r, left);
5317 outs() << " (category_t entends past the end of the section)\n";
5318 } else
5319 memcpy(&c, r, sizeof(struct category64_t));
5320 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5321 swapStruct(c);
5322
5323 outs() << " name ";
5324 sym_name = get_symbol_64(offset + offsetof(struct category64_t, name), S,
5325 info, n_value, c.name);
5326 if (n_value != 0) {
5327 if (info->verbose && sym_name != nullptr)
5328 outs() << sym_name;
5329 else
5330 outs() << format("0x%" PRIx64, n_value);
5331 if (c.name != 0)
5332 outs() << " + " << format("0x%" PRIx64, c.name);
5333 } else
5334 outs() << format("0x%" PRIx64, c.name);
5335 name = get_pointer_64(c.name + n_value, xoffset, left, xS, info);
5336 if (name != nullptr)
5337 outs() << format(" %.*s", left, name);
5338 outs() << "\n";
5339
5340 outs() << " cls ";
5341 sym_name = get_symbol_64(offset + offsetof(struct category64_t, cls), S, info,
5342 n_value, c.cls);
5343 if (n_value != 0) {
5344 if (info->verbose && sym_name != nullptr)
5345 outs() << sym_name;
5346 else
5347 outs() << format("0x%" PRIx64, n_value);
5348 if (c.cls != 0)
5349 outs() << " + " << format("0x%" PRIx64, c.cls);
5350 } else
5351 outs() << format("0x%" PRIx64, c.cls);
5352 outs() << "\n";
5353 if (c.cls + n_value != 0)
5354 print_class64_t(c.cls + n_value, info);
5355
5356 outs() << " instanceMethods ";
5357 sym_name =
5358 get_symbol_64(offset + offsetof(struct category64_t, instanceMethods), S,
5359 info, n_value, c.instanceMethods);
5360 if (n_value != 0) {
5361 if (info->verbose && sym_name != nullptr)
5362 outs() << sym_name;
5363 else
5364 outs() << format("0x%" PRIx64, n_value);
5365 if (c.instanceMethods != 0)
5366 outs() << " + " << format("0x%" PRIx64, c.instanceMethods);
5367 } else
5368 outs() << format("0x%" PRIx64, c.instanceMethods);
5369 outs() << "\n";
5370 if (c.instanceMethods + n_value != 0)
5371 print_method_list64_t(c.instanceMethods + n_value, info, "");
5372
5373 outs() << " classMethods ";
5374 sym_name = get_symbol_64(offset + offsetof(struct category64_t, classMethods),
5375 S, info, n_value, c.classMethods);
5376 if (n_value != 0) {
5377 if (info->verbose && sym_name != nullptr)
5378 outs() << sym_name;
5379 else
5380 outs() << format("0x%" PRIx64, n_value);
5381 if (c.classMethods != 0)
5382 outs() << " + " << format("0x%" PRIx64, c.classMethods);
5383 } else
5384 outs() << format("0x%" PRIx64, c.classMethods);
5385 outs() << "\n";
5386 if (c.classMethods + n_value != 0)
5387 print_method_list64_t(c.classMethods + n_value, info, "");
5388
5389 outs() << " protocols ";
5390 sym_name = get_symbol_64(offset + offsetof(struct category64_t, protocols), S,
5391 info, n_value, c.protocols);
5392 if (n_value != 0) {
5393 if (info->verbose && sym_name != nullptr)
5394 outs() << sym_name;
5395 else
5396 outs() << format("0x%" PRIx64, n_value);
5397 if (c.protocols != 0)
5398 outs() << " + " << format("0x%" PRIx64, c.protocols);
5399 } else
5400 outs() << format("0x%" PRIx64, c.protocols);
5401 outs() << "\n";
5402 if (c.protocols + n_value != 0)
5403 print_protocol_list64_t(c.protocols + n_value, info);
5404
5405 outs() << "instanceProperties ";
5406 sym_name =
5407 get_symbol_64(offset + offsetof(struct category64_t, instanceProperties),
5408 S, info, n_value, c.instanceProperties);
5409 if (n_value != 0) {
5410 if (info->verbose && sym_name != nullptr)
5411 outs() << sym_name;
5412 else
5413 outs() << format("0x%" PRIx64, n_value);
5414 if (c.instanceProperties != 0)
5415 outs() << " + " << format("0x%" PRIx64, c.instanceProperties);
5416 } else
5417 outs() << format("0x%" PRIx64, c.instanceProperties);
5418 outs() << "\n";
5419 if (c.instanceProperties + n_value != 0)
5420 print_objc_property_list64(c.instanceProperties + n_value, info);
5421}
5422
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005423static void print_category32_t(uint32_t p, struct DisassembleInfo *info) {
5424 struct category32_t c;
5425 const char *r;
5426 uint32_t offset, left;
5427 SectionRef S, xS;
5428 const char *name;
5429
5430 r = get_pointer_32(p, offset, left, S, info);
5431 if (r == nullptr)
5432 return;
5433 memset(&c, '\0', sizeof(struct category32_t));
5434 if (left < sizeof(struct category32_t)) {
5435 memcpy(&c, r, left);
5436 outs() << " (category_t entends past the end of the section)\n";
5437 } else
5438 memcpy(&c, r, sizeof(struct category32_t));
5439 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5440 swapStruct(c);
5441
5442 outs() << " name " << format("0x%" PRIx32, c.name);
5443 name = get_symbol_32(offset + offsetof(struct category32_t, name), S, info,
5444 c.name);
Hans Wennborgcc9deb42015-09-29 18:02:48 +00005445 if (name)
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005446 outs() << " " << name;
5447 outs() << "\n";
5448
5449 outs() << " cls " << format("0x%" PRIx32, c.cls) << "\n";
5450 if (c.cls != 0)
5451 print_class32_t(c.cls, info);
5452 outs() << " instanceMethods " << format("0x%" PRIx32, c.instanceMethods)
5453 << "\n";
5454 if (c.instanceMethods != 0)
5455 print_method_list32_t(c.instanceMethods, info, "");
5456 outs() << " classMethods " << format("0x%" PRIx32, c.classMethods)
5457 << "\n";
5458 if (c.classMethods != 0)
5459 print_method_list32_t(c.classMethods, info, "");
5460 outs() << " protocols " << format("0x%" PRIx32, c.protocols) << "\n";
5461 if (c.protocols != 0)
5462 print_protocol_list32_t(c.protocols, info);
5463 outs() << "instanceProperties " << format("0x%" PRIx32, c.instanceProperties)
5464 << "\n";
5465 if (c.instanceProperties != 0)
5466 print_objc_property_list32(c.instanceProperties, info);
5467}
5468
Kevin Enderby0fc11822015-04-01 20:57:01 +00005469static void print_message_refs64(SectionRef S, struct DisassembleInfo *info) {
5470 uint32_t i, left, offset, xoffset;
5471 uint64_t p, n_value;
5472 struct message_ref64 mr;
5473 const char *name, *sym_name;
5474 const char *r;
5475 SectionRef xS;
5476
5477 if (S == SectionRef())
5478 return;
5479
5480 StringRef SectName;
5481 S.getName(SectName);
5482 DataRefImpl Ref = S.getRawDataRefImpl();
5483 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5484 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5485 offset = 0;
5486 for (i = 0; i < S.getSize(); i += sizeof(struct message_ref64)) {
5487 p = S.getAddress() + i;
5488 r = get_pointer_64(p, offset, left, S, info);
5489 if (r == nullptr)
5490 return;
5491 memset(&mr, '\0', sizeof(struct message_ref64));
5492 if (left < sizeof(struct message_ref64)) {
5493 memcpy(&mr, r, left);
5494 outs() << " (message_ref entends past the end of the section)\n";
5495 } else
5496 memcpy(&mr, r, sizeof(struct message_ref64));
5497 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5498 swapStruct(mr);
5499
5500 outs() << " imp ";
5501 name = get_symbol_64(offset + offsetof(struct message_ref64, imp), S, info,
5502 n_value, mr.imp);
5503 if (n_value != 0) {
5504 outs() << format("0x%" PRIx64, n_value) << " ";
5505 if (mr.imp != 0)
5506 outs() << "+ " << format("0x%" PRIx64, mr.imp) << " ";
5507 } else
5508 outs() << format("0x%" PRIx64, mr.imp) << " ";
5509 if (name != nullptr)
5510 outs() << " " << name;
5511 outs() << "\n";
5512
5513 outs() << " sel ";
5514 sym_name = get_symbol_64(offset + offsetof(struct message_ref64, sel), S,
5515 info, n_value, mr.sel);
5516 if (n_value != 0) {
5517 if (info->verbose && sym_name != nullptr)
5518 outs() << sym_name;
5519 else
5520 outs() << format("0x%" PRIx64, n_value);
5521 if (mr.sel != 0)
5522 outs() << " + " << format("0x%" PRIx64, mr.sel);
5523 } else
5524 outs() << format("0x%" PRIx64, mr.sel);
5525 name = get_pointer_64(mr.sel + n_value, xoffset, left, xS, info);
5526 if (name != nullptr)
5527 outs() << format(" %.*s", left, name);
5528 outs() << "\n";
5529
5530 offset += sizeof(struct message_ref64);
5531 }
5532}
5533
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005534static void print_message_refs32(SectionRef S, struct DisassembleInfo *info) {
5535 uint32_t i, left, offset, xoffset, p;
5536 struct message_ref32 mr;
5537 const char *name, *r;
5538 SectionRef xS;
5539
5540 if (S == SectionRef())
5541 return;
5542
5543 StringRef SectName;
5544 S.getName(SectName);
5545 DataRefImpl Ref = S.getRawDataRefImpl();
5546 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5547 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5548 offset = 0;
5549 for (i = 0; i < S.getSize(); i += sizeof(struct message_ref64)) {
5550 p = S.getAddress() + i;
5551 r = get_pointer_32(p, offset, left, S, info);
5552 if (r == nullptr)
5553 return;
5554 memset(&mr, '\0', sizeof(struct message_ref32));
5555 if (left < sizeof(struct message_ref32)) {
5556 memcpy(&mr, r, left);
5557 outs() << " (message_ref entends past the end of the section)\n";
5558 } else
5559 memcpy(&mr, r, sizeof(struct message_ref32));
5560 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5561 swapStruct(mr);
5562
5563 outs() << " imp " << format("0x%" PRIx32, mr.imp);
5564 name = get_symbol_32(offset + offsetof(struct message_ref32, imp), S, info,
5565 mr.imp);
5566 if (name != nullptr)
5567 outs() << " " << name;
5568 outs() << "\n";
5569
5570 outs() << " sel " << format("0x%" PRIx32, mr.sel);
5571 name = get_pointer_32(mr.sel, xoffset, left, xS, info);
5572 if (name != nullptr)
5573 outs() << " " << name;
5574 outs() << "\n";
5575
5576 offset += sizeof(struct message_ref32);
5577 }
5578}
5579
Kevin Enderby0fc11822015-04-01 20:57:01 +00005580static void print_image_info64(SectionRef S, struct DisassembleInfo *info) {
5581 uint32_t left, offset, swift_version;
5582 uint64_t p;
5583 struct objc_image_info64 o;
5584 const char *r;
5585
Kevin Enderbyaf7c9d02015-10-09 16:48:44 +00005586 if (S == SectionRef())
5587 return;
5588
Kevin Enderby0fc11822015-04-01 20:57:01 +00005589 StringRef SectName;
5590 S.getName(SectName);
5591 DataRefImpl Ref = S.getRawDataRefImpl();
5592 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5593 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5594 p = S.getAddress();
5595 r = get_pointer_64(p, offset, left, S, info);
5596 if (r == nullptr)
5597 return;
5598 memset(&o, '\0', sizeof(struct objc_image_info64));
5599 if (left < sizeof(struct objc_image_info64)) {
5600 memcpy(&o, r, left);
5601 outs() << " (objc_image_info entends past the end of the section)\n";
5602 } else
5603 memcpy(&o, r, sizeof(struct objc_image_info64));
5604 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5605 swapStruct(o);
5606 outs() << " version " << o.version << "\n";
5607 outs() << " flags " << format("0x%" PRIx32, o.flags);
5608 if (o.flags & OBJC_IMAGE_IS_REPLACEMENT)
5609 outs() << " OBJC_IMAGE_IS_REPLACEMENT";
5610 if (o.flags & OBJC_IMAGE_SUPPORTS_GC)
5611 outs() << " OBJC_IMAGE_SUPPORTS_GC";
Dave Lee390abe42018-07-06 05:11:35 +00005612 if (o.flags & OBJC_IMAGE_IS_SIMULATED)
5613 outs() << " OBJC_IMAGE_IS_SIMULATED";
5614 if (o.flags & OBJC_IMAGE_HAS_CATEGORY_CLASS_PROPERTIES)
5615 outs() << " OBJC_IMAGE_HAS_CATEGORY_CLASS_PROPERTIES";
Kevin Enderby0fc11822015-04-01 20:57:01 +00005616 swift_version = (o.flags >> 8) & 0xff;
5617 if (swift_version != 0) {
5618 if (swift_version == 1)
5619 outs() << " Swift 1.0";
5620 else if (swift_version == 2)
5621 outs() << " Swift 1.1";
Kevin Enderbycda2ced2018-02-09 19:31:27 +00005622 else if(swift_version == 3)
5623 outs() << " Swift 2.0";
5624 else if(swift_version == 4)
5625 outs() << " Swift 3.0";
5626 else if(swift_version == 5)
5627 outs() << " Swift 4.0";
5628 else if(swift_version == 6)
5629 outs() << " Swift 4.1";
Kevin Enderby0fc11822015-04-01 20:57:01 +00005630 else
5631 outs() << " unknown future Swift version (" << swift_version << ")";
5632 }
5633 outs() << "\n";
5634}
5635
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005636static void print_image_info32(SectionRef S, struct DisassembleInfo *info) {
5637 uint32_t left, offset, swift_version, p;
5638 struct objc_image_info32 o;
5639 const char *r;
5640
Kevin Enderby19be2512016-04-21 19:49:29 +00005641 if (S == SectionRef())
5642 return;
5643
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005644 StringRef SectName;
5645 S.getName(SectName);
5646 DataRefImpl Ref = S.getRawDataRefImpl();
5647 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5648 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5649 p = S.getAddress();
5650 r = get_pointer_32(p, offset, left, S, info);
5651 if (r == nullptr)
5652 return;
5653 memset(&o, '\0', sizeof(struct objc_image_info32));
5654 if (left < sizeof(struct objc_image_info32)) {
5655 memcpy(&o, r, left);
5656 outs() << " (objc_image_info entends past the end of the section)\n";
5657 } else
5658 memcpy(&o, r, sizeof(struct objc_image_info32));
5659 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5660 swapStruct(o);
5661 outs() << " version " << o.version << "\n";
5662 outs() << " flags " << format("0x%" PRIx32, o.flags);
5663 if (o.flags & OBJC_IMAGE_IS_REPLACEMENT)
5664 outs() << " OBJC_IMAGE_IS_REPLACEMENT";
5665 if (o.flags & OBJC_IMAGE_SUPPORTS_GC)
5666 outs() << " OBJC_IMAGE_SUPPORTS_GC";
5667 swift_version = (o.flags >> 8) & 0xff;
5668 if (swift_version != 0) {
5669 if (swift_version == 1)
5670 outs() << " Swift 1.0";
5671 else if (swift_version == 2)
5672 outs() << " Swift 1.1";
Kevin Enderbycda2ced2018-02-09 19:31:27 +00005673 else if(swift_version == 3)
5674 outs() << " Swift 2.0";
5675 else if(swift_version == 4)
5676 outs() << " Swift 3.0";
5677 else if(swift_version == 5)
5678 outs() << " Swift 4.0";
5679 else if(swift_version == 6)
5680 outs() << " Swift 4.1";
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005681 else
5682 outs() << " unknown future Swift version (" << swift_version << ")";
5683 }
5684 outs() << "\n";
5685}
5686
Kevin Enderby846c0002015-04-16 17:19:59 +00005687static void print_image_info(SectionRef S, struct DisassembleInfo *info) {
5688 uint32_t left, offset, p;
5689 struct imageInfo_t o;
5690 const char *r;
5691
5692 StringRef SectName;
5693 S.getName(SectName);
5694 DataRefImpl Ref = S.getRawDataRefImpl();
5695 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5696 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5697 p = S.getAddress();
5698 r = get_pointer_32(p, offset, left, S, info);
5699 if (r == nullptr)
5700 return;
5701 memset(&o, '\0', sizeof(struct imageInfo_t));
5702 if (left < sizeof(struct imageInfo_t)) {
5703 memcpy(&o, r, left);
5704 outs() << " (imageInfo entends past the end of the section)\n";
5705 } else
5706 memcpy(&o, r, sizeof(struct imageInfo_t));
5707 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5708 swapStruct(o);
5709 outs() << " version " << o.version << "\n";
5710 outs() << " flags " << format("0x%" PRIx32, o.flags);
5711 if (o.flags & 0x1)
5712 outs() << " F&C";
5713 if (o.flags & 0x2)
5714 outs() << " GC";
5715 if (o.flags & 0x4)
5716 outs() << " GC-only";
5717 else
5718 outs() << " RR";
5719 outs() << "\n";
5720}
5721
Kevin Enderby0fc11822015-04-01 20:57:01 +00005722static void printObjc2_64bit_MetaData(MachOObjectFile *O, bool verbose) {
5723 SymbolAddressMap AddrMap;
5724 if (verbose)
5725 CreateSymbolAddressMap(O, &AddrMap);
5726
5727 std::vector<SectionRef> Sections;
5728 for (const SectionRef &Section : O->sections()) {
5729 StringRef SectName;
5730 Section.getName(SectName);
5731 Sections.push_back(Section);
5732 }
5733
Serge Pavlove4e9a1f2018-02-14 03:26:27 +00005734 struct DisassembleInfo info(O, &AddrMap, &Sections, verbose);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005735
Davide Italiano62507042015-12-11 22:27:59 +00005736 SectionRef CL = get_section(O, "__OBJC2", "__class_list");
5737 if (CL == SectionRef())
5738 CL = get_section(O, "__DATA", "__objc_classlist");
Kevin Enderby5879a482017-02-09 17:56:26 +00005739 if (CL == SectionRef())
5740 CL = get_section(O, "__DATA_CONST", "__objc_classlist");
5741 if (CL == SectionRef())
5742 CL = get_section(O, "__DATA_DIRTY", "__objc_classlist");
Davide Italiano62507042015-12-11 22:27:59 +00005743 info.S = CL;
5744 walk_pointer_list_64("class", CL, O, &info, print_class64_t);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005745
Davide Italiano62507042015-12-11 22:27:59 +00005746 SectionRef CR = get_section(O, "__OBJC2", "__class_refs");
5747 if (CR == SectionRef())
5748 CR = get_section(O, "__DATA", "__objc_classrefs");
Kevin Enderby5879a482017-02-09 17:56:26 +00005749 if (CR == SectionRef())
5750 CR = get_section(O, "__DATA_CONST", "__objc_classrefs");
5751 if (CR == SectionRef())
5752 CR = get_section(O, "__DATA_DIRTY", "__objc_classrefs");
Davide Italiano62507042015-12-11 22:27:59 +00005753 info.S = CR;
5754 walk_pointer_list_64("class refs", CR, O, &info, nullptr);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005755
Davide Italiano62507042015-12-11 22:27:59 +00005756 SectionRef SR = get_section(O, "__OBJC2", "__super_refs");
5757 if (SR == SectionRef())
5758 SR = get_section(O, "__DATA", "__objc_superrefs");
Kevin Enderby5879a482017-02-09 17:56:26 +00005759 if (SR == SectionRef())
5760 SR = get_section(O, "__DATA_CONST", "__objc_superrefs");
5761 if (SR == SectionRef())
5762 SR = get_section(O, "__DATA_DIRTY", "__objc_superrefs");
Davide Italiano62507042015-12-11 22:27:59 +00005763 info.S = SR;
5764 walk_pointer_list_64("super refs", SR, O, &info, nullptr);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005765
Davide Italiano62507042015-12-11 22:27:59 +00005766 SectionRef CA = get_section(O, "__OBJC2", "__category_list");
5767 if (CA == SectionRef())
5768 CA = get_section(O, "__DATA", "__objc_catlist");
Kevin Enderby5879a482017-02-09 17:56:26 +00005769 if (CA == SectionRef())
5770 CA = get_section(O, "__DATA_CONST", "__objc_catlist");
5771 if (CA == SectionRef())
5772 CA = get_section(O, "__DATA_DIRTY", "__objc_catlist");
Davide Italiano62507042015-12-11 22:27:59 +00005773 info.S = CA;
5774 walk_pointer_list_64("category", CA, O, &info, print_category64_t);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005775
Davide Italiano62507042015-12-11 22:27:59 +00005776 SectionRef PL = get_section(O, "__OBJC2", "__protocol_list");
5777 if (PL == SectionRef())
5778 PL = get_section(O, "__DATA", "__objc_protolist");
Kevin Enderby5879a482017-02-09 17:56:26 +00005779 if (PL == SectionRef())
5780 PL = get_section(O, "__DATA_CONST", "__objc_protolist");
5781 if (PL == SectionRef())
5782 PL = get_section(O, "__DATA_DIRTY", "__objc_protolist");
Davide Italiano62507042015-12-11 22:27:59 +00005783 info.S = PL;
5784 walk_pointer_list_64("protocol", PL, O, &info, nullptr);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005785
Davide Italiano62507042015-12-11 22:27:59 +00005786 SectionRef MR = get_section(O, "__OBJC2", "__message_refs");
5787 if (MR == SectionRef())
5788 MR = get_section(O, "__DATA", "__objc_msgrefs");
Kevin Enderby5879a482017-02-09 17:56:26 +00005789 if (MR == SectionRef())
5790 MR = get_section(O, "__DATA_CONST", "__objc_msgrefs");
5791 if (MR == SectionRef())
5792 MR = get_section(O, "__DATA_DIRTY", "__objc_msgrefs");
Davide Italiano62507042015-12-11 22:27:59 +00005793 info.S = MR;
5794 print_message_refs64(MR, &info);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005795
Davide Italiano62507042015-12-11 22:27:59 +00005796 SectionRef II = get_section(O, "__OBJC2", "__image_info");
5797 if (II == SectionRef())
5798 II = get_section(O, "__DATA", "__objc_imageinfo");
Kevin Enderby5879a482017-02-09 17:56:26 +00005799 if (II == SectionRef())
5800 II = get_section(O, "__DATA_CONST", "__objc_imageinfo");
5801 if (II == SectionRef())
5802 II = get_section(O, "__DATA_DIRTY", "__objc_imageinfo");
Davide Italiano62507042015-12-11 22:27:59 +00005803 info.S = II;
5804 print_image_info64(II, &info);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005805}
5806
5807static void printObjc2_32bit_MetaData(MachOObjectFile *O, bool verbose) {
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005808 SymbolAddressMap AddrMap;
5809 if (verbose)
5810 CreateSymbolAddressMap(O, &AddrMap);
5811
5812 std::vector<SectionRef> Sections;
5813 for (const SectionRef &Section : O->sections()) {
5814 StringRef SectName;
5815 Section.getName(SectName);
5816 Sections.push_back(Section);
5817 }
5818
Serge Pavlove4e9a1f2018-02-14 03:26:27 +00005819 struct DisassembleInfo info(O, &AddrMap, &Sections, verbose);
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005820
Kevin Enderby5879a482017-02-09 17:56:26 +00005821 SectionRef CL = get_section(O, "__OBJC2", "__class_list");
5822 if (CL == SectionRef())
5823 CL = get_section(O, "__DATA", "__objc_classlist");
5824 if (CL == SectionRef())
5825 CL = get_section(O, "__DATA_CONST", "__objc_classlist");
5826 if (CL == SectionRef())
5827 CL = get_section(O, "__DATA_DIRTY", "__objc_classlist");
5828 info.S = CL;
5829 walk_pointer_list_32("class", CL, O, &info, print_class32_t);
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005830
Kevin Enderby5879a482017-02-09 17:56:26 +00005831 SectionRef CR = get_section(O, "__OBJC2", "__class_refs");
5832 if (CR == SectionRef())
5833 CR = get_section(O, "__DATA", "__objc_classrefs");
5834 if (CR == SectionRef())
5835 CR = get_section(O, "__DATA_CONST", "__objc_classrefs");
5836 if (CR == SectionRef())
5837 CR = get_section(O, "__DATA_DIRTY", "__objc_classrefs");
5838 info.S = CR;
5839 walk_pointer_list_32("class refs", CR, O, &info, nullptr);
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005840
Kevin Enderby5879a482017-02-09 17:56:26 +00005841 SectionRef SR = get_section(O, "__OBJC2", "__super_refs");
5842 if (SR == SectionRef())
5843 SR = get_section(O, "__DATA", "__objc_superrefs");
5844 if (SR == SectionRef())
5845 SR = get_section(O, "__DATA_CONST", "__objc_superrefs");
5846 if (SR == SectionRef())
5847 SR = get_section(O, "__DATA_DIRTY", "__objc_superrefs");
5848 info.S = SR;
5849 walk_pointer_list_32("super refs", SR, O, &info, nullptr);
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005850
Kevin Enderby5879a482017-02-09 17:56:26 +00005851 SectionRef CA = get_section(O, "__OBJC2", "__category_list");
5852 if (CA == SectionRef())
5853 CA = get_section(O, "__DATA", "__objc_catlist");
5854 if (CA == SectionRef())
5855 CA = get_section(O, "__DATA_CONST", "__objc_catlist");
5856 if (CA == SectionRef())
5857 CA = get_section(O, "__DATA_DIRTY", "__objc_catlist");
5858 info.S = CA;
5859 walk_pointer_list_32("category", CA, O, &info, print_category32_t);
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005860
Kevin Enderby5879a482017-02-09 17:56:26 +00005861 SectionRef PL = get_section(O, "__OBJC2", "__protocol_list");
5862 if (PL == SectionRef())
5863 PL = get_section(O, "__DATA", "__objc_protolist");
5864 if (PL == SectionRef())
5865 PL = get_section(O, "__DATA_CONST", "__objc_protolist");
5866 if (PL == SectionRef())
5867 PL = get_section(O, "__DATA_DIRTY", "__objc_protolist");
5868 info.S = PL;
5869 walk_pointer_list_32("protocol", PL, O, &info, nullptr);
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005870
Kevin Enderby5879a482017-02-09 17:56:26 +00005871 SectionRef MR = get_section(O, "__OBJC2", "__message_refs");
5872 if (MR == SectionRef())
5873 MR = get_section(O, "__DATA", "__objc_msgrefs");
5874 if (MR == SectionRef())
5875 MR = get_section(O, "__DATA_CONST", "__objc_msgrefs");
5876 if (MR == SectionRef())
5877 MR = get_section(O, "__DATA_DIRTY", "__objc_msgrefs");
5878 info.S = MR;
5879 print_message_refs32(MR, &info);
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005880
Kevin Enderby5879a482017-02-09 17:56:26 +00005881 SectionRef II = get_section(O, "__OBJC2", "__image_info");
5882 if (II == SectionRef())
5883 II = get_section(O, "__DATA", "__objc_imageinfo");
5884 if (II == SectionRef())
5885 II = get_section(O, "__DATA_CONST", "__objc_imageinfo");
5886 if (II == SectionRef())
5887 II = get_section(O, "__DATA_DIRTY", "__objc_imageinfo");
5888 info.S = II;
5889 print_image_info32(II, &info);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005890}
5891
5892static bool printObjc1_32bit_MetaData(MachOObjectFile *O, bool verbose) {
Kevin Enderby846c0002015-04-16 17:19:59 +00005893 uint32_t i, j, p, offset, xoffset, left, defs_left, def;
5894 const char *r, *name, *defs;
5895 struct objc_module_t module;
5896 SectionRef S, xS;
5897 struct objc_symtab_t symtab;
5898 struct objc_class_t objc_class;
5899 struct objc_category_t objc_category;
5900
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005901 outs() << "Objective-C segment\n";
Kevin Enderby846c0002015-04-16 17:19:59 +00005902 S = get_section(O, "__OBJC", "__module_info");
5903 if (S == SectionRef())
5904 return false;
5905
5906 SymbolAddressMap AddrMap;
5907 if (verbose)
5908 CreateSymbolAddressMap(O, &AddrMap);
5909
5910 std::vector<SectionRef> Sections;
5911 for (const SectionRef &Section : O->sections()) {
5912 StringRef SectName;
5913 Section.getName(SectName);
5914 Sections.push_back(Section);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005915 }
Kevin Enderby846c0002015-04-16 17:19:59 +00005916
Serge Pavlove4e9a1f2018-02-14 03:26:27 +00005917 struct DisassembleInfo info(O, &AddrMap, &Sections, verbose);
Kevin Enderby846c0002015-04-16 17:19:59 +00005918
5919 for (i = 0; i < S.getSize(); i += sizeof(struct objc_module_t)) {
5920 p = S.getAddress() + i;
5921 r = get_pointer_32(p, offset, left, S, &info, true);
5922 if (r == nullptr)
5923 return true;
5924 memset(&module, '\0', sizeof(struct objc_module_t));
5925 if (left < sizeof(struct objc_module_t)) {
5926 memcpy(&module, r, left);
5927 outs() << " (module extends past end of __module_info section)\n";
5928 } else
5929 memcpy(&module, r, sizeof(struct objc_module_t));
5930 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5931 swapStruct(module);
5932
5933 outs() << "Module " << format("0x%" PRIx32, p) << "\n";
5934 outs() << " version " << module.version << "\n";
5935 outs() << " size " << module.size << "\n";
5936 outs() << " name ";
5937 name = get_pointer_32(module.name, xoffset, left, xS, &info, true);
5938 if (name != nullptr)
5939 outs() << format("%.*s", left, name);
5940 else
5941 outs() << format("0x%08" PRIx32, module.name)
5942 << "(not in an __OBJC section)";
5943 outs() << "\n";
5944
5945 r = get_pointer_32(module.symtab, xoffset, left, xS, &info, true);
5946 if (module.symtab == 0 || r == nullptr) {
5947 outs() << " symtab " << format("0x%08" PRIx32, module.symtab)
5948 << " (not in an __OBJC section)\n";
5949 continue;
5950 }
5951 outs() << " symtab " << format("0x%08" PRIx32, module.symtab) << "\n";
5952 memset(&symtab, '\0', sizeof(struct objc_symtab_t));
5953 defs_left = 0;
5954 defs = nullptr;
5955 if (left < sizeof(struct objc_symtab_t)) {
5956 memcpy(&symtab, r, left);
5957 outs() << "\tsymtab extends past end of an __OBJC section)\n";
5958 } else {
5959 memcpy(&symtab, r, sizeof(struct objc_symtab_t));
5960 if (left > sizeof(struct objc_symtab_t)) {
5961 defs_left = left - sizeof(struct objc_symtab_t);
5962 defs = r + sizeof(struct objc_symtab_t);
5963 }
5964 }
5965 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5966 swapStruct(symtab);
5967
5968 outs() << "\tsel_ref_cnt " << symtab.sel_ref_cnt << "\n";
5969 r = get_pointer_32(symtab.refs, xoffset, left, xS, &info, true);
5970 outs() << "\trefs " << format("0x%08" PRIx32, symtab.refs);
5971 if (r == nullptr)
5972 outs() << " (not in an __OBJC section)";
5973 outs() << "\n";
5974 outs() << "\tcls_def_cnt " << symtab.cls_def_cnt << "\n";
5975 outs() << "\tcat_def_cnt " << symtab.cat_def_cnt << "\n";
5976 if (symtab.cls_def_cnt > 0)
5977 outs() << "\tClass Definitions\n";
5978 for (j = 0; j < symtab.cls_def_cnt; j++) {
5979 if ((j + 1) * sizeof(uint32_t) > defs_left) {
5980 outs() << "\t(remaining class defs entries entends past the end of the "
5981 << "section)\n";
5982 break;
5983 }
5984 memcpy(&def, defs + j * sizeof(uint32_t), sizeof(uint32_t));
5985 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5986 sys::swapByteOrder(def);
5987
5988 r = get_pointer_32(def, xoffset, left, xS, &info, true);
5989 outs() << "\tdefs[" << j << "] " << format("0x%08" PRIx32, def);
5990 if (r != nullptr) {
5991 if (left > sizeof(struct objc_class_t)) {
5992 outs() << "\n";
5993 memcpy(&objc_class, r, sizeof(struct objc_class_t));
5994 } else {
5995 outs() << " (entends past the end of the section)\n";
5996 memset(&objc_class, '\0', sizeof(struct objc_class_t));
5997 memcpy(&objc_class, r, left);
5998 }
5999 if (O->isLittleEndian() != sys::IsLittleEndianHost)
6000 swapStruct(objc_class);
6001 print_objc_class_t(&objc_class, &info);
6002 } else {
6003 outs() << "(not in an __OBJC section)\n";
6004 }
6005
6006 if (CLS_GETINFO(&objc_class, CLS_CLASS)) {
6007 outs() << "\tMeta Class";
6008 r = get_pointer_32(objc_class.isa, xoffset, left, xS, &info, true);
6009 if (r != nullptr) {
6010 if (left > sizeof(struct objc_class_t)) {
6011 outs() << "\n";
6012 memcpy(&objc_class, r, sizeof(struct objc_class_t));
6013 } else {
6014 outs() << " (entends past the end of the section)\n";
6015 memset(&objc_class, '\0', sizeof(struct objc_class_t));
6016 memcpy(&objc_class, r, left);
6017 }
6018 if (O->isLittleEndian() != sys::IsLittleEndianHost)
6019 swapStruct(objc_class);
6020 print_objc_class_t(&objc_class, &info);
6021 } else {
6022 outs() << "(not in an __OBJC section)\n";
6023 }
6024 }
6025 }
6026 if (symtab.cat_def_cnt > 0)
6027 outs() << "\tCategory Definitions\n";
6028 for (j = 0; j < symtab.cat_def_cnt; j++) {
6029 if ((j + symtab.cls_def_cnt + 1) * sizeof(uint32_t) > defs_left) {
6030 outs() << "\t(remaining category defs entries entends past the end of "
6031 << "the section)\n";
6032 break;
6033 }
6034 memcpy(&def, defs + (j + symtab.cls_def_cnt) * sizeof(uint32_t),
6035 sizeof(uint32_t));
6036 if (O->isLittleEndian() != sys::IsLittleEndianHost)
6037 sys::swapByteOrder(def);
6038
6039 r = get_pointer_32(def, xoffset, left, xS, &info, true);
6040 outs() << "\tdefs[" << j + symtab.cls_def_cnt << "] "
6041 << format("0x%08" PRIx32, def);
6042 if (r != nullptr) {
6043 if (left > sizeof(struct objc_category_t)) {
6044 outs() << "\n";
6045 memcpy(&objc_category, r, sizeof(struct objc_category_t));
6046 } else {
6047 outs() << " (entends past the end of the section)\n";
6048 memset(&objc_category, '\0', sizeof(struct objc_category_t));
6049 memcpy(&objc_category, r, left);
6050 }
6051 if (O->isLittleEndian() != sys::IsLittleEndianHost)
6052 swapStruct(objc_category);
6053 print_objc_objc_category_t(&objc_category, &info);
6054 } else {
6055 outs() << "(not in an __OBJC section)\n";
6056 }
6057 }
6058 }
6059 const SectionRef II = get_section(O, "__OBJC", "__image_info");
6060 if (II != SectionRef())
6061 print_image_info(II, &info);
6062
6063 return true;
Kevin Enderby0fc11822015-04-01 20:57:01 +00006064}
6065
Kevin Enderby4ad9bde2015-04-16 22:33:20 +00006066static void DumpProtocolSection(MachOObjectFile *O, const char *sect,
6067 uint32_t size, uint32_t addr) {
6068 SymbolAddressMap AddrMap;
6069 CreateSymbolAddressMap(O, &AddrMap);
6070
6071 std::vector<SectionRef> Sections;
6072 for (const SectionRef &Section : O->sections()) {
6073 StringRef SectName;
6074 Section.getName(SectName);
6075 Sections.push_back(Section);
6076 }
6077
Serge Pavlove4e9a1f2018-02-14 03:26:27 +00006078 struct DisassembleInfo info(O, &AddrMap, &Sections, true);
Kevin Enderby4ad9bde2015-04-16 22:33:20 +00006079
6080 const char *p;
6081 struct objc_protocol_t protocol;
6082 uint32_t left, paddr;
6083 for (p = sect; p < sect + size; p += sizeof(struct objc_protocol_t)) {
6084 memset(&protocol, '\0', sizeof(struct objc_protocol_t));
6085 left = size - (p - sect);
6086 if (left < sizeof(struct objc_protocol_t)) {
6087 outs() << "Protocol extends past end of __protocol section\n";
6088 memcpy(&protocol, p, left);
6089 } else
6090 memcpy(&protocol, p, sizeof(struct objc_protocol_t));
6091 if (O->isLittleEndian() != sys::IsLittleEndianHost)
6092 swapStruct(protocol);
6093 paddr = addr + (p - sect);
6094 outs() << "Protocol " << format("0x%" PRIx32, paddr);
6095 if (print_protocol(paddr, 0, &info))
6096 outs() << "(not in an __OBJC section)\n";
6097 }
6098}
6099
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006100#ifdef HAVE_LIBXAR
6101inline void swapStruct(struct xar_header &xar) {
6102 sys::swapByteOrder(xar.magic);
6103 sys::swapByteOrder(xar.size);
6104 sys::swapByteOrder(xar.version);
6105 sys::swapByteOrder(xar.toc_length_compressed);
6106 sys::swapByteOrder(xar.toc_length_uncompressed);
6107 sys::swapByteOrder(xar.cksum_alg);
6108}
6109
6110static void PrintModeVerbose(uint32_t mode) {
6111 switch(mode & S_IFMT){
6112 case S_IFDIR:
6113 outs() << "d";
6114 break;
6115 case S_IFCHR:
6116 outs() << "c";
6117 break;
6118 case S_IFBLK:
6119 outs() << "b";
6120 break;
6121 case S_IFREG:
6122 outs() << "-";
6123 break;
6124 case S_IFLNK:
6125 outs() << "l";
6126 break;
6127 case S_IFSOCK:
6128 outs() << "s";
6129 break;
6130 default:
6131 outs() << "?";
6132 break;
6133 }
6134
6135 /* owner permissions */
6136 if(mode & S_IREAD)
6137 outs() << "r";
6138 else
6139 outs() << "-";
6140 if(mode & S_IWRITE)
6141 outs() << "w";
6142 else
6143 outs() << "-";
6144 if(mode & S_ISUID)
6145 outs() << "s";
6146 else if(mode & S_IEXEC)
6147 outs() << "x";
6148 else
6149 outs() << "-";
6150
6151 /* group permissions */
6152 if(mode & (S_IREAD >> 3))
6153 outs() << "r";
6154 else
6155 outs() << "-";
6156 if(mode & (S_IWRITE >> 3))
6157 outs() << "w";
6158 else
6159 outs() << "-";
6160 if(mode & S_ISGID)
6161 outs() << "s";
6162 else if(mode & (S_IEXEC >> 3))
6163 outs() << "x";
6164 else
6165 outs() << "-";
6166
6167 /* other permissions */
6168 if(mode & (S_IREAD >> 6))
6169 outs() << "r";
6170 else
6171 outs() << "-";
6172 if(mode & (S_IWRITE >> 6))
6173 outs() << "w";
6174 else
6175 outs() << "-";
6176 if(mode & S_ISVTX)
6177 outs() << "t";
6178 else if(mode & (S_IEXEC >> 6))
6179 outs() << "x";
6180 else
6181 outs() << "-";
6182}
6183
6184static void PrintXarFilesSummary(const char *XarFilename, xar_t xar) {
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006185 xar_file_t xf;
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006186 const char *key, *type, *mode, *user, *group, *size, *mtime, *name, *m;
6187 char *endp;
6188 uint32_t mode_value;
6189
Francis Ricci6f942972017-10-06 15:33:28 +00006190 ScopedXarIter xi;
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006191 if (!xi) {
Jonas Devliegheree787efd2018-11-11 22:12:04 +00006192 WithColor::error(errs(), "llvm-objdump")
6193 << "can't obtain an xar iterator for xar archive " << XarFilename
6194 << "\n";
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006195 return;
6196 }
6197
6198 // Go through the xar's files.
6199 for (xf = xar_file_first(xar, xi); xf; xf = xar_file_next(xi)) {
Francis Ricci6f942972017-10-06 15:33:28 +00006200 ScopedXarIter xp;
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006201 if(!xp){
Jonas Devliegheree787efd2018-11-11 22:12:04 +00006202 WithColor::error(errs(), "llvm-objdump")
6203 << "can't obtain an xar iterator for xar archive " << XarFilename
6204 << "\n";
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006205 return;
6206 }
6207 type = nullptr;
6208 mode = nullptr;
6209 user = nullptr;
6210 group = nullptr;
6211 size = nullptr;
6212 mtime = nullptr;
6213 name = nullptr;
6214 for(key = xar_prop_first(xf, xp); key; key = xar_prop_next(xp)){
Jonas Devliegherec0a758d2017-09-18 14:15:57 +00006215 const char *val = nullptr;
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006216 xar_prop_get(xf, key, &val);
6217#if 0 // Useful for debugging.
6218 outs() << "key: " << key << " value: " << val << "\n";
6219#endif
6220 if(strcmp(key, "type") == 0)
6221 type = val;
6222 if(strcmp(key, "mode") == 0)
6223 mode = val;
6224 if(strcmp(key, "user") == 0)
6225 user = val;
6226 if(strcmp(key, "group") == 0)
6227 group = val;
6228 if(strcmp(key, "data/size") == 0)
6229 size = val;
6230 if(strcmp(key, "mtime") == 0)
6231 mtime = val;
6232 if(strcmp(key, "name") == 0)
6233 name = val;
6234 }
6235 if(mode != nullptr){
6236 mode_value = strtoul(mode, &endp, 8);
6237 if(*endp != '\0')
6238 outs() << "(mode: \"" << mode << "\" contains non-octal chars) ";
6239 if(strcmp(type, "file") == 0)
6240 mode_value |= S_IFREG;
6241 PrintModeVerbose(mode_value);
6242 outs() << " ";
6243 }
6244 if(user != nullptr)
6245 outs() << format("%10s/", user);
6246 if(group != nullptr)
6247 outs() << format("%-10s ", group);
6248 if(size != nullptr)
6249 outs() << format("%7s ", size);
6250 if(mtime != nullptr){
6251 for(m = mtime; *m != 'T' && *m != '\0'; m++)
6252 outs() << *m;
6253 if(*m == 'T')
6254 m++;
6255 outs() << " ";
6256 for( ; *m != 'Z' && *m != '\0'; m++)
6257 outs() << *m;
6258 outs() << " ";
6259 }
6260 if(name != nullptr)
6261 outs() << name;
6262 outs() << "\n";
6263 }
6264}
6265
6266static void DumpBitcodeSection(MachOObjectFile *O, const char *sect,
6267 uint32_t size, bool verbose,
6268 bool PrintXarHeader, bool PrintXarFileHeaders,
6269 std::string XarMemberName) {
6270 if(size < sizeof(struct xar_header)) {
6271 outs() << "size of (__LLVM,__bundle) section too small (smaller than size "
6272 "of struct xar_header)\n";
6273 return;
6274 }
6275 struct xar_header XarHeader;
6276 memcpy(&XarHeader, sect, sizeof(struct xar_header));
6277 if (sys::IsLittleEndianHost)
6278 swapStruct(XarHeader);
6279 if (PrintXarHeader) {
6280 if (!XarMemberName.empty())
6281 outs() << "In xar member " << XarMemberName << ": ";
6282 else
6283 outs() << "For (__LLVM,__bundle) section: ";
6284 outs() << "xar header\n";
6285 if (XarHeader.magic == XAR_HEADER_MAGIC)
6286 outs() << " magic XAR_HEADER_MAGIC\n";
6287 else
6288 outs() << " magic "
6289 << format_hex(XarHeader.magic, 10, true)
6290 << " (not XAR_HEADER_MAGIC)\n";
6291 outs() << " size " << XarHeader.size << "\n";
6292 outs() << " version " << XarHeader.version << "\n";
6293 outs() << " toc_length_compressed " << XarHeader.toc_length_compressed
6294 << "\n";
6295 outs() << "toc_length_uncompressed " << XarHeader.toc_length_uncompressed
6296 << "\n";
6297 outs() << " cksum_alg ";
6298 switch (XarHeader.cksum_alg) {
6299 case XAR_CKSUM_NONE:
6300 outs() << "XAR_CKSUM_NONE\n";
6301 break;
6302 case XAR_CKSUM_SHA1:
6303 outs() << "XAR_CKSUM_SHA1\n";
6304 break;
6305 case XAR_CKSUM_MD5:
6306 outs() << "XAR_CKSUM_MD5\n";
6307 break;
Kevin Enderby42882282016-05-23 22:18:59 +00006308#ifdef XAR_CKSUM_SHA256
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006309 case XAR_CKSUM_SHA256:
6310 outs() << "XAR_CKSUM_SHA256\n";
6311 break;
Kevin Enderby42882282016-05-23 22:18:59 +00006312#endif
6313#ifdef XAR_CKSUM_SHA512
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006314 case XAR_CKSUM_SHA512:
6315 outs() << "XAR_CKSUM_SHA512\n";
6316 break;
Kevin Enderby42882282016-05-23 22:18:59 +00006317#endif
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006318 default:
6319 outs() << XarHeader.cksum_alg << "\n";
6320 }
6321 }
6322
6323 SmallString<128> XarFilename;
6324 int FD;
6325 std::error_code XarEC =
6326 sys::fs::createTemporaryFile("llvm-objdump", "xar", FD, XarFilename);
6327 if (XarEC) {
Jonas Devliegheree787efd2018-11-11 22:12:04 +00006328 WithColor::error(errs(), "llvm-objdump") << XarEC.message() << "\n";
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006329 return;
6330 }
Reid Kleckner3fc649c2017-09-23 01:03:17 +00006331 ToolOutputFile XarFile(XarFilename, FD);
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006332 raw_fd_ostream &XarOut = XarFile.os();
6333 StringRef XarContents(sect, size);
6334 XarOut << XarContents;
6335 XarOut.close();
6336 if (XarOut.has_error())
6337 return;
6338
Francis Ricci6f942972017-10-06 15:33:28 +00006339 ScopedXarFile xar(XarFilename.c_str(), READ);
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006340 if (!xar) {
Jonas Devliegheree787efd2018-11-11 22:12:04 +00006341 WithColor::error(errs(), "llvm-objdump")
6342 << "can't create temporary xar archive " << XarFilename << "\n";
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006343 return;
6344 }
6345
6346 SmallString<128> TocFilename;
6347 std::error_code TocEC =
6348 sys::fs::createTemporaryFile("llvm-objdump", "toc", TocFilename);
6349 if (TocEC) {
Jonas Devliegheree787efd2018-11-11 22:12:04 +00006350 WithColor::error(errs(), "llvm-objdump") << TocEC.message() << "\n";
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006351 return;
6352 }
6353 xar_serialize(xar, TocFilename.c_str());
6354
6355 if (PrintXarFileHeaders) {
6356 if (!XarMemberName.empty())
6357 outs() << "In xar member " << XarMemberName << ": ";
6358 else
6359 outs() << "For (__LLVM,__bundle) section: ";
6360 outs() << "xar archive files:\n";
6361 PrintXarFilesSummary(XarFilename.c_str(), xar);
6362 }
6363
6364 ErrorOr<std::unique_ptr<MemoryBuffer>> FileOrErr =
6365 MemoryBuffer::getFileOrSTDIN(TocFilename.c_str());
6366 if (std::error_code EC = FileOrErr.getError()) {
Jonas Devliegheree787efd2018-11-11 22:12:04 +00006367 WithColor::error(errs(), "llvm-objdump") << EC.message() << "\n";
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006368 return;
6369 }
6370 std::unique_ptr<MemoryBuffer> &Buffer = FileOrErr.get();
6371
6372 if (!XarMemberName.empty())
6373 outs() << "In xar member " << XarMemberName << ": ";
6374 else
6375 outs() << "For (__LLVM,__bundle) section: ";
6376 outs() << "xar table of contents:\n";
6377 outs() << Buffer->getBuffer() << "\n";
6378
6379 // TODO: Go through the xar's files.
Francis Ricci6f942972017-10-06 15:33:28 +00006380 ScopedXarIter xi;
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006381 if(!xi){
Jonas Devliegheree787efd2018-11-11 22:12:04 +00006382 WithColor::error(errs(), "llvm-objdump")
6383 << "can't obtain an xar iterator for xar archive "
6384 << XarFilename.c_str() << "\n";
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006385 return;
6386 }
6387 for(xar_file_t xf = xar_file_first(xar, xi); xf; xf = xar_file_next(xi)){
6388 const char *key;
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006389 const char *member_name, *member_type, *member_size_string;
6390 size_t member_size;
6391
Francis Ricci6f942972017-10-06 15:33:28 +00006392 ScopedXarIter xp;
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006393 if(!xp){
Jonas Devliegheree787efd2018-11-11 22:12:04 +00006394 WithColor::error(errs(), "llvm-objdump")
6395 << "can't obtain an xar iterator for xar archive "
6396 << XarFilename.c_str() << "\n";
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006397 return;
6398 }
6399 member_name = NULL;
6400 member_type = NULL;
6401 member_size_string = NULL;
6402 for(key = xar_prop_first(xf, xp); key; key = xar_prop_next(xp)){
Jonas Devliegherec0a758d2017-09-18 14:15:57 +00006403 const char *val = nullptr;
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006404 xar_prop_get(xf, key, &val);
6405#if 0 // Useful for debugging.
6406 outs() << "key: " << key << " value: " << val << "\n";
6407#endif
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +00006408 if (strcmp(key, "name") == 0)
6409 member_name = val;
6410 if (strcmp(key, "type") == 0)
6411 member_type = val;
6412 if (strcmp(key, "data/size") == 0)
6413 member_size_string = val;
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006414 }
6415 /*
6416 * If we find a file with a name, date/size and type properties
6417 * and with the type being "file" see if that is a xar file.
6418 */
6419 if (member_name != NULL && member_type != NULL &&
6420 strcmp(member_type, "file") == 0 &&
6421 member_size_string != NULL){
6422 // Extract the file into a buffer.
6423 char *endptr;
6424 member_size = strtoul(member_size_string, &endptr, 10);
6425 if (*endptr == '\0' && member_size != 0) {
Francis Ricci1bae0ac2017-09-13 13:57:45 +00006426 char *buffer;
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +00006427 if (xar_extract_tobuffersz(xar, xf, &buffer, &member_size) == 0) {
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006428#if 0 // Useful for debugging.
NAKAMURA Takumi6f43bd42017-10-18 13:31:28 +00006429 outs() << "xar member: " << member_name << " extracted\n";
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006430#endif
6431 // Set the XarMemberName we want to see printed in the header.
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +00006432 std::string OldXarMemberName;
6433 // If XarMemberName is already set this is nested. So
6434 // save the old name and create the nested name.
6435 if (!XarMemberName.empty()) {
6436 OldXarMemberName = XarMemberName;
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006437 XarMemberName =
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +00006438 (Twine("[") + XarMemberName + "]" + member_name).str();
6439 } else {
6440 OldXarMemberName = "";
6441 XarMemberName = member_name;
6442 }
6443 // See if this is could be a xar file (nested).
6444 if (member_size >= sizeof(struct xar_header)) {
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006445#if 0 // Useful for debugging.
NAKAMURA Takumi6f43bd42017-10-18 13:31:28 +00006446 outs() << "could be a xar file: " << member_name << "\n";
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006447#endif
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +00006448 memcpy((char *)&XarHeader, buffer, sizeof(struct xar_header));
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006449 if (sys::IsLittleEndianHost)
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +00006450 swapStruct(XarHeader);
6451 if (XarHeader.magic == XAR_HEADER_MAGIC)
6452 DumpBitcodeSection(O, buffer, member_size, verbose,
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006453 PrintXarHeader, PrintXarFileHeaders,
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +00006454 XarMemberName);
6455 }
6456 XarMemberName = OldXarMemberName;
Francis Ricci1bae0ac2017-09-13 13:57:45 +00006457 delete buffer;
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +00006458 }
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006459 }
6460 }
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006461 }
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006462}
6463#endif // defined(HAVE_LIBXAR)
6464
Kevin Enderby0fc11822015-04-01 20:57:01 +00006465static void printObjcMetaData(MachOObjectFile *O, bool verbose) {
6466 if (O->is64Bit())
6467 printObjc2_64bit_MetaData(O, verbose);
6468 else {
6469 MachO::mach_header H;
6470 H = O->getHeader();
6471 if (H.cputype == MachO::CPU_TYPE_ARM)
6472 printObjc2_32bit_MetaData(O, verbose);
6473 else {
6474 // This is the 32-bit non-arm cputype case. Which is normally
6475 // the first Objective-C ABI. But it may be the case of a
6476 // binary for the iOS simulator which is the second Objective-C
6477 // ABI. In that case printObjc1_32bit_MetaData() will determine that
6478 // and return false.
Hans Wennborgcc9deb42015-09-29 18:02:48 +00006479 if (!printObjc1_32bit_MetaData(O, verbose))
Kevin Enderby0fc11822015-04-01 20:57:01 +00006480 printObjc2_32bit_MetaData(O, verbose);
6481 }
6482 }
6483}
6484
Kevin Enderbybf246f52014-09-24 23:08:22 +00006485// GuessLiteralPointer returns a string which for the item in the Mach-O file
6486// for the address passed in as ReferenceValue for printing as a comment with
6487// the instruction and also returns the corresponding type of that item
6488// indirectly through ReferenceType.
6489//
6490// If ReferenceValue is an address of literal cstring then a pointer to the
6491// cstring is returned and ReferenceType is set to
6492// LLVMDisassembler_ReferenceType_Out_LitPool_CstrAddr .
6493//
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006494// If ReferenceValue is an address of an Objective-C CFString, Selector ref or
6495// Class ref that name is returned and the ReferenceType is set accordingly.
6496//
6497// Lastly, literals which are Symbol address in a literal pool are looked for
6498// and if found the symbol name is returned and ReferenceType is set to
6499// LLVMDisassembler_ReferenceType_Out_LitPool_SymAddr .
6500//
6501// If there is no item in the Mach-O file for the address passed in as
6502// ReferenceValue nullptr is returned and ReferenceType is unchanged.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00006503static const char *GuessLiteralPointer(uint64_t ReferenceValue,
6504 uint64_t ReferencePC,
6505 uint64_t *ReferenceType,
6506 struct DisassembleInfo *info) {
Kevin Enderbybf246f52014-09-24 23:08:22 +00006507 // First see if there is an external relocation entry at the ReferencePC.
Kevin Enderbyd90a4172015-10-10 00:05:01 +00006508 if (info->O->getHeader().filetype == MachO::MH_OBJECT) {
6509 uint64_t sect_addr = info->S.getAddress();
6510 uint64_t sect_offset = ReferencePC - sect_addr;
6511 bool reloc_found = false;
6512 DataRefImpl Rel;
6513 MachO::any_relocation_info RE;
6514 bool isExtern = false;
6515 SymbolRef Symbol;
6516 for (const RelocationRef &Reloc : info->S.relocations()) {
6517 uint64_t RelocOffset = Reloc.getOffset();
6518 if (RelocOffset == sect_offset) {
6519 Rel = Reloc.getRawDataRefImpl();
6520 RE = info->O->getRelocation(Rel);
6521 if (info->O->isRelocationScattered(RE))
6522 continue;
6523 isExtern = info->O->getPlainRelocationExternal(RE);
6524 if (isExtern) {
6525 symbol_iterator RelocSym = Reloc.getSymbol();
6526 Symbol = *RelocSym;
6527 }
6528 reloc_found = true;
6529 break;
Kevin Enderbybf246f52014-09-24 23:08:22 +00006530 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00006531 }
Kevin Enderbyd90a4172015-10-10 00:05:01 +00006532 // If there is an external relocation entry for a symbol in a section
6533 // then used that symbol's value for the value of the reference.
6534 if (reloc_found && isExtern) {
6535 if (info->O->getAnyRelocationPCRel(RE)) {
6536 unsigned Type = info->O->getAnyRelocationType(RE);
6537 if (Type == MachO::X86_64_RELOC_SIGNED) {
6538 ReferenceValue = Symbol.getValue();
6539 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00006540 }
6541 }
6542 }
6543
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006544 // Look for literals such as Objective-C CFStrings refs, Selector refs,
6545 // Message refs and Class refs.
6546 bool classref, selref, msgref, cfstring;
6547 uint64_t pointer_value = GuessPointerPointer(ReferenceValue, info, classref,
6548 selref, msgref, cfstring);
David Blaikie33dd45d02015-03-23 18:39:02 +00006549 if (classref && pointer_value == 0) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006550 // Note the ReferenceValue is a pointer into the __objc_classrefs section.
6551 // And the pointer_value in that section is typically zero as it will be
6552 // set by dyld as part of the "bind information".
6553 const char *name = get_dyld_bind_info_symbolname(ReferenceValue, info);
6554 if (name != nullptr) {
6555 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Class_Ref;
Hans Wennborgdb53e302014-10-23 21:59:17 +00006556 const char *class_name = strrchr(name, '$');
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006557 if (class_name != nullptr && class_name[1] == '_' &&
6558 class_name[2] != '\0') {
6559 info->class_name = class_name + 2;
6560 return name;
6561 }
6562 }
6563 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00006564
David Blaikie33dd45d02015-03-23 18:39:02 +00006565 if (classref) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006566 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Class_Ref;
6567 const char *name =
6568 get_objc2_64bit_class_name(pointer_value, ReferenceValue, info);
6569 if (name != nullptr)
6570 info->class_name = name;
6571 else
6572 name = "bad class ref";
Kevin Enderbybf246f52014-09-24 23:08:22 +00006573 return name;
6574 }
6575
David Blaikie33dd45d02015-03-23 18:39:02 +00006576 if (cfstring) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006577 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_CFString_Ref;
6578 const char *name = get_objc2_64bit_cfstring_name(ReferenceValue, info);
6579 return name;
6580 }
6581
David Blaikie33dd45d02015-03-23 18:39:02 +00006582 if (selref && pointer_value == 0)
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006583 pointer_value = get_objc2_64bit_selref(ReferenceValue, info);
6584
6585 if (pointer_value != 0)
6586 ReferenceValue = pointer_value;
6587
6588 const char *name = GuessCstringPointer(ReferenceValue, info);
6589 if (name) {
David Blaikie33dd45d02015-03-23 18:39:02 +00006590 if (pointer_value != 0 && selref) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006591 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Selector_Ref;
6592 info->selector_name = name;
David Blaikie33dd45d02015-03-23 18:39:02 +00006593 } else if (pointer_value != 0 && msgref) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006594 info->class_name = nullptr;
6595 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message_Ref;
6596 info->selector_name = name;
6597 } else
6598 *ReferenceType = LLVMDisassembler_ReferenceType_Out_LitPool_CstrAddr;
6599 return name;
6600 }
6601
6602 // Lastly look for an indirect symbol with this ReferenceValue which is in
6603 // a literal pool. If found return that symbol name.
6604 name = GuessIndirectSymbol(ReferenceValue, info);
6605 if (name) {
6606 *ReferenceType = LLVMDisassembler_ReferenceType_Out_LitPool_SymAddr;
6607 return name;
6608 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00006609
6610 return nullptr;
6611}
6612
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006613// SymbolizerSymbolLookUp is the symbol lookup function passed when creating
Kevin Enderbybf246f52014-09-24 23:08:22 +00006614// the Symbolizer. It looks up the ReferenceValue using the info passed via the
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006615// pointer to the struct DisassembleInfo that was passed when MCSymbolizer
6616// is created and returns the symbol name that matches the ReferenceValue or
6617// nullptr if none. The ReferenceType is passed in for the IN type of
6618// reference the instruction is making from the values in defined in the header
6619// "llvm-c/Disassembler.h". On return the ReferenceType can set to a specific
6620// Out type and the ReferenceName will also be set which is added as a comment
6621// to the disassembled instruction.
6622//
Kevin Enderby04bf6932014-10-28 23:39:46 +00006623// If the symbol name is a C++ mangled name then the demangled name is
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006624// returned through ReferenceName and ReferenceType is set to
6625// LLVMDisassembler_ReferenceType_DeMangled_Name .
6626//
6627// When this is called to get a symbol name for a branch target then the
6628// ReferenceType will be LLVMDisassembler_ReferenceType_In_Branch and then
6629// SymbolValue will be looked for in the indirect symbol table to determine if
6630// it is an address for a symbol stub. If so then the symbol name for that
6631// stub is returned indirectly through ReferenceName and then ReferenceType is
6632// set to LLVMDisassembler_ReferenceType_Out_SymbolStub.
6633//
Kevin Enderbybf246f52014-09-24 23:08:22 +00006634// When this is called with an value loaded via a PC relative load then
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006635// ReferenceType will be LLVMDisassembler_ReferenceType_In_PCrel_Load then the
6636// SymbolValue is checked to be an address of literal pointer, symbol pointer,
6637// or an Objective-C meta data reference. If so the output ReferenceType is
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006638// set to correspond to that as well as setting the ReferenceName.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00006639static const char *SymbolizerSymbolLookUp(void *DisInfo,
6640 uint64_t ReferenceValue,
6641 uint64_t *ReferenceType,
6642 uint64_t ReferencePC,
6643 const char **ReferenceName) {
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006644 struct DisassembleInfo *info = (struct DisassembleInfo *)DisInfo;
Kevin Enderbybf246f52014-09-24 23:08:22 +00006645 // If no verbose symbolic information is wanted then just return nullptr.
David Blaikie33dd45d02015-03-23 18:39:02 +00006646 if (!info->verbose) {
Kevin Enderbybf246f52014-09-24 23:08:22 +00006647 *ReferenceName = nullptr;
6648 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006649 return nullptr;
6650 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00006651
Kevin Enderbyf6d25852015-01-31 00:37:11 +00006652 const char *SymbolName = GuessSymbolName(ReferenceValue, info->AddrMap);
Kevin Enderbybf246f52014-09-24 23:08:22 +00006653
Kevin Enderby85974882014-09-26 22:20:44 +00006654 if (*ReferenceType == LLVMDisassembler_ReferenceType_In_Branch) {
6655 *ReferenceName = GuessIndirectSymbol(ReferenceValue, info);
Kevin Enderby04bf6932014-10-28 23:39:46 +00006656 if (*ReferenceName != nullptr) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006657 method_reference(info, ReferenceType, ReferenceName);
6658 if (*ReferenceType != LLVMDisassembler_ReferenceType_Out_Objc_Message)
6659 *ReferenceType = LLVMDisassembler_ReferenceType_Out_SymbolStub;
Rafael Espindolab940b662016-09-06 19:16:48 +00006660 } else if (SymbolName != nullptr && strncmp(SymbolName, "__Z", 3) == 0) {
Kevin Enderby04bf6932014-10-28 23:39:46 +00006661 if (info->demangled_name != nullptr)
6662 free(info->demangled_name);
6663 int status;
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006664 info->demangled_name =
Rafael Espindolab940b662016-09-06 19:16:48 +00006665 itaniumDemangle(SymbolName + 1, nullptr, nullptr, &status);
Kevin Enderby04bf6932014-10-28 23:39:46 +00006666 if (info->demangled_name != nullptr) {
6667 *ReferenceName = info->demangled_name;
6668 *ReferenceType = LLVMDisassembler_ReferenceType_DeMangled_Name;
6669 } else
6670 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
6671 } else
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006672 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
6673 } else if (*ReferenceType == LLVMDisassembler_ReferenceType_In_PCrel_Load) {
6674 *ReferenceName =
6675 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
Kevin Enderby85974882014-09-26 22:20:44 +00006676 if (*ReferenceName)
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006677 method_reference(info, ReferenceType, ReferenceName);
Kevin Enderby85974882014-09-26 22:20:44 +00006678 else
6679 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
Kevin Enderbyae3c1262014-11-14 21:52:18 +00006680 // If this is arm64 and the reference is an adrp instruction save the
6681 // instruction, passed in ReferenceValue and the address of the instruction
6682 // for use later if we see and add immediate instruction.
6683 } else if (info->O->getArch() == Triple::aarch64 &&
6684 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADRP) {
6685 info->adrp_inst = ReferenceValue;
6686 info->adrp_addr = ReferencePC;
6687 SymbolName = nullptr;
6688 *ReferenceName = nullptr;
6689 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
6690 // If this is arm64 and reference is an add immediate instruction and we
6691 // have
6692 // seen an adrp instruction just before it and the adrp's Xd register
6693 // matches
6694 // this add's Xn register reconstruct the value being referenced and look to
6695 // see if it is a literal pointer. Note the add immediate instruction is
6696 // passed in ReferenceValue.
6697 } else if (info->O->getArch() == Triple::aarch64 &&
6698 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADDXri &&
6699 ReferencePC - 4 == info->adrp_addr &&
6700 (info->adrp_inst & 0x9f000000) == 0x90000000 &&
6701 (info->adrp_inst & 0x1f) == ((ReferenceValue >> 5) & 0x1f)) {
6702 uint32_t addxri_inst;
6703 uint64_t adrp_imm, addxri_imm;
6704
6705 adrp_imm =
6706 ((info->adrp_inst & 0x00ffffe0) >> 3) | ((info->adrp_inst >> 29) & 0x3);
6707 if (info->adrp_inst & 0x0200000)
6708 adrp_imm |= 0xfffffffffc000000LL;
6709
6710 addxri_inst = ReferenceValue;
6711 addxri_imm = (addxri_inst >> 10) & 0xfff;
6712 if (((addxri_inst >> 22) & 0x3) == 1)
6713 addxri_imm <<= 12;
6714
6715 ReferenceValue = (info->adrp_addr & 0xfffffffffffff000LL) +
6716 (adrp_imm << 12) + addxri_imm;
6717
6718 *ReferenceName =
6719 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
6720 if (*ReferenceName == nullptr)
6721 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
6722 // If this is arm64 and the reference is a load register instruction and we
6723 // have seen an adrp instruction just before it and the adrp's Xd register
6724 // matches this add's Xn register reconstruct the value being referenced and
6725 // look to see if it is a literal pointer. Note the load register
6726 // instruction is passed in ReferenceValue.
6727 } else if (info->O->getArch() == Triple::aarch64 &&
6728 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_LDRXui &&
6729 ReferencePC - 4 == info->adrp_addr &&
6730 (info->adrp_inst & 0x9f000000) == 0x90000000 &&
6731 (info->adrp_inst & 0x1f) == ((ReferenceValue >> 5) & 0x1f)) {
6732 uint32_t ldrxui_inst;
6733 uint64_t adrp_imm, ldrxui_imm;
6734
6735 adrp_imm =
6736 ((info->adrp_inst & 0x00ffffe0) >> 3) | ((info->adrp_inst >> 29) & 0x3);
6737 if (info->adrp_inst & 0x0200000)
6738 adrp_imm |= 0xfffffffffc000000LL;
6739
6740 ldrxui_inst = ReferenceValue;
6741 ldrxui_imm = (ldrxui_inst >> 10) & 0xfff;
6742
6743 ReferenceValue = (info->adrp_addr & 0xfffffffffffff000LL) +
6744 (adrp_imm << 12) + (ldrxui_imm << 3);
6745
6746 *ReferenceName =
6747 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
6748 if (*ReferenceName == nullptr)
6749 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
6750 }
6751 // If this arm64 and is an load register (PC-relative) instruction the
6752 // ReferenceValue is the PC plus the immediate value.
6753 else if (info->O->getArch() == Triple::aarch64 &&
6754 (*ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_LDRXl ||
6755 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADR)) {
6756 *ReferenceName =
6757 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
6758 if (*ReferenceName == nullptr)
6759 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
Rafael Espindolab940b662016-09-06 19:16:48 +00006760 } else if (SymbolName != nullptr && strncmp(SymbolName, "__Z", 3) == 0) {
Kevin Enderby04bf6932014-10-28 23:39:46 +00006761 if (info->demangled_name != nullptr)
6762 free(info->demangled_name);
6763 int status;
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006764 info->demangled_name =
Rafael Espindolab940b662016-09-06 19:16:48 +00006765 itaniumDemangle(SymbolName + 1, nullptr, nullptr, &status);
Kevin Enderby04bf6932014-10-28 23:39:46 +00006766 if (info->demangled_name != nullptr) {
6767 *ReferenceName = info->demangled_name;
6768 *ReferenceType = LLVMDisassembler_ReferenceType_DeMangled_Name;
6769 }
6770 }
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006771 else {
Kevin Enderbybf246f52014-09-24 23:08:22 +00006772 *ReferenceName = nullptr;
6773 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
6774 }
6775
6776 return SymbolName;
6777}
6778
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00006779/// Emits the comments that are stored in the CommentStream.
Kevin Enderbybf246f52014-09-24 23:08:22 +00006780/// Each comment in the CommentStream must end with a newline.
6781static void emitComments(raw_svector_ostream &CommentStream,
6782 SmallString<128> &CommentsToEmit,
6783 formatted_raw_ostream &FormattedOS,
6784 const MCAsmInfo &MAI) {
6785 // Flush the stream before taking its content.
Kevin Enderbybf246f52014-09-24 23:08:22 +00006786 StringRef Comments = CommentsToEmit.str();
6787 // Get the default information for printing a comment.
Mehdi Amini36d33fc2016-10-01 06:46:33 +00006788 StringRef CommentBegin = MAI.getCommentString();
Kevin Enderbybf246f52014-09-24 23:08:22 +00006789 unsigned CommentColumn = MAI.getCommentColumn();
6790 bool IsFirst = true;
6791 while (!Comments.empty()) {
6792 if (!IsFirst)
6793 FormattedOS << '\n';
6794 // Emit a line of comments.
6795 FormattedOS.PadToColumn(CommentColumn);
6796 size_t Position = Comments.find('\n');
6797 FormattedOS << CommentBegin << ' ' << Comments.substr(0, Position);
6798 // Move after the newline character.
6799 Comments = Comments.substr(Position + 1);
6800 IsFirst = false;
6801 }
6802 FormattedOS.flush();
6803
6804 // Tell the comment stream that the vector changed underneath it.
6805 CommentsToEmit.clear();
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006806}
6807
Kevin Enderby95df54c2015-02-04 01:01:38 +00006808static void DisassembleMachO(StringRef Filename, MachOObjectFile *MachOOF,
6809 StringRef DisSegName, StringRef DisSectName) {
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006810 const char *McpuDefault = nullptr;
6811 const Target *ThumbTarget = nullptr;
6812 const Target *TheTarget = GetTarget(MachOOF, &McpuDefault, &ThumbTarget);
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006813 if (!TheTarget) {
6814 // GetTarget prints out stuff.
6815 return;
6816 }
Kevin Enderbyf310e622017-09-21 21:45:02 +00006817 std::string MachOMCPU;
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006818 if (MCPU.empty() && McpuDefault)
Kevin Enderbyf310e622017-09-21 21:45:02 +00006819 MachOMCPU = McpuDefault;
6820 else
6821 MachOMCPU = MCPU;
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006822
Ahmed Charles56440fd2014-03-06 05:51:42 +00006823 std::unique_ptr<const MCInstrInfo> InstrInfo(TheTarget->createMCInstrInfo());
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006824 std::unique_ptr<const MCInstrInfo> ThumbInstrInfo;
Kevin Enderbyae3c1262014-11-14 21:52:18 +00006825 if (ThumbTarget)
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006826 ThumbInstrInfo.reset(ThumbTarget->createMCInstrInfo());
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006827
Kevin Enderbyc9595622014-08-06 23:24:41 +00006828 // Package up features to be passed to target/subtarget
6829 std::string FeaturesStr;
6830 if (MAttrs.size()) {
6831 SubtargetFeatures Features;
6832 for (unsigned i = 0; i != MAttrs.size(); ++i)
6833 Features.AddFeature(MAttrs[i]);
6834 FeaturesStr = Features.getString();
6835 }
6836
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006837 // Set up disassembler.
Ahmed Charles56440fd2014-03-06 05:51:42 +00006838 std::unique_ptr<const MCRegisterInfo> MRI(
6839 TheTarget->createMCRegInfo(TripleName));
6840 std::unique_ptr<const MCAsmInfo> AsmInfo(
Rafael Espindola227144c2013-05-13 01:16:13 +00006841 TheTarget->createMCAsmInfo(*MRI, TripleName));
Ahmed Charles56440fd2014-03-06 05:51:42 +00006842 std::unique_ptr<const MCSubtargetInfo> STI(
Kevin Enderbyf310e622017-09-21 21:45:02 +00006843 TheTarget->createMCSubtargetInfo(TripleName, MachOMCPU, FeaturesStr));
Craig Toppere6cb63e2014-04-25 04:24:47 +00006844 MCContext Ctx(AsmInfo.get(), MRI.get(), nullptr);
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006845 std::unique_ptr<MCDisassembler> DisAsm(
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006846 TheTarget->createMCDisassembler(*STI, Ctx));
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006847 std::unique_ptr<MCSymbolizer> Symbolizer;
Serge Pavlove4e9a1f2018-02-14 03:26:27 +00006848 struct DisassembleInfo SymbolizerInfo(nullptr, nullptr, nullptr, false);
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006849 std::unique_ptr<MCRelocationInfo> RelInfo(
6850 TheTarget->createMCRelocationInfo(TripleName, Ctx));
6851 if (RelInfo) {
6852 Symbolizer.reset(TheTarget->createMCSymbolizer(
6853 TripleName, SymbolizerGetOpInfo, SymbolizerSymbolLookUp,
David Blaikie186db432015-01-18 20:45:48 +00006854 &SymbolizerInfo, &Ctx, std::move(RelInfo)));
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006855 DisAsm->setSymbolizer(std::move(Symbolizer));
6856 }
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006857 int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
Ahmed Charles56440fd2014-03-06 05:51:42 +00006858 std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
Daniel Sanders50f17232015-09-15 16:17:27 +00006859 Triple(TripleName), AsmPrinterVariant, *AsmInfo, *InstrInfo, *MRI));
Kevin Enderbybf246f52014-09-24 23:08:22 +00006860 // Set the display preference for hex vs. decimal immediates.
6861 IP->setPrintImmHex(PrintImmHex);
6862 // Comment stream and backing vector.
6863 SmallString<128> CommentsToEmit;
6864 raw_svector_ostream CommentStream(CommentsToEmit);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00006865 // FIXME: Setting the CommentStream in the InstPrinter is problematic in that
6866 // if it is done then arm64 comments for string literals don't get printed
6867 // and some constant get printed instead and not setting it causes intel
6868 // (32-bit and 64-bit) comments printed with different spacing before the
6869 // comment causing different diffs with the 'C' disassembler library API.
6870 // IP->setCommentStream(CommentStream);
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00006871
Kevin Enderbyae3c1262014-11-14 21:52:18 +00006872 if (!AsmInfo || !STI || !DisAsm || !IP) {
Jonas Devliegheree787efd2018-11-11 22:12:04 +00006873 WithColor::error(errs(), "llvm-objdump")
6874 << "couldn't initialize disassembler for target " << TripleName << '\n';
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006875 return;
6876 }
6877
Tim Northover09ca33e2016-04-22 23:23:31 +00006878 // Set up separate thumb disassembler if needed.
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006879 std::unique_ptr<const MCRegisterInfo> ThumbMRI;
6880 std::unique_ptr<const MCAsmInfo> ThumbAsmInfo;
6881 std::unique_ptr<const MCSubtargetInfo> ThumbSTI;
Kevin Enderby930fdc72014-11-06 19:00:13 +00006882 std::unique_ptr<MCDisassembler> ThumbDisAsm;
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006883 std::unique_ptr<MCInstPrinter> ThumbIP;
6884 std::unique_ptr<MCContext> ThumbCtx;
Kevin Enderby930fdc72014-11-06 19:00:13 +00006885 std::unique_ptr<MCSymbolizer> ThumbSymbolizer;
Serge Pavlove4e9a1f2018-02-14 03:26:27 +00006886 struct DisassembleInfo ThumbSymbolizerInfo(nullptr, nullptr, nullptr, false);
Kevin Enderby930fdc72014-11-06 19:00:13 +00006887 std::unique_ptr<MCRelocationInfo> ThumbRelInfo;
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006888 if (ThumbTarget) {
6889 ThumbMRI.reset(ThumbTarget->createMCRegInfo(ThumbTripleName));
6890 ThumbAsmInfo.reset(
6891 ThumbTarget->createMCAsmInfo(*ThumbMRI, ThumbTripleName));
6892 ThumbSTI.reset(
Kevin Enderbyf310e622017-09-21 21:45:02 +00006893 ThumbTarget->createMCSubtargetInfo(ThumbTripleName, MachOMCPU,
6894 FeaturesStr));
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006895 ThumbCtx.reset(new MCContext(ThumbAsmInfo.get(), ThumbMRI.get(), nullptr));
6896 ThumbDisAsm.reset(ThumbTarget->createMCDisassembler(*ThumbSTI, *ThumbCtx));
Kevin Enderby930fdc72014-11-06 19:00:13 +00006897 MCContext *PtrThumbCtx = ThumbCtx.get();
6898 ThumbRelInfo.reset(
6899 ThumbTarget->createMCRelocationInfo(ThumbTripleName, *PtrThumbCtx));
6900 if (ThumbRelInfo) {
6901 ThumbSymbolizer.reset(ThumbTarget->createMCSymbolizer(
6902 ThumbTripleName, SymbolizerGetOpInfo, SymbolizerSymbolLookUp,
David Blaikie186db432015-01-18 20:45:48 +00006903 &ThumbSymbolizerInfo, PtrThumbCtx, std::move(ThumbRelInfo)));
Kevin Enderby930fdc72014-11-06 19:00:13 +00006904 ThumbDisAsm->setSymbolizer(std::move(ThumbSymbolizer));
6905 }
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006906 int ThumbAsmPrinterVariant = ThumbAsmInfo->getAssemblerDialect();
6907 ThumbIP.reset(ThumbTarget->createMCInstPrinter(
Daniel Sanders50f17232015-09-15 16:17:27 +00006908 Triple(ThumbTripleName), ThumbAsmPrinterVariant, *ThumbAsmInfo,
6909 *ThumbInstrInfo, *ThumbMRI));
Kevin Enderbybf246f52014-09-24 23:08:22 +00006910 // Set the display preference for hex vs. decimal immediates.
6911 ThumbIP->setPrintImmHex(PrintImmHex);
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006912 }
6913
Kevin Enderbyae3c1262014-11-14 21:52:18 +00006914 if (ThumbTarget && (!ThumbAsmInfo || !ThumbSTI || !ThumbDisAsm || !ThumbIP)) {
Jonas Devliegheree787efd2018-11-11 22:12:04 +00006915 WithColor::error(errs(), "llvm-objdump")
6916 << "couldn't initialize disassembler for target " << ThumbTripleName
6917 << '\n';
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006918 return;
6919 }
6920
Charles Davis8bdfafd2013-09-01 04:28:48 +00006921 MachO::mach_header Header = MachOOF->getHeader();
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006922
Ahmed Bougachaaa790682013-05-24 01:07:04 +00006923 // FIXME: Using the -cfg command line option, this code used to be able to
6924 // annotate relocations with the referenced symbol's name, and if this was
6925 // inside a __[cf]string section, the data it points to. This is now replaced
6926 // by the upcoming MCSymbolizer, which needs the appropriate setup done above.
Owen Andersond9243c42011-10-17 21:37:35 +00006927 std::vector<SectionRef> Sections;
6928 std::vector<SymbolRef> Symbols;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006929 SmallVector<uint64_t, 8> FoundFns;
Kevin Enderby273ae012013-06-06 17:20:50 +00006930 uint64_t BaseSegmentAddress;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006931
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00006932 getSectionsAndSymbols(MachOOF, Sections, Symbols, FoundFns,
Kevin Enderby273ae012013-06-06 17:20:50 +00006933 BaseSegmentAddress);
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006934
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006935 // Sort the symbols by address, just in case they didn't come in that way.
Fangrui Song0cac7262018-09-27 02:13:45 +00006936 llvm::sort(Symbols, SymbolSorter());
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006937
Kevin Enderby273ae012013-06-06 17:20:50 +00006938 // Build a data in code table that is sorted on by the address of each entry.
6939 uint64_t BaseAddress = 0;
Charles Davis8bdfafd2013-09-01 04:28:48 +00006940 if (Header.filetype == MachO::MH_OBJECT)
Rafael Espindola80291272014-10-08 15:28:58 +00006941 BaseAddress = Sections[0].getAddress();
Kevin Enderby273ae012013-06-06 17:20:50 +00006942 else
6943 BaseAddress = BaseSegmentAddress;
6944 DiceTable Dices;
Kevin Enderby273ae012013-06-06 17:20:50 +00006945 for (dice_iterator DI = MachOOF->begin_dices(), DE = MachOOF->end_dices();
Rafael Espindola5e812af2014-01-30 02:49:50 +00006946 DI != DE; ++DI) {
Kevin Enderby273ae012013-06-06 17:20:50 +00006947 uint32_t Offset;
6948 DI->getOffset(Offset);
6949 Dices.push_back(std::make_pair(BaseAddress + Offset, *DI));
6950 }
6951 array_pod_sort(Dices.begin(), Dices.end());
6952
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006953#ifndef NDEBUG
6954 raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls();
6955#else
6956 raw_ostream &DebugOut = nulls();
6957#endif
6958
Ahmed Charles56440fd2014-03-06 05:51:42 +00006959 std::unique_ptr<DIContext> diContext;
Rafael Espindola9b709252013-04-13 01:45:40 +00006960 ObjectFile *DbgObj = MachOOF;
Francis Visoiu Mistrih8e864be2018-08-31 13:10:54 +00006961 std::unique_ptr<MemoryBuffer> DSYMBuf;
Benjamin Kramer699128e2011-09-21 01:13:19 +00006962 // Try to find debug info and set up the DIContext for it.
6963 if (UseDbg) {
Benjamin Kramer699128e2011-09-21 01:13:19 +00006964 // A separate DSym file path was specified, parse it as a macho file,
6965 // get the sections and supply it to the section name parsing machinery.
6966 if (!DSYMFile.empty()) {
Rafael Espindola48af1c22014-08-19 18:44:46 +00006967 ErrorOr<std::unique_ptr<MemoryBuffer>> BufOrErr =
Rafael Espindolaadf21f22014-07-06 17:43:13 +00006968 MemoryBuffer::getFileOrSTDIN(DSYMFile);
Rafael Espindola48af1c22014-08-19 18:44:46 +00006969 if (std::error_code EC = BufOrErr.getError()) {
Jonas Devliegheree787efd2018-11-11 22:12:04 +00006970 WithColor::error(errs(), "llvm-objdump")
6971 << Filename << ": " << EC.message() << '\n';
Benjamin Kramer699128e2011-09-21 01:13:19 +00006972 return;
6973 }
Gerolf Hoflehnerbf26d542018-04-19 20:48:35 +00006974 Expected<std::unique_ptr<MachOObjectFile>> DbgObjCheck =
6975 ObjectFile::createMachOObjectFile(BufOrErr.get()->getMemBufferRef());
6976
6977 if (DbgObjCheck.takeError())
6978 report_error(MachOOF->getFileName(), DbgObjCheck.takeError());
6979 DbgObj = DbgObjCheck.get().release();
Francis Visoiu Mistrih8e864be2018-08-31 13:10:54 +00006980 // We need to keep the file alive, because we're replacing DbgObj with it.
6981 DSYMBuf = std::move(BufOrErr.get());
Benjamin Kramer699128e2011-09-21 01:13:19 +00006982 }
6983
Eric Christopher7370b552012-11-12 21:40:38 +00006984 // Setup the DIContext
Rafael Espindolac398e672017-07-19 22:27:28 +00006985 diContext = DWARFContext::create(*DbgObj);
Benjamin Kramer699128e2011-09-21 01:13:19 +00006986 }
6987
Colin LeMahieufcc32762015-07-29 19:08:10 +00006988 if (FilterSections.size() == 0)
Kevin Enderby95df54c2015-02-04 01:01:38 +00006989 outs() << "(" << DisSegName << "," << DisSectName << ") section\n";
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00006990
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006991 for (unsigned SectIdx = 0; SectIdx != Sections.size(); SectIdx++) {
Owen Andersond9243c42011-10-17 21:37:35 +00006992 StringRef SectName;
Kevin Enderby95df54c2015-02-04 01:01:38 +00006993 if (Sections[SectIdx].getName(SectName) || SectName != DisSectName)
6994 continue;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006995
Rafael Espindolaa9f810b2012-12-21 03:47:03 +00006996 DataRefImpl DR = Sections[SectIdx].getRawDataRefImpl();
Ahmed Bougachaaa790682013-05-24 01:07:04 +00006997
Rafael Espindolab0f76a42013-04-05 15:15:22 +00006998 StringRef SegmentName = MachOOF->getSectionFinalSegmentName(DR);
Kevin Enderby95df54c2015-02-04 01:01:38 +00006999 if (SegmentName != DisSegName)
Rafael Espindolaa9f810b2012-12-21 03:47:03 +00007000 continue;
7001
Rafael Espindola7fc5b872014-11-12 02:04:27 +00007002 StringRef BytesStr;
7003 Sections[SectIdx].getContents(BytesStr);
Aaron Ballman106fd7b2014-11-12 14:01:17 +00007004 ArrayRef<uint8_t> Bytes(reinterpret_cast<const uint8_t *>(BytesStr.data()),
7005 BytesStr.size());
Rafael Espindola80291272014-10-08 15:28:58 +00007006 uint64_t SectAddress = Sections[SectIdx].getAddress();
Rafael Espindolabd604f22014-11-07 00:52:15 +00007007
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007008 bool symbolTableWorked = false;
7009
Kevin Enderbybf246f52014-09-24 23:08:22 +00007010 // Create a map of symbol addresses to symbol names for use by
7011 // the SymbolizerSymbolLookUp() routine.
7012 SymbolAddressMap AddrMap;
Kevin Enderby6a221752015-03-17 17:10:57 +00007013 bool DisSymNameFound = false;
Kevin Enderbybf246f52014-09-24 23:08:22 +00007014 for (const SymbolRef &Symbol : MachOOF->symbols()) {
Kevin Enderby7bd8d992016-05-02 20:28:12 +00007015 Expected<SymbolRef::Type> STOrErr = Symbol.getType();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00007016 if (!STOrErr)
7017 report_error(MachOOF->getFileName(), STOrErr.takeError());
Kevin Enderby5afbc1c2016-03-23 20:27:00 +00007018 SymbolRef::Type ST = *STOrErr;
Kevin Enderbybf246f52014-09-24 23:08:22 +00007019 if (ST == SymbolRef::ST_Function || ST == SymbolRef::ST_Data ||
7020 ST == SymbolRef::ST_Other) {
Rafael Espindoladea00162015-07-03 17:44:18 +00007021 uint64_t Address = Symbol.getValue();
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00007022 Expected<StringRef> SymNameOrErr = Symbol.getName();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00007023 if (!SymNameOrErr)
7024 report_error(MachOOF->getFileName(), SymNameOrErr.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00007025 StringRef SymName = *SymNameOrErr;
Kevin Enderbybf246f52014-09-24 23:08:22 +00007026 AddrMap[Address] = SymName;
Kevin Enderby6a221752015-03-17 17:10:57 +00007027 if (!DisSymName.empty() && DisSymName == SymName)
7028 DisSymNameFound = true;
Kevin Enderbybf246f52014-09-24 23:08:22 +00007029 }
7030 }
David Blaikie33dd45d02015-03-23 18:39:02 +00007031 if (!DisSymName.empty() && !DisSymNameFound) {
Kevin Enderby6a221752015-03-17 17:10:57 +00007032 outs() << "Can't find -dis-symname: " << DisSymName << "\n";
7033 return;
7034 }
Kevin Enderby98c9acc2014-09-16 18:00:57 +00007035 // Set up the block of info used by the Symbolizer call backs.
Kevin Enderby8e29ec92015-03-17 22:26:11 +00007036 SymbolizerInfo.verbose = !NoSymbolicOperands;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00007037 SymbolizerInfo.O = MachOOF;
7038 SymbolizerInfo.S = Sections[SectIdx];
Kevin Enderbybf246f52014-09-24 23:08:22 +00007039 SymbolizerInfo.AddrMap = &AddrMap;
Kevin Enderby6f326ce2014-10-23 19:37:31 +00007040 SymbolizerInfo.Sections = &Sections;
Kevin Enderby930fdc72014-11-06 19:00:13 +00007041 // Same for the ThumbSymbolizer
Kevin Enderby8e29ec92015-03-17 22:26:11 +00007042 ThumbSymbolizerInfo.verbose = !NoSymbolicOperands;
Kevin Enderby930fdc72014-11-06 19:00:13 +00007043 ThumbSymbolizerInfo.O = MachOOF;
7044 ThumbSymbolizerInfo.S = Sections[SectIdx];
7045 ThumbSymbolizerInfo.AddrMap = &AddrMap;
7046 ThumbSymbolizerInfo.Sections = &Sections;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00007047
Kevin Enderby4b627be2016-04-28 20:14:13 +00007048 unsigned int Arch = MachOOF->getArch();
7049
Tim Northoverf203ab52016-07-14 22:13:32 +00007050 // Skip all symbols if this is a stubs file.
7051 if (Bytes.size() == 0)
7052 return;
7053
Kevin Enderbyc138da32017-02-06 18:43:18 +00007054 // If the section has symbols but no symbol at the start of the section
7055 // these are used to make sure the bytes before the first symbol are
7056 // disassembled.
7057 bool FirstSymbol = true;
7058 bool FirstSymbolAtSectionStart = true;
7059
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00007060 // Disassemble symbol by symbol.
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007061 for (unsigned SymIdx = 0; SymIdx != Symbols.size(); SymIdx++) {
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00007062 Expected<StringRef> SymNameOrErr = Symbols[SymIdx].getName();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00007063 if (!SymNameOrErr)
7064 report_error(MachOOF->getFileName(), SymNameOrErr.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00007065 StringRef SymName = *SymNameOrErr;
Owen Andersond9243c42011-10-17 21:37:35 +00007066
Kevin Enderby7bd8d992016-05-02 20:28:12 +00007067 Expected<SymbolRef::Type> STOrErr = Symbols[SymIdx].getType();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00007068 if (!STOrErr)
7069 report_error(MachOOF->getFileName(), STOrErr.takeError());
Kevin Enderby5afbc1c2016-03-23 20:27:00 +00007070 SymbolRef::Type ST = *STOrErr;
Kuba Breckade833222015-11-12 09:40:29 +00007071 if (ST != SymbolRef::ST_Function && ST != SymbolRef::ST_Data)
Owen Andersond9243c42011-10-17 21:37:35 +00007072 continue;
7073
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00007074 // Make sure the symbol is defined in this section.
Rafael Espindola80291272014-10-08 15:28:58 +00007075 bool containsSym = Sections[SectIdx].containsSymbol(Symbols[SymIdx]);
Kevin Enderbyd8a6e832016-06-15 21:14:01 +00007076 if (!containsSym) {
7077 if (!DisSymName.empty() && DisSymName == SymName) {
7078 outs() << "-dis-symname: " << DisSymName << " not in the section\n";
7079 return;
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +00007080 }
Kevin Enderbyd8a6e832016-06-15 21:14:01 +00007081 continue;
7082 }
7083 // The __mh_execute_header is special and we need to deal with that fact
7084 // this symbol is before the start of the (__TEXT,__text) section and at the
7085 // address of the start of the __TEXT segment. This is because this symbol
7086 // is an N_SECT symbol in the (__TEXT,__text) but its address is before the
7087 // start of the section in a standard MH_EXECUTE filetype.
7088 if (!DisSymName.empty() && DisSymName == "__mh_execute_header") {
7089 outs() << "-dis-symname: __mh_execute_header not in any section\n";
7090 return;
7091 }
Tim Northoverfbefee32016-07-14 23:13:03 +00007092 // When this code is trying to disassemble a symbol at a time and in the
7093 // case there is only the __mh_execute_header symbol left as in a stripped
7094 // executable, we need to deal with this by ignoring this symbol so the
7095 // whole section is disassembled and this symbol is then not displayed.
7096 if (SymName == "__mh_execute_header" || SymName == "__mh_dylib_header" ||
7097 SymName == "__mh_bundle_header" || SymName == "__mh_object_header" ||
7098 SymName == "__mh_preload_header" || SymName == "__mh_dylinker_header")
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007099 continue;
7100
Kevin Enderby6a221752015-03-17 17:10:57 +00007101 // If we are only disassembling one symbol see if this is that symbol.
7102 if (!DisSymName.empty() && DisSymName != SymName)
7103 continue;
7104
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00007105 // Start at the address of the symbol relative to the section's address.
Tim Northoverf203ab52016-07-14 22:13:32 +00007106 uint64_t SectSize = Sections[SectIdx].getSize();
Rafael Espindoladea00162015-07-03 17:44:18 +00007107 uint64_t Start = Symbols[SymIdx].getValue();
Rafael Espindola80291272014-10-08 15:28:58 +00007108 uint64_t SectionAddress = Sections[SectIdx].getAddress();
Cameron Zwarich54478a52012-02-03 05:42:17 +00007109 Start -= SectionAddress;
Owen Andersond9243c42011-10-17 21:37:35 +00007110
Tim Northoverf203ab52016-07-14 22:13:32 +00007111 if (Start > SectSize) {
7112 outs() << "section data ends, " << SymName
7113 << " lies outside valid range\n";
7114 return;
7115 }
7116
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00007117 // Stop disassembling either at the beginning of the next symbol or at
7118 // the end of the section.
Kevin Enderbyedd58722012-05-15 18:57:14 +00007119 bool containsNextSym = false;
Owen Andersond9243c42011-10-17 21:37:35 +00007120 uint64_t NextSym = 0;
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007121 uint64_t NextSymIdx = SymIdx + 1;
Owen Andersond9243c42011-10-17 21:37:35 +00007122 while (Symbols.size() > NextSymIdx) {
Kevin Enderby7bd8d992016-05-02 20:28:12 +00007123 Expected<SymbolRef::Type> STOrErr = Symbols[NextSymIdx].getType();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00007124 if (!STOrErr)
7125 report_error(MachOOF->getFileName(), STOrErr.takeError());
Kevin Enderby5afbc1c2016-03-23 20:27:00 +00007126 SymbolRef::Type NextSymType = *STOrErr;
Owen Andersond9243c42011-10-17 21:37:35 +00007127 if (NextSymType == SymbolRef::ST_Function) {
Rafael Espindola80291272014-10-08 15:28:58 +00007128 containsNextSym =
7129 Sections[SectIdx].containsSymbol(Symbols[NextSymIdx]);
Rafael Espindoladea00162015-07-03 17:44:18 +00007130 NextSym = Symbols[NextSymIdx].getValue();
Cameron Zwarich54478a52012-02-03 05:42:17 +00007131 NextSym -= SectionAddress;
Owen Andersond9243c42011-10-17 21:37:35 +00007132 break;
7133 }
7134 ++NextSymIdx;
7135 }
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007136
Tim Northoverf203ab52016-07-14 22:13:32 +00007137 uint64_t End = containsNextSym ? std::min(NextSym, SectSize) : SectSize;
Owen Andersond9243c42011-10-17 21:37:35 +00007138 uint64_t Size;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007139
7140 symbolTableWorked = true;
Rafael Espindolabd604f22014-11-07 00:52:15 +00007141
Kevin Enderbyec5ca032014-08-18 20:21:02 +00007142 DataRefImpl Symb = Symbols[SymIdx].getRawDataRefImpl();
Tim Northover09ca33e2016-04-22 23:23:31 +00007143 bool IsThumb = MachOOF->getSymbolFlags(Symb) & SymbolRef::SF_Thumb;
7144
7145 // We only need the dedicated Thumb target if there's a real choice
7146 // (i.e. we're not targeting M-class) and the function is Thumb.
7147 bool UseThumbTarget = IsThumb && ThumbTarget;
Kevin Enderbyec5ca032014-08-18 20:21:02 +00007148
Kevin Enderbyc138da32017-02-06 18:43:18 +00007149 // If we are not specifying a symbol to start disassembly with and this
7150 // is the first symbol in the section but not at the start of the section
7151 // then move the disassembly index to the start of the section and
7152 // don't print the symbol name just yet. This is so the bytes before the
7153 // first symbol are disassembled.
7154 uint64_t SymbolStart = Start;
7155 if (DisSymName.empty() && FirstSymbol && Start != 0) {
7156 FirstSymbolAtSectionStart = false;
7157 Start = 0;
7158 }
7159 else
7160 outs() << SymName << ":\n";
7161
Ahmed Bougachaaa790682013-05-24 01:07:04 +00007162 DILineInfo lastLine;
7163 for (uint64_t Index = Start; Index < End; Index += Size) {
7164 MCInst Inst;
Owen Andersond9243c42011-10-17 21:37:35 +00007165
Kevin Enderbyc138da32017-02-06 18:43:18 +00007166 // If this is the first symbol in the section and it was not at the
7167 // start of the section, see if we are at its Index now and if so print
7168 // the symbol name.
7169 if (FirstSymbol && !FirstSymbolAtSectionStart && Index == SymbolStart)
7170 outs() << SymName << ":\n";
7171
Kevin Enderbybf246f52014-09-24 23:08:22 +00007172 uint64_t PC = SectAddress + Index;
Kevin Enderbyab5e6c92015-03-17 21:07:39 +00007173 if (!NoLeadingAddr) {
7174 if (FullLeadingAddr) {
7175 if (MachOOF->is64Bit())
7176 outs() << format("%016" PRIx64, PC);
7177 else
7178 outs() << format("%08" PRIx64, PC);
7179 } else {
7180 outs() << format("%8" PRIx64 ":", PC);
7181 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00007182 }
Kevin Enderby4b627be2016-04-28 20:14:13 +00007183 if (!NoShowRawInsn || Arch == Triple::arm)
Kevin Enderbybf246f52014-09-24 23:08:22 +00007184 outs() << "\t";
Kevin Enderby273ae012013-06-06 17:20:50 +00007185
7186 // Check the data in code table here to see if this is data not an
7187 // instruction to be disassembled.
7188 DiceTable Dice;
Kevin Enderbybf246f52014-09-24 23:08:22 +00007189 Dice.push_back(std::make_pair(PC, DiceRef()));
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007190 dice_table_iterator DTI =
7191 std::search(Dices.begin(), Dices.end(), Dice.begin(), Dice.end(),
7192 compareDiceTableEntries);
7193 if (DTI != Dices.end()) {
Kevin Enderby273ae012013-06-06 17:20:50 +00007194 uint16_t Length;
7195 DTI->second.getLength(Length);
Kevin Enderby273ae012013-06-06 17:20:50 +00007196 uint16_t Kind;
7197 DTI->second.getKind(Kind);
Colin LeMahieufc32b1b2015-03-18 19:27:31 +00007198 Size = DumpDataInCode(Bytes.data() + Index, Length, Kind);
Kevin Enderby930fdc72014-11-06 19:00:13 +00007199 if ((Kind == MachO::DICE_KIND_JUMP_TABLE8) &&
7200 (PC == (DTI->first + Length - 1)) && (Length & 1))
7201 Size++;
Kevin Enderby273ae012013-06-06 17:20:50 +00007202 continue;
7203 }
7204
Kevin Enderbybf246f52014-09-24 23:08:22 +00007205 SmallVector<char, 64> AnnotationsBytes;
7206 raw_svector_ostream Annotations(AnnotationsBytes);
7207
Kevin Enderbyec5ca032014-08-18 20:21:02 +00007208 bool gotInst;
Tim Northover09ca33e2016-04-22 23:23:31 +00007209 if (UseThumbTarget)
Rafael Espindola7fc5b872014-11-12 02:04:27 +00007210 gotInst = ThumbDisAsm->getInstruction(Inst, Size, Bytes.slice(Index),
Kevin Enderby6f326ce2014-10-23 19:37:31 +00007211 PC, DebugOut, Annotations);
Kevin Enderbyec5ca032014-08-18 20:21:02 +00007212 else
Rafael Espindola7fc5b872014-11-12 02:04:27 +00007213 gotInst = DisAsm->getInstruction(Inst, Size, Bytes.slice(Index), PC,
Kevin Enderbybf246f52014-09-24 23:08:22 +00007214 DebugOut, Annotations);
Kevin Enderbyec5ca032014-08-18 20:21:02 +00007215 if (gotInst) {
Kevin Enderby4b627be2016-04-28 20:14:13 +00007216 if (!NoShowRawInsn || Arch == Triple::arm) {
Craig Topper0013be12015-09-21 05:32:41 +00007217 dumpBytes(makeArrayRef(Bytes.data() + Index, Size), outs());
Kevin Enderbybf246f52014-09-24 23:08:22 +00007218 }
7219 formatted_raw_ostream FormattedOS(outs());
Kevin Enderbybf246f52014-09-24 23:08:22 +00007220 StringRef AnnotationsStr = Annotations.str();
Tim Northover09ca33e2016-04-22 23:23:31 +00007221 if (UseThumbTarget)
Akira Hatanakab46d0232015-03-27 20:36:02 +00007222 ThumbIP->printInst(&Inst, FormattedOS, AnnotationsStr, *ThumbSTI);
Kevin Enderbyec5ca032014-08-18 20:21:02 +00007223 else
Akira Hatanaka1d079942015-03-28 20:44:05 +00007224 IP->printInst(&Inst, FormattedOS, AnnotationsStr, *STI);
Kevin Enderbybf246f52014-09-24 23:08:22 +00007225 emitComments(CommentStream, CommentsToEmit, FormattedOS, *AsmInfo);
Owen Andersond9243c42011-10-17 21:37:35 +00007226
Ahmed Bougachaaa790682013-05-24 01:07:04 +00007227 // Print debug info.
7228 if (diContext) {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007229 DILineInfo dli = diContext->getLineInfoForAddress(PC);
Ahmed Bougachaaa790682013-05-24 01:07:04 +00007230 // Print valid line info if it changed.
Alexey Samsonovd0109992014-04-18 21:36:39 +00007231 if (dli != lastLine && dli.Line != 0)
7232 outs() << "\t## " << dli.FileName << ':' << dli.Line << ':'
7233 << dli.Column;
Ahmed Bougachaaa790682013-05-24 01:07:04 +00007234 lastLine = dli;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007235 }
Ahmed Bougachaaa790682013-05-24 01:07:04 +00007236 outs() << "\n";
7237 } else {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00007238 unsigned int Arch = MachOOF->getArch();
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007239 if (Arch == Triple::x86_64 || Arch == Triple::x86) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00007240 outs() << format("\t.byte 0x%02x #bad opcode\n",
7241 *(Bytes.data() + Index) & 0xff);
7242 Size = 1; // skip exactly one illegible byte and move on.
Tim Northover09ca33e2016-04-22 23:23:31 +00007243 } else if (Arch == Triple::aarch64 ||
7244 (Arch == Triple::arm && !IsThumb)) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00007245 uint32_t opcode = (*(Bytes.data() + Index) & 0xff) |
7246 (*(Bytes.data() + Index + 1) & 0xff) << 8 |
7247 (*(Bytes.data() + Index + 2) & 0xff) << 16 |
7248 (*(Bytes.data() + Index + 3) & 0xff) << 24;
7249 outs() << format("\t.long\t0x%08x\n", opcode);
7250 Size = 4;
Tim Northover09ca33e2016-04-22 23:23:31 +00007251 } else if (Arch == Triple::arm) {
7252 assert(IsThumb && "ARM mode should have been dealt with above");
7253 uint32_t opcode = (*(Bytes.data() + Index) & 0xff) |
7254 (*(Bytes.data() + Index + 1) & 0xff) << 8;
7255 outs() << format("\t.short\t0x%04x\n", opcode);
7256 Size = 2;
7257 } else{
Jonas Devliegheree787efd2018-11-11 22:12:04 +00007258 WithColor::warning(errs(), "llvm-objdump")
7259 << "invalid instruction encoding\n";
Kevin Enderby6f326ce2014-10-23 19:37:31 +00007260 if (Size == 0)
7261 Size = 1; // skip illegible bytes
7262 }
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007263 }
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007264 }
Kevin Enderbyc138da32017-02-06 18:43:18 +00007265 // Now that we are done disassembled the first symbol set the bool that
7266 // were doing this to false.
7267 FirstSymbol = false;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007268 }
Ahmed Bougachaaa790682013-05-24 01:07:04 +00007269 if (!symbolTableWorked) {
Rafael Espindola80291272014-10-08 15:28:58 +00007270 // Reading the symbol table didn't work, disassemble the whole section.
7271 uint64_t SectAddress = Sections[SectIdx].getAddress();
7272 uint64_t SectSize = Sections[SectIdx].getSize();
Kevin Enderbybadd1002012-05-18 00:13:56 +00007273 uint64_t InstSize;
7274 for (uint64_t Index = 0; Index < SectSize; Index += InstSize) {
Bill Wendling4e68e062012-07-19 00:17:40 +00007275 MCInst Inst;
Kevin Enderbybadd1002012-05-18 00:13:56 +00007276
Kevin Enderbybf246f52014-09-24 23:08:22 +00007277 uint64_t PC = SectAddress + Index;
Kevin Enderby02d3a372017-01-31 18:09:10 +00007278 SmallVector<char, 64> AnnotationsBytes;
7279 raw_svector_ostream Annotations(AnnotationsBytes);
Rafael Espindola7fc5b872014-11-12 02:04:27 +00007280 if (DisAsm->getInstruction(Inst, InstSize, Bytes.slice(Index), PC,
Kevin Enderby02d3a372017-01-31 18:09:10 +00007281 DebugOut, Annotations)) {
Kevin Enderbyab5e6c92015-03-17 21:07:39 +00007282 if (!NoLeadingAddr) {
7283 if (FullLeadingAddr) {
7284 if (MachOOF->is64Bit())
7285 outs() << format("%016" PRIx64, PC);
7286 else
7287 outs() << format("%08" PRIx64, PC);
7288 } else {
7289 outs() << format("%8" PRIx64 ":", PC);
7290 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00007291 }
Kevin Enderby4b627be2016-04-28 20:14:13 +00007292 if (!NoShowRawInsn || Arch == Triple::arm) {
Kevin Enderbybf246f52014-09-24 23:08:22 +00007293 outs() << "\t";
Craig Topper0013be12015-09-21 05:32:41 +00007294 dumpBytes(makeArrayRef(Bytes.data() + Index, InstSize), outs());
Kevin Enderbybf246f52014-09-24 23:08:22 +00007295 }
Kevin Enderby02d3a372017-01-31 18:09:10 +00007296 StringRef AnnotationsStr = Annotations.str();
7297 IP->printInst(&Inst, outs(), AnnotationsStr, *STI);
Bill Wendling4e68e062012-07-19 00:17:40 +00007298 outs() << "\n";
7299 } else {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00007300 unsigned int Arch = MachOOF->getArch();
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007301 if (Arch == Triple::x86_64 || Arch == Triple::x86) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00007302 outs() << format("\t.byte 0x%02x #bad opcode\n",
7303 *(Bytes.data() + Index) & 0xff);
7304 InstSize = 1; // skip exactly one illegible byte and move on.
7305 } else {
Jonas Devliegheree787efd2018-11-11 22:12:04 +00007306 WithColor::warning(errs(), "llvm-objdump")
7307 << "invalid instruction encoding\n";
Kevin Enderby6f326ce2014-10-23 19:37:31 +00007308 if (InstSize == 0)
7309 InstSize = 1; // skip illegible bytes
7310 }
Bill Wendling4e68e062012-07-19 00:17:40 +00007311 }
Kevin Enderbybadd1002012-05-18 00:13:56 +00007312 }
7313 }
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00007314 // The TripleName's need to be reset if we are called again for a different
7315 // archtecture.
7316 TripleName = "";
7317 ThumbTripleName = "";
7318
Kevin Enderby04bf6932014-10-28 23:39:46 +00007319 if (SymbolizerInfo.demangled_name != nullptr)
7320 free(SymbolizerInfo.demangled_name);
Kevin Enderby930fdc72014-11-06 19:00:13 +00007321 if (ThumbSymbolizerInfo.demangled_name != nullptr)
7322 free(ThumbSymbolizerInfo.demangled_name);
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007323 }
7324}
Tim Northover4bd286a2014-08-01 13:07:19 +00007325
Tim Northover39c70bb2014-08-12 11:52:59 +00007326//===----------------------------------------------------------------------===//
7327// __compact_unwind section dumping
7328//===----------------------------------------------------------------------===//
7329
Tim Northover4bd286a2014-08-01 13:07:19 +00007330namespace {
Tim Northover39c70bb2014-08-12 11:52:59 +00007331
Tim Northover3a4e1c72018-01-23 13:51:57 +00007332template <typename T>
7333static uint64_t read(StringRef Contents, ptrdiff_t Offset) {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007334 using llvm::support::little;
7335 using llvm::support::unaligned;
Tim Northover39c70bb2014-08-12 11:52:59 +00007336
Tim Northover3a4e1c72018-01-23 13:51:57 +00007337 if (Offset + sizeof(T) > Contents.size()) {
7338 outs() << "warning: attempt to read past end of buffer\n";
7339 return T();
7340 }
7341
7342 uint64_t Val =
7343 support::endian::read<T, little, unaligned>(Contents.data() + Offset);
7344 return Val;
7345}
7346
7347template <typename T>
7348static uint64_t readNext(StringRef Contents, ptrdiff_t &Offset) {
7349 T Val = read<T>(Contents, Offset);
7350 Offset += sizeof(T);
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007351 return Val;
7352}
Tim Northover39c70bb2014-08-12 11:52:59 +00007353
Tim Northover4bd286a2014-08-01 13:07:19 +00007354struct CompactUnwindEntry {
7355 uint32_t OffsetInSection;
7356
7357 uint64_t FunctionAddr;
7358 uint32_t Length;
7359 uint32_t CompactEncoding;
7360 uint64_t PersonalityAddr;
7361 uint64_t LSDAAddr;
7362
7363 RelocationRef FunctionReloc;
7364 RelocationRef PersonalityReloc;
7365 RelocationRef LSDAReloc;
7366
7367 CompactUnwindEntry(StringRef Contents, unsigned Offset, bool Is64)
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007368 : OffsetInSection(Offset) {
Tim Northover4bd286a2014-08-01 13:07:19 +00007369 if (Is64)
Tim Northover3a4e1c72018-01-23 13:51:57 +00007370 read<uint64_t>(Contents, Offset);
Tim Northover4bd286a2014-08-01 13:07:19 +00007371 else
Tim Northover3a4e1c72018-01-23 13:51:57 +00007372 read<uint32_t>(Contents, Offset);
Tim Northover4bd286a2014-08-01 13:07:19 +00007373 }
7374
7375private:
Tim Northover3a4e1c72018-01-23 13:51:57 +00007376 template <typename UIntPtr> void read(StringRef Contents, ptrdiff_t Offset) {
7377 FunctionAddr = readNext<UIntPtr>(Contents, Offset);
7378 Length = readNext<uint32_t>(Contents, Offset);
7379 CompactEncoding = readNext<uint32_t>(Contents, Offset);
7380 PersonalityAddr = readNext<UIntPtr>(Contents, Offset);
7381 LSDAAddr = readNext<UIntPtr>(Contents, Offset);
Tim Northover4bd286a2014-08-01 13:07:19 +00007382 }
7383};
7384}
7385
7386/// Given a relocation from __compact_unwind, consisting of the RelocationRef
7387/// and data being relocated, determine the best base Name and Addend to use for
7388/// display purposes.
7389///
7390/// 1. An Extern relocation will directly reference a symbol (and the data is
7391/// then already an addend), so use that.
7392/// 2. Otherwise the data is an offset in the object file's layout; try to find
7393// a symbol before it in the same section, and use the offset from there.
7394/// 3. Finally, if all that fails, fall back to an offset from the start of the
7395/// referenced section.
7396static void findUnwindRelocNameAddend(const MachOObjectFile *Obj,
7397 std::map<uint64_t, SymbolRef> &Symbols,
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007398 const RelocationRef &Reloc, uint64_t Addr,
Tim Northover4bd286a2014-08-01 13:07:19 +00007399 StringRef &Name, uint64_t &Addend) {
7400 if (Reloc.getSymbol() != Obj->symbol_end()) {
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00007401 Expected<StringRef> NameOrErr = Reloc.getSymbol()->getName();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00007402 if (!NameOrErr)
7403 report_error(Obj->getFileName(), NameOrErr.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00007404 Name = *NameOrErr;
Tim Northover4bd286a2014-08-01 13:07:19 +00007405 Addend = Addr;
7406 return;
7407 }
7408
7409 auto RE = Obj->getRelocation(Reloc.getRawDataRefImpl());
Keno Fischerc780e8e2015-05-21 21:24:32 +00007410 SectionRef RelocSection = Obj->getAnyRelocationSection(RE);
Tim Northover4bd286a2014-08-01 13:07:19 +00007411
Rafael Espindola80291272014-10-08 15:28:58 +00007412 uint64_t SectionAddr = RelocSection.getAddress();
Tim Northover4bd286a2014-08-01 13:07:19 +00007413
7414 auto Sym = Symbols.upper_bound(Addr);
7415 if (Sym == Symbols.begin()) {
7416 // The first symbol in the object is after this reference, the best we can
7417 // do is section-relative notation.
7418 RelocSection.getName(Name);
7419 Addend = Addr - SectionAddr;
7420 return;
7421 }
7422
7423 // Go back one so that SymbolAddress <= Addr.
7424 --Sym;
7425
Kevin Enderby7bd8d992016-05-02 20:28:12 +00007426 auto SectOrErr = Sym->second.getSection();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00007427 if (!SectOrErr)
7428 report_error(Obj->getFileName(), SectOrErr.takeError());
Kevin Enderby7bd8d992016-05-02 20:28:12 +00007429 section_iterator SymSection = *SectOrErr;
Tim Northover4bd286a2014-08-01 13:07:19 +00007430 if (RelocSection == *SymSection) {
7431 // There's a valid symbol in the same section before this reference.
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00007432 Expected<StringRef> NameOrErr = Sym->second.getName();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00007433 if (!NameOrErr)
7434 report_error(Obj->getFileName(), NameOrErr.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00007435 Name = *NameOrErr;
Tim Northover4bd286a2014-08-01 13:07:19 +00007436 Addend = Addr - Sym->first;
7437 return;
7438 }
7439
7440 // There is a symbol before this reference, but it's in a different
7441 // section. Probably not helpful to mention it, so use the section name.
7442 RelocSection.getName(Name);
7443 Addend = Addr - SectionAddr;
7444}
7445
7446static void printUnwindRelocDest(const MachOObjectFile *Obj,
7447 std::map<uint64_t, SymbolRef> &Symbols,
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007448 const RelocationRef &Reloc, uint64_t Addr) {
Tim Northover4bd286a2014-08-01 13:07:19 +00007449 StringRef Name;
7450 uint64_t Addend;
7451
Rafael Espindola854038e2015-06-26 14:51:16 +00007452 if (!Reloc.getObject())
Tim Northover0b0add52014-09-09 10:45:06 +00007453 return;
7454
Tim Northover4bd286a2014-08-01 13:07:19 +00007455 findUnwindRelocNameAddend(Obj, Symbols, Reloc, Addr, Name, Addend);
7456
7457 outs() << Name;
7458 if (Addend)
Tim Northover63a25622014-08-11 09:14:06 +00007459 outs() << " + " << format("0x%" PRIx64, Addend);
Tim Northover4bd286a2014-08-01 13:07:19 +00007460}
7461
7462static void
7463printMachOCompactUnwindSection(const MachOObjectFile *Obj,
7464 std::map<uint64_t, SymbolRef> &Symbols,
7465 const SectionRef &CompactUnwind) {
7466
Tim Northoverbf55f7e2016-11-15 20:26:01 +00007467 if (!Obj->isLittleEndian()) {
7468 outs() << "Skipping big-endian __compact_unwind section\n";
7469 return;
7470 }
Tim Northover4bd286a2014-08-01 13:07:19 +00007471
7472 bool Is64 = Obj->is64Bit();
7473 uint32_t PointerSize = Is64 ? sizeof(uint64_t) : sizeof(uint32_t);
7474 uint32_t EntrySize = 3 * PointerSize + 2 * sizeof(uint32_t);
7475
7476 StringRef Contents;
7477 CompactUnwind.getContents(Contents);
7478
7479 SmallVector<CompactUnwindEntry, 4> CompactUnwinds;
7480
7481 // First populate the initial raw offsets, encodings and so on from the entry.
7482 for (unsigned Offset = 0; Offset < Contents.size(); Offset += EntrySize) {
Tim Northover3a4e1c72018-01-23 13:51:57 +00007483 CompactUnwindEntry Entry(Contents, Offset, Is64);
Tim Northover4bd286a2014-08-01 13:07:19 +00007484 CompactUnwinds.push_back(Entry);
7485 }
7486
7487 // Next we need to look at the relocations to find out what objects are
7488 // actually being referred to.
7489 for (const RelocationRef &Reloc : CompactUnwind.relocations()) {
Rafael Espindola96d071c2015-06-29 23:29:12 +00007490 uint64_t RelocAddress = Reloc.getOffset();
Tim Northover4bd286a2014-08-01 13:07:19 +00007491
7492 uint32_t EntryIdx = RelocAddress / EntrySize;
7493 uint32_t OffsetInEntry = RelocAddress - EntryIdx * EntrySize;
7494 CompactUnwindEntry &Entry = CompactUnwinds[EntryIdx];
7495
7496 if (OffsetInEntry == 0)
7497 Entry.FunctionReloc = Reloc;
7498 else if (OffsetInEntry == PointerSize + 2 * sizeof(uint32_t))
7499 Entry.PersonalityReloc = Reloc;
7500 else if (OffsetInEntry == 2 * PointerSize + 2 * sizeof(uint32_t))
7501 Entry.LSDAReloc = Reloc;
Tim Northoverbf55f7e2016-11-15 20:26:01 +00007502 else {
7503 outs() << "Invalid relocation in __compact_unwind section\n";
7504 return;
7505 }
Tim Northover4bd286a2014-08-01 13:07:19 +00007506 }
7507
7508 // Finally, we're ready to print the data we've gathered.
7509 outs() << "Contents of __compact_unwind section:\n";
7510 for (auto &Entry : CompactUnwinds) {
Tim Northover06af2602014-08-08 12:08:51 +00007511 outs() << " Entry at offset "
7512 << format("0x%" PRIx32, Entry.OffsetInSection) << ":\n";
Tim Northover4bd286a2014-08-01 13:07:19 +00007513
7514 // 1. Start of the region this entry applies to.
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007515 outs() << " start: " << format("0x%" PRIx64,
7516 Entry.FunctionAddr) << ' ';
7517 printUnwindRelocDest(Obj, Symbols, Entry.FunctionReloc, Entry.FunctionAddr);
Tim Northover4bd286a2014-08-01 13:07:19 +00007518 outs() << '\n';
7519
7520 // 2. Length of the region this entry applies to.
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007521 outs() << " length: " << format("0x%" PRIx32, Entry.Length)
7522 << '\n';
Tim Northover4bd286a2014-08-01 13:07:19 +00007523 // 3. The 32-bit compact encoding.
7524 outs() << " compact encoding: "
Tim Northoverb911bf82014-08-08 12:00:09 +00007525 << format("0x%08" PRIx32, Entry.CompactEncoding) << '\n';
Tim Northover4bd286a2014-08-01 13:07:19 +00007526
7527 // 4. The personality function, if present.
Rafael Espindola854038e2015-06-26 14:51:16 +00007528 if (Entry.PersonalityReloc.getObject()) {
Tim Northover4bd286a2014-08-01 13:07:19 +00007529 outs() << " personality function: "
Tim Northoverb911bf82014-08-08 12:00:09 +00007530 << format("0x%" PRIx64, Entry.PersonalityAddr) << ' ';
Tim Northover4bd286a2014-08-01 13:07:19 +00007531 printUnwindRelocDest(Obj, Symbols, Entry.PersonalityReloc,
7532 Entry.PersonalityAddr);
7533 outs() << '\n';
7534 }
7535
7536 // 5. This entry's language-specific data area.
Rafael Espindola854038e2015-06-26 14:51:16 +00007537 if (Entry.LSDAReloc.getObject()) {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007538 outs() << " LSDA: " << format("0x%" PRIx64,
7539 Entry.LSDAAddr) << ' ';
Tim Northover4bd286a2014-08-01 13:07:19 +00007540 printUnwindRelocDest(Obj, Symbols, Entry.LSDAReloc, Entry.LSDAAddr);
7541 outs() << '\n';
7542 }
7543 }
7544}
7545
Tim Northover39c70bb2014-08-12 11:52:59 +00007546//===----------------------------------------------------------------------===//
7547// __unwind_info section dumping
7548//===----------------------------------------------------------------------===//
7549
Tim Northover3a4e1c72018-01-23 13:51:57 +00007550static void printRegularSecondLevelUnwindPage(StringRef PageData) {
7551 ptrdiff_t Pos = 0;
7552 uint32_t Kind = readNext<uint32_t>(PageData, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007553 (void)Kind;
7554 assert(Kind == 2 && "kind for a regular 2nd level index should be 2");
7555
Tim Northover3a4e1c72018-01-23 13:51:57 +00007556 uint16_t EntriesStart = readNext<uint16_t>(PageData, Pos);
7557 uint16_t NumEntries = readNext<uint16_t>(PageData, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007558
Tim Northover3a4e1c72018-01-23 13:51:57 +00007559 Pos = EntriesStart;
Tim Northover39c70bb2014-08-12 11:52:59 +00007560 for (unsigned i = 0; i < NumEntries; ++i) {
Tim Northover3a4e1c72018-01-23 13:51:57 +00007561 uint32_t FunctionOffset = readNext<uint32_t>(PageData, Pos);
7562 uint32_t Encoding = readNext<uint32_t>(PageData, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007563
7564 outs() << " [" << i << "]: "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007565 << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
7566 << ", "
7567 << "encoding=" << format("0x%08" PRIx32, Encoding) << '\n';
Tim Northover39c70bb2014-08-12 11:52:59 +00007568 }
7569}
7570
7571static void printCompressedSecondLevelUnwindPage(
Tim Northover3a4e1c72018-01-23 13:51:57 +00007572 StringRef PageData, uint32_t FunctionBase,
Tim Northover39c70bb2014-08-12 11:52:59 +00007573 const SmallVectorImpl<uint32_t> &CommonEncodings) {
Tim Northover3a4e1c72018-01-23 13:51:57 +00007574 ptrdiff_t Pos = 0;
7575 uint32_t Kind = readNext<uint32_t>(PageData, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007576 (void)Kind;
7577 assert(Kind == 3 && "kind for a compressed 2nd level index should be 3");
7578
Tim Northover3a4e1c72018-01-23 13:51:57 +00007579 uint16_t EntriesStart = readNext<uint16_t>(PageData, Pos);
7580 uint16_t NumEntries = readNext<uint16_t>(PageData, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007581
Tim Northover3a4e1c72018-01-23 13:51:57 +00007582 uint16_t EncodingsStart = readNext<uint16_t>(PageData, Pos);
7583 readNext<uint16_t>(PageData, Pos);
7584 StringRef PageEncodings = PageData.substr(EncodingsStart, StringRef::npos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007585
Tim Northover3a4e1c72018-01-23 13:51:57 +00007586 Pos = EntriesStart;
Tim Northover39c70bb2014-08-12 11:52:59 +00007587 for (unsigned i = 0; i < NumEntries; ++i) {
Tim Northover3a4e1c72018-01-23 13:51:57 +00007588 uint32_t Entry = readNext<uint32_t>(PageData, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007589 uint32_t FunctionOffset = FunctionBase + (Entry & 0xffffff);
7590 uint32_t EncodingIdx = Entry >> 24;
7591
7592 uint32_t Encoding;
7593 if (EncodingIdx < CommonEncodings.size())
7594 Encoding = CommonEncodings[EncodingIdx];
7595 else
Tim Northover3a4e1c72018-01-23 13:51:57 +00007596 Encoding = read<uint32_t>(PageEncodings,
7597 sizeof(uint32_t) *
7598 (EncodingIdx - CommonEncodings.size()));
Tim Northover39c70bb2014-08-12 11:52:59 +00007599
7600 outs() << " [" << i << "]: "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007601 << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
7602 << ", "
7603 << "encoding[" << EncodingIdx
7604 << "]=" << format("0x%08" PRIx32, Encoding) << '\n';
Tim Northover39c70bb2014-08-12 11:52:59 +00007605 }
7606}
7607
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007608static void printMachOUnwindInfoSection(const MachOObjectFile *Obj,
7609 std::map<uint64_t, SymbolRef> &Symbols,
7610 const SectionRef &UnwindInfo) {
Tim Northover39c70bb2014-08-12 11:52:59 +00007611
Tim Northoverbf55f7e2016-11-15 20:26:01 +00007612 if (!Obj->isLittleEndian()) {
7613 outs() << "Skipping big-endian __unwind_info section\n";
7614 return;
7615 }
Tim Northover39c70bb2014-08-12 11:52:59 +00007616
7617 outs() << "Contents of __unwind_info section:\n";
7618
7619 StringRef Contents;
7620 UnwindInfo.getContents(Contents);
Tim Northover3a4e1c72018-01-23 13:51:57 +00007621 ptrdiff_t Pos = 0;
Tim Northover39c70bb2014-08-12 11:52:59 +00007622
7623 //===----------------------------------
7624 // Section header
7625 //===----------------------------------
7626
Tim Northover3a4e1c72018-01-23 13:51:57 +00007627 uint32_t Version = readNext<uint32_t>(Contents, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007628 outs() << " Version: "
7629 << format("0x%" PRIx32, Version) << '\n';
Tim Northoverbf55f7e2016-11-15 20:26:01 +00007630 if (Version != 1) {
7631 outs() << " Skipping section with unknown version\n";
7632 return;
7633 }
Tim Northover39c70bb2014-08-12 11:52:59 +00007634
Tim Northover3a4e1c72018-01-23 13:51:57 +00007635 uint32_t CommonEncodingsStart = readNext<uint32_t>(Contents, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007636 outs() << " Common encodings array section offset: "
7637 << format("0x%" PRIx32, CommonEncodingsStart) << '\n';
Tim Northover3a4e1c72018-01-23 13:51:57 +00007638 uint32_t NumCommonEncodings = readNext<uint32_t>(Contents, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007639 outs() << " Number of common encodings in array: "
7640 << format("0x%" PRIx32, NumCommonEncodings) << '\n';
7641
Tim Northover3a4e1c72018-01-23 13:51:57 +00007642 uint32_t PersonalitiesStart = readNext<uint32_t>(Contents, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007643 outs() << " Personality function array section offset: "
7644 << format("0x%" PRIx32, PersonalitiesStart) << '\n';
Tim Northover3a4e1c72018-01-23 13:51:57 +00007645 uint32_t NumPersonalities = readNext<uint32_t>(Contents, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007646 outs() << " Number of personality functions in array: "
7647 << format("0x%" PRIx32, NumPersonalities) << '\n';
7648
Tim Northover3a4e1c72018-01-23 13:51:57 +00007649 uint32_t IndicesStart = readNext<uint32_t>(Contents, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007650 outs() << " Index array section offset: "
7651 << format("0x%" PRIx32, IndicesStart) << '\n';
Tim Northover3a4e1c72018-01-23 13:51:57 +00007652 uint32_t NumIndices = readNext<uint32_t>(Contents, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007653 outs() << " Number of indices in array: "
7654 << format("0x%" PRIx32, NumIndices) << '\n';
7655
7656 //===----------------------------------
7657 // A shared list of common encodings
7658 //===----------------------------------
7659
7660 // These occupy indices in the range [0, N] whenever an encoding is referenced
7661 // from a compressed 2nd level index table. In practice the linker only
7662 // creates ~128 of these, so that indices are available to embed encodings in
7663 // the 2nd level index.
7664
7665 SmallVector<uint32_t, 64> CommonEncodings;
7666 outs() << " Common encodings: (count = " << NumCommonEncodings << ")\n";
Tim Northover3a4e1c72018-01-23 13:51:57 +00007667 Pos = CommonEncodingsStart;
Tim Northover39c70bb2014-08-12 11:52:59 +00007668 for (unsigned i = 0; i < NumCommonEncodings; ++i) {
Tim Northover3a4e1c72018-01-23 13:51:57 +00007669 uint32_t Encoding = readNext<uint32_t>(Contents, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007670 CommonEncodings.push_back(Encoding);
7671
7672 outs() << " encoding[" << i << "]: " << format("0x%08" PRIx32, Encoding)
7673 << '\n';
7674 }
7675
Tim Northover39c70bb2014-08-12 11:52:59 +00007676 //===----------------------------------
7677 // Personality functions used in this executable
7678 //===----------------------------------
7679
7680 // There should be only a handful of these (one per source language,
7681 // roughly). Particularly since they only get 2 bits in the compact encoding.
7682
7683 outs() << " Personality functions: (count = " << NumPersonalities << ")\n";
Tim Northover3a4e1c72018-01-23 13:51:57 +00007684 Pos = PersonalitiesStart;
Tim Northover39c70bb2014-08-12 11:52:59 +00007685 for (unsigned i = 0; i < NumPersonalities; ++i) {
Tim Northover3a4e1c72018-01-23 13:51:57 +00007686 uint32_t PersonalityFn = readNext<uint32_t>(Contents, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007687 outs() << " personality[" << i + 1
7688 << "]: " << format("0x%08" PRIx32, PersonalityFn) << '\n';
7689 }
7690
7691 //===----------------------------------
7692 // The level 1 index entries
7693 //===----------------------------------
7694
7695 // These specify an approximate place to start searching for the more detailed
7696 // information, sorted by PC.
7697
7698 struct IndexEntry {
7699 uint32_t FunctionOffset;
7700 uint32_t SecondLevelPageStart;
7701 uint32_t LSDAStart;
7702 };
7703
7704 SmallVector<IndexEntry, 4> IndexEntries;
7705
7706 outs() << " Top level indices: (count = " << NumIndices << ")\n";
Tim Northover3a4e1c72018-01-23 13:51:57 +00007707 Pos = IndicesStart;
Tim Northover39c70bb2014-08-12 11:52:59 +00007708 for (unsigned i = 0; i < NumIndices; ++i) {
7709 IndexEntry Entry;
7710
Tim Northover3a4e1c72018-01-23 13:51:57 +00007711 Entry.FunctionOffset = readNext<uint32_t>(Contents, Pos);
7712 Entry.SecondLevelPageStart = readNext<uint32_t>(Contents, Pos);
7713 Entry.LSDAStart = readNext<uint32_t>(Contents, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007714 IndexEntries.push_back(Entry);
7715
7716 outs() << " [" << i << "]: "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007717 << "function offset=" << format("0x%08" PRIx32, Entry.FunctionOffset)
7718 << ", "
Tim Northover39c70bb2014-08-12 11:52:59 +00007719 << "2nd level page offset="
7720 << format("0x%08" PRIx32, Entry.SecondLevelPageStart) << ", "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007721 << "LSDA offset=" << format("0x%08" PRIx32, Entry.LSDAStart) << '\n';
Tim Northover39c70bb2014-08-12 11:52:59 +00007722 }
7723
Tim Northover39c70bb2014-08-12 11:52:59 +00007724 //===----------------------------------
7725 // Next come the LSDA tables
7726 //===----------------------------------
7727
7728 // The LSDA layout is rather implicit: it's a contiguous array of entries from
7729 // the first top-level index's LSDAOffset to the last (sentinel).
7730
7731 outs() << " LSDA descriptors:\n";
Tim Northover3a4e1c72018-01-23 13:51:57 +00007732 Pos = IndexEntries[0].LSDAStart;
7733 const uint32_t LSDASize = 2 * sizeof(uint32_t);
7734 int NumLSDAs =
7735 (IndexEntries.back().LSDAStart - IndexEntries[0].LSDAStart) / LSDASize;
7736
Tim Northover39c70bb2014-08-12 11:52:59 +00007737 for (int i = 0; i < NumLSDAs; ++i) {
Tim Northover3a4e1c72018-01-23 13:51:57 +00007738 uint32_t FunctionOffset = readNext<uint32_t>(Contents, Pos);
7739 uint32_t LSDAOffset = readNext<uint32_t>(Contents, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007740 outs() << " [" << i << "]: "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007741 << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
7742 << ", "
7743 << "LSDA offset=" << format("0x%08" PRIx32, LSDAOffset) << '\n';
Tim Northover39c70bb2014-08-12 11:52:59 +00007744 }
7745
7746 //===----------------------------------
7747 // Finally, the 2nd level indices
7748 //===----------------------------------
7749
7750 // Generally these are 4K in size, and have 2 possible forms:
7751 // + Regular stores up to 511 entries with disparate encodings
7752 // + Compressed stores up to 1021 entries if few enough compact encoding
7753 // values are used.
7754 outs() << " Second level indices:\n";
7755 for (unsigned i = 0; i < IndexEntries.size() - 1; ++i) {
7756 // The final sentinel top-level index has no associated 2nd level page
7757 if (IndexEntries[i].SecondLevelPageStart == 0)
7758 break;
7759
7760 outs() << " Second level index[" << i << "]: "
7761 << "offset in section="
7762 << format("0x%08" PRIx32, IndexEntries[i].SecondLevelPageStart)
7763 << ", "
7764 << "base function offset="
7765 << format("0x%08" PRIx32, IndexEntries[i].FunctionOffset) << '\n';
7766
Tim Northover3a4e1c72018-01-23 13:51:57 +00007767 Pos = IndexEntries[i].SecondLevelPageStart;
7768 if (Pos + sizeof(uint32_t) > Contents.size()) {
7769 outs() << "warning: invalid offset for second level page: " << Pos << '\n';
7770 continue;
7771 }
7772
7773 uint32_t Kind =
7774 *reinterpret_cast<const support::ulittle32_t *>(Contents.data() + Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007775 if (Kind == 2)
Tim Northover3a4e1c72018-01-23 13:51:57 +00007776 printRegularSecondLevelUnwindPage(Contents.substr(Pos, 4096));
Tim Northover39c70bb2014-08-12 11:52:59 +00007777 else if (Kind == 3)
Tim Northover3a4e1c72018-01-23 13:51:57 +00007778 printCompressedSecondLevelUnwindPage(Contents.substr(Pos, 4096),
7779 IndexEntries[i].FunctionOffset,
Tim Northover39c70bb2014-08-12 11:52:59 +00007780 CommonEncodings);
7781 else
Tim Northoverbf55f7e2016-11-15 20:26:01 +00007782 outs() << " Skipping 2nd level page with unknown kind " << Kind
7783 << '\n';
Tim Northover39c70bb2014-08-12 11:52:59 +00007784 }
7785}
7786
Tim Northover4bd286a2014-08-01 13:07:19 +00007787void llvm::printMachOUnwindInfo(const MachOObjectFile *Obj) {
7788 std::map<uint64_t, SymbolRef> Symbols;
7789 for (const SymbolRef &SymRef : Obj->symbols()) {
7790 // Discard any undefined or absolute symbols. They're not going to take part
7791 // in the convenience lookup for unwind info and just take up resources.
Kevin Enderby7bd8d992016-05-02 20:28:12 +00007792 auto SectOrErr = SymRef.getSection();
7793 if (!SectOrErr) {
7794 // TODO: Actually report errors helpfully.
7795 consumeError(SectOrErr.takeError());
7796 continue;
7797 }
7798 section_iterator Section = *SectOrErr;
Tim Northover4bd286a2014-08-01 13:07:19 +00007799 if (Section == Obj->section_end())
7800 continue;
7801
Rafael Espindoladea00162015-07-03 17:44:18 +00007802 uint64_t Addr = SymRef.getValue();
Tim Northover4bd286a2014-08-01 13:07:19 +00007803 Symbols.insert(std::make_pair(Addr, SymRef));
7804 }
7805
7806 for (const SectionRef &Section : Obj->sections()) {
7807 StringRef SectName;
7808 Section.getName(SectName);
7809 if (SectName == "__compact_unwind")
7810 printMachOCompactUnwindSection(Obj, Symbols, Section);
7811 else if (SectName == "__unwind_info")
Tim Northover39c70bb2014-08-12 11:52:59 +00007812 printMachOUnwindInfoSection(Obj, Symbols, Section);
Tim Northover4bd286a2014-08-01 13:07:19 +00007813 }
7814}
Kevin Enderbyb76d3862014-08-22 20:35:18 +00007815
7816static void PrintMachHeader(uint32_t magic, uint32_t cputype,
7817 uint32_t cpusubtype, uint32_t filetype,
7818 uint32_t ncmds, uint32_t sizeofcmds, uint32_t flags,
7819 bool verbose) {
7820 outs() << "Mach header\n";
7821 outs() << " magic cputype cpusubtype caps filetype ncmds "
7822 "sizeofcmds flags\n";
7823 if (verbose) {
7824 if (magic == MachO::MH_MAGIC)
7825 outs() << " MH_MAGIC";
7826 else if (magic == MachO::MH_MAGIC_64)
7827 outs() << "MH_MAGIC_64";
7828 else
7829 outs() << format(" 0x%08" PRIx32, magic);
7830 switch (cputype) {
7831 case MachO::CPU_TYPE_I386:
7832 outs() << " I386";
7833 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
7834 case MachO::CPU_SUBTYPE_I386_ALL:
7835 outs() << " ALL";
7836 break;
7837 default:
7838 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
7839 break;
7840 }
7841 break;
7842 case MachO::CPU_TYPE_X86_64:
7843 outs() << " X86_64";
Kevin Enderby131d1772015-01-09 19:22:37 +00007844 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
7845 case MachO::CPU_SUBTYPE_X86_64_ALL:
7846 outs() << " ALL";
7847 break;
7848 case MachO::CPU_SUBTYPE_X86_64_H:
7849 outs() << " Haswell";
7850 break;
7851 default:
7852 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
7853 break;
7854 }
Kevin Enderbyb76d3862014-08-22 20:35:18 +00007855 break;
7856 case MachO::CPU_TYPE_ARM:
7857 outs() << " ARM";
7858 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
7859 case MachO::CPU_SUBTYPE_ARM_ALL:
7860 outs() << " ALL";
7861 break;
7862 case MachO::CPU_SUBTYPE_ARM_V4T:
7863 outs() << " V4T";
7864 break;
7865 case MachO::CPU_SUBTYPE_ARM_V5TEJ:
7866 outs() << " V5TEJ";
7867 break;
7868 case MachO::CPU_SUBTYPE_ARM_XSCALE:
7869 outs() << " XSCALE";
7870 break;
7871 case MachO::CPU_SUBTYPE_ARM_V6:
7872 outs() << " V6";
7873 break;
7874 case MachO::CPU_SUBTYPE_ARM_V6M:
7875 outs() << " V6M";
7876 break;
7877 case MachO::CPU_SUBTYPE_ARM_V7:
7878 outs() << " V7";
7879 break;
7880 case MachO::CPU_SUBTYPE_ARM_V7EM:
7881 outs() << " V7EM";
7882 break;
7883 case MachO::CPU_SUBTYPE_ARM_V7K:
7884 outs() << " V7K";
7885 break;
7886 case MachO::CPU_SUBTYPE_ARM_V7M:
7887 outs() << " V7M";
7888 break;
7889 case MachO::CPU_SUBTYPE_ARM_V7S:
7890 outs() << " V7S";
7891 break;
7892 default:
7893 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
7894 break;
7895 }
7896 break;
7897 case MachO::CPU_TYPE_ARM64:
7898 outs() << " ARM64";
7899 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
7900 case MachO::CPU_SUBTYPE_ARM64_ALL:
7901 outs() << " ALL";
7902 break;
7903 default:
7904 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
7905 break;
7906 }
7907 break;
7908 case MachO::CPU_TYPE_POWERPC:
7909 outs() << " PPC";
7910 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
7911 case MachO::CPU_SUBTYPE_POWERPC_ALL:
7912 outs() << " ALL";
7913 break;
7914 default:
7915 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
7916 break;
7917 }
7918 break;
7919 case MachO::CPU_TYPE_POWERPC64:
7920 outs() << " PPC64";
7921 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
7922 case MachO::CPU_SUBTYPE_POWERPC_ALL:
7923 outs() << " ALL";
7924 break;
7925 default:
7926 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
7927 break;
7928 }
7929 break;
Kevin Enderby40fdbf82016-01-26 18:20:49 +00007930 default:
7931 outs() << format(" %7d", cputype);
7932 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
7933 break;
Kevin Enderbyb76d3862014-08-22 20:35:18 +00007934 }
7935 if ((cpusubtype & MachO::CPU_SUBTYPE_MASK) == MachO::CPU_SUBTYPE_LIB64) {
Kevin Enderby8ae63c12014-09-04 16:54:47 +00007936 outs() << " LIB64";
Kevin Enderbyb76d3862014-08-22 20:35:18 +00007937 } else {
7938 outs() << format(" 0x%02" PRIx32,
7939 (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24);
7940 }
7941 switch (filetype) {
7942 case MachO::MH_OBJECT:
7943 outs() << " OBJECT";
7944 break;
7945 case MachO::MH_EXECUTE:
7946 outs() << " EXECUTE";
7947 break;
7948 case MachO::MH_FVMLIB:
7949 outs() << " FVMLIB";
7950 break;
7951 case MachO::MH_CORE:
7952 outs() << " CORE";
7953 break;
7954 case MachO::MH_PRELOAD:
7955 outs() << " PRELOAD";
7956 break;
7957 case MachO::MH_DYLIB:
7958 outs() << " DYLIB";
7959 break;
7960 case MachO::MH_DYLIB_STUB:
7961 outs() << " DYLIB_STUB";
7962 break;
7963 case MachO::MH_DYLINKER:
7964 outs() << " DYLINKER";
7965 break;
7966 case MachO::MH_BUNDLE:
7967 outs() << " BUNDLE";
7968 break;
7969 case MachO::MH_DSYM:
7970 outs() << " DSYM";
7971 break;
7972 case MachO::MH_KEXT_BUNDLE:
7973 outs() << " KEXTBUNDLE";
7974 break;
7975 default:
7976 outs() << format(" %10u", filetype);
7977 break;
7978 }
7979 outs() << format(" %5u", ncmds);
7980 outs() << format(" %10u", sizeofcmds);
7981 uint32_t f = flags;
7982 if (f & MachO::MH_NOUNDEFS) {
7983 outs() << " NOUNDEFS";
7984 f &= ~MachO::MH_NOUNDEFS;
7985 }
7986 if (f & MachO::MH_INCRLINK) {
7987 outs() << " INCRLINK";
7988 f &= ~MachO::MH_INCRLINK;
7989 }
7990 if (f & MachO::MH_DYLDLINK) {
7991 outs() << " DYLDLINK";
7992 f &= ~MachO::MH_DYLDLINK;
7993 }
7994 if (f & MachO::MH_BINDATLOAD) {
7995 outs() << " BINDATLOAD";
7996 f &= ~MachO::MH_BINDATLOAD;
7997 }
7998 if (f & MachO::MH_PREBOUND) {
7999 outs() << " PREBOUND";
8000 f &= ~MachO::MH_PREBOUND;
8001 }
8002 if (f & MachO::MH_SPLIT_SEGS) {
8003 outs() << " SPLIT_SEGS";
8004 f &= ~MachO::MH_SPLIT_SEGS;
8005 }
8006 if (f & MachO::MH_LAZY_INIT) {
8007 outs() << " LAZY_INIT";
8008 f &= ~MachO::MH_LAZY_INIT;
8009 }
8010 if (f & MachO::MH_TWOLEVEL) {
8011 outs() << " TWOLEVEL";
8012 f &= ~MachO::MH_TWOLEVEL;
8013 }
8014 if (f & MachO::MH_FORCE_FLAT) {
8015 outs() << " FORCE_FLAT";
8016 f &= ~MachO::MH_FORCE_FLAT;
8017 }
8018 if (f & MachO::MH_NOMULTIDEFS) {
8019 outs() << " NOMULTIDEFS";
8020 f &= ~MachO::MH_NOMULTIDEFS;
8021 }
8022 if (f & MachO::MH_NOFIXPREBINDING) {
8023 outs() << " NOFIXPREBINDING";
8024 f &= ~MachO::MH_NOFIXPREBINDING;
8025 }
8026 if (f & MachO::MH_PREBINDABLE) {
8027 outs() << " PREBINDABLE";
8028 f &= ~MachO::MH_PREBINDABLE;
8029 }
8030 if (f & MachO::MH_ALLMODSBOUND) {
8031 outs() << " ALLMODSBOUND";
8032 f &= ~MachO::MH_ALLMODSBOUND;
8033 }
8034 if (f & MachO::MH_SUBSECTIONS_VIA_SYMBOLS) {
8035 outs() << " SUBSECTIONS_VIA_SYMBOLS";
8036 f &= ~MachO::MH_SUBSECTIONS_VIA_SYMBOLS;
8037 }
8038 if (f & MachO::MH_CANONICAL) {
8039 outs() << " CANONICAL";
8040 f &= ~MachO::MH_CANONICAL;
8041 }
8042 if (f & MachO::MH_WEAK_DEFINES) {
8043 outs() << " WEAK_DEFINES";
8044 f &= ~MachO::MH_WEAK_DEFINES;
8045 }
8046 if (f & MachO::MH_BINDS_TO_WEAK) {
8047 outs() << " BINDS_TO_WEAK";
8048 f &= ~MachO::MH_BINDS_TO_WEAK;
8049 }
8050 if (f & MachO::MH_ALLOW_STACK_EXECUTION) {
8051 outs() << " ALLOW_STACK_EXECUTION";
8052 f &= ~MachO::MH_ALLOW_STACK_EXECUTION;
8053 }
8054 if (f & MachO::MH_DEAD_STRIPPABLE_DYLIB) {
8055 outs() << " DEAD_STRIPPABLE_DYLIB";
8056 f &= ~MachO::MH_DEAD_STRIPPABLE_DYLIB;
8057 }
8058 if (f & MachO::MH_PIE) {
8059 outs() << " PIE";
8060 f &= ~MachO::MH_PIE;
8061 }
8062 if (f & MachO::MH_NO_REEXPORTED_DYLIBS) {
8063 outs() << " NO_REEXPORTED_DYLIBS";
8064 f &= ~MachO::MH_NO_REEXPORTED_DYLIBS;
8065 }
8066 if (f & MachO::MH_HAS_TLV_DESCRIPTORS) {
8067 outs() << " MH_HAS_TLV_DESCRIPTORS";
8068 f &= ~MachO::MH_HAS_TLV_DESCRIPTORS;
8069 }
8070 if (f & MachO::MH_NO_HEAP_EXECUTION) {
8071 outs() << " MH_NO_HEAP_EXECUTION";
8072 f &= ~MachO::MH_NO_HEAP_EXECUTION;
8073 }
8074 if (f & MachO::MH_APP_EXTENSION_SAFE) {
8075 outs() << " APP_EXTENSION_SAFE";
8076 f &= ~MachO::MH_APP_EXTENSION_SAFE;
8077 }
Kevin Enderbydf0d6da2017-06-19 19:38:22 +00008078 if (f & MachO::MH_NLIST_OUTOFSYNC_WITH_DYLDINFO) {
8079 outs() << " NLIST_OUTOFSYNC_WITH_DYLDINFO";
8080 f &= ~MachO::MH_NLIST_OUTOFSYNC_WITH_DYLDINFO;
8081 }
Kevin Enderbyb76d3862014-08-22 20:35:18 +00008082 if (f != 0 || flags == 0)
8083 outs() << format(" 0x%08" PRIx32, f);
8084 } else {
8085 outs() << format(" 0x%08" PRIx32, magic);
8086 outs() << format(" %7d", cputype);
8087 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
8088 outs() << format(" 0x%02" PRIx32,
8089 (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24);
8090 outs() << format(" %10u", filetype);
8091 outs() << format(" %5u", ncmds);
8092 outs() << format(" %10u", sizeofcmds);
8093 outs() << format(" 0x%08" PRIx32, flags);
8094 }
8095 outs() << "\n";
8096}
8097
Kevin Enderby956366c2014-08-29 22:30:52 +00008098static void PrintSegmentCommand(uint32_t cmd, uint32_t cmdsize,
8099 StringRef SegName, uint64_t vmaddr,
8100 uint64_t vmsize, uint64_t fileoff,
8101 uint64_t filesize, uint32_t maxprot,
8102 uint32_t initprot, uint32_t nsects,
8103 uint32_t flags, uint32_t object_size,
8104 bool verbose) {
8105 uint64_t expected_cmdsize;
8106 if (cmd == MachO::LC_SEGMENT) {
8107 outs() << " cmd LC_SEGMENT\n";
8108 expected_cmdsize = nsects;
8109 expected_cmdsize *= sizeof(struct MachO::section);
8110 expected_cmdsize += sizeof(struct MachO::segment_command);
8111 } else {
8112 outs() << " cmd LC_SEGMENT_64\n";
8113 expected_cmdsize = nsects;
8114 expected_cmdsize *= sizeof(struct MachO::section_64);
8115 expected_cmdsize += sizeof(struct MachO::segment_command_64);
8116 }
8117 outs() << " cmdsize " << cmdsize;
8118 if (cmdsize != expected_cmdsize)
8119 outs() << " Inconsistent size\n";
8120 else
8121 outs() << "\n";
8122 outs() << " segname " << SegName << "\n";
8123 if (cmd == MachO::LC_SEGMENT_64) {
8124 outs() << " vmaddr " << format("0x%016" PRIx64, vmaddr) << "\n";
8125 outs() << " vmsize " << format("0x%016" PRIx64, vmsize) << "\n";
8126 } else {
Kevin Enderbyadb7c432014-12-16 18:58:11 +00008127 outs() << " vmaddr " << format("0x%08" PRIx64, vmaddr) << "\n";
8128 outs() << " vmsize " << format("0x%08" PRIx64, vmsize) << "\n";
Kevin Enderby956366c2014-08-29 22:30:52 +00008129 }
8130 outs() << " fileoff " << fileoff;
8131 if (fileoff > object_size)
8132 outs() << " (past end of file)\n";
8133 else
8134 outs() << "\n";
8135 outs() << " filesize " << filesize;
8136 if (fileoff + filesize > object_size)
8137 outs() << " (past end of file)\n";
8138 else
8139 outs() << "\n";
8140 if (verbose) {
8141 if ((maxprot &
8142 ~(MachO::VM_PROT_READ | MachO::VM_PROT_WRITE |
8143 MachO::VM_PROT_EXECUTE)) != 0)
8144 outs() << " maxprot ?" << format("0x%08" PRIx32, maxprot) << "\n";
8145 else {
Davide Italiano37ff06a2015-09-02 16:53:25 +00008146 outs() << " maxprot ";
8147 outs() << ((maxprot & MachO::VM_PROT_READ) ? "r" : "-");
8148 outs() << ((maxprot & MachO::VM_PROT_WRITE) ? "w" : "-");
8149 outs() << ((maxprot & MachO::VM_PROT_EXECUTE) ? "x\n" : "-\n");
Kevin Enderby956366c2014-08-29 22:30:52 +00008150 }
8151 if ((initprot &
8152 ~(MachO::VM_PROT_READ | MachO::VM_PROT_WRITE |
8153 MachO::VM_PROT_EXECUTE)) != 0)
Kevin Enderby41c9c002016-10-21 18:22:35 +00008154 outs() << " initprot ?" << format("0x%08" PRIx32, initprot) << "\n";
Kevin Enderby956366c2014-08-29 22:30:52 +00008155 else {
Kevin Enderby41c9c002016-10-21 18:22:35 +00008156 outs() << " initprot ";
Davide Italiano37ff06a2015-09-02 16:53:25 +00008157 outs() << ((initprot & MachO::VM_PROT_READ) ? "r" : "-");
8158 outs() << ((initprot & MachO::VM_PROT_WRITE) ? "w" : "-");
8159 outs() << ((initprot & MachO::VM_PROT_EXECUTE) ? "x\n" : "-\n");
Kevin Enderby956366c2014-08-29 22:30:52 +00008160 }
8161 } else {
8162 outs() << " maxprot " << format("0x%08" PRIx32, maxprot) << "\n";
8163 outs() << " initprot " << format("0x%08" PRIx32, initprot) << "\n";
8164 }
8165 outs() << " nsects " << nsects << "\n";
8166 if (verbose) {
8167 outs() << " flags";
8168 if (flags == 0)
8169 outs() << " (none)\n";
8170 else {
8171 if (flags & MachO::SG_HIGHVM) {
8172 outs() << " HIGHVM";
8173 flags &= ~MachO::SG_HIGHVM;
8174 }
8175 if (flags & MachO::SG_FVMLIB) {
8176 outs() << " FVMLIB";
8177 flags &= ~MachO::SG_FVMLIB;
8178 }
8179 if (flags & MachO::SG_NORELOC) {
8180 outs() << " NORELOC";
8181 flags &= ~MachO::SG_NORELOC;
8182 }
8183 if (flags & MachO::SG_PROTECTED_VERSION_1) {
8184 outs() << " PROTECTED_VERSION_1";
8185 flags &= ~MachO::SG_PROTECTED_VERSION_1;
8186 }
8187 if (flags)
8188 outs() << format(" 0x%08" PRIx32, flags) << " (unknown flags)\n";
8189 else
8190 outs() << "\n";
8191 }
8192 } else {
8193 outs() << " flags " << format("0x%" PRIx32, flags) << "\n";
8194 }
8195}
8196
8197static void PrintSection(const char *sectname, const char *segname,
8198 uint64_t addr, uint64_t size, uint32_t offset,
8199 uint32_t align, uint32_t reloff, uint32_t nreloc,
8200 uint32_t flags, uint32_t reserved1, uint32_t reserved2,
8201 uint32_t cmd, const char *sg_segname,
8202 uint32_t filetype, uint32_t object_size,
8203 bool verbose) {
8204 outs() << "Section\n";
8205 outs() << " sectname " << format("%.16s\n", sectname);
8206 outs() << " segname " << format("%.16s", segname);
8207 if (filetype != MachO::MH_OBJECT && strncmp(sg_segname, segname, 16) != 0)
8208 outs() << " (does not match segment)\n";
8209 else
8210 outs() << "\n";
8211 if (cmd == MachO::LC_SEGMENT_64) {
8212 outs() << " addr " << format("0x%016" PRIx64, addr) << "\n";
8213 outs() << " size " << format("0x%016" PRIx64, size);
8214 } else {
Kevin Enderby75594b62014-12-16 21:00:25 +00008215 outs() << " addr " << format("0x%08" PRIx64, addr) << "\n";
8216 outs() << " size " << format("0x%08" PRIx64, size);
Kevin Enderby956366c2014-08-29 22:30:52 +00008217 }
8218 if ((flags & MachO::S_ZEROFILL) != 0 && offset + size > object_size)
8219 outs() << " (past end of file)\n";
8220 else
8221 outs() << "\n";
8222 outs() << " offset " << offset;
8223 if (offset > object_size)
8224 outs() << " (past end of file)\n";
8225 else
8226 outs() << "\n";
8227 uint32_t align_shifted = 1 << align;
8228 outs() << " align 2^" << align << " (" << align_shifted << ")\n";
8229 outs() << " reloff " << reloff;
8230 if (reloff > object_size)
8231 outs() << " (past end of file)\n";
8232 else
8233 outs() << "\n";
8234 outs() << " nreloc " << nreloc;
8235 if (reloff + nreloc * sizeof(struct MachO::relocation_info) > object_size)
8236 outs() << " (past end of file)\n";
8237 else
8238 outs() << "\n";
8239 uint32_t section_type = flags & MachO::SECTION_TYPE;
8240 if (verbose) {
8241 outs() << " type";
8242 if (section_type == MachO::S_REGULAR)
8243 outs() << " S_REGULAR\n";
8244 else if (section_type == MachO::S_ZEROFILL)
8245 outs() << " S_ZEROFILL\n";
8246 else if (section_type == MachO::S_CSTRING_LITERALS)
8247 outs() << " S_CSTRING_LITERALS\n";
8248 else if (section_type == MachO::S_4BYTE_LITERALS)
8249 outs() << " S_4BYTE_LITERALS\n";
8250 else if (section_type == MachO::S_8BYTE_LITERALS)
8251 outs() << " S_8BYTE_LITERALS\n";
8252 else if (section_type == MachO::S_16BYTE_LITERALS)
8253 outs() << " S_16BYTE_LITERALS\n";
8254 else if (section_type == MachO::S_LITERAL_POINTERS)
8255 outs() << " S_LITERAL_POINTERS\n";
8256 else if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS)
8257 outs() << " S_NON_LAZY_SYMBOL_POINTERS\n";
8258 else if (section_type == MachO::S_LAZY_SYMBOL_POINTERS)
8259 outs() << " S_LAZY_SYMBOL_POINTERS\n";
8260 else if (section_type == MachO::S_SYMBOL_STUBS)
8261 outs() << " S_SYMBOL_STUBS\n";
8262 else if (section_type == MachO::S_MOD_INIT_FUNC_POINTERS)
8263 outs() << " S_MOD_INIT_FUNC_POINTERS\n";
8264 else if (section_type == MachO::S_MOD_TERM_FUNC_POINTERS)
8265 outs() << " S_MOD_TERM_FUNC_POINTERS\n";
8266 else if (section_type == MachO::S_COALESCED)
8267 outs() << " S_COALESCED\n";
8268 else if (section_type == MachO::S_INTERPOSING)
8269 outs() << " S_INTERPOSING\n";
8270 else if (section_type == MachO::S_DTRACE_DOF)
8271 outs() << " S_DTRACE_DOF\n";
8272 else if (section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS)
8273 outs() << " S_LAZY_DYLIB_SYMBOL_POINTERS\n";
8274 else if (section_type == MachO::S_THREAD_LOCAL_REGULAR)
8275 outs() << " S_THREAD_LOCAL_REGULAR\n";
8276 else if (section_type == MachO::S_THREAD_LOCAL_ZEROFILL)
8277 outs() << " S_THREAD_LOCAL_ZEROFILL\n";
8278 else if (section_type == MachO::S_THREAD_LOCAL_VARIABLES)
8279 outs() << " S_THREAD_LOCAL_VARIABLES\n";
8280 else if (section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS)
8281 outs() << " S_THREAD_LOCAL_VARIABLE_POINTERS\n";
8282 else if (section_type == MachO::S_THREAD_LOCAL_INIT_FUNCTION_POINTERS)
8283 outs() << " S_THREAD_LOCAL_INIT_FUNCTION_POINTERS\n";
8284 else
8285 outs() << format("0x%08" PRIx32, section_type) << "\n";
8286 outs() << "attributes";
8287 uint32_t section_attributes = flags & MachO::SECTION_ATTRIBUTES;
8288 if (section_attributes & MachO::S_ATTR_PURE_INSTRUCTIONS)
8289 outs() << " PURE_INSTRUCTIONS";
8290 if (section_attributes & MachO::S_ATTR_NO_TOC)
8291 outs() << " NO_TOC";
8292 if (section_attributes & MachO::S_ATTR_STRIP_STATIC_SYMS)
8293 outs() << " STRIP_STATIC_SYMS";
8294 if (section_attributes & MachO::S_ATTR_NO_DEAD_STRIP)
8295 outs() << " NO_DEAD_STRIP";
8296 if (section_attributes & MachO::S_ATTR_LIVE_SUPPORT)
8297 outs() << " LIVE_SUPPORT";
8298 if (section_attributes & MachO::S_ATTR_SELF_MODIFYING_CODE)
8299 outs() << " SELF_MODIFYING_CODE";
8300 if (section_attributes & MachO::S_ATTR_DEBUG)
8301 outs() << " DEBUG";
8302 if (section_attributes & MachO::S_ATTR_SOME_INSTRUCTIONS)
8303 outs() << " SOME_INSTRUCTIONS";
8304 if (section_attributes & MachO::S_ATTR_EXT_RELOC)
8305 outs() << " EXT_RELOC";
8306 if (section_attributes & MachO::S_ATTR_LOC_RELOC)
8307 outs() << " LOC_RELOC";
8308 if (section_attributes == 0)
8309 outs() << " (none)";
8310 outs() << "\n";
8311 } else
8312 outs() << " flags " << format("0x%08" PRIx32, flags) << "\n";
8313 outs() << " reserved1 " << reserved1;
8314 if (section_type == MachO::S_SYMBOL_STUBS ||
8315 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
8316 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
8317 section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
8318 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS)
8319 outs() << " (index into indirect symbol table)\n";
8320 else
8321 outs() << "\n";
8322 outs() << " reserved2 " << reserved2;
8323 if (section_type == MachO::S_SYMBOL_STUBS)
8324 outs() << " (size of stubs)\n";
8325 else
8326 outs() << "\n";
8327}
8328
David Majnemer73cc6ff2014-11-13 19:48:56 +00008329static void PrintSymtabLoadCommand(MachO::symtab_command st, bool Is64Bit,
Kevin Enderby956366c2014-08-29 22:30:52 +00008330 uint32_t object_size) {
8331 outs() << " cmd LC_SYMTAB\n";
8332 outs() << " cmdsize " << st.cmdsize;
8333 if (st.cmdsize != sizeof(struct MachO::symtab_command))
8334 outs() << " Incorrect size\n";
8335 else
8336 outs() << "\n";
8337 outs() << " symoff " << st.symoff;
8338 if (st.symoff > object_size)
8339 outs() << " (past end of file)\n";
8340 else
8341 outs() << "\n";
8342 outs() << " nsyms " << st.nsyms;
8343 uint64_t big_size;
David Majnemer73cc6ff2014-11-13 19:48:56 +00008344 if (Is64Bit) {
Kevin Enderby956366c2014-08-29 22:30:52 +00008345 big_size = st.nsyms;
8346 big_size *= sizeof(struct MachO::nlist_64);
8347 big_size += st.symoff;
8348 if (big_size > object_size)
8349 outs() << " (past end of file)\n";
8350 else
8351 outs() << "\n";
8352 } else {
8353 big_size = st.nsyms;
8354 big_size *= sizeof(struct MachO::nlist);
8355 big_size += st.symoff;
8356 if (big_size > object_size)
8357 outs() << " (past end of file)\n";
8358 else
8359 outs() << "\n";
8360 }
8361 outs() << " stroff " << st.stroff;
8362 if (st.stroff > object_size)
8363 outs() << " (past end of file)\n";
8364 else
8365 outs() << "\n";
8366 outs() << " strsize " << st.strsize;
8367 big_size = st.stroff;
8368 big_size += st.strsize;
8369 if (big_size > object_size)
8370 outs() << " (past end of file)\n";
8371 else
8372 outs() << "\n";
8373}
8374
8375static void PrintDysymtabLoadCommand(MachO::dysymtab_command dyst,
8376 uint32_t nsyms, uint32_t object_size,
David Majnemer73cc6ff2014-11-13 19:48:56 +00008377 bool Is64Bit) {
Kevin Enderby956366c2014-08-29 22:30:52 +00008378 outs() << " cmd LC_DYSYMTAB\n";
8379 outs() << " cmdsize " << dyst.cmdsize;
8380 if (dyst.cmdsize != sizeof(struct MachO::dysymtab_command))
8381 outs() << " Incorrect size\n";
8382 else
8383 outs() << "\n";
8384 outs() << " ilocalsym " << dyst.ilocalsym;
8385 if (dyst.ilocalsym > nsyms)
8386 outs() << " (greater than the number of symbols)\n";
8387 else
8388 outs() << "\n";
8389 outs() << " nlocalsym " << dyst.nlocalsym;
8390 uint64_t big_size;
8391 big_size = dyst.ilocalsym;
8392 big_size += dyst.nlocalsym;
8393 if (big_size > nsyms)
8394 outs() << " (past the end of the symbol table)\n";
8395 else
8396 outs() << "\n";
8397 outs() << " iextdefsym " << dyst.iextdefsym;
8398 if (dyst.iextdefsym > nsyms)
8399 outs() << " (greater than the number of symbols)\n";
8400 else
8401 outs() << "\n";
8402 outs() << " nextdefsym " << dyst.nextdefsym;
8403 big_size = dyst.iextdefsym;
8404 big_size += dyst.nextdefsym;
8405 if (big_size > nsyms)
8406 outs() << " (past the end of the symbol table)\n";
8407 else
8408 outs() << "\n";
8409 outs() << " iundefsym " << dyst.iundefsym;
8410 if (dyst.iundefsym > nsyms)
8411 outs() << " (greater than the number of symbols)\n";
8412 else
8413 outs() << "\n";
8414 outs() << " nundefsym " << dyst.nundefsym;
8415 big_size = dyst.iundefsym;
8416 big_size += dyst.nundefsym;
8417 if (big_size > nsyms)
8418 outs() << " (past the end of the symbol table)\n";
8419 else
8420 outs() << "\n";
8421 outs() << " tocoff " << dyst.tocoff;
8422 if (dyst.tocoff > object_size)
8423 outs() << " (past end of file)\n";
8424 else
8425 outs() << "\n";
8426 outs() << " ntoc " << dyst.ntoc;
8427 big_size = dyst.ntoc;
8428 big_size *= sizeof(struct MachO::dylib_table_of_contents);
8429 big_size += dyst.tocoff;
8430 if (big_size > object_size)
8431 outs() << " (past end of file)\n";
8432 else
8433 outs() << "\n";
8434 outs() << " modtaboff " << dyst.modtaboff;
8435 if (dyst.modtaboff > object_size)
8436 outs() << " (past end of file)\n";
8437 else
8438 outs() << "\n";
8439 outs() << " nmodtab " << dyst.nmodtab;
8440 uint64_t modtabend;
David Majnemer73cc6ff2014-11-13 19:48:56 +00008441 if (Is64Bit) {
Kevin Enderby956366c2014-08-29 22:30:52 +00008442 modtabend = dyst.nmodtab;
8443 modtabend *= sizeof(struct MachO::dylib_module_64);
8444 modtabend += dyst.modtaboff;
8445 } else {
8446 modtabend = dyst.nmodtab;
8447 modtabend *= sizeof(struct MachO::dylib_module);
8448 modtabend += dyst.modtaboff;
8449 }
8450 if (modtabend > object_size)
8451 outs() << " (past end of file)\n";
8452 else
8453 outs() << "\n";
8454 outs() << " extrefsymoff " << dyst.extrefsymoff;
8455 if (dyst.extrefsymoff > object_size)
8456 outs() << " (past end of file)\n";
8457 else
8458 outs() << "\n";
8459 outs() << " nextrefsyms " << dyst.nextrefsyms;
8460 big_size = dyst.nextrefsyms;
8461 big_size *= sizeof(struct MachO::dylib_reference);
8462 big_size += dyst.extrefsymoff;
8463 if (big_size > object_size)
8464 outs() << " (past end of file)\n";
8465 else
8466 outs() << "\n";
8467 outs() << " indirectsymoff " << dyst.indirectsymoff;
8468 if (dyst.indirectsymoff > object_size)
8469 outs() << " (past end of file)\n";
8470 else
8471 outs() << "\n";
8472 outs() << " nindirectsyms " << dyst.nindirectsyms;
8473 big_size = dyst.nindirectsyms;
8474 big_size *= sizeof(uint32_t);
8475 big_size += dyst.indirectsymoff;
8476 if (big_size > object_size)
8477 outs() << " (past end of file)\n";
8478 else
8479 outs() << "\n";
8480 outs() << " extreloff " << dyst.extreloff;
8481 if (dyst.extreloff > object_size)
8482 outs() << " (past end of file)\n";
8483 else
8484 outs() << "\n";
8485 outs() << " nextrel " << dyst.nextrel;
8486 big_size = dyst.nextrel;
8487 big_size *= sizeof(struct MachO::relocation_info);
8488 big_size += dyst.extreloff;
8489 if (big_size > object_size)
8490 outs() << " (past end of file)\n";
8491 else
8492 outs() << "\n";
8493 outs() << " locreloff " << dyst.locreloff;
8494 if (dyst.locreloff > object_size)
8495 outs() << " (past end of file)\n";
8496 else
8497 outs() << "\n";
8498 outs() << " nlocrel " << dyst.nlocrel;
8499 big_size = dyst.nlocrel;
8500 big_size *= sizeof(struct MachO::relocation_info);
8501 big_size += dyst.locreloff;
8502 if (big_size > object_size)
8503 outs() << " (past end of file)\n";
8504 else
8505 outs() << "\n";
8506}
8507
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008508static void PrintDyldInfoLoadCommand(MachO::dyld_info_command dc,
8509 uint32_t object_size) {
8510 if (dc.cmd == MachO::LC_DYLD_INFO)
8511 outs() << " cmd LC_DYLD_INFO\n";
8512 else
8513 outs() << " cmd LC_DYLD_INFO_ONLY\n";
8514 outs() << " cmdsize " << dc.cmdsize;
8515 if (dc.cmdsize != sizeof(struct MachO::dyld_info_command))
8516 outs() << " Incorrect size\n";
8517 else
8518 outs() << "\n";
8519 outs() << " rebase_off " << dc.rebase_off;
8520 if (dc.rebase_off > object_size)
8521 outs() << " (past end of file)\n";
8522 else
8523 outs() << "\n";
8524 outs() << " rebase_size " << dc.rebase_size;
8525 uint64_t big_size;
8526 big_size = dc.rebase_off;
8527 big_size += dc.rebase_size;
8528 if (big_size > object_size)
8529 outs() << " (past end of file)\n";
8530 else
8531 outs() << "\n";
8532 outs() << " bind_off " << dc.bind_off;
8533 if (dc.bind_off > object_size)
8534 outs() << " (past end of file)\n";
8535 else
8536 outs() << "\n";
8537 outs() << " bind_size " << dc.bind_size;
8538 big_size = dc.bind_off;
8539 big_size += dc.bind_size;
8540 if (big_size > object_size)
8541 outs() << " (past end of file)\n";
8542 else
8543 outs() << "\n";
8544 outs() << " weak_bind_off " << dc.weak_bind_off;
8545 if (dc.weak_bind_off > object_size)
8546 outs() << " (past end of file)\n";
8547 else
8548 outs() << "\n";
8549 outs() << " weak_bind_size " << dc.weak_bind_size;
8550 big_size = dc.weak_bind_off;
8551 big_size += dc.weak_bind_size;
8552 if (big_size > object_size)
8553 outs() << " (past end of file)\n";
8554 else
8555 outs() << "\n";
8556 outs() << " lazy_bind_off " << dc.lazy_bind_off;
8557 if (dc.lazy_bind_off > object_size)
8558 outs() << " (past end of file)\n";
8559 else
8560 outs() << "\n";
8561 outs() << " lazy_bind_size " << dc.lazy_bind_size;
8562 big_size = dc.lazy_bind_off;
8563 big_size += dc.lazy_bind_size;
8564 if (big_size > object_size)
8565 outs() << " (past end of file)\n";
8566 else
8567 outs() << "\n";
8568 outs() << " export_off " << dc.export_off;
8569 if (dc.export_off > object_size)
8570 outs() << " (past end of file)\n";
8571 else
8572 outs() << "\n";
8573 outs() << " export_size " << dc.export_size;
8574 big_size = dc.export_off;
8575 big_size += dc.export_size;
8576 if (big_size > object_size)
8577 outs() << " (past end of file)\n";
8578 else
8579 outs() << "\n";
8580}
8581
8582static void PrintDyldLoadCommand(MachO::dylinker_command dyld,
8583 const char *Ptr) {
8584 if (dyld.cmd == MachO::LC_ID_DYLINKER)
8585 outs() << " cmd LC_ID_DYLINKER\n";
8586 else if (dyld.cmd == MachO::LC_LOAD_DYLINKER)
8587 outs() << " cmd LC_LOAD_DYLINKER\n";
8588 else if (dyld.cmd == MachO::LC_DYLD_ENVIRONMENT)
8589 outs() << " cmd LC_DYLD_ENVIRONMENT\n";
8590 else
8591 outs() << " cmd ?(" << dyld.cmd << ")\n";
8592 outs() << " cmdsize " << dyld.cmdsize;
8593 if (dyld.cmdsize < sizeof(struct MachO::dylinker_command))
8594 outs() << " Incorrect size\n";
8595 else
8596 outs() << "\n";
8597 if (dyld.name >= dyld.cmdsize)
8598 outs() << " name ?(bad offset " << dyld.name << ")\n";
8599 else {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00008600 const char *P = (const char *)(Ptr) + dyld.name;
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008601 outs() << " name " << P << " (offset " << dyld.name << ")\n";
8602 }
8603}
8604
8605static void PrintUuidLoadCommand(MachO::uuid_command uuid) {
8606 outs() << " cmd LC_UUID\n";
8607 outs() << " cmdsize " << uuid.cmdsize;
8608 if (uuid.cmdsize != sizeof(struct MachO::uuid_command))
8609 outs() << " Incorrect size\n";
8610 else
8611 outs() << "\n";
8612 outs() << " uuid ";
Davide Italianoc74277a2015-12-07 00:03:28 +00008613 for (int i = 0; i < 16; ++i) {
8614 outs() << format("%02" PRIX32, uuid.uuid[i]);
8615 if (i == 3 || i == 5 || i == 7 || i == 9)
8616 outs() << "-";
8617 }
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008618 outs() << "\n";
8619}
8620
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008621static void PrintRpathLoadCommand(MachO::rpath_command rpath, const char *Ptr) {
Jean-Daniel Dupas00cc1f52014-12-04 07:37:02 +00008622 outs() << " cmd LC_RPATH\n";
8623 outs() << " cmdsize " << rpath.cmdsize;
8624 if (rpath.cmdsize < sizeof(struct MachO::rpath_command))
8625 outs() << " Incorrect size\n";
8626 else
8627 outs() << "\n";
8628 if (rpath.path >= rpath.cmdsize)
8629 outs() << " path ?(bad offset " << rpath.path << ")\n";
8630 else {
8631 const char *P = (const char *)(Ptr) + rpath.path;
8632 outs() << " path " << P << " (offset " << rpath.path << ")\n";
8633 }
8634}
8635
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008636static void PrintVersionMinLoadCommand(MachO::version_min_command vd) {
Tim Northoverbfbfb122015-11-02 21:26:58 +00008637 StringRef LoadCmdName;
8638 switch (vd.cmd) {
8639 case MachO::LC_VERSION_MIN_MACOSX:
8640 LoadCmdName = "LC_VERSION_MIN_MACOSX";
8641 break;
8642 case MachO::LC_VERSION_MIN_IPHONEOS:
8643 LoadCmdName = "LC_VERSION_MIN_IPHONEOS";
8644 break;
8645 case MachO::LC_VERSION_MIN_TVOS:
8646 LoadCmdName = "LC_VERSION_MIN_TVOS";
8647 break;
8648 case MachO::LC_VERSION_MIN_WATCHOS:
8649 LoadCmdName = "LC_VERSION_MIN_WATCHOS";
8650 break;
8651 default:
8652 llvm_unreachable("Unknown version min load command");
8653 }
8654
8655 outs() << " cmd " << LoadCmdName << '\n';
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008656 outs() << " cmdsize " << vd.cmdsize;
8657 if (vd.cmdsize != sizeof(struct MachO::version_min_command))
8658 outs() << " Incorrect size\n";
8659 else
8660 outs() << "\n";
Davide Italiano56baef32015-08-26 12:26:11 +00008661 outs() << " version "
8662 << MachOObjectFile::getVersionMinMajor(vd, false) << "."
8663 << MachOObjectFile::getVersionMinMinor(vd, false);
8664 uint32_t Update = MachOObjectFile::getVersionMinUpdate(vd, false);
8665 if (Update != 0)
8666 outs() << "." << Update;
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008667 outs() << "\n";
8668 if (vd.sdk == 0)
Kevin Enderby57538292014-12-17 01:01:30 +00008669 outs() << " sdk n/a";
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008670 else {
Davide Italiano56baef32015-08-26 12:26:11 +00008671 outs() << " sdk "
8672 << MachOObjectFile::getVersionMinMajor(vd, true) << "."
8673 << MachOObjectFile::getVersionMinMinor(vd, true);
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008674 }
Davide Italiano56baef32015-08-26 12:26:11 +00008675 Update = MachOObjectFile::getVersionMinUpdate(vd, true);
8676 if (Update != 0)
8677 outs() << "." << Update;
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008678 outs() << "\n";
8679}
8680
Kevin Enderbya4579c42017-01-19 17:36:31 +00008681static void PrintNoteLoadCommand(MachO::note_command Nt) {
8682 outs() << " cmd LC_NOTE\n";
8683 outs() << " cmdsize " << Nt.cmdsize;
8684 if (Nt.cmdsize != sizeof(struct MachO::note_command))
8685 outs() << " Incorrect size\n";
8686 else
8687 outs() << "\n";
8688 const char *d = Nt.data_owner;
8689 outs() << "data_owner " << format("%.16s\n", d);
8690 outs() << " offset " << Nt.offset << "\n";
8691 outs() << " size " << Nt.size << "\n";
8692}
8693
Steven Wu5b54a422017-01-23 20:07:55 +00008694static void PrintBuildToolVersion(MachO::build_tool_version bv) {
8695 outs() << " tool " << MachOObjectFile::getBuildTool(bv.tool) << "\n";
8696 outs() << " version " << MachOObjectFile::getVersionString(bv.version)
8697 << "\n";
8698}
8699
8700static void PrintBuildVersionLoadCommand(const MachOObjectFile *obj,
8701 MachO::build_version_command bd) {
8702 outs() << " cmd LC_BUILD_VERSION\n";
8703 outs() << " cmdsize " << bd.cmdsize;
8704 if (bd.cmdsize !=
8705 sizeof(struct MachO::build_version_command) +
8706 bd.ntools * sizeof(struct MachO::build_tool_version))
8707 outs() << " Incorrect size\n";
8708 else
8709 outs() << "\n";
8710 outs() << " platform " << MachOObjectFile::getBuildPlatform(bd.platform)
8711 << "\n";
8712 if (bd.sdk)
8713 outs() << " sdk " << MachOObjectFile::getVersionString(bd.sdk)
8714 << "\n";
8715 else
8716 outs() << " sdk n/a\n";
8717 outs() << " minos " << MachOObjectFile::getVersionString(bd.minos)
8718 << "\n";
8719 outs() << " ntools " << bd.ntools << "\n";
8720 for (unsigned i = 0; i < bd.ntools; ++i) {
8721 MachO::build_tool_version bv = obj->getBuildToolVersion(i);
8722 PrintBuildToolVersion(bv);
8723 }
8724}
8725
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008726static void PrintSourceVersionCommand(MachO::source_version_command sd) {
8727 outs() << " cmd LC_SOURCE_VERSION\n";
8728 outs() << " cmdsize " << sd.cmdsize;
8729 if (sd.cmdsize != sizeof(struct MachO::source_version_command))
8730 outs() << " Incorrect size\n";
8731 else
8732 outs() << "\n";
8733 uint64_t a = (sd.version >> 40) & 0xffffff;
8734 uint64_t b = (sd.version >> 30) & 0x3ff;
8735 uint64_t c = (sd.version >> 20) & 0x3ff;
8736 uint64_t d = (sd.version >> 10) & 0x3ff;
8737 uint64_t e = sd.version & 0x3ff;
8738 outs() << " version " << a << "." << b;
8739 if (e != 0)
8740 outs() << "." << c << "." << d << "." << e;
8741 else if (d != 0)
8742 outs() << "." << c << "." << d;
8743 else if (c != 0)
8744 outs() << "." << c;
8745 outs() << "\n";
8746}
8747
8748static void PrintEntryPointCommand(MachO::entry_point_command ep) {
8749 outs() << " cmd LC_MAIN\n";
8750 outs() << " cmdsize " << ep.cmdsize;
8751 if (ep.cmdsize != sizeof(struct MachO::entry_point_command))
8752 outs() << " Incorrect size\n";
8753 else
8754 outs() << "\n";
8755 outs() << " entryoff " << ep.entryoff << "\n";
8756 outs() << " stacksize " << ep.stacksize << "\n";
8757}
8758
Kevin Enderby0804f4672014-12-16 23:25:52 +00008759static void PrintEncryptionInfoCommand(MachO::encryption_info_command ec,
8760 uint32_t object_size) {
8761 outs() << " cmd LC_ENCRYPTION_INFO\n";
8762 outs() << " cmdsize " << ec.cmdsize;
8763 if (ec.cmdsize != sizeof(struct MachO::encryption_info_command))
8764 outs() << " Incorrect size\n";
8765 else
8766 outs() << "\n";
8767 outs() << " cryptoff " << ec.cryptoff;
8768 if (ec.cryptoff > object_size)
8769 outs() << " (past end of file)\n";
8770 else
8771 outs() << "\n";
8772 outs() << " cryptsize " << ec.cryptsize;
8773 if (ec.cryptsize > object_size)
8774 outs() << " (past end of file)\n";
8775 else
8776 outs() << "\n";
8777 outs() << " cryptid " << ec.cryptid << "\n";
8778}
8779
Kevin Enderby57538292014-12-17 01:01:30 +00008780static void PrintEncryptionInfoCommand64(MachO::encryption_info_command_64 ec,
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008781 uint32_t object_size) {
Kevin Enderby57538292014-12-17 01:01:30 +00008782 outs() << " cmd LC_ENCRYPTION_INFO_64\n";
8783 outs() << " cmdsize " << ec.cmdsize;
8784 if (ec.cmdsize != sizeof(struct MachO::encryption_info_command_64))
8785 outs() << " Incorrect size\n";
8786 else
8787 outs() << "\n";
8788 outs() << " cryptoff " << ec.cryptoff;
8789 if (ec.cryptoff > object_size)
8790 outs() << " (past end of file)\n";
8791 else
8792 outs() << "\n";
8793 outs() << " cryptsize " << ec.cryptsize;
8794 if (ec.cryptsize > object_size)
8795 outs() << " (past end of file)\n";
8796 else
8797 outs() << "\n";
8798 outs() << " cryptid " << ec.cryptid << "\n";
8799 outs() << " pad " << ec.pad << "\n";
8800}
8801
Kevin Enderbyd0b6b7f2014-12-18 00:53:40 +00008802static void PrintLinkerOptionCommand(MachO::linker_option_command lo,
8803 const char *Ptr) {
8804 outs() << " cmd LC_LINKER_OPTION\n";
8805 outs() << " cmdsize " << lo.cmdsize;
8806 if (lo.cmdsize < sizeof(struct MachO::linker_option_command))
8807 outs() << " Incorrect size\n";
8808 else
8809 outs() << "\n";
8810 outs() << " count " << lo.count << "\n";
8811 const char *string = Ptr + sizeof(struct MachO::linker_option_command);
8812 uint32_t left = lo.cmdsize - sizeof(struct MachO::linker_option_command);
8813 uint32_t i = 0;
8814 while (left > 0) {
8815 while (*string == '\0' && left > 0) {
8816 string++;
8817 left--;
8818 }
8819 if (left > 0) {
8820 i++;
8821 outs() << " string #" << i << " " << format("%.*s\n", left, string);
David Majnemerd4449ed2014-12-20 08:24:43 +00008822 uint32_t NullPos = StringRef(string, left).find('\0');
8823 uint32_t len = std::min(NullPos, left) + 1;
Kevin Enderbyd0b6b7f2014-12-18 00:53:40 +00008824 string += len;
8825 left -= len;
8826 }
8827 }
8828 if (lo.count != i)
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008829 outs() << " count " << lo.count << " does not match number of strings "
8830 << i << "\n";
Kevin Enderbyd0b6b7f2014-12-18 00:53:40 +00008831}
8832
Kevin Enderbyb4b79312014-12-18 19:24:35 +00008833static void PrintSubFrameworkCommand(MachO::sub_framework_command sub,
8834 const char *Ptr) {
8835 outs() << " cmd LC_SUB_FRAMEWORK\n";
8836 outs() << " cmdsize " << sub.cmdsize;
8837 if (sub.cmdsize < sizeof(struct MachO::sub_framework_command))
8838 outs() << " Incorrect size\n";
8839 else
8840 outs() << "\n";
8841 if (sub.umbrella < sub.cmdsize) {
8842 const char *P = Ptr + sub.umbrella;
8843 outs() << " umbrella " << P << " (offset " << sub.umbrella << ")\n";
8844 } else {
8845 outs() << " umbrella ?(bad offset " << sub.umbrella << ")\n";
8846 }
8847}
8848
Kevin Enderbya2bd8d92014-12-18 23:13:26 +00008849static void PrintSubUmbrellaCommand(MachO::sub_umbrella_command sub,
8850 const char *Ptr) {
8851 outs() << " cmd LC_SUB_UMBRELLA\n";
8852 outs() << " cmdsize " << sub.cmdsize;
8853 if (sub.cmdsize < sizeof(struct MachO::sub_umbrella_command))
8854 outs() << " Incorrect size\n";
8855 else
8856 outs() << "\n";
8857 if (sub.sub_umbrella < sub.cmdsize) {
8858 const char *P = Ptr + sub.sub_umbrella;
8859 outs() << " sub_umbrella " << P << " (offset " << sub.sub_umbrella << ")\n";
8860 } else {
8861 outs() << " sub_umbrella ?(bad offset " << sub.sub_umbrella << ")\n";
8862 }
8863}
8864
Kevin Enderby36c8d3a2014-12-19 19:48:16 +00008865static void PrintSubLibraryCommand(MachO::sub_library_command sub,
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008866 const char *Ptr) {
Kevin Enderby36c8d3a2014-12-19 19:48:16 +00008867 outs() << " cmd LC_SUB_LIBRARY\n";
8868 outs() << " cmdsize " << sub.cmdsize;
8869 if (sub.cmdsize < sizeof(struct MachO::sub_library_command))
8870 outs() << " Incorrect size\n";
8871 else
8872 outs() << "\n";
8873 if (sub.sub_library < sub.cmdsize) {
8874 const char *P = Ptr + sub.sub_library;
8875 outs() << " sub_library " << P << " (offset " << sub.sub_library << ")\n";
8876 } else {
8877 outs() << " sub_library ?(bad offset " << sub.sub_library << ")\n";
8878 }
8879}
8880
Kevin Enderby186eac32014-12-19 21:06:24 +00008881static void PrintSubClientCommand(MachO::sub_client_command sub,
8882 const char *Ptr) {
8883 outs() << " cmd LC_SUB_CLIENT\n";
8884 outs() << " cmdsize " << sub.cmdsize;
8885 if (sub.cmdsize < sizeof(struct MachO::sub_client_command))
8886 outs() << " Incorrect size\n";
8887 else
8888 outs() << "\n";
8889 if (sub.client < sub.cmdsize) {
8890 const char *P = Ptr + sub.client;
8891 outs() << " client " << P << " (offset " << sub.client << ")\n";
8892 } else {
8893 outs() << " client ?(bad offset " << sub.client << ")\n";
8894 }
8895}
Kevin Enderby36c8d3a2014-12-19 19:48:16 +00008896
Kevin Enderby52e4ce42014-12-19 22:25:22 +00008897static void PrintRoutinesCommand(MachO::routines_command r) {
8898 outs() << " cmd LC_ROUTINES\n";
8899 outs() << " cmdsize " << r.cmdsize;
8900 if (r.cmdsize != sizeof(struct MachO::routines_command))
8901 outs() << " Incorrect size\n";
8902 else
8903 outs() << "\n";
8904 outs() << " init_address " << format("0x%08" PRIx32, r.init_address) << "\n";
8905 outs() << " init_module " << r.init_module << "\n";
8906 outs() << " reserved1 " << r.reserved1 << "\n";
8907 outs() << " reserved2 " << r.reserved2 << "\n";
8908 outs() << " reserved3 " << r.reserved3 << "\n";
8909 outs() << " reserved4 " << r.reserved4 << "\n";
8910 outs() << " reserved5 " << r.reserved5 << "\n";
8911 outs() << " reserved6 " << r.reserved6 << "\n";
8912}
8913
8914static void PrintRoutinesCommand64(MachO::routines_command_64 r) {
8915 outs() << " cmd LC_ROUTINES_64\n";
8916 outs() << " cmdsize " << r.cmdsize;
8917 if (r.cmdsize != sizeof(struct MachO::routines_command_64))
8918 outs() << " Incorrect size\n";
8919 else
8920 outs() << "\n";
8921 outs() << " init_address " << format("0x%016" PRIx64, r.init_address) << "\n";
8922 outs() << " init_module " << r.init_module << "\n";
8923 outs() << " reserved1 " << r.reserved1 << "\n";
8924 outs() << " reserved2 " << r.reserved2 << "\n";
8925 outs() << " reserved3 " << r.reserved3 << "\n";
8926 outs() << " reserved4 " << r.reserved4 << "\n";
8927 outs() << " reserved5 " << r.reserved5 << "\n";
8928 outs() << " reserved6 " << r.reserved6 << "\n";
8929}
8930
Kevin Enderbyc3a035d2017-01-23 21:13:29 +00008931static void Print_x86_thread_state32_t(MachO::x86_thread_state32_t &cpu32) {
8932 outs() << "\t eax " << format("0x%08" PRIx32, cpu32.eax);
8933 outs() << " ebx " << format("0x%08" PRIx32, cpu32.ebx);
8934 outs() << " ecx " << format("0x%08" PRIx32, cpu32.ecx);
8935 outs() << " edx " << format("0x%08" PRIx32, cpu32.edx) << "\n";
8936 outs() << "\t edi " << format("0x%08" PRIx32, cpu32.edi);
8937 outs() << " esi " << format("0x%08" PRIx32, cpu32.esi);
8938 outs() << " ebp " << format("0x%08" PRIx32, cpu32.ebp);
8939 outs() << " esp " << format("0x%08" PRIx32, cpu32.esp) << "\n";
8940 outs() << "\t ss " << format("0x%08" PRIx32, cpu32.ss);
8941 outs() << " eflags " << format("0x%08" PRIx32, cpu32.eflags);
8942 outs() << " eip " << format("0x%08" PRIx32, cpu32.eip);
8943 outs() << " cs " << format("0x%08" PRIx32, cpu32.cs) << "\n";
8944 outs() << "\t ds " << format("0x%08" PRIx32, cpu32.ds);
8945 outs() << " es " << format("0x%08" PRIx32, cpu32.es);
8946 outs() << " fs " << format("0x%08" PRIx32, cpu32.fs);
8947 outs() << " gs " << format("0x%08" PRIx32, cpu32.gs) << "\n";
8948}
8949
Kevin Enderby48ef5342014-12-23 22:56:39 +00008950static void Print_x86_thread_state64_t(MachO::x86_thread_state64_t &cpu64) {
8951 outs() << " rax " << format("0x%016" PRIx64, cpu64.rax);
8952 outs() << " rbx " << format("0x%016" PRIx64, cpu64.rbx);
8953 outs() << " rcx " << format("0x%016" PRIx64, cpu64.rcx) << "\n";
8954 outs() << " rdx " << format("0x%016" PRIx64, cpu64.rdx);
8955 outs() << " rdi " << format("0x%016" PRIx64, cpu64.rdi);
8956 outs() << " rsi " << format("0x%016" PRIx64, cpu64.rsi) << "\n";
8957 outs() << " rbp " << format("0x%016" PRIx64, cpu64.rbp);
8958 outs() << " rsp " << format("0x%016" PRIx64, cpu64.rsp);
8959 outs() << " r8 " << format("0x%016" PRIx64, cpu64.r8) << "\n";
8960 outs() << " r9 " << format("0x%016" PRIx64, cpu64.r9);
8961 outs() << " r10 " << format("0x%016" PRIx64, cpu64.r10);
8962 outs() << " r11 " << format("0x%016" PRIx64, cpu64.r11) << "\n";
8963 outs() << " r12 " << format("0x%016" PRIx64, cpu64.r12);
8964 outs() << " r13 " << format("0x%016" PRIx64, cpu64.r13);
8965 outs() << " r14 " << format("0x%016" PRIx64, cpu64.r14) << "\n";
8966 outs() << " r15 " << format("0x%016" PRIx64, cpu64.r15);
8967 outs() << " rip " << format("0x%016" PRIx64, cpu64.rip) << "\n";
8968 outs() << "rflags " << format("0x%016" PRIx64, cpu64.rflags);
8969 outs() << " cs " << format("0x%016" PRIx64, cpu64.cs);
8970 outs() << " fs " << format("0x%016" PRIx64, cpu64.fs) << "\n";
8971 outs() << " gs " << format("0x%016" PRIx64, cpu64.gs) << "\n";
8972}
8973
Kevin Enderby227df342014-12-23 23:43:59 +00008974static void Print_mmst_reg(MachO::mmst_reg_t &r) {
Kevin Enderby48ef5342014-12-23 22:56:39 +00008975 uint32_t f;
8976 outs() << "\t mmst_reg ";
8977 for (f = 0; f < 10; f++)
8978 outs() << format("%02" PRIx32, (r.mmst_reg[f] & 0xff)) << " ";
8979 outs() << "\n";
8980 outs() << "\t mmst_rsrv ";
8981 for (f = 0; f < 6; f++)
8982 outs() << format("%02" PRIx32, (r.mmst_rsrv[f] & 0xff)) << " ";
8983 outs() << "\n";
8984}
8985
Kevin Enderbyaefb0032014-12-24 00:16:51 +00008986static void Print_xmm_reg(MachO::xmm_reg_t &r) {
Kevin Enderby48ef5342014-12-23 22:56:39 +00008987 uint32_t f;
8988 outs() << "\t xmm_reg ";
8989 for (f = 0; f < 16; f++)
8990 outs() << format("%02" PRIx32, (r.xmm_reg[f] & 0xff)) << " ";
8991 outs() << "\n";
8992}
8993
8994static void Print_x86_float_state_t(MachO::x86_float_state64_t &fpu) {
8995 outs() << "\t fpu_reserved[0] " << fpu.fpu_reserved[0];
8996 outs() << " fpu_reserved[1] " << fpu.fpu_reserved[1] << "\n";
8997 outs() << "\t control: invalid " << fpu.fpu_fcw.invalid;
8998 outs() << " denorm " << fpu.fpu_fcw.denorm;
8999 outs() << " zdiv " << fpu.fpu_fcw.zdiv;
9000 outs() << " ovrfl " << fpu.fpu_fcw.ovrfl;
9001 outs() << " undfl " << fpu.fpu_fcw.undfl;
9002 outs() << " precis " << fpu.fpu_fcw.precis << "\n";
9003 outs() << "\t\t pc ";
9004 if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_24B)
9005 outs() << "FP_PREC_24B ";
9006 else if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_53B)
9007 outs() << "FP_PREC_53B ";
9008 else if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_64B)
9009 outs() << "FP_PREC_64B ";
9010 else
9011 outs() << fpu.fpu_fcw.pc << " ";
9012 outs() << "rc ";
9013 if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_NEAR)
9014 outs() << "FP_RND_NEAR ";
9015 else if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_DOWN)
9016 outs() << "FP_RND_DOWN ";
9017 else if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_UP)
9018 outs() << "FP_RND_UP ";
9019 else if (fpu.fpu_fcw.rc == MachO::x86_FP_CHOP)
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009020 outs() << "FP_CHOP ";
Kevin Enderby48ef5342014-12-23 22:56:39 +00009021 outs() << "\n";
9022 outs() << "\t status: invalid " << fpu.fpu_fsw.invalid;
9023 outs() << " denorm " << fpu.fpu_fsw.denorm;
9024 outs() << " zdiv " << fpu.fpu_fsw.zdiv;
9025 outs() << " ovrfl " << fpu.fpu_fsw.ovrfl;
9026 outs() << " undfl " << fpu.fpu_fsw.undfl;
9027 outs() << " precis " << fpu.fpu_fsw.precis;
9028 outs() << " stkflt " << fpu.fpu_fsw.stkflt << "\n";
9029 outs() << "\t errsumm " << fpu.fpu_fsw.errsumm;
9030 outs() << " c0 " << fpu.fpu_fsw.c0;
9031 outs() << " c1 " << fpu.fpu_fsw.c1;
9032 outs() << " c2 " << fpu.fpu_fsw.c2;
9033 outs() << " tos " << fpu.fpu_fsw.tos;
9034 outs() << " c3 " << fpu.fpu_fsw.c3;
9035 outs() << " busy " << fpu.fpu_fsw.busy << "\n";
9036 outs() << "\t fpu_ftw " << format("0x%02" PRIx32, fpu.fpu_ftw);
9037 outs() << " fpu_rsrv1 " << format("0x%02" PRIx32, fpu.fpu_rsrv1);
9038 outs() << " fpu_fop " << format("0x%04" PRIx32, fpu.fpu_fop);
9039 outs() << " fpu_ip " << format("0x%08" PRIx32, fpu.fpu_ip) << "\n";
9040 outs() << "\t fpu_cs " << format("0x%04" PRIx32, fpu.fpu_cs);
9041 outs() << " fpu_rsrv2 " << format("0x%04" PRIx32, fpu.fpu_rsrv2);
9042 outs() << " fpu_dp " << format("0x%08" PRIx32, fpu.fpu_dp);
9043 outs() << " fpu_ds " << format("0x%04" PRIx32, fpu.fpu_ds) << "\n";
9044 outs() << "\t fpu_rsrv3 " << format("0x%04" PRIx32, fpu.fpu_rsrv3);
9045 outs() << " fpu_mxcsr " << format("0x%08" PRIx32, fpu.fpu_mxcsr);
9046 outs() << " fpu_mxcsrmask " << format("0x%08" PRIx32, fpu.fpu_mxcsrmask);
9047 outs() << "\n";
9048 outs() << "\t fpu_stmm0:\n";
9049 Print_mmst_reg(fpu.fpu_stmm0);
9050 outs() << "\t fpu_stmm1:\n";
9051 Print_mmst_reg(fpu.fpu_stmm1);
9052 outs() << "\t fpu_stmm2:\n";
9053 Print_mmst_reg(fpu.fpu_stmm2);
9054 outs() << "\t fpu_stmm3:\n";
9055 Print_mmst_reg(fpu.fpu_stmm3);
9056 outs() << "\t fpu_stmm4:\n";
9057 Print_mmst_reg(fpu.fpu_stmm4);
9058 outs() << "\t fpu_stmm5:\n";
9059 Print_mmst_reg(fpu.fpu_stmm5);
9060 outs() << "\t fpu_stmm6:\n";
9061 Print_mmst_reg(fpu.fpu_stmm6);
9062 outs() << "\t fpu_stmm7:\n";
9063 Print_mmst_reg(fpu.fpu_stmm7);
9064 outs() << "\t fpu_xmm0:\n";
9065 Print_xmm_reg(fpu.fpu_xmm0);
9066 outs() << "\t fpu_xmm1:\n";
9067 Print_xmm_reg(fpu.fpu_xmm1);
9068 outs() << "\t fpu_xmm2:\n";
9069 Print_xmm_reg(fpu.fpu_xmm2);
9070 outs() << "\t fpu_xmm3:\n";
9071 Print_xmm_reg(fpu.fpu_xmm3);
9072 outs() << "\t fpu_xmm4:\n";
9073 Print_xmm_reg(fpu.fpu_xmm4);
9074 outs() << "\t fpu_xmm5:\n";
9075 Print_xmm_reg(fpu.fpu_xmm5);
9076 outs() << "\t fpu_xmm6:\n";
9077 Print_xmm_reg(fpu.fpu_xmm6);
9078 outs() << "\t fpu_xmm7:\n";
9079 Print_xmm_reg(fpu.fpu_xmm7);
9080 outs() << "\t fpu_xmm8:\n";
9081 Print_xmm_reg(fpu.fpu_xmm8);
9082 outs() << "\t fpu_xmm9:\n";
9083 Print_xmm_reg(fpu.fpu_xmm9);
9084 outs() << "\t fpu_xmm10:\n";
9085 Print_xmm_reg(fpu.fpu_xmm10);
9086 outs() << "\t fpu_xmm11:\n";
9087 Print_xmm_reg(fpu.fpu_xmm11);
9088 outs() << "\t fpu_xmm12:\n";
9089 Print_xmm_reg(fpu.fpu_xmm12);
9090 outs() << "\t fpu_xmm13:\n";
9091 Print_xmm_reg(fpu.fpu_xmm13);
9092 outs() << "\t fpu_xmm14:\n";
9093 Print_xmm_reg(fpu.fpu_xmm14);
9094 outs() << "\t fpu_xmm15:\n";
9095 Print_xmm_reg(fpu.fpu_xmm15);
9096 outs() << "\t fpu_rsrv4:\n";
9097 for (uint32_t f = 0; f < 6; f++) {
9098 outs() << "\t ";
9099 for (uint32_t g = 0; g < 16; g++)
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009100 outs() << format("%02" PRIx32, fpu.fpu_rsrv4[f * g]) << " ";
Kevin Enderby48ef5342014-12-23 22:56:39 +00009101 outs() << "\n";
9102 }
9103 outs() << "\t fpu_reserved1 " << format("0x%08" PRIx32, fpu.fpu_reserved1);
9104 outs() << "\n";
9105}
9106
9107static void Print_x86_exception_state_t(MachO::x86_exception_state64_t &exc64) {
9108 outs() << "\t trapno " << format("0x%08" PRIx32, exc64.trapno);
9109 outs() << " err " << format("0x%08" PRIx32, exc64.err);
9110 outs() << " faultvaddr " << format("0x%016" PRIx64, exc64.faultvaddr) << "\n";
9111}
9112
Kevin Enderby41c9c002016-10-21 18:22:35 +00009113static void Print_arm_thread_state32_t(MachO::arm_thread_state32_t &cpu32) {
9114 outs() << "\t r0 " << format("0x%08" PRIx32, cpu32.r[0]);
9115 outs() << " r1 " << format("0x%08" PRIx32, cpu32.r[1]);
9116 outs() << " r2 " << format("0x%08" PRIx32, cpu32.r[2]);
9117 outs() << " r3 " << format("0x%08" PRIx32, cpu32.r[3]) << "\n";
9118 outs() << "\t r4 " << format("0x%08" PRIx32, cpu32.r[4]);
9119 outs() << " r5 " << format("0x%08" PRIx32, cpu32.r[5]);
9120 outs() << " r6 " << format("0x%08" PRIx32, cpu32.r[6]);
9121 outs() << " r7 " << format("0x%08" PRIx32, cpu32.r[7]) << "\n";
9122 outs() << "\t r8 " << format("0x%08" PRIx32, cpu32.r[8]);
9123 outs() << " r9 " << format("0x%08" PRIx32, cpu32.r[9]);
9124 outs() << " r10 " << format("0x%08" PRIx32, cpu32.r[10]);
9125 outs() << " r11 " << format("0x%08" PRIx32, cpu32.r[11]) << "\n";
9126 outs() << "\t r12 " << format("0x%08" PRIx32, cpu32.r[12]);
9127 outs() << " sp " << format("0x%08" PRIx32, cpu32.sp);
9128 outs() << " lr " << format("0x%08" PRIx32, cpu32.lr);
9129 outs() << " pc " << format("0x%08" PRIx32, cpu32.pc) << "\n";
9130 outs() << "\t cpsr " << format("0x%08" PRIx32, cpu32.cpsr) << "\n";
9131}
9132
Kevin Enderby7747cb52016-11-03 20:51:28 +00009133static void Print_arm_thread_state64_t(MachO::arm_thread_state64_t &cpu64) {
9134 outs() << "\t x0 " << format("0x%016" PRIx64, cpu64.x[0]);
9135 outs() << " x1 " << format("0x%016" PRIx64, cpu64.x[1]);
9136 outs() << " x2 " << format("0x%016" PRIx64, cpu64.x[2]) << "\n";
9137 outs() << "\t x3 " << format("0x%016" PRIx64, cpu64.x[3]);
9138 outs() << " x4 " << format("0x%016" PRIx64, cpu64.x[4]);
9139 outs() << " x5 " << format("0x%016" PRIx64, cpu64.x[5]) << "\n";
9140 outs() << "\t x6 " << format("0x%016" PRIx64, cpu64.x[6]);
9141 outs() << " x7 " << format("0x%016" PRIx64, cpu64.x[7]);
9142 outs() << " x8 " << format("0x%016" PRIx64, cpu64.x[8]) << "\n";
9143 outs() << "\t x9 " << format("0x%016" PRIx64, cpu64.x[9]);
9144 outs() << " x10 " << format("0x%016" PRIx64, cpu64.x[10]);
9145 outs() << " x11 " << format("0x%016" PRIx64, cpu64.x[11]) << "\n";
9146 outs() << "\t x12 " << format("0x%016" PRIx64, cpu64.x[12]);
9147 outs() << " x13 " << format("0x%016" PRIx64, cpu64.x[13]);
9148 outs() << " x14 " << format("0x%016" PRIx64, cpu64.x[14]) << "\n";
9149 outs() << "\t x15 " << format("0x%016" PRIx64, cpu64.x[15]);
9150 outs() << " x16 " << format("0x%016" PRIx64, cpu64.x[16]);
9151 outs() << " x17 " << format("0x%016" PRIx64, cpu64.x[17]) << "\n";
9152 outs() << "\t x18 " << format("0x%016" PRIx64, cpu64.x[18]);
9153 outs() << " x19 " << format("0x%016" PRIx64, cpu64.x[19]);
9154 outs() << " x20 " << format("0x%016" PRIx64, cpu64.x[20]) << "\n";
9155 outs() << "\t x21 " << format("0x%016" PRIx64, cpu64.x[21]);
9156 outs() << " x22 " << format("0x%016" PRIx64, cpu64.x[22]);
9157 outs() << " x23 " << format("0x%016" PRIx64, cpu64.x[23]) << "\n";
9158 outs() << "\t x24 " << format("0x%016" PRIx64, cpu64.x[24]);
9159 outs() << " x25 " << format("0x%016" PRIx64, cpu64.x[25]);
9160 outs() << " x26 " << format("0x%016" PRIx64, cpu64.x[26]) << "\n";
9161 outs() << "\t x27 " << format("0x%016" PRIx64, cpu64.x[27]);
9162 outs() << " x28 " << format("0x%016" PRIx64, cpu64.x[28]);
9163 outs() << " fp " << format("0x%016" PRIx64, cpu64.fp) << "\n";
9164 outs() << "\t lr " << format("0x%016" PRIx64, cpu64.lr);
9165 outs() << " sp " << format("0x%016" PRIx64, cpu64.sp);
9166 outs() << " pc " << format("0x%016" PRIx64, cpu64.pc) << "\n";
9167 outs() << "\t cpsr " << format("0x%08" PRIx32, cpu64.cpsr) << "\n";
9168}
9169
Kevin Enderby48ef5342014-12-23 22:56:39 +00009170static void PrintThreadCommand(MachO::thread_command t, const char *Ptr,
9171 bool isLittleEndian, uint32_t cputype) {
9172 if (t.cmd == MachO::LC_THREAD)
9173 outs() << " cmd LC_THREAD\n";
9174 else if (t.cmd == MachO::LC_UNIXTHREAD)
9175 outs() << " cmd LC_UNIXTHREAD\n";
9176 else
9177 outs() << " cmd " << t.cmd << " (unknown)\n";
9178 outs() << " cmdsize " << t.cmdsize;
9179 if (t.cmdsize < sizeof(struct MachO::thread_command) + 2 * sizeof(uint32_t))
9180 outs() << " Incorrect size\n";
9181 else
9182 outs() << "\n";
9183
9184 const char *begin = Ptr + sizeof(struct MachO::thread_command);
9185 const char *end = Ptr + t.cmdsize;
9186 uint32_t flavor, count, left;
Kevin Enderbyc3a035d2017-01-23 21:13:29 +00009187 if (cputype == MachO::CPU_TYPE_I386) {
9188 while (begin < end) {
9189 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9190 memcpy((char *)&flavor, begin, sizeof(uint32_t));
9191 begin += sizeof(uint32_t);
9192 } else {
9193 flavor = 0;
9194 begin = end;
9195 }
9196 if (isLittleEndian != sys::IsLittleEndianHost)
9197 sys::swapByteOrder(flavor);
9198 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9199 memcpy((char *)&count, begin, sizeof(uint32_t));
9200 begin += sizeof(uint32_t);
9201 } else {
9202 count = 0;
9203 begin = end;
9204 }
9205 if (isLittleEndian != sys::IsLittleEndianHost)
9206 sys::swapByteOrder(count);
9207 if (flavor == MachO::x86_THREAD_STATE32) {
9208 outs() << " flavor i386_THREAD_STATE\n";
9209 if (count == MachO::x86_THREAD_STATE32_COUNT)
9210 outs() << " count i386_THREAD_STATE_COUNT\n";
9211 else
9212 outs() << " count " << count
9213 << " (not x86_THREAD_STATE32_COUNT)\n";
9214 MachO::x86_thread_state32_t cpu32;
9215 left = end - begin;
9216 if (left >= sizeof(MachO::x86_thread_state32_t)) {
9217 memcpy(&cpu32, begin, sizeof(MachO::x86_thread_state32_t));
9218 begin += sizeof(MachO::x86_thread_state32_t);
9219 } else {
9220 memset(&cpu32, '\0', sizeof(MachO::x86_thread_state32_t));
9221 memcpy(&cpu32, begin, left);
9222 begin += left;
9223 }
9224 if (isLittleEndian != sys::IsLittleEndianHost)
9225 swapStruct(cpu32);
9226 Print_x86_thread_state32_t(cpu32);
9227 } else if (flavor == MachO::x86_THREAD_STATE) {
9228 outs() << " flavor x86_THREAD_STATE\n";
9229 if (count == MachO::x86_THREAD_STATE_COUNT)
9230 outs() << " count x86_THREAD_STATE_COUNT\n";
9231 else
9232 outs() << " count " << count
9233 << " (not x86_THREAD_STATE_COUNT)\n";
9234 struct MachO::x86_thread_state_t ts;
9235 left = end - begin;
9236 if (left >= sizeof(MachO::x86_thread_state_t)) {
9237 memcpy(&ts, begin, sizeof(MachO::x86_thread_state_t));
9238 begin += sizeof(MachO::x86_thread_state_t);
9239 } else {
9240 memset(&ts, '\0', sizeof(MachO::x86_thread_state_t));
9241 memcpy(&ts, begin, left);
9242 begin += left;
9243 }
9244 if (isLittleEndian != sys::IsLittleEndianHost)
9245 swapStruct(ts);
9246 if (ts.tsh.flavor == MachO::x86_THREAD_STATE32) {
9247 outs() << "\t tsh.flavor x86_THREAD_STATE32 ";
9248 if (ts.tsh.count == MachO::x86_THREAD_STATE32_COUNT)
9249 outs() << "tsh.count x86_THREAD_STATE32_COUNT\n";
9250 else
9251 outs() << "tsh.count " << ts.tsh.count
9252 << " (not x86_THREAD_STATE32_COUNT\n";
9253 Print_x86_thread_state32_t(ts.uts.ts32);
9254 } else {
9255 outs() << "\t tsh.flavor " << ts.tsh.flavor << " tsh.count "
9256 << ts.tsh.count << "\n";
9257 }
9258 } else {
9259 outs() << " flavor " << flavor << " (unknown)\n";
9260 outs() << " count " << count << "\n";
9261 outs() << " state (unknown)\n";
9262 begin += count * sizeof(uint32_t);
9263 }
9264 }
9265 } else if (cputype == MachO::CPU_TYPE_X86_64) {
Kevin Enderby48ef5342014-12-23 22:56:39 +00009266 while (begin < end) {
9267 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9268 memcpy((char *)&flavor, begin, sizeof(uint32_t));
9269 begin += sizeof(uint32_t);
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009270 } else {
Kevin Enderby48ef5342014-12-23 22:56:39 +00009271 flavor = 0;
9272 begin = end;
9273 }
9274 if (isLittleEndian != sys::IsLittleEndianHost)
9275 sys::swapByteOrder(flavor);
9276 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9277 memcpy((char *)&count, begin, sizeof(uint32_t));
9278 begin += sizeof(uint32_t);
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009279 } else {
Kevin Enderby48ef5342014-12-23 22:56:39 +00009280 count = 0;
9281 begin = end;
9282 }
9283 if (isLittleEndian != sys::IsLittleEndianHost)
9284 sys::swapByteOrder(count);
9285 if (flavor == MachO::x86_THREAD_STATE64) {
9286 outs() << " flavor x86_THREAD_STATE64\n";
9287 if (count == MachO::x86_THREAD_STATE64_COUNT)
9288 outs() << " count x86_THREAD_STATE64_COUNT\n";
9289 else
9290 outs() << " count " << count
9291 << " (not x86_THREAD_STATE64_COUNT)\n";
9292 MachO::x86_thread_state64_t cpu64;
9293 left = end - begin;
9294 if (left >= sizeof(MachO::x86_thread_state64_t)) {
9295 memcpy(&cpu64, begin, sizeof(MachO::x86_thread_state64_t));
9296 begin += sizeof(MachO::x86_thread_state64_t);
9297 } else {
9298 memset(&cpu64, '\0', sizeof(MachO::x86_thread_state64_t));
9299 memcpy(&cpu64, begin, left);
9300 begin += left;
9301 }
9302 if (isLittleEndian != sys::IsLittleEndianHost)
9303 swapStruct(cpu64);
9304 Print_x86_thread_state64_t(cpu64);
9305 } else if (flavor == MachO::x86_THREAD_STATE) {
9306 outs() << " flavor x86_THREAD_STATE\n";
9307 if (count == MachO::x86_THREAD_STATE_COUNT)
9308 outs() << " count x86_THREAD_STATE_COUNT\n";
9309 else
9310 outs() << " count " << count
9311 << " (not x86_THREAD_STATE_COUNT)\n";
9312 struct MachO::x86_thread_state_t ts;
9313 left = end - begin;
9314 if (left >= sizeof(MachO::x86_thread_state_t)) {
9315 memcpy(&ts, begin, sizeof(MachO::x86_thread_state_t));
9316 begin += sizeof(MachO::x86_thread_state_t);
9317 } else {
9318 memset(&ts, '\0', sizeof(MachO::x86_thread_state_t));
9319 memcpy(&ts, begin, left);
9320 begin += left;
9321 }
9322 if (isLittleEndian != sys::IsLittleEndianHost)
9323 swapStruct(ts);
9324 if (ts.tsh.flavor == MachO::x86_THREAD_STATE64) {
9325 outs() << "\t tsh.flavor x86_THREAD_STATE64 ";
9326 if (ts.tsh.count == MachO::x86_THREAD_STATE64_COUNT)
9327 outs() << "tsh.count x86_THREAD_STATE64_COUNT\n";
9328 else
9329 outs() << "tsh.count " << ts.tsh.count
9330 << " (not x86_THREAD_STATE64_COUNT\n";
9331 Print_x86_thread_state64_t(ts.uts.ts64);
9332 } else {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009333 outs() << "\t tsh.flavor " << ts.tsh.flavor << " tsh.count "
9334 << ts.tsh.count << "\n";
Kevin Enderby48ef5342014-12-23 22:56:39 +00009335 }
9336 } else if (flavor == MachO::x86_FLOAT_STATE) {
9337 outs() << " flavor x86_FLOAT_STATE\n";
9338 if (count == MachO::x86_FLOAT_STATE_COUNT)
9339 outs() << " count x86_FLOAT_STATE_COUNT\n";
9340 else
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009341 outs() << " count " << count << " (not x86_FLOAT_STATE_COUNT)\n";
Kevin Enderby48ef5342014-12-23 22:56:39 +00009342 struct MachO::x86_float_state_t fs;
9343 left = end - begin;
9344 if (left >= sizeof(MachO::x86_float_state_t)) {
9345 memcpy(&fs, begin, sizeof(MachO::x86_float_state_t));
9346 begin += sizeof(MachO::x86_float_state_t);
9347 } else {
9348 memset(&fs, '\0', sizeof(MachO::x86_float_state_t));
9349 memcpy(&fs, begin, left);
9350 begin += left;
9351 }
9352 if (isLittleEndian != sys::IsLittleEndianHost)
9353 swapStruct(fs);
9354 if (fs.fsh.flavor == MachO::x86_FLOAT_STATE64) {
9355 outs() << "\t fsh.flavor x86_FLOAT_STATE64 ";
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009356 if (fs.fsh.count == MachO::x86_FLOAT_STATE64_COUNT)
Kevin Enderby48ef5342014-12-23 22:56:39 +00009357 outs() << "fsh.count x86_FLOAT_STATE64_COUNT\n";
9358 else
9359 outs() << "fsh.count " << fs.fsh.count
9360 << " (not x86_FLOAT_STATE64_COUNT\n";
9361 Print_x86_float_state_t(fs.ufs.fs64);
9362 } else {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009363 outs() << "\t fsh.flavor " << fs.fsh.flavor << " fsh.count "
9364 << fs.fsh.count << "\n";
Kevin Enderby48ef5342014-12-23 22:56:39 +00009365 }
9366 } else if (flavor == MachO::x86_EXCEPTION_STATE) {
9367 outs() << " flavor x86_EXCEPTION_STATE\n";
9368 if (count == MachO::x86_EXCEPTION_STATE_COUNT)
9369 outs() << " count x86_EXCEPTION_STATE_COUNT\n";
9370 else
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009371 outs() << " count " << count
Kevin Enderby48ef5342014-12-23 22:56:39 +00009372 << " (not x86_EXCEPTION_STATE_COUNT)\n";
9373 struct MachO::x86_exception_state_t es;
9374 left = end - begin;
9375 if (left >= sizeof(MachO::x86_exception_state_t)) {
9376 memcpy(&es, begin, sizeof(MachO::x86_exception_state_t));
9377 begin += sizeof(MachO::x86_exception_state_t);
9378 } else {
9379 memset(&es, '\0', sizeof(MachO::x86_exception_state_t));
9380 memcpy(&es, begin, left);
9381 begin += left;
9382 }
9383 if (isLittleEndian != sys::IsLittleEndianHost)
9384 swapStruct(es);
9385 if (es.esh.flavor == MachO::x86_EXCEPTION_STATE64) {
9386 outs() << "\t esh.flavor x86_EXCEPTION_STATE64\n";
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009387 if (es.esh.count == MachO::x86_EXCEPTION_STATE64_COUNT)
Kevin Enderby48ef5342014-12-23 22:56:39 +00009388 outs() << "\t esh.count x86_EXCEPTION_STATE64_COUNT\n";
9389 else
9390 outs() << "\t esh.count " << es.esh.count
9391 << " (not x86_EXCEPTION_STATE64_COUNT\n";
9392 Print_x86_exception_state_t(es.ues.es64);
9393 } else {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009394 outs() << "\t esh.flavor " << es.esh.flavor << " esh.count "
9395 << es.esh.count << "\n";
Kevin Enderby48ef5342014-12-23 22:56:39 +00009396 }
Kevin Enderby299cd892018-03-08 23:10:38 +00009397 } else if (flavor == MachO::x86_EXCEPTION_STATE64) {
9398 outs() << " flavor x86_EXCEPTION_STATE64\n";
9399 if (count == MachO::x86_EXCEPTION_STATE64_COUNT)
9400 outs() << " count x86_EXCEPTION_STATE64_COUNT\n";
9401 else
9402 outs() << " count " << count
9403 << " (not x86_EXCEPTION_STATE64_COUNT)\n";
9404 struct MachO::x86_exception_state64_t es64;
9405 left = end - begin;
9406 if (left >= sizeof(MachO::x86_exception_state64_t)) {
9407 memcpy(&es64, begin, sizeof(MachO::x86_exception_state64_t));
9408 begin += sizeof(MachO::x86_exception_state64_t);
9409 } else {
9410 memset(&es64, '\0', sizeof(MachO::x86_exception_state64_t));
9411 memcpy(&es64, begin, left);
9412 begin += left;
9413 }
9414 if (isLittleEndian != sys::IsLittleEndianHost)
9415 swapStruct(es64);
9416 Print_x86_exception_state_t(es64);
Kevin Enderby48ef5342014-12-23 22:56:39 +00009417 } else {
9418 outs() << " flavor " << flavor << " (unknown)\n";
9419 outs() << " count " << count << "\n";
9420 outs() << " state (unknown)\n";
9421 begin += count * sizeof(uint32_t);
9422 }
9423 }
Kevin Enderby41c9c002016-10-21 18:22:35 +00009424 } else if (cputype == MachO::CPU_TYPE_ARM) {
9425 while (begin < end) {
9426 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9427 memcpy((char *)&flavor, begin, sizeof(uint32_t));
9428 begin += sizeof(uint32_t);
9429 } else {
9430 flavor = 0;
9431 begin = end;
9432 }
9433 if (isLittleEndian != sys::IsLittleEndianHost)
9434 sys::swapByteOrder(flavor);
9435 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9436 memcpy((char *)&count, begin, sizeof(uint32_t));
9437 begin += sizeof(uint32_t);
9438 } else {
9439 count = 0;
9440 begin = end;
9441 }
9442 if (isLittleEndian != sys::IsLittleEndianHost)
9443 sys::swapByteOrder(count);
9444 if (flavor == MachO::ARM_THREAD_STATE) {
9445 outs() << " flavor ARM_THREAD_STATE\n";
9446 if (count == MachO::ARM_THREAD_STATE_COUNT)
9447 outs() << " count ARM_THREAD_STATE_COUNT\n";
9448 else
9449 outs() << " count " << count
9450 << " (not ARM_THREAD_STATE_COUNT)\n";
9451 MachO::arm_thread_state32_t cpu32;
9452 left = end - begin;
9453 if (left >= sizeof(MachO::arm_thread_state32_t)) {
9454 memcpy(&cpu32, begin, sizeof(MachO::arm_thread_state32_t));
9455 begin += sizeof(MachO::arm_thread_state32_t);
9456 } else {
9457 memset(&cpu32, '\0', sizeof(MachO::arm_thread_state32_t));
9458 memcpy(&cpu32, begin, left);
9459 begin += left;
9460 }
9461 if (isLittleEndian != sys::IsLittleEndianHost)
9462 swapStruct(cpu32);
9463 Print_arm_thread_state32_t(cpu32);
9464 } else {
9465 outs() << " flavor " << flavor << " (unknown)\n";
9466 outs() << " count " << count << "\n";
9467 outs() << " state (unknown)\n";
9468 begin += count * sizeof(uint32_t);
9469 }
9470 }
Kevin Enderby7747cb52016-11-03 20:51:28 +00009471 } else if (cputype == MachO::CPU_TYPE_ARM64) {
9472 while (begin < end) {
9473 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9474 memcpy((char *)&flavor, begin, sizeof(uint32_t));
9475 begin += sizeof(uint32_t);
9476 } else {
9477 flavor = 0;
9478 begin = end;
9479 }
9480 if (isLittleEndian != sys::IsLittleEndianHost)
9481 sys::swapByteOrder(flavor);
9482 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9483 memcpy((char *)&count, begin, sizeof(uint32_t));
9484 begin += sizeof(uint32_t);
9485 } else {
9486 count = 0;
9487 begin = end;
9488 }
9489 if (isLittleEndian != sys::IsLittleEndianHost)
9490 sys::swapByteOrder(count);
9491 if (flavor == MachO::ARM_THREAD_STATE64) {
9492 outs() << " flavor ARM_THREAD_STATE64\n";
9493 if (count == MachO::ARM_THREAD_STATE64_COUNT)
9494 outs() << " count ARM_THREAD_STATE64_COUNT\n";
9495 else
9496 outs() << " count " << count
9497 << " (not ARM_THREAD_STATE64_COUNT)\n";
9498 MachO::arm_thread_state64_t cpu64;
9499 left = end - begin;
9500 if (left >= sizeof(MachO::arm_thread_state64_t)) {
9501 memcpy(&cpu64, begin, sizeof(MachO::arm_thread_state64_t));
9502 begin += sizeof(MachO::arm_thread_state64_t);
9503 } else {
9504 memset(&cpu64, '\0', sizeof(MachO::arm_thread_state64_t));
9505 memcpy(&cpu64, begin, left);
9506 begin += left;
9507 }
9508 if (isLittleEndian != sys::IsLittleEndianHost)
9509 swapStruct(cpu64);
9510 Print_arm_thread_state64_t(cpu64);
9511 } else {
9512 outs() << " flavor " << flavor << " (unknown)\n";
9513 outs() << " count " << count << "\n";
9514 outs() << " state (unknown)\n";
9515 begin += count * sizeof(uint32_t);
9516 }
9517 }
Kevin Enderby48ef5342014-12-23 22:56:39 +00009518 } else {
9519 while (begin < end) {
9520 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9521 memcpy((char *)&flavor, begin, sizeof(uint32_t));
9522 begin += sizeof(uint32_t);
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009523 } else {
Kevin Enderby48ef5342014-12-23 22:56:39 +00009524 flavor = 0;
9525 begin = end;
9526 }
9527 if (isLittleEndian != sys::IsLittleEndianHost)
9528 sys::swapByteOrder(flavor);
9529 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9530 memcpy((char *)&count, begin, sizeof(uint32_t));
9531 begin += sizeof(uint32_t);
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009532 } else {
Kevin Enderby48ef5342014-12-23 22:56:39 +00009533 count = 0;
9534 begin = end;
9535 }
9536 if (isLittleEndian != sys::IsLittleEndianHost)
9537 sys::swapByteOrder(count);
9538 outs() << " flavor " << flavor << "\n";
9539 outs() << " count " << count << "\n";
9540 outs() << " state (Unknown cputype/cpusubtype)\n";
9541 begin += count * sizeof(uint32_t);
9542 }
9543 }
9544}
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009545
Kevin Enderby8ae63c12014-09-04 16:54:47 +00009546static void PrintDylibCommand(MachO::dylib_command dl, const char *Ptr) {
9547 if (dl.cmd == MachO::LC_ID_DYLIB)
9548 outs() << " cmd LC_ID_DYLIB\n";
9549 else if (dl.cmd == MachO::LC_LOAD_DYLIB)
9550 outs() << " cmd LC_LOAD_DYLIB\n";
9551 else if (dl.cmd == MachO::LC_LOAD_WEAK_DYLIB)
9552 outs() << " cmd LC_LOAD_WEAK_DYLIB\n";
9553 else if (dl.cmd == MachO::LC_REEXPORT_DYLIB)
9554 outs() << " cmd LC_REEXPORT_DYLIB\n";
9555 else if (dl.cmd == MachO::LC_LAZY_LOAD_DYLIB)
9556 outs() << " cmd LC_LAZY_LOAD_DYLIB\n";
9557 else if (dl.cmd == MachO::LC_LOAD_UPWARD_DYLIB)
9558 outs() << " cmd LC_LOAD_UPWARD_DYLIB\n";
9559 else
9560 outs() << " cmd " << dl.cmd << " (unknown)\n";
9561 outs() << " cmdsize " << dl.cmdsize;
9562 if (dl.cmdsize < sizeof(struct MachO::dylib_command))
9563 outs() << " Incorrect size\n";
9564 else
9565 outs() << "\n";
9566 if (dl.dylib.name < dl.cmdsize) {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00009567 const char *P = (const char *)(Ptr) + dl.dylib.name;
Kevin Enderby8ae63c12014-09-04 16:54:47 +00009568 outs() << " name " << P << " (offset " << dl.dylib.name << ")\n";
9569 } else {
9570 outs() << " name ?(bad offset " << dl.dylib.name << ")\n";
9571 }
9572 outs() << " time stamp " << dl.dylib.timestamp << " ";
9573 time_t t = dl.dylib.timestamp;
9574 outs() << ctime(&t);
9575 outs() << " current version ";
9576 if (dl.dylib.current_version == 0xffffffff)
9577 outs() << "n/a\n";
9578 else
9579 outs() << ((dl.dylib.current_version >> 16) & 0xffff) << "."
9580 << ((dl.dylib.current_version >> 8) & 0xff) << "."
9581 << (dl.dylib.current_version & 0xff) << "\n";
9582 outs() << "compatibility version ";
9583 if (dl.dylib.compatibility_version == 0xffffffff)
9584 outs() << "n/a\n";
9585 else
9586 outs() << ((dl.dylib.compatibility_version >> 16) & 0xffff) << "."
9587 << ((dl.dylib.compatibility_version >> 8) & 0xff) << "."
9588 << (dl.dylib.compatibility_version & 0xff) << "\n";
9589}
9590
9591static void PrintLinkEditDataCommand(MachO::linkedit_data_command ld,
9592 uint32_t object_size) {
9593 if (ld.cmd == MachO::LC_CODE_SIGNATURE)
Kevin Enderby1be37a32016-04-28 21:07:20 +00009594 outs() << " cmd LC_CODE_SIGNATURE\n";
Kevin Enderby8ae63c12014-09-04 16:54:47 +00009595 else if (ld.cmd == MachO::LC_SEGMENT_SPLIT_INFO)
9596 outs() << " cmd LC_SEGMENT_SPLIT_INFO\n";
9597 else if (ld.cmd == MachO::LC_FUNCTION_STARTS)
9598 outs() << " cmd LC_FUNCTION_STARTS\n";
9599 else if (ld.cmd == MachO::LC_DATA_IN_CODE)
9600 outs() << " cmd LC_DATA_IN_CODE\n";
9601 else if (ld.cmd == MachO::LC_DYLIB_CODE_SIGN_DRS)
9602 outs() << " cmd LC_DYLIB_CODE_SIGN_DRS\n";
9603 else if (ld.cmd == MachO::LC_LINKER_OPTIMIZATION_HINT)
9604 outs() << " cmd LC_LINKER_OPTIMIZATION_HINT\n";
9605 else
9606 outs() << " cmd " << ld.cmd << " (?)\n";
9607 outs() << " cmdsize " << ld.cmdsize;
9608 if (ld.cmdsize != sizeof(struct MachO::linkedit_data_command))
9609 outs() << " Incorrect size\n";
9610 else
9611 outs() << "\n";
9612 outs() << " dataoff " << ld.dataoff;
9613 if (ld.dataoff > object_size)
9614 outs() << " (past end of file)\n";
9615 else
9616 outs() << "\n";
9617 outs() << " datasize " << ld.datasize;
9618 uint64_t big_size = ld.dataoff;
9619 big_size += ld.datasize;
9620 if (big_size > object_size)
9621 outs() << " (past end of file)\n";
9622 else
9623 outs() << "\n";
9624}
9625
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00009626static void PrintLoadCommands(const MachOObjectFile *Obj, uint32_t filetype,
9627 uint32_t cputype, bool verbose) {
Kevin Enderby956366c2014-08-29 22:30:52 +00009628 StringRef Buf = Obj->getData();
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00009629 unsigned Index = 0;
9630 for (const auto &Command : Obj->load_commands()) {
9631 outs() << "Load command " << Index++ << "\n";
Kevin Enderby956366c2014-08-29 22:30:52 +00009632 if (Command.C.cmd == MachO::LC_SEGMENT) {
9633 MachO::segment_command SLC = Obj->getSegmentLoadCommand(Command);
9634 const char *sg_segname = SLC.segname;
9635 PrintSegmentCommand(SLC.cmd, SLC.cmdsize, SLC.segname, SLC.vmaddr,
9636 SLC.vmsize, SLC.fileoff, SLC.filesize, SLC.maxprot,
9637 SLC.initprot, SLC.nsects, SLC.flags, Buf.size(),
9638 verbose);
9639 for (unsigned j = 0; j < SLC.nsects; j++) {
Kevin Enderbyc9713382014-12-16 01:14:45 +00009640 MachO::section S = Obj->getSection(Command, j);
Kevin Enderby956366c2014-08-29 22:30:52 +00009641 PrintSection(S.sectname, S.segname, S.addr, S.size, S.offset, S.align,
9642 S.reloff, S.nreloc, S.flags, S.reserved1, S.reserved2,
9643 SLC.cmd, sg_segname, filetype, Buf.size(), verbose);
9644 }
9645 } else if (Command.C.cmd == MachO::LC_SEGMENT_64) {
9646 MachO::segment_command_64 SLC_64 = Obj->getSegment64LoadCommand(Command);
9647 const char *sg_segname = SLC_64.segname;
9648 PrintSegmentCommand(SLC_64.cmd, SLC_64.cmdsize, SLC_64.segname,
9649 SLC_64.vmaddr, SLC_64.vmsize, SLC_64.fileoff,
9650 SLC_64.filesize, SLC_64.maxprot, SLC_64.initprot,
9651 SLC_64.nsects, SLC_64.flags, Buf.size(), verbose);
9652 for (unsigned j = 0; j < SLC_64.nsects; j++) {
9653 MachO::section_64 S_64 = Obj->getSection64(Command, j);
9654 PrintSection(S_64.sectname, S_64.segname, S_64.addr, S_64.size,
9655 S_64.offset, S_64.align, S_64.reloff, S_64.nreloc,
9656 S_64.flags, S_64.reserved1, S_64.reserved2, SLC_64.cmd,
9657 sg_segname, filetype, Buf.size(), verbose);
9658 }
9659 } else if (Command.C.cmd == MachO::LC_SYMTAB) {
9660 MachO::symtab_command Symtab = Obj->getSymtabLoadCommand();
David Majnemer73cc6ff2014-11-13 19:48:56 +00009661 PrintSymtabLoadCommand(Symtab, Obj->is64Bit(), Buf.size());
Kevin Enderby956366c2014-08-29 22:30:52 +00009662 } else if (Command.C.cmd == MachO::LC_DYSYMTAB) {
9663 MachO::dysymtab_command Dysymtab = Obj->getDysymtabLoadCommand();
9664 MachO::symtab_command Symtab = Obj->getSymtabLoadCommand();
David Majnemer73cc6ff2014-11-13 19:48:56 +00009665 PrintDysymtabLoadCommand(Dysymtab, Symtab.nsyms, Buf.size(),
9666 Obj->is64Bit());
Kevin Enderby8ae63c12014-09-04 16:54:47 +00009667 } else if (Command.C.cmd == MachO::LC_DYLD_INFO ||
9668 Command.C.cmd == MachO::LC_DYLD_INFO_ONLY) {
9669 MachO::dyld_info_command DyldInfo = Obj->getDyldInfoLoadCommand(Command);
9670 PrintDyldInfoLoadCommand(DyldInfo, Buf.size());
9671 } else if (Command.C.cmd == MachO::LC_LOAD_DYLINKER ||
9672 Command.C.cmd == MachO::LC_ID_DYLINKER ||
9673 Command.C.cmd == MachO::LC_DYLD_ENVIRONMENT) {
9674 MachO::dylinker_command Dyld = Obj->getDylinkerCommand(Command);
9675 PrintDyldLoadCommand(Dyld, Command.Ptr);
9676 } else if (Command.C.cmd == MachO::LC_UUID) {
9677 MachO::uuid_command Uuid = Obj->getUuidCommand(Command);
9678 PrintUuidLoadCommand(Uuid);
Jean-Daniel Dupas00cc1f52014-12-04 07:37:02 +00009679 } else if (Command.C.cmd == MachO::LC_RPATH) {
9680 MachO::rpath_command Rpath = Obj->getRpathCommand(Command);
9681 PrintRpathLoadCommand(Rpath, Command.Ptr);
Kevin Enderby1ff0ecc2014-12-16 21:48:27 +00009682 } else if (Command.C.cmd == MachO::LC_VERSION_MIN_MACOSX ||
Tim Northoverbfbfb122015-11-02 21:26:58 +00009683 Command.C.cmd == MachO::LC_VERSION_MIN_IPHONEOS ||
9684 Command.C.cmd == MachO::LC_VERSION_MIN_TVOS ||
9685 Command.C.cmd == MachO::LC_VERSION_MIN_WATCHOS) {
Kevin Enderby8ae63c12014-09-04 16:54:47 +00009686 MachO::version_min_command Vd = Obj->getVersionMinLoadCommand(Command);
9687 PrintVersionMinLoadCommand(Vd);
Kevin Enderbya4579c42017-01-19 17:36:31 +00009688 } else if (Command.C.cmd == MachO::LC_NOTE) {
9689 MachO::note_command Nt = Obj->getNoteLoadCommand(Command);
9690 PrintNoteLoadCommand(Nt);
Steven Wu5b54a422017-01-23 20:07:55 +00009691 } else if (Command.C.cmd == MachO::LC_BUILD_VERSION) {
9692 MachO::build_version_command Bv =
9693 Obj->getBuildVersionLoadCommand(Command);
9694 PrintBuildVersionLoadCommand(Obj, Bv);
Kevin Enderby8ae63c12014-09-04 16:54:47 +00009695 } else if (Command.C.cmd == MachO::LC_SOURCE_VERSION) {
9696 MachO::source_version_command Sd = Obj->getSourceVersionCommand(Command);
9697 PrintSourceVersionCommand(Sd);
9698 } else if (Command.C.cmd == MachO::LC_MAIN) {
9699 MachO::entry_point_command Ep = Obj->getEntryPointCommand(Command);
9700 PrintEntryPointCommand(Ep);
Kevin Enderby0804f4672014-12-16 23:25:52 +00009701 } else if (Command.C.cmd == MachO::LC_ENCRYPTION_INFO) {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009702 MachO::encryption_info_command Ei =
9703 Obj->getEncryptionInfoCommand(Command);
Kevin Enderby0804f4672014-12-16 23:25:52 +00009704 PrintEncryptionInfoCommand(Ei, Buf.size());
Kevin Enderby57538292014-12-17 01:01:30 +00009705 } else if (Command.C.cmd == MachO::LC_ENCRYPTION_INFO_64) {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009706 MachO::encryption_info_command_64 Ei =
9707 Obj->getEncryptionInfoCommand64(Command);
Kevin Enderby57538292014-12-17 01:01:30 +00009708 PrintEncryptionInfoCommand64(Ei, Buf.size());
Kevin Enderbyd0b6b7f2014-12-18 00:53:40 +00009709 } else if (Command.C.cmd == MachO::LC_LINKER_OPTION) {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009710 MachO::linker_option_command Lo =
9711 Obj->getLinkerOptionLoadCommand(Command);
Kevin Enderbyd0b6b7f2014-12-18 00:53:40 +00009712 PrintLinkerOptionCommand(Lo, Command.Ptr);
Kevin Enderbyb4b79312014-12-18 19:24:35 +00009713 } else if (Command.C.cmd == MachO::LC_SUB_FRAMEWORK) {
9714 MachO::sub_framework_command Sf = Obj->getSubFrameworkCommand(Command);
9715 PrintSubFrameworkCommand(Sf, Command.Ptr);
Kevin Enderbya2bd8d92014-12-18 23:13:26 +00009716 } else if (Command.C.cmd == MachO::LC_SUB_UMBRELLA) {
9717 MachO::sub_umbrella_command Sf = Obj->getSubUmbrellaCommand(Command);
9718 PrintSubUmbrellaCommand(Sf, Command.Ptr);
Kevin Enderby36c8d3a2014-12-19 19:48:16 +00009719 } else if (Command.C.cmd == MachO::LC_SUB_LIBRARY) {
9720 MachO::sub_library_command Sl = Obj->getSubLibraryCommand(Command);
9721 PrintSubLibraryCommand(Sl, Command.Ptr);
Kevin Enderby186eac32014-12-19 21:06:24 +00009722 } else if (Command.C.cmd == MachO::LC_SUB_CLIENT) {
9723 MachO::sub_client_command Sc = Obj->getSubClientCommand(Command);
9724 PrintSubClientCommand(Sc, Command.Ptr);
Kevin Enderby52e4ce42014-12-19 22:25:22 +00009725 } else if (Command.C.cmd == MachO::LC_ROUTINES) {
9726 MachO::routines_command Rc = Obj->getRoutinesCommand(Command);
9727 PrintRoutinesCommand(Rc);
9728 } else if (Command.C.cmd == MachO::LC_ROUTINES_64) {
9729 MachO::routines_command_64 Rc = Obj->getRoutinesCommand64(Command);
9730 PrintRoutinesCommand64(Rc);
Kevin Enderby48ef5342014-12-23 22:56:39 +00009731 } else if (Command.C.cmd == MachO::LC_THREAD ||
9732 Command.C.cmd == MachO::LC_UNIXTHREAD) {
9733 MachO::thread_command Tc = Obj->getThreadCommand(Command);
9734 PrintThreadCommand(Tc, Command.Ptr, Obj->isLittleEndian(), cputype);
Nick Kledzik15558912014-10-16 18:58:20 +00009735 } else if (Command.C.cmd == MachO::LC_LOAD_DYLIB ||
9736 Command.C.cmd == MachO::LC_ID_DYLIB ||
9737 Command.C.cmd == MachO::LC_LOAD_WEAK_DYLIB ||
9738 Command.C.cmd == MachO::LC_REEXPORT_DYLIB ||
9739 Command.C.cmd == MachO::LC_LAZY_LOAD_DYLIB ||
9740 Command.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB) {
Kevin Enderby8ae63c12014-09-04 16:54:47 +00009741 MachO::dylib_command Dl = Obj->getDylibIDLoadCommand(Command);
9742 PrintDylibCommand(Dl, Command.Ptr);
9743 } else if (Command.C.cmd == MachO::LC_CODE_SIGNATURE ||
9744 Command.C.cmd == MachO::LC_SEGMENT_SPLIT_INFO ||
9745 Command.C.cmd == MachO::LC_FUNCTION_STARTS ||
9746 Command.C.cmd == MachO::LC_DATA_IN_CODE ||
9747 Command.C.cmd == MachO::LC_DYLIB_CODE_SIGN_DRS ||
9748 Command.C.cmd == MachO::LC_LINKER_OPTIMIZATION_HINT) {
9749 MachO::linkedit_data_command Ld =
9750 Obj->getLinkeditDataLoadCommand(Command);
9751 PrintLinkEditDataCommand(Ld, Buf.size());
Kevin Enderby956366c2014-08-29 22:30:52 +00009752 } else {
9753 outs() << " cmd ?(" << format("0x%08" PRIx32, Command.C.cmd)
9754 << ")\n";
9755 outs() << " cmdsize " << Command.C.cmdsize << "\n";
9756 // TODO: get and print the raw bytes of the load command.
9757 }
9758 // TODO: print all the other kinds of load commands.
Kevin Enderby956366c2014-08-29 22:30:52 +00009759 }
9760}
9761
Kevin Enderby0ae163f2016-01-13 00:25:36 +00009762static void PrintMachHeader(const MachOObjectFile *Obj, bool verbose) {
Kevin Enderbyb76d3862014-08-22 20:35:18 +00009763 if (Obj->is64Bit()) {
9764 MachO::mach_header_64 H_64;
9765 H_64 = Obj->getHeader64();
9766 PrintMachHeader(H_64.magic, H_64.cputype, H_64.cpusubtype, H_64.filetype,
9767 H_64.ncmds, H_64.sizeofcmds, H_64.flags, verbose);
9768 } else {
9769 MachO::mach_header H;
9770 H = Obj->getHeader();
9771 PrintMachHeader(H.magic, H.cputype, H.cpusubtype, H.filetype, H.ncmds,
9772 H.sizeofcmds, H.flags, verbose);
9773 }
9774}
9775
9776void llvm::printMachOFileHeader(const object::ObjectFile *Obj) {
9777 const MachOObjectFile *file = dyn_cast<const MachOObjectFile>(Obj);
Kevin Enderby0ae163f2016-01-13 00:25:36 +00009778 PrintMachHeader(file, !NonVerbose);
9779}
9780
9781void llvm::printMachOLoadCommands(const object::ObjectFile *Obj) {
9782 const MachOObjectFile *file = dyn_cast<const MachOObjectFile>(Obj);
Kevin Enderby956366c2014-08-29 22:30:52 +00009783 uint32_t filetype = 0;
9784 uint32_t cputype = 0;
Kevin Enderby0ae163f2016-01-13 00:25:36 +00009785 if (file->is64Bit()) {
9786 MachO::mach_header_64 H_64;
9787 H_64 = file->getHeader64();
9788 filetype = H_64.filetype;
9789 cputype = H_64.cputype;
9790 } else {
9791 MachO::mach_header H;
9792 H = file->getHeader();
9793 filetype = H.filetype;
9794 cputype = H.cputype;
9795 }
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00009796 PrintLoadCommands(file, filetype, cputype, !NonVerbose);
Kevin Enderbyb76d3862014-08-22 20:35:18 +00009797}
Nick Kledzikd04bc352014-08-30 00:20:14 +00009798
9799//===----------------------------------------------------------------------===//
9800// export trie dumping
9801//===----------------------------------------------------------------------===//
9802
9803void llvm::printMachOExportsTrie(const object::MachOObjectFile *Obj) {
Kevin Enderby0d5ec112017-06-19 21:23:07 +00009804 uint64_t BaseSegmentAddress = 0;
9805 for (const auto &Command : Obj->load_commands()) {
9806 if (Command.C.cmd == MachO::LC_SEGMENT) {
9807 MachO::segment_command Seg = Obj->getSegmentLoadCommand(Command);
9808 if (Seg.fileoff == 0 && Seg.filesize != 0) {
9809 BaseSegmentAddress = Seg.vmaddr;
9810 break;
9811 }
9812 } else if (Command.C.cmd == MachO::LC_SEGMENT_64) {
9813 MachO::segment_command_64 Seg = Obj->getSegment64LoadCommand(Command);
9814 if (Seg.fileoff == 0 && Seg.filesize != 0) {
9815 BaseSegmentAddress = Seg.vmaddr;
9816 break;
9817 }
9818 }
9819 }
Kevin Enderby3e95bd22017-07-20 23:08:41 +00009820 Error Err = Error::success();
Alexander Shaposhnikove5740342017-07-29 00:30:45 +00009821 for (const llvm::object::ExportEntry &Entry : Obj->exports(Err)) {
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00009822 uint64_t Flags = Entry.flags();
Nick Kledzikd04bc352014-08-30 00:20:14 +00009823 bool ReExport = (Flags & MachO::EXPORT_SYMBOL_FLAGS_REEXPORT);
9824 bool WeakDef = (Flags & MachO::EXPORT_SYMBOL_FLAGS_WEAK_DEFINITION);
9825 bool ThreadLocal = ((Flags & MachO::EXPORT_SYMBOL_FLAGS_KIND_MASK) ==
9826 MachO::EXPORT_SYMBOL_FLAGS_KIND_THREAD_LOCAL);
9827 bool Abs = ((Flags & MachO::EXPORT_SYMBOL_FLAGS_KIND_MASK) ==
9828 MachO::EXPORT_SYMBOL_FLAGS_KIND_ABSOLUTE);
9829 bool Resolver = (Flags & MachO::EXPORT_SYMBOL_FLAGS_STUB_AND_RESOLVER);
9830 if (ReExport)
9831 outs() << "[re-export] ";
9832 else
Kevin Enderbyb28ed012014-10-29 21:28:24 +00009833 outs() << format("0x%08llX ",
Kevin Enderby0d5ec112017-06-19 21:23:07 +00009834 Entry.address() + BaseSegmentAddress);
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00009835 outs() << Entry.name();
Nick Kledzikd04bc352014-08-30 00:20:14 +00009836 if (WeakDef || ThreadLocal || Resolver || Abs) {
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00009837 bool NeedsComma = false;
Nick Kledzik1d1ac4b2014-09-03 01:12:52 +00009838 outs() << " [";
Nick Kledzikd04bc352014-08-30 00:20:14 +00009839 if (WeakDef) {
9840 outs() << "weak_def";
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00009841 NeedsComma = true;
Nick Kledzikd04bc352014-08-30 00:20:14 +00009842 }
9843 if (ThreadLocal) {
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00009844 if (NeedsComma)
Nick Kledzikd04bc352014-08-30 00:20:14 +00009845 outs() << ", ";
9846 outs() << "per-thread";
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00009847 NeedsComma = true;
Nick Kledzikd04bc352014-08-30 00:20:14 +00009848 }
9849 if (Abs) {
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00009850 if (NeedsComma)
Nick Kledzikd04bc352014-08-30 00:20:14 +00009851 outs() << ", ";
9852 outs() << "absolute";
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00009853 NeedsComma = true;
Nick Kledzikd04bc352014-08-30 00:20:14 +00009854 }
9855 if (Resolver) {
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00009856 if (NeedsComma)
Nick Kledzikd04bc352014-08-30 00:20:14 +00009857 outs() << ", ";
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00009858 outs() << format("resolver=0x%08llX", Entry.other());
9859 NeedsComma = true;
Nick Kledzikd04bc352014-08-30 00:20:14 +00009860 }
9861 outs() << "]";
9862 }
9863 if (ReExport) {
9864 StringRef DylibName = "unknown";
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00009865 int Ordinal = Entry.other() - 1;
9866 Obj->getLibraryShortNameByIndex(Ordinal, DylibName);
9867 if (Entry.otherName().empty())
Nick Kledzikd04bc352014-08-30 00:20:14 +00009868 outs() << " (from " << DylibName << ")";
9869 else
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00009870 outs() << " (" << Entry.otherName() << " from " << DylibName << ")";
Nick Kledzikd04bc352014-08-30 00:20:14 +00009871 }
9872 outs() << "\n";
9873 }
Kevin Enderby3e95bd22017-07-20 23:08:41 +00009874 if (Err)
9875 report_error(Obj->getFileName(), std::move(Err));
Nick Kledzikd04bc352014-08-30 00:20:14 +00009876}
Nick Kledzikac431442014-09-12 21:34:15 +00009877
Nick Kledzikac431442014-09-12 21:34:15 +00009878//===----------------------------------------------------------------------===//
9879// rebase table dumping
9880//===----------------------------------------------------------------------===//
9881
Kevin Enderbya8d256c2017-03-20 19:46:55 +00009882void llvm::printMachORebaseTable(object::MachOObjectFile *Obj) {
Nick Kledzikac431442014-09-12 21:34:15 +00009883 outs() << "segment section address type\n";
Kevin Enderbya8d256c2017-03-20 19:46:55 +00009884 Error Err = Error::success();
9885 for (const llvm::object::MachORebaseEntry &Entry : Obj->rebaseTable(Err)) {
9886 StringRef SegmentName = Entry.segmentName();
9887 StringRef SectionName = Entry.sectionName();
9888 uint64_t Address = Entry.address();
Nick Kledzikac431442014-09-12 21:34:15 +00009889
9890 // Table lines look like: __DATA __nl_symbol_ptr 0x0000F00C pointer
Kevin Enderbyb28ed012014-10-29 21:28:24 +00009891 outs() << format("%-8s %-18s 0x%08" PRIX64 " %s\n",
9892 SegmentName.str().c_str(), SectionName.str().c_str(),
9893 Address, Entry.typeName().str().c_str());
Nick Kledzikac431442014-09-12 21:34:15 +00009894 }
Kevin Enderbya8d256c2017-03-20 19:46:55 +00009895 if (Err)
9896 report_error(Obj->getFileName(), std::move(Err));
Nick Kledzikac431442014-09-12 21:34:15 +00009897}
Nick Kledzik56ebef42014-09-16 01:41:51 +00009898
9899static StringRef ordinalName(const object::MachOObjectFile *Obj, int Ordinal) {
9900 StringRef DylibName;
9901 switch (Ordinal) {
9902 case MachO::BIND_SPECIAL_DYLIB_SELF:
9903 return "this-image";
9904 case MachO::BIND_SPECIAL_DYLIB_MAIN_EXECUTABLE:
9905 return "main-executable";
9906 case MachO::BIND_SPECIAL_DYLIB_FLAT_LOOKUP:
9907 return "flat-namespace";
9908 default:
Nick Kledzikabd29872014-09-16 22:03:13 +00009909 if (Ordinal > 0) {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00009910 std::error_code EC =
9911 Obj->getLibraryShortNameByIndex(Ordinal - 1, DylibName);
Nick Kledzikabd29872014-09-16 22:03:13 +00009912 if (EC)
Nick Kledzik51d2c2b2014-10-14 23:29:38 +00009913 return "<<bad library ordinal>>";
Nick Kledzikabd29872014-09-16 22:03:13 +00009914 return DylibName;
9915 }
Nick Kledzik56ebef42014-09-16 01:41:51 +00009916 }
Nick Kledzikabd29872014-09-16 22:03:13 +00009917 return "<<unknown special ordinal>>";
Nick Kledzik56ebef42014-09-16 01:41:51 +00009918}
9919
9920//===----------------------------------------------------------------------===//
9921// bind table dumping
9922//===----------------------------------------------------------------------===//
9923
Kevin Enderbya8d256c2017-03-20 19:46:55 +00009924void llvm::printMachOBindTable(object::MachOObjectFile *Obj) {
Nick Kledzik56ebef42014-09-16 01:41:51 +00009925 // Build table of sections so names can used in final output.
Nick Kledzik5ffacc12014-09-30 00:19:58 +00009926 outs() << "segment section address type "
9927 "addend dylib symbol\n";
Kevin Enderbyfeb63b92017-02-28 21:47:07 +00009928 Error Err = Error::success();
9929 for (const llvm::object::MachOBindEntry &Entry : Obj->bindTable(Err)) {
Kevin Enderbya8d256c2017-03-20 19:46:55 +00009930 StringRef SegmentName = Entry.segmentName();
9931 StringRef SectionName = Entry.sectionName();
9932 uint64_t Address = Entry.address();
Nick Kledzik56ebef42014-09-16 01:41:51 +00009933
9934 // Table lines look like:
9935 // __DATA __got 0x00012010 pointer 0 libSystem ___stack_chk_guard
Nick Kledzik5ffacc12014-09-30 00:19:58 +00009936 StringRef Attr;
Nick Kledzik56ebef42014-09-16 01:41:51 +00009937 if (Entry.flags() & MachO::BIND_SYMBOL_FLAGS_WEAK_IMPORT)
Nick Kledzik5ffacc12014-09-30 00:19:58 +00009938 Attr = " (weak_import)";
Kevin Enderbyb28ed012014-10-29 21:28:24 +00009939 outs() << left_justify(SegmentName, 8) << " "
Nick Kledzik5ffacc12014-09-30 00:19:58 +00009940 << left_justify(SectionName, 18) << " "
9941 << format_hex(Address, 10, true) << " "
9942 << left_justify(Entry.typeName(), 8) << " "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00009943 << format_decimal(Entry.addend(), 8) << " "
Nick Kledzik5ffacc12014-09-30 00:19:58 +00009944 << left_justify(ordinalName(Obj, Entry.ordinal()), 16) << " "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00009945 << Entry.symbolName() << Attr << "\n";
Nick Kledzik56ebef42014-09-16 01:41:51 +00009946 }
Kevin Enderbyfeb63b92017-02-28 21:47:07 +00009947 if (Err)
9948 report_error(Obj->getFileName(), std::move(Err));
Nick Kledzik56ebef42014-09-16 01:41:51 +00009949}
9950
9951//===----------------------------------------------------------------------===//
9952// lazy bind table dumping
9953//===----------------------------------------------------------------------===//
9954
Kevin Enderbya8d256c2017-03-20 19:46:55 +00009955void llvm::printMachOLazyBindTable(object::MachOObjectFile *Obj) {
Nick Kledzik5ffacc12014-09-30 00:19:58 +00009956 outs() << "segment section address "
9957 "dylib symbol\n";
Kevin Enderbyfeb63b92017-02-28 21:47:07 +00009958 Error Err = Error::success();
9959 for (const llvm::object::MachOBindEntry &Entry : Obj->lazyBindTable(Err)) {
Kevin Enderbya8d256c2017-03-20 19:46:55 +00009960 StringRef SegmentName = Entry.segmentName();
9961 StringRef SectionName = Entry.sectionName();
9962 uint64_t Address = Entry.address();
Nick Kledzik56ebef42014-09-16 01:41:51 +00009963
9964 // Table lines look like:
9965 // __DATA __got 0x00012010 libSystem ___stack_chk_guard
Kevin Enderbyb28ed012014-10-29 21:28:24 +00009966 outs() << left_justify(SegmentName, 8) << " "
Nick Kledzik5ffacc12014-09-30 00:19:58 +00009967 << left_justify(SectionName, 18) << " "
9968 << format_hex(Address, 10, true) << " "
9969 << left_justify(ordinalName(Obj, Entry.ordinal()), 16) << " "
Nick Kledzik56ebef42014-09-16 01:41:51 +00009970 << Entry.symbolName() << "\n";
9971 }
Kevin Enderbyfeb63b92017-02-28 21:47:07 +00009972 if (Err)
9973 report_error(Obj->getFileName(), std::move(Err));
Nick Kledzik56ebef42014-09-16 01:41:51 +00009974}
9975
Nick Kledzik56ebef42014-09-16 01:41:51 +00009976//===----------------------------------------------------------------------===//
9977// weak bind table dumping
9978//===----------------------------------------------------------------------===//
9979
Kevin Enderbya8d256c2017-03-20 19:46:55 +00009980void llvm::printMachOWeakBindTable(object::MachOObjectFile *Obj) {
Nick Kledzik5ffacc12014-09-30 00:19:58 +00009981 outs() << "segment section address "
9982 "type addend symbol\n";
Kevin Enderbyfeb63b92017-02-28 21:47:07 +00009983 Error Err = Error::success();
9984 for (const llvm::object::MachOBindEntry &Entry : Obj->weakBindTable(Err)) {
Nick Kledzik56ebef42014-09-16 01:41:51 +00009985 // Strong symbols don't have a location to update.
9986 if (Entry.flags() & MachO::BIND_SYMBOL_FLAGS_NON_WEAK_DEFINITION) {
Nick Kledzik5ffacc12014-09-30 00:19:58 +00009987 outs() << " strong "
Nick Kledzik56ebef42014-09-16 01:41:51 +00009988 << Entry.symbolName() << "\n";
9989 continue;
9990 }
Kevin Enderbya8d256c2017-03-20 19:46:55 +00009991 StringRef SegmentName = Entry.segmentName();
9992 StringRef SectionName = Entry.sectionName();
9993 uint64_t Address = Entry.address();
Nick Kledzik56ebef42014-09-16 01:41:51 +00009994
9995 // Table lines look like:
9996 // __DATA __data 0x00001000 pointer 0 _foo
Kevin Enderbyb28ed012014-10-29 21:28:24 +00009997 outs() << left_justify(SegmentName, 8) << " "
Nick Kledzik5ffacc12014-09-30 00:19:58 +00009998 << left_justify(SectionName, 18) << " "
9999 << format_hex(Address, 10, true) << " "
10000 << left_justify(Entry.typeName(), 8) << " "
Kevin Enderbyb28ed012014-10-29 21:28:24 +000010001 << format_decimal(Entry.addend(), 8) << " " << Entry.symbolName()
10002 << "\n";
Nick Kledzik56ebef42014-09-16 01:41:51 +000010003 }
Kevin Enderbyfeb63b92017-02-28 21:47:07 +000010004 if (Err)
10005 report_error(Obj->getFileName(), std::move(Err));
Nick Kledzik56ebef42014-09-16 01:41:51 +000010006}
10007
Kevin Enderby6f326ce2014-10-23 19:37:31 +000010008// get_dyld_bind_info_symbolname() is used for disassembly and passed an
10009// address, ReferenceValue, in the Mach-O file and looks in the dyld bind
10010// information for that address. If the address is found its binding symbol
10011// name is returned. If not nullptr is returned.
10012static const char *get_dyld_bind_info_symbolname(uint64_t ReferenceValue,
10013 struct DisassembleInfo *info) {
Kevin Enderby078be602014-10-23 19:53:12 +000010014 if (info->bindtable == nullptr) {
Saleem Abdulrasool1d84d9a2017-01-08 19:14:15 +000010015 info->bindtable = llvm::make_unique<SymbolAddressMap>();
Kevin Enderbyfeb63b92017-02-28 21:47:07 +000010016 Error Err = Error::success();
10017 for (const llvm::object::MachOBindEntry &Entry : info->O->bindTable(Err)) {
Kevin Enderbya8d256c2017-03-20 19:46:55 +000010018 uint64_t Address = Entry.address();
Kevin Enderby6f326ce2014-10-23 19:37:31 +000010019 StringRef name = Entry.symbolName();
10020 if (!name.empty())
Saleem Abdulrasool1d84d9a2017-01-08 19:14:15 +000010021 (*info->bindtable)[Address] = name;
Kevin Enderby6f326ce2014-10-23 19:37:31 +000010022 }
Kevin Enderbyfeb63b92017-02-28 21:47:07 +000010023 if (Err)
10024 report_error(info->O->getFileName(), std::move(Err));
Kevin Enderby6f326ce2014-10-23 19:37:31 +000010025 }
Saleem Abdulrasool1d84d9a2017-01-08 19:14:15 +000010026 auto name = info->bindtable->lookup(ReferenceValue);
10027 return !name.empty() ? name.data() : nullptr;
Kevin Enderby6f326ce2014-10-23 19:37:31 +000010028}
Michael Trent1854ecc2017-12-05 07:50:00 +000010029