blob: 549a20311df58998bb52f40b682c088aa923d7d0 [file] [log] [blame]
Benjamin Kramer43a772e2011-09-19 17:56:04 +00001//===-- MachODump.cpp - Object file dumping utility for llvm --------------===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Benjamin Kramer43a772e2011-09-19 17:56:04 +00006//
7//===----------------------------------------------------------------------===//
8//
9// This file implements the MachO-specific dumper for llvm-objdump.
10//
11//===----------------------------------------------------------------------===//
12
13#include "llvm-objdump.h"
Kevin Enderby98c9acc2014-09-16 18:00:57 +000014#include "llvm-c/Disassembler.h"
Benjamin Kramer43a772e2011-09-19 17:56:04 +000015#include "llvm/ADT/STLExtras.h"
Ahmed Bougachaaa790682013-05-24 01:07:04 +000016#include "llvm/ADT/StringExtras.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000017#include "llvm/ADT/Triple.h"
Zachary Turner264b5d92017-06-07 03:48:56 +000018#include "llvm/BinaryFormat/MachO.h"
Kevin Enderby04bf6932014-10-28 23:39:46 +000019#include "llvm/Config/config.h"
Zachary Turner6489d7b2015-04-23 17:37:47 +000020#include "llvm/DebugInfo/DIContext.h"
21#include "llvm/DebugInfo/DWARF/DWARFContext.h"
Rafael Espindolab940b662016-09-06 19:16:48 +000022#include "llvm/Demangle/Demangle.h"
Benjamin Kramer43a772e2011-09-19 17:56:04 +000023#include "llvm/MC/MCAsmInfo.h"
Lang Hamesa1bc0f52014-04-15 04:40:56 +000024#include "llvm/MC/MCContext.h"
Benjamin Kramerf57c1972016-01-26 16:44:37 +000025#include "llvm/MC/MCDisassembler/MCDisassembler.h"
Benjamin Kramer43a772e2011-09-19 17:56:04 +000026#include "llvm/MC/MCInst.h"
27#include "llvm/MC/MCInstPrinter.h"
Benjamin Kramer43a772e2011-09-19 17:56:04 +000028#include "llvm/MC/MCInstrDesc.h"
29#include "llvm/MC/MCInstrInfo.h"
Jim Grosbachfd93a592012-03-05 19:33:20 +000030#include "llvm/MC/MCRegisterInfo.h"
Benjamin Kramer43a772e2011-09-19 17:56:04 +000031#include "llvm/MC/MCSubtargetInfo.h"
Zachary Turner264b5d92017-06-07 03:48:56 +000032#include "llvm/Object/MachO.h"
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +000033#include "llvm/Object/MachOUniversal.h"
Rafael Espindola9b709252013-04-13 01:45:40 +000034#include "llvm/Support/Casting.h"
Benjamin Kramer43a772e2011-09-19 17:56:04 +000035#include "llvm/Support/CommandLine.h"
36#include "llvm/Support/Debug.h"
Tim Northover4bd286a2014-08-01 13:07:19 +000037#include "llvm/Support/Endian.h"
Benjamin Kramer43a772e2011-09-19 17:56:04 +000038#include "llvm/Support/Format.h"
Chandler Carruthd9903882015-01-14 11:23:27 +000039#include "llvm/Support/FormattedStream.h"
Benjamin Kramer43a772e2011-09-19 17:56:04 +000040#include "llvm/Support/GraphWriter.h"
Kevin Enderby9a509442015-01-27 21:28:24 +000041#include "llvm/Support/LEB128.h"
Benjamin Kramer43a772e2011-09-19 17:56:04 +000042#include "llvm/Support/MemoryBuffer.h"
43#include "llvm/Support/TargetRegistry.h"
44#include "llvm/Support/TargetSelect.h"
Kevin Enderby9873e2c2016-05-23 21:34:12 +000045#include "llvm/Support/ToolOutputFile.h"
Jonas Devliegheree787efd2018-11-11 22:12:04 +000046#include "llvm/Support/WithColor.h"
Benjamin Kramer43a772e2011-09-19 17:56:04 +000047#include "llvm/Support/raw_ostream.h"
Benjamin Kramer43a772e2011-09-19 17:56:04 +000048#include <algorithm>
49#include <cstring>
Rafael Espindolaa6e9c3e2014-06-12 17:38:55 +000050#include <system_error>
Kevin Enderby04bf6932014-10-28 23:39:46 +000051
Kevin Enderby9873e2c2016-05-23 21:34:12 +000052#ifdef HAVE_LIBXAR
53extern "C" {
54#include <xar/xar.h>
55}
56#endif
57
Benjamin Kramer43a772e2011-09-19 17:56:04 +000058using namespace llvm;
59using namespace object;
60
61static cl::opt<bool>
Kevin Enderbyb28ed012014-10-29 21:28:24 +000062 UseDbg("g",
63 cl::desc("Print line information from debug info if available"));
Benjamin Kramer699128e2011-09-21 01:13:19 +000064
Kevin Enderbyb28ed012014-10-29 21:28:24 +000065static cl::opt<std::string> DSYMFile("dsym",
66 cl::desc("Use .dSYM file for debug info"));
Benjamin Kramer699128e2011-09-21 01:13:19 +000067
Kevin Enderbyb28ed012014-10-29 21:28:24 +000068static cl::opt<bool> FullLeadingAddr("full-leading-addr",
69 cl::desc("Print full leading address"));
Kevin Enderbybf246f52014-09-24 23:08:22 +000070
Kevin Enderbyf9d60f02016-11-29 21:43:40 +000071static cl::opt<bool> NoLeadingHeaders("no-leading-headers",
72 cl::desc("Print no leading headers"));
73
Kevin Enderby13023a12015-01-15 23:19:11 +000074cl::opt<bool> llvm::UniversalHeaders("universal-headers",
75 cl::desc("Print Mach-O universal headers "
76 "(requires -macho)"));
77
Kevin Enderby131d1772015-01-09 19:22:37 +000078cl::opt<bool>
Kevin Enderby8972e482015-04-30 20:30:42 +000079 ArchiveMemberOffsets("archive-member-offsets",
80 cl::desc("Print the offset to each archive member for "
81 "Mach-O archives (requires -macho and "
82 "-archive-headers)"));
83
84cl::opt<bool>
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +000085 llvm::IndirectSymbols("indirect-symbols",
86 cl::desc("Print indirect symbol table for Mach-O "
87 "objects (requires -macho)"));
88
Kevin Enderby69fe98d2015-01-23 18:52:17 +000089cl::opt<bool>
90 llvm::DataInCode("data-in-code",
91 cl::desc("Print the data in code table for Mach-O objects "
92 "(requires -macho)"));
93
Kevin Enderby9a509442015-01-27 21:28:24 +000094cl::opt<bool>
95 llvm::LinkOptHints("link-opt-hints",
96 cl::desc("Print the linker optimization hints for "
97 "Mach-O objects (requires -macho)"));
98
Kevin Enderbycd66be52015-03-11 22:06:32 +000099cl::opt<bool>
100 llvm::InfoPlist("info-plist",
101 cl::desc("Print the info plist section as strings for "
102 "Mach-O objects (requires -macho)"));
103
Kevin Enderbyf0640752015-03-13 17:56:32 +0000104cl::opt<bool>
Kevin Enderbybc847fa2015-03-16 20:08:09 +0000105 llvm::DylibsUsed("dylibs-used",
106 cl::desc("Print the shared libraries used for linked "
107 "Mach-O files (requires -macho)"));
108
109cl::opt<bool>
110 llvm::DylibId("dylib-id",
111 cl::desc("Print the shared library's id for the dylib Mach-O "
112 "file (requires -macho)"));
113
114cl::opt<bool>
Kevin Enderbyf0640752015-03-13 17:56:32 +0000115 llvm::NonVerbose("non-verbose",
116 cl::desc("Print the info for Mach-O objects in "
117 "non-verbose or numeric form (requires -macho)"));
118
Kevin Enderby0fc11822015-04-01 20:57:01 +0000119cl::opt<bool>
120 llvm::ObjcMetaData("objc-meta-data",
121 cl::desc("Print the Objective-C runtime meta data for "
122 "Mach-O files (requires -macho)"));
123
Kevin Enderby6a221752015-03-17 17:10:57 +0000124cl::opt<std::string> llvm::DisSymName(
125 "dis-symname",
Saleem Abdulrasoolec6a7742016-09-08 23:17:34 +0000126 cl::desc("disassemble just this symbol's instructions (requires -macho)"));
Kevin Enderby6a221752015-03-17 17:10:57 +0000127
Kevin Enderby8e29ec92015-03-17 22:26:11 +0000128static cl::opt<bool> NoSymbolicOperands(
129 "no-symbolic-operands",
130 cl::desc("do not symbolic operands when disassembling (requires -macho)"));
131
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +0000132static cl::list<std::string>
133 ArchFlags("arch", cl::desc("architecture(s) from a Mach-O file to dump"),
134 cl::ZeroOrMore);
Hans Wennborgcc9deb42015-09-29 18:02:48 +0000135
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +0000136bool ArchAll = false;
137
Kevin Enderbyec5ca032014-08-18 20:21:02 +0000138static std::string ThumbTripleName;
139
140static const Target *GetTarget(const MachOObjectFile *MachOObj,
141 const char **McpuDefault,
142 const Target **ThumbTarget) {
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000143 // Figure out the target triple.
Tim Northover9e8eb412016-04-22 23:21:13 +0000144 llvm::Triple TT(TripleName);
Cameron Zwarich88cc16a2012-02-03 06:35:22 +0000145 if (TripleName.empty()) {
Tim Northover9e8eb412016-04-22 23:21:13 +0000146 TT = MachOObj->getArchTriple(McpuDefault);
Cameron Zwarich88cc16a2012-02-03 06:35:22 +0000147 TripleName = TT.str();
Tim Northover9e8eb412016-04-22 23:21:13 +0000148 }
149
150 if (TT.getArch() == Triple::arm) {
151 // We've inferred a 32-bit ARM target from the object file. All MachO CPUs
152 // that support ARM are also capable of Thumb mode.
153 llvm::Triple ThumbTriple = TT;
154 std::string ThumbName = (Twine("thumb") + TT.getArchName().substr(3)).str();
155 ThumbTriple.setArchName(ThumbName);
Kevin Enderbyec5ca032014-08-18 20:21:02 +0000156 ThumbTripleName = ThumbTriple.str();
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000157 }
158
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000159 // Get the target specific parser.
160 std::string Error;
161 const Target *TheTarget = TargetRegistry::lookupTarget(TripleName, Error);
Kevin Enderbyec5ca032014-08-18 20:21:02 +0000162 if (TheTarget && ThumbTripleName.empty())
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000163 return TheTarget;
164
Kevin Enderbyec5ca032014-08-18 20:21:02 +0000165 *ThumbTarget = TargetRegistry::lookupTarget(ThumbTripleName, Error);
166 if (*ThumbTarget)
167 return TheTarget;
168
Jonas Devliegheree787efd2018-11-11 22:12:04 +0000169 WithColor::error(errs(), "llvm-objdump") << "unable to get target for '";
Kevin Enderbyec5ca032014-08-18 20:21:02 +0000170 if (!TheTarget)
171 errs() << TripleName;
172 else
173 errs() << ThumbTripleName;
174 errs() << "', see --version and --triple.\n";
Craig Toppere6cb63e2014-04-25 04:24:47 +0000175 return nullptr;
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000176}
177
Owen Andersond9243c42011-10-17 21:37:35 +0000178struct SymbolSorter {
179 bool operator()(const SymbolRef &A, const SymbolRef &B) {
Kevin Enderby7bd8d992016-05-02 20:28:12 +0000180 Expected<SymbolRef::Type> ATypeOrErr = A.getType();
Kevin Enderby844c4ac2016-11-15 23:07:41 +0000181 if (!ATypeOrErr)
182 report_error(A.getObject()->getFileName(), ATypeOrErr.takeError());
Kevin Enderby5afbc1c2016-03-23 20:27:00 +0000183 SymbolRef::Type AType = *ATypeOrErr;
Kevin Enderby7bd8d992016-05-02 20:28:12 +0000184 Expected<SymbolRef::Type> BTypeOrErr = B.getType();
Kevin Enderby844c4ac2016-11-15 23:07:41 +0000185 if (!BTypeOrErr)
186 report_error(B.getObject()->getFileName(), BTypeOrErr.takeError());
Kevin Enderby74f58d42016-03-23 21:45:21 +0000187 SymbolRef::Type BType = *BTypeOrErr;
Kevin Enderby5afbc1c2016-03-23 20:27:00 +0000188 uint64_t AAddr = (AType != SymbolRef::ST_Function) ? 0 : A.getValue();
189 uint64_t BAddr = (BType != SymbolRef::ST_Function) ? 0 : B.getValue();
Owen Andersond9243c42011-10-17 21:37:35 +0000190 return AAddr < BAddr;
191 }
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000192};
193
Kevin Enderby273ae012013-06-06 17:20:50 +0000194// Types for the storted data in code table that is built before disassembly
195// and the predicate function to sort them.
196typedef std::pair<uint64_t, DiceRef> DiceTableEntry;
197typedef std::vector<DiceTableEntry> DiceTable;
198typedef DiceTable::iterator dice_table_iterator;
199
Francis Ricci195a66f2017-10-06 15:54:20 +0000200#ifdef HAVE_LIBXAR
Francis Ricci6f942972017-10-06 15:33:28 +0000201namespace {
202struct ScopedXarFile {
203 xar_t xar;
Francis Ricci57d84522017-10-09 20:27:14 +0000204 ScopedXarFile(const char *filename, int32_t flags)
205 : xar(xar_open(filename, flags)) {}
Francis Ricci6f942972017-10-06 15:33:28 +0000206 ~ScopedXarFile() {
207 if (xar)
208 xar_close(xar);
209 }
210 ScopedXarFile(const ScopedXarFile &) = delete;
211 ScopedXarFile &operator=(const ScopedXarFile &) = delete;
212 operator xar_t() { return xar; }
213};
214
215struct ScopedXarIter {
216 xar_iter_t iter;
Francis Ricci57d84522017-10-09 20:27:14 +0000217 ScopedXarIter() : iter(xar_iter_new()) {}
Francis Ricci6f942972017-10-06 15:33:28 +0000218 ~ScopedXarIter() {
219 if (iter)
220 xar_iter_free(iter);
221 }
222 ScopedXarIter(const ScopedXarIter &) = delete;
223 ScopedXarIter &operator=(const ScopedXarIter &) = delete;
224 operator xar_iter_t() { return iter; }
225};
226} // namespace
Francis Ricci195a66f2017-10-06 15:54:20 +0000227#endif // defined(HAVE_LIBXAR)
Francis Ricci6f942972017-10-06 15:33:28 +0000228
Kevin Enderby930fdc72014-11-06 19:00:13 +0000229// This is used to search for a data in code table entry for the PC being
230// disassembled. The j parameter has the PC in j.first. A single data in code
231// table entry can cover many bytes for each of its Kind's. So if the offset,
232// aka the i.first value, of the data in code table entry plus its Length
233// covers the PC being searched for this will return true. If not it will
234// return false.
David Majnemerea9b8ee2014-11-04 08:41:48 +0000235static bool compareDiceTableEntries(const DiceTableEntry &i,
236 const DiceTableEntry &j) {
Kevin Enderby930fdc72014-11-06 19:00:13 +0000237 uint16_t Length;
238 i.second.getLength(Length);
239
240 return j.first >= i.first && j.first < i.first + Length;
Kevin Enderby273ae012013-06-06 17:20:50 +0000241}
242
Colin LeMahieufc32b1b2015-03-18 19:27:31 +0000243static uint64_t DumpDataInCode(const uint8_t *bytes, uint64_t Length,
Kevin Enderby930fdc72014-11-06 19:00:13 +0000244 unsigned short Kind) {
245 uint32_t Value, Size = 1;
Kevin Enderby273ae012013-06-06 17:20:50 +0000246
247 switch (Kind) {
Kevin Enderby930fdc72014-11-06 19:00:13 +0000248 default:
Charles Davis8bdfafd2013-09-01 04:28:48 +0000249 case MachO::DICE_KIND_DATA:
Kevin Enderby930fdc72014-11-06 19:00:13 +0000250 if (Length >= 4) {
251 if (!NoShowRawInsn)
Craig Topper0013be12015-09-21 05:32:41 +0000252 dumpBytes(makeArrayRef(bytes, 4), outs());
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000253 Value = bytes[3] << 24 | bytes[2] << 16 | bytes[1] << 8 | bytes[0];
Kevin Enderby273ae012013-06-06 17:20:50 +0000254 outs() << "\t.long " << Value;
Kevin Enderby930fdc72014-11-06 19:00:13 +0000255 Size = 4;
256 } else if (Length >= 2) {
257 if (!NoShowRawInsn)
Craig Topper0013be12015-09-21 05:32:41 +0000258 dumpBytes(makeArrayRef(bytes, 2), outs());
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000259 Value = bytes[1] << 8 | bytes[0];
Kevin Enderby273ae012013-06-06 17:20:50 +0000260 outs() << "\t.short " << Value;
Kevin Enderby930fdc72014-11-06 19:00:13 +0000261 Size = 2;
262 } else {
263 if (!NoShowRawInsn)
Craig Topper0013be12015-09-21 05:32:41 +0000264 dumpBytes(makeArrayRef(bytes, 2), outs());
Kevin Enderby273ae012013-06-06 17:20:50 +0000265 Value = bytes[0];
266 outs() << "\t.byte " << Value;
Kevin Enderby930fdc72014-11-06 19:00:13 +0000267 Size = 1;
Kevin Enderby273ae012013-06-06 17:20:50 +0000268 }
Kevin Enderby930fdc72014-11-06 19:00:13 +0000269 if (Kind == MachO::DICE_KIND_DATA)
270 outs() << "\t@ KIND_DATA\n";
271 else
272 outs() << "\t@ data in code kind = " << Kind << "\n";
Kevin Enderby273ae012013-06-06 17:20:50 +0000273 break;
Charles Davis8bdfafd2013-09-01 04:28:48 +0000274 case MachO::DICE_KIND_JUMP_TABLE8:
Kevin Enderby930fdc72014-11-06 19:00:13 +0000275 if (!NoShowRawInsn)
Craig Topper0013be12015-09-21 05:32:41 +0000276 dumpBytes(makeArrayRef(bytes, 1), outs());
Kevin Enderby273ae012013-06-06 17:20:50 +0000277 Value = bytes[0];
Kevin Enderby930fdc72014-11-06 19:00:13 +0000278 outs() << "\t.byte " << format("%3u", Value) << "\t@ KIND_JUMP_TABLE8\n";
279 Size = 1;
Kevin Enderby273ae012013-06-06 17:20:50 +0000280 break;
Charles Davis8bdfafd2013-09-01 04:28:48 +0000281 case MachO::DICE_KIND_JUMP_TABLE16:
Kevin Enderby930fdc72014-11-06 19:00:13 +0000282 if (!NoShowRawInsn)
Craig Topper0013be12015-09-21 05:32:41 +0000283 dumpBytes(makeArrayRef(bytes, 2), outs());
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000284 Value = bytes[1] << 8 | bytes[0];
Kevin Enderby930fdc72014-11-06 19:00:13 +0000285 outs() << "\t.short " << format("%5u", Value & 0xffff)
286 << "\t@ KIND_JUMP_TABLE16\n";
287 Size = 2;
Kevin Enderby273ae012013-06-06 17:20:50 +0000288 break;
Charles Davis8bdfafd2013-09-01 04:28:48 +0000289 case MachO::DICE_KIND_JUMP_TABLE32:
Kevin Enderby930fdc72014-11-06 19:00:13 +0000290 case MachO::DICE_KIND_ABS_JUMP_TABLE32:
291 if (!NoShowRawInsn)
Craig Topper0013be12015-09-21 05:32:41 +0000292 dumpBytes(makeArrayRef(bytes, 4), outs());
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000293 Value = bytes[3] << 24 | bytes[2] << 16 | bytes[1] << 8 | bytes[0];
Kevin Enderby930fdc72014-11-06 19:00:13 +0000294 outs() << "\t.long " << Value;
295 if (Kind == MachO::DICE_KIND_JUMP_TABLE32)
296 outs() << "\t@ KIND_JUMP_TABLE32\n";
297 else
298 outs() << "\t@ KIND_ABS_JUMP_TABLE32\n";
299 Size = 4;
Kevin Enderby273ae012013-06-06 17:20:50 +0000300 break;
301 }
Kevin Enderby930fdc72014-11-06 19:00:13 +0000302 return Size;
Kevin Enderby273ae012013-06-06 17:20:50 +0000303}
304
Alexey Samsonovd319c4f2015-06-03 22:19:36 +0000305static void getSectionsAndSymbols(MachOObjectFile *MachOObj,
Alexey Samsonov464d2e42014-03-17 07:28:19 +0000306 std::vector<SectionRef> &Sections,
307 std::vector<SymbolRef> &Symbols,
308 SmallVectorImpl<uint64_t> &FoundFns,
309 uint64_t &BaseSegmentAddress) {
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +0000310 for (const SymbolRef &Symbol : MachOObj->symbols()) {
Kevin Enderby81e8b7d2016-04-20 21:24:34 +0000311 Expected<StringRef> SymName = Symbol.getName();
Kevin Enderby844c4ac2016-11-15 23:07:41 +0000312 if (!SymName)
313 report_error(MachOObj->getFileName(), SymName.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +0000314 if (!SymName->startswith("ltmp"))
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +0000315 Symbols.push_back(Symbol);
316 }
Owen Andersond9243c42011-10-17 21:37:35 +0000317
Alexey Samsonov48803e52014-03-13 14:37:36 +0000318 for (const SectionRef &Section : MachOObj->sections()) {
Owen Andersond9243c42011-10-17 21:37:35 +0000319 StringRef SectName;
Alexey Samsonov48803e52014-03-13 14:37:36 +0000320 Section.getName(SectName);
321 Sections.push_back(Section);
Owen Andersond9243c42011-10-17 21:37:35 +0000322 }
323
Kevin Enderby273ae012013-06-06 17:20:50 +0000324 bool BaseSegmentAddressSet = false;
Alexey Samsonovd319c4f2015-06-03 22:19:36 +0000325 for (const auto &Command : MachOObj->load_commands()) {
Charles Davis8bdfafd2013-09-01 04:28:48 +0000326 if (Command.C.cmd == MachO::LC_FUNCTION_STARTS) {
Benjamin Kramer699128e2011-09-21 01:13:19 +0000327 // We found a function starts segment, parse the addresses for later
328 // consumption.
Charles Davis8bdfafd2013-09-01 04:28:48 +0000329 MachO::linkedit_data_command LLC =
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000330 MachOObj->getLinkeditDataLoadCommand(Command);
Benjamin Kramer699128e2011-09-21 01:13:19 +0000331
Charles Davis8bdfafd2013-09-01 04:28:48 +0000332 MachOObj->ReadULEB128s(LLC.dataoff, FoundFns);
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000333 } else if (Command.C.cmd == MachO::LC_SEGMENT) {
334 MachO::segment_command SLC = MachOObj->getSegmentLoadCommand(Command);
Charles Davis8bdfafd2013-09-01 04:28:48 +0000335 StringRef SegName = SLC.segname;
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000336 if (!BaseSegmentAddressSet && SegName != "__PAGEZERO") {
Kevin Enderby273ae012013-06-06 17:20:50 +0000337 BaseSegmentAddressSet = true;
Charles Davis8bdfafd2013-09-01 04:28:48 +0000338 BaseSegmentAddress = SLC.vmaddr;
Kevin Enderby273ae012013-06-06 17:20:50 +0000339 }
340 }
Benjamin Kramer8a529dc2011-09-21 22:16:43 +0000341 }
Benjamin Kramer699128e2011-09-21 01:13:19 +0000342}
343
George Rimarc1964882019-01-18 11:33:26 +0000344static void printRelocationTargetName(const MachOObjectFile *O,
345 const MachO::any_relocation_info &RE,
346 raw_string_ostream &Fmt) {
347 // Target of a scattered relocation is an address. In the interest of
348 // generating pretty output, scan through the symbol table looking for a
349 // symbol that aligns with that address. If we find one, print it.
350 // Otherwise, we just print the hex address of the target.
351 if (O->isRelocationScattered(RE)) {
352 uint32_t Val = O->getPlainRelocationSymbolNum(RE);
353
354 for (const SymbolRef &Symbol : O->symbols()) {
355 Expected<uint64_t> Addr = Symbol.getAddress();
356 if (!Addr)
357 report_error(O->getFileName(), Addr.takeError());
358 if (*Addr != Val)
359 continue;
360 Expected<StringRef> Name = Symbol.getName();
361 if (!Name)
362 report_error(O->getFileName(), Name.takeError());
363 Fmt << *Name;
364 return;
365 }
366
367 // If we couldn't find a symbol that this relocation refers to, try
368 // to find a section beginning instead.
369 for (const SectionRef &Section : ToolSectionFilter(*O)) {
370 std::error_code ec;
371
372 StringRef Name;
373 uint64_t Addr = Section.getAddress();
374 if (Addr != Val)
375 continue;
376 if ((ec = Section.getName(Name)))
377 report_error(O->getFileName(), ec);
378 Fmt << Name;
379 return;
380 }
381
382 Fmt << format("0x%x", Val);
383 return;
384 }
385
386 StringRef S;
387 bool isExtern = O->getPlainRelocationExternal(RE);
388 uint64_t Val = O->getPlainRelocationSymbolNum(RE);
389
390 if (O->getAnyRelocationType(RE) == MachO::ARM64_RELOC_ADDEND) {
391 Fmt << format("0x%0" PRIx64, Val);
392 return;
393 }
394
395 if (isExtern) {
396 symbol_iterator SI = O->symbol_begin();
397 advance(SI, Val);
398 Expected<StringRef> SOrErr = SI->getName();
399 if (!SOrErr)
400 report_error(O->getFileName(), SOrErr.takeError());
401 S = *SOrErr;
402 } else {
403 section_iterator SI = O->section_begin();
404 // Adjust for the fact that sections are 1-indexed.
405 if (Val == 0) {
406 Fmt << "0 (?,?)";
407 return;
408 }
409 uint32_t I = Val - 1;
410 while (I != 0 && SI != O->section_end()) {
411 --I;
412 advance(SI, 1);
413 }
414 if (SI == O->section_end())
415 Fmt << Val << " (?,?)";
416 else
417 SI->getName(S);
418 }
419
420 Fmt << S;
421}
422
423std::error_code
424llvm::getMachORelocationValueString(const MachOObjectFile *Obj,
425 const RelocationRef &RelRef,
426 SmallVectorImpl<char> &Result) {
427 DataRefImpl Rel = RelRef.getRawDataRefImpl();
428 MachO::any_relocation_info RE = Obj->getRelocation(Rel);
429
430 unsigned Arch = Obj->getArch();
431
432 std::string FmtBuf;
433 raw_string_ostream Fmt(FmtBuf);
434 unsigned Type = Obj->getAnyRelocationType(RE);
435 bool IsPCRel = Obj->getAnyRelocationPCRel(RE);
436
437 // Determine any addends that should be displayed with the relocation.
438 // These require decoding the relocation type, which is triple-specific.
439
440 // X86_64 has entirely custom relocation types.
441 if (Arch == Triple::x86_64) {
442 switch (Type) {
443 case MachO::X86_64_RELOC_GOT_LOAD:
444 case MachO::X86_64_RELOC_GOT: {
445 printRelocationTargetName(Obj, RE, Fmt);
446 Fmt << "@GOT";
447 if (IsPCRel)
448 Fmt << "PCREL";
449 break;
450 }
451 case MachO::X86_64_RELOC_SUBTRACTOR: {
452 DataRefImpl RelNext = Rel;
453 Obj->moveRelocationNext(RelNext);
454 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
455
456 // X86_64_RELOC_SUBTRACTOR must be followed by a relocation of type
457 // X86_64_RELOC_UNSIGNED.
458 // NOTE: Scattered relocations don't exist on x86_64.
459 unsigned RType = Obj->getAnyRelocationType(RENext);
460 if (RType != MachO::X86_64_RELOC_UNSIGNED)
461 report_error(Obj->getFileName(), "Expected X86_64_RELOC_UNSIGNED after "
462 "X86_64_RELOC_SUBTRACTOR.");
463
464 // The X86_64_RELOC_UNSIGNED contains the minuend symbol;
465 // X86_64_RELOC_SUBTRACTOR contains the subtrahend.
466 printRelocationTargetName(Obj, RENext, Fmt);
467 Fmt << "-";
468 printRelocationTargetName(Obj, RE, Fmt);
469 break;
470 }
471 case MachO::X86_64_RELOC_TLV:
472 printRelocationTargetName(Obj, RE, Fmt);
473 Fmt << "@TLV";
474 if (IsPCRel)
475 Fmt << "P";
476 break;
477 case MachO::X86_64_RELOC_SIGNED_1:
478 printRelocationTargetName(Obj, RE, Fmt);
479 Fmt << "-1";
480 break;
481 case MachO::X86_64_RELOC_SIGNED_2:
482 printRelocationTargetName(Obj, RE, Fmt);
483 Fmt << "-2";
484 break;
485 case MachO::X86_64_RELOC_SIGNED_4:
486 printRelocationTargetName(Obj, RE, Fmt);
487 Fmt << "-4";
488 break;
489 default:
490 printRelocationTargetName(Obj, RE, Fmt);
491 break;
492 }
493 // X86 and ARM share some relocation types in common.
494 } else if (Arch == Triple::x86 || Arch == Triple::arm ||
495 Arch == Triple::ppc) {
496 // Generic relocation types...
497 switch (Type) {
498 case MachO::GENERIC_RELOC_PAIR: // prints no info
499 return std::error_code();
500 case MachO::GENERIC_RELOC_SECTDIFF: {
501 DataRefImpl RelNext = Rel;
502 Obj->moveRelocationNext(RelNext);
503 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
504
505 // X86 sect diff's must be followed by a relocation of type
506 // GENERIC_RELOC_PAIR.
507 unsigned RType = Obj->getAnyRelocationType(RENext);
508
509 if (RType != MachO::GENERIC_RELOC_PAIR)
510 report_error(Obj->getFileName(), "Expected GENERIC_RELOC_PAIR after "
511 "GENERIC_RELOC_SECTDIFF.");
512
513 printRelocationTargetName(Obj, RE, Fmt);
514 Fmt << "-";
515 printRelocationTargetName(Obj, RENext, Fmt);
516 break;
517 }
518 }
519
520 if (Arch == Triple::x86 || Arch == Triple::ppc) {
521 switch (Type) {
522 case MachO::GENERIC_RELOC_LOCAL_SECTDIFF: {
523 DataRefImpl RelNext = Rel;
524 Obj->moveRelocationNext(RelNext);
525 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
526
527 // X86 sect diff's must be followed by a relocation of type
528 // GENERIC_RELOC_PAIR.
529 unsigned RType = Obj->getAnyRelocationType(RENext);
530 if (RType != MachO::GENERIC_RELOC_PAIR)
531 report_error(Obj->getFileName(), "Expected GENERIC_RELOC_PAIR after "
532 "GENERIC_RELOC_LOCAL_SECTDIFF.");
533
534 printRelocationTargetName(Obj, RE, Fmt);
535 Fmt << "-";
536 printRelocationTargetName(Obj, RENext, Fmt);
537 break;
538 }
539 case MachO::GENERIC_RELOC_TLV: {
540 printRelocationTargetName(Obj, RE, Fmt);
541 Fmt << "@TLV";
542 if (IsPCRel)
543 Fmt << "P";
544 break;
545 }
546 default:
547 printRelocationTargetName(Obj, RE, Fmt);
548 }
549 } else { // ARM-specific relocations
550 switch (Type) {
551 case MachO::ARM_RELOC_HALF:
552 case MachO::ARM_RELOC_HALF_SECTDIFF: {
553 // Half relocations steal a bit from the length field to encode
554 // whether this is an upper16 or a lower16 relocation.
555 bool isUpper = (Obj->getAnyRelocationLength(RE) & 0x1) == 1;
556
557 if (isUpper)
558 Fmt << ":upper16:(";
559 else
560 Fmt << ":lower16:(";
561 printRelocationTargetName(Obj, RE, Fmt);
562
563 DataRefImpl RelNext = Rel;
564 Obj->moveRelocationNext(RelNext);
565 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
566
567 // ARM half relocs must be followed by a relocation of type
568 // ARM_RELOC_PAIR.
569 unsigned RType = Obj->getAnyRelocationType(RENext);
570 if (RType != MachO::ARM_RELOC_PAIR)
571 report_error(Obj->getFileName(), "Expected ARM_RELOC_PAIR after "
572 "ARM_RELOC_HALF");
573
574 // NOTE: The half of the target virtual address is stashed in the
575 // address field of the secondary relocation, but we can't reverse
576 // engineer the constant offset from it without decoding the movw/movt
577 // instruction to find the other half in its immediate field.
578
579 // ARM_RELOC_HALF_SECTDIFF encodes the second section in the
580 // symbol/section pointer of the follow-on relocation.
581 if (Type == MachO::ARM_RELOC_HALF_SECTDIFF) {
582 Fmt << "-";
583 printRelocationTargetName(Obj, RENext, Fmt);
584 }
585
586 Fmt << ")";
587 break;
588 }
589 default: {
590 printRelocationTargetName(Obj, RE, Fmt);
591 }
592 }
593 }
594 } else
595 printRelocationTargetName(Obj, RE, Fmt);
596
597 Fmt.flush();
598 Result.append(FmtBuf.begin(), FmtBuf.end());
599 return std::error_code();
600}
601
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +0000602static void PrintIndirectSymbolTable(MachOObjectFile *O, bool verbose,
603 uint32_t n, uint32_t count,
604 uint32_t stride, uint64_t addr) {
605 MachO::dysymtab_command Dysymtab = O->getDysymtabLoadCommand();
606 uint32_t nindirectsyms = Dysymtab.nindirectsyms;
607 if (n > nindirectsyms)
608 outs() << " (entries start past the end of the indirect symbol "
609 "table) (reserved1 field greater than the table size)";
610 else if (n + count > nindirectsyms)
611 outs() << " (entries extends past the end of the indirect symbol "
612 "table)";
613 outs() << "\n";
614 uint32_t cputype = O->getHeader().cputype;
615 if (cputype & MachO::CPU_ARCH_ABI64)
616 outs() << "address index";
617 else
618 outs() << "address index";
619 if (verbose)
620 outs() << " name\n";
621 else
622 outs() << "\n";
623 for (uint32_t j = 0; j < count && n + j < nindirectsyms; j++) {
624 if (cputype & MachO::CPU_ARCH_ABI64)
625 outs() << format("0x%016" PRIx64, addr + j * stride) << " ";
626 else
Tim Northover43978372016-04-26 18:29:16 +0000627 outs() << format("0x%08" PRIx32, (uint32_t)addr + j * stride) << " ";
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +0000628 MachO::dysymtab_command Dysymtab = O->getDysymtabLoadCommand();
629 uint32_t indirect_symbol = O->getIndirectSymbolTableEntry(Dysymtab, n + j);
630 if (indirect_symbol == MachO::INDIRECT_SYMBOL_LOCAL) {
631 outs() << "LOCAL\n";
632 continue;
633 }
634 if (indirect_symbol ==
635 (MachO::INDIRECT_SYMBOL_LOCAL | MachO::INDIRECT_SYMBOL_ABS)) {
636 outs() << "LOCAL ABSOLUTE\n";
637 continue;
638 }
639 if (indirect_symbol == MachO::INDIRECT_SYMBOL_ABS) {
640 outs() << "ABSOLUTE\n";
641 continue;
642 }
643 outs() << format("%5u ", indirect_symbol);
Kevin Enderbyf0640752015-03-13 17:56:32 +0000644 if (verbose) {
645 MachO::symtab_command Symtab = O->getSymtabLoadCommand();
646 if (indirect_symbol < Symtab.nsyms) {
647 symbol_iterator Sym = O->getSymbolByIndex(indirect_symbol);
648 SymbolRef Symbol = *Sym;
Kevin Enderby81e8b7d2016-04-20 21:24:34 +0000649 Expected<StringRef> SymName = Symbol.getName();
Kevin Enderby844c4ac2016-11-15 23:07:41 +0000650 if (!SymName)
651 report_error(O->getFileName(), SymName.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +0000652 outs() << *SymName;
Kevin Enderbyf0640752015-03-13 17:56:32 +0000653 } else {
654 outs() << "?";
655 }
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +0000656 }
657 outs() << "\n";
658 }
659}
660
661static void PrintIndirectSymbols(MachOObjectFile *O, bool verbose) {
Alexey Samsonovd319c4f2015-06-03 22:19:36 +0000662 for (const auto &Load : O->load_commands()) {
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +0000663 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
664 MachO::segment_command_64 Seg = O->getSegment64LoadCommand(Load);
665 for (unsigned J = 0; J < Seg.nsects; ++J) {
666 MachO::section_64 Sec = O->getSection64(Load, J);
667 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
668 if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
669 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
670 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
671 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
672 section_type == MachO::S_SYMBOL_STUBS) {
673 uint32_t stride;
674 if (section_type == MachO::S_SYMBOL_STUBS)
675 stride = Sec.reserved2;
676 else
677 stride = 8;
678 if (stride == 0) {
679 outs() << "Can't print indirect symbols for (" << Sec.segname << ","
680 << Sec.sectname << ") "
681 << "(size of stubs in reserved2 field is zero)\n";
682 continue;
683 }
684 uint32_t count = Sec.size / stride;
685 outs() << "Indirect symbols for (" << Sec.segname << ","
686 << Sec.sectname << ") " << count << " entries";
687 uint32_t n = Sec.reserved1;
688 PrintIndirectSymbolTable(O, verbose, n, count, stride, Sec.addr);
689 }
690 }
691 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
692 MachO::segment_command Seg = O->getSegmentLoadCommand(Load);
693 for (unsigned J = 0; J < Seg.nsects; ++J) {
694 MachO::section Sec = O->getSection(Load, J);
695 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
696 if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
697 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
698 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
699 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
700 section_type == MachO::S_SYMBOL_STUBS) {
701 uint32_t stride;
702 if (section_type == MachO::S_SYMBOL_STUBS)
703 stride = Sec.reserved2;
704 else
705 stride = 4;
706 if (stride == 0) {
707 outs() << "Can't print indirect symbols for (" << Sec.segname << ","
708 << Sec.sectname << ") "
709 << "(size of stubs in reserved2 field is zero)\n";
710 continue;
711 }
712 uint32_t count = Sec.size / stride;
713 outs() << "Indirect symbols for (" << Sec.segname << ","
714 << Sec.sectname << ") " << count << " entries";
715 uint32_t n = Sec.reserved1;
716 PrintIndirectSymbolTable(O, verbose, n, count, stride, Sec.addr);
717 }
718 }
719 }
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +0000720 }
721}
722
Michael Trenta1703b12017-12-15 17:57:40 +0000723static void PrintRType(const uint64_t cputype, const unsigned r_type) {
724 static char const *generic_r_types[] = {
725 "VANILLA ", "PAIR ", "SECTDIF ", "PBLAPTR ", "LOCSDIF ", "TLV ",
726 " 6 (?) ", " 7 (?) ", " 8 (?) ", " 9 (?) ", " 10 (?) ", " 11 (?) ",
727 " 12 (?) ", " 13 (?) ", " 14 (?) ", " 15 (?) "
728 };
729 static char const *x86_64_r_types[] = {
730 "UNSIGND ", "SIGNED ", "BRANCH ", "GOT_LD ", "GOT ", "SUB ",
731 "SIGNED1 ", "SIGNED2 ", "SIGNED4 ", "TLV ", " 10 (?) ", " 11 (?) ",
732 " 12 (?) ", " 13 (?) ", " 14 (?) ", " 15 (?) "
733 };
734 static char const *arm_r_types[] = {
735 "VANILLA ", "PAIR ", "SECTDIFF", "LOCSDIF ", "PBLAPTR ",
736 "BR24 ", "T_BR22 ", "T_BR32 ", "HALF ", "HALFDIF ",
737 " 10 (?) ", " 11 (?) ", " 12 (?) ", " 13 (?) ", " 14 (?) ", " 15 (?) "
738 };
739 static char const *arm64_r_types[] = {
740 "UNSIGND ", "SUB ", "BR26 ", "PAGE21 ", "PAGOF12 ",
741 "GOTLDP ", "GOTLDPOF", "PTRTGOT ", "TLVLDP ", "TLVLDPOF",
742 "ADDEND ", " 11 (?) ", " 12 (?) ", " 13 (?) ", " 14 (?) ", " 15 (?) "
743 };
Jonas Devliegheree787efd2018-11-11 22:12:04 +0000744
Michael Trenta1703b12017-12-15 17:57:40 +0000745 if (r_type > 0xf){
746 outs() << format("%-7u", r_type) << " ";
747 return;
748 }
749 switch (cputype) {
750 case MachO::CPU_TYPE_I386:
751 outs() << generic_r_types[r_type];
752 break;
753 case MachO::CPU_TYPE_X86_64:
754 outs() << x86_64_r_types[r_type];
755 break;
756 case MachO::CPU_TYPE_ARM:
757 outs() << arm_r_types[r_type];
758 break;
759 case MachO::CPU_TYPE_ARM64:
760 outs() << arm64_r_types[r_type];
761 break;
762 default:
763 outs() << format("%-7u ", r_type);
764 }
765}
766
767static void PrintRLength(const uint64_t cputype, const unsigned r_type,
768 const unsigned r_length, const bool previous_arm_half){
769 if (cputype == MachO::CPU_TYPE_ARM &&
770 (r_type == llvm::MachO::ARM_RELOC_HALF ||
771 r_type == llvm::MachO::ARM_RELOC_HALF_SECTDIFF ||
772 previous_arm_half == true)) {
773 if ((r_length & 0x1) == 0)
774 outs() << "lo/";
775 else
776 outs() << "hi/";
777 if ((r_length & 0x1) == 0)
778 outs() << "arm ";
779 else
780 outs() << "thm ";
781 } else {
782 switch (r_length) {
783 case 0:
784 outs() << "byte ";
785 break;
786 case 1:
787 outs() << "word ";
788 break;
789 case 2:
790 outs() << "long ";
791 break;
792 case 3:
793 if (cputype == MachO::CPU_TYPE_X86_64)
794 outs() << "quad ";
795 else
796 outs() << format("?(%2d) ", r_length);
797 break;
798 default:
799 outs() << format("?(%2d) ", r_length);
800 }
801 }
802}
803
804static void PrintRelocationEntries(const MachOObjectFile *O,
805 const relocation_iterator Begin,
806 const relocation_iterator End,
807 const uint64_t cputype,
808 const bool verbose) {
809 const MachO::symtab_command Symtab = O->getSymtabLoadCommand();
810 bool previous_arm_half = false;
811 bool previous_sectdiff = false;
812 uint32_t sectdiff_r_type = 0;
Jonas Devliegheree787efd2018-11-11 22:12:04 +0000813
Michael Trenta1703b12017-12-15 17:57:40 +0000814 for (relocation_iterator Reloc = Begin; Reloc != End; ++Reloc) {
815 const DataRefImpl Rel = Reloc->getRawDataRefImpl();
816 const MachO::any_relocation_info RE = O->getRelocation(Rel);
817 const unsigned r_type = O->getAnyRelocationType(RE);
818 const bool r_scattered = O->isRelocationScattered(RE);
819 const unsigned r_pcrel = O->getAnyRelocationPCRel(RE);
820 const unsigned r_length = O->getAnyRelocationLength(RE);
821 const unsigned r_address = O->getAnyRelocationAddress(RE);
822 const bool r_extern = (r_scattered ? false :
823 O->getPlainRelocationExternal(RE));
824 const uint32_t r_value = (r_scattered ?
825 O->getScatteredRelocationValue(RE) : 0);
826 const unsigned r_symbolnum = (r_scattered ? 0 :
827 O->getPlainRelocationSymbolNum(RE));
Jonas Devliegheree787efd2018-11-11 22:12:04 +0000828
Michael Trenta1703b12017-12-15 17:57:40 +0000829 if (r_scattered && cputype != MachO::CPU_TYPE_X86_64) {
830 if (verbose) {
831 // scattered: address
832 if ((cputype == MachO::CPU_TYPE_I386 &&
833 r_type == llvm::MachO::GENERIC_RELOC_PAIR) ||
834 (cputype == MachO::CPU_TYPE_ARM &&
835 r_type == llvm::MachO::ARM_RELOC_PAIR))
836 outs() << " ";
837 else
838 outs() << format("%08x ", (unsigned int)r_address);
Jonas Devliegheree787efd2018-11-11 22:12:04 +0000839
Michael Trenta1703b12017-12-15 17:57:40 +0000840 // scattered: pcrel
841 if (r_pcrel)
842 outs() << "True ";
843 else
844 outs() << "False ";
Jonas Devliegheree787efd2018-11-11 22:12:04 +0000845
Michael Trenta1703b12017-12-15 17:57:40 +0000846 // scattered: length
847 PrintRLength(cputype, r_type, r_length, previous_arm_half);
Jonas Devliegheree787efd2018-11-11 22:12:04 +0000848
Michael Trenta1703b12017-12-15 17:57:40 +0000849 // scattered: extern & type
850 outs() << "n/a ";
851 PrintRType(cputype, r_type);
Jonas Devliegheree787efd2018-11-11 22:12:04 +0000852
Michael Trenta1703b12017-12-15 17:57:40 +0000853 // scattered: scattered & value
854 outs() << format("True 0x%08x", (unsigned int)r_value);
855 if (previous_sectdiff == false) {
856 if ((cputype == MachO::CPU_TYPE_ARM &&
857 r_type == llvm::MachO::ARM_RELOC_PAIR))
858 outs() << format(" half = 0x%04x ", (unsigned int)r_address);
859 }
860 else if (cputype == MachO::CPU_TYPE_ARM &&
861 sectdiff_r_type == llvm::MachO::ARM_RELOC_HALF_SECTDIFF)
862 outs() << format(" other_half = 0x%04x ", (unsigned int)r_address);
863 if ((cputype == MachO::CPU_TYPE_I386 &&
864 (r_type == llvm::MachO::GENERIC_RELOC_SECTDIFF ||
865 r_type == llvm::MachO::GENERIC_RELOC_LOCAL_SECTDIFF)) ||
866 (cputype == MachO::CPU_TYPE_ARM &&
867 (sectdiff_r_type == llvm::MachO::ARM_RELOC_SECTDIFF ||
868 sectdiff_r_type == llvm::MachO::ARM_RELOC_LOCAL_SECTDIFF ||
869 sectdiff_r_type == llvm::MachO::ARM_RELOC_HALF_SECTDIFF))) {
870 previous_sectdiff = true;
871 sectdiff_r_type = r_type;
872 }
873 else {
874 previous_sectdiff = false;
875 sectdiff_r_type = 0;
876 }
877 if (cputype == MachO::CPU_TYPE_ARM &&
878 (r_type == llvm::MachO::ARM_RELOC_HALF ||
879 r_type == llvm::MachO::ARM_RELOC_HALF_SECTDIFF))
880 previous_arm_half = true;
881 else
882 previous_arm_half = false;
883 outs() << "\n";
884 }
885 else {
886 // scattered: address pcrel length extern type scattered value
887 outs() << format("%08x %1d %-2d n/a %-7d 1 0x%08x\n",
888 (unsigned int)r_address, r_pcrel, r_length, r_type,
889 (unsigned int)r_value);
890 }
891 }
892 else {
893 if (verbose) {
894 // plain: address
895 if (cputype == MachO::CPU_TYPE_ARM &&
896 r_type == llvm::MachO::ARM_RELOC_PAIR)
897 outs() << " ";
898 else
899 outs() << format("%08x ", (unsigned int)r_address);
Jonas Devliegheree787efd2018-11-11 22:12:04 +0000900
Michael Trenta1703b12017-12-15 17:57:40 +0000901 // plain: pcrel
902 if (r_pcrel)
903 outs() << "True ";
904 else
905 outs() << "False ";
Jonas Devliegheree787efd2018-11-11 22:12:04 +0000906
Michael Trenta1703b12017-12-15 17:57:40 +0000907 // plain: length
908 PrintRLength(cputype, r_type, r_length, previous_arm_half);
Jonas Devliegheree787efd2018-11-11 22:12:04 +0000909
Michael Trenta1703b12017-12-15 17:57:40 +0000910 if (r_extern) {
911 // plain: extern & type & scattered
912 outs() << "True ";
913 PrintRType(cputype, r_type);
914 outs() << "False ";
Jonas Devliegheree787efd2018-11-11 22:12:04 +0000915
Michael Trenta1703b12017-12-15 17:57:40 +0000916 // plain: symbolnum/value
917 if (r_symbolnum > Symtab.nsyms)
918 outs() << format("?(%d)\n", r_symbolnum);
919 else {
920 SymbolRef Symbol = *O->getSymbolByIndex(r_symbolnum);
921 Expected<StringRef> SymNameNext = Symbol.getName();
922 const char *name = NULL;
923 if (SymNameNext)
924 name = SymNameNext->data();
925 if (name == NULL)
926 outs() << format("?(%d)\n", r_symbolnum);
927 else
928 outs() << name << "\n";
929 }
930 }
931 else {
932 // plain: extern & type & scattered
933 outs() << "False ";
934 PrintRType(cputype, r_type);
935 outs() << "False ";
Jonas Devliegheree787efd2018-11-11 22:12:04 +0000936
Michael Trenta1703b12017-12-15 17:57:40 +0000937 // plain: symbolnum/value
938 if (cputype == MachO::CPU_TYPE_ARM &&
939 r_type == llvm::MachO::ARM_RELOC_PAIR)
940 outs() << format("other_half = 0x%04x\n", (unsigned int)r_address);
941 else if (cputype == MachO::CPU_TYPE_ARM64 &&
942 r_type == llvm::MachO::ARM64_RELOC_ADDEND)
943 outs() << format("addend = 0x%06x\n", (unsigned int)r_symbolnum);
944 else {
945 outs() << format("%d ", r_symbolnum);
946 if (r_symbolnum == llvm::MachO::R_ABS)
947 outs() << "R_ABS\n";
948 else {
949 // in this case, r_symbolnum is actually a 1-based section number
950 uint32_t nsects = O->section_end()->getRawDataRefImpl().d.a;
951 if (r_symbolnum > 0 && r_symbolnum <= nsects) {
952 llvm::object::DataRefImpl DRI;
953 DRI.d.a = r_symbolnum-1;
954 StringRef SegName = O->getSectionFinalSegmentName(DRI);
955 StringRef SectName;
956 if (O->getSectionName(DRI, SectName))
957 outs() << "(?,?)\n";
958 else
959 outs() << "(" << SegName << "," << SectName << ")\n";
960 }
961 else {
962 outs() << "(?,?)\n";
963 }
964 }
965 }
966 }
967 if (cputype == MachO::CPU_TYPE_ARM &&
968 (r_type == llvm::MachO::ARM_RELOC_HALF ||
969 r_type == llvm::MachO::ARM_RELOC_HALF_SECTDIFF))
970 previous_arm_half = true;
971 else
972 previous_arm_half = false;
973 }
974 else {
975 // plain: address pcrel length extern type scattered symbolnum/section
976 outs() << format("%08x %1d %-2d %1d %-7d 0 %d\n",
977 (unsigned int)r_address, r_pcrel, r_length, r_extern,
978 r_type, r_symbolnum);
979 }
980 }
981 }
982}
983
984static void PrintRelocations(const MachOObjectFile *O, const bool verbose) {
985 const uint64_t cputype = O->getHeader().cputype;
986 const MachO::dysymtab_command Dysymtab = O->getDysymtabLoadCommand();
987 if (Dysymtab.nextrel != 0) {
988 outs() << "External relocation information " << Dysymtab.nextrel
989 << " entries";
990 outs() << "\naddress pcrel length extern type scattered "
991 "symbolnum/value\n";
992 PrintRelocationEntries(O, O->extrel_begin(), O->extrel_end(), cputype,
993 verbose);
994 }
995 if (Dysymtab.nlocrel != 0) {
996 outs() << format("Local relocation information %u entries",
997 Dysymtab.nlocrel);
998 outs() << "\naddress pcrel length extern type scattered "
999 "symbolnum/value\n";
1000 PrintRelocationEntries(O, O->locrel_begin(), O->locrel_end(), cputype,
1001 verbose);
1002 }
1003 for (const auto &Load : O->load_commands()) {
1004 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
1005 const MachO::segment_command_64 Seg = O->getSegment64LoadCommand(Load);
1006 for (unsigned J = 0; J < Seg.nsects; ++J) {
1007 const MachO::section_64 Sec = O->getSection64(Load, J);
1008 if (Sec.nreloc != 0) {
1009 DataRefImpl DRI;
1010 DRI.d.a = J;
1011 const StringRef SegName = O->getSectionFinalSegmentName(DRI);
1012 StringRef SectName;
1013 if (O->getSectionName(DRI, SectName))
1014 outs() << "Relocation information (" << SegName << ",?) "
1015 << format("%u entries", Sec.nreloc);
1016 else
1017 outs() << "Relocation information (" << SegName << ","
1018 << SectName << format(") %u entries", Sec.nreloc);
1019 outs() << "\naddress pcrel length extern type scattered "
1020 "symbolnum/value\n";
1021 PrintRelocationEntries(O, O->section_rel_begin(DRI),
1022 O->section_rel_end(DRI), cputype, verbose);
1023 }
1024 }
1025 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
1026 const MachO::segment_command Seg = O->getSegmentLoadCommand(Load);
1027 for (unsigned J = 0; J < Seg.nsects; ++J) {
1028 const MachO::section Sec = O->getSection(Load, J);
1029 if (Sec.nreloc != 0) {
1030 DataRefImpl DRI;
1031 DRI.d.a = J;
1032 const StringRef SegName = O->getSectionFinalSegmentName(DRI);
1033 StringRef SectName;
1034 if (O->getSectionName(DRI, SectName))
1035 outs() << "Relocation information (" << SegName << ",?) "
1036 << format("%u entries", Sec.nreloc);
1037 else
1038 outs() << "Relocation information (" << SegName << ","
1039 << SectName << format(") %u entries", Sec.nreloc);
1040 outs() << "\naddress pcrel length extern type scattered "
1041 "symbolnum/value\n";
1042 PrintRelocationEntries(O, O->section_rel_begin(DRI),
1043 O->section_rel_end(DRI), cputype, verbose);
1044 }
1045 }
1046 }
1047 }
1048}
1049
Kevin Enderby69fe98d2015-01-23 18:52:17 +00001050static void PrintDataInCodeTable(MachOObjectFile *O, bool verbose) {
1051 MachO::linkedit_data_command DIC = O->getDataInCodeLoadCommand();
1052 uint32_t nentries = DIC.datasize / sizeof(struct MachO::data_in_code_entry);
1053 outs() << "Data in code table (" << nentries << " entries)\n";
1054 outs() << "offset length kind\n";
1055 for (dice_iterator DI = O->begin_dices(), DE = O->end_dices(); DI != DE;
1056 ++DI) {
1057 uint32_t Offset;
1058 DI->getOffset(Offset);
1059 outs() << format("0x%08" PRIx32, Offset) << " ";
1060 uint16_t Length;
1061 DI->getLength(Length);
1062 outs() << format("%6u", Length) << " ";
1063 uint16_t Kind;
1064 DI->getKind(Kind);
1065 if (verbose) {
1066 switch (Kind) {
1067 case MachO::DICE_KIND_DATA:
1068 outs() << "DATA";
1069 break;
1070 case MachO::DICE_KIND_JUMP_TABLE8:
1071 outs() << "JUMP_TABLE8";
1072 break;
1073 case MachO::DICE_KIND_JUMP_TABLE16:
1074 outs() << "JUMP_TABLE16";
1075 break;
1076 case MachO::DICE_KIND_JUMP_TABLE32:
1077 outs() << "JUMP_TABLE32";
1078 break;
1079 case MachO::DICE_KIND_ABS_JUMP_TABLE32:
1080 outs() << "ABS_JUMP_TABLE32";
1081 break;
1082 default:
1083 outs() << format("0x%04" PRIx32, Kind);
1084 break;
1085 }
1086 } else
1087 outs() << format("0x%04" PRIx32, Kind);
1088 outs() << "\n";
1089 }
1090}
1091
Kevin Enderby9a509442015-01-27 21:28:24 +00001092static void PrintLinkOptHints(MachOObjectFile *O) {
1093 MachO::linkedit_data_command LohLC = O->getLinkOptHintsLoadCommand();
1094 const char *loh = O->getData().substr(LohLC.dataoff, 1).data();
1095 uint32_t nloh = LohLC.datasize;
1096 outs() << "Linker optimiztion hints (" << nloh << " total bytes)\n";
1097 for (uint32_t i = 0; i < nloh;) {
1098 unsigned n;
1099 uint64_t identifier = decodeULEB128((const uint8_t *)(loh + i), &n);
1100 i += n;
1101 outs() << " identifier " << identifier << " ";
1102 if (i >= nloh)
1103 return;
1104 switch (identifier) {
1105 case 1:
1106 outs() << "AdrpAdrp\n";
1107 break;
1108 case 2:
1109 outs() << "AdrpLdr\n";
1110 break;
1111 case 3:
1112 outs() << "AdrpAddLdr\n";
1113 break;
1114 case 4:
1115 outs() << "AdrpLdrGotLdr\n";
1116 break;
1117 case 5:
1118 outs() << "AdrpAddStr\n";
1119 break;
1120 case 6:
1121 outs() << "AdrpLdrGotStr\n";
1122 break;
1123 case 7:
1124 outs() << "AdrpAdd\n";
1125 break;
1126 case 8:
1127 outs() << "AdrpLdrGot\n";
1128 break;
1129 default:
1130 outs() << "Unknown identifier value\n";
1131 break;
1132 }
1133 uint64_t narguments = decodeULEB128((const uint8_t *)(loh + i), &n);
1134 i += n;
1135 outs() << " narguments " << narguments << "\n";
1136 if (i >= nloh)
1137 return;
1138
1139 for (uint32_t j = 0; j < narguments; j++) {
1140 uint64_t value = decodeULEB128((const uint8_t *)(loh + i), &n);
1141 i += n;
1142 outs() << "\tvalue " << format("0x%" PRIx64, value) << "\n";
1143 if (i >= nloh)
1144 return;
1145 }
1146 }
1147}
1148
Kevin Enderbybc847fa2015-03-16 20:08:09 +00001149static void PrintDylibs(MachOObjectFile *O, bool JustId) {
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00001150 unsigned Index = 0;
1151 for (const auto &Load : O->load_commands()) {
Kevin Enderbybc847fa2015-03-16 20:08:09 +00001152 if ((JustId && Load.C.cmd == MachO::LC_ID_DYLIB) ||
1153 (!JustId && (Load.C.cmd == MachO::LC_ID_DYLIB ||
1154 Load.C.cmd == MachO::LC_LOAD_DYLIB ||
1155 Load.C.cmd == MachO::LC_LOAD_WEAK_DYLIB ||
1156 Load.C.cmd == MachO::LC_REEXPORT_DYLIB ||
1157 Load.C.cmd == MachO::LC_LAZY_LOAD_DYLIB ||
1158 Load.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB))) {
1159 MachO::dylib_command dl = O->getDylibIDLoadCommand(Load);
1160 if (dl.dylib.name < dl.cmdsize) {
1161 const char *p = (const char *)(Load.Ptr) + dl.dylib.name;
1162 if (JustId)
1163 outs() << p << "\n";
1164 else {
1165 outs() << "\t" << p;
1166 outs() << " (compatibility version "
1167 << ((dl.dylib.compatibility_version >> 16) & 0xffff) << "."
1168 << ((dl.dylib.compatibility_version >> 8) & 0xff) << "."
1169 << (dl.dylib.compatibility_version & 0xff) << ",";
1170 outs() << " current version "
1171 << ((dl.dylib.current_version >> 16) & 0xffff) << "."
1172 << ((dl.dylib.current_version >> 8) & 0xff) << "."
1173 << (dl.dylib.current_version & 0xff) << ")\n";
1174 }
1175 } else {
1176 outs() << "\tBad offset (" << dl.dylib.name << ") for name of ";
1177 if (Load.C.cmd == MachO::LC_ID_DYLIB)
1178 outs() << "LC_ID_DYLIB ";
1179 else if (Load.C.cmd == MachO::LC_LOAD_DYLIB)
1180 outs() << "LC_LOAD_DYLIB ";
1181 else if (Load.C.cmd == MachO::LC_LOAD_WEAK_DYLIB)
1182 outs() << "LC_LOAD_WEAK_DYLIB ";
1183 else if (Load.C.cmd == MachO::LC_LAZY_LOAD_DYLIB)
1184 outs() << "LC_LAZY_LOAD_DYLIB ";
1185 else if (Load.C.cmd == MachO::LC_REEXPORT_DYLIB)
1186 outs() << "LC_REEXPORT_DYLIB ";
1187 else if (Load.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB)
1188 outs() << "LC_LOAD_UPWARD_DYLIB ";
1189 else
1190 outs() << "LC_??? ";
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00001191 outs() << "command " << Index++ << "\n";
Kevin Enderbybc847fa2015-03-16 20:08:09 +00001192 }
1193 }
Kevin Enderbybc847fa2015-03-16 20:08:09 +00001194 }
1195}
1196
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001197typedef DenseMap<uint64_t, StringRef> SymbolAddressMap;
1198
1199static void CreateSymbolAddressMap(MachOObjectFile *O,
1200 SymbolAddressMap *AddrMap) {
1201 // Create a map of symbol addresses to symbol names.
1202 for (const SymbolRef &Symbol : O->symbols()) {
Kevin Enderby7bd8d992016-05-02 20:28:12 +00001203 Expected<SymbolRef::Type> STOrErr = Symbol.getType();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00001204 if (!STOrErr)
1205 report_error(O->getFileName(), STOrErr.takeError());
Kevin Enderby5afbc1c2016-03-23 20:27:00 +00001206 SymbolRef::Type ST = *STOrErr;
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001207 if (ST == SymbolRef::ST_Function || ST == SymbolRef::ST_Data ||
1208 ST == SymbolRef::ST_Other) {
Rafael Espindoladea00162015-07-03 17:44:18 +00001209 uint64_t Address = Symbol.getValue();
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00001210 Expected<StringRef> SymNameOrErr = Symbol.getName();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00001211 if (!SymNameOrErr)
1212 report_error(O->getFileName(), SymNameOrErr.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00001213 StringRef SymName = *SymNameOrErr;
Kevin Enderby846c0002015-04-16 17:19:59 +00001214 if (!SymName.startswith(".objc"))
1215 (*AddrMap)[Address] = SymName;
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001216 }
1217 }
1218}
1219
1220// GuessSymbolName is passed the address of what might be a symbol and a
1221// pointer to the SymbolAddressMap. It returns the name of a symbol
1222// with that address or nullptr if no symbol is found with that address.
1223static const char *GuessSymbolName(uint64_t value, SymbolAddressMap *AddrMap) {
1224 const char *SymbolName = nullptr;
1225 // A DenseMap can't lookup up some values.
1226 if (value != 0xffffffffffffffffULL && value != 0xfffffffffffffffeULL) {
1227 StringRef name = AddrMap->lookup(value);
1228 if (!name.empty())
1229 SymbolName = name.data();
1230 }
1231 return SymbolName;
1232}
1233
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001234static void DumpCstringChar(const char c) {
1235 char p[2];
1236 p[0] = c;
1237 p[1] = '\0';
1238 outs().write_escaped(p);
1239}
1240
Kevin Enderby10ba0412015-02-04 21:38:42 +00001241static void DumpCstringSection(MachOObjectFile *O, const char *sect,
1242 uint32_t sect_size, uint64_t sect_addr,
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001243 bool print_addresses) {
Kevin Enderby10ba0412015-02-04 21:38:42 +00001244 for (uint32_t i = 0; i < sect_size; i++) {
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001245 if (print_addresses) {
1246 if (O->is64Bit())
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001247 outs() << format("%016" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001248 else
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001249 outs() << format("%08" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001250 }
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001251 for (; i < sect_size && sect[i] != '\0'; i++)
1252 DumpCstringChar(sect[i]);
Kevin Enderby10ba0412015-02-04 21:38:42 +00001253 if (i < sect_size && sect[i] == '\0')
1254 outs() << "\n";
1255 }
1256}
1257
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001258static void DumpLiteral4(uint32_t l, float f) {
1259 outs() << format("0x%08" PRIx32, l);
1260 if ((l & 0x7f800000) != 0x7f800000)
1261 outs() << format(" (%.16e)\n", f);
1262 else {
1263 if (l == 0x7f800000)
1264 outs() << " (+Infinity)\n";
1265 else if (l == 0xff800000)
1266 outs() << " (-Infinity)\n";
1267 else if ((l & 0x00400000) == 0x00400000)
1268 outs() << " (non-signaling Not-a-Number)\n";
1269 else
1270 outs() << " (signaling Not-a-Number)\n";
1271 }
1272}
1273
1274static void DumpLiteral4Section(MachOObjectFile *O, const char *sect,
1275 uint32_t sect_size, uint64_t sect_addr,
1276 bool print_addresses) {
1277 for (uint32_t i = 0; i < sect_size; i += sizeof(float)) {
1278 if (print_addresses) {
1279 if (O->is64Bit())
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001280 outs() << format("%016" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001281 else
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001282 outs() << format("%08" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001283 }
1284 float f;
1285 memcpy(&f, sect + i, sizeof(float));
1286 if (O->isLittleEndian() != sys::IsLittleEndianHost)
1287 sys::swapByteOrder(f);
1288 uint32_t l;
1289 memcpy(&l, sect + i, sizeof(uint32_t));
1290 if (O->isLittleEndian() != sys::IsLittleEndianHost)
1291 sys::swapByteOrder(l);
1292 DumpLiteral4(l, f);
1293 }
1294}
1295
1296static void DumpLiteral8(MachOObjectFile *O, uint32_t l0, uint32_t l1,
1297 double d) {
1298 outs() << format("0x%08" PRIx32, l0) << " " << format("0x%08" PRIx32, l1);
1299 uint32_t Hi, Lo;
Davide Italianob627d9f2015-12-12 21:50:11 +00001300 Hi = (O->isLittleEndian()) ? l1 : l0;
1301 Lo = (O->isLittleEndian()) ? l0 : l1;
1302
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001303 // Hi is the high word, so this is equivalent to if(isfinite(d))
1304 if ((Hi & 0x7ff00000) != 0x7ff00000)
1305 outs() << format(" (%.16e)\n", d);
1306 else {
1307 if (Hi == 0x7ff00000 && Lo == 0)
1308 outs() << " (+Infinity)\n";
1309 else if (Hi == 0xfff00000 && Lo == 0)
1310 outs() << " (-Infinity)\n";
1311 else if ((Hi & 0x00080000) == 0x00080000)
1312 outs() << " (non-signaling Not-a-Number)\n";
1313 else
1314 outs() << " (signaling Not-a-Number)\n";
1315 }
1316}
1317
1318static void DumpLiteral8Section(MachOObjectFile *O, const char *sect,
1319 uint32_t sect_size, uint64_t sect_addr,
1320 bool print_addresses) {
1321 for (uint32_t i = 0; i < sect_size; i += sizeof(double)) {
1322 if (print_addresses) {
1323 if (O->is64Bit())
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001324 outs() << format("%016" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001325 else
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001326 outs() << format("%08" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001327 }
1328 double d;
1329 memcpy(&d, sect + i, sizeof(double));
1330 if (O->isLittleEndian() != sys::IsLittleEndianHost)
1331 sys::swapByteOrder(d);
1332 uint32_t l0, l1;
1333 memcpy(&l0, sect + i, sizeof(uint32_t));
1334 memcpy(&l1, sect + i + sizeof(uint32_t), sizeof(uint32_t));
1335 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
1336 sys::swapByteOrder(l0);
1337 sys::swapByteOrder(l1);
1338 }
1339 DumpLiteral8(O, l0, l1, d);
1340 }
1341}
1342
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001343static void DumpLiteral16(uint32_t l0, uint32_t l1, uint32_t l2, uint32_t l3) {
1344 outs() << format("0x%08" PRIx32, l0) << " ";
1345 outs() << format("0x%08" PRIx32, l1) << " ";
1346 outs() << format("0x%08" PRIx32, l2) << " ";
1347 outs() << format("0x%08" PRIx32, l3) << "\n";
1348}
1349
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001350static void DumpLiteral16Section(MachOObjectFile *O, const char *sect,
1351 uint32_t sect_size, uint64_t sect_addr,
1352 bool print_addresses) {
1353 for (uint32_t i = 0; i < sect_size; i += 16) {
1354 if (print_addresses) {
1355 if (O->is64Bit())
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001356 outs() << format("%016" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001357 else
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001358 outs() << format("%08" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001359 }
1360 uint32_t l0, l1, l2, l3;
1361 memcpy(&l0, sect + i, sizeof(uint32_t));
1362 memcpy(&l1, sect + i + sizeof(uint32_t), sizeof(uint32_t));
1363 memcpy(&l2, sect + i + 2 * sizeof(uint32_t), sizeof(uint32_t));
1364 memcpy(&l3, sect + i + 3 * sizeof(uint32_t), sizeof(uint32_t));
1365 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
1366 sys::swapByteOrder(l0);
1367 sys::swapByteOrder(l1);
1368 sys::swapByteOrder(l2);
1369 sys::swapByteOrder(l3);
1370 }
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001371 DumpLiteral16(l0, l1, l2, l3);
1372 }
1373}
1374
1375static void DumpLiteralPointerSection(MachOObjectFile *O,
1376 const SectionRef &Section,
1377 const char *sect, uint32_t sect_size,
1378 uint64_t sect_addr,
1379 bool print_addresses) {
1380 // Collect the literal sections in this Mach-O file.
1381 std::vector<SectionRef> LiteralSections;
1382 for (const SectionRef &Section : O->sections()) {
1383 DataRefImpl Ref = Section.getRawDataRefImpl();
1384 uint32_t section_type;
1385 if (O->is64Bit()) {
1386 const MachO::section_64 Sec = O->getSection64(Ref);
1387 section_type = Sec.flags & MachO::SECTION_TYPE;
1388 } else {
1389 const MachO::section Sec = O->getSection(Ref);
1390 section_type = Sec.flags & MachO::SECTION_TYPE;
1391 }
1392 if (section_type == MachO::S_CSTRING_LITERALS ||
1393 section_type == MachO::S_4BYTE_LITERALS ||
1394 section_type == MachO::S_8BYTE_LITERALS ||
1395 section_type == MachO::S_16BYTE_LITERALS)
1396 LiteralSections.push_back(Section);
1397 }
1398
1399 // Set the size of the literal pointer.
1400 uint32_t lp_size = O->is64Bit() ? 8 : 4;
1401
Eric Christopher572e03a2015-06-19 01:53:21 +00001402 // Collect the external relocation symbols for the literal pointers.
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001403 std::vector<std::pair<uint64_t, SymbolRef>> Relocs;
1404 for (const RelocationRef &Reloc : Section.relocations()) {
1405 DataRefImpl Rel;
1406 MachO::any_relocation_info RE;
1407 bool isExtern = false;
1408 Rel = Reloc.getRawDataRefImpl();
1409 RE = O->getRelocation(Rel);
1410 isExtern = O->getPlainRelocationExternal(RE);
1411 if (isExtern) {
Rafael Espindola96d071c2015-06-29 23:29:12 +00001412 uint64_t RelocOffset = Reloc.getOffset();
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001413 symbol_iterator RelocSym = Reloc.getSymbol();
1414 Relocs.push_back(std::make_pair(RelocOffset, *RelocSym));
1415 }
1416 }
1417 array_pod_sort(Relocs.begin(), Relocs.end());
1418
1419 // Dump each literal pointer.
1420 for (uint32_t i = 0; i < sect_size; i += lp_size) {
1421 if (print_addresses) {
1422 if (O->is64Bit())
1423 outs() << format("%016" PRIx64, sect_addr + i) << " ";
1424 else
1425 outs() << format("%08" PRIx64, sect_addr + i) << " ";
1426 }
1427 uint64_t lp;
1428 if (O->is64Bit()) {
1429 memcpy(&lp, sect + i, sizeof(uint64_t));
1430 if (O->isLittleEndian() != sys::IsLittleEndianHost)
1431 sys::swapByteOrder(lp);
1432 } else {
1433 uint32_t li;
1434 memcpy(&li, sect + i, sizeof(uint32_t));
1435 if (O->isLittleEndian() != sys::IsLittleEndianHost)
1436 sys::swapByteOrder(li);
1437 lp = li;
1438 }
1439
1440 // First look for an external relocation entry for this literal pointer.
David Majnemer42531262016-08-12 03:55:06 +00001441 auto Reloc = find_if(Relocs, [&](const std::pair<uint64_t, SymbolRef> &P) {
1442 return P.first == i;
1443 });
David Blaikie33dd45d02015-03-23 18:39:02 +00001444 if (Reloc != Relocs.end()) {
1445 symbol_iterator RelocSym = Reloc->second;
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00001446 Expected<StringRef> SymName = RelocSym->getName();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00001447 if (!SymName)
1448 report_error(O->getFileName(), SymName.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00001449 outs() << "external relocation entry for symbol:" << *SymName << "\n";
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001450 continue;
David Blaikie33dd45d02015-03-23 18:39:02 +00001451 }
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001452
1453 // For local references see what the section the literal pointer points to.
David Majnemer562e8292016-08-12 00:18:03 +00001454 auto Sect = find_if(LiteralSections, [&](const SectionRef &R) {
1455 return lp >= R.getAddress() && lp < R.getAddress() + R.getSize();
1456 });
David Blaikie33dd45d02015-03-23 18:39:02 +00001457 if (Sect == LiteralSections.end()) {
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001458 outs() << format("0x%" PRIx64, lp) << " (not in a literal section)\n";
David Blaikie33dd45d02015-03-23 18:39:02 +00001459 continue;
1460 }
1461
1462 uint64_t SectAddress = Sect->getAddress();
1463 uint64_t SectSize = Sect->getSize();
1464
1465 StringRef SectName;
1466 Sect->getName(SectName);
1467 DataRefImpl Ref = Sect->getRawDataRefImpl();
1468 StringRef SegmentName = O->getSectionFinalSegmentName(Ref);
1469 outs() << SegmentName << ":" << SectName << ":";
1470
1471 uint32_t section_type;
1472 if (O->is64Bit()) {
1473 const MachO::section_64 Sec = O->getSection64(Ref);
1474 section_type = Sec.flags & MachO::SECTION_TYPE;
1475 } else {
1476 const MachO::section Sec = O->getSection(Ref);
1477 section_type = Sec.flags & MachO::SECTION_TYPE;
1478 }
1479
1480 StringRef BytesStr;
1481 Sect->getContents(BytesStr);
1482 const char *Contents = reinterpret_cast<const char *>(BytesStr.data());
1483
1484 switch (section_type) {
1485 case MachO::S_CSTRING_LITERALS:
1486 for (uint64_t i = lp - SectAddress; i < SectSize && Contents[i] != '\0';
1487 i++) {
1488 DumpCstringChar(Contents[i]);
1489 }
1490 outs() << "\n";
1491 break;
1492 case MachO::S_4BYTE_LITERALS:
1493 float f;
1494 memcpy(&f, Contents + (lp - SectAddress), sizeof(float));
1495 uint32_t l;
1496 memcpy(&l, Contents + (lp - SectAddress), sizeof(uint32_t));
1497 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
1498 sys::swapByteOrder(f);
1499 sys::swapByteOrder(l);
1500 }
1501 DumpLiteral4(l, f);
1502 break;
1503 case MachO::S_8BYTE_LITERALS: {
1504 double d;
1505 memcpy(&d, Contents + (lp - SectAddress), sizeof(double));
1506 uint32_t l0, l1;
1507 memcpy(&l0, Contents + (lp - SectAddress), sizeof(uint32_t));
1508 memcpy(&l1, Contents + (lp - SectAddress) + sizeof(uint32_t),
1509 sizeof(uint32_t));
1510 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
1511 sys::swapByteOrder(f);
1512 sys::swapByteOrder(l0);
1513 sys::swapByteOrder(l1);
1514 }
1515 DumpLiteral8(O, l0, l1, d);
1516 break;
1517 }
1518 case MachO::S_16BYTE_LITERALS: {
1519 uint32_t l0, l1, l2, l3;
1520 memcpy(&l0, Contents + (lp - SectAddress), sizeof(uint32_t));
1521 memcpy(&l1, Contents + (lp - SectAddress) + sizeof(uint32_t),
1522 sizeof(uint32_t));
1523 memcpy(&l2, Contents + (lp - SectAddress) + 2 * sizeof(uint32_t),
1524 sizeof(uint32_t));
1525 memcpy(&l3, Contents + (lp - SectAddress) + 3 * sizeof(uint32_t),
1526 sizeof(uint32_t));
1527 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
1528 sys::swapByteOrder(l0);
1529 sys::swapByteOrder(l1);
1530 sys::swapByteOrder(l2);
1531 sys::swapByteOrder(l3);
1532 }
1533 DumpLiteral16(l0, l1, l2, l3);
1534 break;
1535 }
1536 }
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001537 }
1538}
1539
Kevin Enderby85b7a662018-03-20 20:29:52 +00001540static void DumpInitTermPointerSection(MachOObjectFile *O,
1541 const SectionRef &Section,
1542 const char *sect,
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001543 uint32_t sect_size, uint64_t sect_addr,
1544 SymbolAddressMap *AddrMap,
1545 bool verbose) {
1546 uint32_t stride;
Davide Italiano3eb47e22015-12-15 23:14:21 +00001547 stride = (O->is64Bit()) ? sizeof(uint64_t) : sizeof(uint32_t);
Kevin Enderby85b7a662018-03-20 20:29:52 +00001548
1549 // Collect the external relocation symbols for the pointers.
1550 std::vector<std::pair<uint64_t, SymbolRef>> Relocs;
1551 for (const RelocationRef &Reloc : Section.relocations()) {
1552 DataRefImpl Rel;
1553 MachO::any_relocation_info RE;
1554 bool isExtern = false;
1555 Rel = Reloc.getRawDataRefImpl();
1556 RE = O->getRelocation(Rel);
1557 isExtern = O->getPlainRelocationExternal(RE);
1558 if (isExtern) {
1559 uint64_t RelocOffset = Reloc.getOffset();
1560 symbol_iterator RelocSym = Reloc.getSymbol();
1561 Relocs.push_back(std::make_pair(RelocOffset, *RelocSym));
1562 }
1563 }
1564 array_pod_sort(Relocs.begin(), Relocs.end());
1565
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001566 for (uint32_t i = 0; i < sect_size; i += stride) {
1567 const char *SymbolName = nullptr;
Kevin Enderby85b7a662018-03-20 20:29:52 +00001568 uint64_t p;
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001569 if (O->is64Bit()) {
1570 outs() << format("0x%016" PRIx64, sect_addr + i * stride) << " ";
1571 uint64_t pointer_value;
1572 memcpy(&pointer_value, sect + i, stride);
1573 if (O->isLittleEndian() != sys::IsLittleEndianHost)
1574 sys::swapByteOrder(pointer_value);
1575 outs() << format("0x%016" PRIx64, pointer_value);
Kevin Enderby85b7a662018-03-20 20:29:52 +00001576 p = pointer_value;
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001577 } else {
1578 outs() << format("0x%08" PRIx64, sect_addr + i * stride) << " ";
1579 uint32_t pointer_value;
1580 memcpy(&pointer_value, sect + i, stride);
1581 if (O->isLittleEndian() != sys::IsLittleEndianHost)
1582 sys::swapByteOrder(pointer_value);
1583 outs() << format("0x%08" PRIx32, pointer_value);
Kevin Enderby85b7a662018-03-20 20:29:52 +00001584 p = pointer_value;
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001585 }
Kevin Enderby85b7a662018-03-20 20:29:52 +00001586 if (verbose) {
1587 // First look for an external relocation entry for this pointer.
1588 auto Reloc = find_if(Relocs, [&](const std::pair<uint64_t, SymbolRef> &P) {
1589 return P.first == i;
1590 });
1591 if (Reloc != Relocs.end()) {
1592 symbol_iterator RelocSym = Reloc->second;
1593 Expected<StringRef> SymName = RelocSym->getName();
1594 if (!SymName)
1595 report_error(O->getFileName(), SymName.takeError());
1596 outs() << " " << *SymName;
1597 } else {
1598 SymbolName = GuessSymbolName(p, AddrMap);
1599 if (SymbolName)
1600 outs() << " " << SymbolName;
1601 }
1602 }
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001603 outs() << "\n";
1604 }
1605}
1606
1607static void DumpRawSectionContents(MachOObjectFile *O, const char *sect,
1608 uint32_t size, uint64_t addr) {
1609 uint32_t cputype = O->getHeader().cputype;
1610 if (cputype == MachO::CPU_TYPE_I386 || cputype == MachO::CPU_TYPE_X86_64) {
1611 uint32_t j;
1612 for (uint32_t i = 0; i < size; i += j, addr += j) {
1613 if (O->is64Bit())
1614 outs() << format("%016" PRIx64, addr) << "\t";
1615 else
Kevin Enderbyf0640752015-03-13 17:56:32 +00001616 outs() << format("%08" PRIx64, addr) << "\t";
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001617 for (j = 0; j < 16 && i + j < size; j++) {
1618 uint8_t byte_word = *(sect + i + j);
1619 outs() << format("%02" PRIx32, (uint32_t)byte_word) << " ";
1620 }
1621 outs() << "\n";
1622 }
1623 } else {
1624 uint32_t j;
1625 for (uint32_t i = 0; i < size; i += j, addr += j) {
1626 if (O->is64Bit())
1627 outs() << format("%016" PRIx64, addr) << "\t";
1628 else
Kevin Enderbyc4930852016-04-27 22:36:18 +00001629 outs() << format("%08" PRIx64, addr) << "\t";
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001630 for (j = 0; j < 4 * sizeof(int32_t) && i + j < size;
1631 j += sizeof(int32_t)) {
Kevin Enderby8eccdad2016-04-27 23:43:00 +00001632 if (i + j + sizeof(int32_t) <= size) {
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001633 uint32_t long_word;
1634 memcpy(&long_word, sect + i + j, sizeof(int32_t));
1635 if (O->isLittleEndian() != sys::IsLittleEndianHost)
1636 sys::swapByteOrder(long_word);
1637 outs() << format("%08" PRIx32, long_word) << " ";
1638 } else {
1639 for (uint32_t k = 0; i + j + k < size; k++) {
Kevin Enderby8eccdad2016-04-27 23:43:00 +00001640 uint8_t byte_word = *(sect + i + j + k);
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001641 outs() << format("%02" PRIx32, (uint32_t)byte_word) << " ";
1642 }
1643 }
1644 }
1645 outs() << "\n";
1646 }
1647 }
1648}
1649
Kevin Enderby95df54c2015-02-04 01:01:38 +00001650static void DisassembleMachO(StringRef Filename, MachOObjectFile *MachOOF,
1651 StringRef DisSegName, StringRef DisSectName);
Kevin Enderby4ad9bde2015-04-16 22:33:20 +00001652static void DumpProtocolSection(MachOObjectFile *O, const char *sect,
1653 uint32_t size, uint32_t addr);
Kevin Enderby9873e2c2016-05-23 21:34:12 +00001654#ifdef HAVE_LIBXAR
1655static void DumpBitcodeSection(MachOObjectFile *O, const char *sect,
1656 uint32_t size, bool verbose,
1657 bool PrintXarHeader, bool PrintXarFileHeaders,
1658 std::string XarMemberName);
1659#endif // defined(HAVE_LIBXAR)
Kevin Enderby95df54c2015-02-04 01:01:38 +00001660
1661static void DumpSectionContents(StringRef Filename, MachOObjectFile *O,
1662 bool verbose) {
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001663 SymbolAddressMap AddrMap;
1664 if (verbose)
1665 CreateSymbolAddressMap(O, &AddrMap);
1666
Colin LeMahieufcc32762015-07-29 19:08:10 +00001667 for (unsigned i = 0; i < FilterSections.size(); ++i) {
1668 StringRef DumpSection = FilterSections[i];
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001669 std::pair<StringRef, StringRef> DumpSegSectName;
1670 DumpSegSectName = DumpSection.split(',');
1671 StringRef DumpSegName, DumpSectName;
Jordan Rupprecht16a0de22018-12-20 00:57:06 +00001672 if (!DumpSegSectName.second.empty()) {
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001673 DumpSegName = DumpSegSectName.first;
1674 DumpSectName = DumpSegSectName.second;
1675 } else {
1676 DumpSegName = "";
1677 DumpSectName = DumpSegSectName.first;
1678 }
1679 for (const SectionRef &Section : O->sections()) {
1680 StringRef SectName;
1681 Section.getName(SectName);
1682 DataRefImpl Ref = Section.getRawDataRefImpl();
1683 StringRef SegName = O->getSectionFinalSegmentName(Ref);
1684 if ((DumpSegName.empty() || SegName == DumpSegName) &&
1685 (SectName == DumpSectName)) {
Adrian Prantlc2401dd2015-03-27 17:31:15 +00001686
Kevin Enderby95df54c2015-02-04 01:01:38 +00001687 uint32_t section_flags;
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001688 if (O->is64Bit()) {
1689 const MachO::section_64 Sec = O->getSection64(Ref);
Kevin Enderby95df54c2015-02-04 01:01:38 +00001690 section_flags = Sec.flags;
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001691
1692 } else {
1693 const MachO::section Sec = O->getSection(Ref);
Kevin Enderby95df54c2015-02-04 01:01:38 +00001694 section_flags = Sec.flags;
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001695 }
Kevin Enderby95df54c2015-02-04 01:01:38 +00001696 uint32_t section_type = section_flags & MachO::SECTION_TYPE;
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001697
1698 StringRef BytesStr;
1699 Section.getContents(BytesStr);
1700 const char *sect = reinterpret_cast<const char *>(BytesStr.data());
1701 uint32_t sect_size = BytesStr.size();
1702 uint64_t sect_addr = Section.getAddress();
1703
Adrian Prantlc2401dd2015-03-27 17:31:15 +00001704 outs() << "Contents of (" << SegName << "," << SectName
1705 << ") section\n";
1706
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001707 if (verbose) {
Kevin Enderby95df54c2015-02-04 01:01:38 +00001708 if ((section_flags & MachO::S_ATTR_PURE_INSTRUCTIONS) ||
1709 (section_flags & MachO::S_ATTR_SOME_INSTRUCTIONS)) {
1710 DisassembleMachO(Filename, O, SegName, SectName);
1711 continue;
1712 }
Kevin Enderbycd66be52015-03-11 22:06:32 +00001713 if (SegName == "__TEXT" && SectName == "__info_plist") {
1714 outs() << sect;
1715 continue;
1716 }
Kevin Enderby4ad9bde2015-04-16 22:33:20 +00001717 if (SegName == "__OBJC" && SectName == "__protocol") {
1718 DumpProtocolSection(O, sect, sect_size, sect_addr);
1719 continue;
1720 }
Kevin Enderby9873e2c2016-05-23 21:34:12 +00001721#ifdef HAVE_LIBXAR
1722 if (SegName == "__LLVM" && SectName == "__bundle") {
1723 DumpBitcodeSection(O, sect, sect_size, verbose, !NoSymbolicOperands,
1724 ArchiveHeaders, "");
1725 continue;
1726 }
1727#endif // defined(HAVE_LIBXAR)
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001728 switch (section_type) {
1729 case MachO::S_REGULAR:
1730 DumpRawSectionContents(O, sect, sect_size, sect_addr);
1731 break;
1732 case MachO::S_ZEROFILL:
1733 outs() << "zerofill section and has no contents in the file\n";
1734 break;
Kevin Enderby10ba0412015-02-04 21:38:42 +00001735 case MachO::S_CSTRING_LITERALS:
Kevin Enderbyab5e6c92015-03-17 21:07:39 +00001736 DumpCstringSection(O, sect, sect_size, sect_addr, !NoLeadingAddr);
Kevin Enderby10ba0412015-02-04 21:38:42 +00001737 break;
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001738 case MachO::S_4BYTE_LITERALS:
Kevin Enderbyab5e6c92015-03-17 21:07:39 +00001739 DumpLiteral4Section(O, sect, sect_size, sect_addr, !NoLeadingAddr);
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001740 break;
1741 case MachO::S_8BYTE_LITERALS:
Kevin Enderbyab5e6c92015-03-17 21:07:39 +00001742 DumpLiteral8Section(O, sect, sect_size, sect_addr, !NoLeadingAddr);
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001743 break;
1744 case MachO::S_16BYTE_LITERALS:
Kevin Enderby0fc11822015-04-01 20:57:01 +00001745 DumpLiteral16Section(O, sect, sect_size, sect_addr, !NoLeadingAddr);
1746 break;
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001747 case MachO::S_LITERAL_POINTERS:
1748 DumpLiteralPointerSection(O, Section, sect, sect_size, sect_addr,
Kevin Enderbyab5e6c92015-03-17 21:07:39 +00001749 !NoLeadingAddr);
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001750 break;
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001751 case MachO::S_MOD_INIT_FUNC_POINTERS:
1752 case MachO::S_MOD_TERM_FUNC_POINTERS:
Kevin Enderby85b7a662018-03-20 20:29:52 +00001753 DumpInitTermPointerSection(O, Section, sect, sect_size, sect_addr,
1754 &AddrMap, verbose);
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001755 break;
1756 default:
1757 outs() << "Unknown section type ("
1758 << format("0x%08" PRIx32, section_type) << ")\n";
1759 DumpRawSectionContents(O, sect, sect_size, sect_addr);
1760 break;
1761 }
1762 } else {
1763 if (section_type == MachO::S_ZEROFILL)
1764 outs() << "zerofill section and has no contents in the file\n";
1765 else
1766 DumpRawSectionContents(O, sect, sect_size, sect_addr);
1767 }
1768 }
1769 }
1770 }
1771}
1772
Kevin Enderbycd66be52015-03-11 22:06:32 +00001773static void DumpInfoPlistSectionContents(StringRef Filename,
1774 MachOObjectFile *O) {
1775 for (const SectionRef &Section : O->sections()) {
1776 StringRef SectName;
1777 Section.getName(SectName);
1778 DataRefImpl Ref = Section.getRawDataRefImpl();
1779 StringRef SegName = O->getSectionFinalSegmentName(Ref);
1780 if (SegName == "__TEXT" && SectName == "__info_plist") {
Kevin Enderby30cf2e82017-06-20 21:00:25 +00001781 if (!NoLeadingHeaders)
1782 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
Kevin Enderbycd66be52015-03-11 22:06:32 +00001783 StringRef BytesStr;
1784 Section.getContents(BytesStr);
1785 const char *sect = reinterpret_cast<const char *>(BytesStr.data());
Kevin Enderby418659f2017-02-06 21:01:08 +00001786 outs() << format("%.*s", BytesStr.size(), sect) << "\n";
Kevin Enderbycd66be52015-03-11 22:06:32 +00001787 return;
1788 }
1789 }
1790}
1791
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001792// checkMachOAndArchFlags() checks to see if the ObjectFile is a Mach-O file
1793// and if it is and there is a list of architecture flags is specified then
1794// check to make sure this Mach-O file is one of those architectures or all
1795// architectures were specified. If not then an error is generated and this
1796// routine returns false. Else it returns true.
1797static bool checkMachOAndArchFlags(ObjectFile *O, StringRef Filename) {
David Majnemer91160d82016-10-31 17:11:31 +00001798 auto *MachO = dyn_cast<MachOObjectFile>(O);
1799
1800 if (!MachO || ArchAll || ArchFlags.empty())
1801 return true;
1802
1803 MachO::mach_header H;
1804 MachO::mach_header_64 H_64;
1805 Triple T;
Kevin Enderby59343a92016-12-16 22:54:02 +00001806 const char *McpuDefault, *ArchFlag;
David Majnemer91160d82016-10-31 17:11:31 +00001807 if (MachO->is64Bit()) {
1808 H_64 = MachO->MachOObjectFile::getHeader64();
Kevin Enderby59343a92016-12-16 22:54:02 +00001809 T = MachOObjectFile::getArchTriple(H_64.cputype, H_64.cpusubtype,
1810 &McpuDefault, &ArchFlag);
David Majnemer91160d82016-10-31 17:11:31 +00001811 } else {
1812 H = MachO->MachOObjectFile::getHeader();
Kevin Enderby59343a92016-12-16 22:54:02 +00001813 T = MachOObjectFile::getArchTriple(H.cputype, H.cpusubtype,
1814 &McpuDefault, &ArchFlag);
David Majnemer91160d82016-10-31 17:11:31 +00001815 }
Kevin Enderby59343a92016-12-16 22:54:02 +00001816 const std::string ArchFlagName(ArchFlag);
David Majnemer91160d82016-10-31 17:11:31 +00001817 if (none_of(ArchFlags, [&](const std::string &Name) {
Kevin Enderby59343a92016-12-16 22:54:02 +00001818 return Name == ArchFlagName;
David Majnemer91160d82016-10-31 17:11:31 +00001819 })) {
Jonas Devliegheree787efd2018-11-11 22:12:04 +00001820 WithColor::error(errs(), "llvm-objdump")
1821 << Filename << ": no architecture specified.\n";
David Majnemer91160d82016-10-31 17:11:31 +00001822 return false;
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001823 }
1824 return true;
1825}
1826
Kevin Enderby0fc11822015-04-01 20:57:01 +00001827static void printObjcMetaData(MachOObjectFile *O, bool verbose);
1828
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001829// ProcessMachO() is passed a single opened Mach-O file, which may be an
1830// archive member and or in a slice of a universal file. It prints the
1831// the file name and header info and then processes it according to the
1832// command line options.
Kevin Enderby844c4ac2016-11-15 23:07:41 +00001833static void ProcessMachO(StringRef Name, MachOObjectFile *MachOOF,
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001834 StringRef ArchiveMemberName = StringRef(),
1835 StringRef ArchitectureName = StringRef()) {
Kevin Enderby131d1772015-01-09 19:22:37 +00001836 // If we are doing some processing here on the Mach-O file print the header
1837 // info. And don't print it otherwise like in the case of printing the
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +00001838 // UniversalHeaders or ArchiveHeaders.
Michael Trenta1703b12017-12-15 17:57:40 +00001839 if (Disassemble || Relocations || PrivateHeaders || ExportsTrie || Rebase ||
1840 Bind || SymbolTable || LazyBind || WeakBind || IndirectSymbols ||
1841 DataInCode || LinkOptHints || DylibsUsed || DylibId || ObjcMetaData ||
Jordan Rupprecht16a0de22018-12-20 00:57:06 +00001842 (!FilterSections.empty())) {
Kevin Enderbyf9d60f02016-11-29 21:43:40 +00001843 if (!NoLeadingHeaders) {
1844 outs() << Name;
1845 if (!ArchiveMemberName.empty())
1846 outs() << '(' << ArchiveMemberName << ')';
1847 if (!ArchitectureName.empty())
1848 outs() << " (architecture " << ArchitectureName << ")";
1849 outs() << ":\n";
1850 }
Kevin Enderby131d1772015-01-09 19:22:37 +00001851 }
Kevin Enderby844c4ac2016-11-15 23:07:41 +00001852 // To use the report_error() form with an ArchiveName and FileName set
1853 // these up based on what is passed for Name and ArchiveMemberName.
1854 StringRef ArchiveName;
1855 StringRef FileName;
1856 if (!ArchiveMemberName.empty()) {
1857 ArchiveName = Name;
1858 FileName = ArchiveMemberName;
1859 } else {
1860 ArchiveName = StringRef();
1861 FileName = Name;
1862 }
1863
1864 // If we need the symbol table to do the operation then check it here to
1865 // produce a good error message as to where the Mach-O file comes from in
1866 // the error message.
Jordan Rupprecht16a0de22018-12-20 00:57:06 +00001867 if (Disassemble || IndirectSymbols || !FilterSections.empty() || UnwindInfo)
Kevin Enderby844c4ac2016-11-15 23:07:41 +00001868 if (Error Err = MachOOF->checkSymbolTable())
1869 report_error(ArchiveName, FileName, std::move(Err), ArchitectureName);
Michael Trent7e660212019-01-15 20:41:30 +00001870
1871 if (DisassembleAll) {
1872 for (const SectionRef &Section : MachOOF->sections()) {
1873 StringRef SectName;
1874 Section.getName(SectName);
1875 if (SectName.equals("__text")) {
1876 DataRefImpl Ref = Section.getRawDataRefImpl();
1877 StringRef SegName = MachOOF->getSectionFinalSegmentName(Ref);
1878 DisassembleMachO(FileName, MachOOF, SegName, SectName);
1879 }
1880 }
1881 }
1882 else if (Disassemble) {
Kevin Enderbyaf2999a2017-06-22 19:50:56 +00001883 if (MachOOF->getHeader().filetype == MachO::MH_KEXT_BUNDLE &&
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +00001884 MachOOF->getHeader().cputype == MachO::CPU_TYPE_ARM64)
Kevin Enderbyaf2999a2017-06-22 19:50:56 +00001885 DisassembleMachO(FileName, MachOOF, "__TEXT_EXEC", "__text");
1886 else
1887 DisassembleMachO(FileName, MachOOF, "__TEXT", "__text");
1888 }
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +00001889 if (IndirectSymbols)
Kevin Enderbyf0640752015-03-13 17:56:32 +00001890 PrintIndirectSymbols(MachOOF, !NonVerbose);
Kevin Enderby69fe98d2015-01-23 18:52:17 +00001891 if (DataInCode)
Kevin Enderbyf0640752015-03-13 17:56:32 +00001892 PrintDataInCodeTable(MachOOF, !NonVerbose);
Kevin Enderby9a509442015-01-27 21:28:24 +00001893 if (LinkOptHints)
1894 PrintLinkOptHints(MachOOF);
Kevin Enderby98da6132015-01-20 21:47:46 +00001895 if (Relocations)
Michael Trenta1703b12017-12-15 17:57:40 +00001896 PrintRelocations(MachOOF, !NonVerbose);
Kevin Enderby98da6132015-01-20 21:47:46 +00001897 if (SectionHeaders)
George Rimar73a27232019-01-15 09:19:18 +00001898 printSectionHeaders(MachOOF);
Kevin Enderby98da6132015-01-20 21:47:46 +00001899 if (SectionContents)
George Rimar73a27232019-01-15 09:19:18 +00001900 printSectionContents(MachOOF);
Jordan Rupprecht16a0de22018-12-20 00:57:06 +00001901 if (!FilterSections.empty())
Kevin Enderby844c4ac2016-11-15 23:07:41 +00001902 DumpSectionContents(FileName, MachOOF, !NonVerbose);
Kevin Enderbycd66be52015-03-11 22:06:32 +00001903 if (InfoPlist)
Kevin Enderby844c4ac2016-11-15 23:07:41 +00001904 DumpInfoPlistSectionContents(FileName, MachOOF);
Kevin Enderbybc847fa2015-03-16 20:08:09 +00001905 if (DylibsUsed)
1906 PrintDylibs(MachOOF, false);
1907 if (DylibId)
1908 PrintDylibs(MachOOF, true);
Kevin Enderby844c4ac2016-11-15 23:07:41 +00001909 if (SymbolTable)
George Rimar73a27232019-01-15 09:19:18 +00001910 printSymbolTable(MachOOF, ArchiveName, ArchitectureName);
Kevin Enderby98da6132015-01-20 21:47:46 +00001911 if (UnwindInfo)
1912 printMachOUnwindInfo(MachOOF);
Kevin Enderby0ae163f2016-01-13 00:25:36 +00001913 if (PrivateHeaders) {
1914 printMachOFileHeader(MachOOF);
1915 printMachOLoadCommands(MachOOF);
1916 }
1917 if (FirstPrivateHeader)
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001918 printMachOFileHeader(MachOOF);
Kevin Enderby0fc11822015-04-01 20:57:01 +00001919 if (ObjcMetaData)
1920 printObjcMetaData(MachOOF, !NonVerbose);
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001921 if (ExportsTrie)
1922 printExportsTrie(MachOOF);
1923 if (Rebase)
1924 printRebaseTable(MachOOF);
1925 if (Bind)
1926 printBindTable(MachOOF);
1927 if (LazyBind)
1928 printLazyBindTable(MachOOF);
1929 if (WeakBind)
1930 printWeakBindTable(MachOOF);
Igor Laevsky03a670c2016-01-26 15:09:42 +00001931
1932 if (DwarfDumpType != DIDT_Null) {
Rafael Espindolac398e672017-07-19 22:27:28 +00001933 std::unique_ptr<DIContext> DICtx = DWARFContext::create(*MachOOF);
Igor Laevsky03a670c2016-01-26 15:09:42 +00001934 // Dump the complete DWARF structure.
Adrian Prantlf4bc1f72017-06-01 18:18:23 +00001935 DIDumpOptions DumpOpts;
1936 DumpOpts.DumpType = DwarfDumpType;
Adrian Prantlf4bc1f72017-06-01 18:18:23 +00001937 DICtx->dump(outs(), DumpOpts);
Igor Laevsky03a670c2016-01-26 15:09:42 +00001938 }
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001939}
1940
Kevin Enderby131d1772015-01-09 19:22:37 +00001941// printUnknownCPUType() helps print_fat_headers for unknown CPU's.
1942static void printUnknownCPUType(uint32_t cputype, uint32_t cpusubtype) {
1943 outs() << " cputype (" << cputype << ")\n";
1944 outs() << " cpusubtype (" << cpusubtype << ")\n";
1945}
1946
1947// printCPUType() helps print_fat_headers by printing the cputype and
1948// pusubtype (symbolically for the one's it knows about).
1949static void printCPUType(uint32_t cputype, uint32_t cpusubtype) {
1950 switch (cputype) {
1951 case MachO::CPU_TYPE_I386:
1952 switch (cpusubtype) {
1953 case MachO::CPU_SUBTYPE_I386_ALL:
1954 outs() << " cputype CPU_TYPE_I386\n";
1955 outs() << " cpusubtype CPU_SUBTYPE_I386_ALL\n";
1956 break;
1957 default:
1958 printUnknownCPUType(cputype, cpusubtype);
1959 break;
1960 }
1961 break;
1962 case MachO::CPU_TYPE_X86_64:
1963 switch (cpusubtype) {
1964 case MachO::CPU_SUBTYPE_X86_64_ALL:
1965 outs() << " cputype CPU_TYPE_X86_64\n";
1966 outs() << " cpusubtype CPU_SUBTYPE_X86_64_ALL\n";
1967 break;
1968 case MachO::CPU_SUBTYPE_X86_64_H:
1969 outs() << " cputype CPU_TYPE_X86_64\n";
1970 outs() << " cpusubtype CPU_SUBTYPE_X86_64_H\n";
1971 break;
1972 default:
1973 printUnknownCPUType(cputype, cpusubtype);
1974 break;
1975 }
1976 break;
1977 case MachO::CPU_TYPE_ARM:
1978 switch (cpusubtype) {
1979 case MachO::CPU_SUBTYPE_ARM_ALL:
1980 outs() << " cputype CPU_TYPE_ARM\n";
1981 outs() << " cpusubtype CPU_SUBTYPE_ARM_ALL\n";
1982 break;
1983 case MachO::CPU_SUBTYPE_ARM_V4T:
1984 outs() << " cputype CPU_TYPE_ARM\n";
1985 outs() << " cpusubtype CPU_SUBTYPE_ARM_V4T\n";
1986 break;
1987 case MachO::CPU_SUBTYPE_ARM_V5TEJ:
1988 outs() << " cputype CPU_TYPE_ARM\n";
1989 outs() << " cpusubtype CPU_SUBTYPE_ARM_V5TEJ\n";
1990 break;
1991 case MachO::CPU_SUBTYPE_ARM_XSCALE:
1992 outs() << " cputype CPU_TYPE_ARM\n";
1993 outs() << " cpusubtype CPU_SUBTYPE_ARM_XSCALE\n";
1994 break;
1995 case MachO::CPU_SUBTYPE_ARM_V6:
1996 outs() << " cputype CPU_TYPE_ARM\n";
1997 outs() << " cpusubtype CPU_SUBTYPE_ARM_V6\n";
1998 break;
1999 case MachO::CPU_SUBTYPE_ARM_V6M:
2000 outs() << " cputype CPU_TYPE_ARM\n";
2001 outs() << " cpusubtype CPU_SUBTYPE_ARM_V6M\n";
2002 break;
2003 case MachO::CPU_SUBTYPE_ARM_V7:
2004 outs() << " cputype CPU_TYPE_ARM\n";
2005 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7\n";
2006 break;
2007 case MachO::CPU_SUBTYPE_ARM_V7EM:
2008 outs() << " cputype CPU_TYPE_ARM\n";
2009 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7EM\n";
2010 break;
2011 case MachO::CPU_SUBTYPE_ARM_V7K:
2012 outs() << " cputype CPU_TYPE_ARM\n";
2013 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7K\n";
2014 break;
2015 case MachO::CPU_SUBTYPE_ARM_V7M:
2016 outs() << " cputype CPU_TYPE_ARM\n";
2017 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7M\n";
2018 break;
2019 case MachO::CPU_SUBTYPE_ARM_V7S:
2020 outs() << " cputype CPU_TYPE_ARM\n";
2021 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7S\n";
2022 break;
2023 default:
2024 printUnknownCPUType(cputype, cpusubtype);
2025 break;
2026 }
2027 break;
2028 case MachO::CPU_TYPE_ARM64:
2029 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
2030 case MachO::CPU_SUBTYPE_ARM64_ALL:
2031 outs() << " cputype CPU_TYPE_ARM64\n";
2032 outs() << " cpusubtype CPU_SUBTYPE_ARM64_ALL\n";
2033 break;
2034 default:
2035 printUnknownCPUType(cputype, cpusubtype);
2036 break;
2037 }
2038 break;
2039 default:
2040 printUnknownCPUType(cputype, cpusubtype);
2041 break;
2042 }
2043}
2044
2045static void printMachOUniversalHeaders(const object::MachOUniversalBinary *UB,
2046 bool verbose) {
2047 outs() << "Fat headers\n";
Kevin Enderby606a3382016-06-21 21:55:01 +00002048 if (verbose) {
2049 if (UB->getMagic() == MachO::FAT_MAGIC)
2050 outs() << "fat_magic FAT_MAGIC\n";
2051 else // UB->getMagic() == MachO::FAT_MAGIC_64
2052 outs() << "fat_magic FAT_MAGIC_64\n";
2053 } else
Kevin Enderby131d1772015-01-09 19:22:37 +00002054 outs() << "fat_magic " << format("0x%" PRIx32, MachO::FAT_MAGIC) << "\n";
2055
2056 uint32_t nfat_arch = UB->getNumberOfObjects();
2057 StringRef Buf = UB->getData();
2058 uint64_t size = Buf.size();
2059 uint64_t big_size = sizeof(struct MachO::fat_header) +
2060 nfat_arch * sizeof(struct MachO::fat_arch);
2061 outs() << "nfat_arch " << UB->getNumberOfObjects();
2062 if (nfat_arch == 0)
2063 outs() << " (malformed, contains zero architecture types)\n";
2064 else if (big_size > size)
2065 outs() << " (malformed, architectures past end of file)\n";
2066 else
2067 outs() << "\n";
2068
2069 for (uint32_t i = 0; i < nfat_arch; ++i) {
2070 MachOUniversalBinary::ObjectForArch OFA(UB, i);
2071 uint32_t cputype = OFA.getCPUType();
2072 uint32_t cpusubtype = OFA.getCPUSubType();
2073 outs() << "architecture ";
2074 for (uint32_t j = 0; i != 0 && j <= i - 1; j++) {
2075 MachOUniversalBinary::ObjectForArch other_OFA(UB, j);
2076 uint32_t other_cputype = other_OFA.getCPUType();
2077 uint32_t other_cpusubtype = other_OFA.getCPUSubType();
Kevin Enderby0512bd72015-01-09 21:55:03 +00002078 if (cputype != 0 && cpusubtype != 0 && cputype == other_cputype &&
Kevin Enderby131d1772015-01-09 19:22:37 +00002079 (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) ==
Kevin Enderby0512bd72015-01-09 21:55:03 +00002080 (other_cpusubtype & ~MachO::CPU_SUBTYPE_MASK)) {
Kevin Enderby131d1772015-01-09 19:22:37 +00002081 outs() << "(illegal duplicate architecture) ";
2082 break;
Kevin Enderby0512bd72015-01-09 21:55:03 +00002083 }
Kevin Enderby131d1772015-01-09 19:22:37 +00002084 }
2085 if (verbose) {
Kevin Enderby59343a92016-12-16 22:54:02 +00002086 outs() << OFA.getArchFlagName() << "\n";
Kevin Enderby131d1772015-01-09 19:22:37 +00002087 printCPUType(cputype, cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
2088 } else {
2089 outs() << i << "\n";
2090 outs() << " cputype " << cputype << "\n";
2091 outs() << " cpusubtype " << (cpusubtype & ~MachO::CPU_SUBTYPE_MASK)
2092 << "\n";
2093 }
2094 if (verbose &&
2095 (cpusubtype & MachO::CPU_SUBTYPE_MASK) == MachO::CPU_SUBTYPE_LIB64)
2096 outs() << " capabilities CPU_SUBTYPE_LIB64\n";
2097 else
2098 outs() << " capabilities "
2099 << format("0x%" PRIx32,
2100 (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24) << "\n";
2101 outs() << " offset " << OFA.getOffset();
2102 if (OFA.getOffset() > size)
2103 outs() << " (past end of file)";
2104 if (OFA.getOffset() % (1 << OFA.getAlign()) != 0)
2105 outs() << " (not aligned on it's alignment (2^" << OFA.getAlign() << ")";
2106 outs() << "\n";
2107 outs() << " size " << OFA.getSize();
2108 big_size = OFA.getOffset() + OFA.getSize();
2109 if (big_size > size)
2110 outs() << " (past end of file)";
2111 outs() << "\n";
2112 outs() << " align 2^" << OFA.getAlign() << " (" << (1 << OFA.getAlign())
2113 << ")\n";
2114 }
2115}
2116
Kevin Enderby6524bd82016-07-19 20:47:07 +00002117static void printArchiveChild(StringRef Filename, const Archive::Child &C,
2118 bool verbose, bool print_offset,
2119 StringRef ArchitectureName = StringRef()) {
Kevin Enderby13023a12015-01-15 23:19:11 +00002120 if (print_offset)
2121 outs() << C.getChildOffset() << "\t";
Vedant Kumar4031d9f2016-08-03 19:02:50 +00002122 Expected<sys::fs::perms> ModeOrErr = C.getAccessMode();
2123 if (!ModeOrErr)
2124 report_error(Filename, C, ModeOrErr.takeError(), ArchitectureName);
2125 sys::fs::perms Mode = ModeOrErr.get();
Kevin Enderby13023a12015-01-15 23:19:11 +00002126 if (verbose) {
2127 // FIXME: this first dash, "-", is for (Mode & S_IFMT) == S_IFREG.
2128 // But there is nothing in sys::fs::perms for S_IFMT or S_IFREG.
2129 outs() << "-";
Davide Italianobb9a6cc2015-09-07 20:47:03 +00002130 outs() << ((Mode & sys::fs::owner_read) ? "r" : "-");
2131 outs() << ((Mode & sys::fs::owner_write) ? "w" : "-");
2132 outs() << ((Mode & sys::fs::owner_exe) ? "x" : "-");
2133 outs() << ((Mode & sys::fs::group_read) ? "r" : "-");
2134 outs() << ((Mode & sys::fs::group_write) ? "w" : "-");
2135 outs() << ((Mode & sys::fs::group_exe) ? "x" : "-");
2136 outs() << ((Mode & sys::fs::others_read) ? "r" : "-");
2137 outs() << ((Mode & sys::fs::others_write) ? "w" : "-");
2138 outs() << ((Mode & sys::fs::others_exe) ? "x" : "-");
Kevin Enderby13023a12015-01-15 23:19:11 +00002139 } else {
2140 outs() << format("0%o ", Mode);
2141 }
2142
Vedant Kumar4031d9f2016-08-03 19:02:50 +00002143 Expected<unsigned> UIDOrErr = C.getUID();
2144 if (!UIDOrErr)
2145 report_error(Filename, C, UIDOrErr.takeError(), ArchitectureName);
2146 unsigned UID = UIDOrErr.get();
Kevin Enderby13023a12015-01-15 23:19:11 +00002147 outs() << format("%3d/", UID);
Vedant Kumar4031d9f2016-08-03 19:02:50 +00002148 Expected<unsigned> GIDOrErr = C.getGID();
2149 if (!GIDOrErr)
2150 report_error(Filename, C, GIDOrErr.takeError(), ArchitectureName);
2151 unsigned GID = GIDOrErr.get();
Kevin Enderby13023a12015-01-15 23:19:11 +00002152 outs() << format("%-3d ", GID);
Kevin Enderby6524bd82016-07-19 20:47:07 +00002153 Expected<uint64_t> Size = C.getRawSize();
2154 if (!Size)
2155 report_error(Filename, C, Size.takeError(), ArchitectureName);
Kevin Enderby7a969422015-11-05 19:24:56 +00002156 outs() << format("%5" PRId64, Size.get()) << " ";
Kevin Enderby13023a12015-01-15 23:19:11 +00002157
2158 StringRef RawLastModified = C.getRawLastModified();
2159 if (verbose) {
2160 unsigned Seconds;
2161 if (RawLastModified.getAsInteger(10, Seconds))
Vedant Kumar4031d9f2016-08-03 19:02:50 +00002162 outs() << "(date: \"" << RawLastModified
2163 << "\" contains non-decimal chars) ";
Kevin Enderby13023a12015-01-15 23:19:11 +00002164 else {
2165 // Since cime(3) returns a 26 character string of the form:
2166 // "Sun Sep 16 01:03:52 1973\n\0"
2167 // just print 24 characters.
2168 time_t t = Seconds;
2169 outs() << format("%.24s ", ctime(&t));
2170 }
2171 } else {
2172 outs() << RawLastModified << " ";
2173 }
2174
2175 if (verbose) {
Kevin Enderbyf4586032016-07-29 17:44:13 +00002176 Expected<StringRef> NameOrErr = C.getName();
2177 if (!NameOrErr) {
2178 consumeError(NameOrErr.takeError());
2179 Expected<StringRef> NameOrErr = C.getRawName();
2180 if (!NameOrErr)
2181 report_error(Filename, C, NameOrErr.takeError(), ArchitectureName);
2182 StringRef RawName = NameOrErr.get();
Kevin Enderby13023a12015-01-15 23:19:11 +00002183 outs() << RawName << "\n";
2184 } else {
2185 StringRef Name = NameOrErr.get();
2186 outs() << Name << "\n";
2187 }
2188 } else {
Kevin Enderbyf4586032016-07-29 17:44:13 +00002189 Expected<StringRef> NameOrErr = C.getRawName();
2190 if (!NameOrErr)
2191 report_error(Filename, C, NameOrErr.takeError(), ArchitectureName);
2192 StringRef RawName = NameOrErr.get();
Kevin Enderby13023a12015-01-15 23:19:11 +00002193 outs() << RawName << "\n";
2194 }
2195}
2196
Kevin Enderby6524bd82016-07-19 20:47:07 +00002197static void printArchiveHeaders(StringRef Filename, Archive *A, bool verbose,
2198 bool print_offset,
2199 StringRef ArchitectureName = StringRef()) {
Mehdi Amini41af4302016-11-11 04:28:40 +00002200 Error Err = Error::success();
2201 ;
Lang Hamesfc209622016-07-14 02:24:01 +00002202 for (const auto &C : A->children(Err, false))
Kevin Enderby6524bd82016-07-19 20:47:07 +00002203 printArchiveChild(Filename, C, verbose, print_offset, ArchitectureName);
2204
Lang Hamesfc209622016-07-14 02:24:01 +00002205 if (Err)
Kevin Enderby844c4ac2016-11-15 23:07:41 +00002206 report_error(StringRef(), Filename, std::move(Err), ArchitectureName);
Kevin Enderby13023a12015-01-15 23:19:11 +00002207}
2208
Dave Lee3fb120f2018-08-03 00:06:38 +00002209static bool ValidateArchFlags() {
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00002210 // Check for -arch all and verifiy the -arch flags are valid.
2211 for (unsigned i = 0; i < ArchFlags.size(); ++i) {
2212 if (ArchFlags[i] == "all") {
2213 ArchAll = true;
2214 } else {
2215 if (!MachOObjectFile::isValidArch(ArchFlags[i])) {
Jonas Devliegheree787efd2018-11-11 22:12:04 +00002216 WithColor::error(errs(), "llvm-objdump")
2217 << "unknown architecture named '" + ArchFlags[i] +
2218 "'for the -arch option\n";
Dave Lee3fb120f2018-08-03 00:06:38 +00002219 return false;
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00002220 }
2221 }
2222 }
Dave Lee3fb120f2018-08-03 00:06:38 +00002223 return true;
2224}
2225
2226// ParseInputMachO() parses the named Mach-O file in Filename and handles the
2227// -arch flags selecting just those slices as specified by them and also parses
2228// archive files. Then for each individual Mach-O file ProcessMachO() is
2229// called to process the file based on the command line options.
George Rimar73a27232019-01-15 09:19:18 +00002230void llvm::parseInputMachO(StringRef Filename) {
Dave Lee3fb120f2018-08-03 00:06:38 +00002231 if (!ValidateArchFlags())
2232 return;
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00002233
2234 // Attempt to open the binary.
Kevin Enderby3fcdf6a2016-04-06 22:14:09 +00002235 Expected<OwningBinary<Binary>> BinaryOrErr = createBinary(Filename);
Kevin Enderby98898f22017-01-30 20:53:17 +00002236 if (!BinaryOrErr) {
2237 if (auto E = isNotObjectErrorInvalidFileType(BinaryOrErr.takeError()))
2238 report_error(Filename, std::move(E));
2239 else
2240 outs() << Filename << ": is not an object file\n";
2241 return;
2242 }
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00002243 Binary &Bin = *BinaryOrErr.get().getBinary();
Kevin Enderby3f0ffab2014-12-03 22:29:40 +00002244
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00002245 if (Archive *A = dyn_cast<Archive>(&Bin)) {
2246 outs() << "Archive : " << Filename << "\n";
Kevin Enderby13023a12015-01-15 23:19:11 +00002247 if (ArchiveHeaders)
Kevin Enderby6524bd82016-07-19 20:47:07 +00002248 printArchiveHeaders(Filename, A, !NonVerbose, ArchiveMemberOffsets);
2249
Mehdi Amini41af4302016-11-11 04:28:40 +00002250 Error Err = Error::success();
Lang Hamesfc209622016-07-14 02:24:01 +00002251 for (auto &C : A->children(Err)) {
Kevin Enderbyac9e1552016-05-17 17:10:12 +00002252 Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
2253 if (!ChildOrErr) {
2254 if (auto E = isNotObjectErrorInvalidFileType(ChildOrErr.takeError()))
2255 report_error(Filename, C, std::move(E));
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00002256 continue;
Kevin Enderbyac9e1552016-05-17 17:10:12 +00002257 }
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00002258 if (MachOObjectFile *O = dyn_cast<MachOObjectFile>(&*ChildOrErr.get())) {
2259 if (!checkMachOAndArchFlags(O, Filename))
2260 return;
Kevin Enderbye2297dd2015-01-07 21:02:18 +00002261 ProcessMachO(Filename, O, O->getFileName());
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00002262 }
2263 }
Lang Hamesfc209622016-07-14 02:24:01 +00002264 if (Err)
2265 report_error(Filename, std::move(Err));
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00002266 return;
2267 }
2268 if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(&Bin)) {
George Rimar73a27232019-01-15 09:19:18 +00002269 parseInputMachO(UB);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00002270 return;
2271 }
2272 if (ObjectFile *O = dyn_cast<ObjectFile>(&Bin)) {
2273 if (!checkMachOAndArchFlags(O, Filename))
2274 return;
Dave Lee3fb120f2018-08-03 00:06:38 +00002275 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&*O))
Kevin Enderbye2297dd2015-01-07 21:02:18 +00002276 ProcessMachO(Filename, MachOOF);
Dave Lee3fb120f2018-08-03 00:06:38 +00002277 else
Jonas Devliegheree787efd2018-11-11 22:12:04 +00002278 WithColor::error(errs(), "llvm-objdump")
2279 << Filename << "': "
2280 << "object is not a Mach-O file type.\n";
Davide Italiano25d84582016-01-13 04:11:36 +00002281 return;
2282 }
2283 llvm_unreachable("Input object can't be invalid at this point");
Rafael Espindola9b709252013-04-13 01:45:40 +00002284}
2285
George Rimar73a27232019-01-15 09:19:18 +00002286void llvm::parseInputMachO(MachOUniversalBinary *UB) {
Dave Lee3fb120f2018-08-03 00:06:38 +00002287 if (!ValidateArchFlags())
2288 return;
2289
2290 auto Filename = UB->getFileName();
2291
2292 if (UniversalHeaders)
2293 printMachOUniversalHeaders(UB, !NonVerbose);
2294
2295 // If we have a list of architecture flags specified dump only those.
Jordan Rupprecht16a0de22018-12-20 00:57:06 +00002296 if (!ArchAll && !ArchFlags.empty()) {
Dave Lee3fb120f2018-08-03 00:06:38 +00002297 // Look for a slice in the universal binary that matches each ArchFlag.
2298 bool ArchFound;
2299 for (unsigned i = 0; i < ArchFlags.size(); ++i) {
2300 ArchFound = false;
2301 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
2302 E = UB->end_objects();
2303 I != E; ++I) {
2304 if (ArchFlags[i] == I->getArchFlagName()) {
2305 ArchFound = true;
2306 Expected<std::unique_ptr<ObjectFile>> ObjOrErr =
2307 I->getAsObjectFile();
2308 std::string ArchitectureName = "";
2309 if (ArchFlags.size() > 1)
2310 ArchitectureName = I->getArchFlagName();
2311 if (ObjOrErr) {
2312 ObjectFile &O = *ObjOrErr.get();
2313 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&O))
2314 ProcessMachO(Filename, MachOOF, "", ArchitectureName);
2315 } else if (auto E = isNotObjectErrorInvalidFileType(
2316 ObjOrErr.takeError())) {
2317 report_error(Filename, StringRef(), std::move(E),
2318 ArchitectureName);
2319 continue;
2320 } else if (Expected<std::unique_ptr<Archive>> AOrErr =
2321 I->getAsArchive()) {
2322 std::unique_ptr<Archive> &A = *AOrErr;
2323 outs() << "Archive : " << Filename;
2324 if (!ArchitectureName.empty())
2325 outs() << " (architecture " << ArchitectureName << ")";
2326 outs() << "\n";
2327 if (ArchiveHeaders)
2328 printArchiveHeaders(Filename, A.get(), !NonVerbose,
2329 ArchiveMemberOffsets, ArchitectureName);
2330 Error Err = Error::success();
2331 for (auto &C : A->children(Err)) {
2332 Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
2333 if (!ChildOrErr) {
2334 if (auto E = isNotObjectErrorInvalidFileType(ChildOrErr.takeError()))
2335 report_error(Filename, C, std::move(E), ArchitectureName);
2336 continue;
2337 }
2338 if (MachOObjectFile *O =
2339 dyn_cast<MachOObjectFile>(&*ChildOrErr.get()))
2340 ProcessMachO(Filename, O, O->getFileName(), ArchitectureName);
2341 }
2342 if (Err)
2343 report_error(Filename, std::move(Err));
2344 } else {
2345 consumeError(AOrErr.takeError());
2346 error("Mach-O universal file: " + Filename + " for " +
2347 "architecture " + StringRef(I->getArchFlagName()) +
2348 " is not a Mach-O file or an archive file");
2349 }
2350 }
2351 }
2352 if (!ArchFound) {
Jonas Devliegheree787efd2018-11-11 22:12:04 +00002353 WithColor::error(errs(), "llvm-objdump")
2354 << "file: " + Filename + " does not contain "
2355 << "architecture: " + ArchFlags[i] + "\n";
Dave Lee3fb120f2018-08-03 00:06:38 +00002356 return;
2357 }
2358 }
2359 return;
2360 }
2361 // No architecture flags were specified so if this contains a slice that
2362 // matches the host architecture dump only that.
2363 if (!ArchAll) {
2364 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
2365 E = UB->end_objects();
2366 I != E; ++I) {
2367 if (MachOObjectFile::getHostArch().getArchName() ==
2368 I->getArchFlagName()) {
2369 Expected<std::unique_ptr<ObjectFile>> ObjOrErr = I->getAsObjectFile();
2370 std::string ArchiveName;
2371 ArchiveName.clear();
2372 if (ObjOrErr) {
2373 ObjectFile &O = *ObjOrErr.get();
2374 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&O))
2375 ProcessMachO(Filename, MachOOF);
2376 } else if (auto E = isNotObjectErrorInvalidFileType(
2377 ObjOrErr.takeError())) {
2378 report_error(Filename, std::move(E));
Dave Lee3fb120f2018-08-03 00:06:38 +00002379 } else if (Expected<std::unique_ptr<Archive>> AOrErr =
2380 I->getAsArchive()) {
2381 std::unique_ptr<Archive> &A = *AOrErr;
2382 outs() << "Archive : " << Filename << "\n";
2383 if (ArchiveHeaders)
2384 printArchiveHeaders(Filename, A.get(), !NonVerbose,
2385 ArchiveMemberOffsets);
2386 Error Err = Error::success();
2387 for (auto &C : A->children(Err)) {
2388 Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
2389 if (!ChildOrErr) {
2390 if (auto E = isNotObjectErrorInvalidFileType(ChildOrErr.takeError()))
2391 report_error(Filename, C, std::move(E));
2392 continue;
2393 }
2394 if (MachOObjectFile *O =
2395 dyn_cast<MachOObjectFile>(&*ChildOrErr.get()))
2396 ProcessMachO(Filename, O, O->getFileName());
2397 }
2398 if (Err)
2399 report_error(Filename, std::move(Err));
2400 } else {
2401 consumeError(AOrErr.takeError());
2402 error("Mach-O universal file: " + Filename + " for architecture " +
2403 StringRef(I->getArchFlagName()) +
2404 " is not a Mach-O file or an archive file");
2405 }
2406 return;
2407 }
2408 }
2409 }
2410 // Either all architectures have been specified or none have been specified
2411 // and this does not contain the host architecture so dump all the slices.
2412 bool moreThanOneArch = UB->getNumberOfObjects() > 1;
2413 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
2414 E = UB->end_objects();
2415 I != E; ++I) {
2416 Expected<std::unique_ptr<ObjectFile>> ObjOrErr = I->getAsObjectFile();
2417 std::string ArchitectureName = "";
2418 if (moreThanOneArch)
2419 ArchitectureName = I->getArchFlagName();
2420 if (ObjOrErr) {
2421 ObjectFile &Obj = *ObjOrErr.get();
2422 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&Obj))
2423 ProcessMachO(Filename, MachOOF, "", ArchitectureName);
2424 } else if (auto E = isNotObjectErrorInvalidFileType(
2425 ObjOrErr.takeError())) {
2426 report_error(StringRef(), Filename, std::move(E), ArchitectureName);
Dave Lee3fb120f2018-08-03 00:06:38 +00002427 } else if (Expected<std::unique_ptr<Archive>> AOrErr =
2428 I->getAsArchive()) {
2429 std::unique_ptr<Archive> &A = *AOrErr;
2430 outs() << "Archive : " << Filename;
2431 if (!ArchitectureName.empty())
2432 outs() << " (architecture " << ArchitectureName << ")";
2433 outs() << "\n";
2434 if (ArchiveHeaders)
2435 printArchiveHeaders(Filename, A.get(), !NonVerbose,
2436 ArchiveMemberOffsets, ArchitectureName);
2437 Error Err = Error::success();
2438 for (auto &C : A->children(Err)) {
2439 Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
2440 if (!ChildOrErr) {
2441 if (auto E = isNotObjectErrorInvalidFileType(ChildOrErr.takeError()))
2442 report_error(Filename, C, std::move(E), ArchitectureName);
2443 continue;
2444 }
2445 if (MachOObjectFile *O =
2446 dyn_cast<MachOObjectFile>(&*ChildOrErr.get())) {
2447 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(O))
2448 ProcessMachO(Filename, MachOOF, MachOOF->getFileName(),
2449 ArchitectureName);
2450 }
2451 }
2452 if (Err)
2453 report_error(Filename, std::move(Err));
2454 } else {
2455 consumeError(AOrErr.takeError());
2456 error("Mach-O universal file: " + Filename + " for architecture " +
2457 StringRef(I->getArchFlagName()) +
2458 " is not a Mach-O file or an archive file");
2459 }
2460 }
2461}
2462
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002463// The block of info used by the Symbolizer call backs.
2464struct DisassembleInfo {
Serge Pavlove4e9a1f2018-02-14 03:26:27 +00002465 DisassembleInfo(MachOObjectFile *O, SymbolAddressMap *AddrMap,
2466 std::vector<SectionRef> *Sections, bool verbose)
2467 : verbose(verbose), O(O), AddrMap(AddrMap), Sections(Sections) {}
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002468 bool verbose;
2469 MachOObjectFile *O;
2470 SectionRef S;
Kevin Enderbybf246f52014-09-24 23:08:22 +00002471 SymbolAddressMap *AddrMap;
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002472 std::vector<SectionRef> *Sections;
Serge Pavlove4e9a1f2018-02-14 03:26:27 +00002473 const char *class_name = nullptr;
2474 const char *selector_name = nullptr;
David Blaikie0e550682018-02-20 18:48:51 +00002475 std::unique_ptr<char[]> method = nullptr;
Serge Pavlove4e9a1f2018-02-14 03:26:27 +00002476 char *demangled_name = nullptr;
2477 uint64_t adrp_addr = 0;
2478 uint32_t adrp_inst = 0;
Saleem Abdulrasool1d84d9a2017-01-08 19:14:15 +00002479 std::unique_ptr<SymbolAddressMap> bindtable;
Serge Pavlove4e9a1f2018-02-14 03:26:27 +00002480 uint32_t depth = 0;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002481};
2482
2483// SymbolizerGetOpInfo() is the operand information call back function.
2484// This is called to get the symbolic information for operand(s) of an
2485// instruction when it is being done. This routine does this from
2486// the relocation information, symbol table, etc. That block of information
2487// is a pointer to the struct DisassembleInfo that was passed when the
2488// disassembler context was created and passed to back to here when
2489// called back by the disassembler for instruction operands that could have
2490// relocation information. The address of the instruction containing operand is
2491// at the Pc parameter. The immediate value the operand has is passed in
2492// op_info->Value and is at Offset past the start of the instruction and has a
2493// byte Size of 1, 2 or 4. The symbolc information is returned in TagBuf is the
2494// LLVMOpInfo1 struct defined in the header "llvm-c/Disassembler.h" as symbol
2495// names and addends of the symbolic expression to add for the operand. The
2496// value of TagType is currently 1 (for the LLVMOpInfo1 struct). If symbolic
2497// information is returned then this function returns 1 else it returns 0.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00002498static int SymbolizerGetOpInfo(void *DisInfo, uint64_t Pc, uint64_t Offset,
2499 uint64_t Size, int TagType, void *TagBuf) {
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002500 struct DisassembleInfo *info = (struct DisassembleInfo *)DisInfo;
2501 struct LLVMOpInfo1 *op_info = (struct LLVMOpInfo1 *)TagBuf;
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002502 uint64_t value = op_info->Value;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002503
2504 // Make sure all fields returned are zero if we don't set them.
2505 memset((void *)op_info, '\0', sizeof(struct LLVMOpInfo1));
2506 op_info->Value = value;
2507
2508 // If the TagType is not the value 1 which it code knows about or if no
2509 // verbose symbolic information is wanted then just return 0, indicating no
2510 // information is being returned.
David Blaikie33dd45d02015-03-23 18:39:02 +00002511 if (TagType != 1 || !info->verbose)
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002512 return 0;
2513
2514 unsigned int Arch = info->O->getArch();
2515 if (Arch == Triple::x86) {
Kevin Enderby9907d0a2014-11-04 00:43:16 +00002516 if (Size != 1 && Size != 2 && Size != 4 && Size != 0)
2517 return 0;
Kevin Enderbyd90a4172015-10-10 00:05:01 +00002518 if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
2519 // TODO:
2520 // Search the external relocation entries of a fully linked image
2521 // (if any) for an entry that matches this segment offset.
2522 // uint32_t seg_offset = (Pc + Offset);
2523 return 0;
2524 }
2525 // In MH_OBJECT filetypes search the section's relocation entries (if any)
2526 // for an entry for this section offset.
Kevin Enderby9907d0a2014-11-04 00:43:16 +00002527 uint32_t sect_addr = info->S.getAddress();
2528 uint32_t sect_offset = (Pc + Offset) - sect_addr;
2529 bool reloc_found = false;
2530 DataRefImpl Rel;
2531 MachO::any_relocation_info RE;
2532 bool isExtern = false;
2533 SymbolRef Symbol;
2534 bool r_scattered = false;
2535 uint32_t r_value, pair_r_value, r_type;
2536 for (const RelocationRef &Reloc : info->S.relocations()) {
Rafael Espindola96d071c2015-06-29 23:29:12 +00002537 uint64_t RelocOffset = Reloc.getOffset();
Kevin Enderby9907d0a2014-11-04 00:43:16 +00002538 if (RelocOffset == sect_offset) {
2539 Rel = Reloc.getRawDataRefImpl();
2540 RE = info->O->getRelocation(Rel);
Kevin Enderby3eb73e12014-11-11 19:16:45 +00002541 r_type = info->O->getAnyRelocationType(RE);
Kevin Enderby9907d0a2014-11-04 00:43:16 +00002542 r_scattered = info->O->isRelocationScattered(RE);
2543 if (r_scattered) {
2544 r_value = info->O->getScatteredRelocationValue(RE);
Kevin Enderby9907d0a2014-11-04 00:43:16 +00002545 if (r_type == MachO::GENERIC_RELOC_SECTDIFF ||
2546 r_type == MachO::GENERIC_RELOC_LOCAL_SECTDIFF) {
2547 DataRefImpl RelNext = Rel;
2548 info->O->moveRelocationNext(RelNext);
2549 MachO::any_relocation_info RENext;
2550 RENext = info->O->getRelocation(RelNext);
2551 if (info->O->isRelocationScattered(RENext))
Kevin Enderby930fdc72014-11-06 19:00:13 +00002552 pair_r_value = info->O->getScatteredRelocationValue(RENext);
Kevin Enderby9907d0a2014-11-04 00:43:16 +00002553 else
2554 return 0;
2555 }
2556 } else {
2557 isExtern = info->O->getPlainRelocationExternal(RE);
2558 if (isExtern) {
2559 symbol_iterator RelocSym = Reloc.getSymbol();
2560 Symbol = *RelocSym;
2561 }
2562 }
2563 reloc_found = true;
2564 break;
2565 }
2566 }
2567 if (reloc_found && isExtern) {
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00002568 Expected<StringRef> SymName = Symbol.getName();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00002569 if (!SymName)
2570 report_error(info->O->getFileName(), SymName.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00002571 const char *name = SymName->data();
Kevin Enderby9907d0a2014-11-04 00:43:16 +00002572 op_info->AddSymbol.Present = 1;
2573 op_info->AddSymbol.Name = name;
2574 // For i386 extern relocation entries the value in the instruction is
2575 // the offset from the symbol, and value is already set in op_info->Value.
2576 return 1;
2577 }
2578 if (reloc_found && (r_type == MachO::GENERIC_RELOC_SECTDIFF ||
2579 r_type == MachO::GENERIC_RELOC_LOCAL_SECTDIFF)) {
Kevin Enderbyf6d25852015-01-31 00:37:11 +00002580 const char *add = GuessSymbolName(r_value, info->AddrMap);
2581 const char *sub = GuessSymbolName(pair_r_value, info->AddrMap);
Kevin Enderby9907d0a2014-11-04 00:43:16 +00002582 uint32_t offset = value - (r_value - pair_r_value);
2583 op_info->AddSymbol.Present = 1;
2584 if (add != nullptr)
2585 op_info->AddSymbol.Name = add;
2586 else
2587 op_info->AddSymbol.Value = r_value;
2588 op_info->SubtractSymbol.Present = 1;
2589 if (sub != nullptr)
2590 op_info->SubtractSymbol.Name = sub;
2591 else
2592 op_info->SubtractSymbol.Value = pair_r_value;
2593 op_info->Value = offset;
2594 return 1;
2595 }
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002596 return 0;
David Blaikie33dd45d02015-03-23 18:39:02 +00002597 }
2598 if (Arch == Triple::x86_64) {
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002599 if (Size != 1 && Size != 2 && Size != 4 && Size != 0)
2600 return 0;
Kevin Enderbyabf10f22017-06-22 17:41:22 +00002601 // For non MH_OBJECT types, like MH_KEXT_BUNDLE, Search the external
2602 // relocation entries of a linked image (if any) for an entry that matches
2603 // this segment offset.
Kevin Enderbyd90a4172015-10-10 00:05:01 +00002604 if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
Kevin Enderbyabf10f22017-06-22 17:41:22 +00002605 uint64_t seg_offset = Pc + Offset;
2606 bool reloc_found = false;
2607 DataRefImpl Rel;
2608 MachO::any_relocation_info RE;
2609 bool isExtern = false;
2610 SymbolRef Symbol;
2611 for (const RelocationRef &Reloc : info->O->external_relocations()) {
2612 uint64_t RelocOffset = Reloc.getOffset();
2613 if (RelocOffset == seg_offset) {
2614 Rel = Reloc.getRawDataRefImpl();
2615 RE = info->O->getRelocation(Rel);
2616 // external relocation entries should always be external.
2617 isExtern = info->O->getPlainRelocationExternal(RE);
2618 if (isExtern) {
2619 symbol_iterator RelocSym = Reloc.getSymbol();
2620 Symbol = *RelocSym;
2621 }
2622 reloc_found = true;
2623 break;
2624 }
2625 }
2626 if (reloc_found && isExtern) {
2627 // The Value passed in will be adjusted by the Pc if the instruction
2628 // adds the Pc. But for x86_64 external relocation entries the Value
2629 // is the offset from the external symbol.
2630 if (info->O->getAnyRelocationPCRel(RE))
2631 op_info->Value -= Pc + Offset + Size;
2632 Expected<StringRef> SymName = Symbol.getName();
2633 if (!SymName)
2634 report_error(info->O->getFileName(), SymName.takeError());
2635 const char *name = SymName->data();
2636 op_info->AddSymbol.Present = 1;
2637 op_info->AddSymbol.Name = name;
2638 return 1;
2639 }
Kevin Enderbyd90a4172015-10-10 00:05:01 +00002640 return 0;
2641 }
2642 // In MH_OBJECT filetypes search the section's relocation entries (if any)
2643 // for an entry for this section offset.
Rafael Espindola80291272014-10-08 15:28:58 +00002644 uint64_t sect_addr = info->S.getAddress();
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002645 uint64_t sect_offset = (Pc + Offset) - sect_addr;
2646 bool reloc_found = false;
2647 DataRefImpl Rel;
2648 MachO::any_relocation_info RE;
2649 bool isExtern = false;
2650 SymbolRef Symbol;
2651 for (const RelocationRef &Reloc : info->S.relocations()) {
Rafael Espindola96d071c2015-06-29 23:29:12 +00002652 uint64_t RelocOffset = Reloc.getOffset();
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002653 if (RelocOffset == sect_offset) {
2654 Rel = Reloc.getRawDataRefImpl();
2655 RE = info->O->getRelocation(Rel);
2656 // NOTE: Scattered relocations don't exist on x86_64.
2657 isExtern = info->O->getPlainRelocationExternal(RE);
2658 if (isExtern) {
2659 symbol_iterator RelocSym = Reloc.getSymbol();
2660 Symbol = *RelocSym;
2661 }
2662 reloc_found = true;
2663 break;
2664 }
2665 }
2666 if (reloc_found && isExtern) {
2667 // The Value passed in will be adjusted by the Pc if the instruction
2668 // adds the Pc. But for x86_64 external relocation entries the Value
2669 // is the offset from the external symbol.
2670 if (info->O->getAnyRelocationPCRel(RE))
2671 op_info->Value -= Pc + Offset + Size;
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00002672 Expected<StringRef> SymName = Symbol.getName();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00002673 if (!SymName)
2674 report_error(info->O->getFileName(), SymName.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00002675 const char *name = SymName->data();
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002676 unsigned Type = info->O->getAnyRelocationType(RE);
2677 if (Type == MachO::X86_64_RELOC_SUBTRACTOR) {
2678 DataRefImpl RelNext = Rel;
2679 info->O->moveRelocationNext(RelNext);
2680 MachO::any_relocation_info RENext = info->O->getRelocation(RelNext);
2681 unsigned TypeNext = info->O->getAnyRelocationType(RENext);
2682 bool isExternNext = info->O->getPlainRelocationExternal(RENext);
2683 unsigned SymbolNum = info->O->getPlainRelocationSymbolNum(RENext);
2684 if (TypeNext == MachO::X86_64_RELOC_UNSIGNED && isExternNext) {
2685 op_info->SubtractSymbol.Present = 1;
2686 op_info->SubtractSymbol.Name = name;
2687 symbol_iterator RelocSymNext = info->O->getSymbolByIndex(SymbolNum);
2688 Symbol = *RelocSymNext;
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00002689 Expected<StringRef> SymNameNext = Symbol.getName();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00002690 if (!SymNameNext)
2691 report_error(info->O->getFileName(), SymNameNext.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00002692 name = SymNameNext->data();
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002693 }
2694 }
2695 // TODO: add the VariantKinds to op_info->VariantKind for relocation types
2696 // like: X86_64_RELOC_TLV, X86_64_RELOC_GOT_LOAD and X86_64_RELOC_GOT.
2697 op_info->AddSymbol.Present = 1;
2698 op_info->AddSymbol.Name = name;
2699 return 1;
2700 }
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002701 return 0;
David Blaikie33dd45d02015-03-23 18:39:02 +00002702 }
2703 if (Arch == Triple::arm) {
Kevin Enderby930fdc72014-11-06 19:00:13 +00002704 if (Offset != 0 || (Size != 4 && Size != 2))
2705 return 0;
Kevin Enderbyd90a4172015-10-10 00:05:01 +00002706 if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
2707 // TODO:
2708 // Search the external relocation entries of a fully linked image
2709 // (if any) for an entry that matches this segment offset.
2710 // uint32_t seg_offset = (Pc + Offset);
2711 return 0;
2712 }
2713 // In MH_OBJECT filetypes search the section's relocation entries (if any)
2714 // for an entry for this section offset.
Kevin Enderby930fdc72014-11-06 19:00:13 +00002715 uint32_t sect_addr = info->S.getAddress();
2716 uint32_t sect_offset = (Pc + Offset) - sect_addr;
Kevin Enderby930fdc72014-11-06 19:00:13 +00002717 DataRefImpl Rel;
2718 MachO::any_relocation_info RE;
2719 bool isExtern = false;
2720 SymbolRef Symbol;
2721 bool r_scattered = false;
2722 uint32_t r_value, pair_r_value, r_type, r_length, other_half;
David Blaikie33dd45d02015-03-23 18:39:02 +00002723 auto Reloc =
David Majnemer562e8292016-08-12 00:18:03 +00002724 find_if(info->S.relocations(), [&](const RelocationRef &Reloc) {
2725 uint64_t RelocOffset = Reloc.getOffset();
2726 return RelocOffset == sect_offset;
2727 });
David Blaikie33dd45d02015-03-23 18:39:02 +00002728
2729 if (Reloc == info->S.relocations().end())
2730 return 0;
2731
2732 Rel = Reloc->getRawDataRefImpl();
2733 RE = info->O->getRelocation(Rel);
2734 r_length = info->O->getAnyRelocationLength(RE);
2735 r_scattered = info->O->isRelocationScattered(RE);
2736 if (r_scattered) {
2737 r_value = info->O->getScatteredRelocationValue(RE);
2738 r_type = info->O->getScatteredRelocationType(RE);
2739 } else {
2740 r_type = info->O->getAnyRelocationType(RE);
2741 isExtern = info->O->getPlainRelocationExternal(RE);
2742 if (isExtern) {
2743 symbol_iterator RelocSym = Reloc->getSymbol();
2744 Symbol = *RelocSym;
Kevin Enderby930fdc72014-11-06 19:00:13 +00002745 }
2746 }
David Blaikie33dd45d02015-03-23 18:39:02 +00002747 if (r_type == MachO::ARM_RELOC_HALF ||
2748 r_type == MachO::ARM_RELOC_SECTDIFF ||
2749 r_type == MachO::ARM_RELOC_LOCAL_SECTDIFF ||
2750 r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
2751 DataRefImpl RelNext = Rel;
2752 info->O->moveRelocationNext(RelNext);
2753 MachO::any_relocation_info RENext;
2754 RENext = info->O->getRelocation(RelNext);
2755 other_half = info->O->getAnyRelocationAddress(RENext) & 0xffff;
2756 if (info->O->isRelocationScattered(RENext))
2757 pair_r_value = info->O->getScatteredRelocationValue(RENext);
2758 }
2759
2760 if (isExtern) {
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00002761 Expected<StringRef> SymName = Symbol.getName();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00002762 if (!SymName)
2763 report_error(info->O->getFileName(), SymName.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00002764 const char *name = SymName->data();
Kevin Enderby930fdc72014-11-06 19:00:13 +00002765 op_info->AddSymbol.Present = 1;
2766 op_info->AddSymbol.Name = name;
Sylvestre Ledru648cced2015-02-05 17:00:23 +00002767 switch (r_type) {
2768 case MachO::ARM_RELOC_HALF:
2769 if ((r_length & 0x1) == 1) {
2770 op_info->Value = value << 16 | other_half;
2771 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
2772 } else {
2773 op_info->Value = other_half << 16 | value;
2774 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
Sylvestre Ledrufe0c7ad2015-02-05 16:35:44 +00002775 }
Sylvestre Ledru648cced2015-02-05 17:00:23 +00002776 break;
2777 default:
2778 break;
Kevin Enderby930fdc72014-11-06 19:00:13 +00002779 }
2780 return 1;
2781 }
2782 // If we have a branch that is not an external relocation entry then
2783 // return 0 so the code in tryAddingSymbolicOperand() can use the
2784 // SymbolLookUp call back with the branch target address to look up the
Simon Pilgrimdae11f72016-11-20 13:31:13 +00002785 // symbol and possibility add an annotation for a symbol stub.
David Blaikie33dd45d02015-03-23 18:39:02 +00002786 if (isExtern == 0 && (r_type == MachO::ARM_RELOC_BR24 ||
2787 r_type == MachO::ARM_THUMB_RELOC_BR22))
Kevin Enderby930fdc72014-11-06 19:00:13 +00002788 return 0;
2789
2790 uint32_t offset = 0;
David Blaikie33dd45d02015-03-23 18:39:02 +00002791 if (r_type == MachO::ARM_RELOC_HALF ||
2792 r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
2793 if ((r_length & 0x1) == 1)
2794 value = value << 16 | other_half;
2795 else
2796 value = other_half << 16 | value;
2797 }
2798 if (r_scattered && (r_type != MachO::ARM_RELOC_HALF &&
2799 r_type != MachO::ARM_RELOC_HALF_SECTDIFF)) {
2800 offset = value - r_value;
2801 value = r_value;
Kevin Enderby930fdc72014-11-06 19:00:13 +00002802 }
2803
David Blaikie33dd45d02015-03-23 18:39:02 +00002804 if (r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
Kevin Enderby930fdc72014-11-06 19:00:13 +00002805 if ((r_length & 0x1) == 1)
2806 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
2807 else
2808 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
Kevin Enderbyf6d25852015-01-31 00:37:11 +00002809 const char *add = GuessSymbolName(r_value, info->AddrMap);
2810 const char *sub = GuessSymbolName(pair_r_value, info->AddrMap);
Kevin Enderby930fdc72014-11-06 19:00:13 +00002811 int32_t offset = value - (r_value - pair_r_value);
2812 op_info->AddSymbol.Present = 1;
2813 if (add != nullptr)
2814 op_info->AddSymbol.Name = add;
2815 else
2816 op_info->AddSymbol.Value = r_value;
2817 op_info->SubtractSymbol.Present = 1;
2818 if (sub != nullptr)
2819 op_info->SubtractSymbol.Name = sub;
2820 else
2821 op_info->SubtractSymbol.Value = pair_r_value;
2822 op_info->Value = offset;
2823 return 1;
2824 }
2825
Kevin Enderby930fdc72014-11-06 19:00:13 +00002826 op_info->AddSymbol.Present = 1;
2827 op_info->Value = offset;
David Blaikie33dd45d02015-03-23 18:39:02 +00002828 if (r_type == MachO::ARM_RELOC_HALF) {
2829 if ((r_length & 0x1) == 1)
2830 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
2831 else
2832 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
Kevin Enderby930fdc72014-11-06 19:00:13 +00002833 }
Kevin Enderbyf6d25852015-01-31 00:37:11 +00002834 const char *add = GuessSymbolName(value, info->AddrMap);
Kevin Enderby930fdc72014-11-06 19:00:13 +00002835 if (add != nullptr) {
2836 op_info->AddSymbol.Name = add;
2837 return 1;
2838 }
2839 op_info->AddSymbol.Value = value;
2840 return 1;
David Blaikie33dd45d02015-03-23 18:39:02 +00002841 }
2842 if (Arch == Triple::aarch64) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002843 if (Offset != 0 || Size != 4)
2844 return 0;
Kevin Enderbyd90a4172015-10-10 00:05:01 +00002845 if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
2846 // TODO:
2847 // Search the external relocation entries of a fully linked image
2848 // (if any) for an entry that matches this segment offset.
2849 // uint64_t seg_offset = (Pc + Offset);
2850 return 0;
2851 }
2852 // In MH_OBJECT filetypes search the section's relocation entries (if any)
2853 // for an entry for this section offset.
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002854 uint64_t sect_addr = info->S.getAddress();
2855 uint64_t sect_offset = (Pc + Offset) - sect_addr;
David Blaikie33dd45d02015-03-23 18:39:02 +00002856 auto Reloc =
David Majnemer562e8292016-08-12 00:18:03 +00002857 find_if(info->S.relocations(), [&](const RelocationRef &Reloc) {
2858 uint64_t RelocOffset = Reloc.getOffset();
2859 return RelocOffset == sect_offset;
2860 });
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002861
David Blaikie33dd45d02015-03-23 18:39:02 +00002862 if (Reloc == info->S.relocations().end())
2863 return 0;
2864
2865 DataRefImpl Rel = Reloc->getRawDataRefImpl();
2866 MachO::any_relocation_info RE = info->O->getRelocation(Rel);
2867 uint32_t r_type = info->O->getAnyRelocationType(RE);
2868 if (r_type == MachO::ARM64_RELOC_ADDEND) {
2869 DataRefImpl RelNext = Rel;
2870 info->O->moveRelocationNext(RelNext);
2871 MachO::any_relocation_info RENext = info->O->getRelocation(RelNext);
2872 if (value == 0) {
2873 value = info->O->getPlainRelocationSymbolNum(RENext);
2874 op_info->Value = value;
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002875 }
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002876 }
David Blaikie33dd45d02015-03-23 18:39:02 +00002877 // NOTE: Scattered relocations don't exist on arm64.
2878 if (!info->O->getPlainRelocationExternal(RE))
2879 return 0;
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00002880 Expected<StringRef> SymName = Reloc->getSymbol()->getName();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00002881 if (!SymName)
2882 report_error(info->O->getFileName(), SymName.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00002883 const char *name = SymName->data();
David Blaikie33dd45d02015-03-23 18:39:02 +00002884 op_info->AddSymbol.Present = 1;
2885 op_info->AddSymbol.Name = name;
2886
2887 switch (r_type) {
2888 case MachO::ARM64_RELOC_PAGE21:
2889 /* @page */
2890 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_PAGE;
2891 break;
2892 case MachO::ARM64_RELOC_PAGEOFF12:
2893 /* @pageoff */
2894 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_PAGEOFF;
2895 break;
2896 case MachO::ARM64_RELOC_GOT_LOAD_PAGE21:
2897 /* @gotpage */
2898 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_GOTPAGE;
2899 break;
2900 case MachO::ARM64_RELOC_GOT_LOAD_PAGEOFF12:
2901 /* @gotpageoff */
2902 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_GOTPAGEOFF;
2903 break;
2904 case MachO::ARM64_RELOC_TLVP_LOAD_PAGE21:
2905 /* @tvlppage is not implemented in llvm-mc */
2906 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_TLVP;
2907 break;
2908 case MachO::ARM64_RELOC_TLVP_LOAD_PAGEOFF12:
2909 /* @tvlppageoff is not implemented in llvm-mc */
2910 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_TLVOFF;
2911 break;
2912 default:
2913 case MachO::ARM64_RELOC_BRANCH26:
2914 op_info->VariantKind = LLVMDisassembler_VariantKind_None;
2915 break;
2916 }
2917 return 1;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002918 }
David Blaikie33dd45d02015-03-23 18:39:02 +00002919 return 0;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002920}
2921
Kevin Enderbybf246f52014-09-24 23:08:22 +00002922// GuessCstringPointer is passed the address of what might be a pointer to a
2923// literal string in a cstring section. If that address is in a cstring section
2924// it returns a pointer to that string. Else it returns nullptr.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00002925static const char *GuessCstringPointer(uint64_t ReferenceValue,
2926 struct DisassembleInfo *info) {
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00002927 for (const auto &Load : info->O->load_commands()) {
Kevin Enderbybf246f52014-09-24 23:08:22 +00002928 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
2929 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
2930 for (unsigned J = 0; J < Seg.nsects; ++J) {
2931 MachO::section_64 Sec = info->O->getSection64(Load, J);
2932 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
2933 if (section_type == MachO::S_CSTRING_LITERALS &&
2934 ReferenceValue >= Sec.addr &&
2935 ReferenceValue < Sec.addr + Sec.size) {
2936 uint64_t sect_offset = ReferenceValue - Sec.addr;
2937 uint64_t object_offset = Sec.offset + sect_offset;
2938 StringRef MachOContents = info->O->getData();
2939 uint64_t object_size = MachOContents.size();
2940 const char *object_addr = (const char *)MachOContents.data();
2941 if (object_offset < object_size) {
2942 const char *name = object_addr + object_offset;
2943 return name;
2944 } else {
2945 return nullptr;
2946 }
2947 }
2948 }
2949 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
2950 MachO::segment_command Seg = info->O->getSegmentLoadCommand(Load);
2951 for (unsigned J = 0; J < Seg.nsects; ++J) {
2952 MachO::section Sec = info->O->getSection(Load, J);
2953 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
2954 if (section_type == MachO::S_CSTRING_LITERALS &&
2955 ReferenceValue >= Sec.addr &&
2956 ReferenceValue < Sec.addr + Sec.size) {
2957 uint64_t sect_offset = ReferenceValue - Sec.addr;
2958 uint64_t object_offset = Sec.offset + sect_offset;
2959 StringRef MachOContents = info->O->getData();
2960 uint64_t object_size = MachOContents.size();
2961 const char *object_addr = (const char *)MachOContents.data();
2962 if (object_offset < object_size) {
2963 const char *name = object_addr + object_offset;
2964 return name;
2965 } else {
2966 return nullptr;
2967 }
2968 }
2969 }
2970 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00002971 }
2972 return nullptr;
2973}
2974
Kevin Enderby85974882014-09-26 22:20:44 +00002975// GuessIndirectSymbol returns the name of the indirect symbol for the
2976// ReferenceValue passed in or nullptr. This is used when ReferenceValue maybe
2977// an address of a symbol stub or a lazy or non-lazy pointer to associate the
2978// symbol name being referenced by the stub or pointer.
2979static const char *GuessIndirectSymbol(uint64_t ReferenceValue,
2980 struct DisassembleInfo *info) {
Kevin Enderby85974882014-09-26 22:20:44 +00002981 MachO::dysymtab_command Dysymtab = info->O->getDysymtabLoadCommand();
2982 MachO::symtab_command Symtab = info->O->getSymtabLoadCommand();
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00002983 for (const auto &Load : info->O->load_commands()) {
Kevin Enderby85974882014-09-26 22:20:44 +00002984 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
2985 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
2986 for (unsigned J = 0; J < Seg.nsects; ++J) {
2987 MachO::section_64 Sec = info->O->getSection64(Load, J);
2988 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
2989 if ((section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
2990 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
2991 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
2992 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
2993 section_type == MachO::S_SYMBOL_STUBS) &&
2994 ReferenceValue >= Sec.addr &&
2995 ReferenceValue < Sec.addr + Sec.size) {
2996 uint32_t stride;
2997 if (section_type == MachO::S_SYMBOL_STUBS)
2998 stride = Sec.reserved2;
2999 else
3000 stride = 8;
3001 if (stride == 0)
3002 return nullptr;
3003 uint32_t index = Sec.reserved1 + (ReferenceValue - Sec.addr) / stride;
3004 if (index < Dysymtab.nindirectsyms) {
3005 uint32_t indirect_symbol =
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003006 info->O->getIndirectSymbolTableEntry(Dysymtab, index);
Kevin Enderby85974882014-09-26 22:20:44 +00003007 if (indirect_symbol < Symtab.nsyms) {
3008 symbol_iterator Sym = info->O->getSymbolByIndex(indirect_symbol);
3009 SymbolRef Symbol = *Sym;
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00003010 Expected<StringRef> SymName = Symbol.getName();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00003011 if (!SymName)
3012 report_error(info->O->getFileName(), SymName.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00003013 const char *name = SymName->data();
Kevin Enderby85974882014-09-26 22:20:44 +00003014 return name;
3015 }
3016 }
3017 }
3018 }
3019 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
3020 MachO::segment_command Seg = info->O->getSegmentLoadCommand(Load);
3021 for (unsigned J = 0; J < Seg.nsects; ++J) {
3022 MachO::section Sec = info->O->getSection(Load, J);
3023 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
3024 if ((section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
3025 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
3026 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
3027 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
3028 section_type == MachO::S_SYMBOL_STUBS) &&
3029 ReferenceValue >= Sec.addr &&
3030 ReferenceValue < Sec.addr + Sec.size) {
3031 uint32_t stride;
3032 if (section_type == MachO::S_SYMBOL_STUBS)
3033 stride = Sec.reserved2;
3034 else
3035 stride = 4;
3036 if (stride == 0)
3037 return nullptr;
3038 uint32_t index = Sec.reserved1 + (ReferenceValue - Sec.addr) / stride;
3039 if (index < Dysymtab.nindirectsyms) {
3040 uint32_t indirect_symbol =
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003041 info->O->getIndirectSymbolTableEntry(Dysymtab, index);
Kevin Enderby85974882014-09-26 22:20:44 +00003042 if (indirect_symbol < Symtab.nsyms) {
3043 symbol_iterator Sym = info->O->getSymbolByIndex(indirect_symbol);
3044 SymbolRef Symbol = *Sym;
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00003045 Expected<StringRef> SymName = Symbol.getName();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00003046 if (!SymName)
3047 report_error(info->O->getFileName(), SymName.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00003048 const char *name = SymName->data();
Kevin Enderby85974882014-09-26 22:20:44 +00003049 return name;
3050 }
3051 }
3052 }
3053 }
3054 }
Kevin Enderby85974882014-09-26 22:20:44 +00003055 }
3056 return nullptr;
3057}
3058
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003059// method_reference() is called passing it the ReferenceName that might be
3060// a reference it to an Objective-C method call. If so then it allocates and
3061// assembles a method call string with the values last seen and saved in
3062// the DisassembleInfo's class_name and selector_name fields. This is saved
3063// into the method field of the info and any previous string is free'ed.
3064// Then the class_name field in the info is set to nullptr. The method call
3065// string is set into ReferenceName and ReferenceType is set to
3066// LLVMDisassembler_ReferenceType_Out_Objc_Message. If this not a method call
3067// then both ReferenceType and ReferenceName are left unchanged.
3068static void method_reference(struct DisassembleInfo *info,
3069 uint64_t *ReferenceType,
3070 const char **ReferenceName) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00003071 unsigned int Arch = info->O->getArch();
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003072 if (*ReferenceName != nullptr) {
3073 if (strcmp(*ReferenceName, "_objc_msgSend") == 0) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00003074 if (info->selector_name != nullptr) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003075 if (info->class_name != nullptr) {
David Blaikie0e550682018-02-20 18:48:51 +00003076 info->method = llvm::make_unique<char[]>(
3077 5 + strlen(info->class_name) + strlen(info->selector_name));
3078 char *method = info->method.get();
3079 if (method != nullptr) {
3080 strcpy(method, "+[");
3081 strcat(method, info->class_name);
3082 strcat(method, " ");
3083 strcat(method, info->selector_name);
3084 strcat(method, "]");
3085 *ReferenceName = method;
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003086 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
3087 }
3088 } else {
David Blaikie0e550682018-02-20 18:48:51 +00003089 info->method =
3090 llvm::make_unique<char[]>(9 + strlen(info->selector_name));
3091 char *method = info->method.get();
3092 if (method != nullptr) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00003093 if (Arch == Triple::x86_64)
David Blaikie0e550682018-02-20 18:48:51 +00003094 strcpy(method, "-[%rdi ");
Kevin Enderbyae3c1262014-11-14 21:52:18 +00003095 else if (Arch == Triple::aarch64)
David Blaikie0e550682018-02-20 18:48:51 +00003096 strcpy(method, "-[x0 ");
Kevin Enderbyae3c1262014-11-14 21:52:18 +00003097 else
David Blaikie0e550682018-02-20 18:48:51 +00003098 strcpy(method, "-[r? ");
3099 strcat(method, info->selector_name);
3100 strcat(method, "]");
3101 *ReferenceName = method;
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003102 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
3103 }
3104 }
3105 info->class_name = nullptr;
3106 }
3107 } else if (strcmp(*ReferenceName, "_objc_msgSendSuper2") == 0) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00003108 if (info->selector_name != nullptr) {
David Blaikie0e550682018-02-20 18:48:51 +00003109 info->method =
3110 llvm::make_unique<char[]>(17 + strlen(info->selector_name));
3111 char *method = info->method.get();
3112 if (method != nullptr) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00003113 if (Arch == Triple::x86_64)
David Blaikie0e550682018-02-20 18:48:51 +00003114 strcpy(method, "-[[%rdi super] ");
Kevin Enderbyae3c1262014-11-14 21:52:18 +00003115 else if (Arch == Triple::aarch64)
David Blaikie0e550682018-02-20 18:48:51 +00003116 strcpy(method, "-[[x0 super] ");
Kevin Enderbyae3c1262014-11-14 21:52:18 +00003117 else
David Blaikie0e550682018-02-20 18:48:51 +00003118 strcpy(method, "-[[r? super] ");
3119 strcat(method, info->selector_name);
3120 strcat(method, "]");
3121 *ReferenceName = method;
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003122 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
3123 }
3124 info->class_name = nullptr;
3125 }
3126 }
3127 }
3128}
3129
3130// GuessPointerPointer() is passed the address of what might be a pointer to
3131// a reference to an Objective-C class, selector, message ref or cfstring.
3132// If so the value of the pointer is returned and one of the booleans are set
3133// to true. If not zero is returned and all the booleans are set to false.
3134static uint64_t GuessPointerPointer(uint64_t ReferenceValue,
3135 struct DisassembleInfo *info,
3136 bool &classref, bool &selref, bool &msgref,
3137 bool &cfstring) {
3138 classref = false;
3139 selref = false;
3140 msgref = false;
3141 cfstring = false;
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00003142 for (const auto &Load : info->O->load_commands()) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003143 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
3144 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
3145 for (unsigned J = 0; J < Seg.nsects; ++J) {
3146 MachO::section_64 Sec = info->O->getSection64(Load, J);
3147 if ((strncmp(Sec.sectname, "__objc_selrefs", 16) == 0 ||
3148 strncmp(Sec.sectname, "__objc_classrefs", 16) == 0 ||
3149 strncmp(Sec.sectname, "__objc_superrefs", 16) == 0 ||
3150 strncmp(Sec.sectname, "__objc_msgrefs", 16) == 0 ||
3151 strncmp(Sec.sectname, "__cfstring", 16) == 0) &&
3152 ReferenceValue >= Sec.addr &&
3153 ReferenceValue < Sec.addr + Sec.size) {
3154 uint64_t sect_offset = ReferenceValue - Sec.addr;
3155 uint64_t object_offset = Sec.offset + sect_offset;
3156 StringRef MachOContents = info->O->getData();
3157 uint64_t object_size = MachOContents.size();
3158 const char *object_addr = (const char *)MachOContents.data();
3159 if (object_offset < object_size) {
3160 uint64_t pointer_value;
3161 memcpy(&pointer_value, object_addr + object_offset,
3162 sizeof(uint64_t));
3163 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3164 sys::swapByteOrder(pointer_value);
3165 if (strncmp(Sec.sectname, "__objc_selrefs", 16) == 0)
3166 selref = true;
3167 else if (strncmp(Sec.sectname, "__objc_classrefs", 16) == 0 ||
3168 strncmp(Sec.sectname, "__objc_superrefs", 16) == 0)
3169 classref = true;
3170 else if (strncmp(Sec.sectname, "__objc_msgrefs", 16) == 0 &&
3171 ReferenceValue + 8 < Sec.addr + Sec.size) {
3172 msgref = true;
3173 memcpy(&pointer_value, object_addr + object_offset + 8,
3174 sizeof(uint64_t));
3175 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3176 sys::swapByteOrder(pointer_value);
3177 } else if (strncmp(Sec.sectname, "__cfstring", 16) == 0)
3178 cfstring = true;
3179 return pointer_value;
3180 } else {
3181 return 0;
3182 }
3183 }
3184 }
3185 }
3186 // TODO: Look for LC_SEGMENT for 32-bit Mach-O files.
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003187 }
3188 return 0;
3189}
3190
3191// get_pointer_64 returns a pointer to the bytes in the object file at the
3192// Address from a section in the Mach-O file. And indirectly returns the
3193// offset into the section, number of bytes left in the section past the offset
3194// and which section is was being referenced. If the Address is not in a
3195// section nullptr is returned.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00003196static const char *get_pointer_64(uint64_t Address, uint32_t &offset,
3197 uint32_t &left, SectionRef &S,
Kevin Enderby846c0002015-04-16 17:19:59 +00003198 DisassembleInfo *info,
3199 bool objc_only = false) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003200 offset = 0;
3201 left = 0;
3202 S = SectionRef();
3203 for (unsigned SectIdx = 0; SectIdx != info->Sections->size(); SectIdx++) {
3204 uint64_t SectAddress = ((*(info->Sections))[SectIdx]).getAddress();
3205 uint64_t SectSize = ((*(info->Sections))[SectIdx]).getSize();
Kevin Enderby46e642f2015-10-08 22:50:55 +00003206 if (SectSize == 0)
3207 continue;
Kevin Enderby846c0002015-04-16 17:19:59 +00003208 if (objc_only) {
3209 StringRef SectName;
3210 ((*(info->Sections))[SectIdx]).getName(SectName);
3211 DataRefImpl Ref = ((*(info->Sections))[SectIdx]).getRawDataRefImpl();
3212 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
3213 if (SegName != "__OBJC" && SectName != "__cstring")
3214 continue;
3215 }
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003216 if (Address >= SectAddress && Address < SectAddress + SectSize) {
3217 S = (*(info->Sections))[SectIdx];
3218 offset = Address - SectAddress;
3219 left = SectSize - offset;
3220 StringRef SectContents;
3221 ((*(info->Sections))[SectIdx]).getContents(SectContents);
3222 return SectContents.data() + offset;
3223 }
3224 }
3225 return nullptr;
3226}
3227
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003228static const char *get_pointer_32(uint32_t Address, uint32_t &offset,
3229 uint32_t &left, SectionRef &S,
Kevin Enderby846c0002015-04-16 17:19:59 +00003230 DisassembleInfo *info,
3231 bool objc_only = false) {
3232 return get_pointer_64(Address, offset, left, S, info, objc_only);
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003233}
3234
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003235// get_symbol_64() returns the name of a symbol (or nullptr) and the address of
3236// the symbol indirectly through n_value. Based on the relocation information
3237// for the specified section offset in the specified section reference.
Kevin Enderby0fc11822015-04-01 20:57:01 +00003238// If no relocation information is found and a non-zero ReferenceValue for the
3239// symbol is passed, look up that address in the info's AddrMap.
Rafael Espindolad7a32ea2015-06-24 10:20:30 +00003240static const char *get_symbol_64(uint32_t sect_offset, SectionRef S,
3241 DisassembleInfo *info, uint64_t &n_value,
Rafael Espindolabe8b0ea2015-07-07 17:12:59 +00003242 uint64_t ReferenceValue = 0) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003243 n_value = 0;
David Blaikie33dd45d02015-03-23 18:39:02 +00003244 if (!info->verbose)
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003245 return nullptr;
3246
3247 // See if there is an external relocation entry at the sect_offset.
3248 bool reloc_found = false;
3249 DataRefImpl Rel;
3250 MachO::any_relocation_info RE;
3251 bool isExtern = false;
3252 SymbolRef Symbol;
3253 for (const RelocationRef &Reloc : S.relocations()) {
Rafael Espindola96d071c2015-06-29 23:29:12 +00003254 uint64_t RelocOffset = Reloc.getOffset();
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003255 if (RelocOffset == sect_offset) {
3256 Rel = Reloc.getRawDataRefImpl();
3257 RE = info->O->getRelocation(Rel);
3258 if (info->O->isRelocationScattered(RE))
3259 continue;
3260 isExtern = info->O->getPlainRelocationExternal(RE);
3261 if (isExtern) {
3262 symbol_iterator RelocSym = Reloc.getSymbol();
3263 Symbol = *RelocSym;
3264 }
3265 reloc_found = true;
3266 break;
3267 }
3268 }
3269 // If there is an external relocation entry for a symbol in this section
3270 // at this section_offset then use that symbol's value for the n_value
3271 // and return its name.
3272 const char *SymbolName = nullptr;
3273 if (reloc_found && isExtern) {
Rafael Espindoladea00162015-07-03 17:44:18 +00003274 n_value = Symbol.getValue();
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00003275 Expected<StringRef> NameOrError = Symbol.getName();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00003276 if (!NameOrError)
3277 report_error(info->O->getFileName(), NameOrError.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00003278 StringRef Name = *NameOrError;
3279 if (!Name.empty()) {
3280 SymbolName = Name.data();
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003281 return SymbolName;
3282 }
3283 }
3284
3285 // TODO: For fully linked images, look through the external relocation
3286 // entries off the dynamic symtab command. For these the r_offset is from the
3287 // start of the first writeable segment in the Mach-O file. So the offset
3288 // to this section from that segment is passed to this routine by the caller,
3289 // as the database_offset. Which is the difference of the section's starting
3290 // address and the first writable segment.
3291 //
3292 // NOTE: need add passing the database_offset to this routine.
3293
Kevin Enderby0fc11822015-04-01 20:57:01 +00003294 // We did not find an external relocation entry so look up the ReferenceValue
3295 // as an address of a symbol and if found return that symbol's name.
Rafael Espindolabe8b0ea2015-07-07 17:12:59 +00003296 SymbolName = GuessSymbolName(ReferenceValue, info->AddrMap);
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003297
3298 return SymbolName;
3299}
3300
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003301static const char *get_symbol_32(uint32_t sect_offset, SectionRef S,
3302 DisassembleInfo *info,
3303 uint32_t ReferenceValue) {
3304 uint64_t n_value64;
3305 return get_symbol_64(sect_offset, S, info, n_value64, ReferenceValue);
3306}
3307
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003308// These are structs in the Objective-C meta data and read to produce the
3309// comments for disassembly. While these are part of the ABI they are no
Zachary Turner264b5d92017-06-07 03:48:56 +00003310// public defintions. So the are here not in include/llvm/BinaryFormat/MachO.h
3311// .
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003312
3313// The cfstring object in a 64-bit Mach-O file.
3314struct cfstring64_t {
3315 uint64_t isa; // class64_t * (64-bit pointer)
3316 uint64_t flags; // flag bits
3317 uint64_t characters; // char * (64-bit pointer)
3318 uint64_t length; // number of non-NULL characters in above
3319};
3320
3321// The class object in a 64-bit Mach-O file.
3322struct class64_t {
3323 uint64_t isa; // class64_t * (64-bit pointer)
3324 uint64_t superclass; // class64_t * (64-bit pointer)
3325 uint64_t cache; // Cache (64-bit pointer)
3326 uint64_t vtable; // IMP * (64-bit pointer)
3327 uint64_t data; // class_ro64_t * (64-bit pointer)
3328};
3329
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003330struct class32_t {
3331 uint32_t isa; /* class32_t * (32-bit pointer) */
3332 uint32_t superclass; /* class32_t * (32-bit pointer) */
3333 uint32_t cache; /* Cache (32-bit pointer) */
3334 uint32_t vtable; /* IMP * (32-bit pointer) */
3335 uint32_t data; /* class_ro32_t * (32-bit pointer) */
3336};
3337
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003338struct class_ro64_t {
3339 uint32_t flags;
3340 uint32_t instanceStart;
3341 uint32_t instanceSize;
3342 uint32_t reserved;
3343 uint64_t ivarLayout; // const uint8_t * (64-bit pointer)
3344 uint64_t name; // const char * (64-bit pointer)
3345 uint64_t baseMethods; // const method_list_t * (64-bit pointer)
3346 uint64_t baseProtocols; // const protocol_list_t * (64-bit pointer)
3347 uint64_t ivars; // const ivar_list_t * (64-bit pointer)
3348 uint64_t weakIvarLayout; // const uint8_t * (64-bit pointer)
3349 uint64_t baseProperties; // const struct objc_property_list (64-bit pointer)
3350};
3351
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003352struct class_ro32_t {
3353 uint32_t flags;
3354 uint32_t instanceStart;
3355 uint32_t instanceSize;
3356 uint32_t ivarLayout; /* const uint8_t * (32-bit pointer) */
3357 uint32_t name; /* const char * (32-bit pointer) */
3358 uint32_t baseMethods; /* const method_list_t * (32-bit pointer) */
3359 uint32_t baseProtocols; /* const protocol_list_t * (32-bit pointer) */
3360 uint32_t ivars; /* const ivar_list_t * (32-bit pointer) */
3361 uint32_t weakIvarLayout; /* const uint8_t * (32-bit pointer) */
3362 uint32_t baseProperties; /* const struct objc_property_list *
3363 (32-bit pointer) */
3364};
3365
3366/* Values for class_ro{64,32}_t->flags */
Kevin Enderby0fc11822015-04-01 20:57:01 +00003367#define RO_META (1 << 0)
3368#define RO_ROOT (1 << 1)
3369#define RO_HAS_CXX_STRUCTORS (1 << 2)
3370
3371struct method_list64_t {
3372 uint32_t entsize;
3373 uint32_t count;
3374 /* struct method64_t first; These structures follow inline */
3375};
3376
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003377struct method_list32_t {
3378 uint32_t entsize;
3379 uint32_t count;
3380 /* struct method32_t first; These structures follow inline */
3381};
3382
Kevin Enderby0fc11822015-04-01 20:57:01 +00003383struct method64_t {
3384 uint64_t name; /* SEL (64-bit pointer) */
3385 uint64_t types; /* const char * (64-bit pointer) */
3386 uint64_t imp; /* IMP (64-bit pointer) */
3387};
3388
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003389struct method32_t {
3390 uint32_t name; /* SEL (32-bit pointer) */
3391 uint32_t types; /* const char * (32-bit pointer) */
3392 uint32_t imp; /* IMP (32-bit pointer) */
3393};
3394
Kevin Enderby0fc11822015-04-01 20:57:01 +00003395struct protocol_list64_t {
3396 uint64_t count; /* uintptr_t (a 64-bit value) */
3397 /* struct protocol64_t * list[0]; These pointers follow inline */
3398};
3399
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003400struct protocol_list32_t {
3401 uint32_t count; /* uintptr_t (a 32-bit value) */
3402 /* struct protocol32_t * list[0]; These pointers follow inline */
3403};
3404
Kevin Enderby0fc11822015-04-01 20:57:01 +00003405struct protocol64_t {
3406 uint64_t isa; /* id * (64-bit pointer) */
3407 uint64_t name; /* const char * (64-bit pointer) */
3408 uint64_t protocols; /* struct protocol_list64_t *
3409 (64-bit pointer) */
3410 uint64_t instanceMethods; /* method_list_t * (64-bit pointer) */
3411 uint64_t classMethods; /* method_list_t * (64-bit pointer) */
3412 uint64_t optionalInstanceMethods; /* method_list_t * (64-bit pointer) */
3413 uint64_t optionalClassMethods; /* method_list_t * (64-bit pointer) */
3414 uint64_t instanceProperties; /* struct objc_property_list *
3415 (64-bit pointer) */
3416};
3417
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003418struct protocol32_t {
3419 uint32_t isa; /* id * (32-bit pointer) */
3420 uint32_t name; /* const char * (32-bit pointer) */
3421 uint32_t protocols; /* struct protocol_list_t *
3422 (32-bit pointer) */
3423 uint32_t instanceMethods; /* method_list_t * (32-bit pointer) */
3424 uint32_t classMethods; /* method_list_t * (32-bit pointer) */
3425 uint32_t optionalInstanceMethods; /* method_list_t * (32-bit pointer) */
3426 uint32_t optionalClassMethods; /* method_list_t * (32-bit pointer) */
3427 uint32_t instanceProperties; /* struct objc_property_list *
3428 (32-bit pointer) */
3429};
3430
Kevin Enderby0fc11822015-04-01 20:57:01 +00003431struct ivar_list64_t {
3432 uint32_t entsize;
3433 uint32_t count;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003434 /* struct ivar64_t first; These structures follow inline */
3435};
3436
3437struct ivar_list32_t {
3438 uint32_t entsize;
3439 uint32_t count;
3440 /* struct ivar32_t first; These structures follow inline */
Kevin Enderby0fc11822015-04-01 20:57:01 +00003441};
3442
3443struct ivar64_t {
3444 uint64_t offset; /* uintptr_t * (64-bit pointer) */
3445 uint64_t name; /* const char * (64-bit pointer) */
3446 uint64_t type; /* const char * (64-bit pointer) */
3447 uint32_t alignment;
3448 uint32_t size;
3449};
3450
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003451struct ivar32_t {
3452 uint32_t offset; /* uintptr_t * (32-bit pointer) */
3453 uint32_t name; /* const char * (32-bit pointer) */
3454 uint32_t type; /* const char * (32-bit pointer) */
3455 uint32_t alignment;
3456 uint32_t size;
3457};
3458
Kevin Enderby0fc11822015-04-01 20:57:01 +00003459struct objc_property_list64 {
3460 uint32_t entsize;
3461 uint32_t count;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003462 /* struct objc_property64 first; These structures follow inline */
3463};
3464
3465struct objc_property_list32 {
3466 uint32_t entsize;
3467 uint32_t count;
3468 /* struct objc_property32 first; These structures follow inline */
Kevin Enderby0fc11822015-04-01 20:57:01 +00003469};
3470
3471struct objc_property64 {
3472 uint64_t name; /* const char * (64-bit pointer) */
3473 uint64_t attributes; /* const char * (64-bit pointer) */
3474};
3475
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003476struct objc_property32 {
3477 uint32_t name; /* const char * (32-bit pointer) */
3478 uint32_t attributes; /* const char * (32-bit pointer) */
3479};
3480
Kevin Enderby0fc11822015-04-01 20:57:01 +00003481struct category64_t {
3482 uint64_t name; /* const char * (64-bit pointer) */
3483 uint64_t cls; /* struct class_t * (64-bit pointer) */
3484 uint64_t instanceMethods; /* struct method_list_t * (64-bit pointer) */
3485 uint64_t classMethods; /* struct method_list_t * (64-bit pointer) */
3486 uint64_t protocols; /* struct protocol_list_t * (64-bit pointer) */
3487 uint64_t instanceProperties; /* struct objc_property_list *
3488 (64-bit pointer) */
3489};
3490
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003491struct category32_t {
3492 uint32_t name; /* const char * (32-bit pointer) */
3493 uint32_t cls; /* struct class_t * (32-bit pointer) */
3494 uint32_t instanceMethods; /* struct method_list_t * (32-bit pointer) */
3495 uint32_t classMethods; /* struct method_list_t * (32-bit pointer) */
3496 uint32_t protocols; /* struct protocol_list_t * (32-bit pointer) */
3497 uint32_t instanceProperties; /* struct objc_property_list *
3498 (32-bit pointer) */
3499};
3500
Kevin Enderby0fc11822015-04-01 20:57:01 +00003501struct objc_image_info64 {
3502 uint32_t version;
3503 uint32_t flags;
3504};
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003505struct objc_image_info32 {
3506 uint32_t version;
3507 uint32_t flags;
3508};
Kevin Enderby846c0002015-04-16 17:19:59 +00003509struct imageInfo_t {
3510 uint32_t version;
3511 uint32_t flags;
3512};
Kevin Enderby0fc11822015-04-01 20:57:01 +00003513/* masks for objc_image_info.flags */
3514#define OBJC_IMAGE_IS_REPLACEMENT (1 << 0)
3515#define OBJC_IMAGE_SUPPORTS_GC (1 << 1)
Dave Lee390abe42018-07-06 05:11:35 +00003516#define OBJC_IMAGE_IS_SIMULATED (1 << 5)
3517#define OBJC_IMAGE_HAS_CATEGORY_CLASS_PROPERTIES (1 << 6)
Kevin Enderby0fc11822015-04-01 20:57:01 +00003518
3519struct message_ref64 {
3520 uint64_t imp; /* IMP (64-bit pointer) */
3521 uint64_t sel; /* SEL (64-bit pointer) */
3522};
3523
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003524struct message_ref32 {
3525 uint32_t imp; /* IMP (32-bit pointer) */
3526 uint32_t sel; /* SEL (32-bit pointer) */
3527};
3528
Kevin Enderby846c0002015-04-16 17:19:59 +00003529// Objective-C 1 (32-bit only) meta data structs.
3530
3531struct objc_module_t {
3532 uint32_t version;
3533 uint32_t size;
3534 uint32_t name; /* char * (32-bit pointer) */
3535 uint32_t symtab; /* struct objc_symtab * (32-bit pointer) */
3536};
3537
3538struct objc_symtab_t {
3539 uint32_t sel_ref_cnt;
3540 uint32_t refs; /* SEL * (32-bit pointer) */
3541 uint16_t cls_def_cnt;
3542 uint16_t cat_def_cnt;
3543 // uint32_t defs[1]; /* void * (32-bit pointer) variable size */
3544};
3545
3546struct objc_class_t {
3547 uint32_t isa; /* struct objc_class * (32-bit pointer) */
3548 uint32_t super_class; /* struct objc_class * (32-bit pointer) */
3549 uint32_t name; /* const char * (32-bit pointer) */
3550 int32_t version;
3551 int32_t info;
3552 int32_t instance_size;
3553 uint32_t ivars; /* struct objc_ivar_list * (32-bit pointer) */
3554 uint32_t methodLists; /* struct objc_method_list ** (32-bit pointer) */
3555 uint32_t cache; /* struct objc_cache * (32-bit pointer) */
3556 uint32_t protocols; /* struct objc_protocol_list * (32-bit pointer) */
3557};
3558
3559#define CLS_GETINFO(cls, infomask) ((cls)->info & (infomask))
3560// class is not a metaclass
3561#define CLS_CLASS 0x1
3562// class is a metaclass
3563#define CLS_META 0x2
3564
3565struct objc_category_t {
3566 uint32_t category_name; /* char * (32-bit pointer) */
3567 uint32_t class_name; /* char * (32-bit pointer) */
3568 uint32_t instance_methods; /* struct objc_method_list * (32-bit pointer) */
3569 uint32_t class_methods; /* struct objc_method_list * (32-bit pointer) */
3570 uint32_t protocols; /* struct objc_protocol_list * (32-bit ptr) */
3571};
3572
3573struct objc_ivar_t {
3574 uint32_t ivar_name; /* char * (32-bit pointer) */
3575 uint32_t ivar_type; /* char * (32-bit pointer) */
3576 int32_t ivar_offset;
3577};
3578
3579struct objc_ivar_list_t {
3580 int32_t ivar_count;
3581 // struct objc_ivar_t ivar_list[1]; /* variable length structure */
3582};
3583
3584struct objc_method_list_t {
3585 uint32_t obsolete; /* struct objc_method_list * (32-bit pointer) */
3586 int32_t method_count;
3587 // struct objc_method_t method_list[1]; /* variable length structure */
3588};
3589
3590struct objc_method_t {
3591 uint32_t method_name; /* SEL, aka struct objc_selector * (32-bit pointer) */
3592 uint32_t method_types; /* char * (32-bit pointer) */
3593 uint32_t method_imp; /* IMP, aka function pointer, (*IMP)(id, SEL, ...)
3594 (32-bit pointer) */
3595};
3596
3597struct objc_protocol_list_t {
3598 uint32_t next; /* struct objc_protocol_list * (32-bit pointer) */
3599 int32_t count;
3600 // uint32_t list[1]; /* Protocol *, aka struct objc_protocol_t *
3601 // (32-bit pointer) */
3602};
3603
3604struct objc_protocol_t {
3605 uint32_t isa; /* struct objc_class * (32-bit pointer) */
3606 uint32_t protocol_name; /* char * (32-bit pointer) */
3607 uint32_t protocol_list; /* struct objc_protocol_list * (32-bit pointer) */
3608 uint32_t instance_methods; /* struct objc_method_description_list *
3609 (32-bit pointer) */
3610 uint32_t class_methods; /* struct objc_method_description_list *
3611 (32-bit pointer) */
3612};
3613
3614struct objc_method_description_list_t {
3615 int32_t count;
3616 // struct objc_method_description_t list[1];
3617};
3618
3619struct objc_method_description_t {
3620 uint32_t name; /* SEL, aka struct objc_selector * (32-bit pointer) */
3621 uint32_t types; /* char * (32-bit pointer) */
3622};
3623
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003624inline void swapStruct(struct cfstring64_t &cfs) {
3625 sys::swapByteOrder(cfs.isa);
3626 sys::swapByteOrder(cfs.flags);
3627 sys::swapByteOrder(cfs.characters);
3628 sys::swapByteOrder(cfs.length);
3629}
3630
3631inline void swapStruct(struct class64_t &c) {
3632 sys::swapByteOrder(c.isa);
3633 sys::swapByteOrder(c.superclass);
3634 sys::swapByteOrder(c.cache);
3635 sys::swapByteOrder(c.vtable);
3636 sys::swapByteOrder(c.data);
3637}
3638
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003639inline void swapStruct(struct class32_t &c) {
3640 sys::swapByteOrder(c.isa);
3641 sys::swapByteOrder(c.superclass);
3642 sys::swapByteOrder(c.cache);
3643 sys::swapByteOrder(c.vtable);
3644 sys::swapByteOrder(c.data);
3645}
3646
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003647inline void swapStruct(struct class_ro64_t &cro) {
3648 sys::swapByteOrder(cro.flags);
3649 sys::swapByteOrder(cro.instanceStart);
3650 sys::swapByteOrder(cro.instanceSize);
3651 sys::swapByteOrder(cro.reserved);
3652 sys::swapByteOrder(cro.ivarLayout);
3653 sys::swapByteOrder(cro.name);
3654 sys::swapByteOrder(cro.baseMethods);
3655 sys::swapByteOrder(cro.baseProtocols);
3656 sys::swapByteOrder(cro.ivars);
3657 sys::swapByteOrder(cro.weakIvarLayout);
3658 sys::swapByteOrder(cro.baseProperties);
3659}
3660
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003661inline void swapStruct(struct class_ro32_t &cro) {
3662 sys::swapByteOrder(cro.flags);
3663 sys::swapByteOrder(cro.instanceStart);
3664 sys::swapByteOrder(cro.instanceSize);
3665 sys::swapByteOrder(cro.ivarLayout);
3666 sys::swapByteOrder(cro.name);
3667 sys::swapByteOrder(cro.baseMethods);
3668 sys::swapByteOrder(cro.baseProtocols);
3669 sys::swapByteOrder(cro.ivars);
3670 sys::swapByteOrder(cro.weakIvarLayout);
3671 sys::swapByteOrder(cro.baseProperties);
3672}
3673
Kevin Enderby0fc11822015-04-01 20:57:01 +00003674inline void swapStruct(struct method_list64_t &ml) {
3675 sys::swapByteOrder(ml.entsize);
3676 sys::swapByteOrder(ml.count);
3677}
3678
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003679inline void swapStruct(struct method_list32_t &ml) {
3680 sys::swapByteOrder(ml.entsize);
3681 sys::swapByteOrder(ml.count);
3682}
3683
Kevin Enderby0fc11822015-04-01 20:57:01 +00003684inline void swapStruct(struct method64_t &m) {
3685 sys::swapByteOrder(m.name);
3686 sys::swapByteOrder(m.types);
3687 sys::swapByteOrder(m.imp);
3688}
3689
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003690inline void swapStruct(struct method32_t &m) {
3691 sys::swapByteOrder(m.name);
3692 sys::swapByteOrder(m.types);
3693 sys::swapByteOrder(m.imp);
3694}
3695
Kevin Enderby0fc11822015-04-01 20:57:01 +00003696inline void swapStruct(struct protocol_list64_t &pl) {
3697 sys::swapByteOrder(pl.count);
3698}
3699
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003700inline void swapStruct(struct protocol_list32_t &pl) {
3701 sys::swapByteOrder(pl.count);
3702}
3703
Kevin Enderby0fc11822015-04-01 20:57:01 +00003704inline void swapStruct(struct protocol64_t &p) {
3705 sys::swapByteOrder(p.isa);
3706 sys::swapByteOrder(p.name);
3707 sys::swapByteOrder(p.protocols);
3708 sys::swapByteOrder(p.instanceMethods);
3709 sys::swapByteOrder(p.classMethods);
3710 sys::swapByteOrder(p.optionalInstanceMethods);
3711 sys::swapByteOrder(p.optionalClassMethods);
3712 sys::swapByteOrder(p.instanceProperties);
3713}
3714
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003715inline void swapStruct(struct protocol32_t &p) {
3716 sys::swapByteOrder(p.isa);
3717 sys::swapByteOrder(p.name);
3718 sys::swapByteOrder(p.protocols);
3719 sys::swapByteOrder(p.instanceMethods);
3720 sys::swapByteOrder(p.classMethods);
3721 sys::swapByteOrder(p.optionalInstanceMethods);
3722 sys::swapByteOrder(p.optionalClassMethods);
3723 sys::swapByteOrder(p.instanceProperties);
3724}
3725
Kevin Enderby0fc11822015-04-01 20:57:01 +00003726inline void swapStruct(struct ivar_list64_t &il) {
3727 sys::swapByteOrder(il.entsize);
3728 sys::swapByteOrder(il.count);
3729}
3730
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003731inline void swapStruct(struct ivar_list32_t &il) {
3732 sys::swapByteOrder(il.entsize);
3733 sys::swapByteOrder(il.count);
3734}
3735
Kevin Enderby0fc11822015-04-01 20:57:01 +00003736inline void swapStruct(struct ivar64_t &i) {
3737 sys::swapByteOrder(i.offset);
3738 sys::swapByteOrder(i.name);
3739 sys::swapByteOrder(i.type);
3740 sys::swapByteOrder(i.alignment);
3741 sys::swapByteOrder(i.size);
3742}
3743
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003744inline void swapStruct(struct ivar32_t &i) {
3745 sys::swapByteOrder(i.offset);
3746 sys::swapByteOrder(i.name);
3747 sys::swapByteOrder(i.type);
3748 sys::swapByteOrder(i.alignment);
3749 sys::swapByteOrder(i.size);
3750}
3751
Kevin Enderby0fc11822015-04-01 20:57:01 +00003752inline void swapStruct(struct objc_property_list64 &pl) {
3753 sys::swapByteOrder(pl.entsize);
3754 sys::swapByteOrder(pl.count);
3755}
3756
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003757inline void swapStruct(struct objc_property_list32 &pl) {
3758 sys::swapByteOrder(pl.entsize);
3759 sys::swapByteOrder(pl.count);
3760}
3761
Kevin Enderby0fc11822015-04-01 20:57:01 +00003762inline void swapStruct(struct objc_property64 &op) {
3763 sys::swapByteOrder(op.name);
3764 sys::swapByteOrder(op.attributes);
3765}
3766
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003767inline void swapStruct(struct objc_property32 &op) {
3768 sys::swapByteOrder(op.name);
3769 sys::swapByteOrder(op.attributes);
3770}
3771
Kevin Enderby0fc11822015-04-01 20:57:01 +00003772inline void swapStruct(struct category64_t &c) {
3773 sys::swapByteOrder(c.name);
3774 sys::swapByteOrder(c.cls);
3775 sys::swapByteOrder(c.instanceMethods);
3776 sys::swapByteOrder(c.classMethods);
3777 sys::swapByteOrder(c.protocols);
3778 sys::swapByteOrder(c.instanceProperties);
3779}
3780
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003781inline void swapStruct(struct category32_t &c) {
3782 sys::swapByteOrder(c.name);
3783 sys::swapByteOrder(c.cls);
3784 sys::swapByteOrder(c.instanceMethods);
3785 sys::swapByteOrder(c.classMethods);
3786 sys::swapByteOrder(c.protocols);
3787 sys::swapByteOrder(c.instanceProperties);
3788}
3789
Kevin Enderby0fc11822015-04-01 20:57:01 +00003790inline void swapStruct(struct objc_image_info64 &o) {
3791 sys::swapByteOrder(o.version);
3792 sys::swapByteOrder(o.flags);
3793}
3794
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003795inline void swapStruct(struct objc_image_info32 &o) {
3796 sys::swapByteOrder(o.version);
3797 sys::swapByteOrder(o.flags);
3798}
3799
Kevin Enderby846c0002015-04-16 17:19:59 +00003800inline void swapStruct(struct imageInfo_t &o) {
3801 sys::swapByteOrder(o.version);
3802 sys::swapByteOrder(o.flags);
3803}
3804
Kevin Enderby0fc11822015-04-01 20:57:01 +00003805inline void swapStruct(struct message_ref64 &mr) {
3806 sys::swapByteOrder(mr.imp);
3807 sys::swapByteOrder(mr.sel);
3808}
3809
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003810inline void swapStruct(struct message_ref32 &mr) {
3811 sys::swapByteOrder(mr.imp);
3812 sys::swapByteOrder(mr.sel);
3813}
3814
Kevin Enderby846c0002015-04-16 17:19:59 +00003815inline void swapStruct(struct objc_module_t &module) {
3816 sys::swapByteOrder(module.version);
3817 sys::swapByteOrder(module.size);
3818 sys::swapByteOrder(module.name);
3819 sys::swapByteOrder(module.symtab);
Jingyue Wufedecc42015-04-16 18:43:44 +00003820}
Kevin Enderby846c0002015-04-16 17:19:59 +00003821
3822inline void swapStruct(struct objc_symtab_t &symtab) {
3823 sys::swapByteOrder(symtab.sel_ref_cnt);
3824 sys::swapByteOrder(symtab.refs);
3825 sys::swapByteOrder(symtab.cls_def_cnt);
3826 sys::swapByteOrder(symtab.cat_def_cnt);
Jingyue Wufedecc42015-04-16 18:43:44 +00003827}
Kevin Enderby846c0002015-04-16 17:19:59 +00003828
3829inline void swapStruct(struct objc_class_t &objc_class) {
3830 sys::swapByteOrder(objc_class.isa);
3831 sys::swapByteOrder(objc_class.super_class);
3832 sys::swapByteOrder(objc_class.name);
3833 sys::swapByteOrder(objc_class.version);
3834 sys::swapByteOrder(objc_class.info);
3835 sys::swapByteOrder(objc_class.instance_size);
3836 sys::swapByteOrder(objc_class.ivars);
3837 sys::swapByteOrder(objc_class.methodLists);
3838 sys::swapByteOrder(objc_class.cache);
3839 sys::swapByteOrder(objc_class.protocols);
Jingyue Wufedecc42015-04-16 18:43:44 +00003840}
Kevin Enderby846c0002015-04-16 17:19:59 +00003841
3842inline void swapStruct(struct objc_category_t &objc_category) {
3843 sys::swapByteOrder(objc_category.category_name);
3844 sys::swapByteOrder(objc_category.class_name);
3845 sys::swapByteOrder(objc_category.instance_methods);
3846 sys::swapByteOrder(objc_category.class_methods);
3847 sys::swapByteOrder(objc_category.protocols);
3848}
3849
3850inline void swapStruct(struct objc_ivar_list_t &objc_ivar_list) {
3851 sys::swapByteOrder(objc_ivar_list.ivar_count);
3852}
3853
3854inline void swapStruct(struct objc_ivar_t &objc_ivar) {
3855 sys::swapByteOrder(objc_ivar.ivar_name);
3856 sys::swapByteOrder(objc_ivar.ivar_type);
3857 sys::swapByteOrder(objc_ivar.ivar_offset);
Jingyue Wufedecc42015-04-16 18:43:44 +00003858}
Kevin Enderby846c0002015-04-16 17:19:59 +00003859
3860inline void swapStruct(struct objc_method_list_t &method_list) {
3861 sys::swapByteOrder(method_list.obsolete);
3862 sys::swapByteOrder(method_list.method_count);
3863}
3864
3865inline void swapStruct(struct objc_method_t &method) {
3866 sys::swapByteOrder(method.method_name);
3867 sys::swapByteOrder(method.method_types);
3868 sys::swapByteOrder(method.method_imp);
3869}
3870
3871inline void swapStruct(struct objc_protocol_list_t &protocol_list) {
3872 sys::swapByteOrder(protocol_list.next);
3873 sys::swapByteOrder(protocol_list.count);
3874}
3875
3876inline void swapStruct(struct objc_protocol_t &protocol) {
3877 sys::swapByteOrder(protocol.isa);
3878 sys::swapByteOrder(protocol.protocol_name);
3879 sys::swapByteOrder(protocol.protocol_list);
3880 sys::swapByteOrder(protocol.instance_methods);
3881 sys::swapByteOrder(protocol.class_methods);
3882}
3883
3884inline void swapStruct(struct objc_method_description_list_t &mdl) {
3885 sys::swapByteOrder(mdl.count);
3886}
3887
3888inline void swapStruct(struct objc_method_description_t &md) {
3889 sys::swapByteOrder(md.name);
3890 sys::swapByteOrder(md.types);
3891}
3892
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003893static const char *get_dyld_bind_info_symbolname(uint64_t ReferenceValue,
3894 struct DisassembleInfo *info);
3895
3896// get_objc2_64bit_class_name() is used for disassembly and is passed a pointer
3897// to an Objective-C class and returns the class name. It is also passed the
3898// address of the pointer, so when the pointer is zero as it can be in an .o
3899// file, that is used to look for an external relocation entry with a symbol
3900// name.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00003901static const char *get_objc2_64bit_class_name(uint64_t pointer_value,
3902 uint64_t ReferenceValue,
3903 struct DisassembleInfo *info) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003904 const char *r;
3905 uint32_t offset, left;
3906 SectionRef S;
3907
3908 // The pointer_value can be 0 in an object file and have a relocation
3909 // entry for the class symbol at the ReferenceValue (the address of the
3910 // pointer).
3911 if (pointer_value == 0) {
3912 r = get_pointer_64(ReferenceValue, offset, left, S, info);
3913 if (r == nullptr || left < sizeof(uint64_t))
3914 return nullptr;
3915 uint64_t n_value;
3916 const char *symbol_name = get_symbol_64(offset, S, info, n_value);
3917 if (symbol_name == nullptr)
3918 return nullptr;
Hans Wennborgdb53e302014-10-23 21:59:17 +00003919 const char *class_name = strrchr(symbol_name, '$');
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003920 if (class_name != nullptr && class_name[1] == '_' && class_name[2] != '\0')
3921 return class_name + 2;
3922 else
3923 return nullptr;
3924 }
3925
3926 // The case were the pointer_value is non-zero and points to a class defined
3927 // in this Mach-O file.
3928 r = get_pointer_64(pointer_value, offset, left, S, info);
3929 if (r == nullptr || left < sizeof(struct class64_t))
3930 return nullptr;
3931 struct class64_t c;
3932 memcpy(&c, r, sizeof(struct class64_t));
3933 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3934 swapStruct(c);
3935 if (c.data == 0)
3936 return nullptr;
3937 r = get_pointer_64(c.data, offset, left, S, info);
3938 if (r == nullptr || left < sizeof(struct class_ro64_t))
3939 return nullptr;
3940 struct class_ro64_t cro;
3941 memcpy(&cro, r, sizeof(struct class_ro64_t));
3942 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3943 swapStruct(cro);
3944 if (cro.name == 0)
3945 return nullptr;
3946 const char *name = get_pointer_64(cro.name, offset, left, S, info);
3947 return name;
3948}
3949
3950// get_objc2_64bit_cfstring_name is used for disassembly and is passed a
3951// pointer to a cfstring and returns its name or nullptr.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00003952static const char *get_objc2_64bit_cfstring_name(uint64_t ReferenceValue,
3953 struct DisassembleInfo *info) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003954 const char *r, *name;
3955 uint32_t offset, left;
3956 SectionRef S;
3957 struct cfstring64_t cfs;
3958 uint64_t cfs_characters;
3959
3960 r = get_pointer_64(ReferenceValue, offset, left, S, info);
3961 if (r == nullptr || left < sizeof(struct cfstring64_t))
3962 return nullptr;
3963 memcpy(&cfs, r, sizeof(struct cfstring64_t));
3964 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3965 swapStruct(cfs);
3966 if (cfs.characters == 0) {
3967 uint64_t n_value;
3968 const char *symbol_name = get_symbol_64(
3969 offset + offsetof(struct cfstring64_t, characters), S, info, n_value);
3970 if (symbol_name == nullptr)
3971 return nullptr;
3972 cfs_characters = n_value;
3973 } else
3974 cfs_characters = cfs.characters;
3975 name = get_pointer_64(cfs_characters, offset, left, S, info);
3976
3977 return name;
3978}
3979
3980// get_objc2_64bit_selref() is used for disassembly and is passed a the address
3981// of a pointer to an Objective-C selector reference when the pointer value is
3982// zero as in a .o file and is likely to have a external relocation entry with
3983// who's symbol's n_value is the real pointer to the selector name. If that is
3984// the case the real pointer to the selector name is returned else 0 is
3985// returned
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00003986static uint64_t get_objc2_64bit_selref(uint64_t ReferenceValue,
3987 struct DisassembleInfo *info) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003988 uint32_t offset, left;
3989 SectionRef S;
3990
3991 const char *r = get_pointer_64(ReferenceValue, offset, left, S, info);
3992 if (r == nullptr || left < sizeof(uint64_t))
3993 return 0;
3994 uint64_t n_value;
3995 const char *symbol_name = get_symbol_64(offset, S, info, n_value);
3996 if (symbol_name == nullptr)
3997 return 0;
3998 return n_value;
3999}
4000
Kevin Enderby0fc11822015-04-01 20:57:01 +00004001static const SectionRef get_section(MachOObjectFile *O, const char *segname,
4002 const char *sectname) {
4003 for (const SectionRef &Section : O->sections()) {
4004 StringRef SectName;
4005 Section.getName(SectName);
4006 DataRefImpl Ref = Section.getRawDataRefImpl();
4007 StringRef SegName = O->getSectionFinalSegmentName(Ref);
4008 if (SegName == segname && SectName == sectname)
4009 return Section;
4010 }
4011 return SectionRef();
4012}
4013
4014static void
4015walk_pointer_list_64(const char *listname, const SectionRef S,
4016 MachOObjectFile *O, struct DisassembleInfo *info,
4017 void (*func)(uint64_t, struct DisassembleInfo *info)) {
4018 if (S == SectionRef())
4019 return;
4020
4021 StringRef SectName;
4022 S.getName(SectName);
4023 DataRefImpl Ref = S.getRawDataRefImpl();
4024 StringRef SegName = O->getSectionFinalSegmentName(Ref);
4025 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
4026
4027 StringRef BytesStr;
4028 S.getContents(BytesStr);
4029 const char *Contents = reinterpret_cast<const char *>(BytesStr.data());
4030
4031 for (uint32_t i = 0; i < S.getSize(); i += sizeof(uint64_t)) {
4032 uint32_t left = S.getSize() - i;
4033 uint32_t size = left < sizeof(uint64_t) ? left : sizeof(uint64_t);
4034 uint64_t p = 0;
4035 memcpy(&p, Contents + i, size);
4036 if (i + sizeof(uint64_t) > S.getSize())
4037 outs() << listname << " list pointer extends past end of (" << SegName
4038 << "," << SectName << ") section\n";
4039 outs() << format("%016" PRIx64, S.getAddress() + i) << " ";
4040
4041 if (O->isLittleEndian() != sys::IsLittleEndianHost)
4042 sys::swapByteOrder(p);
4043
4044 uint64_t n_value = 0;
4045 const char *name = get_symbol_64(i, S, info, n_value, p);
4046 if (name == nullptr)
4047 name = get_dyld_bind_info_symbolname(S.getAddress() + i, info);
4048
4049 if (n_value != 0) {
4050 outs() << format("0x%" PRIx64, n_value);
4051 if (p != 0)
4052 outs() << " + " << format("0x%" PRIx64, p);
4053 } else
4054 outs() << format("0x%" PRIx64, p);
4055 if (name != nullptr)
4056 outs() << " " << name;
4057 outs() << "\n";
4058
4059 p += n_value;
4060 if (func)
4061 func(p, info);
4062 }
4063}
4064
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004065static void
4066walk_pointer_list_32(const char *listname, const SectionRef S,
4067 MachOObjectFile *O, struct DisassembleInfo *info,
4068 void (*func)(uint32_t, struct DisassembleInfo *info)) {
4069 if (S == SectionRef())
4070 return;
4071
4072 StringRef SectName;
4073 S.getName(SectName);
4074 DataRefImpl Ref = S.getRawDataRefImpl();
4075 StringRef SegName = O->getSectionFinalSegmentName(Ref);
4076 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
4077
4078 StringRef BytesStr;
4079 S.getContents(BytesStr);
4080 const char *Contents = reinterpret_cast<const char *>(BytesStr.data());
4081
4082 for (uint32_t i = 0; i < S.getSize(); i += sizeof(uint32_t)) {
4083 uint32_t left = S.getSize() - i;
4084 uint32_t size = left < sizeof(uint32_t) ? left : sizeof(uint32_t);
4085 uint32_t p = 0;
4086 memcpy(&p, Contents + i, size);
4087 if (i + sizeof(uint32_t) > S.getSize())
4088 outs() << listname << " list pointer extends past end of (" << SegName
4089 << "," << SectName << ") section\n";
Kevin Enderbycf261312015-04-06 22:33:43 +00004090 uint32_t Address = S.getAddress() + i;
4091 outs() << format("%08" PRIx32, Address) << " ";
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004092
4093 if (O->isLittleEndian() != sys::IsLittleEndianHost)
4094 sys::swapByteOrder(p);
4095 outs() << format("0x%" PRIx32, p);
4096
4097 const char *name = get_symbol_32(i, S, info, p);
4098 if (name != nullptr)
4099 outs() << " " << name;
4100 outs() << "\n";
4101
4102 if (func)
4103 func(p, info);
4104 }
4105}
4106
4107static void print_layout_map(const char *layout_map, uint32_t left) {
Kevin Enderbya59824a2015-10-06 22:27:08 +00004108 if (layout_map == nullptr)
4109 return;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004110 outs() << " layout map: ";
4111 do {
4112 outs() << format("0x%02" PRIx32, (*layout_map) & 0xff) << " ";
4113 left--;
4114 layout_map++;
4115 } while (*layout_map != '\0' && left != 0);
4116 outs() << "\n";
4117}
4118
Kevin Enderby0fc11822015-04-01 20:57:01 +00004119static void print_layout_map64(uint64_t p, struct DisassembleInfo *info) {
4120 uint32_t offset, left;
4121 SectionRef S;
4122 const char *layout_map;
4123
4124 if (p == 0)
4125 return;
4126 layout_map = get_pointer_64(p, offset, left, S, info);
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004127 print_layout_map(layout_map, left);
4128}
4129
4130static void print_layout_map32(uint32_t p, struct DisassembleInfo *info) {
4131 uint32_t offset, left;
4132 SectionRef S;
4133 const char *layout_map;
4134
4135 if (p == 0)
4136 return;
4137 layout_map = get_pointer_32(p, offset, left, S, info);
4138 print_layout_map(layout_map, left);
Kevin Enderby0fc11822015-04-01 20:57:01 +00004139}
4140
4141static void print_method_list64_t(uint64_t p, struct DisassembleInfo *info,
4142 const char *indent) {
4143 struct method_list64_t ml;
4144 struct method64_t m;
4145 const char *r;
4146 uint32_t offset, xoffset, left, i;
4147 SectionRef S, xS;
4148 const char *name, *sym_name;
4149 uint64_t n_value;
4150
4151 r = get_pointer_64(p, offset, left, S, info);
4152 if (r == nullptr)
4153 return;
4154 memset(&ml, '\0', sizeof(struct method_list64_t));
4155 if (left < sizeof(struct method_list64_t)) {
4156 memcpy(&ml, r, left);
4157 outs() << " (method_list_t entends past the end of the section)\n";
4158 } else
4159 memcpy(&ml, r, sizeof(struct method_list64_t));
4160 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4161 swapStruct(ml);
4162 outs() << indent << "\t\t entsize " << ml.entsize << "\n";
4163 outs() << indent << "\t\t count " << ml.count << "\n";
4164
4165 p += sizeof(struct method_list64_t);
4166 offset += sizeof(struct method_list64_t);
4167 for (i = 0; i < ml.count; i++) {
4168 r = get_pointer_64(p, offset, left, S, info);
4169 if (r == nullptr)
4170 return;
4171 memset(&m, '\0', sizeof(struct method64_t));
4172 if (left < sizeof(struct method64_t)) {
Kevin Enderbya59824a2015-10-06 22:27:08 +00004173 memcpy(&m, r, left);
4174 outs() << indent << " (method_t extends past the end of the section)\n";
Kevin Enderby0fc11822015-04-01 20:57:01 +00004175 } else
4176 memcpy(&m, r, sizeof(struct method64_t));
4177 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4178 swapStruct(m);
4179
4180 outs() << indent << "\t\t name ";
4181 sym_name = get_symbol_64(offset + offsetof(struct method64_t, name), S,
4182 info, n_value, m.name);
4183 if (n_value != 0) {
4184 if (info->verbose && sym_name != nullptr)
4185 outs() << sym_name;
4186 else
4187 outs() << format("0x%" PRIx64, n_value);
4188 if (m.name != 0)
4189 outs() << " + " << format("0x%" PRIx64, m.name);
4190 } else
4191 outs() << format("0x%" PRIx64, m.name);
4192 name = get_pointer_64(m.name + n_value, xoffset, left, xS, info);
4193 if (name != nullptr)
4194 outs() << format(" %.*s", left, name);
4195 outs() << "\n";
4196
4197 outs() << indent << "\t\t types ";
4198 sym_name = get_symbol_64(offset + offsetof(struct method64_t, types), S,
4199 info, n_value, m.types);
4200 if (n_value != 0) {
4201 if (info->verbose && sym_name != nullptr)
4202 outs() << sym_name;
4203 else
4204 outs() << format("0x%" PRIx64, n_value);
4205 if (m.types != 0)
4206 outs() << " + " << format("0x%" PRIx64, m.types);
4207 } else
4208 outs() << format("0x%" PRIx64, m.types);
4209 name = get_pointer_64(m.types + n_value, xoffset, left, xS, info);
4210 if (name != nullptr)
4211 outs() << format(" %.*s", left, name);
4212 outs() << "\n";
4213
4214 outs() << indent << "\t\t imp ";
4215 name = get_symbol_64(offset + offsetof(struct method64_t, imp), S, info,
4216 n_value, m.imp);
4217 if (info->verbose && name == nullptr) {
4218 if (n_value != 0) {
4219 outs() << format("0x%" PRIx64, n_value) << " ";
4220 if (m.imp != 0)
4221 outs() << "+ " << format("0x%" PRIx64, m.imp) << " ";
4222 } else
4223 outs() << format("0x%" PRIx64, m.imp) << " ";
4224 }
4225 if (name != nullptr)
4226 outs() << name;
4227 outs() << "\n";
4228
4229 p += sizeof(struct method64_t);
4230 offset += sizeof(struct method64_t);
4231 }
4232}
4233
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004234static void print_method_list32_t(uint64_t p, struct DisassembleInfo *info,
4235 const char *indent) {
4236 struct method_list32_t ml;
4237 struct method32_t m;
Kevin Enderby846c0002015-04-16 17:19:59 +00004238 const char *r, *name;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004239 uint32_t offset, xoffset, left, i;
4240 SectionRef S, xS;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004241
4242 r = get_pointer_32(p, offset, left, S, info);
4243 if (r == nullptr)
4244 return;
4245 memset(&ml, '\0', sizeof(struct method_list32_t));
4246 if (left < sizeof(struct method_list32_t)) {
4247 memcpy(&ml, r, left);
4248 outs() << " (method_list_t entends past the end of the section)\n";
4249 } else
4250 memcpy(&ml, r, sizeof(struct method_list32_t));
4251 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4252 swapStruct(ml);
4253 outs() << indent << "\t\t entsize " << ml.entsize << "\n";
4254 outs() << indent << "\t\t count " << ml.count << "\n";
4255
4256 p += sizeof(struct method_list32_t);
4257 offset += sizeof(struct method_list32_t);
4258 for (i = 0; i < ml.count; i++) {
4259 r = get_pointer_32(p, offset, left, S, info);
4260 if (r == nullptr)
4261 return;
4262 memset(&m, '\0', sizeof(struct method32_t));
4263 if (left < sizeof(struct method32_t)) {
4264 memcpy(&ml, r, left);
4265 outs() << indent << " (method_t entends past the end of the section)\n";
4266 } else
4267 memcpy(&m, r, sizeof(struct method32_t));
4268 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4269 swapStruct(m);
4270
4271 outs() << indent << "\t\t name " << format("0x%" PRIx32, m.name);
4272 name = get_pointer_32(m.name, xoffset, left, xS, info);
4273 if (name != nullptr)
4274 outs() << format(" %.*s", left, name);
4275 outs() << "\n";
4276
4277 outs() << indent << "\t\t types " << format("0x%" PRIx32, m.types);
4278 name = get_pointer_32(m.types, xoffset, left, xS, info);
4279 if (name != nullptr)
4280 outs() << format(" %.*s", left, name);
4281 outs() << "\n";
4282
4283 outs() << indent << "\t\t imp " << format("0x%" PRIx32, m.imp);
4284 name = get_symbol_32(offset + offsetof(struct method32_t, imp), S, info,
4285 m.imp);
4286 if (name != nullptr)
4287 outs() << " " << name;
4288 outs() << "\n";
4289
4290 p += sizeof(struct method32_t);
4291 offset += sizeof(struct method32_t);
4292 }
4293}
4294
Kevin Enderby846c0002015-04-16 17:19:59 +00004295static bool print_method_list(uint32_t p, struct DisassembleInfo *info) {
4296 uint32_t offset, left, xleft;
4297 SectionRef S;
4298 struct objc_method_list_t method_list;
4299 struct objc_method_t method;
4300 const char *r, *methods, *name, *SymbolName;
4301 int32_t i;
4302
4303 r = get_pointer_32(p, offset, left, S, info, true);
4304 if (r == nullptr)
4305 return true;
4306
4307 outs() << "\n";
4308 if (left > sizeof(struct objc_method_list_t)) {
4309 memcpy(&method_list, r, sizeof(struct objc_method_list_t));
4310 } else {
4311 outs() << "\t\t objc_method_list extends past end of the section\n";
4312 memset(&method_list, '\0', sizeof(struct objc_method_list_t));
4313 memcpy(&method_list, r, left);
4314 }
4315 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4316 swapStruct(method_list);
4317
4318 outs() << "\t\t obsolete "
4319 << format("0x%08" PRIx32, method_list.obsolete) << "\n";
4320 outs() << "\t\t method_count " << method_list.method_count << "\n";
4321
4322 methods = r + sizeof(struct objc_method_list_t);
4323 for (i = 0; i < method_list.method_count; i++) {
4324 if ((i + 1) * sizeof(struct objc_method_t) > left) {
4325 outs() << "\t\t remaining method's extend past the of the section\n";
4326 break;
4327 }
4328 memcpy(&method, methods + i * sizeof(struct objc_method_t),
4329 sizeof(struct objc_method_t));
4330 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4331 swapStruct(method);
4332
4333 outs() << "\t\t method_name "
4334 << format("0x%08" PRIx32, method.method_name);
4335 if (info->verbose) {
4336 name = get_pointer_32(method.method_name, offset, xleft, S, info, true);
4337 if (name != nullptr)
4338 outs() << format(" %.*s", xleft, name);
4339 else
4340 outs() << " (not in an __OBJC section)";
4341 }
4342 outs() << "\n";
4343
4344 outs() << "\t\t method_types "
4345 << format("0x%08" PRIx32, method.method_types);
4346 if (info->verbose) {
4347 name = get_pointer_32(method.method_types, offset, xleft, S, info, true);
4348 if (name != nullptr)
4349 outs() << format(" %.*s", xleft, name);
4350 else
4351 outs() << " (not in an __OBJC section)";
4352 }
4353 outs() << "\n";
4354
4355 outs() << "\t\t method_imp "
4356 << format("0x%08" PRIx32, method.method_imp) << " ";
4357 if (info->verbose) {
4358 SymbolName = GuessSymbolName(method.method_imp, info->AddrMap);
4359 if (SymbolName != nullptr)
4360 outs() << SymbolName;
4361 }
4362 outs() << "\n";
4363 }
4364 return false;
4365}
4366
Kevin Enderby0fc11822015-04-01 20:57:01 +00004367static void print_protocol_list64_t(uint64_t p, struct DisassembleInfo *info) {
4368 struct protocol_list64_t pl;
4369 uint64_t q, n_value;
4370 struct protocol64_t pc;
4371 const char *r;
4372 uint32_t offset, xoffset, left, i;
4373 SectionRef S, xS;
4374 const char *name, *sym_name;
4375
4376 r = get_pointer_64(p, offset, left, S, info);
4377 if (r == nullptr)
4378 return;
4379 memset(&pl, '\0', sizeof(struct protocol_list64_t));
4380 if (left < sizeof(struct protocol_list64_t)) {
4381 memcpy(&pl, r, left);
4382 outs() << " (protocol_list_t entends past the end of the section)\n";
4383 } else
4384 memcpy(&pl, r, sizeof(struct protocol_list64_t));
4385 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4386 swapStruct(pl);
4387 outs() << " count " << pl.count << "\n";
4388
4389 p += sizeof(struct protocol_list64_t);
4390 offset += sizeof(struct protocol_list64_t);
4391 for (i = 0; i < pl.count; i++) {
4392 r = get_pointer_64(p, offset, left, S, info);
4393 if (r == nullptr)
4394 return;
4395 q = 0;
4396 if (left < sizeof(uint64_t)) {
4397 memcpy(&q, r, left);
4398 outs() << " (protocol_t * entends past the end of the section)\n";
4399 } else
4400 memcpy(&q, r, sizeof(uint64_t));
4401 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4402 sys::swapByteOrder(q);
4403
4404 outs() << "\t\t list[" << i << "] ";
4405 sym_name = get_symbol_64(offset, S, info, n_value, q);
4406 if (n_value != 0) {
4407 if (info->verbose && sym_name != nullptr)
4408 outs() << sym_name;
4409 else
4410 outs() << format("0x%" PRIx64, n_value);
4411 if (q != 0)
4412 outs() << " + " << format("0x%" PRIx64, q);
4413 } else
4414 outs() << format("0x%" PRIx64, q);
4415 outs() << " (struct protocol_t *)\n";
4416
4417 r = get_pointer_64(q + n_value, offset, left, S, info);
4418 if (r == nullptr)
4419 return;
4420 memset(&pc, '\0', sizeof(struct protocol64_t));
4421 if (left < sizeof(struct protocol64_t)) {
4422 memcpy(&pc, r, left);
4423 outs() << " (protocol_t entends past the end of the section)\n";
4424 } else
4425 memcpy(&pc, r, sizeof(struct protocol64_t));
4426 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4427 swapStruct(pc);
4428
4429 outs() << "\t\t\t isa " << format("0x%" PRIx64, pc.isa) << "\n";
4430
4431 outs() << "\t\t\t name ";
4432 sym_name = get_symbol_64(offset + offsetof(struct protocol64_t, name), S,
4433 info, n_value, pc.name);
4434 if (n_value != 0) {
4435 if (info->verbose && sym_name != nullptr)
4436 outs() << sym_name;
4437 else
4438 outs() << format("0x%" PRIx64, n_value);
4439 if (pc.name != 0)
4440 outs() << " + " << format("0x%" PRIx64, pc.name);
4441 } else
4442 outs() << format("0x%" PRIx64, pc.name);
4443 name = get_pointer_64(pc.name + n_value, xoffset, left, xS, info);
4444 if (name != nullptr)
4445 outs() << format(" %.*s", left, name);
4446 outs() << "\n";
4447
4448 outs() << "\t\t\tprotocols " << format("0x%" PRIx64, pc.protocols) << "\n";
4449
4450 outs() << "\t\t instanceMethods ";
4451 sym_name =
4452 get_symbol_64(offset + offsetof(struct protocol64_t, instanceMethods),
4453 S, info, n_value, pc.instanceMethods);
4454 if (n_value != 0) {
4455 if (info->verbose && sym_name != nullptr)
4456 outs() << sym_name;
4457 else
4458 outs() << format("0x%" PRIx64, n_value);
4459 if (pc.instanceMethods != 0)
4460 outs() << " + " << format("0x%" PRIx64, pc.instanceMethods);
4461 } else
4462 outs() << format("0x%" PRIx64, pc.instanceMethods);
4463 outs() << " (struct method_list_t *)\n";
4464 if (pc.instanceMethods + n_value != 0)
4465 print_method_list64_t(pc.instanceMethods + n_value, info, "\t");
4466
4467 outs() << "\t\t classMethods ";
4468 sym_name =
4469 get_symbol_64(offset + offsetof(struct protocol64_t, classMethods), S,
4470 info, n_value, pc.classMethods);
4471 if (n_value != 0) {
4472 if (info->verbose && sym_name != nullptr)
4473 outs() << sym_name;
4474 else
4475 outs() << format("0x%" PRIx64, n_value);
4476 if (pc.classMethods != 0)
4477 outs() << " + " << format("0x%" PRIx64, pc.classMethods);
4478 } else
4479 outs() << format("0x%" PRIx64, pc.classMethods);
4480 outs() << " (struct method_list_t *)\n";
4481 if (pc.classMethods + n_value != 0)
4482 print_method_list64_t(pc.classMethods + n_value, info, "\t");
4483
4484 outs() << "\t optionalInstanceMethods "
4485 << format("0x%" PRIx64, pc.optionalInstanceMethods) << "\n";
4486 outs() << "\t optionalClassMethods "
4487 << format("0x%" PRIx64, pc.optionalClassMethods) << "\n";
4488 outs() << "\t instanceProperties "
4489 << format("0x%" PRIx64, pc.instanceProperties) << "\n";
4490
4491 p += sizeof(uint64_t);
4492 offset += sizeof(uint64_t);
4493 }
4494}
4495
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004496static void print_protocol_list32_t(uint32_t p, struct DisassembleInfo *info) {
4497 struct protocol_list32_t pl;
4498 uint32_t q;
4499 struct protocol32_t pc;
4500 const char *r;
4501 uint32_t offset, xoffset, left, i;
4502 SectionRef S, xS;
4503 const char *name;
4504
4505 r = get_pointer_32(p, offset, left, S, info);
4506 if (r == nullptr)
4507 return;
4508 memset(&pl, '\0', sizeof(struct protocol_list32_t));
4509 if (left < sizeof(struct protocol_list32_t)) {
4510 memcpy(&pl, r, left);
4511 outs() << " (protocol_list_t entends past the end of the section)\n";
4512 } else
4513 memcpy(&pl, r, sizeof(struct protocol_list32_t));
4514 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4515 swapStruct(pl);
4516 outs() << " count " << pl.count << "\n";
4517
4518 p += sizeof(struct protocol_list32_t);
4519 offset += sizeof(struct protocol_list32_t);
4520 for (i = 0; i < pl.count; i++) {
4521 r = get_pointer_32(p, offset, left, S, info);
4522 if (r == nullptr)
4523 return;
4524 q = 0;
4525 if (left < sizeof(uint32_t)) {
4526 memcpy(&q, r, left);
4527 outs() << " (protocol_t * entends past the end of the section)\n";
4528 } else
4529 memcpy(&q, r, sizeof(uint32_t));
4530 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4531 sys::swapByteOrder(q);
4532 outs() << "\t\t list[" << i << "] " << format("0x%" PRIx32, q)
4533 << " (struct protocol_t *)\n";
4534 r = get_pointer_32(q, offset, left, S, info);
4535 if (r == nullptr)
4536 return;
4537 memset(&pc, '\0', sizeof(struct protocol32_t));
4538 if (left < sizeof(struct protocol32_t)) {
4539 memcpy(&pc, r, left);
4540 outs() << " (protocol_t entends past the end of the section)\n";
4541 } else
4542 memcpy(&pc, r, sizeof(struct protocol32_t));
4543 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4544 swapStruct(pc);
4545 outs() << "\t\t\t isa " << format("0x%" PRIx32, pc.isa) << "\n";
4546 outs() << "\t\t\t name " << format("0x%" PRIx32, pc.name);
4547 name = get_pointer_32(pc.name, xoffset, left, xS, info);
4548 if (name != nullptr)
4549 outs() << format(" %.*s", left, name);
4550 outs() << "\n";
4551 outs() << "\t\t\tprotocols " << format("0x%" PRIx32, pc.protocols) << "\n";
4552 outs() << "\t\t instanceMethods "
4553 << format("0x%" PRIx32, pc.instanceMethods)
4554 << " (struct method_list_t *)\n";
4555 if (pc.instanceMethods != 0)
4556 print_method_list32_t(pc.instanceMethods, info, "\t");
4557 outs() << "\t\t classMethods " << format("0x%" PRIx32, pc.classMethods)
4558 << " (struct method_list_t *)\n";
4559 if (pc.classMethods != 0)
4560 print_method_list32_t(pc.classMethods, info, "\t");
4561 outs() << "\t optionalInstanceMethods "
4562 << format("0x%" PRIx32, pc.optionalInstanceMethods) << "\n";
4563 outs() << "\t optionalClassMethods "
4564 << format("0x%" PRIx32, pc.optionalClassMethods) << "\n";
4565 outs() << "\t instanceProperties "
4566 << format("0x%" PRIx32, pc.instanceProperties) << "\n";
4567 p += sizeof(uint32_t);
4568 offset += sizeof(uint32_t);
4569 }
4570}
4571
Kevin Enderby846c0002015-04-16 17:19:59 +00004572static void print_indent(uint32_t indent) {
4573 for (uint32_t i = 0; i < indent;) {
4574 if (indent - i >= 8) {
4575 outs() << "\t";
4576 i += 8;
4577 } else {
4578 for (uint32_t j = i; j < indent; j++)
4579 outs() << " ";
4580 return;
4581 }
4582 }
4583}
4584
4585static bool print_method_description_list(uint32_t p, uint32_t indent,
4586 struct DisassembleInfo *info) {
4587 uint32_t offset, left, xleft;
4588 SectionRef S;
4589 struct objc_method_description_list_t mdl;
4590 struct objc_method_description_t md;
4591 const char *r, *list, *name;
4592 int32_t i;
4593
4594 r = get_pointer_32(p, offset, left, S, info, true);
4595 if (r == nullptr)
4596 return true;
4597
4598 outs() << "\n";
4599 if (left > sizeof(struct objc_method_description_list_t)) {
4600 memcpy(&mdl, r, sizeof(struct objc_method_description_list_t));
4601 } else {
4602 print_indent(indent);
4603 outs() << " objc_method_description_list extends past end of the section\n";
4604 memset(&mdl, '\0', sizeof(struct objc_method_description_list_t));
4605 memcpy(&mdl, r, left);
4606 }
4607 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4608 swapStruct(mdl);
4609
4610 print_indent(indent);
4611 outs() << " count " << mdl.count << "\n";
4612
4613 list = r + sizeof(struct objc_method_description_list_t);
4614 for (i = 0; i < mdl.count; i++) {
4615 if ((i + 1) * sizeof(struct objc_method_description_t) > left) {
4616 print_indent(indent);
4617 outs() << " remaining list entries extend past the of the section\n";
4618 break;
4619 }
4620 print_indent(indent);
4621 outs() << " list[" << i << "]\n";
4622 memcpy(&md, list + i * sizeof(struct objc_method_description_t),
4623 sizeof(struct objc_method_description_t));
4624 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4625 swapStruct(md);
4626
4627 print_indent(indent);
4628 outs() << " name " << format("0x%08" PRIx32, md.name);
4629 if (info->verbose) {
4630 name = get_pointer_32(md.name, offset, xleft, S, info, true);
4631 if (name != nullptr)
4632 outs() << format(" %.*s", xleft, name);
4633 else
4634 outs() << " (not in an __OBJC section)";
4635 }
4636 outs() << "\n";
4637
4638 print_indent(indent);
4639 outs() << " types " << format("0x%08" PRIx32, md.types);
4640 if (info->verbose) {
4641 name = get_pointer_32(md.types, offset, xleft, S, info, true);
4642 if (name != nullptr)
4643 outs() << format(" %.*s", xleft, name);
4644 else
4645 outs() << " (not in an __OBJC section)";
4646 }
4647 outs() << "\n";
4648 }
4649 return false;
4650}
4651
4652static bool print_protocol_list(uint32_t p, uint32_t indent,
4653 struct DisassembleInfo *info);
4654
4655static bool print_protocol(uint32_t p, uint32_t indent,
4656 struct DisassembleInfo *info) {
4657 uint32_t offset, left;
4658 SectionRef S;
4659 struct objc_protocol_t protocol;
4660 const char *r, *name;
4661
4662 r = get_pointer_32(p, offset, left, S, info, true);
4663 if (r == nullptr)
4664 return true;
4665
4666 outs() << "\n";
4667 if (left >= sizeof(struct objc_protocol_t)) {
4668 memcpy(&protocol, r, sizeof(struct objc_protocol_t));
4669 } else {
4670 print_indent(indent);
4671 outs() << " Protocol extends past end of the section\n";
4672 memset(&protocol, '\0', sizeof(struct objc_protocol_t));
4673 memcpy(&protocol, r, left);
4674 }
4675 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4676 swapStruct(protocol);
4677
4678 print_indent(indent);
4679 outs() << " isa " << format("0x%08" PRIx32, protocol.isa)
4680 << "\n";
4681
4682 print_indent(indent);
4683 outs() << " protocol_name "
4684 << format("0x%08" PRIx32, protocol.protocol_name);
4685 if (info->verbose) {
4686 name = get_pointer_32(protocol.protocol_name, offset, left, S, info, true);
4687 if (name != nullptr)
4688 outs() << format(" %.*s", left, name);
4689 else
4690 outs() << " (not in an __OBJC section)";
4691 }
4692 outs() << "\n";
4693
4694 print_indent(indent);
4695 outs() << " protocol_list "
4696 << format("0x%08" PRIx32, protocol.protocol_list);
4697 if (print_protocol_list(protocol.protocol_list, indent + 4, info))
4698 outs() << " (not in an __OBJC section)\n";
4699
4700 print_indent(indent);
4701 outs() << " instance_methods "
4702 << format("0x%08" PRIx32, protocol.instance_methods);
4703 if (print_method_description_list(protocol.instance_methods, indent, info))
4704 outs() << " (not in an __OBJC section)\n";
4705
4706 print_indent(indent);
4707 outs() << " class_methods "
4708 << format("0x%08" PRIx32, protocol.class_methods);
4709 if (print_method_description_list(protocol.class_methods, indent, info))
4710 outs() << " (not in an __OBJC section)\n";
4711
4712 return false;
4713}
4714
4715static bool print_protocol_list(uint32_t p, uint32_t indent,
4716 struct DisassembleInfo *info) {
4717 uint32_t offset, left, l;
4718 SectionRef S;
4719 struct objc_protocol_list_t protocol_list;
4720 const char *r, *list;
4721 int32_t i;
4722
4723 r = get_pointer_32(p, offset, left, S, info, true);
4724 if (r == nullptr)
4725 return true;
4726
4727 outs() << "\n";
4728 if (left > sizeof(struct objc_protocol_list_t)) {
4729 memcpy(&protocol_list, r, sizeof(struct objc_protocol_list_t));
4730 } else {
4731 outs() << "\t\t objc_protocol_list_t extends past end of the section\n";
4732 memset(&protocol_list, '\0', sizeof(struct objc_protocol_list_t));
4733 memcpy(&protocol_list, r, left);
4734 }
4735 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4736 swapStruct(protocol_list);
4737
4738 print_indent(indent);
4739 outs() << " next " << format("0x%08" PRIx32, protocol_list.next)
4740 << "\n";
4741 print_indent(indent);
4742 outs() << " count " << protocol_list.count << "\n";
4743
4744 list = r + sizeof(struct objc_protocol_list_t);
4745 for (i = 0; i < protocol_list.count; i++) {
4746 if ((i + 1) * sizeof(uint32_t) > left) {
4747 outs() << "\t\t remaining list entries extend past the of the section\n";
4748 break;
4749 }
4750 memcpy(&l, list + i * sizeof(uint32_t), sizeof(uint32_t));
4751 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4752 sys::swapByteOrder(l);
4753
4754 print_indent(indent);
4755 outs() << " list[" << i << "] " << format("0x%08" PRIx32, l);
4756 if (print_protocol(l, indent, info))
4757 outs() << "(not in an __OBJC section)\n";
4758 }
4759 return false;
4760}
4761
Kevin Enderby0fc11822015-04-01 20:57:01 +00004762static void print_ivar_list64_t(uint64_t p, struct DisassembleInfo *info) {
4763 struct ivar_list64_t il;
4764 struct ivar64_t i;
4765 const char *r;
4766 uint32_t offset, xoffset, left, j;
4767 SectionRef S, xS;
4768 const char *name, *sym_name, *ivar_offset_p;
4769 uint64_t ivar_offset, n_value;
4770
4771 r = get_pointer_64(p, offset, left, S, info);
4772 if (r == nullptr)
4773 return;
4774 memset(&il, '\0', sizeof(struct ivar_list64_t));
4775 if (left < sizeof(struct ivar_list64_t)) {
4776 memcpy(&il, r, left);
4777 outs() << " (ivar_list_t entends past the end of the section)\n";
4778 } else
4779 memcpy(&il, r, sizeof(struct ivar_list64_t));
4780 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4781 swapStruct(il);
4782 outs() << " entsize " << il.entsize << "\n";
4783 outs() << " count " << il.count << "\n";
4784
4785 p += sizeof(struct ivar_list64_t);
4786 offset += sizeof(struct ivar_list64_t);
4787 for (j = 0; j < il.count; j++) {
4788 r = get_pointer_64(p, offset, left, S, info);
4789 if (r == nullptr)
4790 return;
4791 memset(&i, '\0', sizeof(struct ivar64_t));
4792 if (left < sizeof(struct ivar64_t)) {
4793 memcpy(&i, r, left);
4794 outs() << " (ivar_t entends past the end of the section)\n";
4795 } else
4796 memcpy(&i, r, sizeof(struct ivar64_t));
4797 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4798 swapStruct(i);
4799
4800 outs() << "\t\t\t offset ";
4801 sym_name = get_symbol_64(offset + offsetof(struct ivar64_t, offset), S,
4802 info, n_value, i.offset);
4803 if (n_value != 0) {
4804 if (info->verbose && sym_name != nullptr)
4805 outs() << sym_name;
4806 else
4807 outs() << format("0x%" PRIx64, n_value);
4808 if (i.offset != 0)
4809 outs() << " + " << format("0x%" PRIx64, i.offset);
4810 } else
4811 outs() << format("0x%" PRIx64, i.offset);
4812 ivar_offset_p = get_pointer_64(i.offset + n_value, xoffset, left, xS, info);
4813 if (ivar_offset_p != nullptr && left >= sizeof(*ivar_offset_p)) {
4814 memcpy(&ivar_offset, ivar_offset_p, sizeof(ivar_offset));
4815 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4816 sys::swapByteOrder(ivar_offset);
4817 outs() << " " << ivar_offset << "\n";
4818 } else
4819 outs() << "\n";
4820
4821 outs() << "\t\t\t name ";
4822 sym_name = get_symbol_64(offset + offsetof(struct ivar64_t, name), S, info,
4823 n_value, i.name);
4824 if (n_value != 0) {
4825 if (info->verbose && sym_name != nullptr)
4826 outs() << sym_name;
4827 else
4828 outs() << format("0x%" PRIx64, n_value);
4829 if (i.name != 0)
4830 outs() << " + " << format("0x%" PRIx64, i.name);
4831 } else
4832 outs() << format("0x%" PRIx64, i.name);
4833 name = get_pointer_64(i.name + n_value, xoffset, left, xS, info);
4834 if (name != nullptr)
4835 outs() << format(" %.*s", left, name);
4836 outs() << "\n";
4837
4838 outs() << "\t\t\t type ";
4839 sym_name = get_symbol_64(offset + offsetof(struct ivar64_t, type), S, info,
4840 n_value, i.name);
4841 name = get_pointer_64(i.type + n_value, xoffset, left, xS, info);
4842 if (n_value != 0) {
4843 if (info->verbose && sym_name != nullptr)
4844 outs() << sym_name;
4845 else
4846 outs() << format("0x%" PRIx64, n_value);
4847 if (i.type != 0)
4848 outs() << " + " << format("0x%" PRIx64, i.type);
4849 } else
4850 outs() << format("0x%" PRIx64, i.type);
4851 if (name != nullptr)
4852 outs() << format(" %.*s", left, name);
4853 outs() << "\n";
4854
4855 outs() << "\t\t\talignment " << i.alignment << "\n";
4856 outs() << "\t\t\t size " << i.size << "\n";
4857
4858 p += sizeof(struct ivar64_t);
4859 offset += sizeof(struct ivar64_t);
4860 }
4861}
4862
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004863static void print_ivar_list32_t(uint32_t p, struct DisassembleInfo *info) {
4864 struct ivar_list32_t il;
4865 struct ivar32_t i;
4866 const char *r;
4867 uint32_t offset, xoffset, left, j;
4868 SectionRef S, xS;
4869 const char *name, *ivar_offset_p;
4870 uint32_t ivar_offset;
4871
4872 r = get_pointer_32(p, offset, left, S, info);
4873 if (r == nullptr)
4874 return;
4875 memset(&il, '\0', sizeof(struct ivar_list32_t));
4876 if (left < sizeof(struct ivar_list32_t)) {
4877 memcpy(&il, r, left);
4878 outs() << " (ivar_list_t entends past the end of the section)\n";
4879 } else
4880 memcpy(&il, r, sizeof(struct ivar_list32_t));
4881 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4882 swapStruct(il);
4883 outs() << " entsize " << il.entsize << "\n";
4884 outs() << " count " << il.count << "\n";
4885
4886 p += sizeof(struct ivar_list32_t);
4887 offset += sizeof(struct ivar_list32_t);
4888 for (j = 0; j < il.count; j++) {
4889 r = get_pointer_32(p, offset, left, S, info);
4890 if (r == nullptr)
4891 return;
4892 memset(&i, '\0', sizeof(struct ivar32_t));
4893 if (left < sizeof(struct ivar32_t)) {
4894 memcpy(&i, r, left);
4895 outs() << " (ivar_t entends past the end of the section)\n";
4896 } else
4897 memcpy(&i, r, sizeof(struct ivar32_t));
4898 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4899 swapStruct(i);
4900
4901 outs() << "\t\t\t offset " << format("0x%" PRIx32, i.offset);
4902 ivar_offset_p = get_pointer_32(i.offset, xoffset, left, xS, info);
4903 if (ivar_offset_p != nullptr && left >= sizeof(*ivar_offset_p)) {
4904 memcpy(&ivar_offset, ivar_offset_p, sizeof(ivar_offset));
4905 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4906 sys::swapByteOrder(ivar_offset);
4907 outs() << " " << ivar_offset << "\n";
4908 } else
4909 outs() << "\n";
4910
4911 outs() << "\t\t\t name " << format("0x%" PRIx32, i.name);
4912 name = get_pointer_32(i.name, xoffset, left, xS, info);
4913 if (name != nullptr)
4914 outs() << format(" %.*s", left, name);
4915 outs() << "\n";
4916
4917 outs() << "\t\t\t type " << format("0x%" PRIx32, i.type);
4918 name = get_pointer_32(i.type, xoffset, left, xS, info);
4919 if (name != nullptr)
4920 outs() << format(" %.*s", left, name);
4921 outs() << "\n";
4922
4923 outs() << "\t\t\talignment " << i.alignment << "\n";
4924 outs() << "\t\t\t size " << i.size << "\n";
4925
4926 p += sizeof(struct ivar32_t);
4927 offset += sizeof(struct ivar32_t);
4928 }
4929}
4930
Kevin Enderby0fc11822015-04-01 20:57:01 +00004931static void print_objc_property_list64(uint64_t p,
4932 struct DisassembleInfo *info) {
4933 struct objc_property_list64 opl;
4934 struct objc_property64 op;
4935 const char *r;
4936 uint32_t offset, xoffset, left, j;
4937 SectionRef S, xS;
4938 const char *name, *sym_name;
4939 uint64_t n_value;
4940
4941 r = get_pointer_64(p, offset, left, S, info);
4942 if (r == nullptr)
4943 return;
4944 memset(&opl, '\0', sizeof(struct objc_property_list64));
4945 if (left < sizeof(struct objc_property_list64)) {
4946 memcpy(&opl, r, left);
4947 outs() << " (objc_property_list entends past the end of the section)\n";
4948 } else
4949 memcpy(&opl, r, sizeof(struct objc_property_list64));
4950 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4951 swapStruct(opl);
4952 outs() << " entsize " << opl.entsize << "\n";
4953 outs() << " count " << opl.count << "\n";
4954
4955 p += sizeof(struct objc_property_list64);
4956 offset += sizeof(struct objc_property_list64);
4957 for (j = 0; j < opl.count; j++) {
4958 r = get_pointer_64(p, offset, left, S, info);
4959 if (r == nullptr)
4960 return;
4961 memset(&op, '\0', sizeof(struct objc_property64));
4962 if (left < sizeof(struct objc_property64)) {
4963 memcpy(&op, r, left);
4964 outs() << " (objc_property entends past the end of the section)\n";
4965 } else
4966 memcpy(&op, r, sizeof(struct objc_property64));
4967 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4968 swapStruct(op);
4969
4970 outs() << "\t\t\t name ";
4971 sym_name = get_symbol_64(offset + offsetof(struct objc_property64, name), S,
4972 info, n_value, op.name);
4973 if (n_value != 0) {
4974 if (info->verbose && sym_name != nullptr)
4975 outs() << sym_name;
4976 else
4977 outs() << format("0x%" PRIx64, n_value);
4978 if (op.name != 0)
4979 outs() << " + " << format("0x%" PRIx64, op.name);
4980 } else
4981 outs() << format("0x%" PRIx64, op.name);
4982 name = get_pointer_64(op.name + n_value, xoffset, left, xS, info);
4983 if (name != nullptr)
4984 outs() << format(" %.*s", left, name);
4985 outs() << "\n";
4986
4987 outs() << "\t\t\tattributes ";
4988 sym_name =
4989 get_symbol_64(offset + offsetof(struct objc_property64, attributes), S,
4990 info, n_value, op.attributes);
4991 if (n_value != 0) {
4992 if (info->verbose && sym_name != nullptr)
4993 outs() << sym_name;
4994 else
4995 outs() << format("0x%" PRIx64, n_value);
4996 if (op.attributes != 0)
4997 outs() << " + " << format("0x%" PRIx64, op.attributes);
4998 } else
4999 outs() << format("0x%" PRIx64, op.attributes);
5000 name = get_pointer_64(op.attributes + n_value, xoffset, left, xS, info);
5001 if (name != nullptr)
5002 outs() << format(" %.*s", left, name);
5003 outs() << "\n";
5004
5005 p += sizeof(struct objc_property64);
5006 offset += sizeof(struct objc_property64);
5007 }
5008}
5009
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005010static void print_objc_property_list32(uint32_t p,
5011 struct DisassembleInfo *info) {
5012 struct objc_property_list32 opl;
5013 struct objc_property32 op;
5014 const char *r;
5015 uint32_t offset, xoffset, left, j;
5016 SectionRef S, xS;
5017 const char *name;
5018
5019 r = get_pointer_32(p, offset, left, S, info);
5020 if (r == nullptr)
5021 return;
5022 memset(&opl, '\0', sizeof(struct objc_property_list32));
5023 if (left < sizeof(struct objc_property_list32)) {
5024 memcpy(&opl, r, left);
5025 outs() << " (objc_property_list entends past the end of the section)\n";
5026 } else
5027 memcpy(&opl, r, sizeof(struct objc_property_list32));
5028 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5029 swapStruct(opl);
5030 outs() << " entsize " << opl.entsize << "\n";
5031 outs() << " count " << opl.count << "\n";
5032
5033 p += sizeof(struct objc_property_list32);
5034 offset += sizeof(struct objc_property_list32);
5035 for (j = 0; j < opl.count; j++) {
5036 r = get_pointer_32(p, offset, left, S, info);
5037 if (r == nullptr)
5038 return;
5039 memset(&op, '\0', sizeof(struct objc_property32));
5040 if (left < sizeof(struct objc_property32)) {
5041 memcpy(&op, r, left);
5042 outs() << " (objc_property entends past the end of the section)\n";
5043 } else
5044 memcpy(&op, r, sizeof(struct objc_property32));
5045 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5046 swapStruct(op);
5047
5048 outs() << "\t\t\t name " << format("0x%" PRIx32, op.name);
5049 name = get_pointer_32(op.name, xoffset, left, xS, info);
5050 if (name != nullptr)
5051 outs() << format(" %.*s", left, name);
5052 outs() << "\n";
5053
5054 outs() << "\t\t\tattributes " << format("0x%" PRIx32, op.attributes);
5055 name = get_pointer_32(op.attributes, xoffset, left, xS, info);
5056 if (name != nullptr)
5057 outs() << format(" %.*s", left, name);
5058 outs() << "\n";
5059
5060 p += sizeof(struct objc_property32);
5061 offset += sizeof(struct objc_property32);
5062 }
5063}
5064
Richard Smith81ff44d2015-10-09 22:09:56 +00005065static bool print_class_ro64_t(uint64_t p, struct DisassembleInfo *info,
Kevin Enderby0fc11822015-04-01 20:57:01 +00005066 bool &is_meta_class) {
5067 struct class_ro64_t cro;
5068 const char *r;
5069 uint32_t offset, xoffset, left;
5070 SectionRef S, xS;
5071 const char *name, *sym_name;
5072 uint64_t n_value;
5073
5074 r = get_pointer_64(p, offset, left, S, info);
5075 if (r == nullptr || left < sizeof(struct class_ro64_t))
Richard Smith81ff44d2015-10-09 22:09:56 +00005076 return false;
Chandler Carruth33e58902016-11-04 07:10:24 +00005077 memcpy(&cro, r, sizeof(struct class_ro64_t));
Kevin Enderby0fc11822015-04-01 20:57:01 +00005078 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5079 swapStruct(cro);
5080 outs() << " flags " << format("0x%" PRIx32, cro.flags);
5081 if (cro.flags & RO_META)
5082 outs() << " RO_META";
5083 if (cro.flags & RO_ROOT)
5084 outs() << " RO_ROOT";
5085 if (cro.flags & RO_HAS_CXX_STRUCTORS)
5086 outs() << " RO_HAS_CXX_STRUCTORS";
5087 outs() << "\n";
5088 outs() << " instanceStart " << cro.instanceStart << "\n";
5089 outs() << " instanceSize " << cro.instanceSize << "\n";
5090 outs() << " reserved " << format("0x%" PRIx32, cro.reserved)
5091 << "\n";
5092 outs() << " ivarLayout " << format("0x%" PRIx64, cro.ivarLayout)
5093 << "\n";
5094 print_layout_map64(cro.ivarLayout, info);
5095
5096 outs() << " name ";
5097 sym_name = get_symbol_64(offset + offsetof(struct class_ro64_t, name), S,
5098 info, n_value, cro.name);
5099 if (n_value != 0) {
5100 if (info->verbose && sym_name != nullptr)
5101 outs() << sym_name;
5102 else
5103 outs() << format("0x%" PRIx64, n_value);
5104 if (cro.name != 0)
5105 outs() << " + " << format("0x%" PRIx64, cro.name);
5106 } else
5107 outs() << format("0x%" PRIx64, cro.name);
5108 name = get_pointer_64(cro.name + n_value, xoffset, left, xS, info);
5109 if (name != nullptr)
5110 outs() << format(" %.*s", left, name);
5111 outs() << "\n";
5112
5113 outs() << " baseMethods ";
5114 sym_name = get_symbol_64(offset + offsetof(struct class_ro64_t, baseMethods),
5115 S, info, n_value, cro.baseMethods);
5116 if (n_value != 0) {
5117 if (info->verbose && sym_name != nullptr)
5118 outs() << sym_name;
5119 else
5120 outs() << format("0x%" PRIx64, n_value);
5121 if (cro.baseMethods != 0)
5122 outs() << " + " << format("0x%" PRIx64, cro.baseMethods);
5123 } else
5124 outs() << format("0x%" PRIx64, cro.baseMethods);
5125 outs() << " (struct method_list_t *)\n";
5126 if (cro.baseMethods + n_value != 0)
5127 print_method_list64_t(cro.baseMethods + n_value, info, "");
5128
5129 outs() << " baseProtocols ";
5130 sym_name =
5131 get_symbol_64(offset + offsetof(struct class_ro64_t, baseProtocols), S,
5132 info, n_value, cro.baseProtocols);
5133 if (n_value != 0) {
5134 if (info->verbose && sym_name != nullptr)
5135 outs() << sym_name;
5136 else
5137 outs() << format("0x%" PRIx64, n_value);
5138 if (cro.baseProtocols != 0)
5139 outs() << " + " << format("0x%" PRIx64, cro.baseProtocols);
5140 } else
5141 outs() << format("0x%" PRIx64, cro.baseProtocols);
5142 outs() << "\n";
5143 if (cro.baseProtocols + n_value != 0)
5144 print_protocol_list64_t(cro.baseProtocols + n_value, info);
5145
5146 outs() << " ivars ";
5147 sym_name = get_symbol_64(offset + offsetof(struct class_ro64_t, ivars), S,
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005148 info, n_value, cro.ivars);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005149 if (n_value != 0) {
5150 if (info->verbose && sym_name != nullptr)
5151 outs() << sym_name;
5152 else
5153 outs() << format("0x%" PRIx64, n_value);
5154 if (cro.ivars != 0)
5155 outs() << " + " << format("0x%" PRIx64, cro.ivars);
5156 } else
5157 outs() << format("0x%" PRIx64, cro.ivars);
5158 outs() << "\n";
5159 if (cro.ivars + n_value != 0)
5160 print_ivar_list64_t(cro.ivars + n_value, info);
5161
5162 outs() << " weakIvarLayout ";
5163 sym_name =
5164 get_symbol_64(offset + offsetof(struct class_ro64_t, weakIvarLayout), S,
5165 info, n_value, cro.weakIvarLayout);
5166 if (n_value != 0) {
5167 if (info->verbose && sym_name != nullptr)
5168 outs() << sym_name;
5169 else
5170 outs() << format("0x%" PRIx64, n_value);
5171 if (cro.weakIvarLayout != 0)
5172 outs() << " + " << format("0x%" PRIx64, cro.weakIvarLayout);
5173 } else
5174 outs() << format("0x%" PRIx64, cro.weakIvarLayout);
5175 outs() << "\n";
5176 print_layout_map64(cro.weakIvarLayout + n_value, info);
5177
5178 outs() << " baseProperties ";
5179 sym_name =
5180 get_symbol_64(offset + offsetof(struct class_ro64_t, baseProperties), S,
5181 info, n_value, cro.baseProperties);
5182 if (n_value != 0) {
5183 if (info->verbose && sym_name != nullptr)
5184 outs() << sym_name;
5185 else
5186 outs() << format("0x%" PRIx64, n_value);
5187 if (cro.baseProperties != 0)
5188 outs() << " + " << format("0x%" PRIx64, cro.baseProperties);
5189 } else
5190 outs() << format("0x%" PRIx64, cro.baseProperties);
5191 outs() << "\n";
5192 if (cro.baseProperties + n_value != 0)
5193 print_objc_property_list64(cro.baseProperties + n_value, info);
5194
Rafael Espindolab9091322015-10-24 23:19:10 +00005195 is_meta_class = (cro.flags & RO_META) != 0;
Richard Smith81ff44d2015-10-09 22:09:56 +00005196 return true;
Kevin Enderby0fc11822015-04-01 20:57:01 +00005197}
5198
Richard Smith81ff44d2015-10-09 22:09:56 +00005199static bool print_class_ro32_t(uint32_t p, struct DisassembleInfo *info,
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005200 bool &is_meta_class) {
5201 struct class_ro32_t cro;
5202 const char *r;
5203 uint32_t offset, xoffset, left;
5204 SectionRef S, xS;
5205 const char *name;
5206
5207 r = get_pointer_32(p, offset, left, S, info);
5208 if (r == nullptr)
Richard Smith81ff44d2015-10-09 22:09:56 +00005209 return false;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005210 memset(&cro, '\0', sizeof(struct class_ro32_t));
5211 if (left < sizeof(struct class_ro32_t)) {
5212 memcpy(&cro, r, left);
5213 outs() << " (class_ro_t entends past the end of the section)\n";
5214 } else
5215 memcpy(&cro, r, sizeof(struct class_ro32_t));
5216 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5217 swapStruct(cro);
5218 outs() << " flags " << format("0x%" PRIx32, cro.flags);
5219 if (cro.flags & RO_META)
5220 outs() << " RO_META";
5221 if (cro.flags & RO_ROOT)
5222 outs() << " RO_ROOT";
5223 if (cro.flags & RO_HAS_CXX_STRUCTORS)
5224 outs() << " RO_HAS_CXX_STRUCTORS";
5225 outs() << "\n";
5226 outs() << " instanceStart " << cro.instanceStart << "\n";
5227 outs() << " instanceSize " << cro.instanceSize << "\n";
5228 outs() << " ivarLayout " << format("0x%" PRIx32, cro.ivarLayout)
5229 << "\n";
5230 print_layout_map32(cro.ivarLayout, info);
5231
5232 outs() << " name " << format("0x%" PRIx32, cro.name);
5233 name = get_pointer_32(cro.name, xoffset, left, xS, info);
5234 if (name != nullptr)
5235 outs() << format(" %.*s", left, name);
5236 outs() << "\n";
5237
5238 outs() << " baseMethods "
5239 << format("0x%" PRIx32, cro.baseMethods)
5240 << " (struct method_list_t *)\n";
5241 if (cro.baseMethods != 0)
5242 print_method_list32_t(cro.baseMethods, info, "");
5243
5244 outs() << " baseProtocols "
5245 << format("0x%" PRIx32, cro.baseProtocols) << "\n";
5246 if (cro.baseProtocols != 0)
5247 print_protocol_list32_t(cro.baseProtocols, info);
5248 outs() << " ivars " << format("0x%" PRIx32, cro.ivars)
5249 << "\n";
5250 if (cro.ivars != 0)
5251 print_ivar_list32_t(cro.ivars, info);
5252 outs() << " weakIvarLayout "
5253 << format("0x%" PRIx32, cro.weakIvarLayout) << "\n";
5254 print_layout_map32(cro.weakIvarLayout, info);
5255 outs() << " baseProperties "
5256 << format("0x%" PRIx32, cro.baseProperties) << "\n";
5257 if (cro.baseProperties != 0)
5258 print_objc_property_list32(cro.baseProperties, info);
Rafael Espindolab9091322015-10-24 23:19:10 +00005259 is_meta_class = (cro.flags & RO_META) != 0;
Richard Smith81ff44d2015-10-09 22:09:56 +00005260 return true;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005261}
5262
Kevin Enderby0fc11822015-04-01 20:57:01 +00005263static void print_class64_t(uint64_t p, struct DisassembleInfo *info) {
5264 struct class64_t c;
5265 const char *r;
5266 uint32_t offset, left;
5267 SectionRef S;
5268 const char *name;
5269 uint64_t isa_n_value, n_value;
5270
5271 r = get_pointer_64(p, offset, left, S, info);
5272 if (r == nullptr || left < sizeof(struct class64_t))
5273 return;
Chandler Carruth33e58902016-11-04 07:10:24 +00005274 memcpy(&c, r, sizeof(struct class64_t));
Kevin Enderby0fc11822015-04-01 20:57:01 +00005275 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5276 swapStruct(c);
5277
5278 outs() << " isa " << format("0x%" PRIx64, c.isa);
5279 name = get_symbol_64(offset + offsetof(struct class64_t, isa), S, info,
5280 isa_n_value, c.isa);
5281 if (name != nullptr)
5282 outs() << " " << name;
5283 outs() << "\n";
5284
5285 outs() << " superclass " << format("0x%" PRIx64, c.superclass);
5286 name = get_symbol_64(offset + offsetof(struct class64_t, superclass), S, info,
5287 n_value, c.superclass);
5288 if (name != nullptr)
5289 outs() << " " << name;
Kevin Enderby1ce38582017-06-20 22:55:11 +00005290 else {
5291 name = get_dyld_bind_info_symbolname(S.getAddress() +
5292 offset + offsetof(struct class64_t, superclass), info);
5293 if (name != nullptr)
5294 outs() << " " << name;
5295 }
Kevin Enderby0fc11822015-04-01 20:57:01 +00005296 outs() << "\n";
5297
5298 outs() << " cache " << format("0x%" PRIx64, c.cache);
5299 name = get_symbol_64(offset + offsetof(struct class64_t, cache), S, info,
5300 n_value, c.cache);
5301 if (name != nullptr)
5302 outs() << " " << name;
5303 outs() << "\n";
5304
5305 outs() << " vtable " << format("0x%" PRIx64, c.vtable);
5306 name = get_symbol_64(offset + offsetof(struct class64_t, vtable), S, info,
5307 n_value, c.vtable);
5308 if (name != nullptr)
5309 outs() << " " << name;
5310 outs() << "\n";
5311
5312 name = get_symbol_64(offset + offsetof(struct class64_t, data), S, info,
5313 n_value, c.data);
5314 outs() << " data ";
5315 if (n_value != 0) {
5316 if (info->verbose && name != nullptr)
5317 outs() << name;
5318 else
5319 outs() << format("0x%" PRIx64, n_value);
5320 if (c.data != 0)
5321 outs() << " + " << format("0x%" PRIx64, c.data);
5322 } else
5323 outs() << format("0x%" PRIx64, c.data);
5324 outs() << " (struct class_ro_t *)";
5325
5326 // This is a Swift class if some of the low bits of the pointer are set.
5327 if ((c.data + n_value) & 0x7)
5328 outs() << " Swift class";
5329 outs() << "\n";
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005330 bool is_meta_class;
Richard Smith81ff44d2015-10-09 22:09:56 +00005331 if (!print_class_ro64_t((c.data + n_value) & ~0x7, info, is_meta_class))
5332 return;
Kevin Enderby0fc11822015-04-01 20:57:01 +00005333
Kevin Enderbyaac75382015-10-08 16:56:35 +00005334 if (!is_meta_class &&
5335 c.isa + isa_n_value != p &&
5336 c.isa + isa_n_value != 0 &&
5337 info->depth < 100) {
5338 info->depth++;
5339 outs() << "Meta Class\n";
5340 print_class64_t(c.isa + isa_n_value, info);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005341 }
5342}
5343
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005344static void print_class32_t(uint32_t p, struct DisassembleInfo *info) {
5345 struct class32_t c;
5346 const char *r;
5347 uint32_t offset, left;
5348 SectionRef S;
5349 const char *name;
5350
5351 r = get_pointer_32(p, offset, left, S, info);
5352 if (r == nullptr)
5353 return;
5354 memset(&c, '\0', sizeof(struct class32_t));
5355 if (left < sizeof(struct class32_t)) {
5356 memcpy(&c, r, left);
5357 outs() << " (class_t entends past the end of the section)\n";
5358 } else
5359 memcpy(&c, r, sizeof(struct class32_t));
5360 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5361 swapStruct(c);
5362
5363 outs() << " isa " << format("0x%" PRIx32, c.isa);
5364 name =
5365 get_symbol_32(offset + offsetof(struct class32_t, isa), S, info, c.isa);
5366 if (name != nullptr)
5367 outs() << " " << name;
5368 outs() << "\n";
5369
5370 outs() << " superclass " << format("0x%" PRIx32, c.superclass);
5371 name = get_symbol_32(offset + offsetof(struct class32_t, superclass), S, info,
5372 c.superclass);
5373 if (name != nullptr)
5374 outs() << " " << name;
5375 outs() << "\n";
5376
5377 outs() << " cache " << format("0x%" PRIx32, c.cache);
5378 name = get_symbol_32(offset + offsetof(struct class32_t, cache), S, info,
5379 c.cache);
5380 if (name != nullptr)
5381 outs() << " " << name;
5382 outs() << "\n";
5383
5384 outs() << " vtable " << format("0x%" PRIx32, c.vtable);
5385 name = get_symbol_32(offset + offsetof(struct class32_t, vtable), S, info,
5386 c.vtable);
5387 if (name != nullptr)
5388 outs() << " " << name;
5389 outs() << "\n";
5390
5391 name =
5392 get_symbol_32(offset + offsetof(struct class32_t, data), S, info, c.data);
5393 outs() << " data " << format("0x%" PRIx32, c.data)
5394 << " (struct class_ro_t *)";
5395
5396 // This is a Swift class if some of the low bits of the pointer are set.
5397 if (c.data & 0x3)
5398 outs() << " Swift class";
5399 outs() << "\n";
5400 bool is_meta_class;
Richard Smith81ff44d2015-10-09 22:09:56 +00005401 if (!print_class_ro32_t(c.data & ~0x3, info, is_meta_class))
5402 return;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005403
Hans Wennborgcc9deb42015-09-29 18:02:48 +00005404 if (!is_meta_class) {
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005405 outs() << "Meta Class\n";
5406 print_class32_t(c.isa, info);
5407 }
5408}
5409
Kevin Enderby846c0002015-04-16 17:19:59 +00005410static void print_objc_class_t(struct objc_class_t *objc_class,
5411 struct DisassembleInfo *info) {
5412 uint32_t offset, left, xleft;
5413 const char *name, *p, *ivar_list;
5414 SectionRef S;
5415 int32_t i;
5416 struct objc_ivar_list_t objc_ivar_list;
5417 struct objc_ivar_t ivar;
5418
5419 outs() << "\t\t isa " << format("0x%08" PRIx32, objc_class->isa);
5420 if (info->verbose && CLS_GETINFO(objc_class, CLS_META)) {
5421 name = get_pointer_32(objc_class->isa, offset, left, S, info, true);
5422 if (name != nullptr)
5423 outs() << format(" %.*s", left, name);
5424 else
5425 outs() << " (not in an __OBJC section)";
5426 }
5427 outs() << "\n";
5428
5429 outs() << "\t super_class "
5430 << format("0x%08" PRIx32, objc_class->super_class);
5431 if (info->verbose) {
5432 name = get_pointer_32(objc_class->super_class, offset, left, S, info, true);
5433 if (name != nullptr)
5434 outs() << format(" %.*s", left, name);
5435 else
5436 outs() << " (not in an __OBJC section)";
5437 }
5438 outs() << "\n";
5439
5440 outs() << "\t\t name " << format("0x%08" PRIx32, objc_class->name);
5441 if (info->verbose) {
5442 name = get_pointer_32(objc_class->name, offset, left, S, info, true);
5443 if (name != nullptr)
5444 outs() << format(" %.*s", left, name);
5445 else
5446 outs() << " (not in an __OBJC section)";
5447 }
5448 outs() << "\n";
5449
5450 outs() << "\t\t version " << format("0x%08" PRIx32, objc_class->version)
5451 << "\n";
5452
5453 outs() << "\t\t info " << format("0x%08" PRIx32, objc_class->info);
5454 if (info->verbose) {
5455 if (CLS_GETINFO(objc_class, CLS_CLASS))
5456 outs() << " CLS_CLASS";
5457 else if (CLS_GETINFO(objc_class, CLS_META))
5458 outs() << " CLS_META";
5459 }
5460 outs() << "\n";
5461
5462 outs() << "\t instance_size "
5463 << format("0x%08" PRIx32, objc_class->instance_size) << "\n";
5464
5465 p = get_pointer_32(objc_class->ivars, offset, left, S, info, true);
5466 outs() << "\t\t ivars " << format("0x%08" PRIx32, objc_class->ivars);
5467 if (p != nullptr) {
5468 if (left > sizeof(struct objc_ivar_list_t)) {
5469 outs() << "\n";
5470 memcpy(&objc_ivar_list, p, sizeof(struct objc_ivar_list_t));
5471 } else {
5472 outs() << " (entends past the end of the section)\n";
5473 memset(&objc_ivar_list, '\0', sizeof(struct objc_ivar_list_t));
5474 memcpy(&objc_ivar_list, p, left);
5475 }
5476 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5477 swapStruct(objc_ivar_list);
5478 outs() << "\t\t ivar_count " << objc_ivar_list.ivar_count << "\n";
5479 ivar_list = p + sizeof(struct objc_ivar_list_t);
5480 for (i = 0; i < objc_ivar_list.ivar_count; i++) {
5481 if ((i + 1) * sizeof(struct objc_ivar_t) > left) {
5482 outs() << "\t\t remaining ivar's extend past the of the section\n";
5483 break;
5484 }
5485 memcpy(&ivar, ivar_list + i * sizeof(struct objc_ivar_t),
5486 sizeof(struct objc_ivar_t));
5487 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5488 swapStruct(ivar);
5489
5490 outs() << "\t\t\tivar_name " << format("0x%08" PRIx32, ivar.ivar_name);
5491 if (info->verbose) {
5492 name = get_pointer_32(ivar.ivar_name, offset, xleft, S, info, true);
5493 if (name != nullptr)
5494 outs() << format(" %.*s", xleft, name);
5495 else
5496 outs() << " (not in an __OBJC section)";
5497 }
5498 outs() << "\n";
5499
5500 outs() << "\t\t\tivar_type " << format("0x%08" PRIx32, ivar.ivar_type);
5501 if (info->verbose) {
5502 name = get_pointer_32(ivar.ivar_type, offset, xleft, S, info, true);
5503 if (name != nullptr)
5504 outs() << format(" %.*s", xleft, name);
5505 else
5506 outs() << " (not in an __OBJC section)";
5507 }
5508 outs() << "\n";
5509
5510 outs() << "\t\t ivar_offset "
5511 << format("0x%08" PRIx32, ivar.ivar_offset) << "\n";
5512 }
5513 } else {
5514 outs() << " (not in an __OBJC section)\n";
5515 }
5516
5517 outs() << "\t\t methods " << format("0x%08" PRIx32, objc_class->methodLists);
5518 if (print_method_list(objc_class->methodLists, info))
5519 outs() << " (not in an __OBJC section)\n";
5520
5521 outs() << "\t\t cache " << format("0x%08" PRIx32, objc_class->cache)
5522 << "\n";
5523
5524 outs() << "\t\tprotocols " << format("0x%08" PRIx32, objc_class->protocols);
5525 if (print_protocol_list(objc_class->protocols, 16, info))
5526 outs() << " (not in an __OBJC section)\n";
5527}
5528
5529static void print_objc_objc_category_t(struct objc_category_t *objc_category,
5530 struct DisassembleInfo *info) {
5531 uint32_t offset, left;
5532 const char *name;
5533 SectionRef S;
5534
5535 outs() << "\t category name "
5536 << format("0x%08" PRIx32, objc_category->category_name);
5537 if (info->verbose) {
5538 name = get_pointer_32(objc_category->category_name, offset, left, S, info,
5539 true);
5540 if (name != nullptr)
5541 outs() << format(" %.*s", left, name);
5542 else
5543 outs() << " (not in an __OBJC section)";
5544 }
5545 outs() << "\n";
5546
5547 outs() << "\t\t class name "
5548 << format("0x%08" PRIx32, objc_category->class_name);
5549 if (info->verbose) {
5550 name =
5551 get_pointer_32(objc_category->class_name, offset, left, S, info, true);
5552 if (name != nullptr)
5553 outs() << format(" %.*s", left, name);
5554 else
5555 outs() << " (not in an __OBJC section)";
5556 }
5557 outs() << "\n";
5558
5559 outs() << "\t instance methods "
5560 << format("0x%08" PRIx32, objc_category->instance_methods);
5561 if (print_method_list(objc_category->instance_methods, info))
5562 outs() << " (not in an __OBJC section)\n";
5563
5564 outs() << "\t class methods "
5565 << format("0x%08" PRIx32, objc_category->class_methods);
5566 if (print_method_list(objc_category->class_methods, info))
5567 outs() << " (not in an __OBJC section)\n";
5568}
5569
Kevin Enderby0fc11822015-04-01 20:57:01 +00005570static void print_category64_t(uint64_t p, struct DisassembleInfo *info) {
5571 struct category64_t c;
5572 const char *r;
5573 uint32_t offset, xoffset, left;
5574 SectionRef S, xS;
5575 const char *name, *sym_name;
5576 uint64_t n_value;
5577
5578 r = get_pointer_64(p, offset, left, S, info);
5579 if (r == nullptr)
5580 return;
5581 memset(&c, '\0', sizeof(struct category64_t));
5582 if (left < sizeof(struct category64_t)) {
5583 memcpy(&c, r, left);
5584 outs() << " (category_t entends past the end of the section)\n";
5585 } else
5586 memcpy(&c, r, sizeof(struct category64_t));
5587 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5588 swapStruct(c);
5589
5590 outs() << " name ";
5591 sym_name = get_symbol_64(offset + offsetof(struct category64_t, name), S,
5592 info, n_value, c.name);
5593 if (n_value != 0) {
5594 if (info->verbose && sym_name != nullptr)
5595 outs() << sym_name;
5596 else
5597 outs() << format("0x%" PRIx64, n_value);
5598 if (c.name != 0)
5599 outs() << " + " << format("0x%" PRIx64, c.name);
5600 } else
5601 outs() << format("0x%" PRIx64, c.name);
5602 name = get_pointer_64(c.name + n_value, xoffset, left, xS, info);
5603 if (name != nullptr)
5604 outs() << format(" %.*s", left, name);
5605 outs() << "\n";
5606
5607 outs() << " cls ";
5608 sym_name = get_symbol_64(offset + offsetof(struct category64_t, cls), S, info,
5609 n_value, c.cls);
5610 if (n_value != 0) {
5611 if (info->verbose && sym_name != nullptr)
5612 outs() << sym_name;
5613 else
5614 outs() << format("0x%" PRIx64, n_value);
5615 if (c.cls != 0)
5616 outs() << " + " << format("0x%" PRIx64, c.cls);
5617 } else
5618 outs() << format("0x%" PRIx64, c.cls);
5619 outs() << "\n";
5620 if (c.cls + n_value != 0)
5621 print_class64_t(c.cls + n_value, info);
5622
5623 outs() << " instanceMethods ";
5624 sym_name =
5625 get_symbol_64(offset + offsetof(struct category64_t, instanceMethods), S,
5626 info, n_value, c.instanceMethods);
5627 if (n_value != 0) {
5628 if (info->verbose && sym_name != nullptr)
5629 outs() << sym_name;
5630 else
5631 outs() << format("0x%" PRIx64, n_value);
5632 if (c.instanceMethods != 0)
5633 outs() << " + " << format("0x%" PRIx64, c.instanceMethods);
5634 } else
5635 outs() << format("0x%" PRIx64, c.instanceMethods);
5636 outs() << "\n";
5637 if (c.instanceMethods + n_value != 0)
5638 print_method_list64_t(c.instanceMethods + n_value, info, "");
5639
5640 outs() << " classMethods ";
5641 sym_name = get_symbol_64(offset + offsetof(struct category64_t, classMethods),
5642 S, info, n_value, c.classMethods);
5643 if (n_value != 0) {
5644 if (info->verbose && sym_name != nullptr)
5645 outs() << sym_name;
5646 else
5647 outs() << format("0x%" PRIx64, n_value);
5648 if (c.classMethods != 0)
5649 outs() << " + " << format("0x%" PRIx64, c.classMethods);
5650 } else
5651 outs() << format("0x%" PRIx64, c.classMethods);
5652 outs() << "\n";
5653 if (c.classMethods + n_value != 0)
5654 print_method_list64_t(c.classMethods + n_value, info, "");
5655
5656 outs() << " protocols ";
5657 sym_name = get_symbol_64(offset + offsetof(struct category64_t, protocols), S,
5658 info, n_value, c.protocols);
5659 if (n_value != 0) {
5660 if (info->verbose && sym_name != nullptr)
5661 outs() << sym_name;
5662 else
5663 outs() << format("0x%" PRIx64, n_value);
5664 if (c.protocols != 0)
5665 outs() << " + " << format("0x%" PRIx64, c.protocols);
5666 } else
5667 outs() << format("0x%" PRIx64, c.protocols);
5668 outs() << "\n";
5669 if (c.protocols + n_value != 0)
5670 print_protocol_list64_t(c.protocols + n_value, info);
5671
5672 outs() << "instanceProperties ";
5673 sym_name =
5674 get_symbol_64(offset + offsetof(struct category64_t, instanceProperties),
5675 S, info, n_value, c.instanceProperties);
5676 if (n_value != 0) {
5677 if (info->verbose && sym_name != nullptr)
5678 outs() << sym_name;
5679 else
5680 outs() << format("0x%" PRIx64, n_value);
5681 if (c.instanceProperties != 0)
5682 outs() << " + " << format("0x%" PRIx64, c.instanceProperties);
5683 } else
5684 outs() << format("0x%" PRIx64, c.instanceProperties);
5685 outs() << "\n";
5686 if (c.instanceProperties + n_value != 0)
5687 print_objc_property_list64(c.instanceProperties + n_value, info);
5688}
5689
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005690static void print_category32_t(uint32_t p, struct DisassembleInfo *info) {
5691 struct category32_t c;
5692 const char *r;
5693 uint32_t offset, left;
5694 SectionRef S, xS;
5695 const char *name;
5696
5697 r = get_pointer_32(p, offset, left, S, info);
5698 if (r == nullptr)
5699 return;
5700 memset(&c, '\0', sizeof(struct category32_t));
5701 if (left < sizeof(struct category32_t)) {
5702 memcpy(&c, r, left);
5703 outs() << " (category_t entends past the end of the section)\n";
5704 } else
5705 memcpy(&c, r, sizeof(struct category32_t));
5706 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5707 swapStruct(c);
5708
5709 outs() << " name " << format("0x%" PRIx32, c.name);
5710 name = get_symbol_32(offset + offsetof(struct category32_t, name), S, info,
5711 c.name);
Hans Wennborgcc9deb42015-09-29 18:02:48 +00005712 if (name)
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005713 outs() << " " << name;
5714 outs() << "\n";
5715
5716 outs() << " cls " << format("0x%" PRIx32, c.cls) << "\n";
5717 if (c.cls != 0)
5718 print_class32_t(c.cls, info);
5719 outs() << " instanceMethods " << format("0x%" PRIx32, c.instanceMethods)
5720 << "\n";
5721 if (c.instanceMethods != 0)
5722 print_method_list32_t(c.instanceMethods, info, "");
5723 outs() << " classMethods " << format("0x%" PRIx32, c.classMethods)
5724 << "\n";
5725 if (c.classMethods != 0)
5726 print_method_list32_t(c.classMethods, info, "");
5727 outs() << " protocols " << format("0x%" PRIx32, c.protocols) << "\n";
5728 if (c.protocols != 0)
5729 print_protocol_list32_t(c.protocols, info);
5730 outs() << "instanceProperties " << format("0x%" PRIx32, c.instanceProperties)
5731 << "\n";
5732 if (c.instanceProperties != 0)
5733 print_objc_property_list32(c.instanceProperties, info);
5734}
5735
Kevin Enderby0fc11822015-04-01 20:57:01 +00005736static void print_message_refs64(SectionRef S, struct DisassembleInfo *info) {
5737 uint32_t i, left, offset, xoffset;
5738 uint64_t p, n_value;
5739 struct message_ref64 mr;
5740 const char *name, *sym_name;
5741 const char *r;
5742 SectionRef xS;
5743
5744 if (S == SectionRef())
5745 return;
5746
5747 StringRef SectName;
5748 S.getName(SectName);
5749 DataRefImpl Ref = S.getRawDataRefImpl();
5750 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5751 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5752 offset = 0;
5753 for (i = 0; i < S.getSize(); i += sizeof(struct message_ref64)) {
5754 p = S.getAddress() + i;
5755 r = get_pointer_64(p, offset, left, S, info);
5756 if (r == nullptr)
5757 return;
5758 memset(&mr, '\0', sizeof(struct message_ref64));
5759 if (left < sizeof(struct message_ref64)) {
5760 memcpy(&mr, r, left);
5761 outs() << " (message_ref entends past the end of the section)\n";
5762 } else
5763 memcpy(&mr, r, sizeof(struct message_ref64));
5764 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5765 swapStruct(mr);
5766
5767 outs() << " imp ";
5768 name = get_symbol_64(offset + offsetof(struct message_ref64, imp), S, info,
5769 n_value, mr.imp);
5770 if (n_value != 0) {
5771 outs() << format("0x%" PRIx64, n_value) << " ";
5772 if (mr.imp != 0)
5773 outs() << "+ " << format("0x%" PRIx64, mr.imp) << " ";
5774 } else
5775 outs() << format("0x%" PRIx64, mr.imp) << " ";
5776 if (name != nullptr)
5777 outs() << " " << name;
5778 outs() << "\n";
5779
5780 outs() << " sel ";
5781 sym_name = get_symbol_64(offset + offsetof(struct message_ref64, sel), S,
5782 info, n_value, mr.sel);
5783 if (n_value != 0) {
5784 if (info->verbose && sym_name != nullptr)
5785 outs() << sym_name;
5786 else
5787 outs() << format("0x%" PRIx64, n_value);
5788 if (mr.sel != 0)
5789 outs() << " + " << format("0x%" PRIx64, mr.sel);
5790 } else
5791 outs() << format("0x%" PRIx64, mr.sel);
5792 name = get_pointer_64(mr.sel + n_value, xoffset, left, xS, info);
5793 if (name != nullptr)
5794 outs() << format(" %.*s", left, name);
5795 outs() << "\n";
5796
5797 offset += sizeof(struct message_ref64);
5798 }
5799}
5800
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005801static void print_message_refs32(SectionRef S, struct DisassembleInfo *info) {
5802 uint32_t i, left, offset, xoffset, p;
5803 struct message_ref32 mr;
5804 const char *name, *r;
5805 SectionRef xS;
5806
5807 if (S == SectionRef())
5808 return;
5809
5810 StringRef SectName;
5811 S.getName(SectName);
5812 DataRefImpl Ref = S.getRawDataRefImpl();
5813 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5814 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5815 offset = 0;
5816 for (i = 0; i < S.getSize(); i += sizeof(struct message_ref64)) {
5817 p = S.getAddress() + i;
5818 r = get_pointer_32(p, offset, left, S, info);
5819 if (r == nullptr)
5820 return;
5821 memset(&mr, '\0', sizeof(struct message_ref32));
5822 if (left < sizeof(struct message_ref32)) {
5823 memcpy(&mr, r, left);
5824 outs() << " (message_ref entends past the end of the section)\n";
5825 } else
5826 memcpy(&mr, r, sizeof(struct message_ref32));
5827 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5828 swapStruct(mr);
5829
5830 outs() << " imp " << format("0x%" PRIx32, mr.imp);
5831 name = get_symbol_32(offset + offsetof(struct message_ref32, imp), S, info,
5832 mr.imp);
5833 if (name != nullptr)
5834 outs() << " " << name;
5835 outs() << "\n";
5836
5837 outs() << " sel " << format("0x%" PRIx32, mr.sel);
5838 name = get_pointer_32(mr.sel, xoffset, left, xS, info);
5839 if (name != nullptr)
5840 outs() << " " << name;
5841 outs() << "\n";
5842
5843 offset += sizeof(struct message_ref32);
5844 }
5845}
5846
Kevin Enderby0fc11822015-04-01 20:57:01 +00005847static void print_image_info64(SectionRef S, struct DisassembleInfo *info) {
5848 uint32_t left, offset, swift_version;
5849 uint64_t p;
5850 struct objc_image_info64 o;
5851 const char *r;
5852
Kevin Enderbyaf7c9d02015-10-09 16:48:44 +00005853 if (S == SectionRef())
5854 return;
5855
Kevin Enderby0fc11822015-04-01 20:57:01 +00005856 StringRef SectName;
5857 S.getName(SectName);
5858 DataRefImpl Ref = S.getRawDataRefImpl();
5859 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5860 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5861 p = S.getAddress();
5862 r = get_pointer_64(p, offset, left, S, info);
5863 if (r == nullptr)
5864 return;
5865 memset(&o, '\0', sizeof(struct objc_image_info64));
5866 if (left < sizeof(struct objc_image_info64)) {
5867 memcpy(&o, r, left);
5868 outs() << " (objc_image_info entends past the end of the section)\n";
5869 } else
5870 memcpy(&o, r, sizeof(struct objc_image_info64));
5871 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5872 swapStruct(o);
5873 outs() << " version " << o.version << "\n";
5874 outs() << " flags " << format("0x%" PRIx32, o.flags);
5875 if (o.flags & OBJC_IMAGE_IS_REPLACEMENT)
5876 outs() << " OBJC_IMAGE_IS_REPLACEMENT";
5877 if (o.flags & OBJC_IMAGE_SUPPORTS_GC)
5878 outs() << " OBJC_IMAGE_SUPPORTS_GC";
Dave Lee390abe42018-07-06 05:11:35 +00005879 if (o.flags & OBJC_IMAGE_IS_SIMULATED)
5880 outs() << " OBJC_IMAGE_IS_SIMULATED";
5881 if (o.flags & OBJC_IMAGE_HAS_CATEGORY_CLASS_PROPERTIES)
5882 outs() << " OBJC_IMAGE_HAS_CATEGORY_CLASS_PROPERTIES";
Kevin Enderby0fc11822015-04-01 20:57:01 +00005883 swift_version = (o.flags >> 8) & 0xff;
5884 if (swift_version != 0) {
5885 if (swift_version == 1)
5886 outs() << " Swift 1.0";
5887 else if (swift_version == 2)
5888 outs() << " Swift 1.1";
Kevin Enderbycda2ced2018-02-09 19:31:27 +00005889 else if(swift_version == 3)
5890 outs() << " Swift 2.0";
5891 else if(swift_version == 4)
5892 outs() << " Swift 3.0";
5893 else if(swift_version == 5)
5894 outs() << " Swift 4.0";
5895 else if(swift_version == 6)
Michael Trentf7254a62018-12-07 19:55:03 +00005896 outs() << " Swift 4.1/Swift 4.2";
5897 else if(swift_version == 7)
5898 outs() << " Swift 5 or later";
Kevin Enderby0fc11822015-04-01 20:57:01 +00005899 else
5900 outs() << " unknown future Swift version (" << swift_version << ")";
5901 }
5902 outs() << "\n";
5903}
5904
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005905static void print_image_info32(SectionRef S, struct DisassembleInfo *info) {
5906 uint32_t left, offset, swift_version, p;
5907 struct objc_image_info32 o;
5908 const char *r;
5909
Kevin Enderby19be2512016-04-21 19:49:29 +00005910 if (S == SectionRef())
5911 return;
5912
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005913 StringRef SectName;
5914 S.getName(SectName);
5915 DataRefImpl Ref = S.getRawDataRefImpl();
5916 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5917 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5918 p = S.getAddress();
5919 r = get_pointer_32(p, offset, left, S, info);
5920 if (r == nullptr)
5921 return;
5922 memset(&o, '\0', sizeof(struct objc_image_info32));
5923 if (left < sizeof(struct objc_image_info32)) {
5924 memcpy(&o, r, left);
5925 outs() << " (objc_image_info entends past the end of the section)\n";
5926 } else
5927 memcpy(&o, r, sizeof(struct objc_image_info32));
5928 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5929 swapStruct(o);
5930 outs() << " version " << o.version << "\n";
5931 outs() << " flags " << format("0x%" PRIx32, o.flags);
5932 if (o.flags & OBJC_IMAGE_IS_REPLACEMENT)
5933 outs() << " OBJC_IMAGE_IS_REPLACEMENT";
5934 if (o.flags & OBJC_IMAGE_SUPPORTS_GC)
5935 outs() << " OBJC_IMAGE_SUPPORTS_GC";
5936 swift_version = (o.flags >> 8) & 0xff;
5937 if (swift_version != 0) {
5938 if (swift_version == 1)
5939 outs() << " Swift 1.0";
5940 else if (swift_version == 2)
5941 outs() << " Swift 1.1";
Kevin Enderbycda2ced2018-02-09 19:31:27 +00005942 else if(swift_version == 3)
5943 outs() << " Swift 2.0";
5944 else if(swift_version == 4)
5945 outs() << " Swift 3.0";
5946 else if(swift_version == 5)
5947 outs() << " Swift 4.0";
5948 else if(swift_version == 6)
Michael Trentf7254a62018-12-07 19:55:03 +00005949 outs() << " Swift 4.1/Swift 4.2";
5950 else if(swift_version == 7)
5951 outs() << " Swift 5 or later";
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005952 else
5953 outs() << " unknown future Swift version (" << swift_version << ")";
5954 }
5955 outs() << "\n";
5956}
5957
Kevin Enderby846c0002015-04-16 17:19:59 +00005958static void print_image_info(SectionRef S, struct DisassembleInfo *info) {
5959 uint32_t left, offset, p;
5960 struct imageInfo_t o;
5961 const char *r;
5962
5963 StringRef SectName;
5964 S.getName(SectName);
5965 DataRefImpl Ref = S.getRawDataRefImpl();
5966 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5967 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5968 p = S.getAddress();
5969 r = get_pointer_32(p, offset, left, S, info);
5970 if (r == nullptr)
5971 return;
5972 memset(&o, '\0', sizeof(struct imageInfo_t));
5973 if (left < sizeof(struct imageInfo_t)) {
5974 memcpy(&o, r, left);
5975 outs() << " (imageInfo entends past the end of the section)\n";
5976 } else
5977 memcpy(&o, r, sizeof(struct imageInfo_t));
5978 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5979 swapStruct(o);
5980 outs() << " version " << o.version << "\n";
5981 outs() << " flags " << format("0x%" PRIx32, o.flags);
5982 if (o.flags & 0x1)
5983 outs() << " F&C";
5984 if (o.flags & 0x2)
5985 outs() << " GC";
5986 if (o.flags & 0x4)
5987 outs() << " GC-only";
5988 else
5989 outs() << " RR";
5990 outs() << "\n";
5991}
5992
Kevin Enderby0fc11822015-04-01 20:57:01 +00005993static void printObjc2_64bit_MetaData(MachOObjectFile *O, bool verbose) {
5994 SymbolAddressMap AddrMap;
5995 if (verbose)
5996 CreateSymbolAddressMap(O, &AddrMap);
5997
5998 std::vector<SectionRef> Sections;
5999 for (const SectionRef &Section : O->sections()) {
6000 StringRef SectName;
6001 Section.getName(SectName);
6002 Sections.push_back(Section);
6003 }
6004
Serge Pavlove4e9a1f2018-02-14 03:26:27 +00006005 struct DisassembleInfo info(O, &AddrMap, &Sections, verbose);
Kevin Enderby0fc11822015-04-01 20:57:01 +00006006
Davide Italiano62507042015-12-11 22:27:59 +00006007 SectionRef CL = get_section(O, "__OBJC2", "__class_list");
6008 if (CL == SectionRef())
6009 CL = get_section(O, "__DATA", "__objc_classlist");
Kevin Enderby5879a482017-02-09 17:56:26 +00006010 if (CL == SectionRef())
6011 CL = get_section(O, "__DATA_CONST", "__objc_classlist");
6012 if (CL == SectionRef())
6013 CL = get_section(O, "__DATA_DIRTY", "__objc_classlist");
Davide Italiano62507042015-12-11 22:27:59 +00006014 info.S = CL;
6015 walk_pointer_list_64("class", CL, O, &info, print_class64_t);
Kevin Enderby0fc11822015-04-01 20:57:01 +00006016
Davide Italiano62507042015-12-11 22:27:59 +00006017 SectionRef CR = get_section(O, "__OBJC2", "__class_refs");
6018 if (CR == SectionRef())
6019 CR = get_section(O, "__DATA", "__objc_classrefs");
Kevin Enderby5879a482017-02-09 17:56:26 +00006020 if (CR == SectionRef())
6021 CR = get_section(O, "__DATA_CONST", "__objc_classrefs");
6022 if (CR == SectionRef())
6023 CR = get_section(O, "__DATA_DIRTY", "__objc_classrefs");
Davide Italiano62507042015-12-11 22:27:59 +00006024 info.S = CR;
6025 walk_pointer_list_64("class refs", CR, O, &info, nullptr);
Kevin Enderby0fc11822015-04-01 20:57:01 +00006026
Davide Italiano62507042015-12-11 22:27:59 +00006027 SectionRef SR = get_section(O, "__OBJC2", "__super_refs");
6028 if (SR == SectionRef())
6029 SR = get_section(O, "__DATA", "__objc_superrefs");
Kevin Enderby5879a482017-02-09 17:56:26 +00006030 if (SR == SectionRef())
6031 SR = get_section(O, "__DATA_CONST", "__objc_superrefs");
6032 if (SR == SectionRef())
6033 SR = get_section(O, "__DATA_DIRTY", "__objc_superrefs");
Davide Italiano62507042015-12-11 22:27:59 +00006034 info.S = SR;
6035 walk_pointer_list_64("super refs", SR, O, &info, nullptr);
Kevin Enderby0fc11822015-04-01 20:57:01 +00006036
Davide Italiano62507042015-12-11 22:27:59 +00006037 SectionRef CA = get_section(O, "__OBJC2", "__category_list");
6038 if (CA == SectionRef())
6039 CA = get_section(O, "__DATA", "__objc_catlist");
Kevin Enderby5879a482017-02-09 17:56:26 +00006040 if (CA == SectionRef())
6041 CA = get_section(O, "__DATA_CONST", "__objc_catlist");
6042 if (CA == SectionRef())
6043 CA = get_section(O, "__DATA_DIRTY", "__objc_catlist");
Davide Italiano62507042015-12-11 22:27:59 +00006044 info.S = CA;
6045 walk_pointer_list_64("category", CA, O, &info, print_category64_t);
Kevin Enderby0fc11822015-04-01 20:57:01 +00006046
Davide Italiano62507042015-12-11 22:27:59 +00006047 SectionRef PL = get_section(O, "__OBJC2", "__protocol_list");
6048 if (PL == SectionRef())
6049 PL = get_section(O, "__DATA", "__objc_protolist");
Kevin Enderby5879a482017-02-09 17:56:26 +00006050 if (PL == SectionRef())
6051 PL = get_section(O, "__DATA_CONST", "__objc_protolist");
6052 if (PL == SectionRef())
6053 PL = get_section(O, "__DATA_DIRTY", "__objc_protolist");
Davide Italiano62507042015-12-11 22:27:59 +00006054 info.S = PL;
6055 walk_pointer_list_64("protocol", PL, O, &info, nullptr);
Kevin Enderby0fc11822015-04-01 20:57:01 +00006056
Davide Italiano62507042015-12-11 22:27:59 +00006057 SectionRef MR = get_section(O, "__OBJC2", "__message_refs");
6058 if (MR == SectionRef())
6059 MR = get_section(O, "__DATA", "__objc_msgrefs");
Kevin Enderby5879a482017-02-09 17:56:26 +00006060 if (MR == SectionRef())
6061 MR = get_section(O, "__DATA_CONST", "__objc_msgrefs");
6062 if (MR == SectionRef())
6063 MR = get_section(O, "__DATA_DIRTY", "__objc_msgrefs");
Davide Italiano62507042015-12-11 22:27:59 +00006064 info.S = MR;
6065 print_message_refs64(MR, &info);
Kevin Enderby0fc11822015-04-01 20:57:01 +00006066
Davide Italiano62507042015-12-11 22:27:59 +00006067 SectionRef II = get_section(O, "__OBJC2", "__image_info");
6068 if (II == SectionRef())
6069 II = get_section(O, "__DATA", "__objc_imageinfo");
Kevin Enderby5879a482017-02-09 17:56:26 +00006070 if (II == SectionRef())
6071 II = get_section(O, "__DATA_CONST", "__objc_imageinfo");
6072 if (II == SectionRef())
6073 II = get_section(O, "__DATA_DIRTY", "__objc_imageinfo");
Davide Italiano62507042015-12-11 22:27:59 +00006074 info.S = II;
6075 print_image_info64(II, &info);
Kevin Enderby0fc11822015-04-01 20:57:01 +00006076}
6077
6078static void printObjc2_32bit_MetaData(MachOObjectFile *O, bool verbose) {
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00006079 SymbolAddressMap AddrMap;
6080 if (verbose)
6081 CreateSymbolAddressMap(O, &AddrMap);
6082
6083 std::vector<SectionRef> Sections;
6084 for (const SectionRef &Section : O->sections()) {
6085 StringRef SectName;
6086 Section.getName(SectName);
6087 Sections.push_back(Section);
6088 }
6089
Serge Pavlove4e9a1f2018-02-14 03:26:27 +00006090 struct DisassembleInfo info(O, &AddrMap, &Sections, verbose);
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00006091
Kevin Enderby5879a482017-02-09 17:56:26 +00006092 SectionRef CL = get_section(O, "__OBJC2", "__class_list");
6093 if (CL == SectionRef())
6094 CL = get_section(O, "__DATA", "__objc_classlist");
6095 if (CL == SectionRef())
6096 CL = get_section(O, "__DATA_CONST", "__objc_classlist");
6097 if (CL == SectionRef())
6098 CL = get_section(O, "__DATA_DIRTY", "__objc_classlist");
6099 info.S = CL;
6100 walk_pointer_list_32("class", CL, O, &info, print_class32_t);
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00006101
Kevin Enderby5879a482017-02-09 17:56:26 +00006102 SectionRef CR = get_section(O, "__OBJC2", "__class_refs");
6103 if (CR == SectionRef())
6104 CR = get_section(O, "__DATA", "__objc_classrefs");
6105 if (CR == SectionRef())
6106 CR = get_section(O, "__DATA_CONST", "__objc_classrefs");
6107 if (CR == SectionRef())
6108 CR = get_section(O, "__DATA_DIRTY", "__objc_classrefs");
6109 info.S = CR;
6110 walk_pointer_list_32("class refs", CR, O, &info, nullptr);
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00006111
Kevin Enderby5879a482017-02-09 17:56:26 +00006112 SectionRef SR = get_section(O, "__OBJC2", "__super_refs");
6113 if (SR == SectionRef())
6114 SR = get_section(O, "__DATA", "__objc_superrefs");
6115 if (SR == SectionRef())
6116 SR = get_section(O, "__DATA_CONST", "__objc_superrefs");
6117 if (SR == SectionRef())
6118 SR = get_section(O, "__DATA_DIRTY", "__objc_superrefs");
6119 info.S = SR;
6120 walk_pointer_list_32("super refs", SR, O, &info, nullptr);
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00006121
Kevin Enderby5879a482017-02-09 17:56:26 +00006122 SectionRef CA = get_section(O, "__OBJC2", "__category_list");
6123 if (CA == SectionRef())
6124 CA = get_section(O, "__DATA", "__objc_catlist");
6125 if (CA == SectionRef())
6126 CA = get_section(O, "__DATA_CONST", "__objc_catlist");
6127 if (CA == SectionRef())
6128 CA = get_section(O, "__DATA_DIRTY", "__objc_catlist");
6129 info.S = CA;
6130 walk_pointer_list_32("category", CA, O, &info, print_category32_t);
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00006131
Kevin Enderby5879a482017-02-09 17:56:26 +00006132 SectionRef PL = get_section(O, "__OBJC2", "__protocol_list");
6133 if (PL == SectionRef())
6134 PL = get_section(O, "__DATA", "__objc_protolist");
6135 if (PL == SectionRef())
6136 PL = get_section(O, "__DATA_CONST", "__objc_protolist");
6137 if (PL == SectionRef())
6138 PL = get_section(O, "__DATA_DIRTY", "__objc_protolist");
6139 info.S = PL;
6140 walk_pointer_list_32("protocol", PL, O, &info, nullptr);
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00006141
Kevin Enderby5879a482017-02-09 17:56:26 +00006142 SectionRef MR = get_section(O, "__OBJC2", "__message_refs");
6143 if (MR == SectionRef())
6144 MR = get_section(O, "__DATA", "__objc_msgrefs");
6145 if (MR == SectionRef())
6146 MR = get_section(O, "__DATA_CONST", "__objc_msgrefs");
6147 if (MR == SectionRef())
6148 MR = get_section(O, "__DATA_DIRTY", "__objc_msgrefs");
6149 info.S = MR;
6150 print_message_refs32(MR, &info);
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00006151
Kevin Enderby5879a482017-02-09 17:56:26 +00006152 SectionRef II = get_section(O, "__OBJC2", "__image_info");
6153 if (II == SectionRef())
6154 II = get_section(O, "__DATA", "__objc_imageinfo");
6155 if (II == SectionRef())
6156 II = get_section(O, "__DATA_CONST", "__objc_imageinfo");
6157 if (II == SectionRef())
6158 II = get_section(O, "__DATA_DIRTY", "__objc_imageinfo");
6159 info.S = II;
6160 print_image_info32(II, &info);
Kevin Enderby0fc11822015-04-01 20:57:01 +00006161}
6162
6163static bool printObjc1_32bit_MetaData(MachOObjectFile *O, bool verbose) {
Kevin Enderby846c0002015-04-16 17:19:59 +00006164 uint32_t i, j, p, offset, xoffset, left, defs_left, def;
6165 const char *r, *name, *defs;
6166 struct objc_module_t module;
6167 SectionRef S, xS;
6168 struct objc_symtab_t symtab;
6169 struct objc_class_t objc_class;
6170 struct objc_category_t objc_category;
6171
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00006172 outs() << "Objective-C segment\n";
Kevin Enderby846c0002015-04-16 17:19:59 +00006173 S = get_section(O, "__OBJC", "__module_info");
6174 if (S == SectionRef())
6175 return false;
6176
6177 SymbolAddressMap AddrMap;
6178 if (verbose)
6179 CreateSymbolAddressMap(O, &AddrMap);
6180
6181 std::vector<SectionRef> Sections;
6182 for (const SectionRef &Section : O->sections()) {
6183 StringRef SectName;
6184 Section.getName(SectName);
6185 Sections.push_back(Section);
Kevin Enderby0fc11822015-04-01 20:57:01 +00006186 }
Kevin Enderby846c0002015-04-16 17:19:59 +00006187
Serge Pavlove4e9a1f2018-02-14 03:26:27 +00006188 struct DisassembleInfo info(O, &AddrMap, &Sections, verbose);
Kevin Enderby846c0002015-04-16 17:19:59 +00006189
6190 for (i = 0; i < S.getSize(); i += sizeof(struct objc_module_t)) {
6191 p = S.getAddress() + i;
6192 r = get_pointer_32(p, offset, left, S, &info, true);
6193 if (r == nullptr)
6194 return true;
6195 memset(&module, '\0', sizeof(struct objc_module_t));
6196 if (left < sizeof(struct objc_module_t)) {
6197 memcpy(&module, r, left);
6198 outs() << " (module extends past end of __module_info section)\n";
6199 } else
6200 memcpy(&module, r, sizeof(struct objc_module_t));
6201 if (O->isLittleEndian() != sys::IsLittleEndianHost)
6202 swapStruct(module);
6203
6204 outs() << "Module " << format("0x%" PRIx32, p) << "\n";
6205 outs() << " version " << module.version << "\n";
6206 outs() << " size " << module.size << "\n";
6207 outs() << " name ";
6208 name = get_pointer_32(module.name, xoffset, left, xS, &info, true);
6209 if (name != nullptr)
6210 outs() << format("%.*s", left, name);
6211 else
6212 outs() << format("0x%08" PRIx32, module.name)
6213 << "(not in an __OBJC section)";
6214 outs() << "\n";
6215
6216 r = get_pointer_32(module.symtab, xoffset, left, xS, &info, true);
6217 if (module.symtab == 0 || r == nullptr) {
6218 outs() << " symtab " << format("0x%08" PRIx32, module.symtab)
6219 << " (not in an __OBJC section)\n";
6220 continue;
6221 }
6222 outs() << " symtab " << format("0x%08" PRIx32, module.symtab) << "\n";
6223 memset(&symtab, '\0', sizeof(struct objc_symtab_t));
6224 defs_left = 0;
6225 defs = nullptr;
6226 if (left < sizeof(struct objc_symtab_t)) {
6227 memcpy(&symtab, r, left);
6228 outs() << "\tsymtab extends past end of an __OBJC section)\n";
6229 } else {
6230 memcpy(&symtab, r, sizeof(struct objc_symtab_t));
6231 if (left > sizeof(struct objc_symtab_t)) {
6232 defs_left = left - sizeof(struct objc_symtab_t);
6233 defs = r + sizeof(struct objc_symtab_t);
6234 }
6235 }
6236 if (O->isLittleEndian() != sys::IsLittleEndianHost)
6237 swapStruct(symtab);
6238
6239 outs() << "\tsel_ref_cnt " << symtab.sel_ref_cnt << "\n";
6240 r = get_pointer_32(symtab.refs, xoffset, left, xS, &info, true);
6241 outs() << "\trefs " << format("0x%08" PRIx32, symtab.refs);
6242 if (r == nullptr)
6243 outs() << " (not in an __OBJC section)";
6244 outs() << "\n";
6245 outs() << "\tcls_def_cnt " << symtab.cls_def_cnt << "\n";
6246 outs() << "\tcat_def_cnt " << symtab.cat_def_cnt << "\n";
6247 if (symtab.cls_def_cnt > 0)
6248 outs() << "\tClass Definitions\n";
6249 for (j = 0; j < symtab.cls_def_cnt; j++) {
6250 if ((j + 1) * sizeof(uint32_t) > defs_left) {
6251 outs() << "\t(remaining class defs entries entends past the end of the "
6252 << "section)\n";
6253 break;
6254 }
6255 memcpy(&def, defs + j * sizeof(uint32_t), sizeof(uint32_t));
6256 if (O->isLittleEndian() != sys::IsLittleEndianHost)
6257 sys::swapByteOrder(def);
6258
6259 r = get_pointer_32(def, xoffset, left, xS, &info, true);
6260 outs() << "\tdefs[" << j << "] " << format("0x%08" PRIx32, def);
6261 if (r != nullptr) {
6262 if (left > sizeof(struct objc_class_t)) {
6263 outs() << "\n";
6264 memcpy(&objc_class, r, sizeof(struct objc_class_t));
6265 } else {
6266 outs() << " (entends past the end of the section)\n";
6267 memset(&objc_class, '\0', sizeof(struct objc_class_t));
6268 memcpy(&objc_class, r, left);
6269 }
6270 if (O->isLittleEndian() != sys::IsLittleEndianHost)
6271 swapStruct(objc_class);
6272 print_objc_class_t(&objc_class, &info);
6273 } else {
6274 outs() << "(not in an __OBJC section)\n";
6275 }
6276
6277 if (CLS_GETINFO(&objc_class, CLS_CLASS)) {
6278 outs() << "\tMeta Class";
6279 r = get_pointer_32(objc_class.isa, xoffset, left, xS, &info, true);
6280 if (r != nullptr) {
6281 if (left > sizeof(struct objc_class_t)) {
6282 outs() << "\n";
6283 memcpy(&objc_class, r, sizeof(struct objc_class_t));
6284 } else {
6285 outs() << " (entends past the end of the section)\n";
6286 memset(&objc_class, '\0', sizeof(struct objc_class_t));
6287 memcpy(&objc_class, r, left);
6288 }
6289 if (O->isLittleEndian() != sys::IsLittleEndianHost)
6290 swapStruct(objc_class);
6291 print_objc_class_t(&objc_class, &info);
6292 } else {
6293 outs() << "(not in an __OBJC section)\n";
6294 }
6295 }
6296 }
6297 if (symtab.cat_def_cnt > 0)
6298 outs() << "\tCategory Definitions\n";
6299 for (j = 0; j < symtab.cat_def_cnt; j++) {
6300 if ((j + symtab.cls_def_cnt + 1) * sizeof(uint32_t) > defs_left) {
6301 outs() << "\t(remaining category defs entries entends past the end of "
6302 << "the section)\n";
6303 break;
6304 }
6305 memcpy(&def, defs + (j + symtab.cls_def_cnt) * sizeof(uint32_t),
6306 sizeof(uint32_t));
6307 if (O->isLittleEndian() != sys::IsLittleEndianHost)
6308 sys::swapByteOrder(def);
6309
6310 r = get_pointer_32(def, xoffset, left, xS, &info, true);
6311 outs() << "\tdefs[" << j + symtab.cls_def_cnt << "] "
6312 << format("0x%08" PRIx32, def);
6313 if (r != nullptr) {
6314 if (left > sizeof(struct objc_category_t)) {
6315 outs() << "\n";
6316 memcpy(&objc_category, r, sizeof(struct objc_category_t));
6317 } else {
6318 outs() << " (entends past the end of the section)\n";
6319 memset(&objc_category, '\0', sizeof(struct objc_category_t));
6320 memcpy(&objc_category, r, left);
6321 }
6322 if (O->isLittleEndian() != sys::IsLittleEndianHost)
6323 swapStruct(objc_category);
6324 print_objc_objc_category_t(&objc_category, &info);
6325 } else {
6326 outs() << "(not in an __OBJC section)\n";
6327 }
6328 }
6329 }
6330 const SectionRef II = get_section(O, "__OBJC", "__image_info");
6331 if (II != SectionRef())
6332 print_image_info(II, &info);
6333
6334 return true;
Kevin Enderby0fc11822015-04-01 20:57:01 +00006335}
6336
Kevin Enderby4ad9bde2015-04-16 22:33:20 +00006337static void DumpProtocolSection(MachOObjectFile *O, const char *sect,
6338 uint32_t size, uint32_t addr) {
6339 SymbolAddressMap AddrMap;
6340 CreateSymbolAddressMap(O, &AddrMap);
6341
6342 std::vector<SectionRef> Sections;
6343 for (const SectionRef &Section : O->sections()) {
6344 StringRef SectName;
6345 Section.getName(SectName);
6346 Sections.push_back(Section);
6347 }
6348
Serge Pavlove4e9a1f2018-02-14 03:26:27 +00006349 struct DisassembleInfo info(O, &AddrMap, &Sections, true);
Kevin Enderby4ad9bde2015-04-16 22:33:20 +00006350
6351 const char *p;
6352 struct objc_protocol_t protocol;
6353 uint32_t left, paddr;
6354 for (p = sect; p < sect + size; p += sizeof(struct objc_protocol_t)) {
6355 memset(&protocol, '\0', sizeof(struct objc_protocol_t));
6356 left = size - (p - sect);
6357 if (left < sizeof(struct objc_protocol_t)) {
6358 outs() << "Protocol extends past end of __protocol section\n";
6359 memcpy(&protocol, p, left);
6360 } else
6361 memcpy(&protocol, p, sizeof(struct objc_protocol_t));
6362 if (O->isLittleEndian() != sys::IsLittleEndianHost)
6363 swapStruct(protocol);
6364 paddr = addr + (p - sect);
6365 outs() << "Protocol " << format("0x%" PRIx32, paddr);
6366 if (print_protocol(paddr, 0, &info))
6367 outs() << "(not in an __OBJC section)\n";
6368 }
6369}
6370
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006371#ifdef HAVE_LIBXAR
6372inline void swapStruct(struct xar_header &xar) {
6373 sys::swapByteOrder(xar.magic);
6374 sys::swapByteOrder(xar.size);
6375 sys::swapByteOrder(xar.version);
6376 sys::swapByteOrder(xar.toc_length_compressed);
6377 sys::swapByteOrder(xar.toc_length_uncompressed);
6378 sys::swapByteOrder(xar.cksum_alg);
6379}
6380
6381static void PrintModeVerbose(uint32_t mode) {
6382 switch(mode & S_IFMT){
6383 case S_IFDIR:
6384 outs() << "d";
6385 break;
6386 case S_IFCHR:
6387 outs() << "c";
6388 break;
6389 case S_IFBLK:
6390 outs() << "b";
6391 break;
6392 case S_IFREG:
6393 outs() << "-";
6394 break;
6395 case S_IFLNK:
6396 outs() << "l";
6397 break;
6398 case S_IFSOCK:
6399 outs() << "s";
6400 break;
6401 default:
6402 outs() << "?";
6403 break;
6404 }
6405
6406 /* owner permissions */
6407 if(mode & S_IREAD)
6408 outs() << "r";
6409 else
6410 outs() << "-";
6411 if(mode & S_IWRITE)
6412 outs() << "w";
6413 else
6414 outs() << "-";
6415 if(mode & S_ISUID)
6416 outs() << "s";
6417 else if(mode & S_IEXEC)
6418 outs() << "x";
6419 else
6420 outs() << "-";
6421
6422 /* group permissions */
6423 if(mode & (S_IREAD >> 3))
6424 outs() << "r";
6425 else
6426 outs() << "-";
6427 if(mode & (S_IWRITE >> 3))
6428 outs() << "w";
6429 else
6430 outs() << "-";
6431 if(mode & S_ISGID)
6432 outs() << "s";
6433 else if(mode & (S_IEXEC >> 3))
6434 outs() << "x";
6435 else
6436 outs() << "-";
6437
6438 /* other permissions */
6439 if(mode & (S_IREAD >> 6))
6440 outs() << "r";
6441 else
6442 outs() << "-";
6443 if(mode & (S_IWRITE >> 6))
6444 outs() << "w";
6445 else
6446 outs() << "-";
6447 if(mode & S_ISVTX)
6448 outs() << "t";
6449 else if(mode & (S_IEXEC >> 6))
6450 outs() << "x";
6451 else
6452 outs() << "-";
6453}
6454
6455static void PrintXarFilesSummary(const char *XarFilename, xar_t xar) {
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006456 xar_file_t xf;
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006457 const char *key, *type, *mode, *user, *group, *size, *mtime, *name, *m;
6458 char *endp;
6459 uint32_t mode_value;
6460
Francis Ricci6f942972017-10-06 15:33:28 +00006461 ScopedXarIter xi;
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006462 if (!xi) {
Jonas Devliegheree787efd2018-11-11 22:12:04 +00006463 WithColor::error(errs(), "llvm-objdump")
6464 << "can't obtain an xar iterator for xar archive " << XarFilename
6465 << "\n";
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006466 return;
6467 }
6468
6469 // Go through the xar's files.
6470 for (xf = xar_file_first(xar, xi); xf; xf = xar_file_next(xi)) {
Francis Ricci6f942972017-10-06 15:33:28 +00006471 ScopedXarIter xp;
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006472 if(!xp){
Jonas Devliegheree787efd2018-11-11 22:12:04 +00006473 WithColor::error(errs(), "llvm-objdump")
6474 << "can't obtain an xar iterator for xar archive " << XarFilename
6475 << "\n";
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006476 return;
6477 }
6478 type = nullptr;
6479 mode = nullptr;
6480 user = nullptr;
6481 group = nullptr;
6482 size = nullptr;
6483 mtime = nullptr;
6484 name = nullptr;
6485 for(key = xar_prop_first(xf, xp); key; key = xar_prop_next(xp)){
Jonas Devliegherec0a758d2017-09-18 14:15:57 +00006486 const char *val = nullptr;
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006487 xar_prop_get(xf, key, &val);
6488#if 0 // Useful for debugging.
6489 outs() << "key: " << key << " value: " << val << "\n";
6490#endif
6491 if(strcmp(key, "type") == 0)
6492 type = val;
6493 if(strcmp(key, "mode") == 0)
6494 mode = val;
6495 if(strcmp(key, "user") == 0)
6496 user = val;
6497 if(strcmp(key, "group") == 0)
6498 group = val;
6499 if(strcmp(key, "data/size") == 0)
6500 size = val;
6501 if(strcmp(key, "mtime") == 0)
6502 mtime = val;
6503 if(strcmp(key, "name") == 0)
6504 name = val;
6505 }
6506 if(mode != nullptr){
6507 mode_value = strtoul(mode, &endp, 8);
6508 if(*endp != '\0')
6509 outs() << "(mode: \"" << mode << "\" contains non-octal chars) ";
6510 if(strcmp(type, "file") == 0)
6511 mode_value |= S_IFREG;
6512 PrintModeVerbose(mode_value);
6513 outs() << " ";
6514 }
6515 if(user != nullptr)
6516 outs() << format("%10s/", user);
6517 if(group != nullptr)
6518 outs() << format("%-10s ", group);
6519 if(size != nullptr)
6520 outs() << format("%7s ", size);
6521 if(mtime != nullptr){
6522 for(m = mtime; *m != 'T' && *m != '\0'; m++)
6523 outs() << *m;
6524 if(*m == 'T')
6525 m++;
6526 outs() << " ";
6527 for( ; *m != 'Z' && *m != '\0'; m++)
6528 outs() << *m;
6529 outs() << " ";
6530 }
6531 if(name != nullptr)
6532 outs() << name;
6533 outs() << "\n";
6534 }
6535}
6536
6537static void DumpBitcodeSection(MachOObjectFile *O, const char *sect,
6538 uint32_t size, bool verbose,
6539 bool PrintXarHeader, bool PrintXarFileHeaders,
6540 std::string XarMemberName) {
6541 if(size < sizeof(struct xar_header)) {
6542 outs() << "size of (__LLVM,__bundle) section too small (smaller than size "
6543 "of struct xar_header)\n";
6544 return;
6545 }
6546 struct xar_header XarHeader;
6547 memcpy(&XarHeader, sect, sizeof(struct xar_header));
6548 if (sys::IsLittleEndianHost)
6549 swapStruct(XarHeader);
6550 if (PrintXarHeader) {
6551 if (!XarMemberName.empty())
6552 outs() << "In xar member " << XarMemberName << ": ";
6553 else
6554 outs() << "For (__LLVM,__bundle) section: ";
6555 outs() << "xar header\n";
6556 if (XarHeader.magic == XAR_HEADER_MAGIC)
6557 outs() << " magic XAR_HEADER_MAGIC\n";
6558 else
6559 outs() << " magic "
6560 << format_hex(XarHeader.magic, 10, true)
6561 << " (not XAR_HEADER_MAGIC)\n";
6562 outs() << " size " << XarHeader.size << "\n";
6563 outs() << " version " << XarHeader.version << "\n";
6564 outs() << " toc_length_compressed " << XarHeader.toc_length_compressed
6565 << "\n";
6566 outs() << "toc_length_uncompressed " << XarHeader.toc_length_uncompressed
6567 << "\n";
6568 outs() << " cksum_alg ";
6569 switch (XarHeader.cksum_alg) {
6570 case XAR_CKSUM_NONE:
6571 outs() << "XAR_CKSUM_NONE\n";
6572 break;
6573 case XAR_CKSUM_SHA1:
6574 outs() << "XAR_CKSUM_SHA1\n";
6575 break;
6576 case XAR_CKSUM_MD5:
6577 outs() << "XAR_CKSUM_MD5\n";
6578 break;
Kevin Enderby42882282016-05-23 22:18:59 +00006579#ifdef XAR_CKSUM_SHA256
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006580 case XAR_CKSUM_SHA256:
6581 outs() << "XAR_CKSUM_SHA256\n";
6582 break;
Kevin Enderby42882282016-05-23 22:18:59 +00006583#endif
6584#ifdef XAR_CKSUM_SHA512
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006585 case XAR_CKSUM_SHA512:
6586 outs() << "XAR_CKSUM_SHA512\n";
6587 break;
Kevin Enderby42882282016-05-23 22:18:59 +00006588#endif
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006589 default:
6590 outs() << XarHeader.cksum_alg << "\n";
6591 }
6592 }
6593
6594 SmallString<128> XarFilename;
6595 int FD;
6596 std::error_code XarEC =
6597 sys::fs::createTemporaryFile("llvm-objdump", "xar", FD, XarFilename);
6598 if (XarEC) {
Jonas Devliegheree787efd2018-11-11 22:12:04 +00006599 WithColor::error(errs(), "llvm-objdump") << XarEC.message() << "\n";
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006600 return;
6601 }
Reid Kleckner3fc649c2017-09-23 01:03:17 +00006602 ToolOutputFile XarFile(XarFilename, FD);
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006603 raw_fd_ostream &XarOut = XarFile.os();
6604 StringRef XarContents(sect, size);
6605 XarOut << XarContents;
6606 XarOut.close();
6607 if (XarOut.has_error())
6608 return;
6609
Francis Ricci6f942972017-10-06 15:33:28 +00006610 ScopedXarFile xar(XarFilename.c_str(), READ);
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006611 if (!xar) {
Jonas Devliegheree787efd2018-11-11 22:12:04 +00006612 WithColor::error(errs(), "llvm-objdump")
6613 << "can't create temporary xar archive " << XarFilename << "\n";
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006614 return;
6615 }
6616
6617 SmallString<128> TocFilename;
6618 std::error_code TocEC =
6619 sys::fs::createTemporaryFile("llvm-objdump", "toc", TocFilename);
6620 if (TocEC) {
Jonas Devliegheree787efd2018-11-11 22:12:04 +00006621 WithColor::error(errs(), "llvm-objdump") << TocEC.message() << "\n";
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006622 return;
6623 }
6624 xar_serialize(xar, TocFilename.c_str());
6625
6626 if (PrintXarFileHeaders) {
6627 if (!XarMemberName.empty())
6628 outs() << "In xar member " << XarMemberName << ": ";
6629 else
6630 outs() << "For (__LLVM,__bundle) section: ";
6631 outs() << "xar archive files:\n";
6632 PrintXarFilesSummary(XarFilename.c_str(), xar);
6633 }
6634
6635 ErrorOr<std::unique_ptr<MemoryBuffer>> FileOrErr =
6636 MemoryBuffer::getFileOrSTDIN(TocFilename.c_str());
6637 if (std::error_code EC = FileOrErr.getError()) {
Jonas Devliegheree787efd2018-11-11 22:12:04 +00006638 WithColor::error(errs(), "llvm-objdump") << EC.message() << "\n";
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006639 return;
6640 }
6641 std::unique_ptr<MemoryBuffer> &Buffer = FileOrErr.get();
6642
6643 if (!XarMemberName.empty())
6644 outs() << "In xar member " << XarMemberName << ": ";
6645 else
6646 outs() << "For (__LLVM,__bundle) section: ";
6647 outs() << "xar table of contents:\n";
6648 outs() << Buffer->getBuffer() << "\n";
6649
6650 // TODO: Go through the xar's files.
Francis Ricci6f942972017-10-06 15:33:28 +00006651 ScopedXarIter xi;
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006652 if(!xi){
Jonas Devliegheree787efd2018-11-11 22:12:04 +00006653 WithColor::error(errs(), "llvm-objdump")
6654 << "can't obtain an xar iterator for xar archive "
6655 << XarFilename.c_str() << "\n";
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006656 return;
6657 }
6658 for(xar_file_t xf = xar_file_first(xar, xi); xf; xf = xar_file_next(xi)){
6659 const char *key;
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006660 const char *member_name, *member_type, *member_size_string;
6661 size_t member_size;
6662
Francis Ricci6f942972017-10-06 15:33:28 +00006663 ScopedXarIter xp;
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006664 if(!xp){
Jonas Devliegheree787efd2018-11-11 22:12:04 +00006665 WithColor::error(errs(), "llvm-objdump")
6666 << "can't obtain an xar iterator for xar archive "
6667 << XarFilename.c_str() << "\n";
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006668 return;
6669 }
6670 member_name = NULL;
6671 member_type = NULL;
6672 member_size_string = NULL;
6673 for(key = xar_prop_first(xf, xp); key; key = xar_prop_next(xp)){
Jonas Devliegherec0a758d2017-09-18 14:15:57 +00006674 const char *val = nullptr;
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006675 xar_prop_get(xf, key, &val);
6676#if 0 // Useful for debugging.
6677 outs() << "key: " << key << " value: " << val << "\n";
6678#endif
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +00006679 if (strcmp(key, "name") == 0)
6680 member_name = val;
6681 if (strcmp(key, "type") == 0)
6682 member_type = val;
6683 if (strcmp(key, "data/size") == 0)
6684 member_size_string = val;
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006685 }
6686 /*
6687 * If we find a file with a name, date/size and type properties
6688 * and with the type being "file" see if that is a xar file.
6689 */
6690 if (member_name != NULL && member_type != NULL &&
6691 strcmp(member_type, "file") == 0 &&
6692 member_size_string != NULL){
6693 // Extract the file into a buffer.
6694 char *endptr;
6695 member_size = strtoul(member_size_string, &endptr, 10);
6696 if (*endptr == '\0' && member_size != 0) {
Francis Ricci1bae0ac2017-09-13 13:57:45 +00006697 char *buffer;
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +00006698 if (xar_extract_tobuffersz(xar, xf, &buffer, &member_size) == 0) {
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006699#if 0 // Useful for debugging.
NAKAMURA Takumi6f43bd42017-10-18 13:31:28 +00006700 outs() << "xar member: " << member_name << " extracted\n";
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006701#endif
6702 // Set the XarMemberName we want to see printed in the header.
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +00006703 std::string OldXarMemberName;
6704 // If XarMemberName is already set this is nested. So
6705 // save the old name and create the nested name.
6706 if (!XarMemberName.empty()) {
6707 OldXarMemberName = XarMemberName;
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006708 XarMemberName =
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +00006709 (Twine("[") + XarMemberName + "]" + member_name).str();
6710 } else {
6711 OldXarMemberName = "";
6712 XarMemberName = member_name;
6713 }
6714 // See if this is could be a xar file (nested).
6715 if (member_size >= sizeof(struct xar_header)) {
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006716#if 0 // Useful for debugging.
NAKAMURA Takumi6f43bd42017-10-18 13:31:28 +00006717 outs() << "could be a xar file: " << member_name << "\n";
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006718#endif
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +00006719 memcpy((char *)&XarHeader, buffer, sizeof(struct xar_header));
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006720 if (sys::IsLittleEndianHost)
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +00006721 swapStruct(XarHeader);
6722 if (XarHeader.magic == XAR_HEADER_MAGIC)
6723 DumpBitcodeSection(O, buffer, member_size, verbose,
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006724 PrintXarHeader, PrintXarFileHeaders,
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +00006725 XarMemberName);
6726 }
6727 XarMemberName = OldXarMemberName;
Francis Ricci1bae0ac2017-09-13 13:57:45 +00006728 delete buffer;
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +00006729 }
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006730 }
6731 }
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006732 }
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006733}
6734#endif // defined(HAVE_LIBXAR)
6735
Kevin Enderby0fc11822015-04-01 20:57:01 +00006736static void printObjcMetaData(MachOObjectFile *O, bool verbose) {
6737 if (O->is64Bit())
6738 printObjc2_64bit_MetaData(O, verbose);
6739 else {
6740 MachO::mach_header H;
6741 H = O->getHeader();
6742 if (H.cputype == MachO::CPU_TYPE_ARM)
6743 printObjc2_32bit_MetaData(O, verbose);
6744 else {
6745 // This is the 32-bit non-arm cputype case. Which is normally
6746 // the first Objective-C ABI. But it may be the case of a
6747 // binary for the iOS simulator which is the second Objective-C
6748 // ABI. In that case printObjc1_32bit_MetaData() will determine that
6749 // and return false.
Hans Wennborgcc9deb42015-09-29 18:02:48 +00006750 if (!printObjc1_32bit_MetaData(O, verbose))
Kevin Enderby0fc11822015-04-01 20:57:01 +00006751 printObjc2_32bit_MetaData(O, verbose);
6752 }
6753 }
6754}
6755
Kevin Enderbybf246f52014-09-24 23:08:22 +00006756// GuessLiteralPointer returns a string which for the item in the Mach-O file
6757// for the address passed in as ReferenceValue for printing as a comment with
6758// the instruction and also returns the corresponding type of that item
6759// indirectly through ReferenceType.
6760//
6761// If ReferenceValue is an address of literal cstring then a pointer to the
6762// cstring is returned and ReferenceType is set to
6763// LLVMDisassembler_ReferenceType_Out_LitPool_CstrAddr .
6764//
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006765// If ReferenceValue is an address of an Objective-C CFString, Selector ref or
6766// Class ref that name is returned and the ReferenceType is set accordingly.
6767//
6768// Lastly, literals which are Symbol address in a literal pool are looked for
6769// and if found the symbol name is returned and ReferenceType is set to
6770// LLVMDisassembler_ReferenceType_Out_LitPool_SymAddr .
6771//
6772// If there is no item in the Mach-O file for the address passed in as
6773// ReferenceValue nullptr is returned and ReferenceType is unchanged.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00006774static const char *GuessLiteralPointer(uint64_t ReferenceValue,
6775 uint64_t ReferencePC,
6776 uint64_t *ReferenceType,
6777 struct DisassembleInfo *info) {
Kevin Enderbybf246f52014-09-24 23:08:22 +00006778 // First see if there is an external relocation entry at the ReferencePC.
Kevin Enderbyd90a4172015-10-10 00:05:01 +00006779 if (info->O->getHeader().filetype == MachO::MH_OBJECT) {
6780 uint64_t sect_addr = info->S.getAddress();
6781 uint64_t sect_offset = ReferencePC - sect_addr;
6782 bool reloc_found = false;
6783 DataRefImpl Rel;
6784 MachO::any_relocation_info RE;
6785 bool isExtern = false;
6786 SymbolRef Symbol;
6787 for (const RelocationRef &Reloc : info->S.relocations()) {
6788 uint64_t RelocOffset = Reloc.getOffset();
6789 if (RelocOffset == sect_offset) {
6790 Rel = Reloc.getRawDataRefImpl();
6791 RE = info->O->getRelocation(Rel);
6792 if (info->O->isRelocationScattered(RE))
6793 continue;
6794 isExtern = info->O->getPlainRelocationExternal(RE);
6795 if (isExtern) {
6796 symbol_iterator RelocSym = Reloc.getSymbol();
6797 Symbol = *RelocSym;
6798 }
6799 reloc_found = true;
6800 break;
Kevin Enderbybf246f52014-09-24 23:08:22 +00006801 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00006802 }
Kevin Enderbyd90a4172015-10-10 00:05:01 +00006803 // If there is an external relocation entry for a symbol in a section
6804 // then used that symbol's value for the value of the reference.
6805 if (reloc_found && isExtern) {
6806 if (info->O->getAnyRelocationPCRel(RE)) {
6807 unsigned Type = info->O->getAnyRelocationType(RE);
6808 if (Type == MachO::X86_64_RELOC_SIGNED) {
6809 ReferenceValue = Symbol.getValue();
6810 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00006811 }
6812 }
6813 }
6814
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006815 // Look for literals such as Objective-C CFStrings refs, Selector refs,
6816 // Message refs and Class refs.
6817 bool classref, selref, msgref, cfstring;
6818 uint64_t pointer_value = GuessPointerPointer(ReferenceValue, info, classref,
6819 selref, msgref, cfstring);
David Blaikie33dd45d02015-03-23 18:39:02 +00006820 if (classref && pointer_value == 0) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006821 // Note the ReferenceValue is a pointer into the __objc_classrefs section.
6822 // And the pointer_value in that section is typically zero as it will be
6823 // set by dyld as part of the "bind information".
6824 const char *name = get_dyld_bind_info_symbolname(ReferenceValue, info);
6825 if (name != nullptr) {
6826 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Class_Ref;
Hans Wennborgdb53e302014-10-23 21:59:17 +00006827 const char *class_name = strrchr(name, '$');
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006828 if (class_name != nullptr && class_name[1] == '_' &&
6829 class_name[2] != '\0') {
6830 info->class_name = class_name + 2;
6831 return name;
6832 }
6833 }
6834 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00006835
David Blaikie33dd45d02015-03-23 18:39:02 +00006836 if (classref) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006837 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Class_Ref;
6838 const char *name =
6839 get_objc2_64bit_class_name(pointer_value, ReferenceValue, info);
6840 if (name != nullptr)
6841 info->class_name = name;
6842 else
6843 name = "bad class ref";
Kevin Enderbybf246f52014-09-24 23:08:22 +00006844 return name;
6845 }
6846
David Blaikie33dd45d02015-03-23 18:39:02 +00006847 if (cfstring) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006848 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_CFString_Ref;
6849 const char *name = get_objc2_64bit_cfstring_name(ReferenceValue, info);
6850 return name;
6851 }
6852
David Blaikie33dd45d02015-03-23 18:39:02 +00006853 if (selref && pointer_value == 0)
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006854 pointer_value = get_objc2_64bit_selref(ReferenceValue, info);
6855
6856 if (pointer_value != 0)
6857 ReferenceValue = pointer_value;
6858
6859 const char *name = GuessCstringPointer(ReferenceValue, info);
6860 if (name) {
David Blaikie33dd45d02015-03-23 18:39:02 +00006861 if (pointer_value != 0 && selref) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006862 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Selector_Ref;
6863 info->selector_name = name;
David Blaikie33dd45d02015-03-23 18:39:02 +00006864 } else if (pointer_value != 0 && msgref) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006865 info->class_name = nullptr;
6866 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message_Ref;
6867 info->selector_name = name;
6868 } else
6869 *ReferenceType = LLVMDisassembler_ReferenceType_Out_LitPool_CstrAddr;
6870 return name;
6871 }
6872
6873 // Lastly look for an indirect symbol with this ReferenceValue which is in
6874 // a literal pool. If found return that symbol name.
6875 name = GuessIndirectSymbol(ReferenceValue, info);
6876 if (name) {
6877 *ReferenceType = LLVMDisassembler_ReferenceType_Out_LitPool_SymAddr;
6878 return name;
6879 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00006880
6881 return nullptr;
6882}
6883
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006884// SymbolizerSymbolLookUp is the symbol lookup function passed when creating
Kevin Enderbybf246f52014-09-24 23:08:22 +00006885// the Symbolizer. It looks up the ReferenceValue using the info passed via the
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006886// pointer to the struct DisassembleInfo that was passed when MCSymbolizer
6887// is created and returns the symbol name that matches the ReferenceValue or
6888// nullptr if none. The ReferenceType is passed in for the IN type of
6889// reference the instruction is making from the values in defined in the header
6890// "llvm-c/Disassembler.h". On return the ReferenceType can set to a specific
6891// Out type and the ReferenceName will also be set which is added as a comment
6892// to the disassembled instruction.
6893//
Kevin Enderby04bf6932014-10-28 23:39:46 +00006894// If the symbol name is a C++ mangled name then the demangled name is
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006895// returned through ReferenceName and ReferenceType is set to
6896// LLVMDisassembler_ReferenceType_DeMangled_Name .
6897//
6898// When this is called to get a symbol name for a branch target then the
6899// ReferenceType will be LLVMDisassembler_ReferenceType_In_Branch and then
6900// SymbolValue will be looked for in the indirect symbol table to determine if
6901// it is an address for a symbol stub. If so then the symbol name for that
6902// stub is returned indirectly through ReferenceName and then ReferenceType is
6903// set to LLVMDisassembler_ReferenceType_Out_SymbolStub.
6904//
Kevin Enderbybf246f52014-09-24 23:08:22 +00006905// When this is called with an value loaded via a PC relative load then
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006906// ReferenceType will be LLVMDisassembler_ReferenceType_In_PCrel_Load then the
6907// SymbolValue is checked to be an address of literal pointer, symbol pointer,
6908// or an Objective-C meta data reference. If so the output ReferenceType is
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006909// set to correspond to that as well as setting the ReferenceName.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00006910static const char *SymbolizerSymbolLookUp(void *DisInfo,
6911 uint64_t ReferenceValue,
6912 uint64_t *ReferenceType,
6913 uint64_t ReferencePC,
6914 const char **ReferenceName) {
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006915 struct DisassembleInfo *info = (struct DisassembleInfo *)DisInfo;
Kevin Enderbybf246f52014-09-24 23:08:22 +00006916 // If no verbose symbolic information is wanted then just return nullptr.
David Blaikie33dd45d02015-03-23 18:39:02 +00006917 if (!info->verbose) {
Kevin Enderbybf246f52014-09-24 23:08:22 +00006918 *ReferenceName = nullptr;
6919 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006920 return nullptr;
6921 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00006922
Kevin Enderbyf6d25852015-01-31 00:37:11 +00006923 const char *SymbolName = GuessSymbolName(ReferenceValue, info->AddrMap);
Kevin Enderbybf246f52014-09-24 23:08:22 +00006924
Kevin Enderby85974882014-09-26 22:20:44 +00006925 if (*ReferenceType == LLVMDisassembler_ReferenceType_In_Branch) {
6926 *ReferenceName = GuessIndirectSymbol(ReferenceValue, info);
Kevin Enderby04bf6932014-10-28 23:39:46 +00006927 if (*ReferenceName != nullptr) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006928 method_reference(info, ReferenceType, ReferenceName);
6929 if (*ReferenceType != LLVMDisassembler_ReferenceType_Out_Objc_Message)
6930 *ReferenceType = LLVMDisassembler_ReferenceType_Out_SymbolStub;
Rafael Espindolab940b662016-09-06 19:16:48 +00006931 } else if (SymbolName != nullptr && strncmp(SymbolName, "__Z", 3) == 0) {
Kevin Enderby04bf6932014-10-28 23:39:46 +00006932 if (info->demangled_name != nullptr)
6933 free(info->demangled_name);
6934 int status;
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006935 info->demangled_name =
Rafael Espindolab940b662016-09-06 19:16:48 +00006936 itaniumDemangle(SymbolName + 1, nullptr, nullptr, &status);
Kevin Enderby04bf6932014-10-28 23:39:46 +00006937 if (info->demangled_name != nullptr) {
6938 *ReferenceName = info->demangled_name;
6939 *ReferenceType = LLVMDisassembler_ReferenceType_DeMangled_Name;
6940 } else
6941 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
6942 } else
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006943 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
6944 } else if (*ReferenceType == LLVMDisassembler_ReferenceType_In_PCrel_Load) {
6945 *ReferenceName =
6946 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
Kevin Enderby85974882014-09-26 22:20:44 +00006947 if (*ReferenceName)
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006948 method_reference(info, ReferenceType, ReferenceName);
Kevin Enderby85974882014-09-26 22:20:44 +00006949 else
6950 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
Kevin Enderbyae3c1262014-11-14 21:52:18 +00006951 // If this is arm64 and the reference is an adrp instruction save the
6952 // instruction, passed in ReferenceValue and the address of the instruction
6953 // for use later if we see and add immediate instruction.
6954 } else if (info->O->getArch() == Triple::aarch64 &&
6955 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADRP) {
6956 info->adrp_inst = ReferenceValue;
6957 info->adrp_addr = ReferencePC;
6958 SymbolName = nullptr;
6959 *ReferenceName = nullptr;
6960 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
6961 // If this is arm64 and reference is an add immediate instruction and we
6962 // have
6963 // seen an adrp instruction just before it and the adrp's Xd register
6964 // matches
6965 // this add's Xn register reconstruct the value being referenced and look to
6966 // see if it is a literal pointer. Note the add immediate instruction is
6967 // passed in ReferenceValue.
6968 } else if (info->O->getArch() == Triple::aarch64 &&
6969 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADDXri &&
6970 ReferencePC - 4 == info->adrp_addr &&
6971 (info->adrp_inst & 0x9f000000) == 0x90000000 &&
6972 (info->adrp_inst & 0x1f) == ((ReferenceValue >> 5) & 0x1f)) {
6973 uint32_t addxri_inst;
6974 uint64_t adrp_imm, addxri_imm;
6975
6976 adrp_imm =
6977 ((info->adrp_inst & 0x00ffffe0) >> 3) | ((info->adrp_inst >> 29) & 0x3);
6978 if (info->adrp_inst & 0x0200000)
6979 adrp_imm |= 0xfffffffffc000000LL;
6980
6981 addxri_inst = ReferenceValue;
6982 addxri_imm = (addxri_inst >> 10) & 0xfff;
6983 if (((addxri_inst >> 22) & 0x3) == 1)
6984 addxri_imm <<= 12;
6985
6986 ReferenceValue = (info->adrp_addr & 0xfffffffffffff000LL) +
6987 (adrp_imm << 12) + addxri_imm;
6988
6989 *ReferenceName =
6990 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
6991 if (*ReferenceName == nullptr)
6992 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
6993 // If this is arm64 and the reference is a load register instruction and we
6994 // have seen an adrp instruction just before it and the adrp's Xd register
6995 // matches this add's Xn register reconstruct the value being referenced and
6996 // look to see if it is a literal pointer. Note the load register
6997 // instruction is passed in ReferenceValue.
6998 } else if (info->O->getArch() == Triple::aarch64 &&
6999 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_LDRXui &&
7000 ReferencePC - 4 == info->adrp_addr &&
7001 (info->adrp_inst & 0x9f000000) == 0x90000000 &&
7002 (info->adrp_inst & 0x1f) == ((ReferenceValue >> 5) & 0x1f)) {
7003 uint32_t ldrxui_inst;
7004 uint64_t adrp_imm, ldrxui_imm;
7005
7006 adrp_imm =
7007 ((info->adrp_inst & 0x00ffffe0) >> 3) | ((info->adrp_inst >> 29) & 0x3);
7008 if (info->adrp_inst & 0x0200000)
7009 adrp_imm |= 0xfffffffffc000000LL;
7010
7011 ldrxui_inst = ReferenceValue;
7012 ldrxui_imm = (ldrxui_inst >> 10) & 0xfff;
7013
7014 ReferenceValue = (info->adrp_addr & 0xfffffffffffff000LL) +
7015 (adrp_imm << 12) + (ldrxui_imm << 3);
7016
7017 *ReferenceName =
7018 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
7019 if (*ReferenceName == nullptr)
7020 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
7021 }
7022 // If this arm64 and is an load register (PC-relative) instruction the
7023 // ReferenceValue is the PC plus the immediate value.
7024 else if (info->O->getArch() == Triple::aarch64 &&
7025 (*ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_LDRXl ||
7026 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADR)) {
7027 *ReferenceName =
7028 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
7029 if (*ReferenceName == nullptr)
7030 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
Rafael Espindolab940b662016-09-06 19:16:48 +00007031 } else if (SymbolName != nullptr && strncmp(SymbolName, "__Z", 3) == 0) {
Kevin Enderby04bf6932014-10-28 23:39:46 +00007032 if (info->demangled_name != nullptr)
7033 free(info->demangled_name);
7034 int status;
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007035 info->demangled_name =
Rafael Espindolab940b662016-09-06 19:16:48 +00007036 itaniumDemangle(SymbolName + 1, nullptr, nullptr, &status);
Kevin Enderby04bf6932014-10-28 23:39:46 +00007037 if (info->demangled_name != nullptr) {
7038 *ReferenceName = info->demangled_name;
7039 *ReferenceType = LLVMDisassembler_ReferenceType_DeMangled_Name;
7040 }
7041 }
Kevin Enderby6f326ce2014-10-23 19:37:31 +00007042 else {
Kevin Enderbybf246f52014-09-24 23:08:22 +00007043 *ReferenceName = nullptr;
7044 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
7045 }
7046
7047 return SymbolName;
7048}
7049
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00007050/// Emits the comments that are stored in the CommentStream.
Kevin Enderbybf246f52014-09-24 23:08:22 +00007051/// Each comment in the CommentStream must end with a newline.
7052static void emitComments(raw_svector_ostream &CommentStream,
7053 SmallString<128> &CommentsToEmit,
7054 formatted_raw_ostream &FormattedOS,
7055 const MCAsmInfo &MAI) {
7056 // Flush the stream before taking its content.
Kevin Enderbybf246f52014-09-24 23:08:22 +00007057 StringRef Comments = CommentsToEmit.str();
7058 // Get the default information for printing a comment.
Mehdi Amini36d33fc2016-10-01 06:46:33 +00007059 StringRef CommentBegin = MAI.getCommentString();
Kevin Enderbybf246f52014-09-24 23:08:22 +00007060 unsigned CommentColumn = MAI.getCommentColumn();
7061 bool IsFirst = true;
7062 while (!Comments.empty()) {
7063 if (!IsFirst)
7064 FormattedOS << '\n';
7065 // Emit a line of comments.
7066 FormattedOS.PadToColumn(CommentColumn);
7067 size_t Position = Comments.find('\n');
7068 FormattedOS << CommentBegin << ' ' << Comments.substr(0, Position);
7069 // Move after the newline character.
7070 Comments = Comments.substr(Position + 1);
7071 IsFirst = false;
7072 }
7073 FormattedOS.flush();
7074
7075 // Tell the comment stream that the vector changed underneath it.
7076 CommentsToEmit.clear();
Kevin Enderby98c9acc2014-09-16 18:00:57 +00007077}
7078
Kevin Enderby95df54c2015-02-04 01:01:38 +00007079static void DisassembleMachO(StringRef Filename, MachOObjectFile *MachOOF,
7080 StringRef DisSegName, StringRef DisSectName) {
Kevin Enderbyec5ca032014-08-18 20:21:02 +00007081 const char *McpuDefault = nullptr;
7082 const Target *ThumbTarget = nullptr;
7083 const Target *TheTarget = GetTarget(MachOOF, &McpuDefault, &ThumbTarget);
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007084 if (!TheTarget) {
7085 // GetTarget prints out stuff.
7086 return;
7087 }
Kevin Enderbyf310e622017-09-21 21:45:02 +00007088 std::string MachOMCPU;
Kevin Enderbyec5ca032014-08-18 20:21:02 +00007089 if (MCPU.empty() && McpuDefault)
Kevin Enderbyf310e622017-09-21 21:45:02 +00007090 MachOMCPU = McpuDefault;
7091 else
7092 MachOMCPU = MCPU;
Kevin Enderbyec5ca032014-08-18 20:21:02 +00007093
Ahmed Charles56440fd2014-03-06 05:51:42 +00007094 std::unique_ptr<const MCInstrInfo> InstrInfo(TheTarget->createMCInstrInfo());
Kevin Enderbyec5ca032014-08-18 20:21:02 +00007095 std::unique_ptr<const MCInstrInfo> ThumbInstrInfo;
Kevin Enderbyae3c1262014-11-14 21:52:18 +00007096 if (ThumbTarget)
Kevin Enderbyec5ca032014-08-18 20:21:02 +00007097 ThumbInstrInfo.reset(ThumbTarget->createMCInstrInfo());
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007098
Kevin Enderbyc9595622014-08-06 23:24:41 +00007099 // Package up features to be passed to target/subtarget
7100 std::string FeaturesStr;
Jordan Rupprecht16a0de22018-12-20 00:57:06 +00007101 if (!MAttrs.empty()) {
Kevin Enderbyc9595622014-08-06 23:24:41 +00007102 SubtargetFeatures Features;
7103 for (unsigned i = 0; i != MAttrs.size(); ++i)
7104 Features.AddFeature(MAttrs[i]);
7105 FeaturesStr = Features.getString();
7106 }
7107
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007108 // Set up disassembler.
Ahmed Charles56440fd2014-03-06 05:51:42 +00007109 std::unique_ptr<const MCRegisterInfo> MRI(
7110 TheTarget->createMCRegInfo(TripleName));
7111 std::unique_ptr<const MCAsmInfo> AsmInfo(
Rafael Espindola227144c2013-05-13 01:16:13 +00007112 TheTarget->createMCAsmInfo(*MRI, TripleName));
Ahmed Charles56440fd2014-03-06 05:51:42 +00007113 std::unique_ptr<const MCSubtargetInfo> STI(
Kevin Enderbyf310e622017-09-21 21:45:02 +00007114 TheTarget->createMCSubtargetInfo(TripleName, MachOMCPU, FeaturesStr));
Craig Toppere6cb63e2014-04-25 04:24:47 +00007115 MCContext Ctx(AsmInfo.get(), MRI.get(), nullptr);
Kevin Enderby98c9acc2014-09-16 18:00:57 +00007116 std::unique_ptr<MCDisassembler> DisAsm(
Kevin Enderbyec5ca032014-08-18 20:21:02 +00007117 TheTarget->createMCDisassembler(*STI, Ctx));
Kevin Enderby98c9acc2014-09-16 18:00:57 +00007118 std::unique_ptr<MCSymbolizer> Symbolizer;
Serge Pavlove4e9a1f2018-02-14 03:26:27 +00007119 struct DisassembleInfo SymbolizerInfo(nullptr, nullptr, nullptr, false);
Kevin Enderby98c9acc2014-09-16 18:00:57 +00007120 std::unique_ptr<MCRelocationInfo> RelInfo(
7121 TheTarget->createMCRelocationInfo(TripleName, Ctx));
7122 if (RelInfo) {
7123 Symbolizer.reset(TheTarget->createMCSymbolizer(
7124 TripleName, SymbolizerGetOpInfo, SymbolizerSymbolLookUp,
David Blaikie186db432015-01-18 20:45:48 +00007125 &SymbolizerInfo, &Ctx, std::move(RelInfo)));
Kevin Enderby98c9acc2014-09-16 18:00:57 +00007126 DisAsm->setSymbolizer(std::move(Symbolizer));
7127 }
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007128 int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
Ahmed Charles56440fd2014-03-06 05:51:42 +00007129 std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
Daniel Sanders50f17232015-09-15 16:17:27 +00007130 Triple(TripleName), AsmPrinterVariant, *AsmInfo, *InstrInfo, *MRI));
Kevin Enderbybf246f52014-09-24 23:08:22 +00007131 // Set the display preference for hex vs. decimal immediates.
7132 IP->setPrintImmHex(PrintImmHex);
7133 // Comment stream and backing vector.
7134 SmallString<128> CommentsToEmit;
7135 raw_svector_ostream CommentStream(CommentsToEmit);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00007136 // FIXME: Setting the CommentStream in the InstPrinter is problematic in that
7137 // if it is done then arm64 comments for string literals don't get printed
7138 // and some constant get printed instead and not setting it causes intel
7139 // (32-bit and 64-bit) comments printed with different spacing before the
7140 // comment causing different diffs with the 'C' disassembler library API.
7141 // IP->setCommentStream(CommentStream);
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00007142
Kevin Enderbyae3c1262014-11-14 21:52:18 +00007143 if (!AsmInfo || !STI || !DisAsm || !IP) {
Jonas Devliegheree787efd2018-11-11 22:12:04 +00007144 WithColor::error(errs(), "llvm-objdump")
7145 << "couldn't initialize disassembler for target " << TripleName << '\n';
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007146 return;
7147 }
7148
Tim Northover09ca33e2016-04-22 23:23:31 +00007149 // Set up separate thumb disassembler if needed.
Kevin Enderbyec5ca032014-08-18 20:21:02 +00007150 std::unique_ptr<const MCRegisterInfo> ThumbMRI;
7151 std::unique_ptr<const MCAsmInfo> ThumbAsmInfo;
7152 std::unique_ptr<const MCSubtargetInfo> ThumbSTI;
Kevin Enderby930fdc72014-11-06 19:00:13 +00007153 std::unique_ptr<MCDisassembler> ThumbDisAsm;
Kevin Enderbyec5ca032014-08-18 20:21:02 +00007154 std::unique_ptr<MCInstPrinter> ThumbIP;
7155 std::unique_ptr<MCContext> ThumbCtx;
Kevin Enderby930fdc72014-11-06 19:00:13 +00007156 std::unique_ptr<MCSymbolizer> ThumbSymbolizer;
Serge Pavlove4e9a1f2018-02-14 03:26:27 +00007157 struct DisassembleInfo ThumbSymbolizerInfo(nullptr, nullptr, nullptr, false);
Kevin Enderby930fdc72014-11-06 19:00:13 +00007158 std::unique_ptr<MCRelocationInfo> ThumbRelInfo;
Kevin Enderbyec5ca032014-08-18 20:21:02 +00007159 if (ThumbTarget) {
7160 ThumbMRI.reset(ThumbTarget->createMCRegInfo(ThumbTripleName));
7161 ThumbAsmInfo.reset(
7162 ThumbTarget->createMCAsmInfo(*ThumbMRI, ThumbTripleName));
7163 ThumbSTI.reset(
Kevin Enderbyf310e622017-09-21 21:45:02 +00007164 ThumbTarget->createMCSubtargetInfo(ThumbTripleName, MachOMCPU,
7165 FeaturesStr));
Kevin Enderbyec5ca032014-08-18 20:21:02 +00007166 ThumbCtx.reset(new MCContext(ThumbAsmInfo.get(), ThumbMRI.get(), nullptr));
7167 ThumbDisAsm.reset(ThumbTarget->createMCDisassembler(*ThumbSTI, *ThumbCtx));
Kevin Enderby930fdc72014-11-06 19:00:13 +00007168 MCContext *PtrThumbCtx = ThumbCtx.get();
7169 ThumbRelInfo.reset(
7170 ThumbTarget->createMCRelocationInfo(ThumbTripleName, *PtrThumbCtx));
7171 if (ThumbRelInfo) {
7172 ThumbSymbolizer.reset(ThumbTarget->createMCSymbolizer(
7173 ThumbTripleName, SymbolizerGetOpInfo, SymbolizerSymbolLookUp,
David Blaikie186db432015-01-18 20:45:48 +00007174 &ThumbSymbolizerInfo, PtrThumbCtx, std::move(ThumbRelInfo)));
Kevin Enderby930fdc72014-11-06 19:00:13 +00007175 ThumbDisAsm->setSymbolizer(std::move(ThumbSymbolizer));
7176 }
Kevin Enderbyec5ca032014-08-18 20:21:02 +00007177 int ThumbAsmPrinterVariant = ThumbAsmInfo->getAssemblerDialect();
7178 ThumbIP.reset(ThumbTarget->createMCInstPrinter(
Daniel Sanders50f17232015-09-15 16:17:27 +00007179 Triple(ThumbTripleName), ThumbAsmPrinterVariant, *ThumbAsmInfo,
7180 *ThumbInstrInfo, *ThumbMRI));
Kevin Enderbybf246f52014-09-24 23:08:22 +00007181 // Set the display preference for hex vs. decimal immediates.
7182 ThumbIP->setPrintImmHex(PrintImmHex);
Kevin Enderbyec5ca032014-08-18 20:21:02 +00007183 }
7184
Kevin Enderbyae3c1262014-11-14 21:52:18 +00007185 if (ThumbTarget && (!ThumbAsmInfo || !ThumbSTI || !ThumbDisAsm || !ThumbIP)) {
Jonas Devliegheree787efd2018-11-11 22:12:04 +00007186 WithColor::error(errs(), "llvm-objdump")
7187 << "couldn't initialize disassembler for target " << ThumbTripleName
7188 << '\n';
Kevin Enderbyec5ca032014-08-18 20:21:02 +00007189 return;
7190 }
7191
Charles Davis8bdfafd2013-09-01 04:28:48 +00007192 MachO::mach_header Header = MachOOF->getHeader();
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007193
Ahmed Bougachaaa790682013-05-24 01:07:04 +00007194 // FIXME: Using the -cfg command line option, this code used to be able to
7195 // annotate relocations with the referenced symbol's name, and if this was
7196 // inside a __[cf]string section, the data it points to. This is now replaced
7197 // by the upcoming MCSymbolizer, which needs the appropriate setup done above.
Owen Andersond9243c42011-10-17 21:37:35 +00007198 std::vector<SectionRef> Sections;
7199 std::vector<SymbolRef> Symbols;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007200 SmallVector<uint64_t, 8> FoundFns;
Kevin Enderby273ae012013-06-06 17:20:50 +00007201 uint64_t BaseSegmentAddress;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007202
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00007203 getSectionsAndSymbols(MachOOF, Sections, Symbols, FoundFns,
Kevin Enderby273ae012013-06-06 17:20:50 +00007204 BaseSegmentAddress);
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007205
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007206 // Sort the symbols by address, just in case they didn't come in that way.
Fangrui Song0cac7262018-09-27 02:13:45 +00007207 llvm::sort(Symbols, SymbolSorter());
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007208
Kevin Enderby273ae012013-06-06 17:20:50 +00007209 // Build a data in code table that is sorted on by the address of each entry.
7210 uint64_t BaseAddress = 0;
Charles Davis8bdfafd2013-09-01 04:28:48 +00007211 if (Header.filetype == MachO::MH_OBJECT)
Rafael Espindola80291272014-10-08 15:28:58 +00007212 BaseAddress = Sections[0].getAddress();
Kevin Enderby273ae012013-06-06 17:20:50 +00007213 else
7214 BaseAddress = BaseSegmentAddress;
7215 DiceTable Dices;
Kevin Enderby273ae012013-06-06 17:20:50 +00007216 for (dice_iterator DI = MachOOF->begin_dices(), DE = MachOOF->end_dices();
Rafael Espindola5e812af2014-01-30 02:49:50 +00007217 DI != DE; ++DI) {
Kevin Enderby273ae012013-06-06 17:20:50 +00007218 uint32_t Offset;
7219 DI->getOffset(Offset);
7220 Dices.push_back(std::make_pair(BaseAddress + Offset, *DI));
7221 }
7222 array_pod_sort(Dices.begin(), Dices.end());
7223
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007224#ifndef NDEBUG
7225 raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls();
7226#else
7227 raw_ostream &DebugOut = nulls();
7228#endif
7229
Ahmed Charles56440fd2014-03-06 05:51:42 +00007230 std::unique_ptr<DIContext> diContext;
Rafael Espindola9b709252013-04-13 01:45:40 +00007231 ObjectFile *DbgObj = MachOOF;
Francis Visoiu Mistrih8e864be2018-08-31 13:10:54 +00007232 std::unique_ptr<MemoryBuffer> DSYMBuf;
Benjamin Kramer699128e2011-09-21 01:13:19 +00007233 // Try to find debug info and set up the DIContext for it.
7234 if (UseDbg) {
Benjamin Kramer699128e2011-09-21 01:13:19 +00007235 // A separate DSym file path was specified, parse it as a macho file,
7236 // get the sections and supply it to the section name parsing machinery.
7237 if (!DSYMFile.empty()) {
Rafael Espindola48af1c22014-08-19 18:44:46 +00007238 ErrorOr<std::unique_ptr<MemoryBuffer>> BufOrErr =
Rafael Espindolaadf21f22014-07-06 17:43:13 +00007239 MemoryBuffer::getFileOrSTDIN(DSYMFile);
Rafael Espindola48af1c22014-08-19 18:44:46 +00007240 if (std::error_code EC = BufOrErr.getError()) {
Francis Visoiu Mistrihb8819dc2019-01-10 17:36:54 +00007241 report_error(DSYMFile, errorCodeToError(EC));
Benjamin Kramer699128e2011-09-21 01:13:19 +00007242 return;
7243 }
Francis Visoiu Mistrihb8819dc2019-01-10 17:36:54 +00007244
Gerolf Hoflehnerbf26d542018-04-19 20:48:35 +00007245 Expected<std::unique_ptr<MachOObjectFile>> DbgObjCheck =
7246 ObjectFile::createMachOObjectFile(BufOrErr.get()->getMemBufferRef());
7247
Francis Visoiu Mistrihb8819dc2019-01-10 17:36:54 +00007248 if (Error E = DbgObjCheck.takeError()) {
Francis Visoiu Mistrih1b427d42019-01-10 17:16:42 +00007249 report_error(DSYMFile, std::move(E));
Francis Visoiu Mistrihb8819dc2019-01-10 17:36:54 +00007250 return;
7251 }
Francis Visoiu Mistrih9f4f0112019-01-10 17:16:37 +00007252
Gerolf Hoflehnerbf26d542018-04-19 20:48:35 +00007253 DbgObj = DbgObjCheck.get().release();
Francis Visoiu Mistrih8e864be2018-08-31 13:10:54 +00007254 // We need to keep the file alive, because we're replacing DbgObj with it.
7255 DSYMBuf = std::move(BufOrErr.get());
Benjamin Kramer699128e2011-09-21 01:13:19 +00007256 }
7257
Eric Christopher7370b552012-11-12 21:40:38 +00007258 // Setup the DIContext
Rafael Espindolac398e672017-07-19 22:27:28 +00007259 diContext = DWARFContext::create(*DbgObj);
Benjamin Kramer699128e2011-09-21 01:13:19 +00007260 }
7261
Jordan Rupprecht16a0de22018-12-20 00:57:06 +00007262 if (FilterSections.empty())
Kevin Enderby95df54c2015-02-04 01:01:38 +00007263 outs() << "(" << DisSegName << "," << DisSectName << ") section\n";
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00007264
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007265 for (unsigned SectIdx = 0; SectIdx != Sections.size(); SectIdx++) {
Owen Andersond9243c42011-10-17 21:37:35 +00007266 StringRef SectName;
Kevin Enderby95df54c2015-02-04 01:01:38 +00007267 if (Sections[SectIdx].getName(SectName) || SectName != DisSectName)
7268 continue;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007269
Rafael Espindolaa9f810b2012-12-21 03:47:03 +00007270 DataRefImpl DR = Sections[SectIdx].getRawDataRefImpl();
Ahmed Bougachaaa790682013-05-24 01:07:04 +00007271
Rafael Espindolab0f76a42013-04-05 15:15:22 +00007272 StringRef SegmentName = MachOOF->getSectionFinalSegmentName(DR);
Kevin Enderby95df54c2015-02-04 01:01:38 +00007273 if (SegmentName != DisSegName)
Rafael Espindolaa9f810b2012-12-21 03:47:03 +00007274 continue;
7275
Rafael Espindola7fc5b872014-11-12 02:04:27 +00007276 StringRef BytesStr;
7277 Sections[SectIdx].getContents(BytesStr);
Aaron Ballman106fd7b2014-11-12 14:01:17 +00007278 ArrayRef<uint8_t> Bytes(reinterpret_cast<const uint8_t *>(BytesStr.data()),
7279 BytesStr.size());
Rafael Espindola80291272014-10-08 15:28:58 +00007280 uint64_t SectAddress = Sections[SectIdx].getAddress();
Rafael Espindolabd604f22014-11-07 00:52:15 +00007281
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007282 bool symbolTableWorked = false;
7283
Kevin Enderbybf246f52014-09-24 23:08:22 +00007284 // Create a map of symbol addresses to symbol names for use by
7285 // the SymbolizerSymbolLookUp() routine.
7286 SymbolAddressMap AddrMap;
Kevin Enderby6a221752015-03-17 17:10:57 +00007287 bool DisSymNameFound = false;
Kevin Enderbybf246f52014-09-24 23:08:22 +00007288 for (const SymbolRef &Symbol : MachOOF->symbols()) {
Kevin Enderby7bd8d992016-05-02 20:28:12 +00007289 Expected<SymbolRef::Type> STOrErr = Symbol.getType();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00007290 if (!STOrErr)
7291 report_error(MachOOF->getFileName(), STOrErr.takeError());
Kevin Enderby5afbc1c2016-03-23 20:27:00 +00007292 SymbolRef::Type ST = *STOrErr;
Kevin Enderbybf246f52014-09-24 23:08:22 +00007293 if (ST == SymbolRef::ST_Function || ST == SymbolRef::ST_Data ||
7294 ST == SymbolRef::ST_Other) {
Rafael Espindoladea00162015-07-03 17:44:18 +00007295 uint64_t Address = Symbol.getValue();
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00007296 Expected<StringRef> SymNameOrErr = Symbol.getName();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00007297 if (!SymNameOrErr)
7298 report_error(MachOOF->getFileName(), SymNameOrErr.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00007299 StringRef SymName = *SymNameOrErr;
Kevin Enderbybf246f52014-09-24 23:08:22 +00007300 AddrMap[Address] = SymName;
Kevin Enderby6a221752015-03-17 17:10:57 +00007301 if (!DisSymName.empty() && DisSymName == SymName)
7302 DisSymNameFound = true;
Kevin Enderbybf246f52014-09-24 23:08:22 +00007303 }
7304 }
David Blaikie33dd45d02015-03-23 18:39:02 +00007305 if (!DisSymName.empty() && !DisSymNameFound) {
Kevin Enderby6a221752015-03-17 17:10:57 +00007306 outs() << "Can't find -dis-symname: " << DisSymName << "\n";
7307 return;
7308 }
Kevin Enderby98c9acc2014-09-16 18:00:57 +00007309 // Set up the block of info used by the Symbolizer call backs.
Kevin Enderby8e29ec92015-03-17 22:26:11 +00007310 SymbolizerInfo.verbose = !NoSymbolicOperands;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00007311 SymbolizerInfo.O = MachOOF;
7312 SymbolizerInfo.S = Sections[SectIdx];
Kevin Enderbybf246f52014-09-24 23:08:22 +00007313 SymbolizerInfo.AddrMap = &AddrMap;
Kevin Enderby6f326ce2014-10-23 19:37:31 +00007314 SymbolizerInfo.Sections = &Sections;
Kevin Enderby930fdc72014-11-06 19:00:13 +00007315 // Same for the ThumbSymbolizer
Kevin Enderby8e29ec92015-03-17 22:26:11 +00007316 ThumbSymbolizerInfo.verbose = !NoSymbolicOperands;
Kevin Enderby930fdc72014-11-06 19:00:13 +00007317 ThumbSymbolizerInfo.O = MachOOF;
7318 ThumbSymbolizerInfo.S = Sections[SectIdx];
7319 ThumbSymbolizerInfo.AddrMap = &AddrMap;
7320 ThumbSymbolizerInfo.Sections = &Sections;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00007321
Kevin Enderby4b627be2016-04-28 20:14:13 +00007322 unsigned int Arch = MachOOF->getArch();
7323
Tim Northoverf203ab52016-07-14 22:13:32 +00007324 // Skip all symbols if this is a stubs file.
Jordan Rupprecht16a0de22018-12-20 00:57:06 +00007325 if (Bytes.empty())
Tim Northoverf203ab52016-07-14 22:13:32 +00007326 return;
7327
Kevin Enderbyc138da32017-02-06 18:43:18 +00007328 // If the section has symbols but no symbol at the start of the section
7329 // these are used to make sure the bytes before the first symbol are
7330 // disassembled.
7331 bool FirstSymbol = true;
7332 bool FirstSymbolAtSectionStart = true;
7333
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00007334 // Disassemble symbol by symbol.
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007335 for (unsigned SymIdx = 0; SymIdx != Symbols.size(); SymIdx++) {
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00007336 Expected<StringRef> SymNameOrErr = Symbols[SymIdx].getName();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00007337 if (!SymNameOrErr)
7338 report_error(MachOOF->getFileName(), SymNameOrErr.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00007339 StringRef SymName = *SymNameOrErr;
Owen Andersond9243c42011-10-17 21:37:35 +00007340
Kevin Enderby7bd8d992016-05-02 20:28:12 +00007341 Expected<SymbolRef::Type> STOrErr = Symbols[SymIdx].getType();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00007342 if (!STOrErr)
7343 report_error(MachOOF->getFileName(), STOrErr.takeError());
Kevin Enderby5afbc1c2016-03-23 20:27:00 +00007344 SymbolRef::Type ST = *STOrErr;
Kuba Breckade833222015-11-12 09:40:29 +00007345 if (ST != SymbolRef::ST_Function && ST != SymbolRef::ST_Data)
Owen Andersond9243c42011-10-17 21:37:35 +00007346 continue;
7347
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00007348 // Make sure the symbol is defined in this section.
Rafael Espindola80291272014-10-08 15:28:58 +00007349 bool containsSym = Sections[SectIdx].containsSymbol(Symbols[SymIdx]);
Kevin Enderbyd8a6e832016-06-15 21:14:01 +00007350 if (!containsSym) {
7351 if (!DisSymName.empty() && DisSymName == SymName) {
7352 outs() << "-dis-symname: " << DisSymName << " not in the section\n";
7353 return;
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +00007354 }
Kevin Enderbyd8a6e832016-06-15 21:14:01 +00007355 continue;
7356 }
7357 // The __mh_execute_header is special and we need to deal with that fact
7358 // this symbol is before the start of the (__TEXT,__text) section and at the
7359 // address of the start of the __TEXT segment. This is because this symbol
7360 // is an N_SECT symbol in the (__TEXT,__text) but its address is before the
7361 // start of the section in a standard MH_EXECUTE filetype.
7362 if (!DisSymName.empty() && DisSymName == "__mh_execute_header") {
7363 outs() << "-dis-symname: __mh_execute_header not in any section\n";
7364 return;
7365 }
Tim Northoverfbefee32016-07-14 23:13:03 +00007366 // When this code is trying to disassemble a symbol at a time and in the
7367 // case there is only the __mh_execute_header symbol left as in a stripped
7368 // executable, we need to deal with this by ignoring this symbol so the
7369 // whole section is disassembled and this symbol is then not displayed.
7370 if (SymName == "__mh_execute_header" || SymName == "__mh_dylib_header" ||
7371 SymName == "__mh_bundle_header" || SymName == "__mh_object_header" ||
7372 SymName == "__mh_preload_header" || SymName == "__mh_dylinker_header")
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007373 continue;
7374
Kevin Enderby6a221752015-03-17 17:10:57 +00007375 // If we are only disassembling one symbol see if this is that symbol.
7376 if (!DisSymName.empty() && DisSymName != SymName)
7377 continue;
7378
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00007379 // Start at the address of the symbol relative to the section's address.
Tim Northoverf203ab52016-07-14 22:13:32 +00007380 uint64_t SectSize = Sections[SectIdx].getSize();
Rafael Espindoladea00162015-07-03 17:44:18 +00007381 uint64_t Start = Symbols[SymIdx].getValue();
Rafael Espindola80291272014-10-08 15:28:58 +00007382 uint64_t SectionAddress = Sections[SectIdx].getAddress();
Cameron Zwarich54478a52012-02-03 05:42:17 +00007383 Start -= SectionAddress;
Owen Andersond9243c42011-10-17 21:37:35 +00007384
Tim Northoverf203ab52016-07-14 22:13:32 +00007385 if (Start > SectSize) {
7386 outs() << "section data ends, " << SymName
7387 << " lies outside valid range\n";
7388 return;
7389 }
7390
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00007391 // Stop disassembling either at the beginning of the next symbol or at
7392 // the end of the section.
Kevin Enderbyedd58722012-05-15 18:57:14 +00007393 bool containsNextSym = false;
Owen Andersond9243c42011-10-17 21:37:35 +00007394 uint64_t NextSym = 0;
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007395 uint64_t NextSymIdx = SymIdx + 1;
Owen Andersond9243c42011-10-17 21:37:35 +00007396 while (Symbols.size() > NextSymIdx) {
Kevin Enderby7bd8d992016-05-02 20:28:12 +00007397 Expected<SymbolRef::Type> STOrErr = Symbols[NextSymIdx].getType();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00007398 if (!STOrErr)
7399 report_error(MachOOF->getFileName(), STOrErr.takeError());
Kevin Enderby5afbc1c2016-03-23 20:27:00 +00007400 SymbolRef::Type NextSymType = *STOrErr;
Owen Andersond9243c42011-10-17 21:37:35 +00007401 if (NextSymType == SymbolRef::ST_Function) {
Rafael Espindola80291272014-10-08 15:28:58 +00007402 containsNextSym =
7403 Sections[SectIdx].containsSymbol(Symbols[NextSymIdx]);
Rafael Espindoladea00162015-07-03 17:44:18 +00007404 NextSym = Symbols[NextSymIdx].getValue();
Cameron Zwarich54478a52012-02-03 05:42:17 +00007405 NextSym -= SectionAddress;
Owen Andersond9243c42011-10-17 21:37:35 +00007406 break;
7407 }
7408 ++NextSymIdx;
7409 }
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007410
Tim Northoverf203ab52016-07-14 22:13:32 +00007411 uint64_t End = containsNextSym ? std::min(NextSym, SectSize) : SectSize;
Owen Andersond9243c42011-10-17 21:37:35 +00007412 uint64_t Size;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007413
7414 symbolTableWorked = true;
Rafael Espindolabd604f22014-11-07 00:52:15 +00007415
Kevin Enderbyec5ca032014-08-18 20:21:02 +00007416 DataRefImpl Symb = Symbols[SymIdx].getRawDataRefImpl();
Tim Northover09ca33e2016-04-22 23:23:31 +00007417 bool IsThumb = MachOOF->getSymbolFlags(Symb) & SymbolRef::SF_Thumb;
7418
7419 // We only need the dedicated Thumb target if there's a real choice
7420 // (i.e. we're not targeting M-class) and the function is Thumb.
7421 bool UseThumbTarget = IsThumb && ThumbTarget;
Kevin Enderbyec5ca032014-08-18 20:21:02 +00007422
Kevin Enderbyc138da32017-02-06 18:43:18 +00007423 // If we are not specifying a symbol to start disassembly with and this
7424 // is the first symbol in the section but not at the start of the section
7425 // then move the disassembly index to the start of the section and
7426 // don't print the symbol name just yet. This is so the bytes before the
7427 // first symbol are disassembled.
7428 uint64_t SymbolStart = Start;
7429 if (DisSymName.empty() && FirstSymbol && Start != 0) {
7430 FirstSymbolAtSectionStart = false;
7431 Start = 0;
7432 }
7433 else
7434 outs() << SymName << ":\n";
7435
Ahmed Bougachaaa790682013-05-24 01:07:04 +00007436 DILineInfo lastLine;
7437 for (uint64_t Index = Start; Index < End; Index += Size) {
7438 MCInst Inst;
Owen Andersond9243c42011-10-17 21:37:35 +00007439
Kevin Enderbyc138da32017-02-06 18:43:18 +00007440 // If this is the first symbol in the section and it was not at the
7441 // start of the section, see if we are at its Index now and if so print
7442 // the symbol name.
7443 if (FirstSymbol && !FirstSymbolAtSectionStart && Index == SymbolStart)
7444 outs() << SymName << ":\n";
7445
Kevin Enderbybf246f52014-09-24 23:08:22 +00007446 uint64_t PC = SectAddress + Index;
Kevin Enderbyab5e6c92015-03-17 21:07:39 +00007447 if (!NoLeadingAddr) {
7448 if (FullLeadingAddr) {
7449 if (MachOOF->is64Bit())
7450 outs() << format("%016" PRIx64, PC);
7451 else
7452 outs() << format("%08" PRIx64, PC);
7453 } else {
7454 outs() << format("%8" PRIx64 ":", PC);
7455 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00007456 }
Kevin Enderby4b627be2016-04-28 20:14:13 +00007457 if (!NoShowRawInsn || Arch == Triple::arm)
Kevin Enderbybf246f52014-09-24 23:08:22 +00007458 outs() << "\t";
Kevin Enderby273ae012013-06-06 17:20:50 +00007459
7460 // Check the data in code table here to see if this is data not an
7461 // instruction to be disassembled.
7462 DiceTable Dice;
Kevin Enderbybf246f52014-09-24 23:08:22 +00007463 Dice.push_back(std::make_pair(PC, DiceRef()));
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007464 dice_table_iterator DTI =
7465 std::search(Dices.begin(), Dices.end(), Dice.begin(), Dice.end(),
7466 compareDiceTableEntries);
7467 if (DTI != Dices.end()) {
Kevin Enderby273ae012013-06-06 17:20:50 +00007468 uint16_t Length;
7469 DTI->second.getLength(Length);
Kevin Enderby273ae012013-06-06 17:20:50 +00007470 uint16_t Kind;
7471 DTI->second.getKind(Kind);
Colin LeMahieufc32b1b2015-03-18 19:27:31 +00007472 Size = DumpDataInCode(Bytes.data() + Index, Length, Kind);
Kevin Enderby930fdc72014-11-06 19:00:13 +00007473 if ((Kind == MachO::DICE_KIND_JUMP_TABLE8) &&
7474 (PC == (DTI->first + Length - 1)) && (Length & 1))
7475 Size++;
Kevin Enderby273ae012013-06-06 17:20:50 +00007476 continue;
7477 }
7478
Kevin Enderbybf246f52014-09-24 23:08:22 +00007479 SmallVector<char, 64> AnnotationsBytes;
7480 raw_svector_ostream Annotations(AnnotationsBytes);
7481
Kevin Enderbyec5ca032014-08-18 20:21:02 +00007482 bool gotInst;
Tim Northover09ca33e2016-04-22 23:23:31 +00007483 if (UseThumbTarget)
Rafael Espindola7fc5b872014-11-12 02:04:27 +00007484 gotInst = ThumbDisAsm->getInstruction(Inst, Size, Bytes.slice(Index),
Kevin Enderby6f326ce2014-10-23 19:37:31 +00007485 PC, DebugOut, Annotations);
Kevin Enderbyec5ca032014-08-18 20:21:02 +00007486 else
Rafael Espindola7fc5b872014-11-12 02:04:27 +00007487 gotInst = DisAsm->getInstruction(Inst, Size, Bytes.slice(Index), PC,
Kevin Enderbybf246f52014-09-24 23:08:22 +00007488 DebugOut, Annotations);
Kevin Enderbyec5ca032014-08-18 20:21:02 +00007489 if (gotInst) {
Kevin Enderby4b627be2016-04-28 20:14:13 +00007490 if (!NoShowRawInsn || Arch == Triple::arm) {
Craig Topper0013be12015-09-21 05:32:41 +00007491 dumpBytes(makeArrayRef(Bytes.data() + Index, Size), outs());
Kevin Enderbybf246f52014-09-24 23:08:22 +00007492 }
7493 formatted_raw_ostream FormattedOS(outs());
Kevin Enderbybf246f52014-09-24 23:08:22 +00007494 StringRef AnnotationsStr = Annotations.str();
Tim Northover09ca33e2016-04-22 23:23:31 +00007495 if (UseThumbTarget)
Akira Hatanakab46d0232015-03-27 20:36:02 +00007496 ThumbIP->printInst(&Inst, FormattedOS, AnnotationsStr, *ThumbSTI);
Kevin Enderbyec5ca032014-08-18 20:21:02 +00007497 else
Akira Hatanaka1d079942015-03-28 20:44:05 +00007498 IP->printInst(&Inst, FormattedOS, AnnotationsStr, *STI);
Kevin Enderbybf246f52014-09-24 23:08:22 +00007499 emitComments(CommentStream, CommentsToEmit, FormattedOS, *AsmInfo);
Owen Andersond9243c42011-10-17 21:37:35 +00007500
Ahmed Bougachaaa790682013-05-24 01:07:04 +00007501 // Print debug info.
7502 if (diContext) {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007503 DILineInfo dli = diContext->getLineInfoForAddress(PC);
Ahmed Bougachaaa790682013-05-24 01:07:04 +00007504 // Print valid line info if it changed.
Alexey Samsonovd0109992014-04-18 21:36:39 +00007505 if (dli != lastLine && dli.Line != 0)
7506 outs() << "\t## " << dli.FileName << ':' << dli.Line << ':'
7507 << dli.Column;
Ahmed Bougachaaa790682013-05-24 01:07:04 +00007508 lastLine = dli;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007509 }
Ahmed Bougachaaa790682013-05-24 01:07:04 +00007510 outs() << "\n";
7511 } else {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00007512 unsigned int Arch = MachOOF->getArch();
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007513 if (Arch == Triple::x86_64 || Arch == Triple::x86) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00007514 outs() << format("\t.byte 0x%02x #bad opcode\n",
7515 *(Bytes.data() + Index) & 0xff);
7516 Size = 1; // skip exactly one illegible byte and move on.
Tim Northover09ca33e2016-04-22 23:23:31 +00007517 } else if (Arch == Triple::aarch64 ||
7518 (Arch == Triple::arm && !IsThumb)) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00007519 uint32_t opcode = (*(Bytes.data() + Index) & 0xff) |
7520 (*(Bytes.data() + Index + 1) & 0xff) << 8 |
7521 (*(Bytes.data() + Index + 2) & 0xff) << 16 |
7522 (*(Bytes.data() + Index + 3) & 0xff) << 24;
7523 outs() << format("\t.long\t0x%08x\n", opcode);
7524 Size = 4;
Tim Northover09ca33e2016-04-22 23:23:31 +00007525 } else if (Arch == Triple::arm) {
7526 assert(IsThumb && "ARM mode should have been dealt with above");
7527 uint32_t opcode = (*(Bytes.data() + Index) & 0xff) |
7528 (*(Bytes.data() + Index + 1) & 0xff) << 8;
7529 outs() << format("\t.short\t0x%04x\n", opcode);
7530 Size = 2;
7531 } else{
Jonas Devliegheree787efd2018-11-11 22:12:04 +00007532 WithColor::warning(errs(), "llvm-objdump")
7533 << "invalid instruction encoding\n";
Kevin Enderby6f326ce2014-10-23 19:37:31 +00007534 if (Size == 0)
7535 Size = 1; // skip illegible bytes
7536 }
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007537 }
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007538 }
Kevin Enderbyc138da32017-02-06 18:43:18 +00007539 // Now that we are done disassembled the first symbol set the bool that
7540 // were doing this to false.
7541 FirstSymbol = false;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007542 }
Ahmed Bougachaaa790682013-05-24 01:07:04 +00007543 if (!symbolTableWorked) {
Rafael Espindola80291272014-10-08 15:28:58 +00007544 // Reading the symbol table didn't work, disassemble the whole section.
7545 uint64_t SectAddress = Sections[SectIdx].getAddress();
7546 uint64_t SectSize = Sections[SectIdx].getSize();
Kevin Enderbybadd1002012-05-18 00:13:56 +00007547 uint64_t InstSize;
7548 for (uint64_t Index = 0; Index < SectSize; Index += InstSize) {
Bill Wendling4e68e062012-07-19 00:17:40 +00007549 MCInst Inst;
Kevin Enderbybadd1002012-05-18 00:13:56 +00007550
Kevin Enderbybf246f52014-09-24 23:08:22 +00007551 uint64_t PC = SectAddress + Index;
Kevin Enderby02d3a372017-01-31 18:09:10 +00007552 SmallVector<char, 64> AnnotationsBytes;
7553 raw_svector_ostream Annotations(AnnotationsBytes);
Rafael Espindola7fc5b872014-11-12 02:04:27 +00007554 if (DisAsm->getInstruction(Inst, InstSize, Bytes.slice(Index), PC,
Kevin Enderby02d3a372017-01-31 18:09:10 +00007555 DebugOut, Annotations)) {
Kevin Enderbyab5e6c92015-03-17 21:07:39 +00007556 if (!NoLeadingAddr) {
7557 if (FullLeadingAddr) {
7558 if (MachOOF->is64Bit())
7559 outs() << format("%016" PRIx64, PC);
7560 else
7561 outs() << format("%08" PRIx64, PC);
7562 } else {
7563 outs() << format("%8" PRIx64 ":", PC);
7564 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00007565 }
Kevin Enderby4b627be2016-04-28 20:14:13 +00007566 if (!NoShowRawInsn || Arch == Triple::arm) {
Kevin Enderbybf246f52014-09-24 23:08:22 +00007567 outs() << "\t";
Craig Topper0013be12015-09-21 05:32:41 +00007568 dumpBytes(makeArrayRef(Bytes.data() + Index, InstSize), outs());
Kevin Enderbybf246f52014-09-24 23:08:22 +00007569 }
Kevin Enderby02d3a372017-01-31 18:09:10 +00007570 StringRef AnnotationsStr = Annotations.str();
7571 IP->printInst(&Inst, outs(), AnnotationsStr, *STI);
Bill Wendling4e68e062012-07-19 00:17:40 +00007572 outs() << "\n";
7573 } else {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00007574 unsigned int Arch = MachOOF->getArch();
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007575 if (Arch == Triple::x86_64 || Arch == Triple::x86) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00007576 outs() << format("\t.byte 0x%02x #bad opcode\n",
7577 *(Bytes.data() + Index) & 0xff);
7578 InstSize = 1; // skip exactly one illegible byte and move on.
7579 } else {
Jonas Devliegheree787efd2018-11-11 22:12:04 +00007580 WithColor::warning(errs(), "llvm-objdump")
7581 << "invalid instruction encoding\n";
Kevin Enderby6f326ce2014-10-23 19:37:31 +00007582 if (InstSize == 0)
7583 InstSize = 1; // skip illegible bytes
7584 }
Bill Wendling4e68e062012-07-19 00:17:40 +00007585 }
Kevin Enderbybadd1002012-05-18 00:13:56 +00007586 }
7587 }
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00007588 // The TripleName's need to be reset if we are called again for a different
7589 // archtecture.
7590 TripleName = "";
7591 ThumbTripleName = "";
7592
Kevin Enderby04bf6932014-10-28 23:39:46 +00007593 if (SymbolizerInfo.demangled_name != nullptr)
7594 free(SymbolizerInfo.demangled_name);
Kevin Enderby930fdc72014-11-06 19:00:13 +00007595 if (ThumbSymbolizerInfo.demangled_name != nullptr)
7596 free(ThumbSymbolizerInfo.demangled_name);
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007597 }
7598}
Tim Northover4bd286a2014-08-01 13:07:19 +00007599
Tim Northover39c70bb2014-08-12 11:52:59 +00007600//===----------------------------------------------------------------------===//
7601// __compact_unwind section dumping
7602//===----------------------------------------------------------------------===//
7603
Tim Northover4bd286a2014-08-01 13:07:19 +00007604namespace {
Tim Northover39c70bb2014-08-12 11:52:59 +00007605
Tim Northover3a4e1c72018-01-23 13:51:57 +00007606template <typename T>
7607static uint64_t read(StringRef Contents, ptrdiff_t Offset) {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007608 using llvm::support::little;
7609 using llvm::support::unaligned;
Tim Northover39c70bb2014-08-12 11:52:59 +00007610
Tim Northover3a4e1c72018-01-23 13:51:57 +00007611 if (Offset + sizeof(T) > Contents.size()) {
7612 outs() << "warning: attempt to read past end of buffer\n";
7613 return T();
7614 }
7615
7616 uint64_t Val =
7617 support::endian::read<T, little, unaligned>(Contents.data() + Offset);
7618 return Val;
7619}
7620
7621template <typename T>
7622static uint64_t readNext(StringRef Contents, ptrdiff_t &Offset) {
7623 T Val = read<T>(Contents, Offset);
7624 Offset += sizeof(T);
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007625 return Val;
7626}
Tim Northover39c70bb2014-08-12 11:52:59 +00007627
Tim Northover4bd286a2014-08-01 13:07:19 +00007628struct CompactUnwindEntry {
7629 uint32_t OffsetInSection;
7630
7631 uint64_t FunctionAddr;
7632 uint32_t Length;
7633 uint32_t CompactEncoding;
7634 uint64_t PersonalityAddr;
7635 uint64_t LSDAAddr;
7636
7637 RelocationRef FunctionReloc;
7638 RelocationRef PersonalityReloc;
7639 RelocationRef LSDAReloc;
7640
7641 CompactUnwindEntry(StringRef Contents, unsigned Offset, bool Is64)
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007642 : OffsetInSection(Offset) {
Tim Northover4bd286a2014-08-01 13:07:19 +00007643 if (Is64)
Tim Northover3a4e1c72018-01-23 13:51:57 +00007644 read<uint64_t>(Contents, Offset);
Tim Northover4bd286a2014-08-01 13:07:19 +00007645 else
Tim Northover3a4e1c72018-01-23 13:51:57 +00007646 read<uint32_t>(Contents, Offset);
Tim Northover4bd286a2014-08-01 13:07:19 +00007647 }
7648
7649private:
Tim Northover3a4e1c72018-01-23 13:51:57 +00007650 template <typename UIntPtr> void read(StringRef Contents, ptrdiff_t Offset) {
7651 FunctionAddr = readNext<UIntPtr>(Contents, Offset);
7652 Length = readNext<uint32_t>(Contents, Offset);
7653 CompactEncoding = readNext<uint32_t>(Contents, Offset);
7654 PersonalityAddr = readNext<UIntPtr>(Contents, Offset);
7655 LSDAAddr = readNext<UIntPtr>(Contents, Offset);
Tim Northover4bd286a2014-08-01 13:07:19 +00007656 }
7657};
7658}
7659
7660/// Given a relocation from __compact_unwind, consisting of the RelocationRef
7661/// and data being relocated, determine the best base Name and Addend to use for
7662/// display purposes.
7663///
7664/// 1. An Extern relocation will directly reference a symbol (and the data is
7665/// then already an addend), so use that.
7666/// 2. Otherwise the data is an offset in the object file's layout; try to find
7667// a symbol before it in the same section, and use the offset from there.
7668/// 3. Finally, if all that fails, fall back to an offset from the start of the
7669/// referenced section.
7670static void findUnwindRelocNameAddend(const MachOObjectFile *Obj,
7671 std::map<uint64_t, SymbolRef> &Symbols,
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007672 const RelocationRef &Reloc, uint64_t Addr,
Tim Northover4bd286a2014-08-01 13:07:19 +00007673 StringRef &Name, uint64_t &Addend) {
7674 if (Reloc.getSymbol() != Obj->symbol_end()) {
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00007675 Expected<StringRef> NameOrErr = Reloc.getSymbol()->getName();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00007676 if (!NameOrErr)
7677 report_error(Obj->getFileName(), NameOrErr.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00007678 Name = *NameOrErr;
Tim Northover4bd286a2014-08-01 13:07:19 +00007679 Addend = Addr;
7680 return;
7681 }
7682
7683 auto RE = Obj->getRelocation(Reloc.getRawDataRefImpl());
Keno Fischerc780e8e2015-05-21 21:24:32 +00007684 SectionRef RelocSection = Obj->getAnyRelocationSection(RE);
Tim Northover4bd286a2014-08-01 13:07:19 +00007685
Rafael Espindola80291272014-10-08 15:28:58 +00007686 uint64_t SectionAddr = RelocSection.getAddress();
Tim Northover4bd286a2014-08-01 13:07:19 +00007687
7688 auto Sym = Symbols.upper_bound(Addr);
7689 if (Sym == Symbols.begin()) {
7690 // The first symbol in the object is after this reference, the best we can
7691 // do is section-relative notation.
7692 RelocSection.getName(Name);
7693 Addend = Addr - SectionAddr;
7694 return;
7695 }
7696
7697 // Go back one so that SymbolAddress <= Addr.
7698 --Sym;
7699
Kevin Enderby7bd8d992016-05-02 20:28:12 +00007700 auto SectOrErr = Sym->second.getSection();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00007701 if (!SectOrErr)
7702 report_error(Obj->getFileName(), SectOrErr.takeError());
Kevin Enderby7bd8d992016-05-02 20:28:12 +00007703 section_iterator SymSection = *SectOrErr;
Tim Northover4bd286a2014-08-01 13:07:19 +00007704 if (RelocSection == *SymSection) {
7705 // There's a valid symbol in the same section before this reference.
Kevin Enderby81e8b7d2016-04-20 21:24:34 +00007706 Expected<StringRef> NameOrErr = Sym->second.getName();
Kevin Enderby844c4ac2016-11-15 23:07:41 +00007707 if (!NameOrErr)
7708 report_error(Obj->getFileName(), NameOrErr.takeError());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00007709 Name = *NameOrErr;
Tim Northover4bd286a2014-08-01 13:07:19 +00007710 Addend = Addr - Sym->first;
7711 return;
7712 }
7713
7714 // There is a symbol before this reference, but it's in a different
7715 // section. Probably not helpful to mention it, so use the section name.
7716 RelocSection.getName(Name);
7717 Addend = Addr - SectionAddr;
7718}
7719
7720static void printUnwindRelocDest(const MachOObjectFile *Obj,
7721 std::map<uint64_t, SymbolRef> &Symbols,
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007722 const RelocationRef &Reloc, uint64_t Addr) {
Tim Northover4bd286a2014-08-01 13:07:19 +00007723 StringRef Name;
7724 uint64_t Addend;
7725
Rafael Espindola854038e2015-06-26 14:51:16 +00007726 if (!Reloc.getObject())
Tim Northover0b0add52014-09-09 10:45:06 +00007727 return;
7728
Tim Northover4bd286a2014-08-01 13:07:19 +00007729 findUnwindRelocNameAddend(Obj, Symbols, Reloc, Addr, Name, Addend);
7730
7731 outs() << Name;
7732 if (Addend)
Tim Northover63a25622014-08-11 09:14:06 +00007733 outs() << " + " << format("0x%" PRIx64, Addend);
Tim Northover4bd286a2014-08-01 13:07:19 +00007734}
7735
7736static void
7737printMachOCompactUnwindSection(const MachOObjectFile *Obj,
7738 std::map<uint64_t, SymbolRef> &Symbols,
7739 const SectionRef &CompactUnwind) {
7740
Tim Northoverbf55f7e2016-11-15 20:26:01 +00007741 if (!Obj->isLittleEndian()) {
7742 outs() << "Skipping big-endian __compact_unwind section\n";
7743 return;
7744 }
Tim Northover4bd286a2014-08-01 13:07:19 +00007745
7746 bool Is64 = Obj->is64Bit();
7747 uint32_t PointerSize = Is64 ? sizeof(uint64_t) : sizeof(uint32_t);
7748 uint32_t EntrySize = 3 * PointerSize + 2 * sizeof(uint32_t);
7749
7750 StringRef Contents;
7751 CompactUnwind.getContents(Contents);
7752
7753 SmallVector<CompactUnwindEntry, 4> CompactUnwinds;
7754
7755 // First populate the initial raw offsets, encodings and so on from the entry.
7756 for (unsigned Offset = 0; Offset < Contents.size(); Offset += EntrySize) {
Tim Northover3a4e1c72018-01-23 13:51:57 +00007757 CompactUnwindEntry Entry(Contents, Offset, Is64);
Tim Northover4bd286a2014-08-01 13:07:19 +00007758 CompactUnwinds.push_back(Entry);
7759 }
7760
7761 // Next we need to look at the relocations to find out what objects are
7762 // actually being referred to.
7763 for (const RelocationRef &Reloc : CompactUnwind.relocations()) {
Rafael Espindola96d071c2015-06-29 23:29:12 +00007764 uint64_t RelocAddress = Reloc.getOffset();
Tim Northover4bd286a2014-08-01 13:07:19 +00007765
7766 uint32_t EntryIdx = RelocAddress / EntrySize;
7767 uint32_t OffsetInEntry = RelocAddress - EntryIdx * EntrySize;
7768 CompactUnwindEntry &Entry = CompactUnwinds[EntryIdx];
7769
7770 if (OffsetInEntry == 0)
7771 Entry.FunctionReloc = Reloc;
7772 else if (OffsetInEntry == PointerSize + 2 * sizeof(uint32_t))
7773 Entry.PersonalityReloc = Reloc;
7774 else if (OffsetInEntry == 2 * PointerSize + 2 * sizeof(uint32_t))
7775 Entry.LSDAReloc = Reloc;
Tim Northoverbf55f7e2016-11-15 20:26:01 +00007776 else {
7777 outs() << "Invalid relocation in __compact_unwind section\n";
7778 return;
7779 }
Tim Northover4bd286a2014-08-01 13:07:19 +00007780 }
7781
7782 // Finally, we're ready to print the data we've gathered.
7783 outs() << "Contents of __compact_unwind section:\n";
7784 for (auto &Entry : CompactUnwinds) {
Tim Northover06af2602014-08-08 12:08:51 +00007785 outs() << " Entry at offset "
7786 << format("0x%" PRIx32, Entry.OffsetInSection) << ":\n";
Tim Northover4bd286a2014-08-01 13:07:19 +00007787
7788 // 1. Start of the region this entry applies to.
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007789 outs() << " start: " << format("0x%" PRIx64,
7790 Entry.FunctionAddr) << ' ';
7791 printUnwindRelocDest(Obj, Symbols, Entry.FunctionReloc, Entry.FunctionAddr);
Tim Northover4bd286a2014-08-01 13:07:19 +00007792 outs() << '\n';
7793
7794 // 2. Length of the region this entry applies to.
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007795 outs() << " length: " << format("0x%" PRIx32, Entry.Length)
7796 << '\n';
Tim Northover4bd286a2014-08-01 13:07:19 +00007797 // 3. The 32-bit compact encoding.
7798 outs() << " compact encoding: "
Tim Northoverb911bf82014-08-08 12:00:09 +00007799 << format("0x%08" PRIx32, Entry.CompactEncoding) << '\n';
Tim Northover4bd286a2014-08-01 13:07:19 +00007800
7801 // 4. The personality function, if present.
Rafael Espindola854038e2015-06-26 14:51:16 +00007802 if (Entry.PersonalityReloc.getObject()) {
Tim Northover4bd286a2014-08-01 13:07:19 +00007803 outs() << " personality function: "
Tim Northoverb911bf82014-08-08 12:00:09 +00007804 << format("0x%" PRIx64, Entry.PersonalityAddr) << ' ';
Tim Northover4bd286a2014-08-01 13:07:19 +00007805 printUnwindRelocDest(Obj, Symbols, Entry.PersonalityReloc,
7806 Entry.PersonalityAddr);
7807 outs() << '\n';
7808 }
7809
7810 // 5. This entry's language-specific data area.
Rafael Espindola854038e2015-06-26 14:51:16 +00007811 if (Entry.LSDAReloc.getObject()) {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007812 outs() << " LSDA: " << format("0x%" PRIx64,
7813 Entry.LSDAAddr) << ' ';
Tim Northover4bd286a2014-08-01 13:07:19 +00007814 printUnwindRelocDest(Obj, Symbols, Entry.LSDAReloc, Entry.LSDAAddr);
7815 outs() << '\n';
7816 }
7817 }
7818}
7819
Tim Northover39c70bb2014-08-12 11:52:59 +00007820//===----------------------------------------------------------------------===//
7821// __unwind_info section dumping
7822//===----------------------------------------------------------------------===//
7823
Tim Northover3a4e1c72018-01-23 13:51:57 +00007824static void printRegularSecondLevelUnwindPage(StringRef PageData) {
7825 ptrdiff_t Pos = 0;
7826 uint32_t Kind = readNext<uint32_t>(PageData, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007827 (void)Kind;
7828 assert(Kind == 2 && "kind for a regular 2nd level index should be 2");
7829
Tim Northover3a4e1c72018-01-23 13:51:57 +00007830 uint16_t EntriesStart = readNext<uint16_t>(PageData, Pos);
7831 uint16_t NumEntries = readNext<uint16_t>(PageData, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007832
Tim Northover3a4e1c72018-01-23 13:51:57 +00007833 Pos = EntriesStart;
Tim Northover39c70bb2014-08-12 11:52:59 +00007834 for (unsigned i = 0; i < NumEntries; ++i) {
Tim Northover3a4e1c72018-01-23 13:51:57 +00007835 uint32_t FunctionOffset = readNext<uint32_t>(PageData, Pos);
7836 uint32_t Encoding = readNext<uint32_t>(PageData, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007837
7838 outs() << " [" << i << "]: "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007839 << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
7840 << ", "
7841 << "encoding=" << format("0x%08" PRIx32, Encoding) << '\n';
Tim Northover39c70bb2014-08-12 11:52:59 +00007842 }
7843}
7844
7845static void printCompressedSecondLevelUnwindPage(
Tim Northover3a4e1c72018-01-23 13:51:57 +00007846 StringRef PageData, uint32_t FunctionBase,
Tim Northover39c70bb2014-08-12 11:52:59 +00007847 const SmallVectorImpl<uint32_t> &CommonEncodings) {
Tim Northover3a4e1c72018-01-23 13:51:57 +00007848 ptrdiff_t Pos = 0;
7849 uint32_t Kind = readNext<uint32_t>(PageData, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007850 (void)Kind;
7851 assert(Kind == 3 && "kind for a compressed 2nd level index should be 3");
7852
Tim Northover3a4e1c72018-01-23 13:51:57 +00007853 uint16_t EntriesStart = readNext<uint16_t>(PageData, Pos);
7854 uint16_t NumEntries = readNext<uint16_t>(PageData, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007855
Tim Northover3a4e1c72018-01-23 13:51:57 +00007856 uint16_t EncodingsStart = readNext<uint16_t>(PageData, Pos);
7857 readNext<uint16_t>(PageData, Pos);
7858 StringRef PageEncodings = PageData.substr(EncodingsStart, StringRef::npos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007859
Tim Northover3a4e1c72018-01-23 13:51:57 +00007860 Pos = EntriesStart;
Tim Northover39c70bb2014-08-12 11:52:59 +00007861 for (unsigned i = 0; i < NumEntries; ++i) {
Tim Northover3a4e1c72018-01-23 13:51:57 +00007862 uint32_t Entry = readNext<uint32_t>(PageData, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007863 uint32_t FunctionOffset = FunctionBase + (Entry & 0xffffff);
7864 uint32_t EncodingIdx = Entry >> 24;
7865
7866 uint32_t Encoding;
7867 if (EncodingIdx < CommonEncodings.size())
7868 Encoding = CommonEncodings[EncodingIdx];
7869 else
Tim Northover3a4e1c72018-01-23 13:51:57 +00007870 Encoding = read<uint32_t>(PageEncodings,
7871 sizeof(uint32_t) *
7872 (EncodingIdx - CommonEncodings.size()));
Tim Northover39c70bb2014-08-12 11:52:59 +00007873
7874 outs() << " [" << i << "]: "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007875 << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
7876 << ", "
7877 << "encoding[" << EncodingIdx
7878 << "]=" << format("0x%08" PRIx32, Encoding) << '\n';
Tim Northover39c70bb2014-08-12 11:52:59 +00007879 }
7880}
7881
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007882static void printMachOUnwindInfoSection(const MachOObjectFile *Obj,
7883 std::map<uint64_t, SymbolRef> &Symbols,
7884 const SectionRef &UnwindInfo) {
Tim Northover39c70bb2014-08-12 11:52:59 +00007885
Tim Northoverbf55f7e2016-11-15 20:26:01 +00007886 if (!Obj->isLittleEndian()) {
7887 outs() << "Skipping big-endian __unwind_info section\n";
7888 return;
7889 }
Tim Northover39c70bb2014-08-12 11:52:59 +00007890
7891 outs() << "Contents of __unwind_info section:\n";
7892
7893 StringRef Contents;
7894 UnwindInfo.getContents(Contents);
Tim Northover3a4e1c72018-01-23 13:51:57 +00007895 ptrdiff_t Pos = 0;
Tim Northover39c70bb2014-08-12 11:52:59 +00007896
7897 //===----------------------------------
7898 // Section header
7899 //===----------------------------------
7900
Tim Northover3a4e1c72018-01-23 13:51:57 +00007901 uint32_t Version = readNext<uint32_t>(Contents, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007902 outs() << " Version: "
7903 << format("0x%" PRIx32, Version) << '\n';
Tim Northoverbf55f7e2016-11-15 20:26:01 +00007904 if (Version != 1) {
7905 outs() << " Skipping section with unknown version\n";
7906 return;
7907 }
Tim Northover39c70bb2014-08-12 11:52:59 +00007908
Tim Northover3a4e1c72018-01-23 13:51:57 +00007909 uint32_t CommonEncodingsStart = readNext<uint32_t>(Contents, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007910 outs() << " Common encodings array section offset: "
7911 << format("0x%" PRIx32, CommonEncodingsStart) << '\n';
Tim Northover3a4e1c72018-01-23 13:51:57 +00007912 uint32_t NumCommonEncodings = readNext<uint32_t>(Contents, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007913 outs() << " Number of common encodings in array: "
7914 << format("0x%" PRIx32, NumCommonEncodings) << '\n';
7915
Tim Northover3a4e1c72018-01-23 13:51:57 +00007916 uint32_t PersonalitiesStart = readNext<uint32_t>(Contents, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007917 outs() << " Personality function array section offset: "
7918 << format("0x%" PRIx32, PersonalitiesStart) << '\n';
Tim Northover3a4e1c72018-01-23 13:51:57 +00007919 uint32_t NumPersonalities = readNext<uint32_t>(Contents, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007920 outs() << " Number of personality functions in array: "
7921 << format("0x%" PRIx32, NumPersonalities) << '\n';
7922
Tim Northover3a4e1c72018-01-23 13:51:57 +00007923 uint32_t IndicesStart = readNext<uint32_t>(Contents, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007924 outs() << " Index array section offset: "
7925 << format("0x%" PRIx32, IndicesStart) << '\n';
Tim Northover3a4e1c72018-01-23 13:51:57 +00007926 uint32_t NumIndices = readNext<uint32_t>(Contents, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007927 outs() << " Number of indices in array: "
7928 << format("0x%" PRIx32, NumIndices) << '\n';
7929
7930 //===----------------------------------
7931 // A shared list of common encodings
7932 //===----------------------------------
7933
7934 // These occupy indices in the range [0, N] whenever an encoding is referenced
7935 // from a compressed 2nd level index table. In practice the linker only
7936 // creates ~128 of these, so that indices are available to embed encodings in
7937 // the 2nd level index.
7938
7939 SmallVector<uint32_t, 64> CommonEncodings;
7940 outs() << " Common encodings: (count = " << NumCommonEncodings << ")\n";
Tim Northover3a4e1c72018-01-23 13:51:57 +00007941 Pos = CommonEncodingsStart;
Tim Northover39c70bb2014-08-12 11:52:59 +00007942 for (unsigned i = 0; i < NumCommonEncodings; ++i) {
Tim Northover3a4e1c72018-01-23 13:51:57 +00007943 uint32_t Encoding = readNext<uint32_t>(Contents, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007944 CommonEncodings.push_back(Encoding);
7945
7946 outs() << " encoding[" << i << "]: " << format("0x%08" PRIx32, Encoding)
7947 << '\n';
7948 }
7949
Tim Northover39c70bb2014-08-12 11:52:59 +00007950 //===----------------------------------
7951 // Personality functions used in this executable
7952 //===----------------------------------
7953
7954 // There should be only a handful of these (one per source language,
7955 // roughly). Particularly since they only get 2 bits in the compact encoding.
7956
7957 outs() << " Personality functions: (count = " << NumPersonalities << ")\n";
Tim Northover3a4e1c72018-01-23 13:51:57 +00007958 Pos = PersonalitiesStart;
Tim Northover39c70bb2014-08-12 11:52:59 +00007959 for (unsigned i = 0; i < NumPersonalities; ++i) {
Tim Northover3a4e1c72018-01-23 13:51:57 +00007960 uint32_t PersonalityFn = readNext<uint32_t>(Contents, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007961 outs() << " personality[" << i + 1
7962 << "]: " << format("0x%08" PRIx32, PersonalityFn) << '\n';
7963 }
7964
7965 //===----------------------------------
7966 // The level 1 index entries
7967 //===----------------------------------
7968
7969 // These specify an approximate place to start searching for the more detailed
7970 // information, sorted by PC.
7971
7972 struct IndexEntry {
7973 uint32_t FunctionOffset;
7974 uint32_t SecondLevelPageStart;
7975 uint32_t LSDAStart;
7976 };
7977
7978 SmallVector<IndexEntry, 4> IndexEntries;
7979
7980 outs() << " Top level indices: (count = " << NumIndices << ")\n";
Tim Northover3a4e1c72018-01-23 13:51:57 +00007981 Pos = IndicesStart;
Tim Northover39c70bb2014-08-12 11:52:59 +00007982 for (unsigned i = 0; i < NumIndices; ++i) {
7983 IndexEntry Entry;
7984
Tim Northover3a4e1c72018-01-23 13:51:57 +00007985 Entry.FunctionOffset = readNext<uint32_t>(Contents, Pos);
7986 Entry.SecondLevelPageStart = readNext<uint32_t>(Contents, Pos);
7987 Entry.LSDAStart = readNext<uint32_t>(Contents, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007988 IndexEntries.push_back(Entry);
7989
7990 outs() << " [" << i << "]: "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007991 << "function offset=" << format("0x%08" PRIx32, Entry.FunctionOffset)
7992 << ", "
Tim Northover39c70bb2014-08-12 11:52:59 +00007993 << "2nd level page offset="
7994 << format("0x%08" PRIx32, Entry.SecondLevelPageStart) << ", "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007995 << "LSDA offset=" << format("0x%08" PRIx32, Entry.LSDAStart) << '\n';
Tim Northover39c70bb2014-08-12 11:52:59 +00007996 }
7997
Tim Northover39c70bb2014-08-12 11:52:59 +00007998 //===----------------------------------
7999 // Next come the LSDA tables
8000 //===----------------------------------
8001
8002 // The LSDA layout is rather implicit: it's a contiguous array of entries from
8003 // the first top-level index's LSDAOffset to the last (sentinel).
8004
8005 outs() << " LSDA descriptors:\n";
Tim Northover3a4e1c72018-01-23 13:51:57 +00008006 Pos = IndexEntries[0].LSDAStart;
8007 const uint32_t LSDASize = 2 * sizeof(uint32_t);
8008 int NumLSDAs =
8009 (IndexEntries.back().LSDAStart - IndexEntries[0].LSDAStart) / LSDASize;
8010
Tim Northover39c70bb2014-08-12 11:52:59 +00008011 for (int i = 0; i < NumLSDAs; ++i) {
Tim Northover3a4e1c72018-01-23 13:51:57 +00008012 uint32_t FunctionOffset = readNext<uint32_t>(Contents, Pos);
8013 uint32_t LSDAOffset = readNext<uint32_t>(Contents, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00008014 outs() << " [" << i << "]: "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00008015 << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
8016 << ", "
8017 << "LSDA offset=" << format("0x%08" PRIx32, LSDAOffset) << '\n';
Tim Northover39c70bb2014-08-12 11:52:59 +00008018 }
8019
8020 //===----------------------------------
8021 // Finally, the 2nd level indices
8022 //===----------------------------------
8023
8024 // Generally these are 4K in size, and have 2 possible forms:
8025 // + Regular stores up to 511 entries with disparate encodings
8026 // + Compressed stores up to 1021 entries if few enough compact encoding
8027 // values are used.
8028 outs() << " Second level indices:\n";
8029 for (unsigned i = 0; i < IndexEntries.size() - 1; ++i) {
8030 // The final sentinel top-level index has no associated 2nd level page
8031 if (IndexEntries[i].SecondLevelPageStart == 0)
8032 break;
8033
8034 outs() << " Second level index[" << i << "]: "
8035 << "offset in section="
8036 << format("0x%08" PRIx32, IndexEntries[i].SecondLevelPageStart)
8037 << ", "
8038 << "base function offset="
8039 << format("0x%08" PRIx32, IndexEntries[i].FunctionOffset) << '\n';
8040
Tim Northover3a4e1c72018-01-23 13:51:57 +00008041 Pos = IndexEntries[i].SecondLevelPageStart;
8042 if (Pos + sizeof(uint32_t) > Contents.size()) {
8043 outs() << "warning: invalid offset for second level page: " << Pos << '\n';
8044 continue;
8045 }
8046
8047 uint32_t Kind =
8048 *reinterpret_cast<const support::ulittle32_t *>(Contents.data() + Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00008049 if (Kind == 2)
Tim Northover3a4e1c72018-01-23 13:51:57 +00008050 printRegularSecondLevelUnwindPage(Contents.substr(Pos, 4096));
Tim Northover39c70bb2014-08-12 11:52:59 +00008051 else if (Kind == 3)
Tim Northover3a4e1c72018-01-23 13:51:57 +00008052 printCompressedSecondLevelUnwindPage(Contents.substr(Pos, 4096),
8053 IndexEntries[i].FunctionOffset,
Tim Northover39c70bb2014-08-12 11:52:59 +00008054 CommonEncodings);
8055 else
Tim Northoverbf55f7e2016-11-15 20:26:01 +00008056 outs() << " Skipping 2nd level page with unknown kind " << Kind
8057 << '\n';
Tim Northover39c70bb2014-08-12 11:52:59 +00008058 }
8059}
8060
Tim Northover4bd286a2014-08-01 13:07:19 +00008061void llvm::printMachOUnwindInfo(const MachOObjectFile *Obj) {
8062 std::map<uint64_t, SymbolRef> Symbols;
8063 for (const SymbolRef &SymRef : Obj->symbols()) {
8064 // Discard any undefined or absolute symbols. They're not going to take part
8065 // in the convenience lookup for unwind info and just take up resources.
Kevin Enderby7bd8d992016-05-02 20:28:12 +00008066 auto SectOrErr = SymRef.getSection();
8067 if (!SectOrErr) {
8068 // TODO: Actually report errors helpfully.
8069 consumeError(SectOrErr.takeError());
8070 continue;
8071 }
8072 section_iterator Section = *SectOrErr;
Tim Northover4bd286a2014-08-01 13:07:19 +00008073 if (Section == Obj->section_end())
8074 continue;
8075
Rafael Espindoladea00162015-07-03 17:44:18 +00008076 uint64_t Addr = SymRef.getValue();
Tim Northover4bd286a2014-08-01 13:07:19 +00008077 Symbols.insert(std::make_pair(Addr, SymRef));
8078 }
8079
8080 for (const SectionRef &Section : Obj->sections()) {
8081 StringRef SectName;
8082 Section.getName(SectName);
8083 if (SectName == "__compact_unwind")
8084 printMachOCompactUnwindSection(Obj, Symbols, Section);
8085 else if (SectName == "__unwind_info")
Tim Northover39c70bb2014-08-12 11:52:59 +00008086 printMachOUnwindInfoSection(Obj, Symbols, Section);
Tim Northover4bd286a2014-08-01 13:07:19 +00008087 }
8088}
Kevin Enderbyb76d3862014-08-22 20:35:18 +00008089
8090static void PrintMachHeader(uint32_t magic, uint32_t cputype,
8091 uint32_t cpusubtype, uint32_t filetype,
8092 uint32_t ncmds, uint32_t sizeofcmds, uint32_t flags,
8093 bool verbose) {
8094 outs() << "Mach header\n";
8095 outs() << " magic cputype cpusubtype caps filetype ncmds "
8096 "sizeofcmds flags\n";
8097 if (verbose) {
8098 if (magic == MachO::MH_MAGIC)
8099 outs() << " MH_MAGIC";
8100 else if (magic == MachO::MH_MAGIC_64)
8101 outs() << "MH_MAGIC_64";
8102 else
8103 outs() << format(" 0x%08" PRIx32, magic);
8104 switch (cputype) {
8105 case MachO::CPU_TYPE_I386:
8106 outs() << " I386";
8107 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
8108 case MachO::CPU_SUBTYPE_I386_ALL:
8109 outs() << " ALL";
8110 break;
8111 default:
8112 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
8113 break;
8114 }
8115 break;
8116 case MachO::CPU_TYPE_X86_64:
8117 outs() << " X86_64";
Kevin Enderby131d1772015-01-09 19:22:37 +00008118 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
8119 case MachO::CPU_SUBTYPE_X86_64_ALL:
8120 outs() << " ALL";
8121 break;
8122 case MachO::CPU_SUBTYPE_X86_64_H:
8123 outs() << " Haswell";
8124 break;
8125 default:
8126 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
8127 break;
8128 }
Kevin Enderbyb76d3862014-08-22 20:35:18 +00008129 break;
8130 case MachO::CPU_TYPE_ARM:
8131 outs() << " ARM";
8132 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
8133 case MachO::CPU_SUBTYPE_ARM_ALL:
8134 outs() << " ALL";
8135 break;
8136 case MachO::CPU_SUBTYPE_ARM_V4T:
8137 outs() << " V4T";
8138 break;
8139 case MachO::CPU_SUBTYPE_ARM_V5TEJ:
8140 outs() << " V5TEJ";
8141 break;
8142 case MachO::CPU_SUBTYPE_ARM_XSCALE:
8143 outs() << " XSCALE";
8144 break;
8145 case MachO::CPU_SUBTYPE_ARM_V6:
8146 outs() << " V6";
8147 break;
8148 case MachO::CPU_SUBTYPE_ARM_V6M:
8149 outs() << " V6M";
8150 break;
8151 case MachO::CPU_SUBTYPE_ARM_V7:
8152 outs() << " V7";
8153 break;
8154 case MachO::CPU_SUBTYPE_ARM_V7EM:
8155 outs() << " V7EM";
8156 break;
8157 case MachO::CPU_SUBTYPE_ARM_V7K:
8158 outs() << " V7K";
8159 break;
8160 case MachO::CPU_SUBTYPE_ARM_V7M:
8161 outs() << " V7M";
8162 break;
8163 case MachO::CPU_SUBTYPE_ARM_V7S:
8164 outs() << " V7S";
8165 break;
8166 default:
8167 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
8168 break;
8169 }
8170 break;
8171 case MachO::CPU_TYPE_ARM64:
8172 outs() << " ARM64";
8173 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
8174 case MachO::CPU_SUBTYPE_ARM64_ALL:
8175 outs() << " ALL";
8176 break;
8177 default:
8178 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
8179 break;
8180 }
8181 break;
8182 case MachO::CPU_TYPE_POWERPC:
8183 outs() << " PPC";
8184 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
8185 case MachO::CPU_SUBTYPE_POWERPC_ALL:
8186 outs() << " ALL";
8187 break;
8188 default:
8189 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
8190 break;
8191 }
8192 break;
8193 case MachO::CPU_TYPE_POWERPC64:
8194 outs() << " PPC64";
8195 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
8196 case MachO::CPU_SUBTYPE_POWERPC_ALL:
8197 outs() << " ALL";
8198 break;
8199 default:
8200 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
8201 break;
8202 }
8203 break;
Kevin Enderby40fdbf82016-01-26 18:20:49 +00008204 default:
8205 outs() << format(" %7d", cputype);
8206 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
8207 break;
Kevin Enderbyb76d3862014-08-22 20:35:18 +00008208 }
8209 if ((cpusubtype & MachO::CPU_SUBTYPE_MASK) == MachO::CPU_SUBTYPE_LIB64) {
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008210 outs() << " LIB64";
Kevin Enderbyb76d3862014-08-22 20:35:18 +00008211 } else {
8212 outs() << format(" 0x%02" PRIx32,
8213 (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24);
8214 }
8215 switch (filetype) {
8216 case MachO::MH_OBJECT:
8217 outs() << " OBJECT";
8218 break;
8219 case MachO::MH_EXECUTE:
8220 outs() << " EXECUTE";
8221 break;
8222 case MachO::MH_FVMLIB:
8223 outs() << " FVMLIB";
8224 break;
8225 case MachO::MH_CORE:
8226 outs() << " CORE";
8227 break;
8228 case MachO::MH_PRELOAD:
8229 outs() << " PRELOAD";
8230 break;
8231 case MachO::MH_DYLIB:
8232 outs() << " DYLIB";
8233 break;
8234 case MachO::MH_DYLIB_STUB:
8235 outs() << " DYLIB_STUB";
8236 break;
8237 case MachO::MH_DYLINKER:
8238 outs() << " DYLINKER";
8239 break;
8240 case MachO::MH_BUNDLE:
8241 outs() << " BUNDLE";
8242 break;
8243 case MachO::MH_DSYM:
8244 outs() << " DSYM";
8245 break;
8246 case MachO::MH_KEXT_BUNDLE:
8247 outs() << " KEXTBUNDLE";
8248 break;
8249 default:
8250 outs() << format(" %10u", filetype);
8251 break;
8252 }
8253 outs() << format(" %5u", ncmds);
8254 outs() << format(" %10u", sizeofcmds);
8255 uint32_t f = flags;
8256 if (f & MachO::MH_NOUNDEFS) {
8257 outs() << " NOUNDEFS";
8258 f &= ~MachO::MH_NOUNDEFS;
8259 }
8260 if (f & MachO::MH_INCRLINK) {
8261 outs() << " INCRLINK";
8262 f &= ~MachO::MH_INCRLINK;
8263 }
8264 if (f & MachO::MH_DYLDLINK) {
8265 outs() << " DYLDLINK";
8266 f &= ~MachO::MH_DYLDLINK;
8267 }
8268 if (f & MachO::MH_BINDATLOAD) {
8269 outs() << " BINDATLOAD";
8270 f &= ~MachO::MH_BINDATLOAD;
8271 }
8272 if (f & MachO::MH_PREBOUND) {
8273 outs() << " PREBOUND";
8274 f &= ~MachO::MH_PREBOUND;
8275 }
8276 if (f & MachO::MH_SPLIT_SEGS) {
8277 outs() << " SPLIT_SEGS";
8278 f &= ~MachO::MH_SPLIT_SEGS;
8279 }
8280 if (f & MachO::MH_LAZY_INIT) {
8281 outs() << " LAZY_INIT";
8282 f &= ~MachO::MH_LAZY_INIT;
8283 }
8284 if (f & MachO::MH_TWOLEVEL) {
8285 outs() << " TWOLEVEL";
8286 f &= ~MachO::MH_TWOLEVEL;
8287 }
8288 if (f & MachO::MH_FORCE_FLAT) {
8289 outs() << " FORCE_FLAT";
8290 f &= ~MachO::MH_FORCE_FLAT;
8291 }
8292 if (f & MachO::MH_NOMULTIDEFS) {
8293 outs() << " NOMULTIDEFS";
8294 f &= ~MachO::MH_NOMULTIDEFS;
8295 }
8296 if (f & MachO::MH_NOFIXPREBINDING) {
8297 outs() << " NOFIXPREBINDING";
8298 f &= ~MachO::MH_NOFIXPREBINDING;
8299 }
8300 if (f & MachO::MH_PREBINDABLE) {
8301 outs() << " PREBINDABLE";
8302 f &= ~MachO::MH_PREBINDABLE;
8303 }
8304 if (f & MachO::MH_ALLMODSBOUND) {
8305 outs() << " ALLMODSBOUND";
8306 f &= ~MachO::MH_ALLMODSBOUND;
8307 }
8308 if (f & MachO::MH_SUBSECTIONS_VIA_SYMBOLS) {
8309 outs() << " SUBSECTIONS_VIA_SYMBOLS";
8310 f &= ~MachO::MH_SUBSECTIONS_VIA_SYMBOLS;
8311 }
8312 if (f & MachO::MH_CANONICAL) {
8313 outs() << " CANONICAL";
8314 f &= ~MachO::MH_CANONICAL;
8315 }
8316 if (f & MachO::MH_WEAK_DEFINES) {
8317 outs() << " WEAK_DEFINES";
8318 f &= ~MachO::MH_WEAK_DEFINES;
8319 }
8320 if (f & MachO::MH_BINDS_TO_WEAK) {
8321 outs() << " BINDS_TO_WEAK";
8322 f &= ~MachO::MH_BINDS_TO_WEAK;
8323 }
8324 if (f & MachO::MH_ALLOW_STACK_EXECUTION) {
8325 outs() << " ALLOW_STACK_EXECUTION";
8326 f &= ~MachO::MH_ALLOW_STACK_EXECUTION;
8327 }
8328 if (f & MachO::MH_DEAD_STRIPPABLE_DYLIB) {
8329 outs() << " DEAD_STRIPPABLE_DYLIB";
8330 f &= ~MachO::MH_DEAD_STRIPPABLE_DYLIB;
8331 }
8332 if (f & MachO::MH_PIE) {
8333 outs() << " PIE";
8334 f &= ~MachO::MH_PIE;
8335 }
8336 if (f & MachO::MH_NO_REEXPORTED_DYLIBS) {
8337 outs() << " NO_REEXPORTED_DYLIBS";
8338 f &= ~MachO::MH_NO_REEXPORTED_DYLIBS;
8339 }
8340 if (f & MachO::MH_HAS_TLV_DESCRIPTORS) {
8341 outs() << " MH_HAS_TLV_DESCRIPTORS";
8342 f &= ~MachO::MH_HAS_TLV_DESCRIPTORS;
8343 }
8344 if (f & MachO::MH_NO_HEAP_EXECUTION) {
8345 outs() << " MH_NO_HEAP_EXECUTION";
8346 f &= ~MachO::MH_NO_HEAP_EXECUTION;
8347 }
8348 if (f & MachO::MH_APP_EXTENSION_SAFE) {
8349 outs() << " APP_EXTENSION_SAFE";
8350 f &= ~MachO::MH_APP_EXTENSION_SAFE;
8351 }
Kevin Enderbydf0d6da2017-06-19 19:38:22 +00008352 if (f & MachO::MH_NLIST_OUTOFSYNC_WITH_DYLDINFO) {
8353 outs() << " NLIST_OUTOFSYNC_WITH_DYLDINFO";
8354 f &= ~MachO::MH_NLIST_OUTOFSYNC_WITH_DYLDINFO;
8355 }
Kevin Enderbyb76d3862014-08-22 20:35:18 +00008356 if (f != 0 || flags == 0)
8357 outs() << format(" 0x%08" PRIx32, f);
8358 } else {
8359 outs() << format(" 0x%08" PRIx32, magic);
8360 outs() << format(" %7d", cputype);
8361 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
8362 outs() << format(" 0x%02" PRIx32,
8363 (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24);
8364 outs() << format(" %10u", filetype);
8365 outs() << format(" %5u", ncmds);
8366 outs() << format(" %10u", sizeofcmds);
8367 outs() << format(" 0x%08" PRIx32, flags);
8368 }
8369 outs() << "\n";
8370}
8371
Kevin Enderby956366c2014-08-29 22:30:52 +00008372static void PrintSegmentCommand(uint32_t cmd, uint32_t cmdsize,
8373 StringRef SegName, uint64_t vmaddr,
8374 uint64_t vmsize, uint64_t fileoff,
8375 uint64_t filesize, uint32_t maxprot,
8376 uint32_t initprot, uint32_t nsects,
8377 uint32_t flags, uint32_t object_size,
8378 bool verbose) {
8379 uint64_t expected_cmdsize;
8380 if (cmd == MachO::LC_SEGMENT) {
8381 outs() << " cmd LC_SEGMENT\n";
8382 expected_cmdsize = nsects;
8383 expected_cmdsize *= sizeof(struct MachO::section);
8384 expected_cmdsize += sizeof(struct MachO::segment_command);
8385 } else {
8386 outs() << " cmd LC_SEGMENT_64\n";
8387 expected_cmdsize = nsects;
8388 expected_cmdsize *= sizeof(struct MachO::section_64);
8389 expected_cmdsize += sizeof(struct MachO::segment_command_64);
8390 }
8391 outs() << " cmdsize " << cmdsize;
8392 if (cmdsize != expected_cmdsize)
8393 outs() << " Inconsistent size\n";
8394 else
8395 outs() << "\n";
8396 outs() << " segname " << SegName << "\n";
8397 if (cmd == MachO::LC_SEGMENT_64) {
8398 outs() << " vmaddr " << format("0x%016" PRIx64, vmaddr) << "\n";
8399 outs() << " vmsize " << format("0x%016" PRIx64, vmsize) << "\n";
8400 } else {
Kevin Enderbyadb7c432014-12-16 18:58:11 +00008401 outs() << " vmaddr " << format("0x%08" PRIx64, vmaddr) << "\n";
8402 outs() << " vmsize " << format("0x%08" PRIx64, vmsize) << "\n";
Kevin Enderby956366c2014-08-29 22:30:52 +00008403 }
8404 outs() << " fileoff " << fileoff;
8405 if (fileoff > object_size)
8406 outs() << " (past end of file)\n";
8407 else
8408 outs() << "\n";
8409 outs() << " filesize " << filesize;
8410 if (fileoff + filesize > object_size)
8411 outs() << " (past end of file)\n";
8412 else
8413 outs() << "\n";
8414 if (verbose) {
8415 if ((maxprot &
8416 ~(MachO::VM_PROT_READ | MachO::VM_PROT_WRITE |
8417 MachO::VM_PROT_EXECUTE)) != 0)
8418 outs() << " maxprot ?" << format("0x%08" PRIx32, maxprot) << "\n";
8419 else {
Davide Italiano37ff06a2015-09-02 16:53:25 +00008420 outs() << " maxprot ";
8421 outs() << ((maxprot & MachO::VM_PROT_READ) ? "r" : "-");
8422 outs() << ((maxprot & MachO::VM_PROT_WRITE) ? "w" : "-");
8423 outs() << ((maxprot & MachO::VM_PROT_EXECUTE) ? "x\n" : "-\n");
Kevin Enderby956366c2014-08-29 22:30:52 +00008424 }
8425 if ((initprot &
8426 ~(MachO::VM_PROT_READ | MachO::VM_PROT_WRITE |
8427 MachO::VM_PROT_EXECUTE)) != 0)
Kevin Enderby41c9c002016-10-21 18:22:35 +00008428 outs() << " initprot ?" << format("0x%08" PRIx32, initprot) << "\n";
Kevin Enderby956366c2014-08-29 22:30:52 +00008429 else {
Kevin Enderby41c9c002016-10-21 18:22:35 +00008430 outs() << " initprot ";
Davide Italiano37ff06a2015-09-02 16:53:25 +00008431 outs() << ((initprot & MachO::VM_PROT_READ) ? "r" : "-");
8432 outs() << ((initprot & MachO::VM_PROT_WRITE) ? "w" : "-");
8433 outs() << ((initprot & MachO::VM_PROT_EXECUTE) ? "x\n" : "-\n");
Kevin Enderby956366c2014-08-29 22:30:52 +00008434 }
8435 } else {
8436 outs() << " maxprot " << format("0x%08" PRIx32, maxprot) << "\n";
8437 outs() << " initprot " << format("0x%08" PRIx32, initprot) << "\n";
8438 }
8439 outs() << " nsects " << nsects << "\n";
8440 if (verbose) {
8441 outs() << " flags";
8442 if (flags == 0)
8443 outs() << " (none)\n";
8444 else {
8445 if (flags & MachO::SG_HIGHVM) {
8446 outs() << " HIGHVM";
8447 flags &= ~MachO::SG_HIGHVM;
8448 }
8449 if (flags & MachO::SG_FVMLIB) {
8450 outs() << " FVMLIB";
8451 flags &= ~MachO::SG_FVMLIB;
8452 }
8453 if (flags & MachO::SG_NORELOC) {
8454 outs() << " NORELOC";
8455 flags &= ~MachO::SG_NORELOC;
8456 }
8457 if (flags & MachO::SG_PROTECTED_VERSION_1) {
8458 outs() << " PROTECTED_VERSION_1";
8459 flags &= ~MachO::SG_PROTECTED_VERSION_1;
8460 }
8461 if (flags)
8462 outs() << format(" 0x%08" PRIx32, flags) << " (unknown flags)\n";
8463 else
8464 outs() << "\n";
8465 }
8466 } else {
8467 outs() << " flags " << format("0x%" PRIx32, flags) << "\n";
8468 }
8469}
8470
8471static void PrintSection(const char *sectname, const char *segname,
8472 uint64_t addr, uint64_t size, uint32_t offset,
8473 uint32_t align, uint32_t reloff, uint32_t nreloc,
8474 uint32_t flags, uint32_t reserved1, uint32_t reserved2,
8475 uint32_t cmd, const char *sg_segname,
8476 uint32_t filetype, uint32_t object_size,
8477 bool verbose) {
8478 outs() << "Section\n";
8479 outs() << " sectname " << format("%.16s\n", sectname);
8480 outs() << " segname " << format("%.16s", segname);
8481 if (filetype != MachO::MH_OBJECT && strncmp(sg_segname, segname, 16) != 0)
8482 outs() << " (does not match segment)\n";
8483 else
8484 outs() << "\n";
8485 if (cmd == MachO::LC_SEGMENT_64) {
8486 outs() << " addr " << format("0x%016" PRIx64, addr) << "\n";
8487 outs() << " size " << format("0x%016" PRIx64, size);
8488 } else {
Kevin Enderby75594b62014-12-16 21:00:25 +00008489 outs() << " addr " << format("0x%08" PRIx64, addr) << "\n";
8490 outs() << " size " << format("0x%08" PRIx64, size);
Kevin Enderby956366c2014-08-29 22:30:52 +00008491 }
8492 if ((flags & MachO::S_ZEROFILL) != 0 && offset + size > object_size)
8493 outs() << " (past end of file)\n";
8494 else
8495 outs() << "\n";
8496 outs() << " offset " << offset;
8497 if (offset > object_size)
8498 outs() << " (past end of file)\n";
8499 else
8500 outs() << "\n";
8501 uint32_t align_shifted = 1 << align;
8502 outs() << " align 2^" << align << " (" << align_shifted << ")\n";
8503 outs() << " reloff " << reloff;
8504 if (reloff > object_size)
8505 outs() << " (past end of file)\n";
8506 else
8507 outs() << "\n";
8508 outs() << " nreloc " << nreloc;
8509 if (reloff + nreloc * sizeof(struct MachO::relocation_info) > object_size)
8510 outs() << " (past end of file)\n";
8511 else
8512 outs() << "\n";
8513 uint32_t section_type = flags & MachO::SECTION_TYPE;
8514 if (verbose) {
8515 outs() << " type";
8516 if (section_type == MachO::S_REGULAR)
8517 outs() << " S_REGULAR\n";
8518 else if (section_type == MachO::S_ZEROFILL)
8519 outs() << " S_ZEROFILL\n";
8520 else if (section_type == MachO::S_CSTRING_LITERALS)
8521 outs() << " S_CSTRING_LITERALS\n";
8522 else if (section_type == MachO::S_4BYTE_LITERALS)
8523 outs() << " S_4BYTE_LITERALS\n";
8524 else if (section_type == MachO::S_8BYTE_LITERALS)
8525 outs() << " S_8BYTE_LITERALS\n";
8526 else if (section_type == MachO::S_16BYTE_LITERALS)
8527 outs() << " S_16BYTE_LITERALS\n";
8528 else if (section_type == MachO::S_LITERAL_POINTERS)
8529 outs() << " S_LITERAL_POINTERS\n";
8530 else if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS)
8531 outs() << " S_NON_LAZY_SYMBOL_POINTERS\n";
8532 else if (section_type == MachO::S_LAZY_SYMBOL_POINTERS)
8533 outs() << " S_LAZY_SYMBOL_POINTERS\n";
8534 else if (section_type == MachO::S_SYMBOL_STUBS)
8535 outs() << " S_SYMBOL_STUBS\n";
8536 else if (section_type == MachO::S_MOD_INIT_FUNC_POINTERS)
8537 outs() << " S_MOD_INIT_FUNC_POINTERS\n";
8538 else if (section_type == MachO::S_MOD_TERM_FUNC_POINTERS)
8539 outs() << " S_MOD_TERM_FUNC_POINTERS\n";
8540 else if (section_type == MachO::S_COALESCED)
8541 outs() << " S_COALESCED\n";
8542 else if (section_type == MachO::S_INTERPOSING)
8543 outs() << " S_INTERPOSING\n";
8544 else if (section_type == MachO::S_DTRACE_DOF)
8545 outs() << " S_DTRACE_DOF\n";
8546 else if (section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS)
8547 outs() << " S_LAZY_DYLIB_SYMBOL_POINTERS\n";
8548 else if (section_type == MachO::S_THREAD_LOCAL_REGULAR)
8549 outs() << " S_THREAD_LOCAL_REGULAR\n";
8550 else if (section_type == MachO::S_THREAD_LOCAL_ZEROFILL)
8551 outs() << " S_THREAD_LOCAL_ZEROFILL\n";
8552 else if (section_type == MachO::S_THREAD_LOCAL_VARIABLES)
8553 outs() << " S_THREAD_LOCAL_VARIABLES\n";
8554 else if (section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS)
8555 outs() << " S_THREAD_LOCAL_VARIABLE_POINTERS\n";
8556 else if (section_type == MachO::S_THREAD_LOCAL_INIT_FUNCTION_POINTERS)
8557 outs() << " S_THREAD_LOCAL_INIT_FUNCTION_POINTERS\n";
8558 else
8559 outs() << format("0x%08" PRIx32, section_type) << "\n";
8560 outs() << "attributes";
8561 uint32_t section_attributes = flags & MachO::SECTION_ATTRIBUTES;
8562 if (section_attributes & MachO::S_ATTR_PURE_INSTRUCTIONS)
8563 outs() << " PURE_INSTRUCTIONS";
8564 if (section_attributes & MachO::S_ATTR_NO_TOC)
8565 outs() << " NO_TOC";
8566 if (section_attributes & MachO::S_ATTR_STRIP_STATIC_SYMS)
8567 outs() << " STRIP_STATIC_SYMS";
8568 if (section_attributes & MachO::S_ATTR_NO_DEAD_STRIP)
8569 outs() << " NO_DEAD_STRIP";
8570 if (section_attributes & MachO::S_ATTR_LIVE_SUPPORT)
8571 outs() << " LIVE_SUPPORT";
8572 if (section_attributes & MachO::S_ATTR_SELF_MODIFYING_CODE)
8573 outs() << " SELF_MODIFYING_CODE";
8574 if (section_attributes & MachO::S_ATTR_DEBUG)
8575 outs() << " DEBUG";
8576 if (section_attributes & MachO::S_ATTR_SOME_INSTRUCTIONS)
8577 outs() << " SOME_INSTRUCTIONS";
8578 if (section_attributes & MachO::S_ATTR_EXT_RELOC)
8579 outs() << " EXT_RELOC";
8580 if (section_attributes & MachO::S_ATTR_LOC_RELOC)
8581 outs() << " LOC_RELOC";
8582 if (section_attributes == 0)
8583 outs() << " (none)";
8584 outs() << "\n";
8585 } else
8586 outs() << " flags " << format("0x%08" PRIx32, flags) << "\n";
8587 outs() << " reserved1 " << reserved1;
8588 if (section_type == MachO::S_SYMBOL_STUBS ||
8589 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
8590 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
8591 section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
8592 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS)
8593 outs() << " (index into indirect symbol table)\n";
8594 else
8595 outs() << "\n";
8596 outs() << " reserved2 " << reserved2;
8597 if (section_type == MachO::S_SYMBOL_STUBS)
8598 outs() << " (size of stubs)\n";
8599 else
8600 outs() << "\n";
8601}
8602
David Majnemer73cc6ff2014-11-13 19:48:56 +00008603static void PrintSymtabLoadCommand(MachO::symtab_command st, bool Is64Bit,
Kevin Enderby956366c2014-08-29 22:30:52 +00008604 uint32_t object_size) {
8605 outs() << " cmd LC_SYMTAB\n";
8606 outs() << " cmdsize " << st.cmdsize;
8607 if (st.cmdsize != sizeof(struct MachO::symtab_command))
8608 outs() << " Incorrect size\n";
8609 else
8610 outs() << "\n";
8611 outs() << " symoff " << st.symoff;
8612 if (st.symoff > object_size)
8613 outs() << " (past end of file)\n";
8614 else
8615 outs() << "\n";
8616 outs() << " nsyms " << st.nsyms;
8617 uint64_t big_size;
David Majnemer73cc6ff2014-11-13 19:48:56 +00008618 if (Is64Bit) {
Kevin Enderby956366c2014-08-29 22:30:52 +00008619 big_size = st.nsyms;
8620 big_size *= sizeof(struct MachO::nlist_64);
8621 big_size += st.symoff;
8622 if (big_size > object_size)
8623 outs() << " (past end of file)\n";
8624 else
8625 outs() << "\n";
8626 } else {
8627 big_size = st.nsyms;
8628 big_size *= sizeof(struct MachO::nlist);
8629 big_size += st.symoff;
8630 if (big_size > object_size)
8631 outs() << " (past end of file)\n";
8632 else
8633 outs() << "\n";
8634 }
8635 outs() << " stroff " << st.stroff;
8636 if (st.stroff > object_size)
8637 outs() << " (past end of file)\n";
8638 else
8639 outs() << "\n";
8640 outs() << " strsize " << st.strsize;
8641 big_size = st.stroff;
8642 big_size += st.strsize;
8643 if (big_size > object_size)
8644 outs() << " (past end of file)\n";
8645 else
8646 outs() << "\n";
8647}
8648
8649static void PrintDysymtabLoadCommand(MachO::dysymtab_command dyst,
8650 uint32_t nsyms, uint32_t object_size,
David Majnemer73cc6ff2014-11-13 19:48:56 +00008651 bool Is64Bit) {
Kevin Enderby956366c2014-08-29 22:30:52 +00008652 outs() << " cmd LC_DYSYMTAB\n";
8653 outs() << " cmdsize " << dyst.cmdsize;
8654 if (dyst.cmdsize != sizeof(struct MachO::dysymtab_command))
8655 outs() << " Incorrect size\n";
8656 else
8657 outs() << "\n";
8658 outs() << " ilocalsym " << dyst.ilocalsym;
8659 if (dyst.ilocalsym > nsyms)
8660 outs() << " (greater than the number of symbols)\n";
8661 else
8662 outs() << "\n";
8663 outs() << " nlocalsym " << dyst.nlocalsym;
8664 uint64_t big_size;
8665 big_size = dyst.ilocalsym;
8666 big_size += dyst.nlocalsym;
8667 if (big_size > nsyms)
8668 outs() << " (past the end of the symbol table)\n";
8669 else
8670 outs() << "\n";
8671 outs() << " iextdefsym " << dyst.iextdefsym;
8672 if (dyst.iextdefsym > nsyms)
8673 outs() << " (greater than the number of symbols)\n";
8674 else
8675 outs() << "\n";
8676 outs() << " nextdefsym " << dyst.nextdefsym;
8677 big_size = dyst.iextdefsym;
8678 big_size += dyst.nextdefsym;
8679 if (big_size > nsyms)
8680 outs() << " (past the end of the symbol table)\n";
8681 else
8682 outs() << "\n";
8683 outs() << " iundefsym " << dyst.iundefsym;
8684 if (dyst.iundefsym > nsyms)
8685 outs() << " (greater than the number of symbols)\n";
8686 else
8687 outs() << "\n";
8688 outs() << " nundefsym " << dyst.nundefsym;
8689 big_size = dyst.iundefsym;
8690 big_size += dyst.nundefsym;
8691 if (big_size > nsyms)
8692 outs() << " (past the end of the symbol table)\n";
8693 else
8694 outs() << "\n";
8695 outs() << " tocoff " << dyst.tocoff;
8696 if (dyst.tocoff > object_size)
8697 outs() << " (past end of file)\n";
8698 else
8699 outs() << "\n";
8700 outs() << " ntoc " << dyst.ntoc;
8701 big_size = dyst.ntoc;
8702 big_size *= sizeof(struct MachO::dylib_table_of_contents);
8703 big_size += dyst.tocoff;
8704 if (big_size > object_size)
8705 outs() << " (past end of file)\n";
8706 else
8707 outs() << "\n";
8708 outs() << " modtaboff " << dyst.modtaboff;
8709 if (dyst.modtaboff > object_size)
8710 outs() << " (past end of file)\n";
8711 else
8712 outs() << "\n";
8713 outs() << " nmodtab " << dyst.nmodtab;
8714 uint64_t modtabend;
David Majnemer73cc6ff2014-11-13 19:48:56 +00008715 if (Is64Bit) {
Kevin Enderby956366c2014-08-29 22:30:52 +00008716 modtabend = dyst.nmodtab;
8717 modtabend *= sizeof(struct MachO::dylib_module_64);
8718 modtabend += dyst.modtaboff;
8719 } else {
8720 modtabend = dyst.nmodtab;
8721 modtabend *= sizeof(struct MachO::dylib_module);
8722 modtabend += dyst.modtaboff;
8723 }
8724 if (modtabend > object_size)
8725 outs() << " (past end of file)\n";
8726 else
8727 outs() << "\n";
8728 outs() << " extrefsymoff " << dyst.extrefsymoff;
8729 if (dyst.extrefsymoff > object_size)
8730 outs() << " (past end of file)\n";
8731 else
8732 outs() << "\n";
8733 outs() << " nextrefsyms " << dyst.nextrefsyms;
8734 big_size = dyst.nextrefsyms;
8735 big_size *= sizeof(struct MachO::dylib_reference);
8736 big_size += dyst.extrefsymoff;
8737 if (big_size > object_size)
8738 outs() << " (past end of file)\n";
8739 else
8740 outs() << "\n";
8741 outs() << " indirectsymoff " << dyst.indirectsymoff;
8742 if (dyst.indirectsymoff > object_size)
8743 outs() << " (past end of file)\n";
8744 else
8745 outs() << "\n";
8746 outs() << " nindirectsyms " << dyst.nindirectsyms;
8747 big_size = dyst.nindirectsyms;
8748 big_size *= sizeof(uint32_t);
8749 big_size += dyst.indirectsymoff;
8750 if (big_size > object_size)
8751 outs() << " (past end of file)\n";
8752 else
8753 outs() << "\n";
8754 outs() << " extreloff " << dyst.extreloff;
8755 if (dyst.extreloff > object_size)
8756 outs() << " (past end of file)\n";
8757 else
8758 outs() << "\n";
8759 outs() << " nextrel " << dyst.nextrel;
8760 big_size = dyst.nextrel;
8761 big_size *= sizeof(struct MachO::relocation_info);
8762 big_size += dyst.extreloff;
8763 if (big_size > object_size)
8764 outs() << " (past end of file)\n";
8765 else
8766 outs() << "\n";
8767 outs() << " locreloff " << dyst.locreloff;
8768 if (dyst.locreloff > object_size)
8769 outs() << " (past end of file)\n";
8770 else
8771 outs() << "\n";
8772 outs() << " nlocrel " << dyst.nlocrel;
8773 big_size = dyst.nlocrel;
8774 big_size *= sizeof(struct MachO::relocation_info);
8775 big_size += dyst.locreloff;
8776 if (big_size > object_size)
8777 outs() << " (past end of file)\n";
8778 else
8779 outs() << "\n";
8780}
8781
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008782static void PrintDyldInfoLoadCommand(MachO::dyld_info_command dc,
8783 uint32_t object_size) {
8784 if (dc.cmd == MachO::LC_DYLD_INFO)
8785 outs() << " cmd LC_DYLD_INFO\n";
8786 else
8787 outs() << " cmd LC_DYLD_INFO_ONLY\n";
8788 outs() << " cmdsize " << dc.cmdsize;
8789 if (dc.cmdsize != sizeof(struct MachO::dyld_info_command))
8790 outs() << " Incorrect size\n";
8791 else
8792 outs() << "\n";
8793 outs() << " rebase_off " << dc.rebase_off;
8794 if (dc.rebase_off > object_size)
8795 outs() << " (past end of file)\n";
8796 else
8797 outs() << "\n";
8798 outs() << " rebase_size " << dc.rebase_size;
8799 uint64_t big_size;
8800 big_size = dc.rebase_off;
8801 big_size += dc.rebase_size;
8802 if (big_size > object_size)
8803 outs() << " (past end of file)\n";
8804 else
8805 outs() << "\n";
8806 outs() << " bind_off " << dc.bind_off;
8807 if (dc.bind_off > object_size)
8808 outs() << " (past end of file)\n";
8809 else
8810 outs() << "\n";
8811 outs() << " bind_size " << dc.bind_size;
8812 big_size = dc.bind_off;
8813 big_size += dc.bind_size;
8814 if (big_size > object_size)
8815 outs() << " (past end of file)\n";
8816 else
8817 outs() << "\n";
8818 outs() << " weak_bind_off " << dc.weak_bind_off;
8819 if (dc.weak_bind_off > object_size)
8820 outs() << " (past end of file)\n";
8821 else
8822 outs() << "\n";
8823 outs() << " weak_bind_size " << dc.weak_bind_size;
8824 big_size = dc.weak_bind_off;
8825 big_size += dc.weak_bind_size;
8826 if (big_size > object_size)
8827 outs() << " (past end of file)\n";
8828 else
8829 outs() << "\n";
8830 outs() << " lazy_bind_off " << dc.lazy_bind_off;
8831 if (dc.lazy_bind_off > object_size)
8832 outs() << " (past end of file)\n";
8833 else
8834 outs() << "\n";
8835 outs() << " lazy_bind_size " << dc.lazy_bind_size;
8836 big_size = dc.lazy_bind_off;
8837 big_size += dc.lazy_bind_size;
8838 if (big_size > object_size)
8839 outs() << " (past end of file)\n";
8840 else
8841 outs() << "\n";
8842 outs() << " export_off " << dc.export_off;
8843 if (dc.export_off > object_size)
8844 outs() << " (past end of file)\n";
8845 else
8846 outs() << "\n";
8847 outs() << " export_size " << dc.export_size;
8848 big_size = dc.export_off;
8849 big_size += dc.export_size;
8850 if (big_size > object_size)
8851 outs() << " (past end of file)\n";
8852 else
8853 outs() << "\n";
8854}
8855
8856static void PrintDyldLoadCommand(MachO::dylinker_command dyld,
8857 const char *Ptr) {
8858 if (dyld.cmd == MachO::LC_ID_DYLINKER)
8859 outs() << " cmd LC_ID_DYLINKER\n";
8860 else if (dyld.cmd == MachO::LC_LOAD_DYLINKER)
8861 outs() << " cmd LC_LOAD_DYLINKER\n";
8862 else if (dyld.cmd == MachO::LC_DYLD_ENVIRONMENT)
8863 outs() << " cmd LC_DYLD_ENVIRONMENT\n";
8864 else
8865 outs() << " cmd ?(" << dyld.cmd << ")\n";
8866 outs() << " cmdsize " << dyld.cmdsize;
8867 if (dyld.cmdsize < sizeof(struct MachO::dylinker_command))
8868 outs() << " Incorrect size\n";
8869 else
8870 outs() << "\n";
8871 if (dyld.name >= dyld.cmdsize)
8872 outs() << " name ?(bad offset " << dyld.name << ")\n";
8873 else {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00008874 const char *P = (const char *)(Ptr) + dyld.name;
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008875 outs() << " name " << P << " (offset " << dyld.name << ")\n";
8876 }
8877}
8878
8879static void PrintUuidLoadCommand(MachO::uuid_command uuid) {
8880 outs() << " cmd LC_UUID\n";
8881 outs() << " cmdsize " << uuid.cmdsize;
8882 if (uuid.cmdsize != sizeof(struct MachO::uuid_command))
8883 outs() << " Incorrect size\n";
8884 else
8885 outs() << "\n";
8886 outs() << " uuid ";
Davide Italianoc74277a2015-12-07 00:03:28 +00008887 for (int i = 0; i < 16; ++i) {
8888 outs() << format("%02" PRIX32, uuid.uuid[i]);
8889 if (i == 3 || i == 5 || i == 7 || i == 9)
8890 outs() << "-";
8891 }
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008892 outs() << "\n";
8893}
8894
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008895static void PrintRpathLoadCommand(MachO::rpath_command rpath, const char *Ptr) {
Jean-Daniel Dupas00cc1f52014-12-04 07:37:02 +00008896 outs() << " cmd LC_RPATH\n";
8897 outs() << " cmdsize " << rpath.cmdsize;
8898 if (rpath.cmdsize < sizeof(struct MachO::rpath_command))
8899 outs() << " Incorrect size\n";
8900 else
8901 outs() << "\n";
8902 if (rpath.path >= rpath.cmdsize)
8903 outs() << " path ?(bad offset " << rpath.path << ")\n";
8904 else {
8905 const char *P = (const char *)(Ptr) + rpath.path;
8906 outs() << " path " << P << " (offset " << rpath.path << ")\n";
8907 }
8908}
8909
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008910static void PrintVersionMinLoadCommand(MachO::version_min_command vd) {
Tim Northoverbfbfb122015-11-02 21:26:58 +00008911 StringRef LoadCmdName;
8912 switch (vd.cmd) {
8913 case MachO::LC_VERSION_MIN_MACOSX:
8914 LoadCmdName = "LC_VERSION_MIN_MACOSX";
8915 break;
8916 case MachO::LC_VERSION_MIN_IPHONEOS:
8917 LoadCmdName = "LC_VERSION_MIN_IPHONEOS";
8918 break;
8919 case MachO::LC_VERSION_MIN_TVOS:
8920 LoadCmdName = "LC_VERSION_MIN_TVOS";
8921 break;
8922 case MachO::LC_VERSION_MIN_WATCHOS:
8923 LoadCmdName = "LC_VERSION_MIN_WATCHOS";
8924 break;
8925 default:
8926 llvm_unreachable("Unknown version min load command");
8927 }
8928
8929 outs() << " cmd " << LoadCmdName << '\n';
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008930 outs() << " cmdsize " << vd.cmdsize;
8931 if (vd.cmdsize != sizeof(struct MachO::version_min_command))
8932 outs() << " Incorrect size\n";
8933 else
8934 outs() << "\n";
Davide Italiano56baef32015-08-26 12:26:11 +00008935 outs() << " version "
8936 << MachOObjectFile::getVersionMinMajor(vd, false) << "."
8937 << MachOObjectFile::getVersionMinMinor(vd, false);
8938 uint32_t Update = MachOObjectFile::getVersionMinUpdate(vd, false);
8939 if (Update != 0)
8940 outs() << "." << Update;
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008941 outs() << "\n";
8942 if (vd.sdk == 0)
Kevin Enderby57538292014-12-17 01:01:30 +00008943 outs() << " sdk n/a";
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008944 else {
Davide Italiano56baef32015-08-26 12:26:11 +00008945 outs() << " sdk "
8946 << MachOObjectFile::getVersionMinMajor(vd, true) << "."
8947 << MachOObjectFile::getVersionMinMinor(vd, true);
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008948 }
Davide Italiano56baef32015-08-26 12:26:11 +00008949 Update = MachOObjectFile::getVersionMinUpdate(vd, true);
8950 if (Update != 0)
8951 outs() << "." << Update;
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008952 outs() << "\n";
8953}
8954
Kevin Enderbya4579c42017-01-19 17:36:31 +00008955static void PrintNoteLoadCommand(MachO::note_command Nt) {
8956 outs() << " cmd LC_NOTE\n";
8957 outs() << " cmdsize " << Nt.cmdsize;
8958 if (Nt.cmdsize != sizeof(struct MachO::note_command))
8959 outs() << " Incorrect size\n";
8960 else
8961 outs() << "\n";
8962 const char *d = Nt.data_owner;
8963 outs() << "data_owner " << format("%.16s\n", d);
8964 outs() << " offset " << Nt.offset << "\n";
8965 outs() << " size " << Nt.size << "\n";
8966}
8967
Steven Wu5b54a422017-01-23 20:07:55 +00008968static void PrintBuildToolVersion(MachO::build_tool_version bv) {
8969 outs() << " tool " << MachOObjectFile::getBuildTool(bv.tool) << "\n";
8970 outs() << " version " << MachOObjectFile::getVersionString(bv.version)
8971 << "\n";
8972}
8973
8974static void PrintBuildVersionLoadCommand(const MachOObjectFile *obj,
8975 MachO::build_version_command bd) {
8976 outs() << " cmd LC_BUILD_VERSION\n";
8977 outs() << " cmdsize " << bd.cmdsize;
8978 if (bd.cmdsize !=
8979 sizeof(struct MachO::build_version_command) +
8980 bd.ntools * sizeof(struct MachO::build_tool_version))
8981 outs() << " Incorrect size\n";
8982 else
8983 outs() << "\n";
8984 outs() << " platform " << MachOObjectFile::getBuildPlatform(bd.platform)
8985 << "\n";
8986 if (bd.sdk)
8987 outs() << " sdk " << MachOObjectFile::getVersionString(bd.sdk)
8988 << "\n";
8989 else
8990 outs() << " sdk n/a\n";
8991 outs() << " minos " << MachOObjectFile::getVersionString(bd.minos)
8992 << "\n";
8993 outs() << " ntools " << bd.ntools << "\n";
8994 for (unsigned i = 0; i < bd.ntools; ++i) {
8995 MachO::build_tool_version bv = obj->getBuildToolVersion(i);
8996 PrintBuildToolVersion(bv);
8997 }
8998}
8999
Kevin Enderby8ae63c12014-09-04 16:54:47 +00009000static void PrintSourceVersionCommand(MachO::source_version_command sd) {
9001 outs() << " cmd LC_SOURCE_VERSION\n";
9002 outs() << " cmdsize " << sd.cmdsize;
9003 if (sd.cmdsize != sizeof(struct MachO::source_version_command))
9004 outs() << " Incorrect size\n";
9005 else
9006 outs() << "\n";
9007 uint64_t a = (sd.version >> 40) & 0xffffff;
9008 uint64_t b = (sd.version >> 30) & 0x3ff;
9009 uint64_t c = (sd.version >> 20) & 0x3ff;
9010 uint64_t d = (sd.version >> 10) & 0x3ff;
9011 uint64_t e = sd.version & 0x3ff;
9012 outs() << " version " << a << "." << b;
9013 if (e != 0)
9014 outs() << "." << c << "." << d << "." << e;
9015 else if (d != 0)
9016 outs() << "." << c << "." << d;
9017 else if (c != 0)
9018 outs() << "." << c;
9019 outs() << "\n";
9020}
9021
9022static void PrintEntryPointCommand(MachO::entry_point_command ep) {
9023 outs() << " cmd LC_MAIN\n";
9024 outs() << " cmdsize " << ep.cmdsize;
9025 if (ep.cmdsize != sizeof(struct MachO::entry_point_command))
9026 outs() << " Incorrect size\n";
9027 else
9028 outs() << "\n";
9029 outs() << " entryoff " << ep.entryoff << "\n";
9030 outs() << " stacksize " << ep.stacksize << "\n";
9031}
9032
Kevin Enderby0804f4672014-12-16 23:25:52 +00009033static void PrintEncryptionInfoCommand(MachO::encryption_info_command ec,
9034 uint32_t object_size) {
9035 outs() << " cmd LC_ENCRYPTION_INFO\n";
9036 outs() << " cmdsize " << ec.cmdsize;
9037 if (ec.cmdsize != sizeof(struct MachO::encryption_info_command))
9038 outs() << " Incorrect size\n";
9039 else
9040 outs() << "\n";
9041 outs() << " cryptoff " << ec.cryptoff;
9042 if (ec.cryptoff > object_size)
9043 outs() << " (past end of file)\n";
9044 else
9045 outs() << "\n";
9046 outs() << " cryptsize " << ec.cryptsize;
9047 if (ec.cryptsize > object_size)
9048 outs() << " (past end of file)\n";
9049 else
9050 outs() << "\n";
9051 outs() << " cryptid " << ec.cryptid << "\n";
9052}
9053
Kevin Enderby57538292014-12-17 01:01:30 +00009054static void PrintEncryptionInfoCommand64(MachO::encryption_info_command_64 ec,
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009055 uint32_t object_size) {
Kevin Enderby57538292014-12-17 01:01:30 +00009056 outs() << " cmd LC_ENCRYPTION_INFO_64\n";
9057 outs() << " cmdsize " << ec.cmdsize;
9058 if (ec.cmdsize != sizeof(struct MachO::encryption_info_command_64))
9059 outs() << " Incorrect size\n";
9060 else
9061 outs() << "\n";
9062 outs() << " cryptoff " << ec.cryptoff;
9063 if (ec.cryptoff > object_size)
9064 outs() << " (past end of file)\n";
9065 else
9066 outs() << "\n";
9067 outs() << " cryptsize " << ec.cryptsize;
9068 if (ec.cryptsize > object_size)
9069 outs() << " (past end of file)\n";
9070 else
9071 outs() << "\n";
9072 outs() << " cryptid " << ec.cryptid << "\n";
9073 outs() << " pad " << ec.pad << "\n";
9074}
9075
Kevin Enderbyd0b6b7f2014-12-18 00:53:40 +00009076static void PrintLinkerOptionCommand(MachO::linker_option_command lo,
9077 const char *Ptr) {
9078 outs() << " cmd LC_LINKER_OPTION\n";
9079 outs() << " cmdsize " << lo.cmdsize;
9080 if (lo.cmdsize < sizeof(struct MachO::linker_option_command))
9081 outs() << " Incorrect size\n";
9082 else
9083 outs() << "\n";
9084 outs() << " count " << lo.count << "\n";
9085 const char *string = Ptr + sizeof(struct MachO::linker_option_command);
9086 uint32_t left = lo.cmdsize - sizeof(struct MachO::linker_option_command);
9087 uint32_t i = 0;
9088 while (left > 0) {
9089 while (*string == '\0' && left > 0) {
9090 string++;
9091 left--;
9092 }
9093 if (left > 0) {
9094 i++;
9095 outs() << " string #" << i << " " << format("%.*s\n", left, string);
David Majnemerd4449ed2014-12-20 08:24:43 +00009096 uint32_t NullPos = StringRef(string, left).find('\0');
9097 uint32_t len = std::min(NullPos, left) + 1;
Kevin Enderbyd0b6b7f2014-12-18 00:53:40 +00009098 string += len;
9099 left -= len;
9100 }
9101 }
9102 if (lo.count != i)
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009103 outs() << " count " << lo.count << " does not match number of strings "
9104 << i << "\n";
Kevin Enderbyd0b6b7f2014-12-18 00:53:40 +00009105}
9106
Kevin Enderbyb4b79312014-12-18 19:24:35 +00009107static void PrintSubFrameworkCommand(MachO::sub_framework_command sub,
9108 const char *Ptr) {
9109 outs() << " cmd LC_SUB_FRAMEWORK\n";
9110 outs() << " cmdsize " << sub.cmdsize;
9111 if (sub.cmdsize < sizeof(struct MachO::sub_framework_command))
9112 outs() << " Incorrect size\n";
9113 else
9114 outs() << "\n";
9115 if (sub.umbrella < sub.cmdsize) {
9116 const char *P = Ptr + sub.umbrella;
9117 outs() << " umbrella " << P << " (offset " << sub.umbrella << ")\n";
9118 } else {
9119 outs() << " umbrella ?(bad offset " << sub.umbrella << ")\n";
9120 }
9121}
9122
Kevin Enderbya2bd8d92014-12-18 23:13:26 +00009123static void PrintSubUmbrellaCommand(MachO::sub_umbrella_command sub,
9124 const char *Ptr) {
9125 outs() << " cmd LC_SUB_UMBRELLA\n";
9126 outs() << " cmdsize " << sub.cmdsize;
9127 if (sub.cmdsize < sizeof(struct MachO::sub_umbrella_command))
9128 outs() << " Incorrect size\n";
9129 else
9130 outs() << "\n";
9131 if (sub.sub_umbrella < sub.cmdsize) {
9132 const char *P = Ptr + sub.sub_umbrella;
9133 outs() << " sub_umbrella " << P << " (offset " << sub.sub_umbrella << ")\n";
9134 } else {
9135 outs() << " sub_umbrella ?(bad offset " << sub.sub_umbrella << ")\n";
9136 }
9137}
9138
Kevin Enderby36c8d3a2014-12-19 19:48:16 +00009139static void PrintSubLibraryCommand(MachO::sub_library_command sub,
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009140 const char *Ptr) {
Kevin Enderby36c8d3a2014-12-19 19:48:16 +00009141 outs() << " cmd LC_SUB_LIBRARY\n";
9142 outs() << " cmdsize " << sub.cmdsize;
9143 if (sub.cmdsize < sizeof(struct MachO::sub_library_command))
9144 outs() << " Incorrect size\n";
9145 else
9146 outs() << "\n";
9147 if (sub.sub_library < sub.cmdsize) {
9148 const char *P = Ptr + sub.sub_library;
9149 outs() << " sub_library " << P << " (offset " << sub.sub_library << ")\n";
9150 } else {
9151 outs() << " sub_library ?(bad offset " << sub.sub_library << ")\n";
9152 }
9153}
9154
Kevin Enderby186eac32014-12-19 21:06:24 +00009155static void PrintSubClientCommand(MachO::sub_client_command sub,
9156 const char *Ptr) {
9157 outs() << " cmd LC_SUB_CLIENT\n";
9158 outs() << " cmdsize " << sub.cmdsize;
9159 if (sub.cmdsize < sizeof(struct MachO::sub_client_command))
9160 outs() << " Incorrect size\n";
9161 else
9162 outs() << "\n";
9163 if (sub.client < sub.cmdsize) {
9164 const char *P = Ptr + sub.client;
9165 outs() << " client " << P << " (offset " << sub.client << ")\n";
9166 } else {
9167 outs() << " client ?(bad offset " << sub.client << ")\n";
9168 }
9169}
Kevin Enderby36c8d3a2014-12-19 19:48:16 +00009170
Kevin Enderby52e4ce42014-12-19 22:25:22 +00009171static void PrintRoutinesCommand(MachO::routines_command r) {
9172 outs() << " cmd LC_ROUTINES\n";
9173 outs() << " cmdsize " << r.cmdsize;
9174 if (r.cmdsize != sizeof(struct MachO::routines_command))
9175 outs() << " Incorrect size\n";
9176 else
9177 outs() << "\n";
9178 outs() << " init_address " << format("0x%08" PRIx32, r.init_address) << "\n";
9179 outs() << " init_module " << r.init_module << "\n";
9180 outs() << " reserved1 " << r.reserved1 << "\n";
9181 outs() << " reserved2 " << r.reserved2 << "\n";
9182 outs() << " reserved3 " << r.reserved3 << "\n";
9183 outs() << " reserved4 " << r.reserved4 << "\n";
9184 outs() << " reserved5 " << r.reserved5 << "\n";
9185 outs() << " reserved6 " << r.reserved6 << "\n";
9186}
9187
9188static void PrintRoutinesCommand64(MachO::routines_command_64 r) {
9189 outs() << " cmd LC_ROUTINES_64\n";
9190 outs() << " cmdsize " << r.cmdsize;
9191 if (r.cmdsize != sizeof(struct MachO::routines_command_64))
9192 outs() << " Incorrect size\n";
9193 else
9194 outs() << "\n";
9195 outs() << " init_address " << format("0x%016" PRIx64, r.init_address) << "\n";
9196 outs() << " init_module " << r.init_module << "\n";
9197 outs() << " reserved1 " << r.reserved1 << "\n";
9198 outs() << " reserved2 " << r.reserved2 << "\n";
9199 outs() << " reserved3 " << r.reserved3 << "\n";
9200 outs() << " reserved4 " << r.reserved4 << "\n";
9201 outs() << " reserved5 " << r.reserved5 << "\n";
9202 outs() << " reserved6 " << r.reserved6 << "\n";
9203}
9204
Kevin Enderbyc3a035d2017-01-23 21:13:29 +00009205static void Print_x86_thread_state32_t(MachO::x86_thread_state32_t &cpu32) {
9206 outs() << "\t eax " << format("0x%08" PRIx32, cpu32.eax);
9207 outs() << " ebx " << format("0x%08" PRIx32, cpu32.ebx);
9208 outs() << " ecx " << format("0x%08" PRIx32, cpu32.ecx);
9209 outs() << " edx " << format("0x%08" PRIx32, cpu32.edx) << "\n";
9210 outs() << "\t edi " << format("0x%08" PRIx32, cpu32.edi);
9211 outs() << " esi " << format("0x%08" PRIx32, cpu32.esi);
9212 outs() << " ebp " << format("0x%08" PRIx32, cpu32.ebp);
9213 outs() << " esp " << format("0x%08" PRIx32, cpu32.esp) << "\n";
9214 outs() << "\t ss " << format("0x%08" PRIx32, cpu32.ss);
9215 outs() << " eflags " << format("0x%08" PRIx32, cpu32.eflags);
9216 outs() << " eip " << format("0x%08" PRIx32, cpu32.eip);
9217 outs() << " cs " << format("0x%08" PRIx32, cpu32.cs) << "\n";
9218 outs() << "\t ds " << format("0x%08" PRIx32, cpu32.ds);
9219 outs() << " es " << format("0x%08" PRIx32, cpu32.es);
9220 outs() << " fs " << format("0x%08" PRIx32, cpu32.fs);
9221 outs() << " gs " << format("0x%08" PRIx32, cpu32.gs) << "\n";
9222}
9223
Kevin Enderby48ef5342014-12-23 22:56:39 +00009224static void Print_x86_thread_state64_t(MachO::x86_thread_state64_t &cpu64) {
9225 outs() << " rax " << format("0x%016" PRIx64, cpu64.rax);
9226 outs() << " rbx " << format("0x%016" PRIx64, cpu64.rbx);
9227 outs() << " rcx " << format("0x%016" PRIx64, cpu64.rcx) << "\n";
9228 outs() << " rdx " << format("0x%016" PRIx64, cpu64.rdx);
9229 outs() << " rdi " << format("0x%016" PRIx64, cpu64.rdi);
9230 outs() << " rsi " << format("0x%016" PRIx64, cpu64.rsi) << "\n";
9231 outs() << " rbp " << format("0x%016" PRIx64, cpu64.rbp);
9232 outs() << " rsp " << format("0x%016" PRIx64, cpu64.rsp);
9233 outs() << " r8 " << format("0x%016" PRIx64, cpu64.r8) << "\n";
9234 outs() << " r9 " << format("0x%016" PRIx64, cpu64.r9);
9235 outs() << " r10 " << format("0x%016" PRIx64, cpu64.r10);
9236 outs() << " r11 " << format("0x%016" PRIx64, cpu64.r11) << "\n";
9237 outs() << " r12 " << format("0x%016" PRIx64, cpu64.r12);
9238 outs() << " r13 " << format("0x%016" PRIx64, cpu64.r13);
9239 outs() << " r14 " << format("0x%016" PRIx64, cpu64.r14) << "\n";
9240 outs() << " r15 " << format("0x%016" PRIx64, cpu64.r15);
9241 outs() << " rip " << format("0x%016" PRIx64, cpu64.rip) << "\n";
9242 outs() << "rflags " << format("0x%016" PRIx64, cpu64.rflags);
9243 outs() << " cs " << format("0x%016" PRIx64, cpu64.cs);
9244 outs() << " fs " << format("0x%016" PRIx64, cpu64.fs) << "\n";
9245 outs() << " gs " << format("0x%016" PRIx64, cpu64.gs) << "\n";
9246}
9247
Kevin Enderby227df342014-12-23 23:43:59 +00009248static void Print_mmst_reg(MachO::mmst_reg_t &r) {
Kevin Enderby48ef5342014-12-23 22:56:39 +00009249 uint32_t f;
9250 outs() << "\t mmst_reg ";
9251 for (f = 0; f < 10; f++)
9252 outs() << format("%02" PRIx32, (r.mmst_reg[f] & 0xff)) << " ";
9253 outs() << "\n";
9254 outs() << "\t mmst_rsrv ";
9255 for (f = 0; f < 6; f++)
9256 outs() << format("%02" PRIx32, (r.mmst_rsrv[f] & 0xff)) << " ";
9257 outs() << "\n";
9258}
9259
Kevin Enderbyaefb0032014-12-24 00:16:51 +00009260static void Print_xmm_reg(MachO::xmm_reg_t &r) {
Kevin Enderby48ef5342014-12-23 22:56:39 +00009261 uint32_t f;
9262 outs() << "\t xmm_reg ";
9263 for (f = 0; f < 16; f++)
9264 outs() << format("%02" PRIx32, (r.xmm_reg[f] & 0xff)) << " ";
9265 outs() << "\n";
9266}
9267
9268static void Print_x86_float_state_t(MachO::x86_float_state64_t &fpu) {
9269 outs() << "\t fpu_reserved[0] " << fpu.fpu_reserved[0];
9270 outs() << " fpu_reserved[1] " << fpu.fpu_reserved[1] << "\n";
9271 outs() << "\t control: invalid " << fpu.fpu_fcw.invalid;
9272 outs() << " denorm " << fpu.fpu_fcw.denorm;
9273 outs() << " zdiv " << fpu.fpu_fcw.zdiv;
9274 outs() << " ovrfl " << fpu.fpu_fcw.ovrfl;
9275 outs() << " undfl " << fpu.fpu_fcw.undfl;
9276 outs() << " precis " << fpu.fpu_fcw.precis << "\n";
9277 outs() << "\t\t pc ";
9278 if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_24B)
9279 outs() << "FP_PREC_24B ";
9280 else if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_53B)
9281 outs() << "FP_PREC_53B ";
9282 else if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_64B)
9283 outs() << "FP_PREC_64B ";
9284 else
9285 outs() << fpu.fpu_fcw.pc << " ";
9286 outs() << "rc ";
9287 if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_NEAR)
9288 outs() << "FP_RND_NEAR ";
9289 else if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_DOWN)
9290 outs() << "FP_RND_DOWN ";
9291 else if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_UP)
9292 outs() << "FP_RND_UP ";
9293 else if (fpu.fpu_fcw.rc == MachO::x86_FP_CHOP)
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009294 outs() << "FP_CHOP ";
Kevin Enderby48ef5342014-12-23 22:56:39 +00009295 outs() << "\n";
9296 outs() << "\t status: invalid " << fpu.fpu_fsw.invalid;
9297 outs() << " denorm " << fpu.fpu_fsw.denorm;
9298 outs() << " zdiv " << fpu.fpu_fsw.zdiv;
9299 outs() << " ovrfl " << fpu.fpu_fsw.ovrfl;
9300 outs() << " undfl " << fpu.fpu_fsw.undfl;
9301 outs() << " precis " << fpu.fpu_fsw.precis;
9302 outs() << " stkflt " << fpu.fpu_fsw.stkflt << "\n";
9303 outs() << "\t errsumm " << fpu.fpu_fsw.errsumm;
9304 outs() << " c0 " << fpu.fpu_fsw.c0;
9305 outs() << " c1 " << fpu.fpu_fsw.c1;
9306 outs() << " c2 " << fpu.fpu_fsw.c2;
9307 outs() << " tos " << fpu.fpu_fsw.tos;
9308 outs() << " c3 " << fpu.fpu_fsw.c3;
9309 outs() << " busy " << fpu.fpu_fsw.busy << "\n";
9310 outs() << "\t fpu_ftw " << format("0x%02" PRIx32, fpu.fpu_ftw);
9311 outs() << " fpu_rsrv1 " << format("0x%02" PRIx32, fpu.fpu_rsrv1);
9312 outs() << " fpu_fop " << format("0x%04" PRIx32, fpu.fpu_fop);
9313 outs() << " fpu_ip " << format("0x%08" PRIx32, fpu.fpu_ip) << "\n";
9314 outs() << "\t fpu_cs " << format("0x%04" PRIx32, fpu.fpu_cs);
9315 outs() << " fpu_rsrv2 " << format("0x%04" PRIx32, fpu.fpu_rsrv2);
9316 outs() << " fpu_dp " << format("0x%08" PRIx32, fpu.fpu_dp);
9317 outs() << " fpu_ds " << format("0x%04" PRIx32, fpu.fpu_ds) << "\n";
9318 outs() << "\t fpu_rsrv3 " << format("0x%04" PRIx32, fpu.fpu_rsrv3);
9319 outs() << " fpu_mxcsr " << format("0x%08" PRIx32, fpu.fpu_mxcsr);
9320 outs() << " fpu_mxcsrmask " << format("0x%08" PRIx32, fpu.fpu_mxcsrmask);
9321 outs() << "\n";
9322 outs() << "\t fpu_stmm0:\n";
9323 Print_mmst_reg(fpu.fpu_stmm0);
9324 outs() << "\t fpu_stmm1:\n";
9325 Print_mmst_reg(fpu.fpu_stmm1);
9326 outs() << "\t fpu_stmm2:\n";
9327 Print_mmst_reg(fpu.fpu_stmm2);
9328 outs() << "\t fpu_stmm3:\n";
9329 Print_mmst_reg(fpu.fpu_stmm3);
9330 outs() << "\t fpu_stmm4:\n";
9331 Print_mmst_reg(fpu.fpu_stmm4);
9332 outs() << "\t fpu_stmm5:\n";
9333 Print_mmst_reg(fpu.fpu_stmm5);
9334 outs() << "\t fpu_stmm6:\n";
9335 Print_mmst_reg(fpu.fpu_stmm6);
9336 outs() << "\t fpu_stmm7:\n";
9337 Print_mmst_reg(fpu.fpu_stmm7);
9338 outs() << "\t fpu_xmm0:\n";
9339 Print_xmm_reg(fpu.fpu_xmm0);
9340 outs() << "\t fpu_xmm1:\n";
9341 Print_xmm_reg(fpu.fpu_xmm1);
9342 outs() << "\t fpu_xmm2:\n";
9343 Print_xmm_reg(fpu.fpu_xmm2);
9344 outs() << "\t fpu_xmm3:\n";
9345 Print_xmm_reg(fpu.fpu_xmm3);
9346 outs() << "\t fpu_xmm4:\n";
9347 Print_xmm_reg(fpu.fpu_xmm4);
9348 outs() << "\t fpu_xmm5:\n";
9349 Print_xmm_reg(fpu.fpu_xmm5);
9350 outs() << "\t fpu_xmm6:\n";
9351 Print_xmm_reg(fpu.fpu_xmm6);
9352 outs() << "\t fpu_xmm7:\n";
9353 Print_xmm_reg(fpu.fpu_xmm7);
9354 outs() << "\t fpu_xmm8:\n";
9355 Print_xmm_reg(fpu.fpu_xmm8);
9356 outs() << "\t fpu_xmm9:\n";
9357 Print_xmm_reg(fpu.fpu_xmm9);
9358 outs() << "\t fpu_xmm10:\n";
9359 Print_xmm_reg(fpu.fpu_xmm10);
9360 outs() << "\t fpu_xmm11:\n";
9361 Print_xmm_reg(fpu.fpu_xmm11);
9362 outs() << "\t fpu_xmm12:\n";
9363 Print_xmm_reg(fpu.fpu_xmm12);
9364 outs() << "\t fpu_xmm13:\n";
9365 Print_xmm_reg(fpu.fpu_xmm13);
9366 outs() << "\t fpu_xmm14:\n";
9367 Print_xmm_reg(fpu.fpu_xmm14);
9368 outs() << "\t fpu_xmm15:\n";
9369 Print_xmm_reg(fpu.fpu_xmm15);
9370 outs() << "\t fpu_rsrv4:\n";
9371 for (uint32_t f = 0; f < 6; f++) {
9372 outs() << "\t ";
9373 for (uint32_t g = 0; g < 16; g++)
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009374 outs() << format("%02" PRIx32, fpu.fpu_rsrv4[f * g]) << " ";
Kevin Enderby48ef5342014-12-23 22:56:39 +00009375 outs() << "\n";
9376 }
9377 outs() << "\t fpu_reserved1 " << format("0x%08" PRIx32, fpu.fpu_reserved1);
9378 outs() << "\n";
9379}
9380
9381static void Print_x86_exception_state_t(MachO::x86_exception_state64_t &exc64) {
9382 outs() << "\t trapno " << format("0x%08" PRIx32, exc64.trapno);
9383 outs() << " err " << format("0x%08" PRIx32, exc64.err);
9384 outs() << " faultvaddr " << format("0x%016" PRIx64, exc64.faultvaddr) << "\n";
9385}
9386
Kevin Enderby41c9c002016-10-21 18:22:35 +00009387static void Print_arm_thread_state32_t(MachO::arm_thread_state32_t &cpu32) {
9388 outs() << "\t r0 " << format("0x%08" PRIx32, cpu32.r[0]);
9389 outs() << " r1 " << format("0x%08" PRIx32, cpu32.r[1]);
9390 outs() << " r2 " << format("0x%08" PRIx32, cpu32.r[2]);
9391 outs() << " r3 " << format("0x%08" PRIx32, cpu32.r[3]) << "\n";
9392 outs() << "\t r4 " << format("0x%08" PRIx32, cpu32.r[4]);
9393 outs() << " r5 " << format("0x%08" PRIx32, cpu32.r[5]);
9394 outs() << " r6 " << format("0x%08" PRIx32, cpu32.r[6]);
9395 outs() << " r7 " << format("0x%08" PRIx32, cpu32.r[7]) << "\n";
9396 outs() << "\t r8 " << format("0x%08" PRIx32, cpu32.r[8]);
9397 outs() << " r9 " << format("0x%08" PRIx32, cpu32.r[9]);
9398 outs() << " r10 " << format("0x%08" PRIx32, cpu32.r[10]);
9399 outs() << " r11 " << format("0x%08" PRIx32, cpu32.r[11]) << "\n";
9400 outs() << "\t r12 " << format("0x%08" PRIx32, cpu32.r[12]);
9401 outs() << " sp " << format("0x%08" PRIx32, cpu32.sp);
9402 outs() << " lr " << format("0x%08" PRIx32, cpu32.lr);
9403 outs() << " pc " << format("0x%08" PRIx32, cpu32.pc) << "\n";
9404 outs() << "\t cpsr " << format("0x%08" PRIx32, cpu32.cpsr) << "\n";
9405}
9406
Kevin Enderby7747cb52016-11-03 20:51:28 +00009407static void Print_arm_thread_state64_t(MachO::arm_thread_state64_t &cpu64) {
9408 outs() << "\t x0 " << format("0x%016" PRIx64, cpu64.x[0]);
9409 outs() << " x1 " << format("0x%016" PRIx64, cpu64.x[1]);
9410 outs() << " x2 " << format("0x%016" PRIx64, cpu64.x[2]) << "\n";
9411 outs() << "\t x3 " << format("0x%016" PRIx64, cpu64.x[3]);
9412 outs() << " x4 " << format("0x%016" PRIx64, cpu64.x[4]);
9413 outs() << " x5 " << format("0x%016" PRIx64, cpu64.x[5]) << "\n";
9414 outs() << "\t x6 " << format("0x%016" PRIx64, cpu64.x[6]);
9415 outs() << " x7 " << format("0x%016" PRIx64, cpu64.x[7]);
9416 outs() << " x8 " << format("0x%016" PRIx64, cpu64.x[8]) << "\n";
9417 outs() << "\t x9 " << format("0x%016" PRIx64, cpu64.x[9]);
9418 outs() << " x10 " << format("0x%016" PRIx64, cpu64.x[10]);
9419 outs() << " x11 " << format("0x%016" PRIx64, cpu64.x[11]) << "\n";
9420 outs() << "\t x12 " << format("0x%016" PRIx64, cpu64.x[12]);
9421 outs() << " x13 " << format("0x%016" PRIx64, cpu64.x[13]);
9422 outs() << " x14 " << format("0x%016" PRIx64, cpu64.x[14]) << "\n";
9423 outs() << "\t x15 " << format("0x%016" PRIx64, cpu64.x[15]);
9424 outs() << " x16 " << format("0x%016" PRIx64, cpu64.x[16]);
9425 outs() << " x17 " << format("0x%016" PRIx64, cpu64.x[17]) << "\n";
9426 outs() << "\t x18 " << format("0x%016" PRIx64, cpu64.x[18]);
9427 outs() << " x19 " << format("0x%016" PRIx64, cpu64.x[19]);
9428 outs() << " x20 " << format("0x%016" PRIx64, cpu64.x[20]) << "\n";
9429 outs() << "\t x21 " << format("0x%016" PRIx64, cpu64.x[21]);
9430 outs() << " x22 " << format("0x%016" PRIx64, cpu64.x[22]);
9431 outs() << " x23 " << format("0x%016" PRIx64, cpu64.x[23]) << "\n";
9432 outs() << "\t x24 " << format("0x%016" PRIx64, cpu64.x[24]);
9433 outs() << " x25 " << format("0x%016" PRIx64, cpu64.x[25]);
9434 outs() << " x26 " << format("0x%016" PRIx64, cpu64.x[26]) << "\n";
9435 outs() << "\t x27 " << format("0x%016" PRIx64, cpu64.x[27]);
9436 outs() << " x28 " << format("0x%016" PRIx64, cpu64.x[28]);
9437 outs() << " fp " << format("0x%016" PRIx64, cpu64.fp) << "\n";
9438 outs() << "\t lr " << format("0x%016" PRIx64, cpu64.lr);
9439 outs() << " sp " << format("0x%016" PRIx64, cpu64.sp);
9440 outs() << " pc " << format("0x%016" PRIx64, cpu64.pc) << "\n";
9441 outs() << "\t cpsr " << format("0x%08" PRIx32, cpu64.cpsr) << "\n";
9442}
9443
Kevin Enderby48ef5342014-12-23 22:56:39 +00009444static void PrintThreadCommand(MachO::thread_command t, const char *Ptr,
9445 bool isLittleEndian, uint32_t cputype) {
9446 if (t.cmd == MachO::LC_THREAD)
9447 outs() << " cmd LC_THREAD\n";
9448 else if (t.cmd == MachO::LC_UNIXTHREAD)
9449 outs() << " cmd LC_UNIXTHREAD\n";
9450 else
9451 outs() << " cmd " << t.cmd << " (unknown)\n";
9452 outs() << " cmdsize " << t.cmdsize;
9453 if (t.cmdsize < sizeof(struct MachO::thread_command) + 2 * sizeof(uint32_t))
9454 outs() << " Incorrect size\n";
9455 else
9456 outs() << "\n";
9457
9458 const char *begin = Ptr + sizeof(struct MachO::thread_command);
9459 const char *end = Ptr + t.cmdsize;
9460 uint32_t flavor, count, left;
Kevin Enderbyc3a035d2017-01-23 21:13:29 +00009461 if (cputype == MachO::CPU_TYPE_I386) {
9462 while (begin < end) {
9463 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9464 memcpy((char *)&flavor, begin, sizeof(uint32_t));
9465 begin += sizeof(uint32_t);
9466 } else {
9467 flavor = 0;
9468 begin = end;
9469 }
9470 if (isLittleEndian != sys::IsLittleEndianHost)
9471 sys::swapByteOrder(flavor);
9472 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9473 memcpy((char *)&count, begin, sizeof(uint32_t));
9474 begin += sizeof(uint32_t);
9475 } else {
9476 count = 0;
9477 begin = end;
9478 }
9479 if (isLittleEndian != sys::IsLittleEndianHost)
9480 sys::swapByteOrder(count);
9481 if (flavor == MachO::x86_THREAD_STATE32) {
9482 outs() << " flavor i386_THREAD_STATE\n";
9483 if (count == MachO::x86_THREAD_STATE32_COUNT)
9484 outs() << " count i386_THREAD_STATE_COUNT\n";
9485 else
9486 outs() << " count " << count
9487 << " (not x86_THREAD_STATE32_COUNT)\n";
9488 MachO::x86_thread_state32_t cpu32;
9489 left = end - begin;
9490 if (left >= sizeof(MachO::x86_thread_state32_t)) {
9491 memcpy(&cpu32, begin, sizeof(MachO::x86_thread_state32_t));
9492 begin += sizeof(MachO::x86_thread_state32_t);
9493 } else {
9494 memset(&cpu32, '\0', sizeof(MachO::x86_thread_state32_t));
9495 memcpy(&cpu32, begin, left);
9496 begin += left;
9497 }
9498 if (isLittleEndian != sys::IsLittleEndianHost)
9499 swapStruct(cpu32);
9500 Print_x86_thread_state32_t(cpu32);
9501 } else if (flavor == MachO::x86_THREAD_STATE) {
9502 outs() << " flavor x86_THREAD_STATE\n";
9503 if (count == MachO::x86_THREAD_STATE_COUNT)
9504 outs() << " count x86_THREAD_STATE_COUNT\n";
9505 else
9506 outs() << " count " << count
9507 << " (not x86_THREAD_STATE_COUNT)\n";
9508 struct MachO::x86_thread_state_t ts;
9509 left = end - begin;
9510 if (left >= sizeof(MachO::x86_thread_state_t)) {
9511 memcpy(&ts, begin, sizeof(MachO::x86_thread_state_t));
9512 begin += sizeof(MachO::x86_thread_state_t);
9513 } else {
9514 memset(&ts, '\0', sizeof(MachO::x86_thread_state_t));
9515 memcpy(&ts, begin, left);
9516 begin += left;
9517 }
9518 if (isLittleEndian != sys::IsLittleEndianHost)
9519 swapStruct(ts);
9520 if (ts.tsh.flavor == MachO::x86_THREAD_STATE32) {
9521 outs() << "\t tsh.flavor x86_THREAD_STATE32 ";
9522 if (ts.tsh.count == MachO::x86_THREAD_STATE32_COUNT)
9523 outs() << "tsh.count x86_THREAD_STATE32_COUNT\n";
9524 else
9525 outs() << "tsh.count " << ts.tsh.count
9526 << " (not x86_THREAD_STATE32_COUNT\n";
9527 Print_x86_thread_state32_t(ts.uts.ts32);
9528 } else {
9529 outs() << "\t tsh.flavor " << ts.tsh.flavor << " tsh.count "
9530 << ts.tsh.count << "\n";
9531 }
9532 } else {
9533 outs() << " flavor " << flavor << " (unknown)\n";
9534 outs() << " count " << count << "\n";
9535 outs() << " state (unknown)\n";
9536 begin += count * sizeof(uint32_t);
9537 }
9538 }
9539 } else if (cputype == MachO::CPU_TYPE_X86_64) {
Kevin Enderby48ef5342014-12-23 22:56:39 +00009540 while (begin < end) {
9541 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9542 memcpy((char *)&flavor, begin, sizeof(uint32_t));
9543 begin += sizeof(uint32_t);
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009544 } else {
Kevin Enderby48ef5342014-12-23 22:56:39 +00009545 flavor = 0;
9546 begin = end;
9547 }
9548 if (isLittleEndian != sys::IsLittleEndianHost)
9549 sys::swapByteOrder(flavor);
9550 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9551 memcpy((char *)&count, begin, sizeof(uint32_t));
9552 begin += sizeof(uint32_t);
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009553 } else {
Kevin Enderby48ef5342014-12-23 22:56:39 +00009554 count = 0;
9555 begin = end;
9556 }
9557 if (isLittleEndian != sys::IsLittleEndianHost)
9558 sys::swapByteOrder(count);
9559 if (flavor == MachO::x86_THREAD_STATE64) {
9560 outs() << " flavor x86_THREAD_STATE64\n";
9561 if (count == MachO::x86_THREAD_STATE64_COUNT)
9562 outs() << " count x86_THREAD_STATE64_COUNT\n";
9563 else
9564 outs() << " count " << count
9565 << " (not x86_THREAD_STATE64_COUNT)\n";
9566 MachO::x86_thread_state64_t cpu64;
9567 left = end - begin;
9568 if (left >= sizeof(MachO::x86_thread_state64_t)) {
9569 memcpy(&cpu64, begin, sizeof(MachO::x86_thread_state64_t));
9570 begin += sizeof(MachO::x86_thread_state64_t);
9571 } else {
9572 memset(&cpu64, '\0', sizeof(MachO::x86_thread_state64_t));
9573 memcpy(&cpu64, begin, left);
9574 begin += left;
9575 }
9576 if (isLittleEndian != sys::IsLittleEndianHost)
9577 swapStruct(cpu64);
9578 Print_x86_thread_state64_t(cpu64);
9579 } else if (flavor == MachO::x86_THREAD_STATE) {
9580 outs() << " flavor x86_THREAD_STATE\n";
9581 if (count == MachO::x86_THREAD_STATE_COUNT)
9582 outs() << " count x86_THREAD_STATE_COUNT\n";
9583 else
9584 outs() << " count " << count
9585 << " (not x86_THREAD_STATE_COUNT)\n";
9586 struct MachO::x86_thread_state_t ts;
9587 left = end - begin;
9588 if (left >= sizeof(MachO::x86_thread_state_t)) {
9589 memcpy(&ts, begin, sizeof(MachO::x86_thread_state_t));
9590 begin += sizeof(MachO::x86_thread_state_t);
9591 } else {
9592 memset(&ts, '\0', sizeof(MachO::x86_thread_state_t));
9593 memcpy(&ts, begin, left);
9594 begin += left;
9595 }
9596 if (isLittleEndian != sys::IsLittleEndianHost)
9597 swapStruct(ts);
9598 if (ts.tsh.flavor == MachO::x86_THREAD_STATE64) {
9599 outs() << "\t tsh.flavor x86_THREAD_STATE64 ";
9600 if (ts.tsh.count == MachO::x86_THREAD_STATE64_COUNT)
9601 outs() << "tsh.count x86_THREAD_STATE64_COUNT\n";
9602 else
9603 outs() << "tsh.count " << ts.tsh.count
9604 << " (not x86_THREAD_STATE64_COUNT\n";
9605 Print_x86_thread_state64_t(ts.uts.ts64);
9606 } else {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009607 outs() << "\t tsh.flavor " << ts.tsh.flavor << " tsh.count "
9608 << ts.tsh.count << "\n";
Kevin Enderby48ef5342014-12-23 22:56:39 +00009609 }
9610 } else if (flavor == MachO::x86_FLOAT_STATE) {
9611 outs() << " flavor x86_FLOAT_STATE\n";
9612 if (count == MachO::x86_FLOAT_STATE_COUNT)
9613 outs() << " count x86_FLOAT_STATE_COUNT\n";
9614 else
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009615 outs() << " count " << count << " (not x86_FLOAT_STATE_COUNT)\n";
Kevin Enderby48ef5342014-12-23 22:56:39 +00009616 struct MachO::x86_float_state_t fs;
9617 left = end - begin;
9618 if (left >= sizeof(MachO::x86_float_state_t)) {
9619 memcpy(&fs, begin, sizeof(MachO::x86_float_state_t));
9620 begin += sizeof(MachO::x86_float_state_t);
9621 } else {
9622 memset(&fs, '\0', sizeof(MachO::x86_float_state_t));
9623 memcpy(&fs, begin, left);
9624 begin += left;
9625 }
9626 if (isLittleEndian != sys::IsLittleEndianHost)
9627 swapStruct(fs);
9628 if (fs.fsh.flavor == MachO::x86_FLOAT_STATE64) {
9629 outs() << "\t fsh.flavor x86_FLOAT_STATE64 ";
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009630 if (fs.fsh.count == MachO::x86_FLOAT_STATE64_COUNT)
Kevin Enderby48ef5342014-12-23 22:56:39 +00009631 outs() << "fsh.count x86_FLOAT_STATE64_COUNT\n";
9632 else
9633 outs() << "fsh.count " << fs.fsh.count
9634 << " (not x86_FLOAT_STATE64_COUNT\n";
9635 Print_x86_float_state_t(fs.ufs.fs64);
9636 } else {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009637 outs() << "\t fsh.flavor " << fs.fsh.flavor << " fsh.count "
9638 << fs.fsh.count << "\n";
Kevin Enderby48ef5342014-12-23 22:56:39 +00009639 }
9640 } else if (flavor == MachO::x86_EXCEPTION_STATE) {
9641 outs() << " flavor x86_EXCEPTION_STATE\n";
9642 if (count == MachO::x86_EXCEPTION_STATE_COUNT)
9643 outs() << " count x86_EXCEPTION_STATE_COUNT\n";
9644 else
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009645 outs() << " count " << count
Kevin Enderby48ef5342014-12-23 22:56:39 +00009646 << " (not x86_EXCEPTION_STATE_COUNT)\n";
9647 struct MachO::x86_exception_state_t es;
9648 left = end - begin;
9649 if (left >= sizeof(MachO::x86_exception_state_t)) {
9650 memcpy(&es, begin, sizeof(MachO::x86_exception_state_t));
9651 begin += sizeof(MachO::x86_exception_state_t);
9652 } else {
9653 memset(&es, '\0', sizeof(MachO::x86_exception_state_t));
9654 memcpy(&es, begin, left);
9655 begin += left;
9656 }
9657 if (isLittleEndian != sys::IsLittleEndianHost)
9658 swapStruct(es);
9659 if (es.esh.flavor == MachO::x86_EXCEPTION_STATE64) {
9660 outs() << "\t esh.flavor x86_EXCEPTION_STATE64\n";
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009661 if (es.esh.count == MachO::x86_EXCEPTION_STATE64_COUNT)
Kevin Enderby48ef5342014-12-23 22:56:39 +00009662 outs() << "\t esh.count x86_EXCEPTION_STATE64_COUNT\n";
9663 else
9664 outs() << "\t esh.count " << es.esh.count
9665 << " (not x86_EXCEPTION_STATE64_COUNT\n";
9666 Print_x86_exception_state_t(es.ues.es64);
9667 } else {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009668 outs() << "\t esh.flavor " << es.esh.flavor << " esh.count "
9669 << es.esh.count << "\n";
Kevin Enderby48ef5342014-12-23 22:56:39 +00009670 }
Kevin Enderby299cd892018-03-08 23:10:38 +00009671 } else if (flavor == MachO::x86_EXCEPTION_STATE64) {
9672 outs() << " flavor x86_EXCEPTION_STATE64\n";
9673 if (count == MachO::x86_EXCEPTION_STATE64_COUNT)
9674 outs() << " count x86_EXCEPTION_STATE64_COUNT\n";
9675 else
9676 outs() << " count " << count
9677 << " (not x86_EXCEPTION_STATE64_COUNT)\n";
9678 struct MachO::x86_exception_state64_t es64;
9679 left = end - begin;
9680 if (left >= sizeof(MachO::x86_exception_state64_t)) {
9681 memcpy(&es64, begin, sizeof(MachO::x86_exception_state64_t));
9682 begin += sizeof(MachO::x86_exception_state64_t);
9683 } else {
9684 memset(&es64, '\0', sizeof(MachO::x86_exception_state64_t));
9685 memcpy(&es64, begin, left);
9686 begin += left;
9687 }
9688 if (isLittleEndian != sys::IsLittleEndianHost)
9689 swapStruct(es64);
9690 Print_x86_exception_state_t(es64);
Kevin Enderby48ef5342014-12-23 22:56:39 +00009691 } else {
9692 outs() << " flavor " << flavor << " (unknown)\n";
9693 outs() << " count " << count << "\n";
9694 outs() << " state (unknown)\n";
9695 begin += count * sizeof(uint32_t);
9696 }
9697 }
Kevin Enderby41c9c002016-10-21 18:22:35 +00009698 } else if (cputype == MachO::CPU_TYPE_ARM) {
9699 while (begin < end) {
9700 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9701 memcpy((char *)&flavor, begin, sizeof(uint32_t));
9702 begin += sizeof(uint32_t);
9703 } else {
9704 flavor = 0;
9705 begin = end;
9706 }
9707 if (isLittleEndian != sys::IsLittleEndianHost)
9708 sys::swapByteOrder(flavor);
9709 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9710 memcpy((char *)&count, begin, sizeof(uint32_t));
9711 begin += sizeof(uint32_t);
9712 } else {
9713 count = 0;
9714 begin = end;
9715 }
9716 if (isLittleEndian != sys::IsLittleEndianHost)
9717 sys::swapByteOrder(count);
9718 if (flavor == MachO::ARM_THREAD_STATE) {
9719 outs() << " flavor ARM_THREAD_STATE\n";
9720 if (count == MachO::ARM_THREAD_STATE_COUNT)
9721 outs() << " count ARM_THREAD_STATE_COUNT\n";
9722 else
9723 outs() << " count " << count
9724 << " (not ARM_THREAD_STATE_COUNT)\n";
9725 MachO::arm_thread_state32_t cpu32;
9726 left = end - begin;
9727 if (left >= sizeof(MachO::arm_thread_state32_t)) {
9728 memcpy(&cpu32, begin, sizeof(MachO::arm_thread_state32_t));
9729 begin += sizeof(MachO::arm_thread_state32_t);
9730 } else {
9731 memset(&cpu32, '\0', sizeof(MachO::arm_thread_state32_t));
9732 memcpy(&cpu32, begin, left);
9733 begin += left;
9734 }
9735 if (isLittleEndian != sys::IsLittleEndianHost)
9736 swapStruct(cpu32);
9737 Print_arm_thread_state32_t(cpu32);
9738 } else {
9739 outs() << " flavor " << flavor << " (unknown)\n";
9740 outs() << " count " << count << "\n";
9741 outs() << " state (unknown)\n";
9742 begin += count * sizeof(uint32_t);
9743 }
9744 }
Kevin Enderby7747cb52016-11-03 20:51:28 +00009745 } else if (cputype == MachO::CPU_TYPE_ARM64) {
9746 while (begin < end) {
9747 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9748 memcpy((char *)&flavor, begin, sizeof(uint32_t));
9749 begin += sizeof(uint32_t);
9750 } else {
9751 flavor = 0;
9752 begin = end;
9753 }
9754 if (isLittleEndian != sys::IsLittleEndianHost)
9755 sys::swapByteOrder(flavor);
9756 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9757 memcpy((char *)&count, begin, sizeof(uint32_t));
9758 begin += sizeof(uint32_t);
9759 } else {
9760 count = 0;
9761 begin = end;
9762 }
9763 if (isLittleEndian != sys::IsLittleEndianHost)
9764 sys::swapByteOrder(count);
9765 if (flavor == MachO::ARM_THREAD_STATE64) {
9766 outs() << " flavor ARM_THREAD_STATE64\n";
9767 if (count == MachO::ARM_THREAD_STATE64_COUNT)
9768 outs() << " count ARM_THREAD_STATE64_COUNT\n";
9769 else
9770 outs() << " count " << count
9771 << " (not ARM_THREAD_STATE64_COUNT)\n";
9772 MachO::arm_thread_state64_t cpu64;
9773 left = end - begin;
9774 if (left >= sizeof(MachO::arm_thread_state64_t)) {
9775 memcpy(&cpu64, begin, sizeof(MachO::arm_thread_state64_t));
9776 begin += sizeof(MachO::arm_thread_state64_t);
9777 } else {
9778 memset(&cpu64, '\0', sizeof(MachO::arm_thread_state64_t));
9779 memcpy(&cpu64, begin, left);
9780 begin += left;
9781 }
9782 if (isLittleEndian != sys::IsLittleEndianHost)
9783 swapStruct(cpu64);
9784 Print_arm_thread_state64_t(cpu64);
9785 } else {
9786 outs() << " flavor " << flavor << " (unknown)\n";
9787 outs() << " count " << count << "\n";
9788 outs() << " state (unknown)\n";
9789 begin += count * sizeof(uint32_t);
9790 }
9791 }
Kevin Enderby48ef5342014-12-23 22:56:39 +00009792 } else {
9793 while (begin < end) {
9794 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9795 memcpy((char *)&flavor, begin, sizeof(uint32_t));
9796 begin += sizeof(uint32_t);
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009797 } else {
Kevin Enderby48ef5342014-12-23 22:56:39 +00009798 flavor = 0;
9799 begin = end;
9800 }
9801 if (isLittleEndian != sys::IsLittleEndianHost)
9802 sys::swapByteOrder(flavor);
9803 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9804 memcpy((char *)&count, begin, sizeof(uint32_t));
9805 begin += sizeof(uint32_t);
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009806 } else {
Kevin Enderby48ef5342014-12-23 22:56:39 +00009807 count = 0;
9808 begin = end;
9809 }
9810 if (isLittleEndian != sys::IsLittleEndianHost)
9811 sys::swapByteOrder(count);
9812 outs() << " flavor " << flavor << "\n";
9813 outs() << " count " << count << "\n";
9814 outs() << " state (Unknown cputype/cpusubtype)\n";
9815 begin += count * sizeof(uint32_t);
9816 }
9817 }
9818}
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009819
Kevin Enderby8ae63c12014-09-04 16:54:47 +00009820static void PrintDylibCommand(MachO::dylib_command dl, const char *Ptr) {
9821 if (dl.cmd == MachO::LC_ID_DYLIB)
9822 outs() << " cmd LC_ID_DYLIB\n";
9823 else if (dl.cmd == MachO::LC_LOAD_DYLIB)
9824 outs() << " cmd LC_LOAD_DYLIB\n";
9825 else if (dl.cmd == MachO::LC_LOAD_WEAK_DYLIB)
9826 outs() << " cmd LC_LOAD_WEAK_DYLIB\n";
9827 else if (dl.cmd == MachO::LC_REEXPORT_DYLIB)
9828 outs() << " cmd LC_REEXPORT_DYLIB\n";
9829 else if (dl.cmd == MachO::LC_LAZY_LOAD_DYLIB)
9830 outs() << " cmd LC_LAZY_LOAD_DYLIB\n";
9831 else if (dl.cmd == MachO::LC_LOAD_UPWARD_DYLIB)
9832 outs() << " cmd LC_LOAD_UPWARD_DYLIB\n";
9833 else
9834 outs() << " cmd " << dl.cmd << " (unknown)\n";
9835 outs() << " cmdsize " << dl.cmdsize;
9836 if (dl.cmdsize < sizeof(struct MachO::dylib_command))
9837 outs() << " Incorrect size\n";
9838 else
9839 outs() << "\n";
9840 if (dl.dylib.name < dl.cmdsize) {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00009841 const char *P = (const char *)(Ptr) + dl.dylib.name;
Kevin Enderby8ae63c12014-09-04 16:54:47 +00009842 outs() << " name " << P << " (offset " << dl.dylib.name << ")\n";
9843 } else {
9844 outs() << " name ?(bad offset " << dl.dylib.name << ")\n";
9845 }
9846 outs() << " time stamp " << dl.dylib.timestamp << " ";
9847 time_t t = dl.dylib.timestamp;
9848 outs() << ctime(&t);
9849 outs() << " current version ";
9850 if (dl.dylib.current_version == 0xffffffff)
9851 outs() << "n/a\n";
9852 else
9853 outs() << ((dl.dylib.current_version >> 16) & 0xffff) << "."
9854 << ((dl.dylib.current_version >> 8) & 0xff) << "."
9855 << (dl.dylib.current_version & 0xff) << "\n";
9856 outs() << "compatibility version ";
9857 if (dl.dylib.compatibility_version == 0xffffffff)
9858 outs() << "n/a\n";
9859 else
9860 outs() << ((dl.dylib.compatibility_version >> 16) & 0xffff) << "."
9861 << ((dl.dylib.compatibility_version >> 8) & 0xff) << "."
9862 << (dl.dylib.compatibility_version & 0xff) << "\n";
9863}
9864
9865static void PrintLinkEditDataCommand(MachO::linkedit_data_command ld,
9866 uint32_t object_size) {
9867 if (ld.cmd == MachO::LC_CODE_SIGNATURE)
Kevin Enderby1be37a32016-04-28 21:07:20 +00009868 outs() << " cmd LC_CODE_SIGNATURE\n";
Kevin Enderby8ae63c12014-09-04 16:54:47 +00009869 else if (ld.cmd == MachO::LC_SEGMENT_SPLIT_INFO)
9870 outs() << " cmd LC_SEGMENT_SPLIT_INFO\n";
9871 else if (ld.cmd == MachO::LC_FUNCTION_STARTS)
9872 outs() << " cmd LC_FUNCTION_STARTS\n";
9873 else if (ld.cmd == MachO::LC_DATA_IN_CODE)
9874 outs() << " cmd LC_DATA_IN_CODE\n";
9875 else if (ld.cmd == MachO::LC_DYLIB_CODE_SIGN_DRS)
9876 outs() << " cmd LC_DYLIB_CODE_SIGN_DRS\n";
9877 else if (ld.cmd == MachO::LC_LINKER_OPTIMIZATION_HINT)
9878 outs() << " cmd LC_LINKER_OPTIMIZATION_HINT\n";
9879 else
9880 outs() << " cmd " << ld.cmd << " (?)\n";
9881 outs() << " cmdsize " << ld.cmdsize;
9882 if (ld.cmdsize != sizeof(struct MachO::linkedit_data_command))
9883 outs() << " Incorrect size\n";
9884 else
9885 outs() << "\n";
9886 outs() << " dataoff " << ld.dataoff;
9887 if (ld.dataoff > object_size)
9888 outs() << " (past end of file)\n";
9889 else
9890 outs() << "\n";
9891 outs() << " datasize " << ld.datasize;
9892 uint64_t big_size = ld.dataoff;
9893 big_size += ld.datasize;
9894 if (big_size > object_size)
9895 outs() << " (past end of file)\n";
9896 else
9897 outs() << "\n";
9898}
9899
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00009900static void PrintLoadCommands(const MachOObjectFile *Obj, uint32_t filetype,
9901 uint32_t cputype, bool verbose) {
Kevin Enderby956366c2014-08-29 22:30:52 +00009902 StringRef Buf = Obj->getData();
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00009903 unsigned Index = 0;
9904 for (const auto &Command : Obj->load_commands()) {
9905 outs() << "Load command " << Index++ << "\n";
Kevin Enderby956366c2014-08-29 22:30:52 +00009906 if (Command.C.cmd == MachO::LC_SEGMENT) {
9907 MachO::segment_command SLC = Obj->getSegmentLoadCommand(Command);
9908 const char *sg_segname = SLC.segname;
9909 PrintSegmentCommand(SLC.cmd, SLC.cmdsize, SLC.segname, SLC.vmaddr,
9910 SLC.vmsize, SLC.fileoff, SLC.filesize, SLC.maxprot,
9911 SLC.initprot, SLC.nsects, SLC.flags, Buf.size(),
9912 verbose);
9913 for (unsigned j = 0; j < SLC.nsects; j++) {
Kevin Enderbyc9713382014-12-16 01:14:45 +00009914 MachO::section S = Obj->getSection(Command, j);
Kevin Enderby956366c2014-08-29 22:30:52 +00009915 PrintSection(S.sectname, S.segname, S.addr, S.size, S.offset, S.align,
9916 S.reloff, S.nreloc, S.flags, S.reserved1, S.reserved2,
9917 SLC.cmd, sg_segname, filetype, Buf.size(), verbose);
9918 }
9919 } else if (Command.C.cmd == MachO::LC_SEGMENT_64) {
9920 MachO::segment_command_64 SLC_64 = Obj->getSegment64LoadCommand(Command);
9921 const char *sg_segname = SLC_64.segname;
9922 PrintSegmentCommand(SLC_64.cmd, SLC_64.cmdsize, SLC_64.segname,
9923 SLC_64.vmaddr, SLC_64.vmsize, SLC_64.fileoff,
9924 SLC_64.filesize, SLC_64.maxprot, SLC_64.initprot,
9925 SLC_64.nsects, SLC_64.flags, Buf.size(), verbose);
9926 for (unsigned j = 0; j < SLC_64.nsects; j++) {
9927 MachO::section_64 S_64 = Obj->getSection64(Command, j);
9928 PrintSection(S_64.sectname, S_64.segname, S_64.addr, S_64.size,
9929 S_64.offset, S_64.align, S_64.reloff, S_64.nreloc,
9930 S_64.flags, S_64.reserved1, S_64.reserved2, SLC_64.cmd,
9931 sg_segname, filetype, Buf.size(), verbose);
9932 }
9933 } else if (Command.C.cmd == MachO::LC_SYMTAB) {
9934 MachO::symtab_command Symtab = Obj->getSymtabLoadCommand();
David Majnemer73cc6ff2014-11-13 19:48:56 +00009935 PrintSymtabLoadCommand(Symtab, Obj->is64Bit(), Buf.size());
Kevin Enderby956366c2014-08-29 22:30:52 +00009936 } else if (Command.C.cmd == MachO::LC_DYSYMTAB) {
9937 MachO::dysymtab_command Dysymtab = Obj->getDysymtabLoadCommand();
9938 MachO::symtab_command Symtab = Obj->getSymtabLoadCommand();
David Majnemer73cc6ff2014-11-13 19:48:56 +00009939 PrintDysymtabLoadCommand(Dysymtab, Symtab.nsyms, Buf.size(),
9940 Obj->is64Bit());
Kevin Enderby8ae63c12014-09-04 16:54:47 +00009941 } else if (Command.C.cmd == MachO::LC_DYLD_INFO ||
9942 Command.C.cmd == MachO::LC_DYLD_INFO_ONLY) {
9943 MachO::dyld_info_command DyldInfo = Obj->getDyldInfoLoadCommand(Command);
9944 PrintDyldInfoLoadCommand(DyldInfo, Buf.size());
9945 } else if (Command.C.cmd == MachO::LC_LOAD_DYLINKER ||
9946 Command.C.cmd == MachO::LC_ID_DYLINKER ||
9947 Command.C.cmd == MachO::LC_DYLD_ENVIRONMENT) {
9948 MachO::dylinker_command Dyld = Obj->getDylinkerCommand(Command);
9949 PrintDyldLoadCommand(Dyld, Command.Ptr);
9950 } else if (Command.C.cmd == MachO::LC_UUID) {
9951 MachO::uuid_command Uuid = Obj->getUuidCommand(Command);
9952 PrintUuidLoadCommand(Uuid);
Jean-Daniel Dupas00cc1f52014-12-04 07:37:02 +00009953 } else if (Command.C.cmd == MachO::LC_RPATH) {
9954 MachO::rpath_command Rpath = Obj->getRpathCommand(Command);
9955 PrintRpathLoadCommand(Rpath, Command.Ptr);
Kevin Enderby1ff0ecc2014-12-16 21:48:27 +00009956 } else if (Command.C.cmd == MachO::LC_VERSION_MIN_MACOSX ||
Tim Northoverbfbfb122015-11-02 21:26:58 +00009957 Command.C.cmd == MachO::LC_VERSION_MIN_IPHONEOS ||
9958 Command.C.cmd == MachO::LC_VERSION_MIN_TVOS ||
9959 Command.C.cmd == MachO::LC_VERSION_MIN_WATCHOS) {
Kevin Enderby8ae63c12014-09-04 16:54:47 +00009960 MachO::version_min_command Vd = Obj->getVersionMinLoadCommand(Command);
9961 PrintVersionMinLoadCommand(Vd);
Kevin Enderbya4579c42017-01-19 17:36:31 +00009962 } else if (Command.C.cmd == MachO::LC_NOTE) {
9963 MachO::note_command Nt = Obj->getNoteLoadCommand(Command);
9964 PrintNoteLoadCommand(Nt);
Steven Wu5b54a422017-01-23 20:07:55 +00009965 } else if (Command.C.cmd == MachO::LC_BUILD_VERSION) {
9966 MachO::build_version_command Bv =
9967 Obj->getBuildVersionLoadCommand(Command);
9968 PrintBuildVersionLoadCommand(Obj, Bv);
Kevin Enderby8ae63c12014-09-04 16:54:47 +00009969 } else if (Command.C.cmd == MachO::LC_SOURCE_VERSION) {
9970 MachO::source_version_command Sd = Obj->getSourceVersionCommand(Command);
9971 PrintSourceVersionCommand(Sd);
9972 } else if (Command.C.cmd == MachO::LC_MAIN) {
9973 MachO::entry_point_command Ep = Obj->getEntryPointCommand(Command);
9974 PrintEntryPointCommand(Ep);
Kevin Enderby0804f4672014-12-16 23:25:52 +00009975 } else if (Command.C.cmd == MachO::LC_ENCRYPTION_INFO) {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009976 MachO::encryption_info_command Ei =
9977 Obj->getEncryptionInfoCommand(Command);
Kevin Enderby0804f4672014-12-16 23:25:52 +00009978 PrintEncryptionInfoCommand(Ei, Buf.size());
Kevin Enderby57538292014-12-17 01:01:30 +00009979 } else if (Command.C.cmd == MachO::LC_ENCRYPTION_INFO_64) {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009980 MachO::encryption_info_command_64 Ei =
9981 Obj->getEncryptionInfoCommand64(Command);
Kevin Enderby57538292014-12-17 01:01:30 +00009982 PrintEncryptionInfoCommand64(Ei, Buf.size());
Kevin Enderbyd0b6b7f2014-12-18 00:53:40 +00009983 } else if (Command.C.cmd == MachO::LC_LINKER_OPTION) {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009984 MachO::linker_option_command Lo =
9985 Obj->getLinkerOptionLoadCommand(Command);
Kevin Enderbyd0b6b7f2014-12-18 00:53:40 +00009986 PrintLinkerOptionCommand(Lo, Command.Ptr);
Kevin Enderbyb4b79312014-12-18 19:24:35 +00009987 } else if (Command.C.cmd == MachO::LC_SUB_FRAMEWORK) {
9988 MachO::sub_framework_command Sf = Obj->getSubFrameworkCommand(Command);
9989 PrintSubFrameworkCommand(Sf, Command.Ptr);
Kevin Enderbya2bd8d92014-12-18 23:13:26 +00009990 } else if (Command.C.cmd == MachO::LC_SUB_UMBRELLA) {
9991 MachO::sub_umbrella_command Sf = Obj->getSubUmbrellaCommand(Command);
9992 PrintSubUmbrellaCommand(Sf, Command.Ptr);
Kevin Enderby36c8d3a2014-12-19 19:48:16 +00009993 } else if (Command.C.cmd == MachO::LC_SUB_LIBRARY) {
9994 MachO::sub_library_command Sl = Obj->getSubLibraryCommand(Command);
9995 PrintSubLibraryCommand(Sl, Command.Ptr);
Kevin Enderby186eac32014-12-19 21:06:24 +00009996 } else if (Command.C.cmd == MachO::LC_SUB_CLIENT) {
9997 MachO::sub_client_command Sc = Obj->getSubClientCommand(Command);
9998 PrintSubClientCommand(Sc, Command.Ptr);
Kevin Enderby52e4ce42014-12-19 22:25:22 +00009999 } else if (Command.C.cmd == MachO::LC_ROUTINES) {
10000 MachO::routines_command Rc = Obj->getRoutinesCommand(Command);
10001 PrintRoutinesCommand(Rc);
10002 } else if (Command.C.cmd == MachO::LC_ROUTINES_64) {
10003 MachO::routines_command_64 Rc = Obj->getRoutinesCommand64(Command);
10004 PrintRoutinesCommand64(Rc);
Kevin Enderby48ef5342014-12-23 22:56:39 +000010005 } else if (Command.C.cmd == MachO::LC_THREAD ||
10006 Command.C.cmd == MachO::LC_UNIXTHREAD) {
10007 MachO::thread_command Tc = Obj->getThreadCommand(Command);
10008 PrintThreadCommand(Tc, Command.Ptr, Obj->isLittleEndian(), cputype);
Nick Kledzik15558912014-10-16 18:58:20 +000010009 } else if (Command.C.cmd == MachO::LC_LOAD_DYLIB ||
10010 Command.C.cmd == MachO::LC_ID_DYLIB ||
10011 Command.C.cmd == MachO::LC_LOAD_WEAK_DYLIB ||
10012 Command.C.cmd == MachO::LC_REEXPORT_DYLIB ||
10013 Command.C.cmd == MachO::LC_LAZY_LOAD_DYLIB ||
10014 Command.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB) {
Kevin Enderby8ae63c12014-09-04 16:54:47 +000010015 MachO::dylib_command Dl = Obj->getDylibIDLoadCommand(Command);
10016 PrintDylibCommand(Dl, Command.Ptr);
10017 } else if (Command.C.cmd == MachO::LC_CODE_SIGNATURE ||
10018 Command.C.cmd == MachO::LC_SEGMENT_SPLIT_INFO ||
10019 Command.C.cmd == MachO::LC_FUNCTION_STARTS ||
10020 Command.C.cmd == MachO::LC_DATA_IN_CODE ||
10021 Command.C.cmd == MachO::LC_DYLIB_CODE_SIGN_DRS ||
10022 Command.C.cmd == MachO::LC_LINKER_OPTIMIZATION_HINT) {
10023 MachO::linkedit_data_command Ld =
10024 Obj->getLinkeditDataLoadCommand(Command);
10025 PrintLinkEditDataCommand(Ld, Buf.size());
Kevin Enderby956366c2014-08-29 22:30:52 +000010026 } else {
10027 outs() << " cmd ?(" << format("0x%08" PRIx32, Command.C.cmd)
10028 << ")\n";
10029 outs() << " cmdsize " << Command.C.cmdsize << "\n";
10030 // TODO: get and print the raw bytes of the load command.
10031 }
10032 // TODO: print all the other kinds of load commands.
Kevin Enderby956366c2014-08-29 22:30:52 +000010033 }
10034}
10035
Kevin Enderby0ae163f2016-01-13 00:25:36 +000010036static void PrintMachHeader(const MachOObjectFile *Obj, bool verbose) {
Kevin Enderbyb76d3862014-08-22 20:35:18 +000010037 if (Obj->is64Bit()) {
10038 MachO::mach_header_64 H_64;
10039 H_64 = Obj->getHeader64();
10040 PrintMachHeader(H_64.magic, H_64.cputype, H_64.cpusubtype, H_64.filetype,
10041 H_64.ncmds, H_64.sizeofcmds, H_64.flags, verbose);
10042 } else {
10043 MachO::mach_header H;
10044 H = Obj->getHeader();
10045 PrintMachHeader(H.magic, H.cputype, H.cpusubtype, H.filetype, H.ncmds,
10046 H.sizeofcmds, H.flags, verbose);
10047 }
10048}
10049
10050void llvm::printMachOFileHeader(const object::ObjectFile *Obj) {
10051 const MachOObjectFile *file = dyn_cast<const MachOObjectFile>(Obj);
Kevin Enderby0ae163f2016-01-13 00:25:36 +000010052 PrintMachHeader(file, !NonVerbose);
10053}
10054
10055void llvm::printMachOLoadCommands(const object::ObjectFile *Obj) {
10056 const MachOObjectFile *file = dyn_cast<const MachOObjectFile>(Obj);
Kevin Enderby956366c2014-08-29 22:30:52 +000010057 uint32_t filetype = 0;
10058 uint32_t cputype = 0;
Kevin Enderby0ae163f2016-01-13 00:25:36 +000010059 if (file->is64Bit()) {
10060 MachO::mach_header_64 H_64;
10061 H_64 = file->getHeader64();
10062 filetype = H_64.filetype;
10063 cputype = H_64.cputype;
10064 } else {
10065 MachO::mach_header H;
10066 H = file->getHeader();
10067 filetype = H.filetype;
10068 cputype = H.cputype;
10069 }
Alexey Samsonovd319c4f2015-06-03 22:19:36 +000010070 PrintLoadCommands(file, filetype, cputype, !NonVerbose);
Kevin Enderbyb76d3862014-08-22 20:35:18 +000010071}
Nick Kledzikd04bc352014-08-30 00:20:14 +000010072
10073//===----------------------------------------------------------------------===//
10074// export trie dumping
10075//===----------------------------------------------------------------------===//
10076
10077void llvm::printMachOExportsTrie(const object::MachOObjectFile *Obj) {
Kevin Enderby0d5ec112017-06-19 21:23:07 +000010078 uint64_t BaseSegmentAddress = 0;
10079 for (const auto &Command : Obj->load_commands()) {
10080 if (Command.C.cmd == MachO::LC_SEGMENT) {
10081 MachO::segment_command Seg = Obj->getSegmentLoadCommand(Command);
10082 if (Seg.fileoff == 0 && Seg.filesize != 0) {
10083 BaseSegmentAddress = Seg.vmaddr;
10084 break;
10085 }
10086 } else if (Command.C.cmd == MachO::LC_SEGMENT_64) {
10087 MachO::segment_command_64 Seg = Obj->getSegment64LoadCommand(Command);
10088 if (Seg.fileoff == 0 && Seg.filesize != 0) {
10089 BaseSegmentAddress = Seg.vmaddr;
10090 break;
10091 }
10092 }
10093 }
Kevin Enderby3e95bd22017-07-20 23:08:41 +000010094 Error Err = Error::success();
Alexander Shaposhnikove5740342017-07-29 00:30:45 +000010095 for (const llvm::object::ExportEntry &Entry : Obj->exports(Err)) {
Nick Kledzikac7cbdc2014-09-02 18:50:24 +000010096 uint64_t Flags = Entry.flags();
Nick Kledzikd04bc352014-08-30 00:20:14 +000010097 bool ReExport = (Flags & MachO::EXPORT_SYMBOL_FLAGS_REEXPORT);
10098 bool WeakDef = (Flags & MachO::EXPORT_SYMBOL_FLAGS_WEAK_DEFINITION);
10099 bool ThreadLocal = ((Flags & MachO::EXPORT_SYMBOL_FLAGS_KIND_MASK) ==
10100 MachO::EXPORT_SYMBOL_FLAGS_KIND_THREAD_LOCAL);
10101 bool Abs = ((Flags & MachO::EXPORT_SYMBOL_FLAGS_KIND_MASK) ==
10102 MachO::EXPORT_SYMBOL_FLAGS_KIND_ABSOLUTE);
10103 bool Resolver = (Flags & MachO::EXPORT_SYMBOL_FLAGS_STUB_AND_RESOLVER);
10104 if (ReExport)
10105 outs() << "[re-export] ";
10106 else
Kevin Enderbyb28ed012014-10-29 21:28:24 +000010107 outs() << format("0x%08llX ",
Kevin Enderby0d5ec112017-06-19 21:23:07 +000010108 Entry.address() + BaseSegmentAddress);
Nick Kledzikac7cbdc2014-09-02 18:50:24 +000010109 outs() << Entry.name();
Nick Kledzikd04bc352014-08-30 00:20:14 +000010110 if (WeakDef || ThreadLocal || Resolver || Abs) {
Nick Kledzikac7cbdc2014-09-02 18:50:24 +000010111 bool NeedsComma = false;
Nick Kledzik1d1ac4b2014-09-03 01:12:52 +000010112 outs() << " [";
Nick Kledzikd04bc352014-08-30 00:20:14 +000010113 if (WeakDef) {
10114 outs() << "weak_def";
Nick Kledzikac7cbdc2014-09-02 18:50:24 +000010115 NeedsComma = true;
Nick Kledzikd04bc352014-08-30 00:20:14 +000010116 }
10117 if (ThreadLocal) {
Nick Kledzikac7cbdc2014-09-02 18:50:24 +000010118 if (NeedsComma)
Nick Kledzikd04bc352014-08-30 00:20:14 +000010119 outs() << ", ";
10120 outs() << "per-thread";
Nick Kledzikac7cbdc2014-09-02 18:50:24 +000010121 NeedsComma = true;
Nick Kledzikd04bc352014-08-30 00:20:14 +000010122 }
10123 if (Abs) {
Nick Kledzikac7cbdc2014-09-02 18:50:24 +000010124 if (NeedsComma)
Nick Kledzikd04bc352014-08-30 00:20:14 +000010125 outs() << ", ";
10126 outs() << "absolute";
Nick Kledzikac7cbdc2014-09-02 18:50:24 +000010127 NeedsComma = true;
Nick Kledzikd04bc352014-08-30 00:20:14 +000010128 }
10129 if (Resolver) {
Nick Kledzikac7cbdc2014-09-02 18:50:24 +000010130 if (NeedsComma)
Nick Kledzikd04bc352014-08-30 00:20:14 +000010131 outs() << ", ";
Nick Kledzikac7cbdc2014-09-02 18:50:24 +000010132 outs() << format("resolver=0x%08llX", Entry.other());
10133 NeedsComma = true;
Nick Kledzikd04bc352014-08-30 00:20:14 +000010134 }
10135 outs() << "]";
10136 }
10137 if (ReExport) {
10138 StringRef DylibName = "unknown";
Nick Kledzikac7cbdc2014-09-02 18:50:24 +000010139 int Ordinal = Entry.other() - 1;
10140 Obj->getLibraryShortNameByIndex(Ordinal, DylibName);
10141 if (Entry.otherName().empty())
Nick Kledzikd04bc352014-08-30 00:20:14 +000010142 outs() << " (from " << DylibName << ")";
10143 else
Nick Kledzikac7cbdc2014-09-02 18:50:24 +000010144 outs() << " (" << Entry.otherName() << " from " << DylibName << ")";
Nick Kledzikd04bc352014-08-30 00:20:14 +000010145 }
10146 outs() << "\n";
10147 }
Kevin Enderby3e95bd22017-07-20 23:08:41 +000010148 if (Err)
10149 report_error(Obj->getFileName(), std::move(Err));
Nick Kledzikd04bc352014-08-30 00:20:14 +000010150}
Nick Kledzikac431442014-09-12 21:34:15 +000010151
Nick Kledzikac431442014-09-12 21:34:15 +000010152//===----------------------------------------------------------------------===//
10153// rebase table dumping
10154//===----------------------------------------------------------------------===//
10155
Kevin Enderbya8d256c2017-03-20 19:46:55 +000010156void llvm::printMachORebaseTable(object::MachOObjectFile *Obj) {
Nick Kledzikac431442014-09-12 21:34:15 +000010157 outs() << "segment section address type\n";
Kevin Enderbya8d256c2017-03-20 19:46:55 +000010158 Error Err = Error::success();
10159 for (const llvm::object::MachORebaseEntry &Entry : Obj->rebaseTable(Err)) {
10160 StringRef SegmentName = Entry.segmentName();
10161 StringRef SectionName = Entry.sectionName();
10162 uint64_t Address = Entry.address();
Nick Kledzikac431442014-09-12 21:34:15 +000010163
10164 // Table lines look like: __DATA __nl_symbol_ptr 0x0000F00C pointer
Kevin Enderbyb28ed012014-10-29 21:28:24 +000010165 outs() << format("%-8s %-18s 0x%08" PRIX64 " %s\n",
10166 SegmentName.str().c_str(), SectionName.str().c_str(),
10167 Address, Entry.typeName().str().c_str());
Nick Kledzikac431442014-09-12 21:34:15 +000010168 }
Kevin Enderbya8d256c2017-03-20 19:46:55 +000010169 if (Err)
10170 report_error(Obj->getFileName(), std::move(Err));
Nick Kledzikac431442014-09-12 21:34:15 +000010171}
Nick Kledzik56ebef42014-09-16 01:41:51 +000010172
10173static StringRef ordinalName(const object::MachOObjectFile *Obj, int Ordinal) {
10174 StringRef DylibName;
10175 switch (Ordinal) {
10176 case MachO::BIND_SPECIAL_DYLIB_SELF:
10177 return "this-image";
10178 case MachO::BIND_SPECIAL_DYLIB_MAIN_EXECUTABLE:
10179 return "main-executable";
10180 case MachO::BIND_SPECIAL_DYLIB_FLAT_LOOKUP:
10181 return "flat-namespace";
10182 default:
Nick Kledzikabd29872014-09-16 22:03:13 +000010183 if (Ordinal > 0) {
Kevin Enderbyb28ed012014-10-29 21:28:24 +000010184 std::error_code EC =
10185 Obj->getLibraryShortNameByIndex(Ordinal - 1, DylibName);
Nick Kledzikabd29872014-09-16 22:03:13 +000010186 if (EC)
Nick Kledzik51d2c2b2014-10-14 23:29:38 +000010187 return "<<bad library ordinal>>";
Nick Kledzikabd29872014-09-16 22:03:13 +000010188 return DylibName;
10189 }
Nick Kledzik56ebef42014-09-16 01:41:51 +000010190 }
Nick Kledzikabd29872014-09-16 22:03:13 +000010191 return "<<unknown special ordinal>>";
Nick Kledzik56ebef42014-09-16 01:41:51 +000010192}
10193
10194//===----------------------------------------------------------------------===//
10195// bind table dumping
10196//===----------------------------------------------------------------------===//
10197
Kevin Enderbya8d256c2017-03-20 19:46:55 +000010198void llvm::printMachOBindTable(object::MachOObjectFile *Obj) {
Nick Kledzik56ebef42014-09-16 01:41:51 +000010199 // Build table of sections so names can used in final output.
Nick Kledzik5ffacc12014-09-30 00:19:58 +000010200 outs() << "segment section address type "
10201 "addend dylib symbol\n";
Kevin Enderbyfeb63b92017-02-28 21:47:07 +000010202 Error Err = Error::success();
10203 for (const llvm::object::MachOBindEntry &Entry : Obj->bindTable(Err)) {
Kevin Enderbya8d256c2017-03-20 19:46:55 +000010204 StringRef SegmentName = Entry.segmentName();
10205 StringRef SectionName = Entry.sectionName();
10206 uint64_t Address = Entry.address();
Nick Kledzik56ebef42014-09-16 01:41:51 +000010207
10208 // Table lines look like:
10209 // __DATA __got 0x00012010 pointer 0 libSystem ___stack_chk_guard
Nick Kledzik5ffacc12014-09-30 00:19:58 +000010210 StringRef Attr;
Nick Kledzik56ebef42014-09-16 01:41:51 +000010211 if (Entry.flags() & MachO::BIND_SYMBOL_FLAGS_WEAK_IMPORT)
Nick Kledzik5ffacc12014-09-30 00:19:58 +000010212 Attr = " (weak_import)";
Kevin Enderbyb28ed012014-10-29 21:28:24 +000010213 outs() << left_justify(SegmentName, 8) << " "
Nick Kledzik5ffacc12014-09-30 00:19:58 +000010214 << left_justify(SectionName, 18) << " "
10215 << format_hex(Address, 10, true) << " "
10216 << left_justify(Entry.typeName(), 8) << " "
Kevin Enderbyb28ed012014-10-29 21:28:24 +000010217 << format_decimal(Entry.addend(), 8) << " "
Nick Kledzik5ffacc12014-09-30 00:19:58 +000010218 << left_justify(ordinalName(Obj, Entry.ordinal()), 16) << " "
Kevin Enderbyb28ed012014-10-29 21:28:24 +000010219 << Entry.symbolName() << Attr << "\n";
Nick Kledzik56ebef42014-09-16 01:41:51 +000010220 }
Kevin Enderbyfeb63b92017-02-28 21:47:07 +000010221 if (Err)
10222 report_error(Obj->getFileName(), std::move(Err));
Nick Kledzik56ebef42014-09-16 01:41:51 +000010223}
10224
10225//===----------------------------------------------------------------------===//
10226// lazy bind table dumping
10227//===----------------------------------------------------------------------===//
10228
Kevin Enderbya8d256c2017-03-20 19:46:55 +000010229void llvm::printMachOLazyBindTable(object::MachOObjectFile *Obj) {
Nick Kledzik5ffacc12014-09-30 00:19:58 +000010230 outs() << "segment section address "
10231 "dylib symbol\n";
Kevin Enderbyfeb63b92017-02-28 21:47:07 +000010232 Error Err = Error::success();
10233 for (const llvm::object::MachOBindEntry &Entry : Obj->lazyBindTable(Err)) {
Kevin Enderbya8d256c2017-03-20 19:46:55 +000010234 StringRef SegmentName = Entry.segmentName();
10235 StringRef SectionName = Entry.sectionName();
10236 uint64_t Address = Entry.address();
Nick Kledzik56ebef42014-09-16 01:41:51 +000010237
10238 // Table lines look like:
10239 // __DATA __got 0x00012010 libSystem ___stack_chk_guard
Kevin Enderbyb28ed012014-10-29 21:28:24 +000010240 outs() << left_justify(SegmentName, 8) << " "
Nick Kledzik5ffacc12014-09-30 00:19:58 +000010241 << left_justify(SectionName, 18) << " "
10242 << format_hex(Address, 10, true) << " "
10243 << left_justify(ordinalName(Obj, Entry.ordinal()), 16) << " "
Nick Kledzik56ebef42014-09-16 01:41:51 +000010244 << Entry.symbolName() << "\n";
10245 }
Kevin Enderbyfeb63b92017-02-28 21:47:07 +000010246 if (Err)
10247 report_error(Obj->getFileName(), std::move(Err));
Nick Kledzik56ebef42014-09-16 01:41:51 +000010248}
10249
Nick Kledzik56ebef42014-09-16 01:41:51 +000010250//===----------------------------------------------------------------------===//
10251// weak bind table dumping
10252//===----------------------------------------------------------------------===//
10253
Kevin Enderbya8d256c2017-03-20 19:46:55 +000010254void llvm::printMachOWeakBindTable(object::MachOObjectFile *Obj) {
Nick Kledzik5ffacc12014-09-30 00:19:58 +000010255 outs() << "segment section address "
10256 "type addend symbol\n";
Kevin Enderbyfeb63b92017-02-28 21:47:07 +000010257 Error Err = Error::success();
10258 for (const llvm::object::MachOBindEntry &Entry : Obj->weakBindTable(Err)) {
Nick Kledzik56ebef42014-09-16 01:41:51 +000010259 // Strong symbols don't have a location to update.
10260 if (Entry.flags() & MachO::BIND_SYMBOL_FLAGS_NON_WEAK_DEFINITION) {
Nick Kledzik5ffacc12014-09-30 00:19:58 +000010261 outs() << " strong "
Nick Kledzik56ebef42014-09-16 01:41:51 +000010262 << Entry.symbolName() << "\n";
10263 continue;
10264 }
Kevin Enderbya8d256c2017-03-20 19:46:55 +000010265 StringRef SegmentName = Entry.segmentName();
10266 StringRef SectionName = Entry.sectionName();
10267 uint64_t Address = Entry.address();
Nick Kledzik56ebef42014-09-16 01:41:51 +000010268
10269 // Table lines look like:
10270 // __DATA __data 0x00001000 pointer 0 _foo
Kevin Enderbyb28ed012014-10-29 21:28:24 +000010271 outs() << left_justify(SegmentName, 8) << " "
Nick Kledzik5ffacc12014-09-30 00:19:58 +000010272 << left_justify(SectionName, 18) << " "
10273 << format_hex(Address, 10, true) << " "
10274 << left_justify(Entry.typeName(), 8) << " "
Kevin Enderbyb28ed012014-10-29 21:28:24 +000010275 << format_decimal(Entry.addend(), 8) << " " << Entry.symbolName()
10276 << "\n";
Nick Kledzik56ebef42014-09-16 01:41:51 +000010277 }
Kevin Enderbyfeb63b92017-02-28 21:47:07 +000010278 if (Err)
10279 report_error(Obj->getFileName(), std::move(Err));
Nick Kledzik56ebef42014-09-16 01:41:51 +000010280}
10281
Kevin Enderby6f326ce2014-10-23 19:37:31 +000010282// get_dyld_bind_info_symbolname() is used for disassembly and passed an
10283// address, ReferenceValue, in the Mach-O file and looks in the dyld bind
10284// information for that address. If the address is found its binding symbol
10285// name is returned. If not nullptr is returned.
10286static const char *get_dyld_bind_info_symbolname(uint64_t ReferenceValue,
10287 struct DisassembleInfo *info) {
Kevin Enderby078be602014-10-23 19:53:12 +000010288 if (info->bindtable == nullptr) {
Saleem Abdulrasool1d84d9a2017-01-08 19:14:15 +000010289 info->bindtable = llvm::make_unique<SymbolAddressMap>();
Kevin Enderbyfeb63b92017-02-28 21:47:07 +000010290 Error Err = Error::success();
10291 for (const llvm::object::MachOBindEntry &Entry : info->O->bindTable(Err)) {
Kevin Enderbya8d256c2017-03-20 19:46:55 +000010292 uint64_t Address = Entry.address();
Kevin Enderby6f326ce2014-10-23 19:37:31 +000010293 StringRef name = Entry.symbolName();
10294 if (!name.empty())
Saleem Abdulrasool1d84d9a2017-01-08 19:14:15 +000010295 (*info->bindtable)[Address] = name;
Kevin Enderby6f326ce2014-10-23 19:37:31 +000010296 }
Kevin Enderbyfeb63b92017-02-28 21:47:07 +000010297 if (Err)
10298 report_error(info->O->getFileName(), std::move(Err));
Kevin Enderby6f326ce2014-10-23 19:37:31 +000010299 }
Saleem Abdulrasool1d84d9a2017-01-08 19:14:15 +000010300 auto name = info->bindtable->lookup(ReferenceValue);
10301 return !name.empty() ? name.data() : nullptr;
Kevin Enderby6f326ce2014-10-23 19:37:31 +000010302}
Michael Trent1854ecc2017-12-05 07:50:00 +000010303