blob: 142ad8f63718cad08f85f1e4ab142061070b6460 [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;
Jordan Rupprecht16a0de22018-12-20 00:57:06 +00001415 if (!DumpSegSectName.second.empty()) {
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001416 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 ||
Jordan Rupprecht16a0de22018-12-20 00:57:06 +00001585 (!FilterSections.empty())) {
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.
Jordan Rupprecht16a0de22018-12-20 00:57:06 +00001610 if (Disassemble || IndirectSymbols || !FilterSections.empty() || UnwindInfo)
Kevin Enderby844c4ac2016-11-15 23:07:41 +00001611 if (Error Err = MachOOF->checkSymbolTable())
1612 report_error(ArchiveName, FileName, std::move(Err), ArchitectureName);
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001613
Kevin Enderbyaf2999a2017-06-22 19:50:56 +00001614 if (Disassemble) {
1615 if (MachOOF->getHeader().filetype == MachO::MH_KEXT_BUNDLE &&
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +00001616 MachOOF->getHeader().cputype == MachO::CPU_TYPE_ARM64)
Kevin Enderbyaf2999a2017-06-22 19:50:56 +00001617 DisassembleMachO(FileName, MachOOF, "__TEXT_EXEC", "__text");
1618 else
1619 DisassembleMachO(FileName, MachOOF, "__TEXT", "__text");
1620 }
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +00001621 if (IndirectSymbols)
Kevin Enderbyf0640752015-03-13 17:56:32 +00001622 PrintIndirectSymbols(MachOOF, !NonVerbose);
Kevin Enderby69fe98d2015-01-23 18:52:17 +00001623 if (DataInCode)
Kevin Enderbyf0640752015-03-13 17:56:32 +00001624 PrintDataInCodeTable(MachOOF, !NonVerbose);
Kevin Enderby9a509442015-01-27 21:28:24 +00001625 if (LinkOptHints)
1626 PrintLinkOptHints(MachOOF);
Kevin Enderby98da6132015-01-20 21:47:46 +00001627 if (Relocations)
Michael Trenta1703b12017-12-15 17:57:40 +00001628 PrintRelocations(MachOOF, !NonVerbose);
Kevin Enderby98da6132015-01-20 21:47:46 +00001629 if (SectionHeaders)
1630 PrintSectionHeaders(MachOOF);
1631 if (SectionContents)
1632 PrintSectionContents(MachOOF);
Jordan Rupprecht16a0de22018-12-20 00:57:06 +00001633 if (!FilterSections.empty())
Kevin Enderby844c4ac2016-11-15 23:07:41 +00001634 DumpSectionContents(FileName, MachOOF, !NonVerbose);
Kevin Enderbycd66be52015-03-11 22:06:32 +00001635 if (InfoPlist)
Kevin Enderby844c4ac2016-11-15 23:07:41 +00001636 DumpInfoPlistSectionContents(FileName, MachOOF);
Kevin Enderbybc847fa2015-03-16 20:08:09 +00001637 if (DylibsUsed)
1638 PrintDylibs(MachOOF, false);
1639 if (DylibId)
1640 PrintDylibs(MachOOF, true);
Kevin Enderby844c4ac2016-11-15 23:07:41 +00001641 if (SymbolTable)
Kevin Enderby9acb1092016-05-31 20:35:34 +00001642 PrintSymbolTable(MachOOF, ArchiveName, ArchitectureName);
Kevin Enderby98da6132015-01-20 21:47:46 +00001643 if (UnwindInfo)
1644 printMachOUnwindInfo(MachOOF);
Kevin Enderby0ae163f2016-01-13 00:25:36 +00001645 if (PrivateHeaders) {
1646 printMachOFileHeader(MachOOF);
1647 printMachOLoadCommands(MachOOF);
1648 }
1649 if (FirstPrivateHeader)
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001650 printMachOFileHeader(MachOOF);
Kevin Enderby0fc11822015-04-01 20:57:01 +00001651 if (ObjcMetaData)
1652 printObjcMetaData(MachOOF, !NonVerbose);
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001653 if (ExportsTrie)
1654 printExportsTrie(MachOOF);
1655 if (Rebase)
1656 printRebaseTable(MachOOF);
1657 if (Bind)
1658 printBindTable(MachOOF);
1659 if (LazyBind)
1660 printLazyBindTable(MachOOF);
1661 if (WeakBind)
1662 printWeakBindTable(MachOOF);
Igor Laevsky03a670c2016-01-26 15:09:42 +00001663
1664 if (DwarfDumpType != DIDT_Null) {
Rafael Espindolac398e672017-07-19 22:27:28 +00001665 std::unique_ptr<DIContext> DICtx = DWARFContext::create(*MachOOF);
Igor Laevsky03a670c2016-01-26 15:09:42 +00001666 // Dump the complete DWARF structure.
Adrian Prantlf4bc1f72017-06-01 18:18:23 +00001667 DIDumpOptions DumpOpts;
1668 DumpOpts.DumpType = DwarfDumpType;
Adrian Prantlf4bc1f72017-06-01 18:18:23 +00001669 DICtx->dump(outs(), DumpOpts);
Igor Laevsky03a670c2016-01-26 15:09:42 +00001670 }
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001671}
1672
Kevin Enderby131d1772015-01-09 19:22:37 +00001673// printUnknownCPUType() helps print_fat_headers for unknown CPU's.
1674static void printUnknownCPUType(uint32_t cputype, uint32_t cpusubtype) {
1675 outs() << " cputype (" << cputype << ")\n";
1676 outs() << " cpusubtype (" << cpusubtype << ")\n";
1677}
1678
1679// printCPUType() helps print_fat_headers by printing the cputype and
1680// pusubtype (symbolically for the one's it knows about).
1681static void printCPUType(uint32_t cputype, uint32_t cpusubtype) {
1682 switch (cputype) {
1683 case MachO::CPU_TYPE_I386:
1684 switch (cpusubtype) {
1685 case MachO::CPU_SUBTYPE_I386_ALL:
1686 outs() << " cputype CPU_TYPE_I386\n";
1687 outs() << " cpusubtype CPU_SUBTYPE_I386_ALL\n";
1688 break;
1689 default:
1690 printUnknownCPUType(cputype, cpusubtype);
1691 break;
1692 }
1693 break;
1694 case MachO::CPU_TYPE_X86_64:
1695 switch (cpusubtype) {
1696 case MachO::CPU_SUBTYPE_X86_64_ALL:
1697 outs() << " cputype CPU_TYPE_X86_64\n";
1698 outs() << " cpusubtype CPU_SUBTYPE_X86_64_ALL\n";
1699 break;
1700 case MachO::CPU_SUBTYPE_X86_64_H:
1701 outs() << " cputype CPU_TYPE_X86_64\n";
1702 outs() << " cpusubtype CPU_SUBTYPE_X86_64_H\n";
1703 break;
1704 default:
1705 printUnknownCPUType(cputype, cpusubtype);
1706 break;
1707 }
1708 break;
1709 case MachO::CPU_TYPE_ARM:
1710 switch (cpusubtype) {
1711 case MachO::CPU_SUBTYPE_ARM_ALL:
1712 outs() << " cputype CPU_TYPE_ARM\n";
1713 outs() << " cpusubtype CPU_SUBTYPE_ARM_ALL\n";
1714 break;
1715 case MachO::CPU_SUBTYPE_ARM_V4T:
1716 outs() << " cputype CPU_TYPE_ARM\n";
1717 outs() << " cpusubtype CPU_SUBTYPE_ARM_V4T\n";
1718 break;
1719 case MachO::CPU_SUBTYPE_ARM_V5TEJ:
1720 outs() << " cputype CPU_TYPE_ARM\n";
1721 outs() << " cpusubtype CPU_SUBTYPE_ARM_V5TEJ\n";
1722 break;
1723 case MachO::CPU_SUBTYPE_ARM_XSCALE:
1724 outs() << " cputype CPU_TYPE_ARM\n";
1725 outs() << " cpusubtype CPU_SUBTYPE_ARM_XSCALE\n";
1726 break;
1727 case MachO::CPU_SUBTYPE_ARM_V6:
1728 outs() << " cputype CPU_TYPE_ARM\n";
1729 outs() << " cpusubtype CPU_SUBTYPE_ARM_V6\n";
1730 break;
1731 case MachO::CPU_SUBTYPE_ARM_V6M:
1732 outs() << " cputype CPU_TYPE_ARM\n";
1733 outs() << " cpusubtype CPU_SUBTYPE_ARM_V6M\n";
1734 break;
1735 case MachO::CPU_SUBTYPE_ARM_V7:
1736 outs() << " cputype CPU_TYPE_ARM\n";
1737 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7\n";
1738 break;
1739 case MachO::CPU_SUBTYPE_ARM_V7EM:
1740 outs() << " cputype CPU_TYPE_ARM\n";
1741 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7EM\n";
1742 break;
1743 case MachO::CPU_SUBTYPE_ARM_V7K:
1744 outs() << " cputype CPU_TYPE_ARM\n";
1745 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7K\n";
1746 break;
1747 case MachO::CPU_SUBTYPE_ARM_V7M:
1748 outs() << " cputype CPU_TYPE_ARM\n";
1749 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7M\n";
1750 break;
1751 case MachO::CPU_SUBTYPE_ARM_V7S:
1752 outs() << " cputype CPU_TYPE_ARM\n";
1753 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7S\n";
1754 break;
1755 default:
1756 printUnknownCPUType(cputype, cpusubtype);
1757 break;
1758 }
1759 break;
1760 case MachO::CPU_TYPE_ARM64:
1761 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
1762 case MachO::CPU_SUBTYPE_ARM64_ALL:
1763 outs() << " cputype CPU_TYPE_ARM64\n";
1764 outs() << " cpusubtype CPU_SUBTYPE_ARM64_ALL\n";
1765 break;
1766 default:
1767 printUnknownCPUType(cputype, cpusubtype);
1768 break;
1769 }
1770 break;
1771 default:
1772 printUnknownCPUType(cputype, cpusubtype);
1773 break;
1774 }
1775}
1776
1777static void printMachOUniversalHeaders(const object::MachOUniversalBinary *UB,
1778 bool verbose) {
1779 outs() << "Fat headers\n";
Kevin Enderby606a3382016-06-21 21:55:01 +00001780 if (verbose) {
1781 if (UB->getMagic() == MachO::FAT_MAGIC)
1782 outs() << "fat_magic FAT_MAGIC\n";
1783 else // UB->getMagic() == MachO::FAT_MAGIC_64
1784 outs() << "fat_magic FAT_MAGIC_64\n";
1785 } else
Kevin Enderby131d1772015-01-09 19:22:37 +00001786 outs() << "fat_magic " << format("0x%" PRIx32, MachO::FAT_MAGIC) << "\n";
1787
1788 uint32_t nfat_arch = UB->getNumberOfObjects();
1789 StringRef Buf = UB->getData();
1790 uint64_t size = Buf.size();
1791 uint64_t big_size = sizeof(struct MachO::fat_header) +
1792 nfat_arch * sizeof(struct MachO::fat_arch);
1793 outs() << "nfat_arch " << UB->getNumberOfObjects();
1794 if (nfat_arch == 0)
1795 outs() << " (malformed, contains zero architecture types)\n";
1796 else if (big_size > size)
1797 outs() << " (malformed, architectures past end of file)\n";
1798 else
1799 outs() << "\n";
1800
1801 for (uint32_t i = 0; i < nfat_arch; ++i) {
1802 MachOUniversalBinary::ObjectForArch OFA(UB, i);
1803 uint32_t cputype = OFA.getCPUType();
1804 uint32_t cpusubtype = OFA.getCPUSubType();
1805 outs() << "architecture ";
1806 for (uint32_t j = 0; i != 0 && j <= i - 1; j++) {
1807 MachOUniversalBinary::ObjectForArch other_OFA(UB, j);
1808 uint32_t other_cputype = other_OFA.getCPUType();
1809 uint32_t other_cpusubtype = other_OFA.getCPUSubType();
Kevin Enderby0512bd72015-01-09 21:55:03 +00001810 if (cputype != 0 && cpusubtype != 0 && cputype == other_cputype &&
Kevin Enderby131d1772015-01-09 19:22:37 +00001811 (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) ==
Kevin Enderby0512bd72015-01-09 21:55:03 +00001812 (other_cpusubtype & ~MachO::CPU_SUBTYPE_MASK)) {
Kevin Enderby131d1772015-01-09 19:22:37 +00001813 outs() << "(illegal duplicate architecture) ";
1814 break;
Kevin Enderby0512bd72015-01-09 21:55:03 +00001815 }
Kevin Enderby131d1772015-01-09 19:22:37 +00001816 }
1817 if (verbose) {
Kevin Enderby59343a92016-12-16 22:54:02 +00001818 outs() << OFA.getArchFlagName() << "\n";
Kevin Enderby131d1772015-01-09 19:22:37 +00001819 printCPUType(cputype, cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
1820 } else {
1821 outs() << i << "\n";
1822 outs() << " cputype " << cputype << "\n";
1823 outs() << " cpusubtype " << (cpusubtype & ~MachO::CPU_SUBTYPE_MASK)
1824 << "\n";
1825 }
1826 if (verbose &&
1827 (cpusubtype & MachO::CPU_SUBTYPE_MASK) == MachO::CPU_SUBTYPE_LIB64)
1828 outs() << " capabilities CPU_SUBTYPE_LIB64\n";
1829 else
1830 outs() << " capabilities "
1831 << format("0x%" PRIx32,
1832 (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24) << "\n";
1833 outs() << " offset " << OFA.getOffset();
1834 if (OFA.getOffset() > size)
1835 outs() << " (past end of file)";
1836 if (OFA.getOffset() % (1 << OFA.getAlign()) != 0)
1837 outs() << " (not aligned on it's alignment (2^" << OFA.getAlign() << ")";
1838 outs() << "\n";
1839 outs() << " size " << OFA.getSize();
1840 big_size = OFA.getOffset() + OFA.getSize();
1841 if (big_size > size)
1842 outs() << " (past end of file)";
1843 outs() << "\n";
1844 outs() << " align 2^" << OFA.getAlign() << " (" << (1 << OFA.getAlign())
1845 << ")\n";
1846 }
1847}
1848
Kevin Enderby6524bd82016-07-19 20:47:07 +00001849static void printArchiveChild(StringRef Filename, const Archive::Child &C,
1850 bool verbose, bool print_offset,
1851 StringRef ArchitectureName = StringRef()) {
Kevin Enderby13023a12015-01-15 23:19:11 +00001852 if (print_offset)
1853 outs() << C.getChildOffset() << "\t";
Vedant Kumar4031d9f2016-08-03 19:02:50 +00001854 Expected<sys::fs::perms> ModeOrErr = C.getAccessMode();
1855 if (!ModeOrErr)
1856 report_error(Filename, C, ModeOrErr.takeError(), ArchitectureName);
1857 sys::fs::perms Mode = ModeOrErr.get();
Kevin Enderby13023a12015-01-15 23:19:11 +00001858 if (verbose) {
1859 // FIXME: this first dash, "-", is for (Mode & S_IFMT) == S_IFREG.
1860 // But there is nothing in sys::fs::perms for S_IFMT or S_IFREG.
1861 outs() << "-";
Davide Italianobb9a6cc2015-09-07 20:47:03 +00001862 outs() << ((Mode & sys::fs::owner_read) ? "r" : "-");
1863 outs() << ((Mode & sys::fs::owner_write) ? "w" : "-");
1864 outs() << ((Mode & sys::fs::owner_exe) ? "x" : "-");
1865 outs() << ((Mode & sys::fs::group_read) ? "r" : "-");
1866 outs() << ((Mode & sys::fs::group_write) ? "w" : "-");
1867 outs() << ((Mode & sys::fs::group_exe) ? "x" : "-");
1868 outs() << ((Mode & sys::fs::others_read) ? "r" : "-");
1869 outs() << ((Mode & sys::fs::others_write) ? "w" : "-");
1870 outs() << ((Mode & sys::fs::others_exe) ? "x" : "-");
Kevin Enderby13023a12015-01-15 23:19:11 +00001871 } else {
1872 outs() << format("0%o ", Mode);
1873 }
1874
Vedant Kumar4031d9f2016-08-03 19:02:50 +00001875 Expected<unsigned> UIDOrErr = C.getUID();
1876 if (!UIDOrErr)
1877 report_error(Filename, C, UIDOrErr.takeError(), ArchitectureName);
1878 unsigned UID = UIDOrErr.get();
Kevin Enderby13023a12015-01-15 23:19:11 +00001879 outs() << format("%3d/", UID);
Vedant Kumar4031d9f2016-08-03 19:02:50 +00001880 Expected<unsigned> GIDOrErr = C.getGID();
1881 if (!GIDOrErr)
1882 report_error(Filename, C, GIDOrErr.takeError(), ArchitectureName);
1883 unsigned GID = GIDOrErr.get();
Kevin Enderby13023a12015-01-15 23:19:11 +00001884 outs() << format("%-3d ", GID);
Kevin Enderby6524bd82016-07-19 20:47:07 +00001885 Expected<uint64_t> Size = C.getRawSize();
1886 if (!Size)
1887 report_error(Filename, C, Size.takeError(), ArchitectureName);
Kevin Enderby7a969422015-11-05 19:24:56 +00001888 outs() << format("%5" PRId64, Size.get()) << " ";
Kevin Enderby13023a12015-01-15 23:19:11 +00001889
1890 StringRef RawLastModified = C.getRawLastModified();
1891 if (verbose) {
1892 unsigned Seconds;
1893 if (RawLastModified.getAsInteger(10, Seconds))
Vedant Kumar4031d9f2016-08-03 19:02:50 +00001894 outs() << "(date: \"" << RawLastModified
1895 << "\" contains non-decimal chars) ";
Kevin Enderby13023a12015-01-15 23:19:11 +00001896 else {
1897 // Since cime(3) returns a 26 character string of the form:
1898 // "Sun Sep 16 01:03:52 1973\n\0"
1899 // just print 24 characters.
1900 time_t t = Seconds;
1901 outs() << format("%.24s ", ctime(&t));
1902 }
1903 } else {
1904 outs() << RawLastModified << " ";
1905 }
1906
1907 if (verbose) {
Kevin Enderbyf4586032016-07-29 17:44:13 +00001908 Expected<StringRef> NameOrErr = C.getName();
1909 if (!NameOrErr) {
1910 consumeError(NameOrErr.takeError());
1911 Expected<StringRef> NameOrErr = C.getRawName();
1912 if (!NameOrErr)
1913 report_error(Filename, C, NameOrErr.takeError(), ArchitectureName);
1914 StringRef RawName = NameOrErr.get();
Kevin Enderby13023a12015-01-15 23:19:11 +00001915 outs() << RawName << "\n";
1916 } else {
1917 StringRef Name = NameOrErr.get();
1918 outs() << Name << "\n";
1919 }
1920 } else {
Kevin Enderbyf4586032016-07-29 17:44:13 +00001921 Expected<StringRef> NameOrErr = C.getRawName();
1922 if (!NameOrErr)
1923 report_error(Filename, C, NameOrErr.takeError(), ArchitectureName);
1924 StringRef RawName = NameOrErr.get();
Kevin Enderby13023a12015-01-15 23:19:11 +00001925 outs() << RawName << "\n";
1926 }
1927}
1928
Kevin Enderby6524bd82016-07-19 20:47:07 +00001929static void printArchiveHeaders(StringRef Filename, Archive *A, bool verbose,
1930 bool print_offset,
1931 StringRef ArchitectureName = StringRef()) {
Mehdi Amini41af4302016-11-11 04:28:40 +00001932 Error Err = Error::success();
1933 ;
Lang Hamesfc209622016-07-14 02:24:01 +00001934 for (const auto &C : A->children(Err, false))
Kevin Enderby6524bd82016-07-19 20:47:07 +00001935 printArchiveChild(Filename, C, verbose, print_offset, ArchitectureName);
1936
Lang Hamesfc209622016-07-14 02:24:01 +00001937 if (Err)
Kevin Enderby844c4ac2016-11-15 23:07:41 +00001938 report_error(StringRef(), Filename, std::move(Err), ArchitectureName);
Kevin Enderby13023a12015-01-15 23:19:11 +00001939}
1940
Dave Lee3fb120f2018-08-03 00:06:38 +00001941static bool ValidateArchFlags() {
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001942 // Check for -arch all and verifiy the -arch flags are valid.
1943 for (unsigned i = 0; i < ArchFlags.size(); ++i) {
1944 if (ArchFlags[i] == "all") {
1945 ArchAll = true;
1946 } else {
1947 if (!MachOObjectFile::isValidArch(ArchFlags[i])) {
Jonas Devliegheree787efd2018-11-11 22:12:04 +00001948 WithColor::error(errs(), "llvm-objdump")
1949 << "unknown architecture named '" + ArchFlags[i] +
1950 "'for the -arch option\n";
Dave Lee3fb120f2018-08-03 00:06:38 +00001951 return false;
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001952 }
1953 }
1954 }
Dave Lee3fb120f2018-08-03 00:06:38 +00001955 return true;
1956}
1957
1958// ParseInputMachO() parses the named Mach-O file in Filename and handles the
1959// -arch flags selecting just those slices as specified by them and also parses
1960// archive files. Then for each individual Mach-O file ProcessMachO() is
1961// called to process the file based on the command line options.
1962void llvm::ParseInputMachO(StringRef Filename) {
1963 if (!ValidateArchFlags())
1964 return;
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001965
1966 // Attempt to open the binary.
Kevin Enderby3fcdf6a2016-04-06 22:14:09 +00001967 Expected<OwningBinary<Binary>> BinaryOrErr = createBinary(Filename);
Kevin Enderby98898f22017-01-30 20:53:17 +00001968 if (!BinaryOrErr) {
1969 if (auto E = isNotObjectErrorInvalidFileType(BinaryOrErr.takeError()))
1970 report_error(Filename, std::move(E));
1971 else
1972 outs() << Filename << ": is not an object file\n";
1973 return;
1974 }
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001975 Binary &Bin = *BinaryOrErr.get().getBinary();
Kevin Enderby3f0ffab2014-12-03 22:29:40 +00001976
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001977 if (Archive *A = dyn_cast<Archive>(&Bin)) {
1978 outs() << "Archive : " << Filename << "\n";
Kevin Enderby13023a12015-01-15 23:19:11 +00001979 if (ArchiveHeaders)
Kevin Enderby6524bd82016-07-19 20:47:07 +00001980 printArchiveHeaders(Filename, A, !NonVerbose, ArchiveMemberOffsets);
1981
Mehdi Amini41af4302016-11-11 04:28:40 +00001982 Error Err = Error::success();
Lang Hamesfc209622016-07-14 02:24:01 +00001983 for (auto &C : A->children(Err)) {
Kevin Enderbyac9e1552016-05-17 17:10:12 +00001984 Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
1985 if (!ChildOrErr) {
1986 if (auto E = isNotObjectErrorInvalidFileType(ChildOrErr.takeError()))
1987 report_error(Filename, C, std::move(E));
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001988 continue;
Kevin Enderbyac9e1552016-05-17 17:10:12 +00001989 }
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001990 if (MachOObjectFile *O = dyn_cast<MachOObjectFile>(&*ChildOrErr.get())) {
1991 if (!checkMachOAndArchFlags(O, Filename))
1992 return;
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001993 ProcessMachO(Filename, O, O->getFileName());
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001994 }
1995 }
Lang Hamesfc209622016-07-14 02:24:01 +00001996 if (Err)
1997 report_error(Filename, std::move(Err));
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001998 return;
1999 }
2000 if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(&Bin)) {
Dave Lee3fb120f2018-08-03 00:06:38 +00002001 ParseInputMachO(UB);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00002002 return;
2003 }
2004 if (ObjectFile *O = dyn_cast<ObjectFile>(&Bin)) {
2005 if (!checkMachOAndArchFlags(O, Filename))
2006 return;
Dave Lee3fb120f2018-08-03 00:06:38 +00002007 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&*O))
Kevin Enderbye2297dd2015-01-07 21:02:18 +00002008 ProcessMachO(Filename, MachOOF);
Dave Lee3fb120f2018-08-03 00:06:38 +00002009 else
Jonas Devliegheree787efd2018-11-11 22:12:04 +00002010 WithColor::error(errs(), "llvm-objdump")
2011 << Filename << "': "
2012 << "object is not a Mach-O file type.\n";
Davide Italiano25d84582016-01-13 04:11:36 +00002013 return;
2014 }
2015 llvm_unreachable("Input object can't be invalid at this point");
Rafael Espindola9b709252013-04-13 01:45:40 +00002016}
2017
Dave Lee3fb120f2018-08-03 00:06:38 +00002018void llvm::ParseInputMachO(MachOUniversalBinary *UB) {
2019 if (!ValidateArchFlags())
2020 return;
2021
2022 auto Filename = UB->getFileName();
2023
2024 if (UniversalHeaders)
2025 printMachOUniversalHeaders(UB, !NonVerbose);
2026
2027 // If we have a list of architecture flags specified dump only those.
Jordan Rupprecht16a0de22018-12-20 00:57:06 +00002028 if (!ArchAll && !ArchFlags.empty()) {
Dave Lee3fb120f2018-08-03 00:06:38 +00002029 // Look for a slice in the universal binary that matches each ArchFlag.
2030 bool ArchFound;
2031 for (unsigned i = 0; i < ArchFlags.size(); ++i) {
2032 ArchFound = false;
2033 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
2034 E = UB->end_objects();
2035 I != E; ++I) {
2036 if (ArchFlags[i] == I->getArchFlagName()) {
2037 ArchFound = true;
2038 Expected<std::unique_ptr<ObjectFile>> ObjOrErr =
2039 I->getAsObjectFile();
2040 std::string ArchitectureName = "";
2041 if (ArchFlags.size() > 1)
2042 ArchitectureName = I->getArchFlagName();
2043 if (ObjOrErr) {
2044 ObjectFile &O = *ObjOrErr.get();
2045 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&O))
2046 ProcessMachO(Filename, MachOOF, "", ArchitectureName);
2047 } else if (auto E = isNotObjectErrorInvalidFileType(
2048 ObjOrErr.takeError())) {
2049 report_error(Filename, StringRef(), std::move(E),
2050 ArchitectureName);
2051 continue;
2052 } else if (Expected<std::unique_ptr<Archive>> AOrErr =
2053 I->getAsArchive()) {
2054 std::unique_ptr<Archive> &A = *AOrErr;
2055 outs() << "Archive : " << Filename;
2056 if (!ArchitectureName.empty())
2057 outs() << " (architecture " << ArchitectureName << ")";
2058 outs() << "\n";
2059 if (ArchiveHeaders)
2060 printArchiveHeaders(Filename, A.get(), !NonVerbose,
2061 ArchiveMemberOffsets, ArchitectureName);
2062 Error Err = Error::success();
2063 for (auto &C : A->children(Err)) {
2064 Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
2065 if (!ChildOrErr) {
2066 if (auto E = isNotObjectErrorInvalidFileType(ChildOrErr.takeError()))
2067 report_error(Filename, C, std::move(E), ArchitectureName);
2068 continue;
2069 }
2070 if (MachOObjectFile *O =
2071 dyn_cast<MachOObjectFile>(&*ChildOrErr.get()))
2072 ProcessMachO(Filename, O, O->getFileName(), ArchitectureName);
2073 }
2074 if (Err)
2075 report_error(Filename, std::move(Err));
2076 } else {
2077 consumeError(AOrErr.takeError());
2078 error("Mach-O universal file: " + Filename + " for " +
2079 "architecture " + StringRef(I->getArchFlagName()) +
2080 " is not a Mach-O file or an archive file");
2081 }
2082 }
2083 }
2084 if (!ArchFound) {
Jonas Devliegheree787efd2018-11-11 22:12:04 +00002085 WithColor::error(errs(), "llvm-objdump")
2086 << "file: " + Filename + " does not contain "
2087 << "architecture: " + ArchFlags[i] + "\n";
Dave Lee3fb120f2018-08-03 00:06:38 +00002088 return;
2089 }
2090 }
2091 return;
2092 }
2093 // No architecture flags were specified so if this contains a slice that
2094 // matches the host architecture dump only that.
2095 if (!ArchAll) {
2096 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
2097 E = UB->end_objects();
2098 I != E; ++I) {
2099 if (MachOObjectFile::getHostArch().getArchName() ==
2100 I->getArchFlagName()) {
2101 Expected<std::unique_ptr<ObjectFile>> ObjOrErr = I->getAsObjectFile();
2102 std::string ArchiveName;
2103 ArchiveName.clear();
2104 if (ObjOrErr) {
2105 ObjectFile &O = *ObjOrErr.get();
2106 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&O))
2107 ProcessMachO(Filename, MachOOF);
2108 } else if (auto E = isNotObjectErrorInvalidFileType(
2109 ObjOrErr.takeError())) {
2110 report_error(Filename, std::move(E));
Dave Lee3fb120f2018-08-03 00:06:38 +00002111 } else if (Expected<std::unique_ptr<Archive>> AOrErr =
2112 I->getAsArchive()) {
2113 std::unique_ptr<Archive> &A = *AOrErr;
2114 outs() << "Archive : " << Filename << "\n";
2115 if (ArchiveHeaders)
2116 printArchiveHeaders(Filename, A.get(), !NonVerbose,
2117 ArchiveMemberOffsets);
2118 Error Err = Error::success();
2119 for (auto &C : A->children(Err)) {
2120 Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
2121 if (!ChildOrErr) {
2122 if (auto E = isNotObjectErrorInvalidFileType(ChildOrErr.takeError()))
2123 report_error(Filename, C, std::move(E));
2124 continue;
2125 }
2126 if (MachOObjectFile *O =
2127 dyn_cast<MachOObjectFile>(&*ChildOrErr.get()))
2128 ProcessMachO(Filename, O, O->getFileName());
2129 }
2130 if (Err)
2131 report_error(Filename, std::move(Err));
2132 } else {
2133 consumeError(AOrErr.takeError());
2134 error("Mach-O universal file: " + Filename + " for architecture " +
2135 StringRef(I->getArchFlagName()) +
2136 " is not a Mach-O file or an archive file");
2137 }
2138 return;
2139 }
2140 }
2141 }
2142 // Either all architectures have been specified or none have been specified
2143 // and this does not contain the host architecture so dump all the slices.
2144 bool moreThanOneArch = UB->getNumberOfObjects() > 1;
2145 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
2146 E = UB->end_objects();
2147 I != E; ++I) {
2148 Expected<std::unique_ptr<ObjectFile>> ObjOrErr = I->getAsObjectFile();
2149 std::string ArchitectureName = "";
2150 if (moreThanOneArch)
2151 ArchitectureName = I->getArchFlagName();
2152 if (ObjOrErr) {
2153 ObjectFile &Obj = *ObjOrErr.get();
2154 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&Obj))
2155 ProcessMachO(Filename, MachOOF, "", ArchitectureName);
2156 } else if (auto E = isNotObjectErrorInvalidFileType(
2157 ObjOrErr.takeError())) {
2158 report_error(StringRef(), Filename, std::move(E), ArchitectureName);
Dave Lee3fb120f2018-08-03 00:06:38 +00002159 } else if (Expected<std::unique_ptr<Archive>> AOrErr =
2160 I->getAsArchive()) {
2161 std::unique_ptr<Archive> &A = *AOrErr;
2162 outs() << "Archive : " << Filename;
2163 if (!ArchitectureName.empty())
2164 outs() << " (architecture " << ArchitectureName << ")";
2165 outs() << "\n";
2166 if (ArchiveHeaders)
2167 printArchiveHeaders(Filename, A.get(), !NonVerbose,
2168 ArchiveMemberOffsets, ArchitectureName);
2169 Error Err = Error::success();
2170 for (auto &C : A->children(Err)) {
2171 Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
2172 if (!ChildOrErr) {
2173 if (auto E = isNotObjectErrorInvalidFileType(ChildOrErr.takeError()))
2174 report_error(Filename, C, std::move(E), ArchitectureName);
2175 continue;
2176 }
2177 if (MachOObjectFile *O =
2178 dyn_cast<MachOObjectFile>(&*ChildOrErr.get())) {
2179 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(O))
2180 ProcessMachO(Filename, MachOOF, MachOOF->getFileName(),
2181 ArchitectureName);
2182 }
2183 }
2184 if (Err)
2185 report_error(Filename, std::move(Err));
2186 } else {
2187 consumeError(AOrErr.takeError());
2188 error("Mach-O universal file: " + Filename + " for architecture " +
2189 StringRef(I->getArchFlagName()) +
2190 " is not a Mach-O file or an archive file");
2191 }
2192 }
2193}
2194
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002195// The block of info used by the Symbolizer call backs.
2196struct DisassembleInfo {
Serge Pavlove4e9a1f2018-02-14 03:26:27 +00002197 DisassembleInfo(MachOObjectFile *O, SymbolAddressMap *AddrMap,
2198 std::vector<SectionRef> *Sections, bool verbose)
2199 : verbose(verbose), O(O), AddrMap(AddrMap), Sections(Sections) {}
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002200 bool verbose;
2201 MachOObjectFile *O;
2202 SectionRef S;
Kevin Enderbybf246f52014-09-24 23:08:22 +00002203 SymbolAddressMap *AddrMap;
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002204 std::vector<SectionRef> *Sections;
Serge Pavlove4e9a1f2018-02-14 03:26:27 +00002205 const char *class_name = nullptr;
2206 const char *selector_name = nullptr;
David Blaikie0e550682018-02-20 18:48:51 +00002207 std::unique_ptr<char[]> method = nullptr;
Serge Pavlove4e9a1f2018-02-14 03:26:27 +00002208 char *demangled_name = nullptr;
2209 uint64_t adrp_addr = 0;
2210 uint32_t adrp_inst = 0;
Saleem Abdulrasool1d84d9a2017-01-08 19:14:15 +00002211 std::unique_ptr<SymbolAddressMap> bindtable;
Serge Pavlove4e9a1f2018-02-14 03:26:27 +00002212 uint32_t depth = 0;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002213};
2214
2215// SymbolizerGetOpInfo() is the operand information call back function.
2216// This is called to get the symbolic information for operand(s) of an
2217// instruction when it is being done. This routine does this from
2218// the relocation information, symbol table, etc. That block of information
2219// is a pointer to the struct DisassembleInfo that was passed when the
2220// disassembler context was created and passed to back to here when
2221// called back by the disassembler for instruction operands that could have
2222// relocation information. The address of the instruction containing operand is
2223// at the Pc parameter. The immediate value the operand has is passed in
2224// op_info->Value and is at Offset past the start of the instruction and has a
2225// byte Size of 1, 2 or 4. The symbolc information is returned in TagBuf is the
2226// LLVMOpInfo1 struct defined in the header "llvm-c/Disassembler.h" as symbol
2227// names and addends of the symbolic expression to add for the operand. The
2228// value of TagType is currently 1 (for the LLVMOpInfo1 struct). If symbolic
2229// information is returned then this function returns 1 else it returns 0.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00002230static int SymbolizerGetOpInfo(void *DisInfo, uint64_t Pc, uint64_t Offset,
2231 uint64_t Size, int TagType, void *TagBuf) {
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002232 struct DisassembleInfo *info = (struct DisassembleInfo *)DisInfo;
2233 struct LLVMOpInfo1 *op_info = (struct LLVMOpInfo1 *)TagBuf;
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002234 uint64_t value = op_info->Value;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002235
2236 // Make sure all fields returned are zero if we don't set them.
2237 memset((void *)op_info, '\0', sizeof(struct LLVMOpInfo1));
2238 op_info->Value = value;
2239
2240 // If the TagType is not the value 1 which it code knows about or if no
2241 // verbose symbolic information is wanted then just return 0, indicating no
2242 // information is being returned.
David Blaikie33dd45d02015-03-23 18:39:02 +00002243 if (TagType != 1 || !info->verbose)
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002244 return 0;
2245
2246 unsigned int Arch = info->O->getArch();
2247 if (Arch == Triple::x86) {
Kevin Enderby9907d0a2014-11-04 00:43:16 +00002248 if (Size != 1 && Size != 2 && Size != 4 && Size != 0)
2249 return 0;
Kevin Enderbyd90a4172015-10-10 00:05:01 +00002250 if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
2251 // TODO:
2252 // Search the external relocation entries of a fully linked image
2253 // (if any) for an entry that matches this segment offset.
2254 // uint32_t seg_offset = (Pc + Offset);
2255 return 0;
2256 }
2257 // In MH_OBJECT filetypes search the section's relocation entries (if any)
2258 // for an entry for this section offset.
Kevin Enderby9907d0a2014-11-04 00:43:16 +00002259 uint32_t sect_addr = info->S.getAddress();
2260 uint32_t sect_offset = (Pc + Offset) - sect_addr;
2261 bool reloc_found = false;
2262 DataRefImpl Rel;
2263 MachO::any_relocation_info RE;
2264 bool isExtern = false;
2265 SymbolRef Symbol;
2266 bool r_scattered = false;
2267 uint32_t r_value, pair_r_value, r_type;
2268 for (const RelocationRef &Reloc : info->S.relocations()) {
Rafael Espindola96d071c2015-06-29 23:29:12 +00002269 uint64_t RelocOffset = Reloc.getOffset();
Kevin Enderby9907d0a2014-11-04 00:43:16 +00002270 if (RelocOffset == sect_offset) {
2271 Rel = Reloc.getRawDataRefImpl();
2272 RE = info->O->getRelocation(Rel);
Kevin Enderby3eb73e12014-11-11 19:16:45 +00002273 r_type = info->O->getAnyRelocationType(RE);
Kevin Enderby9907d0a2014-11-04 00:43:16 +00002274 r_scattered = info->O->isRelocationScattered(RE);
2275 if (r_scattered) {
2276 r_value = info->O->getScatteredRelocationValue(RE);
Kevin Enderby9907d0a2014-11-04 00:43:16 +00002277 if (r_type == MachO::GENERIC_RELOC_SECTDIFF ||
2278 r_type == MachO::GENERIC_RELOC_LOCAL_SECTDIFF) {
2279 DataRefImpl RelNext = Rel;
2280 info->O->moveRelocationNext(RelNext);
2281 MachO::any_relocation_info RENext;
2282 RENext = info->O->getRelocation(RelNext);
2283 if (info->O->isRelocationScattered(RENext))
Kevin Enderby930fdc72014-11-06 19:00:13 +00002284 pair_r_value = info->O->getScatteredRelocationValue(RENext);
Kevin Enderby9907d0a2014-11-04 00:43:16 +00002285 else
2286 return 0;
2287 }
2288 } else {
2289 isExtern = info->O->getPlainRelocationExternal(RE);
2290 if (isExtern) {
2291 symbol_iterator RelocSym = Reloc.getSymbol();
2292 Symbol = *RelocSym;
2293 }
2294 }
2295 reloc_found = true;
2296 break;
2297 }
2298 }
2299 if (reloc_found && isExtern) {
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00002300 Expected<StringRef> SymName = Symbol.getName();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00002301 if (!SymName)
2302 report_error(info->O->getFileName(), SymName.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00002303 const char *name = SymName->data();
Kevin Enderby9907d0a2014-11-04 00:43:16 +00002304 op_info->AddSymbol.Present = 1;
2305 op_info->AddSymbol.Name = name;
2306 // For i386 extern relocation entries the value in the instruction is
2307 // the offset from the symbol, and value is already set in op_info->Value.
2308 return 1;
2309 }
2310 if (reloc_found && (r_type == MachO::GENERIC_RELOC_SECTDIFF ||
2311 r_type == MachO::GENERIC_RELOC_LOCAL_SECTDIFF)) {
Kevin Enderbyf6d25852015-01-31 00:37:11 +00002312 const char *add = GuessSymbolName(r_value, info->AddrMap);
2313 const char *sub = GuessSymbolName(pair_r_value, info->AddrMap);
Kevin Enderby9907d0a2014-11-04 00:43:16 +00002314 uint32_t offset = value - (r_value - pair_r_value);
2315 op_info->AddSymbol.Present = 1;
2316 if (add != nullptr)
2317 op_info->AddSymbol.Name = add;
2318 else
2319 op_info->AddSymbol.Value = r_value;
2320 op_info->SubtractSymbol.Present = 1;
2321 if (sub != nullptr)
2322 op_info->SubtractSymbol.Name = sub;
2323 else
2324 op_info->SubtractSymbol.Value = pair_r_value;
2325 op_info->Value = offset;
2326 return 1;
2327 }
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002328 return 0;
David Blaikie33dd45d02015-03-23 18:39:02 +00002329 }
2330 if (Arch == Triple::x86_64) {
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002331 if (Size != 1 && Size != 2 && Size != 4 && Size != 0)
2332 return 0;
Kevin Enderbyabf10f22017-06-22 17:41:22 +00002333 // For non MH_OBJECT types, like MH_KEXT_BUNDLE, Search the external
2334 // relocation entries of a linked image (if any) for an entry that matches
2335 // this segment offset.
Kevin Enderbyd90a4172015-10-10 00:05:01 +00002336 if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
Kevin Enderbyabf10f22017-06-22 17:41:22 +00002337 uint64_t seg_offset = Pc + Offset;
2338 bool reloc_found = false;
2339 DataRefImpl Rel;
2340 MachO::any_relocation_info RE;
2341 bool isExtern = false;
2342 SymbolRef Symbol;
2343 for (const RelocationRef &Reloc : info->O->external_relocations()) {
2344 uint64_t RelocOffset = Reloc.getOffset();
2345 if (RelocOffset == seg_offset) {
2346 Rel = Reloc.getRawDataRefImpl();
2347 RE = info->O->getRelocation(Rel);
2348 // external relocation entries should always be external.
2349 isExtern = info->O->getPlainRelocationExternal(RE);
2350 if (isExtern) {
2351 symbol_iterator RelocSym = Reloc.getSymbol();
2352 Symbol = *RelocSym;
2353 }
2354 reloc_found = true;
2355 break;
2356 }
2357 }
2358 if (reloc_found && isExtern) {
2359 // The Value passed in will be adjusted by the Pc if the instruction
2360 // adds the Pc. But for x86_64 external relocation entries the Value
2361 // is the offset from the external symbol.
2362 if (info->O->getAnyRelocationPCRel(RE))
2363 op_info->Value -= Pc + Offset + Size;
2364 Expected<StringRef> SymName = Symbol.getName();
2365 if (!SymName)
2366 report_error(info->O->getFileName(), SymName.takeError());
2367 const char *name = SymName->data();
2368 op_info->AddSymbol.Present = 1;
2369 op_info->AddSymbol.Name = name;
2370 return 1;
2371 }
Kevin Enderbyd90a4172015-10-10 00:05:01 +00002372 return 0;
2373 }
2374 // In MH_OBJECT filetypes search the section's relocation entries (if any)
2375 // for an entry for this section offset.
Rafael Espindola80291272014-10-08 15:28:58 +00002376 uint64_t sect_addr = info->S.getAddress();
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002377 uint64_t sect_offset = (Pc + Offset) - sect_addr;
2378 bool reloc_found = false;
2379 DataRefImpl Rel;
2380 MachO::any_relocation_info RE;
2381 bool isExtern = false;
2382 SymbolRef Symbol;
2383 for (const RelocationRef &Reloc : info->S.relocations()) {
Rafael Espindola96d071c2015-06-29 23:29:12 +00002384 uint64_t RelocOffset = Reloc.getOffset();
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002385 if (RelocOffset == sect_offset) {
2386 Rel = Reloc.getRawDataRefImpl();
2387 RE = info->O->getRelocation(Rel);
2388 // NOTE: Scattered relocations don't exist on x86_64.
2389 isExtern = info->O->getPlainRelocationExternal(RE);
2390 if (isExtern) {
2391 symbol_iterator RelocSym = Reloc.getSymbol();
2392 Symbol = *RelocSym;
2393 }
2394 reloc_found = true;
2395 break;
2396 }
2397 }
2398 if (reloc_found && isExtern) {
2399 // The Value passed in will be adjusted by the Pc if the instruction
2400 // adds the Pc. But for x86_64 external relocation entries the Value
2401 // is the offset from the external symbol.
2402 if (info->O->getAnyRelocationPCRel(RE))
2403 op_info->Value -= Pc + Offset + Size;
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00002404 Expected<StringRef> SymName = Symbol.getName();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00002405 if (!SymName)
2406 report_error(info->O->getFileName(), SymName.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00002407 const char *name = SymName->data();
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002408 unsigned Type = info->O->getAnyRelocationType(RE);
2409 if (Type == MachO::X86_64_RELOC_SUBTRACTOR) {
2410 DataRefImpl RelNext = Rel;
2411 info->O->moveRelocationNext(RelNext);
2412 MachO::any_relocation_info RENext = info->O->getRelocation(RelNext);
2413 unsigned TypeNext = info->O->getAnyRelocationType(RENext);
2414 bool isExternNext = info->O->getPlainRelocationExternal(RENext);
2415 unsigned SymbolNum = info->O->getPlainRelocationSymbolNum(RENext);
2416 if (TypeNext == MachO::X86_64_RELOC_UNSIGNED && isExternNext) {
2417 op_info->SubtractSymbol.Present = 1;
2418 op_info->SubtractSymbol.Name = name;
2419 symbol_iterator RelocSymNext = info->O->getSymbolByIndex(SymbolNum);
2420 Symbol = *RelocSymNext;
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00002421 Expected<StringRef> SymNameNext = Symbol.getName();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00002422 if (!SymNameNext)
2423 report_error(info->O->getFileName(), SymNameNext.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00002424 name = SymNameNext->data();
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002425 }
2426 }
2427 // TODO: add the VariantKinds to op_info->VariantKind for relocation types
2428 // like: X86_64_RELOC_TLV, X86_64_RELOC_GOT_LOAD and X86_64_RELOC_GOT.
2429 op_info->AddSymbol.Present = 1;
2430 op_info->AddSymbol.Name = name;
2431 return 1;
2432 }
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002433 return 0;
David Blaikie33dd45d02015-03-23 18:39:02 +00002434 }
2435 if (Arch == Triple::arm) {
Kevin Enderby930fdc72014-11-06 19:00:13 +00002436 if (Offset != 0 || (Size != 4 && Size != 2))
2437 return 0;
Kevin Enderbyd90a4172015-10-10 00:05:01 +00002438 if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
2439 // TODO:
2440 // Search the external relocation entries of a fully linked image
2441 // (if any) for an entry that matches this segment offset.
2442 // uint32_t seg_offset = (Pc + Offset);
2443 return 0;
2444 }
2445 // In MH_OBJECT filetypes search the section's relocation entries (if any)
2446 // for an entry for this section offset.
Kevin Enderby930fdc72014-11-06 19:00:13 +00002447 uint32_t sect_addr = info->S.getAddress();
2448 uint32_t sect_offset = (Pc + Offset) - sect_addr;
Kevin Enderby930fdc72014-11-06 19:00:13 +00002449 DataRefImpl Rel;
2450 MachO::any_relocation_info RE;
2451 bool isExtern = false;
2452 SymbolRef Symbol;
2453 bool r_scattered = false;
2454 uint32_t r_value, pair_r_value, r_type, r_length, other_half;
David Blaikie33dd45d02015-03-23 18:39:02 +00002455 auto Reloc =
David Majnemer562e8292016-08-12 00:18:03 +00002456 find_if(info->S.relocations(), [&](const RelocationRef &Reloc) {
2457 uint64_t RelocOffset = Reloc.getOffset();
2458 return RelocOffset == sect_offset;
2459 });
David Blaikie33dd45d02015-03-23 18:39:02 +00002460
2461 if (Reloc == info->S.relocations().end())
2462 return 0;
2463
2464 Rel = Reloc->getRawDataRefImpl();
2465 RE = info->O->getRelocation(Rel);
2466 r_length = info->O->getAnyRelocationLength(RE);
2467 r_scattered = info->O->isRelocationScattered(RE);
2468 if (r_scattered) {
2469 r_value = info->O->getScatteredRelocationValue(RE);
2470 r_type = info->O->getScatteredRelocationType(RE);
2471 } else {
2472 r_type = info->O->getAnyRelocationType(RE);
2473 isExtern = info->O->getPlainRelocationExternal(RE);
2474 if (isExtern) {
2475 symbol_iterator RelocSym = Reloc->getSymbol();
2476 Symbol = *RelocSym;
Kevin Enderby930fdc72014-11-06 19:00:13 +00002477 }
2478 }
David Blaikie33dd45d02015-03-23 18:39:02 +00002479 if (r_type == MachO::ARM_RELOC_HALF ||
2480 r_type == MachO::ARM_RELOC_SECTDIFF ||
2481 r_type == MachO::ARM_RELOC_LOCAL_SECTDIFF ||
2482 r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
2483 DataRefImpl RelNext = Rel;
2484 info->O->moveRelocationNext(RelNext);
2485 MachO::any_relocation_info RENext;
2486 RENext = info->O->getRelocation(RelNext);
2487 other_half = info->O->getAnyRelocationAddress(RENext) & 0xffff;
2488 if (info->O->isRelocationScattered(RENext))
2489 pair_r_value = info->O->getScatteredRelocationValue(RENext);
2490 }
2491
2492 if (isExtern) {
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00002493 Expected<StringRef> SymName = Symbol.getName();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00002494 if (!SymName)
2495 report_error(info->O->getFileName(), SymName.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00002496 const char *name = SymName->data();
Kevin Enderby930fdc72014-11-06 19:00:13 +00002497 op_info->AddSymbol.Present = 1;
2498 op_info->AddSymbol.Name = name;
Sylvestre Ledru648cced2015-02-05 17:00:23 +00002499 switch (r_type) {
2500 case MachO::ARM_RELOC_HALF:
2501 if ((r_length & 0x1) == 1) {
2502 op_info->Value = value << 16 | other_half;
2503 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
2504 } else {
2505 op_info->Value = other_half << 16 | value;
2506 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
Sylvestre Ledrufe0c7ad2015-02-05 16:35:44 +00002507 }
Sylvestre Ledru648cced2015-02-05 17:00:23 +00002508 break;
2509 default:
2510 break;
Kevin Enderby930fdc72014-11-06 19:00:13 +00002511 }
2512 return 1;
2513 }
2514 // If we have a branch that is not an external relocation entry then
2515 // return 0 so the code in tryAddingSymbolicOperand() can use the
2516 // SymbolLookUp call back with the branch target address to look up the
Simon Pilgrimdae11f72016-11-20 13:31:13 +00002517 // symbol and possibility add an annotation for a symbol stub.
David Blaikie33dd45d02015-03-23 18:39:02 +00002518 if (isExtern == 0 && (r_type == MachO::ARM_RELOC_BR24 ||
2519 r_type == MachO::ARM_THUMB_RELOC_BR22))
Kevin Enderby930fdc72014-11-06 19:00:13 +00002520 return 0;
2521
2522 uint32_t offset = 0;
David Blaikie33dd45d02015-03-23 18:39:02 +00002523 if (r_type == MachO::ARM_RELOC_HALF ||
2524 r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
2525 if ((r_length & 0x1) == 1)
2526 value = value << 16 | other_half;
2527 else
2528 value = other_half << 16 | value;
2529 }
2530 if (r_scattered && (r_type != MachO::ARM_RELOC_HALF &&
2531 r_type != MachO::ARM_RELOC_HALF_SECTDIFF)) {
2532 offset = value - r_value;
2533 value = r_value;
Kevin Enderby930fdc72014-11-06 19:00:13 +00002534 }
2535
David Blaikie33dd45d02015-03-23 18:39:02 +00002536 if (r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
Kevin Enderby930fdc72014-11-06 19:00:13 +00002537 if ((r_length & 0x1) == 1)
2538 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
2539 else
2540 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
Kevin Enderbyf6d25852015-01-31 00:37:11 +00002541 const char *add = GuessSymbolName(r_value, info->AddrMap);
2542 const char *sub = GuessSymbolName(pair_r_value, info->AddrMap);
Kevin Enderby930fdc72014-11-06 19:00:13 +00002543 int32_t offset = value - (r_value - pair_r_value);
2544 op_info->AddSymbol.Present = 1;
2545 if (add != nullptr)
2546 op_info->AddSymbol.Name = add;
2547 else
2548 op_info->AddSymbol.Value = r_value;
2549 op_info->SubtractSymbol.Present = 1;
2550 if (sub != nullptr)
2551 op_info->SubtractSymbol.Name = sub;
2552 else
2553 op_info->SubtractSymbol.Value = pair_r_value;
2554 op_info->Value = offset;
2555 return 1;
2556 }
2557
Kevin Enderby930fdc72014-11-06 19:00:13 +00002558 op_info->AddSymbol.Present = 1;
2559 op_info->Value = offset;
David Blaikie33dd45d02015-03-23 18:39:02 +00002560 if (r_type == MachO::ARM_RELOC_HALF) {
2561 if ((r_length & 0x1) == 1)
2562 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
2563 else
2564 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
Kevin Enderby930fdc72014-11-06 19:00:13 +00002565 }
Kevin Enderbyf6d25852015-01-31 00:37:11 +00002566 const char *add = GuessSymbolName(value, info->AddrMap);
Kevin Enderby930fdc72014-11-06 19:00:13 +00002567 if (add != nullptr) {
2568 op_info->AddSymbol.Name = add;
2569 return 1;
2570 }
2571 op_info->AddSymbol.Value = value;
2572 return 1;
David Blaikie33dd45d02015-03-23 18:39:02 +00002573 }
2574 if (Arch == Triple::aarch64) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002575 if (Offset != 0 || Size != 4)
2576 return 0;
Kevin Enderbyd90a4172015-10-10 00:05:01 +00002577 if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
2578 // TODO:
2579 // Search the external relocation entries of a fully linked image
2580 // (if any) for an entry that matches this segment offset.
2581 // uint64_t seg_offset = (Pc + Offset);
2582 return 0;
2583 }
2584 // In MH_OBJECT filetypes search the section's relocation entries (if any)
2585 // for an entry for this section offset.
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002586 uint64_t sect_addr = info->S.getAddress();
2587 uint64_t sect_offset = (Pc + Offset) - sect_addr;
David Blaikie33dd45d02015-03-23 18:39:02 +00002588 auto Reloc =
David Majnemer562e8292016-08-12 00:18:03 +00002589 find_if(info->S.relocations(), [&](const RelocationRef &Reloc) {
2590 uint64_t RelocOffset = Reloc.getOffset();
2591 return RelocOffset == sect_offset;
2592 });
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002593
David Blaikie33dd45d02015-03-23 18:39:02 +00002594 if (Reloc == info->S.relocations().end())
2595 return 0;
2596
2597 DataRefImpl Rel = Reloc->getRawDataRefImpl();
2598 MachO::any_relocation_info RE = info->O->getRelocation(Rel);
2599 uint32_t r_type = info->O->getAnyRelocationType(RE);
2600 if (r_type == MachO::ARM64_RELOC_ADDEND) {
2601 DataRefImpl RelNext = Rel;
2602 info->O->moveRelocationNext(RelNext);
2603 MachO::any_relocation_info RENext = info->O->getRelocation(RelNext);
2604 if (value == 0) {
2605 value = info->O->getPlainRelocationSymbolNum(RENext);
2606 op_info->Value = value;
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002607 }
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002608 }
David Blaikie33dd45d02015-03-23 18:39:02 +00002609 // NOTE: Scattered relocations don't exist on arm64.
2610 if (!info->O->getPlainRelocationExternal(RE))
2611 return 0;
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00002612 Expected<StringRef> SymName = Reloc->getSymbol()->getName();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00002613 if (!SymName)
2614 report_error(info->O->getFileName(), SymName.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00002615 const char *name = SymName->data();
David Blaikie33dd45d02015-03-23 18:39:02 +00002616 op_info->AddSymbol.Present = 1;
2617 op_info->AddSymbol.Name = name;
2618
2619 switch (r_type) {
2620 case MachO::ARM64_RELOC_PAGE21:
2621 /* @page */
2622 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_PAGE;
2623 break;
2624 case MachO::ARM64_RELOC_PAGEOFF12:
2625 /* @pageoff */
2626 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_PAGEOFF;
2627 break;
2628 case MachO::ARM64_RELOC_GOT_LOAD_PAGE21:
2629 /* @gotpage */
2630 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_GOTPAGE;
2631 break;
2632 case MachO::ARM64_RELOC_GOT_LOAD_PAGEOFF12:
2633 /* @gotpageoff */
2634 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_GOTPAGEOFF;
2635 break;
2636 case MachO::ARM64_RELOC_TLVP_LOAD_PAGE21:
2637 /* @tvlppage is not implemented in llvm-mc */
2638 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_TLVP;
2639 break;
2640 case MachO::ARM64_RELOC_TLVP_LOAD_PAGEOFF12:
2641 /* @tvlppageoff is not implemented in llvm-mc */
2642 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_TLVOFF;
2643 break;
2644 default:
2645 case MachO::ARM64_RELOC_BRANCH26:
2646 op_info->VariantKind = LLVMDisassembler_VariantKind_None;
2647 break;
2648 }
2649 return 1;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002650 }
David Blaikie33dd45d02015-03-23 18:39:02 +00002651 return 0;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002652}
2653
Kevin Enderbybf246f52014-09-24 23:08:22 +00002654// GuessCstringPointer is passed the address of what might be a pointer to a
2655// literal string in a cstring section. If that address is in a cstring section
2656// it returns a pointer to that string. Else it returns nullptr.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00002657static const char *GuessCstringPointer(uint64_t ReferenceValue,
2658 struct DisassembleInfo *info) {
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00002659 for (const auto &Load : info->O->load_commands()) {
Kevin Enderbybf246f52014-09-24 23:08:22 +00002660 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
2661 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
2662 for (unsigned J = 0; J < Seg.nsects; ++J) {
2663 MachO::section_64 Sec = info->O->getSection64(Load, J);
2664 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
2665 if (section_type == MachO::S_CSTRING_LITERALS &&
2666 ReferenceValue >= Sec.addr &&
2667 ReferenceValue < Sec.addr + Sec.size) {
2668 uint64_t sect_offset = ReferenceValue - Sec.addr;
2669 uint64_t object_offset = Sec.offset + sect_offset;
2670 StringRef MachOContents = info->O->getData();
2671 uint64_t object_size = MachOContents.size();
2672 const char *object_addr = (const char *)MachOContents.data();
2673 if (object_offset < object_size) {
2674 const char *name = object_addr + object_offset;
2675 return name;
2676 } else {
2677 return nullptr;
2678 }
2679 }
2680 }
2681 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
2682 MachO::segment_command Seg = info->O->getSegmentLoadCommand(Load);
2683 for (unsigned J = 0; J < Seg.nsects; ++J) {
2684 MachO::section Sec = info->O->getSection(Load, J);
2685 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
2686 if (section_type == MachO::S_CSTRING_LITERALS &&
2687 ReferenceValue >= Sec.addr &&
2688 ReferenceValue < Sec.addr + Sec.size) {
2689 uint64_t sect_offset = ReferenceValue - Sec.addr;
2690 uint64_t object_offset = Sec.offset + sect_offset;
2691 StringRef MachOContents = info->O->getData();
2692 uint64_t object_size = MachOContents.size();
2693 const char *object_addr = (const char *)MachOContents.data();
2694 if (object_offset < object_size) {
2695 const char *name = object_addr + object_offset;
2696 return name;
2697 } else {
2698 return nullptr;
2699 }
2700 }
2701 }
2702 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00002703 }
2704 return nullptr;
2705}
2706
Kevin Enderby85974882014-09-26 22:20:44 +00002707// GuessIndirectSymbol returns the name of the indirect symbol for the
2708// ReferenceValue passed in or nullptr. This is used when ReferenceValue maybe
2709// an address of a symbol stub or a lazy or non-lazy pointer to associate the
2710// symbol name being referenced by the stub or pointer.
2711static const char *GuessIndirectSymbol(uint64_t ReferenceValue,
2712 struct DisassembleInfo *info) {
Kevin Enderby85974882014-09-26 22:20:44 +00002713 MachO::dysymtab_command Dysymtab = info->O->getDysymtabLoadCommand();
2714 MachO::symtab_command Symtab = info->O->getSymtabLoadCommand();
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00002715 for (const auto &Load : info->O->load_commands()) {
Kevin Enderby85974882014-09-26 22:20:44 +00002716 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
2717 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
2718 for (unsigned J = 0; J < Seg.nsects; ++J) {
2719 MachO::section_64 Sec = info->O->getSection64(Load, J);
2720 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
2721 if ((section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
2722 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
2723 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
2724 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
2725 section_type == MachO::S_SYMBOL_STUBS) &&
2726 ReferenceValue >= Sec.addr &&
2727 ReferenceValue < Sec.addr + Sec.size) {
2728 uint32_t stride;
2729 if (section_type == MachO::S_SYMBOL_STUBS)
2730 stride = Sec.reserved2;
2731 else
2732 stride = 8;
2733 if (stride == 0)
2734 return nullptr;
2735 uint32_t index = Sec.reserved1 + (ReferenceValue - Sec.addr) / stride;
2736 if (index < Dysymtab.nindirectsyms) {
2737 uint32_t indirect_symbol =
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002738 info->O->getIndirectSymbolTableEntry(Dysymtab, index);
Kevin Enderby85974882014-09-26 22:20:44 +00002739 if (indirect_symbol < Symtab.nsyms) {
2740 symbol_iterator Sym = info->O->getSymbolByIndex(indirect_symbol);
2741 SymbolRef Symbol = *Sym;
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00002742 Expected<StringRef> SymName = Symbol.getName();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00002743 if (!SymName)
2744 report_error(info->O->getFileName(), SymName.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00002745 const char *name = SymName->data();
Kevin Enderby85974882014-09-26 22:20:44 +00002746 return name;
2747 }
2748 }
2749 }
2750 }
2751 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
2752 MachO::segment_command Seg = info->O->getSegmentLoadCommand(Load);
2753 for (unsigned J = 0; J < Seg.nsects; ++J) {
2754 MachO::section Sec = info->O->getSection(Load, J);
2755 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
2756 if ((section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
2757 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
2758 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
2759 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
2760 section_type == MachO::S_SYMBOL_STUBS) &&
2761 ReferenceValue >= Sec.addr &&
2762 ReferenceValue < Sec.addr + Sec.size) {
2763 uint32_t stride;
2764 if (section_type == MachO::S_SYMBOL_STUBS)
2765 stride = Sec.reserved2;
2766 else
2767 stride = 4;
2768 if (stride == 0)
2769 return nullptr;
2770 uint32_t index = Sec.reserved1 + (ReferenceValue - Sec.addr) / stride;
2771 if (index < Dysymtab.nindirectsyms) {
2772 uint32_t indirect_symbol =
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002773 info->O->getIndirectSymbolTableEntry(Dysymtab, index);
Kevin Enderby85974882014-09-26 22:20:44 +00002774 if (indirect_symbol < Symtab.nsyms) {
2775 symbol_iterator Sym = info->O->getSymbolByIndex(indirect_symbol);
2776 SymbolRef Symbol = *Sym;
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00002777 Expected<StringRef> SymName = Symbol.getName();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00002778 if (!SymName)
2779 report_error(info->O->getFileName(), SymName.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00002780 const char *name = SymName->data();
Kevin Enderby85974882014-09-26 22:20:44 +00002781 return name;
2782 }
2783 }
2784 }
2785 }
2786 }
Kevin Enderby85974882014-09-26 22:20:44 +00002787 }
2788 return nullptr;
2789}
2790
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002791// method_reference() is called passing it the ReferenceName that might be
2792// a reference it to an Objective-C method call. If so then it allocates and
2793// assembles a method call string with the values last seen and saved in
2794// the DisassembleInfo's class_name and selector_name fields. This is saved
2795// into the method field of the info and any previous string is free'ed.
2796// Then the class_name field in the info is set to nullptr. The method call
2797// string is set into ReferenceName and ReferenceType is set to
2798// LLVMDisassembler_ReferenceType_Out_Objc_Message. If this not a method call
2799// then both ReferenceType and ReferenceName are left unchanged.
2800static void method_reference(struct DisassembleInfo *info,
2801 uint64_t *ReferenceType,
2802 const char **ReferenceName) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002803 unsigned int Arch = info->O->getArch();
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002804 if (*ReferenceName != nullptr) {
2805 if (strcmp(*ReferenceName, "_objc_msgSend") == 0) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002806 if (info->selector_name != nullptr) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002807 if (info->class_name != nullptr) {
David Blaikie0e550682018-02-20 18:48:51 +00002808 info->method = llvm::make_unique<char[]>(
2809 5 + strlen(info->class_name) + strlen(info->selector_name));
2810 char *method = info->method.get();
2811 if (method != nullptr) {
2812 strcpy(method, "+[");
2813 strcat(method, info->class_name);
2814 strcat(method, " ");
2815 strcat(method, info->selector_name);
2816 strcat(method, "]");
2817 *ReferenceName = method;
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002818 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
2819 }
2820 } else {
David Blaikie0e550682018-02-20 18:48:51 +00002821 info->method =
2822 llvm::make_unique<char[]>(9 + strlen(info->selector_name));
2823 char *method = info->method.get();
2824 if (method != nullptr) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002825 if (Arch == Triple::x86_64)
David Blaikie0e550682018-02-20 18:48:51 +00002826 strcpy(method, "-[%rdi ");
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002827 else if (Arch == Triple::aarch64)
David Blaikie0e550682018-02-20 18:48:51 +00002828 strcpy(method, "-[x0 ");
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002829 else
David Blaikie0e550682018-02-20 18:48:51 +00002830 strcpy(method, "-[r? ");
2831 strcat(method, info->selector_name);
2832 strcat(method, "]");
2833 *ReferenceName = method;
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002834 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
2835 }
2836 }
2837 info->class_name = nullptr;
2838 }
2839 } else if (strcmp(*ReferenceName, "_objc_msgSendSuper2") == 0) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002840 if (info->selector_name != nullptr) {
David Blaikie0e550682018-02-20 18:48:51 +00002841 info->method =
2842 llvm::make_unique<char[]>(17 + strlen(info->selector_name));
2843 char *method = info->method.get();
2844 if (method != nullptr) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002845 if (Arch == Triple::x86_64)
David Blaikie0e550682018-02-20 18:48:51 +00002846 strcpy(method, "-[[%rdi super] ");
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002847 else if (Arch == Triple::aarch64)
David Blaikie0e550682018-02-20 18:48:51 +00002848 strcpy(method, "-[[x0 super] ");
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002849 else
David Blaikie0e550682018-02-20 18:48:51 +00002850 strcpy(method, "-[[r? super] ");
2851 strcat(method, info->selector_name);
2852 strcat(method, "]");
2853 *ReferenceName = method;
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002854 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
2855 }
2856 info->class_name = nullptr;
2857 }
2858 }
2859 }
2860}
2861
2862// GuessPointerPointer() is passed the address of what might be a pointer to
2863// a reference to an Objective-C class, selector, message ref or cfstring.
2864// If so the value of the pointer is returned and one of the booleans are set
2865// to true. If not zero is returned and all the booleans are set to false.
2866static uint64_t GuessPointerPointer(uint64_t ReferenceValue,
2867 struct DisassembleInfo *info,
2868 bool &classref, bool &selref, bool &msgref,
2869 bool &cfstring) {
2870 classref = false;
2871 selref = false;
2872 msgref = false;
2873 cfstring = false;
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00002874 for (const auto &Load : info->O->load_commands()) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002875 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
2876 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
2877 for (unsigned J = 0; J < Seg.nsects; ++J) {
2878 MachO::section_64 Sec = info->O->getSection64(Load, J);
2879 if ((strncmp(Sec.sectname, "__objc_selrefs", 16) == 0 ||
2880 strncmp(Sec.sectname, "__objc_classrefs", 16) == 0 ||
2881 strncmp(Sec.sectname, "__objc_superrefs", 16) == 0 ||
2882 strncmp(Sec.sectname, "__objc_msgrefs", 16) == 0 ||
2883 strncmp(Sec.sectname, "__cfstring", 16) == 0) &&
2884 ReferenceValue >= Sec.addr &&
2885 ReferenceValue < Sec.addr + Sec.size) {
2886 uint64_t sect_offset = ReferenceValue - Sec.addr;
2887 uint64_t object_offset = Sec.offset + sect_offset;
2888 StringRef MachOContents = info->O->getData();
2889 uint64_t object_size = MachOContents.size();
2890 const char *object_addr = (const char *)MachOContents.data();
2891 if (object_offset < object_size) {
2892 uint64_t pointer_value;
2893 memcpy(&pointer_value, object_addr + object_offset,
2894 sizeof(uint64_t));
2895 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
2896 sys::swapByteOrder(pointer_value);
2897 if (strncmp(Sec.sectname, "__objc_selrefs", 16) == 0)
2898 selref = true;
2899 else if (strncmp(Sec.sectname, "__objc_classrefs", 16) == 0 ||
2900 strncmp(Sec.sectname, "__objc_superrefs", 16) == 0)
2901 classref = true;
2902 else if (strncmp(Sec.sectname, "__objc_msgrefs", 16) == 0 &&
2903 ReferenceValue + 8 < Sec.addr + Sec.size) {
2904 msgref = true;
2905 memcpy(&pointer_value, object_addr + object_offset + 8,
2906 sizeof(uint64_t));
2907 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
2908 sys::swapByteOrder(pointer_value);
2909 } else if (strncmp(Sec.sectname, "__cfstring", 16) == 0)
2910 cfstring = true;
2911 return pointer_value;
2912 } else {
2913 return 0;
2914 }
2915 }
2916 }
2917 }
2918 // TODO: Look for LC_SEGMENT for 32-bit Mach-O files.
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002919 }
2920 return 0;
2921}
2922
2923// get_pointer_64 returns a pointer to the bytes in the object file at the
2924// Address from a section in the Mach-O file. And indirectly returns the
2925// offset into the section, number of bytes left in the section past the offset
2926// and which section is was being referenced. If the Address is not in a
2927// section nullptr is returned.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00002928static const char *get_pointer_64(uint64_t Address, uint32_t &offset,
2929 uint32_t &left, SectionRef &S,
Kevin Enderby846c0002015-04-16 17:19:59 +00002930 DisassembleInfo *info,
2931 bool objc_only = false) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002932 offset = 0;
2933 left = 0;
2934 S = SectionRef();
2935 for (unsigned SectIdx = 0; SectIdx != info->Sections->size(); SectIdx++) {
2936 uint64_t SectAddress = ((*(info->Sections))[SectIdx]).getAddress();
2937 uint64_t SectSize = ((*(info->Sections))[SectIdx]).getSize();
Kevin Enderby46e642f2015-10-08 22:50:55 +00002938 if (SectSize == 0)
2939 continue;
Kevin Enderby846c0002015-04-16 17:19:59 +00002940 if (objc_only) {
2941 StringRef SectName;
2942 ((*(info->Sections))[SectIdx]).getName(SectName);
2943 DataRefImpl Ref = ((*(info->Sections))[SectIdx]).getRawDataRefImpl();
2944 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
2945 if (SegName != "__OBJC" && SectName != "__cstring")
2946 continue;
2947 }
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002948 if (Address >= SectAddress && Address < SectAddress + SectSize) {
2949 S = (*(info->Sections))[SectIdx];
2950 offset = Address - SectAddress;
2951 left = SectSize - offset;
2952 StringRef SectContents;
2953 ((*(info->Sections))[SectIdx]).getContents(SectContents);
2954 return SectContents.data() + offset;
2955 }
2956 }
2957 return nullptr;
2958}
2959
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002960static const char *get_pointer_32(uint32_t Address, uint32_t &offset,
2961 uint32_t &left, SectionRef &S,
Kevin Enderby846c0002015-04-16 17:19:59 +00002962 DisassembleInfo *info,
2963 bool objc_only = false) {
2964 return get_pointer_64(Address, offset, left, S, info, objc_only);
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00002965}
2966
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002967// get_symbol_64() returns the name of a symbol (or nullptr) and the address of
2968// the symbol indirectly through n_value. Based on the relocation information
2969// for the specified section offset in the specified section reference.
Kevin Enderby0fc11822015-04-01 20:57:01 +00002970// If no relocation information is found and a non-zero ReferenceValue for the
2971// symbol is passed, look up that address in the info's AddrMap.
Rafael Espindolad7a32ea2015-06-24 10:20:30 +00002972static const char *get_symbol_64(uint32_t sect_offset, SectionRef S,
2973 DisassembleInfo *info, uint64_t &n_value,
Rafael Espindolabe8b0ea2015-07-07 17:12:59 +00002974 uint64_t ReferenceValue = 0) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002975 n_value = 0;
David Blaikie33dd45d02015-03-23 18:39:02 +00002976 if (!info->verbose)
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002977 return nullptr;
2978
2979 // See if there is an external relocation entry at the sect_offset.
2980 bool reloc_found = false;
2981 DataRefImpl Rel;
2982 MachO::any_relocation_info RE;
2983 bool isExtern = false;
2984 SymbolRef Symbol;
2985 for (const RelocationRef &Reloc : S.relocations()) {
Rafael Espindola96d071c2015-06-29 23:29:12 +00002986 uint64_t RelocOffset = Reloc.getOffset();
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002987 if (RelocOffset == sect_offset) {
2988 Rel = Reloc.getRawDataRefImpl();
2989 RE = info->O->getRelocation(Rel);
2990 if (info->O->isRelocationScattered(RE))
2991 continue;
2992 isExtern = info->O->getPlainRelocationExternal(RE);
2993 if (isExtern) {
2994 symbol_iterator RelocSym = Reloc.getSymbol();
2995 Symbol = *RelocSym;
2996 }
2997 reloc_found = true;
2998 break;
2999 }
3000 }
3001 // If there is an external relocation entry for a symbol in this section
3002 // at this section_offset then use that symbol's value for the n_value
3003 // and return its name.
3004 const char *SymbolName = nullptr;
3005 if (reloc_found && isExtern) {
Rafael Espindoladea00162015-07-03 17:44:18 +00003006 n_value = Symbol.getValue();
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00003007 Expected<StringRef> NameOrError = Symbol.getName();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00003008 if (!NameOrError)
3009 report_error(info->O->getFileName(), NameOrError.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00003010 StringRef Name = *NameOrError;
3011 if (!Name.empty()) {
3012 SymbolName = Name.data();
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003013 return SymbolName;
3014 }
3015 }
3016
3017 // TODO: For fully linked images, look through the external relocation
3018 // entries off the dynamic symtab command. For these the r_offset is from the
3019 // start of the first writeable segment in the Mach-O file. So the offset
3020 // to this section from that segment is passed to this routine by the caller,
3021 // as the database_offset. Which is the difference of the section's starting
3022 // address and the first writable segment.
3023 //
3024 // NOTE: need add passing the database_offset to this routine.
3025
Kevin Enderby0fc11822015-04-01 20:57:01 +00003026 // We did not find an external relocation entry so look up the ReferenceValue
3027 // as an address of a symbol and if found return that symbol's name.
Rafael Espindolabe8b0ea2015-07-07 17:12:59 +00003028 SymbolName = GuessSymbolName(ReferenceValue, info->AddrMap);
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003029
3030 return SymbolName;
3031}
3032
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003033static const char *get_symbol_32(uint32_t sect_offset, SectionRef S,
3034 DisassembleInfo *info,
3035 uint32_t ReferenceValue) {
3036 uint64_t n_value64;
3037 return get_symbol_64(sect_offset, S, info, n_value64, ReferenceValue);
3038}
3039
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003040// These are structs in the Objective-C meta data and read to produce the
3041// comments for disassembly. While these are part of the ABI they are no
Zachary Turner264b5d92017-06-07 03:48:56 +00003042// public defintions. So the are here not in include/llvm/BinaryFormat/MachO.h
3043// .
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003044
3045// The cfstring object in a 64-bit Mach-O file.
3046struct cfstring64_t {
3047 uint64_t isa; // class64_t * (64-bit pointer)
3048 uint64_t flags; // flag bits
3049 uint64_t characters; // char * (64-bit pointer)
3050 uint64_t length; // number of non-NULL characters in above
3051};
3052
3053// The class object in a 64-bit Mach-O file.
3054struct class64_t {
3055 uint64_t isa; // class64_t * (64-bit pointer)
3056 uint64_t superclass; // class64_t * (64-bit pointer)
3057 uint64_t cache; // Cache (64-bit pointer)
3058 uint64_t vtable; // IMP * (64-bit pointer)
3059 uint64_t data; // class_ro64_t * (64-bit pointer)
3060};
3061
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003062struct class32_t {
3063 uint32_t isa; /* class32_t * (32-bit pointer) */
3064 uint32_t superclass; /* class32_t * (32-bit pointer) */
3065 uint32_t cache; /* Cache (32-bit pointer) */
3066 uint32_t vtable; /* IMP * (32-bit pointer) */
3067 uint32_t data; /* class_ro32_t * (32-bit pointer) */
3068};
3069
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003070struct class_ro64_t {
3071 uint32_t flags;
3072 uint32_t instanceStart;
3073 uint32_t instanceSize;
3074 uint32_t reserved;
3075 uint64_t ivarLayout; // const uint8_t * (64-bit pointer)
3076 uint64_t name; // const char * (64-bit pointer)
3077 uint64_t baseMethods; // const method_list_t * (64-bit pointer)
3078 uint64_t baseProtocols; // const protocol_list_t * (64-bit pointer)
3079 uint64_t ivars; // const ivar_list_t * (64-bit pointer)
3080 uint64_t weakIvarLayout; // const uint8_t * (64-bit pointer)
3081 uint64_t baseProperties; // const struct objc_property_list (64-bit pointer)
3082};
3083
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003084struct class_ro32_t {
3085 uint32_t flags;
3086 uint32_t instanceStart;
3087 uint32_t instanceSize;
3088 uint32_t ivarLayout; /* const uint8_t * (32-bit pointer) */
3089 uint32_t name; /* const char * (32-bit pointer) */
3090 uint32_t baseMethods; /* const method_list_t * (32-bit pointer) */
3091 uint32_t baseProtocols; /* const protocol_list_t * (32-bit pointer) */
3092 uint32_t ivars; /* const ivar_list_t * (32-bit pointer) */
3093 uint32_t weakIvarLayout; /* const uint8_t * (32-bit pointer) */
3094 uint32_t baseProperties; /* const struct objc_property_list *
3095 (32-bit pointer) */
3096};
3097
3098/* Values for class_ro{64,32}_t->flags */
Kevin Enderby0fc11822015-04-01 20:57:01 +00003099#define RO_META (1 << 0)
3100#define RO_ROOT (1 << 1)
3101#define RO_HAS_CXX_STRUCTORS (1 << 2)
3102
3103struct method_list64_t {
3104 uint32_t entsize;
3105 uint32_t count;
3106 /* struct method64_t first; These structures follow inline */
3107};
3108
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003109struct method_list32_t {
3110 uint32_t entsize;
3111 uint32_t count;
3112 /* struct method32_t first; These structures follow inline */
3113};
3114
Kevin Enderby0fc11822015-04-01 20:57:01 +00003115struct method64_t {
3116 uint64_t name; /* SEL (64-bit pointer) */
3117 uint64_t types; /* const char * (64-bit pointer) */
3118 uint64_t imp; /* IMP (64-bit pointer) */
3119};
3120
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003121struct method32_t {
3122 uint32_t name; /* SEL (32-bit pointer) */
3123 uint32_t types; /* const char * (32-bit pointer) */
3124 uint32_t imp; /* IMP (32-bit pointer) */
3125};
3126
Kevin Enderby0fc11822015-04-01 20:57:01 +00003127struct protocol_list64_t {
3128 uint64_t count; /* uintptr_t (a 64-bit value) */
3129 /* struct protocol64_t * list[0]; These pointers follow inline */
3130};
3131
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003132struct protocol_list32_t {
3133 uint32_t count; /* uintptr_t (a 32-bit value) */
3134 /* struct protocol32_t * list[0]; These pointers follow inline */
3135};
3136
Kevin Enderby0fc11822015-04-01 20:57:01 +00003137struct protocol64_t {
3138 uint64_t isa; /* id * (64-bit pointer) */
3139 uint64_t name; /* const char * (64-bit pointer) */
3140 uint64_t protocols; /* struct protocol_list64_t *
3141 (64-bit pointer) */
3142 uint64_t instanceMethods; /* method_list_t * (64-bit pointer) */
3143 uint64_t classMethods; /* method_list_t * (64-bit pointer) */
3144 uint64_t optionalInstanceMethods; /* method_list_t * (64-bit pointer) */
3145 uint64_t optionalClassMethods; /* method_list_t * (64-bit pointer) */
3146 uint64_t instanceProperties; /* struct objc_property_list *
3147 (64-bit pointer) */
3148};
3149
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003150struct protocol32_t {
3151 uint32_t isa; /* id * (32-bit pointer) */
3152 uint32_t name; /* const char * (32-bit pointer) */
3153 uint32_t protocols; /* struct protocol_list_t *
3154 (32-bit pointer) */
3155 uint32_t instanceMethods; /* method_list_t * (32-bit pointer) */
3156 uint32_t classMethods; /* method_list_t * (32-bit pointer) */
3157 uint32_t optionalInstanceMethods; /* method_list_t * (32-bit pointer) */
3158 uint32_t optionalClassMethods; /* method_list_t * (32-bit pointer) */
3159 uint32_t instanceProperties; /* struct objc_property_list *
3160 (32-bit pointer) */
3161};
3162
Kevin Enderby0fc11822015-04-01 20:57:01 +00003163struct ivar_list64_t {
3164 uint32_t entsize;
3165 uint32_t count;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003166 /* struct ivar64_t first; These structures follow inline */
3167};
3168
3169struct ivar_list32_t {
3170 uint32_t entsize;
3171 uint32_t count;
3172 /* struct ivar32_t first; These structures follow inline */
Kevin Enderby0fc11822015-04-01 20:57:01 +00003173};
3174
3175struct ivar64_t {
3176 uint64_t offset; /* uintptr_t * (64-bit pointer) */
3177 uint64_t name; /* const char * (64-bit pointer) */
3178 uint64_t type; /* const char * (64-bit pointer) */
3179 uint32_t alignment;
3180 uint32_t size;
3181};
3182
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003183struct ivar32_t {
3184 uint32_t offset; /* uintptr_t * (32-bit pointer) */
3185 uint32_t name; /* const char * (32-bit pointer) */
3186 uint32_t type; /* const char * (32-bit pointer) */
3187 uint32_t alignment;
3188 uint32_t size;
3189};
3190
Kevin Enderby0fc11822015-04-01 20:57:01 +00003191struct objc_property_list64 {
3192 uint32_t entsize;
3193 uint32_t count;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003194 /* struct objc_property64 first; These structures follow inline */
3195};
3196
3197struct objc_property_list32 {
3198 uint32_t entsize;
3199 uint32_t count;
3200 /* struct objc_property32 first; These structures follow inline */
Kevin Enderby0fc11822015-04-01 20:57:01 +00003201};
3202
3203struct objc_property64 {
3204 uint64_t name; /* const char * (64-bit pointer) */
3205 uint64_t attributes; /* const char * (64-bit pointer) */
3206};
3207
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003208struct objc_property32 {
3209 uint32_t name; /* const char * (32-bit pointer) */
3210 uint32_t attributes; /* const char * (32-bit pointer) */
3211};
3212
Kevin Enderby0fc11822015-04-01 20:57:01 +00003213struct category64_t {
3214 uint64_t name; /* const char * (64-bit pointer) */
3215 uint64_t cls; /* struct class_t * (64-bit pointer) */
3216 uint64_t instanceMethods; /* struct method_list_t * (64-bit pointer) */
3217 uint64_t classMethods; /* struct method_list_t * (64-bit pointer) */
3218 uint64_t protocols; /* struct protocol_list_t * (64-bit pointer) */
3219 uint64_t instanceProperties; /* struct objc_property_list *
3220 (64-bit pointer) */
3221};
3222
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003223struct category32_t {
3224 uint32_t name; /* const char * (32-bit pointer) */
3225 uint32_t cls; /* struct class_t * (32-bit pointer) */
3226 uint32_t instanceMethods; /* struct method_list_t * (32-bit pointer) */
3227 uint32_t classMethods; /* struct method_list_t * (32-bit pointer) */
3228 uint32_t protocols; /* struct protocol_list_t * (32-bit pointer) */
3229 uint32_t instanceProperties; /* struct objc_property_list *
3230 (32-bit pointer) */
3231};
3232
Kevin Enderby0fc11822015-04-01 20:57:01 +00003233struct objc_image_info64 {
3234 uint32_t version;
3235 uint32_t flags;
3236};
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003237struct objc_image_info32 {
3238 uint32_t version;
3239 uint32_t flags;
3240};
Kevin Enderby846c0002015-04-16 17:19:59 +00003241struct imageInfo_t {
3242 uint32_t version;
3243 uint32_t flags;
3244};
Kevin Enderby0fc11822015-04-01 20:57:01 +00003245/* masks for objc_image_info.flags */
3246#define OBJC_IMAGE_IS_REPLACEMENT (1 << 0)
3247#define OBJC_IMAGE_SUPPORTS_GC (1 << 1)
Dave Lee390abe42018-07-06 05:11:35 +00003248#define OBJC_IMAGE_IS_SIMULATED (1 << 5)
3249#define OBJC_IMAGE_HAS_CATEGORY_CLASS_PROPERTIES (1 << 6)
Kevin Enderby0fc11822015-04-01 20:57:01 +00003250
3251struct message_ref64 {
3252 uint64_t imp; /* IMP (64-bit pointer) */
3253 uint64_t sel; /* SEL (64-bit pointer) */
3254};
3255
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003256struct message_ref32 {
3257 uint32_t imp; /* IMP (32-bit pointer) */
3258 uint32_t sel; /* SEL (32-bit pointer) */
3259};
3260
Kevin Enderby846c0002015-04-16 17:19:59 +00003261// Objective-C 1 (32-bit only) meta data structs.
3262
3263struct objc_module_t {
3264 uint32_t version;
3265 uint32_t size;
3266 uint32_t name; /* char * (32-bit pointer) */
3267 uint32_t symtab; /* struct objc_symtab * (32-bit pointer) */
3268};
3269
3270struct objc_symtab_t {
3271 uint32_t sel_ref_cnt;
3272 uint32_t refs; /* SEL * (32-bit pointer) */
3273 uint16_t cls_def_cnt;
3274 uint16_t cat_def_cnt;
3275 // uint32_t defs[1]; /* void * (32-bit pointer) variable size */
3276};
3277
3278struct objc_class_t {
3279 uint32_t isa; /* struct objc_class * (32-bit pointer) */
3280 uint32_t super_class; /* struct objc_class * (32-bit pointer) */
3281 uint32_t name; /* const char * (32-bit pointer) */
3282 int32_t version;
3283 int32_t info;
3284 int32_t instance_size;
3285 uint32_t ivars; /* struct objc_ivar_list * (32-bit pointer) */
3286 uint32_t methodLists; /* struct objc_method_list ** (32-bit pointer) */
3287 uint32_t cache; /* struct objc_cache * (32-bit pointer) */
3288 uint32_t protocols; /* struct objc_protocol_list * (32-bit pointer) */
3289};
3290
3291#define CLS_GETINFO(cls, infomask) ((cls)->info & (infomask))
3292// class is not a metaclass
3293#define CLS_CLASS 0x1
3294// class is a metaclass
3295#define CLS_META 0x2
3296
3297struct objc_category_t {
3298 uint32_t category_name; /* char * (32-bit pointer) */
3299 uint32_t class_name; /* char * (32-bit pointer) */
3300 uint32_t instance_methods; /* struct objc_method_list * (32-bit pointer) */
3301 uint32_t class_methods; /* struct objc_method_list * (32-bit pointer) */
3302 uint32_t protocols; /* struct objc_protocol_list * (32-bit ptr) */
3303};
3304
3305struct objc_ivar_t {
3306 uint32_t ivar_name; /* char * (32-bit pointer) */
3307 uint32_t ivar_type; /* char * (32-bit pointer) */
3308 int32_t ivar_offset;
3309};
3310
3311struct objc_ivar_list_t {
3312 int32_t ivar_count;
3313 // struct objc_ivar_t ivar_list[1]; /* variable length structure */
3314};
3315
3316struct objc_method_list_t {
3317 uint32_t obsolete; /* struct objc_method_list * (32-bit pointer) */
3318 int32_t method_count;
3319 // struct objc_method_t method_list[1]; /* variable length structure */
3320};
3321
3322struct objc_method_t {
3323 uint32_t method_name; /* SEL, aka struct objc_selector * (32-bit pointer) */
3324 uint32_t method_types; /* char * (32-bit pointer) */
3325 uint32_t method_imp; /* IMP, aka function pointer, (*IMP)(id, SEL, ...)
3326 (32-bit pointer) */
3327};
3328
3329struct objc_protocol_list_t {
3330 uint32_t next; /* struct objc_protocol_list * (32-bit pointer) */
3331 int32_t count;
3332 // uint32_t list[1]; /* Protocol *, aka struct objc_protocol_t *
3333 // (32-bit pointer) */
3334};
3335
3336struct objc_protocol_t {
3337 uint32_t isa; /* struct objc_class * (32-bit pointer) */
3338 uint32_t protocol_name; /* char * (32-bit pointer) */
3339 uint32_t protocol_list; /* struct objc_protocol_list * (32-bit pointer) */
3340 uint32_t instance_methods; /* struct objc_method_description_list *
3341 (32-bit pointer) */
3342 uint32_t class_methods; /* struct objc_method_description_list *
3343 (32-bit pointer) */
3344};
3345
3346struct objc_method_description_list_t {
3347 int32_t count;
3348 // struct objc_method_description_t list[1];
3349};
3350
3351struct objc_method_description_t {
3352 uint32_t name; /* SEL, aka struct objc_selector * (32-bit pointer) */
3353 uint32_t types; /* char * (32-bit pointer) */
3354};
3355
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003356inline void swapStruct(struct cfstring64_t &cfs) {
3357 sys::swapByteOrder(cfs.isa);
3358 sys::swapByteOrder(cfs.flags);
3359 sys::swapByteOrder(cfs.characters);
3360 sys::swapByteOrder(cfs.length);
3361}
3362
3363inline void swapStruct(struct class64_t &c) {
3364 sys::swapByteOrder(c.isa);
3365 sys::swapByteOrder(c.superclass);
3366 sys::swapByteOrder(c.cache);
3367 sys::swapByteOrder(c.vtable);
3368 sys::swapByteOrder(c.data);
3369}
3370
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003371inline void swapStruct(struct class32_t &c) {
3372 sys::swapByteOrder(c.isa);
3373 sys::swapByteOrder(c.superclass);
3374 sys::swapByteOrder(c.cache);
3375 sys::swapByteOrder(c.vtable);
3376 sys::swapByteOrder(c.data);
3377}
3378
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003379inline void swapStruct(struct class_ro64_t &cro) {
3380 sys::swapByteOrder(cro.flags);
3381 sys::swapByteOrder(cro.instanceStart);
3382 sys::swapByteOrder(cro.instanceSize);
3383 sys::swapByteOrder(cro.reserved);
3384 sys::swapByteOrder(cro.ivarLayout);
3385 sys::swapByteOrder(cro.name);
3386 sys::swapByteOrder(cro.baseMethods);
3387 sys::swapByteOrder(cro.baseProtocols);
3388 sys::swapByteOrder(cro.ivars);
3389 sys::swapByteOrder(cro.weakIvarLayout);
3390 sys::swapByteOrder(cro.baseProperties);
3391}
3392
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003393inline void swapStruct(struct class_ro32_t &cro) {
3394 sys::swapByteOrder(cro.flags);
3395 sys::swapByteOrder(cro.instanceStart);
3396 sys::swapByteOrder(cro.instanceSize);
3397 sys::swapByteOrder(cro.ivarLayout);
3398 sys::swapByteOrder(cro.name);
3399 sys::swapByteOrder(cro.baseMethods);
3400 sys::swapByteOrder(cro.baseProtocols);
3401 sys::swapByteOrder(cro.ivars);
3402 sys::swapByteOrder(cro.weakIvarLayout);
3403 sys::swapByteOrder(cro.baseProperties);
3404}
3405
Kevin Enderby0fc11822015-04-01 20:57:01 +00003406inline void swapStruct(struct method_list64_t &ml) {
3407 sys::swapByteOrder(ml.entsize);
3408 sys::swapByteOrder(ml.count);
3409}
3410
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003411inline void swapStruct(struct method_list32_t &ml) {
3412 sys::swapByteOrder(ml.entsize);
3413 sys::swapByteOrder(ml.count);
3414}
3415
Kevin Enderby0fc11822015-04-01 20:57:01 +00003416inline void swapStruct(struct method64_t &m) {
3417 sys::swapByteOrder(m.name);
3418 sys::swapByteOrder(m.types);
3419 sys::swapByteOrder(m.imp);
3420}
3421
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003422inline void swapStruct(struct method32_t &m) {
3423 sys::swapByteOrder(m.name);
3424 sys::swapByteOrder(m.types);
3425 sys::swapByteOrder(m.imp);
3426}
3427
Kevin Enderby0fc11822015-04-01 20:57:01 +00003428inline void swapStruct(struct protocol_list64_t &pl) {
3429 sys::swapByteOrder(pl.count);
3430}
3431
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003432inline void swapStruct(struct protocol_list32_t &pl) {
3433 sys::swapByteOrder(pl.count);
3434}
3435
Kevin Enderby0fc11822015-04-01 20:57:01 +00003436inline void swapStruct(struct protocol64_t &p) {
3437 sys::swapByteOrder(p.isa);
3438 sys::swapByteOrder(p.name);
3439 sys::swapByteOrder(p.protocols);
3440 sys::swapByteOrder(p.instanceMethods);
3441 sys::swapByteOrder(p.classMethods);
3442 sys::swapByteOrder(p.optionalInstanceMethods);
3443 sys::swapByteOrder(p.optionalClassMethods);
3444 sys::swapByteOrder(p.instanceProperties);
3445}
3446
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003447inline void swapStruct(struct protocol32_t &p) {
3448 sys::swapByteOrder(p.isa);
3449 sys::swapByteOrder(p.name);
3450 sys::swapByteOrder(p.protocols);
3451 sys::swapByteOrder(p.instanceMethods);
3452 sys::swapByteOrder(p.classMethods);
3453 sys::swapByteOrder(p.optionalInstanceMethods);
3454 sys::swapByteOrder(p.optionalClassMethods);
3455 sys::swapByteOrder(p.instanceProperties);
3456}
3457
Kevin Enderby0fc11822015-04-01 20:57:01 +00003458inline void swapStruct(struct ivar_list64_t &il) {
3459 sys::swapByteOrder(il.entsize);
3460 sys::swapByteOrder(il.count);
3461}
3462
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003463inline void swapStruct(struct ivar_list32_t &il) {
3464 sys::swapByteOrder(il.entsize);
3465 sys::swapByteOrder(il.count);
3466}
3467
Kevin Enderby0fc11822015-04-01 20:57:01 +00003468inline void swapStruct(struct ivar64_t &i) {
3469 sys::swapByteOrder(i.offset);
3470 sys::swapByteOrder(i.name);
3471 sys::swapByteOrder(i.type);
3472 sys::swapByteOrder(i.alignment);
3473 sys::swapByteOrder(i.size);
3474}
3475
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003476inline void swapStruct(struct ivar32_t &i) {
3477 sys::swapByteOrder(i.offset);
3478 sys::swapByteOrder(i.name);
3479 sys::swapByteOrder(i.type);
3480 sys::swapByteOrder(i.alignment);
3481 sys::swapByteOrder(i.size);
3482}
3483
Kevin Enderby0fc11822015-04-01 20:57:01 +00003484inline void swapStruct(struct objc_property_list64 &pl) {
3485 sys::swapByteOrder(pl.entsize);
3486 sys::swapByteOrder(pl.count);
3487}
3488
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003489inline void swapStruct(struct objc_property_list32 &pl) {
3490 sys::swapByteOrder(pl.entsize);
3491 sys::swapByteOrder(pl.count);
3492}
3493
Kevin Enderby0fc11822015-04-01 20:57:01 +00003494inline void swapStruct(struct objc_property64 &op) {
3495 sys::swapByteOrder(op.name);
3496 sys::swapByteOrder(op.attributes);
3497}
3498
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003499inline void swapStruct(struct objc_property32 &op) {
3500 sys::swapByteOrder(op.name);
3501 sys::swapByteOrder(op.attributes);
3502}
3503
Kevin Enderby0fc11822015-04-01 20:57:01 +00003504inline void swapStruct(struct category64_t &c) {
3505 sys::swapByteOrder(c.name);
3506 sys::swapByteOrder(c.cls);
3507 sys::swapByteOrder(c.instanceMethods);
3508 sys::swapByteOrder(c.classMethods);
3509 sys::swapByteOrder(c.protocols);
3510 sys::swapByteOrder(c.instanceProperties);
3511}
3512
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003513inline void swapStruct(struct category32_t &c) {
3514 sys::swapByteOrder(c.name);
3515 sys::swapByteOrder(c.cls);
3516 sys::swapByteOrder(c.instanceMethods);
3517 sys::swapByteOrder(c.classMethods);
3518 sys::swapByteOrder(c.protocols);
3519 sys::swapByteOrder(c.instanceProperties);
3520}
3521
Kevin Enderby0fc11822015-04-01 20:57:01 +00003522inline void swapStruct(struct objc_image_info64 &o) {
3523 sys::swapByteOrder(o.version);
3524 sys::swapByteOrder(o.flags);
3525}
3526
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003527inline void swapStruct(struct objc_image_info32 &o) {
3528 sys::swapByteOrder(o.version);
3529 sys::swapByteOrder(o.flags);
3530}
3531
Kevin Enderby846c0002015-04-16 17:19:59 +00003532inline void swapStruct(struct imageInfo_t &o) {
3533 sys::swapByteOrder(o.version);
3534 sys::swapByteOrder(o.flags);
3535}
3536
Kevin Enderby0fc11822015-04-01 20:57:01 +00003537inline void swapStruct(struct message_ref64 &mr) {
3538 sys::swapByteOrder(mr.imp);
3539 sys::swapByteOrder(mr.sel);
3540}
3541
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003542inline void swapStruct(struct message_ref32 &mr) {
3543 sys::swapByteOrder(mr.imp);
3544 sys::swapByteOrder(mr.sel);
3545}
3546
Kevin Enderby846c0002015-04-16 17:19:59 +00003547inline void swapStruct(struct objc_module_t &module) {
3548 sys::swapByteOrder(module.version);
3549 sys::swapByteOrder(module.size);
3550 sys::swapByteOrder(module.name);
3551 sys::swapByteOrder(module.symtab);
Jingyue Wufedecc42015-04-16 18:43:44 +00003552}
Kevin Enderby846c0002015-04-16 17:19:59 +00003553
3554inline void swapStruct(struct objc_symtab_t &symtab) {
3555 sys::swapByteOrder(symtab.sel_ref_cnt);
3556 sys::swapByteOrder(symtab.refs);
3557 sys::swapByteOrder(symtab.cls_def_cnt);
3558 sys::swapByteOrder(symtab.cat_def_cnt);
Jingyue Wufedecc42015-04-16 18:43:44 +00003559}
Kevin Enderby846c0002015-04-16 17:19:59 +00003560
3561inline void swapStruct(struct objc_class_t &objc_class) {
3562 sys::swapByteOrder(objc_class.isa);
3563 sys::swapByteOrder(objc_class.super_class);
3564 sys::swapByteOrder(objc_class.name);
3565 sys::swapByteOrder(objc_class.version);
3566 sys::swapByteOrder(objc_class.info);
3567 sys::swapByteOrder(objc_class.instance_size);
3568 sys::swapByteOrder(objc_class.ivars);
3569 sys::swapByteOrder(objc_class.methodLists);
3570 sys::swapByteOrder(objc_class.cache);
3571 sys::swapByteOrder(objc_class.protocols);
Jingyue Wufedecc42015-04-16 18:43:44 +00003572}
Kevin Enderby846c0002015-04-16 17:19:59 +00003573
3574inline void swapStruct(struct objc_category_t &objc_category) {
3575 sys::swapByteOrder(objc_category.category_name);
3576 sys::swapByteOrder(objc_category.class_name);
3577 sys::swapByteOrder(objc_category.instance_methods);
3578 sys::swapByteOrder(objc_category.class_methods);
3579 sys::swapByteOrder(objc_category.protocols);
3580}
3581
3582inline void swapStruct(struct objc_ivar_list_t &objc_ivar_list) {
3583 sys::swapByteOrder(objc_ivar_list.ivar_count);
3584}
3585
3586inline void swapStruct(struct objc_ivar_t &objc_ivar) {
3587 sys::swapByteOrder(objc_ivar.ivar_name);
3588 sys::swapByteOrder(objc_ivar.ivar_type);
3589 sys::swapByteOrder(objc_ivar.ivar_offset);
Jingyue Wufedecc42015-04-16 18:43:44 +00003590}
Kevin Enderby846c0002015-04-16 17:19:59 +00003591
3592inline void swapStruct(struct objc_method_list_t &method_list) {
3593 sys::swapByteOrder(method_list.obsolete);
3594 sys::swapByteOrder(method_list.method_count);
3595}
3596
3597inline void swapStruct(struct objc_method_t &method) {
3598 sys::swapByteOrder(method.method_name);
3599 sys::swapByteOrder(method.method_types);
3600 sys::swapByteOrder(method.method_imp);
3601}
3602
3603inline void swapStruct(struct objc_protocol_list_t &protocol_list) {
3604 sys::swapByteOrder(protocol_list.next);
3605 sys::swapByteOrder(protocol_list.count);
3606}
3607
3608inline void swapStruct(struct objc_protocol_t &protocol) {
3609 sys::swapByteOrder(protocol.isa);
3610 sys::swapByteOrder(protocol.protocol_name);
3611 sys::swapByteOrder(protocol.protocol_list);
3612 sys::swapByteOrder(protocol.instance_methods);
3613 sys::swapByteOrder(protocol.class_methods);
3614}
3615
3616inline void swapStruct(struct objc_method_description_list_t &mdl) {
3617 sys::swapByteOrder(mdl.count);
3618}
3619
3620inline void swapStruct(struct objc_method_description_t &md) {
3621 sys::swapByteOrder(md.name);
3622 sys::swapByteOrder(md.types);
3623}
3624
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003625static const char *get_dyld_bind_info_symbolname(uint64_t ReferenceValue,
3626 struct DisassembleInfo *info);
3627
3628// get_objc2_64bit_class_name() is used for disassembly and is passed a pointer
3629// to an Objective-C class and returns the class name. It is also passed the
3630// address of the pointer, so when the pointer is zero as it can be in an .o
3631// file, that is used to look for an external relocation entry with a symbol
3632// name.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00003633static const char *get_objc2_64bit_class_name(uint64_t pointer_value,
3634 uint64_t ReferenceValue,
3635 struct DisassembleInfo *info) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003636 const char *r;
3637 uint32_t offset, left;
3638 SectionRef S;
3639
3640 // The pointer_value can be 0 in an object file and have a relocation
3641 // entry for the class symbol at the ReferenceValue (the address of the
3642 // pointer).
3643 if (pointer_value == 0) {
3644 r = get_pointer_64(ReferenceValue, offset, left, S, info);
3645 if (r == nullptr || left < sizeof(uint64_t))
3646 return nullptr;
3647 uint64_t n_value;
3648 const char *symbol_name = get_symbol_64(offset, S, info, n_value);
3649 if (symbol_name == nullptr)
3650 return nullptr;
Hans Wennborgdb53e302014-10-23 21:59:17 +00003651 const char *class_name = strrchr(symbol_name, '$');
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003652 if (class_name != nullptr && class_name[1] == '_' && class_name[2] != '\0')
3653 return class_name + 2;
3654 else
3655 return nullptr;
3656 }
3657
3658 // The case were the pointer_value is non-zero and points to a class defined
3659 // in this Mach-O file.
3660 r = get_pointer_64(pointer_value, offset, left, S, info);
3661 if (r == nullptr || left < sizeof(struct class64_t))
3662 return nullptr;
3663 struct class64_t c;
3664 memcpy(&c, r, sizeof(struct class64_t));
3665 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3666 swapStruct(c);
3667 if (c.data == 0)
3668 return nullptr;
3669 r = get_pointer_64(c.data, offset, left, S, info);
3670 if (r == nullptr || left < sizeof(struct class_ro64_t))
3671 return nullptr;
3672 struct class_ro64_t cro;
3673 memcpy(&cro, r, sizeof(struct class_ro64_t));
3674 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3675 swapStruct(cro);
3676 if (cro.name == 0)
3677 return nullptr;
3678 const char *name = get_pointer_64(cro.name, offset, left, S, info);
3679 return name;
3680}
3681
3682// get_objc2_64bit_cfstring_name is used for disassembly and is passed a
3683// pointer to a cfstring and returns its name or nullptr.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00003684static const char *get_objc2_64bit_cfstring_name(uint64_t ReferenceValue,
3685 struct DisassembleInfo *info) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003686 const char *r, *name;
3687 uint32_t offset, left;
3688 SectionRef S;
3689 struct cfstring64_t cfs;
3690 uint64_t cfs_characters;
3691
3692 r = get_pointer_64(ReferenceValue, offset, left, S, info);
3693 if (r == nullptr || left < sizeof(struct cfstring64_t))
3694 return nullptr;
3695 memcpy(&cfs, r, sizeof(struct cfstring64_t));
3696 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3697 swapStruct(cfs);
3698 if (cfs.characters == 0) {
3699 uint64_t n_value;
3700 const char *symbol_name = get_symbol_64(
3701 offset + offsetof(struct cfstring64_t, characters), S, info, n_value);
3702 if (symbol_name == nullptr)
3703 return nullptr;
3704 cfs_characters = n_value;
3705 } else
3706 cfs_characters = cfs.characters;
3707 name = get_pointer_64(cfs_characters, offset, left, S, info);
3708
3709 return name;
3710}
3711
3712// get_objc2_64bit_selref() is used for disassembly and is passed a the address
3713// of a pointer to an Objective-C selector reference when the pointer value is
3714// zero as in a .o file and is likely to have a external relocation entry with
3715// who's symbol's n_value is the real pointer to the selector name. If that is
3716// the case the real pointer to the selector name is returned else 0 is
3717// returned
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00003718static uint64_t get_objc2_64bit_selref(uint64_t ReferenceValue,
3719 struct DisassembleInfo *info) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003720 uint32_t offset, left;
3721 SectionRef S;
3722
3723 const char *r = get_pointer_64(ReferenceValue, offset, left, S, info);
3724 if (r == nullptr || left < sizeof(uint64_t))
3725 return 0;
3726 uint64_t n_value;
3727 const char *symbol_name = get_symbol_64(offset, S, info, n_value);
3728 if (symbol_name == nullptr)
3729 return 0;
3730 return n_value;
3731}
3732
Kevin Enderby0fc11822015-04-01 20:57:01 +00003733static const SectionRef get_section(MachOObjectFile *O, const char *segname,
3734 const char *sectname) {
3735 for (const SectionRef &Section : O->sections()) {
3736 StringRef SectName;
3737 Section.getName(SectName);
3738 DataRefImpl Ref = Section.getRawDataRefImpl();
3739 StringRef SegName = O->getSectionFinalSegmentName(Ref);
3740 if (SegName == segname && SectName == sectname)
3741 return Section;
3742 }
3743 return SectionRef();
3744}
3745
3746static void
3747walk_pointer_list_64(const char *listname, const SectionRef S,
3748 MachOObjectFile *O, struct DisassembleInfo *info,
3749 void (*func)(uint64_t, struct DisassembleInfo *info)) {
3750 if (S == SectionRef())
3751 return;
3752
3753 StringRef SectName;
3754 S.getName(SectName);
3755 DataRefImpl Ref = S.getRawDataRefImpl();
3756 StringRef SegName = O->getSectionFinalSegmentName(Ref);
3757 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
3758
3759 StringRef BytesStr;
3760 S.getContents(BytesStr);
3761 const char *Contents = reinterpret_cast<const char *>(BytesStr.data());
3762
3763 for (uint32_t i = 0; i < S.getSize(); i += sizeof(uint64_t)) {
3764 uint32_t left = S.getSize() - i;
3765 uint32_t size = left < sizeof(uint64_t) ? left : sizeof(uint64_t);
3766 uint64_t p = 0;
3767 memcpy(&p, Contents + i, size);
3768 if (i + sizeof(uint64_t) > S.getSize())
3769 outs() << listname << " list pointer extends past end of (" << SegName
3770 << "," << SectName << ") section\n";
3771 outs() << format("%016" PRIx64, S.getAddress() + i) << " ";
3772
3773 if (O->isLittleEndian() != sys::IsLittleEndianHost)
3774 sys::swapByteOrder(p);
3775
3776 uint64_t n_value = 0;
3777 const char *name = get_symbol_64(i, S, info, n_value, p);
3778 if (name == nullptr)
3779 name = get_dyld_bind_info_symbolname(S.getAddress() + i, info);
3780
3781 if (n_value != 0) {
3782 outs() << format("0x%" PRIx64, n_value);
3783 if (p != 0)
3784 outs() << " + " << format("0x%" PRIx64, p);
3785 } else
3786 outs() << format("0x%" PRIx64, p);
3787 if (name != nullptr)
3788 outs() << " " << name;
3789 outs() << "\n";
3790
3791 p += n_value;
3792 if (func)
3793 func(p, info);
3794 }
3795}
3796
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003797static void
3798walk_pointer_list_32(const char *listname, const SectionRef S,
3799 MachOObjectFile *O, struct DisassembleInfo *info,
3800 void (*func)(uint32_t, struct DisassembleInfo *info)) {
3801 if (S == SectionRef())
3802 return;
3803
3804 StringRef SectName;
3805 S.getName(SectName);
3806 DataRefImpl Ref = S.getRawDataRefImpl();
3807 StringRef SegName = O->getSectionFinalSegmentName(Ref);
3808 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
3809
3810 StringRef BytesStr;
3811 S.getContents(BytesStr);
3812 const char *Contents = reinterpret_cast<const char *>(BytesStr.data());
3813
3814 for (uint32_t i = 0; i < S.getSize(); i += sizeof(uint32_t)) {
3815 uint32_t left = S.getSize() - i;
3816 uint32_t size = left < sizeof(uint32_t) ? left : sizeof(uint32_t);
3817 uint32_t p = 0;
3818 memcpy(&p, Contents + i, size);
3819 if (i + sizeof(uint32_t) > S.getSize())
3820 outs() << listname << " list pointer extends past end of (" << SegName
3821 << "," << SectName << ") section\n";
Kevin Enderbycf261312015-04-06 22:33:43 +00003822 uint32_t Address = S.getAddress() + i;
3823 outs() << format("%08" PRIx32, Address) << " ";
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003824
3825 if (O->isLittleEndian() != sys::IsLittleEndianHost)
3826 sys::swapByteOrder(p);
3827 outs() << format("0x%" PRIx32, p);
3828
3829 const char *name = get_symbol_32(i, S, info, p);
3830 if (name != nullptr)
3831 outs() << " " << name;
3832 outs() << "\n";
3833
3834 if (func)
3835 func(p, info);
3836 }
3837}
3838
3839static void print_layout_map(const char *layout_map, uint32_t left) {
Kevin Enderbya59824a2015-10-06 22:27:08 +00003840 if (layout_map == nullptr)
3841 return;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003842 outs() << " layout map: ";
3843 do {
3844 outs() << format("0x%02" PRIx32, (*layout_map) & 0xff) << " ";
3845 left--;
3846 layout_map++;
3847 } while (*layout_map != '\0' && left != 0);
3848 outs() << "\n";
3849}
3850
Kevin Enderby0fc11822015-04-01 20:57:01 +00003851static void print_layout_map64(uint64_t p, struct DisassembleInfo *info) {
3852 uint32_t offset, left;
3853 SectionRef S;
3854 const char *layout_map;
3855
3856 if (p == 0)
3857 return;
3858 layout_map = get_pointer_64(p, offset, left, S, info);
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003859 print_layout_map(layout_map, left);
3860}
3861
3862static void print_layout_map32(uint32_t p, struct DisassembleInfo *info) {
3863 uint32_t offset, left;
3864 SectionRef S;
3865 const char *layout_map;
3866
3867 if (p == 0)
3868 return;
3869 layout_map = get_pointer_32(p, offset, left, S, info);
3870 print_layout_map(layout_map, left);
Kevin Enderby0fc11822015-04-01 20:57:01 +00003871}
3872
3873static void print_method_list64_t(uint64_t p, struct DisassembleInfo *info,
3874 const char *indent) {
3875 struct method_list64_t ml;
3876 struct method64_t m;
3877 const char *r;
3878 uint32_t offset, xoffset, left, i;
3879 SectionRef S, xS;
3880 const char *name, *sym_name;
3881 uint64_t n_value;
3882
3883 r = get_pointer_64(p, offset, left, S, info);
3884 if (r == nullptr)
3885 return;
3886 memset(&ml, '\0', sizeof(struct method_list64_t));
3887 if (left < sizeof(struct method_list64_t)) {
3888 memcpy(&ml, r, left);
3889 outs() << " (method_list_t entends past the end of the section)\n";
3890 } else
3891 memcpy(&ml, r, sizeof(struct method_list64_t));
3892 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3893 swapStruct(ml);
3894 outs() << indent << "\t\t entsize " << ml.entsize << "\n";
3895 outs() << indent << "\t\t count " << ml.count << "\n";
3896
3897 p += sizeof(struct method_list64_t);
3898 offset += sizeof(struct method_list64_t);
3899 for (i = 0; i < ml.count; i++) {
3900 r = get_pointer_64(p, offset, left, S, info);
3901 if (r == nullptr)
3902 return;
3903 memset(&m, '\0', sizeof(struct method64_t));
3904 if (left < sizeof(struct method64_t)) {
Kevin Enderbya59824a2015-10-06 22:27:08 +00003905 memcpy(&m, r, left);
3906 outs() << indent << " (method_t extends past the end of the section)\n";
Kevin Enderby0fc11822015-04-01 20:57:01 +00003907 } else
3908 memcpy(&m, r, sizeof(struct method64_t));
3909 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3910 swapStruct(m);
3911
3912 outs() << indent << "\t\t name ";
3913 sym_name = get_symbol_64(offset + offsetof(struct method64_t, name), S,
3914 info, n_value, m.name);
3915 if (n_value != 0) {
3916 if (info->verbose && sym_name != nullptr)
3917 outs() << sym_name;
3918 else
3919 outs() << format("0x%" PRIx64, n_value);
3920 if (m.name != 0)
3921 outs() << " + " << format("0x%" PRIx64, m.name);
3922 } else
3923 outs() << format("0x%" PRIx64, m.name);
3924 name = get_pointer_64(m.name + n_value, xoffset, left, xS, info);
3925 if (name != nullptr)
3926 outs() << format(" %.*s", left, name);
3927 outs() << "\n";
3928
3929 outs() << indent << "\t\t types ";
3930 sym_name = get_symbol_64(offset + offsetof(struct method64_t, types), S,
3931 info, n_value, m.types);
3932 if (n_value != 0) {
3933 if (info->verbose && sym_name != nullptr)
3934 outs() << sym_name;
3935 else
3936 outs() << format("0x%" PRIx64, n_value);
3937 if (m.types != 0)
3938 outs() << " + " << format("0x%" PRIx64, m.types);
3939 } else
3940 outs() << format("0x%" PRIx64, m.types);
3941 name = get_pointer_64(m.types + n_value, xoffset, left, xS, info);
3942 if (name != nullptr)
3943 outs() << format(" %.*s", left, name);
3944 outs() << "\n";
3945
3946 outs() << indent << "\t\t imp ";
3947 name = get_symbol_64(offset + offsetof(struct method64_t, imp), S, info,
3948 n_value, m.imp);
3949 if (info->verbose && name == nullptr) {
3950 if (n_value != 0) {
3951 outs() << format("0x%" PRIx64, n_value) << " ";
3952 if (m.imp != 0)
3953 outs() << "+ " << format("0x%" PRIx64, m.imp) << " ";
3954 } else
3955 outs() << format("0x%" PRIx64, m.imp) << " ";
3956 }
3957 if (name != nullptr)
3958 outs() << name;
3959 outs() << "\n";
3960
3961 p += sizeof(struct method64_t);
3962 offset += sizeof(struct method64_t);
3963 }
3964}
3965
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003966static void print_method_list32_t(uint64_t p, struct DisassembleInfo *info,
3967 const char *indent) {
3968 struct method_list32_t ml;
3969 struct method32_t m;
Kevin Enderby846c0002015-04-16 17:19:59 +00003970 const char *r, *name;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003971 uint32_t offset, xoffset, left, i;
3972 SectionRef S, xS;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003973
3974 r = get_pointer_32(p, offset, left, S, info);
3975 if (r == nullptr)
3976 return;
3977 memset(&ml, '\0', sizeof(struct method_list32_t));
3978 if (left < sizeof(struct method_list32_t)) {
3979 memcpy(&ml, r, left);
3980 outs() << " (method_list_t entends past the end of the section)\n";
3981 } else
3982 memcpy(&ml, r, sizeof(struct method_list32_t));
3983 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3984 swapStruct(ml);
3985 outs() << indent << "\t\t entsize " << ml.entsize << "\n";
3986 outs() << indent << "\t\t count " << ml.count << "\n";
3987
3988 p += sizeof(struct method_list32_t);
3989 offset += sizeof(struct method_list32_t);
3990 for (i = 0; i < ml.count; i++) {
3991 r = get_pointer_32(p, offset, left, S, info);
3992 if (r == nullptr)
3993 return;
3994 memset(&m, '\0', sizeof(struct method32_t));
3995 if (left < sizeof(struct method32_t)) {
3996 memcpy(&ml, r, left);
3997 outs() << indent << " (method_t entends past the end of the section)\n";
3998 } else
3999 memcpy(&m, r, sizeof(struct method32_t));
4000 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4001 swapStruct(m);
4002
4003 outs() << indent << "\t\t name " << format("0x%" PRIx32, m.name);
4004 name = get_pointer_32(m.name, xoffset, left, xS, info);
4005 if (name != nullptr)
4006 outs() << format(" %.*s", left, name);
4007 outs() << "\n";
4008
4009 outs() << indent << "\t\t types " << format("0x%" PRIx32, m.types);
4010 name = get_pointer_32(m.types, xoffset, left, xS, info);
4011 if (name != nullptr)
4012 outs() << format(" %.*s", left, name);
4013 outs() << "\n";
4014
4015 outs() << indent << "\t\t imp " << format("0x%" PRIx32, m.imp);
4016 name = get_symbol_32(offset + offsetof(struct method32_t, imp), S, info,
4017 m.imp);
4018 if (name != nullptr)
4019 outs() << " " << name;
4020 outs() << "\n";
4021
4022 p += sizeof(struct method32_t);
4023 offset += sizeof(struct method32_t);
4024 }
4025}
4026
Kevin Enderby846c0002015-04-16 17:19:59 +00004027static bool print_method_list(uint32_t p, struct DisassembleInfo *info) {
4028 uint32_t offset, left, xleft;
4029 SectionRef S;
4030 struct objc_method_list_t method_list;
4031 struct objc_method_t method;
4032 const char *r, *methods, *name, *SymbolName;
4033 int32_t i;
4034
4035 r = get_pointer_32(p, offset, left, S, info, true);
4036 if (r == nullptr)
4037 return true;
4038
4039 outs() << "\n";
4040 if (left > sizeof(struct objc_method_list_t)) {
4041 memcpy(&method_list, r, sizeof(struct objc_method_list_t));
4042 } else {
4043 outs() << "\t\t objc_method_list extends past end of the section\n";
4044 memset(&method_list, '\0', sizeof(struct objc_method_list_t));
4045 memcpy(&method_list, r, left);
4046 }
4047 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4048 swapStruct(method_list);
4049
4050 outs() << "\t\t obsolete "
4051 << format("0x%08" PRIx32, method_list.obsolete) << "\n";
4052 outs() << "\t\t method_count " << method_list.method_count << "\n";
4053
4054 methods = r + sizeof(struct objc_method_list_t);
4055 for (i = 0; i < method_list.method_count; i++) {
4056 if ((i + 1) * sizeof(struct objc_method_t) > left) {
4057 outs() << "\t\t remaining method's extend past the of the section\n";
4058 break;
4059 }
4060 memcpy(&method, methods + i * sizeof(struct objc_method_t),
4061 sizeof(struct objc_method_t));
4062 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4063 swapStruct(method);
4064
4065 outs() << "\t\t method_name "
4066 << format("0x%08" PRIx32, method.method_name);
4067 if (info->verbose) {
4068 name = get_pointer_32(method.method_name, offset, xleft, S, info, true);
4069 if (name != nullptr)
4070 outs() << format(" %.*s", xleft, name);
4071 else
4072 outs() << " (not in an __OBJC section)";
4073 }
4074 outs() << "\n";
4075
4076 outs() << "\t\t method_types "
4077 << format("0x%08" PRIx32, method.method_types);
4078 if (info->verbose) {
4079 name = get_pointer_32(method.method_types, offset, xleft, S, info, true);
4080 if (name != nullptr)
4081 outs() << format(" %.*s", xleft, name);
4082 else
4083 outs() << " (not in an __OBJC section)";
4084 }
4085 outs() << "\n";
4086
4087 outs() << "\t\t method_imp "
4088 << format("0x%08" PRIx32, method.method_imp) << " ";
4089 if (info->verbose) {
4090 SymbolName = GuessSymbolName(method.method_imp, info->AddrMap);
4091 if (SymbolName != nullptr)
4092 outs() << SymbolName;
4093 }
4094 outs() << "\n";
4095 }
4096 return false;
4097}
4098
Kevin Enderby0fc11822015-04-01 20:57:01 +00004099static void print_protocol_list64_t(uint64_t p, struct DisassembleInfo *info) {
4100 struct protocol_list64_t pl;
4101 uint64_t q, n_value;
4102 struct protocol64_t pc;
4103 const char *r;
4104 uint32_t offset, xoffset, left, i;
4105 SectionRef S, xS;
4106 const char *name, *sym_name;
4107
4108 r = get_pointer_64(p, offset, left, S, info);
4109 if (r == nullptr)
4110 return;
4111 memset(&pl, '\0', sizeof(struct protocol_list64_t));
4112 if (left < sizeof(struct protocol_list64_t)) {
4113 memcpy(&pl, r, left);
4114 outs() << " (protocol_list_t entends past the end of the section)\n";
4115 } else
4116 memcpy(&pl, r, sizeof(struct protocol_list64_t));
4117 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4118 swapStruct(pl);
4119 outs() << " count " << pl.count << "\n";
4120
4121 p += sizeof(struct protocol_list64_t);
4122 offset += sizeof(struct protocol_list64_t);
4123 for (i = 0; i < pl.count; i++) {
4124 r = get_pointer_64(p, offset, left, S, info);
4125 if (r == nullptr)
4126 return;
4127 q = 0;
4128 if (left < sizeof(uint64_t)) {
4129 memcpy(&q, r, left);
4130 outs() << " (protocol_t * entends past the end of the section)\n";
4131 } else
4132 memcpy(&q, r, sizeof(uint64_t));
4133 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4134 sys::swapByteOrder(q);
4135
4136 outs() << "\t\t list[" << i << "] ";
4137 sym_name = get_symbol_64(offset, S, info, n_value, q);
4138 if (n_value != 0) {
4139 if (info->verbose && sym_name != nullptr)
4140 outs() << sym_name;
4141 else
4142 outs() << format("0x%" PRIx64, n_value);
4143 if (q != 0)
4144 outs() << " + " << format("0x%" PRIx64, q);
4145 } else
4146 outs() << format("0x%" PRIx64, q);
4147 outs() << " (struct protocol_t *)\n";
4148
4149 r = get_pointer_64(q + n_value, offset, left, S, info);
4150 if (r == nullptr)
4151 return;
4152 memset(&pc, '\0', sizeof(struct protocol64_t));
4153 if (left < sizeof(struct protocol64_t)) {
4154 memcpy(&pc, r, left);
4155 outs() << " (protocol_t entends past the end of the section)\n";
4156 } else
4157 memcpy(&pc, r, sizeof(struct protocol64_t));
4158 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4159 swapStruct(pc);
4160
4161 outs() << "\t\t\t isa " << format("0x%" PRIx64, pc.isa) << "\n";
4162
4163 outs() << "\t\t\t name ";
4164 sym_name = get_symbol_64(offset + offsetof(struct protocol64_t, name), S,
4165 info, n_value, pc.name);
4166 if (n_value != 0) {
4167 if (info->verbose && sym_name != nullptr)
4168 outs() << sym_name;
4169 else
4170 outs() << format("0x%" PRIx64, n_value);
4171 if (pc.name != 0)
4172 outs() << " + " << format("0x%" PRIx64, pc.name);
4173 } else
4174 outs() << format("0x%" PRIx64, pc.name);
4175 name = get_pointer_64(pc.name + n_value, xoffset, left, xS, info);
4176 if (name != nullptr)
4177 outs() << format(" %.*s", left, name);
4178 outs() << "\n";
4179
4180 outs() << "\t\t\tprotocols " << format("0x%" PRIx64, pc.protocols) << "\n";
4181
4182 outs() << "\t\t instanceMethods ";
4183 sym_name =
4184 get_symbol_64(offset + offsetof(struct protocol64_t, instanceMethods),
4185 S, info, n_value, pc.instanceMethods);
4186 if (n_value != 0) {
4187 if (info->verbose && sym_name != nullptr)
4188 outs() << sym_name;
4189 else
4190 outs() << format("0x%" PRIx64, n_value);
4191 if (pc.instanceMethods != 0)
4192 outs() << " + " << format("0x%" PRIx64, pc.instanceMethods);
4193 } else
4194 outs() << format("0x%" PRIx64, pc.instanceMethods);
4195 outs() << " (struct method_list_t *)\n";
4196 if (pc.instanceMethods + n_value != 0)
4197 print_method_list64_t(pc.instanceMethods + n_value, info, "\t");
4198
4199 outs() << "\t\t classMethods ";
4200 sym_name =
4201 get_symbol_64(offset + offsetof(struct protocol64_t, classMethods), S,
4202 info, n_value, pc.classMethods);
4203 if (n_value != 0) {
4204 if (info->verbose && sym_name != nullptr)
4205 outs() << sym_name;
4206 else
4207 outs() << format("0x%" PRIx64, n_value);
4208 if (pc.classMethods != 0)
4209 outs() << " + " << format("0x%" PRIx64, pc.classMethods);
4210 } else
4211 outs() << format("0x%" PRIx64, pc.classMethods);
4212 outs() << " (struct method_list_t *)\n";
4213 if (pc.classMethods + n_value != 0)
4214 print_method_list64_t(pc.classMethods + n_value, info, "\t");
4215
4216 outs() << "\t optionalInstanceMethods "
4217 << format("0x%" PRIx64, pc.optionalInstanceMethods) << "\n";
4218 outs() << "\t optionalClassMethods "
4219 << format("0x%" PRIx64, pc.optionalClassMethods) << "\n";
4220 outs() << "\t instanceProperties "
4221 << format("0x%" PRIx64, pc.instanceProperties) << "\n";
4222
4223 p += sizeof(uint64_t);
4224 offset += sizeof(uint64_t);
4225 }
4226}
4227
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004228static void print_protocol_list32_t(uint32_t p, struct DisassembleInfo *info) {
4229 struct protocol_list32_t pl;
4230 uint32_t q;
4231 struct protocol32_t pc;
4232 const char *r;
4233 uint32_t offset, xoffset, left, i;
4234 SectionRef S, xS;
4235 const char *name;
4236
4237 r = get_pointer_32(p, offset, left, S, info);
4238 if (r == nullptr)
4239 return;
4240 memset(&pl, '\0', sizeof(struct protocol_list32_t));
4241 if (left < sizeof(struct protocol_list32_t)) {
4242 memcpy(&pl, r, left);
4243 outs() << " (protocol_list_t entends past the end of the section)\n";
4244 } else
4245 memcpy(&pl, r, sizeof(struct protocol_list32_t));
4246 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4247 swapStruct(pl);
4248 outs() << " count " << pl.count << "\n";
4249
4250 p += sizeof(struct protocol_list32_t);
4251 offset += sizeof(struct protocol_list32_t);
4252 for (i = 0; i < pl.count; i++) {
4253 r = get_pointer_32(p, offset, left, S, info);
4254 if (r == nullptr)
4255 return;
4256 q = 0;
4257 if (left < sizeof(uint32_t)) {
4258 memcpy(&q, r, left);
4259 outs() << " (protocol_t * entends past the end of the section)\n";
4260 } else
4261 memcpy(&q, r, sizeof(uint32_t));
4262 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4263 sys::swapByteOrder(q);
4264 outs() << "\t\t list[" << i << "] " << format("0x%" PRIx32, q)
4265 << " (struct protocol_t *)\n";
4266 r = get_pointer_32(q, offset, left, S, info);
4267 if (r == nullptr)
4268 return;
4269 memset(&pc, '\0', sizeof(struct protocol32_t));
4270 if (left < sizeof(struct protocol32_t)) {
4271 memcpy(&pc, r, left);
4272 outs() << " (protocol_t entends past the end of the section)\n";
4273 } else
4274 memcpy(&pc, r, sizeof(struct protocol32_t));
4275 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4276 swapStruct(pc);
4277 outs() << "\t\t\t isa " << format("0x%" PRIx32, pc.isa) << "\n";
4278 outs() << "\t\t\t name " << format("0x%" PRIx32, pc.name);
4279 name = get_pointer_32(pc.name, xoffset, left, xS, info);
4280 if (name != nullptr)
4281 outs() << format(" %.*s", left, name);
4282 outs() << "\n";
4283 outs() << "\t\t\tprotocols " << format("0x%" PRIx32, pc.protocols) << "\n";
4284 outs() << "\t\t instanceMethods "
4285 << format("0x%" PRIx32, pc.instanceMethods)
4286 << " (struct method_list_t *)\n";
4287 if (pc.instanceMethods != 0)
4288 print_method_list32_t(pc.instanceMethods, info, "\t");
4289 outs() << "\t\t classMethods " << format("0x%" PRIx32, pc.classMethods)
4290 << " (struct method_list_t *)\n";
4291 if (pc.classMethods != 0)
4292 print_method_list32_t(pc.classMethods, info, "\t");
4293 outs() << "\t optionalInstanceMethods "
4294 << format("0x%" PRIx32, pc.optionalInstanceMethods) << "\n";
4295 outs() << "\t optionalClassMethods "
4296 << format("0x%" PRIx32, pc.optionalClassMethods) << "\n";
4297 outs() << "\t instanceProperties "
4298 << format("0x%" PRIx32, pc.instanceProperties) << "\n";
4299 p += sizeof(uint32_t);
4300 offset += sizeof(uint32_t);
4301 }
4302}
4303
Kevin Enderby846c0002015-04-16 17:19:59 +00004304static void print_indent(uint32_t indent) {
4305 for (uint32_t i = 0; i < indent;) {
4306 if (indent - i >= 8) {
4307 outs() << "\t";
4308 i += 8;
4309 } else {
4310 for (uint32_t j = i; j < indent; j++)
4311 outs() << " ";
4312 return;
4313 }
4314 }
4315}
4316
4317static bool print_method_description_list(uint32_t p, uint32_t indent,
4318 struct DisassembleInfo *info) {
4319 uint32_t offset, left, xleft;
4320 SectionRef S;
4321 struct objc_method_description_list_t mdl;
4322 struct objc_method_description_t md;
4323 const char *r, *list, *name;
4324 int32_t i;
4325
4326 r = get_pointer_32(p, offset, left, S, info, true);
4327 if (r == nullptr)
4328 return true;
4329
4330 outs() << "\n";
4331 if (left > sizeof(struct objc_method_description_list_t)) {
4332 memcpy(&mdl, r, sizeof(struct objc_method_description_list_t));
4333 } else {
4334 print_indent(indent);
4335 outs() << " objc_method_description_list extends past end of the section\n";
4336 memset(&mdl, '\0', sizeof(struct objc_method_description_list_t));
4337 memcpy(&mdl, r, left);
4338 }
4339 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4340 swapStruct(mdl);
4341
4342 print_indent(indent);
4343 outs() << " count " << mdl.count << "\n";
4344
4345 list = r + sizeof(struct objc_method_description_list_t);
4346 for (i = 0; i < mdl.count; i++) {
4347 if ((i + 1) * sizeof(struct objc_method_description_t) > left) {
4348 print_indent(indent);
4349 outs() << " remaining list entries extend past the of the section\n";
4350 break;
4351 }
4352 print_indent(indent);
4353 outs() << " list[" << i << "]\n";
4354 memcpy(&md, list + i * sizeof(struct objc_method_description_t),
4355 sizeof(struct objc_method_description_t));
4356 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4357 swapStruct(md);
4358
4359 print_indent(indent);
4360 outs() << " name " << format("0x%08" PRIx32, md.name);
4361 if (info->verbose) {
4362 name = get_pointer_32(md.name, offset, xleft, S, info, true);
4363 if (name != nullptr)
4364 outs() << format(" %.*s", xleft, name);
4365 else
4366 outs() << " (not in an __OBJC section)";
4367 }
4368 outs() << "\n";
4369
4370 print_indent(indent);
4371 outs() << " types " << format("0x%08" PRIx32, md.types);
4372 if (info->verbose) {
4373 name = get_pointer_32(md.types, offset, xleft, S, info, true);
4374 if (name != nullptr)
4375 outs() << format(" %.*s", xleft, name);
4376 else
4377 outs() << " (not in an __OBJC section)";
4378 }
4379 outs() << "\n";
4380 }
4381 return false;
4382}
4383
4384static bool print_protocol_list(uint32_t p, uint32_t indent,
4385 struct DisassembleInfo *info);
4386
4387static bool print_protocol(uint32_t p, uint32_t indent,
4388 struct DisassembleInfo *info) {
4389 uint32_t offset, left;
4390 SectionRef S;
4391 struct objc_protocol_t protocol;
4392 const char *r, *name;
4393
4394 r = get_pointer_32(p, offset, left, S, info, true);
4395 if (r == nullptr)
4396 return true;
4397
4398 outs() << "\n";
4399 if (left >= sizeof(struct objc_protocol_t)) {
4400 memcpy(&protocol, r, sizeof(struct objc_protocol_t));
4401 } else {
4402 print_indent(indent);
4403 outs() << " Protocol extends past end of the section\n";
4404 memset(&protocol, '\0', sizeof(struct objc_protocol_t));
4405 memcpy(&protocol, r, left);
4406 }
4407 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4408 swapStruct(protocol);
4409
4410 print_indent(indent);
4411 outs() << " isa " << format("0x%08" PRIx32, protocol.isa)
4412 << "\n";
4413
4414 print_indent(indent);
4415 outs() << " protocol_name "
4416 << format("0x%08" PRIx32, protocol.protocol_name);
4417 if (info->verbose) {
4418 name = get_pointer_32(protocol.protocol_name, offset, left, S, info, true);
4419 if (name != nullptr)
4420 outs() << format(" %.*s", left, name);
4421 else
4422 outs() << " (not in an __OBJC section)";
4423 }
4424 outs() << "\n";
4425
4426 print_indent(indent);
4427 outs() << " protocol_list "
4428 << format("0x%08" PRIx32, protocol.protocol_list);
4429 if (print_protocol_list(protocol.protocol_list, indent + 4, info))
4430 outs() << " (not in an __OBJC section)\n";
4431
4432 print_indent(indent);
4433 outs() << " instance_methods "
4434 << format("0x%08" PRIx32, protocol.instance_methods);
4435 if (print_method_description_list(protocol.instance_methods, indent, info))
4436 outs() << " (not in an __OBJC section)\n";
4437
4438 print_indent(indent);
4439 outs() << " class_methods "
4440 << format("0x%08" PRIx32, protocol.class_methods);
4441 if (print_method_description_list(protocol.class_methods, indent, info))
4442 outs() << " (not in an __OBJC section)\n";
4443
4444 return false;
4445}
4446
4447static bool print_protocol_list(uint32_t p, uint32_t indent,
4448 struct DisassembleInfo *info) {
4449 uint32_t offset, left, l;
4450 SectionRef S;
4451 struct objc_protocol_list_t protocol_list;
4452 const char *r, *list;
4453 int32_t i;
4454
4455 r = get_pointer_32(p, offset, left, S, info, true);
4456 if (r == nullptr)
4457 return true;
4458
4459 outs() << "\n";
4460 if (left > sizeof(struct objc_protocol_list_t)) {
4461 memcpy(&protocol_list, r, sizeof(struct objc_protocol_list_t));
4462 } else {
4463 outs() << "\t\t objc_protocol_list_t extends past end of the section\n";
4464 memset(&protocol_list, '\0', sizeof(struct objc_protocol_list_t));
4465 memcpy(&protocol_list, r, left);
4466 }
4467 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4468 swapStruct(protocol_list);
4469
4470 print_indent(indent);
4471 outs() << " next " << format("0x%08" PRIx32, protocol_list.next)
4472 << "\n";
4473 print_indent(indent);
4474 outs() << " count " << protocol_list.count << "\n";
4475
4476 list = r + sizeof(struct objc_protocol_list_t);
4477 for (i = 0; i < protocol_list.count; i++) {
4478 if ((i + 1) * sizeof(uint32_t) > left) {
4479 outs() << "\t\t remaining list entries extend past the of the section\n";
4480 break;
4481 }
4482 memcpy(&l, list + i * sizeof(uint32_t), sizeof(uint32_t));
4483 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4484 sys::swapByteOrder(l);
4485
4486 print_indent(indent);
4487 outs() << " list[" << i << "] " << format("0x%08" PRIx32, l);
4488 if (print_protocol(l, indent, info))
4489 outs() << "(not in an __OBJC section)\n";
4490 }
4491 return false;
4492}
4493
Kevin Enderby0fc11822015-04-01 20:57:01 +00004494static void print_ivar_list64_t(uint64_t p, struct DisassembleInfo *info) {
4495 struct ivar_list64_t il;
4496 struct ivar64_t i;
4497 const char *r;
4498 uint32_t offset, xoffset, left, j;
4499 SectionRef S, xS;
4500 const char *name, *sym_name, *ivar_offset_p;
4501 uint64_t ivar_offset, n_value;
4502
4503 r = get_pointer_64(p, offset, left, S, info);
4504 if (r == nullptr)
4505 return;
4506 memset(&il, '\0', sizeof(struct ivar_list64_t));
4507 if (left < sizeof(struct ivar_list64_t)) {
4508 memcpy(&il, r, left);
4509 outs() << " (ivar_list_t entends past the end of the section)\n";
4510 } else
4511 memcpy(&il, r, sizeof(struct ivar_list64_t));
4512 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4513 swapStruct(il);
4514 outs() << " entsize " << il.entsize << "\n";
4515 outs() << " count " << il.count << "\n";
4516
4517 p += sizeof(struct ivar_list64_t);
4518 offset += sizeof(struct ivar_list64_t);
4519 for (j = 0; j < il.count; j++) {
4520 r = get_pointer_64(p, offset, left, S, info);
4521 if (r == nullptr)
4522 return;
4523 memset(&i, '\0', sizeof(struct ivar64_t));
4524 if (left < sizeof(struct ivar64_t)) {
4525 memcpy(&i, r, left);
4526 outs() << " (ivar_t entends past the end of the section)\n";
4527 } else
4528 memcpy(&i, r, sizeof(struct ivar64_t));
4529 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4530 swapStruct(i);
4531
4532 outs() << "\t\t\t offset ";
4533 sym_name = get_symbol_64(offset + offsetof(struct ivar64_t, offset), S,
4534 info, n_value, i.offset);
4535 if (n_value != 0) {
4536 if (info->verbose && sym_name != nullptr)
4537 outs() << sym_name;
4538 else
4539 outs() << format("0x%" PRIx64, n_value);
4540 if (i.offset != 0)
4541 outs() << " + " << format("0x%" PRIx64, i.offset);
4542 } else
4543 outs() << format("0x%" PRIx64, i.offset);
4544 ivar_offset_p = get_pointer_64(i.offset + n_value, xoffset, left, xS, info);
4545 if (ivar_offset_p != nullptr && left >= sizeof(*ivar_offset_p)) {
4546 memcpy(&ivar_offset, ivar_offset_p, sizeof(ivar_offset));
4547 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4548 sys::swapByteOrder(ivar_offset);
4549 outs() << " " << ivar_offset << "\n";
4550 } else
4551 outs() << "\n";
4552
4553 outs() << "\t\t\t name ";
4554 sym_name = get_symbol_64(offset + offsetof(struct ivar64_t, name), S, info,
4555 n_value, i.name);
4556 if (n_value != 0) {
4557 if (info->verbose && sym_name != nullptr)
4558 outs() << sym_name;
4559 else
4560 outs() << format("0x%" PRIx64, n_value);
4561 if (i.name != 0)
4562 outs() << " + " << format("0x%" PRIx64, i.name);
4563 } else
4564 outs() << format("0x%" PRIx64, i.name);
4565 name = get_pointer_64(i.name + n_value, xoffset, left, xS, info);
4566 if (name != nullptr)
4567 outs() << format(" %.*s", left, name);
4568 outs() << "\n";
4569
4570 outs() << "\t\t\t type ";
4571 sym_name = get_symbol_64(offset + offsetof(struct ivar64_t, type), S, info,
4572 n_value, i.name);
4573 name = get_pointer_64(i.type + n_value, xoffset, left, xS, info);
4574 if (n_value != 0) {
4575 if (info->verbose && sym_name != nullptr)
4576 outs() << sym_name;
4577 else
4578 outs() << format("0x%" PRIx64, n_value);
4579 if (i.type != 0)
4580 outs() << " + " << format("0x%" PRIx64, i.type);
4581 } else
4582 outs() << format("0x%" PRIx64, i.type);
4583 if (name != nullptr)
4584 outs() << format(" %.*s", left, name);
4585 outs() << "\n";
4586
4587 outs() << "\t\t\talignment " << i.alignment << "\n";
4588 outs() << "\t\t\t size " << i.size << "\n";
4589
4590 p += sizeof(struct ivar64_t);
4591 offset += sizeof(struct ivar64_t);
4592 }
4593}
4594
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004595static void print_ivar_list32_t(uint32_t p, struct DisassembleInfo *info) {
4596 struct ivar_list32_t il;
4597 struct ivar32_t i;
4598 const char *r;
4599 uint32_t offset, xoffset, left, j;
4600 SectionRef S, xS;
4601 const char *name, *ivar_offset_p;
4602 uint32_t ivar_offset;
4603
4604 r = get_pointer_32(p, offset, left, S, info);
4605 if (r == nullptr)
4606 return;
4607 memset(&il, '\0', sizeof(struct ivar_list32_t));
4608 if (left < sizeof(struct ivar_list32_t)) {
4609 memcpy(&il, r, left);
4610 outs() << " (ivar_list_t entends past the end of the section)\n";
4611 } else
4612 memcpy(&il, r, sizeof(struct ivar_list32_t));
4613 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4614 swapStruct(il);
4615 outs() << " entsize " << il.entsize << "\n";
4616 outs() << " count " << il.count << "\n";
4617
4618 p += sizeof(struct ivar_list32_t);
4619 offset += sizeof(struct ivar_list32_t);
4620 for (j = 0; j < il.count; j++) {
4621 r = get_pointer_32(p, offset, left, S, info);
4622 if (r == nullptr)
4623 return;
4624 memset(&i, '\0', sizeof(struct ivar32_t));
4625 if (left < sizeof(struct ivar32_t)) {
4626 memcpy(&i, r, left);
4627 outs() << " (ivar_t entends past the end of the section)\n";
4628 } else
4629 memcpy(&i, r, sizeof(struct ivar32_t));
4630 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4631 swapStruct(i);
4632
4633 outs() << "\t\t\t offset " << format("0x%" PRIx32, i.offset);
4634 ivar_offset_p = get_pointer_32(i.offset, xoffset, left, xS, info);
4635 if (ivar_offset_p != nullptr && left >= sizeof(*ivar_offset_p)) {
4636 memcpy(&ivar_offset, ivar_offset_p, sizeof(ivar_offset));
4637 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4638 sys::swapByteOrder(ivar_offset);
4639 outs() << " " << ivar_offset << "\n";
4640 } else
4641 outs() << "\n";
4642
4643 outs() << "\t\t\t name " << format("0x%" PRIx32, i.name);
4644 name = get_pointer_32(i.name, xoffset, left, xS, info);
4645 if (name != nullptr)
4646 outs() << format(" %.*s", left, name);
4647 outs() << "\n";
4648
4649 outs() << "\t\t\t type " << format("0x%" PRIx32, i.type);
4650 name = get_pointer_32(i.type, xoffset, left, xS, info);
4651 if (name != nullptr)
4652 outs() << format(" %.*s", left, name);
4653 outs() << "\n";
4654
4655 outs() << "\t\t\talignment " << i.alignment << "\n";
4656 outs() << "\t\t\t size " << i.size << "\n";
4657
4658 p += sizeof(struct ivar32_t);
4659 offset += sizeof(struct ivar32_t);
4660 }
4661}
4662
Kevin Enderby0fc11822015-04-01 20:57:01 +00004663static void print_objc_property_list64(uint64_t p,
4664 struct DisassembleInfo *info) {
4665 struct objc_property_list64 opl;
4666 struct objc_property64 op;
4667 const char *r;
4668 uint32_t offset, xoffset, left, j;
4669 SectionRef S, xS;
4670 const char *name, *sym_name;
4671 uint64_t n_value;
4672
4673 r = get_pointer_64(p, offset, left, S, info);
4674 if (r == nullptr)
4675 return;
4676 memset(&opl, '\0', sizeof(struct objc_property_list64));
4677 if (left < sizeof(struct objc_property_list64)) {
4678 memcpy(&opl, r, left);
4679 outs() << " (objc_property_list entends past the end of the section)\n";
4680 } else
4681 memcpy(&opl, r, sizeof(struct objc_property_list64));
4682 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4683 swapStruct(opl);
4684 outs() << " entsize " << opl.entsize << "\n";
4685 outs() << " count " << opl.count << "\n";
4686
4687 p += sizeof(struct objc_property_list64);
4688 offset += sizeof(struct objc_property_list64);
4689 for (j = 0; j < opl.count; j++) {
4690 r = get_pointer_64(p, offset, left, S, info);
4691 if (r == nullptr)
4692 return;
4693 memset(&op, '\0', sizeof(struct objc_property64));
4694 if (left < sizeof(struct objc_property64)) {
4695 memcpy(&op, r, left);
4696 outs() << " (objc_property entends past the end of the section)\n";
4697 } else
4698 memcpy(&op, r, sizeof(struct objc_property64));
4699 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4700 swapStruct(op);
4701
4702 outs() << "\t\t\t name ";
4703 sym_name = get_symbol_64(offset + offsetof(struct objc_property64, name), S,
4704 info, n_value, op.name);
4705 if (n_value != 0) {
4706 if (info->verbose && sym_name != nullptr)
4707 outs() << sym_name;
4708 else
4709 outs() << format("0x%" PRIx64, n_value);
4710 if (op.name != 0)
4711 outs() << " + " << format("0x%" PRIx64, op.name);
4712 } else
4713 outs() << format("0x%" PRIx64, op.name);
4714 name = get_pointer_64(op.name + n_value, xoffset, left, xS, info);
4715 if (name != nullptr)
4716 outs() << format(" %.*s", left, name);
4717 outs() << "\n";
4718
4719 outs() << "\t\t\tattributes ";
4720 sym_name =
4721 get_symbol_64(offset + offsetof(struct objc_property64, attributes), S,
4722 info, n_value, op.attributes);
4723 if (n_value != 0) {
4724 if (info->verbose && sym_name != nullptr)
4725 outs() << sym_name;
4726 else
4727 outs() << format("0x%" PRIx64, n_value);
4728 if (op.attributes != 0)
4729 outs() << " + " << format("0x%" PRIx64, op.attributes);
4730 } else
4731 outs() << format("0x%" PRIx64, op.attributes);
4732 name = get_pointer_64(op.attributes + n_value, xoffset, left, xS, info);
4733 if (name != nullptr)
4734 outs() << format(" %.*s", left, name);
4735 outs() << "\n";
4736
4737 p += sizeof(struct objc_property64);
4738 offset += sizeof(struct objc_property64);
4739 }
4740}
4741
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004742static void print_objc_property_list32(uint32_t p,
4743 struct DisassembleInfo *info) {
4744 struct objc_property_list32 opl;
4745 struct objc_property32 op;
4746 const char *r;
4747 uint32_t offset, xoffset, left, j;
4748 SectionRef S, xS;
4749 const char *name;
4750
4751 r = get_pointer_32(p, offset, left, S, info);
4752 if (r == nullptr)
4753 return;
4754 memset(&opl, '\0', sizeof(struct objc_property_list32));
4755 if (left < sizeof(struct objc_property_list32)) {
4756 memcpy(&opl, r, left);
4757 outs() << " (objc_property_list entends past the end of the section)\n";
4758 } else
4759 memcpy(&opl, r, sizeof(struct objc_property_list32));
4760 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4761 swapStruct(opl);
4762 outs() << " entsize " << opl.entsize << "\n";
4763 outs() << " count " << opl.count << "\n";
4764
4765 p += sizeof(struct objc_property_list32);
4766 offset += sizeof(struct objc_property_list32);
4767 for (j = 0; j < opl.count; j++) {
4768 r = get_pointer_32(p, offset, left, S, info);
4769 if (r == nullptr)
4770 return;
4771 memset(&op, '\0', sizeof(struct objc_property32));
4772 if (left < sizeof(struct objc_property32)) {
4773 memcpy(&op, r, left);
4774 outs() << " (objc_property entends past the end of the section)\n";
4775 } else
4776 memcpy(&op, r, sizeof(struct objc_property32));
4777 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4778 swapStruct(op);
4779
4780 outs() << "\t\t\t name " << format("0x%" PRIx32, op.name);
4781 name = get_pointer_32(op.name, xoffset, left, xS, info);
4782 if (name != nullptr)
4783 outs() << format(" %.*s", left, name);
4784 outs() << "\n";
4785
4786 outs() << "\t\t\tattributes " << format("0x%" PRIx32, op.attributes);
4787 name = get_pointer_32(op.attributes, xoffset, left, xS, info);
4788 if (name != nullptr)
4789 outs() << format(" %.*s", left, name);
4790 outs() << "\n";
4791
4792 p += sizeof(struct objc_property32);
4793 offset += sizeof(struct objc_property32);
4794 }
4795}
4796
Richard Smith81ff44d2015-10-09 22:09:56 +00004797static bool print_class_ro64_t(uint64_t p, struct DisassembleInfo *info,
Kevin Enderby0fc11822015-04-01 20:57:01 +00004798 bool &is_meta_class) {
4799 struct class_ro64_t cro;
4800 const char *r;
4801 uint32_t offset, xoffset, left;
4802 SectionRef S, xS;
4803 const char *name, *sym_name;
4804 uint64_t n_value;
4805
4806 r = get_pointer_64(p, offset, left, S, info);
4807 if (r == nullptr || left < sizeof(struct class_ro64_t))
Richard Smith81ff44d2015-10-09 22:09:56 +00004808 return false;
Chandler Carruth33e58902016-11-04 07:10:24 +00004809 memcpy(&cro, r, sizeof(struct class_ro64_t));
Kevin Enderby0fc11822015-04-01 20:57:01 +00004810 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4811 swapStruct(cro);
4812 outs() << " flags " << format("0x%" PRIx32, cro.flags);
4813 if (cro.flags & RO_META)
4814 outs() << " RO_META";
4815 if (cro.flags & RO_ROOT)
4816 outs() << " RO_ROOT";
4817 if (cro.flags & RO_HAS_CXX_STRUCTORS)
4818 outs() << " RO_HAS_CXX_STRUCTORS";
4819 outs() << "\n";
4820 outs() << " instanceStart " << cro.instanceStart << "\n";
4821 outs() << " instanceSize " << cro.instanceSize << "\n";
4822 outs() << " reserved " << format("0x%" PRIx32, cro.reserved)
4823 << "\n";
4824 outs() << " ivarLayout " << format("0x%" PRIx64, cro.ivarLayout)
4825 << "\n";
4826 print_layout_map64(cro.ivarLayout, info);
4827
4828 outs() << " name ";
4829 sym_name = get_symbol_64(offset + offsetof(struct class_ro64_t, name), S,
4830 info, n_value, cro.name);
4831 if (n_value != 0) {
4832 if (info->verbose && sym_name != nullptr)
4833 outs() << sym_name;
4834 else
4835 outs() << format("0x%" PRIx64, n_value);
4836 if (cro.name != 0)
4837 outs() << " + " << format("0x%" PRIx64, cro.name);
4838 } else
4839 outs() << format("0x%" PRIx64, cro.name);
4840 name = get_pointer_64(cro.name + n_value, xoffset, left, xS, info);
4841 if (name != nullptr)
4842 outs() << format(" %.*s", left, name);
4843 outs() << "\n";
4844
4845 outs() << " baseMethods ";
4846 sym_name = get_symbol_64(offset + offsetof(struct class_ro64_t, baseMethods),
4847 S, info, n_value, cro.baseMethods);
4848 if (n_value != 0) {
4849 if (info->verbose && sym_name != nullptr)
4850 outs() << sym_name;
4851 else
4852 outs() << format("0x%" PRIx64, n_value);
4853 if (cro.baseMethods != 0)
4854 outs() << " + " << format("0x%" PRIx64, cro.baseMethods);
4855 } else
4856 outs() << format("0x%" PRIx64, cro.baseMethods);
4857 outs() << " (struct method_list_t *)\n";
4858 if (cro.baseMethods + n_value != 0)
4859 print_method_list64_t(cro.baseMethods + n_value, info, "");
4860
4861 outs() << " baseProtocols ";
4862 sym_name =
4863 get_symbol_64(offset + offsetof(struct class_ro64_t, baseProtocols), S,
4864 info, n_value, cro.baseProtocols);
4865 if (n_value != 0) {
4866 if (info->verbose && sym_name != nullptr)
4867 outs() << sym_name;
4868 else
4869 outs() << format("0x%" PRIx64, n_value);
4870 if (cro.baseProtocols != 0)
4871 outs() << " + " << format("0x%" PRIx64, cro.baseProtocols);
4872 } else
4873 outs() << format("0x%" PRIx64, cro.baseProtocols);
4874 outs() << "\n";
4875 if (cro.baseProtocols + n_value != 0)
4876 print_protocol_list64_t(cro.baseProtocols + n_value, info);
4877
4878 outs() << " ivars ";
4879 sym_name = get_symbol_64(offset + offsetof(struct class_ro64_t, ivars), S,
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004880 info, n_value, cro.ivars);
Kevin Enderby0fc11822015-04-01 20:57:01 +00004881 if (n_value != 0) {
4882 if (info->verbose && sym_name != nullptr)
4883 outs() << sym_name;
4884 else
4885 outs() << format("0x%" PRIx64, n_value);
4886 if (cro.ivars != 0)
4887 outs() << " + " << format("0x%" PRIx64, cro.ivars);
4888 } else
4889 outs() << format("0x%" PRIx64, cro.ivars);
4890 outs() << "\n";
4891 if (cro.ivars + n_value != 0)
4892 print_ivar_list64_t(cro.ivars + n_value, info);
4893
4894 outs() << " weakIvarLayout ";
4895 sym_name =
4896 get_symbol_64(offset + offsetof(struct class_ro64_t, weakIvarLayout), S,
4897 info, n_value, cro.weakIvarLayout);
4898 if (n_value != 0) {
4899 if (info->verbose && sym_name != nullptr)
4900 outs() << sym_name;
4901 else
4902 outs() << format("0x%" PRIx64, n_value);
4903 if (cro.weakIvarLayout != 0)
4904 outs() << " + " << format("0x%" PRIx64, cro.weakIvarLayout);
4905 } else
4906 outs() << format("0x%" PRIx64, cro.weakIvarLayout);
4907 outs() << "\n";
4908 print_layout_map64(cro.weakIvarLayout + n_value, info);
4909
4910 outs() << " baseProperties ";
4911 sym_name =
4912 get_symbol_64(offset + offsetof(struct class_ro64_t, baseProperties), S,
4913 info, n_value, cro.baseProperties);
4914 if (n_value != 0) {
4915 if (info->verbose && sym_name != nullptr)
4916 outs() << sym_name;
4917 else
4918 outs() << format("0x%" PRIx64, n_value);
4919 if (cro.baseProperties != 0)
4920 outs() << " + " << format("0x%" PRIx64, cro.baseProperties);
4921 } else
4922 outs() << format("0x%" PRIx64, cro.baseProperties);
4923 outs() << "\n";
4924 if (cro.baseProperties + n_value != 0)
4925 print_objc_property_list64(cro.baseProperties + n_value, info);
4926
Rafael Espindolab9091322015-10-24 23:19:10 +00004927 is_meta_class = (cro.flags & RO_META) != 0;
Richard Smith81ff44d2015-10-09 22:09:56 +00004928 return true;
Kevin Enderby0fc11822015-04-01 20:57:01 +00004929}
4930
Richard Smith81ff44d2015-10-09 22:09:56 +00004931static bool print_class_ro32_t(uint32_t p, struct DisassembleInfo *info,
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004932 bool &is_meta_class) {
4933 struct class_ro32_t cro;
4934 const char *r;
4935 uint32_t offset, xoffset, left;
4936 SectionRef S, xS;
4937 const char *name;
4938
4939 r = get_pointer_32(p, offset, left, S, info);
4940 if (r == nullptr)
Richard Smith81ff44d2015-10-09 22:09:56 +00004941 return false;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004942 memset(&cro, '\0', sizeof(struct class_ro32_t));
4943 if (left < sizeof(struct class_ro32_t)) {
4944 memcpy(&cro, r, left);
4945 outs() << " (class_ro_t entends past the end of the section)\n";
4946 } else
4947 memcpy(&cro, r, sizeof(struct class_ro32_t));
4948 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4949 swapStruct(cro);
4950 outs() << " flags " << format("0x%" PRIx32, cro.flags);
4951 if (cro.flags & RO_META)
4952 outs() << " RO_META";
4953 if (cro.flags & RO_ROOT)
4954 outs() << " RO_ROOT";
4955 if (cro.flags & RO_HAS_CXX_STRUCTORS)
4956 outs() << " RO_HAS_CXX_STRUCTORS";
4957 outs() << "\n";
4958 outs() << " instanceStart " << cro.instanceStart << "\n";
4959 outs() << " instanceSize " << cro.instanceSize << "\n";
4960 outs() << " ivarLayout " << format("0x%" PRIx32, cro.ivarLayout)
4961 << "\n";
4962 print_layout_map32(cro.ivarLayout, info);
4963
4964 outs() << " name " << format("0x%" PRIx32, cro.name);
4965 name = get_pointer_32(cro.name, xoffset, left, xS, info);
4966 if (name != nullptr)
4967 outs() << format(" %.*s", left, name);
4968 outs() << "\n";
4969
4970 outs() << " baseMethods "
4971 << format("0x%" PRIx32, cro.baseMethods)
4972 << " (struct method_list_t *)\n";
4973 if (cro.baseMethods != 0)
4974 print_method_list32_t(cro.baseMethods, info, "");
4975
4976 outs() << " baseProtocols "
4977 << format("0x%" PRIx32, cro.baseProtocols) << "\n";
4978 if (cro.baseProtocols != 0)
4979 print_protocol_list32_t(cro.baseProtocols, info);
4980 outs() << " ivars " << format("0x%" PRIx32, cro.ivars)
4981 << "\n";
4982 if (cro.ivars != 0)
4983 print_ivar_list32_t(cro.ivars, info);
4984 outs() << " weakIvarLayout "
4985 << format("0x%" PRIx32, cro.weakIvarLayout) << "\n";
4986 print_layout_map32(cro.weakIvarLayout, info);
4987 outs() << " baseProperties "
4988 << format("0x%" PRIx32, cro.baseProperties) << "\n";
4989 if (cro.baseProperties != 0)
4990 print_objc_property_list32(cro.baseProperties, info);
Rafael Espindolab9091322015-10-24 23:19:10 +00004991 is_meta_class = (cro.flags & RO_META) != 0;
Richard Smith81ff44d2015-10-09 22:09:56 +00004992 return true;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004993}
4994
Kevin Enderby0fc11822015-04-01 20:57:01 +00004995static void print_class64_t(uint64_t p, struct DisassembleInfo *info) {
4996 struct class64_t c;
4997 const char *r;
4998 uint32_t offset, left;
4999 SectionRef S;
5000 const char *name;
5001 uint64_t isa_n_value, n_value;
5002
5003 r = get_pointer_64(p, offset, left, S, info);
5004 if (r == nullptr || left < sizeof(struct class64_t))
5005 return;
Chandler Carruth33e58902016-11-04 07:10:24 +00005006 memcpy(&c, r, sizeof(struct class64_t));
Kevin Enderby0fc11822015-04-01 20:57:01 +00005007 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5008 swapStruct(c);
5009
5010 outs() << " isa " << format("0x%" PRIx64, c.isa);
5011 name = get_symbol_64(offset + offsetof(struct class64_t, isa), S, info,
5012 isa_n_value, c.isa);
5013 if (name != nullptr)
5014 outs() << " " << name;
5015 outs() << "\n";
5016
5017 outs() << " superclass " << format("0x%" PRIx64, c.superclass);
5018 name = get_symbol_64(offset + offsetof(struct class64_t, superclass), S, info,
5019 n_value, c.superclass);
5020 if (name != nullptr)
5021 outs() << " " << name;
Kevin Enderby1ce38582017-06-20 22:55:11 +00005022 else {
5023 name = get_dyld_bind_info_symbolname(S.getAddress() +
5024 offset + offsetof(struct class64_t, superclass), info);
5025 if (name != nullptr)
5026 outs() << " " << name;
5027 }
Kevin Enderby0fc11822015-04-01 20:57:01 +00005028 outs() << "\n";
5029
5030 outs() << " cache " << format("0x%" PRIx64, c.cache);
5031 name = get_symbol_64(offset + offsetof(struct class64_t, cache), S, info,
5032 n_value, c.cache);
5033 if (name != nullptr)
5034 outs() << " " << name;
5035 outs() << "\n";
5036
5037 outs() << " vtable " << format("0x%" PRIx64, c.vtable);
5038 name = get_symbol_64(offset + offsetof(struct class64_t, vtable), S, info,
5039 n_value, c.vtable);
5040 if (name != nullptr)
5041 outs() << " " << name;
5042 outs() << "\n";
5043
5044 name = get_symbol_64(offset + offsetof(struct class64_t, data), S, info,
5045 n_value, c.data);
5046 outs() << " data ";
5047 if (n_value != 0) {
5048 if (info->verbose && name != nullptr)
5049 outs() << name;
5050 else
5051 outs() << format("0x%" PRIx64, n_value);
5052 if (c.data != 0)
5053 outs() << " + " << format("0x%" PRIx64, c.data);
5054 } else
5055 outs() << format("0x%" PRIx64, c.data);
5056 outs() << " (struct class_ro_t *)";
5057
5058 // This is a Swift class if some of the low bits of the pointer are set.
5059 if ((c.data + n_value) & 0x7)
5060 outs() << " Swift class";
5061 outs() << "\n";
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005062 bool is_meta_class;
Richard Smith81ff44d2015-10-09 22:09:56 +00005063 if (!print_class_ro64_t((c.data + n_value) & ~0x7, info, is_meta_class))
5064 return;
Kevin Enderby0fc11822015-04-01 20:57:01 +00005065
Kevin Enderbyaac75382015-10-08 16:56:35 +00005066 if (!is_meta_class &&
5067 c.isa + isa_n_value != p &&
5068 c.isa + isa_n_value != 0 &&
5069 info->depth < 100) {
5070 info->depth++;
5071 outs() << "Meta Class\n";
5072 print_class64_t(c.isa + isa_n_value, info);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005073 }
5074}
5075
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005076static void print_class32_t(uint32_t p, struct DisassembleInfo *info) {
5077 struct class32_t c;
5078 const char *r;
5079 uint32_t offset, left;
5080 SectionRef S;
5081 const char *name;
5082
5083 r = get_pointer_32(p, offset, left, S, info);
5084 if (r == nullptr)
5085 return;
5086 memset(&c, '\0', sizeof(struct class32_t));
5087 if (left < sizeof(struct class32_t)) {
5088 memcpy(&c, r, left);
5089 outs() << " (class_t entends past the end of the section)\n";
5090 } else
5091 memcpy(&c, r, sizeof(struct class32_t));
5092 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5093 swapStruct(c);
5094
5095 outs() << " isa " << format("0x%" PRIx32, c.isa);
5096 name =
5097 get_symbol_32(offset + offsetof(struct class32_t, isa), S, info, c.isa);
5098 if (name != nullptr)
5099 outs() << " " << name;
5100 outs() << "\n";
5101
5102 outs() << " superclass " << format("0x%" PRIx32, c.superclass);
5103 name = get_symbol_32(offset + offsetof(struct class32_t, superclass), S, info,
5104 c.superclass);
5105 if (name != nullptr)
5106 outs() << " " << name;
5107 outs() << "\n";
5108
5109 outs() << " cache " << format("0x%" PRIx32, c.cache);
5110 name = get_symbol_32(offset + offsetof(struct class32_t, cache), S, info,
5111 c.cache);
5112 if (name != nullptr)
5113 outs() << " " << name;
5114 outs() << "\n";
5115
5116 outs() << " vtable " << format("0x%" PRIx32, c.vtable);
5117 name = get_symbol_32(offset + offsetof(struct class32_t, vtable), S, info,
5118 c.vtable);
5119 if (name != nullptr)
5120 outs() << " " << name;
5121 outs() << "\n";
5122
5123 name =
5124 get_symbol_32(offset + offsetof(struct class32_t, data), S, info, c.data);
5125 outs() << " data " << format("0x%" PRIx32, c.data)
5126 << " (struct class_ro_t *)";
5127
5128 // This is a Swift class if some of the low bits of the pointer are set.
5129 if (c.data & 0x3)
5130 outs() << " Swift class";
5131 outs() << "\n";
5132 bool is_meta_class;
Richard Smith81ff44d2015-10-09 22:09:56 +00005133 if (!print_class_ro32_t(c.data & ~0x3, info, is_meta_class))
5134 return;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005135
Hans Wennborgcc9deb42015-09-29 18:02:48 +00005136 if (!is_meta_class) {
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005137 outs() << "Meta Class\n";
5138 print_class32_t(c.isa, info);
5139 }
5140}
5141
Kevin Enderby846c0002015-04-16 17:19:59 +00005142static void print_objc_class_t(struct objc_class_t *objc_class,
5143 struct DisassembleInfo *info) {
5144 uint32_t offset, left, xleft;
5145 const char *name, *p, *ivar_list;
5146 SectionRef S;
5147 int32_t i;
5148 struct objc_ivar_list_t objc_ivar_list;
5149 struct objc_ivar_t ivar;
5150
5151 outs() << "\t\t isa " << format("0x%08" PRIx32, objc_class->isa);
5152 if (info->verbose && CLS_GETINFO(objc_class, CLS_META)) {
5153 name = get_pointer_32(objc_class->isa, offset, left, S, info, true);
5154 if (name != nullptr)
5155 outs() << format(" %.*s", left, name);
5156 else
5157 outs() << " (not in an __OBJC section)";
5158 }
5159 outs() << "\n";
5160
5161 outs() << "\t super_class "
5162 << format("0x%08" PRIx32, objc_class->super_class);
5163 if (info->verbose) {
5164 name = get_pointer_32(objc_class->super_class, offset, left, S, info, true);
5165 if (name != nullptr)
5166 outs() << format(" %.*s", left, name);
5167 else
5168 outs() << " (not in an __OBJC section)";
5169 }
5170 outs() << "\n";
5171
5172 outs() << "\t\t name " << format("0x%08" PRIx32, objc_class->name);
5173 if (info->verbose) {
5174 name = get_pointer_32(objc_class->name, offset, left, S, info, true);
5175 if (name != nullptr)
5176 outs() << format(" %.*s", left, name);
5177 else
5178 outs() << " (not in an __OBJC section)";
5179 }
5180 outs() << "\n";
5181
5182 outs() << "\t\t version " << format("0x%08" PRIx32, objc_class->version)
5183 << "\n";
5184
5185 outs() << "\t\t info " << format("0x%08" PRIx32, objc_class->info);
5186 if (info->verbose) {
5187 if (CLS_GETINFO(objc_class, CLS_CLASS))
5188 outs() << " CLS_CLASS";
5189 else if (CLS_GETINFO(objc_class, CLS_META))
5190 outs() << " CLS_META";
5191 }
5192 outs() << "\n";
5193
5194 outs() << "\t instance_size "
5195 << format("0x%08" PRIx32, objc_class->instance_size) << "\n";
5196
5197 p = get_pointer_32(objc_class->ivars, offset, left, S, info, true);
5198 outs() << "\t\t ivars " << format("0x%08" PRIx32, objc_class->ivars);
5199 if (p != nullptr) {
5200 if (left > sizeof(struct objc_ivar_list_t)) {
5201 outs() << "\n";
5202 memcpy(&objc_ivar_list, p, sizeof(struct objc_ivar_list_t));
5203 } else {
5204 outs() << " (entends past the end of the section)\n";
5205 memset(&objc_ivar_list, '\0', sizeof(struct objc_ivar_list_t));
5206 memcpy(&objc_ivar_list, p, left);
5207 }
5208 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5209 swapStruct(objc_ivar_list);
5210 outs() << "\t\t ivar_count " << objc_ivar_list.ivar_count << "\n";
5211 ivar_list = p + sizeof(struct objc_ivar_list_t);
5212 for (i = 0; i < objc_ivar_list.ivar_count; i++) {
5213 if ((i + 1) * sizeof(struct objc_ivar_t) > left) {
5214 outs() << "\t\t remaining ivar's extend past the of the section\n";
5215 break;
5216 }
5217 memcpy(&ivar, ivar_list + i * sizeof(struct objc_ivar_t),
5218 sizeof(struct objc_ivar_t));
5219 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5220 swapStruct(ivar);
5221
5222 outs() << "\t\t\tivar_name " << format("0x%08" PRIx32, ivar.ivar_name);
5223 if (info->verbose) {
5224 name = get_pointer_32(ivar.ivar_name, offset, xleft, S, info, true);
5225 if (name != nullptr)
5226 outs() << format(" %.*s", xleft, name);
5227 else
5228 outs() << " (not in an __OBJC section)";
5229 }
5230 outs() << "\n";
5231
5232 outs() << "\t\t\tivar_type " << format("0x%08" PRIx32, ivar.ivar_type);
5233 if (info->verbose) {
5234 name = get_pointer_32(ivar.ivar_type, offset, xleft, S, info, true);
5235 if (name != nullptr)
5236 outs() << format(" %.*s", xleft, name);
5237 else
5238 outs() << " (not in an __OBJC section)";
5239 }
5240 outs() << "\n";
5241
5242 outs() << "\t\t ivar_offset "
5243 << format("0x%08" PRIx32, ivar.ivar_offset) << "\n";
5244 }
5245 } else {
5246 outs() << " (not in an __OBJC section)\n";
5247 }
5248
5249 outs() << "\t\t methods " << format("0x%08" PRIx32, objc_class->methodLists);
5250 if (print_method_list(objc_class->methodLists, info))
5251 outs() << " (not in an __OBJC section)\n";
5252
5253 outs() << "\t\t cache " << format("0x%08" PRIx32, objc_class->cache)
5254 << "\n";
5255
5256 outs() << "\t\tprotocols " << format("0x%08" PRIx32, objc_class->protocols);
5257 if (print_protocol_list(objc_class->protocols, 16, info))
5258 outs() << " (not in an __OBJC section)\n";
5259}
5260
5261static void print_objc_objc_category_t(struct objc_category_t *objc_category,
5262 struct DisassembleInfo *info) {
5263 uint32_t offset, left;
5264 const char *name;
5265 SectionRef S;
5266
5267 outs() << "\t category name "
5268 << format("0x%08" PRIx32, objc_category->category_name);
5269 if (info->verbose) {
5270 name = get_pointer_32(objc_category->category_name, offset, left, S, info,
5271 true);
5272 if (name != nullptr)
5273 outs() << format(" %.*s", left, name);
5274 else
5275 outs() << " (not in an __OBJC section)";
5276 }
5277 outs() << "\n";
5278
5279 outs() << "\t\t class name "
5280 << format("0x%08" PRIx32, objc_category->class_name);
5281 if (info->verbose) {
5282 name =
5283 get_pointer_32(objc_category->class_name, offset, left, S, info, true);
5284 if (name != nullptr)
5285 outs() << format(" %.*s", left, name);
5286 else
5287 outs() << " (not in an __OBJC section)";
5288 }
5289 outs() << "\n";
5290
5291 outs() << "\t instance methods "
5292 << format("0x%08" PRIx32, objc_category->instance_methods);
5293 if (print_method_list(objc_category->instance_methods, info))
5294 outs() << " (not in an __OBJC section)\n";
5295
5296 outs() << "\t class methods "
5297 << format("0x%08" PRIx32, objc_category->class_methods);
5298 if (print_method_list(objc_category->class_methods, info))
5299 outs() << " (not in an __OBJC section)\n";
5300}
5301
Kevin Enderby0fc11822015-04-01 20:57:01 +00005302static void print_category64_t(uint64_t p, struct DisassembleInfo *info) {
5303 struct category64_t c;
5304 const char *r;
5305 uint32_t offset, xoffset, left;
5306 SectionRef S, xS;
5307 const char *name, *sym_name;
5308 uint64_t n_value;
5309
5310 r = get_pointer_64(p, offset, left, S, info);
5311 if (r == nullptr)
5312 return;
5313 memset(&c, '\0', sizeof(struct category64_t));
5314 if (left < sizeof(struct category64_t)) {
5315 memcpy(&c, r, left);
5316 outs() << " (category_t entends past the end of the section)\n";
5317 } else
5318 memcpy(&c, r, sizeof(struct category64_t));
5319 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5320 swapStruct(c);
5321
5322 outs() << " name ";
5323 sym_name = get_symbol_64(offset + offsetof(struct category64_t, name), S,
5324 info, n_value, c.name);
5325 if (n_value != 0) {
5326 if (info->verbose && sym_name != nullptr)
5327 outs() << sym_name;
5328 else
5329 outs() << format("0x%" PRIx64, n_value);
5330 if (c.name != 0)
5331 outs() << " + " << format("0x%" PRIx64, c.name);
5332 } else
5333 outs() << format("0x%" PRIx64, c.name);
5334 name = get_pointer_64(c.name + n_value, xoffset, left, xS, info);
5335 if (name != nullptr)
5336 outs() << format(" %.*s", left, name);
5337 outs() << "\n";
5338
5339 outs() << " cls ";
5340 sym_name = get_symbol_64(offset + offsetof(struct category64_t, cls), S, info,
5341 n_value, c.cls);
5342 if (n_value != 0) {
5343 if (info->verbose && sym_name != nullptr)
5344 outs() << sym_name;
5345 else
5346 outs() << format("0x%" PRIx64, n_value);
5347 if (c.cls != 0)
5348 outs() << " + " << format("0x%" PRIx64, c.cls);
5349 } else
5350 outs() << format("0x%" PRIx64, c.cls);
5351 outs() << "\n";
5352 if (c.cls + n_value != 0)
5353 print_class64_t(c.cls + n_value, info);
5354
5355 outs() << " instanceMethods ";
5356 sym_name =
5357 get_symbol_64(offset + offsetof(struct category64_t, instanceMethods), S,
5358 info, n_value, c.instanceMethods);
5359 if (n_value != 0) {
5360 if (info->verbose && sym_name != nullptr)
5361 outs() << sym_name;
5362 else
5363 outs() << format("0x%" PRIx64, n_value);
5364 if (c.instanceMethods != 0)
5365 outs() << " + " << format("0x%" PRIx64, c.instanceMethods);
5366 } else
5367 outs() << format("0x%" PRIx64, c.instanceMethods);
5368 outs() << "\n";
5369 if (c.instanceMethods + n_value != 0)
5370 print_method_list64_t(c.instanceMethods + n_value, info, "");
5371
5372 outs() << " classMethods ";
5373 sym_name = get_symbol_64(offset + offsetof(struct category64_t, classMethods),
5374 S, info, n_value, c.classMethods);
5375 if (n_value != 0) {
5376 if (info->verbose && sym_name != nullptr)
5377 outs() << sym_name;
5378 else
5379 outs() << format("0x%" PRIx64, n_value);
5380 if (c.classMethods != 0)
5381 outs() << " + " << format("0x%" PRIx64, c.classMethods);
5382 } else
5383 outs() << format("0x%" PRIx64, c.classMethods);
5384 outs() << "\n";
5385 if (c.classMethods + n_value != 0)
5386 print_method_list64_t(c.classMethods + n_value, info, "");
5387
5388 outs() << " protocols ";
5389 sym_name = get_symbol_64(offset + offsetof(struct category64_t, protocols), S,
5390 info, n_value, c.protocols);
5391 if (n_value != 0) {
5392 if (info->verbose && sym_name != nullptr)
5393 outs() << sym_name;
5394 else
5395 outs() << format("0x%" PRIx64, n_value);
5396 if (c.protocols != 0)
5397 outs() << " + " << format("0x%" PRIx64, c.protocols);
5398 } else
5399 outs() << format("0x%" PRIx64, c.protocols);
5400 outs() << "\n";
5401 if (c.protocols + n_value != 0)
5402 print_protocol_list64_t(c.protocols + n_value, info);
5403
5404 outs() << "instanceProperties ";
5405 sym_name =
5406 get_symbol_64(offset + offsetof(struct category64_t, instanceProperties),
5407 S, info, n_value, c.instanceProperties);
5408 if (n_value != 0) {
5409 if (info->verbose && sym_name != nullptr)
5410 outs() << sym_name;
5411 else
5412 outs() << format("0x%" PRIx64, n_value);
5413 if (c.instanceProperties != 0)
5414 outs() << " + " << format("0x%" PRIx64, c.instanceProperties);
5415 } else
5416 outs() << format("0x%" PRIx64, c.instanceProperties);
5417 outs() << "\n";
5418 if (c.instanceProperties + n_value != 0)
5419 print_objc_property_list64(c.instanceProperties + n_value, info);
5420}
5421
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005422static void print_category32_t(uint32_t p, struct DisassembleInfo *info) {
5423 struct category32_t c;
5424 const char *r;
5425 uint32_t offset, left;
5426 SectionRef S, xS;
5427 const char *name;
5428
5429 r = get_pointer_32(p, offset, left, S, info);
5430 if (r == nullptr)
5431 return;
5432 memset(&c, '\0', sizeof(struct category32_t));
5433 if (left < sizeof(struct category32_t)) {
5434 memcpy(&c, r, left);
5435 outs() << " (category_t entends past the end of the section)\n";
5436 } else
5437 memcpy(&c, r, sizeof(struct category32_t));
5438 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5439 swapStruct(c);
5440
5441 outs() << " name " << format("0x%" PRIx32, c.name);
5442 name = get_symbol_32(offset + offsetof(struct category32_t, name), S, info,
5443 c.name);
Hans Wennborgcc9deb42015-09-29 18:02:48 +00005444 if (name)
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005445 outs() << " " << name;
5446 outs() << "\n";
5447
5448 outs() << " cls " << format("0x%" PRIx32, c.cls) << "\n";
5449 if (c.cls != 0)
5450 print_class32_t(c.cls, info);
5451 outs() << " instanceMethods " << format("0x%" PRIx32, c.instanceMethods)
5452 << "\n";
5453 if (c.instanceMethods != 0)
5454 print_method_list32_t(c.instanceMethods, info, "");
5455 outs() << " classMethods " << format("0x%" PRIx32, c.classMethods)
5456 << "\n";
5457 if (c.classMethods != 0)
5458 print_method_list32_t(c.classMethods, info, "");
5459 outs() << " protocols " << format("0x%" PRIx32, c.protocols) << "\n";
5460 if (c.protocols != 0)
5461 print_protocol_list32_t(c.protocols, info);
5462 outs() << "instanceProperties " << format("0x%" PRIx32, c.instanceProperties)
5463 << "\n";
5464 if (c.instanceProperties != 0)
5465 print_objc_property_list32(c.instanceProperties, info);
5466}
5467
Kevin Enderby0fc11822015-04-01 20:57:01 +00005468static void print_message_refs64(SectionRef S, struct DisassembleInfo *info) {
5469 uint32_t i, left, offset, xoffset;
5470 uint64_t p, n_value;
5471 struct message_ref64 mr;
5472 const char *name, *sym_name;
5473 const char *r;
5474 SectionRef xS;
5475
5476 if (S == SectionRef())
5477 return;
5478
5479 StringRef SectName;
5480 S.getName(SectName);
5481 DataRefImpl Ref = S.getRawDataRefImpl();
5482 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5483 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5484 offset = 0;
5485 for (i = 0; i < S.getSize(); i += sizeof(struct message_ref64)) {
5486 p = S.getAddress() + i;
5487 r = get_pointer_64(p, offset, left, S, info);
5488 if (r == nullptr)
5489 return;
5490 memset(&mr, '\0', sizeof(struct message_ref64));
5491 if (left < sizeof(struct message_ref64)) {
5492 memcpy(&mr, r, left);
5493 outs() << " (message_ref entends past the end of the section)\n";
5494 } else
5495 memcpy(&mr, r, sizeof(struct message_ref64));
5496 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5497 swapStruct(mr);
5498
5499 outs() << " imp ";
5500 name = get_symbol_64(offset + offsetof(struct message_ref64, imp), S, info,
5501 n_value, mr.imp);
5502 if (n_value != 0) {
5503 outs() << format("0x%" PRIx64, n_value) << " ";
5504 if (mr.imp != 0)
5505 outs() << "+ " << format("0x%" PRIx64, mr.imp) << " ";
5506 } else
5507 outs() << format("0x%" PRIx64, mr.imp) << " ";
5508 if (name != nullptr)
5509 outs() << " " << name;
5510 outs() << "\n";
5511
5512 outs() << " sel ";
5513 sym_name = get_symbol_64(offset + offsetof(struct message_ref64, sel), S,
5514 info, n_value, mr.sel);
5515 if (n_value != 0) {
5516 if (info->verbose && sym_name != nullptr)
5517 outs() << sym_name;
5518 else
5519 outs() << format("0x%" PRIx64, n_value);
5520 if (mr.sel != 0)
5521 outs() << " + " << format("0x%" PRIx64, mr.sel);
5522 } else
5523 outs() << format("0x%" PRIx64, mr.sel);
5524 name = get_pointer_64(mr.sel + n_value, xoffset, left, xS, info);
5525 if (name != nullptr)
5526 outs() << format(" %.*s", left, name);
5527 outs() << "\n";
5528
5529 offset += sizeof(struct message_ref64);
5530 }
5531}
5532
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005533static void print_message_refs32(SectionRef S, struct DisassembleInfo *info) {
5534 uint32_t i, left, offset, xoffset, p;
5535 struct message_ref32 mr;
5536 const char *name, *r;
5537 SectionRef xS;
5538
5539 if (S == SectionRef())
5540 return;
5541
5542 StringRef SectName;
5543 S.getName(SectName);
5544 DataRefImpl Ref = S.getRawDataRefImpl();
5545 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5546 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5547 offset = 0;
5548 for (i = 0; i < S.getSize(); i += sizeof(struct message_ref64)) {
5549 p = S.getAddress() + i;
5550 r = get_pointer_32(p, offset, left, S, info);
5551 if (r == nullptr)
5552 return;
5553 memset(&mr, '\0', sizeof(struct message_ref32));
5554 if (left < sizeof(struct message_ref32)) {
5555 memcpy(&mr, r, left);
5556 outs() << " (message_ref entends past the end of the section)\n";
5557 } else
5558 memcpy(&mr, r, sizeof(struct message_ref32));
5559 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5560 swapStruct(mr);
5561
5562 outs() << " imp " << format("0x%" PRIx32, mr.imp);
5563 name = get_symbol_32(offset + offsetof(struct message_ref32, imp), S, info,
5564 mr.imp);
5565 if (name != nullptr)
5566 outs() << " " << name;
5567 outs() << "\n";
5568
5569 outs() << " sel " << format("0x%" PRIx32, mr.sel);
5570 name = get_pointer_32(mr.sel, xoffset, left, xS, info);
5571 if (name != nullptr)
5572 outs() << " " << name;
5573 outs() << "\n";
5574
5575 offset += sizeof(struct message_ref32);
5576 }
5577}
5578
Kevin Enderby0fc11822015-04-01 20:57:01 +00005579static void print_image_info64(SectionRef S, struct DisassembleInfo *info) {
5580 uint32_t left, offset, swift_version;
5581 uint64_t p;
5582 struct objc_image_info64 o;
5583 const char *r;
5584
Kevin Enderbyaf7c9d02015-10-09 16:48:44 +00005585 if (S == SectionRef())
5586 return;
5587
Kevin Enderby0fc11822015-04-01 20:57:01 +00005588 StringRef SectName;
5589 S.getName(SectName);
5590 DataRefImpl Ref = S.getRawDataRefImpl();
5591 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5592 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5593 p = S.getAddress();
5594 r = get_pointer_64(p, offset, left, S, info);
5595 if (r == nullptr)
5596 return;
5597 memset(&o, '\0', sizeof(struct objc_image_info64));
5598 if (left < sizeof(struct objc_image_info64)) {
5599 memcpy(&o, r, left);
5600 outs() << " (objc_image_info entends past the end of the section)\n";
5601 } else
5602 memcpy(&o, r, sizeof(struct objc_image_info64));
5603 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5604 swapStruct(o);
5605 outs() << " version " << o.version << "\n";
5606 outs() << " flags " << format("0x%" PRIx32, o.flags);
5607 if (o.flags & OBJC_IMAGE_IS_REPLACEMENT)
5608 outs() << " OBJC_IMAGE_IS_REPLACEMENT";
5609 if (o.flags & OBJC_IMAGE_SUPPORTS_GC)
5610 outs() << " OBJC_IMAGE_SUPPORTS_GC";
Dave Lee390abe42018-07-06 05:11:35 +00005611 if (o.flags & OBJC_IMAGE_IS_SIMULATED)
5612 outs() << " OBJC_IMAGE_IS_SIMULATED";
5613 if (o.flags & OBJC_IMAGE_HAS_CATEGORY_CLASS_PROPERTIES)
5614 outs() << " OBJC_IMAGE_HAS_CATEGORY_CLASS_PROPERTIES";
Kevin Enderby0fc11822015-04-01 20:57:01 +00005615 swift_version = (o.flags >> 8) & 0xff;
5616 if (swift_version != 0) {
5617 if (swift_version == 1)
5618 outs() << " Swift 1.0";
5619 else if (swift_version == 2)
5620 outs() << " Swift 1.1";
Kevin Enderbycda2ced2018-02-09 19:31:27 +00005621 else if(swift_version == 3)
5622 outs() << " Swift 2.0";
5623 else if(swift_version == 4)
5624 outs() << " Swift 3.0";
5625 else if(swift_version == 5)
5626 outs() << " Swift 4.0";
5627 else if(swift_version == 6)
Michael Trentf7254a62018-12-07 19:55:03 +00005628 outs() << " Swift 4.1/Swift 4.2";
5629 else if(swift_version == 7)
5630 outs() << " Swift 5 or later";
Kevin Enderby0fc11822015-04-01 20:57:01 +00005631 else
5632 outs() << " unknown future Swift version (" << swift_version << ")";
5633 }
5634 outs() << "\n";
5635}
5636
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005637static void print_image_info32(SectionRef S, struct DisassembleInfo *info) {
5638 uint32_t left, offset, swift_version, p;
5639 struct objc_image_info32 o;
5640 const char *r;
5641
Kevin Enderby19be2512016-04-21 19:49:29 +00005642 if (S == SectionRef())
5643 return;
5644
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005645 StringRef SectName;
5646 S.getName(SectName);
5647 DataRefImpl Ref = S.getRawDataRefImpl();
5648 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5649 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5650 p = S.getAddress();
5651 r = get_pointer_32(p, offset, left, S, info);
5652 if (r == nullptr)
5653 return;
5654 memset(&o, '\0', sizeof(struct objc_image_info32));
5655 if (left < sizeof(struct objc_image_info32)) {
5656 memcpy(&o, r, left);
5657 outs() << " (objc_image_info entends past the end of the section)\n";
5658 } else
5659 memcpy(&o, r, sizeof(struct objc_image_info32));
5660 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5661 swapStruct(o);
5662 outs() << " version " << o.version << "\n";
5663 outs() << " flags " << format("0x%" PRIx32, o.flags);
5664 if (o.flags & OBJC_IMAGE_IS_REPLACEMENT)
5665 outs() << " OBJC_IMAGE_IS_REPLACEMENT";
5666 if (o.flags & OBJC_IMAGE_SUPPORTS_GC)
5667 outs() << " OBJC_IMAGE_SUPPORTS_GC";
5668 swift_version = (o.flags >> 8) & 0xff;
5669 if (swift_version != 0) {
5670 if (swift_version == 1)
5671 outs() << " Swift 1.0";
5672 else if (swift_version == 2)
5673 outs() << " Swift 1.1";
Kevin Enderbycda2ced2018-02-09 19:31:27 +00005674 else if(swift_version == 3)
5675 outs() << " Swift 2.0";
5676 else if(swift_version == 4)
5677 outs() << " Swift 3.0";
5678 else if(swift_version == 5)
5679 outs() << " Swift 4.0";
5680 else if(swift_version == 6)
Michael Trentf7254a62018-12-07 19:55:03 +00005681 outs() << " Swift 4.1/Swift 4.2";
5682 else if(swift_version == 7)
5683 outs() << " Swift 5 or later";
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005684 else
5685 outs() << " unknown future Swift version (" << swift_version << ")";
5686 }
5687 outs() << "\n";
5688}
5689
Kevin Enderby846c0002015-04-16 17:19:59 +00005690static void print_image_info(SectionRef S, struct DisassembleInfo *info) {
5691 uint32_t left, offset, p;
5692 struct imageInfo_t o;
5693 const char *r;
5694
5695 StringRef SectName;
5696 S.getName(SectName);
5697 DataRefImpl Ref = S.getRawDataRefImpl();
5698 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5699 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5700 p = S.getAddress();
5701 r = get_pointer_32(p, offset, left, S, info);
5702 if (r == nullptr)
5703 return;
5704 memset(&o, '\0', sizeof(struct imageInfo_t));
5705 if (left < sizeof(struct imageInfo_t)) {
5706 memcpy(&o, r, left);
5707 outs() << " (imageInfo entends past the end of the section)\n";
5708 } else
5709 memcpy(&o, r, sizeof(struct imageInfo_t));
5710 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5711 swapStruct(o);
5712 outs() << " version " << o.version << "\n";
5713 outs() << " flags " << format("0x%" PRIx32, o.flags);
5714 if (o.flags & 0x1)
5715 outs() << " F&C";
5716 if (o.flags & 0x2)
5717 outs() << " GC";
5718 if (o.flags & 0x4)
5719 outs() << " GC-only";
5720 else
5721 outs() << " RR";
5722 outs() << "\n";
5723}
5724
Kevin Enderby0fc11822015-04-01 20:57:01 +00005725static void printObjc2_64bit_MetaData(MachOObjectFile *O, bool verbose) {
5726 SymbolAddressMap AddrMap;
5727 if (verbose)
5728 CreateSymbolAddressMap(O, &AddrMap);
5729
5730 std::vector<SectionRef> Sections;
5731 for (const SectionRef &Section : O->sections()) {
5732 StringRef SectName;
5733 Section.getName(SectName);
5734 Sections.push_back(Section);
5735 }
5736
Serge Pavlove4e9a1f2018-02-14 03:26:27 +00005737 struct DisassembleInfo info(O, &AddrMap, &Sections, verbose);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005738
Davide Italiano62507042015-12-11 22:27:59 +00005739 SectionRef CL = get_section(O, "__OBJC2", "__class_list");
5740 if (CL == SectionRef())
5741 CL = get_section(O, "__DATA", "__objc_classlist");
Kevin Enderby5879a482017-02-09 17:56:26 +00005742 if (CL == SectionRef())
5743 CL = get_section(O, "__DATA_CONST", "__objc_classlist");
5744 if (CL == SectionRef())
5745 CL = get_section(O, "__DATA_DIRTY", "__objc_classlist");
Davide Italiano62507042015-12-11 22:27:59 +00005746 info.S = CL;
5747 walk_pointer_list_64("class", CL, O, &info, print_class64_t);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005748
Davide Italiano62507042015-12-11 22:27:59 +00005749 SectionRef CR = get_section(O, "__OBJC2", "__class_refs");
5750 if (CR == SectionRef())
5751 CR = get_section(O, "__DATA", "__objc_classrefs");
Kevin Enderby5879a482017-02-09 17:56:26 +00005752 if (CR == SectionRef())
5753 CR = get_section(O, "__DATA_CONST", "__objc_classrefs");
5754 if (CR == SectionRef())
5755 CR = get_section(O, "__DATA_DIRTY", "__objc_classrefs");
Davide Italiano62507042015-12-11 22:27:59 +00005756 info.S = CR;
5757 walk_pointer_list_64("class refs", CR, O, &info, nullptr);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005758
Davide Italiano62507042015-12-11 22:27:59 +00005759 SectionRef SR = get_section(O, "__OBJC2", "__super_refs");
5760 if (SR == SectionRef())
5761 SR = get_section(O, "__DATA", "__objc_superrefs");
Kevin Enderby5879a482017-02-09 17:56:26 +00005762 if (SR == SectionRef())
5763 SR = get_section(O, "__DATA_CONST", "__objc_superrefs");
5764 if (SR == SectionRef())
5765 SR = get_section(O, "__DATA_DIRTY", "__objc_superrefs");
Davide Italiano62507042015-12-11 22:27:59 +00005766 info.S = SR;
5767 walk_pointer_list_64("super refs", SR, O, &info, nullptr);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005768
Davide Italiano62507042015-12-11 22:27:59 +00005769 SectionRef CA = get_section(O, "__OBJC2", "__category_list");
5770 if (CA == SectionRef())
5771 CA = get_section(O, "__DATA", "__objc_catlist");
Kevin Enderby5879a482017-02-09 17:56:26 +00005772 if (CA == SectionRef())
5773 CA = get_section(O, "__DATA_CONST", "__objc_catlist");
5774 if (CA == SectionRef())
5775 CA = get_section(O, "__DATA_DIRTY", "__objc_catlist");
Davide Italiano62507042015-12-11 22:27:59 +00005776 info.S = CA;
5777 walk_pointer_list_64("category", CA, O, &info, print_category64_t);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005778
Davide Italiano62507042015-12-11 22:27:59 +00005779 SectionRef PL = get_section(O, "__OBJC2", "__protocol_list");
5780 if (PL == SectionRef())
5781 PL = get_section(O, "__DATA", "__objc_protolist");
Kevin Enderby5879a482017-02-09 17:56:26 +00005782 if (PL == SectionRef())
5783 PL = get_section(O, "__DATA_CONST", "__objc_protolist");
5784 if (PL == SectionRef())
5785 PL = get_section(O, "__DATA_DIRTY", "__objc_protolist");
Davide Italiano62507042015-12-11 22:27:59 +00005786 info.S = PL;
5787 walk_pointer_list_64("protocol", PL, O, &info, nullptr);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005788
Davide Italiano62507042015-12-11 22:27:59 +00005789 SectionRef MR = get_section(O, "__OBJC2", "__message_refs");
5790 if (MR == SectionRef())
5791 MR = get_section(O, "__DATA", "__objc_msgrefs");
Kevin Enderby5879a482017-02-09 17:56:26 +00005792 if (MR == SectionRef())
5793 MR = get_section(O, "__DATA_CONST", "__objc_msgrefs");
5794 if (MR == SectionRef())
5795 MR = get_section(O, "__DATA_DIRTY", "__objc_msgrefs");
Davide Italiano62507042015-12-11 22:27:59 +00005796 info.S = MR;
5797 print_message_refs64(MR, &info);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005798
Davide Italiano62507042015-12-11 22:27:59 +00005799 SectionRef II = get_section(O, "__OBJC2", "__image_info");
5800 if (II == SectionRef())
5801 II = get_section(O, "__DATA", "__objc_imageinfo");
Kevin Enderby5879a482017-02-09 17:56:26 +00005802 if (II == SectionRef())
5803 II = get_section(O, "__DATA_CONST", "__objc_imageinfo");
5804 if (II == SectionRef())
5805 II = get_section(O, "__DATA_DIRTY", "__objc_imageinfo");
Davide Italiano62507042015-12-11 22:27:59 +00005806 info.S = II;
5807 print_image_info64(II, &info);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005808}
5809
5810static void printObjc2_32bit_MetaData(MachOObjectFile *O, bool verbose) {
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005811 SymbolAddressMap AddrMap;
5812 if (verbose)
5813 CreateSymbolAddressMap(O, &AddrMap);
5814
5815 std::vector<SectionRef> Sections;
5816 for (const SectionRef &Section : O->sections()) {
5817 StringRef SectName;
5818 Section.getName(SectName);
5819 Sections.push_back(Section);
5820 }
5821
Serge Pavlove4e9a1f2018-02-14 03:26:27 +00005822 struct DisassembleInfo info(O, &AddrMap, &Sections, verbose);
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005823
Kevin Enderby5879a482017-02-09 17:56:26 +00005824 SectionRef CL = get_section(O, "__OBJC2", "__class_list");
5825 if (CL == SectionRef())
5826 CL = get_section(O, "__DATA", "__objc_classlist");
5827 if (CL == SectionRef())
5828 CL = get_section(O, "__DATA_CONST", "__objc_classlist");
5829 if (CL == SectionRef())
5830 CL = get_section(O, "__DATA_DIRTY", "__objc_classlist");
5831 info.S = CL;
5832 walk_pointer_list_32("class", CL, O, &info, print_class32_t);
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005833
Kevin Enderby5879a482017-02-09 17:56:26 +00005834 SectionRef CR = get_section(O, "__OBJC2", "__class_refs");
5835 if (CR == SectionRef())
5836 CR = get_section(O, "__DATA", "__objc_classrefs");
5837 if (CR == SectionRef())
5838 CR = get_section(O, "__DATA_CONST", "__objc_classrefs");
5839 if (CR == SectionRef())
5840 CR = get_section(O, "__DATA_DIRTY", "__objc_classrefs");
5841 info.S = CR;
5842 walk_pointer_list_32("class refs", CR, O, &info, nullptr);
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005843
Kevin Enderby5879a482017-02-09 17:56:26 +00005844 SectionRef SR = get_section(O, "__OBJC2", "__super_refs");
5845 if (SR == SectionRef())
5846 SR = get_section(O, "__DATA", "__objc_superrefs");
5847 if (SR == SectionRef())
5848 SR = get_section(O, "__DATA_CONST", "__objc_superrefs");
5849 if (SR == SectionRef())
5850 SR = get_section(O, "__DATA_DIRTY", "__objc_superrefs");
5851 info.S = SR;
5852 walk_pointer_list_32("super refs", SR, O, &info, nullptr);
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005853
Kevin Enderby5879a482017-02-09 17:56:26 +00005854 SectionRef CA = get_section(O, "__OBJC2", "__category_list");
5855 if (CA == SectionRef())
5856 CA = get_section(O, "__DATA", "__objc_catlist");
5857 if (CA == SectionRef())
5858 CA = get_section(O, "__DATA_CONST", "__objc_catlist");
5859 if (CA == SectionRef())
5860 CA = get_section(O, "__DATA_DIRTY", "__objc_catlist");
5861 info.S = CA;
5862 walk_pointer_list_32("category", CA, O, &info, print_category32_t);
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005863
Kevin Enderby5879a482017-02-09 17:56:26 +00005864 SectionRef PL = get_section(O, "__OBJC2", "__protocol_list");
5865 if (PL == SectionRef())
5866 PL = get_section(O, "__DATA", "__objc_protolist");
5867 if (PL == SectionRef())
5868 PL = get_section(O, "__DATA_CONST", "__objc_protolist");
5869 if (PL == SectionRef())
5870 PL = get_section(O, "__DATA_DIRTY", "__objc_protolist");
5871 info.S = PL;
5872 walk_pointer_list_32("protocol", PL, O, &info, nullptr);
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005873
Kevin Enderby5879a482017-02-09 17:56:26 +00005874 SectionRef MR = get_section(O, "__OBJC2", "__message_refs");
5875 if (MR == SectionRef())
5876 MR = get_section(O, "__DATA", "__objc_msgrefs");
5877 if (MR == SectionRef())
5878 MR = get_section(O, "__DATA_CONST", "__objc_msgrefs");
5879 if (MR == SectionRef())
5880 MR = get_section(O, "__DATA_DIRTY", "__objc_msgrefs");
5881 info.S = MR;
5882 print_message_refs32(MR, &info);
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005883
Kevin Enderby5879a482017-02-09 17:56:26 +00005884 SectionRef II = get_section(O, "__OBJC2", "__image_info");
5885 if (II == SectionRef())
5886 II = get_section(O, "__DATA", "__objc_imageinfo");
5887 if (II == SectionRef())
5888 II = get_section(O, "__DATA_CONST", "__objc_imageinfo");
5889 if (II == SectionRef())
5890 II = get_section(O, "__DATA_DIRTY", "__objc_imageinfo");
5891 info.S = II;
5892 print_image_info32(II, &info);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005893}
5894
5895static bool printObjc1_32bit_MetaData(MachOObjectFile *O, bool verbose) {
Kevin Enderby846c0002015-04-16 17:19:59 +00005896 uint32_t i, j, p, offset, xoffset, left, defs_left, def;
5897 const char *r, *name, *defs;
5898 struct objc_module_t module;
5899 SectionRef S, xS;
5900 struct objc_symtab_t symtab;
5901 struct objc_class_t objc_class;
5902 struct objc_category_t objc_category;
5903
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005904 outs() << "Objective-C segment\n";
Kevin Enderby846c0002015-04-16 17:19:59 +00005905 S = get_section(O, "__OBJC", "__module_info");
5906 if (S == SectionRef())
5907 return false;
5908
5909 SymbolAddressMap AddrMap;
5910 if (verbose)
5911 CreateSymbolAddressMap(O, &AddrMap);
5912
5913 std::vector<SectionRef> Sections;
5914 for (const SectionRef &Section : O->sections()) {
5915 StringRef SectName;
5916 Section.getName(SectName);
5917 Sections.push_back(Section);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005918 }
Kevin Enderby846c0002015-04-16 17:19:59 +00005919
Serge Pavlove4e9a1f2018-02-14 03:26:27 +00005920 struct DisassembleInfo info(O, &AddrMap, &Sections, verbose);
Kevin Enderby846c0002015-04-16 17:19:59 +00005921
5922 for (i = 0; i < S.getSize(); i += sizeof(struct objc_module_t)) {
5923 p = S.getAddress() + i;
5924 r = get_pointer_32(p, offset, left, S, &info, true);
5925 if (r == nullptr)
5926 return true;
5927 memset(&module, '\0', sizeof(struct objc_module_t));
5928 if (left < sizeof(struct objc_module_t)) {
5929 memcpy(&module, r, left);
5930 outs() << " (module extends past end of __module_info section)\n";
5931 } else
5932 memcpy(&module, r, sizeof(struct objc_module_t));
5933 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5934 swapStruct(module);
5935
5936 outs() << "Module " << format("0x%" PRIx32, p) << "\n";
5937 outs() << " version " << module.version << "\n";
5938 outs() << " size " << module.size << "\n";
5939 outs() << " name ";
5940 name = get_pointer_32(module.name, xoffset, left, xS, &info, true);
5941 if (name != nullptr)
5942 outs() << format("%.*s", left, name);
5943 else
5944 outs() << format("0x%08" PRIx32, module.name)
5945 << "(not in an __OBJC section)";
5946 outs() << "\n";
5947
5948 r = get_pointer_32(module.symtab, xoffset, left, xS, &info, true);
5949 if (module.symtab == 0 || r == nullptr) {
5950 outs() << " symtab " << format("0x%08" PRIx32, module.symtab)
5951 << " (not in an __OBJC section)\n";
5952 continue;
5953 }
5954 outs() << " symtab " << format("0x%08" PRIx32, module.symtab) << "\n";
5955 memset(&symtab, '\0', sizeof(struct objc_symtab_t));
5956 defs_left = 0;
5957 defs = nullptr;
5958 if (left < sizeof(struct objc_symtab_t)) {
5959 memcpy(&symtab, r, left);
5960 outs() << "\tsymtab extends past end of an __OBJC section)\n";
5961 } else {
5962 memcpy(&symtab, r, sizeof(struct objc_symtab_t));
5963 if (left > sizeof(struct objc_symtab_t)) {
5964 defs_left = left - sizeof(struct objc_symtab_t);
5965 defs = r + sizeof(struct objc_symtab_t);
5966 }
5967 }
5968 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5969 swapStruct(symtab);
5970
5971 outs() << "\tsel_ref_cnt " << symtab.sel_ref_cnt << "\n";
5972 r = get_pointer_32(symtab.refs, xoffset, left, xS, &info, true);
5973 outs() << "\trefs " << format("0x%08" PRIx32, symtab.refs);
5974 if (r == nullptr)
5975 outs() << " (not in an __OBJC section)";
5976 outs() << "\n";
5977 outs() << "\tcls_def_cnt " << symtab.cls_def_cnt << "\n";
5978 outs() << "\tcat_def_cnt " << symtab.cat_def_cnt << "\n";
5979 if (symtab.cls_def_cnt > 0)
5980 outs() << "\tClass Definitions\n";
5981 for (j = 0; j < symtab.cls_def_cnt; j++) {
5982 if ((j + 1) * sizeof(uint32_t) > defs_left) {
5983 outs() << "\t(remaining class defs entries entends past the end of the "
5984 << "section)\n";
5985 break;
5986 }
5987 memcpy(&def, defs + j * sizeof(uint32_t), sizeof(uint32_t));
5988 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5989 sys::swapByteOrder(def);
5990
5991 r = get_pointer_32(def, xoffset, left, xS, &info, true);
5992 outs() << "\tdefs[" << j << "] " << format("0x%08" PRIx32, def);
5993 if (r != nullptr) {
5994 if (left > sizeof(struct objc_class_t)) {
5995 outs() << "\n";
5996 memcpy(&objc_class, r, sizeof(struct objc_class_t));
5997 } else {
5998 outs() << " (entends past the end of the section)\n";
5999 memset(&objc_class, '\0', sizeof(struct objc_class_t));
6000 memcpy(&objc_class, r, left);
6001 }
6002 if (O->isLittleEndian() != sys::IsLittleEndianHost)
6003 swapStruct(objc_class);
6004 print_objc_class_t(&objc_class, &info);
6005 } else {
6006 outs() << "(not in an __OBJC section)\n";
6007 }
6008
6009 if (CLS_GETINFO(&objc_class, CLS_CLASS)) {
6010 outs() << "\tMeta Class";
6011 r = get_pointer_32(objc_class.isa, xoffset, left, xS, &info, true);
6012 if (r != nullptr) {
6013 if (left > sizeof(struct objc_class_t)) {
6014 outs() << "\n";
6015 memcpy(&objc_class, r, sizeof(struct objc_class_t));
6016 } else {
6017 outs() << " (entends past the end of the section)\n";
6018 memset(&objc_class, '\0', sizeof(struct objc_class_t));
6019 memcpy(&objc_class, r, left);
6020 }
6021 if (O->isLittleEndian() != sys::IsLittleEndianHost)
6022 swapStruct(objc_class);
6023 print_objc_class_t(&objc_class, &info);
6024 } else {
6025 outs() << "(not in an __OBJC section)\n";
6026 }
6027 }
6028 }
6029 if (symtab.cat_def_cnt > 0)
6030 outs() << "\tCategory Definitions\n";
6031 for (j = 0; j < symtab.cat_def_cnt; j++) {
6032 if ((j + symtab.cls_def_cnt + 1) * sizeof(uint32_t) > defs_left) {
6033 outs() << "\t(remaining category defs entries entends past the end of "
6034 << "the section)\n";
6035 break;
6036 }
6037 memcpy(&def, defs + (j + symtab.cls_def_cnt) * sizeof(uint32_t),
6038 sizeof(uint32_t));
6039 if (O->isLittleEndian() != sys::IsLittleEndianHost)
6040 sys::swapByteOrder(def);
6041
6042 r = get_pointer_32(def, xoffset, left, xS, &info, true);
6043 outs() << "\tdefs[" << j + symtab.cls_def_cnt << "] "
6044 << format("0x%08" PRIx32, def);
6045 if (r != nullptr) {
6046 if (left > sizeof(struct objc_category_t)) {
6047 outs() << "\n";
6048 memcpy(&objc_category, r, sizeof(struct objc_category_t));
6049 } else {
6050 outs() << " (entends past the end of the section)\n";
6051 memset(&objc_category, '\0', sizeof(struct objc_category_t));
6052 memcpy(&objc_category, r, left);
6053 }
6054 if (O->isLittleEndian() != sys::IsLittleEndianHost)
6055 swapStruct(objc_category);
6056 print_objc_objc_category_t(&objc_category, &info);
6057 } else {
6058 outs() << "(not in an __OBJC section)\n";
6059 }
6060 }
6061 }
6062 const SectionRef II = get_section(O, "__OBJC", "__image_info");
6063 if (II != SectionRef())
6064 print_image_info(II, &info);
6065
6066 return true;
Kevin Enderby0fc11822015-04-01 20:57:01 +00006067}
6068
Kevin Enderby4ad9bde2015-04-16 22:33:20 +00006069static void DumpProtocolSection(MachOObjectFile *O, const char *sect,
6070 uint32_t size, uint32_t addr) {
6071 SymbolAddressMap AddrMap;
6072 CreateSymbolAddressMap(O, &AddrMap);
6073
6074 std::vector<SectionRef> Sections;
6075 for (const SectionRef &Section : O->sections()) {
6076 StringRef SectName;
6077 Section.getName(SectName);
6078 Sections.push_back(Section);
6079 }
6080
Serge Pavlove4e9a1f2018-02-14 03:26:27 +00006081 struct DisassembleInfo info(O, &AddrMap, &Sections, true);
Kevin Enderby4ad9bde2015-04-16 22:33:20 +00006082
6083 const char *p;
6084 struct objc_protocol_t protocol;
6085 uint32_t left, paddr;
6086 for (p = sect; p < sect + size; p += sizeof(struct objc_protocol_t)) {
6087 memset(&protocol, '\0', sizeof(struct objc_protocol_t));
6088 left = size - (p - sect);
6089 if (left < sizeof(struct objc_protocol_t)) {
6090 outs() << "Protocol extends past end of __protocol section\n";
6091 memcpy(&protocol, p, left);
6092 } else
6093 memcpy(&protocol, p, sizeof(struct objc_protocol_t));
6094 if (O->isLittleEndian() != sys::IsLittleEndianHost)
6095 swapStruct(protocol);
6096 paddr = addr + (p - sect);
6097 outs() << "Protocol " << format("0x%" PRIx32, paddr);
6098 if (print_protocol(paddr, 0, &info))
6099 outs() << "(not in an __OBJC section)\n";
6100 }
6101}
6102
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006103#ifdef HAVE_LIBXAR
6104inline void swapStruct(struct xar_header &xar) {
6105 sys::swapByteOrder(xar.magic);
6106 sys::swapByteOrder(xar.size);
6107 sys::swapByteOrder(xar.version);
6108 sys::swapByteOrder(xar.toc_length_compressed);
6109 sys::swapByteOrder(xar.toc_length_uncompressed);
6110 sys::swapByteOrder(xar.cksum_alg);
6111}
6112
6113static void PrintModeVerbose(uint32_t mode) {
6114 switch(mode & S_IFMT){
6115 case S_IFDIR:
6116 outs() << "d";
6117 break;
6118 case S_IFCHR:
6119 outs() << "c";
6120 break;
6121 case S_IFBLK:
6122 outs() << "b";
6123 break;
6124 case S_IFREG:
6125 outs() << "-";
6126 break;
6127 case S_IFLNK:
6128 outs() << "l";
6129 break;
6130 case S_IFSOCK:
6131 outs() << "s";
6132 break;
6133 default:
6134 outs() << "?";
6135 break;
6136 }
6137
6138 /* owner permissions */
6139 if(mode & S_IREAD)
6140 outs() << "r";
6141 else
6142 outs() << "-";
6143 if(mode & S_IWRITE)
6144 outs() << "w";
6145 else
6146 outs() << "-";
6147 if(mode & S_ISUID)
6148 outs() << "s";
6149 else if(mode & S_IEXEC)
6150 outs() << "x";
6151 else
6152 outs() << "-";
6153
6154 /* group permissions */
6155 if(mode & (S_IREAD >> 3))
6156 outs() << "r";
6157 else
6158 outs() << "-";
6159 if(mode & (S_IWRITE >> 3))
6160 outs() << "w";
6161 else
6162 outs() << "-";
6163 if(mode & S_ISGID)
6164 outs() << "s";
6165 else if(mode & (S_IEXEC >> 3))
6166 outs() << "x";
6167 else
6168 outs() << "-";
6169
6170 /* other permissions */
6171 if(mode & (S_IREAD >> 6))
6172 outs() << "r";
6173 else
6174 outs() << "-";
6175 if(mode & (S_IWRITE >> 6))
6176 outs() << "w";
6177 else
6178 outs() << "-";
6179 if(mode & S_ISVTX)
6180 outs() << "t";
6181 else if(mode & (S_IEXEC >> 6))
6182 outs() << "x";
6183 else
6184 outs() << "-";
6185}
6186
6187static void PrintXarFilesSummary(const char *XarFilename, xar_t xar) {
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006188 xar_file_t xf;
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006189 const char *key, *type, *mode, *user, *group, *size, *mtime, *name, *m;
6190 char *endp;
6191 uint32_t mode_value;
6192
Francis Ricci6f942972017-10-06 15:33:28 +00006193 ScopedXarIter xi;
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006194 if (!xi) {
Jonas Devliegheree787efd2018-11-11 22:12:04 +00006195 WithColor::error(errs(), "llvm-objdump")
6196 << "can't obtain an xar iterator for xar archive " << XarFilename
6197 << "\n";
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006198 return;
6199 }
6200
6201 // Go through the xar's files.
6202 for (xf = xar_file_first(xar, xi); xf; xf = xar_file_next(xi)) {
Francis Ricci6f942972017-10-06 15:33:28 +00006203 ScopedXarIter xp;
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006204 if(!xp){
Jonas Devliegheree787efd2018-11-11 22:12:04 +00006205 WithColor::error(errs(), "llvm-objdump")
6206 << "can't obtain an xar iterator for xar archive " << XarFilename
6207 << "\n";
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006208 return;
6209 }
6210 type = nullptr;
6211 mode = nullptr;
6212 user = nullptr;
6213 group = nullptr;
6214 size = nullptr;
6215 mtime = nullptr;
6216 name = nullptr;
6217 for(key = xar_prop_first(xf, xp); key; key = xar_prop_next(xp)){
Jonas Devliegherec0a758d2017-09-18 14:15:57 +00006218 const char *val = nullptr;
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006219 xar_prop_get(xf, key, &val);
6220#if 0 // Useful for debugging.
6221 outs() << "key: " << key << " value: " << val << "\n";
6222#endif
6223 if(strcmp(key, "type") == 0)
6224 type = val;
6225 if(strcmp(key, "mode") == 0)
6226 mode = val;
6227 if(strcmp(key, "user") == 0)
6228 user = val;
6229 if(strcmp(key, "group") == 0)
6230 group = val;
6231 if(strcmp(key, "data/size") == 0)
6232 size = val;
6233 if(strcmp(key, "mtime") == 0)
6234 mtime = val;
6235 if(strcmp(key, "name") == 0)
6236 name = val;
6237 }
6238 if(mode != nullptr){
6239 mode_value = strtoul(mode, &endp, 8);
6240 if(*endp != '\0')
6241 outs() << "(mode: \"" << mode << "\" contains non-octal chars) ";
6242 if(strcmp(type, "file") == 0)
6243 mode_value |= S_IFREG;
6244 PrintModeVerbose(mode_value);
6245 outs() << " ";
6246 }
6247 if(user != nullptr)
6248 outs() << format("%10s/", user);
6249 if(group != nullptr)
6250 outs() << format("%-10s ", group);
6251 if(size != nullptr)
6252 outs() << format("%7s ", size);
6253 if(mtime != nullptr){
6254 for(m = mtime; *m != 'T' && *m != '\0'; m++)
6255 outs() << *m;
6256 if(*m == 'T')
6257 m++;
6258 outs() << " ";
6259 for( ; *m != 'Z' && *m != '\0'; m++)
6260 outs() << *m;
6261 outs() << " ";
6262 }
6263 if(name != nullptr)
6264 outs() << name;
6265 outs() << "\n";
6266 }
6267}
6268
6269static void DumpBitcodeSection(MachOObjectFile *O, const char *sect,
6270 uint32_t size, bool verbose,
6271 bool PrintXarHeader, bool PrintXarFileHeaders,
6272 std::string XarMemberName) {
6273 if(size < sizeof(struct xar_header)) {
6274 outs() << "size of (__LLVM,__bundle) section too small (smaller than size "
6275 "of struct xar_header)\n";
6276 return;
6277 }
6278 struct xar_header XarHeader;
6279 memcpy(&XarHeader, sect, sizeof(struct xar_header));
6280 if (sys::IsLittleEndianHost)
6281 swapStruct(XarHeader);
6282 if (PrintXarHeader) {
6283 if (!XarMemberName.empty())
6284 outs() << "In xar member " << XarMemberName << ": ";
6285 else
6286 outs() << "For (__LLVM,__bundle) section: ";
6287 outs() << "xar header\n";
6288 if (XarHeader.magic == XAR_HEADER_MAGIC)
6289 outs() << " magic XAR_HEADER_MAGIC\n";
6290 else
6291 outs() << " magic "
6292 << format_hex(XarHeader.magic, 10, true)
6293 << " (not XAR_HEADER_MAGIC)\n";
6294 outs() << " size " << XarHeader.size << "\n";
6295 outs() << " version " << XarHeader.version << "\n";
6296 outs() << " toc_length_compressed " << XarHeader.toc_length_compressed
6297 << "\n";
6298 outs() << "toc_length_uncompressed " << XarHeader.toc_length_uncompressed
6299 << "\n";
6300 outs() << " cksum_alg ";
6301 switch (XarHeader.cksum_alg) {
6302 case XAR_CKSUM_NONE:
6303 outs() << "XAR_CKSUM_NONE\n";
6304 break;
6305 case XAR_CKSUM_SHA1:
6306 outs() << "XAR_CKSUM_SHA1\n";
6307 break;
6308 case XAR_CKSUM_MD5:
6309 outs() << "XAR_CKSUM_MD5\n";
6310 break;
Kevin Enderby42882282016-05-23 22:18:59 +00006311#ifdef XAR_CKSUM_SHA256
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006312 case XAR_CKSUM_SHA256:
6313 outs() << "XAR_CKSUM_SHA256\n";
6314 break;
Kevin Enderby42882282016-05-23 22:18:59 +00006315#endif
6316#ifdef XAR_CKSUM_SHA512
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006317 case XAR_CKSUM_SHA512:
6318 outs() << "XAR_CKSUM_SHA512\n";
6319 break;
Kevin Enderby42882282016-05-23 22:18:59 +00006320#endif
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006321 default:
6322 outs() << XarHeader.cksum_alg << "\n";
6323 }
6324 }
6325
6326 SmallString<128> XarFilename;
6327 int FD;
6328 std::error_code XarEC =
6329 sys::fs::createTemporaryFile("llvm-objdump", "xar", FD, XarFilename);
6330 if (XarEC) {
Jonas Devliegheree787efd2018-11-11 22:12:04 +00006331 WithColor::error(errs(), "llvm-objdump") << XarEC.message() << "\n";
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006332 return;
6333 }
Reid Kleckner3fc649c2017-09-23 01:03:17 +00006334 ToolOutputFile XarFile(XarFilename, FD);
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006335 raw_fd_ostream &XarOut = XarFile.os();
6336 StringRef XarContents(sect, size);
6337 XarOut << XarContents;
6338 XarOut.close();
6339 if (XarOut.has_error())
6340 return;
6341
Francis Ricci6f942972017-10-06 15:33:28 +00006342 ScopedXarFile xar(XarFilename.c_str(), READ);
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006343 if (!xar) {
Jonas Devliegheree787efd2018-11-11 22:12:04 +00006344 WithColor::error(errs(), "llvm-objdump")
6345 << "can't create temporary xar archive " << XarFilename << "\n";
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006346 return;
6347 }
6348
6349 SmallString<128> TocFilename;
6350 std::error_code TocEC =
6351 sys::fs::createTemporaryFile("llvm-objdump", "toc", TocFilename);
6352 if (TocEC) {
Jonas Devliegheree787efd2018-11-11 22:12:04 +00006353 WithColor::error(errs(), "llvm-objdump") << TocEC.message() << "\n";
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006354 return;
6355 }
6356 xar_serialize(xar, TocFilename.c_str());
6357
6358 if (PrintXarFileHeaders) {
6359 if (!XarMemberName.empty())
6360 outs() << "In xar member " << XarMemberName << ": ";
6361 else
6362 outs() << "For (__LLVM,__bundle) section: ";
6363 outs() << "xar archive files:\n";
6364 PrintXarFilesSummary(XarFilename.c_str(), xar);
6365 }
6366
6367 ErrorOr<std::unique_ptr<MemoryBuffer>> FileOrErr =
6368 MemoryBuffer::getFileOrSTDIN(TocFilename.c_str());
6369 if (std::error_code EC = FileOrErr.getError()) {
Jonas Devliegheree787efd2018-11-11 22:12:04 +00006370 WithColor::error(errs(), "llvm-objdump") << EC.message() << "\n";
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006371 return;
6372 }
6373 std::unique_ptr<MemoryBuffer> &Buffer = FileOrErr.get();
6374
6375 if (!XarMemberName.empty())
6376 outs() << "In xar member " << XarMemberName << ": ";
6377 else
6378 outs() << "For (__LLVM,__bundle) section: ";
6379 outs() << "xar table of contents:\n";
6380 outs() << Buffer->getBuffer() << "\n";
6381
6382 // TODO: Go through the xar's files.
Francis Ricci6f942972017-10-06 15:33:28 +00006383 ScopedXarIter xi;
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006384 if(!xi){
Jonas Devliegheree787efd2018-11-11 22:12:04 +00006385 WithColor::error(errs(), "llvm-objdump")
6386 << "can't obtain an xar iterator for xar archive "
6387 << XarFilename.c_str() << "\n";
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006388 return;
6389 }
6390 for(xar_file_t xf = xar_file_first(xar, xi); xf; xf = xar_file_next(xi)){
6391 const char *key;
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006392 const char *member_name, *member_type, *member_size_string;
6393 size_t member_size;
6394
Francis Ricci6f942972017-10-06 15:33:28 +00006395 ScopedXarIter xp;
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006396 if(!xp){
Jonas Devliegheree787efd2018-11-11 22:12:04 +00006397 WithColor::error(errs(), "llvm-objdump")
6398 << "can't obtain an xar iterator for xar archive "
6399 << XarFilename.c_str() << "\n";
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006400 return;
6401 }
6402 member_name = NULL;
6403 member_type = NULL;
6404 member_size_string = NULL;
6405 for(key = xar_prop_first(xf, xp); key; key = xar_prop_next(xp)){
Jonas Devliegherec0a758d2017-09-18 14:15:57 +00006406 const char *val = nullptr;
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006407 xar_prop_get(xf, key, &val);
6408#if 0 // Useful for debugging.
6409 outs() << "key: " << key << " value: " << val << "\n";
6410#endif
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +00006411 if (strcmp(key, "name") == 0)
6412 member_name = val;
6413 if (strcmp(key, "type") == 0)
6414 member_type = val;
6415 if (strcmp(key, "data/size") == 0)
6416 member_size_string = val;
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006417 }
6418 /*
6419 * If we find a file with a name, date/size and type properties
6420 * and with the type being "file" see if that is a xar file.
6421 */
6422 if (member_name != NULL && member_type != NULL &&
6423 strcmp(member_type, "file") == 0 &&
6424 member_size_string != NULL){
6425 // Extract the file into a buffer.
6426 char *endptr;
6427 member_size = strtoul(member_size_string, &endptr, 10);
6428 if (*endptr == '\0' && member_size != 0) {
Francis Ricci1bae0ac2017-09-13 13:57:45 +00006429 char *buffer;
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +00006430 if (xar_extract_tobuffersz(xar, xf, &buffer, &member_size) == 0) {
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006431#if 0 // Useful for debugging.
NAKAMURA Takumi6f43bd42017-10-18 13:31:28 +00006432 outs() << "xar member: " << member_name << " extracted\n";
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006433#endif
6434 // Set the XarMemberName we want to see printed in the header.
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +00006435 std::string OldXarMemberName;
6436 // If XarMemberName is already set this is nested. So
6437 // save the old name and create the nested name.
6438 if (!XarMemberName.empty()) {
6439 OldXarMemberName = XarMemberName;
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006440 XarMemberName =
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +00006441 (Twine("[") + XarMemberName + "]" + member_name).str();
6442 } else {
6443 OldXarMemberName = "";
6444 XarMemberName = member_name;
6445 }
6446 // See if this is could be a xar file (nested).
6447 if (member_size >= sizeof(struct xar_header)) {
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006448#if 0 // Useful for debugging.
NAKAMURA Takumi6f43bd42017-10-18 13:31:28 +00006449 outs() << "could be a xar file: " << member_name << "\n";
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006450#endif
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +00006451 memcpy((char *)&XarHeader, buffer, sizeof(struct xar_header));
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006452 if (sys::IsLittleEndianHost)
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +00006453 swapStruct(XarHeader);
6454 if (XarHeader.magic == XAR_HEADER_MAGIC)
6455 DumpBitcodeSection(O, buffer, member_size, verbose,
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006456 PrintXarHeader, PrintXarFileHeaders,
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +00006457 XarMemberName);
6458 }
6459 XarMemberName = OldXarMemberName;
Francis Ricci1bae0ac2017-09-13 13:57:45 +00006460 delete buffer;
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +00006461 }
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006462 }
6463 }
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006464 }
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006465}
6466#endif // defined(HAVE_LIBXAR)
6467
Kevin Enderby0fc11822015-04-01 20:57:01 +00006468static void printObjcMetaData(MachOObjectFile *O, bool verbose) {
6469 if (O->is64Bit())
6470 printObjc2_64bit_MetaData(O, verbose);
6471 else {
6472 MachO::mach_header H;
6473 H = O->getHeader();
6474 if (H.cputype == MachO::CPU_TYPE_ARM)
6475 printObjc2_32bit_MetaData(O, verbose);
6476 else {
6477 // This is the 32-bit non-arm cputype case. Which is normally
6478 // the first Objective-C ABI. But it may be the case of a
6479 // binary for the iOS simulator which is the second Objective-C
6480 // ABI. In that case printObjc1_32bit_MetaData() will determine that
6481 // and return false.
Hans Wennborgcc9deb42015-09-29 18:02:48 +00006482 if (!printObjc1_32bit_MetaData(O, verbose))
Kevin Enderby0fc11822015-04-01 20:57:01 +00006483 printObjc2_32bit_MetaData(O, verbose);
6484 }
6485 }
6486}
6487
Kevin Enderbybf246f52014-09-24 23:08:22 +00006488// GuessLiteralPointer returns a string which for the item in the Mach-O file
6489// for the address passed in as ReferenceValue for printing as a comment with
6490// the instruction and also returns the corresponding type of that item
6491// indirectly through ReferenceType.
6492//
6493// If ReferenceValue is an address of literal cstring then a pointer to the
6494// cstring is returned and ReferenceType is set to
6495// LLVMDisassembler_ReferenceType_Out_LitPool_CstrAddr .
6496//
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006497// If ReferenceValue is an address of an Objective-C CFString, Selector ref or
6498// Class ref that name is returned and the ReferenceType is set accordingly.
6499//
6500// Lastly, literals which are Symbol address in a literal pool are looked for
6501// and if found the symbol name is returned and ReferenceType is set to
6502// LLVMDisassembler_ReferenceType_Out_LitPool_SymAddr .
6503//
6504// If there is no item in the Mach-O file for the address passed in as
6505// ReferenceValue nullptr is returned and ReferenceType is unchanged.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00006506static const char *GuessLiteralPointer(uint64_t ReferenceValue,
6507 uint64_t ReferencePC,
6508 uint64_t *ReferenceType,
6509 struct DisassembleInfo *info) {
Kevin Enderbybf246f52014-09-24 23:08:22 +00006510 // First see if there is an external relocation entry at the ReferencePC.
Kevin Enderbyd90a4172015-10-10 00:05:01 +00006511 if (info->O->getHeader().filetype == MachO::MH_OBJECT) {
6512 uint64_t sect_addr = info->S.getAddress();
6513 uint64_t sect_offset = ReferencePC - sect_addr;
6514 bool reloc_found = false;
6515 DataRefImpl Rel;
6516 MachO::any_relocation_info RE;
6517 bool isExtern = false;
6518 SymbolRef Symbol;
6519 for (const RelocationRef &Reloc : info->S.relocations()) {
6520 uint64_t RelocOffset = Reloc.getOffset();
6521 if (RelocOffset == sect_offset) {
6522 Rel = Reloc.getRawDataRefImpl();
6523 RE = info->O->getRelocation(Rel);
6524 if (info->O->isRelocationScattered(RE))
6525 continue;
6526 isExtern = info->O->getPlainRelocationExternal(RE);
6527 if (isExtern) {
6528 symbol_iterator RelocSym = Reloc.getSymbol();
6529 Symbol = *RelocSym;
6530 }
6531 reloc_found = true;
6532 break;
Kevin Enderbybf246f52014-09-24 23:08:22 +00006533 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00006534 }
Kevin Enderbyd90a4172015-10-10 00:05:01 +00006535 // If there is an external relocation entry for a symbol in a section
6536 // then used that symbol's value for the value of the reference.
6537 if (reloc_found && isExtern) {
6538 if (info->O->getAnyRelocationPCRel(RE)) {
6539 unsigned Type = info->O->getAnyRelocationType(RE);
6540 if (Type == MachO::X86_64_RELOC_SIGNED) {
6541 ReferenceValue = Symbol.getValue();
6542 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00006543 }
6544 }
6545 }
6546
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006547 // Look for literals such as Objective-C CFStrings refs, Selector refs,
6548 // Message refs and Class refs.
6549 bool classref, selref, msgref, cfstring;
6550 uint64_t pointer_value = GuessPointerPointer(ReferenceValue, info, classref,
6551 selref, msgref, cfstring);
David Blaikie33dd45d02015-03-23 18:39:02 +00006552 if (classref && pointer_value == 0) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006553 // Note the ReferenceValue is a pointer into the __objc_classrefs section.
6554 // And the pointer_value in that section is typically zero as it will be
6555 // set by dyld as part of the "bind information".
6556 const char *name = get_dyld_bind_info_symbolname(ReferenceValue, info);
6557 if (name != nullptr) {
6558 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Class_Ref;
Hans Wennborgdb53e302014-10-23 21:59:17 +00006559 const char *class_name = strrchr(name, '$');
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006560 if (class_name != nullptr && class_name[1] == '_' &&
6561 class_name[2] != '\0') {
6562 info->class_name = class_name + 2;
6563 return name;
6564 }
6565 }
6566 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00006567
David Blaikie33dd45d02015-03-23 18:39:02 +00006568 if (classref) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006569 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Class_Ref;
6570 const char *name =
6571 get_objc2_64bit_class_name(pointer_value, ReferenceValue, info);
6572 if (name != nullptr)
6573 info->class_name = name;
6574 else
6575 name = "bad class ref";
Kevin Enderbybf246f52014-09-24 23:08:22 +00006576 return name;
6577 }
6578
David Blaikie33dd45d02015-03-23 18:39:02 +00006579 if (cfstring) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006580 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_CFString_Ref;
6581 const char *name = get_objc2_64bit_cfstring_name(ReferenceValue, info);
6582 return name;
6583 }
6584
David Blaikie33dd45d02015-03-23 18:39:02 +00006585 if (selref && pointer_value == 0)
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006586 pointer_value = get_objc2_64bit_selref(ReferenceValue, info);
6587
6588 if (pointer_value != 0)
6589 ReferenceValue = pointer_value;
6590
6591 const char *name = GuessCstringPointer(ReferenceValue, info);
6592 if (name) {
David Blaikie33dd45d02015-03-23 18:39:02 +00006593 if (pointer_value != 0 && selref) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006594 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Selector_Ref;
6595 info->selector_name = name;
David Blaikie33dd45d02015-03-23 18:39:02 +00006596 } else if (pointer_value != 0 && msgref) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006597 info->class_name = nullptr;
6598 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message_Ref;
6599 info->selector_name = name;
6600 } else
6601 *ReferenceType = LLVMDisassembler_ReferenceType_Out_LitPool_CstrAddr;
6602 return name;
6603 }
6604
6605 // Lastly look for an indirect symbol with this ReferenceValue which is in
6606 // a literal pool. If found return that symbol name.
6607 name = GuessIndirectSymbol(ReferenceValue, info);
6608 if (name) {
6609 *ReferenceType = LLVMDisassembler_ReferenceType_Out_LitPool_SymAddr;
6610 return name;
6611 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00006612
6613 return nullptr;
6614}
6615
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006616// SymbolizerSymbolLookUp is the symbol lookup function passed when creating
Kevin Enderbybf246f52014-09-24 23:08:22 +00006617// the Symbolizer. It looks up the ReferenceValue using the info passed via the
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006618// pointer to the struct DisassembleInfo that was passed when MCSymbolizer
6619// is created and returns the symbol name that matches the ReferenceValue or
6620// nullptr if none. The ReferenceType is passed in for the IN type of
6621// reference the instruction is making from the values in defined in the header
6622// "llvm-c/Disassembler.h". On return the ReferenceType can set to a specific
6623// Out type and the ReferenceName will also be set which is added as a comment
6624// to the disassembled instruction.
6625//
Kevin Enderby04bf6932014-10-28 23:39:46 +00006626// If the symbol name is a C++ mangled name then the demangled name is
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006627// returned through ReferenceName and ReferenceType is set to
6628// LLVMDisassembler_ReferenceType_DeMangled_Name .
6629//
6630// When this is called to get a symbol name for a branch target then the
6631// ReferenceType will be LLVMDisassembler_ReferenceType_In_Branch and then
6632// SymbolValue will be looked for in the indirect symbol table to determine if
6633// it is an address for a symbol stub. If so then the symbol name for that
6634// stub is returned indirectly through ReferenceName and then ReferenceType is
6635// set to LLVMDisassembler_ReferenceType_Out_SymbolStub.
6636//
Kevin Enderbybf246f52014-09-24 23:08:22 +00006637// When this is called with an value loaded via a PC relative load then
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006638// ReferenceType will be LLVMDisassembler_ReferenceType_In_PCrel_Load then the
6639// SymbolValue is checked to be an address of literal pointer, symbol pointer,
6640// or an Objective-C meta data reference. If so the output ReferenceType is
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006641// set to correspond to that as well as setting the ReferenceName.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00006642static const char *SymbolizerSymbolLookUp(void *DisInfo,
6643 uint64_t ReferenceValue,
6644 uint64_t *ReferenceType,
6645 uint64_t ReferencePC,
6646 const char **ReferenceName) {
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006647 struct DisassembleInfo *info = (struct DisassembleInfo *)DisInfo;
Kevin Enderbybf246f52014-09-24 23:08:22 +00006648 // If no verbose symbolic information is wanted then just return nullptr.
David Blaikie33dd45d02015-03-23 18:39:02 +00006649 if (!info->verbose) {
Kevin Enderbybf246f52014-09-24 23:08:22 +00006650 *ReferenceName = nullptr;
6651 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006652 return nullptr;
6653 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00006654
Kevin Enderbyf6d25852015-01-31 00:37:11 +00006655 const char *SymbolName = GuessSymbolName(ReferenceValue, info->AddrMap);
Kevin Enderbybf246f52014-09-24 23:08:22 +00006656
Kevin Enderby85974882014-09-26 22:20:44 +00006657 if (*ReferenceType == LLVMDisassembler_ReferenceType_In_Branch) {
6658 *ReferenceName = GuessIndirectSymbol(ReferenceValue, info);
Kevin Enderby04bf6932014-10-28 23:39:46 +00006659 if (*ReferenceName != nullptr) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006660 method_reference(info, ReferenceType, ReferenceName);
6661 if (*ReferenceType != LLVMDisassembler_ReferenceType_Out_Objc_Message)
6662 *ReferenceType = LLVMDisassembler_ReferenceType_Out_SymbolStub;
Rafael Espindolab940b662016-09-06 19:16:48 +00006663 } else if (SymbolName != nullptr && strncmp(SymbolName, "__Z", 3) == 0) {
Kevin Enderby04bf6932014-10-28 23:39:46 +00006664 if (info->demangled_name != nullptr)
6665 free(info->demangled_name);
6666 int status;
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006667 info->demangled_name =
Rafael Espindolab940b662016-09-06 19:16:48 +00006668 itaniumDemangle(SymbolName + 1, nullptr, nullptr, &status);
Kevin Enderby04bf6932014-10-28 23:39:46 +00006669 if (info->demangled_name != nullptr) {
6670 *ReferenceName = info->demangled_name;
6671 *ReferenceType = LLVMDisassembler_ReferenceType_DeMangled_Name;
6672 } else
6673 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
6674 } else
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006675 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
6676 } else if (*ReferenceType == LLVMDisassembler_ReferenceType_In_PCrel_Load) {
6677 *ReferenceName =
6678 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
Kevin Enderby85974882014-09-26 22:20:44 +00006679 if (*ReferenceName)
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006680 method_reference(info, ReferenceType, ReferenceName);
Kevin Enderby85974882014-09-26 22:20:44 +00006681 else
6682 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
Kevin Enderbyae3c1262014-11-14 21:52:18 +00006683 // If this is arm64 and the reference is an adrp instruction save the
6684 // instruction, passed in ReferenceValue and the address of the instruction
6685 // for use later if we see and add immediate instruction.
6686 } else if (info->O->getArch() == Triple::aarch64 &&
6687 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADRP) {
6688 info->adrp_inst = ReferenceValue;
6689 info->adrp_addr = ReferencePC;
6690 SymbolName = nullptr;
6691 *ReferenceName = nullptr;
6692 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
6693 // If this is arm64 and reference is an add immediate instruction and we
6694 // have
6695 // seen an adrp instruction just before it and the adrp's Xd register
6696 // matches
6697 // this add's Xn register reconstruct the value being referenced and look to
6698 // see if it is a literal pointer. Note the add immediate instruction is
6699 // passed in ReferenceValue.
6700 } else if (info->O->getArch() == Triple::aarch64 &&
6701 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADDXri &&
6702 ReferencePC - 4 == info->adrp_addr &&
6703 (info->adrp_inst & 0x9f000000) == 0x90000000 &&
6704 (info->adrp_inst & 0x1f) == ((ReferenceValue >> 5) & 0x1f)) {
6705 uint32_t addxri_inst;
6706 uint64_t adrp_imm, addxri_imm;
6707
6708 adrp_imm =
6709 ((info->adrp_inst & 0x00ffffe0) >> 3) | ((info->adrp_inst >> 29) & 0x3);
6710 if (info->adrp_inst & 0x0200000)
6711 adrp_imm |= 0xfffffffffc000000LL;
6712
6713 addxri_inst = ReferenceValue;
6714 addxri_imm = (addxri_inst >> 10) & 0xfff;
6715 if (((addxri_inst >> 22) & 0x3) == 1)
6716 addxri_imm <<= 12;
6717
6718 ReferenceValue = (info->adrp_addr & 0xfffffffffffff000LL) +
6719 (adrp_imm << 12) + addxri_imm;
6720
6721 *ReferenceName =
6722 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
6723 if (*ReferenceName == nullptr)
6724 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
6725 // If this is arm64 and the reference is a load register instruction and we
6726 // have seen an adrp instruction just before it and the adrp's Xd register
6727 // matches this add's Xn register reconstruct the value being referenced and
6728 // look to see if it is a literal pointer. Note the load register
6729 // instruction is passed in ReferenceValue.
6730 } else if (info->O->getArch() == Triple::aarch64 &&
6731 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_LDRXui &&
6732 ReferencePC - 4 == info->adrp_addr &&
6733 (info->adrp_inst & 0x9f000000) == 0x90000000 &&
6734 (info->adrp_inst & 0x1f) == ((ReferenceValue >> 5) & 0x1f)) {
6735 uint32_t ldrxui_inst;
6736 uint64_t adrp_imm, ldrxui_imm;
6737
6738 adrp_imm =
6739 ((info->adrp_inst & 0x00ffffe0) >> 3) | ((info->adrp_inst >> 29) & 0x3);
6740 if (info->adrp_inst & 0x0200000)
6741 adrp_imm |= 0xfffffffffc000000LL;
6742
6743 ldrxui_inst = ReferenceValue;
6744 ldrxui_imm = (ldrxui_inst >> 10) & 0xfff;
6745
6746 ReferenceValue = (info->adrp_addr & 0xfffffffffffff000LL) +
6747 (adrp_imm << 12) + (ldrxui_imm << 3);
6748
6749 *ReferenceName =
6750 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
6751 if (*ReferenceName == nullptr)
6752 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
6753 }
6754 // If this arm64 and is an load register (PC-relative) instruction the
6755 // ReferenceValue is the PC plus the immediate value.
6756 else if (info->O->getArch() == Triple::aarch64 &&
6757 (*ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_LDRXl ||
6758 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADR)) {
6759 *ReferenceName =
6760 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
6761 if (*ReferenceName == nullptr)
6762 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
Rafael Espindolab940b662016-09-06 19:16:48 +00006763 } else if (SymbolName != nullptr && strncmp(SymbolName, "__Z", 3) == 0) {
Kevin Enderby04bf6932014-10-28 23:39:46 +00006764 if (info->demangled_name != nullptr)
6765 free(info->demangled_name);
6766 int status;
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006767 info->demangled_name =
Rafael Espindolab940b662016-09-06 19:16:48 +00006768 itaniumDemangle(SymbolName + 1, nullptr, nullptr, &status);
Kevin Enderby04bf6932014-10-28 23:39:46 +00006769 if (info->demangled_name != nullptr) {
6770 *ReferenceName = info->demangled_name;
6771 *ReferenceType = LLVMDisassembler_ReferenceType_DeMangled_Name;
6772 }
6773 }
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006774 else {
Kevin Enderbybf246f52014-09-24 23:08:22 +00006775 *ReferenceName = nullptr;
6776 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
6777 }
6778
6779 return SymbolName;
6780}
6781
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00006782/// Emits the comments that are stored in the CommentStream.
Kevin Enderbybf246f52014-09-24 23:08:22 +00006783/// Each comment in the CommentStream must end with a newline.
6784static void emitComments(raw_svector_ostream &CommentStream,
6785 SmallString<128> &CommentsToEmit,
6786 formatted_raw_ostream &FormattedOS,
6787 const MCAsmInfo &MAI) {
6788 // Flush the stream before taking its content.
Kevin Enderbybf246f52014-09-24 23:08:22 +00006789 StringRef Comments = CommentsToEmit.str();
6790 // Get the default information for printing a comment.
Mehdi Amini36d33fc2016-10-01 06:46:33 +00006791 StringRef CommentBegin = MAI.getCommentString();
Kevin Enderbybf246f52014-09-24 23:08:22 +00006792 unsigned CommentColumn = MAI.getCommentColumn();
6793 bool IsFirst = true;
6794 while (!Comments.empty()) {
6795 if (!IsFirst)
6796 FormattedOS << '\n';
6797 // Emit a line of comments.
6798 FormattedOS.PadToColumn(CommentColumn);
6799 size_t Position = Comments.find('\n');
6800 FormattedOS << CommentBegin << ' ' << Comments.substr(0, Position);
6801 // Move after the newline character.
6802 Comments = Comments.substr(Position + 1);
6803 IsFirst = false;
6804 }
6805 FormattedOS.flush();
6806
6807 // Tell the comment stream that the vector changed underneath it.
6808 CommentsToEmit.clear();
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006809}
6810
Kevin Enderby95df54c2015-02-04 01:01:38 +00006811static void DisassembleMachO(StringRef Filename, MachOObjectFile *MachOOF,
6812 StringRef DisSegName, StringRef DisSectName) {
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006813 const char *McpuDefault = nullptr;
6814 const Target *ThumbTarget = nullptr;
6815 const Target *TheTarget = GetTarget(MachOOF, &McpuDefault, &ThumbTarget);
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006816 if (!TheTarget) {
6817 // GetTarget prints out stuff.
6818 return;
6819 }
Kevin Enderbyf310e622017-09-21 21:45:02 +00006820 std::string MachOMCPU;
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006821 if (MCPU.empty() && McpuDefault)
Kevin Enderbyf310e622017-09-21 21:45:02 +00006822 MachOMCPU = McpuDefault;
6823 else
6824 MachOMCPU = MCPU;
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006825
Ahmed Charles56440fd2014-03-06 05:51:42 +00006826 std::unique_ptr<const MCInstrInfo> InstrInfo(TheTarget->createMCInstrInfo());
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006827 std::unique_ptr<const MCInstrInfo> ThumbInstrInfo;
Kevin Enderbyae3c1262014-11-14 21:52:18 +00006828 if (ThumbTarget)
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006829 ThumbInstrInfo.reset(ThumbTarget->createMCInstrInfo());
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006830
Kevin Enderbyc9595622014-08-06 23:24:41 +00006831 // Package up features to be passed to target/subtarget
6832 std::string FeaturesStr;
Jordan Rupprecht16a0de22018-12-20 00:57:06 +00006833 if (!MAttrs.empty()) {
Kevin Enderbyc9595622014-08-06 23:24:41 +00006834 SubtargetFeatures Features;
6835 for (unsigned i = 0; i != MAttrs.size(); ++i)
6836 Features.AddFeature(MAttrs[i]);
6837 FeaturesStr = Features.getString();
6838 }
6839
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006840 // Set up disassembler.
Ahmed Charles56440fd2014-03-06 05:51:42 +00006841 std::unique_ptr<const MCRegisterInfo> MRI(
6842 TheTarget->createMCRegInfo(TripleName));
6843 std::unique_ptr<const MCAsmInfo> AsmInfo(
Rafael Espindola227144c2013-05-13 01:16:13 +00006844 TheTarget->createMCAsmInfo(*MRI, TripleName));
Ahmed Charles56440fd2014-03-06 05:51:42 +00006845 std::unique_ptr<const MCSubtargetInfo> STI(
Kevin Enderbyf310e622017-09-21 21:45:02 +00006846 TheTarget->createMCSubtargetInfo(TripleName, MachOMCPU, FeaturesStr));
Craig Toppere6cb63e2014-04-25 04:24:47 +00006847 MCContext Ctx(AsmInfo.get(), MRI.get(), nullptr);
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006848 std::unique_ptr<MCDisassembler> DisAsm(
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006849 TheTarget->createMCDisassembler(*STI, Ctx));
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006850 std::unique_ptr<MCSymbolizer> Symbolizer;
Serge Pavlove4e9a1f2018-02-14 03:26:27 +00006851 struct DisassembleInfo SymbolizerInfo(nullptr, nullptr, nullptr, false);
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006852 std::unique_ptr<MCRelocationInfo> RelInfo(
6853 TheTarget->createMCRelocationInfo(TripleName, Ctx));
6854 if (RelInfo) {
6855 Symbolizer.reset(TheTarget->createMCSymbolizer(
6856 TripleName, SymbolizerGetOpInfo, SymbolizerSymbolLookUp,
David Blaikie186db432015-01-18 20:45:48 +00006857 &SymbolizerInfo, &Ctx, std::move(RelInfo)));
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006858 DisAsm->setSymbolizer(std::move(Symbolizer));
6859 }
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006860 int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
Ahmed Charles56440fd2014-03-06 05:51:42 +00006861 std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
Daniel Sanders50f17232015-09-15 16:17:27 +00006862 Triple(TripleName), AsmPrinterVariant, *AsmInfo, *InstrInfo, *MRI));
Kevin Enderbybf246f52014-09-24 23:08:22 +00006863 // Set the display preference for hex vs. decimal immediates.
6864 IP->setPrintImmHex(PrintImmHex);
6865 // Comment stream and backing vector.
6866 SmallString<128> CommentsToEmit;
6867 raw_svector_ostream CommentStream(CommentsToEmit);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00006868 // FIXME: Setting the CommentStream in the InstPrinter is problematic in that
6869 // if it is done then arm64 comments for string literals don't get printed
6870 // and some constant get printed instead and not setting it causes intel
6871 // (32-bit and 64-bit) comments printed with different spacing before the
6872 // comment causing different diffs with the 'C' disassembler library API.
6873 // IP->setCommentStream(CommentStream);
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00006874
Kevin Enderbyae3c1262014-11-14 21:52:18 +00006875 if (!AsmInfo || !STI || !DisAsm || !IP) {
Jonas Devliegheree787efd2018-11-11 22:12:04 +00006876 WithColor::error(errs(), "llvm-objdump")
6877 << "couldn't initialize disassembler for target " << TripleName << '\n';
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006878 return;
6879 }
6880
Tim Northover09ca33e2016-04-22 23:23:31 +00006881 // Set up separate thumb disassembler if needed.
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006882 std::unique_ptr<const MCRegisterInfo> ThumbMRI;
6883 std::unique_ptr<const MCAsmInfo> ThumbAsmInfo;
6884 std::unique_ptr<const MCSubtargetInfo> ThumbSTI;
Kevin Enderby930fdc72014-11-06 19:00:13 +00006885 std::unique_ptr<MCDisassembler> ThumbDisAsm;
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006886 std::unique_ptr<MCInstPrinter> ThumbIP;
6887 std::unique_ptr<MCContext> ThumbCtx;
Kevin Enderby930fdc72014-11-06 19:00:13 +00006888 std::unique_ptr<MCSymbolizer> ThumbSymbolizer;
Serge Pavlove4e9a1f2018-02-14 03:26:27 +00006889 struct DisassembleInfo ThumbSymbolizerInfo(nullptr, nullptr, nullptr, false);
Kevin Enderby930fdc72014-11-06 19:00:13 +00006890 std::unique_ptr<MCRelocationInfo> ThumbRelInfo;
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006891 if (ThumbTarget) {
6892 ThumbMRI.reset(ThumbTarget->createMCRegInfo(ThumbTripleName));
6893 ThumbAsmInfo.reset(
6894 ThumbTarget->createMCAsmInfo(*ThumbMRI, ThumbTripleName));
6895 ThumbSTI.reset(
Kevin Enderbyf310e622017-09-21 21:45:02 +00006896 ThumbTarget->createMCSubtargetInfo(ThumbTripleName, MachOMCPU,
6897 FeaturesStr));
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006898 ThumbCtx.reset(new MCContext(ThumbAsmInfo.get(), ThumbMRI.get(), nullptr));
6899 ThumbDisAsm.reset(ThumbTarget->createMCDisassembler(*ThumbSTI, *ThumbCtx));
Kevin Enderby930fdc72014-11-06 19:00:13 +00006900 MCContext *PtrThumbCtx = ThumbCtx.get();
6901 ThumbRelInfo.reset(
6902 ThumbTarget->createMCRelocationInfo(ThumbTripleName, *PtrThumbCtx));
6903 if (ThumbRelInfo) {
6904 ThumbSymbolizer.reset(ThumbTarget->createMCSymbolizer(
6905 ThumbTripleName, SymbolizerGetOpInfo, SymbolizerSymbolLookUp,
David Blaikie186db432015-01-18 20:45:48 +00006906 &ThumbSymbolizerInfo, PtrThumbCtx, std::move(ThumbRelInfo)));
Kevin Enderby930fdc72014-11-06 19:00:13 +00006907 ThumbDisAsm->setSymbolizer(std::move(ThumbSymbolizer));
6908 }
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006909 int ThumbAsmPrinterVariant = ThumbAsmInfo->getAssemblerDialect();
6910 ThumbIP.reset(ThumbTarget->createMCInstPrinter(
Daniel Sanders50f17232015-09-15 16:17:27 +00006911 Triple(ThumbTripleName), ThumbAsmPrinterVariant, *ThumbAsmInfo,
6912 *ThumbInstrInfo, *ThumbMRI));
Kevin Enderbybf246f52014-09-24 23:08:22 +00006913 // Set the display preference for hex vs. decimal immediates.
6914 ThumbIP->setPrintImmHex(PrintImmHex);
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006915 }
6916
Kevin Enderbyae3c1262014-11-14 21:52:18 +00006917 if (ThumbTarget && (!ThumbAsmInfo || !ThumbSTI || !ThumbDisAsm || !ThumbIP)) {
Jonas Devliegheree787efd2018-11-11 22:12:04 +00006918 WithColor::error(errs(), "llvm-objdump")
6919 << "couldn't initialize disassembler for target " << ThumbTripleName
6920 << '\n';
Kevin Enderbyec5ca032014-08-18 20:21:02 +00006921 return;
6922 }
6923
Charles Davis8bdfafd2013-09-01 04:28:48 +00006924 MachO::mach_header Header = MachOOF->getHeader();
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006925
Ahmed Bougachaaa790682013-05-24 01:07:04 +00006926 // FIXME: Using the -cfg command line option, this code used to be able to
6927 // annotate relocations with the referenced symbol's name, and if this was
6928 // inside a __[cf]string section, the data it points to. This is now replaced
6929 // by the upcoming MCSymbolizer, which needs the appropriate setup done above.
Owen Andersond9243c42011-10-17 21:37:35 +00006930 std::vector<SectionRef> Sections;
6931 std::vector<SymbolRef> Symbols;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006932 SmallVector<uint64_t, 8> FoundFns;
Kevin Enderby273ae012013-06-06 17:20:50 +00006933 uint64_t BaseSegmentAddress;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006934
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00006935 getSectionsAndSymbols(MachOOF, Sections, Symbols, FoundFns,
Kevin Enderby273ae012013-06-06 17:20:50 +00006936 BaseSegmentAddress);
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006937
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006938 // Sort the symbols by address, just in case they didn't come in that way.
Fangrui Song0cac7262018-09-27 02:13:45 +00006939 llvm::sort(Symbols, SymbolSorter());
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006940
Kevin Enderby273ae012013-06-06 17:20:50 +00006941 // Build a data in code table that is sorted on by the address of each entry.
6942 uint64_t BaseAddress = 0;
Charles Davis8bdfafd2013-09-01 04:28:48 +00006943 if (Header.filetype == MachO::MH_OBJECT)
Rafael Espindola80291272014-10-08 15:28:58 +00006944 BaseAddress = Sections[0].getAddress();
Kevin Enderby273ae012013-06-06 17:20:50 +00006945 else
6946 BaseAddress = BaseSegmentAddress;
6947 DiceTable Dices;
Kevin Enderby273ae012013-06-06 17:20:50 +00006948 for (dice_iterator DI = MachOOF->begin_dices(), DE = MachOOF->end_dices();
Rafael Espindola5e812af2014-01-30 02:49:50 +00006949 DI != DE; ++DI) {
Kevin Enderby273ae012013-06-06 17:20:50 +00006950 uint32_t Offset;
6951 DI->getOffset(Offset);
6952 Dices.push_back(std::make_pair(BaseAddress + Offset, *DI));
6953 }
6954 array_pod_sort(Dices.begin(), Dices.end());
6955
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006956#ifndef NDEBUG
6957 raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls();
6958#else
6959 raw_ostream &DebugOut = nulls();
6960#endif
6961
Ahmed Charles56440fd2014-03-06 05:51:42 +00006962 std::unique_ptr<DIContext> diContext;
Rafael Espindola9b709252013-04-13 01:45:40 +00006963 ObjectFile *DbgObj = MachOOF;
Francis Visoiu Mistrih8e864be2018-08-31 13:10:54 +00006964 std::unique_ptr<MemoryBuffer> DSYMBuf;
Benjamin Kramer699128e2011-09-21 01:13:19 +00006965 // Try to find debug info and set up the DIContext for it.
6966 if (UseDbg) {
Benjamin Kramer699128e2011-09-21 01:13:19 +00006967 // A separate DSym file path was specified, parse it as a macho file,
6968 // get the sections and supply it to the section name parsing machinery.
6969 if (!DSYMFile.empty()) {
Rafael Espindola48af1c22014-08-19 18:44:46 +00006970 ErrorOr<std::unique_ptr<MemoryBuffer>> BufOrErr =
Rafael Espindolaadf21f22014-07-06 17:43:13 +00006971 MemoryBuffer::getFileOrSTDIN(DSYMFile);
Rafael Espindola48af1c22014-08-19 18:44:46 +00006972 if (std::error_code EC = BufOrErr.getError()) {
Jonas Devliegheree787efd2018-11-11 22:12:04 +00006973 WithColor::error(errs(), "llvm-objdump")
6974 << Filename << ": " << EC.message() << '\n';
Benjamin Kramer699128e2011-09-21 01:13:19 +00006975 return;
6976 }
Gerolf Hoflehnerbf26d542018-04-19 20:48:35 +00006977 Expected<std::unique_ptr<MachOObjectFile>> DbgObjCheck =
6978 ObjectFile::createMachOObjectFile(BufOrErr.get()->getMemBufferRef());
6979
6980 if (DbgObjCheck.takeError())
6981 report_error(MachOOF->getFileName(), DbgObjCheck.takeError());
6982 DbgObj = DbgObjCheck.get().release();
Francis Visoiu Mistrih8e864be2018-08-31 13:10:54 +00006983 // We need to keep the file alive, because we're replacing DbgObj with it.
6984 DSYMBuf = std::move(BufOrErr.get());
Benjamin Kramer699128e2011-09-21 01:13:19 +00006985 }
6986
Eric Christopher7370b552012-11-12 21:40:38 +00006987 // Setup the DIContext
Rafael Espindolac398e672017-07-19 22:27:28 +00006988 diContext = DWARFContext::create(*DbgObj);
Benjamin Kramer699128e2011-09-21 01:13:19 +00006989 }
6990
Jordan Rupprecht16a0de22018-12-20 00:57:06 +00006991 if (FilterSections.empty())
Kevin Enderby95df54c2015-02-04 01:01:38 +00006992 outs() << "(" << DisSegName << "," << DisSectName << ") section\n";
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00006993
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006994 for (unsigned SectIdx = 0; SectIdx != Sections.size(); SectIdx++) {
Owen Andersond9243c42011-10-17 21:37:35 +00006995 StringRef SectName;
Kevin Enderby95df54c2015-02-04 01:01:38 +00006996 if (Sections[SectIdx].getName(SectName) || SectName != DisSectName)
6997 continue;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006998
Rafael Espindolaa9f810b2012-12-21 03:47:03 +00006999 DataRefImpl DR = Sections[SectIdx].getRawDataRefImpl();
Ahmed Bougachaaa790682013-05-24 01:07:04 +00007000
Rafael Espindolab0f76a42013-04-05 15:15:22 +00007001 StringRef SegmentName = MachOOF->getSectionFinalSegmentName(DR);
Kevin Enderby95df54c2015-02-04 01:01:38 +00007002 if (SegmentName != DisSegName)
Rafael Espindolaa9f810b2012-12-21 03:47:03 +00007003 continue;
7004
Rafael Espindola7fc5b872014-11-12 02:04:27 +00007005 StringRef BytesStr;
7006 Sections[SectIdx].getContents(BytesStr);
Aaron Ballman106fd7b2014-11-12 14:01:17 +00007007 ArrayRef<uint8_t> Bytes(reinterpret_cast<const uint8_t *>(BytesStr.data()),
7008 BytesStr.size());
Rafael Espindola80291272014-10-08 15:28:58 +00007009 uint64_t SectAddress = Sections[SectIdx].getAddress();
Rafael Espindolabd604f22014-11-07 00:52:15 +00007010
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007011 bool symbolTableWorked = false;
7012
Kevin Enderbybf246f52014-09-24 23:08:22 +00007013 // Create a map of symbol addresses to symbol names for use by
7014 // the SymbolizerSymbolLookUp() routine.
7015 SymbolAddressMap AddrMap;
Kevin Enderby6a221752015-03-17 17:10:57 +00007016 bool DisSymNameFound = false;
Kevin Enderbybf246f52014-09-24 23:08:22 +00007017 for (const SymbolRef &Symbol : MachOOF->symbols()) {
Kevin Enderby7bd8d992016-05-02 20:28:12 +00007018 Expected<SymbolRef::Type> STOrErr = Symbol.getType();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00007019 if (!STOrErr)
7020 report_error(MachOOF->getFileName(), STOrErr.takeError());
Kevin Enderby5afbc1c2016-03-23 20:27:00 +00007021 SymbolRef::Type ST = *STOrErr;
Kevin Enderbybf246f52014-09-24 23:08:22 +00007022 if (ST == SymbolRef::ST_Function || ST == SymbolRef::ST_Data ||
7023 ST == SymbolRef::ST_Other) {
Rafael Espindoladea00162015-07-03 17:44:18 +00007024 uint64_t Address = Symbol.getValue();
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00007025 Expected<StringRef> SymNameOrErr = Symbol.getName();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00007026 if (!SymNameOrErr)
7027 report_error(MachOOF->getFileName(), SymNameOrErr.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00007028 StringRef SymName = *SymNameOrErr;
Kevin Enderbybf246f52014-09-24 23:08:22 +00007029 AddrMap[Address] = SymName;
Kevin Enderby6a221752015-03-17 17:10:57 +00007030 if (!DisSymName.empty() && DisSymName == SymName)
7031 DisSymNameFound = true;
Kevin Enderbybf246f52014-09-24 23:08:22 +00007032 }
7033 }
David Blaikie33dd45d02015-03-23 18:39:02 +00007034 if (!DisSymName.empty() && !DisSymNameFound) {
Kevin Enderby6a221752015-03-17 17:10:57 +00007035 outs() << "Can't find -dis-symname: " << DisSymName << "\n";
7036 return;
7037 }
Kevin Enderby98c9acc2014-09-16 18:00:57 +00007038 // Set up the block of info used by the Symbolizer call backs.
Kevin Enderby8e29ec92015-03-17 22:26:11 +00007039 SymbolizerInfo.verbose = !NoSymbolicOperands;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00007040 SymbolizerInfo.O = MachOOF;
7041 SymbolizerInfo.S = Sections[SectIdx];
Kevin Enderbybf246f52014-09-24 23:08:22 +00007042 SymbolizerInfo.AddrMap = &AddrMap;
Kevin Enderby6f326ce2014-10-23 19:37:31 +00007043 SymbolizerInfo.Sections = &Sections;
Kevin Enderby930fdc72014-11-06 19:00:13 +00007044 // Same for the ThumbSymbolizer
Kevin Enderby8e29ec92015-03-17 22:26:11 +00007045 ThumbSymbolizerInfo.verbose = !NoSymbolicOperands;
Kevin Enderby930fdc72014-11-06 19:00:13 +00007046 ThumbSymbolizerInfo.O = MachOOF;
7047 ThumbSymbolizerInfo.S = Sections[SectIdx];
7048 ThumbSymbolizerInfo.AddrMap = &AddrMap;
7049 ThumbSymbolizerInfo.Sections = &Sections;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00007050
Kevin Enderby4b627be2016-04-28 20:14:13 +00007051 unsigned int Arch = MachOOF->getArch();
7052
Tim Northoverf203ab52016-07-14 22:13:32 +00007053 // Skip all symbols if this is a stubs file.
Jordan Rupprecht16a0de22018-12-20 00:57:06 +00007054 if (Bytes.empty())
Tim Northoverf203ab52016-07-14 22:13:32 +00007055 return;
7056
Kevin Enderbyc138da32017-02-06 18:43:18 +00007057 // If the section has symbols but no symbol at the start of the section
7058 // these are used to make sure the bytes before the first symbol are
7059 // disassembled.
7060 bool FirstSymbol = true;
7061 bool FirstSymbolAtSectionStart = true;
7062
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00007063 // Disassemble symbol by symbol.
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007064 for (unsigned SymIdx = 0; SymIdx != Symbols.size(); SymIdx++) {
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00007065 Expected<StringRef> SymNameOrErr = Symbols[SymIdx].getName();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00007066 if (!SymNameOrErr)
7067 report_error(MachOOF->getFileName(), SymNameOrErr.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00007068 StringRef SymName = *SymNameOrErr;
Owen Andersond9243c42011-10-17 21:37:35 +00007069
Kevin Enderby7bd8d992016-05-02 20:28:12 +00007070 Expected<SymbolRef::Type> STOrErr = Symbols[SymIdx].getType();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00007071 if (!STOrErr)
7072 report_error(MachOOF->getFileName(), STOrErr.takeError());
Kevin Enderby5afbc1c2016-03-23 20:27:00 +00007073 SymbolRef::Type ST = *STOrErr;
Kuba Breckade833222015-11-12 09:40:29 +00007074 if (ST != SymbolRef::ST_Function && ST != SymbolRef::ST_Data)
Owen Andersond9243c42011-10-17 21:37:35 +00007075 continue;
7076
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00007077 // Make sure the symbol is defined in this section.
Rafael Espindola80291272014-10-08 15:28:58 +00007078 bool containsSym = Sections[SectIdx].containsSymbol(Symbols[SymIdx]);
Kevin Enderbyd8a6e832016-06-15 21:14:01 +00007079 if (!containsSym) {
7080 if (!DisSymName.empty() && DisSymName == SymName) {
7081 outs() << "-dis-symname: " << DisSymName << " not in the section\n";
7082 return;
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +00007083 }
Kevin Enderbyd8a6e832016-06-15 21:14:01 +00007084 continue;
7085 }
7086 // The __mh_execute_header is special and we need to deal with that fact
7087 // this symbol is before the start of the (__TEXT,__text) section and at the
7088 // address of the start of the __TEXT segment. This is because this symbol
7089 // is an N_SECT symbol in the (__TEXT,__text) but its address is before the
7090 // start of the section in a standard MH_EXECUTE filetype.
7091 if (!DisSymName.empty() && DisSymName == "__mh_execute_header") {
7092 outs() << "-dis-symname: __mh_execute_header not in any section\n";
7093 return;
7094 }
Tim Northoverfbefee32016-07-14 23:13:03 +00007095 // When this code is trying to disassemble a symbol at a time and in the
7096 // case there is only the __mh_execute_header symbol left as in a stripped
7097 // executable, we need to deal with this by ignoring this symbol so the
7098 // whole section is disassembled and this symbol is then not displayed.
7099 if (SymName == "__mh_execute_header" || SymName == "__mh_dylib_header" ||
7100 SymName == "__mh_bundle_header" || SymName == "__mh_object_header" ||
7101 SymName == "__mh_preload_header" || SymName == "__mh_dylinker_header")
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007102 continue;
7103
Kevin Enderby6a221752015-03-17 17:10:57 +00007104 // If we are only disassembling one symbol see if this is that symbol.
7105 if (!DisSymName.empty() && DisSymName != SymName)
7106 continue;
7107
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00007108 // Start at the address of the symbol relative to the section's address.
Tim Northoverf203ab52016-07-14 22:13:32 +00007109 uint64_t SectSize = Sections[SectIdx].getSize();
Rafael Espindoladea00162015-07-03 17:44:18 +00007110 uint64_t Start = Symbols[SymIdx].getValue();
Rafael Espindola80291272014-10-08 15:28:58 +00007111 uint64_t SectionAddress = Sections[SectIdx].getAddress();
Cameron Zwarich54478a52012-02-03 05:42:17 +00007112 Start -= SectionAddress;
Owen Andersond9243c42011-10-17 21:37:35 +00007113
Tim Northoverf203ab52016-07-14 22:13:32 +00007114 if (Start > SectSize) {
7115 outs() << "section data ends, " << SymName
7116 << " lies outside valid range\n";
7117 return;
7118 }
7119
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00007120 // Stop disassembling either at the beginning of the next symbol or at
7121 // the end of the section.
Kevin Enderbyedd58722012-05-15 18:57:14 +00007122 bool containsNextSym = false;
Owen Andersond9243c42011-10-17 21:37:35 +00007123 uint64_t NextSym = 0;
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007124 uint64_t NextSymIdx = SymIdx + 1;
Owen Andersond9243c42011-10-17 21:37:35 +00007125 while (Symbols.size() > NextSymIdx) {
Kevin Enderby7bd8d992016-05-02 20:28:12 +00007126 Expected<SymbolRef::Type> STOrErr = Symbols[NextSymIdx].getType();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00007127 if (!STOrErr)
7128 report_error(MachOOF->getFileName(), STOrErr.takeError());
Kevin Enderby5afbc1c2016-03-23 20:27:00 +00007129 SymbolRef::Type NextSymType = *STOrErr;
Owen Andersond9243c42011-10-17 21:37:35 +00007130 if (NextSymType == SymbolRef::ST_Function) {
Rafael Espindola80291272014-10-08 15:28:58 +00007131 containsNextSym =
7132 Sections[SectIdx].containsSymbol(Symbols[NextSymIdx]);
Rafael Espindoladea00162015-07-03 17:44:18 +00007133 NextSym = Symbols[NextSymIdx].getValue();
Cameron Zwarich54478a52012-02-03 05:42:17 +00007134 NextSym -= SectionAddress;
Owen Andersond9243c42011-10-17 21:37:35 +00007135 break;
7136 }
7137 ++NextSymIdx;
7138 }
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007139
Tim Northoverf203ab52016-07-14 22:13:32 +00007140 uint64_t End = containsNextSym ? std::min(NextSym, SectSize) : SectSize;
Owen Andersond9243c42011-10-17 21:37:35 +00007141 uint64_t Size;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007142
7143 symbolTableWorked = true;
Rafael Espindolabd604f22014-11-07 00:52:15 +00007144
Kevin Enderbyec5ca032014-08-18 20:21:02 +00007145 DataRefImpl Symb = Symbols[SymIdx].getRawDataRefImpl();
Tim Northover09ca33e2016-04-22 23:23:31 +00007146 bool IsThumb = MachOOF->getSymbolFlags(Symb) & SymbolRef::SF_Thumb;
7147
7148 // We only need the dedicated Thumb target if there's a real choice
7149 // (i.e. we're not targeting M-class) and the function is Thumb.
7150 bool UseThumbTarget = IsThumb && ThumbTarget;
Kevin Enderbyec5ca032014-08-18 20:21:02 +00007151
Kevin Enderbyc138da32017-02-06 18:43:18 +00007152 // If we are not specifying a symbol to start disassembly with and this
7153 // is the first symbol in the section but not at the start of the section
7154 // then move the disassembly index to the start of the section and
7155 // don't print the symbol name just yet. This is so the bytes before the
7156 // first symbol are disassembled.
7157 uint64_t SymbolStart = Start;
7158 if (DisSymName.empty() && FirstSymbol && Start != 0) {
7159 FirstSymbolAtSectionStart = false;
7160 Start = 0;
7161 }
7162 else
7163 outs() << SymName << ":\n";
7164
Ahmed Bougachaaa790682013-05-24 01:07:04 +00007165 DILineInfo lastLine;
7166 for (uint64_t Index = Start; Index < End; Index += Size) {
7167 MCInst Inst;
Owen Andersond9243c42011-10-17 21:37:35 +00007168
Kevin Enderbyc138da32017-02-06 18:43:18 +00007169 // If this is the first symbol in the section and it was not at the
7170 // start of the section, see if we are at its Index now and if so print
7171 // the symbol name.
7172 if (FirstSymbol && !FirstSymbolAtSectionStart && Index == SymbolStart)
7173 outs() << SymName << ":\n";
7174
Kevin Enderbybf246f52014-09-24 23:08:22 +00007175 uint64_t PC = SectAddress + Index;
Kevin Enderbyab5e6c92015-03-17 21:07:39 +00007176 if (!NoLeadingAddr) {
7177 if (FullLeadingAddr) {
7178 if (MachOOF->is64Bit())
7179 outs() << format("%016" PRIx64, PC);
7180 else
7181 outs() << format("%08" PRIx64, PC);
7182 } else {
7183 outs() << format("%8" PRIx64 ":", PC);
7184 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00007185 }
Kevin Enderby4b627be2016-04-28 20:14:13 +00007186 if (!NoShowRawInsn || Arch == Triple::arm)
Kevin Enderbybf246f52014-09-24 23:08:22 +00007187 outs() << "\t";
Kevin Enderby273ae012013-06-06 17:20:50 +00007188
7189 // Check the data in code table here to see if this is data not an
7190 // instruction to be disassembled.
7191 DiceTable Dice;
Kevin Enderbybf246f52014-09-24 23:08:22 +00007192 Dice.push_back(std::make_pair(PC, DiceRef()));
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007193 dice_table_iterator DTI =
7194 std::search(Dices.begin(), Dices.end(), Dice.begin(), Dice.end(),
7195 compareDiceTableEntries);
7196 if (DTI != Dices.end()) {
Kevin Enderby273ae012013-06-06 17:20:50 +00007197 uint16_t Length;
7198 DTI->second.getLength(Length);
Kevin Enderby273ae012013-06-06 17:20:50 +00007199 uint16_t Kind;
7200 DTI->second.getKind(Kind);
Colin LeMahieufc32b1b2015-03-18 19:27:31 +00007201 Size = DumpDataInCode(Bytes.data() + Index, Length, Kind);
Kevin Enderby930fdc72014-11-06 19:00:13 +00007202 if ((Kind == MachO::DICE_KIND_JUMP_TABLE8) &&
7203 (PC == (DTI->first + Length - 1)) && (Length & 1))
7204 Size++;
Kevin Enderby273ae012013-06-06 17:20:50 +00007205 continue;
7206 }
7207
Kevin Enderbybf246f52014-09-24 23:08:22 +00007208 SmallVector<char, 64> AnnotationsBytes;
7209 raw_svector_ostream Annotations(AnnotationsBytes);
7210
Kevin Enderbyec5ca032014-08-18 20:21:02 +00007211 bool gotInst;
Tim Northover09ca33e2016-04-22 23:23:31 +00007212 if (UseThumbTarget)
Rafael Espindola7fc5b872014-11-12 02:04:27 +00007213 gotInst = ThumbDisAsm->getInstruction(Inst, Size, Bytes.slice(Index),
Kevin Enderby6f326ce2014-10-23 19:37:31 +00007214 PC, DebugOut, Annotations);
Kevin Enderbyec5ca032014-08-18 20:21:02 +00007215 else
Rafael Espindola7fc5b872014-11-12 02:04:27 +00007216 gotInst = DisAsm->getInstruction(Inst, Size, Bytes.slice(Index), PC,
Kevin Enderbybf246f52014-09-24 23:08:22 +00007217 DebugOut, Annotations);
Kevin Enderbyec5ca032014-08-18 20:21:02 +00007218 if (gotInst) {
Kevin Enderby4b627be2016-04-28 20:14:13 +00007219 if (!NoShowRawInsn || Arch == Triple::arm) {
Craig Topper0013be12015-09-21 05:32:41 +00007220 dumpBytes(makeArrayRef(Bytes.data() + Index, Size), outs());
Kevin Enderbybf246f52014-09-24 23:08:22 +00007221 }
7222 formatted_raw_ostream FormattedOS(outs());
Kevin Enderbybf246f52014-09-24 23:08:22 +00007223 StringRef AnnotationsStr = Annotations.str();
Tim Northover09ca33e2016-04-22 23:23:31 +00007224 if (UseThumbTarget)
Akira Hatanakab46d0232015-03-27 20:36:02 +00007225 ThumbIP->printInst(&Inst, FormattedOS, AnnotationsStr, *ThumbSTI);
Kevin Enderbyec5ca032014-08-18 20:21:02 +00007226 else
Akira Hatanaka1d079942015-03-28 20:44:05 +00007227 IP->printInst(&Inst, FormattedOS, AnnotationsStr, *STI);
Kevin Enderbybf246f52014-09-24 23:08:22 +00007228 emitComments(CommentStream, CommentsToEmit, FormattedOS, *AsmInfo);
Owen Andersond9243c42011-10-17 21:37:35 +00007229
Ahmed Bougachaaa790682013-05-24 01:07:04 +00007230 // Print debug info.
7231 if (diContext) {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007232 DILineInfo dli = diContext->getLineInfoForAddress(PC);
Ahmed Bougachaaa790682013-05-24 01:07:04 +00007233 // Print valid line info if it changed.
Alexey Samsonovd0109992014-04-18 21:36:39 +00007234 if (dli != lastLine && dli.Line != 0)
7235 outs() << "\t## " << dli.FileName << ':' << dli.Line << ':'
7236 << dli.Column;
Ahmed Bougachaaa790682013-05-24 01:07:04 +00007237 lastLine = dli;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007238 }
Ahmed Bougachaaa790682013-05-24 01:07:04 +00007239 outs() << "\n";
7240 } else {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00007241 unsigned int Arch = MachOOF->getArch();
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007242 if (Arch == Triple::x86_64 || Arch == Triple::x86) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00007243 outs() << format("\t.byte 0x%02x #bad opcode\n",
7244 *(Bytes.data() + Index) & 0xff);
7245 Size = 1; // skip exactly one illegible byte and move on.
Tim Northover09ca33e2016-04-22 23:23:31 +00007246 } else if (Arch == Triple::aarch64 ||
7247 (Arch == Triple::arm && !IsThumb)) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00007248 uint32_t opcode = (*(Bytes.data() + Index) & 0xff) |
7249 (*(Bytes.data() + Index + 1) & 0xff) << 8 |
7250 (*(Bytes.data() + Index + 2) & 0xff) << 16 |
7251 (*(Bytes.data() + Index + 3) & 0xff) << 24;
7252 outs() << format("\t.long\t0x%08x\n", opcode);
7253 Size = 4;
Tim Northover09ca33e2016-04-22 23:23:31 +00007254 } else if (Arch == Triple::arm) {
7255 assert(IsThumb && "ARM mode should have been dealt with above");
7256 uint32_t opcode = (*(Bytes.data() + Index) & 0xff) |
7257 (*(Bytes.data() + Index + 1) & 0xff) << 8;
7258 outs() << format("\t.short\t0x%04x\n", opcode);
7259 Size = 2;
7260 } else{
Jonas Devliegheree787efd2018-11-11 22:12:04 +00007261 WithColor::warning(errs(), "llvm-objdump")
7262 << "invalid instruction encoding\n";
Kevin Enderby6f326ce2014-10-23 19:37:31 +00007263 if (Size == 0)
7264 Size = 1; // skip illegible bytes
7265 }
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007266 }
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007267 }
Kevin Enderbyc138da32017-02-06 18:43:18 +00007268 // Now that we are done disassembled the first symbol set the bool that
7269 // were doing this to false.
7270 FirstSymbol = false;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007271 }
Ahmed Bougachaaa790682013-05-24 01:07:04 +00007272 if (!symbolTableWorked) {
Rafael Espindola80291272014-10-08 15:28:58 +00007273 // Reading the symbol table didn't work, disassemble the whole section.
7274 uint64_t SectAddress = Sections[SectIdx].getAddress();
7275 uint64_t SectSize = Sections[SectIdx].getSize();
Kevin Enderbybadd1002012-05-18 00:13:56 +00007276 uint64_t InstSize;
7277 for (uint64_t Index = 0; Index < SectSize; Index += InstSize) {
Bill Wendling4e68e062012-07-19 00:17:40 +00007278 MCInst Inst;
Kevin Enderbybadd1002012-05-18 00:13:56 +00007279
Kevin Enderbybf246f52014-09-24 23:08:22 +00007280 uint64_t PC = SectAddress + Index;
Kevin Enderby02d3a372017-01-31 18:09:10 +00007281 SmallVector<char, 64> AnnotationsBytes;
7282 raw_svector_ostream Annotations(AnnotationsBytes);
Rafael Espindola7fc5b872014-11-12 02:04:27 +00007283 if (DisAsm->getInstruction(Inst, InstSize, Bytes.slice(Index), PC,
Kevin Enderby02d3a372017-01-31 18:09:10 +00007284 DebugOut, Annotations)) {
Kevin Enderbyab5e6c92015-03-17 21:07:39 +00007285 if (!NoLeadingAddr) {
7286 if (FullLeadingAddr) {
7287 if (MachOOF->is64Bit())
7288 outs() << format("%016" PRIx64, PC);
7289 else
7290 outs() << format("%08" PRIx64, PC);
7291 } else {
7292 outs() << format("%8" PRIx64 ":", PC);
7293 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00007294 }
Kevin Enderby4b627be2016-04-28 20:14:13 +00007295 if (!NoShowRawInsn || Arch == Triple::arm) {
Kevin Enderbybf246f52014-09-24 23:08:22 +00007296 outs() << "\t";
Craig Topper0013be12015-09-21 05:32:41 +00007297 dumpBytes(makeArrayRef(Bytes.data() + Index, InstSize), outs());
Kevin Enderbybf246f52014-09-24 23:08:22 +00007298 }
Kevin Enderby02d3a372017-01-31 18:09:10 +00007299 StringRef AnnotationsStr = Annotations.str();
7300 IP->printInst(&Inst, outs(), AnnotationsStr, *STI);
Bill Wendling4e68e062012-07-19 00:17:40 +00007301 outs() << "\n";
7302 } else {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00007303 unsigned int Arch = MachOOF->getArch();
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007304 if (Arch == Triple::x86_64 || Arch == Triple::x86) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00007305 outs() << format("\t.byte 0x%02x #bad opcode\n",
7306 *(Bytes.data() + Index) & 0xff);
7307 InstSize = 1; // skip exactly one illegible byte and move on.
7308 } else {
Jonas Devliegheree787efd2018-11-11 22:12:04 +00007309 WithColor::warning(errs(), "llvm-objdump")
7310 << "invalid instruction encoding\n";
Kevin Enderby6f326ce2014-10-23 19:37:31 +00007311 if (InstSize == 0)
7312 InstSize = 1; // skip illegible bytes
7313 }
Bill Wendling4e68e062012-07-19 00:17:40 +00007314 }
Kevin Enderbybadd1002012-05-18 00:13:56 +00007315 }
7316 }
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00007317 // The TripleName's need to be reset if we are called again for a different
7318 // archtecture.
7319 TripleName = "";
7320 ThumbTripleName = "";
7321
Kevin Enderby04bf6932014-10-28 23:39:46 +00007322 if (SymbolizerInfo.demangled_name != nullptr)
7323 free(SymbolizerInfo.demangled_name);
Kevin Enderby930fdc72014-11-06 19:00:13 +00007324 if (ThumbSymbolizerInfo.demangled_name != nullptr)
7325 free(ThumbSymbolizerInfo.demangled_name);
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007326 }
7327}
Tim Northover4bd286a2014-08-01 13:07:19 +00007328
Tim Northover39c70bb2014-08-12 11:52:59 +00007329//===----------------------------------------------------------------------===//
7330// __compact_unwind section dumping
7331//===----------------------------------------------------------------------===//
7332
Tim Northover4bd286a2014-08-01 13:07:19 +00007333namespace {
Tim Northover39c70bb2014-08-12 11:52:59 +00007334
Tim Northover3a4e1c72018-01-23 13:51:57 +00007335template <typename T>
7336static uint64_t read(StringRef Contents, ptrdiff_t Offset) {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007337 using llvm::support::little;
7338 using llvm::support::unaligned;
Tim Northover39c70bb2014-08-12 11:52:59 +00007339
Tim Northover3a4e1c72018-01-23 13:51:57 +00007340 if (Offset + sizeof(T) > Contents.size()) {
7341 outs() << "warning: attempt to read past end of buffer\n";
7342 return T();
7343 }
7344
7345 uint64_t Val =
7346 support::endian::read<T, little, unaligned>(Contents.data() + Offset);
7347 return Val;
7348}
7349
7350template <typename T>
7351static uint64_t readNext(StringRef Contents, ptrdiff_t &Offset) {
7352 T Val = read<T>(Contents, Offset);
7353 Offset += sizeof(T);
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007354 return Val;
7355}
Tim Northover39c70bb2014-08-12 11:52:59 +00007356
Tim Northover4bd286a2014-08-01 13:07:19 +00007357struct CompactUnwindEntry {
7358 uint32_t OffsetInSection;
7359
7360 uint64_t FunctionAddr;
7361 uint32_t Length;
7362 uint32_t CompactEncoding;
7363 uint64_t PersonalityAddr;
7364 uint64_t LSDAAddr;
7365
7366 RelocationRef FunctionReloc;
7367 RelocationRef PersonalityReloc;
7368 RelocationRef LSDAReloc;
7369
7370 CompactUnwindEntry(StringRef Contents, unsigned Offset, bool Is64)
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007371 : OffsetInSection(Offset) {
Tim Northover4bd286a2014-08-01 13:07:19 +00007372 if (Is64)
Tim Northover3a4e1c72018-01-23 13:51:57 +00007373 read<uint64_t>(Contents, Offset);
Tim Northover4bd286a2014-08-01 13:07:19 +00007374 else
Tim Northover3a4e1c72018-01-23 13:51:57 +00007375 read<uint32_t>(Contents, Offset);
Tim Northover4bd286a2014-08-01 13:07:19 +00007376 }
7377
7378private:
Tim Northover3a4e1c72018-01-23 13:51:57 +00007379 template <typename UIntPtr> void read(StringRef Contents, ptrdiff_t Offset) {
7380 FunctionAddr = readNext<UIntPtr>(Contents, Offset);
7381 Length = readNext<uint32_t>(Contents, Offset);
7382 CompactEncoding = readNext<uint32_t>(Contents, Offset);
7383 PersonalityAddr = readNext<UIntPtr>(Contents, Offset);
7384 LSDAAddr = readNext<UIntPtr>(Contents, Offset);
Tim Northover4bd286a2014-08-01 13:07:19 +00007385 }
7386};
7387}
7388
7389/// Given a relocation from __compact_unwind, consisting of the RelocationRef
7390/// and data being relocated, determine the best base Name and Addend to use for
7391/// display purposes.
7392///
7393/// 1. An Extern relocation will directly reference a symbol (and the data is
7394/// then already an addend), so use that.
7395/// 2. Otherwise the data is an offset in the object file's layout; try to find
7396// a symbol before it in the same section, and use the offset from there.
7397/// 3. Finally, if all that fails, fall back to an offset from the start of the
7398/// referenced section.
7399static void findUnwindRelocNameAddend(const MachOObjectFile *Obj,
7400 std::map<uint64_t, SymbolRef> &Symbols,
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007401 const RelocationRef &Reloc, uint64_t Addr,
Tim Northover4bd286a2014-08-01 13:07:19 +00007402 StringRef &Name, uint64_t &Addend) {
7403 if (Reloc.getSymbol() != Obj->symbol_end()) {
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00007404 Expected<StringRef> NameOrErr = Reloc.getSymbol()->getName();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00007405 if (!NameOrErr)
7406 report_error(Obj->getFileName(), NameOrErr.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00007407 Name = *NameOrErr;
Tim Northover4bd286a2014-08-01 13:07:19 +00007408 Addend = Addr;
7409 return;
7410 }
7411
7412 auto RE = Obj->getRelocation(Reloc.getRawDataRefImpl());
Keno Fischerc780e8e2015-05-21 21:24:32 +00007413 SectionRef RelocSection = Obj->getAnyRelocationSection(RE);
Tim Northover4bd286a2014-08-01 13:07:19 +00007414
Rafael Espindola80291272014-10-08 15:28:58 +00007415 uint64_t SectionAddr = RelocSection.getAddress();
Tim Northover4bd286a2014-08-01 13:07:19 +00007416
7417 auto Sym = Symbols.upper_bound(Addr);
7418 if (Sym == Symbols.begin()) {
7419 // The first symbol in the object is after this reference, the best we can
7420 // do is section-relative notation.
7421 RelocSection.getName(Name);
7422 Addend = Addr - SectionAddr;
7423 return;
7424 }
7425
7426 // Go back one so that SymbolAddress <= Addr.
7427 --Sym;
7428
Kevin Enderby7bd8d992016-05-02 20:28:12 +00007429 auto SectOrErr = Sym->second.getSection();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00007430 if (!SectOrErr)
7431 report_error(Obj->getFileName(), SectOrErr.takeError());
Kevin Enderby7bd8d992016-05-02 20:28:12 +00007432 section_iterator SymSection = *SectOrErr;
Tim Northover4bd286a2014-08-01 13:07:19 +00007433 if (RelocSection == *SymSection) {
7434 // There's a valid symbol in the same section before this reference.
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00007435 Expected<StringRef> NameOrErr = Sym->second.getName();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00007436 if (!NameOrErr)
7437 report_error(Obj->getFileName(), NameOrErr.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00007438 Name = *NameOrErr;
Tim Northover4bd286a2014-08-01 13:07:19 +00007439 Addend = Addr - Sym->first;
7440 return;
7441 }
7442
7443 // There is a symbol before this reference, but it's in a different
7444 // section. Probably not helpful to mention it, so use the section name.
7445 RelocSection.getName(Name);
7446 Addend = Addr - SectionAddr;
7447}
7448
7449static void printUnwindRelocDest(const MachOObjectFile *Obj,
7450 std::map<uint64_t, SymbolRef> &Symbols,
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007451 const RelocationRef &Reloc, uint64_t Addr) {
Tim Northover4bd286a2014-08-01 13:07:19 +00007452 StringRef Name;
7453 uint64_t Addend;
7454
Rafael Espindola854038e2015-06-26 14:51:16 +00007455 if (!Reloc.getObject())
Tim Northover0b0add52014-09-09 10:45:06 +00007456 return;
7457
Tim Northover4bd286a2014-08-01 13:07:19 +00007458 findUnwindRelocNameAddend(Obj, Symbols, Reloc, Addr, Name, Addend);
7459
7460 outs() << Name;
7461 if (Addend)
Tim Northover63a25622014-08-11 09:14:06 +00007462 outs() << " + " << format("0x%" PRIx64, Addend);
Tim Northover4bd286a2014-08-01 13:07:19 +00007463}
7464
7465static void
7466printMachOCompactUnwindSection(const MachOObjectFile *Obj,
7467 std::map<uint64_t, SymbolRef> &Symbols,
7468 const SectionRef &CompactUnwind) {
7469
Tim Northoverbf55f7e2016-11-15 20:26:01 +00007470 if (!Obj->isLittleEndian()) {
7471 outs() << "Skipping big-endian __compact_unwind section\n";
7472 return;
7473 }
Tim Northover4bd286a2014-08-01 13:07:19 +00007474
7475 bool Is64 = Obj->is64Bit();
7476 uint32_t PointerSize = Is64 ? sizeof(uint64_t) : sizeof(uint32_t);
7477 uint32_t EntrySize = 3 * PointerSize + 2 * sizeof(uint32_t);
7478
7479 StringRef Contents;
7480 CompactUnwind.getContents(Contents);
7481
7482 SmallVector<CompactUnwindEntry, 4> CompactUnwinds;
7483
7484 // First populate the initial raw offsets, encodings and so on from the entry.
7485 for (unsigned Offset = 0; Offset < Contents.size(); Offset += EntrySize) {
Tim Northover3a4e1c72018-01-23 13:51:57 +00007486 CompactUnwindEntry Entry(Contents, Offset, Is64);
Tim Northover4bd286a2014-08-01 13:07:19 +00007487 CompactUnwinds.push_back(Entry);
7488 }
7489
7490 // Next we need to look at the relocations to find out what objects are
7491 // actually being referred to.
7492 for (const RelocationRef &Reloc : CompactUnwind.relocations()) {
Rafael Espindola96d071c2015-06-29 23:29:12 +00007493 uint64_t RelocAddress = Reloc.getOffset();
Tim Northover4bd286a2014-08-01 13:07:19 +00007494
7495 uint32_t EntryIdx = RelocAddress / EntrySize;
7496 uint32_t OffsetInEntry = RelocAddress - EntryIdx * EntrySize;
7497 CompactUnwindEntry &Entry = CompactUnwinds[EntryIdx];
7498
7499 if (OffsetInEntry == 0)
7500 Entry.FunctionReloc = Reloc;
7501 else if (OffsetInEntry == PointerSize + 2 * sizeof(uint32_t))
7502 Entry.PersonalityReloc = Reloc;
7503 else if (OffsetInEntry == 2 * PointerSize + 2 * sizeof(uint32_t))
7504 Entry.LSDAReloc = Reloc;
Tim Northoverbf55f7e2016-11-15 20:26:01 +00007505 else {
7506 outs() << "Invalid relocation in __compact_unwind section\n";
7507 return;
7508 }
Tim Northover4bd286a2014-08-01 13:07:19 +00007509 }
7510
7511 // Finally, we're ready to print the data we've gathered.
7512 outs() << "Contents of __compact_unwind section:\n";
7513 for (auto &Entry : CompactUnwinds) {
Tim Northover06af2602014-08-08 12:08:51 +00007514 outs() << " Entry at offset "
7515 << format("0x%" PRIx32, Entry.OffsetInSection) << ":\n";
Tim Northover4bd286a2014-08-01 13:07:19 +00007516
7517 // 1. Start of the region this entry applies to.
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007518 outs() << " start: " << format("0x%" PRIx64,
7519 Entry.FunctionAddr) << ' ';
7520 printUnwindRelocDest(Obj, Symbols, Entry.FunctionReloc, Entry.FunctionAddr);
Tim Northover4bd286a2014-08-01 13:07:19 +00007521 outs() << '\n';
7522
7523 // 2. Length of the region this entry applies to.
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007524 outs() << " length: " << format("0x%" PRIx32, Entry.Length)
7525 << '\n';
Tim Northover4bd286a2014-08-01 13:07:19 +00007526 // 3. The 32-bit compact encoding.
7527 outs() << " compact encoding: "
Tim Northoverb911bf82014-08-08 12:00:09 +00007528 << format("0x%08" PRIx32, Entry.CompactEncoding) << '\n';
Tim Northover4bd286a2014-08-01 13:07:19 +00007529
7530 // 4. The personality function, if present.
Rafael Espindola854038e2015-06-26 14:51:16 +00007531 if (Entry.PersonalityReloc.getObject()) {
Tim Northover4bd286a2014-08-01 13:07:19 +00007532 outs() << " personality function: "
Tim Northoverb911bf82014-08-08 12:00:09 +00007533 << format("0x%" PRIx64, Entry.PersonalityAddr) << ' ';
Tim Northover4bd286a2014-08-01 13:07:19 +00007534 printUnwindRelocDest(Obj, Symbols, Entry.PersonalityReloc,
7535 Entry.PersonalityAddr);
7536 outs() << '\n';
7537 }
7538
7539 // 5. This entry's language-specific data area.
Rafael Espindola854038e2015-06-26 14:51:16 +00007540 if (Entry.LSDAReloc.getObject()) {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007541 outs() << " LSDA: " << format("0x%" PRIx64,
7542 Entry.LSDAAddr) << ' ';
Tim Northover4bd286a2014-08-01 13:07:19 +00007543 printUnwindRelocDest(Obj, Symbols, Entry.LSDAReloc, Entry.LSDAAddr);
7544 outs() << '\n';
7545 }
7546 }
7547}
7548
Tim Northover39c70bb2014-08-12 11:52:59 +00007549//===----------------------------------------------------------------------===//
7550// __unwind_info section dumping
7551//===----------------------------------------------------------------------===//
7552
Tim Northover3a4e1c72018-01-23 13:51:57 +00007553static void printRegularSecondLevelUnwindPage(StringRef PageData) {
7554 ptrdiff_t Pos = 0;
7555 uint32_t Kind = readNext<uint32_t>(PageData, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007556 (void)Kind;
7557 assert(Kind == 2 && "kind for a regular 2nd level index should be 2");
7558
Tim Northover3a4e1c72018-01-23 13:51:57 +00007559 uint16_t EntriesStart = readNext<uint16_t>(PageData, Pos);
7560 uint16_t NumEntries = readNext<uint16_t>(PageData, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007561
Tim Northover3a4e1c72018-01-23 13:51:57 +00007562 Pos = EntriesStart;
Tim Northover39c70bb2014-08-12 11:52:59 +00007563 for (unsigned i = 0; i < NumEntries; ++i) {
Tim Northover3a4e1c72018-01-23 13:51:57 +00007564 uint32_t FunctionOffset = readNext<uint32_t>(PageData, Pos);
7565 uint32_t Encoding = readNext<uint32_t>(PageData, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007566
7567 outs() << " [" << i << "]: "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007568 << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
7569 << ", "
7570 << "encoding=" << format("0x%08" PRIx32, Encoding) << '\n';
Tim Northover39c70bb2014-08-12 11:52:59 +00007571 }
7572}
7573
7574static void printCompressedSecondLevelUnwindPage(
Tim Northover3a4e1c72018-01-23 13:51:57 +00007575 StringRef PageData, uint32_t FunctionBase,
Tim Northover39c70bb2014-08-12 11:52:59 +00007576 const SmallVectorImpl<uint32_t> &CommonEncodings) {
Tim Northover3a4e1c72018-01-23 13:51:57 +00007577 ptrdiff_t Pos = 0;
7578 uint32_t Kind = readNext<uint32_t>(PageData, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007579 (void)Kind;
7580 assert(Kind == 3 && "kind for a compressed 2nd level index should be 3");
7581
Tim Northover3a4e1c72018-01-23 13:51:57 +00007582 uint16_t EntriesStart = readNext<uint16_t>(PageData, Pos);
7583 uint16_t NumEntries = readNext<uint16_t>(PageData, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007584
Tim Northover3a4e1c72018-01-23 13:51:57 +00007585 uint16_t EncodingsStart = readNext<uint16_t>(PageData, Pos);
7586 readNext<uint16_t>(PageData, Pos);
7587 StringRef PageEncodings = PageData.substr(EncodingsStart, StringRef::npos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007588
Tim Northover3a4e1c72018-01-23 13:51:57 +00007589 Pos = EntriesStart;
Tim Northover39c70bb2014-08-12 11:52:59 +00007590 for (unsigned i = 0; i < NumEntries; ++i) {
Tim Northover3a4e1c72018-01-23 13:51:57 +00007591 uint32_t Entry = readNext<uint32_t>(PageData, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007592 uint32_t FunctionOffset = FunctionBase + (Entry & 0xffffff);
7593 uint32_t EncodingIdx = Entry >> 24;
7594
7595 uint32_t Encoding;
7596 if (EncodingIdx < CommonEncodings.size())
7597 Encoding = CommonEncodings[EncodingIdx];
7598 else
Tim Northover3a4e1c72018-01-23 13:51:57 +00007599 Encoding = read<uint32_t>(PageEncodings,
7600 sizeof(uint32_t) *
7601 (EncodingIdx - CommonEncodings.size()));
Tim Northover39c70bb2014-08-12 11:52:59 +00007602
7603 outs() << " [" << i << "]: "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007604 << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
7605 << ", "
7606 << "encoding[" << EncodingIdx
7607 << "]=" << format("0x%08" PRIx32, Encoding) << '\n';
Tim Northover39c70bb2014-08-12 11:52:59 +00007608 }
7609}
7610
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007611static void printMachOUnwindInfoSection(const MachOObjectFile *Obj,
7612 std::map<uint64_t, SymbolRef> &Symbols,
7613 const SectionRef &UnwindInfo) {
Tim Northover39c70bb2014-08-12 11:52:59 +00007614
Tim Northoverbf55f7e2016-11-15 20:26:01 +00007615 if (!Obj->isLittleEndian()) {
7616 outs() << "Skipping big-endian __unwind_info section\n";
7617 return;
7618 }
Tim Northover39c70bb2014-08-12 11:52:59 +00007619
7620 outs() << "Contents of __unwind_info section:\n";
7621
7622 StringRef Contents;
7623 UnwindInfo.getContents(Contents);
Tim Northover3a4e1c72018-01-23 13:51:57 +00007624 ptrdiff_t Pos = 0;
Tim Northover39c70bb2014-08-12 11:52:59 +00007625
7626 //===----------------------------------
7627 // Section header
7628 //===----------------------------------
7629
Tim Northover3a4e1c72018-01-23 13:51:57 +00007630 uint32_t Version = readNext<uint32_t>(Contents, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007631 outs() << " Version: "
7632 << format("0x%" PRIx32, Version) << '\n';
Tim Northoverbf55f7e2016-11-15 20:26:01 +00007633 if (Version != 1) {
7634 outs() << " Skipping section with unknown version\n";
7635 return;
7636 }
Tim Northover39c70bb2014-08-12 11:52:59 +00007637
Tim Northover3a4e1c72018-01-23 13:51:57 +00007638 uint32_t CommonEncodingsStart = readNext<uint32_t>(Contents, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007639 outs() << " Common encodings array section offset: "
7640 << format("0x%" PRIx32, CommonEncodingsStart) << '\n';
Tim Northover3a4e1c72018-01-23 13:51:57 +00007641 uint32_t NumCommonEncodings = readNext<uint32_t>(Contents, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007642 outs() << " Number of common encodings in array: "
7643 << format("0x%" PRIx32, NumCommonEncodings) << '\n';
7644
Tim Northover3a4e1c72018-01-23 13:51:57 +00007645 uint32_t PersonalitiesStart = readNext<uint32_t>(Contents, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007646 outs() << " Personality function array section offset: "
7647 << format("0x%" PRIx32, PersonalitiesStart) << '\n';
Tim Northover3a4e1c72018-01-23 13:51:57 +00007648 uint32_t NumPersonalities = readNext<uint32_t>(Contents, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007649 outs() << " Number of personality functions in array: "
7650 << format("0x%" PRIx32, NumPersonalities) << '\n';
7651
Tim Northover3a4e1c72018-01-23 13:51:57 +00007652 uint32_t IndicesStart = readNext<uint32_t>(Contents, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007653 outs() << " Index array section offset: "
7654 << format("0x%" PRIx32, IndicesStart) << '\n';
Tim Northover3a4e1c72018-01-23 13:51:57 +00007655 uint32_t NumIndices = readNext<uint32_t>(Contents, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007656 outs() << " Number of indices in array: "
7657 << format("0x%" PRIx32, NumIndices) << '\n';
7658
7659 //===----------------------------------
7660 // A shared list of common encodings
7661 //===----------------------------------
7662
7663 // These occupy indices in the range [0, N] whenever an encoding is referenced
7664 // from a compressed 2nd level index table. In practice the linker only
7665 // creates ~128 of these, so that indices are available to embed encodings in
7666 // the 2nd level index.
7667
7668 SmallVector<uint32_t, 64> CommonEncodings;
7669 outs() << " Common encodings: (count = " << NumCommonEncodings << ")\n";
Tim Northover3a4e1c72018-01-23 13:51:57 +00007670 Pos = CommonEncodingsStart;
Tim Northover39c70bb2014-08-12 11:52:59 +00007671 for (unsigned i = 0; i < NumCommonEncodings; ++i) {
Tim Northover3a4e1c72018-01-23 13:51:57 +00007672 uint32_t Encoding = readNext<uint32_t>(Contents, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007673 CommonEncodings.push_back(Encoding);
7674
7675 outs() << " encoding[" << i << "]: " << format("0x%08" PRIx32, Encoding)
7676 << '\n';
7677 }
7678
Tim Northover39c70bb2014-08-12 11:52:59 +00007679 //===----------------------------------
7680 // Personality functions used in this executable
7681 //===----------------------------------
7682
7683 // There should be only a handful of these (one per source language,
7684 // roughly). Particularly since they only get 2 bits in the compact encoding.
7685
7686 outs() << " Personality functions: (count = " << NumPersonalities << ")\n";
Tim Northover3a4e1c72018-01-23 13:51:57 +00007687 Pos = PersonalitiesStart;
Tim Northover39c70bb2014-08-12 11:52:59 +00007688 for (unsigned i = 0; i < NumPersonalities; ++i) {
Tim Northover3a4e1c72018-01-23 13:51:57 +00007689 uint32_t PersonalityFn = readNext<uint32_t>(Contents, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007690 outs() << " personality[" << i + 1
7691 << "]: " << format("0x%08" PRIx32, PersonalityFn) << '\n';
7692 }
7693
7694 //===----------------------------------
7695 // The level 1 index entries
7696 //===----------------------------------
7697
7698 // These specify an approximate place to start searching for the more detailed
7699 // information, sorted by PC.
7700
7701 struct IndexEntry {
7702 uint32_t FunctionOffset;
7703 uint32_t SecondLevelPageStart;
7704 uint32_t LSDAStart;
7705 };
7706
7707 SmallVector<IndexEntry, 4> IndexEntries;
7708
7709 outs() << " Top level indices: (count = " << NumIndices << ")\n";
Tim Northover3a4e1c72018-01-23 13:51:57 +00007710 Pos = IndicesStart;
Tim Northover39c70bb2014-08-12 11:52:59 +00007711 for (unsigned i = 0; i < NumIndices; ++i) {
7712 IndexEntry Entry;
7713
Tim Northover3a4e1c72018-01-23 13:51:57 +00007714 Entry.FunctionOffset = readNext<uint32_t>(Contents, Pos);
7715 Entry.SecondLevelPageStart = readNext<uint32_t>(Contents, Pos);
7716 Entry.LSDAStart = readNext<uint32_t>(Contents, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007717 IndexEntries.push_back(Entry);
7718
7719 outs() << " [" << i << "]: "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007720 << "function offset=" << format("0x%08" PRIx32, Entry.FunctionOffset)
7721 << ", "
Tim Northover39c70bb2014-08-12 11:52:59 +00007722 << "2nd level page offset="
7723 << format("0x%08" PRIx32, Entry.SecondLevelPageStart) << ", "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007724 << "LSDA offset=" << format("0x%08" PRIx32, Entry.LSDAStart) << '\n';
Tim Northover39c70bb2014-08-12 11:52:59 +00007725 }
7726
Tim Northover39c70bb2014-08-12 11:52:59 +00007727 //===----------------------------------
7728 // Next come the LSDA tables
7729 //===----------------------------------
7730
7731 // The LSDA layout is rather implicit: it's a contiguous array of entries from
7732 // the first top-level index's LSDAOffset to the last (sentinel).
7733
7734 outs() << " LSDA descriptors:\n";
Tim Northover3a4e1c72018-01-23 13:51:57 +00007735 Pos = IndexEntries[0].LSDAStart;
7736 const uint32_t LSDASize = 2 * sizeof(uint32_t);
7737 int NumLSDAs =
7738 (IndexEntries.back().LSDAStart - IndexEntries[0].LSDAStart) / LSDASize;
7739
Tim Northover39c70bb2014-08-12 11:52:59 +00007740 for (int i = 0; i < NumLSDAs; ++i) {
Tim Northover3a4e1c72018-01-23 13:51:57 +00007741 uint32_t FunctionOffset = readNext<uint32_t>(Contents, Pos);
7742 uint32_t LSDAOffset = readNext<uint32_t>(Contents, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007743 outs() << " [" << i << "]: "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007744 << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
7745 << ", "
7746 << "LSDA offset=" << format("0x%08" PRIx32, LSDAOffset) << '\n';
Tim Northover39c70bb2014-08-12 11:52:59 +00007747 }
7748
7749 //===----------------------------------
7750 // Finally, the 2nd level indices
7751 //===----------------------------------
7752
7753 // Generally these are 4K in size, and have 2 possible forms:
7754 // + Regular stores up to 511 entries with disparate encodings
7755 // + Compressed stores up to 1021 entries if few enough compact encoding
7756 // values are used.
7757 outs() << " Second level indices:\n";
7758 for (unsigned i = 0; i < IndexEntries.size() - 1; ++i) {
7759 // The final sentinel top-level index has no associated 2nd level page
7760 if (IndexEntries[i].SecondLevelPageStart == 0)
7761 break;
7762
7763 outs() << " Second level index[" << i << "]: "
7764 << "offset in section="
7765 << format("0x%08" PRIx32, IndexEntries[i].SecondLevelPageStart)
7766 << ", "
7767 << "base function offset="
7768 << format("0x%08" PRIx32, IndexEntries[i].FunctionOffset) << '\n';
7769
Tim Northover3a4e1c72018-01-23 13:51:57 +00007770 Pos = IndexEntries[i].SecondLevelPageStart;
7771 if (Pos + sizeof(uint32_t) > Contents.size()) {
7772 outs() << "warning: invalid offset for second level page: " << Pos << '\n';
7773 continue;
7774 }
7775
7776 uint32_t Kind =
7777 *reinterpret_cast<const support::ulittle32_t *>(Contents.data() + Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007778 if (Kind == 2)
Tim Northover3a4e1c72018-01-23 13:51:57 +00007779 printRegularSecondLevelUnwindPage(Contents.substr(Pos, 4096));
Tim Northover39c70bb2014-08-12 11:52:59 +00007780 else if (Kind == 3)
Tim Northover3a4e1c72018-01-23 13:51:57 +00007781 printCompressedSecondLevelUnwindPage(Contents.substr(Pos, 4096),
7782 IndexEntries[i].FunctionOffset,
Tim Northover39c70bb2014-08-12 11:52:59 +00007783 CommonEncodings);
7784 else
Tim Northoverbf55f7e2016-11-15 20:26:01 +00007785 outs() << " Skipping 2nd level page with unknown kind " << Kind
7786 << '\n';
Tim Northover39c70bb2014-08-12 11:52:59 +00007787 }
7788}
7789
Tim Northover4bd286a2014-08-01 13:07:19 +00007790void llvm::printMachOUnwindInfo(const MachOObjectFile *Obj) {
7791 std::map<uint64_t, SymbolRef> Symbols;
7792 for (const SymbolRef &SymRef : Obj->symbols()) {
7793 // Discard any undefined or absolute symbols. They're not going to take part
7794 // in the convenience lookup for unwind info and just take up resources.
Kevin Enderby7bd8d992016-05-02 20:28:12 +00007795 auto SectOrErr = SymRef.getSection();
7796 if (!SectOrErr) {
7797 // TODO: Actually report errors helpfully.
7798 consumeError(SectOrErr.takeError());
7799 continue;
7800 }
7801 section_iterator Section = *SectOrErr;
Tim Northover4bd286a2014-08-01 13:07:19 +00007802 if (Section == Obj->section_end())
7803 continue;
7804
Rafael Espindoladea00162015-07-03 17:44:18 +00007805 uint64_t Addr = SymRef.getValue();
Tim Northover4bd286a2014-08-01 13:07:19 +00007806 Symbols.insert(std::make_pair(Addr, SymRef));
7807 }
7808
7809 for (const SectionRef &Section : Obj->sections()) {
7810 StringRef SectName;
7811 Section.getName(SectName);
7812 if (SectName == "__compact_unwind")
7813 printMachOCompactUnwindSection(Obj, Symbols, Section);
7814 else if (SectName == "__unwind_info")
Tim Northover39c70bb2014-08-12 11:52:59 +00007815 printMachOUnwindInfoSection(Obj, Symbols, Section);
Tim Northover4bd286a2014-08-01 13:07:19 +00007816 }
7817}
Kevin Enderbyb76d3862014-08-22 20:35:18 +00007818
7819static void PrintMachHeader(uint32_t magic, uint32_t cputype,
7820 uint32_t cpusubtype, uint32_t filetype,
7821 uint32_t ncmds, uint32_t sizeofcmds, uint32_t flags,
7822 bool verbose) {
7823 outs() << "Mach header\n";
7824 outs() << " magic cputype cpusubtype caps filetype ncmds "
7825 "sizeofcmds flags\n";
7826 if (verbose) {
7827 if (magic == MachO::MH_MAGIC)
7828 outs() << " MH_MAGIC";
7829 else if (magic == MachO::MH_MAGIC_64)
7830 outs() << "MH_MAGIC_64";
7831 else
7832 outs() << format(" 0x%08" PRIx32, magic);
7833 switch (cputype) {
7834 case MachO::CPU_TYPE_I386:
7835 outs() << " I386";
7836 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
7837 case MachO::CPU_SUBTYPE_I386_ALL:
7838 outs() << " ALL";
7839 break;
7840 default:
7841 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
7842 break;
7843 }
7844 break;
7845 case MachO::CPU_TYPE_X86_64:
7846 outs() << " X86_64";
Kevin Enderby131d1772015-01-09 19:22:37 +00007847 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
7848 case MachO::CPU_SUBTYPE_X86_64_ALL:
7849 outs() << " ALL";
7850 break;
7851 case MachO::CPU_SUBTYPE_X86_64_H:
7852 outs() << " Haswell";
7853 break;
7854 default:
7855 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
7856 break;
7857 }
Kevin Enderbyb76d3862014-08-22 20:35:18 +00007858 break;
7859 case MachO::CPU_TYPE_ARM:
7860 outs() << " ARM";
7861 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
7862 case MachO::CPU_SUBTYPE_ARM_ALL:
7863 outs() << " ALL";
7864 break;
7865 case MachO::CPU_SUBTYPE_ARM_V4T:
7866 outs() << " V4T";
7867 break;
7868 case MachO::CPU_SUBTYPE_ARM_V5TEJ:
7869 outs() << " V5TEJ";
7870 break;
7871 case MachO::CPU_SUBTYPE_ARM_XSCALE:
7872 outs() << " XSCALE";
7873 break;
7874 case MachO::CPU_SUBTYPE_ARM_V6:
7875 outs() << " V6";
7876 break;
7877 case MachO::CPU_SUBTYPE_ARM_V6M:
7878 outs() << " V6M";
7879 break;
7880 case MachO::CPU_SUBTYPE_ARM_V7:
7881 outs() << " V7";
7882 break;
7883 case MachO::CPU_SUBTYPE_ARM_V7EM:
7884 outs() << " V7EM";
7885 break;
7886 case MachO::CPU_SUBTYPE_ARM_V7K:
7887 outs() << " V7K";
7888 break;
7889 case MachO::CPU_SUBTYPE_ARM_V7M:
7890 outs() << " V7M";
7891 break;
7892 case MachO::CPU_SUBTYPE_ARM_V7S:
7893 outs() << " V7S";
7894 break;
7895 default:
7896 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
7897 break;
7898 }
7899 break;
7900 case MachO::CPU_TYPE_ARM64:
7901 outs() << " ARM64";
7902 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
7903 case MachO::CPU_SUBTYPE_ARM64_ALL:
7904 outs() << " ALL";
7905 break;
7906 default:
7907 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
7908 break;
7909 }
7910 break;
7911 case MachO::CPU_TYPE_POWERPC:
7912 outs() << " PPC";
7913 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
7914 case MachO::CPU_SUBTYPE_POWERPC_ALL:
7915 outs() << " ALL";
7916 break;
7917 default:
7918 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
7919 break;
7920 }
7921 break;
7922 case MachO::CPU_TYPE_POWERPC64:
7923 outs() << " PPC64";
7924 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
7925 case MachO::CPU_SUBTYPE_POWERPC_ALL:
7926 outs() << " ALL";
7927 break;
7928 default:
7929 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
7930 break;
7931 }
7932 break;
Kevin Enderby40fdbf82016-01-26 18:20:49 +00007933 default:
7934 outs() << format(" %7d", cputype);
7935 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
7936 break;
Kevin Enderbyb76d3862014-08-22 20:35:18 +00007937 }
7938 if ((cpusubtype & MachO::CPU_SUBTYPE_MASK) == MachO::CPU_SUBTYPE_LIB64) {
Kevin Enderby8ae63c12014-09-04 16:54:47 +00007939 outs() << " LIB64";
Kevin Enderbyb76d3862014-08-22 20:35:18 +00007940 } else {
7941 outs() << format(" 0x%02" PRIx32,
7942 (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24);
7943 }
7944 switch (filetype) {
7945 case MachO::MH_OBJECT:
7946 outs() << " OBJECT";
7947 break;
7948 case MachO::MH_EXECUTE:
7949 outs() << " EXECUTE";
7950 break;
7951 case MachO::MH_FVMLIB:
7952 outs() << " FVMLIB";
7953 break;
7954 case MachO::MH_CORE:
7955 outs() << " CORE";
7956 break;
7957 case MachO::MH_PRELOAD:
7958 outs() << " PRELOAD";
7959 break;
7960 case MachO::MH_DYLIB:
7961 outs() << " DYLIB";
7962 break;
7963 case MachO::MH_DYLIB_STUB:
7964 outs() << " DYLIB_STUB";
7965 break;
7966 case MachO::MH_DYLINKER:
7967 outs() << " DYLINKER";
7968 break;
7969 case MachO::MH_BUNDLE:
7970 outs() << " BUNDLE";
7971 break;
7972 case MachO::MH_DSYM:
7973 outs() << " DSYM";
7974 break;
7975 case MachO::MH_KEXT_BUNDLE:
7976 outs() << " KEXTBUNDLE";
7977 break;
7978 default:
7979 outs() << format(" %10u", filetype);
7980 break;
7981 }
7982 outs() << format(" %5u", ncmds);
7983 outs() << format(" %10u", sizeofcmds);
7984 uint32_t f = flags;
7985 if (f & MachO::MH_NOUNDEFS) {
7986 outs() << " NOUNDEFS";
7987 f &= ~MachO::MH_NOUNDEFS;
7988 }
7989 if (f & MachO::MH_INCRLINK) {
7990 outs() << " INCRLINK";
7991 f &= ~MachO::MH_INCRLINK;
7992 }
7993 if (f & MachO::MH_DYLDLINK) {
7994 outs() << " DYLDLINK";
7995 f &= ~MachO::MH_DYLDLINK;
7996 }
7997 if (f & MachO::MH_BINDATLOAD) {
7998 outs() << " BINDATLOAD";
7999 f &= ~MachO::MH_BINDATLOAD;
8000 }
8001 if (f & MachO::MH_PREBOUND) {
8002 outs() << " PREBOUND";
8003 f &= ~MachO::MH_PREBOUND;
8004 }
8005 if (f & MachO::MH_SPLIT_SEGS) {
8006 outs() << " SPLIT_SEGS";
8007 f &= ~MachO::MH_SPLIT_SEGS;
8008 }
8009 if (f & MachO::MH_LAZY_INIT) {
8010 outs() << " LAZY_INIT";
8011 f &= ~MachO::MH_LAZY_INIT;
8012 }
8013 if (f & MachO::MH_TWOLEVEL) {
8014 outs() << " TWOLEVEL";
8015 f &= ~MachO::MH_TWOLEVEL;
8016 }
8017 if (f & MachO::MH_FORCE_FLAT) {
8018 outs() << " FORCE_FLAT";
8019 f &= ~MachO::MH_FORCE_FLAT;
8020 }
8021 if (f & MachO::MH_NOMULTIDEFS) {
8022 outs() << " NOMULTIDEFS";
8023 f &= ~MachO::MH_NOMULTIDEFS;
8024 }
8025 if (f & MachO::MH_NOFIXPREBINDING) {
8026 outs() << " NOFIXPREBINDING";
8027 f &= ~MachO::MH_NOFIXPREBINDING;
8028 }
8029 if (f & MachO::MH_PREBINDABLE) {
8030 outs() << " PREBINDABLE";
8031 f &= ~MachO::MH_PREBINDABLE;
8032 }
8033 if (f & MachO::MH_ALLMODSBOUND) {
8034 outs() << " ALLMODSBOUND";
8035 f &= ~MachO::MH_ALLMODSBOUND;
8036 }
8037 if (f & MachO::MH_SUBSECTIONS_VIA_SYMBOLS) {
8038 outs() << " SUBSECTIONS_VIA_SYMBOLS";
8039 f &= ~MachO::MH_SUBSECTIONS_VIA_SYMBOLS;
8040 }
8041 if (f & MachO::MH_CANONICAL) {
8042 outs() << " CANONICAL";
8043 f &= ~MachO::MH_CANONICAL;
8044 }
8045 if (f & MachO::MH_WEAK_DEFINES) {
8046 outs() << " WEAK_DEFINES";
8047 f &= ~MachO::MH_WEAK_DEFINES;
8048 }
8049 if (f & MachO::MH_BINDS_TO_WEAK) {
8050 outs() << " BINDS_TO_WEAK";
8051 f &= ~MachO::MH_BINDS_TO_WEAK;
8052 }
8053 if (f & MachO::MH_ALLOW_STACK_EXECUTION) {
8054 outs() << " ALLOW_STACK_EXECUTION";
8055 f &= ~MachO::MH_ALLOW_STACK_EXECUTION;
8056 }
8057 if (f & MachO::MH_DEAD_STRIPPABLE_DYLIB) {
8058 outs() << " DEAD_STRIPPABLE_DYLIB";
8059 f &= ~MachO::MH_DEAD_STRIPPABLE_DYLIB;
8060 }
8061 if (f & MachO::MH_PIE) {
8062 outs() << " PIE";
8063 f &= ~MachO::MH_PIE;
8064 }
8065 if (f & MachO::MH_NO_REEXPORTED_DYLIBS) {
8066 outs() << " NO_REEXPORTED_DYLIBS";
8067 f &= ~MachO::MH_NO_REEXPORTED_DYLIBS;
8068 }
8069 if (f & MachO::MH_HAS_TLV_DESCRIPTORS) {
8070 outs() << " MH_HAS_TLV_DESCRIPTORS";
8071 f &= ~MachO::MH_HAS_TLV_DESCRIPTORS;
8072 }
8073 if (f & MachO::MH_NO_HEAP_EXECUTION) {
8074 outs() << " MH_NO_HEAP_EXECUTION";
8075 f &= ~MachO::MH_NO_HEAP_EXECUTION;
8076 }
8077 if (f & MachO::MH_APP_EXTENSION_SAFE) {
8078 outs() << " APP_EXTENSION_SAFE";
8079 f &= ~MachO::MH_APP_EXTENSION_SAFE;
8080 }
Kevin Enderbydf0d6da2017-06-19 19:38:22 +00008081 if (f & MachO::MH_NLIST_OUTOFSYNC_WITH_DYLDINFO) {
8082 outs() << " NLIST_OUTOFSYNC_WITH_DYLDINFO";
8083 f &= ~MachO::MH_NLIST_OUTOFSYNC_WITH_DYLDINFO;
8084 }
Kevin Enderbyb76d3862014-08-22 20:35:18 +00008085 if (f != 0 || flags == 0)
8086 outs() << format(" 0x%08" PRIx32, f);
8087 } else {
8088 outs() << format(" 0x%08" PRIx32, magic);
8089 outs() << format(" %7d", cputype);
8090 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
8091 outs() << format(" 0x%02" PRIx32,
8092 (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24);
8093 outs() << format(" %10u", filetype);
8094 outs() << format(" %5u", ncmds);
8095 outs() << format(" %10u", sizeofcmds);
8096 outs() << format(" 0x%08" PRIx32, flags);
8097 }
8098 outs() << "\n";
8099}
8100
Kevin Enderby956366c2014-08-29 22:30:52 +00008101static void PrintSegmentCommand(uint32_t cmd, uint32_t cmdsize,
8102 StringRef SegName, uint64_t vmaddr,
8103 uint64_t vmsize, uint64_t fileoff,
8104 uint64_t filesize, uint32_t maxprot,
8105 uint32_t initprot, uint32_t nsects,
8106 uint32_t flags, uint32_t object_size,
8107 bool verbose) {
8108 uint64_t expected_cmdsize;
8109 if (cmd == MachO::LC_SEGMENT) {
8110 outs() << " cmd LC_SEGMENT\n";
8111 expected_cmdsize = nsects;
8112 expected_cmdsize *= sizeof(struct MachO::section);
8113 expected_cmdsize += sizeof(struct MachO::segment_command);
8114 } else {
8115 outs() << " cmd LC_SEGMENT_64\n";
8116 expected_cmdsize = nsects;
8117 expected_cmdsize *= sizeof(struct MachO::section_64);
8118 expected_cmdsize += sizeof(struct MachO::segment_command_64);
8119 }
8120 outs() << " cmdsize " << cmdsize;
8121 if (cmdsize != expected_cmdsize)
8122 outs() << " Inconsistent size\n";
8123 else
8124 outs() << "\n";
8125 outs() << " segname " << SegName << "\n";
8126 if (cmd == MachO::LC_SEGMENT_64) {
8127 outs() << " vmaddr " << format("0x%016" PRIx64, vmaddr) << "\n";
8128 outs() << " vmsize " << format("0x%016" PRIx64, vmsize) << "\n";
8129 } else {
Kevin Enderbyadb7c432014-12-16 18:58:11 +00008130 outs() << " vmaddr " << format("0x%08" PRIx64, vmaddr) << "\n";
8131 outs() << " vmsize " << format("0x%08" PRIx64, vmsize) << "\n";
Kevin Enderby956366c2014-08-29 22:30:52 +00008132 }
8133 outs() << " fileoff " << fileoff;
8134 if (fileoff > object_size)
8135 outs() << " (past end of file)\n";
8136 else
8137 outs() << "\n";
8138 outs() << " filesize " << filesize;
8139 if (fileoff + filesize > object_size)
8140 outs() << " (past end of file)\n";
8141 else
8142 outs() << "\n";
8143 if (verbose) {
8144 if ((maxprot &
8145 ~(MachO::VM_PROT_READ | MachO::VM_PROT_WRITE |
8146 MachO::VM_PROT_EXECUTE)) != 0)
8147 outs() << " maxprot ?" << format("0x%08" PRIx32, maxprot) << "\n";
8148 else {
Davide Italiano37ff06a2015-09-02 16:53:25 +00008149 outs() << " maxprot ";
8150 outs() << ((maxprot & MachO::VM_PROT_READ) ? "r" : "-");
8151 outs() << ((maxprot & MachO::VM_PROT_WRITE) ? "w" : "-");
8152 outs() << ((maxprot & MachO::VM_PROT_EXECUTE) ? "x\n" : "-\n");
Kevin Enderby956366c2014-08-29 22:30:52 +00008153 }
8154 if ((initprot &
8155 ~(MachO::VM_PROT_READ | MachO::VM_PROT_WRITE |
8156 MachO::VM_PROT_EXECUTE)) != 0)
Kevin Enderby41c9c002016-10-21 18:22:35 +00008157 outs() << " initprot ?" << format("0x%08" PRIx32, initprot) << "\n";
Kevin Enderby956366c2014-08-29 22:30:52 +00008158 else {
Kevin Enderby41c9c002016-10-21 18:22:35 +00008159 outs() << " initprot ";
Davide Italiano37ff06a2015-09-02 16:53:25 +00008160 outs() << ((initprot & MachO::VM_PROT_READ) ? "r" : "-");
8161 outs() << ((initprot & MachO::VM_PROT_WRITE) ? "w" : "-");
8162 outs() << ((initprot & MachO::VM_PROT_EXECUTE) ? "x\n" : "-\n");
Kevin Enderby956366c2014-08-29 22:30:52 +00008163 }
8164 } else {
8165 outs() << " maxprot " << format("0x%08" PRIx32, maxprot) << "\n";
8166 outs() << " initprot " << format("0x%08" PRIx32, initprot) << "\n";
8167 }
8168 outs() << " nsects " << nsects << "\n";
8169 if (verbose) {
8170 outs() << " flags";
8171 if (flags == 0)
8172 outs() << " (none)\n";
8173 else {
8174 if (flags & MachO::SG_HIGHVM) {
8175 outs() << " HIGHVM";
8176 flags &= ~MachO::SG_HIGHVM;
8177 }
8178 if (flags & MachO::SG_FVMLIB) {
8179 outs() << " FVMLIB";
8180 flags &= ~MachO::SG_FVMLIB;
8181 }
8182 if (flags & MachO::SG_NORELOC) {
8183 outs() << " NORELOC";
8184 flags &= ~MachO::SG_NORELOC;
8185 }
8186 if (flags & MachO::SG_PROTECTED_VERSION_1) {
8187 outs() << " PROTECTED_VERSION_1";
8188 flags &= ~MachO::SG_PROTECTED_VERSION_1;
8189 }
8190 if (flags)
8191 outs() << format(" 0x%08" PRIx32, flags) << " (unknown flags)\n";
8192 else
8193 outs() << "\n";
8194 }
8195 } else {
8196 outs() << " flags " << format("0x%" PRIx32, flags) << "\n";
8197 }
8198}
8199
8200static void PrintSection(const char *sectname, const char *segname,
8201 uint64_t addr, uint64_t size, uint32_t offset,
8202 uint32_t align, uint32_t reloff, uint32_t nreloc,
8203 uint32_t flags, uint32_t reserved1, uint32_t reserved2,
8204 uint32_t cmd, const char *sg_segname,
8205 uint32_t filetype, uint32_t object_size,
8206 bool verbose) {
8207 outs() << "Section\n";
8208 outs() << " sectname " << format("%.16s\n", sectname);
8209 outs() << " segname " << format("%.16s", segname);
8210 if (filetype != MachO::MH_OBJECT && strncmp(sg_segname, segname, 16) != 0)
8211 outs() << " (does not match segment)\n";
8212 else
8213 outs() << "\n";
8214 if (cmd == MachO::LC_SEGMENT_64) {
8215 outs() << " addr " << format("0x%016" PRIx64, addr) << "\n";
8216 outs() << " size " << format("0x%016" PRIx64, size);
8217 } else {
Kevin Enderby75594b62014-12-16 21:00:25 +00008218 outs() << " addr " << format("0x%08" PRIx64, addr) << "\n";
8219 outs() << " size " << format("0x%08" PRIx64, size);
Kevin Enderby956366c2014-08-29 22:30:52 +00008220 }
8221 if ((flags & MachO::S_ZEROFILL) != 0 && offset + size > object_size)
8222 outs() << " (past end of file)\n";
8223 else
8224 outs() << "\n";
8225 outs() << " offset " << offset;
8226 if (offset > object_size)
8227 outs() << " (past end of file)\n";
8228 else
8229 outs() << "\n";
8230 uint32_t align_shifted = 1 << align;
8231 outs() << " align 2^" << align << " (" << align_shifted << ")\n";
8232 outs() << " reloff " << reloff;
8233 if (reloff > object_size)
8234 outs() << " (past end of file)\n";
8235 else
8236 outs() << "\n";
8237 outs() << " nreloc " << nreloc;
8238 if (reloff + nreloc * sizeof(struct MachO::relocation_info) > object_size)
8239 outs() << " (past end of file)\n";
8240 else
8241 outs() << "\n";
8242 uint32_t section_type = flags & MachO::SECTION_TYPE;
8243 if (verbose) {
8244 outs() << " type";
8245 if (section_type == MachO::S_REGULAR)
8246 outs() << " S_REGULAR\n";
8247 else if (section_type == MachO::S_ZEROFILL)
8248 outs() << " S_ZEROFILL\n";
8249 else if (section_type == MachO::S_CSTRING_LITERALS)
8250 outs() << " S_CSTRING_LITERALS\n";
8251 else if (section_type == MachO::S_4BYTE_LITERALS)
8252 outs() << " S_4BYTE_LITERALS\n";
8253 else if (section_type == MachO::S_8BYTE_LITERALS)
8254 outs() << " S_8BYTE_LITERALS\n";
8255 else if (section_type == MachO::S_16BYTE_LITERALS)
8256 outs() << " S_16BYTE_LITERALS\n";
8257 else if (section_type == MachO::S_LITERAL_POINTERS)
8258 outs() << " S_LITERAL_POINTERS\n";
8259 else if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS)
8260 outs() << " S_NON_LAZY_SYMBOL_POINTERS\n";
8261 else if (section_type == MachO::S_LAZY_SYMBOL_POINTERS)
8262 outs() << " S_LAZY_SYMBOL_POINTERS\n";
8263 else if (section_type == MachO::S_SYMBOL_STUBS)
8264 outs() << " S_SYMBOL_STUBS\n";
8265 else if (section_type == MachO::S_MOD_INIT_FUNC_POINTERS)
8266 outs() << " S_MOD_INIT_FUNC_POINTERS\n";
8267 else if (section_type == MachO::S_MOD_TERM_FUNC_POINTERS)
8268 outs() << " S_MOD_TERM_FUNC_POINTERS\n";
8269 else if (section_type == MachO::S_COALESCED)
8270 outs() << " S_COALESCED\n";
8271 else if (section_type == MachO::S_INTERPOSING)
8272 outs() << " S_INTERPOSING\n";
8273 else if (section_type == MachO::S_DTRACE_DOF)
8274 outs() << " S_DTRACE_DOF\n";
8275 else if (section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS)
8276 outs() << " S_LAZY_DYLIB_SYMBOL_POINTERS\n";
8277 else if (section_type == MachO::S_THREAD_LOCAL_REGULAR)
8278 outs() << " S_THREAD_LOCAL_REGULAR\n";
8279 else if (section_type == MachO::S_THREAD_LOCAL_ZEROFILL)
8280 outs() << " S_THREAD_LOCAL_ZEROFILL\n";
8281 else if (section_type == MachO::S_THREAD_LOCAL_VARIABLES)
8282 outs() << " S_THREAD_LOCAL_VARIABLES\n";
8283 else if (section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS)
8284 outs() << " S_THREAD_LOCAL_VARIABLE_POINTERS\n";
8285 else if (section_type == MachO::S_THREAD_LOCAL_INIT_FUNCTION_POINTERS)
8286 outs() << " S_THREAD_LOCAL_INIT_FUNCTION_POINTERS\n";
8287 else
8288 outs() << format("0x%08" PRIx32, section_type) << "\n";
8289 outs() << "attributes";
8290 uint32_t section_attributes = flags & MachO::SECTION_ATTRIBUTES;
8291 if (section_attributes & MachO::S_ATTR_PURE_INSTRUCTIONS)
8292 outs() << " PURE_INSTRUCTIONS";
8293 if (section_attributes & MachO::S_ATTR_NO_TOC)
8294 outs() << " NO_TOC";
8295 if (section_attributes & MachO::S_ATTR_STRIP_STATIC_SYMS)
8296 outs() << " STRIP_STATIC_SYMS";
8297 if (section_attributes & MachO::S_ATTR_NO_DEAD_STRIP)
8298 outs() << " NO_DEAD_STRIP";
8299 if (section_attributes & MachO::S_ATTR_LIVE_SUPPORT)
8300 outs() << " LIVE_SUPPORT";
8301 if (section_attributes & MachO::S_ATTR_SELF_MODIFYING_CODE)
8302 outs() << " SELF_MODIFYING_CODE";
8303 if (section_attributes & MachO::S_ATTR_DEBUG)
8304 outs() << " DEBUG";
8305 if (section_attributes & MachO::S_ATTR_SOME_INSTRUCTIONS)
8306 outs() << " SOME_INSTRUCTIONS";
8307 if (section_attributes & MachO::S_ATTR_EXT_RELOC)
8308 outs() << " EXT_RELOC";
8309 if (section_attributes & MachO::S_ATTR_LOC_RELOC)
8310 outs() << " LOC_RELOC";
8311 if (section_attributes == 0)
8312 outs() << " (none)";
8313 outs() << "\n";
8314 } else
8315 outs() << " flags " << format("0x%08" PRIx32, flags) << "\n";
8316 outs() << " reserved1 " << reserved1;
8317 if (section_type == MachO::S_SYMBOL_STUBS ||
8318 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
8319 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
8320 section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
8321 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS)
8322 outs() << " (index into indirect symbol table)\n";
8323 else
8324 outs() << "\n";
8325 outs() << " reserved2 " << reserved2;
8326 if (section_type == MachO::S_SYMBOL_STUBS)
8327 outs() << " (size of stubs)\n";
8328 else
8329 outs() << "\n";
8330}
8331
David Majnemer73cc6ff2014-11-13 19:48:56 +00008332static void PrintSymtabLoadCommand(MachO::symtab_command st, bool Is64Bit,
Kevin Enderby956366c2014-08-29 22:30:52 +00008333 uint32_t object_size) {
8334 outs() << " cmd LC_SYMTAB\n";
8335 outs() << " cmdsize " << st.cmdsize;
8336 if (st.cmdsize != sizeof(struct MachO::symtab_command))
8337 outs() << " Incorrect size\n";
8338 else
8339 outs() << "\n";
8340 outs() << " symoff " << st.symoff;
8341 if (st.symoff > object_size)
8342 outs() << " (past end of file)\n";
8343 else
8344 outs() << "\n";
8345 outs() << " nsyms " << st.nsyms;
8346 uint64_t big_size;
David Majnemer73cc6ff2014-11-13 19:48:56 +00008347 if (Is64Bit) {
Kevin Enderby956366c2014-08-29 22:30:52 +00008348 big_size = st.nsyms;
8349 big_size *= sizeof(struct MachO::nlist_64);
8350 big_size += st.symoff;
8351 if (big_size > object_size)
8352 outs() << " (past end of file)\n";
8353 else
8354 outs() << "\n";
8355 } else {
8356 big_size = st.nsyms;
8357 big_size *= sizeof(struct MachO::nlist);
8358 big_size += st.symoff;
8359 if (big_size > object_size)
8360 outs() << " (past end of file)\n";
8361 else
8362 outs() << "\n";
8363 }
8364 outs() << " stroff " << st.stroff;
8365 if (st.stroff > object_size)
8366 outs() << " (past end of file)\n";
8367 else
8368 outs() << "\n";
8369 outs() << " strsize " << st.strsize;
8370 big_size = st.stroff;
8371 big_size += st.strsize;
8372 if (big_size > object_size)
8373 outs() << " (past end of file)\n";
8374 else
8375 outs() << "\n";
8376}
8377
8378static void PrintDysymtabLoadCommand(MachO::dysymtab_command dyst,
8379 uint32_t nsyms, uint32_t object_size,
David Majnemer73cc6ff2014-11-13 19:48:56 +00008380 bool Is64Bit) {
Kevin Enderby956366c2014-08-29 22:30:52 +00008381 outs() << " cmd LC_DYSYMTAB\n";
8382 outs() << " cmdsize " << dyst.cmdsize;
8383 if (dyst.cmdsize != sizeof(struct MachO::dysymtab_command))
8384 outs() << " Incorrect size\n";
8385 else
8386 outs() << "\n";
8387 outs() << " ilocalsym " << dyst.ilocalsym;
8388 if (dyst.ilocalsym > nsyms)
8389 outs() << " (greater than the number of symbols)\n";
8390 else
8391 outs() << "\n";
8392 outs() << " nlocalsym " << dyst.nlocalsym;
8393 uint64_t big_size;
8394 big_size = dyst.ilocalsym;
8395 big_size += dyst.nlocalsym;
8396 if (big_size > nsyms)
8397 outs() << " (past the end of the symbol table)\n";
8398 else
8399 outs() << "\n";
8400 outs() << " iextdefsym " << dyst.iextdefsym;
8401 if (dyst.iextdefsym > nsyms)
8402 outs() << " (greater than the number of symbols)\n";
8403 else
8404 outs() << "\n";
8405 outs() << " nextdefsym " << dyst.nextdefsym;
8406 big_size = dyst.iextdefsym;
8407 big_size += dyst.nextdefsym;
8408 if (big_size > nsyms)
8409 outs() << " (past the end of the symbol table)\n";
8410 else
8411 outs() << "\n";
8412 outs() << " iundefsym " << dyst.iundefsym;
8413 if (dyst.iundefsym > nsyms)
8414 outs() << " (greater than the number of symbols)\n";
8415 else
8416 outs() << "\n";
8417 outs() << " nundefsym " << dyst.nundefsym;
8418 big_size = dyst.iundefsym;
8419 big_size += dyst.nundefsym;
8420 if (big_size > nsyms)
8421 outs() << " (past the end of the symbol table)\n";
8422 else
8423 outs() << "\n";
8424 outs() << " tocoff " << dyst.tocoff;
8425 if (dyst.tocoff > object_size)
8426 outs() << " (past end of file)\n";
8427 else
8428 outs() << "\n";
8429 outs() << " ntoc " << dyst.ntoc;
8430 big_size = dyst.ntoc;
8431 big_size *= sizeof(struct MachO::dylib_table_of_contents);
8432 big_size += dyst.tocoff;
8433 if (big_size > object_size)
8434 outs() << " (past end of file)\n";
8435 else
8436 outs() << "\n";
8437 outs() << " modtaboff " << dyst.modtaboff;
8438 if (dyst.modtaboff > object_size)
8439 outs() << " (past end of file)\n";
8440 else
8441 outs() << "\n";
8442 outs() << " nmodtab " << dyst.nmodtab;
8443 uint64_t modtabend;
David Majnemer73cc6ff2014-11-13 19:48:56 +00008444 if (Is64Bit) {
Kevin Enderby956366c2014-08-29 22:30:52 +00008445 modtabend = dyst.nmodtab;
8446 modtabend *= sizeof(struct MachO::dylib_module_64);
8447 modtabend += dyst.modtaboff;
8448 } else {
8449 modtabend = dyst.nmodtab;
8450 modtabend *= sizeof(struct MachO::dylib_module);
8451 modtabend += dyst.modtaboff;
8452 }
8453 if (modtabend > object_size)
8454 outs() << " (past end of file)\n";
8455 else
8456 outs() << "\n";
8457 outs() << " extrefsymoff " << dyst.extrefsymoff;
8458 if (dyst.extrefsymoff > object_size)
8459 outs() << " (past end of file)\n";
8460 else
8461 outs() << "\n";
8462 outs() << " nextrefsyms " << dyst.nextrefsyms;
8463 big_size = dyst.nextrefsyms;
8464 big_size *= sizeof(struct MachO::dylib_reference);
8465 big_size += dyst.extrefsymoff;
8466 if (big_size > object_size)
8467 outs() << " (past end of file)\n";
8468 else
8469 outs() << "\n";
8470 outs() << " indirectsymoff " << dyst.indirectsymoff;
8471 if (dyst.indirectsymoff > object_size)
8472 outs() << " (past end of file)\n";
8473 else
8474 outs() << "\n";
8475 outs() << " nindirectsyms " << dyst.nindirectsyms;
8476 big_size = dyst.nindirectsyms;
8477 big_size *= sizeof(uint32_t);
8478 big_size += dyst.indirectsymoff;
8479 if (big_size > object_size)
8480 outs() << " (past end of file)\n";
8481 else
8482 outs() << "\n";
8483 outs() << " extreloff " << dyst.extreloff;
8484 if (dyst.extreloff > object_size)
8485 outs() << " (past end of file)\n";
8486 else
8487 outs() << "\n";
8488 outs() << " nextrel " << dyst.nextrel;
8489 big_size = dyst.nextrel;
8490 big_size *= sizeof(struct MachO::relocation_info);
8491 big_size += dyst.extreloff;
8492 if (big_size > object_size)
8493 outs() << " (past end of file)\n";
8494 else
8495 outs() << "\n";
8496 outs() << " locreloff " << dyst.locreloff;
8497 if (dyst.locreloff > object_size)
8498 outs() << " (past end of file)\n";
8499 else
8500 outs() << "\n";
8501 outs() << " nlocrel " << dyst.nlocrel;
8502 big_size = dyst.nlocrel;
8503 big_size *= sizeof(struct MachO::relocation_info);
8504 big_size += dyst.locreloff;
8505 if (big_size > object_size)
8506 outs() << " (past end of file)\n";
8507 else
8508 outs() << "\n";
8509}
8510
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008511static void PrintDyldInfoLoadCommand(MachO::dyld_info_command dc,
8512 uint32_t object_size) {
8513 if (dc.cmd == MachO::LC_DYLD_INFO)
8514 outs() << " cmd LC_DYLD_INFO\n";
8515 else
8516 outs() << " cmd LC_DYLD_INFO_ONLY\n";
8517 outs() << " cmdsize " << dc.cmdsize;
8518 if (dc.cmdsize != sizeof(struct MachO::dyld_info_command))
8519 outs() << " Incorrect size\n";
8520 else
8521 outs() << "\n";
8522 outs() << " rebase_off " << dc.rebase_off;
8523 if (dc.rebase_off > object_size)
8524 outs() << " (past end of file)\n";
8525 else
8526 outs() << "\n";
8527 outs() << " rebase_size " << dc.rebase_size;
8528 uint64_t big_size;
8529 big_size = dc.rebase_off;
8530 big_size += dc.rebase_size;
8531 if (big_size > object_size)
8532 outs() << " (past end of file)\n";
8533 else
8534 outs() << "\n";
8535 outs() << " bind_off " << dc.bind_off;
8536 if (dc.bind_off > object_size)
8537 outs() << " (past end of file)\n";
8538 else
8539 outs() << "\n";
8540 outs() << " bind_size " << dc.bind_size;
8541 big_size = dc.bind_off;
8542 big_size += dc.bind_size;
8543 if (big_size > object_size)
8544 outs() << " (past end of file)\n";
8545 else
8546 outs() << "\n";
8547 outs() << " weak_bind_off " << dc.weak_bind_off;
8548 if (dc.weak_bind_off > object_size)
8549 outs() << " (past end of file)\n";
8550 else
8551 outs() << "\n";
8552 outs() << " weak_bind_size " << dc.weak_bind_size;
8553 big_size = dc.weak_bind_off;
8554 big_size += dc.weak_bind_size;
8555 if (big_size > object_size)
8556 outs() << " (past end of file)\n";
8557 else
8558 outs() << "\n";
8559 outs() << " lazy_bind_off " << dc.lazy_bind_off;
8560 if (dc.lazy_bind_off > object_size)
8561 outs() << " (past end of file)\n";
8562 else
8563 outs() << "\n";
8564 outs() << " lazy_bind_size " << dc.lazy_bind_size;
8565 big_size = dc.lazy_bind_off;
8566 big_size += dc.lazy_bind_size;
8567 if (big_size > object_size)
8568 outs() << " (past end of file)\n";
8569 else
8570 outs() << "\n";
8571 outs() << " export_off " << dc.export_off;
8572 if (dc.export_off > object_size)
8573 outs() << " (past end of file)\n";
8574 else
8575 outs() << "\n";
8576 outs() << " export_size " << dc.export_size;
8577 big_size = dc.export_off;
8578 big_size += dc.export_size;
8579 if (big_size > object_size)
8580 outs() << " (past end of file)\n";
8581 else
8582 outs() << "\n";
8583}
8584
8585static void PrintDyldLoadCommand(MachO::dylinker_command dyld,
8586 const char *Ptr) {
8587 if (dyld.cmd == MachO::LC_ID_DYLINKER)
8588 outs() << " cmd LC_ID_DYLINKER\n";
8589 else if (dyld.cmd == MachO::LC_LOAD_DYLINKER)
8590 outs() << " cmd LC_LOAD_DYLINKER\n";
8591 else if (dyld.cmd == MachO::LC_DYLD_ENVIRONMENT)
8592 outs() << " cmd LC_DYLD_ENVIRONMENT\n";
8593 else
8594 outs() << " cmd ?(" << dyld.cmd << ")\n";
8595 outs() << " cmdsize " << dyld.cmdsize;
8596 if (dyld.cmdsize < sizeof(struct MachO::dylinker_command))
8597 outs() << " Incorrect size\n";
8598 else
8599 outs() << "\n";
8600 if (dyld.name >= dyld.cmdsize)
8601 outs() << " name ?(bad offset " << dyld.name << ")\n";
8602 else {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00008603 const char *P = (const char *)(Ptr) + dyld.name;
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008604 outs() << " name " << P << " (offset " << dyld.name << ")\n";
8605 }
8606}
8607
8608static void PrintUuidLoadCommand(MachO::uuid_command uuid) {
8609 outs() << " cmd LC_UUID\n";
8610 outs() << " cmdsize " << uuid.cmdsize;
8611 if (uuid.cmdsize != sizeof(struct MachO::uuid_command))
8612 outs() << " Incorrect size\n";
8613 else
8614 outs() << "\n";
8615 outs() << " uuid ";
Davide Italianoc74277a2015-12-07 00:03:28 +00008616 for (int i = 0; i < 16; ++i) {
8617 outs() << format("%02" PRIX32, uuid.uuid[i]);
8618 if (i == 3 || i == 5 || i == 7 || i == 9)
8619 outs() << "-";
8620 }
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008621 outs() << "\n";
8622}
8623
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008624static void PrintRpathLoadCommand(MachO::rpath_command rpath, const char *Ptr) {
Jean-Daniel Dupas00cc1f52014-12-04 07:37:02 +00008625 outs() << " cmd LC_RPATH\n";
8626 outs() << " cmdsize " << rpath.cmdsize;
8627 if (rpath.cmdsize < sizeof(struct MachO::rpath_command))
8628 outs() << " Incorrect size\n";
8629 else
8630 outs() << "\n";
8631 if (rpath.path >= rpath.cmdsize)
8632 outs() << " path ?(bad offset " << rpath.path << ")\n";
8633 else {
8634 const char *P = (const char *)(Ptr) + rpath.path;
8635 outs() << " path " << P << " (offset " << rpath.path << ")\n";
8636 }
8637}
8638
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008639static void PrintVersionMinLoadCommand(MachO::version_min_command vd) {
Tim Northoverbfbfb122015-11-02 21:26:58 +00008640 StringRef LoadCmdName;
8641 switch (vd.cmd) {
8642 case MachO::LC_VERSION_MIN_MACOSX:
8643 LoadCmdName = "LC_VERSION_MIN_MACOSX";
8644 break;
8645 case MachO::LC_VERSION_MIN_IPHONEOS:
8646 LoadCmdName = "LC_VERSION_MIN_IPHONEOS";
8647 break;
8648 case MachO::LC_VERSION_MIN_TVOS:
8649 LoadCmdName = "LC_VERSION_MIN_TVOS";
8650 break;
8651 case MachO::LC_VERSION_MIN_WATCHOS:
8652 LoadCmdName = "LC_VERSION_MIN_WATCHOS";
8653 break;
8654 default:
8655 llvm_unreachable("Unknown version min load command");
8656 }
8657
8658 outs() << " cmd " << LoadCmdName << '\n';
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008659 outs() << " cmdsize " << vd.cmdsize;
8660 if (vd.cmdsize != sizeof(struct MachO::version_min_command))
8661 outs() << " Incorrect size\n";
8662 else
8663 outs() << "\n";
Davide Italiano56baef32015-08-26 12:26:11 +00008664 outs() << " version "
8665 << MachOObjectFile::getVersionMinMajor(vd, false) << "."
8666 << MachOObjectFile::getVersionMinMinor(vd, false);
8667 uint32_t Update = MachOObjectFile::getVersionMinUpdate(vd, false);
8668 if (Update != 0)
8669 outs() << "." << Update;
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008670 outs() << "\n";
8671 if (vd.sdk == 0)
Kevin Enderby57538292014-12-17 01:01:30 +00008672 outs() << " sdk n/a";
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008673 else {
Davide Italiano56baef32015-08-26 12:26:11 +00008674 outs() << " sdk "
8675 << MachOObjectFile::getVersionMinMajor(vd, true) << "."
8676 << MachOObjectFile::getVersionMinMinor(vd, true);
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008677 }
Davide Italiano56baef32015-08-26 12:26:11 +00008678 Update = MachOObjectFile::getVersionMinUpdate(vd, true);
8679 if (Update != 0)
8680 outs() << "." << Update;
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008681 outs() << "\n";
8682}
8683
Kevin Enderbya4579c42017-01-19 17:36:31 +00008684static void PrintNoteLoadCommand(MachO::note_command Nt) {
8685 outs() << " cmd LC_NOTE\n";
8686 outs() << " cmdsize " << Nt.cmdsize;
8687 if (Nt.cmdsize != sizeof(struct MachO::note_command))
8688 outs() << " Incorrect size\n";
8689 else
8690 outs() << "\n";
8691 const char *d = Nt.data_owner;
8692 outs() << "data_owner " << format("%.16s\n", d);
8693 outs() << " offset " << Nt.offset << "\n";
8694 outs() << " size " << Nt.size << "\n";
8695}
8696
Steven Wu5b54a422017-01-23 20:07:55 +00008697static void PrintBuildToolVersion(MachO::build_tool_version bv) {
8698 outs() << " tool " << MachOObjectFile::getBuildTool(bv.tool) << "\n";
8699 outs() << " version " << MachOObjectFile::getVersionString(bv.version)
8700 << "\n";
8701}
8702
8703static void PrintBuildVersionLoadCommand(const MachOObjectFile *obj,
8704 MachO::build_version_command bd) {
8705 outs() << " cmd LC_BUILD_VERSION\n";
8706 outs() << " cmdsize " << bd.cmdsize;
8707 if (bd.cmdsize !=
8708 sizeof(struct MachO::build_version_command) +
8709 bd.ntools * sizeof(struct MachO::build_tool_version))
8710 outs() << " Incorrect size\n";
8711 else
8712 outs() << "\n";
8713 outs() << " platform " << MachOObjectFile::getBuildPlatform(bd.platform)
8714 << "\n";
8715 if (bd.sdk)
8716 outs() << " sdk " << MachOObjectFile::getVersionString(bd.sdk)
8717 << "\n";
8718 else
8719 outs() << " sdk n/a\n";
8720 outs() << " minos " << MachOObjectFile::getVersionString(bd.minos)
8721 << "\n";
8722 outs() << " ntools " << bd.ntools << "\n";
8723 for (unsigned i = 0; i < bd.ntools; ++i) {
8724 MachO::build_tool_version bv = obj->getBuildToolVersion(i);
8725 PrintBuildToolVersion(bv);
8726 }
8727}
8728
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008729static void PrintSourceVersionCommand(MachO::source_version_command sd) {
8730 outs() << " cmd LC_SOURCE_VERSION\n";
8731 outs() << " cmdsize " << sd.cmdsize;
8732 if (sd.cmdsize != sizeof(struct MachO::source_version_command))
8733 outs() << " Incorrect size\n";
8734 else
8735 outs() << "\n";
8736 uint64_t a = (sd.version >> 40) & 0xffffff;
8737 uint64_t b = (sd.version >> 30) & 0x3ff;
8738 uint64_t c = (sd.version >> 20) & 0x3ff;
8739 uint64_t d = (sd.version >> 10) & 0x3ff;
8740 uint64_t e = sd.version & 0x3ff;
8741 outs() << " version " << a << "." << b;
8742 if (e != 0)
8743 outs() << "." << c << "." << d << "." << e;
8744 else if (d != 0)
8745 outs() << "." << c << "." << d;
8746 else if (c != 0)
8747 outs() << "." << c;
8748 outs() << "\n";
8749}
8750
8751static void PrintEntryPointCommand(MachO::entry_point_command ep) {
8752 outs() << " cmd LC_MAIN\n";
8753 outs() << " cmdsize " << ep.cmdsize;
8754 if (ep.cmdsize != sizeof(struct MachO::entry_point_command))
8755 outs() << " Incorrect size\n";
8756 else
8757 outs() << "\n";
8758 outs() << " entryoff " << ep.entryoff << "\n";
8759 outs() << " stacksize " << ep.stacksize << "\n";
8760}
8761
Kevin Enderby0804f4672014-12-16 23:25:52 +00008762static void PrintEncryptionInfoCommand(MachO::encryption_info_command ec,
8763 uint32_t object_size) {
8764 outs() << " cmd LC_ENCRYPTION_INFO\n";
8765 outs() << " cmdsize " << ec.cmdsize;
8766 if (ec.cmdsize != sizeof(struct MachO::encryption_info_command))
8767 outs() << " Incorrect size\n";
8768 else
8769 outs() << "\n";
8770 outs() << " cryptoff " << ec.cryptoff;
8771 if (ec.cryptoff > object_size)
8772 outs() << " (past end of file)\n";
8773 else
8774 outs() << "\n";
8775 outs() << " cryptsize " << ec.cryptsize;
8776 if (ec.cryptsize > object_size)
8777 outs() << " (past end of file)\n";
8778 else
8779 outs() << "\n";
8780 outs() << " cryptid " << ec.cryptid << "\n";
8781}
8782
Kevin Enderby57538292014-12-17 01:01:30 +00008783static void PrintEncryptionInfoCommand64(MachO::encryption_info_command_64 ec,
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008784 uint32_t object_size) {
Kevin Enderby57538292014-12-17 01:01:30 +00008785 outs() << " cmd LC_ENCRYPTION_INFO_64\n";
8786 outs() << " cmdsize " << ec.cmdsize;
8787 if (ec.cmdsize != sizeof(struct MachO::encryption_info_command_64))
8788 outs() << " Incorrect size\n";
8789 else
8790 outs() << "\n";
8791 outs() << " cryptoff " << ec.cryptoff;
8792 if (ec.cryptoff > object_size)
8793 outs() << " (past end of file)\n";
8794 else
8795 outs() << "\n";
8796 outs() << " cryptsize " << ec.cryptsize;
8797 if (ec.cryptsize > object_size)
8798 outs() << " (past end of file)\n";
8799 else
8800 outs() << "\n";
8801 outs() << " cryptid " << ec.cryptid << "\n";
8802 outs() << " pad " << ec.pad << "\n";
8803}
8804
Kevin Enderbyd0b6b7f2014-12-18 00:53:40 +00008805static void PrintLinkerOptionCommand(MachO::linker_option_command lo,
8806 const char *Ptr) {
8807 outs() << " cmd LC_LINKER_OPTION\n";
8808 outs() << " cmdsize " << lo.cmdsize;
8809 if (lo.cmdsize < sizeof(struct MachO::linker_option_command))
8810 outs() << " Incorrect size\n";
8811 else
8812 outs() << "\n";
8813 outs() << " count " << lo.count << "\n";
8814 const char *string = Ptr + sizeof(struct MachO::linker_option_command);
8815 uint32_t left = lo.cmdsize - sizeof(struct MachO::linker_option_command);
8816 uint32_t i = 0;
8817 while (left > 0) {
8818 while (*string == '\0' && left > 0) {
8819 string++;
8820 left--;
8821 }
8822 if (left > 0) {
8823 i++;
8824 outs() << " string #" << i << " " << format("%.*s\n", left, string);
David Majnemerd4449ed2014-12-20 08:24:43 +00008825 uint32_t NullPos = StringRef(string, left).find('\0');
8826 uint32_t len = std::min(NullPos, left) + 1;
Kevin Enderbyd0b6b7f2014-12-18 00:53:40 +00008827 string += len;
8828 left -= len;
8829 }
8830 }
8831 if (lo.count != i)
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008832 outs() << " count " << lo.count << " does not match number of strings "
8833 << i << "\n";
Kevin Enderbyd0b6b7f2014-12-18 00:53:40 +00008834}
8835
Kevin Enderbyb4b79312014-12-18 19:24:35 +00008836static void PrintSubFrameworkCommand(MachO::sub_framework_command sub,
8837 const char *Ptr) {
8838 outs() << " cmd LC_SUB_FRAMEWORK\n";
8839 outs() << " cmdsize " << sub.cmdsize;
8840 if (sub.cmdsize < sizeof(struct MachO::sub_framework_command))
8841 outs() << " Incorrect size\n";
8842 else
8843 outs() << "\n";
8844 if (sub.umbrella < sub.cmdsize) {
8845 const char *P = Ptr + sub.umbrella;
8846 outs() << " umbrella " << P << " (offset " << sub.umbrella << ")\n";
8847 } else {
8848 outs() << " umbrella ?(bad offset " << sub.umbrella << ")\n";
8849 }
8850}
8851
Kevin Enderbya2bd8d92014-12-18 23:13:26 +00008852static void PrintSubUmbrellaCommand(MachO::sub_umbrella_command sub,
8853 const char *Ptr) {
8854 outs() << " cmd LC_SUB_UMBRELLA\n";
8855 outs() << " cmdsize " << sub.cmdsize;
8856 if (sub.cmdsize < sizeof(struct MachO::sub_umbrella_command))
8857 outs() << " Incorrect size\n";
8858 else
8859 outs() << "\n";
8860 if (sub.sub_umbrella < sub.cmdsize) {
8861 const char *P = Ptr + sub.sub_umbrella;
8862 outs() << " sub_umbrella " << P << " (offset " << sub.sub_umbrella << ")\n";
8863 } else {
8864 outs() << " sub_umbrella ?(bad offset " << sub.sub_umbrella << ")\n";
8865 }
8866}
8867
Kevin Enderby36c8d3a2014-12-19 19:48:16 +00008868static void PrintSubLibraryCommand(MachO::sub_library_command sub,
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008869 const char *Ptr) {
Kevin Enderby36c8d3a2014-12-19 19:48:16 +00008870 outs() << " cmd LC_SUB_LIBRARY\n";
8871 outs() << " cmdsize " << sub.cmdsize;
8872 if (sub.cmdsize < sizeof(struct MachO::sub_library_command))
8873 outs() << " Incorrect size\n";
8874 else
8875 outs() << "\n";
8876 if (sub.sub_library < sub.cmdsize) {
8877 const char *P = Ptr + sub.sub_library;
8878 outs() << " sub_library " << P << " (offset " << sub.sub_library << ")\n";
8879 } else {
8880 outs() << " sub_library ?(bad offset " << sub.sub_library << ")\n";
8881 }
8882}
8883
Kevin Enderby186eac32014-12-19 21:06:24 +00008884static void PrintSubClientCommand(MachO::sub_client_command sub,
8885 const char *Ptr) {
8886 outs() << " cmd LC_SUB_CLIENT\n";
8887 outs() << " cmdsize " << sub.cmdsize;
8888 if (sub.cmdsize < sizeof(struct MachO::sub_client_command))
8889 outs() << " Incorrect size\n";
8890 else
8891 outs() << "\n";
8892 if (sub.client < sub.cmdsize) {
8893 const char *P = Ptr + sub.client;
8894 outs() << " client " << P << " (offset " << sub.client << ")\n";
8895 } else {
8896 outs() << " client ?(bad offset " << sub.client << ")\n";
8897 }
8898}
Kevin Enderby36c8d3a2014-12-19 19:48:16 +00008899
Kevin Enderby52e4ce42014-12-19 22:25:22 +00008900static void PrintRoutinesCommand(MachO::routines_command r) {
8901 outs() << " cmd LC_ROUTINES\n";
8902 outs() << " cmdsize " << r.cmdsize;
8903 if (r.cmdsize != sizeof(struct MachO::routines_command))
8904 outs() << " Incorrect size\n";
8905 else
8906 outs() << "\n";
8907 outs() << " init_address " << format("0x%08" PRIx32, r.init_address) << "\n";
8908 outs() << " init_module " << r.init_module << "\n";
8909 outs() << " reserved1 " << r.reserved1 << "\n";
8910 outs() << " reserved2 " << r.reserved2 << "\n";
8911 outs() << " reserved3 " << r.reserved3 << "\n";
8912 outs() << " reserved4 " << r.reserved4 << "\n";
8913 outs() << " reserved5 " << r.reserved5 << "\n";
8914 outs() << " reserved6 " << r.reserved6 << "\n";
8915}
8916
8917static void PrintRoutinesCommand64(MachO::routines_command_64 r) {
8918 outs() << " cmd LC_ROUTINES_64\n";
8919 outs() << " cmdsize " << r.cmdsize;
8920 if (r.cmdsize != sizeof(struct MachO::routines_command_64))
8921 outs() << " Incorrect size\n";
8922 else
8923 outs() << "\n";
8924 outs() << " init_address " << format("0x%016" PRIx64, r.init_address) << "\n";
8925 outs() << " init_module " << r.init_module << "\n";
8926 outs() << " reserved1 " << r.reserved1 << "\n";
8927 outs() << " reserved2 " << r.reserved2 << "\n";
8928 outs() << " reserved3 " << r.reserved3 << "\n";
8929 outs() << " reserved4 " << r.reserved4 << "\n";
8930 outs() << " reserved5 " << r.reserved5 << "\n";
8931 outs() << " reserved6 " << r.reserved6 << "\n";
8932}
8933
Kevin Enderbyc3a035d2017-01-23 21:13:29 +00008934static void Print_x86_thread_state32_t(MachO::x86_thread_state32_t &cpu32) {
8935 outs() << "\t eax " << format("0x%08" PRIx32, cpu32.eax);
8936 outs() << " ebx " << format("0x%08" PRIx32, cpu32.ebx);
8937 outs() << " ecx " << format("0x%08" PRIx32, cpu32.ecx);
8938 outs() << " edx " << format("0x%08" PRIx32, cpu32.edx) << "\n";
8939 outs() << "\t edi " << format("0x%08" PRIx32, cpu32.edi);
8940 outs() << " esi " << format("0x%08" PRIx32, cpu32.esi);
8941 outs() << " ebp " << format("0x%08" PRIx32, cpu32.ebp);
8942 outs() << " esp " << format("0x%08" PRIx32, cpu32.esp) << "\n";
8943 outs() << "\t ss " << format("0x%08" PRIx32, cpu32.ss);
8944 outs() << " eflags " << format("0x%08" PRIx32, cpu32.eflags);
8945 outs() << " eip " << format("0x%08" PRIx32, cpu32.eip);
8946 outs() << " cs " << format("0x%08" PRIx32, cpu32.cs) << "\n";
8947 outs() << "\t ds " << format("0x%08" PRIx32, cpu32.ds);
8948 outs() << " es " << format("0x%08" PRIx32, cpu32.es);
8949 outs() << " fs " << format("0x%08" PRIx32, cpu32.fs);
8950 outs() << " gs " << format("0x%08" PRIx32, cpu32.gs) << "\n";
8951}
8952
Kevin Enderby48ef5342014-12-23 22:56:39 +00008953static void Print_x86_thread_state64_t(MachO::x86_thread_state64_t &cpu64) {
8954 outs() << " rax " << format("0x%016" PRIx64, cpu64.rax);
8955 outs() << " rbx " << format("0x%016" PRIx64, cpu64.rbx);
8956 outs() << " rcx " << format("0x%016" PRIx64, cpu64.rcx) << "\n";
8957 outs() << " rdx " << format("0x%016" PRIx64, cpu64.rdx);
8958 outs() << " rdi " << format("0x%016" PRIx64, cpu64.rdi);
8959 outs() << " rsi " << format("0x%016" PRIx64, cpu64.rsi) << "\n";
8960 outs() << " rbp " << format("0x%016" PRIx64, cpu64.rbp);
8961 outs() << " rsp " << format("0x%016" PRIx64, cpu64.rsp);
8962 outs() << " r8 " << format("0x%016" PRIx64, cpu64.r8) << "\n";
8963 outs() << " r9 " << format("0x%016" PRIx64, cpu64.r9);
8964 outs() << " r10 " << format("0x%016" PRIx64, cpu64.r10);
8965 outs() << " r11 " << format("0x%016" PRIx64, cpu64.r11) << "\n";
8966 outs() << " r12 " << format("0x%016" PRIx64, cpu64.r12);
8967 outs() << " r13 " << format("0x%016" PRIx64, cpu64.r13);
8968 outs() << " r14 " << format("0x%016" PRIx64, cpu64.r14) << "\n";
8969 outs() << " r15 " << format("0x%016" PRIx64, cpu64.r15);
8970 outs() << " rip " << format("0x%016" PRIx64, cpu64.rip) << "\n";
8971 outs() << "rflags " << format("0x%016" PRIx64, cpu64.rflags);
8972 outs() << " cs " << format("0x%016" PRIx64, cpu64.cs);
8973 outs() << " fs " << format("0x%016" PRIx64, cpu64.fs) << "\n";
8974 outs() << " gs " << format("0x%016" PRIx64, cpu64.gs) << "\n";
8975}
8976
Kevin Enderby227df342014-12-23 23:43:59 +00008977static void Print_mmst_reg(MachO::mmst_reg_t &r) {
Kevin Enderby48ef5342014-12-23 22:56:39 +00008978 uint32_t f;
8979 outs() << "\t mmst_reg ";
8980 for (f = 0; f < 10; f++)
8981 outs() << format("%02" PRIx32, (r.mmst_reg[f] & 0xff)) << " ";
8982 outs() << "\n";
8983 outs() << "\t mmst_rsrv ";
8984 for (f = 0; f < 6; f++)
8985 outs() << format("%02" PRIx32, (r.mmst_rsrv[f] & 0xff)) << " ";
8986 outs() << "\n";
8987}
8988
Kevin Enderbyaefb0032014-12-24 00:16:51 +00008989static void Print_xmm_reg(MachO::xmm_reg_t &r) {
Kevin Enderby48ef5342014-12-23 22:56:39 +00008990 uint32_t f;
8991 outs() << "\t xmm_reg ";
8992 for (f = 0; f < 16; f++)
8993 outs() << format("%02" PRIx32, (r.xmm_reg[f] & 0xff)) << " ";
8994 outs() << "\n";
8995}
8996
8997static void Print_x86_float_state_t(MachO::x86_float_state64_t &fpu) {
8998 outs() << "\t fpu_reserved[0] " << fpu.fpu_reserved[0];
8999 outs() << " fpu_reserved[1] " << fpu.fpu_reserved[1] << "\n";
9000 outs() << "\t control: invalid " << fpu.fpu_fcw.invalid;
9001 outs() << " denorm " << fpu.fpu_fcw.denorm;
9002 outs() << " zdiv " << fpu.fpu_fcw.zdiv;
9003 outs() << " ovrfl " << fpu.fpu_fcw.ovrfl;
9004 outs() << " undfl " << fpu.fpu_fcw.undfl;
9005 outs() << " precis " << fpu.fpu_fcw.precis << "\n";
9006 outs() << "\t\t pc ";
9007 if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_24B)
9008 outs() << "FP_PREC_24B ";
9009 else if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_53B)
9010 outs() << "FP_PREC_53B ";
9011 else if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_64B)
9012 outs() << "FP_PREC_64B ";
9013 else
9014 outs() << fpu.fpu_fcw.pc << " ";
9015 outs() << "rc ";
9016 if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_NEAR)
9017 outs() << "FP_RND_NEAR ";
9018 else if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_DOWN)
9019 outs() << "FP_RND_DOWN ";
9020 else if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_UP)
9021 outs() << "FP_RND_UP ";
9022 else if (fpu.fpu_fcw.rc == MachO::x86_FP_CHOP)
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009023 outs() << "FP_CHOP ";
Kevin Enderby48ef5342014-12-23 22:56:39 +00009024 outs() << "\n";
9025 outs() << "\t status: invalid " << fpu.fpu_fsw.invalid;
9026 outs() << " denorm " << fpu.fpu_fsw.denorm;
9027 outs() << " zdiv " << fpu.fpu_fsw.zdiv;
9028 outs() << " ovrfl " << fpu.fpu_fsw.ovrfl;
9029 outs() << " undfl " << fpu.fpu_fsw.undfl;
9030 outs() << " precis " << fpu.fpu_fsw.precis;
9031 outs() << " stkflt " << fpu.fpu_fsw.stkflt << "\n";
9032 outs() << "\t errsumm " << fpu.fpu_fsw.errsumm;
9033 outs() << " c0 " << fpu.fpu_fsw.c0;
9034 outs() << " c1 " << fpu.fpu_fsw.c1;
9035 outs() << " c2 " << fpu.fpu_fsw.c2;
9036 outs() << " tos " << fpu.fpu_fsw.tos;
9037 outs() << " c3 " << fpu.fpu_fsw.c3;
9038 outs() << " busy " << fpu.fpu_fsw.busy << "\n";
9039 outs() << "\t fpu_ftw " << format("0x%02" PRIx32, fpu.fpu_ftw);
9040 outs() << " fpu_rsrv1 " << format("0x%02" PRIx32, fpu.fpu_rsrv1);
9041 outs() << " fpu_fop " << format("0x%04" PRIx32, fpu.fpu_fop);
9042 outs() << " fpu_ip " << format("0x%08" PRIx32, fpu.fpu_ip) << "\n";
9043 outs() << "\t fpu_cs " << format("0x%04" PRIx32, fpu.fpu_cs);
9044 outs() << " fpu_rsrv2 " << format("0x%04" PRIx32, fpu.fpu_rsrv2);
9045 outs() << " fpu_dp " << format("0x%08" PRIx32, fpu.fpu_dp);
9046 outs() << " fpu_ds " << format("0x%04" PRIx32, fpu.fpu_ds) << "\n";
9047 outs() << "\t fpu_rsrv3 " << format("0x%04" PRIx32, fpu.fpu_rsrv3);
9048 outs() << " fpu_mxcsr " << format("0x%08" PRIx32, fpu.fpu_mxcsr);
9049 outs() << " fpu_mxcsrmask " << format("0x%08" PRIx32, fpu.fpu_mxcsrmask);
9050 outs() << "\n";
9051 outs() << "\t fpu_stmm0:\n";
9052 Print_mmst_reg(fpu.fpu_stmm0);
9053 outs() << "\t fpu_stmm1:\n";
9054 Print_mmst_reg(fpu.fpu_stmm1);
9055 outs() << "\t fpu_stmm2:\n";
9056 Print_mmst_reg(fpu.fpu_stmm2);
9057 outs() << "\t fpu_stmm3:\n";
9058 Print_mmst_reg(fpu.fpu_stmm3);
9059 outs() << "\t fpu_stmm4:\n";
9060 Print_mmst_reg(fpu.fpu_stmm4);
9061 outs() << "\t fpu_stmm5:\n";
9062 Print_mmst_reg(fpu.fpu_stmm5);
9063 outs() << "\t fpu_stmm6:\n";
9064 Print_mmst_reg(fpu.fpu_stmm6);
9065 outs() << "\t fpu_stmm7:\n";
9066 Print_mmst_reg(fpu.fpu_stmm7);
9067 outs() << "\t fpu_xmm0:\n";
9068 Print_xmm_reg(fpu.fpu_xmm0);
9069 outs() << "\t fpu_xmm1:\n";
9070 Print_xmm_reg(fpu.fpu_xmm1);
9071 outs() << "\t fpu_xmm2:\n";
9072 Print_xmm_reg(fpu.fpu_xmm2);
9073 outs() << "\t fpu_xmm3:\n";
9074 Print_xmm_reg(fpu.fpu_xmm3);
9075 outs() << "\t fpu_xmm4:\n";
9076 Print_xmm_reg(fpu.fpu_xmm4);
9077 outs() << "\t fpu_xmm5:\n";
9078 Print_xmm_reg(fpu.fpu_xmm5);
9079 outs() << "\t fpu_xmm6:\n";
9080 Print_xmm_reg(fpu.fpu_xmm6);
9081 outs() << "\t fpu_xmm7:\n";
9082 Print_xmm_reg(fpu.fpu_xmm7);
9083 outs() << "\t fpu_xmm8:\n";
9084 Print_xmm_reg(fpu.fpu_xmm8);
9085 outs() << "\t fpu_xmm9:\n";
9086 Print_xmm_reg(fpu.fpu_xmm9);
9087 outs() << "\t fpu_xmm10:\n";
9088 Print_xmm_reg(fpu.fpu_xmm10);
9089 outs() << "\t fpu_xmm11:\n";
9090 Print_xmm_reg(fpu.fpu_xmm11);
9091 outs() << "\t fpu_xmm12:\n";
9092 Print_xmm_reg(fpu.fpu_xmm12);
9093 outs() << "\t fpu_xmm13:\n";
9094 Print_xmm_reg(fpu.fpu_xmm13);
9095 outs() << "\t fpu_xmm14:\n";
9096 Print_xmm_reg(fpu.fpu_xmm14);
9097 outs() << "\t fpu_xmm15:\n";
9098 Print_xmm_reg(fpu.fpu_xmm15);
9099 outs() << "\t fpu_rsrv4:\n";
9100 for (uint32_t f = 0; f < 6; f++) {
9101 outs() << "\t ";
9102 for (uint32_t g = 0; g < 16; g++)
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009103 outs() << format("%02" PRIx32, fpu.fpu_rsrv4[f * g]) << " ";
Kevin Enderby48ef5342014-12-23 22:56:39 +00009104 outs() << "\n";
9105 }
9106 outs() << "\t fpu_reserved1 " << format("0x%08" PRIx32, fpu.fpu_reserved1);
9107 outs() << "\n";
9108}
9109
9110static void Print_x86_exception_state_t(MachO::x86_exception_state64_t &exc64) {
9111 outs() << "\t trapno " << format("0x%08" PRIx32, exc64.trapno);
9112 outs() << " err " << format("0x%08" PRIx32, exc64.err);
9113 outs() << " faultvaddr " << format("0x%016" PRIx64, exc64.faultvaddr) << "\n";
9114}
9115
Kevin Enderby41c9c002016-10-21 18:22:35 +00009116static void Print_arm_thread_state32_t(MachO::arm_thread_state32_t &cpu32) {
9117 outs() << "\t r0 " << format("0x%08" PRIx32, cpu32.r[0]);
9118 outs() << " r1 " << format("0x%08" PRIx32, cpu32.r[1]);
9119 outs() << " r2 " << format("0x%08" PRIx32, cpu32.r[2]);
9120 outs() << " r3 " << format("0x%08" PRIx32, cpu32.r[3]) << "\n";
9121 outs() << "\t r4 " << format("0x%08" PRIx32, cpu32.r[4]);
9122 outs() << " r5 " << format("0x%08" PRIx32, cpu32.r[5]);
9123 outs() << " r6 " << format("0x%08" PRIx32, cpu32.r[6]);
9124 outs() << " r7 " << format("0x%08" PRIx32, cpu32.r[7]) << "\n";
9125 outs() << "\t r8 " << format("0x%08" PRIx32, cpu32.r[8]);
9126 outs() << " r9 " << format("0x%08" PRIx32, cpu32.r[9]);
9127 outs() << " r10 " << format("0x%08" PRIx32, cpu32.r[10]);
9128 outs() << " r11 " << format("0x%08" PRIx32, cpu32.r[11]) << "\n";
9129 outs() << "\t r12 " << format("0x%08" PRIx32, cpu32.r[12]);
9130 outs() << " sp " << format("0x%08" PRIx32, cpu32.sp);
9131 outs() << " lr " << format("0x%08" PRIx32, cpu32.lr);
9132 outs() << " pc " << format("0x%08" PRIx32, cpu32.pc) << "\n";
9133 outs() << "\t cpsr " << format("0x%08" PRIx32, cpu32.cpsr) << "\n";
9134}
9135
Kevin Enderby7747cb52016-11-03 20:51:28 +00009136static void Print_arm_thread_state64_t(MachO::arm_thread_state64_t &cpu64) {
9137 outs() << "\t x0 " << format("0x%016" PRIx64, cpu64.x[0]);
9138 outs() << " x1 " << format("0x%016" PRIx64, cpu64.x[1]);
9139 outs() << " x2 " << format("0x%016" PRIx64, cpu64.x[2]) << "\n";
9140 outs() << "\t x3 " << format("0x%016" PRIx64, cpu64.x[3]);
9141 outs() << " x4 " << format("0x%016" PRIx64, cpu64.x[4]);
9142 outs() << " x5 " << format("0x%016" PRIx64, cpu64.x[5]) << "\n";
9143 outs() << "\t x6 " << format("0x%016" PRIx64, cpu64.x[6]);
9144 outs() << " x7 " << format("0x%016" PRIx64, cpu64.x[7]);
9145 outs() << " x8 " << format("0x%016" PRIx64, cpu64.x[8]) << "\n";
9146 outs() << "\t x9 " << format("0x%016" PRIx64, cpu64.x[9]);
9147 outs() << " x10 " << format("0x%016" PRIx64, cpu64.x[10]);
9148 outs() << " x11 " << format("0x%016" PRIx64, cpu64.x[11]) << "\n";
9149 outs() << "\t x12 " << format("0x%016" PRIx64, cpu64.x[12]);
9150 outs() << " x13 " << format("0x%016" PRIx64, cpu64.x[13]);
9151 outs() << " x14 " << format("0x%016" PRIx64, cpu64.x[14]) << "\n";
9152 outs() << "\t x15 " << format("0x%016" PRIx64, cpu64.x[15]);
9153 outs() << " x16 " << format("0x%016" PRIx64, cpu64.x[16]);
9154 outs() << " x17 " << format("0x%016" PRIx64, cpu64.x[17]) << "\n";
9155 outs() << "\t x18 " << format("0x%016" PRIx64, cpu64.x[18]);
9156 outs() << " x19 " << format("0x%016" PRIx64, cpu64.x[19]);
9157 outs() << " x20 " << format("0x%016" PRIx64, cpu64.x[20]) << "\n";
9158 outs() << "\t x21 " << format("0x%016" PRIx64, cpu64.x[21]);
9159 outs() << " x22 " << format("0x%016" PRIx64, cpu64.x[22]);
9160 outs() << " x23 " << format("0x%016" PRIx64, cpu64.x[23]) << "\n";
9161 outs() << "\t x24 " << format("0x%016" PRIx64, cpu64.x[24]);
9162 outs() << " x25 " << format("0x%016" PRIx64, cpu64.x[25]);
9163 outs() << " x26 " << format("0x%016" PRIx64, cpu64.x[26]) << "\n";
9164 outs() << "\t x27 " << format("0x%016" PRIx64, cpu64.x[27]);
9165 outs() << " x28 " << format("0x%016" PRIx64, cpu64.x[28]);
9166 outs() << " fp " << format("0x%016" PRIx64, cpu64.fp) << "\n";
9167 outs() << "\t lr " << format("0x%016" PRIx64, cpu64.lr);
9168 outs() << " sp " << format("0x%016" PRIx64, cpu64.sp);
9169 outs() << " pc " << format("0x%016" PRIx64, cpu64.pc) << "\n";
9170 outs() << "\t cpsr " << format("0x%08" PRIx32, cpu64.cpsr) << "\n";
9171}
9172
Kevin Enderby48ef5342014-12-23 22:56:39 +00009173static void PrintThreadCommand(MachO::thread_command t, const char *Ptr,
9174 bool isLittleEndian, uint32_t cputype) {
9175 if (t.cmd == MachO::LC_THREAD)
9176 outs() << " cmd LC_THREAD\n";
9177 else if (t.cmd == MachO::LC_UNIXTHREAD)
9178 outs() << " cmd LC_UNIXTHREAD\n";
9179 else
9180 outs() << " cmd " << t.cmd << " (unknown)\n";
9181 outs() << " cmdsize " << t.cmdsize;
9182 if (t.cmdsize < sizeof(struct MachO::thread_command) + 2 * sizeof(uint32_t))
9183 outs() << " Incorrect size\n";
9184 else
9185 outs() << "\n";
9186
9187 const char *begin = Ptr + sizeof(struct MachO::thread_command);
9188 const char *end = Ptr + t.cmdsize;
9189 uint32_t flavor, count, left;
Kevin Enderbyc3a035d2017-01-23 21:13:29 +00009190 if (cputype == MachO::CPU_TYPE_I386) {
9191 while (begin < end) {
9192 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9193 memcpy((char *)&flavor, begin, sizeof(uint32_t));
9194 begin += sizeof(uint32_t);
9195 } else {
9196 flavor = 0;
9197 begin = end;
9198 }
9199 if (isLittleEndian != sys::IsLittleEndianHost)
9200 sys::swapByteOrder(flavor);
9201 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9202 memcpy((char *)&count, begin, sizeof(uint32_t));
9203 begin += sizeof(uint32_t);
9204 } else {
9205 count = 0;
9206 begin = end;
9207 }
9208 if (isLittleEndian != sys::IsLittleEndianHost)
9209 sys::swapByteOrder(count);
9210 if (flavor == MachO::x86_THREAD_STATE32) {
9211 outs() << " flavor i386_THREAD_STATE\n";
9212 if (count == MachO::x86_THREAD_STATE32_COUNT)
9213 outs() << " count i386_THREAD_STATE_COUNT\n";
9214 else
9215 outs() << " count " << count
9216 << " (not x86_THREAD_STATE32_COUNT)\n";
9217 MachO::x86_thread_state32_t cpu32;
9218 left = end - begin;
9219 if (left >= sizeof(MachO::x86_thread_state32_t)) {
9220 memcpy(&cpu32, begin, sizeof(MachO::x86_thread_state32_t));
9221 begin += sizeof(MachO::x86_thread_state32_t);
9222 } else {
9223 memset(&cpu32, '\0', sizeof(MachO::x86_thread_state32_t));
9224 memcpy(&cpu32, begin, left);
9225 begin += left;
9226 }
9227 if (isLittleEndian != sys::IsLittleEndianHost)
9228 swapStruct(cpu32);
9229 Print_x86_thread_state32_t(cpu32);
9230 } else if (flavor == MachO::x86_THREAD_STATE) {
9231 outs() << " flavor x86_THREAD_STATE\n";
9232 if (count == MachO::x86_THREAD_STATE_COUNT)
9233 outs() << " count x86_THREAD_STATE_COUNT\n";
9234 else
9235 outs() << " count " << count
9236 << " (not x86_THREAD_STATE_COUNT)\n";
9237 struct MachO::x86_thread_state_t ts;
9238 left = end - begin;
9239 if (left >= sizeof(MachO::x86_thread_state_t)) {
9240 memcpy(&ts, begin, sizeof(MachO::x86_thread_state_t));
9241 begin += sizeof(MachO::x86_thread_state_t);
9242 } else {
9243 memset(&ts, '\0', sizeof(MachO::x86_thread_state_t));
9244 memcpy(&ts, begin, left);
9245 begin += left;
9246 }
9247 if (isLittleEndian != sys::IsLittleEndianHost)
9248 swapStruct(ts);
9249 if (ts.tsh.flavor == MachO::x86_THREAD_STATE32) {
9250 outs() << "\t tsh.flavor x86_THREAD_STATE32 ";
9251 if (ts.tsh.count == MachO::x86_THREAD_STATE32_COUNT)
9252 outs() << "tsh.count x86_THREAD_STATE32_COUNT\n";
9253 else
9254 outs() << "tsh.count " << ts.tsh.count
9255 << " (not x86_THREAD_STATE32_COUNT\n";
9256 Print_x86_thread_state32_t(ts.uts.ts32);
9257 } else {
9258 outs() << "\t tsh.flavor " << ts.tsh.flavor << " tsh.count "
9259 << ts.tsh.count << "\n";
9260 }
9261 } else {
9262 outs() << " flavor " << flavor << " (unknown)\n";
9263 outs() << " count " << count << "\n";
9264 outs() << " state (unknown)\n";
9265 begin += count * sizeof(uint32_t);
9266 }
9267 }
9268 } else if (cputype == MachO::CPU_TYPE_X86_64) {
Kevin Enderby48ef5342014-12-23 22:56:39 +00009269 while (begin < end) {
9270 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9271 memcpy((char *)&flavor, begin, sizeof(uint32_t));
9272 begin += sizeof(uint32_t);
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009273 } else {
Kevin Enderby48ef5342014-12-23 22:56:39 +00009274 flavor = 0;
9275 begin = end;
9276 }
9277 if (isLittleEndian != sys::IsLittleEndianHost)
9278 sys::swapByteOrder(flavor);
9279 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9280 memcpy((char *)&count, begin, sizeof(uint32_t));
9281 begin += sizeof(uint32_t);
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009282 } else {
Kevin Enderby48ef5342014-12-23 22:56:39 +00009283 count = 0;
9284 begin = end;
9285 }
9286 if (isLittleEndian != sys::IsLittleEndianHost)
9287 sys::swapByteOrder(count);
9288 if (flavor == MachO::x86_THREAD_STATE64) {
9289 outs() << " flavor x86_THREAD_STATE64\n";
9290 if (count == MachO::x86_THREAD_STATE64_COUNT)
9291 outs() << " count x86_THREAD_STATE64_COUNT\n";
9292 else
9293 outs() << " count " << count
9294 << " (not x86_THREAD_STATE64_COUNT)\n";
9295 MachO::x86_thread_state64_t cpu64;
9296 left = end - begin;
9297 if (left >= sizeof(MachO::x86_thread_state64_t)) {
9298 memcpy(&cpu64, begin, sizeof(MachO::x86_thread_state64_t));
9299 begin += sizeof(MachO::x86_thread_state64_t);
9300 } else {
9301 memset(&cpu64, '\0', sizeof(MachO::x86_thread_state64_t));
9302 memcpy(&cpu64, begin, left);
9303 begin += left;
9304 }
9305 if (isLittleEndian != sys::IsLittleEndianHost)
9306 swapStruct(cpu64);
9307 Print_x86_thread_state64_t(cpu64);
9308 } else if (flavor == MachO::x86_THREAD_STATE) {
9309 outs() << " flavor x86_THREAD_STATE\n";
9310 if (count == MachO::x86_THREAD_STATE_COUNT)
9311 outs() << " count x86_THREAD_STATE_COUNT\n";
9312 else
9313 outs() << " count " << count
9314 << " (not x86_THREAD_STATE_COUNT)\n";
9315 struct MachO::x86_thread_state_t ts;
9316 left = end - begin;
9317 if (left >= sizeof(MachO::x86_thread_state_t)) {
9318 memcpy(&ts, begin, sizeof(MachO::x86_thread_state_t));
9319 begin += sizeof(MachO::x86_thread_state_t);
9320 } else {
9321 memset(&ts, '\0', sizeof(MachO::x86_thread_state_t));
9322 memcpy(&ts, begin, left);
9323 begin += left;
9324 }
9325 if (isLittleEndian != sys::IsLittleEndianHost)
9326 swapStruct(ts);
9327 if (ts.tsh.flavor == MachO::x86_THREAD_STATE64) {
9328 outs() << "\t tsh.flavor x86_THREAD_STATE64 ";
9329 if (ts.tsh.count == MachO::x86_THREAD_STATE64_COUNT)
9330 outs() << "tsh.count x86_THREAD_STATE64_COUNT\n";
9331 else
9332 outs() << "tsh.count " << ts.tsh.count
9333 << " (not x86_THREAD_STATE64_COUNT\n";
9334 Print_x86_thread_state64_t(ts.uts.ts64);
9335 } else {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009336 outs() << "\t tsh.flavor " << ts.tsh.flavor << " tsh.count "
9337 << ts.tsh.count << "\n";
Kevin Enderby48ef5342014-12-23 22:56:39 +00009338 }
9339 } else if (flavor == MachO::x86_FLOAT_STATE) {
9340 outs() << " flavor x86_FLOAT_STATE\n";
9341 if (count == MachO::x86_FLOAT_STATE_COUNT)
9342 outs() << " count x86_FLOAT_STATE_COUNT\n";
9343 else
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009344 outs() << " count " << count << " (not x86_FLOAT_STATE_COUNT)\n";
Kevin Enderby48ef5342014-12-23 22:56:39 +00009345 struct MachO::x86_float_state_t fs;
9346 left = end - begin;
9347 if (left >= sizeof(MachO::x86_float_state_t)) {
9348 memcpy(&fs, begin, sizeof(MachO::x86_float_state_t));
9349 begin += sizeof(MachO::x86_float_state_t);
9350 } else {
9351 memset(&fs, '\0', sizeof(MachO::x86_float_state_t));
9352 memcpy(&fs, begin, left);
9353 begin += left;
9354 }
9355 if (isLittleEndian != sys::IsLittleEndianHost)
9356 swapStruct(fs);
9357 if (fs.fsh.flavor == MachO::x86_FLOAT_STATE64) {
9358 outs() << "\t fsh.flavor x86_FLOAT_STATE64 ";
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009359 if (fs.fsh.count == MachO::x86_FLOAT_STATE64_COUNT)
Kevin Enderby48ef5342014-12-23 22:56:39 +00009360 outs() << "fsh.count x86_FLOAT_STATE64_COUNT\n";
9361 else
9362 outs() << "fsh.count " << fs.fsh.count
9363 << " (not x86_FLOAT_STATE64_COUNT\n";
9364 Print_x86_float_state_t(fs.ufs.fs64);
9365 } else {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009366 outs() << "\t fsh.flavor " << fs.fsh.flavor << " fsh.count "
9367 << fs.fsh.count << "\n";
Kevin Enderby48ef5342014-12-23 22:56:39 +00009368 }
9369 } else if (flavor == MachO::x86_EXCEPTION_STATE) {
9370 outs() << " flavor x86_EXCEPTION_STATE\n";
9371 if (count == MachO::x86_EXCEPTION_STATE_COUNT)
9372 outs() << " count x86_EXCEPTION_STATE_COUNT\n";
9373 else
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009374 outs() << " count " << count
Kevin Enderby48ef5342014-12-23 22:56:39 +00009375 << " (not x86_EXCEPTION_STATE_COUNT)\n";
9376 struct MachO::x86_exception_state_t es;
9377 left = end - begin;
9378 if (left >= sizeof(MachO::x86_exception_state_t)) {
9379 memcpy(&es, begin, sizeof(MachO::x86_exception_state_t));
9380 begin += sizeof(MachO::x86_exception_state_t);
9381 } else {
9382 memset(&es, '\0', sizeof(MachO::x86_exception_state_t));
9383 memcpy(&es, begin, left);
9384 begin += left;
9385 }
9386 if (isLittleEndian != sys::IsLittleEndianHost)
9387 swapStruct(es);
9388 if (es.esh.flavor == MachO::x86_EXCEPTION_STATE64) {
9389 outs() << "\t esh.flavor x86_EXCEPTION_STATE64\n";
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009390 if (es.esh.count == MachO::x86_EXCEPTION_STATE64_COUNT)
Kevin Enderby48ef5342014-12-23 22:56:39 +00009391 outs() << "\t esh.count x86_EXCEPTION_STATE64_COUNT\n";
9392 else
9393 outs() << "\t esh.count " << es.esh.count
9394 << " (not x86_EXCEPTION_STATE64_COUNT\n";
9395 Print_x86_exception_state_t(es.ues.es64);
9396 } else {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009397 outs() << "\t esh.flavor " << es.esh.flavor << " esh.count "
9398 << es.esh.count << "\n";
Kevin Enderby48ef5342014-12-23 22:56:39 +00009399 }
Kevin Enderby299cd892018-03-08 23:10:38 +00009400 } else if (flavor == MachO::x86_EXCEPTION_STATE64) {
9401 outs() << " flavor x86_EXCEPTION_STATE64\n";
9402 if (count == MachO::x86_EXCEPTION_STATE64_COUNT)
9403 outs() << " count x86_EXCEPTION_STATE64_COUNT\n";
9404 else
9405 outs() << " count " << count
9406 << " (not x86_EXCEPTION_STATE64_COUNT)\n";
9407 struct MachO::x86_exception_state64_t es64;
9408 left = end - begin;
9409 if (left >= sizeof(MachO::x86_exception_state64_t)) {
9410 memcpy(&es64, begin, sizeof(MachO::x86_exception_state64_t));
9411 begin += sizeof(MachO::x86_exception_state64_t);
9412 } else {
9413 memset(&es64, '\0', sizeof(MachO::x86_exception_state64_t));
9414 memcpy(&es64, begin, left);
9415 begin += left;
9416 }
9417 if (isLittleEndian != sys::IsLittleEndianHost)
9418 swapStruct(es64);
9419 Print_x86_exception_state_t(es64);
Kevin Enderby48ef5342014-12-23 22:56:39 +00009420 } else {
9421 outs() << " flavor " << flavor << " (unknown)\n";
9422 outs() << " count " << count << "\n";
9423 outs() << " state (unknown)\n";
9424 begin += count * sizeof(uint32_t);
9425 }
9426 }
Kevin Enderby41c9c002016-10-21 18:22:35 +00009427 } else if (cputype == MachO::CPU_TYPE_ARM) {
9428 while (begin < end) {
9429 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9430 memcpy((char *)&flavor, begin, sizeof(uint32_t));
9431 begin += sizeof(uint32_t);
9432 } else {
9433 flavor = 0;
9434 begin = end;
9435 }
9436 if (isLittleEndian != sys::IsLittleEndianHost)
9437 sys::swapByteOrder(flavor);
9438 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9439 memcpy((char *)&count, begin, sizeof(uint32_t));
9440 begin += sizeof(uint32_t);
9441 } else {
9442 count = 0;
9443 begin = end;
9444 }
9445 if (isLittleEndian != sys::IsLittleEndianHost)
9446 sys::swapByteOrder(count);
9447 if (flavor == MachO::ARM_THREAD_STATE) {
9448 outs() << " flavor ARM_THREAD_STATE\n";
9449 if (count == MachO::ARM_THREAD_STATE_COUNT)
9450 outs() << " count ARM_THREAD_STATE_COUNT\n";
9451 else
9452 outs() << " count " << count
9453 << " (not ARM_THREAD_STATE_COUNT)\n";
9454 MachO::arm_thread_state32_t cpu32;
9455 left = end - begin;
9456 if (left >= sizeof(MachO::arm_thread_state32_t)) {
9457 memcpy(&cpu32, begin, sizeof(MachO::arm_thread_state32_t));
9458 begin += sizeof(MachO::arm_thread_state32_t);
9459 } else {
9460 memset(&cpu32, '\0', sizeof(MachO::arm_thread_state32_t));
9461 memcpy(&cpu32, begin, left);
9462 begin += left;
9463 }
9464 if (isLittleEndian != sys::IsLittleEndianHost)
9465 swapStruct(cpu32);
9466 Print_arm_thread_state32_t(cpu32);
9467 } else {
9468 outs() << " flavor " << flavor << " (unknown)\n";
9469 outs() << " count " << count << "\n";
9470 outs() << " state (unknown)\n";
9471 begin += count * sizeof(uint32_t);
9472 }
9473 }
Kevin Enderby7747cb52016-11-03 20:51:28 +00009474 } else if (cputype == MachO::CPU_TYPE_ARM64) {
9475 while (begin < end) {
9476 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9477 memcpy((char *)&flavor, begin, sizeof(uint32_t));
9478 begin += sizeof(uint32_t);
9479 } else {
9480 flavor = 0;
9481 begin = end;
9482 }
9483 if (isLittleEndian != sys::IsLittleEndianHost)
9484 sys::swapByteOrder(flavor);
9485 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9486 memcpy((char *)&count, begin, sizeof(uint32_t));
9487 begin += sizeof(uint32_t);
9488 } else {
9489 count = 0;
9490 begin = end;
9491 }
9492 if (isLittleEndian != sys::IsLittleEndianHost)
9493 sys::swapByteOrder(count);
9494 if (flavor == MachO::ARM_THREAD_STATE64) {
9495 outs() << " flavor ARM_THREAD_STATE64\n";
9496 if (count == MachO::ARM_THREAD_STATE64_COUNT)
9497 outs() << " count ARM_THREAD_STATE64_COUNT\n";
9498 else
9499 outs() << " count " << count
9500 << " (not ARM_THREAD_STATE64_COUNT)\n";
9501 MachO::arm_thread_state64_t cpu64;
9502 left = end - begin;
9503 if (left >= sizeof(MachO::arm_thread_state64_t)) {
9504 memcpy(&cpu64, begin, sizeof(MachO::arm_thread_state64_t));
9505 begin += sizeof(MachO::arm_thread_state64_t);
9506 } else {
9507 memset(&cpu64, '\0', sizeof(MachO::arm_thread_state64_t));
9508 memcpy(&cpu64, begin, left);
9509 begin += left;
9510 }
9511 if (isLittleEndian != sys::IsLittleEndianHost)
9512 swapStruct(cpu64);
9513 Print_arm_thread_state64_t(cpu64);
9514 } else {
9515 outs() << " flavor " << flavor << " (unknown)\n";
9516 outs() << " count " << count << "\n";
9517 outs() << " state (unknown)\n";
9518 begin += count * sizeof(uint32_t);
9519 }
9520 }
Kevin Enderby48ef5342014-12-23 22:56:39 +00009521 } else {
9522 while (begin < end) {
9523 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9524 memcpy((char *)&flavor, begin, sizeof(uint32_t));
9525 begin += sizeof(uint32_t);
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009526 } else {
Kevin Enderby48ef5342014-12-23 22:56:39 +00009527 flavor = 0;
9528 begin = end;
9529 }
9530 if (isLittleEndian != sys::IsLittleEndianHost)
9531 sys::swapByteOrder(flavor);
9532 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9533 memcpy((char *)&count, begin, sizeof(uint32_t));
9534 begin += sizeof(uint32_t);
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009535 } else {
Kevin Enderby48ef5342014-12-23 22:56:39 +00009536 count = 0;
9537 begin = end;
9538 }
9539 if (isLittleEndian != sys::IsLittleEndianHost)
9540 sys::swapByteOrder(count);
9541 outs() << " flavor " << flavor << "\n";
9542 outs() << " count " << count << "\n";
9543 outs() << " state (Unknown cputype/cpusubtype)\n";
9544 begin += count * sizeof(uint32_t);
9545 }
9546 }
9547}
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009548
Kevin Enderby8ae63c12014-09-04 16:54:47 +00009549static void PrintDylibCommand(MachO::dylib_command dl, const char *Ptr) {
9550 if (dl.cmd == MachO::LC_ID_DYLIB)
9551 outs() << " cmd LC_ID_DYLIB\n";
9552 else if (dl.cmd == MachO::LC_LOAD_DYLIB)
9553 outs() << " cmd LC_LOAD_DYLIB\n";
9554 else if (dl.cmd == MachO::LC_LOAD_WEAK_DYLIB)
9555 outs() << " cmd LC_LOAD_WEAK_DYLIB\n";
9556 else if (dl.cmd == MachO::LC_REEXPORT_DYLIB)
9557 outs() << " cmd LC_REEXPORT_DYLIB\n";
9558 else if (dl.cmd == MachO::LC_LAZY_LOAD_DYLIB)
9559 outs() << " cmd LC_LAZY_LOAD_DYLIB\n";
9560 else if (dl.cmd == MachO::LC_LOAD_UPWARD_DYLIB)
9561 outs() << " cmd LC_LOAD_UPWARD_DYLIB\n";
9562 else
9563 outs() << " cmd " << dl.cmd << " (unknown)\n";
9564 outs() << " cmdsize " << dl.cmdsize;
9565 if (dl.cmdsize < sizeof(struct MachO::dylib_command))
9566 outs() << " Incorrect size\n";
9567 else
9568 outs() << "\n";
9569 if (dl.dylib.name < dl.cmdsize) {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00009570 const char *P = (const char *)(Ptr) + dl.dylib.name;
Kevin Enderby8ae63c12014-09-04 16:54:47 +00009571 outs() << " name " << P << " (offset " << dl.dylib.name << ")\n";
9572 } else {
9573 outs() << " name ?(bad offset " << dl.dylib.name << ")\n";
9574 }
9575 outs() << " time stamp " << dl.dylib.timestamp << " ";
9576 time_t t = dl.dylib.timestamp;
9577 outs() << ctime(&t);
9578 outs() << " current version ";
9579 if (dl.dylib.current_version == 0xffffffff)
9580 outs() << "n/a\n";
9581 else
9582 outs() << ((dl.dylib.current_version >> 16) & 0xffff) << "."
9583 << ((dl.dylib.current_version >> 8) & 0xff) << "."
9584 << (dl.dylib.current_version & 0xff) << "\n";
9585 outs() << "compatibility version ";
9586 if (dl.dylib.compatibility_version == 0xffffffff)
9587 outs() << "n/a\n";
9588 else
9589 outs() << ((dl.dylib.compatibility_version >> 16) & 0xffff) << "."
9590 << ((dl.dylib.compatibility_version >> 8) & 0xff) << "."
9591 << (dl.dylib.compatibility_version & 0xff) << "\n";
9592}
9593
9594static void PrintLinkEditDataCommand(MachO::linkedit_data_command ld,
9595 uint32_t object_size) {
9596 if (ld.cmd == MachO::LC_CODE_SIGNATURE)
Kevin Enderby1be37a32016-04-28 21:07:20 +00009597 outs() << " cmd LC_CODE_SIGNATURE\n";
Kevin Enderby8ae63c12014-09-04 16:54:47 +00009598 else if (ld.cmd == MachO::LC_SEGMENT_SPLIT_INFO)
9599 outs() << " cmd LC_SEGMENT_SPLIT_INFO\n";
9600 else if (ld.cmd == MachO::LC_FUNCTION_STARTS)
9601 outs() << " cmd LC_FUNCTION_STARTS\n";
9602 else if (ld.cmd == MachO::LC_DATA_IN_CODE)
9603 outs() << " cmd LC_DATA_IN_CODE\n";
9604 else if (ld.cmd == MachO::LC_DYLIB_CODE_SIGN_DRS)
9605 outs() << " cmd LC_DYLIB_CODE_SIGN_DRS\n";
9606 else if (ld.cmd == MachO::LC_LINKER_OPTIMIZATION_HINT)
9607 outs() << " cmd LC_LINKER_OPTIMIZATION_HINT\n";
9608 else
9609 outs() << " cmd " << ld.cmd << " (?)\n";
9610 outs() << " cmdsize " << ld.cmdsize;
9611 if (ld.cmdsize != sizeof(struct MachO::linkedit_data_command))
9612 outs() << " Incorrect size\n";
9613 else
9614 outs() << "\n";
9615 outs() << " dataoff " << ld.dataoff;
9616 if (ld.dataoff > object_size)
9617 outs() << " (past end of file)\n";
9618 else
9619 outs() << "\n";
9620 outs() << " datasize " << ld.datasize;
9621 uint64_t big_size = ld.dataoff;
9622 big_size += ld.datasize;
9623 if (big_size > object_size)
9624 outs() << " (past end of file)\n";
9625 else
9626 outs() << "\n";
9627}
9628
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00009629static void PrintLoadCommands(const MachOObjectFile *Obj, uint32_t filetype,
9630 uint32_t cputype, bool verbose) {
Kevin Enderby956366c2014-08-29 22:30:52 +00009631 StringRef Buf = Obj->getData();
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00009632 unsigned Index = 0;
9633 for (const auto &Command : Obj->load_commands()) {
9634 outs() << "Load command " << Index++ << "\n";
Kevin Enderby956366c2014-08-29 22:30:52 +00009635 if (Command.C.cmd == MachO::LC_SEGMENT) {
9636 MachO::segment_command SLC = Obj->getSegmentLoadCommand(Command);
9637 const char *sg_segname = SLC.segname;
9638 PrintSegmentCommand(SLC.cmd, SLC.cmdsize, SLC.segname, SLC.vmaddr,
9639 SLC.vmsize, SLC.fileoff, SLC.filesize, SLC.maxprot,
9640 SLC.initprot, SLC.nsects, SLC.flags, Buf.size(),
9641 verbose);
9642 for (unsigned j = 0; j < SLC.nsects; j++) {
Kevin Enderbyc9713382014-12-16 01:14:45 +00009643 MachO::section S = Obj->getSection(Command, j);
Kevin Enderby956366c2014-08-29 22:30:52 +00009644 PrintSection(S.sectname, S.segname, S.addr, S.size, S.offset, S.align,
9645 S.reloff, S.nreloc, S.flags, S.reserved1, S.reserved2,
9646 SLC.cmd, sg_segname, filetype, Buf.size(), verbose);
9647 }
9648 } else if (Command.C.cmd == MachO::LC_SEGMENT_64) {
9649 MachO::segment_command_64 SLC_64 = Obj->getSegment64LoadCommand(Command);
9650 const char *sg_segname = SLC_64.segname;
9651 PrintSegmentCommand(SLC_64.cmd, SLC_64.cmdsize, SLC_64.segname,
9652 SLC_64.vmaddr, SLC_64.vmsize, SLC_64.fileoff,
9653 SLC_64.filesize, SLC_64.maxprot, SLC_64.initprot,
9654 SLC_64.nsects, SLC_64.flags, Buf.size(), verbose);
9655 for (unsigned j = 0; j < SLC_64.nsects; j++) {
9656 MachO::section_64 S_64 = Obj->getSection64(Command, j);
9657 PrintSection(S_64.sectname, S_64.segname, S_64.addr, S_64.size,
9658 S_64.offset, S_64.align, S_64.reloff, S_64.nreloc,
9659 S_64.flags, S_64.reserved1, S_64.reserved2, SLC_64.cmd,
9660 sg_segname, filetype, Buf.size(), verbose);
9661 }
9662 } else if (Command.C.cmd == MachO::LC_SYMTAB) {
9663 MachO::symtab_command Symtab = Obj->getSymtabLoadCommand();
David Majnemer73cc6ff2014-11-13 19:48:56 +00009664 PrintSymtabLoadCommand(Symtab, Obj->is64Bit(), Buf.size());
Kevin Enderby956366c2014-08-29 22:30:52 +00009665 } else if (Command.C.cmd == MachO::LC_DYSYMTAB) {
9666 MachO::dysymtab_command Dysymtab = Obj->getDysymtabLoadCommand();
9667 MachO::symtab_command Symtab = Obj->getSymtabLoadCommand();
David Majnemer73cc6ff2014-11-13 19:48:56 +00009668 PrintDysymtabLoadCommand(Dysymtab, Symtab.nsyms, Buf.size(),
9669 Obj->is64Bit());
Kevin Enderby8ae63c12014-09-04 16:54:47 +00009670 } else if (Command.C.cmd == MachO::LC_DYLD_INFO ||
9671 Command.C.cmd == MachO::LC_DYLD_INFO_ONLY) {
9672 MachO::dyld_info_command DyldInfo = Obj->getDyldInfoLoadCommand(Command);
9673 PrintDyldInfoLoadCommand(DyldInfo, Buf.size());
9674 } else if (Command.C.cmd == MachO::LC_LOAD_DYLINKER ||
9675 Command.C.cmd == MachO::LC_ID_DYLINKER ||
9676 Command.C.cmd == MachO::LC_DYLD_ENVIRONMENT) {
9677 MachO::dylinker_command Dyld = Obj->getDylinkerCommand(Command);
9678 PrintDyldLoadCommand(Dyld, Command.Ptr);
9679 } else if (Command.C.cmd == MachO::LC_UUID) {
9680 MachO::uuid_command Uuid = Obj->getUuidCommand(Command);
9681 PrintUuidLoadCommand(Uuid);
Jean-Daniel Dupas00cc1f52014-12-04 07:37:02 +00009682 } else if (Command.C.cmd == MachO::LC_RPATH) {
9683 MachO::rpath_command Rpath = Obj->getRpathCommand(Command);
9684 PrintRpathLoadCommand(Rpath, Command.Ptr);
Kevin Enderby1ff0ecc2014-12-16 21:48:27 +00009685 } else if (Command.C.cmd == MachO::LC_VERSION_MIN_MACOSX ||
Tim Northoverbfbfb122015-11-02 21:26:58 +00009686 Command.C.cmd == MachO::LC_VERSION_MIN_IPHONEOS ||
9687 Command.C.cmd == MachO::LC_VERSION_MIN_TVOS ||
9688 Command.C.cmd == MachO::LC_VERSION_MIN_WATCHOS) {
Kevin Enderby8ae63c12014-09-04 16:54:47 +00009689 MachO::version_min_command Vd = Obj->getVersionMinLoadCommand(Command);
9690 PrintVersionMinLoadCommand(Vd);
Kevin Enderbya4579c42017-01-19 17:36:31 +00009691 } else if (Command.C.cmd == MachO::LC_NOTE) {
9692 MachO::note_command Nt = Obj->getNoteLoadCommand(Command);
9693 PrintNoteLoadCommand(Nt);
Steven Wu5b54a422017-01-23 20:07:55 +00009694 } else if (Command.C.cmd == MachO::LC_BUILD_VERSION) {
9695 MachO::build_version_command Bv =
9696 Obj->getBuildVersionLoadCommand(Command);
9697 PrintBuildVersionLoadCommand(Obj, Bv);
Kevin Enderby8ae63c12014-09-04 16:54:47 +00009698 } else if (Command.C.cmd == MachO::LC_SOURCE_VERSION) {
9699 MachO::source_version_command Sd = Obj->getSourceVersionCommand(Command);
9700 PrintSourceVersionCommand(Sd);
9701 } else if (Command.C.cmd == MachO::LC_MAIN) {
9702 MachO::entry_point_command Ep = Obj->getEntryPointCommand(Command);
9703 PrintEntryPointCommand(Ep);
Kevin Enderby0804f4672014-12-16 23:25:52 +00009704 } else if (Command.C.cmd == MachO::LC_ENCRYPTION_INFO) {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009705 MachO::encryption_info_command Ei =
9706 Obj->getEncryptionInfoCommand(Command);
Kevin Enderby0804f4672014-12-16 23:25:52 +00009707 PrintEncryptionInfoCommand(Ei, Buf.size());
Kevin Enderby57538292014-12-17 01:01:30 +00009708 } else if (Command.C.cmd == MachO::LC_ENCRYPTION_INFO_64) {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009709 MachO::encryption_info_command_64 Ei =
9710 Obj->getEncryptionInfoCommand64(Command);
Kevin Enderby57538292014-12-17 01:01:30 +00009711 PrintEncryptionInfoCommand64(Ei, Buf.size());
Kevin Enderbyd0b6b7f2014-12-18 00:53:40 +00009712 } else if (Command.C.cmd == MachO::LC_LINKER_OPTION) {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009713 MachO::linker_option_command Lo =
9714 Obj->getLinkerOptionLoadCommand(Command);
Kevin Enderbyd0b6b7f2014-12-18 00:53:40 +00009715 PrintLinkerOptionCommand(Lo, Command.Ptr);
Kevin Enderbyb4b79312014-12-18 19:24:35 +00009716 } else if (Command.C.cmd == MachO::LC_SUB_FRAMEWORK) {
9717 MachO::sub_framework_command Sf = Obj->getSubFrameworkCommand(Command);
9718 PrintSubFrameworkCommand(Sf, Command.Ptr);
Kevin Enderbya2bd8d92014-12-18 23:13:26 +00009719 } else if (Command.C.cmd == MachO::LC_SUB_UMBRELLA) {
9720 MachO::sub_umbrella_command Sf = Obj->getSubUmbrellaCommand(Command);
9721 PrintSubUmbrellaCommand(Sf, Command.Ptr);
Kevin Enderby36c8d3a2014-12-19 19:48:16 +00009722 } else if (Command.C.cmd == MachO::LC_SUB_LIBRARY) {
9723 MachO::sub_library_command Sl = Obj->getSubLibraryCommand(Command);
9724 PrintSubLibraryCommand(Sl, Command.Ptr);
Kevin Enderby186eac32014-12-19 21:06:24 +00009725 } else if (Command.C.cmd == MachO::LC_SUB_CLIENT) {
9726 MachO::sub_client_command Sc = Obj->getSubClientCommand(Command);
9727 PrintSubClientCommand(Sc, Command.Ptr);
Kevin Enderby52e4ce42014-12-19 22:25:22 +00009728 } else if (Command.C.cmd == MachO::LC_ROUTINES) {
9729 MachO::routines_command Rc = Obj->getRoutinesCommand(Command);
9730 PrintRoutinesCommand(Rc);
9731 } else if (Command.C.cmd == MachO::LC_ROUTINES_64) {
9732 MachO::routines_command_64 Rc = Obj->getRoutinesCommand64(Command);
9733 PrintRoutinesCommand64(Rc);
Kevin Enderby48ef5342014-12-23 22:56:39 +00009734 } else if (Command.C.cmd == MachO::LC_THREAD ||
9735 Command.C.cmd == MachO::LC_UNIXTHREAD) {
9736 MachO::thread_command Tc = Obj->getThreadCommand(Command);
9737 PrintThreadCommand(Tc, Command.Ptr, Obj->isLittleEndian(), cputype);
Nick Kledzik15558912014-10-16 18:58:20 +00009738 } else if (Command.C.cmd == MachO::LC_LOAD_DYLIB ||
9739 Command.C.cmd == MachO::LC_ID_DYLIB ||
9740 Command.C.cmd == MachO::LC_LOAD_WEAK_DYLIB ||
9741 Command.C.cmd == MachO::LC_REEXPORT_DYLIB ||
9742 Command.C.cmd == MachO::LC_LAZY_LOAD_DYLIB ||
9743 Command.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB) {
Kevin Enderby8ae63c12014-09-04 16:54:47 +00009744 MachO::dylib_command Dl = Obj->getDylibIDLoadCommand(Command);
9745 PrintDylibCommand(Dl, Command.Ptr);
9746 } else if (Command.C.cmd == MachO::LC_CODE_SIGNATURE ||
9747 Command.C.cmd == MachO::LC_SEGMENT_SPLIT_INFO ||
9748 Command.C.cmd == MachO::LC_FUNCTION_STARTS ||
9749 Command.C.cmd == MachO::LC_DATA_IN_CODE ||
9750 Command.C.cmd == MachO::LC_DYLIB_CODE_SIGN_DRS ||
9751 Command.C.cmd == MachO::LC_LINKER_OPTIMIZATION_HINT) {
9752 MachO::linkedit_data_command Ld =
9753 Obj->getLinkeditDataLoadCommand(Command);
9754 PrintLinkEditDataCommand(Ld, Buf.size());
Kevin Enderby956366c2014-08-29 22:30:52 +00009755 } else {
9756 outs() << " cmd ?(" << format("0x%08" PRIx32, Command.C.cmd)
9757 << ")\n";
9758 outs() << " cmdsize " << Command.C.cmdsize << "\n";
9759 // TODO: get and print the raw bytes of the load command.
9760 }
9761 // TODO: print all the other kinds of load commands.
Kevin Enderby956366c2014-08-29 22:30:52 +00009762 }
9763}
9764
Kevin Enderby0ae163f2016-01-13 00:25:36 +00009765static void PrintMachHeader(const MachOObjectFile *Obj, bool verbose) {
Kevin Enderbyb76d3862014-08-22 20:35:18 +00009766 if (Obj->is64Bit()) {
9767 MachO::mach_header_64 H_64;
9768 H_64 = Obj->getHeader64();
9769 PrintMachHeader(H_64.magic, H_64.cputype, H_64.cpusubtype, H_64.filetype,
9770 H_64.ncmds, H_64.sizeofcmds, H_64.flags, verbose);
9771 } else {
9772 MachO::mach_header H;
9773 H = Obj->getHeader();
9774 PrintMachHeader(H.magic, H.cputype, H.cpusubtype, H.filetype, H.ncmds,
9775 H.sizeofcmds, H.flags, verbose);
9776 }
9777}
9778
9779void llvm::printMachOFileHeader(const object::ObjectFile *Obj) {
9780 const MachOObjectFile *file = dyn_cast<const MachOObjectFile>(Obj);
Kevin Enderby0ae163f2016-01-13 00:25:36 +00009781 PrintMachHeader(file, !NonVerbose);
9782}
9783
9784void llvm::printMachOLoadCommands(const object::ObjectFile *Obj) {
9785 const MachOObjectFile *file = dyn_cast<const MachOObjectFile>(Obj);
Kevin Enderby956366c2014-08-29 22:30:52 +00009786 uint32_t filetype = 0;
9787 uint32_t cputype = 0;
Kevin Enderby0ae163f2016-01-13 00:25:36 +00009788 if (file->is64Bit()) {
9789 MachO::mach_header_64 H_64;
9790 H_64 = file->getHeader64();
9791 filetype = H_64.filetype;
9792 cputype = H_64.cputype;
9793 } else {
9794 MachO::mach_header H;
9795 H = file->getHeader();
9796 filetype = H.filetype;
9797 cputype = H.cputype;
9798 }
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00009799 PrintLoadCommands(file, filetype, cputype, !NonVerbose);
Kevin Enderbyb76d3862014-08-22 20:35:18 +00009800}
Nick Kledzikd04bc352014-08-30 00:20:14 +00009801
9802//===----------------------------------------------------------------------===//
9803// export trie dumping
9804//===----------------------------------------------------------------------===//
9805
9806void llvm::printMachOExportsTrie(const object::MachOObjectFile *Obj) {
Kevin Enderby0d5ec112017-06-19 21:23:07 +00009807 uint64_t BaseSegmentAddress = 0;
9808 for (const auto &Command : Obj->load_commands()) {
9809 if (Command.C.cmd == MachO::LC_SEGMENT) {
9810 MachO::segment_command Seg = Obj->getSegmentLoadCommand(Command);
9811 if (Seg.fileoff == 0 && Seg.filesize != 0) {
9812 BaseSegmentAddress = Seg.vmaddr;
9813 break;
9814 }
9815 } else if (Command.C.cmd == MachO::LC_SEGMENT_64) {
9816 MachO::segment_command_64 Seg = Obj->getSegment64LoadCommand(Command);
9817 if (Seg.fileoff == 0 && Seg.filesize != 0) {
9818 BaseSegmentAddress = Seg.vmaddr;
9819 break;
9820 }
9821 }
9822 }
Kevin Enderby3e95bd22017-07-20 23:08:41 +00009823 Error Err = Error::success();
Alexander Shaposhnikove5740342017-07-29 00:30:45 +00009824 for (const llvm::object::ExportEntry &Entry : Obj->exports(Err)) {
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00009825 uint64_t Flags = Entry.flags();
Nick Kledzikd04bc352014-08-30 00:20:14 +00009826 bool ReExport = (Flags & MachO::EXPORT_SYMBOL_FLAGS_REEXPORT);
9827 bool WeakDef = (Flags & MachO::EXPORT_SYMBOL_FLAGS_WEAK_DEFINITION);
9828 bool ThreadLocal = ((Flags & MachO::EXPORT_SYMBOL_FLAGS_KIND_MASK) ==
9829 MachO::EXPORT_SYMBOL_FLAGS_KIND_THREAD_LOCAL);
9830 bool Abs = ((Flags & MachO::EXPORT_SYMBOL_FLAGS_KIND_MASK) ==
9831 MachO::EXPORT_SYMBOL_FLAGS_KIND_ABSOLUTE);
9832 bool Resolver = (Flags & MachO::EXPORT_SYMBOL_FLAGS_STUB_AND_RESOLVER);
9833 if (ReExport)
9834 outs() << "[re-export] ";
9835 else
Kevin Enderbyb28ed012014-10-29 21:28:24 +00009836 outs() << format("0x%08llX ",
Kevin Enderby0d5ec112017-06-19 21:23:07 +00009837 Entry.address() + BaseSegmentAddress);
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00009838 outs() << Entry.name();
Nick Kledzikd04bc352014-08-30 00:20:14 +00009839 if (WeakDef || ThreadLocal || Resolver || Abs) {
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00009840 bool NeedsComma = false;
Nick Kledzik1d1ac4b2014-09-03 01:12:52 +00009841 outs() << " [";
Nick Kledzikd04bc352014-08-30 00:20:14 +00009842 if (WeakDef) {
9843 outs() << "weak_def";
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00009844 NeedsComma = true;
Nick Kledzikd04bc352014-08-30 00:20:14 +00009845 }
9846 if (ThreadLocal) {
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00009847 if (NeedsComma)
Nick Kledzikd04bc352014-08-30 00:20:14 +00009848 outs() << ", ";
9849 outs() << "per-thread";
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00009850 NeedsComma = true;
Nick Kledzikd04bc352014-08-30 00:20:14 +00009851 }
9852 if (Abs) {
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00009853 if (NeedsComma)
Nick Kledzikd04bc352014-08-30 00:20:14 +00009854 outs() << ", ";
9855 outs() << "absolute";
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00009856 NeedsComma = true;
Nick Kledzikd04bc352014-08-30 00:20:14 +00009857 }
9858 if (Resolver) {
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00009859 if (NeedsComma)
Nick Kledzikd04bc352014-08-30 00:20:14 +00009860 outs() << ", ";
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00009861 outs() << format("resolver=0x%08llX", Entry.other());
9862 NeedsComma = true;
Nick Kledzikd04bc352014-08-30 00:20:14 +00009863 }
9864 outs() << "]";
9865 }
9866 if (ReExport) {
9867 StringRef DylibName = "unknown";
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00009868 int Ordinal = Entry.other() - 1;
9869 Obj->getLibraryShortNameByIndex(Ordinal, DylibName);
9870 if (Entry.otherName().empty())
Nick Kledzikd04bc352014-08-30 00:20:14 +00009871 outs() << " (from " << DylibName << ")";
9872 else
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00009873 outs() << " (" << Entry.otherName() << " from " << DylibName << ")";
Nick Kledzikd04bc352014-08-30 00:20:14 +00009874 }
9875 outs() << "\n";
9876 }
Kevin Enderby3e95bd22017-07-20 23:08:41 +00009877 if (Err)
9878 report_error(Obj->getFileName(), std::move(Err));
Nick Kledzikd04bc352014-08-30 00:20:14 +00009879}
Nick Kledzikac431442014-09-12 21:34:15 +00009880
Nick Kledzikac431442014-09-12 21:34:15 +00009881//===----------------------------------------------------------------------===//
9882// rebase table dumping
9883//===----------------------------------------------------------------------===//
9884
Kevin Enderbya8d256c2017-03-20 19:46:55 +00009885void llvm::printMachORebaseTable(object::MachOObjectFile *Obj) {
Nick Kledzikac431442014-09-12 21:34:15 +00009886 outs() << "segment section address type\n";
Kevin Enderbya8d256c2017-03-20 19:46:55 +00009887 Error Err = Error::success();
9888 for (const llvm::object::MachORebaseEntry &Entry : Obj->rebaseTable(Err)) {
9889 StringRef SegmentName = Entry.segmentName();
9890 StringRef SectionName = Entry.sectionName();
9891 uint64_t Address = Entry.address();
Nick Kledzikac431442014-09-12 21:34:15 +00009892
9893 // Table lines look like: __DATA __nl_symbol_ptr 0x0000F00C pointer
Kevin Enderbyb28ed012014-10-29 21:28:24 +00009894 outs() << format("%-8s %-18s 0x%08" PRIX64 " %s\n",
9895 SegmentName.str().c_str(), SectionName.str().c_str(),
9896 Address, Entry.typeName().str().c_str());
Nick Kledzikac431442014-09-12 21:34:15 +00009897 }
Kevin Enderbya8d256c2017-03-20 19:46:55 +00009898 if (Err)
9899 report_error(Obj->getFileName(), std::move(Err));
Nick Kledzikac431442014-09-12 21:34:15 +00009900}
Nick Kledzik56ebef42014-09-16 01:41:51 +00009901
9902static StringRef ordinalName(const object::MachOObjectFile *Obj, int Ordinal) {
9903 StringRef DylibName;
9904 switch (Ordinal) {
9905 case MachO::BIND_SPECIAL_DYLIB_SELF:
9906 return "this-image";
9907 case MachO::BIND_SPECIAL_DYLIB_MAIN_EXECUTABLE:
9908 return "main-executable";
9909 case MachO::BIND_SPECIAL_DYLIB_FLAT_LOOKUP:
9910 return "flat-namespace";
9911 default:
Nick Kledzikabd29872014-09-16 22:03:13 +00009912 if (Ordinal > 0) {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00009913 std::error_code EC =
9914 Obj->getLibraryShortNameByIndex(Ordinal - 1, DylibName);
Nick Kledzikabd29872014-09-16 22:03:13 +00009915 if (EC)
Nick Kledzik51d2c2b2014-10-14 23:29:38 +00009916 return "<<bad library ordinal>>";
Nick Kledzikabd29872014-09-16 22:03:13 +00009917 return DylibName;
9918 }
Nick Kledzik56ebef42014-09-16 01:41:51 +00009919 }
Nick Kledzikabd29872014-09-16 22:03:13 +00009920 return "<<unknown special ordinal>>";
Nick Kledzik56ebef42014-09-16 01:41:51 +00009921}
9922
9923//===----------------------------------------------------------------------===//
9924// bind table dumping
9925//===----------------------------------------------------------------------===//
9926
Kevin Enderbya8d256c2017-03-20 19:46:55 +00009927void llvm::printMachOBindTable(object::MachOObjectFile *Obj) {
Nick Kledzik56ebef42014-09-16 01:41:51 +00009928 // Build table of sections so names can used in final output.
Nick Kledzik5ffacc12014-09-30 00:19:58 +00009929 outs() << "segment section address type "
9930 "addend dylib symbol\n";
Kevin Enderbyfeb63b92017-02-28 21:47:07 +00009931 Error Err = Error::success();
9932 for (const llvm::object::MachOBindEntry &Entry : Obj->bindTable(Err)) {
Kevin Enderbya8d256c2017-03-20 19:46:55 +00009933 StringRef SegmentName = Entry.segmentName();
9934 StringRef SectionName = Entry.sectionName();
9935 uint64_t Address = Entry.address();
Nick Kledzik56ebef42014-09-16 01:41:51 +00009936
9937 // Table lines look like:
9938 // __DATA __got 0x00012010 pointer 0 libSystem ___stack_chk_guard
Nick Kledzik5ffacc12014-09-30 00:19:58 +00009939 StringRef Attr;
Nick Kledzik56ebef42014-09-16 01:41:51 +00009940 if (Entry.flags() & MachO::BIND_SYMBOL_FLAGS_WEAK_IMPORT)
Nick Kledzik5ffacc12014-09-30 00:19:58 +00009941 Attr = " (weak_import)";
Kevin Enderbyb28ed012014-10-29 21:28:24 +00009942 outs() << left_justify(SegmentName, 8) << " "
Nick Kledzik5ffacc12014-09-30 00:19:58 +00009943 << left_justify(SectionName, 18) << " "
9944 << format_hex(Address, 10, true) << " "
9945 << left_justify(Entry.typeName(), 8) << " "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00009946 << format_decimal(Entry.addend(), 8) << " "
Nick Kledzik5ffacc12014-09-30 00:19:58 +00009947 << left_justify(ordinalName(Obj, Entry.ordinal()), 16) << " "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00009948 << Entry.symbolName() << Attr << "\n";
Nick Kledzik56ebef42014-09-16 01:41:51 +00009949 }
Kevin Enderbyfeb63b92017-02-28 21:47:07 +00009950 if (Err)
9951 report_error(Obj->getFileName(), std::move(Err));
Nick Kledzik56ebef42014-09-16 01:41:51 +00009952}
9953
9954//===----------------------------------------------------------------------===//
9955// lazy bind table dumping
9956//===----------------------------------------------------------------------===//
9957
Kevin Enderbya8d256c2017-03-20 19:46:55 +00009958void llvm::printMachOLazyBindTable(object::MachOObjectFile *Obj) {
Nick Kledzik5ffacc12014-09-30 00:19:58 +00009959 outs() << "segment section address "
9960 "dylib symbol\n";
Kevin Enderbyfeb63b92017-02-28 21:47:07 +00009961 Error Err = Error::success();
9962 for (const llvm::object::MachOBindEntry &Entry : Obj->lazyBindTable(Err)) {
Kevin Enderbya8d256c2017-03-20 19:46:55 +00009963 StringRef SegmentName = Entry.segmentName();
9964 StringRef SectionName = Entry.sectionName();
9965 uint64_t Address = Entry.address();
Nick Kledzik56ebef42014-09-16 01:41:51 +00009966
9967 // Table lines look like:
9968 // __DATA __got 0x00012010 libSystem ___stack_chk_guard
Kevin Enderbyb28ed012014-10-29 21:28:24 +00009969 outs() << left_justify(SegmentName, 8) << " "
Nick Kledzik5ffacc12014-09-30 00:19:58 +00009970 << left_justify(SectionName, 18) << " "
9971 << format_hex(Address, 10, true) << " "
9972 << left_justify(ordinalName(Obj, Entry.ordinal()), 16) << " "
Nick Kledzik56ebef42014-09-16 01:41:51 +00009973 << Entry.symbolName() << "\n";
9974 }
Kevin Enderbyfeb63b92017-02-28 21:47:07 +00009975 if (Err)
9976 report_error(Obj->getFileName(), std::move(Err));
Nick Kledzik56ebef42014-09-16 01:41:51 +00009977}
9978
Nick Kledzik56ebef42014-09-16 01:41:51 +00009979//===----------------------------------------------------------------------===//
9980// weak bind table dumping
9981//===----------------------------------------------------------------------===//
9982
Kevin Enderbya8d256c2017-03-20 19:46:55 +00009983void llvm::printMachOWeakBindTable(object::MachOObjectFile *Obj) {
Nick Kledzik5ffacc12014-09-30 00:19:58 +00009984 outs() << "segment section address "
9985 "type addend symbol\n";
Kevin Enderbyfeb63b92017-02-28 21:47:07 +00009986 Error Err = Error::success();
9987 for (const llvm::object::MachOBindEntry &Entry : Obj->weakBindTable(Err)) {
Nick Kledzik56ebef42014-09-16 01:41:51 +00009988 // Strong symbols don't have a location to update.
9989 if (Entry.flags() & MachO::BIND_SYMBOL_FLAGS_NON_WEAK_DEFINITION) {
Nick Kledzik5ffacc12014-09-30 00:19:58 +00009990 outs() << " strong "
Nick Kledzik56ebef42014-09-16 01:41:51 +00009991 << Entry.symbolName() << "\n";
9992 continue;
9993 }
Kevin Enderbya8d256c2017-03-20 19:46:55 +00009994 StringRef SegmentName = Entry.segmentName();
9995 StringRef SectionName = Entry.sectionName();
9996 uint64_t Address = Entry.address();
Nick Kledzik56ebef42014-09-16 01:41:51 +00009997
9998 // Table lines look like:
9999 // __DATA __data 0x00001000 pointer 0 _foo
Kevin Enderbyb28ed012014-10-29 21:28:24 +000010000 outs() << left_justify(SegmentName, 8) << " "
Nick Kledzik5ffacc12014-09-30 00:19:58 +000010001 << left_justify(SectionName, 18) << " "
10002 << format_hex(Address, 10, true) << " "
10003 << left_justify(Entry.typeName(), 8) << " "
Kevin Enderbyb28ed012014-10-29 21:28:24 +000010004 << format_decimal(Entry.addend(), 8) << " " << Entry.symbolName()
10005 << "\n";
Nick Kledzik56ebef42014-09-16 01:41:51 +000010006 }
Kevin Enderbyfeb63b92017-02-28 21:47:07 +000010007 if (Err)
10008 report_error(Obj->getFileName(), std::move(Err));
Nick Kledzik56ebef42014-09-16 01:41:51 +000010009}
10010
Kevin Enderby6f326ce2014-10-23 19:37:31 +000010011// get_dyld_bind_info_symbolname() is used for disassembly and passed an
10012// address, ReferenceValue, in the Mach-O file and looks in the dyld bind
10013// information for that address. If the address is found its binding symbol
10014// name is returned. If not nullptr is returned.
10015static const char *get_dyld_bind_info_symbolname(uint64_t ReferenceValue,
10016 struct DisassembleInfo *info) {
Kevin Enderby078be602014-10-23 19:53:12 +000010017 if (info->bindtable == nullptr) {
Saleem Abdulrasool1d84d9a2017-01-08 19:14:15 +000010018 info->bindtable = llvm::make_unique<SymbolAddressMap>();
Kevin Enderbyfeb63b92017-02-28 21:47:07 +000010019 Error Err = Error::success();
10020 for (const llvm::object::MachOBindEntry &Entry : info->O->bindTable(Err)) {
Kevin Enderbya8d256c2017-03-20 19:46:55 +000010021 uint64_t Address = Entry.address();
Kevin Enderby6f326ce2014-10-23 19:37:31 +000010022 StringRef name = Entry.symbolName();
10023 if (!name.empty())
Saleem Abdulrasool1d84d9a2017-01-08 19:14:15 +000010024 (*info->bindtable)[Address] = name;
Kevin Enderby6f326ce2014-10-23 19:37:31 +000010025 }
Kevin Enderbyfeb63b92017-02-28 21:47:07 +000010026 if (Err)
10027 report_error(info->O->getFileName(), std::move(Err));
Kevin Enderby6f326ce2014-10-23 19:37:31 +000010028 }
Saleem Abdulrasool1d84d9a2017-01-08 19:14:15 +000010029 auto name = info->bindtable->lookup(ReferenceValue);
10030 return !name.empty() ? name.data() : nullptr;
Kevin Enderby6f326ce2014-10-23 19:37:31 +000010031}
Michael Trent1854ecc2017-12-05 07:50:00 +000010032