blob: 54c954340f814f305de7fba26dc87a3145cde2b9 [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>
Matthew Voss0f436772019-02-19 19:46:08 +000062 UseDbg("g", cl::Grouping,
Kevin Enderbyb28ed012014-10-29 21:28:24 +000063 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)
Fangrui Songe7834bd2019-04-07 08:19:55 +0000182 report_error(ATypeOrErr.takeError(), A.getObject()->getFileName());
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)
Fangrui Songe7834bd2019-04-07 08:19:55 +0000186 report_error(BTypeOrErr.takeError(), B.getObject()->getFileName());
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) {
Fangrui Songe7834bd2019-04-07 08:19:55 +0000310 const StringRef FileName = MachOObj->getFileName();
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +0000311 for (const SymbolRef &Symbol : MachOObj->symbols()) {
Fangrui Songe7834bd2019-04-07 08:19:55 +0000312 StringRef SymName = unwrapOrError(Symbol.getName(), FileName);
313 if (!SymName.startswith("ltmp"))
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +0000314 Symbols.push_back(Symbol);
315 }
Owen Andersond9243c42011-10-17 21:37:35 +0000316
Alexey Samsonov48803e52014-03-13 14:37:36 +0000317 for (const SectionRef &Section : MachOObj->sections()) {
Owen Andersond9243c42011-10-17 21:37:35 +0000318 StringRef SectName;
Alexey Samsonov48803e52014-03-13 14:37:36 +0000319 Section.getName(SectName);
320 Sections.push_back(Section);
Owen Andersond9243c42011-10-17 21:37:35 +0000321 }
322
Kevin Enderby273ae012013-06-06 17:20:50 +0000323 bool BaseSegmentAddressSet = false;
Alexey Samsonovd319c4f2015-06-03 22:19:36 +0000324 for (const auto &Command : MachOObj->load_commands()) {
Charles Davis8bdfafd2013-09-01 04:28:48 +0000325 if (Command.C.cmd == MachO::LC_FUNCTION_STARTS) {
Benjamin Kramer699128e2011-09-21 01:13:19 +0000326 // We found a function starts segment, parse the addresses for later
327 // consumption.
Charles Davis8bdfafd2013-09-01 04:28:48 +0000328 MachO::linkedit_data_command LLC =
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000329 MachOObj->getLinkeditDataLoadCommand(Command);
Benjamin Kramer699128e2011-09-21 01:13:19 +0000330
Charles Davis8bdfafd2013-09-01 04:28:48 +0000331 MachOObj->ReadULEB128s(LLC.dataoff, FoundFns);
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000332 } else if (Command.C.cmd == MachO::LC_SEGMENT) {
333 MachO::segment_command SLC = MachOObj->getSegmentLoadCommand(Command);
Charles Davis8bdfafd2013-09-01 04:28:48 +0000334 StringRef SegName = SLC.segname;
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000335 if (!BaseSegmentAddressSet && SegName != "__PAGEZERO") {
Kevin Enderby273ae012013-06-06 17:20:50 +0000336 BaseSegmentAddressSet = true;
Charles Davis8bdfafd2013-09-01 04:28:48 +0000337 BaseSegmentAddress = SLC.vmaddr;
Kevin Enderby273ae012013-06-06 17:20:50 +0000338 }
339 }
Benjamin Kramer8a529dc2011-09-21 22:16:43 +0000340 }
Benjamin Kramer699128e2011-09-21 01:13:19 +0000341}
342
George Rimarc1964882019-01-18 11:33:26 +0000343static void printRelocationTargetName(const MachOObjectFile *O,
344 const MachO::any_relocation_info &RE,
345 raw_string_ostream &Fmt) {
346 // Target of a scattered relocation is an address. In the interest of
347 // generating pretty output, scan through the symbol table looking for a
348 // symbol that aligns with that address. If we find one, print it.
349 // Otherwise, we just print the hex address of the target.
Fangrui Songe7834bd2019-04-07 08:19:55 +0000350 const StringRef FileName = O->getFileName();
George Rimarc1964882019-01-18 11:33:26 +0000351 if (O->isRelocationScattered(RE)) {
352 uint32_t Val = O->getPlainRelocationSymbolNum(RE);
353
354 for (const SymbolRef &Symbol : O->symbols()) {
Fangrui Songe7834bd2019-04-07 08:19:55 +0000355 uint64_t Addr = unwrapOrError(Symbol.getAddress(), FileName);
356 if (Addr != Val)
George Rimarc1964882019-01-18 11:33:26 +0000357 continue;
Fangrui Songe7834bd2019-04-07 08:19:55 +0000358 Fmt << unwrapOrError(Symbol.getName(), FileName);
George Rimarc1964882019-01-18 11:33:26 +0000359 return;
360 }
361
362 // If we couldn't find a symbol that this relocation refers to, try
363 // to find a section beginning instead.
364 for (const SectionRef &Section : ToolSectionFilter(*O)) {
365 std::error_code ec;
366
367 StringRef Name;
368 uint64_t Addr = Section.getAddress();
369 if (Addr != Val)
370 continue;
371 if ((ec = Section.getName(Name)))
372 report_error(O->getFileName(), ec);
373 Fmt << Name;
374 return;
375 }
376
377 Fmt << format("0x%x", Val);
378 return;
379 }
380
381 StringRef S;
382 bool isExtern = O->getPlainRelocationExternal(RE);
383 uint64_t Val = O->getPlainRelocationSymbolNum(RE);
384
385 if (O->getAnyRelocationType(RE) == MachO::ARM64_RELOC_ADDEND) {
386 Fmt << format("0x%0" PRIx64, Val);
387 return;
388 }
389
390 if (isExtern) {
391 symbol_iterator SI = O->symbol_begin();
392 advance(SI, Val);
Fangrui Songe7834bd2019-04-07 08:19:55 +0000393 S = unwrapOrError(SI->getName(), FileName);
George Rimarc1964882019-01-18 11:33:26 +0000394 } else {
395 section_iterator SI = O->section_begin();
396 // Adjust for the fact that sections are 1-indexed.
397 if (Val == 0) {
398 Fmt << "0 (?,?)";
399 return;
400 }
401 uint32_t I = Val - 1;
402 while (I != 0 && SI != O->section_end()) {
403 --I;
404 advance(SI, 1);
405 }
406 if (SI == O->section_end())
407 Fmt << Val << " (?,?)";
408 else
409 SI->getName(S);
410 }
411
412 Fmt << S;
413}
414
Fangrui Songf67de6c2019-04-08 16:24:08 +0000415Error llvm::getMachORelocationValueString(const MachOObjectFile *Obj,
416 const RelocationRef &RelRef,
417 SmallVectorImpl<char> &Result) {
George Rimarc1964882019-01-18 11:33:26 +0000418 DataRefImpl Rel = RelRef.getRawDataRefImpl();
419 MachO::any_relocation_info RE = Obj->getRelocation(Rel);
420
421 unsigned Arch = Obj->getArch();
422
423 std::string FmtBuf;
424 raw_string_ostream Fmt(FmtBuf);
425 unsigned Type = Obj->getAnyRelocationType(RE);
426 bool IsPCRel = Obj->getAnyRelocationPCRel(RE);
427
428 // Determine any addends that should be displayed with the relocation.
429 // These require decoding the relocation type, which is triple-specific.
430
431 // X86_64 has entirely custom relocation types.
432 if (Arch == Triple::x86_64) {
433 switch (Type) {
434 case MachO::X86_64_RELOC_GOT_LOAD:
435 case MachO::X86_64_RELOC_GOT: {
436 printRelocationTargetName(Obj, RE, Fmt);
437 Fmt << "@GOT";
438 if (IsPCRel)
439 Fmt << "PCREL";
440 break;
441 }
442 case MachO::X86_64_RELOC_SUBTRACTOR: {
443 DataRefImpl RelNext = Rel;
444 Obj->moveRelocationNext(RelNext);
445 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
446
447 // X86_64_RELOC_SUBTRACTOR must be followed by a relocation of type
448 // X86_64_RELOC_UNSIGNED.
449 // NOTE: Scattered relocations don't exist on x86_64.
450 unsigned RType = Obj->getAnyRelocationType(RENext);
451 if (RType != MachO::X86_64_RELOC_UNSIGNED)
452 report_error(Obj->getFileName(), "Expected X86_64_RELOC_UNSIGNED after "
453 "X86_64_RELOC_SUBTRACTOR.");
454
455 // The X86_64_RELOC_UNSIGNED contains the minuend symbol;
456 // X86_64_RELOC_SUBTRACTOR contains the subtrahend.
457 printRelocationTargetName(Obj, RENext, Fmt);
458 Fmt << "-";
459 printRelocationTargetName(Obj, RE, Fmt);
460 break;
461 }
462 case MachO::X86_64_RELOC_TLV:
463 printRelocationTargetName(Obj, RE, Fmt);
464 Fmt << "@TLV";
465 if (IsPCRel)
466 Fmt << "P";
467 break;
468 case MachO::X86_64_RELOC_SIGNED_1:
469 printRelocationTargetName(Obj, RE, Fmt);
470 Fmt << "-1";
471 break;
472 case MachO::X86_64_RELOC_SIGNED_2:
473 printRelocationTargetName(Obj, RE, Fmt);
474 Fmt << "-2";
475 break;
476 case MachO::X86_64_RELOC_SIGNED_4:
477 printRelocationTargetName(Obj, RE, Fmt);
478 Fmt << "-4";
479 break;
480 default:
481 printRelocationTargetName(Obj, RE, Fmt);
482 break;
483 }
484 // X86 and ARM share some relocation types in common.
485 } else if (Arch == Triple::x86 || Arch == Triple::arm ||
486 Arch == Triple::ppc) {
487 // Generic relocation types...
488 switch (Type) {
489 case MachO::GENERIC_RELOC_PAIR: // prints no info
Fangrui Songf67de6c2019-04-08 16:24:08 +0000490 return Error::success();
George Rimarc1964882019-01-18 11:33:26 +0000491 case MachO::GENERIC_RELOC_SECTDIFF: {
492 DataRefImpl RelNext = Rel;
493 Obj->moveRelocationNext(RelNext);
494 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
495
496 // X86 sect diff's must be followed by a relocation of type
497 // GENERIC_RELOC_PAIR.
498 unsigned RType = Obj->getAnyRelocationType(RENext);
499
500 if (RType != MachO::GENERIC_RELOC_PAIR)
501 report_error(Obj->getFileName(), "Expected GENERIC_RELOC_PAIR after "
502 "GENERIC_RELOC_SECTDIFF.");
503
504 printRelocationTargetName(Obj, RE, Fmt);
505 Fmt << "-";
506 printRelocationTargetName(Obj, RENext, Fmt);
507 break;
508 }
509 }
510
511 if (Arch == Triple::x86 || Arch == Triple::ppc) {
512 switch (Type) {
513 case MachO::GENERIC_RELOC_LOCAL_SECTDIFF: {
514 DataRefImpl RelNext = Rel;
515 Obj->moveRelocationNext(RelNext);
516 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
517
518 // X86 sect diff's must be followed by a relocation of type
519 // GENERIC_RELOC_PAIR.
520 unsigned RType = Obj->getAnyRelocationType(RENext);
521 if (RType != MachO::GENERIC_RELOC_PAIR)
522 report_error(Obj->getFileName(), "Expected GENERIC_RELOC_PAIR after "
523 "GENERIC_RELOC_LOCAL_SECTDIFF.");
524
525 printRelocationTargetName(Obj, RE, Fmt);
526 Fmt << "-";
527 printRelocationTargetName(Obj, RENext, Fmt);
528 break;
529 }
530 case MachO::GENERIC_RELOC_TLV: {
531 printRelocationTargetName(Obj, RE, Fmt);
532 Fmt << "@TLV";
533 if (IsPCRel)
534 Fmt << "P";
535 break;
536 }
537 default:
538 printRelocationTargetName(Obj, RE, Fmt);
539 }
540 } else { // ARM-specific relocations
541 switch (Type) {
542 case MachO::ARM_RELOC_HALF:
543 case MachO::ARM_RELOC_HALF_SECTDIFF: {
544 // Half relocations steal a bit from the length field to encode
545 // whether this is an upper16 or a lower16 relocation.
546 bool isUpper = (Obj->getAnyRelocationLength(RE) & 0x1) == 1;
547
548 if (isUpper)
549 Fmt << ":upper16:(";
550 else
551 Fmt << ":lower16:(";
552 printRelocationTargetName(Obj, RE, Fmt);
553
554 DataRefImpl RelNext = Rel;
555 Obj->moveRelocationNext(RelNext);
556 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
557
558 // ARM half relocs must be followed by a relocation of type
559 // ARM_RELOC_PAIR.
560 unsigned RType = Obj->getAnyRelocationType(RENext);
561 if (RType != MachO::ARM_RELOC_PAIR)
562 report_error(Obj->getFileName(), "Expected ARM_RELOC_PAIR after "
563 "ARM_RELOC_HALF");
564
565 // NOTE: The half of the target virtual address is stashed in the
566 // address field of the secondary relocation, but we can't reverse
567 // engineer the constant offset from it without decoding the movw/movt
568 // instruction to find the other half in its immediate field.
569
570 // ARM_RELOC_HALF_SECTDIFF encodes the second section in the
571 // symbol/section pointer of the follow-on relocation.
572 if (Type == MachO::ARM_RELOC_HALF_SECTDIFF) {
573 Fmt << "-";
574 printRelocationTargetName(Obj, RENext, Fmt);
575 }
576
577 Fmt << ")";
578 break;
579 }
580 default: {
581 printRelocationTargetName(Obj, RE, Fmt);
582 }
583 }
584 }
585 } else
586 printRelocationTargetName(Obj, RE, Fmt);
587
588 Fmt.flush();
589 Result.append(FmtBuf.begin(), FmtBuf.end());
Fangrui Songf67de6c2019-04-08 16:24:08 +0000590 return Error::success();
George Rimarc1964882019-01-18 11:33:26 +0000591}
592
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +0000593static void PrintIndirectSymbolTable(MachOObjectFile *O, bool verbose,
594 uint32_t n, uint32_t count,
595 uint32_t stride, uint64_t addr) {
596 MachO::dysymtab_command Dysymtab = O->getDysymtabLoadCommand();
597 uint32_t nindirectsyms = Dysymtab.nindirectsyms;
598 if (n > nindirectsyms)
599 outs() << " (entries start past the end of the indirect symbol "
600 "table) (reserved1 field greater than the table size)";
601 else if (n + count > nindirectsyms)
602 outs() << " (entries extends past the end of the indirect symbol "
603 "table)";
604 outs() << "\n";
605 uint32_t cputype = O->getHeader().cputype;
606 if (cputype & MachO::CPU_ARCH_ABI64)
607 outs() << "address index";
608 else
609 outs() << "address index";
610 if (verbose)
611 outs() << " name\n";
612 else
613 outs() << "\n";
614 for (uint32_t j = 0; j < count && n + j < nindirectsyms; j++) {
615 if (cputype & MachO::CPU_ARCH_ABI64)
616 outs() << format("0x%016" PRIx64, addr + j * stride) << " ";
617 else
Tim Northover43978372016-04-26 18:29:16 +0000618 outs() << format("0x%08" PRIx32, (uint32_t)addr + j * stride) << " ";
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +0000619 MachO::dysymtab_command Dysymtab = O->getDysymtabLoadCommand();
620 uint32_t indirect_symbol = O->getIndirectSymbolTableEntry(Dysymtab, n + j);
621 if (indirect_symbol == MachO::INDIRECT_SYMBOL_LOCAL) {
622 outs() << "LOCAL\n";
623 continue;
624 }
625 if (indirect_symbol ==
626 (MachO::INDIRECT_SYMBOL_LOCAL | MachO::INDIRECT_SYMBOL_ABS)) {
627 outs() << "LOCAL ABSOLUTE\n";
628 continue;
629 }
630 if (indirect_symbol == MachO::INDIRECT_SYMBOL_ABS) {
631 outs() << "ABSOLUTE\n";
632 continue;
633 }
634 outs() << format("%5u ", indirect_symbol);
Kevin Enderbyf0640752015-03-13 17:56:32 +0000635 if (verbose) {
636 MachO::symtab_command Symtab = O->getSymtabLoadCommand();
637 if (indirect_symbol < Symtab.nsyms) {
638 symbol_iterator Sym = O->getSymbolByIndex(indirect_symbol);
639 SymbolRef Symbol = *Sym;
Fangrui Songe7834bd2019-04-07 08:19:55 +0000640 outs() << unwrapOrError(Symbol.getName(), O->getFileName());
Kevin Enderbyf0640752015-03-13 17:56:32 +0000641 } else {
642 outs() << "?";
643 }
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +0000644 }
645 outs() << "\n";
646 }
647}
648
649static void PrintIndirectSymbols(MachOObjectFile *O, bool verbose) {
Alexey Samsonovd319c4f2015-06-03 22:19:36 +0000650 for (const auto &Load : O->load_commands()) {
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +0000651 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
652 MachO::segment_command_64 Seg = O->getSegment64LoadCommand(Load);
653 for (unsigned J = 0; J < Seg.nsects; ++J) {
654 MachO::section_64 Sec = O->getSection64(Load, J);
655 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
656 if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
657 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
658 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
659 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
660 section_type == MachO::S_SYMBOL_STUBS) {
661 uint32_t stride;
662 if (section_type == MachO::S_SYMBOL_STUBS)
663 stride = Sec.reserved2;
664 else
665 stride = 8;
666 if (stride == 0) {
667 outs() << "Can't print indirect symbols for (" << Sec.segname << ","
668 << Sec.sectname << ") "
669 << "(size of stubs in reserved2 field is zero)\n";
670 continue;
671 }
672 uint32_t count = Sec.size / stride;
673 outs() << "Indirect symbols for (" << Sec.segname << ","
674 << Sec.sectname << ") " << count << " entries";
675 uint32_t n = Sec.reserved1;
676 PrintIndirectSymbolTable(O, verbose, n, count, stride, Sec.addr);
677 }
678 }
679 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
680 MachO::segment_command Seg = O->getSegmentLoadCommand(Load);
681 for (unsigned J = 0; J < Seg.nsects; ++J) {
682 MachO::section Sec = O->getSection(Load, J);
683 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
684 if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
685 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
686 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
687 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
688 section_type == MachO::S_SYMBOL_STUBS) {
689 uint32_t stride;
690 if (section_type == MachO::S_SYMBOL_STUBS)
691 stride = Sec.reserved2;
692 else
693 stride = 4;
694 if (stride == 0) {
695 outs() << "Can't print indirect symbols for (" << Sec.segname << ","
696 << Sec.sectname << ") "
697 << "(size of stubs in reserved2 field is zero)\n";
698 continue;
699 }
700 uint32_t count = Sec.size / stride;
701 outs() << "Indirect symbols for (" << Sec.segname << ","
702 << Sec.sectname << ") " << count << " entries";
703 uint32_t n = Sec.reserved1;
704 PrintIndirectSymbolTable(O, verbose, n, count, stride, Sec.addr);
705 }
706 }
707 }
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +0000708 }
709}
710
Michael Trenta1703b12017-12-15 17:57:40 +0000711static void PrintRType(const uint64_t cputype, const unsigned r_type) {
712 static char const *generic_r_types[] = {
713 "VANILLA ", "PAIR ", "SECTDIF ", "PBLAPTR ", "LOCSDIF ", "TLV ",
714 " 6 (?) ", " 7 (?) ", " 8 (?) ", " 9 (?) ", " 10 (?) ", " 11 (?) ",
715 " 12 (?) ", " 13 (?) ", " 14 (?) ", " 15 (?) "
716 };
717 static char const *x86_64_r_types[] = {
718 "UNSIGND ", "SIGNED ", "BRANCH ", "GOT_LD ", "GOT ", "SUB ",
719 "SIGNED1 ", "SIGNED2 ", "SIGNED4 ", "TLV ", " 10 (?) ", " 11 (?) ",
720 " 12 (?) ", " 13 (?) ", " 14 (?) ", " 15 (?) "
721 };
722 static char const *arm_r_types[] = {
723 "VANILLA ", "PAIR ", "SECTDIFF", "LOCSDIF ", "PBLAPTR ",
724 "BR24 ", "T_BR22 ", "T_BR32 ", "HALF ", "HALFDIF ",
725 " 10 (?) ", " 11 (?) ", " 12 (?) ", " 13 (?) ", " 14 (?) ", " 15 (?) "
726 };
727 static char const *arm64_r_types[] = {
728 "UNSIGND ", "SUB ", "BR26 ", "PAGE21 ", "PAGOF12 ",
729 "GOTLDP ", "GOTLDPOF", "PTRTGOT ", "TLVLDP ", "TLVLDPOF",
730 "ADDEND ", " 11 (?) ", " 12 (?) ", " 13 (?) ", " 14 (?) ", " 15 (?) "
731 };
Jonas Devliegheree787efd2018-11-11 22:12:04 +0000732
Michael Trenta1703b12017-12-15 17:57:40 +0000733 if (r_type > 0xf){
734 outs() << format("%-7u", r_type) << " ";
735 return;
736 }
737 switch (cputype) {
738 case MachO::CPU_TYPE_I386:
739 outs() << generic_r_types[r_type];
740 break;
741 case MachO::CPU_TYPE_X86_64:
742 outs() << x86_64_r_types[r_type];
743 break;
744 case MachO::CPU_TYPE_ARM:
745 outs() << arm_r_types[r_type];
746 break;
747 case MachO::CPU_TYPE_ARM64:
748 outs() << arm64_r_types[r_type];
749 break;
750 default:
751 outs() << format("%-7u ", r_type);
752 }
753}
754
755static void PrintRLength(const uint64_t cputype, const unsigned r_type,
756 const unsigned r_length, const bool previous_arm_half){
757 if (cputype == MachO::CPU_TYPE_ARM &&
758 (r_type == llvm::MachO::ARM_RELOC_HALF ||
759 r_type == llvm::MachO::ARM_RELOC_HALF_SECTDIFF ||
760 previous_arm_half == true)) {
761 if ((r_length & 0x1) == 0)
762 outs() << "lo/";
763 else
764 outs() << "hi/";
765 if ((r_length & 0x1) == 0)
766 outs() << "arm ";
767 else
768 outs() << "thm ";
769 } else {
770 switch (r_length) {
771 case 0:
772 outs() << "byte ";
773 break;
774 case 1:
775 outs() << "word ";
776 break;
777 case 2:
778 outs() << "long ";
779 break;
780 case 3:
781 if (cputype == MachO::CPU_TYPE_X86_64)
782 outs() << "quad ";
783 else
784 outs() << format("?(%2d) ", r_length);
785 break;
786 default:
787 outs() << format("?(%2d) ", r_length);
788 }
789 }
790}
791
792static void PrintRelocationEntries(const MachOObjectFile *O,
793 const relocation_iterator Begin,
794 const relocation_iterator End,
795 const uint64_t cputype,
796 const bool verbose) {
797 const MachO::symtab_command Symtab = O->getSymtabLoadCommand();
798 bool previous_arm_half = false;
799 bool previous_sectdiff = false;
800 uint32_t sectdiff_r_type = 0;
Jonas Devliegheree787efd2018-11-11 22:12:04 +0000801
Michael Trenta1703b12017-12-15 17:57:40 +0000802 for (relocation_iterator Reloc = Begin; Reloc != End; ++Reloc) {
803 const DataRefImpl Rel = Reloc->getRawDataRefImpl();
804 const MachO::any_relocation_info RE = O->getRelocation(Rel);
805 const unsigned r_type = O->getAnyRelocationType(RE);
806 const bool r_scattered = O->isRelocationScattered(RE);
807 const unsigned r_pcrel = O->getAnyRelocationPCRel(RE);
808 const unsigned r_length = O->getAnyRelocationLength(RE);
809 const unsigned r_address = O->getAnyRelocationAddress(RE);
810 const bool r_extern = (r_scattered ? false :
811 O->getPlainRelocationExternal(RE));
812 const uint32_t r_value = (r_scattered ?
813 O->getScatteredRelocationValue(RE) : 0);
814 const unsigned r_symbolnum = (r_scattered ? 0 :
815 O->getPlainRelocationSymbolNum(RE));
Jonas Devliegheree787efd2018-11-11 22:12:04 +0000816
Michael Trenta1703b12017-12-15 17:57:40 +0000817 if (r_scattered && cputype != MachO::CPU_TYPE_X86_64) {
818 if (verbose) {
819 // scattered: address
820 if ((cputype == MachO::CPU_TYPE_I386 &&
821 r_type == llvm::MachO::GENERIC_RELOC_PAIR) ||
822 (cputype == MachO::CPU_TYPE_ARM &&
823 r_type == llvm::MachO::ARM_RELOC_PAIR))
824 outs() << " ";
825 else
826 outs() << format("%08x ", (unsigned int)r_address);
Jonas Devliegheree787efd2018-11-11 22:12:04 +0000827
Michael Trenta1703b12017-12-15 17:57:40 +0000828 // scattered: pcrel
829 if (r_pcrel)
830 outs() << "True ";
831 else
832 outs() << "False ";
Jonas Devliegheree787efd2018-11-11 22:12:04 +0000833
Michael Trenta1703b12017-12-15 17:57:40 +0000834 // scattered: length
835 PrintRLength(cputype, r_type, r_length, previous_arm_half);
Jonas Devliegheree787efd2018-11-11 22:12:04 +0000836
Michael Trenta1703b12017-12-15 17:57:40 +0000837 // scattered: extern & type
838 outs() << "n/a ";
839 PrintRType(cputype, r_type);
Jonas Devliegheree787efd2018-11-11 22:12:04 +0000840
Michael Trenta1703b12017-12-15 17:57:40 +0000841 // scattered: scattered & value
842 outs() << format("True 0x%08x", (unsigned int)r_value);
843 if (previous_sectdiff == false) {
844 if ((cputype == MachO::CPU_TYPE_ARM &&
845 r_type == llvm::MachO::ARM_RELOC_PAIR))
846 outs() << format(" half = 0x%04x ", (unsigned int)r_address);
847 }
848 else if (cputype == MachO::CPU_TYPE_ARM &&
849 sectdiff_r_type == llvm::MachO::ARM_RELOC_HALF_SECTDIFF)
850 outs() << format(" other_half = 0x%04x ", (unsigned int)r_address);
851 if ((cputype == MachO::CPU_TYPE_I386 &&
852 (r_type == llvm::MachO::GENERIC_RELOC_SECTDIFF ||
853 r_type == llvm::MachO::GENERIC_RELOC_LOCAL_SECTDIFF)) ||
854 (cputype == MachO::CPU_TYPE_ARM &&
855 (sectdiff_r_type == llvm::MachO::ARM_RELOC_SECTDIFF ||
856 sectdiff_r_type == llvm::MachO::ARM_RELOC_LOCAL_SECTDIFF ||
857 sectdiff_r_type == llvm::MachO::ARM_RELOC_HALF_SECTDIFF))) {
858 previous_sectdiff = true;
859 sectdiff_r_type = r_type;
860 }
861 else {
862 previous_sectdiff = false;
863 sectdiff_r_type = 0;
864 }
865 if (cputype == MachO::CPU_TYPE_ARM &&
866 (r_type == llvm::MachO::ARM_RELOC_HALF ||
867 r_type == llvm::MachO::ARM_RELOC_HALF_SECTDIFF))
868 previous_arm_half = true;
869 else
870 previous_arm_half = false;
871 outs() << "\n";
872 }
873 else {
874 // scattered: address pcrel length extern type scattered value
875 outs() << format("%08x %1d %-2d n/a %-7d 1 0x%08x\n",
876 (unsigned int)r_address, r_pcrel, r_length, r_type,
877 (unsigned int)r_value);
878 }
879 }
880 else {
881 if (verbose) {
882 // plain: address
883 if (cputype == MachO::CPU_TYPE_ARM &&
884 r_type == llvm::MachO::ARM_RELOC_PAIR)
885 outs() << " ";
886 else
887 outs() << format("%08x ", (unsigned int)r_address);
Jonas Devliegheree787efd2018-11-11 22:12:04 +0000888
Michael Trenta1703b12017-12-15 17:57:40 +0000889 // plain: pcrel
890 if (r_pcrel)
891 outs() << "True ";
892 else
893 outs() << "False ";
Jonas Devliegheree787efd2018-11-11 22:12:04 +0000894
Michael Trenta1703b12017-12-15 17:57:40 +0000895 // plain: length
896 PrintRLength(cputype, r_type, r_length, previous_arm_half);
Jonas Devliegheree787efd2018-11-11 22:12:04 +0000897
Michael Trenta1703b12017-12-15 17:57:40 +0000898 if (r_extern) {
899 // plain: extern & type & scattered
900 outs() << "True ";
901 PrintRType(cputype, r_type);
902 outs() << "False ";
Jonas Devliegheree787efd2018-11-11 22:12:04 +0000903
Michael Trenta1703b12017-12-15 17:57:40 +0000904 // plain: symbolnum/value
905 if (r_symbolnum > Symtab.nsyms)
906 outs() << format("?(%d)\n", r_symbolnum);
907 else {
908 SymbolRef Symbol = *O->getSymbolByIndex(r_symbolnum);
909 Expected<StringRef> SymNameNext = Symbol.getName();
910 const char *name = NULL;
911 if (SymNameNext)
912 name = SymNameNext->data();
913 if (name == NULL)
914 outs() << format("?(%d)\n", r_symbolnum);
915 else
916 outs() << name << "\n";
917 }
918 }
919 else {
920 // plain: extern & type & scattered
921 outs() << "False ";
922 PrintRType(cputype, r_type);
923 outs() << "False ";
Jonas Devliegheree787efd2018-11-11 22:12:04 +0000924
Michael Trenta1703b12017-12-15 17:57:40 +0000925 // plain: symbolnum/value
926 if (cputype == MachO::CPU_TYPE_ARM &&
927 r_type == llvm::MachO::ARM_RELOC_PAIR)
928 outs() << format("other_half = 0x%04x\n", (unsigned int)r_address);
929 else if (cputype == MachO::CPU_TYPE_ARM64 &&
930 r_type == llvm::MachO::ARM64_RELOC_ADDEND)
931 outs() << format("addend = 0x%06x\n", (unsigned int)r_symbolnum);
932 else {
933 outs() << format("%d ", r_symbolnum);
934 if (r_symbolnum == llvm::MachO::R_ABS)
935 outs() << "R_ABS\n";
936 else {
937 // in this case, r_symbolnum is actually a 1-based section number
938 uint32_t nsects = O->section_end()->getRawDataRefImpl().d.a;
939 if (r_symbolnum > 0 && r_symbolnum <= nsects) {
940 llvm::object::DataRefImpl DRI;
941 DRI.d.a = r_symbolnum-1;
942 StringRef SegName = O->getSectionFinalSegmentName(DRI);
943 StringRef SectName;
944 if (O->getSectionName(DRI, SectName))
945 outs() << "(?,?)\n";
946 else
947 outs() << "(" << SegName << "," << SectName << ")\n";
948 }
949 else {
950 outs() << "(?,?)\n";
951 }
952 }
953 }
954 }
955 if (cputype == MachO::CPU_TYPE_ARM &&
956 (r_type == llvm::MachO::ARM_RELOC_HALF ||
957 r_type == llvm::MachO::ARM_RELOC_HALF_SECTDIFF))
958 previous_arm_half = true;
959 else
960 previous_arm_half = false;
961 }
962 else {
963 // plain: address pcrel length extern type scattered symbolnum/section
964 outs() << format("%08x %1d %-2d %1d %-7d 0 %d\n",
965 (unsigned int)r_address, r_pcrel, r_length, r_extern,
966 r_type, r_symbolnum);
967 }
968 }
969 }
970}
971
972static void PrintRelocations(const MachOObjectFile *O, const bool verbose) {
973 const uint64_t cputype = O->getHeader().cputype;
974 const MachO::dysymtab_command Dysymtab = O->getDysymtabLoadCommand();
975 if (Dysymtab.nextrel != 0) {
976 outs() << "External relocation information " << Dysymtab.nextrel
977 << " entries";
978 outs() << "\naddress pcrel length extern type scattered "
979 "symbolnum/value\n";
980 PrintRelocationEntries(O, O->extrel_begin(), O->extrel_end(), cputype,
981 verbose);
982 }
983 if (Dysymtab.nlocrel != 0) {
984 outs() << format("Local relocation information %u entries",
985 Dysymtab.nlocrel);
986 outs() << "\naddress pcrel length extern type scattered "
987 "symbolnum/value\n";
988 PrintRelocationEntries(O, O->locrel_begin(), O->locrel_end(), cputype,
989 verbose);
990 }
991 for (const auto &Load : O->load_commands()) {
992 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
993 const MachO::segment_command_64 Seg = O->getSegment64LoadCommand(Load);
994 for (unsigned J = 0; J < Seg.nsects; ++J) {
995 const MachO::section_64 Sec = O->getSection64(Load, J);
996 if (Sec.nreloc != 0) {
997 DataRefImpl DRI;
998 DRI.d.a = J;
999 const StringRef SegName = O->getSectionFinalSegmentName(DRI);
1000 StringRef SectName;
1001 if (O->getSectionName(DRI, SectName))
1002 outs() << "Relocation information (" << SegName << ",?) "
1003 << format("%u entries", Sec.nreloc);
1004 else
1005 outs() << "Relocation information (" << SegName << ","
1006 << SectName << format(") %u entries", Sec.nreloc);
1007 outs() << "\naddress pcrel length extern type scattered "
1008 "symbolnum/value\n";
1009 PrintRelocationEntries(O, O->section_rel_begin(DRI),
1010 O->section_rel_end(DRI), cputype, verbose);
1011 }
1012 }
1013 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
1014 const MachO::segment_command Seg = O->getSegmentLoadCommand(Load);
1015 for (unsigned J = 0; J < Seg.nsects; ++J) {
1016 const MachO::section Sec = O->getSection(Load, J);
1017 if (Sec.nreloc != 0) {
1018 DataRefImpl DRI;
1019 DRI.d.a = J;
1020 const StringRef SegName = O->getSectionFinalSegmentName(DRI);
1021 StringRef SectName;
1022 if (O->getSectionName(DRI, SectName))
1023 outs() << "Relocation information (" << SegName << ",?) "
1024 << format("%u entries", Sec.nreloc);
1025 else
1026 outs() << "Relocation information (" << SegName << ","
1027 << SectName << format(") %u entries", Sec.nreloc);
1028 outs() << "\naddress pcrel length extern type scattered "
1029 "symbolnum/value\n";
1030 PrintRelocationEntries(O, O->section_rel_begin(DRI),
1031 O->section_rel_end(DRI), cputype, verbose);
1032 }
1033 }
1034 }
1035 }
1036}
1037
Kevin Enderby69fe98d2015-01-23 18:52:17 +00001038static void PrintDataInCodeTable(MachOObjectFile *O, bool verbose) {
1039 MachO::linkedit_data_command DIC = O->getDataInCodeLoadCommand();
1040 uint32_t nentries = DIC.datasize / sizeof(struct MachO::data_in_code_entry);
1041 outs() << "Data in code table (" << nentries << " entries)\n";
1042 outs() << "offset length kind\n";
1043 for (dice_iterator DI = O->begin_dices(), DE = O->end_dices(); DI != DE;
1044 ++DI) {
1045 uint32_t Offset;
1046 DI->getOffset(Offset);
1047 outs() << format("0x%08" PRIx32, Offset) << " ";
1048 uint16_t Length;
1049 DI->getLength(Length);
1050 outs() << format("%6u", Length) << " ";
1051 uint16_t Kind;
1052 DI->getKind(Kind);
1053 if (verbose) {
1054 switch (Kind) {
1055 case MachO::DICE_KIND_DATA:
1056 outs() << "DATA";
1057 break;
1058 case MachO::DICE_KIND_JUMP_TABLE8:
1059 outs() << "JUMP_TABLE8";
1060 break;
1061 case MachO::DICE_KIND_JUMP_TABLE16:
1062 outs() << "JUMP_TABLE16";
1063 break;
1064 case MachO::DICE_KIND_JUMP_TABLE32:
1065 outs() << "JUMP_TABLE32";
1066 break;
1067 case MachO::DICE_KIND_ABS_JUMP_TABLE32:
1068 outs() << "ABS_JUMP_TABLE32";
1069 break;
1070 default:
1071 outs() << format("0x%04" PRIx32, Kind);
1072 break;
1073 }
1074 } else
1075 outs() << format("0x%04" PRIx32, Kind);
1076 outs() << "\n";
1077 }
1078}
1079
Kevin Enderby9a509442015-01-27 21:28:24 +00001080static void PrintLinkOptHints(MachOObjectFile *O) {
1081 MachO::linkedit_data_command LohLC = O->getLinkOptHintsLoadCommand();
1082 const char *loh = O->getData().substr(LohLC.dataoff, 1).data();
1083 uint32_t nloh = LohLC.datasize;
1084 outs() << "Linker optimiztion hints (" << nloh << " total bytes)\n";
1085 for (uint32_t i = 0; i < nloh;) {
1086 unsigned n;
1087 uint64_t identifier = decodeULEB128((const uint8_t *)(loh + i), &n);
1088 i += n;
1089 outs() << " identifier " << identifier << " ";
1090 if (i >= nloh)
1091 return;
1092 switch (identifier) {
1093 case 1:
1094 outs() << "AdrpAdrp\n";
1095 break;
1096 case 2:
1097 outs() << "AdrpLdr\n";
1098 break;
1099 case 3:
1100 outs() << "AdrpAddLdr\n";
1101 break;
1102 case 4:
1103 outs() << "AdrpLdrGotLdr\n";
1104 break;
1105 case 5:
1106 outs() << "AdrpAddStr\n";
1107 break;
1108 case 6:
1109 outs() << "AdrpLdrGotStr\n";
1110 break;
1111 case 7:
1112 outs() << "AdrpAdd\n";
1113 break;
1114 case 8:
1115 outs() << "AdrpLdrGot\n";
1116 break;
1117 default:
1118 outs() << "Unknown identifier value\n";
1119 break;
1120 }
1121 uint64_t narguments = decodeULEB128((const uint8_t *)(loh + i), &n);
1122 i += n;
1123 outs() << " narguments " << narguments << "\n";
1124 if (i >= nloh)
1125 return;
1126
1127 for (uint32_t j = 0; j < narguments; j++) {
1128 uint64_t value = decodeULEB128((const uint8_t *)(loh + i), &n);
1129 i += n;
1130 outs() << "\tvalue " << format("0x%" PRIx64, value) << "\n";
1131 if (i >= nloh)
1132 return;
1133 }
1134 }
1135}
1136
Kevin Enderbybc847fa2015-03-16 20:08:09 +00001137static void PrintDylibs(MachOObjectFile *O, bool JustId) {
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00001138 unsigned Index = 0;
1139 for (const auto &Load : O->load_commands()) {
Kevin Enderbybc847fa2015-03-16 20:08:09 +00001140 if ((JustId && Load.C.cmd == MachO::LC_ID_DYLIB) ||
1141 (!JustId && (Load.C.cmd == MachO::LC_ID_DYLIB ||
1142 Load.C.cmd == MachO::LC_LOAD_DYLIB ||
1143 Load.C.cmd == MachO::LC_LOAD_WEAK_DYLIB ||
1144 Load.C.cmd == MachO::LC_REEXPORT_DYLIB ||
1145 Load.C.cmd == MachO::LC_LAZY_LOAD_DYLIB ||
1146 Load.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB))) {
1147 MachO::dylib_command dl = O->getDylibIDLoadCommand(Load);
1148 if (dl.dylib.name < dl.cmdsize) {
1149 const char *p = (const char *)(Load.Ptr) + dl.dylib.name;
1150 if (JustId)
1151 outs() << p << "\n";
1152 else {
1153 outs() << "\t" << p;
1154 outs() << " (compatibility version "
1155 << ((dl.dylib.compatibility_version >> 16) & 0xffff) << "."
1156 << ((dl.dylib.compatibility_version >> 8) & 0xff) << "."
1157 << (dl.dylib.compatibility_version & 0xff) << ",";
1158 outs() << " current version "
1159 << ((dl.dylib.current_version >> 16) & 0xffff) << "."
1160 << ((dl.dylib.current_version >> 8) & 0xff) << "."
1161 << (dl.dylib.current_version & 0xff) << ")\n";
1162 }
1163 } else {
1164 outs() << "\tBad offset (" << dl.dylib.name << ") for name of ";
1165 if (Load.C.cmd == MachO::LC_ID_DYLIB)
1166 outs() << "LC_ID_DYLIB ";
1167 else if (Load.C.cmd == MachO::LC_LOAD_DYLIB)
1168 outs() << "LC_LOAD_DYLIB ";
1169 else if (Load.C.cmd == MachO::LC_LOAD_WEAK_DYLIB)
1170 outs() << "LC_LOAD_WEAK_DYLIB ";
1171 else if (Load.C.cmd == MachO::LC_LAZY_LOAD_DYLIB)
1172 outs() << "LC_LAZY_LOAD_DYLIB ";
1173 else if (Load.C.cmd == MachO::LC_REEXPORT_DYLIB)
1174 outs() << "LC_REEXPORT_DYLIB ";
1175 else if (Load.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB)
1176 outs() << "LC_LOAD_UPWARD_DYLIB ";
1177 else
1178 outs() << "LC_??? ";
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00001179 outs() << "command " << Index++ << "\n";
Kevin Enderbybc847fa2015-03-16 20:08:09 +00001180 }
1181 }
Kevin Enderbybc847fa2015-03-16 20:08:09 +00001182 }
1183}
1184
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001185typedef DenseMap<uint64_t, StringRef> SymbolAddressMap;
1186
1187static void CreateSymbolAddressMap(MachOObjectFile *O,
1188 SymbolAddressMap *AddrMap) {
1189 // Create a map of symbol addresses to symbol names.
Fangrui Songe7834bd2019-04-07 08:19:55 +00001190 const StringRef FileName = O->getFileName();
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001191 for (const SymbolRef &Symbol : O->symbols()) {
Fangrui Songe7834bd2019-04-07 08:19:55 +00001192 SymbolRef::Type ST = unwrapOrError(Symbol.getType(), FileName);
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001193 if (ST == SymbolRef::ST_Function || ST == SymbolRef::ST_Data ||
1194 ST == SymbolRef::ST_Other) {
Rafael Espindoladea00162015-07-03 17:44:18 +00001195 uint64_t Address = Symbol.getValue();
Fangrui Songe7834bd2019-04-07 08:19:55 +00001196 StringRef SymName = unwrapOrError(Symbol.getName(), FileName);
Kevin Enderby846c0002015-04-16 17:19:59 +00001197 if (!SymName.startswith(".objc"))
1198 (*AddrMap)[Address] = SymName;
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001199 }
1200 }
1201}
1202
1203// GuessSymbolName is passed the address of what might be a symbol and a
1204// pointer to the SymbolAddressMap. It returns the name of a symbol
1205// with that address or nullptr if no symbol is found with that address.
1206static const char *GuessSymbolName(uint64_t value, SymbolAddressMap *AddrMap) {
1207 const char *SymbolName = nullptr;
1208 // A DenseMap can't lookup up some values.
1209 if (value != 0xffffffffffffffffULL && value != 0xfffffffffffffffeULL) {
1210 StringRef name = AddrMap->lookup(value);
1211 if (!name.empty())
1212 SymbolName = name.data();
1213 }
1214 return SymbolName;
1215}
1216
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001217static void DumpCstringChar(const char c) {
1218 char p[2];
1219 p[0] = c;
1220 p[1] = '\0';
1221 outs().write_escaped(p);
1222}
1223
Kevin Enderby10ba0412015-02-04 21:38:42 +00001224static void DumpCstringSection(MachOObjectFile *O, const char *sect,
1225 uint32_t sect_size, uint64_t sect_addr,
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001226 bool print_addresses) {
Kevin Enderby10ba0412015-02-04 21:38:42 +00001227 for (uint32_t i = 0; i < sect_size; i++) {
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001228 if (print_addresses) {
1229 if (O->is64Bit())
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001230 outs() << format("%016" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001231 else
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001232 outs() << format("%08" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001233 }
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001234 for (; i < sect_size && sect[i] != '\0'; i++)
1235 DumpCstringChar(sect[i]);
Kevin Enderby10ba0412015-02-04 21:38:42 +00001236 if (i < sect_size && sect[i] == '\0')
1237 outs() << "\n";
1238 }
1239}
1240
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001241static void DumpLiteral4(uint32_t l, float f) {
1242 outs() << format("0x%08" PRIx32, l);
1243 if ((l & 0x7f800000) != 0x7f800000)
1244 outs() << format(" (%.16e)\n", f);
1245 else {
1246 if (l == 0x7f800000)
1247 outs() << " (+Infinity)\n";
1248 else if (l == 0xff800000)
1249 outs() << " (-Infinity)\n";
1250 else if ((l & 0x00400000) == 0x00400000)
1251 outs() << " (non-signaling Not-a-Number)\n";
1252 else
1253 outs() << " (signaling Not-a-Number)\n";
1254 }
1255}
1256
1257static void DumpLiteral4Section(MachOObjectFile *O, const char *sect,
1258 uint32_t sect_size, uint64_t sect_addr,
1259 bool print_addresses) {
1260 for (uint32_t i = 0; i < sect_size; i += sizeof(float)) {
1261 if (print_addresses) {
1262 if (O->is64Bit())
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001263 outs() << format("%016" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001264 else
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001265 outs() << format("%08" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001266 }
1267 float f;
1268 memcpy(&f, sect + i, sizeof(float));
1269 if (O->isLittleEndian() != sys::IsLittleEndianHost)
1270 sys::swapByteOrder(f);
1271 uint32_t l;
1272 memcpy(&l, sect + i, sizeof(uint32_t));
1273 if (O->isLittleEndian() != sys::IsLittleEndianHost)
1274 sys::swapByteOrder(l);
1275 DumpLiteral4(l, f);
1276 }
1277}
1278
1279static void DumpLiteral8(MachOObjectFile *O, uint32_t l0, uint32_t l1,
1280 double d) {
1281 outs() << format("0x%08" PRIx32, l0) << " " << format("0x%08" PRIx32, l1);
1282 uint32_t Hi, Lo;
Davide Italianob627d9f2015-12-12 21:50:11 +00001283 Hi = (O->isLittleEndian()) ? l1 : l0;
1284 Lo = (O->isLittleEndian()) ? l0 : l1;
1285
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001286 // Hi is the high word, so this is equivalent to if(isfinite(d))
1287 if ((Hi & 0x7ff00000) != 0x7ff00000)
1288 outs() << format(" (%.16e)\n", d);
1289 else {
1290 if (Hi == 0x7ff00000 && Lo == 0)
1291 outs() << " (+Infinity)\n";
1292 else if (Hi == 0xfff00000 && Lo == 0)
1293 outs() << " (-Infinity)\n";
1294 else if ((Hi & 0x00080000) == 0x00080000)
1295 outs() << " (non-signaling Not-a-Number)\n";
1296 else
1297 outs() << " (signaling Not-a-Number)\n";
1298 }
1299}
1300
1301static void DumpLiteral8Section(MachOObjectFile *O, const char *sect,
1302 uint32_t sect_size, uint64_t sect_addr,
1303 bool print_addresses) {
1304 for (uint32_t i = 0; i < sect_size; i += sizeof(double)) {
1305 if (print_addresses) {
1306 if (O->is64Bit())
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001307 outs() << format("%016" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001308 else
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001309 outs() << format("%08" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001310 }
1311 double d;
1312 memcpy(&d, sect + i, sizeof(double));
1313 if (O->isLittleEndian() != sys::IsLittleEndianHost)
1314 sys::swapByteOrder(d);
1315 uint32_t l0, l1;
1316 memcpy(&l0, sect + i, sizeof(uint32_t));
1317 memcpy(&l1, sect + i + sizeof(uint32_t), sizeof(uint32_t));
1318 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
1319 sys::swapByteOrder(l0);
1320 sys::swapByteOrder(l1);
1321 }
1322 DumpLiteral8(O, l0, l1, d);
1323 }
1324}
1325
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001326static void DumpLiteral16(uint32_t l0, uint32_t l1, uint32_t l2, uint32_t l3) {
1327 outs() << format("0x%08" PRIx32, l0) << " ";
1328 outs() << format("0x%08" PRIx32, l1) << " ";
1329 outs() << format("0x%08" PRIx32, l2) << " ";
1330 outs() << format("0x%08" PRIx32, l3) << "\n";
1331}
1332
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001333static void DumpLiteral16Section(MachOObjectFile *O, const char *sect,
1334 uint32_t sect_size, uint64_t sect_addr,
1335 bool print_addresses) {
1336 for (uint32_t i = 0; i < sect_size; i += 16) {
1337 if (print_addresses) {
1338 if (O->is64Bit())
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001339 outs() << format("%016" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001340 else
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001341 outs() << format("%08" PRIx64, sect_addr + i) << " ";
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001342 }
1343 uint32_t l0, l1, l2, l3;
1344 memcpy(&l0, sect + i, sizeof(uint32_t));
1345 memcpy(&l1, sect + i + sizeof(uint32_t), sizeof(uint32_t));
1346 memcpy(&l2, sect + i + 2 * sizeof(uint32_t), sizeof(uint32_t));
1347 memcpy(&l3, sect + i + 3 * sizeof(uint32_t), sizeof(uint32_t));
1348 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
1349 sys::swapByteOrder(l0);
1350 sys::swapByteOrder(l1);
1351 sys::swapByteOrder(l2);
1352 sys::swapByteOrder(l3);
1353 }
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001354 DumpLiteral16(l0, l1, l2, l3);
1355 }
1356}
1357
1358static void DumpLiteralPointerSection(MachOObjectFile *O,
1359 const SectionRef &Section,
1360 const char *sect, uint32_t sect_size,
1361 uint64_t sect_addr,
1362 bool print_addresses) {
1363 // Collect the literal sections in this Mach-O file.
1364 std::vector<SectionRef> LiteralSections;
1365 for (const SectionRef &Section : O->sections()) {
1366 DataRefImpl Ref = Section.getRawDataRefImpl();
1367 uint32_t section_type;
1368 if (O->is64Bit()) {
1369 const MachO::section_64 Sec = O->getSection64(Ref);
1370 section_type = Sec.flags & MachO::SECTION_TYPE;
1371 } else {
1372 const MachO::section Sec = O->getSection(Ref);
1373 section_type = Sec.flags & MachO::SECTION_TYPE;
1374 }
1375 if (section_type == MachO::S_CSTRING_LITERALS ||
1376 section_type == MachO::S_4BYTE_LITERALS ||
1377 section_type == MachO::S_8BYTE_LITERALS ||
1378 section_type == MachO::S_16BYTE_LITERALS)
1379 LiteralSections.push_back(Section);
1380 }
1381
1382 // Set the size of the literal pointer.
1383 uint32_t lp_size = O->is64Bit() ? 8 : 4;
1384
Eric Christopher572e03a2015-06-19 01:53:21 +00001385 // Collect the external relocation symbols for the literal pointers.
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001386 std::vector<std::pair<uint64_t, SymbolRef>> Relocs;
1387 for (const RelocationRef &Reloc : Section.relocations()) {
1388 DataRefImpl Rel;
1389 MachO::any_relocation_info RE;
1390 bool isExtern = false;
1391 Rel = Reloc.getRawDataRefImpl();
1392 RE = O->getRelocation(Rel);
1393 isExtern = O->getPlainRelocationExternal(RE);
1394 if (isExtern) {
Rafael Espindola96d071c2015-06-29 23:29:12 +00001395 uint64_t RelocOffset = Reloc.getOffset();
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001396 symbol_iterator RelocSym = Reloc.getSymbol();
1397 Relocs.push_back(std::make_pair(RelocOffset, *RelocSym));
1398 }
1399 }
1400 array_pod_sort(Relocs.begin(), Relocs.end());
1401
1402 // Dump each literal pointer.
1403 for (uint32_t i = 0; i < sect_size; i += lp_size) {
1404 if (print_addresses) {
1405 if (O->is64Bit())
1406 outs() << format("%016" PRIx64, sect_addr + i) << " ";
1407 else
1408 outs() << format("%08" PRIx64, sect_addr + i) << " ";
1409 }
1410 uint64_t lp;
1411 if (O->is64Bit()) {
1412 memcpy(&lp, sect + i, sizeof(uint64_t));
1413 if (O->isLittleEndian() != sys::IsLittleEndianHost)
1414 sys::swapByteOrder(lp);
1415 } else {
1416 uint32_t li;
1417 memcpy(&li, sect + i, sizeof(uint32_t));
1418 if (O->isLittleEndian() != sys::IsLittleEndianHost)
1419 sys::swapByteOrder(li);
1420 lp = li;
1421 }
1422
1423 // First look for an external relocation entry for this literal pointer.
David Majnemer42531262016-08-12 03:55:06 +00001424 auto Reloc = find_if(Relocs, [&](const std::pair<uint64_t, SymbolRef> &P) {
1425 return P.first == i;
1426 });
David Blaikie33dd45d02015-03-23 18:39:02 +00001427 if (Reloc != Relocs.end()) {
1428 symbol_iterator RelocSym = Reloc->second;
Fangrui Songe7834bd2019-04-07 08:19:55 +00001429 StringRef SymName = unwrapOrError(RelocSym->getName(), O->getFileName());
1430 outs() << "external relocation entry for symbol:" << SymName << "\n";
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001431 continue;
David Blaikie33dd45d02015-03-23 18:39:02 +00001432 }
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001433
1434 // For local references see what the section the literal pointer points to.
David Majnemer562e8292016-08-12 00:18:03 +00001435 auto Sect = find_if(LiteralSections, [&](const SectionRef &R) {
1436 return lp >= R.getAddress() && lp < R.getAddress() + R.getSize();
1437 });
David Blaikie33dd45d02015-03-23 18:39:02 +00001438 if (Sect == LiteralSections.end()) {
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001439 outs() << format("0x%" PRIx64, lp) << " (not in a literal section)\n";
David Blaikie33dd45d02015-03-23 18:39:02 +00001440 continue;
1441 }
1442
1443 uint64_t SectAddress = Sect->getAddress();
1444 uint64_t SectSize = Sect->getSize();
1445
1446 StringRef SectName;
1447 Sect->getName(SectName);
1448 DataRefImpl Ref = Sect->getRawDataRefImpl();
1449 StringRef SegmentName = O->getSectionFinalSegmentName(Ref);
1450 outs() << SegmentName << ":" << SectName << ":";
1451
1452 uint32_t section_type;
1453 if (O->is64Bit()) {
1454 const MachO::section_64 Sec = O->getSection64(Ref);
1455 section_type = Sec.flags & MachO::SECTION_TYPE;
1456 } else {
1457 const MachO::section Sec = O->getSection(Ref);
1458 section_type = Sec.flags & MachO::SECTION_TYPE;
1459 }
1460
1461 StringRef BytesStr;
1462 Sect->getContents(BytesStr);
1463 const char *Contents = reinterpret_cast<const char *>(BytesStr.data());
1464
1465 switch (section_type) {
1466 case MachO::S_CSTRING_LITERALS:
1467 for (uint64_t i = lp - SectAddress; i < SectSize && Contents[i] != '\0';
1468 i++) {
1469 DumpCstringChar(Contents[i]);
1470 }
1471 outs() << "\n";
1472 break;
1473 case MachO::S_4BYTE_LITERALS:
1474 float f;
1475 memcpy(&f, Contents + (lp - SectAddress), sizeof(float));
1476 uint32_t l;
1477 memcpy(&l, Contents + (lp - SectAddress), sizeof(uint32_t));
1478 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
1479 sys::swapByteOrder(f);
1480 sys::swapByteOrder(l);
1481 }
1482 DumpLiteral4(l, f);
1483 break;
1484 case MachO::S_8BYTE_LITERALS: {
1485 double d;
1486 memcpy(&d, Contents + (lp - SectAddress), sizeof(double));
1487 uint32_t l0, l1;
1488 memcpy(&l0, Contents + (lp - SectAddress), sizeof(uint32_t));
1489 memcpy(&l1, Contents + (lp - SectAddress) + sizeof(uint32_t),
1490 sizeof(uint32_t));
1491 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
1492 sys::swapByteOrder(f);
1493 sys::swapByteOrder(l0);
1494 sys::swapByteOrder(l1);
1495 }
1496 DumpLiteral8(O, l0, l1, d);
1497 break;
1498 }
1499 case MachO::S_16BYTE_LITERALS: {
1500 uint32_t l0, l1, l2, l3;
1501 memcpy(&l0, Contents + (lp - SectAddress), sizeof(uint32_t));
1502 memcpy(&l1, Contents + (lp - SectAddress) + sizeof(uint32_t),
1503 sizeof(uint32_t));
1504 memcpy(&l2, Contents + (lp - SectAddress) + 2 * sizeof(uint32_t),
1505 sizeof(uint32_t));
1506 memcpy(&l3, Contents + (lp - SectAddress) + 3 * sizeof(uint32_t),
1507 sizeof(uint32_t));
1508 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
1509 sys::swapByteOrder(l0);
1510 sys::swapByteOrder(l1);
1511 sys::swapByteOrder(l2);
1512 sys::swapByteOrder(l3);
1513 }
1514 DumpLiteral16(l0, l1, l2, l3);
1515 break;
1516 }
1517 }
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001518 }
1519}
1520
Kevin Enderby85b7a662018-03-20 20:29:52 +00001521static void DumpInitTermPointerSection(MachOObjectFile *O,
1522 const SectionRef &Section,
1523 const char *sect,
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001524 uint32_t sect_size, uint64_t sect_addr,
1525 SymbolAddressMap *AddrMap,
1526 bool verbose) {
1527 uint32_t stride;
Davide Italiano3eb47e22015-12-15 23:14:21 +00001528 stride = (O->is64Bit()) ? sizeof(uint64_t) : sizeof(uint32_t);
Kevin Enderby85b7a662018-03-20 20:29:52 +00001529
1530 // Collect the external relocation symbols for the pointers.
1531 std::vector<std::pair<uint64_t, SymbolRef>> Relocs;
1532 for (const RelocationRef &Reloc : Section.relocations()) {
1533 DataRefImpl Rel;
1534 MachO::any_relocation_info RE;
1535 bool isExtern = false;
1536 Rel = Reloc.getRawDataRefImpl();
1537 RE = O->getRelocation(Rel);
1538 isExtern = O->getPlainRelocationExternal(RE);
1539 if (isExtern) {
1540 uint64_t RelocOffset = Reloc.getOffset();
1541 symbol_iterator RelocSym = Reloc.getSymbol();
1542 Relocs.push_back(std::make_pair(RelocOffset, *RelocSym));
1543 }
1544 }
1545 array_pod_sort(Relocs.begin(), Relocs.end());
1546
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001547 for (uint32_t i = 0; i < sect_size; i += stride) {
1548 const char *SymbolName = nullptr;
Kevin Enderby85b7a662018-03-20 20:29:52 +00001549 uint64_t p;
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001550 if (O->is64Bit()) {
1551 outs() << format("0x%016" PRIx64, sect_addr + i * stride) << " ";
1552 uint64_t pointer_value;
1553 memcpy(&pointer_value, sect + i, stride);
1554 if (O->isLittleEndian() != sys::IsLittleEndianHost)
1555 sys::swapByteOrder(pointer_value);
1556 outs() << format("0x%016" PRIx64, pointer_value);
Kevin Enderby85b7a662018-03-20 20:29:52 +00001557 p = pointer_value;
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001558 } else {
1559 outs() << format("0x%08" PRIx64, sect_addr + i * stride) << " ";
1560 uint32_t pointer_value;
1561 memcpy(&pointer_value, sect + i, stride);
1562 if (O->isLittleEndian() != sys::IsLittleEndianHost)
1563 sys::swapByteOrder(pointer_value);
1564 outs() << format("0x%08" PRIx32, pointer_value);
Kevin Enderby85b7a662018-03-20 20:29:52 +00001565 p = pointer_value;
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001566 }
Kevin Enderby85b7a662018-03-20 20:29:52 +00001567 if (verbose) {
1568 // First look for an external relocation entry for this pointer.
1569 auto Reloc = find_if(Relocs, [&](const std::pair<uint64_t, SymbolRef> &P) {
1570 return P.first == i;
1571 });
1572 if (Reloc != Relocs.end()) {
1573 symbol_iterator RelocSym = Reloc->second;
Fangrui Songe7834bd2019-04-07 08:19:55 +00001574 outs() << " " << unwrapOrError(RelocSym->getName(), O->getFileName());
Kevin Enderby85b7a662018-03-20 20:29:52 +00001575 } else {
1576 SymbolName = GuessSymbolName(p, AddrMap);
1577 if (SymbolName)
1578 outs() << " " << SymbolName;
1579 }
1580 }
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001581 outs() << "\n";
1582 }
1583}
1584
1585static void DumpRawSectionContents(MachOObjectFile *O, const char *sect,
1586 uint32_t size, uint64_t addr) {
1587 uint32_t cputype = O->getHeader().cputype;
1588 if (cputype == MachO::CPU_TYPE_I386 || cputype == MachO::CPU_TYPE_X86_64) {
1589 uint32_t j;
1590 for (uint32_t i = 0; i < size; i += j, addr += j) {
1591 if (O->is64Bit())
1592 outs() << format("%016" PRIx64, addr) << "\t";
1593 else
Kevin Enderbyf0640752015-03-13 17:56:32 +00001594 outs() << format("%08" PRIx64, addr) << "\t";
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001595 for (j = 0; j < 16 && i + j < size; j++) {
1596 uint8_t byte_word = *(sect + i + j);
1597 outs() << format("%02" PRIx32, (uint32_t)byte_word) << " ";
1598 }
1599 outs() << "\n";
1600 }
1601 } else {
1602 uint32_t j;
1603 for (uint32_t i = 0; i < size; i += j, addr += j) {
1604 if (O->is64Bit())
1605 outs() << format("%016" PRIx64, addr) << "\t";
1606 else
Kevin Enderbyc4930852016-04-27 22:36:18 +00001607 outs() << format("%08" PRIx64, addr) << "\t";
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001608 for (j = 0; j < 4 * sizeof(int32_t) && i + j < size;
1609 j += sizeof(int32_t)) {
Kevin Enderby8eccdad2016-04-27 23:43:00 +00001610 if (i + j + sizeof(int32_t) <= size) {
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001611 uint32_t long_word;
1612 memcpy(&long_word, sect + i + j, sizeof(int32_t));
1613 if (O->isLittleEndian() != sys::IsLittleEndianHost)
1614 sys::swapByteOrder(long_word);
1615 outs() << format("%08" PRIx32, long_word) << " ";
1616 } else {
1617 for (uint32_t k = 0; i + j + k < size; k++) {
Kevin Enderby8eccdad2016-04-27 23:43:00 +00001618 uint8_t byte_word = *(sect + i + j + k);
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001619 outs() << format("%02" PRIx32, (uint32_t)byte_word) << " ";
1620 }
1621 }
1622 }
1623 outs() << "\n";
1624 }
1625 }
1626}
1627
Kevin Enderby95df54c2015-02-04 01:01:38 +00001628static void DisassembleMachO(StringRef Filename, MachOObjectFile *MachOOF,
1629 StringRef DisSegName, StringRef DisSectName);
Kevin Enderby4ad9bde2015-04-16 22:33:20 +00001630static void DumpProtocolSection(MachOObjectFile *O, const char *sect,
1631 uint32_t size, uint32_t addr);
Kevin Enderby9873e2c2016-05-23 21:34:12 +00001632#ifdef HAVE_LIBXAR
1633static void DumpBitcodeSection(MachOObjectFile *O, const char *sect,
1634 uint32_t size, bool verbose,
1635 bool PrintXarHeader, bool PrintXarFileHeaders,
1636 std::string XarMemberName);
1637#endif // defined(HAVE_LIBXAR)
Kevin Enderby95df54c2015-02-04 01:01:38 +00001638
1639static void DumpSectionContents(StringRef Filename, MachOObjectFile *O,
1640 bool verbose) {
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001641 SymbolAddressMap AddrMap;
1642 if (verbose)
1643 CreateSymbolAddressMap(O, &AddrMap);
1644
Colin LeMahieufcc32762015-07-29 19:08:10 +00001645 for (unsigned i = 0; i < FilterSections.size(); ++i) {
1646 StringRef DumpSection = FilterSections[i];
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001647 std::pair<StringRef, StringRef> DumpSegSectName;
1648 DumpSegSectName = DumpSection.split(',');
1649 StringRef DumpSegName, DumpSectName;
Jordan Rupprecht16a0de22018-12-20 00:57:06 +00001650 if (!DumpSegSectName.second.empty()) {
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001651 DumpSegName = DumpSegSectName.first;
1652 DumpSectName = DumpSegSectName.second;
1653 } else {
1654 DumpSegName = "";
1655 DumpSectName = DumpSegSectName.first;
1656 }
1657 for (const SectionRef &Section : O->sections()) {
1658 StringRef SectName;
1659 Section.getName(SectName);
1660 DataRefImpl Ref = Section.getRawDataRefImpl();
1661 StringRef SegName = O->getSectionFinalSegmentName(Ref);
1662 if ((DumpSegName.empty() || SegName == DumpSegName) &&
1663 (SectName == DumpSectName)) {
Adrian Prantlc2401dd2015-03-27 17:31:15 +00001664
Kevin Enderby95df54c2015-02-04 01:01:38 +00001665 uint32_t section_flags;
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001666 if (O->is64Bit()) {
1667 const MachO::section_64 Sec = O->getSection64(Ref);
Kevin Enderby95df54c2015-02-04 01:01:38 +00001668 section_flags = Sec.flags;
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001669
1670 } else {
1671 const MachO::section Sec = O->getSection(Ref);
Kevin Enderby95df54c2015-02-04 01:01:38 +00001672 section_flags = Sec.flags;
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001673 }
Kevin Enderby95df54c2015-02-04 01:01:38 +00001674 uint32_t section_type = section_flags & MachO::SECTION_TYPE;
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001675
1676 StringRef BytesStr;
1677 Section.getContents(BytesStr);
1678 const char *sect = reinterpret_cast<const char *>(BytesStr.data());
1679 uint32_t sect_size = BytesStr.size();
1680 uint64_t sect_addr = Section.getAddress();
1681
Adrian Prantlc2401dd2015-03-27 17:31:15 +00001682 outs() << "Contents of (" << SegName << "," << SectName
1683 << ") section\n";
1684
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001685 if (verbose) {
Kevin Enderby95df54c2015-02-04 01:01:38 +00001686 if ((section_flags & MachO::S_ATTR_PURE_INSTRUCTIONS) ||
1687 (section_flags & MachO::S_ATTR_SOME_INSTRUCTIONS)) {
1688 DisassembleMachO(Filename, O, SegName, SectName);
1689 continue;
1690 }
Kevin Enderbycd66be52015-03-11 22:06:32 +00001691 if (SegName == "__TEXT" && SectName == "__info_plist") {
1692 outs() << sect;
1693 continue;
1694 }
Kevin Enderby4ad9bde2015-04-16 22:33:20 +00001695 if (SegName == "__OBJC" && SectName == "__protocol") {
1696 DumpProtocolSection(O, sect, sect_size, sect_addr);
1697 continue;
1698 }
Kevin Enderby9873e2c2016-05-23 21:34:12 +00001699#ifdef HAVE_LIBXAR
1700 if (SegName == "__LLVM" && SectName == "__bundle") {
1701 DumpBitcodeSection(O, sect, sect_size, verbose, !NoSymbolicOperands,
1702 ArchiveHeaders, "");
1703 continue;
1704 }
1705#endif // defined(HAVE_LIBXAR)
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001706 switch (section_type) {
1707 case MachO::S_REGULAR:
1708 DumpRawSectionContents(O, sect, sect_size, sect_addr);
1709 break;
1710 case MachO::S_ZEROFILL:
1711 outs() << "zerofill section and has no contents in the file\n";
1712 break;
Kevin Enderby10ba0412015-02-04 21:38:42 +00001713 case MachO::S_CSTRING_LITERALS:
Kevin Enderbyab5e6c92015-03-17 21:07:39 +00001714 DumpCstringSection(O, sect, sect_size, sect_addr, !NoLeadingAddr);
Kevin Enderby10ba0412015-02-04 21:38:42 +00001715 break;
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001716 case MachO::S_4BYTE_LITERALS:
Kevin Enderbyab5e6c92015-03-17 21:07:39 +00001717 DumpLiteral4Section(O, sect, sect_size, sect_addr, !NoLeadingAddr);
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001718 break;
1719 case MachO::S_8BYTE_LITERALS:
Kevin Enderbyab5e6c92015-03-17 21:07:39 +00001720 DumpLiteral8Section(O, sect, sect_size, sect_addr, !NoLeadingAddr);
Kevin Enderby74b43cb2015-02-06 23:25:38 +00001721 break;
1722 case MachO::S_16BYTE_LITERALS:
Kevin Enderby0fc11822015-04-01 20:57:01 +00001723 DumpLiteral16Section(O, sect, sect_size, sect_addr, !NoLeadingAddr);
1724 break;
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001725 case MachO::S_LITERAL_POINTERS:
1726 DumpLiteralPointerSection(O, Section, sect, sect_size, sect_addr,
Kevin Enderbyab5e6c92015-03-17 21:07:39 +00001727 !NoLeadingAddr);
Kevin Enderby578fe5a2015-02-17 21:35:48 +00001728 break;
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001729 case MachO::S_MOD_INIT_FUNC_POINTERS:
1730 case MachO::S_MOD_TERM_FUNC_POINTERS:
Kevin Enderby85b7a662018-03-20 20:29:52 +00001731 DumpInitTermPointerSection(O, Section, sect, sect_size, sect_addr,
1732 &AddrMap, verbose);
Kevin Enderbyf6d25852015-01-31 00:37:11 +00001733 break;
1734 default:
1735 outs() << "Unknown section type ("
1736 << format("0x%08" PRIx32, section_type) << ")\n";
1737 DumpRawSectionContents(O, sect, sect_size, sect_addr);
1738 break;
1739 }
1740 } else {
1741 if (section_type == MachO::S_ZEROFILL)
1742 outs() << "zerofill section and has no contents in the file\n";
1743 else
1744 DumpRawSectionContents(O, sect, sect_size, sect_addr);
1745 }
1746 }
1747 }
1748 }
1749}
1750
Kevin Enderbycd66be52015-03-11 22:06:32 +00001751static void DumpInfoPlistSectionContents(StringRef Filename,
1752 MachOObjectFile *O) {
1753 for (const SectionRef &Section : O->sections()) {
1754 StringRef SectName;
1755 Section.getName(SectName);
1756 DataRefImpl Ref = Section.getRawDataRefImpl();
1757 StringRef SegName = O->getSectionFinalSegmentName(Ref);
1758 if (SegName == "__TEXT" && SectName == "__info_plist") {
Kevin Enderby30cf2e82017-06-20 21:00:25 +00001759 if (!NoLeadingHeaders)
1760 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
Kevin Enderbycd66be52015-03-11 22:06:32 +00001761 StringRef BytesStr;
1762 Section.getContents(BytesStr);
1763 const char *sect = reinterpret_cast<const char *>(BytesStr.data());
Kevin Enderby418659f2017-02-06 21:01:08 +00001764 outs() << format("%.*s", BytesStr.size(), sect) << "\n";
Kevin Enderbycd66be52015-03-11 22:06:32 +00001765 return;
1766 }
1767 }
1768}
1769
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001770// checkMachOAndArchFlags() checks to see if the ObjectFile is a Mach-O file
1771// and if it is and there is a list of architecture flags is specified then
1772// check to make sure this Mach-O file is one of those architectures or all
1773// architectures were specified. If not then an error is generated and this
1774// routine returns false. Else it returns true.
1775static bool checkMachOAndArchFlags(ObjectFile *O, StringRef Filename) {
David Majnemer91160d82016-10-31 17:11:31 +00001776 auto *MachO = dyn_cast<MachOObjectFile>(O);
1777
1778 if (!MachO || ArchAll || ArchFlags.empty())
1779 return true;
1780
1781 MachO::mach_header H;
1782 MachO::mach_header_64 H_64;
1783 Triple T;
Kevin Enderby59343a92016-12-16 22:54:02 +00001784 const char *McpuDefault, *ArchFlag;
David Majnemer91160d82016-10-31 17:11:31 +00001785 if (MachO->is64Bit()) {
1786 H_64 = MachO->MachOObjectFile::getHeader64();
Kevin Enderby59343a92016-12-16 22:54:02 +00001787 T = MachOObjectFile::getArchTriple(H_64.cputype, H_64.cpusubtype,
1788 &McpuDefault, &ArchFlag);
David Majnemer91160d82016-10-31 17:11:31 +00001789 } else {
1790 H = MachO->MachOObjectFile::getHeader();
Kevin Enderby59343a92016-12-16 22:54:02 +00001791 T = MachOObjectFile::getArchTriple(H.cputype, H.cpusubtype,
1792 &McpuDefault, &ArchFlag);
David Majnemer91160d82016-10-31 17:11:31 +00001793 }
Kevin Enderby59343a92016-12-16 22:54:02 +00001794 const std::string ArchFlagName(ArchFlag);
David Majnemer91160d82016-10-31 17:11:31 +00001795 if (none_of(ArchFlags, [&](const std::string &Name) {
Kevin Enderby59343a92016-12-16 22:54:02 +00001796 return Name == ArchFlagName;
David Majnemer91160d82016-10-31 17:11:31 +00001797 })) {
Jonas Devliegheree787efd2018-11-11 22:12:04 +00001798 WithColor::error(errs(), "llvm-objdump")
1799 << Filename << ": no architecture specified.\n";
David Majnemer91160d82016-10-31 17:11:31 +00001800 return false;
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00001801 }
1802 return true;
1803}
1804
Kevin Enderby0fc11822015-04-01 20:57:01 +00001805static void printObjcMetaData(MachOObjectFile *O, bool verbose);
1806
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001807// ProcessMachO() is passed a single opened Mach-O file, which may be an
1808// archive member and or in a slice of a universal file. It prints the
1809// the file name and header info and then processes it according to the
1810// command line options.
Kevin Enderby844c4ac2016-11-15 23:07:41 +00001811static void ProcessMachO(StringRef Name, MachOObjectFile *MachOOF,
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001812 StringRef ArchiveMemberName = StringRef(),
1813 StringRef ArchitectureName = StringRef()) {
Kevin Enderby131d1772015-01-09 19:22:37 +00001814 // If we are doing some processing here on the Mach-O file print the header
1815 // info. And don't print it otherwise like in the case of printing the
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +00001816 // UniversalHeaders or ArchiveHeaders.
Michael Trenta1703b12017-12-15 17:57:40 +00001817 if (Disassemble || Relocations || PrivateHeaders || ExportsTrie || Rebase ||
1818 Bind || SymbolTable || LazyBind || WeakBind || IndirectSymbols ||
1819 DataInCode || LinkOptHints || DylibsUsed || DylibId || ObjcMetaData ||
Jordan Rupprecht16a0de22018-12-20 00:57:06 +00001820 (!FilterSections.empty())) {
Kevin Enderbyf9d60f02016-11-29 21:43:40 +00001821 if (!NoLeadingHeaders) {
1822 outs() << Name;
1823 if (!ArchiveMemberName.empty())
1824 outs() << '(' << ArchiveMemberName << ')';
1825 if (!ArchitectureName.empty())
1826 outs() << " (architecture " << ArchitectureName << ")";
1827 outs() << ":\n";
1828 }
Kevin Enderby131d1772015-01-09 19:22:37 +00001829 }
Kevin Enderby844c4ac2016-11-15 23:07:41 +00001830 // To use the report_error() form with an ArchiveName and FileName set
1831 // these up based on what is passed for Name and ArchiveMemberName.
1832 StringRef ArchiveName;
1833 StringRef FileName;
1834 if (!ArchiveMemberName.empty()) {
1835 ArchiveName = Name;
1836 FileName = ArchiveMemberName;
1837 } else {
1838 ArchiveName = StringRef();
1839 FileName = Name;
1840 }
1841
1842 // If we need the symbol table to do the operation then check it here to
1843 // produce a good error message as to where the Mach-O file comes from in
1844 // the error message.
Jordan Rupprecht16a0de22018-12-20 00:57:06 +00001845 if (Disassemble || IndirectSymbols || !FilterSections.empty() || UnwindInfo)
Kevin Enderby844c4ac2016-11-15 23:07:41 +00001846 if (Error Err = MachOOF->checkSymbolTable())
Fangrui Songe7834bd2019-04-07 08:19:55 +00001847 report_error(std::move(Err), ArchiveName, FileName, ArchitectureName);
1848
Michael Trent7e660212019-01-15 20:41:30 +00001849 if (DisassembleAll) {
1850 for (const SectionRef &Section : MachOOF->sections()) {
1851 StringRef SectName;
1852 Section.getName(SectName);
1853 if (SectName.equals("__text")) {
1854 DataRefImpl Ref = Section.getRawDataRefImpl();
1855 StringRef SegName = MachOOF->getSectionFinalSegmentName(Ref);
1856 DisassembleMachO(FileName, MachOOF, SegName, SectName);
1857 }
1858 }
1859 }
1860 else if (Disassemble) {
Kevin Enderbyaf2999a2017-06-22 19:50:56 +00001861 if (MachOOF->getHeader().filetype == MachO::MH_KEXT_BUNDLE &&
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +00001862 MachOOF->getHeader().cputype == MachO::CPU_TYPE_ARM64)
Kevin Enderbyaf2999a2017-06-22 19:50:56 +00001863 DisassembleMachO(FileName, MachOOF, "__TEXT_EXEC", "__text");
1864 else
1865 DisassembleMachO(FileName, MachOOF, "__TEXT", "__text");
1866 }
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +00001867 if (IndirectSymbols)
Kevin Enderbyf0640752015-03-13 17:56:32 +00001868 PrintIndirectSymbols(MachOOF, !NonVerbose);
Kevin Enderby69fe98d2015-01-23 18:52:17 +00001869 if (DataInCode)
Kevin Enderbyf0640752015-03-13 17:56:32 +00001870 PrintDataInCodeTable(MachOOF, !NonVerbose);
Kevin Enderby9a509442015-01-27 21:28:24 +00001871 if (LinkOptHints)
1872 PrintLinkOptHints(MachOOF);
Kevin Enderby98da6132015-01-20 21:47:46 +00001873 if (Relocations)
Michael Trenta1703b12017-12-15 17:57:40 +00001874 PrintRelocations(MachOOF, !NonVerbose);
Kevin Enderby98da6132015-01-20 21:47:46 +00001875 if (SectionHeaders)
George Rimar73a27232019-01-15 09:19:18 +00001876 printSectionHeaders(MachOOF);
Kevin Enderby98da6132015-01-20 21:47:46 +00001877 if (SectionContents)
George Rimar73a27232019-01-15 09:19:18 +00001878 printSectionContents(MachOOF);
Jordan Rupprecht16a0de22018-12-20 00:57:06 +00001879 if (!FilterSections.empty())
Kevin Enderby844c4ac2016-11-15 23:07:41 +00001880 DumpSectionContents(FileName, MachOOF, !NonVerbose);
Kevin Enderbycd66be52015-03-11 22:06:32 +00001881 if (InfoPlist)
Kevin Enderby844c4ac2016-11-15 23:07:41 +00001882 DumpInfoPlistSectionContents(FileName, MachOOF);
Kevin Enderbybc847fa2015-03-16 20:08:09 +00001883 if (DylibsUsed)
1884 PrintDylibs(MachOOF, false);
1885 if (DylibId)
1886 PrintDylibs(MachOOF, true);
Kevin Enderby844c4ac2016-11-15 23:07:41 +00001887 if (SymbolTable)
George Rimar73a27232019-01-15 09:19:18 +00001888 printSymbolTable(MachOOF, ArchiveName, ArchitectureName);
Kevin Enderby98da6132015-01-20 21:47:46 +00001889 if (UnwindInfo)
1890 printMachOUnwindInfo(MachOOF);
Kevin Enderby0ae163f2016-01-13 00:25:36 +00001891 if (PrivateHeaders) {
1892 printMachOFileHeader(MachOOF);
1893 printMachOLoadCommands(MachOOF);
1894 }
1895 if (FirstPrivateHeader)
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001896 printMachOFileHeader(MachOOF);
Kevin Enderby0fc11822015-04-01 20:57:01 +00001897 if (ObjcMetaData)
1898 printObjcMetaData(MachOOF, !NonVerbose);
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001899 if (ExportsTrie)
1900 printExportsTrie(MachOOF);
1901 if (Rebase)
1902 printRebaseTable(MachOOF);
1903 if (Bind)
1904 printBindTable(MachOOF);
1905 if (LazyBind)
1906 printLazyBindTable(MachOOF);
1907 if (WeakBind)
1908 printWeakBindTable(MachOOF);
Igor Laevsky03a670c2016-01-26 15:09:42 +00001909
1910 if (DwarfDumpType != DIDT_Null) {
Rafael Espindolac398e672017-07-19 22:27:28 +00001911 std::unique_ptr<DIContext> DICtx = DWARFContext::create(*MachOOF);
Igor Laevsky03a670c2016-01-26 15:09:42 +00001912 // Dump the complete DWARF structure.
Adrian Prantlf4bc1f72017-06-01 18:18:23 +00001913 DIDumpOptions DumpOpts;
1914 DumpOpts.DumpType = DwarfDumpType;
Adrian Prantlf4bc1f72017-06-01 18:18:23 +00001915 DICtx->dump(outs(), DumpOpts);
Igor Laevsky03a670c2016-01-26 15:09:42 +00001916 }
Kevin Enderbye2297dd2015-01-07 21:02:18 +00001917}
1918
Kevin Enderby131d1772015-01-09 19:22:37 +00001919// printUnknownCPUType() helps print_fat_headers for unknown CPU's.
1920static void printUnknownCPUType(uint32_t cputype, uint32_t cpusubtype) {
1921 outs() << " cputype (" << cputype << ")\n";
1922 outs() << " cpusubtype (" << cpusubtype << ")\n";
1923}
1924
1925// printCPUType() helps print_fat_headers by printing the cputype and
1926// pusubtype (symbolically for the one's it knows about).
1927static void printCPUType(uint32_t cputype, uint32_t cpusubtype) {
1928 switch (cputype) {
1929 case MachO::CPU_TYPE_I386:
1930 switch (cpusubtype) {
1931 case MachO::CPU_SUBTYPE_I386_ALL:
1932 outs() << " cputype CPU_TYPE_I386\n";
1933 outs() << " cpusubtype CPU_SUBTYPE_I386_ALL\n";
1934 break;
1935 default:
1936 printUnknownCPUType(cputype, cpusubtype);
1937 break;
1938 }
1939 break;
1940 case MachO::CPU_TYPE_X86_64:
1941 switch (cpusubtype) {
1942 case MachO::CPU_SUBTYPE_X86_64_ALL:
1943 outs() << " cputype CPU_TYPE_X86_64\n";
1944 outs() << " cpusubtype CPU_SUBTYPE_X86_64_ALL\n";
1945 break;
1946 case MachO::CPU_SUBTYPE_X86_64_H:
1947 outs() << " cputype CPU_TYPE_X86_64\n";
1948 outs() << " cpusubtype CPU_SUBTYPE_X86_64_H\n";
1949 break;
1950 default:
1951 printUnknownCPUType(cputype, cpusubtype);
1952 break;
1953 }
1954 break;
1955 case MachO::CPU_TYPE_ARM:
1956 switch (cpusubtype) {
1957 case MachO::CPU_SUBTYPE_ARM_ALL:
1958 outs() << " cputype CPU_TYPE_ARM\n";
1959 outs() << " cpusubtype CPU_SUBTYPE_ARM_ALL\n";
1960 break;
1961 case MachO::CPU_SUBTYPE_ARM_V4T:
1962 outs() << " cputype CPU_TYPE_ARM\n";
1963 outs() << " cpusubtype CPU_SUBTYPE_ARM_V4T\n";
1964 break;
1965 case MachO::CPU_SUBTYPE_ARM_V5TEJ:
1966 outs() << " cputype CPU_TYPE_ARM\n";
1967 outs() << " cpusubtype CPU_SUBTYPE_ARM_V5TEJ\n";
1968 break;
1969 case MachO::CPU_SUBTYPE_ARM_XSCALE:
1970 outs() << " cputype CPU_TYPE_ARM\n";
1971 outs() << " cpusubtype CPU_SUBTYPE_ARM_XSCALE\n";
1972 break;
1973 case MachO::CPU_SUBTYPE_ARM_V6:
1974 outs() << " cputype CPU_TYPE_ARM\n";
1975 outs() << " cpusubtype CPU_SUBTYPE_ARM_V6\n";
1976 break;
1977 case MachO::CPU_SUBTYPE_ARM_V6M:
1978 outs() << " cputype CPU_TYPE_ARM\n";
1979 outs() << " cpusubtype CPU_SUBTYPE_ARM_V6M\n";
1980 break;
1981 case MachO::CPU_SUBTYPE_ARM_V7:
1982 outs() << " cputype CPU_TYPE_ARM\n";
1983 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7\n";
1984 break;
1985 case MachO::CPU_SUBTYPE_ARM_V7EM:
1986 outs() << " cputype CPU_TYPE_ARM\n";
1987 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7EM\n";
1988 break;
1989 case MachO::CPU_SUBTYPE_ARM_V7K:
1990 outs() << " cputype CPU_TYPE_ARM\n";
1991 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7K\n";
1992 break;
1993 case MachO::CPU_SUBTYPE_ARM_V7M:
1994 outs() << " cputype CPU_TYPE_ARM\n";
1995 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7M\n";
1996 break;
1997 case MachO::CPU_SUBTYPE_ARM_V7S:
1998 outs() << " cputype CPU_TYPE_ARM\n";
1999 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7S\n";
2000 break;
2001 default:
2002 printUnknownCPUType(cputype, cpusubtype);
2003 break;
2004 }
2005 break;
2006 case MachO::CPU_TYPE_ARM64:
2007 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
2008 case MachO::CPU_SUBTYPE_ARM64_ALL:
2009 outs() << " cputype CPU_TYPE_ARM64\n";
2010 outs() << " cpusubtype CPU_SUBTYPE_ARM64_ALL\n";
2011 break;
2012 default:
2013 printUnknownCPUType(cputype, cpusubtype);
2014 break;
2015 }
2016 break;
2017 default:
2018 printUnknownCPUType(cputype, cpusubtype);
2019 break;
2020 }
2021}
2022
2023static void printMachOUniversalHeaders(const object::MachOUniversalBinary *UB,
2024 bool verbose) {
2025 outs() << "Fat headers\n";
Kevin Enderby606a3382016-06-21 21:55:01 +00002026 if (verbose) {
2027 if (UB->getMagic() == MachO::FAT_MAGIC)
2028 outs() << "fat_magic FAT_MAGIC\n";
2029 else // UB->getMagic() == MachO::FAT_MAGIC_64
2030 outs() << "fat_magic FAT_MAGIC_64\n";
2031 } else
Kevin Enderby131d1772015-01-09 19:22:37 +00002032 outs() << "fat_magic " << format("0x%" PRIx32, MachO::FAT_MAGIC) << "\n";
2033
2034 uint32_t nfat_arch = UB->getNumberOfObjects();
2035 StringRef Buf = UB->getData();
2036 uint64_t size = Buf.size();
2037 uint64_t big_size = sizeof(struct MachO::fat_header) +
2038 nfat_arch * sizeof(struct MachO::fat_arch);
2039 outs() << "nfat_arch " << UB->getNumberOfObjects();
2040 if (nfat_arch == 0)
2041 outs() << " (malformed, contains zero architecture types)\n";
2042 else if (big_size > size)
2043 outs() << " (malformed, architectures past end of file)\n";
2044 else
2045 outs() << "\n";
2046
2047 for (uint32_t i = 0; i < nfat_arch; ++i) {
2048 MachOUniversalBinary::ObjectForArch OFA(UB, i);
2049 uint32_t cputype = OFA.getCPUType();
2050 uint32_t cpusubtype = OFA.getCPUSubType();
2051 outs() << "architecture ";
2052 for (uint32_t j = 0; i != 0 && j <= i - 1; j++) {
2053 MachOUniversalBinary::ObjectForArch other_OFA(UB, j);
2054 uint32_t other_cputype = other_OFA.getCPUType();
2055 uint32_t other_cpusubtype = other_OFA.getCPUSubType();
Kevin Enderby0512bd72015-01-09 21:55:03 +00002056 if (cputype != 0 && cpusubtype != 0 && cputype == other_cputype &&
Kevin Enderby131d1772015-01-09 19:22:37 +00002057 (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) ==
Kevin Enderby0512bd72015-01-09 21:55:03 +00002058 (other_cpusubtype & ~MachO::CPU_SUBTYPE_MASK)) {
Kevin Enderby131d1772015-01-09 19:22:37 +00002059 outs() << "(illegal duplicate architecture) ";
2060 break;
Kevin Enderby0512bd72015-01-09 21:55:03 +00002061 }
Kevin Enderby131d1772015-01-09 19:22:37 +00002062 }
2063 if (verbose) {
Kevin Enderby59343a92016-12-16 22:54:02 +00002064 outs() << OFA.getArchFlagName() << "\n";
Kevin Enderby131d1772015-01-09 19:22:37 +00002065 printCPUType(cputype, cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
2066 } else {
2067 outs() << i << "\n";
2068 outs() << " cputype " << cputype << "\n";
2069 outs() << " cpusubtype " << (cpusubtype & ~MachO::CPU_SUBTYPE_MASK)
2070 << "\n";
2071 }
2072 if (verbose &&
2073 (cpusubtype & MachO::CPU_SUBTYPE_MASK) == MachO::CPU_SUBTYPE_LIB64)
2074 outs() << " capabilities CPU_SUBTYPE_LIB64\n";
2075 else
2076 outs() << " capabilities "
2077 << format("0x%" PRIx32,
2078 (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24) << "\n";
2079 outs() << " offset " << OFA.getOffset();
2080 if (OFA.getOffset() > size)
2081 outs() << " (past end of file)";
2082 if (OFA.getOffset() % (1 << OFA.getAlign()) != 0)
2083 outs() << " (not aligned on it's alignment (2^" << OFA.getAlign() << ")";
2084 outs() << "\n";
2085 outs() << " size " << OFA.getSize();
2086 big_size = OFA.getOffset() + OFA.getSize();
2087 if (big_size > size)
2088 outs() << " (past end of file)";
2089 outs() << "\n";
2090 outs() << " align 2^" << OFA.getAlign() << " (" << (1 << OFA.getAlign())
2091 << ")\n";
2092 }
2093}
2094
Kevin Enderby6524bd82016-07-19 20:47:07 +00002095static void printArchiveChild(StringRef Filename, const Archive::Child &C,
2096 bool verbose, bool print_offset,
2097 StringRef ArchitectureName = StringRef()) {
Kevin Enderby13023a12015-01-15 23:19:11 +00002098 if (print_offset)
2099 outs() << C.getChildOffset() << "\t";
Fangrui Songe7834bd2019-04-07 08:19:55 +00002100 sys::fs::perms Mode =
2101 unwrapOrError(C.getAccessMode(), Filename, C, ArchitectureName);
Kevin Enderby13023a12015-01-15 23:19:11 +00002102 if (verbose) {
2103 // FIXME: this first dash, "-", is for (Mode & S_IFMT) == S_IFREG.
2104 // But there is nothing in sys::fs::perms for S_IFMT or S_IFREG.
2105 outs() << "-";
Davide Italianobb9a6cc2015-09-07 20:47:03 +00002106 outs() << ((Mode & sys::fs::owner_read) ? "r" : "-");
2107 outs() << ((Mode & sys::fs::owner_write) ? "w" : "-");
2108 outs() << ((Mode & sys::fs::owner_exe) ? "x" : "-");
2109 outs() << ((Mode & sys::fs::group_read) ? "r" : "-");
2110 outs() << ((Mode & sys::fs::group_write) ? "w" : "-");
2111 outs() << ((Mode & sys::fs::group_exe) ? "x" : "-");
2112 outs() << ((Mode & sys::fs::others_read) ? "r" : "-");
2113 outs() << ((Mode & sys::fs::others_write) ? "w" : "-");
2114 outs() << ((Mode & sys::fs::others_exe) ? "x" : "-");
Kevin Enderby13023a12015-01-15 23:19:11 +00002115 } else {
2116 outs() << format("0%o ", Mode);
2117 }
2118
Fangrui Songe7834bd2019-04-07 08:19:55 +00002119 outs() << format(
2120 "%3d/%-3d %5" PRId64 " ",
2121 unwrapOrError(C.getUID(), Filename, C, ArchitectureName),
2122 unwrapOrError(C.getGID(), Filename, C, ArchitectureName),
2123 unwrapOrError(C.getRawSize(), Filename, C, ArchitectureName));
Kevin Enderby13023a12015-01-15 23:19:11 +00002124
2125 StringRef RawLastModified = C.getRawLastModified();
2126 if (verbose) {
2127 unsigned Seconds;
2128 if (RawLastModified.getAsInteger(10, Seconds))
Vedant Kumar4031d9f2016-08-03 19:02:50 +00002129 outs() << "(date: \"" << RawLastModified
2130 << "\" contains non-decimal chars) ";
Kevin Enderby13023a12015-01-15 23:19:11 +00002131 else {
2132 // Since cime(3) returns a 26 character string of the form:
2133 // "Sun Sep 16 01:03:52 1973\n\0"
2134 // just print 24 characters.
2135 time_t t = Seconds;
2136 outs() << format("%.24s ", ctime(&t));
2137 }
2138 } else {
2139 outs() << RawLastModified << " ";
2140 }
2141
2142 if (verbose) {
Kevin Enderbyf4586032016-07-29 17:44:13 +00002143 Expected<StringRef> NameOrErr = C.getName();
2144 if (!NameOrErr) {
2145 consumeError(NameOrErr.takeError());
Fangrui Songe7834bd2019-04-07 08:19:55 +00002146 outs() << unwrapOrError(C.getRawName(), Filename, C, ArchitectureName)
2147 << "\n";
Kevin Enderby13023a12015-01-15 23:19:11 +00002148 } else {
2149 StringRef Name = NameOrErr.get();
2150 outs() << Name << "\n";
2151 }
2152 } else {
Fangrui Songe7834bd2019-04-07 08:19:55 +00002153 outs() << unwrapOrError(C.getRawName(), Filename, C, ArchitectureName)
2154 << "\n";
Kevin Enderby13023a12015-01-15 23:19:11 +00002155 }
2156}
2157
Kevin Enderby6524bd82016-07-19 20:47:07 +00002158static void printArchiveHeaders(StringRef Filename, Archive *A, bool verbose,
2159 bool print_offset,
2160 StringRef ArchitectureName = StringRef()) {
Mehdi Amini41af4302016-11-11 04:28:40 +00002161 Error Err = Error::success();
Lang Hamesfc209622016-07-14 02:24:01 +00002162 for (const auto &C : A->children(Err, false))
Kevin Enderby6524bd82016-07-19 20:47:07 +00002163 printArchiveChild(Filename, C, verbose, print_offset, ArchitectureName);
2164
Lang Hamesfc209622016-07-14 02:24:01 +00002165 if (Err)
Fangrui Songe7834bd2019-04-07 08:19:55 +00002166 report_error(std::move(Err), StringRef(), Filename, ArchitectureName);
Kevin Enderby13023a12015-01-15 23:19:11 +00002167}
2168
Dave Lee3fb120f2018-08-03 00:06:38 +00002169static bool ValidateArchFlags() {
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00002170 // Check for -arch all and verifiy the -arch flags are valid.
2171 for (unsigned i = 0; i < ArchFlags.size(); ++i) {
2172 if (ArchFlags[i] == "all") {
2173 ArchAll = true;
2174 } else {
2175 if (!MachOObjectFile::isValidArch(ArchFlags[i])) {
Jonas Devliegheree787efd2018-11-11 22:12:04 +00002176 WithColor::error(errs(), "llvm-objdump")
2177 << "unknown architecture named '" + ArchFlags[i] +
2178 "'for the -arch option\n";
Dave Lee3fb120f2018-08-03 00:06:38 +00002179 return false;
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00002180 }
2181 }
2182 }
Dave Lee3fb120f2018-08-03 00:06:38 +00002183 return true;
2184}
2185
2186// ParseInputMachO() parses the named Mach-O file in Filename and handles the
2187// -arch flags selecting just those slices as specified by them and also parses
2188// archive files. Then for each individual Mach-O file ProcessMachO() is
2189// called to process the file based on the command line options.
George Rimar73a27232019-01-15 09:19:18 +00002190void llvm::parseInputMachO(StringRef Filename) {
Dave Lee3fb120f2018-08-03 00:06:38 +00002191 if (!ValidateArchFlags())
2192 return;
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00002193
2194 // Attempt to open the binary.
Kevin Enderby3fcdf6a2016-04-06 22:14:09 +00002195 Expected<OwningBinary<Binary>> BinaryOrErr = createBinary(Filename);
Kevin Enderby98898f22017-01-30 20:53:17 +00002196 if (!BinaryOrErr) {
Fangrui Songe7834bd2019-04-07 08:19:55 +00002197 if (Error E = isNotObjectErrorInvalidFileType(BinaryOrErr.takeError()))
2198 report_error(std::move(E), Filename);
Kevin Enderby98898f22017-01-30 20:53:17 +00002199 else
2200 outs() << Filename << ": is not an object file\n";
2201 return;
2202 }
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00002203 Binary &Bin = *BinaryOrErr.get().getBinary();
Kevin Enderby3f0ffab2014-12-03 22:29:40 +00002204
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00002205 if (Archive *A = dyn_cast<Archive>(&Bin)) {
2206 outs() << "Archive : " << Filename << "\n";
Kevin Enderby13023a12015-01-15 23:19:11 +00002207 if (ArchiveHeaders)
Kevin Enderby6524bd82016-07-19 20:47:07 +00002208 printArchiveHeaders(Filename, A, !NonVerbose, ArchiveMemberOffsets);
2209
Mehdi Amini41af4302016-11-11 04:28:40 +00002210 Error Err = Error::success();
Lang Hamesfc209622016-07-14 02:24:01 +00002211 for (auto &C : A->children(Err)) {
Kevin Enderbyac9e1552016-05-17 17:10:12 +00002212 Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
2213 if (!ChildOrErr) {
Fangrui Songe7834bd2019-04-07 08:19:55 +00002214 if (Error E = isNotObjectErrorInvalidFileType(ChildOrErr.takeError()))
2215 report_error(std::move(E), Filename, C);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00002216 continue;
Kevin Enderbyac9e1552016-05-17 17:10:12 +00002217 }
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00002218 if (MachOObjectFile *O = dyn_cast<MachOObjectFile>(&*ChildOrErr.get())) {
2219 if (!checkMachOAndArchFlags(O, Filename))
2220 return;
Kevin Enderbye2297dd2015-01-07 21:02:18 +00002221 ProcessMachO(Filename, O, O->getFileName());
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00002222 }
2223 }
Lang Hamesfc209622016-07-14 02:24:01 +00002224 if (Err)
Fangrui Songe7834bd2019-04-07 08:19:55 +00002225 report_error(std::move(Err), Filename);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00002226 return;
2227 }
2228 if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(&Bin)) {
George Rimar73a27232019-01-15 09:19:18 +00002229 parseInputMachO(UB);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00002230 return;
2231 }
2232 if (ObjectFile *O = dyn_cast<ObjectFile>(&Bin)) {
2233 if (!checkMachOAndArchFlags(O, Filename))
2234 return;
Dave Lee3fb120f2018-08-03 00:06:38 +00002235 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&*O))
Kevin Enderbye2297dd2015-01-07 21:02:18 +00002236 ProcessMachO(Filename, MachOOF);
Dave Lee3fb120f2018-08-03 00:06:38 +00002237 else
Jonas Devliegheree787efd2018-11-11 22:12:04 +00002238 WithColor::error(errs(), "llvm-objdump")
2239 << Filename << "': "
2240 << "object is not a Mach-O file type.\n";
Davide Italiano25d84582016-01-13 04:11:36 +00002241 return;
2242 }
2243 llvm_unreachable("Input object can't be invalid at this point");
Rafael Espindola9b709252013-04-13 01:45:40 +00002244}
2245
George Rimar73a27232019-01-15 09:19:18 +00002246void llvm::parseInputMachO(MachOUniversalBinary *UB) {
Dave Lee3fb120f2018-08-03 00:06:38 +00002247 if (!ValidateArchFlags())
2248 return;
2249
2250 auto Filename = UB->getFileName();
2251
2252 if (UniversalHeaders)
2253 printMachOUniversalHeaders(UB, !NonVerbose);
2254
2255 // If we have a list of architecture flags specified dump only those.
Jordan Rupprecht16a0de22018-12-20 00:57:06 +00002256 if (!ArchAll && !ArchFlags.empty()) {
Dave Lee3fb120f2018-08-03 00:06:38 +00002257 // Look for a slice in the universal binary that matches each ArchFlag.
2258 bool ArchFound;
2259 for (unsigned i = 0; i < ArchFlags.size(); ++i) {
2260 ArchFound = false;
2261 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
2262 E = UB->end_objects();
2263 I != E; ++I) {
2264 if (ArchFlags[i] == I->getArchFlagName()) {
2265 ArchFound = true;
2266 Expected<std::unique_ptr<ObjectFile>> ObjOrErr =
2267 I->getAsObjectFile();
2268 std::string ArchitectureName = "";
2269 if (ArchFlags.size() > 1)
2270 ArchitectureName = I->getArchFlagName();
2271 if (ObjOrErr) {
2272 ObjectFile &O = *ObjOrErr.get();
2273 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&O))
2274 ProcessMachO(Filename, MachOOF, "", ArchitectureName);
Fangrui Songe7834bd2019-04-07 08:19:55 +00002275 } else if (Error E = isNotObjectErrorInvalidFileType(
2276 ObjOrErr.takeError())) {
2277 report_error(std::move(E), Filename, StringRef(), ArchitectureName);
Dave Lee3fb120f2018-08-03 00:06:38 +00002278 continue;
2279 } else if (Expected<std::unique_ptr<Archive>> AOrErr =
Fangrui Songe7834bd2019-04-07 08:19:55 +00002280 I->getAsArchive()) {
Dave Lee3fb120f2018-08-03 00:06:38 +00002281 std::unique_ptr<Archive> &A = *AOrErr;
2282 outs() << "Archive : " << Filename;
2283 if (!ArchitectureName.empty())
2284 outs() << " (architecture " << ArchitectureName << ")";
2285 outs() << "\n";
2286 if (ArchiveHeaders)
2287 printArchiveHeaders(Filename, A.get(), !NonVerbose,
2288 ArchiveMemberOffsets, ArchitectureName);
2289 Error Err = Error::success();
2290 for (auto &C : A->children(Err)) {
2291 Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
2292 if (!ChildOrErr) {
Fangrui Songe7834bd2019-04-07 08:19:55 +00002293 if (Error E = isNotObjectErrorInvalidFileType(ChildOrErr.takeError()))
2294 report_error(std::move(E), Filename, C, ArchitectureName);
Dave Lee3fb120f2018-08-03 00:06:38 +00002295 continue;
2296 }
2297 if (MachOObjectFile *O =
2298 dyn_cast<MachOObjectFile>(&*ChildOrErr.get()))
2299 ProcessMachO(Filename, O, O->getFileName(), ArchitectureName);
2300 }
2301 if (Err)
Fangrui Songe7834bd2019-04-07 08:19:55 +00002302 report_error(std::move(Err), Filename);
Dave Lee3fb120f2018-08-03 00:06:38 +00002303 } else {
2304 consumeError(AOrErr.takeError());
2305 error("Mach-O universal file: " + Filename + " for " +
2306 "architecture " + StringRef(I->getArchFlagName()) +
2307 " is not a Mach-O file or an archive file");
2308 }
2309 }
2310 }
2311 if (!ArchFound) {
Jonas Devliegheree787efd2018-11-11 22:12:04 +00002312 WithColor::error(errs(), "llvm-objdump")
2313 << "file: " + Filename + " does not contain "
2314 << "architecture: " + ArchFlags[i] + "\n";
Dave Lee3fb120f2018-08-03 00:06:38 +00002315 return;
2316 }
2317 }
2318 return;
2319 }
2320 // No architecture flags were specified so if this contains a slice that
2321 // matches the host architecture dump only that.
2322 if (!ArchAll) {
2323 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
2324 E = UB->end_objects();
2325 I != E; ++I) {
2326 if (MachOObjectFile::getHostArch().getArchName() ==
2327 I->getArchFlagName()) {
2328 Expected<std::unique_ptr<ObjectFile>> ObjOrErr = I->getAsObjectFile();
2329 std::string ArchiveName;
2330 ArchiveName.clear();
2331 if (ObjOrErr) {
2332 ObjectFile &O = *ObjOrErr.get();
2333 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&O))
2334 ProcessMachO(Filename, MachOOF);
Fangrui Songe7834bd2019-04-07 08:19:55 +00002335 } else if (Error E =
2336 isNotObjectErrorInvalidFileType(ObjOrErr.takeError())) {
2337 report_error(std::move(E), Filename);
Dave Lee3fb120f2018-08-03 00:06:38 +00002338 } else if (Expected<std::unique_ptr<Archive>> AOrErr =
Fangrui Songe7834bd2019-04-07 08:19:55 +00002339 I->getAsArchive()) {
Dave Lee3fb120f2018-08-03 00:06:38 +00002340 std::unique_ptr<Archive> &A = *AOrErr;
2341 outs() << "Archive : " << Filename << "\n";
2342 if (ArchiveHeaders)
2343 printArchiveHeaders(Filename, A.get(), !NonVerbose,
2344 ArchiveMemberOffsets);
2345 Error Err = Error::success();
2346 for (auto &C : A->children(Err)) {
2347 Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
2348 if (!ChildOrErr) {
Fangrui Songe7834bd2019-04-07 08:19:55 +00002349 if (Error E =
2350 isNotObjectErrorInvalidFileType(ChildOrErr.takeError()))
2351 report_error(std::move(E), Filename, C);
Dave Lee3fb120f2018-08-03 00:06:38 +00002352 continue;
2353 }
2354 if (MachOObjectFile *O =
2355 dyn_cast<MachOObjectFile>(&*ChildOrErr.get()))
2356 ProcessMachO(Filename, O, O->getFileName());
2357 }
2358 if (Err)
Fangrui Songe7834bd2019-04-07 08:19:55 +00002359 report_error(std::move(Err), Filename);
Dave Lee3fb120f2018-08-03 00:06:38 +00002360 } else {
2361 consumeError(AOrErr.takeError());
2362 error("Mach-O universal file: " + Filename + " for architecture " +
2363 StringRef(I->getArchFlagName()) +
2364 " is not a Mach-O file or an archive file");
2365 }
2366 return;
2367 }
2368 }
2369 }
2370 // Either all architectures have been specified or none have been specified
2371 // and this does not contain the host architecture so dump all the slices.
2372 bool moreThanOneArch = UB->getNumberOfObjects() > 1;
2373 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
2374 E = UB->end_objects();
2375 I != E; ++I) {
2376 Expected<std::unique_ptr<ObjectFile>> ObjOrErr = I->getAsObjectFile();
2377 std::string ArchitectureName = "";
2378 if (moreThanOneArch)
2379 ArchitectureName = I->getArchFlagName();
2380 if (ObjOrErr) {
2381 ObjectFile &Obj = *ObjOrErr.get();
2382 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&Obj))
2383 ProcessMachO(Filename, MachOOF, "", ArchitectureName);
Fangrui Songe7834bd2019-04-07 08:19:55 +00002384 } else if (Error E =
2385 isNotObjectErrorInvalidFileType(ObjOrErr.takeError())) {
2386 report_error(std::move(E), StringRef(), Filename, ArchitectureName);
2387 } else if (Expected<std::unique_ptr<Archive>> AOrErr = I->getAsArchive()) {
Dave Lee3fb120f2018-08-03 00:06:38 +00002388 std::unique_ptr<Archive> &A = *AOrErr;
2389 outs() << "Archive : " << Filename;
2390 if (!ArchitectureName.empty())
2391 outs() << " (architecture " << ArchitectureName << ")";
2392 outs() << "\n";
2393 if (ArchiveHeaders)
2394 printArchiveHeaders(Filename, A.get(), !NonVerbose,
2395 ArchiveMemberOffsets, ArchitectureName);
2396 Error Err = Error::success();
2397 for (auto &C : A->children(Err)) {
2398 Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
2399 if (!ChildOrErr) {
Fangrui Songe7834bd2019-04-07 08:19:55 +00002400 if (Error E = isNotObjectErrorInvalidFileType(ChildOrErr.takeError()))
2401 report_error(std::move(E), Filename, C, ArchitectureName);
Dave Lee3fb120f2018-08-03 00:06:38 +00002402 continue;
2403 }
2404 if (MachOObjectFile *O =
2405 dyn_cast<MachOObjectFile>(&*ChildOrErr.get())) {
2406 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(O))
2407 ProcessMachO(Filename, MachOOF, MachOOF->getFileName(),
2408 ArchitectureName);
2409 }
2410 }
2411 if (Err)
Fangrui Songe7834bd2019-04-07 08:19:55 +00002412 report_error(std::move(Err), Filename);
Dave Lee3fb120f2018-08-03 00:06:38 +00002413 } else {
2414 consumeError(AOrErr.takeError());
2415 error("Mach-O universal file: " + Filename + " for architecture " +
2416 StringRef(I->getArchFlagName()) +
2417 " is not a Mach-O file or an archive file");
2418 }
2419 }
2420}
2421
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002422// The block of info used by the Symbolizer call backs.
2423struct DisassembleInfo {
Serge Pavlove4e9a1f2018-02-14 03:26:27 +00002424 DisassembleInfo(MachOObjectFile *O, SymbolAddressMap *AddrMap,
2425 std::vector<SectionRef> *Sections, bool verbose)
2426 : verbose(verbose), O(O), AddrMap(AddrMap), Sections(Sections) {}
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002427 bool verbose;
2428 MachOObjectFile *O;
2429 SectionRef S;
Kevin Enderbybf246f52014-09-24 23:08:22 +00002430 SymbolAddressMap *AddrMap;
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002431 std::vector<SectionRef> *Sections;
Serge Pavlove4e9a1f2018-02-14 03:26:27 +00002432 const char *class_name = nullptr;
2433 const char *selector_name = nullptr;
David Blaikie0e550682018-02-20 18:48:51 +00002434 std::unique_ptr<char[]> method = nullptr;
Serge Pavlove4e9a1f2018-02-14 03:26:27 +00002435 char *demangled_name = nullptr;
2436 uint64_t adrp_addr = 0;
2437 uint32_t adrp_inst = 0;
Saleem Abdulrasool1d84d9a2017-01-08 19:14:15 +00002438 std::unique_ptr<SymbolAddressMap> bindtable;
Serge Pavlove4e9a1f2018-02-14 03:26:27 +00002439 uint32_t depth = 0;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002440};
2441
2442// SymbolizerGetOpInfo() is the operand information call back function.
2443// This is called to get the symbolic information for operand(s) of an
2444// instruction when it is being done. This routine does this from
2445// the relocation information, symbol table, etc. That block of information
2446// is a pointer to the struct DisassembleInfo that was passed when the
2447// disassembler context was created and passed to back to here when
2448// called back by the disassembler for instruction operands that could have
2449// relocation information. The address of the instruction containing operand is
2450// at the Pc parameter. The immediate value the operand has is passed in
2451// op_info->Value and is at Offset past the start of the instruction and has a
2452// byte Size of 1, 2 or 4. The symbolc information is returned in TagBuf is the
2453// LLVMOpInfo1 struct defined in the header "llvm-c/Disassembler.h" as symbol
2454// names and addends of the symbolic expression to add for the operand. The
2455// value of TagType is currently 1 (for the LLVMOpInfo1 struct). If symbolic
2456// information is returned then this function returns 1 else it returns 0.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00002457static int SymbolizerGetOpInfo(void *DisInfo, uint64_t Pc, uint64_t Offset,
2458 uint64_t Size, int TagType, void *TagBuf) {
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002459 struct DisassembleInfo *info = (struct DisassembleInfo *)DisInfo;
2460 struct LLVMOpInfo1 *op_info = (struct LLVMOpInfo1 *)TagBuf;
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002461 uint64_t value = op_info->Value;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002462
2463 // Make sure all fields returned are zero if we don't set them.
2464 memset((void *)op_info, '\0', sizeof(struct LLVMOpInfo1));
2465 op_info->Value = value;
2466
2467 // If the TagType is not the value 1 which it code knows about or if no
2468 // verbose symbolic information is wanted then just return 0, indicating no
2469 // information is being returned.
David Blaikie33dd45d02015-03-23 18:39:02 +00002470 if (TagType != 1 || !info->verbose)
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002471 return 0;
2472
2473 unsigned int Arch = info->O->getArch();
2474 if (Arch == Triple::x86) {
Kevin Enderby9907d0a2014-11-04 00:43:16 +00002475 if (Size != 1 && Size != 2 && Size != 4 && Size != 0)
2476 return 0;
Kevin Enderbyd90a4172015-10-10 00:05:01 +00002477 if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
2478 // TODO:
2479 // Search the external relocation entries of a fully linked image
2480 // (if any) for an entry that matches this segment offset.
2481 // uint32_t seg_offset = (Pc + Offset);
2482 return 0;
2483 }
2484 // In MH_OBJECT filetypes search the section's relocation entries (if any)
2485 // for an entry for this section offset.
Kevin Enderby9907d0a2014-11-04 00:43:16 +00002486 uint32_t sect_addr = info->S.getAddress();
2487 uint32_t sect_offset = (Pc + Offset) - sect_addr;
2488 bool reloc_found = false;
2489 DataRefImpl Rel;
2490 MachO::any_relocation_info RE;
2491 bool isExtern = false;
2492 SymbolRef Symbol;
2493 bool r_scattered = false;
2494 uint32_t r_value, pair_r_value, r_type;
2495 for (const RelocationRef &Reloc : info->S.relocations()) {
Rafael Espindola96d071c2015-06-29 23:29:12 +00002496 uint64_t RelocOffset = Reloc.getOffset();
Kevin Enderby9907d0a2014-11-04 00:43:16 +00002497 if (RelocOffset == sect_offset) {
2498 Rel = Reloc.getRawDataRefImpl();
2499 RE = info->O->getRelocation(Rel);
Kevin Enderby3eb73e12014-11-11 19:16:45 +00002500 r_type = info->O->getAnyRelocationType(RE);
Kevin Enderby9907d0a2014-11-04 00:43:16 +00002501 r_scattered = info->O->isRelocationScattered(RE);
2502 if (r_scattered) {
2503 r_value = info->O->getScatteredRelocationValue(RE);
Kevin Enderby9907d0a2014-11-04 00:43:16 +00002504 if (r_type == MachO::GENERIC_RELOC_SECTDIFF ||
2505 r_type == MachO::GENERIC_RELOC_LOCAL_SECTDIFF) {
2506 DataRefImpl RelNext = Rel;
2507 info->O->moveRelocationNext(RelNext);
2508 MachO::any_relocation_info RENext;
2509 RENext = info->O->getRelocation(RelNext);
2510 if (info->O->isRelocationScattered(RENext))
Kevin Enderby930fdc72014-11-06 19:00:13 +00002511 pair_r_value = info->O->getScatteredRelocationValue(RENext);
Kevin Enderby9907d0a2014-11-04 00:43:16 +00002512 else
2513 return 0;
2514 }
2515 } else {
2516 isExtern = info->O->getPlainRelocationExternal(RE);
2517 if (isExtern) {
2518 symbol_iterator RelocSym = Reloc.getSymbol();
2519 Symbol = *RelocSym;
2520 }
2521 }
2522 reloc_found = true;
2523 break;
2524 }
2525 }
2526 if (reloc_found && isExtern) {
Kevin Enderby9907d0a2014-11-04 00:43:16 +00002527 op_info->AddSymbol.Present = 1;
Fangrui Songe7834bd2019-04-07 08:19:55 +00002528 op_info->AddSymbol.Name =
2529 unwrapOrError(Symbol.getName(), info->O->getFileName()).data();
Kevin Enderby9907d0a2014-11-04 00:43:16 +00002530 // For i386 extern relocation entries the value in the instruction is
2531 // the offset from the symbol, and value is already set in op_info->Value.
2532 return 1;
2533 }
2534 if (reloc_found && (r_type == MachO::GENERIC_RELOC_SECTDIFF ||
2535 r_type == MachO::GENERIC_RELOC_LOCAL_SECTDIFF)) {
Kevin Enderbyf6d25852015-01-31 00:37:11 +00002536 const char *add = GuessSymbolName(r_value, info->AddrMap);
2537 const char *sub = GuessSymbolName(pair_r_value, info->AddrMap);
Kevin Enderby9907d0a2014-11-04 00:43:16 +00002538 uint32_t offset = value - (r_value - pair_r_value);
2539 op_info->AddSymbol.Present = 1;
2540 if (add != nullptr)
2541 op_info->AddSymbol.Name = add;
2542 else
2543 op_info->AddSymbol.Value = r_value;
2544 op_info->SubtractSymbol.Present = 1;
2545 if (sub != nullptr)
2546 op_info->SubtractSymbol.Name = sub;
2547 else
2548 op_info->SubtractSymbol.Value = pair_r_value;
2549 op_info->Value = offset;
2550 return 1;
2551 }
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002552 return 0;
David Blaikie33dd45d02015-03-23 18:39:02 +00002553 }
2554 if (Arch == Triple::x86_64) {
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002555 if (Size != 1 && Size != 2 && Size != 4 && Size != 0)
2556 return 0;
Kevin Enderbyabf10f22017-06-22 17:41:22 +00002557 // For non MH_OBJECT types, like MH_KEXT_BUNDLE, Search the external
2558 // relocation entries of a linked image (if any) for an entry that matches
2559 // this segment offset.
Kevin Enderbyd90a4172015-10-10 00:05:01 +00002560 if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
Kevin Enderbyabf10f22017-06-22 17:41:22 +00002561 uint64_t seg_offset = Pc + Offset;
2562 bool reloc_found = false;
2563 DataRefImpl Rel;
2564 MachO::any_relocation_info RE;
2565 bool isExtern = false;
2566 SymbolRef Symbol;
2567 for (const RelocationRef &Reloc : info->O->external_relocations()) {
2568 uint64_t RelocOffset = Reloc.getOffset();
2569 if (RelocOffset == seg_offset) {
2570 Rel = Reloc.getRawDataRefImpl();
2571 RE = info->O->getRelocation(Rel);
2572 // external relocation entries should always be external.
2573 isExtern = info->O->getPlainRelocationExternal(RE);
2574 if (isExtern) {
2575 symbol_iterator RelocSym = Reloc.getSymbol();
2576 Symbol = *RelocSym;
2577 }
2578 reloc_found = true;
2579 break;
2580 }
2581 }
2582 if (reloc_found && isExtern) {
2583 // The Value passed in will be adjusted by the Pc if the instruction
2584 // adds the Pc. But for x86_64 external relocation entries the Value
2585 // is the offset from the external symbol.
2586 if (info->O->getAnyRelocationPCRel(RE))
2587 op_info->Value -= Pc + Offset + Size;
Fangrui Songe7834bd2019-04-07 08:19:55 +00002588 const char *name =
2589 unwrapOrError(Symbol.getName(), info->O->getFileName()).data();
Kevin Enderbyabf10f22017-06-22 17:41:22 +00002590 op_info->AddSymbol.Present = 1;
2591 op_info->AddSymbol.Name = name;
2592 return 1;
2593 }
Kevin Enderbyd90a4172015-10-10 00:05:01 +00002594 return 0;
2595 }
2596 // In MH_OBJECT filetypes search the section's relocation entries (if any)
2597 // for an entry for this section offset.
Rafael Espindola80291272014-10-08 15:28:58 +00002598 uint64_t sect_addr = info->S.getAddress();
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002599 uint64_t sect_offset = (Pc + Offset) - sect_addr;
2600 bool reloc_found = false;
2601 DataRefImpl Rel;
2602 MachO::any_relocation_info RE;
2603 bool isExtern = false;
2604 SymbolRef Symbol;
2605 for (const RelocationRef &Reloc : info->S.relocations()) {
Rafael Espindola96d071c2015-06-29 23:29:12 +00002606 uint64_t RelocOffset = Reloc.getOffset();
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002607 if (RelocOffset == sect_offset) {
2608 Rel = Reloc.getRawDataRefImpl();
2609 RE = info->O->getRelocation(Rel);
2610 // NOTE: Scattered relocations don't exist on x86_64.
2611 isExtern = info->O->getPlainRelocationExternal(RE);
2612 if (isExtern) {
2613 symbol_iterator RelocSym = Reloc.getSymbol();
2614 Symbol = *RelocSym;
2615 }
2616 reloc_found = true;
2617 break;
2618 }
2619 }
2620 if (reloc_found && isExtern) {
2621 // The Value passed in will be adjusted by the Pc if the instruction
2622 // adds the Pc. But for x86_64 external relocation entries the Value
2623 // is the offset from the external symbol.
2624 if (info->O->getAnyRelocationPCRel(RE))
2625 op_info->Value -= Pc + Offset + Size;
Fangrui Songe7834bd2019-04-07 08:19:55 +00002626 const char *name =
2627 unwrapOrError(Symbol.getName(), info->O->getFileName()).data();
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002628 unsigned Type = info->O->getAnyRelocationType(RE);
2629 if (Type == MachO::X86_64_RELOC_SUBTRACTOR) {
2630 DataRefImpl RelNext = Rel;
2631 info->O->moveRelocationNext(RelNext);
2632 MachO::any_relocation_info RENext = info->O->getRelocation(RelNext);
2633 unsigned TypeNext = info->O->getAnyRelocationType(RENext);
2634 bool isExternNext = info->O->getPlainRelocationExternal(RENext);
2635 unsigned SymbolNum = info->O->getPlainRelocationSymbolNum(RENext);
2636 if (TypeNext == MachO::X86_64_RELOC_UNSIGNED && isExternNext) {
2637 op_info->SubtractSymbol.Present = 1;
2638 op_info->SubtractSymbol.Name = name;
2639 symbol_iterator RelocSymNext = info->O->getSymbolByIndex(SymbolNum);
2640 Symbol = *RelocSymNext;
Fangrui Songe7834bd2019-04-07 08:19:55 +00002641 name = unwrapOrError(Symbol.getName(), info->O->getFileName()).data();
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002642 }
2643 }
2644 // TODO: add the VariantKinds to op_info->VariantKind for relocation types
2645 // like: X86_64_RELOC_TLV, X86_64_RELOC_GOT_LOAD and X86_64_RELOC_GOT.
2646 op_info->AddSymbol.Present = 1;
2647 op_info->AddSymbol.Name = name;
2648 return 1;
2649 }
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002650 return 0;
David Blaikie33dd45d02015-03-23 18:39:02 +00002651 }
2652 if (Arch == Triple::arm) {
Kevin Enderby930fdc72014-11-06 19:00:13 +00002653 if (Offset != 0 || (Size != 4 && Size != 2))
2654 return 0;
Kevin Enderbyd90a4172015-10-10 00:05:01 +00002655 if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
2656 // TODO:
2657 // Search the external relocation entries of a fully linked image
2658 // (if any) for an entry that matches this segment offset.
2659 // uint32_t seg_offset = (Pc + Offset);
2660 return 0;
2661 }
2662 // In MH_OBJECT filetypes search the section's relocation entries (if any)
2663 // for an entry for this section offset.
Kevin Enderby930fdc72014-11-06 19:00:13 +00002664 uint32_t sect_addr = info->S.getAddress();
2665 uint32_t sect_offset = (Pc + Offset) - sect_addr;
Kevin Enderby930fdc72014-11-06 19:00:13 +00002666 DataRefImpl Rel;
2667 MachO::any_relocation_info RE;
2668 bool isExtern = false;
2669 SymbolRef Symbol;
2670 bool r_scattered = false;
2671 uint32_t r_value, pair_r_value, r_type, r_length, other_half;
David Blaikie33dd45d02015-03-23 18:39:02 +00002672 auto Reloc =
David Majnemer562e8292016-08-12 00:18:03 +00002673 find_if(info->S.relocations(), [&](const RelocationRef &Reloc) {
2674 uint64_t RelocOffset = Reloc.getOffset();
2675 return RelocOffset == sect_offset;
2676 });
David Blaikie33dd45d02015-03-23 18:39:02 +00002677
2678 if (Reloc == info->S.relocations().end())
2679 return 0;
2680
2681 Rel = Reloc->getRawDataRefImpl();
2682 RE = info->O->getRelocation(Rel);
2683 r_length = info->O->getAnyRelocationLength(RE);
2684 r_scattered = info->O->isRelocationScattered(RE);
2685 if (r_scattered) {
2686 r_value = info->O->getScatteredRelocationValue(RE);
2687 r_type = info->O->getScatteredRelocationType(RE);
2688 } else {
2689 r_type = info->O->getAnyRelocationType(RE);
2690 isExtern = info->O->getPlainRelocationExternal(RE);
2691 if (isExtern) {
2692 symbol_iterator RelocSym = Reloc->getSymbol();
2693 Symbol = *RelocSym;
Kevin Enderby930fdc72014-11-06 19:00:13 +00002694 }
2695 }
David Blaikie33dd45d02015-03-23 18:39:02 +00002696 if (r_type == MachO::ARM_RELOC_HALF ||
2697 r_type == MachO::ARM_RELOC_SECTDIFF ||
2698 r_type == MachO::ARM_RELOC_LOCAL_SECTDIFF ||
2699 r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
2700 DataRefImpl RelNext = Rel;
2701 info->O->moveRelocationNext(RelNext);
2702 MachO::any_relocation_info RENext;
2703 RENext = info->O->getRelocation(RelNext);
2704 other_half = info->O->getAnyRelocationAddress(RENext) & 0xffff;
2705 if (info->O->isRelocationScattered(RENext))
2706 pair_r_value = info->O->getScatteredRelocationValue(RENext);
2707 }
2708
2709 if (isExtern) {
Fangrui Songe7834bd2019-04-07 08:19:55 +00002710 const char *name =
2711 unwrapOrError(Symbol.getName(), info->O->getFileName()).data();
Kevin Enderby930fdc72014-11-06 19:00:13 +00002712 op_info->AddSymbol.Present = 1;
2713 op_info->AddSymbol.Name = name;
Sylvestre Ledru648cced2015-02-05 17:00:23 +00002714 switch (r_type) {
2715 case MachO::ARM_RELOC_HALF:
2716 if ((r_length & 0x1) == 1) {
2717 op_info->Value = value << 16 | other_half;
2718 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
2719 } else {
2720 op_info->Value = other_half << 16 | value;
2721 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
Sylvestre Ledrufe0c7ad2015-02-05 16:35:44 +00002722 }
Sylvestre Ledru648cced2015-02-05 17:00:23 +00002723 break;
2724 default:
2725 break;
Kevin Enderby930fdc72014-11-06 19:00:13 +00002726 }
2727 return 1;
2728 }
2729 // If we have a branch that is not an external relocation entry then
2730 // return 0 so the code in tryAddingSymbolicOperand() can use the
2731 // SymbolLookUp call back with the branch target address to look up the
Simon Pilgrimdae11f72016-11-20 13:31:13 +00002732 // symbol and possibility add an annotation for a symbol stub.
David Blaikie33dd45d02015-03-23 18:39:02 +00002733 if (isExtern == 0 && (r_type == MachO::ARM_RELOC_BR24 ||
2734 r_type == MachO::ARM_THUMB_RELOC_BR22))
Kevin Enderby930fdc72014-11-06 19:00:13 +00002735 return 0;
2736
2737 uint32_t offset = 0;
David Blaikie33dd45d02015-03-23 18:39:02 +00002738 if (r_type == MachO::ARM_RELOC_HALF ||
2739 r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
2740 if ((r_length & 0x1) == 1)
2741 value = value << 16 | other_half;
2742 else
2743 value = other_half << 16 | value;
2744 }
2745 if (r_scattered && (r_type != MachO::ARM_RELOC_HALF &&
2746 r_type != MachO::ARM_RELOC_HALF_SECTDIFF)) {
2747 offset = value - r_value;
2748 value = r_value;
Kevin Enderby930fdc72014-11-06 19:00:13 +00002749 }
2750
David Blaikie33dd45d02015-03-23 18:39:02 +00002751 if (r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
Kevin Enderby930fdc72014-11-06 19:00:13 +00002752 if ((r_length & 0x1) == 1)
2753 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
2754 else
2755 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
Kevin Enderbyf6d25852015-01-31 00:37:11 +00002756 const char *add = GuessSymbolName(r_value, info->AddrMap);
2757 const char *sub = GuessSymbolName(pair_r_value, info->AddrMap);
Kevin Enderby930fdc72014-11-06 19:00:13 +00002758 int32_t offset = value - (r_value - pair_r_value);
2759 op_info->AddSymbol.Present = 1;
2760 if (add != nullptr)
2761 op_info->AddSymbol.Name = add;
2762 else
2763 op_info->AddSymbol.Value = r_value;
2764 op_info->SubtractSymbol.Present = 1;
2765 if (sub != nullptr)
2766 op_info->SubtractSymbol.Name = sub;
2767 else
2768 op_info->SubtractSymbol.Value = pair_r_value;
2769 op_info->Value = offset;
2770 return 1;
2771 }
2772
Kevin Enderby930fdc72014-11-06 19:00:13 +00002773 op_info->AddSymbol.Present = 1;
2774 op_info->Value = offset;
David Blaikie33dd45d02015-03-23 18:39:02 +00002775 if (r_type == MachO::ARM_RELOC_HALF) {
2776 if ((r_length & 0x1) == 1)
2777 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
2778 else
2779 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
Kevin Enderby930fdc72014-11-06 19:00:13 +00002780 }
Kevin Enderbyf6d25852015-01-31 00:37:11 +00002781 const char *add = GuessSymbolName(value, info->AddrMap);
Kevin Enderby930fdc72014-11-06 19:00:13 +00002782 if (add != nullptr) {
2783 op_info->AddSymbol.Name = add;
2784 return 1;
2785 }
2786 op_info->AddSymbol.Value = value;
2787 return 1;
David Blaikie33dd45d02015-03-23 18:39:02 +00002788 }
2789 if (Arch == Triple::aarch64) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002790 if (Offset != 0 || Size != 4)
2791 return 0;
Kevin Enderbyd90a4172015-10-10 00:05:01 +00002792 if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
2793 // TODO:
2794 // Search the external relocation entries of a fully linked image
2795 // (if any) for an entry that matches this segment offset.
2796 // uint64_t seg_offset = (Pc + Offset);
2797 return 0;
2798 }
2799 // In MH_OBJECT filetypes search the section's relocation entries (if any)
2800 // for an entry for this section offset.
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002801 uint64_t sect_addr = info->S.getAddress();
2802 uint64_t sect_offset = (Pc + Offset) - sect_addr;
David Blaikie33dd45d02015-03-23 18:39:02 +00002803 auto Reloc =
David Majnemer562e8292016-08-12 00:18:03 +00002804 find_if(info->S.relocations(), [&](const RelocationRef &Reloc) {
2805 uint64_t RelocOffset = Reloc.getOffset();
2806 return RelocOffset == sect_offset;
2807 });
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002808
David Blaikie33dd45d02015-03-23 18:39:02 +00002809 if (Reloc == info->S.relocations().end())
2810 return 0;
2811
2812 DataRefImpl Rel = Reloc->getRawDataRefImpl();
2813 MachO::any_relocation_info RE = info->O->getRelocation(Rel);
2814 uint32_t r_type = info->O->getAnyRelocationType(RE);
2815 if (r_type == MachO::ARM64_RELOC_ADDEND) {
2816 DataRefImpl RelNext = Rel;
2817 info->O->moveRelocationNext(RelNext);
2818 MachO::any_relocation_info RENext = info->O->getRelocation(RelNext);
2819 if (value == 0) {
2820 value = info->O->getPlainRelocationSymbolNum(RENext);
2821 op_info->Value = value;
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002822 }
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002823 }
David Blaikie33dd45d02015-03-23 18:39:02 +00002824 // NOTE: Scattered relocations don't exist on arm64.
2825 if (!info->O->getPlainRelocationExternal(RE))
2826 return 0;
Fangrui Songe7834bd2019-04-07 08:19:55 +00002827 const char *name =
2828 unwrapOrError(Reloc->getSymbol()->getName(), info->O->getFileName())
2829 .data();
David Blaikie33dd45d02015-03-23 18:39:02 +00002830 op_info->AddSymbol.Present = 1;
2831 op_info->AddSymbol.Name = name;
2832
2833 switch (r_type) {
2834 case MachO::ARM64_RELOC_PAGE21:
2835 /* @page */
2836 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_PAGE;
2837 break;
2838 case MachO::ARM64_RELOC_PAGEOFF12:
2839 /* @pageoff */
2840 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_PAGEOFF;
2841 break;
2842 case MachO::ARM64_RELOC_GOT_LOAD_PAGE21:
2843 /* @gotpage */
2844 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_GOTPAGE;
2845 break;
2846 case MachO::ARM64_RELOC_GOT_LOAD_PAGEOFF12:
2847 /* @gotpageoff */
2848 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_GOTPAGEOFF;
2849 break;
2850 case MachO::ARM64_RELOC_TLVP_LOAD_PAGE21:
2851 /* @tvlppage is not implemented in llvm-mc */
2852 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_TLVP;
2853 break;
2854 case MachO::ARM64_RELOC_TLVP_LOAD_PAGEOFF12:
2855 /* @tvlppageoff is not implemented in llvm-mc */
2856 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_TLVOFF;
2857 break;
2858 default:
2859 case MachO::ARM64_RELOC_BRANCH26:
2860 op_info->VariantKind = LLVMDisassembler_VariantKind_None;
2861 break;
2862 }
2863 return 1;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002864 }
David Blaikie33dd45d02015-03-23 18:39:02 +00002865 return 0;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002866}
2867
Kevin Enderbybf246f52014-09-24 23:08:22 +00002868// GuessCstringPointer is passed the address of what might be a pointer to a
2869// literal string in a cstring section. If that address is in a cstring section
2870// it returns a pointer to that string. Else it returns nullptr.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00002871static const char *GuessCstringPointer(uint64_t ReferenceValue,
2872 struct DisassembleInfo *info) {
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00002873 for (const auto &Load : info->O->load_commands()) {
Kevin Enderbybf246f52014-09-24 23:08:22 +00002874 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
2875 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
2876 for (unsigned J = 0; J < Seg.nsects; ++J) {
2877 MachO::section_64 Sec = info->O->getSection64(Load, J);
2878 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
2879 if (section_type == MachO::S_CSTRING_LITERALS &&
2880 ReferenceValue >= Sec.addr &&
2881 ReferenceValue < Sec.addr + Sec.size) {
2882 uint64_t sect_offset = ReferenceValue - Sec.addr;
2883 uint64_t object_offset = Sec.offset + sect_offset;
2884 StringRef MachOContents = info->O->getData();
2885 uint64_t object_size = MachOContents.size();
2886 const char *object_addr = (const char *)MachOContents.data();
2887 if (object_offset < object_size) {
2888 const char *name = object_addr + object_offset;
2889 return name;
2890 } else {
2891 return nullptr;
2892 }
2893 }
2894 }
2895 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
2896 MachO::segment_command Seg = info->O->getSegmentLoadCommand(Load);
2897 for (unsigned J = 0; J < Seg.nsects; ++J) {
2898 MachO::section Sec = info->O->getSection(Load, J);
2899 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
2900 if (section_type == MachO::S_CSTRING_LITERALS &&
2901 ReferenceValue >= Sec.addr &&
2902 ReferenceValue < Sec.addr + Sec.size) {
2903 uint64_t sect_offset = ReferenceValue - Sec.addr;
2904 uint64_t object_offset = Sec.offset + sect_offset;
2905 StringRef MachOContents = info->O->getData();
2906 uint64_t object_size = MachOContents.size();
2907 const char *object_addr = (const char *)MachOContents.data();
2908 if (object_offset < object_size) {
2909 const char *name = object_addr + object_offset;
2910 return name;
2911 } else {
2912 return nullptr;
2913 }
2914 }
2915 }
2916 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00002917 }
2918 return nullptr;
2919}
2920
Kevin Enderby85974882014-09-26 22:20:44 +00002921// GuessIndirectSymbol returns the name of the indirect symbol for the
2922// ReferenceValue passed in or nullptr. This is used when ReferenceValue maybe
2923// an address of a symbol stub or a lazy or non-lazy pointer to associate the
2924// symbol name being referenced by the stub or pointer.
2925static const char *GuessIndirectSymbol(uint64_t ReferenceValue,
2926 struct DisassembleInfo *info) {
Kevin Enderby85974882014-09-26 22:20:44 +00002927 MachO::dysymtab_command Dysymtab = info->O->getDysymtabLoadCommand();
2928 MachO::symtab_command Symtab = info->O->getSymtabLoadCommand();
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00002929 for (const auto &Load : info->O->load_commands()) {
Kevin Enderby85974882014-09-26 22:20:44 +00002930 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
2931 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
2932 for (unsigned J = 0; J < Seg.nsects; ++J) {
2933 MachO::section_64 Sec = info->O->getSection64(Load, J);
2934 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
2935 if ((section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
2936 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
2937 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
2938 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
2939 section_type == MachO::S_SYMBOL_STUBS) &&
2940 ReferenceValue >= Sec.addr &&
2941 ReferenceValue < Sec.addr + Sec.size) {
2942 uint32_t stride;
2943 if (section_type == MachO::S_SYMBOL_STUBS)
2944 stride = Sec.reserved2;
2945 else
2946 stride = 8;
2947 if (stride == 0)
2948 return nullptr;
2949 uint32_t index = Sec.reserved1 + (ReferenceValue - Sec.addr) / stride;
2950 if (index < Dysymtab.nindirectsyms) {
2951 uint32_t indirect_symbol =
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002952 info->O->getIndirectSymbolTableEntry(Dysymtab, index);
Kevin Enderby85974882014-09-26 22:20:44 +00002953 if (indirect_symbol < Symtab.nsyms) {
2954 symbol_iterator Sym = info->O->getSymbolByIndex(indirect_symbol);
Fangrui Songe7834bd2019-04-07 08:19:55 +00002955 return unwrapOrError(Sym->getName(), info->O->getFileName())
2956 .data();
Kevin Enderby85974882014-09-26 22:20:44 +00002957 }
2958 }
2959 }
2960 }
2961 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
2962 MachO::segment_command Seg = info->O->getSegmentLoadCommand(Load);
2963 for (unsigned J = 0; J < Seg.nsects; ++J) {
2964 MachO::section Sec = info->O->getSection(Load, J);
2965 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
2966 if ((section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
2967 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
2968 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
2969 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
2970 section_type == MachO::S_SYMBOL_STUBS) &&
2971 ReferenceValue >= Sec.addr &&
2972 ReferenceValue < Sec.addr + Sec.size) {
2973 uint32_t stride;
2974 if (section_type == MachO::S_SYMBOL_STUBS)
2975 stride = Sec.reserved2;
2976 else
2977 stride = 4;
2978 if (stride == 0)
2979 return nullptr;
2980 uint32_t index = Sec.reserved1 + (ReferenceValue - Sec.addr) / stride;
2981 if (index < Dysymtab.nindirectsyms) {
2982 uint32_t indirect_symbol =
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002983 info->O->getIndirectSymbolTableEntry(Dysymtab, index);
Kevin Enderby85974882014-09-26 22:20:44 +00002984 if (indirect_symbol < Symtab.nsyms) {
2985 symbol_iterator Sym = info->O->getSymbolByIndex(indirect_symbol);
Fangrui Songe7834bd2019-04-07 08:19:55 +00002986 return unwrapOrError(Sym->getName(), info->O->getFileName())
2987 .data();
Kevin Enderby85974882014-09-26 22:20:44 +00002988 }
2989 }
2990 }
2991 }
2992 }
Kevin Enderby85974882014-09-26 22:20:44 +00002993 }
2994 return nullptr;
2995}
2996
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002997// method_reference() is called passing it the ReferenceName that might be
2998// a reference it to an Objective-C method call. If so then it allocates and
2999// assembles a method call string with the values last seen and saved in
3000// the DisassembleInfo's class_name and selector_name fields. This is saved
3001// into the method field of the info and any previous string is free'ed.
3002// Then the class_name field in the info is set to nullptr. The method call
3003// string is set into ReferenceName and ReferenceType is set to
3004// LLVMDisassembler_ReferenceType_Out_Objc_Message. If this not a method call
3005// then both ReferenceType and ReferenceName are left unchanged.
3006static void method_reference(struct DisassembleInfo *info,
3007 uint64_t *ReferenceType,
3008 const char **ReferenceName) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00003009 unsigned int Arch = info->O->getArch();
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003010 if (*ReferenceName != nullptr) {
3011 if (strcmp(*ReferenceName, "_objc_msgSend") == 0) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00003012 if (info->selector_name != nullptr) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003013 if (info->class_name != nullptr) {
David Blaikie0e550682018-02-20 18:48:51 +00003014 info->method = llvm::make_unique<char[]>(
3015 5 + strlen(info->class_name) + strlen(info->selector_name));
3016 char *method = info->method.get();
3017 if (method != nullptr) {
3018 strcpy(method, "+[");
3019 strcat(method, info->class_name);
3020 strcat(method, " ");
3021 strcat(method, info->selector_name);
3022 strcat(method, "]");
3023 *ReferenceName = method;
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003024 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
3025 }
3026 } else {
David Blaikie0e550682018-02-20 18:48:51 +00003027 info->method =
3028 llvm::make_unique<char[]>(9 + strlen(info->selector_name));
3029 char *method = info->method.get();
3030 if (method != nullptr) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00003031 if (Arch == Triple::x86_64)
David Blaikie0e550682018-02-20 18:48:51 +00003032 strcpy(method, "-[%rdi ");
Kevin Enderbyae3c1262014-11-14 21:52:18 +00003033 else if (Arch == Triple::aarch64)
David Blaikie0e550682018-02-20 18:48:51 +00003034 strcpy(method, "-[x0 ");
Kevin Enderbyae3c1262014-11-14 21:52:18 +00003035 else
David Blaikie0e550682018-02-20 18:48:51 +00003036 strcpy(method, "-[r? ");
3037 strcat(method, info->selector_name);
3038 strcat(method, "]");
3039 *ReferenceName = method;
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003040 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
3041 }
3042 }
3043 info->class_name = nullptr;
3044 }
3045 } else if (strcmp(*ReferenceName, "_objc_msgSendSuper2") == 0) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00003046 if (info->selector_name != nullptr) {
David Blaikie0e550682018-02-20 18:48:51 +00003047 info->method =
3048 llvm::make_unique<char[]>(17 + strlen(info->selector_name));
3049 char *method = info->method.get();
3050 if (method != nullptr) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00003051 if (Arch == Triple::x86_64)
David Blaikie0e550682018-02-20 18:48:51 +00003052 strcpy(method, "-[[%rdi super] ");
Kevin Enderbyae3c1262014-11-14 21:52:18 +00003053 else if (Arch == Triple::aarch64)
David Blaikie0e550682018-02-20 18:48:51 +00003054 strcpy(method, "-[[x0 super] ");
Kevin Enderbyae3c1262014-11-14 21:52:18 +00003055 else
David Blaikie0e550682018-02-20 18:48:51 +00003056 strcpy(method, "-[[r? super] ");
3057 strcat(method, info->selector_name);
3058 strcat(method, "]");
3059 *ReferenceName = method;
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003060 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
3061 }
3062 info->class_name = nullptr;
3063 }
3064 }
3065 }
3066}
3067
3068// GuessPointerPointer() is passed the address of what might be a pointer to
3069// a reference to an Objective-C class, selector, message ref or cfstring.
3070// If so the value of the pointer is returned and one of the booleans are set
3071// to true. If not zero is returned and all the booleans are set to false.
3072static uint64_t GuessPointerPointer(uint64_t ReferenceValue,
3073 struct DisassembleInfo *info,
3074 bool &classref, bool &selref, bool &msgref,
3075 bool &cfstring) {
3076 classref = false;
3077 selref = false;
3078 msgref = false;
3079 cfstring = false;
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00003080 for (const auto &Load : info->O->load_commands()) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003081 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
3082 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
3083 for (unsigned J = 0; J < Seg.nsects; ++J) {
3084 MachO::section_64 Sec = info->O->getSection64(Load, J);
3085 if ((strncmp(Sec.sectname, "__objc_selrefs", 16) == 0 ||
3086 strncmp(Sec.sectname, "__objc_classrefs", 16) == 0 ||
3087 strncmp(Sec.sectname, "__objc_superrefs", 16) == 0 ||
3088 strncmp(Sec.sectname, "__objc_msgrefs", 16) == 0 ||
3089 strncmp(Sec.sectname, "__cfstring", 16) == 0) &&
3090 ReferenceValue >= Sec.addr &&
3091 ReferenceValue < Sec.addr + Sec.size) {
3092 uint64_t sect_offset = ReferenceValue - Sec.addr;
3093 uint64_t object_offset = Sec.offset + sect_offset;
3094 StringRef MachOContents = info->O->getData();
3095 uint64_t object_size = MachOContents.size();
3096 const char *object_addr = (const char *)MachOContents.data();
3097 if (object_offset < object_size) {
3098 uint64_t pointer_value;
3099 memcpy(&pointer_value, object_addr + object_offset,
3100 sizeof(uint64_t));
3101 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3102 sys::swapByteOrder(pointer_value);
3103 if (strncmp(Sec.sectname, "__objc_selrefs", 16) == 0)
3104 selref = true;
3105 else if (strncmp(Sec.sectname, "__objc_classrefs", 16) == 0 ||
3106 strncmp(Sec.sectname, "__objc_superrefs", 16) == 0)
3107 classref = true;
3108 else if (strncmp(Sec.sectname, "__objc_msgrefs", 16) == 0 &&
3109 ReferenceValue + 8 < Sec.addr + Sec.size) {
3110 msgref = true;
3111 memcpy(&pointer_value, object_addr + object_offset + 8,
3112 sizeof(uint64_t));
3113 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3114 sys::swapByteOrder(pointer_value);
3115 } else if (strncmp(Sec.sectname, "__cfstring", 16) == 0)
3116 cfstring = true;
3117 return pointer_value;
3118 } else {
3119 return 0;
3120 }
3121 }
3122 }
3123 }
3124 // TODO: Look for LC_SEGMENT for 32-bit Mach-O files.
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003125 }
3126 return 0;
3127}
3128
3129// get_pointer_64 returns a pointer to the bytes in the object file at the
3130// Address from a section in the Mach-O file. And indirectly returns the
3131// offset into the section, number of bytes left in the section past the offset
3132// and which section is was being referenced. If the Address is not in a
3133// section nullptr is returned.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00003134static const char *get_pointer_64(uint64_t Address, uint32_t &offset,
3135 uint32_t &left, SectionRef &S,
Kevin Enderby846c0002015-04-16 17:19:59 +00003136 DisassembleInfo *info,
3137 bool objc_only = false) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003138 offset = 0;
3139 left = 0;
3140 S = SectionRef();
3141 for (unsigned SectIdx = 0; SectIdx != info->Sections->size(); SectIdx++) {
3142 uint64_t SectAddress = ((*(info->Sections))[SectIdx]).getAddress();
3143 uint64_t SectSize = ((*(info->Sections))[SectIdx]).getSize();
Kevin Enderby46e642f2015-10-08 22:50:55 +00003144 if (SectSize == 0)
3145 continue;
Kevin Enderby846c0002015-04-16 17:19:59 +00003146 if (objc_only) {
3147 StringRef SectName;
3148 ((*(info->Sections))[SectIdx]).getName(SectName);
3149 DataRefImpl Ref = ((*(info->Sections))[SectIdx]).getRawDataRefImpl();
3150 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
3151 if (SegName != "__OBJC" && SectName != "__cstring")
3152 continue;
3153 }
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003154 if (Address >= SectAddress && Address < SectAddress + SectSize) {
3155 S = (*(info->Sections))[SectIdx];
3156 offset = Address - SectAddress;
3157 left = SectSize - offset;
3158 StringRef SectContents;
3159 ((*(info->Sections))[SectIdx]).getContents(SectContents);
3160 return SectContents.data() + offset;
3161 }
3162 }
3163 return nullptr;
3164}
3165
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003166static const char *get_pointer_32(uint32_t Address, uint32_t &offset,
3167 uint32_t &left, SectionRef &S,
Kevin Enderby846c0002015-04-16 17:19:59 +00003168 DisassembleInfo *info,
3169 bool objc_only = false) {
3170 return get_pointer_64(Address, offset, left, S, info, objc_only);
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003171}
3172
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003173// get_symbol_64() returns the name of a symbol (or nullptr) and the address of
3174// the symbol indirectly through n_value. Based on the relocation information
3175// for the specified section offset in the specified section reference.
Kevin Enderby0fc11822015-04-01 20:57:01 +00003176// If no relocation information is found and a non-zero ReferenceValue for the
3177// symbol is passed, look up that address in the info's AddrMap.
Rafael Espindolad7a32ea2015-06-24 10:20:30 +00003178static const char *get_symbol_64(uint32_t sect_offset, SectionRef S,
3179 DisassembleInfo *info, uint64_t &n_value,
Rafael Espindolabe8b0ea2015-07-07 17:12:59 +00003180 uint64_t ReferenceValue = 0) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003181 n_value = 0;
David Blaikie33dd45d02015-03-23 18:39:02 +00003182 if (!info->verbose)
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003183 return nullptr;
3184
3185 // See if there is an external relocation entry at the sect_offset.
3186 bool reloc_found = false;
3187 DataRefImpl Rel;
3188 MachO::any_relocation_info RE;
3189 bool isExtern = false;
3190 SymbolRef Symbol;
3191 for (const RelocationRef &Reloc : S.relocations()) {
Rafael Espindola96d071c2015-06-29 23:29:12 +00003192 uint64_t RelocOffset = Reloc.getOffset();
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003193 if (RelocOffset == sect_offset) {
3194 Rel = Reloc.getRawDataRefImpl();
3195 RE = info->O->getRelocation(Rel);
3196 if (info->O->isRelocationScattered(RE))
3197 continue;
3198 isExtern = info->O->getPlainRelocationExternal(RE);
3199 if (isExtern) {
3200 symbol_iterator RelocSym = Reloc.getSymbol();
3201 Symbol = *RelocSym;
3202 }
3203 reloc_found = true;
3204 break;
3205 }
3206 }
3207 // If there is an external relocation entry for a symbol in this section
3208 // at this section_offset then use that symbol's value for the n_value
3209 // and return its name.
3210 const char *SymbolName = nullptr;
3211 if (reloc_found && isExtern) {
Rafael Espindoladea00162015-07-03 17:44:18 +00003212 n_value = Symbol.getValue();
Fangrui Songe7834bd2019-04-07 08:19:55 +00003213 StringRef Name = unwrapOrError(Symbol.getName(), info->O->getFileName());
Rafael Espindola5d0c2ff2015-07-02 20:55:21 +00003214 if (!Name.empty()) {
3215 SymbolName = Name.data();
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003216 return SymbolName;
3217 }
3218 }
3219
3220 // TODO: For fully linked images, look through the external relocation
3221 // entries off the dynamic symtab command. For these the r_offset is from the
3222 // start of the first writeable segment in the Mach-O file. So the offset
3223 // to this section from that segment is passed to this routine by the caller,
3224 // as the database_offset. Which is the difference of the section's starting
3225 // address and the first writable segment.
3226 //
3227 // NOTE: need add passing the database_offset to this routine.
3228
Kevin Enderby0fc11822015-04-01 20:57:01 +00003229 // We did not find an external relocation entry so look up the ReferenceValue
3230 // as an address of a symbol and if found return that symbol's name.
Rafael Espindolabe8b0ea2015-07-07 17:12:59 +00003231 SymbolName = GuessSymbolName(ReferenceValue, info->AddrMap);
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003232
3233 return SymbolName;
3234}
3235
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003236static const char *get_symbol_32(uint32_t sect_offset, SectionRef S,
3237 DisassembleInfo *info,
3238 uint32_t ReferenceValue) {
3239 uint64_t n_value64;
3240 return get_symbol_64(sect_offset, S, info, n_value64, ReferenceValue);
3241}
3242
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003243// These are structs in the Objective-C meta data and read to produce the
3244// comments for disassembly. While these are part of the ABI they are no
Zachary Turner264b5d92017-06-07 03:48:56 +00003245// public defintions. So the are here not in include/llvm/BinaryFormat/MachO.h
3246// .
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003247
3248// The cfstring object in a 64-bit Mach-O file.
3249struct cfstring64_t {
3250 uint64_t isa; // class64_t * (64-bit pointer)
3251 uint64_t flags; // flag bits
3252 uint64_t characters; // char * (64-bit pointer)
3253 uint64_t length; // number of non-NULL characters in above
3254};
3255
3256// The class object in a 64-bit Mach-O file.
3257struct class64_t {
3258 uint64_t isa; // class64_t * (64-bit pointer)
3259 uint64_t superclass; // class64_t * (64-bit pointer)
3260 uint64_t cache; // Cache (64-bit pointer)
3261 uint64_t vtable; // IMP * (64-bit pointer)
3262 uint64_t data; // class_ro64_t * (64-bit pointer)
3263};
3264
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003265struct class32_t {
3266 uint32_t isa; /* class32_t * (32-bit pointer) */
3267 uint32_t superclass; /* class32_t * (32-bit pointer) */
3268 uint32_t cache; /* Cache (32-bit pointer) */
3269 uint32_t vtable; /* IMP * (32-bit pointer) */
3270 uint32_t data; /* class_ro32_t * (32-bit pointer) */
3271};
3272
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003273struct class_ro64_t {
3274 uint32_t flags;
3275 uint32_t instanceStart;
3276 uint32_t instanceSize;
3277 uint32_t reserved;
3278 uint64_t ivarLayout; // const uint8_t * (64-bit pointer)
3279 uint64_t name; // const char * (64-bit pointer)
3280 uint64_t baseMethods; // const method_list_t * (64-bit pointer)
3281 uint64_t baseProtocols; // const protocol_list_t * (64-bit pointer)
3282 uint64_t ivars; // const ivar_list_t * (64-bit pointer)
3283 uint64_t weakIvarLayout; // const uint8_t * (64-bit pointer)
3284 uint64_t baseProperties; // const struct objc_property_list (64-bit pointer)
3285};
3286
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003287struct class_ro32_t {
3288 uint32_t flags;
3289 uint32_t instanceStart;
3290 uint32_t instanceSize;
3291 uint32_t ivarLayout; /* const uint8_t * (32-bit pointer) */
3292 uint32_t name; /* const char * (32-bit pointer) */
3293 uint32_t baseMethods; /* const method_list_t * (32-bit pointer) */
3294 uint32_t baseProtocols; /* const protocol_list_t * (32-bit pointer) */
3295 uint32_t ivars; /* const ivar_list_t * (32-bit pointer) */
3296 uint32_t weakIvarLayout; /* const uint8_t * (32-bit pointer) */
3297 uint32_t baseProperties; /* const struct objc_property_list *
3298 (32-bit pointer) */
3299};
3300
3301/* Values for class_ro{64,32}_t->flags */
Kevin Enderby0fc11822015-04-01 20:57:01 +00003302#define RO_META (1 << 0)
3303#define RO_ROOT (1 << 1)
3304#define RO_HAS_CXX_STRUCTORS (1 << 2)
3305
3306struct method_list64_t {
3307 uint32_t entsize;
3308 uint32_t count;
3309 /* struct method64_t first; These structures follow inline */
3310};
3311
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003312struct method_list32_t {
3313 uint32_t entsize;
3314 uint32_t count;
3315 /* struct method32_t first; These structures follow inline */
3316};
3317
Kevin Enderby0fc11822015-04-01 20:57:01 +00003318struct method64_t {
3319 uint64_t name; /* SEL (64-bit pointer) */
3320 uint64_t types; /* const char * (64-bit pointer) */
3321 uint64_t imp; /* IMP (64-bit pointer) */
3322};
3323
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003324struct method32_t {
3325 uint32_t name; /* SEL (32-bit pointer) */
3326 uint32_t types; /* const char * (32-bit pointer) */
3327 uint32_t imp; /* IMP (32-bit pointer) */
3328};
3329
Kevin Enderby0fc11822015-04-01 20:57:01 +00003330struct protocol_list64_t {
3331 uint64_t count; /* uintptr_t (a 64-bit value) */
3332 /* struct protocol64_t * list[0]; These pointers follow inline */
3333};
3334
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003335struct protocol_list32_t {
3336 uint32_t count; /* uintptr_t (a 32-bit value) */
3337 /* struct protocol32_t * list[0]; These pointers follow inline */
3338};
3339
Kevin Enderby0fc11822015-04-01 20:57:01 +00003340struct protocol64_t {
3341 uint64_t isa; /* id * (64-bit pointer) */
3342 uint64_t name; /* const char * (64-bit pointer) */
3343 uint64_t protocols; /* struct protocol_list64_t *
3344 (64-bit pointer) */
3345 uint64_t instanceMethods; /* method_list_t * (64-bit pointer) */
3346 uint64_t classMethods; /* method_list_t * (64-bit pointer) */
3347 uint64_t optionalInstanceMethods; /* method_list_t * (64-bit pointer) */
3348 uint64_t optionalClassMethods; /* method_list_t * (64-bit pointer) */
3349 uint64_t instanceProperties; /* struct objc_property_list *
3350 (64-bit pointer) */
3351};
3352
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003353struct protocol32_t {
3354 uint32_t isa; /* id * (32-bit pointer) */
3355 uint32_t name; /* const char * (32-bit pointer) */
3356 uint32_t protocols; /* struct protocol_list_t *
3357 (32-bit pointer) */
3358 uint32_t instanceMethods; /* method_list_t * (32-bit pointer) */
3359 uint32_t classMethods; /* method_list_t * (32-bit pointer) */
3360 uint32_t optionalInstanceMethods; /* method_list_t * (32-bit pointer) */
3361 uint32_t optionalClassMethods; /* method_list_t * (32-bit pointer) */
3362 uint32_t instanceProperties; /* struct objc_property_list *
3363 (32-bit pointer) */
3364};
3365
Kevin Enderby0fc11822015-04-01 20:57:01 +00003366struct ivar_list64_t {
3367 uint32_t entsize;
3368 uint32_t count;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003369 /* struct ivar64_t first; These structures follow inline */
3370};
3371
3372struct ivar_list32_t {
3373 uint32_t entsize;
3374 uint32_t count;
3375 /* struct ivar32_t first; These structures follow inline */
Kevin Enderby0fc11822015-04-01 20:57:01 +00003376};
3377
3378struct ivar64_t {
3379 uint64_t offset; /* uintptr_t * (64-bit pointer) */
3380 uint64_t name; /* const char * (64-bit pointer) */
3381 uint64_t type; /* const char * (64-bit pointer) */
3382 uint32_t alignment;
3383 uint32_t size;
3384};
3385
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003386struct ivar32_t {
3387 uint32_t offset; /* uintptr_t * (32-bit pointer) */
3388 uint32_t name; /* const char * (32-bit pointer) */
3389 uint32_t type; /* const char * (32-bit pointer) */
3390 uint32_t alignment;
3391 uint32_t size;
3392};
3393
Kevin Enderby0fc11822015-04-01 20:57:01 +00003394struct objc_property_list64 {
3395 uint32_t entsize;
3396 uint32_t count;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003397 /* struct objc_property64 first; These structures follow inline */
3398};
3399
3400struct objc_property_list32 {
3401 uint32_t entsize;
3402 uint32_t count;
3403 /* struct objc_property32 first; These structures follow inline */
Kevin Enderby0fc11822015-04-01 20:57:01 +00003404};
3405
3406struct objc_property64 {
3407 uint64_t name; /* const char * (64-bit pointer) */
3408 uint64_t attributes; /* const char * (64-bit pointer) */
3409};
3410
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003411struct objc_property32 {
3412 uint32_t name; /* const char * (32-bit pointer) */
3413 uint32_t attributes; /* const char * (32-bit pointer) */
3414};
3415
Kevin Enderby0fc11822015-04-01 20:57:01 +00003416struct category64_t {
3417 uint64_t name; /* const char * (64-bit pointer) */
3418 uint64_t cls; /* struct class_t * (64-bit pointer) */
3419 uint64_t instanceMethods; /* struct method_list_t * (64-bit pointer) */
3420 uint64_t classMethods; /* struct method_list_t * (64-bit pointer) */
3421 uint64_t protocols; /* struct protocol_list_t * (64-bit pointer) */
3422 uint64_t instanceProperties; /* struct objc_property_list *
3423 (64-bit pointer) */
3424};
3425
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003426struct category32_t {
3427 uint32_t name; /* const char * (32-bit pointer) */
3428 uint32_t cls; /* struct class_t * (32-bit pointer) */
3429 uint32_t instanceMethods; /* struct method_list_t * (32-bit pointer) */
3430 uint32_t classMethods; /* struct method_list_t * (32-bit pointer) */
3431 uint32_t protocols; /* struct protocol_list_t * (32-bit pointer) */
3432 uint32_t instanceProperties; /* struct objc_property_list *
3433 (32-bit pointer) */
3434};
3435
Kevin Enderby0fc11822015-04-01 20:57:01 +00003436struct objc_image_info64 {
3437 uint32_t version;
3438 uint32_t flags;
3439};
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003440struct objc_image_info32 {
3441 uint32_t version;
3442 uint32_t flags;
3443};
Kevin Enderby846c0002015-04-16 17:19:59 +00003444struct imageInfo_t {
3445 uint32_t version;
3446 uint32_t flags;
3447};
Kevin Enderby0fc11822015-04-01 20:57:01 +00003448/* masks for objc_image_info.flags */
3449#define OBJC_IMAGE_IS_REPLACEMENT (1 << 0)
3450#define OBJC_IMAGE_SUPPORTS_GC (1 << 1)
Dave Lee390abe42018-07-06 05:11:35 +00003451#define OBJC_IMAGE_IS_SIMULATED (1 << 5)
3452#define OBJC_IMAGE_HAS_CATEGORY_CLASS_PROPERTIES (1 << 6)
Kevin Enderby0fc11822015-04-01 20:57:01 +00003453
3454struct message_ref64 {
3455 uint64_t imp; /* IMP (64-bit pointer) */
3456 uint64_t sel; /* SEL (64-bit pointer) */
3457};
3458
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003459struct message_ref32 {
3460 uint32_t imp; /* IMP (32-bit pointer) */
3461 uint32_t sel; /* SEL (32-bit pointer) */
3462};
3463
Kevin Enderby846c0002015-04-16 17:19:59 +00003464// Objective-C 1 (32-bit only) meta data structs.
3465
3466struct objc_module_t {
3467 uint32_t version;
3468 uint32_t size;
3469 uint32_t name; /* char * (32-bit pointer) */
3470 uint32_t symtab; /* struct objc_symtab * (32-bit pointer) */
3471};
3472
3473struct objc_symtab_t {
3474 uint32_t sel_ref_cnt;
3475 uint32_t refs; /* SEL * (32-bit pointer) */
3476 uint16_t cls_def_cnt;
3477 uint16_t cat_def_cnt;
3478 // uint32_t defs[1]; /* void * (32-bit pointer) variable size */
3479};
3480
3481struct objc_class_t {
3482 uint32_t isa; /* struct objc_class * (32-bit pointer) */
3483 uint32_t super_class; /* struct objc_class * (32-bit pointer) */
3484 uint32_t name; /* const char * (32-bit pointer) */
3485 int32_t version;
3486 int32_t info;
3487 int32_t instance_size;
3488 uint32_t ivars; /* struct objc_ivar_list * (32-bit pointer) */
3489 uint32_t methodLists; /* struct objc_method_list ** (32-bit pointer) */
3490 uint32_t cache; /* struct objc_cache * (32-bit pointer) */
3491 uint32_t protocols; /* struct objc_protocol_list * (32-bit pointer) */
3492};
3493
3494#define CLS_GETINFO(cls, infomask) ((cls)->info & (infomask))
3495// class is not a metaclass
3496#define CLS_CLASS 0x1
3497// class is a metaclass
3498#define CLS_META 0x2
3499
3500struct objc_category_t {
3501 uint32_t category_name; /* char * (32-bit pointer) */
3502 uint32_t class_name; /* char * (32-bit pointer) */
3503 uint32_t instance_methods; /* struct objc_method_list * (32-bit pointer) */
3504 uint32_t class_methods; /* struct objc_method_list * (32-bit pointer) */
3505 uint32_t protocols; /* struct objc_protocol_list * (32-bit ptr) */
3506};
3507
3508struct objc_ivar_t {
3509 uint32_t ivar_name; /* char * (32-bit pointer) */
3510 uint32_t ivar_type; /* char * (32-bit pointer) */
3511 int32_t ivar_offset;
3512};
3513
3514struct objc_ivar_list_t {
3515 int32_t ivar_count;
3516 // struct objc_ivar_t ivar_list[1]; /* variable length structure */
3517};
3518
3519struct objc_method_list_t {
3520 uint32_t obsolete; /* struct objc_method_list * (32-bit pointer) */
3521 int32_t method_count;
3522 // struct objc_method_t method_list[1]; /* variable length structure */
3523};
3524
3525struct objc_method_t {
3526 uint32_t method_name; /* SEL, aka struct objc_selector * (32-bit pointer) */
3527 uint32_t method_types; /* char * (32-bit pointer) */
3528 uint32_t method_imp; /* IMP, aka function pointer, (*IMP)(id, SEL, ...)
3529 (32-bit pointer) */
3530};
3531
3532struct objc_protocol_list_t {
3533 uint32_t next; /* struct objc_protocol_list * (32-bit pointer) */
3534 int32_t count;
3535 // uint32_t list[1]; /* Protocol *, aka struct objc_protocol_t *
3536 // (32-bit pointer) */
3537};
3538
3539struct objc_protocol_t {
3540 uint32_t isa; /* struct objc_class * (32-bit pointer) */
3541 uint32_t protocol_name; /* char * (32-bit pointer) */
3542 uint32_t protocol_list; /* struct objc_protocol_list * (32-bit pointer) */
3543 uint32_t instance_methods; /* struct objc_method_description_list *
3544 (32-bit pointer) */
3545 uint32_t class_methods; /* struct objc_method_description_list *
3546 (32-bit pointer) */
3547};
3548
3549struct objc_method_description_list_t {
3550 int32_t count;
3551 // struct objc_method_description_t list[1];
3552};
3553
3554struct objc_method_description_t {
3555 uint32_t name; /* SEL, aka struct objc_selector * (32-bit pointer) */
3556 uint32_t types; /* char * (32-bit pointer) */
3557};
3558
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003559inline void swapStruct(struct cfstring64_t &cfs) {
3560 sys::swapByteOrder(cfs.isa);
3561 sys::swapByteOrder(cfs.flags);
3562 sys::swapByteOrder(cfs.characters);
3563 sys::swapByteOrder(cfs.length);
3564}
3565
3566inline void swapStruct(struct class64_t &c) {
3567 sys::swapByteOrder(c.isa);
3568 sys::swapByteOrder(c.superclass);
3569 sys::swapByteOrder(c.cache);
3570 sys::swapByteOrder(c.vtable);
3571 sys::swapByteOrder(c.data);
3572}
3573
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003574inline void swapStruct(struct class32_t &c) {
3575 sys::swapByteOrder(c.isa);
3576 sys::swapByteOrder(c.superclass);
3577 sys::swapByteOrder(c.cache);
3578 sys::swapByteOrder(c.vtable);
3579 sys::swapByteOrder(c.data);
3580}
3581
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003582inline void swapStruct(struct class_ro64_t &cro) {
3583 sys::swapByteOrder(cro.flags);
3584 sys::swapByteOrder(cro.instanceStart);
3585 sys::swapByteOrder(cro.instanceSize);
3586 sys::swapByteOrder(cro.reserved);
3587 sys::swapByteOrder(cro.ivarLayout);
3588 sys::swapByteOrder(cro.name);
3589 sys::swapByteOrder(cro.baseMethods);
3590 sys::swapByteOrder(cro.baseProtocols);
3591 sys::swapByteOrder(cro.ivars);
3592 sys::swapByteOrder(cro.weakIvarLayout);
3593 sys::swapByteOrder(cro.baseProperties);
3594}
3595
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003596inline void swapStruct(struct class_ro32_t &cro) {
3597 sys::swapByteOrder(cro.flags);
3598 sys::swapByteOrder(cro.instanceStart);
3599 sys::swapByteOrder(cro.instanceSize);
3600 sys::swapByteOrder(cro.ivarLayout);
3601 sys::swapByteOrder(cro.name);
3602 sys::swapByteOrder(cro.baseMethods);
3603 sys::swapByteOrder(cro.baseProtocols);
3604 sys::swapByteOrder(cro.ivars);
3605 sys::swapByteOrder(cro.weakIvarLayout);
3606 sys::swapByteOrder(cro.baseProperties);
3607}
3608
Kevin Enderby0fc11822015-04-01 20:57:01 +00003609inline void swapStruct(struct method_list64_t &ml) {
3610 sys::swapByteOrder(ml.entsize);
3611 sys::swapByteOrder(ml.count);
3612}
3613
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003614inline void swapStruct(struct method_list32_t &ml) {
3615 sys::swapByteOrder(ml.entsize);
3616 sys::swapByteOrder(ml.count);
3617}
3618
Kevin Enderby0fc11822015-04-01 20:57:01 +00003619inline void swapStruct(struct method64_t &m) {
3620 sys::swapByteOrder(m.name);
3621 sys::swapByteOrder(m.types);
3622 sys::swapByteOrder(m.imp);
3623}
3624
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003625inline void swapStruct(struct method32_t &m) {
3626 sys::swapByteOrder(m.name);
3627 sys::swapByteOrder(m.types);
3628 sys::swapByteOrder(m.imp);
3629}
3630
Kevin Enderby0fc11822015-04-01 20:57:01 +00003631inline void swapStruct(struct protocol_list64_t &pl) {
3632 sys::swapByteOrder(pl.count);
3633}
3634
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003635inline void swapStruct(struct protocol_list32_t &pl) {
3636 sys::swapByteOrder(pl.count);
3637}
3638
Kevin Enderby0fc11822015-04-01 20:57:01 +00003639inline void swapStruct(struct protocol64_t &p) {
3640 sys::swapByteOrder(p.isa);
3641 sys::swapByteOrder(p.name);
3642 sys::swapByteOrder(p.protocols);
3643 sys::swapByteOrder(p.instanceMethods);
3644 sys::swapByteOrder(p.classMethods);
3645 sys::swapByteOrder(p.optionalInstanceMethods);
3646 sys::swapByteOrder(p.optionalClassMethods);
3647 sys::swapByteOrder(p.instanceProperties);
3648}
3649
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003650inline void swapStruct(struct protocol32_t &p) {
3651 sys::swapByteOrder(p.isa);
3652 sys::swapByteOrder(p.name);
3653 sys::swapByteOrder(p.protocols);
3654 sys::swapByteOrder(p.instanceMethods);
3655 sys::swapByteOrder(p.classMethods);
3656 sys::swapByteOrder(p.optionalInstanceMethods);
3657 sys::swapByteOrder(p.optionalClassMethods);
3658 sys::swapByteOrder(p.instanceProperties);
3659}
3660
Kevin Enderby0fc11822015-04-01 20:57:01 +00003661inline void swapStruct(struct ivar_list64_t &il) {
3662 sys::swapByteOrder(il.entsize);
3663 sys::swapByteOrder(il.count);
3664}
3665
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003666inline void swapStruct(struct ivar_list32_t &il) {
3667 sys::swapByteOrder(il.entsize);
3668 sys::swapByteOrder(il.count);
3669}
3670
Kevin Enderby0fc11822015-04-01 20:57:01 +00003671inline void swapStruct(struct ivar64_t &i) {
3672 sys::swapByteOrder(i.offset);
3673 sys::swapByteOrder(i.name);
3674 sys::swapByteOrder(i.type);
3675 sys::swapByteOrder(i.alignment);
3676 sys::swapByteOrder(i.size);
3677}
3678
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003679inline void swapStruct(struct ivar32_t &i) {
3680 sys::swapByteOrder(i.offset);
3681 sys::swapByteOrder(i.name);
3682 sys::swapByteOrder(i.type);
3683 sys::swapByteOrder(i.alignment);
3684 sys::swapByteOrder(i.size);
3685}
3686
Kevin Enderby0fc11822015-04-01 20:57:01 +00003687inline void swapStruct(struct objc_property_list64 &pl) {
3688 sys::swapByteOrder(pl.entsize);
3689 sys::swapByteOrder(pl.count);
3690}
3691
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003692inline void swapStruct(struct objc_property_list32 &pl) {
3693 sys::swapByteOrder(pl.entsize);
3694 sys::swapByteOrder(pl.count);
3695}
3696
Kevin Enderby0fc11822015-04-01 20:57:01 +00003697inline void swapStruct(struct objc_property64 &op) {
3698 sys::swapByteOrder(op.name);
3699 sys::swapByteOrder(op.attributes);
3700}
3701
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003702inline void swapStruct(struct objc_property32 &op) {
3703 sys::swapByteOrder(op.name);
3704 sys::swapByteOrder(op.attributes);
3705}
3706
Kevin Enderby0fc11822015-04-01 20:57:01 +00003707inline void swapStruct(struct category64_t &c) {
3708 sys::swapByteOrder(c.name);
3709 sys::swapByteOrder(c.cls);
3710 sys::swapByteOrder(c.instanceMethods);
3711 sys::swapByteOrder(c.classMethods);
3712 sys::swapByteOrder(c.protocols);
3713 sys::swapByteOrder(c.instanceProperties);
3714}
3715
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003716inline void swapStruct(struct category32_t &c) {
3717 sys::swapByteOrder(c.name);
3718 sys::swapByteOrder(c.cls);
3719 sys::swapByteOrder(c.instanceMethods);
3720 sys::swapByteOrder(c.classMethods);
3721 sys::swapByteOrder(c.protocols);
3722 sys::swapByteOrder(c.instanceProperties);
3723}
3724
Kevin Enderby0fc11822015-04-01 20:57:01 +00003725inline void swapStruct(struct objc_image_info64 &o) {
3726 sys::swapByteOrder(o.version);
3727 sys::swapByteOrder(o.flags);
3728}
3729
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003730inline void swapStruct(struct objc_image_info32 &o) {
3731 sys::swapByteOrder(o.version);
3732 sys::swapByteOrder(o.flags);
3733}
3734
Kevin Enderby846c0002015-04-16 17:19:59 +00003735inline void swapStruct(struct imageInfo_t &o) {
3736 sys::swapByteOrder(o.version);
3737 sys::swapByteOrder(o.flags);
3738}
3739
Kevin Enderby0fc11822015-04-01 20:57:01 +00003740inline void swapStruct(struct message_ref64 &mr) {
3741 sys::swapByteOrder(mr.imp);
3742 sys::swapByteOrder(mr.sel);
3743}
3744
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00003745inline void swapStruct(struct message_ref32 &mr) {
3746 sys::swapByteOrder(mr.imp);
3747 sys::swapByteOrder(mr.sel);
3748}
3749
Kevin Enderby846c0002015-04-16 17:19:59 +00003750inline void swapStruct(struct objc_module_t &module) {
3751 sys::swapByteOrder(module.version);
3752 sys::swapByteOrder(module.size);
3753 sys::swapByteOrder(module.name);
3754 sys::swapByteOrder(module.symtab);
Jingyue Wufedecc42015-04-16 18:43:44 +00003755}
Kevin Enderby846c0002015-04-16 17:19:59 +00003756
3757inline void swapStruct(struct objc_symtab_t &symtab) {
3758 sys::swapByteOrder(symtab.sel_ref_cnt);
3759 sys::swapByteOrder(symtab.refs);
3760 sys::swapByteOrder(symtab.cls_def_cnt);
3761 sys::swapByteOrder(symtab.cat_def_cnt);
Jingyue Wufedecc42015-04-16 18:43:44 +00003762}
Kevin Enderby846c0002015-04-16 17:19:59 +00003763
3764inline void swapStruct(struct objc_class_t &objc_class) {
3765 sys::swapByteOrder(objc_class.isa);
3766 sys::swapByteOrder(objc_class.super_class);
3767 sys::swapByteOrder(objc_class.name);
3768 sys::swapByteOrder(objc_class.version);
3769 sys::swapByteOrder(objc_class.info);
3770 sys::swapByteOrder(objc_class.instance_size);
3771 sys::swapByteOrder(objc_class.ivars);
3772 sys::swapByteOrder(objc_class.methodLists);
3773 sys::swapByteOrder(objc_class.cache);
3774 sys::swapByteOrder(objc_class.protocols);
Jingyue Wufedecc42015-04-16 18:43:44 +00003775}
Kevin Enderby846c0002015-04-16 17:19:59 +00003776
3777inline void swapStruct(struct objc_category_t &objc_category) {
3778 sys::swapByteOrder(objc_category.category_name);
3779 sys::swapByteOrder(objc_category.class_name);
3780 sys::swapByteOrder(objc_category.instance_methods);
3781 sys::swapByteOrder(objc_category.class_methods);
3782 sys::swapByteOrder(objc_category.protocols);
3783}
3784
3785inline void swapStruct(struct objc_ivar_list_t &objc_ivar_list) {
3786 sys::swapByteOrder(objc_ivar_list.ivar_count);
3787}
3788
3789inline void swapStruct(struct objc_ivar_t &objc_ivar) {
3790 sys::swapByteOrder(objc_ivar.ivar_name);
3791 sys::swapByteOrder(objc_ivar.ivar_type);
3792 sys::swapByteOrder(objc_ivar.ivar_offset);
Jingyue Wufedecc42015-04-16 18:43:44 +00003793}
Kevin Enderby846c0002015-04-16 17:19:59 +00003794
3795inline void swapStruct(struct objc_method_list_t &method_list) {
3796 sys::swapByteOrder(method_list.obsolete);
3797 sys::swapByteOrder(method_list.method_count);
3798}
3799
3800inline void swapStruct(struct objc_method_t &method) {
3801 sys::swapByteOrder(method.method_name);
3802 sys::swapByteOrder(method.method_types);
3803 sys::swapByteOrder(method.method_imp);
3804}
3805
3806inline void swapStruct(struct objc_protocol_list_t &protocol_list) {
3807 sys::swapByteOrder(protocol_list.next);
3808 sys::swapByteOrder(protocol_list.count);
3809}
3810
3811inline void swapStruct(struct objc_protocol_t &protocol) {
3812 sys::swapByteOrder(protocol.isa);
3813 sys::swapByteOrder(protocol.protocol_name);
3814 sys::swapByteOrder(protocol.protocol_list);
3815 sys::swapByteOrder(protocol.instance_methods);
3816 sys::swapByteOrder(protocol.class_methods);
3817}
3818
3819inline void swapStruct(struct objc_method_description_list_t &mdl) {
3820 sys::swapByteOrder(mdl.count);
3821}
3822
3823inline void swapStruct(struct objc_method_description_t &md) {
3824 sys::swapByteOrder(md.name);
3825 sys::swapByteOrder(md.types);
3826}
3827
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003828static const char *get_dyld_bind_info_symbolname(uint64_t ReferenceValue,
3829 struct DisassembleInfo *info);
3830
3831// get_objc2_64bit_class_name() is used for disassembly and is passed a pointer
3832// to an Objective-C class and returns the class name. It is also passed the
3833// address of the pointer, so when the pointer is zero as it can be in an .o
3834// file, that is used to look for an external relocation entry with a symbol
3835// name.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00003836static const char *get_objc2_64bit_class_name(uint64_t pointer_value,
3837 uint64_t ReferenceValue,
3838 struct DisassembleInfo *info) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003839 const char *r;
3840 uint32_t offset, left;
3841 SectionRef S;
3842
3843 // The pointer_value can be 0 in an object file and have a relocation
3844 // entry for the class symbol at the ReferenceValue (the address of the
3845 // pointer).
3846 if (pointer_value == 0) {
3847 r = get_pointer_64(ReferenceValue, offset, left, S, info);
3848 if (r == nullptr || left < sizeof(uint64_t))
3849 return nullptr;
3850 uint64_t n_value;
3851 const char *symbol_name = get_symbol_64(offset, S, info, n_value);
3852 if (symbol_name == nullptr)
3853 return nullptr;
Hans Wennborgdb53e302014-10-23 21:59:17 +00003854 const char *class_name = strrchr(symbol_name, '$');
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003855 if (class_name != nullptr && class_name[1] == '_' && class_name[2] != '\0')
3856 return class_name + 2;
3857 else
3858 return nullptr;
3859 }
3860
3861 // The case were the pointer_value is non-zero and points to a class defined
3862 // in this Mach-O file.
3863 r = get_pointer_64(pointer_value, offset, left, S, info);
3864 if (r == nullptr || left < sizeof(struct class64_t))
3865 return nullptr;
3866 struct class64_t c;
3867 memcpy(&c, r, sizeof(struct class64_t));
3868 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3869 swapStruct(c);
3870 if (c.data == 0)
3871 return nullptr;
3872 r = get_pointer_64(c.data, offset, left, S, info);
3873 if (r == nullptr || left < sizeof(struct class_ro64_t))
3874 return nullptr;
3875 struct class_ro64_t cro;
3876 memcpy(&cro, r, sizeof(struct class_ro64_t));
3877 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3878 swapStruct(cro);
3879 if (cro.name == 0)
3880 return nullptr;
3881 const char *name = get_pointer_64(cro.name, offset, left, S, info);
3882 return name;
3883}
3884
3885// get_objc2_64bit_cfstring_name is used for disassembly and is passed a
3886// pointer to a cfstring and returns its name or nullptr.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00003887static const char *get_objc2_64bit_cfstring_name(uint64_t ReferenceValue,
3888 struct DisassembleInfo *info) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003889 const char *r, *name;
3890 uint32_t offset, left;
3891 SectionRef S;
3892 struct cfstring64_t cfs;
3893 uint64_t cfs_characters;
3894
3895 r = get_pointer_64(ReferenceValue, offset, left, S, info);
3896 if (r == nullptr || left < sizeof(struct cfstring64_t))
3897 return nullptr;
3898 memcpy(&cfs, r, sizeof(struct cfstring64_t));
3899 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3900 swapStruct(cfs);
3901 if (cfs.characters == 0) {
3902 uint64_t n_value;
3903 const char *symbol_name = get_symbol_64(
3904 offset + offsetof(struct cfstring64_t, characters), S, info, n_value);
3905 if (symbol_name == nullptr)
3906 return nullptr;
3907 cfs_characters = n_value;
3908 } else
3909 cfs_characters = cfs.characters;
3910 name = get_pointer_64(cfs_characters, offset, left, S, info);
3911
3912 return name;
3913}
3914
3915// get_objc2_64bit_selref() is used for disassembly and is passed a the address
3916// of a pointer to an Objective-C selector reference when the pointer value is
3917// zero as in a .o file and is likely to have a external relocation entry with
3918// who's symbol's n_value is the real pointer to the selector name. If that is
3919// the case the real pointer to the selector name is returned else 0 is
3920// returned
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00003921static uint64_t get_objc2_64bit_selref(uint64_t ReferenceValue,
3922 struct DisassembleInfo *info) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003923 uint32_t offset, left;
3924 SectionRef S;
3925
3926 const char *r = get_pointer_64(ReferenceValue, offset, left, S, info);
3927 if (r == nullptr || left < sizeof(uint64_t))
3928 return 0;
3929 uint64_t n_value;
3930 const char *symbol_name = get_symbol_64(offset, S, info, n_value);
3931 if (symbol_name == nullptr)
3932 return 0;
3933 return n_value;
3934}
3935
Kevin Enderby0fc11822015-04-01 20:57:01 +00003936static const SectionRef get_section(MachOObjectFile *O, const char *segname,
3937 const char *sectname) {
3938 for (const SectionRef &Section : O->sections()) {
3939 StringRef SectName;
3940 Section.getName(SectName);
3941 DataRefImpl Ref = Section.getRawDataRefImpl();
3942 StringRef SegName = O->getSectionFinalSegmentName(Ref);
3943 if (SegName == segname && SectName == sectname)
3944 return Section;
3945 }
3946 return SectionRef();
3947}
3948
3949static void
3950walk_pointer_list_64(const char *listname, const SectionRef S,
3951 MachOObjectFile *O, struct DisassembleInfo *info,
3952 void (*func)(uint64_t, struct DisassembleInfo *info)) {
3953 if (S == SectionRef())
3954 return;
3955
3956 StringRef SectName;
3957 S.getName(SectName);
3958 DataRefImpl Ref = S.getRawDataRefImpl();
3959 StringRef SegName = O->getSectionFinalSegmentName(Ref);
3960 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
3961
3962 StringRef BytesStr;
3963 S.getContents(BytesStr);
3964 const char *Contents = reinterpret_cast<const char *>(BytesStr.data());
3965
3966 for (uint32_t i = 0; i < S.getSize(); i += sizeof(uint64_t)) {
3967 uint32_t left = S.getSize() - i;
3968 uint32_t size = left < sizeof(uint64_t) ? left : sizeof(uint64_t);
3969 uint64_t p = 0;
3970 memcpy(&p, Contents + i, size);
3971 if (i + sizeof(uint64_t) > S.getSize())
3972 outs() << listname << " list pointer extends past end of (" << SegName
3973 << "," << SectName << ") section\n";
3974 outs() << format("%016" PRIx64, S.getAddress() + i) << " ";
3975
3976 if (O->isLittleEndian() != sys::IsLittleEndianHost)
3977 sys::swapByteOrder(p);
3978
3979 uint64_t n_value = 0;
3980 const char *name = get_symbol_64(i, S, info, n_value, p);
3981 if (name == nullptr)
3982 name = get_dyld_bind_info_symbolname(S.getAddress() + i, info);
3983
3984 if (n_value != 0) {
3985 outs() << format("0x%" PRIx64, n_value);
3986 if (p != 0)
3987 outs() << " + " << format("0x%" PRIx64, p);
3988 } else
3989 outs() << format("0x%" PRIx64, p);
3990 if (name != nullptr)
3991 outs() << " " << name;
3992 outs() << "\n";
3993
3994 p += n_value;
3995 if (func)
3996 func(p, info);
3997 }
3998}
3999
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004000static void
4001walk_pointer_list_32(const char *listname, const SectionRef S,
4002 MachOObjectFile *O, struct DisassembleInfo *info,
4003 void (*func)(uint32_t, struct DisassembleInfo *info)) {
4004 if (S == SectionRef())
4005 return;
4006
4007 StringRef SectName;
4008 S.getName(SectName);
4009 DataRefImpl Ref = S.getRawDataRefImpl();
4010 StringRef SegName = O->getSectionFinalSegmentName(Ref);
4011 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
4012
4013 StringRef BytesStr;
4014 S.getContents(BytesStr);
4015 const char *Contents = reinterpret_cast<const char *>(BytesStr.data());
4016
4017 for (uint32_t i = 0; i < S.getSize(); i += sizeof(uint32_t)) {
4018 uint32_t left = S.getSize() - i;
4019 uint32_t size = left < sizeof(uint32_t) ? left : sizeof(uint32_t);
4020 uint32_t p = 0;
4021 memcpy(&p, Contents + i, size);
4022 if (i + sizeof(uint32_t) > S.getSize())
4023 outs() << listname << " list pointer extends past end of (" << SegName
4024 << "," << SectName << ") section\n";
Kevin Enderbycf261312015-04-06 22:33:43 +00004025 uint32_t Address = S.getAddress() + i;
4026 outs() << format("%08" PRIx32, Address) << " ";
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004027
4028 if (O->isLittleEndian() != sys::IsLittleEndianHost)
4029 sys::swapByteOrder(p);
4030 outs() << format("0x%" PRIx32, p);
4031
4032 const char *name = get_symbol_32(i, S, info, p);
4033 if (name != nullptr)
4034 outs() << " " << name;
4035 outs() << "\n";
4036
4037 if (func)
4038 func(p, info);
4039 }
4040}
4041
4042static void print_layout_map(const char *layout_map, uint32_t left) {
Kevin Enderbya59824a2015-10-06 22:27:08 +00004043 if (layout_map == nullptr)
4044 return;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004045 outs() << " layout map: ";
4046 do {
4047 outs() << format("0x%02" PRIx32, (*layout_map) & 0xff) << " ";
4048 left--;
4049 layout_map++;
4050 } while (*layout_map != '\0' && left != 0);
4051 outs() << "\n";
4052}
4053
Kevin Enderby0fc11822015-04-01 20:57:01 +00004054static void print_layout_map64(uint64_t p, struct DisassembleInfo *info) {
4055 uint32_t offset, left;
4056 SectionRef S;
4057 const char *layout_map;
4058
4059 if (p == 0)
4060 return;
4061 layout_map = get_pointer_64(p, offset, left, S, info);
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004062 print_layout_map(layout_map, left);
4063}
4064
4065static void print_layout_map32(uint32_t p, struct DisassembleInfo *info) {
4066 uint32_t offset, left;
4067 SectionRef S;
4068 const char *layout_map;
4069
4070 if (p == 0)
4071 return;
4072 layout_map = get_pointer_32(p, offset, left, S, info);
4073 print_layout_map(layout_map, left);
Kevin Enderby0fc11822015-04-01 20:57:01 +00004074}
4075
4076static void print_method_list64_t(uint64_t p, struct DisassembleInfo *info,
4077 const char *indent) {
4078 struct method_list64_t ml;
4079 struct method64_t m;
4080 const char *r;
4081 uint32_t offset, xoffset, left, i;
4082 SectionRef S, xS;
4083 const char *name, *sym_name;
4084 uint64_t n_value;
4085
4086 r = get_pointer_64(p, offset, left, S, info);
4087 if (r == nullptr)
4088 return;
4089 memset(&ml, '\0', sizeof(struct method_list64_t));
4090 if (left < sizeof(struct method_list64_t)) {
4091 memcpy(&ml, r, left);
4092 outs() << " (method_list_t entends past the end of the section)\n";
4093 } else
4094 memcpy(&ml, r, sizeof(struct method_list64_t));
4095 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4096 swapStruct(ml);
4097 outs() << indent << "\t\t entsize " << ml.entsize << "\n";
4098 outs() << indent << "\t\t count " << ml.count << "\n";
4099
4100 p += sizeof(struct method_list64_t);
4101 offset += sizeof(struct method_list64_t);
4102 for (i = 0; i < ml.count; i++) {
4103 r = get_pointer_64(p, offset, left, S, info);
4104 if (r == nullptr)
4105 return;
4106 memset(&m, '\0', sizeof(struct method64_t));
4107 if (left < sizeof(struct method64_t)) {
Kevin Enderbya59824a2015-10-06 22:27:08 +00004108 memcpy(&m, r, left);
4109 outs() << indent << " (method_t extends past the end of the section)\n";
Kevin Enderby0fc11822015-04-01 20:57:01 +00004110 } else
4111 memcpy(&m, r, sizeof(struct method64_t));
4112 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4113 swapStruct(m);
4114
4115 outs() << indent << "\t\t name ";
4116 sym_name = get_symbol_64(offset + offsetof(struct method64_t, name), S,
4117 info, n_value, m.name);
4118 if (n_value != 0) {
4119 if (info->verbose && sym_name != nullptr)
4120 outs() << sym_name;
4121 else
4122 outs() << format("0x%" PRIx64, n_value);
4123 if (m.name != 0)
4124 outs() << " + " << format("0x%" PRIx64, m.name);
4125 } else
4126 outs() << format("0x%" PRIx64, m.name);
4127 name = get_pointer_64(m.name + n_value, xoffset, left, xS, info);
4128 if (name != nullptr)
4129 outs() << format(" %.*s", left, name);
4130 outs() << "\n";
4131
4132 outs() << indent << "\t\t types ";
4133 sym_name = get_symbol_64(offset + offsetof(struct method64_t, types), S,
4134 info, n_value, m.types);
4135 if (n_value != 0) {
4136 if (info->verbose && sym_name != nullptr)
4137 outs() << sym_name;
4138 else
4139 outs() << format("0x%" PRIx64, n_value);
4140 if (m.types != 0)
4141 outs() << " + " << format("0x%" PRIx64, m.types);
4142 } else
4143 outs() << format("0x%" PRIx64, m.types);
4144 name = get_pointer_64(m.types + n_value, xoffset, left, xS, info);
4145 if (name != nullptr)
4146 outs() << format(" %.*s", left, name);
4147 outs() << "\n";
4148
4149 outs() << indent << "\t\t imp ";
4150 name = get_symbol_64(offset + offsetof(struct method64_t, imp), S, info,
4151 n_value, m.imp);
4152 if (info->verbose && name == nullptr) {
4153 if (n_value != 0) {
4154 outs() << format("0x%" PRIx64, n_value) << " ";
4155 if (m.imp != 0)
4156 outs() << "+ " << format("0x%" PRIx64, m.imp) << " ";
4157 } else
4158 outs() << format("0x%" PRIx64, m.imp) << " ";
4159 }
4160 if (name != nullptr)
4161 outs() << name;
4162 outs() << "\n";
4163
4164 p += sizeof(struct method64_t);
4165 offset += sizeof(struct method64_t);
4166 }
4167}
4168
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004169static void print_method_list32_t(uint64_t p, struct DisassembleInfo *info,
4170 const char *indent) {
4171 struct method_list32_t ml;
4172 struct method32_t m;
Kevin Enderby846c0002015-04-16 17:19:59 +00004173 const char *r, *name;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004174 uint32_t offset, xoffset, left, i;
4175 SectionRef S, xS;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004176
4177 r = get_pointer_32(p, offset, left, S, info);
4178 if (r == nullptr)
4179 return;
4180 memset(&ml, '\0', sizeof(struct method_list32_t));
4181 if (left < sizeof(struct method_list32_t)) {
4182 memcpy(&ml, r, left);
4183 outs() << " (method_list_t entends past the end of the section)\n";
4184 } else
4185 memcpy(&ml, r, sizeof(struct method_list32_t));
4186 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4187 swapStruct(ml);
4188 outs() << indent << "\t\t entsize " << ml.entsize << "\n";
4189 outs() << indent << "\t\t count " << ml.count << "\n";
4190
4191 p += sizeof(struct method_list32_t);
4192 offset += sizeof(struct method_list32_t);
4193 for (i = 0; i < ml.count; i++) {
4194 r = get_pointer_32(p, offset, left, S, info);
4195 if (r == nullptr)
4196 return;
4197 memset(&m, '\0', sizeof(struct method32_t));
4198 if (left < sizeof(struct method32_t)) {
4199 memcpy(&ml, r, left);
4200 outs() << indent << " (method_t entends past the end of the section)\n";
4201 } else
4202 memcpy(&m, r, sizeof(struct method32_t));
4203 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4204 swapStruct(m);
4205
4206 outs() << indent << "\t\t name " << format("0x%" PRIx32, m.name);
4207 name = get_pointer_32(m.name, xoffset, left, xS, info);
4208 if (name != nullptr)
4209 outs() << format(" %.*s", left, name);
4210 outs() << "\n";
4211
4212 outs() << indent << "\t\t types " << format("0x%" PRIx32, m.types);
4213 name = get_pointer_32(m.types, xoffset, left, xS, info);
4214 if (name != nullptr)
4215 outs() << format(" %.*s", left, name);
4216 outs() << "\n";
4217
4218 outs() << indent << "\t\t imp " << format("0x%" PRIx32, m.imp);
4219 name = get_symbol_32(offset + offsetof(struct method32_t, imp), S, info,
4220 m.imp);
4221 if (name != nullptr)
4222 outs() << " " << name;
4223 outs() << "\n";
4224
4225 p += sizeof(struct method32_t);
4226 offset += sizeof(struct method32_t);
4227 }
4228}
4229
Kevin Enderby846c0002015-04-16 17:19:59 +00004230static bool print_method_list(uint32_t p, struct DisassembleInfo *info) {
4231 uint32_t offset, left, xleft;
4232 SectionRef S;
4233 struct objc_method_list_t method_list;
4234 struct objc_method_t method;
4235 const char *r, *methods, *name, *SymbolName;
4236 int32_t i;
4237
4238 r = get_pointer_32(p, offset, left, S, info, true);
4239 if (r == nullptr)
4240 return true;
4241
4242 outs() << "\n";
4243 if (left > sizeof(struct objc_method_list_t)) {
4244 memcpy(&method_list, r, sizeof(struct objc_method_list_t));
4245 } else {
4246 outs() << "\t\t objc_method_list extends past end of the section\n";
4247 memset(&method_list, '\0', sizeof(struct objc_method_list_t));
4248 memcpy(&method_list, r, left);
4249 }
4250 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4251 swapStruct(method_list);
4252
4253 outs() << "\t\t obsolete "
4254 << format("0x%08" PRIx32, method_list.obsolete) << "\n";
4255 outs() << "\t\t method_count " << method_list.method_count << "\n";
4256
4257 methods = r + sizeof(struct objc_method_list_t);
4258 for (i = 0; i < method_list.method_count; i++) {
4259 if ((i + 1) * sizeof(struct objc_method_t) > left) {
4260 outs() << "\t\t remaining method's extend past the of the section\n";
4261 break;
4262 }
4263 memcpy(&method, methods + i * sizeof(struct objc_method_t),
4264 sizeof(struct objc_method_t));
4265 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4266 swapStruct(method);
4267
4268 outs() << "\t\t method_name "
4269 << format("0x%08" PRIx32, method.method_name);
4270 if (info->verbose) {
4271 name = get_pointer_32(method.method_name, offset, xleft, S, info, true);
4272 if (name != nullptr)
4273 outs() << format(" %.*s", xleft, name);
4274 else
4275 outs() << " (not in an __OBJC section)";
4276 }
4277 outs() << "\n";
4278
4279 outs() << "\t\t method_types "
4280 << format("0x%08" PRIx32, method.method_types);
4281 if (info->verbose) {
4282 name = get_pointer_32(method.method_types, offset, xleft, S, info, true);
4283 if (name != nullptr)
4284 outs() << format(" %.*s", xleft, name);
4285 else
4286 outs() << " (not in an __OBJC section)";
4287 }
4288 outs() << "\n";
4289
4290 outs() << "\t\t method_imp "
4291 << format("0x%08" PRIx32, method.method_imp) << " ";
4292 if (info->verbose) {
4293 SymbolName = GuessSymbolName(method.method_imp, info->AddrMap);
4294 if (SymbolName != nullptr)
4295 outs() << SymbolName;
4296 }
4297 outs() << "\n";
4298 }
4299 return false;
4300}
4301
Kevin Enderby0fc11822015-04-01 20:57:01 +00004302static void print_protocol_list64_t(uint64_t p, struct DisassembleInfo *info) {
4303 struct protocol_list64_t pl;
4304 uint64_t q, n_value;
4305 struct protocol64_t pc;
4306 const char *r;
4307 uint32_t offset, xoffset, left, i;
4308 SectionRef S, xS;
4309 const char *name, *sym_name;
4310
4311 r = get_pointer_64(p, offset, left, S, info);
4312 if (r == nullptr)
4313 return;
4314 memset(&pl, '\0', sizeof(struct protocol_list64_t));
4315 if (left < sizeof(struct protocol_list64_t)) {
4316 memcpy(&pl, r, left);
4317 outs() << " (protocol_list_t entends past the end of the section)\n";
4318 } else
4319 memcpy(&pl, r, sizeof(struct protocol_list64_t));
4320 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4321 swapStruct(pl);
4322 outs() << " count " << pl.count << "\n";
4323
4324 p += sizeof(struct protocol_list64_t);
4325 offset += sizeof(struct protocol_list64_t);
4326 for (i = 0; i < pl.count; i++) {
4327 r = get_pointer_64(p, offset, left, S, info);
4328 if (r == nullptr)
4329 return;
4330 q = 0;
4331 if (left < sizeof(uint64_t)) {
4332 memcpy(&q, r, left);
4333 outs() << " (protocol_t * entends past the end of the section)\n";
4334 } else
4335 memcpy(&q, r, sizeof(uint64_t));
4336 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4337 sys::swapByteOrder(q);
4338
4339 outs() << "\t\t list[" << i << "] ";
4340 sym_name = get_symbol_64(offset, S, info, n_value, q);
4341 if (n_value != 0) {
4342 if (info->verbose && sym_name != nullptr)
4343 outs() << sym_name;
4344 else
4345 outs() << format("0x%" PRIx64, n_value);
4346 if (q != 0)
4347 outs() << " + " << format("0x%" PRIx64, q);
4348 } else
4349 outs() << format("0x%" PRIx64, q);
4350 outs() << " (struct protocol_t *)\n";
4351
4352 r = get_pointer_64(q + n_value, offset, left, S, info);
4353 if (r == nullptr)
4354 return;
4355 memset(&pc, '\0', sizeof(struct protocol64_t));
4356 if (left < sizeof(struct protocol64_t)) {
4357 memcpy(&pc, r, left);
4358 outs() << " (protocol_t entends past the end of the section)\n";
4359 } else
4360 memcpy(&pc, r, sizeof(struct protocol64_t));
4361 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4362 swapStruct(pc);
4363
4364 outs() << "\t\t\t isa " << format("0x%" PRIx64, pc.isa) << "\n";
4365
4366 outs() << "\t\t\t name ";
4367 sym_name = get_symbol_64(offset + offsetof(struct protocol64_t, name), S,
4368 info, n_value, pc.name);
4369 if (n_value != 0) {
4370 if (info->verbose && sym_name != nullptr)
4371 outs() << sym_name;
4372 else
4373 outs() << format("0x%" PRIx64, n_value);
4374 if (pc.name != 0)
4375 outs() << " + " << format("0x%" PRIx64, pc.name);
4376 } else
4377 outs() << format("0x%" PRIx64, pc.name);
4378 name = get_pointer_64(pc.name + n_value, xoffset, left, xS, info);
4379 if (name != nullptr)
4380 outs() << format(" %.*s", left, name);
4381 outs() << "\n";
4382
4383 outs() << "\t\t\tprotocols " << format("0x%" PRIx64, pc.protocols) << "\n";
4384
4385 outs() << "\t\t instanceMethods ";
4386 sym_name =
4387 get_symbol_64(offset + offsetof(struct protocol64_t, instanceMethods),
4388 S, info, n_value, pc.instanceMethods);
4389 if (n_value != 0) {
4390 if (info->verbose && sym_name != nullptr)
4391 outs() << sym_name;
4392 else
4393 outs() << format("0x%" PRIx64, n_value);
4394 if (pc.instanceMethods != 0)
4395 outs() << " + " << format("0x%" PRIx64, pc.instanceMethods);
4396 } else
4397 outs() << format("0x%" PRIx64, pc.instanceMethods);
4398 outs() << " (struct method_list_t *)\n";
4399 if (pc.instanceMethods + n_value != 0)
4400 print_method_list64_t(pc.instanceMethods + n_value, info, "\t");
4401
4402 outs() << "\t\t classMethods ";
4403 sym_name =
4404 get_symbol_64(offset + offsetof(struct protocol64_t, classMethods), S,
4405 info, n_value, pc.classMethods);
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 (pc.classMethods != 0)
4412 outs() << " + " << format("0x%" PRIx64, pc.classMethods);
4413 } else
4414 outs() << format("0x%" PRIx64, pc.classMethods);
4415 outs() << " (struct method_list_t *)\n";
4416 if (pc.classMethods + n_value != 0)
4417 print_method_list64_t(pc.classMethods + n_value, info, "\t");
4418
4419 outs() << "\t optionalInstanceMethods "
4420 << format("0x%" PRIx64, pc.optionalInstanceMethods) << "\n";
4421 outs() << "\t optionalClassMethods "
4422 << format("0x%" PRIx64, pc.optionalClassMethods) << "\n";
4423 outs() << "\t instanceProperties "
4424 << format("0x%" PRIx64, pc.instanceProperties) << "\n";
4425
4426 p += sizeof(uint64_t);
4427 offset += sizeof(uint64_t);
4428 }
4429}
4430
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004431static void print_protocol_list32_t(uint32_t p, struct DisassembleInfo *info) {
4432 struct protocol_list32_t pl;
4433 uint32_t q;
4434 struct protocol32_t pc;
4435 const char *r;
4436 uint32_t offset, xoffset, left, i;
4437 SectionRef S, xS;
4438 const char *name;
4439
4440 r = get_pointer_32(p, offset, left, S, info);
4441 if (r == nullptr)
4442 return;
4443 memset(&pl, '\0', sizeof(struct protocol_list32_t));
4444 if (left < sizeof(struct protocol_list32_t)) {
4445 memcpy(&pl, r, left);
4446 outs() << " (protocol_list_t entends past the end of the section)\n";
4447 } else
4448 memcpy(&pl, r, sizeof(struct protocol_list32_t));
4449 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4450 swapStruct(pl);
4451 outs() << " count " << pl.count << "\n";
4452
4453 p += sizeof(struct protocol_list32_t);
4454 offset += sizeof(struct protocol_list32_t);
4455 for (i = 0; i < pl.count; i++) {
4456 r = get_pointer_32(p, offset, left, S, info);
4457 if (r == nullptr)
4458 return;
4459 q = 0;
4460 if (left < sizeof(uint32_t)) {
4461 memcpy(&q, r, left);
4462 outs() << " (protocol_t * entends past the end of the section)\n";
4463 } else
4464 memcpy(&q, r, sizeof(uint32_t));
4465 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4466 sys::swapByteOrder(q);
4467 outs() << "\t\t list[" << i << "] " << format("0x%" PRIx32, q)
4468 << " (struct protocol_t *)\n";
4469 r = get_pointer_32(q, offset, left, S, info);
4470 if (r == nullptr)
4471 return;
4472 memset(&pc, '\0', sizeof(struct protocol32_t));
4473 if (left < sizeof(struct protocol32_t)) {
4474 memcpy(&pc, r, left);
4475 outs() << " (protocol_t entends past the end of the section)\n";
4476 } else
4477 memcpy(&pc, r, sizeof(struct protocol32_t));
4478 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4479 swapStruct(pc);
4480 outs() << "\t\t\t isa " << format("0x%" PRIx32, pc.isa) << "\n";
4481 outs() << "\t\t\t name " << format("0x%" PRIx32, pc.name);
4482 name = get_pointer_32(pc.name, xoffset, left, xS, info);
4483 if (name != nullptr)
4484 outs() << format(" %.*s", left, name);
4485 outs() << "\n";
4486 outs() << "\t\t\tprotocols " << format("0x%" PRIx32, pc.protocols) << "\n";
4487 outs() << "\t\t instanceMethods "
4488 << format("0x%" PRIx32, pc.instanceMethods)
4489 << " (struct method_list_t *)\n";
4490 if (pc.instanceMethods != 0)
4491 print_method_list32_t(pc.instanceMethods, info, "\t");
4492 outs() << "\t\t classMethods " << format("0x%" PRIx32, pc.classMethods)
4493 << " (struct method_list_t *)\n";
4494 if (pc.classMethods != 0)
4495 print_method_list32_t(pc.classMethods, info, "\t");
4496 outs() << "\t optionalInstanceMethods "
4497 << format("0x%" PRIx32, pc.optionalInstanceMethods) << "\n";
4498 outs() << "\t optionalClassMethods "
4499 << format("0x%" PRIx32, pc.optionalClassMethods) << "\n";
4500 outs() << "\t instanceProperties "
4501 << format("0x%" PRIx32, pc.instanceProperties) << "\n";
4502 p += sizeof(uint32_t);
4503 offset += sizeof(uint32_t);
4504 }
4505}
4506
Kevin Enderby846c0002015-04-16 17:19:59 +00004507static void print_indent(uint32_t indent) {
4508 for (uint32_t i = 0; i < indent;) {
4509 if (indent - i >= 8) {
4510 outs() << "\t";
4511 i += 8;
4512 } else {
4513 for (uint32_t j = i; j < indent; j++)
4514 outs() << " ";
4515 return;
4516 }
4517 }
4518}
4519
4520static bool print_method_description_list(uint32_t p, uint32_t indent,
4521 struct DisassembleInfo *info) {
4522 uint32_t offset, left, xleft;
4523 SectionRef S;
4524 struct objc_method_description_list_t mdl;
4525 struct objc_method_description_t md;
4526 const char *r, *list, *name;
4527 int32_t i;
4528
4529 r = get_pointer_32(p, offset, left, S, info, true);
4530 if (r == nullptr)
4531 return true;
4532
4533 outs() << "\n";
4534 if (left > sizeof(struct objc_method_description_list_t)) {
4535 memcpy(&mdl, r, sizeof(struct objc_method_description_list_t));
4536 } else {
4537 print_indent(indent);
4538 outs() << " objc_method_description_list extends past end of the section\n";
4539 memset(&mdl, '\0', sizeof(struct objc_method_description_list_t));
4540 memcpy(&mdl, r, left);
4541 }
4542 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4543 swapStruct(mdl);
4544
4545 print_indent(indent);
4546 outs() << " count " << mdl.count << "\n";
4547
4548 list = r + sizeof(struct objc_method_description_list_t);
4549 for (i = 0; i < mdl.count; i++) {
4550 if ((i + 1) * sizeof(struct objc_method_description_t) > left) {
4551 print_indent(indent);
4552 outs() << " remaining list entries extend past the of the section\n";
4553 break;
4554 }
4555 print_indent(indent);
4556 outs() << " list[" << i << "]\n";
4557 memcpy(&md, list + i * sizeof(struct objc_method_description_t),
4558 sizeof(struct objc_method_description_t));
4559 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4560 swapStruct(md);
4561
4562 print_indent(indent);
4563 outs() << " name " << format("0x%08" PRIx32, md.name);
4564 if (info->verbose) {
4565 name = get_pointer_32(md.name, offset, xleft, S, info, true);
4566 if (name != nullptr)
4567 outs() << format(" %.*s", xleft, name);
4568 else
4569 outs() << " (not in an __OBJC section)";
4570 }
4571 outs() << "\n";
4572
4573 print_indent(indent);
4574 outs() << " types " << format("0x%08" PRIx32, md.types);
4575 if (info->verbose) {
4576 name = get_pointer_32(md.types, offset, xleft, S, info, true);
4577 if (name != nullptr)
4578 outs() << format(" %.*s", xleft, name);
4579 else
4580 outs() << " (not in an __OBJC section)";
4581 }
4582 outs() << "\n";
4583 }
4584 return false;
4585}
4586
4587static bool print_protocol_list(uint32_t p, uint32_t indent,
4588 struct DisassembleInfo *info);
4589
4590static bool print_protocol(uint32_t p, uint32_t indent,
4591 struct DisassembleInfo *info) {
4592 uint32_t offset, left;
4593 SectionRef S;
4594 struct objc_protocol_t protocol;
4595 const char *r, *name;
4596
4597 r = get_pointer_32(p, offset, left, S, info, true);
4598 if (r == nullptr)
4599 return true;
4600
4601 outs() << "\n";
4602 if (left >= sizeof(struct objc_protocol_t)) {
4603 memcpy(&protocol, r, sizeof(struct objc_protocol_t));
4604 } else {
4605 print_indent(indent);
4606 outs() << " Protocol extends past end of the section\n";
4607 memset(&protocol, '\0', sizeof(struct objc_protocol_t));
4608 memcpy(&protocol, r, left);
4609 }
4610 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4611 swapStruct(protocol);
4612
4613 print_indent(indent);
4614 outs() << " isa " << format("0x%08" PRIx32, protocol.isa)
4615 << "\n";
4616
4617 print_indent(indent);
4618 outs() << " protocol_name "
4619 << format("0x%08" PRIx32, protocol.protocol_name);
4620 if (info->verbose) {
4621 name = get_pointer_32(protocol.protocol_name, offset, left, S, info, true);
4622 if (name != nullptr)
4623 outs() << format(" %.*s", left, name);
4624 else
4625 outs() << " (not in an __OBJC section)";
4626 }
4627 outs() << "\n";
4628
4629 print_indent(indent);
4630 outs() << " protocol_list "
4631 << format("0x%08" PRIx32, protocol.protocol_list);
4632 if (print_protocol_list(protocol.protocol_list, indent + 4, info))
4633 outs() << " (not in an __OBJC section)\n";
4634
4635 print_indent(indent);
4636 outs() << " instance_methods "
4637 << format("0x%08" PRIx32, protocol.instance_methods);
4638 if (print_method_description_list(protocol.instance_methods, indent, info))
4639 outs() << " (not in an __OBJC section)\n";
4640
4641 print_indent(indent);
4642 outs() << " class_methods "
4643 << format("0x%08" PRIx32, protocol.class_methods);
4644 if (print_method_description_list(protocol.class_methods, indent, info))
4645 outs() << " (not in an __OBJC section)\n";
4646
4647 return false;
4648}
4649
4650static bool print_protocol_list(uint32_t p, uint32_t indent,
4651 struct DisassembleInfo *info) {
4652 uint32_t offset, left, l;
4653 SectionRef S;
4654 struct objc_protocol_list_t protocol_list;
4655 const char *r, *list;
4656 int32_t i;
4657
4658 r = get_pointer_32(p, offset, left, S, info, true);
4659 if (r == nullptr)
4660 return true;
4661
4662 outs() << "\n";
4663 if (left > sizeof(struct objc_protocol_list_t)) {
4664 memcpy(&protocol_list, r, sizeof(struct objc_protocol_list_t));
4665 } else {
4666 outs() << "\t\t objc_protocol_list_t extends past end of the section\n";
4667 memset(&protocol_list, '\0', sizeof(struct objc_protocol_list_t));
4668 memcpy(&protocol_list, r, left);
4669 }
4670 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4671 swapStruct(protocol_list);
4672
4673 print_indent(indent);
4674 outs() << " next " << format("0x%08" PRIx32, protocol_list.next)
4675 << "\n";
4676 print_indent(indent);
4677 outs() << " count " << protocol_list.count << "\n";
4678
4679 list = r + sizeof(struct objc_protocol_list_t);
4680 for (i = 0; i < protocol_list.count; i++) {
4681 if ((i + 1) * sizeof(uint32_t) > left) {
4682 outs() << "\t\t remaining list entries extend past the of the section\n";
4683 break;
4684 }
4685 memcpy(&l, list + i * sizeof(uint32_t), sizeof(uint32_t));
4686 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4687 sys::swapByteOrder(l);
4688
4689 print_indent(indent);
4690 outs() << " list[" << i << "] " << format("0x%08" PRIx32, l);
4691 if (print_protocol(l, indent, info))
4692 outs() << "(not in an __OBJC section)\n";
4693 }
4694 return false;
4695}
4696
Kevin Enderby0fc11822015-04-01 20:57:01 +00004697static void print_ivar_list64_t(uint64_t p, struct DisassembleInfo *info) {
4698 struct ivar_list64_t il;
4699 struct ivar64_t i;
4700 const char *r;
4701 uint32_t offset, xoffset, left, j;
4702 SectionRef S, xS;
4703 const char *name, *sym_name, *ivar_offset_p;
4704 uint64_t ivar_offset, n_value;
4705
4706 r = get_pointer_64(p, offset, left, S, info);
4707 if (r == nullptr)
4708 return;
4709 memset(&il, '\0', sizeof(struct ivar_list64_t));
4710 if (left < sizeof(struct ivar_list64_t)) {
4711 memcpy(&il, r, left);
4712 outs() << " (ivar_list_t entends past the end of the section)\n";
4713 } else
4714 memcpy(&il, r, sizeof(struct ivar_list64_t));
4715 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4716 swapStruct(il);
4717 outs() << " entsize " << il.entsize << "\n";
4718 outs() << " count " << il.count << "\n";
4719
4720 p += sizeof(struct ivar_list64_t);
4721 offset += sizeof(struct ivar_list64_t);
4722 for (j = 0; j < il.count; j++) {
4723 r = get_pointer_64(p, offset, left, S, info);
4724 if (r == nullptr)
4725 return;
4726 memset(&i, '\0', sizeof(struct ivar64_t));
4727 if (left < sizeof(struct ivar64_t)) {
4728 memcpy(&i, r, left);
4729 outs() << " (ivar_t entends past the end of the section)\n";
4730 } else
4731 memcpy(&i, r, sizeof(struct ivar64_t));
4732 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4733 swapStruct(i);
4734
4735 outs() << "\t\t\t offset ";
4736 sym_name = get_symbol_64(offset + offsetof(struct ivar64_t, offset), S,
4737 info, n_value, i.offset);
4738 if (n_value != 0) {
4739 if (info->verbose && sym_name != nullptr)
4740 outs() << sym_name;
4741 else
4742 outs() << format("0x%" PRIx64, n_value);
4743 if (i.offset != 0)
4744 outs() << " + " << format("0x%" PRIx64, i.offset);
4745 } else
4746 outs() << format("0x%" PRIx64, i.offset);
4747 ivar_offset_p = get_pointer_64(i.offset + n_value, xoffset, left, xS, info);
4748 if (ivar_offset_p != nullptr && left >= sizeof(*ivar_offset_p)) {
4749 memcpy(&ivar_offset, ivar_offset_p, sizeof(ivar_offset));
4750 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4751 sys::swapByteOrder(ivar_offset);
4752 outs() << " " << ivar_offset << "\n";
4753 } else
4754 outs() << "\n";
4755
4756 outs() << "\t\t\t name ";
4757 sym_name = get_symbol_64(offset + offsetof(struct ivar64_t, name), S, info,
4758 n_value, i.name);
4759 if (n_value != 0) {
4760 if (info->verbose && sym_name != nullptr)
4761 outs() << sym_name;
4762 else
4763 outs() << format("0x%" PRIx64, n_value);
4764 if (i.name != 0)
4765 outs() << " + " << format("0x%" PRIx64, i.name);
4766 } else
4767 outs() << format("0x%" PRIx64, i.name);
4768 name = get_pointer_64(i.name + n_value, xoffset, left, xS, info);
4769 if (name != nullptr)
4770 outs() << format(" %.*s", left, name);
4771 outs() << "\n";
4772
4773 outs() << "\t\t\t type ";
4774 sym_name = get_symbol_64(offset + offsetof(struct ivar64_t, type), S, info,
4775 n_value, i.name);
4776 name = get_pointer_64(i.type + n_value, xoffset, left, xS, info);
4777 if (n_value != 0) {
4778 if (info->verbose && sym_name != nullptr)
4779 outs() << sym_name;
4780 else
4781 outs() << format("0x%" PRIx64, n_value);
4782 if (i.type != 0)
4783 outs() << " + " << format("0x%" PRIx64, i.type);
4784 } else
4785 outs() << format("0x%" PRIx64, i.type);
4786 if (name != nullptr)
4787 outs() << format(" %.*s", left, name);
4788 outs() << "\n";
4789
4790 outs() << "\t\t\talignment " << i.alignment << "\n";
4791 outs() << "\t\t\t size " << i.size << "\n";
4792
4793 p += sizeof(struct ivar64_t);
4794 offset += sizeof(struct ivar64_t);
4795 }
4796}
4797
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004798static void print_ivar_list32_t(uint32_t p, struct DisassembleInfo *info) {
4799 struct ivar_list32_t il;
4800 struct ivar32_t i;
4801 const char *r;
4802 uint32_t offset, xoffset, left, j;
4803 SectionRef S, xS;
4804 const char *name, *ivar_offset_p;
4805 uint32_t ivar_offset;
4806
4807 r = get_pointer_32(p, offset, left, S, info);
4808 if (r == nullptr)
4809 return;
4810 memset(&il, '\0', sizeof(struct ivar_list32_t));
4811 if (left < sizeof(struct ivar_list32_t)) {
4812 memcpy(&il, r, left);
4813 outs() << " (ivar_list_t entends past the end of the section)\n";
4814 } else
4815 memcpy(&il, r, sizeof(struct ivar_list32_t));
4816 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4817 swapStruct(il);
4818 outs() << " entsize " << il.entsize << "\n";
4819 outs() << " count " << il.count << "\n";
4820
4821 p += sizeof(struct ivar_list32_t);
4822 offset += sizeof(struct ivar_list32_t);
4823 for (j = 0; j < il.count; j++) {
4824 r = get_pointer_32(p, offset, left, S, info);
4825 if (r == nullptr)
4826 return;
4827 memset(&i, '\0', sizeof(struct ivar32_t));
4828 if (left < sizeof(struct ivar32_t)) {
4829 memcpy(&i, r, left);
4830 outs() << " (ivar_t entends past the end of the section)\n";
4831 } else
4832 memcpy(&i, r, sizeof(struct ivar32_t));
4833 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4834 swapStruct(i);
4835
4836 outs() << "\t\t\t offset " << format("0x%" PRIx32, i.offset);
4837 ivar_offset_p = get_pointer_32(i.offset, xoffset, left, xS, info);
4838 if (ivar_offset_p != nullptr && left >= sizeof(*ivar_offset_p)) {
4839 memcpy(&ivar_offset, ivar_offset_p, sizeof(ivar_offset));
4840 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4841 sys::swapByteOrder(ivar_offset);
4842 outs() << " " << ivar_offset << "\n";
4843 } else
4844 outs() << "\n";
4845
4846 outs() << "\t\t\t name " << format("0x%" PRIx32, i.name);
4847 name = get_pointer_32(i.name, xoffset, left, xS, info);
4848 if (name != nullptr)
4849 outs() << format(" %.*s", left, name);
4850 outs() << "\n";
4851
4852 outs() << "\t\t\t type " << format("0x%" PRIx32, i.type);
4853 name = get_pointer_32(i.type, xoffset, left, xS, info);
4854 if (name != nullptr)
4855 outs() << format(" %.*s", left, name);
4856 outs() << "\n";
4857
4858 outs() << "\t\t\talignment " << i.alignment << "\n";
4859 outs() << "\t\t\t size " << i.size << "\n";
4860
4861 p += sizeof(struct ivar32_t);
4862 offset += sizeof(struct ivar32_t);
4863 }
4864}
4865
Kevin Enderby0fc11822015-04-01 20:57:01 +00004866static void print_objc_property_list64(uint64_t p,
4867 struct DisassembleInfo *info) {
4868 struct objc_property_list64 opl;
4869 struct objc_property64 op;
4870 const char *r;
4871 uint32_t offset, xoffset, left, j;
4872 SectionRef S, xS;
4873 const char *name, *sym_name;
4874 uint64_t n_value;
4875
4876 r = get_pointer_64(p, offset, left, S, info);
4877 if (r == nullptr)
4878 return;
4879 memset(&opl, '\0', sizeof(struct objc_property_list64));
4880 if (left < sizeof(struct objc_property_list64)) {
4881 memcpy(&opl, r, left);
4882 outs() << " (objc_property_list entends past the end of the section)\n";
4883 } else
4884 memcpy(&opl, r, sizeof(struct objc_property_list64));
4885 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4886 swapStruct(opl);
4887 outs() << " entsize " << opl.entsize << "\n";
4888 outs() << " count " << opl.count << "\n";
4889
4890 p += sizeof(struct objc_property_list64);
4891 offset += sizeof(struct objc_property_list64);
4892 for (j = 0; j < opl.count; j++) {
4893 r = get_pointer_64(p, offset, left, S, info);
4894 if (r == nullptr)
4895 return;
4896 memset(&op, '\0', sizeof(struct objc_property64));
4897 if (left < sizeof(struct objc_property64)) {
4898 memcpy(&op, r, left);
4899 outs() << " (objc_property entends past the end of the section)\n";
4900 } else
4901 memcpy(&op, r, sizeof(struct objc_property64));
4902 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4903 swapStruct(op);
4904
4905 outs() << "\t\t\t name ";
4906 sym_name = get_symbol_64(offset + offsetof(struct objc_property64, name), S,
4907 info, n_value, op.name);
4908 if (n_value != 0) {
4909 if (info->verbose && sym_name != nullptr)
4910 outs() << sym_name;
4911 else
4912 outs() << format("0x%" PRIx64, n_value);
4913 if (op.name != 0)
4914 outs() << " + " << format("0x%" PRIx64, op.name);
4915 } else
4916 outs() << format("0x%" PRIx64, op.name);
4917 name = get_pointer_64(op.name + n_value, xoffset, left, xS, info);
4918 if (name != nullptr)
4919 outs() << format(" %.*s", left, name);
4920 outs() << "\n";
4921
4922 outs() << "\t\t\tattributes ";
4923 sym_name =
4924 get_symbol_64(offset + offsetof(struct objc_property64, attributes), S,
4925 info, n_value, op.attributes);
4926 if (n_value != 0) {
4927 if (info->verbose && sym_name != nullptr)
4928 outs() << sym_name;
4929 else
4930 outs() << format("0x%" PRIx64, n_value);
4931 if (op.attributes != 0)
4932 outs() << " + " << format("0x%" PRIx64, op.attributes);
4933 } else
4934 outs() << format("0x%" PRIx64, op.attributes);
4935 name = get_pointer_64(op.attributes + n_value, xoffset, left, xS, info);
4936 if (name != nullptr)
4937 outs() << format(" %.*s", left, name);
4938 outs() << "\n";
4939
4940 p += sizeof(struct objc_property64);
4941 offset += sizeof(struct objc_property64);
4942 }
4943}
4944
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00004945static void print_objc_property_list32(uint32_t p,
4946 struct DisassembleInfo *info) {
4947 struct objc_property_list32 opl;
4948 struct objc_property32 op;
4949 const char *r;
4950 uint32_t offset, xoffset, left, j;
4951 SectionRef S, xS;
4952 const char *name;
4953
4954 r = get_pointer_32(p, offset, left, S, info);
4955 if (r == nullptr)
4956 return;
4957 memset(&opl, '\0', sizeof(struct objc_property_list32));
4958 if (left < sizeof(struct objc_property_list32)) {
4959 memcpy(&opl, r, left);
4960 outs() << " (objc_property_list entends past the end of the section)\n";
4961 } else
4962 memcpy(&opl, r, sizeof(struct objc_property_list32));
4963 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4964 swapStruct(opl);
4965 outs() << " entsize " << opl.entsize << "\n";
4966 outs() << " count " << opl.count << "\n";
4967
4968 p += sizeof(struct objc_property_list32);
4969 offset += sizeof(struct objc_property_list32);
4970 for (j = 0; j < opl.count; j++) {
4971 r = get_pointer_32(p, offset, left, S, info);
4972 if (r == nullptr)
4973 return;
4974 memset(&op, '\0', sizeof(struct objc_property32));
4975 if (left < sizeof(struct objc_property32)) {
4976 memcpy(&op, r, left);
4977 outs() << " (objc_property entends past the end of the section)\n";
4978 } else
4979 memcpy(&op, r, sizeof(struct objc_property32));
4980 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4981 swapStruct(op);
4982
4983 outs() << "\t\t\t name " << format("0x%" PRIx32, op.name);
4984 name = get_pointer_32(op.name, xoffset, left, xS, info);
4985 if (name != nullptr)
4986 outs() << format(" %.*s", left, name);
4987 outs() << "\n";
4988
4989 outs() << "\t\t\tattributes " << format("0x%" PRIx32, op.attributes);
4990 name = get_pointer_32(op.attributes, xoffset, left, xS, info);
4991 if (name != nullptr)
4992 outs() << format(" %.*s", left, name);
4993 outs() << "\n";
4994
4995 p += sizeof(struct objc_property32);
4996 offset += sizeof(struct objc_property32);
4997 }
4998}
4999
Richard Smith81ff44d2015-10-09 22:09:56 +00005000static bool print_class_ro64_t(uint64_t p, struct DisassembleInfo *info,
Kevin Enderby0fc11822015-04-01 20:57:01 +00005001 bool &is_meta_class) {
5002 struct class_ro64_t cro;
5003 const char *r;
5004 uint32_t offset, xoffset, left;
5005 SectionRef S, xS;
5006 const char *name, *sym_name;
5007 uint64_t n_value;
5008
5009 r = get_pointer_64(p, offset, left, S, info);
5010 if (r == nullptr || left < sizeof(struct class_ro64_t))
Richard Smith81ff44d2015-10-09 22:09:56 +00005011 return false;
Chandler Carruth33e58902016-11-04 07:10:24 +00005012 memcpy(&cro, r, sizeof(struct class_ro64_t));
Kevin Enderby0fc11822015-04-01 20:57:01 +00005013 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5014 swapStruct(cro);
5015 outs() << " flags " << format("0x%" PRIx32, cro.flags);
5016 if (cro.flags & RO_META)
5017 outs() << " RO_META";
5018 if (cro.flags & RO_ROOT)
5019 outs() << " RO_ROOT";
5020 if (cro.flags & RO_HAS_CXX_STRUCTORS)
5021 outs() << " RO_HAS_CXX_STRUCTORS";
5022 outs() << "\n";
5023 outs() << " instanceStart " << cro.instanceStart << "\n";
5024 outs() << " instanceSize " << cro.instanceSize << "\n";
5025 outs() << " reserved " << format("0x%" PRIx32, cro.reserved)
5026 << "\n";
5027 outs() << " ivarLayout " << format("0x%" PRIx64, cro.ivarLayout)
5028 << "\n";
5029 print_layout_map64(cro.ivarLayout, info);
5030
5031 outs() << " name ";
5032 sym_name = get_symbol_64(offset + offsetof(struct class_ro64_t, name), S,
5033 info, n_value, cro.name);
5034 if (n_value != 0) {
5035 if (info->verbose && sym_name != nullptr)
5036 outs() << sym_name;
5037 else
5038 outs() << format("0x%" PRIx64, n_value);
5039 if (cro.name != 0)
5040 outs() << " + " << format("0x%" PRIx64, cro.name);
5041 } else
5042 outs() << format("0x%" PRIx64, cro.name);
5043 name = get_pointer_64(cro.name + n_value, xoffset, left, xS, info);
5044 if (name != nullptr)
5045 outs() << format(" %.*s", left, name);
5046 outs() << "\n";
5047
5048 outs() << " baseMethods ";
5049 sym_name = get_symbol_64(offset + offsetof(struct class_ro64_t, baseMethods),
5050 S, info, n_value, cro.baseMethods);
5051 if (n_value != 0) {
5052 if (info->verbose && sym_name != nullptr)
5053 outs() << sym_name;
5054 else
5055 outs() << format("0x%" PRIx64, n_value);
5056 if (cro.baseMethods != 0)
5057 outs() << " + " << format("0x%" PRIx64, cro.baseMethods);
5058 } else
5059 outs() << format("0x%" PRIx64, cro.baseMethods);
5060 outs() << " (struct method_list_t *)\n";
5061 if (cro.baseMethods + n_value != 0)
5062 print_method_list64_t(cro.baseMethods + n_value, info, "");
5063
5064 outs() << " baseProtocols ";
5065 sym_name =
5066 get_symbol_64(offset + offsetof(struct class_ro64_t, baseProtocols), S,
5067 info, n_value, cro.baseProtocols);
5068 if (n_value != 0) {
5069 if (info->verbose && sym_name != nullptr)
5070 outs() << sym_name;
5071 else
5072 outs() << format("0x%" PRIx64, n_value);
5073 if (cro.baseProtocols != 0)
5074 outs() << " + " << format("0x%" PRIx64, cro.baseProtocols);
5075 } else
5076 outs() << format("0x%" PRIx64, cro.baseProtocols);
5077 outs() << "\n";
5078 if (cro.baseProtocols + n_value != 0)
5079 print_protocol_list64_t(cro.baseProtocols + n_value, info);
5080
5081 outs() << " ivars ";
5082 sym_name = get_symbol_64(offset + offsetof(struct class_ro64_t, ivars), S,
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005083 info, n_value, cro.ivars);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005084 if (n_value != 0) {
5085 if (info->verbose && sym_name != nullptr)
5086 outs() << sym_name;
5087 else
5088 outs() << format("0x%" PRIx64, n_value);
5089 if (cro.ivars != 0)
5090 outs() << " + " << format("0x%" PRIx64, cro.ivars);
5091 } else
5092 outs() << format("0x%" PRIx64, cro.ivars);
5093 outs() << "\n";
5094 if (cro.ivars + n_value != 0)
5095 print_ivar_list64_t(cro.ivars + n_value, info);
5096
5097 outs() << " weakIvarLayout ";
5098 sym_name =
5099 get_symbol_64(offset + offsetof(struct class_ro64_t, weakIvarLayout), S,
5100 info, n_value, cro.weakIvarLayout);
5101 if (n_value != 0) {
5102 if (info->verbose && sym_name != nullptr)
5103 outs() << sym_name;
5104 else
5105 outs() << format("0x%" PRIx64, n_value);
5106 if (cro.weakIvarLayout != 0)
5107 outs() << " + " << format("0x%" PRIx64, cro.weakIvarLayout);
5108 } else
5109 outs() << format("0x%" PRIx64, cro.weakIvarLayout);
5110 outs() << "\n";
5111 print_layout_map64(cro.weakIvarLayout + n_value, info);
5112
5113 outs() << " baseProperties ";
5114 sym_name =
5115 get_symbol_64(offset + offsetof(struct class_ro64_t, baseProperties), S,
5116 info, n_value, cro.baseProperties);
5117 if (n_value != 0) {
5118 if (info->verbose && sym_name != nullptr)
5119 outs() << sym_name;
5120 else
5121 outs() << format("0x%" PRIx64, n_value);
5122 if (cro.baseProperties != 0)
5123 outs() << " + " << format("0x%" PRIx64, cro.baseProperties);
5124 } else
5125 outs() << format("0x%" PRIx64, cro.baseProperties);
5126 outs() << "\n";
5127 if (cro.baseProperties + n_value != 0)
5128 print_objc_property_list64(cro.baseProperties + n_value, info);
5129
Rafael Espindolab9091322015-10-24 23:19:10 +00005130 is_meta_class = (cro.flags & RO_META) != 0;
Richard Smith81ff44d2015-10-09 22:09:56 +00005131 return true;
Kevin Enderby0fc11822015-04-01 20:57:01 +00005132}
5133
Richard Smith81ff44d2015-10-09 22:09:56 +00005134static bool print_class_ro32_t(uint32_t p, struct DisassembleInfo *info,
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005135 bool &is_meta_class) {
5136 struct class_ro32_t cro;
5137 const char *r;
5138 uint32_t offset, xoffset, left;
5139 SectionRef S, xS;
5140 const char *name;
5141
5142 r = get_pointer_32(p, offset, left, S, info);
5143 if (r == nullptr)
Richard Smith81ff44d2015-10-09 22:09:56 +00005144 return false;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005145 memset(&cro, '\0', sizeof(struct class_ro32_t));
5146 if (left < sizeof(struct class_ro32_t)) {
5147 memcpy(&cro, r, left);
5148 outs() << " (class_ro_t entends past the end of the section)\n";
5149 } else
5150 memcpy(&cro, r, sizeof(struct class_ro32_t));
5151 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5152 swapStruct(cro);
5153 outs() << " flags " << format("0x%" PRIx32, cro.flags);
5154 if (cro.flags & RO_META)
5155 outs() << " RO_META";
5156 if (cro.flags & RO_ROOT)
5157 outs() << " RO_ROOT";
5158 if (cro.flags & RO_HAS_CXX_STRUCTORS)
5159 outs() << " RO_HAS_CXX_STRUCTORS";
5160 outs() << "\n";
5161 outs() << " instanceStart " << cro.instanceStart << "\n";
5162 outs() << " instanceSize " << cro.instanceSize << "\n";
5163 outs() << " ivarLayout " << format("0x%" PRIx32, cro.ivarLayout)
5164 << "\n";
5165 print_layout_map32(cro.ivarLayout, info);
5166
5167 outs() << " name " << format("0x%" PRIx32, cro.name);
5168 name = get_pointer_32(cro.name, xoffset, left, xS, info);
5169 if (name != nullptr)
5170 outs() << format(" %.*s", left, name);
5171 outs() << "\n";
5172
5173 outs() << " baseMethods "
5174 << format("0x%" PRIx32, cro.baseMethods)
5175 << " (struct method_list_t *)\n";
5176 if (cro.baseMethods != 0)
5177 print_method_list32_t(cro.baseMethods, info, "");
5178
5179 outs() << " baseProtocols "
5180 << format("0x%" PRIx32, cro.baseProtocols) << "\n";
5181 if (cro.baseProtocols != 0)
5182 print_protocol_list32_t(cro.baseProtocols, info);
5183 outs() << " ivars " << format("0x%" PRIx32, cro.ivars)
5184 << "\n";
5185 if (cro.ivars != 0)
5186 print_ivar_list32_t(cro.ivars, info);
5187 outs() << " weakIvarLayout "
5188 << format("0x%" PRIx32, cro.weakIvarLayout) << "\n";
5189 print_layout_map32(cro.weakIvarLayout, info);
5190 outs() << " baseProperties "
5191 << format("0x%" PRIx32, cro.baseProperties) << "\n";
5192 if (cro.baseProperties != 0)
5193 print_objc_property_list32(cro.baseProperties, info);
Rafael Espindolab9091322015-10-24 23:19:10 +00005194 is_meta_class = (cro.flags & RO_META) != 0;
Richard Smith81ff44d2015-10-09 22:09:56 +00005195 return true;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005196}
5197
Kevin Enderby0fc11822015-04-01 20:57:01 +00005198static void print_class64_t(uint64_t p, struct DisassembleInfo *info) {
5199 struct class64_t c;
5200 const char *r;
5201 uint32_t offset, left;
5202 SectionRef S;
5203 const char *name;
5204 uint64_t isa_n_value, n_value;
5205
5206 r = get_pointer_64(p, offset, left, S, info);
5207 if (r == nullptr || left < sizeof(struct class64_t))
5208 return;
Chandler Carruth33e58902016-11-04 07:10:24 +00005209 memcpy(&c, r, sizeof(struct class64_t));
Kevin Enderby0fc11822015-04-01 20:57:01 +00005210 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5211 swapStruct(c);
5212
5213 outs() << " isa " << format("0x%" PRIx64, c.isa);
5214 name = get_symbol_64(offset + offsetof(struct class64_t, isa), S, info,
5215 isa_n_value, c.isa);
5216 if (name != nullptr)
5217 outs() << " " << name;
5218 outs() << "\n";
5219
5220 outs() << " superclass " << format("0x%" PRIx64, c.superclass);
5221 name = get_symbol_64(offset + offsetof(struct class64_t, superclass), S, info,
5222 n_value, c.superclass);
5223 if (name != nullptr)
5224 outs() << " " << name;
Kevin Enderby1ce38582017-06-20 22:55:11 +00005225 else {
5226 name = get_dyld_bind_info_symbolname(S.getAddress() +
5227 offset + offsetof(struct class64_t, superclass), info);
5228 if (name != nullptr)
5229 outs() << " " << name;
5230 }
Kevin Enderby0fc11822015-04-01 20:57:01 +00005231 outs() << "\n";
5232
5233 outs() << " cache " << format("0x%" PRIx64, c.cache);
5234 name = get_symbol_64(offset + offsetof(struct class64_t, cache), S, info,
5235 n_value, c.cache);
5236 if (name != nullptr)
5237 outs() << " " << name;
5238 outs() << "\n";
5239
5240 outs() << " vtable " << format("0x%" PRIx64, c.vtable);
5241 name = get_symbol_64(offset + offsetof(struct class64_t, vtable), S, info,
5242 n_value, c.vtable);
5243 if (name != nullptr)
5244 outs() << " " << name;
5245 outs() << "\n";
5246
5247 name = get_symbol_64(offset + offsetof(struct class64_t, data), S, info,
5248 n_value, c.data);
5249 outs() << " data ";
5250 if (n_value != 0) {
5251 if (info->verbose && name != nullptr)
5252 outs() << name;
5253 else
5254 outs() << format("0x%" PRIx64, n_value);
5255 if (c.data != 0)
5256 outs() << " + " << format("0x%" PRIx64, c.data);
5257 } else
5258 outs() << format("0x%" PRIx64, c.data);
5259 outs() << " (struct class_ro_t *)";
5260
5261 // This is a Swift class if some of the low bits of the pointer are set.
5262 if ((c.data + n_value) & 0x7)
5263 outs() << " Swift class";
5264 outs() << "\n";
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005265 bool is_meta_class;
Richard Smith81ff44d2015-10-09 22:09:56 +00005266 if (!print_class_ro64_t((c.data + n_value) & ~0x7, info, is_meta_class))
5267 return;
Kevin Enderby0fc11822015-04-01 20:57:01 +00005268
Kevin Enderbyaac75382015-10-08 16:56:35 +00005269 if (!is_meta_class &&
5270 c.isa + isa_n_value != p &&
5271 c.isa + isa_n_value != 0 &&
5272 info->depth < 100) {
5273 info->depth++;
5274 outs() << "Meta Class\n";
5275 print_class64_t(c.isa + isa_n_value, info);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005276 }
5277}
5278
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005279static void print_class32_t(uint32_t p, struct DisassembleInfo *info) {
5280 struct class32_t c;
5281 const char *r;
5282 uint32_t offset, left;
5283 SectionRef S;
5284 const char *name;
5285
5286 r = get_pointer_32(p, offset, left, S, info);
5287 if (r == nullptr)
5288 return;
5289 memset(&c, '\0', sizeof(struct class32_t));
5290 if (left < sizeof(struct class32_t)) {
5291 memcpy(&c, r, left);
5292 outs() << " (class_t entends past the end of the section)\n";
5293 } else
5294 memcpy(&c, r, sizeof(struct class32_t));
5295 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5296 swapStruct(c);
5297
5298 outs() << " isa " << format("0x%" PRIx32, c.isa);
5299 name =
5300 get_symbol_32(offset + offsetof(struct class32_t, isa), S, info, c.isa);
5301 if (name != nullptr)
5302 outs() << " " << name;
5303 outs() << "\n";
5304
5305 outs() << " superclass " << format("0x%" PRIx32, c.superclass);
5306 name = get_symbol_32(offset + offsetof(struct class32_t, superclass), S, info,
5307 c.superclass);
5308 if (name != nullptr)
5309 outs() << " " << name;
5310 outs() << "\n";
5311
5312 outs() << " cache " << format("0x%" PRIx32, c.cache);
5313 name = get_symbol_32(offset + offsetof(struct class32_t, cache), S, info,
5314 c.cache);
5315 if (name != nullptr)
5316 outs() << " " << name;
5317 outs() << "\n";
5318
5319 outs() << " vtable " << format("0x%" PRIx32, c.vtable);
5320 name = get_symbol_32(offset + offsetof(struct class32_t, vtable), S, info,
5321 c.vtable);
5322 if (name != nullptr)
5323 outs() << " " << name;
5324 outs() << "\n";
5325
5326 name =
5327 get_symbol_32(offset + offsetof(struct class32_t, data), S, info, c.data);
5328 outs() << " data " << format("0x%" PRIx32, c.data)
5329 << " (struct class_ro_t *)";
5330
5331 // This is a Swift class if some of the low bits of the pointer are set.
5332 if (c.data & 0x3)
5333 outs() << " Swift class";
5334 outs() << "\n";
5335 bool is_meta_class;
Richard Smith81ff44d2015-10-09 22:09:56 +00005336 if (!print_class_ro32_t(c.data & ~0x3, info, is_meta_class))
5337 return;
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005338
Hans Wennborgcc9deb42015-09-29 18:02:48 +00005339 if (!is_meta_class) {
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005340 outs() << "Meta Class\n";
5341 print_class32_t(c.isa, info);
5342 }
5343}
5344
Kevin Enderby846c0002015-04-16 17:19:59 +00005345static void print_objc_class_t(struct objc_class_t *objc_class,
5346 struct DisassembleInfo *info) {
5347 uint32_t offset, left, xleft;
5348 const char *name, *p, *ivar_list;
5349 SectionRef S;
5350 int32_t i;
5351 struct objc_ivar_list_t objc_ivar_list;
5352 struct objc_ivar_t ivar;
5353
5354 outs() << "\t\t isa " << format("0x%08" PRIx32, objc_class->isa);
5355 if (info->verbose && CLS_GETINFO(objc_class, CLS_META)) {
5356 name = get_pointer_32(objc_class->isa, offset, left, S, info, true);
5357 if (name != nullptr)
5358 outs() << format(" %.*s", left, name);
5359 else
5360 outs() << " (not in an __OBJC section)";
5361 }
5362 outs() << "\n";
5363
5364 outs() << "\t super_class "
5365 << format("0x%08" PRIx32, objc_class->super_class);
5366 if (info->verbose) {
5367 name = get_pointer_32(objc_class->super_class, offset, left, S, info, true);
5368 if (name != nullptr)
5369 outs() << format(" %.*s", left, name);
5370 else
5371 outs() << " (not in an __OBJC section)";
5372 }
5373 outs() << "\n";
5374
5375 outs() << "\t\t name " << format("0x%08" PRIx32, objc_class->name);
5376 if (info->verbose) {
5377 name = get_pointer_32(objc_class->name, offset, left, S, info, true);
5378 if (name != nullptr)
5379 outs() << format(" %.*s", left, name);
5380 else
5381 outs() << " (not in an __OBJC section)";
5382 }
5383 outs() << "\n";
5384
5385 outs() << "\t\t version " << format("0x%08" PRIx32, objc_class->version)
5386 << "\n";
5387
5388 outs() << "\t\t info " << format("0x%08" PRIx32, objc_class->info);
5389 if (info->verbose) {
5390 if (CLS_GETINFO(objc_class, CLS_CLASS))
5391 outs() << " CLS_CLASS";
5392 else if (CLS_GETINFO(objc_class, CLS_META))
5393 outs() << " CLS_META";
5394 }
5395 outs() << "\n";
5396
5397 outs() << "\t instance_size "
5398 << format("0x%08" PRIx32, objc_class->instance_size) << "\n";
5399
5400 p = get_pointer_32(objc_class->ivars, offset, left, S, info, true);
5401 outs() << "\t\t ivars " << format("0x%08" PRIx32, objc_class->ivars);
5402 if (p != nullptr) {
5403 if (left > sizeof(struct objc_ivar_list_t)) {
5404 outs() << "\n";
5405 memcpy(&objc_ivar_list, p, sizeof(struct objc_ivar_list_t));
5406 } else {
5407 outs() << " (entends past the end of the section)\n";
5408 memset(&objc_ivar_list, '\0', sizeof(struct objc_ivar_list_t));
5409 memcpy(&objc_ivar_list, p, left);
5410 }
5411 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5412 swapStruct(objc_ivar_list);
5413 outs() << "\t\t ivar_count " << objc_ivar_list.ivar_count << "\n";
5414 ivar_list = p + sizeof(struct objc_ivar_list_t);
5415 for (i = 0; i < objc_ivar_list.ivar_count; i++) {
5416 if ((i + 1) * sizeof(struct objc_ivar_t) > left) {
5417 outs() << "\t\t remaining ivar's extend past the of the section\n";
5418 break;
5419 }
5420 memcpy(&ivar, ivar_list + i * sizeof(struct objc_ivar_t),
5421 sizeof(struct objc_ivar_t));
5422 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5423 swapStruct(ivar);
5424
5425 outs() << "\t\t\tivar_name " << format("0x%08" PRIx32, ivar.ivar_name);
5426 if (info->verbose) {
5427 name = get_pointer_32(ivar.ivar_name, offset, xleft, S, info, true);
5428 if (name != nullptr)
5429 outs() << format(" %.*s", xleft, name);
5430 else
5431 outs() << " (not in an __OBJC section)";
5432 }
5433 outs() << "\n";
5434
5435 outs() << "\t\t\tivar_type " << format("0x%08" PRIx32, ivar.ivar_type);
5436 if (info->verbose) {
5437 name = get_pointer_32(ivar.ivar_type, offset, xleft, S, info, true);
5438 if (name != nullptr)
5439 outs() << format(" %.*s", xleft, name);
5440 else
5441 outs() << " (not in an __OBJC section)";
5442 }
5443 outs() << "\n";
5444
5445 outs() << "\t\t ivar_offset "
5446 << format("0x%08" PRIx32, ivar.ivar_offset) << "\n";
5447 }
5448 } else {
5449 outs() << " (not in an __OBJC section)\n";
5450 }
5451
5452 outs() << "\t\t methods " << format("0x%08" PRIx32, objc_class->methodLists);
5453 if (print_method_list(objc_class->methodLists, info))
5454 outs() << " (not in an __OBJC section)\n";
5455
5456 outs() << "\t\t cache " << format("0x%08" PRIx32, objc_class->cache)
5457 << "\n";
5458
5459 outs() << "\t\tprotocols " << format("0x%08" PRIx32, objc_class->protocols);
5460 if (print_protocol_list(objc_class->protocols, 16, info))
5461 outs() << " (not in an __OBJC section)\n";
5462}
5463
5464static void print_objc_objc_category_t(struct objc_category_t *objc_category,
5465 struct DisassembleInfo *info) {
5466 uint32_t offset, left;
5467 const char *name;
5468 SectionRef S;
5469
5470 outs() << "\t category name "
5471 << format("0x%08" PRIx32, objc_category->category_name);
5472 if (info->verbose) {
5473 name = get_pointer_32(objc_category->category_name, offset, left, S, info,
5474 true);
5475 if (name != nullptr)
5476 outs() << format(" %.*s", left, name);
5477 else
5478 outs() << " (not in an __OBJC section)";
5479 }
5480 outs() << "\n";
5481
5482 outs() << "\t\t class name "
5483 << format("0x%08" PRIx32, objc_category->class_name);
5484 if (info->verbose) {
5485 name =
5486 get_pointer_32(objc_category->class_name, offset, left, S, info, true);
5487 if (name != nullptr)
5488 outs() << format(" %.*s", left, name);
5489 else
5490 outs() << " (not in an __OBJC section)";
5491 }
5492 outs() << "\n";
5493
5494 outs() << "\t instance methods "
5495 << format("0x%08" PRIx32, objc_category->instance_methods);
5496 if (print_method_list(objc_category->instance_methods, info))
5497 outs() << " (not in an __OBJC section)\n";
5498
5499 outs() << "\t class methods "
5500 << format("0x%08" PRIx32, objc_category->class_methods);
5501 if (print_method_list(objc_category->class_methods, info))
5502 outs() << " (not in an __OBJC section)\n";
5503}
5504
Kevin Enderby0fc11822015-04-01 20:57:01 +00005505static void print_category64_t(uint64_t p, struct DisassembleInfo *info) {
5506 struct category64_t c;
5507 const char *r;
5508 uint32_t offset, xoffset, left;
5509 SectionRef S, xS;
5510 const char *name, *sym_name;
5511 uint64_t n_value;
5512
5513 r = get_pointer_64(p, offset, left, S, info);
5514 if (r == nullptr)
5515 return;
5516 memset(&c, '\0', sizeof(struct category64_t));
5517 if (left < sizeof(struct category64_t)) {
5518 memcpy(&c, r, left);
5519 outs() << " (category_t entends past the end of the section)\n";
5520 } else
5521 memcpy(&c, r, sizeof(struct category64_t));
5522 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5523 swapStruct(c);
5524
5525 outs() << " name ";
5526 sym_name = get_symbol_64(offset + offsetof(struct category64_t, name), S,
5527 info, n_value, c.name);
5528 if (n_value != 0) {
5529 if (info->verbose && sym_name != nullptr)
5530 outs() << sym_name;
5531 else
5532 outs() << format("0x%" PRIx64, n_value);
5533 if (c.name != 0)
5534 outs() << " + " << format("0x%" PRIx64, c.name);
5535 } else
5536 outs() << format("0x%" PRIx64, c.name);
5537 name = get_pointer_64(c.name + n_value, xoffset, left, xS, info);
5538 if (name != nullptr)
5539 outs() << format(" %.*s", left, name);
5540 outs() << "\n";
5541
5542 outs() << " cls ";
5543 sym_name = get_symbol_64(offset + offsetof(struct category64_t, cls), S, info,
5544 n_value, c.cls);
5545 if (n_value != 0) {
5546 if (info->verbose && sym_name != nullptr)
5547 outs() << sym_name;
5548 else
5549 outs() << format("0x%" PRIx64, n_value);
5550 if (c.cls != 0)
5551 outs() << " + " << format("0x%" PRIx64, c.cls);
5552 } else
5553 outs() << format("0x%" PRIx64, c.cls);
5554 outs() << "\n";
5555 if (c.cls + n_value != 0)
5556 print_class64_t(c.cls + n_value, info);
5557
5558 outs() << " instanceMethods ";
5559 sym_name =
5560 get_symbol_64(offset + offsetof(struct category64_t, instanceMethods), S,
5561 info, n_value, c.instanceMethods);
5562 if (n_value != 0) {
5563 if (info->verbose && sym_name != nullptr)
5564 outs() << sym_name;
5565 else
5566 outs() << format("0x%" PRIx64, n_value);
5567 if (c.instanceMethods != 0)
5568 outs() << " + " << format("0x%" PRIx64, c.instanceMethods);
5569 } else
5570 outs() << format("0x%" PRIx64, c.instanceMethods);
5571 outs() << "\n";
5572 if (c.instanceMethods + n_value != 0)
5573 print_method_list64_t(c.instanceMethods + n_value, info, "");
5574
5575 outs() << " classMethods ";
5576 sym_name = get_symbol_64(offset + offsetof(struct category64_t, classMethods),
5577 S, info, n_value, c.classMethods);
5578 if (n_value != 0) {
5579 if (info->verbose && sym_name != nullptr)
5580 outs() << sym_name;
5581 else
5582 outs() << format("0x%" PRIx64, n_value);
5583 if (c.classMethods != 0)
5584 outs() << " + " << format("0x%" PRIx64, c.classMethods);
5585 } else
5586 outs() << format("0x%" PRIx64, c.classMethods);
5587 outs() << "\n";
5588 if (c.classMethods + n_value != 0)
5589 print_method_list64_t(c.classMethods + n_value, info, "");
5590
5591 outs() << " protocols ";
5592 sym_name = get_symbol_64(offset + offsetof(struct category64_t, protocols), S,
5593 info, n_value, c.protocols);
5594 if (n_value != 0) {
5595 if (info->verbose && sym_name != nullptr)
5596 outs() << sym_name;
5597 else
5598 outs() << format("0x%" PRIx64, n_value);
5599 if (c.protocols != 0)
5600 outs() << " + " << format("0x%" PRIx64, c.protocols);
5601 } else
5602 outs() << format("0x%" PRIx64, c.protocols);
5603 outs() << "\n";
5604 if (c.protocols + n_value != 0)
5605 print_protocol_list64_t(c.protocols + n_value, info);
5606
5607 outs() << "instanceProperties ";
5608 sym_name =
5609 get_symbol_64(offset + offsetof(struct category64_t, instanceProperties),
5610 S, info, n_value, c.instanceProperties);
5611 if (n_value != 0) {
5612 if (info->verbose && sym_name != nullptr)
5613 outs() << sym_name;
5614 else
5615 outs() << format("0x%" PRIx64, n_value);
5616 if (c.instanceProperties != 0)
5617 outs() << " + " << format("0x%" PRIx64, c.instanceProperties);
5618 } else
5619 outs() << format("0x%" PRIx64, c.instanceProperties);
5620 outs() << "\n";
5621 if (c.instanceProperties + n_value != 0)
5622 print_objc_property_list64(c.instanceProperties + n_value, info);
5623}
5624
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005625static void print_category32_t(uint32_t p, struct DisassembleInfo *info) {
5626 struct category32_t c;
5627 const char *r;
5628 uint32_t offset, left;
5629 SectionRef S, xS;
5630 const char *name;
5631
5632 r = get_pointer_32(p, offset, left, S, info);
5633 if (r == nullptr)
5634 return;
5635 memset(&c, '\0', sizeof(struct category32_t));
5636 if (left < sizeof(struct category32_t)) {
5637 memcpy(&c, r, left);
5638 outs() << " (category_t entends past the end of the section)\n";
5639 } else
5640 memcpy(&c, r, sizeof(struct category32_t));
5641 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5642 swapStruct(c);
5643
5644 outs() << " name " << format("0x%" PRIx32, c.name);
5645 name = get_symbol_32(offset + offsetof(struct category32_t, name), S, info,
5646 c.name);
Hans Wennborgcc9deb42015-09-29 18:02:48 +00005647 if (name)
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005648 outs() << " " << name;
5649 outs() << "\n";
5650
5651 outs() << " cls " << format("0x%" PRIx32, c.cls) << "\n";
5652 if (c.cls != 0)
5653 print_class32_t(c.cls, info);
5654 outs() << " instanceMethods " << format("0x%" PRIx32, c.instanceMethods)
5655 << "\n";
5656 if (c.instanceMethods != 0)
5657 print_method_list32_t(c.instanceMethods, info, "");
5658 outs() << " classMethods " << format("0x%" PRIx32, c.classMethods)
5659 << "\n";
5660 if (c.classMethods != 0)
5661 print_method_list32_t(c.classMethods, info, "");
5662 outs() << " protocols " << format("0x%" PRIx32, c.protocols) << "\n";
5663 if (c.protocols != 0)
5664 print_protocol_list32_t(c.protocols, info);
5665 outs() << "instanceProperties " << format("0x%" PRIx32, c.instanceProperties)
5666 << "\n";
5667 if (c.instanceProperties != 0)
5668 print_objc_property_list32(c.instanceProperties, info);
5669}
5670
Kevin Enderby0fc11822015-04-01 20:57:01 +00005671static void print_message_refs64(SectionRef S, struct DisassembleInfo *info) {
5672 uint32_t i, left, offset, xoffset;
5673 uint64_t p, n_value;
5674 struct message_ref64 mr;
5675 const char *name, *sym_name;
5676 const char *r;
5677 SectionRef xS;
5678
5679 if (S == SectionRef())
5680 return;
5681
5682 StringRef SectName;
5683 S.getName(SectName);
5684 DataRefImpl Ref = S.getRawDataRefImpl();
5685 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5686 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5687 offset = 0;
5688 for (i = 0; i < S.getSize(); i += sizeof(struct message_ref64)) {
5689 p = S.getAddress() + i;
5690 r = get_pointer_64(p, offset, left, S, info);
5691 if (r == nullptr)
5692 return;
5693 memset(&mr, '\0', sizeof(struct message_ref64));
5694 if (left < sizeof(struct message_ref64)) {
5695 memcpy(&mr, r, left);
5696 outs() << " (message_ref entends past the end of the section)\n";
5697 } else
5698 memcpy(&mr, r, sizeof(struct message_ref64));
5699 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5700 swapStruct(mr);
5701
5702 outs() << " imp ";
5703 name = get_symbol_64(offset + offsetof(struct message_ref64, imp), S, info,
5704 n_value, mr.imp);
5705 if (n_value != 0) {
5706 outs() << format("0x%" PRIx64, n_value) << " ";
5707 if (mr.imp != 0)
5708 outs() << "+ " << format("0x%" PRIx64, mr.imp) << " ";
5709 } else
5710 outs() << format("0x%" PRIx64, mr.imp) << " ";
5711 if (name != nullptr)
5712 outs() << " " << name;
5713 outs() << "\n";
5714
5715 outs() << " sel ";
5716 sym_name = get_symbol_64(offset + offsetof(struct message_ref64, sel), S,
5717 info, n_value, mr.sel);
5718 if (n_value != 0) {
5719 if (info->verbose && sym_name != nullptr)
5720 outs() << sym_name;
5721 else
5722 outs() << format("0x%" PRIx64, n_value);
5723 if (mr.sel != 0)
5724 outs() << " + " << format("0x%" PRIx64, mr.sel);
5725 } else
5726 outs() << format("0x%" PRIx64, mr.sel);
5727 name = get_pointer_64(mr.sel + n_value, xoffset, left, xS, info);
5728 if (name != nullptr)
5729 outs() << format(" %.*s", left, name);
5730 outs() << "\n";
5731
5732 offset += sizeof(struct message_ref64);
5733 }
5734}
5735
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005736static void print_message_refs32(SectionRef S, struct DisassembleInfo *info) {
5737 uint32_t i, left, offset, xoffset, p;
5738 struct message_ref32 mr;
5739 const char *name, *r;
5740 SectionRef xS;
5741
5742 if (S == SectionRef())
5743 return;
5744
5745 StringRef SectName;
5746 S.getName(SectName);
5747 DataRefImpl Ref = S.getRawDataRefImpl();
5748 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5749 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5750 offset = 0;
5751 for (i = 0; i < S.getSize(); i += sizeof(struct message_ref64)) {
5752 p = S.getAddress() + i;
5753 r = get_pointer_32(p, offset, left, S, info);
5754 if (r == nullptr)
5755 return;
5756 memset(&mr, '\0', sizeof(struct message_ref32));
5757 if (left < sizeof(struct message_ref32)) {
5758 memcpy(&mr, r, left);
5759 outs() << " (message_ref entends past the end of the section)\n";
5760 } else
5761 memcpy(&mr, r, sizeof(struct message_ref32));
5762 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5763 swapStruct(mr);
5764
5765 outs() << " imp " << format("0x%" PRIx32, mr.imp);
5766 name = get_symbol_32(offset + offsetof(struct message_ref32, imp), S, info,
5767 mr.imp);
5768 if (name != nullptr)
5769 outs() << " " << name;
5770 outs() << "\n";
5771
5772 outs() << " sel " << format("0x%" PRIx32, mr.sel);
5773 name = get_pointer_32(mr.sel, xoffset, left, xS, info);
5774 if (name != nullptr)
5775 outs() << " " << name;
5776 outs() << "\n";
5777
5778 offset += sizeof(struct message_ref32);
5779 }
5780}
5781
Kevin Enderby0fc11822015-04-01 20:57:01 +00005782static void print_image_info64(SectionRef S, struct DisassembleInfo *info) {
5783 uint32_t left, offset, swift_version;
5784 uint64_t p;
5785 struct objc_image_info64 o;
5786 const char *r;
5787
Kevin Enderbyaf7c9d02015-10-09 16:48:44 +00005788 if (S == SectionRef())
5789 return;
5790
Kevin Enderby0fc11822015-04-01 20:57:01 +00005791 StringRef SectName;
5792 S.getName(SectName);
5793 DataRefImpl Ref = S.getRawDataRefImpl();
5794 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5795 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5796 p = S.getAddress();
5797 r = get_pointer_64(p, offset, left, S, info);
5798 if (r == nullptr)
5799 return;
5800 memset(&o, '\0', sizeof(struct objc_image_info64));
5801 if (left < sizeof(struct objc_image_info64)) {
5802 memcpy(&o, r, left);
5803 outs() << " (objc_image_info entends past the end of the section)\n";
5804 } else
5805 memcpy(&o, r, sizeof(struct objc_image_info64));
5806 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5807 swapStruct(o);
5808 outs() << " version " << o.version << "\n";
5809 outs() << " flags " << format("0x%" PRIx32, o.flags);
5810 if (o.flags & OBJC_IMAGE_IS_REPLACEMENT)
5811 outs() << " OBJC_IMAGE_IS_REPLACEMENT";
5812 if (o.flags & OBJC_IMAGE_SUPPORTS_GC)
5813 outs() << " OBJC_IMAGE_SUPPORTS_GC";
Dave Lee390abe42018-07-06 05:11:35 +00005814 if (o.flags & OBJC_IMAGE_IS_SIMULATED)
5815 outs() << " OBJC_IMAGE_IS_SIMULATED";
5816 if (o.flags & OBJC_IMAGE_HAS_CATEGORY_CLASS_PROPERTIES)
5817 outs() << " OBJC_IMAGE_HAS_CATEGORY_CLASS_PROPERTIES";
Kevin Enderby0fc11822015-04-01 20:57:01 +00005818 swift_version = (o.flags >> 8) & 0xff;
5819 if (swift_version != 0) {
5820 if (swift_version == 1)
5821 outs() << " Swift 1.0";
5822 else if (swift_version == 2)
5823 outs() << " Swift 1.1";
Kevin Enderbycda2ced2018-02-09 19:31:27 +00005824 else if(swift_version == 3)
5825 outs() << " Swift 2.0";
5826 else if(swift_version == 4)
5827 outs() << " Swift 3.0";
5828 else if(swift_version == 5)
5829 outs() << " Swift 4.0";
5830 else if(swift_version == 6)
Michael Trentf7254a62018-12-07 19:55:03 +00005831 outs() << " Swift 4.1/Swift 4.2";
5832 else if(swift_version == 7)
5833 outs() << " Swift 5 or later";
Kevin Enderby0fc11822015-04-01 20:57:01 +00005834 else
5835 outs() << " unknown future Swift version (" << swift_version << ")";
5836 }
5837 outs() << "\n";
5838}
5839
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005840static void print_image_info32(SectionRef S, struct DisassembleInfo *info) {
5841 uint32_t left, offset, swift_version, p;
5842 struct objc_image_info32 o;
5843 const char *r;
5844
Kevin Enderby19be2512016-04-21 19:49:29 +00005845 if (S == SectionRef())
5846 return;
5847
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005848 StringRef SectName;
5849 S.getName(SectName);
5850 DataRefImpl Ref = S.getRawDataRefImpl();
5851 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5852 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5853 p = S.getAddress();
5854 r = get_pointer_32(p, offset, left, S, info);
5855 if (r == nullptr)
5856 return;
5857 memset(&o, '\0', sizeof(struct objc_image_info32));
5858 if (left < sizeof(struct objc_image_info32)) {
5859 memcpy(&o, r, left);
5860 outs() << " (objc_image_info entends past the end of the section)\n";
5861 } else
5862 memcpy(&o, r, sizeof(struct objc_image_info32));
5863 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5864 swapStruct(o);
5865 outs() << " version " << o.version << "\n";
5866 outs() << " flags " << format("0x%" PRIx32, o.flags);
5867 if (o.flags & OBJC_IMAGE_IS_REPLACEMENT)
5868 outs() << " OBJC_IMAGE_IS_REPLACEMENT";
5869 if (o.flags & OBJC_IMAGE_SUPPORTS_GC)
5870 outs() << " OBJC_IMAGE_SUPPORTS_GC";
5871 swift_version = (o.flags >> 8) & 0xff;
5872 if (swift_version != 0) {
5873 if (swift_version == 1)
5874 outs() << " Swift 1.0";
5875 else if (swift_version == 2)
5876 outs() << " Swift 1.1";
Kevin Enderbycda2ced2018-02-09 19:31:27 +00005877 else if(swift_version == 3)
5878 outs() << " Swift 2.0";
5879 else if(swift_version == 4)
5880 outs() << " Swift 3.0";
5881 else if(swift_version == 5)
5882 outs() << " Swift 4.0";
5883 else if(swift_version == 6)
Michael Trentf7254a62018-12-07 19:55:03 +00005884 outs() << " Swift 4.1/Swift 4.2";
5885 else if(swift_version == 7)
5886 outs() << " Swift 5 or later";
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00005887 else
5888 outs() << " unknown future Swift version (" << swift_version << ")";
5889 }
5890 outs() << "\n";
5891}
5892
Kevin Enderby846c0002015-04-16 17:19:59 +00005893static void print_image_info(SectionRef S, struct DisassembleInfo *info) {
5894 uint32_t left, offset, p;
5895 struct imageInfo_t o;
5896 const char *r;
5897
5898 StringRef SectName;
5899 S.getName(SectName);
5900 DataRefImpl Ref = S.getRawDataRefImpl();
5901 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5902 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5903 p = S.getAddress();
5904 r = get_pointer_32(p, offset, left, S, info);
5905 if (r == nullptr)
5906 return;
5907 memset(&o, '\0', sizeof(struct imageInfo_t));
5908 if (left < sizeof(struct imageInfo_t)) {
5909 memcpy(&o, r, left);
5910 outs() << " (imageInfo entends past the end of the section)\n";
5911 } else
5912 memcpy(&o, r, sizeof(struct imageInfo_t));
5913 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5914 swapStruct(o);
5915 outs() << " version " << o.version << "\n";
5916 outs() << " flags " << format("0x%" PRIx32, o.flags);
5917 if (o.flags & 0x1)
5918 outs() << " F&C";
5919 if (o.flags & 0x2)
5920 outs() << " GC";
5921 if (o.flags & 0x4)
5922 outs() << " GC-only";
5923 else
5924 outs() << " RR";
5925 outs() << "\n";
5926}
5927
Kevin Enderby0fc11822015-04-01 20:57:01 +00005928static void printObjc2_64bit_MetaData(MachOObjectFile *O, bool verbose) {
5929 SymbolAddressMap AddrMap;
5930 if (verbose)
5931 CreateSymbolAddressMap(O, &AddrMap);
5932
5933 std::vector<SectionRef> Sections;
5934 for (const SectionRef &Section : O->sections()) {
5935 StringRef SectName;
5936 Section.getName(SectName);
5937 Sections.push_back(Section);
5938 }
5939
Serge Pavlove4e9a1f2018-02-14 03:26:27 +00005940 struct DisassembleInfo info(O, &AddrMap, &Sections, verbose);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005941
Davide Italiano62507042015-12-11 22:27:59 +00005942 SectionRef CL = get_section(O, "__OBJC2", "__class_list");
5943 if (CL == SectionRef())
5944 CL = get_section(O, "__DATA", "__objc_classlist");
Kevin Enderby5879a482017-02-09 17:56:26 +00005945 if (CL == SectionRef())
5946 CL = get_section(O, "__DATA_CONST", "__objc_classlist");
5947 if (CL == SectionRef())
5948 CL = get_section(O, "__DATA_DIRTY", "__objc_classlist");
Davide Italiano62507042015-12-11 22:27:59 +00005949 info.S = CL;
5950 walk_pointer_list_64("class", CL, O, &info, print_class64_t);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005951
Davide Italiano62507042015-12-11 22:27:59 +00005952 SectionRef CR = get_section(O, "__OBJC2", "__class_refs");
5953 if (CR == SectionRef())
5954 CR = get_section(O, "__DATA", "__objc_classrefs");
Kevin Enderby5879a482017-02-09 17:56:26 +00005955 if (CR == SectionRef())
5956 CR = get_section(O, "__DATA_CONST", "__objc_classrefs");
5957 if (CR == SectionRef())
5958 CR = get_section(O, "__DATA_DIRTY", "__objc_classrefs");
Davide Italiano62507042015-12-11 22:27:59 +00005959 info.S = CR;
5960 walk_pointer_list_64("class refs", CR, O, &info, nullptr);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005961
Davide Italiano62507042015-12-11 22:27:59 +00005962 SectionRef SR = get_section(O, "__OBJC2", "__super_refs");
5963 if (SR == SectionRef())
5964 SR = get_section(O, "__DATA", "__objc_superrefs");
Kevin Enderby5879a482017-02-09 17:56:26 +00005965 if (SR == SectionRef())
5966 SR = get_section(O, "__DATA_CONST", "__objc_superrefs");
5967 if (SR == SectionRef())
5968 SR = get_section(O, "__DATA_DIRTY", "__objc_superrefs");
Davide Italiano62507042015-12-11 22:27:59 +00005969 info.S = SR;
5970 walk_pointer_list_64("super refs", SR, O, &info, nullptr);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005971
Davide Italiano62507042015-12-11 22:27:59 +00005972 SectionRef CA = get_section(O, "__OBJC2", "__category_list");
5973 if (CA == SectionRef())
5974 CA = get_section(O, "__DATA", "__objc_catlist");
Kevin Enderby5879a482017-02-09 17:56:26 +00005975 if (CA == SectionRef())
5976 CA = get_section(O, "__DATA_CONST", "__objc_catlist");
5977 if (CA == SectionRef())
5978 CA = get_section(O, "__DATA_DIRTY", "__objc_catlist");
Davide Italiano62507042015-12-11 22:27:59 +00005979 info.S = CA;
5980 walk_pointer_list_64("category", CA, O, &info, print_category64_t);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005981
Davide Italiano62507042015-12-11 22:27:59 +00005982 SectionRef PL = get_section(O, "__OBJC2", "__protocol_list");
5983 if (PL == SectionRef())
5984 PL = get_section(O, "__DATA", "__objc_protolist");
Kevin Enderby5879a482017-02-09 17:56:26 +00005985 if (PL == SectionRef())
5986 PL = get_section(O, "__DATA_CONST", "__objc_protolist");
5987 if (PL == SectionRef())
5988 PL = get_section(O, "__DATA_DIRTY", "__objc_protolist");
Davide Italiano62507042015-12-11 22:27:59 +00005989 info.S = PL;
5990 walk_pointer_list_64("protocol", PL, O, &info, nullptr);
Kevin Enderby0fc11822015-04-01 20:57:01 +00005991
Davide Italiano62507042015-12-11 22:27:59 +00005992 SectionRef MR = get_section(O, "__OBJC2", "__message_refs");
5993 if (MR == SectionRef())
5994 MR = get_section(O, "__DATA", "__objc_msgrefs");
Kevin Enderby5879a482017-02-09 17:56:26 +00005995 if (MR == SectionRef())
5996 MR = get_section(O, "__DATA_CONST", "__objc_msgrefs");
5997 if (MR == SectionRef())
5998 MR = get_section(O, "__DATA_DIRTY", "__objc_msgrefs");
Davide Italiano62507042015-12-11 22:27:59 +00005999 info.S = MR;
6000 print_message_refs64(MR, &info);
Kevin Enderby0fc11822015-04-01 20:57:01 +00006001
Davide Italiano62507042015-12-11 22:27:59 +00006002 SectionRef II = get_section(O, "__OBJC2", "__image_info");
6003 if (II == SectionRef())
6004 II = get_section(O, "__DATA", "__objc_imageinfo");
Kevin Enderby5879a482017-02-09 17:56:26 +00006005 if (II == SectionRef())
6006 II = get_section(O, "__DATA_CONST", "__objc_imageinfo");
6007 if (II == SectionRef())
6008 II = get_section(O, "__DATA_DIRTY", "__objc_imageinfo");
Davide Italiano62507042015-12-11 22:27:59 +00006009 info.S = II;
6010 print_image_info64(II, &info);
Kevin Enderby0fc11822015-04-01 20:57:01 +00006011}
6012
6013static void printObjc2_32bit_MetaData(MachOObjectFile *O, bool verbose) {
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00006014 SymbolAddressMap AddrMap;
6015 if (verbose)
6016 CreateSymbolAddressMap(O, &AddrMap);
6017
6018 std::vector<SectionRef> Sections;
6019 for (const SectionRef &Section : O->sections()) {
6020 StringRef SectName;
6021 Section.getName(SectName);
6022 Sections.push_back(Section);
6023 }
6024
Serge Pavlove4e9a1f2018-02-14 03:26:27 +00006025 struct DisassembleInfo info(O, &AddrMap, &Sections, verbose);
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00006026
Kevin Enderby5879a482017-02-09 17:56:26 +00006027 SectionRef CL = get_section(O, "__OBJC2", "__class_list");
6028 if (CL == SectionRef())
6029 CL = get_section(O, "__DATA", "__objc_classlist");
6030 if (CL == SectionRef())
6031 CL = get_section(O, "__DATA_CONST", "__objc_classlist");
6032 if (CL == SectionRef())
6033 CL = get_section(O, "__DATA_DIRTY", "__objc_classlist");
6034 info.S = CL;
6035 walk_pointer_list_32("class", CL, O, &info, print_class32_t);
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00006036
Kevin Enderby5879a482017-02-09 17:56:26 +00006037 SectionRef CR = get_section(O, "__OBJC2", "__class_refs");
6038 if (CR == SectionRef())
6039 CR = get_section(O, "__DATA", "__objc_classrefs");
6040 if (CR == SectionRef())
6041 CR = get_section(O, "__DATA_CONST", "__objc_classrefs");
6042 if (CR == SectionRef())
6043 CR = get_section(O, "__DATA_DIRTY", "__objc_classrefs");
6044 info.S = CR;
6045 walk_pointer_list_32("class refs", CR, O, &info, nullptr);
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00006046
Kevin Enderby5879a482017-02-09 17:56:26 +00006047 SectionRef SR = get_section(O, "__OBJC2", "__super_refs");
6048 if (SR == SectionRef())
6049 SR = get_section(O, "__DATA", "__objc_superrefs");
6050 if (SR == SectionRef())
6051 SR = get_section(O, "__DATA_CONST", "__objc_superrefs");
6052 if (SR == SectionRef())
6053 SR = get_section(O, "__DATA_DIRTY", "__objc_superrefs");
6054 info.S = SR;
6055 walk_pointer_list_32("super refs", SR, O, &info, nullptr);
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00006056
Kevin Enderby5879a482017-02-09 17:56:26 +00006057 SectionRef CA = get_section(O, "__OBJC2", "__category_list");
6058 if (CA == SectionRef())
6059 CA = get_section(O, "__DATA", "__objc_catlist");
6060 if (CA == SectionRef())
6061 CA = get_section(O, "__DATA_CONST", "__objc_catlist");
6062 if (CA == SectionRef())
6063 CA = get_section(O, "__DATA_DIRTY", "__objc_catlist");
6064 info.S = CA;
6065 walk_pointer_list_32("category", CA, O, &info, print_category32_t);
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00006066
Kevin Enderby5879a482017-02-09 17:56:26 +00006067 SectionRef PL = get_section(O, "__OBJC2", "__protocol_list");
6068 if (PL == SectionRef())
6069 PL = get_section(O, "__DATA", "__objc_protolist");
6070 if (PL == SectionRef())
6071 PL = get_section(O, "__DATA_CONST", "__objc_protolist");
6072 if (PL == SectionRef())
6073 PL = get_section(O, "__DATA_DIRTY", "__objc_protolist");
6074 info.S = PL;
6075 walk_pointer_list_32("protocol", PL, O, &info, nullptr);
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00006076
Kevin Enderby5879a482017-02-09 17:56:26 +00006077 SectionRef MR = get_section(O, "__OBJC2", "__message_refs");
6078 if (MR == SectionRef())
6079 MR = get_section(O, "__DATA", "__objc_msgrefs");
6080 if (MR == SectionRef())
6081 MR = get_section(O, "__DATA_CONST", "__objc_msgrefs");
6082 if (MR == SectionRef())
6083 MR = get_section(O, "__DATA_DIRTY", "__objc_msgrefs");
6084 info.S = MR;
6085 print_message_refs32(MR, &info);
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00006086
Kevin Enderby5879a482017-02-09 17:56:26 +00006087 SectionRef II = get_section(O, "__OBJC2", "__image_info");
6088 if (II == SectionRef())
6089 II = get_section(O, "__DATA", "__objc_imageinfo");
6090 if (II == SectionRef())
6091 II = get_section(O, "__DATA_CONST", "__objc_imageinfo");
6092 if (II == SectionRef())
6093 II = get_section(O, "__DATA_DIRTY", "__objc_imageinfo");
6094 info.S = II;
6095 print_image_info32(II, &info);
Kevin Enderby0fc11822015-04-01 20:57:01 +00006096}
6097
6098static bool printObjc1_32bit_MetaData(MachOObjectFile *O, bool verbose) {
Kevin Enderby846c0002015-04-16 17:19:59 +00006099 uint32_t i, j, p, offset, xoffset, left, defs_left, def;
6100 const char *r, *name, *defs;
6101 struct objc_module_t module;
6102 SectionRef S, xS;
6103 struct objc_symtab_t symtab;
6104 struct objc_class_t objc_class;
6105 struct objc_category_t objc_category;
6106
Kevin Enderby28c1c1b2015-04-06 17:47:03 +00006107 outs() << "Objective-C segment\n";
Kevin Enderby846c0002015-04-16 17:19:59 +00006108 S = get_section(O, "__OBJC", "__module_info");
6109 if (S == SectionRef())
6110 return false;
6111
6112 SymbolAddressMap AddrMap;
6113 if (verbose)
6114 CreateSymbolAddressMap(O, &AddrMap);
6115
6116 std::vector<SectionRef> Sections;
6117 for (const SectionRef &Section : O->sections()) {
6118 StringRef SectName;
6119 Section.getName(SectName);
6120 Sections.push_back(Section);
Kevin Enderby0fc11822015-04-01 20:57:01 +00006121 }
Kevin Enderby846c0002015-04-16 17:19:59 +00006122
Serge Pavlove4e9a1f2018-02-14 03:26:27 +00006123 struct DisassembleInfo info(O, &AddrMap, &Sections, verbose);
Kevin Enderby846c0002015-04-16 17:19:59 +00006124
6125 for (i = 0; i < S.getSize(); i += sizeof(struct objc_module_t)) {
6126 p = S.getAddress() + i;
6127 r = get_pointer_32(p, offset, left, S, &info, true);
6128 if (r == nullptr)
6129 return true;
6130 memset(&module, '\0', sizeof(struct objc_module_t));
6131 if (left < sizeof(struct objc_module_t)) {
6132 memcpy(&module, r, left);
6133 outs() << " (module extends past end of __module_info section)\n";
6134 } else
6135 memcpy(&module, r, sizeof(struct objc_module_t));
6136 if (O->isLittleEndian() != sys::IsLittleEndianHost)
6137 swapStruct(module);
6138
6139 outs() << "Module " << format("0x%" PRIx32, p) << "\n";
6140 outs() << " version " << module.version << "\n";
6141 outs() << " size " << module.size << "\n";
6142 outs() << " name ";
6143 name = get_pointer_32(module.name, xoffset, left, xS, &info, true);
6144 if (name != nullptr)
6145 outs() << format("%.*s", left, name);
6146 else
6147 outs() << format("0x%08" PRIx32, module.name)
6148 << "(not in an __OBJC section)";
6149 outs() << "\n";
6150
6151 r = get_pointer_32(module.symtab, xoffset, left, xS, &info, true);
6152 if (module.symtab == 0 || r == nullptr) {
6153 outs() << " symtab " << format("0x%08" PRIx32, module.symtab)
6154 << " (not in an __OBJC section)\n";
6155 continue;
6156 }
6157 outs() << " symtab " << format("0x%08" PRIx32, module.symtab) << "\n";
6158 memset(&symtab, '\0', sizeof(struct objc_symtab_t));
6159 defs_left = 0;
6160 defs = nullptr;
6161 if (left < sizeof(struct objc_symtab_t)) {
6162 memcpy(&symtab, r, left);
6163 outs() << "\tsymtab extends past end of an __OBJC section)\n";
6164 } else {
6165 memcpy(&symtab, r, sizeof(struct objc_symtab_t));
6166 if (left > sizeof(struct objc_symtab_t)) {
6167 defs_left = left - sizeof(struct objc_symtab_t);
6168 defs = r + sizeof(struct objc_symtab_t);
6169 }
6170 }
6171 if (O->isLittleEndian() != sys::IsLittleEndianHost)
6172 swapStruct(symtab);
6173
6174 outs() << "\tsel_ref_cnt " << symtab.sel_ref_cnt << "\n";
6175 r = get_pointer_32(symtab.refs, xoffset, left, xS, &info, true);
6176 outs() << "\trefs " << format("0x%08" PRIx32, symtab.refs);
6177 if (r == nullptr)
6178 outs() << " (not in an __OBJC section)";
6179 outs() << "\n";
6180 outs() << "\tcls_def_cnt " << symtab.cls_def_cnt << "\n";
6181 outs() << "\tcat_def_cnt " << symtab.cat_def_cnt << "\n";
6182 if (symtab.cls_def_cnt > 0)
6183 outs() << "\tClass Definitions\n";
6184 for (j = 0; j < symtab.cls_def_cnt; j++) {
6185 if ((j + 1) * sizeof(uint32_t) > defs_left) {
6186 outs() << "\t(remaining class defs entries entends past the end of the "
6187 << "section)\n";
6188 break;
6189 }
6190 memcpy(&def, defs + j * sizeof(uint32_t), sizeof(uint32_t));
6191 if (O->isLittleEndian() != sys::IsLittleEndianHost)
6192 sys::swapByteOrder(def);
6193
6194 r = get_pointer_32(def, xoffset, left, xS, &info, true);
6195 outs() << "\tdefs[" << j << "] " << format("0x%08" PRIx32, def);
6196 if (r != nullptr) {
6197 if (left > sizeof(struct objc_class_t)) {
6198 outs() << "\n";
6199 memcpy(&objc_class, r, sizeof(struct objc_class_t));
6200 } else {
6201 outs() << " (entends past the end of the section)\n";
6202 memset(&objc_class, '\0', sizeof(struct objc_class_t));
6203 memcpy(&objc_class, r, left);
6204 }
6205 if (O->isLittleEndian() != sys::IsLittleEndianHost)
6206 swapStruct(objc_class);
6207 print_objc_class_t(&objc_class, &info);
6208 } else {
6209 outs() << "(not in an __OBJC section)\n";
6210 }
6211
6212 if (CLS_GETINFO(&objc_class, CLS_CLASS)) {
6213 outs() << "\tMeta Class";
6214 r = get_pointer_32(objc_class.isa, xoffset, left, xS, &info, true);
6215 if (r != nullptr) {
6216 if (left > sizeof(struct objc_class_t)) {
6217 outs() << "\n";
6218 memcpy(&objc_class, r, sizeof(struct objc_class_t));
6219 } else {
6220 outs() << " (entends past the end of the section)\n";
6221 memset(&objc_class, '\0', sizeof(struct objc_class_t));
6222 memcpy(&objc_class, r, left);
6223 }
6224 if (O->isLittleEndian() != sys::IsLittleEndianHost)
6225 swapStruct(objc_class);
6226 print_objc_class_t(&objc_class, &info);
6227 } else {
6228 outs() << "(not in an __OBJC section)\n";
6229 }
6230 }
6231 }
6232 if (symtab.cat_def_cnt > 0)
6233 outs() << "\tCategory Definitions\n";
6234 for (j = 0; j < symtab.cat_def_cnt; j++) {
6235 if ((j + symtab.cls_def_cnt + 1) * sizeof(uint32_t) > defs_left) {
6236 outs() << "\t(remaining category defs entries entends past the end of "
6237 << "the section)\n";
6238 break;
6239 }
6240 memcpy(&def, defs + (j + symtab.cls_def_cnt) * sizeof(uint32_t),
6241 sizeof(uint32_t));
6242 if (O->isLittleEndian() != sys::IsLittleEndianHost)
6243 sys::swapByteOrder(def);
6244
6245 r = get_pointer_32(def, xoffset, left, xS, &info, true);
6246 outs() << "\tdefs[" << j + symtab.cls_def_cnt << "] "
6247 << format("0x%08" PRIx32, def);
6248 if (r != nullptr) {
6249 if (left > sizeof(struct objc_category_t)) {
6250 outs() << "\n";
6251 memcpy(&objc_category, r, sizeof(struct objc_category_t));
6252 } else {
6253 outs() << " (entends past the end of the section)\n";
6254 memset(&objc_category, '\0', sizeof(struct objc_category_t));
6255 memcpy(&objc_category, r, left);
6256 }
6257 if (O->isLittleEndian() != sys::IsLittleEndianHost)
6258 swapStruct(objc_category);
6259 print_objc_objc_category_t(&objc_category, &info);
6260 } else {
6261 outs() << "(not in an __OBJC section)\n";
6262 }
6263 }
6264 }
6265 const SectionRef II = get_section(O, "__OBJC", "__image_info");
6266 if (II != SectionRef())
6267 print_image_info(II, &info);
6268
6269 return true;
Kevin Enderby0fc11822015-04-01 20:57:01 +00006270}
6271
Kevin Enderby4ad9bde2015-04-16 22:33:20 +00006272static void DumpProtocolSection(MachOObjectFile *O, const char *sect,
6273 uint32_t size, uint32_t addr) {
6274 SymbolAddressMap AddrMap;
6275 CreateSymbolAddressMap(O, &AddrMap);
6276
6277 std::vector<SectionRef> Sections;
6278 for (const SectionRef &Section : O->sections()) {
6279 StringRef SectName;
6280 Section.getName(SectName);
6281 Sections.push_back(Section);
6282 }
6283
Serge Pavlove4e9a1f2018-02-14 03:26:27 +00006284 struct DisassembleInfo info(O, &AddrMap, &Sections, true);
Kevin Enderby4ad9bde2015-04-16 22:33:20 +00006285
6286 const char *p;
6287 struct objc_protocol_t protocol;
6288 uint32_t left, paddr;
6289 for (p = sect; p < sect + size; p += sizeof(struct objc_protocol_t)) {
6290 memset(&protocol, '\0', sizeof(struct objc_protocol_t));
6291 left = size - (p - sect);
6292 if (left < sizeof(struct objc_protocol_t)) {
6293 outs() << "Protocol extends past end of __protocol section\n";
6294 memcpy(&protocol, p, left);
6295 } else
6296 memcpy(&protocol, p, sizeof(struct objc_protocol_t));
6297 if (O->isLittleEndian() != sys::IsLittleEndianHost)
6298 swapStruct(protocol);
6299 paddr = addr + (p - sect);
6300 outs() << "Protocol " << format("0x%" PRIx32, paddr);
6301 if (print_protocol(paddr, 0, &info))
6302 outs() << "(not in an __OBJC section)\n";
6303 }
6304}
6305
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006306#ifdef HAVE_LIBXAR
6307inline void swapStruct(struct xar_header &xar) {
6308 sys::swapByteOrder(xar.magic);
6309 sys::swapByteOrder(xar.size);
6310 sys::swapByteOrder(xar.version);
6311 sys::swapByteOrder(xar.toc_length_compressed);
6312 sys::swapByteOrder(xar.toc_length_uncompressed);
6313 sys::swapByteOrder(xar.cksum_alg);
6314}
6315
6316static void PrintModeVerbose(uint32_t mode) {
6317 switch(mode & S_IFMT){
6318 case S_IFDIR:
6319 outs() << "d";
6320 break;
6321 case S_IFCHR:
6322 outs() << "c";
6323 break;
6324 case S_IFBLK:
6325 outs() << "b";
6326 break;
6327 case S_IFREG:
6328 outs() << "-";
6329 break;
6330 case S_IFLNK:
6331 outs() << "l";
6332 break;
6333 case S_IFSOCK:
6334 outs() << "s";
6335 break;
6336 default:
6337 outs() << "?";
6338 break;
6339 }
6340
6341 /* owner permissions */
6342 if(mode & S_IREAD)
6343 outs() << "r";
6344 else
6345 outs() << "-";
6346 if(mode & S_IWRITE)
6347 outs() << "w";
6348 else
6349 outs() << "-";
6350 if(mode & S_ISUID)
6351 outs() << "s";
6352 else if(mode & S_IEXEC)
6353 outs() << "x";
6354 else
6355 outs() << "-";
6356
6357 /* group permissions */
6358 if(mode & (S_IREAD >> 3))
6359 outs() << "r";
6360 else
6361 outs() << "-";
6362 if(mode & (S_IWRITE >> 3))
6363 outs() << "w";
6364 else
6365 outs() << "-";
6366 if(mode & S_ISGID)
6367 outs() << "s";
6368 else if(mode & (S_IEXEC >> 3))
6369 outs() << "x";
6370 else
6371 outs() << "-";
6372
6373 /* other permissions */
6374 if(mode & (S_IREAD >> 6))
6375 outs() << "r";
6376 else
6377 outs() << "-";
6378 if(mode & (S_IWRITE >> 6))
6379 outs() << "w";
6380 else
6381 outs() << "-";
6382 if(mode & S_ISVTX)
6383 outs() << "t";
6384 else if(mode & (S_IEXEC >> 6))
6385 outs() << "x";
6386 else
6387 outs() << "-";
6388}
6389
6390static void PrintXarFilesSummary(const char *XarFilename, xar_t xar) {
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006391 xar_file_t xf;
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006392 const char *key, *type, *mode, *user, *group, *size, *mtime, *name, *m;
6393 char *endp;
6394 uint32_t mode_value;
6395
Francis Ricci6f942972017-10-06 15:33:28 +00006396 ScopedXarIter xi;
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006397 if (!xi) {
Jonas Devliegheree787efd2018-11-11 22:12:04 +00006398 WithColor::error(errs(), "llvm-objdump")
6399 << "can't obtain an xar iterator for xar archive " << XarFilename
6400 << "\n";
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006401 return;
6402 }
6403
6404 // Go through the xar's files.
6405 for (xf = xar_file_first(xar, xi); xf; xf = xar_file_next(xi)) {
Francis Ricci6f942972017-10-06 15:33:28 +00006406 ScopedXarIter xp;
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006407 if(!xp){
Jonas Devliegheree787efd2018-11-11 22:12:04 +00006408 WithColor::error(errs(), "llvm-objdump")
6409 << "can't obtain an xar iterator for xar archive " << XarFilename
6410 << "\n";
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006411 return;
6412 }
6413 type = nullptr;
6414 mode = nullptr;
6415 user = nullptr;
6416 group = nullptr;
6417 size = nullptr;
6418 mtime = nullptr;
6419 name = nullptr;
6420 for(key = xar_prop_first(xf, xp); key; key = xar_prop_next(xp)){
Jonas Devliegherec0a758d2017-09-18 14:15:57 +00006421 const char *val = nullptr;
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006422 xar_prop_get(xf, key, &val);
6423#if 0 // Useful for debugging.
6424 outs() << "key: " << key << " value: " << val << "\n";
6425#endif
6426 if(strcmp(key, "type") == 0)
6427 type = val;
6428 if(strcmp(key, "mode") == 0)
6429 mode = val;
6430 if(strcmp(key, "user") == 0)
6431 user = val;
6432 if(strcmp(key, "group") == 0)
6433 group = val;
6434 if(strcmp(key, "data/size") == 0)
6435 size = val;
6436 if(strcmp(key, "mtime") == 0)
6437 mtime = val;
6438 if(strcmp(key, "name") == 0)
6439 name = val;
6440 }
6441 if(mode != nullptr){
6442 mode_value = strtoul(mode, &endp, 8);
6443 if(*endp != '\0')
6444 outs() << "(mode: \"" << mode << "\" contains non-octal chars) ";
6445 if(strcmp(type, "file") == 0)
6446 mode_value |= S_IFREG;
6447 PrintModeVerbose(mode_value);
6448 outs() << " ";
6449 }
6450 if(user != nullptr)
6451 outs() << format("%10s/", user);
6452 if(group != nullptr)
6453 outs() << format("%-10s ", group);
6454 if(size != nullptr)
6455 outs() << format("%7s ", size);
6456 if(mtime != nullptr){
6457 for(m = mtime; *m != 'T' && *m != '\0'; m++)
6458 outs() << *m;
6459 if(*m == 'T')
6460 m++;
6461 outs() << " ";
6462 for( ; *m != 'Z' && *m != '\0'; m++)
6463 outs() << *m;
6464 outs() << " ";
6465 }
6466 if(name != nullptr)
6467 outs() << name;
6468 outs() << "\n";
6469 }
6470}
6471
6472static void DumpBitcodeSection(MachOObjectFile *O, const char *sect,
6473 uint32_t size, bool verbose,
6474 bool PrintXarHeader, bool PrintXarFileHeaders,
6475 std::string XarMemberName) {
6476 if(size < sizeof(struct xar_header)) {
6477 outs() << "size of (__LLVM,__bundle) section too small (smaller than size "
6478 "of struct xar_header)\n";
6479 return;
6480 }
6481 struct xar_header XarHeader;
6482 memcpy(&XarHeader, sect, sizeof(struct xar_header));
6483 if (sys::IsLittleEndianHost)
6484 swapStruct(XarHeader);
6485 if (PrintXarHeader) {
6486 if (!XarMemberName.empty())
6487 outs() << "In xar member " << XarMemberName << ": ";
6488 else
6489 outs() << "For (__LLVM,__bundle) section: ";
6490 outs() << "xar header\n";
6491 if (XarHeader.magic == XAR_HEADER_MAGIC)
6492 outs() << " magic XAR_HEADER_MAGIC\n";
6493 else
6494 outs() << " magic "
6495 << format_hex(XarHeader.magic, 10, true)
6496 << " (not XAR_HEADER_MAGIC)\n";
6497 outs() << " size " << XarHeader.size << "\n";
6498 outs() << " version " << XarHeader.version << "\n";
6499 outs() << " toc_length_compressed " << XarHeader.toc_length_compressed
6500 << "\n";
6501 outs() << "toc_length_uncompressed " << XarHeader.toc_length_uncompressed
6502 << "\n";
6503 outs() << " cksum_alg ";
6504 switch (XarHeader.cksum_alg) {
6505 case XAR_CKSUM_NONE:
6506 outs() << "XAR_CKSUM_NONE\n";
6507 break;
6508 case XAR_CKSUM_SHA1:
6509 outs() << "XAR_CKSUM_SHA1\n";
6510 break;
6511 case XAR_CKSUM_MD5:
6512 outs() << "XAR_CKSUM_MD5\n";
6513 break;
Kevin Enderby42882282016-05-23 22:18:59 +00006514#ifdef XAR_CKSUM_SHA256
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006515 case XAR_CKSUM_SHA256:
6516 outs() << "XAR_CKSUM_SHA256\n";
6517 break;
Kevin Enderby42882282016-05-23 22:18:59 +00006518#endif
6519#ifdef XAR_CKSUM_SHA512
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006520 case XAR_CKSUM_SHA512:
6521 outs() << "XAR_CKSUM_SHA512\n";
6522 break;
Kevin Enderby42882282016-05-23 22:18:59 +00006523#endif
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006524 default:
6525 outs() << XarHeader.cksum_alg << "\n";
6526 }
6527 }
6528
6529 SmallString<128> XarFilename;
6530 int FD;
6531 std::error_code XarEC =
6532 sys::fs::createTemporaryFile("llvm-objdump", "xar", FD, XarFilename);
6533 if (XarEC) {
Jonas Devliegheree787efd2018-11-11 22:12:04 +00006534 WithColor::error(errs(), "llvm-objdump") << XarEC.message() << "\n";
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006535 return;
6536 }
Reid Kleckner3fc649c2017-09-23 01:03:17 +00006537 ToolOutputFile XarFile(XarFilename, FD);
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006538 raw_fd_ostream &XarOut = XarFile.os();
6539 StringRef XarContents(sect, size);
6540 XarOut << XarContents;
6541 XarOut.close();
6542 if (XarOut.has_error())
6543 return;
6544
Francis Ricci6f942972017-10-06 15:33:28 +00006545 ScopedXarFile xar(XarFilename.c_str(), READ);
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006546 if (!xar) {
Jonas Devliegheree787efd2018-11-11 22:12:04 +00006547 WithColor::error(errs(), "llvm-objdump")
6548 << "can't create temporary xar archive " << XarFilename << "\n";
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006549 return;
6550 }
6551
6552 SmallString<128> TocFilename;
6553 std::error_code TocEC =
6554 sys::fs::createTemporaryFile("llvm-objdump", "toc", TocFilename);
6555 if (TocEC) {
Jonas Devliegheree787efd2018-11-11 22:12:04 +00006556 WithColor::error(errs(), "llvm-objdump") << TocEC.message() << "\n";
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006557 return;
6558 }
6559 xar_serialize(xar, TocFilename.c_str());
6560
6561 if (PrintXarFileHeaders) {
6562 if (!XarMemberName.empty())
6563 outs() << "In xar member " << XarMemberName << ": ";
6564 else
6565 outs() << "For (__LLVM,__bundle) section: ";
6566 outs() << "xar archive files:\n";
6567 PrintXarFilesSummary(XarFilename.c_str(), xar);
6568 }
6569
6570 ErrorOr<std::unique_ptr<MemoryBuffer>> FileOrErr =
6571 MemoryBuffer::getFileOrSTDIN(TocFilename.c_str());
6572 if (std::error_code EC = FileOrErr.getError()) {
Jonas Devliegheree787efd2018-11-11 22:12:04 +00006573 WithColor::error(errs(), "llvm-objdump") << EC.message() << "\n";
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006574 return;
6575 }
6576 std::unique_ptr<MemoryBuffer> &Buffer = FileOrErr.get();
6577
6578 if (!XarMemberName.empty())
6579 outs() << "In xar member " << XarMemberName << ": ";
6580 else
6581 outs() << "For (__LLVM,__bundle) section: ";
6582 outs() << "xar table of contents:\n";
6583 outs() << Buffer->getBuffer() << "\n";
6584
6585 // TODO: Go through the xar's files.
Francis Ricci6f942972017-10-06 15:33:28 +00006586 ScopedXarIter xi;
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006587 if(!xi){
Jonas Devliegheree787efd2018-11-11 22:12:04 +00006588 WithColor::error(errs(), "llvm-objdump")
6589 << "can't obtain an xar iterator for xar archive "
6590 << XarFilename.c_str() << "\n";
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006591 return;
6592 }
6593 for(xar_file_t xf = xar_file_first(xar, xi); xf; xf = xar_file_next(xi)){
6594 const char *key;
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006595 const char *member_name, *member_type, *member_size_string;
6596 size_t member_size;
6597
Francis Ricci6f942972017-10-06 15:33:28 +00006598 ScopedXarIter xp;
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006599 if(!xp){
Jonas Devliegheree787efd2018-11-11 22:12:04 +00006600 WithColor::error(errs(), "llvm-objdump")
6601 << "can't obtain an xar iterator for xar archive "
6602 << XarFilename.c_str() << "\n";
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006603 return;
6604 }
6605 member_name = NULL;
6606 member_type = NULL;
6607 member_size_string = NULL;
6608 for(key = xar_prop_first(xf, xp); key; key = xar_prop_next(xp)){
Jonas Devliegherec0a758d2017-09-18 14:15:57 +00006609 const char *val = nullptr;
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006610 xar_prop_get(xf, key, &val);
6611#if 0 // Useful for debugging.
6612 outs() << "key: " << key << " value: " << val << "\n";
6613#endif
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +00006614 if (strcmp(key, "name") == 0)
6615 member_name = val;
6616 if (strcmp(key, "type") == 0)
6617 member_type = val;
6618 if (strcmp(key, "data/size") == 0)
6619 member_size_string = val;
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006620 }
6621 /*
6622 * If we find a file with a name, date/size and type properties
6623 * and with the type being "file" see if that is a xar file.
6624 */
6625 if (member_name != NULL && member_type != NULL &&
6626 strcmp(member_type, "file") == 0 &&
6627 member_size_string != NULL){
6628 // Extract the file into a buffer.
6629 char *endptr;
6630 member_size = strtoul(member_size_string, &endptr, 10);
6631 if (*endptr == '\0' && member_size != 0) {
Francis Ricci1bae0ac2017-09-13 13:57:45 +00006632 char *buffer;
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +00006633 if (xar_extract_tobuffersz(xar, xf, &buffer, &member_size) == 0) {
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006634#if 0 // Useful for debugging.
NAKAMURA Takumi6f43bd42017-10-18 13:31:28 +00006635 outs() << "xar member: " << member_name << " extracted\n";
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006636#endif
6637 // Set the XarMemberName we want to see printed in the header.
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +00006638 std::string OldXarMemberName;
6639 // If XarMemberName is already set this is nested. So
6640 // save the old name and create the nested name.
6641 if (!XarMemberName.empty()) {
6642 OldXarMemberName = XarMemberName;
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006643 XarMemberName =
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +00006644 (Twine("[") + XarMemberName + "]" + member_name).str();
6645 } else {
6646 OldXarMemberName = "";
6647 XarMemberName = member_name;
6648 }
6649 // See if this is could be a xar file (nested).
6650 if (member_size >= sizeof(struct xar_header)) {
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006651#if 0 // Useful for debugging.
NAKAMURA Takumi6f43bd42017-10-18 13:31:28 +00006652 outs() << "could be a xar file: " << member_name << "\n";
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006653#endif
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +00006654 memcpy((char *)&XarHeader, buffer, sizeof(struct xar_header));
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006655 if (sys::IsLittleEndianHost)
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +00006656 swapStruct(XarHeader);
6657 if (XarHeader.magic == XAR_HEADER_MAGIC)
6658 DumpBitcodeSection(O, buffer, member_size, verbose,
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006659 PrintXarHeader, PrintXarFileHeaders,
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +00006660 XarMemberName);
6661 }
6662 XarMemberName = OldXarMemberName;
Francis Ricci1bae0ac2017-09-13 13:57:45 +00006663 delete buffer;
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +00006664 }
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006665 }
6666 }
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006667 }
Kevin Enderby9873e2c2016-05-23 21:34:12 +00006668}
6669#endif // defined(HAVE_LIBXAR)
6670
Kevin Enderby0fc11822015-04-01 20:57:01 +00006671static void printObjcMetaData(MachOObjectFile *O, bool verbose) {
6672 if (O->is64Bit())
6673 printObjc2_64bit_MetaData(O, verbose);
6674 else {
6675 MachO::mach_header H;
6676 H = O->getHeader();
6677 if (H.cputype == MachO::CPU_TYPE_ARM)
6678 printObjc2_32bit_MetaData(O, verbose);
6679 else {
6680 // This is the 32-bit non-arm cputype case. Which is normally
6681 // the first Objective-C ABI. But it may be the case of a
6682 // binary for the iOS simulator which is the second Objective-C
6683 // ABI. In that case printObjc1_32bit_MetaData() will determine that
6684 // and return false.
Hans Wennborgcc9deb42015-09-29 18:02:48 +00006685 if (!printObjc1_32bit_MetaData(O, verbose))
Kevin Enderby0fc11822015-04-01 20:57:01 +00006686 printObjc2_32bit_MetaData(O, verbose);
6687 }
6688 }
6689}
6690
Kevin Enderbybf246f52014-09-24 23:08:22 +00006691// GuessLiteralPointer returns a string which for the item in the Mach-O file
6692// for the address passed in as ReferenceValue for printing as a comment with
6693// the instruction and also returns the corresponding type of that item
6694// indirectly through ReferenceType.
6695//
6696// If ReferenceValue is an address of literal cstring then a pointer to the
6697// cstring is returned and ReferenceType is set to
6698// LLVMDisassembler_ReferenceType_Out_LitPool_CstrAddr .
6699//
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006700// If ReferenceValue is an address of an Objective-C CFString, Selector ref or
6701// Class ref that name is returned and the ReferenceType is set accordingly.
6702//
6703// Lastly, literals which are Symbol address in a literal pool are looked for
6704// and if found the symbol name is returned and ReferenceType is set to
6705// LLVMDisassembler_ReferenceType_Out_LitPool_SymAddr .
6706//
6707// If there is no item in the Mach-O file for the address passed in as
6708// ReferenceValue nullptr is returned and ReferenceType is unchanged.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00006709static const char *GuessLiteralPointer(uint64_t ReferenceValue,
6710 uint64_t ReferencePC,
6711 uint64_t *ReferenceType,
6712 struct DisassembleInfo *info) {
Kevin Enderbybf246f52014-09-24 23:08:22 +00006713 // First see if there is an external relocation entry at the ReferencePC.
Kevin Enderbyd90a4172015-10-10 00:05:01 +00006714 if (info->O->getHeader().filetype == MachO::MH_OBJECT) {
6715 uint64_t sect_addr = info->S.getAddress();
6716 uint64_t sect_offset = ReferencePC - sect_addr;
6717 bool reloc_found = false;
6718 DataRefImpl Rel;
6719 MachO::any_relocation_info RE;
6720 bool isExtern = false;
6721 SymbolRef Symbol;
6722 for (const RelocationRef &Reloc : info->S.relocations()) {
6723 uint64_t RelocOffset = Reloc.getOffset();
6724 if (RelocOffset == sect_offset) {
6725 Rel = Reloc.getRawDataRefImpl();
6726 RE = info->O->getRelocation(Rel);
6727 if (info->O->isRelocationScattered(RE))
6728 continue;
6729 isExtern = info->O->getPlainRelocationExternal(RE);
6730 if (isExtern) {
6731 symbol_iterator RelocSym = Reloc.getSymbol();
6732 Symbol = *RelocSym;
6733 }
6734 reloc_found = true;
6735 break;
Kevin Enderbybf246f52014-09-24 23:08:22 +00006736 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00006737 }
Kevin Enderbyd90a4172015-10-10 00:05:01 +00006738 // If there is an external relocation entry for a symbol in a section
6739 // then used that symbol's value for the value of the reference.
6740 if (reloc_found && isExtern) {
6741 if (info->O->getAnyRelocationPCRel(RE)) {
6742 unsigned Type = info->O->getAnyRelocationType(RE);
6743 if (Type == MachO::X86_64_RELOC_SIGNED) {
6744 ReferenceValue = Symbol.getValue();
6745 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00006746 }
6747 }
6748 }
6749
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006750 // Look for literals such as Objective-C CFStrings refs, Selector refs,
6751 // Message refs and Class refs.
6752 bool classref, selref, msgref, cfstring;
6753 uint64_t pointer_value = GuessPointerPointer(ReferenceValue, info, classref,
6754 selref, msgref, cfstring);
David Blaikie33dd45d02015-03-23 18:39:02 +00006755 if (classref && pointer_value == 0) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006756 // Note the ReferenceValue is a pointer into the __objc_classrefs section.
6757 // And the pointer_value in that section is typically zero as it will be
6758 // set by dyld as part of the "bind information".
6759 const char *name = get_dyld_bind_info_symbolname(ReferenceValue, info);
6760 if (name != nullptr) {
6761 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Class_Ref;
Hans Wennborgdb53e302014-10-23 21:59:17 +00006762 const char *class_name = strrchr(name, '$');
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006763 if (class_name != nullptr && class_name[1] == '_' &&
6764 class_name[2] != '\0') {
6765 info->class_name = class_name + 2;
6766 return name;
6767 }
6768 }
6769 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00006770
David Blaikie33dd45d02015-03-23 18:39:02 +00006771 if (classref) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006772 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Class_Ref;
6773 const char *name =
6774 get_objc2_64bit_class_name(pointer_value, ReferenceValue, info);
6775 if (name != nullptr)
6776 info->class_name = name;
6777 else
6778 name = "bad class ref";
Kevin Enderbybf246f52014-09-24 23:08:22 +00006779 return name;
6780 }
6781
David Blaikie33dd45d02015-03-23 18:39:02 +00006782 if (cfstring) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006783 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_CFString_Ref;
6784 const char *name = get_objc2_64bit_cfstring_name(ReferenceValue, info);
6785 return name;
6786 }
6787
David Blaikie33dd45d02015-03-23 18:39:02 +00006788 if (selref && pointer_value == 0)
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006789 pointer_value = get_objc2_64bit_selref(ReferenceValue, info);
6790
6791 if (pointer_value != 0)
6792 ReferenceValue = pointer_value;
6793
6794 const char *name = GuessCstringPointer(ReferenceValue, info);
6795 if (name) {
David Blaikie33dd45d02015-03-23 18:39:02 +00006796 if (pointer_value != 0 && selref) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006797 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Selector_Ref;
6798 info->selector_name = name;
David Blaikie33dd45d02015-03-23 18:39:02 +00006799 } else if (pointer_value != 0 && msgref) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006800 info->class_name = nullptr;
6801 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message_Ref;
6802 info->selector_name = name;
6803 } else
6804 *ReferenceType = LLVMDisassembler_ReferenceType_Out_LitPool_CstrAddr;
6805 return name;
6806 }
6807
6808 // Lastly look for an indirect symbol with this ReferenceValue which is in
6809 // a literal pool. If found return that symbol name.
6810 name = GuessIndirectSymbol(ReferenceValue, info);
6811 if (name) {
6812 *ReferenceType = LLVMDisassembler_ReferenceType_Out_LitPool_SymAddr;
6813 return name;
6814 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00006815
6816 return nullptr;
6817}
6818
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006819// SymbolizerSymbolLookUp is the symbol lookup function passed when creating
Kevin Enderbybf246f52014-09-24 23:08:22 +00006820// the Symbolizer. It looks up the ReferenceValue using the info passed via the
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006821// pointer to the struct DisassembleInfo that was passed when MCSymbolizer
6822// is created and returns the symbol name that matches the ReferenceValue or
6823// nullptr if none. The ReferenceType is passed in for the IN type of
6824// reference the instruction is making from the values in defined in the header
6825// "llvm-c/Disassembler.h". On return the ReferenceType can set to a specific
6826// Out type and the ReferenceName will also be set which is added as a comment
6827// to the disassembled instruction.
6828//
Kevin Enderby04bf6932014-10-28 23:39:46 +00006829// If the symbol name is a C++ mangled name then the demangled name is
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006830// returned through ReferenceName and ReferenceType is set to
6831// LLVMDisassembler_ReferenceType_DeMangled_Name .
6832//
6833// When this is called to get a symbol name for a branch target then the
6834// ReferenceType will be LLVMDisassembler_ReferenceType_In_Branch and then
6835// SymbolValue will be looked for in the indirect symbol table to determine if
6836// it is an address for a symbol stub. If so then the symbol name for that
6837// stub is returned indirectly through ReferenceName and then ReferenceType is
6838// set to LLVMDisassembler_ReferenceType_Out_SymbolStub.
6839//
Kevin Enderbybf246f52014-09-24 23:08:22 +00006840// When this is called with an value loaded via a PC relative load then
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006841// ReferenceType will be LLVMDisassembler_ReferenceType_In_PCrel_Load then the
6842// SymbolValue is checked to be an address of literal pointer, symbol pointer,
6843// or an Objective-C meta data reference. If so the output ReferenceType is
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006844// set to correspond to that as well as setting the ReferenceName.
Benjamin Kramerf044d3f2015-03-09 16:23:46 +00006845static const char *SymbolizerSymbolLookUp(void *DisInfo,
6846 uint64_t ReferenceValue,
6847 uint64_t *ReferenceType,
6848 uint64_t ReferencePC,
6849 const char **ReferenceName) {
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006850 struct DisassembleInfo *info = (struct DisassembleInfo *)DisInfo;
Kevin Enderbybf246f52014-09-24 23:08:22 +00006851 // If no verbose symbolic information is wanted then just return nullptr.
David Blaikie33dd45d02015-03-23 18:39:02 +00006852 if (!info->verbose) {
Kevin Enderbybf246f52014-09-24 23:08:22 +00006853 *ReferenceName = nullptr;
6854 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00006855 return nullptr;
6856 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00006857
Kevin Enderbyf6d25852015-01-31 00:37:11 +00006858 const char *SymbolName = GuessSymbolName(ReferenceValue, info->AddrMap);
Kevin Enderbybf246f52014-09-24 23:08:22 +00006859
Kevin Enderby85974882014-09-26 22:20:44 +00006860 if (*ReferenceType == LLVMDisassembler_ReferenceType_In_Branch) {
6861 *ReferenceName = GuessIndirectSymbol(ReferenceValue, info);
Kevin Enderby04bf6932014-10-28 23:39:46 +00006862 if (*ReferenceName != nullptr) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006863 method_reference(info, ReferenceType, ReferenceName);
6864 if (*ReferenceType != LLVMDisassembler_ReferenceType_Out_Objc_Message)
6865 *ReferenceType = LLVMDisassembler_ReferenceType_Out_SymbolStub;
Rafael Espindolab940b662016-09-06 19:16:48 +00006866 } else if (SymbolName != nullptr && strncmp(SymbolName, "__Z", 3) == 0) {
Kevin Enderby04bf6932014-10-28 23:39:46 +00006867 if (info->demangled_name != nullptr)
6868 free(info->demangled_name);
6869 int status;
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006870 info->demangled_name =
Rafael Espindolab940b662016-09-06 19:16:48 +00006871 itaniumDemangle(SymbolName + 1, nullptr, nullptr, &status);
Kevin Enderby04bf6932014-10-28 23:39:46 +00006872 if (info->demangled_name != nullptr) {
6873 *ReferenceName = info->demangled_name;
6874 *ReferenceType = LLVMDisassembler_ReferenceType_DeMangled_Name;
6875 } else
6876 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
6877 } else
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006878 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
6879 } else if (*ReferenceType == LLVMDisassembler_ReferenceType_In_PCrel_Load) {
6880 *ReferenceName =
6881 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
Kevin Enderby85974882014-09-26 22:20:44 +00006882 if (*ReferenceName)
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006883 method_reference(info, ReferenceType, ReferenceName);
Kevin Enderby85974882014-09-26 22:20:44 +00006884 else
6885 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
Kevin Enderbyae3c1262014-11-14 21:52:18 +00006886 // If this is arm64 and the reference is an adrp instruction save the
6887 // instruction, passed in ReferenceValue and the address of the instruction
6888 // for use later if we see and add immediate instruction.
6889 } else if (info->O->getArch() == Triple::aarch64 &&
6890 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADRP) {
6891 info->adrp_inst = ReferenceValue;
6892 info->adrp_addr = ReferencePC;
6893 SymbolName = nullptr;
6894 *ReferenceName = nullptr;
6895 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
6896 // If this is arm64 and reference is an add immediate instruction and we
6897 // have
6898 // seen an adrp instruction just before it and the adrp's Xd register
6899 // matches
6900 // this add's Xn register reconstruct the value being referenced and look to
6901 // see if it is a literal pointer. Note the add immediate instruction is
6902 // passed in ReferenceValue.
6903 } else if (info->O->getArch() == Triple::aarch64 &&
6904 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADDXri &&
6905 ReferencePC - 4 == info->adrp_addr &&
6906 (info->adrp_inst & 0x9f000000) == 0x90000000 &&
6907 (info->adrp_inst & 0x1f) == ((ReferenceValue >> 5) & 0x1f)) {
6908 uint32_t addxri_inst;
6909 uint64_t adrp_imm, addxri_imm;
6910
6911 adrp_imm =
6912 ((info->adrp_inst & 0x00ffffe0) >> 3) | ((info->adrp_inst >> 29) & 0x3);
6913 if (info->adrp_inst & 0x0200000)
6914 adrp_imm |= 0xfffffffffc000000LL;
6915
6916 addxri_inst = ReferenceValue;
6917 addxri_imm = (addxri_inst >> 10) & 0xfff;
6918 if (((addxri_inst >> 22) & 0x3) == 1)
6919 addxri_imm <<= 12;
6920
6921 ReferenceValue = (info->adrp_addr & 0xfffffffffffff000LL) +
6922 (adrp_imm << 12) + addxri_imm;
6923
6924 *ReferenceName =
6925 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
6926 if (*ReferenceName == nullptr)
6927 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
6928 // If this is arm64 and the reference is a load register instruction and we
6929 // have seen an adrp instruction just before it and the adrp's Xd register
6930 // matches this add's Xn register reconstruct the value being referenced and
6931 // look to see if it is a literal pointer. Note the load register
6932 // instruction is passed in ReferenceValue.
6933 } else if (info->O->getArch() == Triple::aarch64 &&
6934 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_LDRXui &&
6935 ReferencePC - 4 == info->adrp_addr &&
6936 (info->adrp_inst & 0x9f000000) == 0x90000000 &&
6937 (info->adrp_inst & 0x1f) == ((ReferenceValue >> 5) & 0x1f)) {
6938 uint32_t ldrxui_inst;
6939 uint64_t adrp_imm, ldrxui_imm;
6940
6941 adrp_imm =
6942 ((info->adrp_inst & 0x00ffffe0) >> 3) | ((info->adrp_inst >> 29) & 0x3);
6943 if (info->adrp_inst & 0x0200000)
6944 adrp_imm |= 0xfffffffffc000000LL;
6945
6946 ldrxui_inst = ReferenceValue;
6947 ldrxui_imm = (ldrxui_inst >> 10) & 0xfff;
6948
6949 ReferenceValue = (info->adrp_addr & 0xfffffffffffff000LL) +
6950 (adrp_imm << 12) + (ldrxui_imm << 3);
6951
6952 *ReferenceName =
6953 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
6954 if (*ReferenceName == nullptr)
6955 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
6956 }
6957 // If this arm64 and is an load register (PC-relative) instruction the
6958 // ReferenceValue is the PC plus the immediate value.
6959 else if (info->O->getArch() == Triple::aarch64 &&
6960 (*ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_LDRXl ||
6961 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADR)) {
6962 *ReferenceName =
6963 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
6964 if (*ReferenceName == nullptr)
6965 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
Rafael Espindolab940b662016-09-06 19:16:48 +00006966 } else if (SymbolName != nullptr && strncmp(SymbolName, "__Z", 3) == 0) {
Kevin Enderby04bf6932014-10-28 23:39:46 +00006967 if (info->demangled_name != nullptr)
6968 free(info->demangled_name);
6969 int status;
Kevin Enderbyb28ed012014-10-29 21:28:24 +00006970 info->demangled_name =
Rafael Espindolab940b662016-09-06 19:16:48 +00006971 itaniumDemangle(SymbolName + 1, nullptr, nullptr, &status);
Kevin Enderby04bf6932014-10-28 23:39:46 +00006972 if (info->demangled_name != nullptr) {
6973 *ReferenceName = info->demangled_name;
6974 *ReferenceType = LLVMDisassembler_ReferenceType_DeMangled_Name;
6975 }
6976 }
Kevin Enderby6f326ce2014-10-23 19:37:31 +00006977 else {
Kevin Enderbybf246f52014-09-24 23:08:22 +00006978 *ReferenceName = nullptr;
6979 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
6980 }
6981
6982 return SymbolName;
6983}
6984
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00006985/// Emits the comments that are stored in the CommentStream.
Kevin Enderbybf246f52014-09-24 23:08:22 +00006986/// Each comment in the CommentStream must end with a newline.
6987static void emitComments(raw_svector_ostream &CommentStream,
6988 SmallString<128> &CommentsToEmit,
6989 formatted_raw_ostream &FormattedOS,
6990 const MCAsmInfo &MAI) {
6991 // Flush the stream before taking its content.
Kevin Enderbybf246f52014-09-24 23:08:22 +00006992 StringRef Comments = CommentsToEmit.str();
6993 // Get the default information for printing a comment.
Mehdi Amini36d33fc2016-10-01 06:46:33 +00006994 StringRef CommentBegin = MAI.getCommentString();
Kevin Enderbybf246f52014-09-24 23:08:22 +00006995 unsigned CommentColumn = MAI.getCommentColumn();
6996 bool IsFirst = true;
6997 while (!Comments.empty()) {
6998 if (!IsFirst)
6999 FormattedOS << '\n';
7000 // Emit a line of comments.
7001 FormattedOS.PadToColumn(CommentColumn);
7002 size_t Position = Comments.find('\n');
7003 FormattedOS << CommentBegin << ' ' << Comments.substr(0, Position);
7004 // Move after the newline character.
7005 Comments = Comments.substr(Position + 1);
7006 IsFirst = false;
7007 }
7008 FormattedOS.flush();
7009
7010 // Tell the comment stream that the vector changed underneath it.
7011 CommentsToEmit.clear();
Kevin Enderby98c9acc2014-09-16 18:00:57 +00007012}
7013
Kevin Enderby95df54c2015-02-04 01:01:38 +00007014static void DisassembleMachO(StringRef Filename, MachOObjectFile *MachOOF,
7015 StringRef DisSegName, StringRef DisSectName) {
Kevin Enderbyec5ca032014-08-18 20:21:02 +00007016 const char *McpuDefault = nullptr;
7017 const Target *ThumbTarget = nullptr;
7018 const Target *TheTarget = GetTarget(MachOOF, &McpuDefault, &ThumbTarget);
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007019 if (!TheTarget) {
7020 // GetTarget prints out stuff.
7021 return;
7022 }
Kevin Enderbyf310e622017-09-21 21:45:02 +00007023 std::string MachOMCPU;
Kevin Enderbyec5ca032014-08-18 20:21:02 +00007024 if (MCPU.empty() && McpuDefault)
Kevin Enderbyf310e622017-09-21 21:45:02 +00007025 MachOMCPU = McpuDefault;
7026 else
7027 MachOMCPU = MCPU;
Kevin Enderbyec5ca032014-08-18 20:21:02 +00007028
Ahmed Charles56440fd2014-03-06 05:51:42 +00007029 std::unique_ptr<const MCInstrInfo> InstrInfo(TheTarget->createMCInstrInfo());
Kevin Enderbyec5ca032014-08-18 20:21:02 +00007030 std::unique_ptr<const MCInstrInfo> ThumbInstrInfo;
Kevin Enderbyae3c1262014-11-14 21:52:18 +00007031 if (ThumbTarget)
Kevin Enderbyec5ca032014-08-18 20:21:02 +00007032 ThumbInstrInfo.reset(ThumbTarget->createMCInstrInfo());
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007033
Kevin Enderbyc9595622014-08-06 23:24:41 +00007034 // Package up features to be passed to target/subtarget
7035 std::string FeaturesStr;
Jordan Rupprecht16a0de22018-12-20 00:57:06 +00007036 if (!MAttrs.empty()) {
Kevin Enderbyc9595622014-08-06 23:24:41 +00007037 SubtargetFeatures Features;
7038 for (unsigned i = 0; i != MAttrs.size(); ++i)
7039 Features.AddFeature(MAttrs[i]);
7040 FeaturesStr = Features.getString();
7041 }
7042
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007043 // Set up disassembler.
Ahmed Charles56440fd2014-03-06 05:51:42 +00007044 std::unique_ptr<const MCRegisterInfo> MRI(
7045 TheTarget->createMCRegInfo(TripleName));
7046 std::unique_ptr<const MCAsmInfo> AsmInfo(
Rafael Espindola227144c2013-05-13 01:16:13 +00007047 TheTarget->createMCAsmInfo(*MRI, TripleName));
Ahmed Charles56440fd2014-03-06 05:51:42 +00007048 std::unique_ptr<const MCSubtargetInfo> STI(
Kevin Enderbyf310e622017-09-21 21:45:02 +00007049 TheTarget->createMCSubtargetInfo(TripleName, MachOMCPU, FeaturesStr));
Craig Toppere6cb63e2014-04-25 04:24:47 +00007050 MCContext Ctx(AsmInfo.get(), MRI.get(), nullptr);
Kevin Enderby98c9acc2014-09-16 18:00:57 +00007051 std::unique_ptr<MCDisassembler> DisAsm(
Kevin Enderbyec5ca032014-08-18 20:21:02 +00007052 TheTarget->createMCDisassembler(*STI, Ctx));
Kevin Enderby98c9acc2014-09-16 18:00:57 +00007053 std::unique_ptr<MCSymbolizer> Symbolizer;
Serge Pavlove4e9a1f2018-02-14 03:26:27 +00007054 struct DisassembleInfo SymbolizerInfo(nullptr, nullptr, nullptr, false);
Kevin Enderby98c9acc2014-09-16 18:00:57 +00007055 std::unique_ptr<MCRelocationInfo> RelInfo(
7056 TheTarget->createMCRelocationInfo(TripleName, Ctx));
7057 if (RelInfo) {
7058 Symbolizer.reset(TheTarget->createMCSymbolizer(
7059 TripleName, SymbolizerGetOpInfo, SymbolizerSymbolLookUp,
David Blaikie186db432015-01-18 20:45:48 +00007060 &SymbolizerInfo, &Ctx, std::move(RelInfo)));
Kevin Enderby98c9acc2014-09-16 18:00:57 +00007061 DisAsm->setSymbolizer(std::move(Symbolizer));
7062 }
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007063 int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
Ahmed Charles56440fd2014-03-06 05:51:42 +00007064 std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
Daniel Sanders50f17232015-09-15 16:17:27 +00007065 Triple(TripleName), AsmPrinterVariant, *AsmInfo, *InstrInfo, *MRI));
Kevin Enderbybf246f52014-09-24 23:08:22 +00007066 // Set the display preference for hex vs. decimal immediates.
7067 IP->setPrintImmHex(PrintImmHex);
7068 // Comment stream and backing vector.
7069 SmallString<128> CommentsToEmit;
7070 raw_svector_ostream CommentStream(CommentsToEmit);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00007071 // FIXME: Setting the CommentStream in the InstPrinter is problematic in that
7072 // if it is done then arm64 comments for string literals don't get printed
7073 // and some constant get printed instead and not setting it causes intel
7074 // (32-bit and 64-bit) comments printed with different spacing before the
7075 // comment causing different diffs with the 'C' disassembler library API.
7076 // IP->setCommentStream(CommentStream);
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00007077
Kevin Enderbyae3c1262014-11-14 21:52:18 +00007078 if (!AsmInfo || !STI || !DisAsm || !IP) {
Jonas Devliegheree787efd2018-11-11 22:12:04 +00007079 WithColor::error(errs(), "llvm-objdump")
7080 << "couldn't initialize disassembler for target " << TripleName << '\n';
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007081 return;
7082 }
7083
Tim Northover09ca33e2016-04-22 23:23:31 +00007084 // Set up separate thumb disassembler if needed.
Kevin Enderbyec5ca032014-08-18 20:21:02 +00007085 std::unique_ptr<const MCRegisterInfo> ThumbMRI;
7086 std::unique_ptr<const MCAsmInfo> ThumbAsmInfo;
7087 std::unique_ptr<const MCSubtargetInfo> ThumbSTI;
Kevin Enderby930fdc72014-11-06 19:00:13 +00007088 std::unique_ptr<MCDisassembler> ThumbDisAsm;
Kevin Enderbyec5ca032014-08-18 20:21:02 +00007089 std::unique_ptr<MCInstPrinter> ThumbIP;
7090 std::unique_ptr<MCContext> ThumbCtx;
Kevin Enderby930fdc72014-11-06 19:00:13 +00007091 std::unique_ptr<MCSymbolizer> ThumbSymbolizer;
Serge Pavlove4e9a1f2018-02-14 03:26:27 +00007092 struct DisassembleInfo ThumbSymbolizerInfo(nullptr, nullptr, nullptr, false);
Kevin Enderby930fdc72014-11-06 19:00:13 +00007093 std::unique_ptr<MCRelocationInfo> ThumbRelInfo;
Kevin Enderbyec5ca032014-08-18 20:21:02 +00007094 if (ThumbTarget) {
7095 ThumbMRI.reset(ThumbTarget->createMCRegInfo(ThumbTripleName));
7096 ThumbAsmInfo.reset(
7097 ThumbTarget->createMCAsmInfo(*ThumbMRI, ThumbTripleName));
7098 ThumbSTI.reset(
Kevin Enderbyf310e622017-09-21 21:45:02 +00007099 ThumbTarget->createMCSubtargetInfo(ThumbTripleName, MachOMCPU,
7100 FeaturesStr));
Kevin Enderbyec5ca032014-08-18 20:21:02 +00007101 ThumbCtx.reset(new MCContext(ThumbAsmInfo.get(), ThumbMRI.get(), nullptr));
7102 ThumbDisAsm.reset(ThumbTarget->createMCDisassembler(*ThumbSTI, *ThumbCtx));
Kevin Enderby930fdc72014-11-06 19:00:13 +00007103 MCContext *PtrThumbCtx = ThumbCtx.get();
7104 ThumbRelInfo.reset(
7105 ThumbTarget->createMCRelocationInfo(ThumbTripleName, *PtrThumbCtx));
7106 if (ThumbRelInfo) {
7107 ThumbSymbolizer.reset(ThumbTarget->createMCSymbolizer(
7108 ThumbTripleName, SymbolizerGetOpInfo, SymbolizerSymbolLookUp,
David Blaikie186db432015-01-18 20:45:48 +00007109 &ThumbSymbolizerInfo, PtrThumbCtx, std::move(ThumbRelInfo)));
Kevin Enderby930fdc72014-11-06 19:00:13 +00007110 ThumbDisAsm->setSymbolizer(std::move(ThumbSymbolizer));
7111 }
Kevin Enderbyec5ca032014-08-18 20:21:02 +00007112 int ThumbAsmPrinterVariant = ThumbAsmInfo->getAssemblerDialect();
7113 ThumbIP.reset(ThumbTarget->createMCInstPrinter(
Daniel Sanders50f17232015-09-15 16:17:27 +00007114 Triple(ThumbTripleName), ThumbAsmPrinterVariant, *ThumbAsmInfo,
7115 *ThumbInstrInfo, *ThumbMRI));
Kevin Enderbybf246f52014-09-24 23:08:22 +00007116 // Set the display preference for hex vs. decimal immediates.
7117 ThumbIP->setPrintImmHex(PrintImmHex);
Kevin Enderbyec5ca032014-08-18 20:21:02 +00007118 }
7119
Kevin Enderbyae3c1262014-11-14 21:52:18 +00007120 if (ThumbTarget && (!ThumbAsmInfo || !ThumbSTI || !ThumbDisAsm || !ThumbIP)) {
Jonas Devliegheree787efd2018-11-11 22:12:04 +00007121 WithColor::error(errs(), "llvm-objdump")
7122 << "couldn't initialize disassembler for target " << ThumbTripleName
7123 << '\n';
Kevin Enderbyec5ca032014-08-18 20:21:02 +00007124 return;
7125 }
7126
Charles Davis8bdfafd2013-09-01 04:28:48 +00007127 MachO::mach_header Header = MachOOF->getHeader();
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007128
Ahmed Bougachaaa790682013-05-24 01:07:04 +00007129 // FIXME: Using the -cfg command line option, this code used to be able to
7130 // annotate relocations with the referenced symbol's name, and if this was
7131 // inside a __[cf]string section, the data it points to. This is now replaced
7132 // by the upcoming MCSymbolizer, which needs the appropriate setup done above.
Owen Andersond9243c42011-10-17 21:37:35 +00007133 std::vector<SectionRef> Sections;
7134 std::vector<SymbolRef> Symbols;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007135 SmallVector<uint64_t, 8> FoundFns;
Kevin Enderby273ae012013-06-06 17:20:50 +00007136 uint64_t BaseSegmentAddress;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007137
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00007138 getSectionsAndSymbols(MachOOF, Sections, Symbols, FoundFns,
Kevin Enderby273ae012013-06-06 17:20:50 +00007139 BaseSegmentAddress);
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007140
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007141 // Sort the symbols by address, just in case they didn't come in that way.
Fangrui Song0cac7262018-09-27 02:13:45 +00007142 llvm::sort(Symbols, SymbolSorter());
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007143
Kevin Enderby273ae012013-06-06 17:20:50 +00007144 // Build a data in code table that is sorted on by the address of each entry.
7145 uint64_t BaseAddress = 0;
Charles Davis8bdfafd2013-09-01 04:28:48 +00007146 if (Header.filetype == MachO::MH_OBJECT)
Rafael Espindola80291272014-10-08 15:28:58 +00007147 BaseAddress = Sections[0].getAddress();
Kevin Enderby273ae012013-06-06 17:20:50 +00007148 else
7149 BaseAddress = BaseSegmentAddress;
7150 DiceTable Dices;
Kevin Enderby273ae012013-06-06 17:20:50 +00007151 for (dice_iterator DI = MachOOF->begin_dices(), DE = MachOOF->end_dices();
Rafael Espindola5e812af2014-01-30 02:49:50 +00007152 DI != DE; ++DI) {
Kevin Enderby273ae012013-06-06 17:20:50 +00007153 uint32_t Offset;
7154 DI->getOffset(Offset);
7155 Dices.push_back(std::make_pair(BaseAddress + Offset, *DI));
7156 }
7157 array_pod_sort(Dices.begin(), Dices.end());
7158
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007159#ifndef NDEBUG
7160 raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls();
7161#else
7162 raw_ostream &DebugOut = nulls();
7163#endif
7164
Ahmed Charles56440fd2014-03-06 05:51:42 +00007165 std::unique_ptr<DIContext> diContext;
Rafael Espindola9b709252013-04-13 01:45:40 +00007166 ObjectFile *DbgObj = MachOOF;
Francis Visoiu Mistrih8e864be2018-08-31 13:10:54 +00007167 std::unique_ptr<MemoryBuffer> DSYMBuf;
Benjamin Kramer699128e2011-09-21 01:13:19 +00007168 // Try to find debug info and set up the DIContext for it.
7169 if (UseDbg) {
Benjamin Kramer699128e2011-09-21 01:13:19 +00007170 // A separate DSym file path was specified, parse it as a macho file,
7171 // get the sections and supply it to the section name parsing machinery.
7172 if (!DSYMFile.empty()) {
Rafael Espindola48af1c22014-08-19 18:44:46 +00007173 ErrorOr<std::unique_ptr<MemoryBuffer>> BufOrErr =
Rafael Espindolaadf21f22014-07-06 17:43:13 +00007174 MemoryBuffer::getFileOrSTDIN(DSYMFile);
Rafael Espindola48af1c22014-08-19 18:44:46 +00007175 if (std::error_code EC = BufOrErr.getError()) {
Fangrui Songe7834bd2019-04-07 08:19:55 +00007176 report_error(errorCodeToError(EC), DSYMFile);
Benjamin Kramer699128e2011-09-21 01:13:19 +00007177 return;
7178 }
Francis Visoiu Mistrihb8819dc2019-01-10 17:36:54 +00007179
Fangrui Songe7834bd2019-04-07 08:19:55 +00007180 std::unique_ptr<MachOObjectFile> DbgObjCheck = unwrapOrError(
7181 ObjectFile::createMachOObjectFile(BufOrErr.get()->getMemBufferRef()),
7182 DSYMFile.getValue());
7183 DbgObj = DbgObjCheck.release();
Francis Visoiu Mistrih8e864be2018-08-31 13:10:54 +00007184 // We need to keep the file alive, because we're replacing DbgObj with it.
7185 DSYMBuf = std::move(BufOrErr.get());
Benjamin Kramer699128e2011-09-21 01:13:19 +00007186 }
7187
Eric Christopher7370b552012-11-12 21:40:38 +00007188 // Setup the DIContext
Rafael Espindolac398e672017-07-19 22:27:28 +00007189 diContext = DWARFContext::create(*DbgObj);
Benjamin Kramer699128e2011-09-21 01:13:19 +00007190 }
7191
Jordan Rupprecht16a0de22018-12-20 00:57:06 +00007192 if (FilterSections.empty())
Kevin Enderby95df54c2015-02-04 01:01:38 +00007193 outs() << "(" << DisSegName << "," << DisSectName << ") section\n";
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00007194
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007195 for (unsigned SectIdx = 0; SectIdx != Sections.size(); SectIdx++) {
Owen Andersond9243c42011-10-17 21:37:35 +00007196 StringRef SectName;
Kevin Enderby95df54c2015-02-04 01:01:38 +00007197 if (Sections[SectIdx].getName(SectName) || SectName != DisSectName)
7198 continue;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007199
Rafael Espindolaa9f810b2012-12-21 03:47:03 +00007200 DataRefImpl DR = Sections[SectIdx].getRawDataRefImpl();
Ahmed Bougachaaa790682013-05-24 01:07:04 +00007201
Rafael Espindolab0f76a42013-04-05 15:15:22 +00007202 StringRef SegmentName = MachOOF->getSectionFinalSegmentName(DR);
Kevin Enderby95df54c2015-02-04 01:01:38 +00007203 if (SegmentName != DisSegName)
Rafael Espindolaa9f810b2012-12-21 03:47:03 +00007204 continue;
7205
Rafael Espindola7fc5b872014-11-12 02:04:27 +00007206 StringRef BytesStr;
7207 Sections[SectIdx].getContents(BytesStr);
Fangrui Song6a0746a2019-04-07 03:58:42 +00007208 ArrayRef<uint8_t> Bytes = arrayRefFromStringRef(BytesStr);
Rafael Espindola80291272014-10-08 15:28:58 +00007209 uint64_t SectAddress = Sections[SectIdx].getAddress();
Rafael Espindolabd604f22014-11-07 00:52:15 +00007210
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007211 bool symbolTableWorked = false;
7212
Kevin Enderbybf246f52014-09-24 23:08:22 +00007213 // Create a map of symbol addresses to symbol names for use by
7214 // the SymbolizerSymbolLookUp() routine.
7215 SymbolAddressMap AddrMap;
Kevin Enderby6a221752015-03-17 17:10:57 +00007216 bool DisSymNameFound = false;
Kevin Enderbybf246f52014-09-24 23:08:22 +00007217 for (const SymbolRef &Symbol : MachOOF->symbols()) {
Fangrui Songe7834bd2019-04-07 08:19:55 +00007218 SymbolRef::Type ST =
7219 unwrapOrError(Symbol.getType(), MachOOF->getFileName());
Kevin Enderbybf246f52014-09-24 23:08:22 +00007220 if (ST == SymbolRef::ST_Function || ST == SymbolRef::ST_Data ||
7221 ST == SymbolRef::ST_Other) {
Rafael Espindoladea00162015-07-03 17:44:18 +00007222 uint64_t Address = Symbol.getValue();
Fangrui Songe7834bd2019-04-07 08:19:55 +00007223 StringRef SymName =
7224 unwrapOrError(Symbol.getName(), MachOOF->getFileName());
Kevin Enderbybf246f52014-09-24 23:08:22 +00007225 AddrMap[Address] = SymName;
Kevin Enderby6a221752015-03-17 17:10:57 +00007226 if (!DisSymName.empty() && DisSymName == SymName)
7227 DisSymNameFound = true;
Kevin Enderbybf246f52014-09-24 23:08:22 +00007228 }
7229 }
David Blaikie33dd45d02015-03-23 18:39:02 +00007230 if (!DisSymName.empty() && !DisSymNameFound) {
Kevin Enderby6a221752015-03-17 17:10:57 +00007231 outs() << "Can't find -dis-symname: " << DisSymName << "\n";
7232 return;
7233 }
Kevin Enderby98c9acc2014-09-16 18:00:57 +00007234 // Set up the block of info used by the Symbolizer call backs.
Kevin Enderby8e29ec92015-03-17 22:26:11 +00007235 SymbolizerInfo.verbose = !NoSymbolicOperands;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00007236 SymbolizerInfo.O = MachOOF;
7237 SymbolizerInfo.S = Sections[SectIdx];
Kevin Enderbybf246f52014-09-24 23:08:22 +00007238 SymbolizerInfo.AddrMap = &AddrMap;
Kevin Enderby6f326ce2014-10-23 19:37:31 +00007239 SymbolizerInfo.Sections = &Sections;
Kevin Enderby930fdc72014-11-06 19:00:13 +00007240 // Same for the ThumbSymbolizer
Kevin Enderby8e29ec92015-03-17 22:26:11 +00007241 ThumbSymbolizerInfo.verbose = !NoSymbolicOperands;
Kevin Enderby930fdc72014-11-06 19:00:13 +00007242 ThumbSymbolizerInfo.O = MachOOF;
7243 ThumbSymbolizerInfo.S = Sections[SectIdx];
7244 ThumbSymbolizerInfo.AddrMap = &AddrMap;
7245 ThumbSymbolizerInfo.Sections = &Sections;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00007246
Kevin Enderby4b627be2016-04-28 20:14:13 +00007247 unsigned int Arch = MachOOF->getArch();
7248
Tim Northoverf203ab52016-07-14 22:13:32 +00007249 // Skip all symbols if this is a stubs file.
Jordan Rupprecht16a0de22018-12-20 00:57:06 +00007250 if (Bytes.empty())
Tim Northoverf203ab52016-07-14 22:13:32 +00007251 return;
7252
Kevin Enderbyc138da32017-02-06 18:43:18 +00007253 // If the section has symbols but no symbol at the start of the section
7254 // these are used to make sure the bytes before the first symbol are
7255 // disassembled.
7256 bool FirstSymbol = true;
7257 bool FirstSymbolAtSectionStart = true;
7258
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00007259 // Disassemble symbol by symbol.
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007260 for (unsigned SymIdx = 0; SymIdx != Symbols.size(); SymIdx++) {
Fangrui Songe7834bd2019-04-07 08:19:55 +00007261 StringRef SymName =
7262 unwrapOrError(Symbols[SymIdx].getName(), MachOOF->getFileName());
7263 SymbolRef::Type ST =
7264 unwrapOrError(Symbols[SymIdx].getType(), MachOOF->getFileName());
Kuba Breckade833222015-11-12 09:40:29 +00007265 if (ST != SymbolRef::ST_Function && ST != SymbolRef::ST_Data)
Owen Andersond9243c42011-10-17 21:37:35 +00007266 continue;
7267
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00007268 // Make sure the symbol is defined in this section.
Rafael Espindola80291272014-10-08 15:28:58 +00007269 bool containsSym = Sections[SectIdx].containsSymbol(Symbols[SymIdx]);
Kevin Enderbyd8a6e832016-06-15 21:14:01 +00007270 if (!containsSym) {
7271 if (!DisSymName.empty() && DisSymName == SymName) {
7272 outs() << "-dis-symname: " << DisSymName << " not in the section\n";
7273 return;
NAKAMURA Takumia1e97a72017-08-28 06:47:47 +00007274 }
Kevin Enderbyd8a6e832016-06-15 21:14:01 +00007275 continue;
7276 }
7277 // The __mh_execute_header is special and we need to deal with that fact
7278 // this symbol is before the start of the (__TEXT,__text) section and at the
7279 // address of the start of the __TEXT segment. This is because this symbol
7280 // is an N_SECT symbol in the (__TEXT,__text) but its address is before the
7281 // start of the section in a standard MH_EXECUTE filetype.
7282 if (!DisSymName.empty() && DisSymName == "__mh_execute_header") {
7283 outs() << "-dis-symname: __mh_execute_header not in any section\n";
7284 return;
7285 }
Tim Northoverfbefee32016-07-14 23:13:03 +00007286 // When this code is trying to disassemble a symbol at a time and in the
7287 // case there is only the __mh_execute_header symbol left as in a stripped
7288 // executable, we need to deal with this by ignoring this symbol so the
7289 // whole section is disassembled and this symbol is then not displayed.
7290 if (SymName == "__mh_execute_header" || SymName == "__mh_dylib_header" ||
7291 SymName == "__mh_bundle_header" || SymName == "__mh_object_header" ||
7292 SymName == "__mh_preload_header" || SymName == "__mh_dylinker_header")
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007293 continue;
7294
Kevin Enderby6a221752015-03-17 17:10:57 +00007295 // If we are only disassembling one symbol see if this is that symbol.
7296 if (!DisSymName.empty() && DisSymName != SymName)
7297 continue;
7298
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00007299 // Start at the address of the symbol relative to the section's address.
Tim Northoverf203ab52016-07-14 22:13:32 +00007300 uint64_t SectSize = Sections[SectIdx].getSize();
Rafael Espindoladea00162015-07-03 17:44:18 +00007301 uint64_t Start = Symbols[SymIdx].getValue();
Rafael Espindola80291272014-10-08 15:28:58 +00007302 uint64_t SectionAddress = Sections[SectIdx].getAddress();
Cameron Zwarich54478a52012-02-03 05:42:17 +00007303 Start -= SectionAddress;
Owen Andersond9243c42011-10-17 21:37:35 +00007304
Tim Northoverf203ab52016-07-14 22:13:32 +00007305 if (Start > SectSize) {
7306 outs() << "section data ends, " << SymName
7307 << " lies outside valid range\n";
7308 return;
7309 }
7310
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00007311 // Stop disassembling either at the beginning of the next symbol or at
7312 // the end of the section.
Kevin Enderbyedd58722012-05-15 18:57:14 +00007313 bool containsNextSym = false;
Owen Andersond9243c42011-10-17 21:37:35 +00007314 uint64_t NextSym = 0;
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007315 uint64_t NextSymIdx = SymIdx + 1;
Owen Andersond9243c42011-10-17 21:37:35 +00007316 while (Symbols.size() > NextSymIdx) {
Fangrui Songe7834bd2019-04-07 08:19:55 +00007317 SymbolRef::Type NextSymType = unwrapOrError(
7318 Symbols[NextSymIdx].getType(), MachOOF->getFileName());
Owen Andersond9243c42011-10-17 21:37:35 +00007319 if (NextSymType == SymbolRef::ST_Function) {
Rafael Espindola80291272014-10-08 15:28:58 +00007320 containsNextSym =
7321 Sections[SectIdx].containsSymbol(Symbols[NextSymIdx]);
Rafael Espindoladea00162015-07-03 17:44:18 +00007322 NextSym = Symbols[NextSymIdx].getValue();
Cameron Zwarich54478a52012-02-03 05:42:17 +00007323 NextSym -= SectionAddress;
Owen Andersond9243c42011-10-17 21:37:35 +00007324 break;
7325 }
7326 ++NextSymIdx;
7327 }
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007328
Tim Northoverf203ab52016-07-14 22:13:32 +00007329 uint64_t End = containsNextSym ? std::min(NextSym, SectSize) : SectSize;
Owen Andersond9243c42011-10-17 21:37:35 +00007330 uint64_t Size;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007331
7332 symbolTableWorked = true;
Rafael Espindolabd604f22014-11-07 00:52:15 +00007333
Kevin Enderbyec5ca032014-08-18 20:21:02 +00007334 DataRefImpl Symb = Symbols[SymIdx].getRawDataRefImpl();
Tim Northover09ca33e2016-04-22 23:23:31 +00007335 bool IsThumb = MachOOF->getSymbolFlags(Symb) & SymbolRef::SF_Thumb;
7336
7337 // We only need the dedicated Thumb target if there's a real choice
7338 // (i.e. we're not targeting M-class) and the function is Thumb.
7339 bool UseThumbTarget = IsThumb && ThumbTarget;
Kevin Enderbyec5ca032014-08-18 20:21:02 +00007340
Kevin Enderbyc138da32017-02-06 18:43:18 +00007341 // If we are not specifying a symbol to start disassembly with and this
7342 // is the first symbol in the section but not at the start of the section
7343 // then move the disassembly index to the start of the section and
7344 // don't print the symbol name just yet. This is so the bytes before the
7345 // first symbol are disassembled.
7346 uint64_t SymbolStart = Start;
7347 if (DisSymName.empty() && FirstSymbol && Start != 0) {
7348 FirstSymbolAtSectionStart = false;
7349 Start = 0;
7350 }
7351 else
7352 outs() << SymName << ":\n";
7353
Ahmed Bougachaaa790682013-05-24 01:07:04 +00007354 DILineInfo lastLine;
7355 for (uint64_t Index = Start; Index < End; Index += Size) {
7356 MCInst Inst;
Owen Andersond9243c42011-10-17 21:37:35 +00007357
Kevin Enderbyc138da32017-02-06 18:43:18 +00007358 // If this is the first symbol in the section and it was not at the
7359 // start of the section, see if we are at its Index now and if so print
7360 // the symbol name.
7361 if (FirstSymbol && !FirstSymbolAtSectionStart && Index == SymbolStart)
7362 outs() << SymName << ":\n";
7363
Kevin Enderbybf246f52014-09-24 23:08:22 +00007364 uint64_t PC = SectAddress + Index;
Kevin Enderbyab5e6c92015-03-17 21:07:39 +00007365 if (!NoLeadingAddr) {
7366 if (FullLeadingAddr) {
7367 if (MachOOF->is64Bit())
7368 outs() << format("%016" PRIx64, PC);
7369 else
7370 outs() << format("%08" PRIx64, PC);
7371 } else {
7372 outs() << format("%8" PRIx64 ":", PC);
7373 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00007374 }
Kevin Enderby4b627be2016-04-28 20:14:13 +00007375 if (!NoShowRawInsn || Arch == Triple::arm)
Kevin Enderbybf246f52014-09-24 23:08:22 +00007376 outs() << "\t";
Kevin Enderby273ae012013-06-06 17:20:50 +00007377
7378 // Check the data in code table here to see if this is data not an
7379 // instruction to be disassembled.
7380 DiceTable Dice;
Kevin Enderbybf246f52014-09-24 23:08:22 +00007381 Dice.push_back(std::make_pair(PC, DiceRef()));
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007382 dice_table_iterator DTI =
7383 std::search(Dices.begin(), Dices.end(), Dice.begin(), Dice.end(),
7384 compareDiceTableEntries);
7385 if (DTI != Dices.end()) {
Kevin Enderby273ae012013-06-06 17:20:50 +00007386 uint16_t Length;
7387 DTI->second.getLength(Length);
Kevin Enderby273ae012013-06-06 17:20:50 +00007388 uint16_t Kind;
7389 DTI->second.getKind(Kind);
Colin LeMahieufc32b1b2015-03-18 19:27:31 +00007390 Size = DumpDataInCode(Bytes.data() + Index, Length, Kind);
Kevin Enderby930fdc72014-11-06 19:00:13 +00007391 if ((Kind == MachO::DICE_KIND_JUMP_TABLE8) &&
7392 (PC == (DTI->first + Length - 1)) && (Length & 1))
7393 Size++;
Kevin Enderby273ae012013-06-06 17:20:50 +00007394 continue;
7395 }
7396
Kevin Enderbybf246f52014-09-24 23:08:22 +00007397 SmallVector<char, 64> AnnotationsBytes;
7398 raw_svector_ostream Annotations(AnnotationsBytes);
7399
Kevin Enderbyec5ca032014-08-18 20:21:02 +00007400 bool gotInst;
Tim Northover09ca33e2016-04-22 23:23:31 +00007401 if (UseThumbTarget)
Rafael Espindola7fc5b872014-11-12 02:04:27 +00007402 gotInst = ThumbDisAsm->getInstruction(Inst, Size, Bytes.slice(Index),
Kevin Enderby6f326ce2014-10-23 19:37:31 +00007403 PC, DebugOut, Annotations);
Kevin Enderbyec5ca032014-08-18 20:21:02 +00007404 else
Rafael Espindola7fc5b872014-11-12 02:04:27 +00007405 gotInst = DisAsm->getInstruction(Inst, Size, Bytes.slice(Index), PC,
Kevin Enderbybf246f52014-09-24 23:08:22 +00007406 DebugOut, Annotations);
Kevin Enderbyec5ca032014-08-18 20:21:02 +00007407 if (gotInst) {
Kevin Enderby4b627be2016-04-28 20:14:13 +00007408 if (!NoShowRawInsn || Arch == Triple::arm) {
Craig Topper0013be12015-09-21 05:32:41 +00007409 dumpBytes(makeArrayRef(Bytes.data() + Index, Size), outs());
Kevin Enderbybf246f52014-09-24 23:08:22 +00007410 }
7411 formatted_raw_ostream FormattedOS(outs());
Kevin Enderbybf246f52014-09-24 23:08:22 +00007412 StringRef AnnotationsStr = Annotations.str();
Tim Northover09ca33e2016-04-22 23:23:31 +00007413 if (UseThumbTarget)
Akira Hatanakab46d0232015-03-27 20:36:02 +00007414 ThumbIP->printInst(&Inst, FormattedOS, AnnotationsStr, *ThumbSTI);
Kevin Enderbyec5ca032014-08-18 20:21:02 +00007415 else
Akira Hatanaka1d079942015-03-28 20:44:05 +00007416 IP->printInst(&Inst, FormattedOS, AnnotationsStr, *STI);
Kevin Enderbybf246f52014-09-24 23:08:22 +00007417 emitComments(CommentStream, CommentsToEmit, FormattedOS, *AsmInfo);
Owen Andersond9243c42011-10-17 21:37:35 +00007418
Ahmed Bougachaaa790682013-05-24 01:07:04 +00007419 // Print debug info.
7420 if (diContext) {
Alexey Lapshin77fc1f62019-02-27 13:17:36 +00007421 DILineInfo dli = diContext->getLineInfoForAddress({PC, SectIdx});
Ahmed Bougachaaa790682013-05-24 01:07:04 +00007422 // Print valid line info if it changed.
Alexey Samsonovd0109992014-04-18 21:36:39 +00007423 if (dli != lastLine && dli.Line != 0)
7424 outs() << "\t## " << dli.FileName << ':' << dli.Line << ':'
7425 << dli.Column;
Ahmed Bougachaaa790682013-05-24 01:07:04 +00007426 lastLine = dli;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007427 }
Ahmed Bougachaaa790682013-05-24 01:07:04 +00007428 outs() << "\n";
7429 } else {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00007430 unsigned int Arch = MachOOF->getArch();
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007431 if (Arch == Triple::x86_64 || Arch == Triple::x86) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00007432 outs() << format("\t.byte 0x%02x #bad opcode\n",
7433 *(Bytes.data() + Index) & 0xff);
7434 Size = 1; // skip exactly one illegible byte and move on.
Tim Northover09ca33e2016-04-22 23:23:31 +00007435 } else if (Arch == Triple::aarch64 ||
7436 (Arch == Triple::arm && !IsThumb)) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00007437 uint32_t opcode = (*(Bytes.data() + Index) & 0xff) |
7438 (*(Bytes.data() + Index + 1) & 0xff) << 8 |
7439 (*(Bytes.data() + Index + 2) & 0xff) << 16 |
7440 (*(Bytes.data() + Index + 3) & 0xff) << 24;
7441 outs() << format("\t.long\t0x%08x\n", opcode);
7442 Size = 4;
Tim Northover09ca33e2016-04-22 23:23:31 +00007443 } else if (Arch == Triple::arm) {
7444 assert(IsThumb && "ARM mode should have been dealt with above");
7445 uint32_t opcode = (*(Bytes.data() + Index) & 0xff) |
7446 (*(Bytes.data() + Index + 1) & 0xff) << 8;
7447 outs() << format("\t.short\t0x%04x\n", opcode);
7448 Size = 2;
7449 } else{
Jonas Devliegheree787efd2018-11-11 22:12:04 +00007450 WithColor::warning(errs(), "llvm-objdump")
7451 << "invalid instruction encoding\n";
Kevin Enderby6f326ce2014-10-23 19:37:31 +00007452 if (Size == 0)
7453 Size = 1; // skip illegible bytes
7454 }
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007455 }
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007456 }
Kevin Enderbyc138da32017-02-06 18:43:18 +00007457 // Now that we are done disassembled the first symbol set the bool that
7458 // were doing this to false.
7459 FirstSymbol = false;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007460 }
Ahmed Bougachaaa790682013-05-24 01:07:04 +00007461 if (!symbolTableWorked) {
Rafael Espindola80291272014-10-08 15:28:58 +00007462 // Reading the symbol table didn't work, disassemble the whole section.
7463 uint64_t SectAddress = Sections[SectIdx].getAddress();
7464 uint64_t SectSize = Sections[SectIdx].getSize();
Kevin Enderbybadd1002012-05-18 00:13:56 +00007465 uint64_t InstSize;
7466 for (uint64_t Index = 0; Index < SectSize; Index += InstSize) {
Bill Wendling4e68e062012-07-19 00:17:40 +00007467 MCInst Inst;
Kevin Enderbybadd1002012-05-18 00:13:56 +00007468
Kevin Enderbybf246f52014-09-24 23:08:22 +00007469 uint64_t PC = SectAddress + Index;
Kevin Enderby02d3a372017-01-31 18:09:10 +00007470 SmallVector<char, 64> AnnotationsBytes;
7471 raw_svector_ostream Annotations(AnnotationsBytes);
Rafael Espindola7fc5b872014-11-12 02:04:27 +00007472 if (DisAsm->getInstruction(Inst, InstSize, Bytes.slice(Index), PC,
Kevin Enderby02d3a372017-01-31 18:09:10 +00007473 DebugOut, Annotations)) {
Kevin Enderbyab5e6c92015-03-17 21:07:39 +00007474 if (!NoLeadingAddr) {
7475 if (FullLeadingAddr) {
7476 if (MachOOF->is64Bit())
7477 outs() << format("%016" PRIx64, PC);
7478 else
7479 outs() << format("%08" PRIx64, PC);
7480 } else {
7481 outs() << format("%8" PRIx64 ":", PC);
7482 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00007483 }
Kevin Enderby4b627be2016-04-28 20:14:13 +00007484 if (!NoShowRawInsn || Arch == Triple::arm) {
Kevin Enderbybf246f52014-09-24 23:08:22 +00007485 outs() << "\t";
Craig Topper0013be12015-09-21 05:32:41 +00007486 dumpBytes(makeArrayRef(Bytes.data() + Index, InstSize), outs());
Kevin Enderbybf246f52014-09-24 23:08:22 +00007487 }
Kevin Enderby02d3a372017-01-31 18:09:10 +00007488 StringRef AnnotationsStr = Annotations.str();
7489 IP->printInst(&Inst, outs(), AnnotationsStr, *STI);
Bill Wendling4e68e062012-07-19 00:17:40 +00007490 outs() << "\n";
7491 } else {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00007492 unsigned int Arch = MachOOF->getArch();
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007493 if (Arch == Triple::x86_64 || Arch == Triple::x86) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00007494 outs() << format("\t.byte 0x%02x #bad opcode\n",
7495 *(Bytes.data() + Index) & 0xff);
7496 InstSize = 1; // skip exactly one illegible byte and move on.
7497 } else {
Jonas Devliegheree787efd2018-11-11 22:12:04 +00007498 WithColor::warning(errs(), "llvm-objdump")
7499 << "invalid instruction encoding\n";
Kevin Enderby6f326ce2014-10-23 19:37:31 +00007500 if (InstSize == 0)
7501 InstSize = 1; // skip illegible bytes
7502 }
Bill Wendling4e68e062012-07-19 00:17:40 +00007503 }
Kevin Enderbybadd1002012-05-18 00:13:56 +00007504 }
7505 }
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00007506 // The TripleName's need to be reset if we are called again for a different
7507 // archtecture.
7508 TripleName = "";
7509 ThumbTripleName = "";
7510
Kevin Enderby04bf6932014-10-28 23:39:46 +00007511 if (SymbolizerInfo.demangled_name != nullptr)
7512 free(SymbolizerInfo.demangled_name);
Kevin Enderby930fdc72014-11-06 19:00:13 +00007513 if (ThumbSymbolizerInfo.demangled_name != nullptr)
7514 free(ThumbSymbolizerInfo.demangled_name);
Benjamin Kramer43a772e2011-09-19 17:56:04 +00007515 }
7516}
Tim Northover4bd286a2014-08-01 13:07:19 +00007517
Tim Northover39c70bb2014-08-12 11:52:59 +00007518//===----------------------------------------------------------------------===//
7519// __compact_unwind section dumping
7520//===----------------------------------------------------------------------===//
7521
Tim Northover4bd286a2014-08-01 13:07:19 +00007522namespace {
Tim Northover39c70bb2014-08-12 11:52:59 +00007523
Tim Northover3a4e1c72018-01-23 13:51:57 +00007524template <typename T>
7525static uint64_t read(StringRef Contents, ptrdiff_t Offset) {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007526 using llvm::support::little;
7527 using llvm::support::unaligned;
Tim Northover39c70bb2014-08-12 11:52:59 +00007528
Tim Northover3a4e1c72018-01-23 13:51:57 +00007529 if (Offset + sizeof(T) > Contents.size()) {
7530 outs() << "warning: attempt to read past end of buffer\n";
7531 return T();
7532 }
7533
7534 uint64_t Val =
7535 support::endian::read<T, little, unaligned>(Contents.data() + Offset);
7536 return Val;
7537}
7538
7539template <typename T>
7540static uint64_t readNext(StringRef Contents, ptrdiff_t &Offset) {
7541 T Val = read<T>(Contents, Offset);
7542 Offset += sizeof(T);
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007543 return Val;
7544}
Tim Northover39c70bb2014-08-12 11:52:59 +00007545
Tim Northover4bd286a2014-08-01 13:07:19 +00007546struct CompactUnwindEntry {
7547 uint32_t OffsetInSection;
7548
7549 uint64_t FunctionAddr;
7550 uint32_t Length;
7551 uint32_t CompactEncoding;
7552 uint64_t PersonalityAddr;
7553 uint64_t LSDAAddr;
7554
7555 RelocationRef FunctionReloc;
7556 RelocationRef PersonalityReloc;
7557 RelocationRef LSDAReloc;
7558
7559 CompactUnwindEntry(StringRef Contents, unsigned Offset, bool Is64)
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007560 : OffsetInSection(Offset) {
Tim Northover4bd286a2014-08-01 13:07:19 +00007561 if (Is64)
Tim Northover3a4e1c72018-01-23 13:51:57 +00007562 read<uint64_t>(Contents, Offset);
Tim Northover4bd286a2014-08-01 13:07:19 +00007563 else
Tim Northover3a4e1c72018-01-23 13:51:57 +00007564 read<uint32_t>(Contents, Offset);
Tim Northover4bd286a2014-08-01 13:07:19 +00007565 }
7566
7567private:
Tim Northover3a4e1c72018-01-23 13:51:57 +00007568 template <typename UIntPtr> void read(StringRef Contents, ptrdiff_t Offset) {
7569 FunctionAddr = readNext<UIntPtr>(Contents, Offset);
7570 Length = readNext<uint32_t>(Contents, Offset);
7571 CompactEncoding = readNext<uint32_t>(Contents, Offset);
7572 PersonalityAddr = readNext<UIntPtr>(Contents, Offset);
7573 LSDAAddr = readNext<UIntPtr>(Contents, Offset);
Tim Northover4bd286a2014-08-01 13:07:19 +00007574 }
7575};
7576}
7577
7578/// Given a relocation from __compact_unwind, consisting of the RelocationRef
7579/// and data being relocated, determine the best base Name and Addend to use for
7580/// display purposes.
7581///
7582/// 1. An Extern relocation will directly reference a symbol (and the data is
7583/// then already an addend), so use that.
7584/// 2. Otherwise the data is an offset in the object file's layout; try to find
7585// a symbol before it in the same section, and use the offset from there.
7586/// 3. Finally, if all that fails, fall back to an offset from the start of the
7587/// referenced section.
7588static void findUnwindRelocNameAddend(const MachOObjectFile *Obj,
7589 std::map<uint64_t, SymbolRef> &Symbols,
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007590 const RelocationRef &Reloc, uint64_t Addr,
Tim Northover4bd286a2014-08-01 13:07:19 +00007591 StringRef &Name, uint64_t &Addend) {
7592 if (Reloc.getSymbol() != Obj->symbol_end()) {
Fangrui Songe7834bd2019-04-07 08:19:55 +00007593 Name = unwrapOrError(Reloc.getSymbol()->getName(), Obj->getFileName());
Tim Northover4bd286a2014-08-01 13:07:19 +00007594 Addend = Addr;
7595 return;
7596 }
7597
7598 auto RE = Obj->getRelocation(Reloc.getRawDataRefImpl());
Keno Fischerc780e8e2015-05-21 21:24:32 +00007599 SectionRef RelocSection = Obj->getAnyRelocationSection(RE);
Tim Northover4bd286a2014-08-01 13:07:19 +00007600
Rafael Espindola80291272014-10-08 15:28:58 +00007601 uint64_t SectionAddr = RelocSection.getAddress();
Tim Northover4bd286a2014-08-01 13:07:19 +00007602
7603 auto Sym = Symbols.upper_bound(Addr);
7604 if (Sym == Symbols.begin()) {
7605 // The first symbol in the object is after this reference, the best we can
7606 // do is section-relative notation.
7607 RelocSection.getName(Name);
7608 Addend = Addr - SectionAddr;
7609 return;
7610 }
7611
7612 // Go back one so that SymbolAddress <= Addr.
7613 --Sym;
7614
Fangrui Songe7834bd2019-04-07 08:19:55 +00007615 section_iterator SymSection =
7616 unwrapOrError(Sym->second.getSection(), Obj->getFileName());
Tim Northover4bd286a2014-08-01 13:07:19 +00007617 if (RelocSection == *SymSection) {
7618 // There's a valid symbol in the same section before this reference.
Fangrui Songe7834bd2019-04-07 08:19:55 +00007619 Name = unwrapOrError(Sym->second.getName(), Obj->getFileName());
Tim Northover4bd286a2014-08-01 13:07:19 +00007620 Addend = Addr - Sym->first;
7621 return;
7622 }
7623
7624 // There is a symbol before this reference, but it's in a different
7625 // section. Probably not helpful to mention it, so use the section name.
7626 RelocSection.getName(Name);
7627 Addend = Addr - SectionAddr;
7628}
7629
7630static void printUnwindRelocDest(const MachOObjectFile *Obj,
7631 std::map<uint64_t, SymbolRef> &Symbols,
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007632 const RelocationRef &Reloc, uint64_t Addr) {
Tim Northover4bd286a2014-08-01 13:07:19 +00007633 StringRef Name;
7634 uint64_t Addend;
7635
Rafael Espindola854038e2015-06-26 14:51:16 +00007636 if (!Reloc.getObject())
Tim Northover0b0add52014-09-09 10:45:06 +00007637 return;
7638
Tim Northover4bd286a2014-08-01 13:07:19 +00007639 findUnwindRelocNameAddend(Obj, Symbols, Reloc, Addr, Name, Addend);
7640
7641 outs() << Name;
7642 if (Addend)
Tim Northover63a25622014-08-11 09:14:06 +00007643 outs() << " + " << format("0x%" PRIx64, Addend);
Tim Northover4bd286a2014-08-01 13:07:19 +00007644}
7645
7646static void
7647printMachOCompactUnwindSection(const MachOObjectFile *Obj,
7648 std::map<uint64_t, SymbolRef> &Symbols,
7649 const SectionRef &CompactUnwind) {
7650
Tim Northoverbf55f7e2016-11-15 20:26:01 +00007651 if (!Obj->isLittleEndian()) {
7652 outs() << "Skipping big-endian __compact_unwind section\n";
7653 return;
7654 }
Tim Northover4bd286a2014-08-01 13:07:19 +00007655
7656 bool Is64 = Obj->is64Bit();
7657 uint32_t PointerSize = Is64 ? sizeof(uint64_t) : sizeof(uint32_t);
7658 uint32_t EntrySize = 3 * PointerSize + 2 * sizeof(uint32_t);
7659
7660 StringRef Contents;
7661 CompactUnwind.getContents(Contents);
7662
7663 SmallVector<CompactUnwindEntry, 4> CompactUnwinds;
7664
7665 // First populate the initial raw offsets, encodings and so on from the entry.
7666 for (unsigned Offset = 0; Offset < Contents.size(); Offset += EntrySize) {
Tim Northover3a4e1c72018-01-23 13:51:57 +00007667 CompactUnwindEntry Entry(Contents, Offset, Is64);
Tim Northover4bd286a2014-08-01 13:07:19 +00007668 CompactUnwinds.push_back(Entry);
7669 }
7670
7671 // Next we need to look at the relocations to find out what objects are
7672 // actually being referred to.
7673 for (const RelocationRef &Reloc : CompactUnwind.relocations()) {
Rafael Espindola96d071c2015-06-29 23:29:12 +00007674 uint64_t RelocAddress = Reloc.getOffset();
Tim Northover4bd286a2014-08-01 13:07:19 +00007675
7676 uint32_t EntryIdx = RelocAddress / EntrySize;
7677 uint32_t OffsetInEntry = RelocAddress - EntryIdx * EntrySize;
7678 CompactUnwindEntry &Entry = CompactUnwinds[EntryIdx];
7679
7680 if (OffsetInEntry == 0)
7681 Entry.FunctionReloc = Reloc;
7682 else if (OffsetInEntry == PointerSize + 2 * sizeof(uint32_t))
7683 Entry.PersonalityReloc = Reloc;
7684 else if (OffsetInEntry == 2 * PointerSize + 2 * sizeof(uint32_t))
7685 Entry.LSDAReloc = Reloc;
Tim Northoverbf55f7e2016-11-15 20:26:01 +00007686 else {
7687 outs() << "Invalid relocation in __compact_unwind section\n";
7688 return;
7689 }
Tim Northover4bd286a2014-08-01 13:07:19 +00007690 }
7691
7692 // Finally, we're ready to print the data we've gathered.
7693 outs() << "Contents of __compact_unwind section:\n";
7694 for (auto &Entry : CompactUnwinds) {
Tim Northover06af2602014-08-08 12:08:51 +00007695 outs() << " Entry at offset "
7696 << format("0x%" PRIx32, Entry.OffsetInSection) << ":\n";
Tim Northover4bd286a2014-08-01 13:07:19 +00007697
7698 // 1. Start of the region this entry applies to.
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007699 outs() << " start: " << format("0x%" PRIx64,
7700 Entry.FunctionAddr) << ' ';
7701 printUnwindRelocDest(Obj, Symbols, Entry.FunctionReloc, Entry.FunctionAddr);
Tim Northover4bd286a2014-08-01 13:07:19 +00007702 outs() << '\n';
7703
7704 // 2. Length of the region this entry applies to.
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007705 outs() << " length: " << format("0x%" PRIx32, Entry.Length)
7706 << '\n';
Tim Northover4bd286a2014-08-01 13:07:19 +00007707 // 3. The 32-bit compact encoding.
7708 outs() << " compact encoding: "
Tim Northoverb911bf82014-08-08 12:00:09 +00007709 << format("0x%08" PRIx32, Entry.CompactEncoding) << '\n';
Tim Northover4bd286a2014-08-01 13:07:19 +00007710
7711 // 4. The personality function, if present.
Rafael Espindola854038e2015-06-26 14:51:16 +00007712 if (Entry.PersonalityReloc.getObject()) {
Tim Northover4bd286a2014-08-01 13:07:19 +00007713 outs() << " personality function: "
Tim Northoverb911bf82014-08-08 12:00:09 +00007714 << format("0x%" PRIx64, Entry.PersonalityAddr) << ' ';
Tim Northover4bd286a2014-08-01 13:07:19 +00007715 printUnwindRelocDest(Obj, Symbols, Entry.PersonalityReloc,
7716 Entry.PersonalityAddr);
7717 outs() << '\n';
7718 }
7719
7720 // 5. This entry's language-specific data area.
Rafael Espindola854038e2015-06-26 14:51:16 +00007721 if (Entry.LSDAReloc.getObject()) {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007722 outs() << " LSDA: " << format("0x%" PRIx64,
7723 Entry.LSDAAddr) << ' ';
Tim Northover4bd286a2014-08-01 13:07:19 +00007724 printUnwindRelocDest(Obj, Symbols, Entry.LSDAReloc, Entry.LSDAAddr);
7725 outs() << '\n';
7726 }
7727 }
7728}
7729
Tim Northover39c70bb2014-08-12 11:52:59 +00007730//===----------------------------------------------------------------------===//
7731// __unwind_info section dumping
7732//===----------------------------------------------------------------------===//
7733
Tim Northover3a4e1c72018-01-23 13:51:57 +00007734static void printRegularSecondLevelUnwindPage(StringRef PageData) {
7735 ptrdiff_t Pos = 0;
7736 uint32_t Kind = readNext<uint32_t>(PageData, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007737 (void)Kind;
7738 assert(Kind == 2 && "kind for a regular 2nd level index should be 2");
7739
Tim Northover3a4e1c72018-01-23 13:51:57 +00007740 uint16_t EntriesStart = readNext<uint16_t>(PageData, Pos);
7741 uint16_t NumEntries = readNext<uint16_t>(PageData, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007742
Tim Northover3a4e1c72018-01-23 13:51:57 +00007743 Pos = EntriesStart;
Tim Northover39c70bb2014-08-12 11:52:59 +00007744 for (unsigned i = 0; i < NumEntries; ++i) {
Tim Northover3a4e1c72018-01-23 13:51:57 +00007745 uint32_t FunctionOffset = readNext<uint32_t>(PageData, Pos);
7746 uint32_t Encoding = readNext<uint32_t>(PageData, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007747
7748 outs() << " [" << i << "]: "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007749 << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
7750 << ", "
7751 << "encoding=" << format("0x%08" PRIx32, Encoding) << '\n';
Tim Northover39c70bb2014-08-12 11:52:59 +00007752 }
7753}
7754
7755static void printCompressedSecondLevelUnwindPage(
Tim Northover3a4e1c72018-01-23 13:51:57 +00007756 StringRef PageData, uint32_t FunctionBase,
Tim Northover39c70bb2014-08-12 11:52:59 +00007757 const SmallVectorImpl<uint32_t> &CommonEncodings) {
Tim Northover3a4e1c72018-01-23 13:51:57 +00007758 ptrdiff_t Pos = 0;
7759 uint32_t Kind = readNext<uint32_t>(PageData, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007760 (void)Kind;
7761 assert(Kind == 3 && "kind for a compressed 2nd level index should be 3");
7762
Tim Northover3a4e1c72018-01-23 13:51:57 +00007763 uint16_t EntriesStart = readNext<uint16_t>(PageData, Pos);
7764 uint16_t NumEntries = readNext<uint16_t>(PageData, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007765
Tim Northover3a4e1c72018-01-23 13:51:57 +00007766 uint16_t EncodingsStart = readNext<uint16_t>(PageData, Pos);
7767 readNext<uint16_t>(PageData, Pos);
7768 StringRef PageEncodings = PageData.substr(EncodingsStart, StringRef::npos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007769
Tim Northover3a4e1c72018-01-23 13:51:57 +00007770 Pos = EntriesStart;
Tim Northover39c70bb2014-08-12 11:52:59 +00007771 for (unsigned i = 0; i < NumEntries; ++i) {
Tim Northover3a4e1c72018-01-23 13:51:57 +00007772 uint32_t Entry = readNext<uint32_t>(PageData, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007773 uint32_t FunctionOffset = FunctionBase + (Entry & 0xffffff);
7774 uint32_t EncodingIdx = Entry >> 24;
7775
7776 uint32_t Encoding;
7777 if (EncodingIdx < CommonEncodings.size())
7778 Encoding = CommonEncodings[EncodingIdx];
7779 else
Tim Northover3a4e1c72018-01-23 13:51:57 +00007780 Encoding = read<uint32_t>(PageEncodings,
7781 sizeof(uint32_t) *
7782 (EncodingIdx - CommonEncodings.size()));
Tim Northover39c70bb2014-08-12 11:52:59 +00007783
7784 outs() << " [" << i << "]: "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007785 << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
7786 << ", "
7787 << "encoding[" << EncodingIdx
7788 << "]=" << format("0x%08" PRIx32, Encoding) << '\n';
Tim Northover39c70bb2014-08-12 11:52:59 +00007789 }
7790}
7791
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007792static void printMachOUnwindInfoSection(const MachOObjectFile *Obj,
7793 std::map<uint64_t, SymbolRef> &Symbols,
7794 const SectionRef &UnwindInfo) {
Tim Northover39c70bb2014-08-12 11:52:59 +00007795
Tim Northoverbf55f7e2016-11-15 20:26:01 +00007796 if (!Obj->isLittleEndian()) {
7797 outs() << "Skipping big-endian __unwind_info section\n";
7798 return;
7799 }
Tim Northover39c70bb2014-08-12 11:52:59 +00007800
7801 outs() << "Contents of __unwind_info section:\n";
7802
7803 StringRef Contents;
7804 UnwindInfo.getContents(Contents);
Tim Northover3a4e1c72018-01-23 13:51:57 +00007805 ptrdiff_t Pos = 0;
Tim Northover39c70bb2014-08-12 11:52:59 +00007806
7807 //===----------------------------------
7808 // Section header
7809 //===----------------------------------
7810
Tim Northover3a4e1c72018-01-23 13:51:57 +00007811 uint32_t Version = readNext<uint32_t>(Contents, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007812 outs() << " Version: "
7813 << format("0x%" PRIx32, Version) << '\n';
Tim Northoverbf55f7e2016-11-15 20:26:01 +00007814 if (Version != 1) {
7815 outs() << " Skipping section with unknown version\n";
7816 return;
7817 }
Tim Northover39c70bb2014-08-12 11:52:59 +00007818
Tim Northover3a4e1c72018-01-23 13:51:57 +00007819 uint32_t CommonEncodingsStart = readNext<uint32_t>(Contents, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007820 outs() << " Common encodings array section offset: "
7821 << format("0x%" PRIx32, CommonEncodingsStart) << '\n';
Tim Northover3a4e1c72018-01-23 13:51:57 +00007822 uint32_t NumCommonEncodings = readNext<uint32_t>(Contents, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007823 outs() << " Number of common encodings in array: "
7824 << format("0x%" PRIx32, NumCommonEncodings) << '\n';
7825
Tim Northover3a4e1c72018-01-23 13:51:57 +00007826 uint32_t PersonalitiesStart = readNext<uint32_t>(Contents, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007827 outs() << " Personality function array section offset: "
7828 << format("0x%" PRIx32, PersonalitiesStart) << '\n';
Tim Northover3a4e1c72018-01-23 13:51:57 +00007829 uint32_t NumPersonalities = readNext<uint32_t>(Contents, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007830 outs() << " Number of personality functions in array: "
7831 << format("0x%" PRIx32, NumPersonalities) << '\n';
7832
Tim Northover3a4e1c72018-01-23 13:51:57 +00007833 uint32_t IndicesStart = readNext<uint32_t>(Contents, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007834 outs() << " Index array section offset: "
7835 << format("0x%" PRIx32, IndicesStart) << '\n';
Tim Northover3a4e1c72018-01-23 13:51:57 +00007836 uint32_t NumIndices = readNext<uint32_t>(Contents, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007837 outs() << " Number of indices in array: "
7838 << format("0x%" PRIx32, NumIndices) << '\n';
7839
7840 //===----------------------------------
7841 // A shared list of common encodings
7842 //===----------------------------------
7843
7844 // These occupy indices in the range [0, N] whenever an encoding is referenced
7845 // from a compressed 2nd level index table. In practice the linker only
7846 // creates ~128 of these, so that indices are available to embed encodings in
7847 // the 2nd level index.
7848
7849 SmallVector<uint32_t, 64> CommonEncodings;
7850 outs() << " Common encodings: (count = " << NumCommonEncodings << ")\n";
Tim Northover3a4e1c72018-01-23 13:51:57 +00007851 Pos = CommonEncodingsStart;
Tim Northover39c70bb2014-08-12 11:52:59 +00007852 for (unsigned i = 0; i < NumCommonEncodings; ++i) {
Tim Northover3a4e1c72018-01-23 13:51:57 +00007853 uint32_t Encoding = readNext<uint32_t>(Contents, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007854 CommonEncodings.push_back(Encoding);
7855
7856 outs() << " encoding[" << i << "]: " << format("0x%08" PRIx32, Encoding)
7857 << '\n';
7858 }
7859
Tim Northover39c70bb2014-08-12 11:52:59 +00007860 //===----------------------------------
7861 // Personality functions used in this executable
7862 //===----------------------------------
7863
7864 // There should be only a handful of these (one per source language,
7865 // roughly). Particularly since they only get 2 bits in the compact encoding.
7866
7867 outs() << " Personality functions: (count = " << NumPersonalities << ")\n";
Tim Northover3a4e1c72018-01-23 13:51:57 +00007868 Pos = PersonalitiesStart;
Tim Northover39c70bb2014-08-12 11:52:59 +00007869 for (unsigned i = 0; i < NumPersonalities; ++i) {
Tim Northover3a4e1c72018-01-23 13:51:57 +00007870 uint32_t PersonalityFn = readNext<uint32_t>(Contents, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007871 outs() << " personality[" << i + 1
7872 << "]: " << format("0x%08" PRIx32, PersonalityFn) << '\n';
7873 }
7874
7875 //===----------------------------------
7876 // The level 1 index entries
7877 //===----------------------------------
7878
7879 // These specify an approximate place to start searching for the more detailed
7880 // information, sorted by PC.
7881
7882 struct IndexEntry {
7883 uint32_t FunctionOffset;
7884 uint32_t SecondLevelPageStart;
7885 uint32_t LSDAStart;
7886 };
7887
7888 SmallVector<IndexEntry, 4> IndexEntries;
7889
7890 outs() << " Top level indices: (count = " << NumIndices << ")\n";
Tim Northover3a4e1c72018-01-23 13:51:57 +00007891 Pos = IndicesStart;
Tim Northover39c70bb2014-08-12 11:52:59 +00007892 for (unsigned i = 0; i < NumIndices; ++i) {
7893 IndexEntry Entry;
7894
Tim Northover3a4e1c72018-01-23 13:51:57 +00007895 Entry.FunctionOffset = readNext<uint32_t>(Contents, Pos);
7896 Entry.SecondLevelPageStart = readNext<uint32_t>(Contents, Pos);
7897 Entry.LSDAStart = readNext<uint32_t>(Contents, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007898 IndexEntries.push_back(Entry);
7899
7900 outs() << " [" << i << "]: "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007901 << "function offset=" << format("0x%08" PRIx32, Entry.FunctionOffset)
7902 << ", "
Tim Northover39c70bb2014-08-12 11:52:59 +00007903 << "2nd level page offset="
7904 << format("0x%08" PRIx32, Entry.SecondLevelPageStart) << ", "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007905 << "LSDA offset=" << format("0x%08" PRIx32, Entry.LSDAStart) << '\n';
Tim Northover39c70bb2014-08-12 11:52:59 +00007906 }
7907
Tim Northover39c70bb2014-08-12 11:52:59 +00007908 //===----------------------------------
7909 // Next come the LSDA tables
7910 //===----------------------------------
7911
7912 // The LSDA layout is rather implicit: it's a contiguous array of entries from
7913 // the first top-level index's LSDAOffset to the last (sentinel).
7914
7915 outs() << " LSDA descriptors:\n";
Tim Northover3a4e1c72018-01-23 13:51:57 +00007916 Pos = IndexEntries[0].LSDAStart;
7917 const uint32_t LSDASize = 2 * sizeof(uint32_t);
7918 int NumLSDAs =
7919 (IndexEntries.back().LSDAStart - IndexEntries[0].LSDAStart) / LSDASize;
7920
Tim Northover39c70bb2014-08-12 11:52:59 +00007921 for (int i = 0; i < NumLSDAs; ++i) {
Tim Northover3a4e1c72018-01-23 13:51:57 +00007922 uint32_t FunctionOffset = readNext<uint32_t>(Contents, Pos);
7923 uint32_t LSDAOffset = readNext<uint32_t>(Contents, Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007924 outs() << " [" << i << "]: "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00007925 << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
7926 << ", "
7927 << "LSDA offset=" << format("0x%08" PRIx32, LSDAOffset) << '\n';
Tim Northover39c70bb2014-08-12 11:52:59 +00007928 }
7929
7930 //===----------------------------------
7931 // Finally, the 2nd level indices
7932 //===----------------------------------
7933
7934 // Generally these are 4K in size, and have 2 possible forms:
7935 // + Regular stores up to 511 entries with disparate encodings
7936 // + Compressed stores up to 1021 entries if few enough compact encoding
7937 // values are used.
7938 outs() << " Second level indices:\n";
7939 for (unsigned i = 0; i < IndexEntries.size() - 1; ++i) {
7940 // The final sentinel top-level index has no associated 2nd level page
7941 if (IndexEntries[i].SecondLevelPageStart == 0)
7942 break;
7943
7944 outs() << " Second level index[" << i << "]: "
7945 << "offset in section="
7946 << format("0x%08" PRIx32, IndexEntries[i].SecondLevelPageStart)
7947 << ", "
7948 << "base function offset="
7949 << format("0x%08" PRIx32, IndexEntries[i].FunctionOffset) << '\n';
7950
Tim Northover3a4e1c72018-01-23 13:51:57 +00007951 Pos = IndexEntries[i].SecondLevelPageStart;
7952 if (Pos + sizeof(uint32_t) > Contents.size()) {
7953 outs() << "warning: invalid offset for second level page: " << Pos << '\n';
7954 continue;
7955 }
7956
7957 uint32_t Kind =
7958 *reinterpret_cast<const support::ulittle32_t *>(Contents.data() + Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00007959 if (Kind == 2)
Tim Northover3a4e1c72018-01-23 13:51:57 +00007960 printRegularSecondLevelUnwindPage(Contents.substr(Pos, 4096));
Tim Northover39c70bb2014-08-12 11:52:59 +00007961 else if (Kind == 3)
Tim Northover3a4e1c72018-01-23 13:51:57 +00007962 printCompressedSecondLevelUnwindPage(Contents.substr(Pos, 4096),
7963 IndexEntries[i].FunctionOffset,
Tim Northover39c70bb2014-08-12 11:52:59 +00007964 CommonEncodings);
7965 else
Tim Northoverbf55f7e2016-11-15 20:26:01 +00007966 outs() << " Skipping 2nd level page with unknown kind " << Kind
7967 << '\n';
Tim Northover39c70bb2014-08-12 11:52:59 +00007968 }
7969}
7970
Tim Northover4bd286a2014-08-01 13:07:19 +00007971void llvm::printMachOUnwindInfo(const MachOObjectFile *Obj) {
7972 std::map<uint64_t, SymbolRef> Symbols;
7973 for (const SymbolRef &SymRef : Obj->symbols()) {
7974 // Discard any undefined or absolute symbols. They're not going to take part
7975 // in the convenience lookup for unwind info and just take up resources.
Kevin Enderby7bd8d992016-05-02 20:28:12 +00007976 auto SectOrErr = SymRef.getSection();
7977 if (!SectOrErr) {
7978 // TODO: Actually report errors helpfully.
7979 consumeError(SectOrErr.takeError());
7980 continue;
7981 }
7982 section_iterator Section = *SectOrErr;
Tim Northover4bd286a2014-08-01 13:07:19 +00007983 if (Section == Obj->section_end())
7984 continue;
7985
Rafael Espindoladea00162015-07-03 17:44:18 +00007986 uint64_t Addr = SymRef.getValue();
Tim Northover4bd286a2014-08-01 13:07:19 +00007987 Symbols.insert(std::make_pair(Addr, SymRef));
7988 }
7989
7990 for (const SectionRef &Section : Obj->sections()) {
7991 StringRef SectName;
7992 Section.getName(SectName);
7993 if (SectName == "__compact_unwind")
7994 printMachOCompactUnwindSection(Obj, Symbols, Section);
7995 else if (SectName == "__unwind_info")
Tim Northover39c70bb2014-08-12 11:52:59 +00007996 printMachOUnwindInfoSection(Obj, Symbols, Section);
Tim Northover4bd286a2014-08-01 13:07:19 +00007997 }
7998}
Kevin Enderbyb76d3862014-08-22 20:35:18 +00007999
8000static void PrintMachHeader(uint32_t magic, uint32_t cputype,
8001 uint32_t cpusubtype, uint32_t filetype,
8002 uint32_t ncmds, uint32_t sizeofcmds, uint32_t flags,
8003 bool verbose) {
8004 outs() << "Mach header\n";
8005 outs() << " magic cputype cpusubtype caps filetype ncmds "
8006 "sizeofcmds flags\n";
8007 if (verbose) {
8008 if (magic == MachO::MH_MAGIC)
8009 outs() << " MH_MAGIC";
8010 else if (magic == MachO::MH_MAGIC_64)
8011 outs() << "MH_MAGIC_64";
8012 else
8013 outs() << format(" 0x%08" PRIx32, magic);
8014 switch (cputype) {
8015 case MachO::CPU_TYPE_I386:
8016 outs() << " I386";
8017 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
8018 case MachO::CPU_SUBTYPE_I386_ALL:
8019 outs() << " ALL";
8020 break;
8021 default:
8022 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
8023 break;
8024 }
8025 break;
8026 case MachO::CPU_TYPE_X86_64:
8027 outs() << " X86_64";
Kevin Enderby131d1772015-01-09 19:22:37 +00008028 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
8029 case MachO::CPU_SUBTYPE_X86_64_ALL:
8030 outs() << " ALL";
8031 break;
8032 case MachO::CPU_SUBTYPE_X86_64_H:
8033 outs() << " Haswell";
8034 break;
8035 default:
8036 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
8037 break;
8038 }
Kevin Enderbyb76d3862014-08-22 20:35:18 +00008039 break;
8040 case MachO::CPU_TYPE_ARM:
8041 outs() << " ARM";
8042 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
8043 case MachO::CPU_SUBTYPE_ARM_ALL:
8044 outs() << " ALL";
8045 break;
8046 case MachO::CPU_SUBTYPE_ARM_V4T:
8047 outs() << " V4T";
8048 break;
8049 case MachO::CPU_SUBTYPE_ARM_V5TEJ:
8050 outs() << " V5TEJ";
8051 break;
8052 case MachO::CPU_SUBTYPE_ARM_XSCALE:
8053 outs() << " XSCALE";
8054 break;
8055 case MachO::CPU_SUBTYPE_ARM_V6:
8056 outs() << " V6";
8057 break;
8058 case MachO::CPU_SUBTYPE_ARM_V6M:
8059 outs() << " V6M";
8060 break;
8061 case MachO::CPU_SUBTYPE_ARM_V7:
8062 outs() << " V7";
8063 break;
8064 case MachO::CPU_SUBTYPE_ARM_V7EM:
8065 outs() << " V7EM";
8066 break;
8067 case MachO::CPU_SUBTYPE_ARM_V7K:
8068 outs() << " V7K";
8069 break;
8070 case MachO::CPU_SUBTYPE_ARM_V7M:
8071 outs() << " V7M";
8072 break;
8073 case MachO::CPU_SUBTYPE_ARM_V7S:
8074 outs() << " V7S";
8075 break;
8076 default:
8077 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
8078 break;
8079 }
8080 break;
8081 case MachO::CPU_TYPE_ARM64:
8082 outs() << " ARM64";
8083 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
8084 case MachO::CPU_SUBTYPE_ARM64_ALL:
8085 outs() << " ALL";
8086 break;
8087 default:
8088 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
8089 break;
8090 }
8091 break;
8092 case MachO::CPU_TYPE_POWERPC:
8093 outs() << " PPC";
8094 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
8095 case MachO::CPU_SUBTYPE_POWERPC_ALL:
8096 outs() << " ALL";
8097 break;
8098 default:
8099 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
8100 break;
8101 }
8102 break;
8103 case MachO::CPU_TYPE_POWERPC64:
8104 outs() << " PPC64";
8105 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
8106 case MachO::CPU_SUBTYPE_POWERPC_ALL:
8107 outs() << " ALL";
8108 break;
8109 default:
8110 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
8111 break;
8112 }
8113 break;
Kevin Enderby40fdbf82016-01-26 18:20:49 +00008114 default:
8115 outs() << format(" %7d", cputype);
8116 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
8117 break;
Kevin Enderbyb76d3862014-08-22 20:35:18 +00008118 }
8119 if ((cpusubtype & MachO::CPU_SUBTYPE_MASK) == MachO::CPU_SUBTYPE_LIB64) {
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008120 outs() << " LIB64";
Kevin Enderbyb76d3862014-08-22 20:35:18 +00008121 } else {
8122 outs() << format(" 0x%02" PRIx32,
8123 (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24);
8124 }
8125 switch (filetype) {
8126 case MachO::MH_OBJECT:
8127 outs() << " OBJECT";
8128 break;
8129 case MachO::MH_EXECUTE:
8130 outs() << " EXECUTE";
8131 break;
8132 case MachO::MH_FVMLIB:
8133 outs() << " FVMLIB";
8134 break;
8135 case MachO::MH_CORE:
8136 outs() << " CORE";
8137 break;
8138 case MachO::MH_PRELOAD:
8139 outs() << " PRELOAD";
8140 break;
8141 case MachO::MH_DYLIB:
8142 outs() << " DYLIB";
8143 break;
8144 case MachO::MH_DYLIB_STUB:
8145 outs() << " DYLIB_STUB";
8146 break;
8147 case MachO::MH_DYLINKER:
8148 outs() << " DYLINKER";
8149 break;
8150 case MachO::MH_BUNDLE:
8151 outs() << " BUNDLE";
8152 break;
8153 case MachO::MH_DSYM:
8154 outs() << " DSYM";
8155 break;
8156 case MachO::MH_KEXT_BUNDLE:
8157 outs() << " KEXTBUNDLE";
8158 break;
8159 default:
8160 outs() << format(" %10u", filetype);
8161 break;
8162 }
8163 outs() << format(" %5u", ncmds);
8164 outs() << format(" %10u", sizeofcmds);
8165 uint32_t f = flags;
8166 if (f & MachO::MH_NOUNDEFS) {
8167 outs() << " NOUNDEFS";
8168 f &= ~MachO::MH_NOUNDEFS;
8169 }
8170 if (f & MachO::MH_INCRLINK) {
8171 outs() << " INCRLINK";
8172 f &= ~MachO::MH_INCRLINK;
8173 }
8174 if (f & MachO::MH_DYLDLINK) {
8175 outs() << " DYLDLINK";
8176 f &= ~MachO::MH_DYLDLINK;
8177 }
8178 if (f & MachO::MH_BINDATLOAD) {
8179 outs() << " BINDATLOAD";
8180 f &= ~MachO::MH_BINDATLOAD;
8181 }
8182 if (f & MachO::MH_PREBOUND) {
8183 outs() << " PREBOUND";
8184 f &= ~MachO::MH_PREBOUND;
8185 }
8186 if (f & MachO::MH_SPLIT_SEGS) {
8187 outs() << " SPLIT_SEGS";
8188 f &= ~MachO::MH_SPLIT_SEGS;
8189 }
8190 if (f & MachO::MH_LAZY_INIT) {
8191 outs() << " LAZY_INIT";
8192 f &= ~MachO::MH_LAZY_INIT;
8193 }
8194 if (f & MachO::MH_TWOLEVEL) {
8195 outs() << " TWOLEVEL";
8196 f &= ~MachO::MH_TWOLEVEL;
8197 }
8198 if (f & MachO::MH_FORCE_FLAT) {
8199 outs() << " FORCE_FLAT";
8200 f &= ~MachO::MH_FORCE_FLAT;
8201 }
8202 if (f & MachO::MH_NOMULTIDEFS) {
8203 outs() << " NOMULTIDEFS";
8204 f &= ~MachO::MH_NOMULTIDEFS;
8205 }
8206 if (f & MachO::MH_NOFIXPREBINDING) {
8207 outs() << " NOFIXPREBINDING";
8208 f &= ~MachO::MH_NOFIXPREBINDING;
8209 }
8210 if (f & MachO::MH_PREBINDABLE) {
8211 outs() << " PREBINDABLE";
8212 f &= ~MachO::MH_PREBINDABLE;
8213 }
8214 if (f & MachO::MH_ALLMODSBOUND) {
8215 outs() << " ALLMODSBOUND";
8216 f &= ~MachO::MH_ALLMODSBOUND;
8217 }
8218 if (f & MachO::MH_SUBSECTIONS_VIA_SYMBOLS) {
8219 outs() << " SUBSECTIONS_VIA_SYMBOLS";
8220 f &= ~MachO::MH_SUBSECTIONS_VIA_SYMBOLS;
8221 }
8222 if (f & MachO::MH_CANONICAL) {
8223 outs() << " CANONICAL";
8224 f &= ~MachO::MH_CANONICAL;
8225 }
8226 if (f & MachO::MH_WEAK_DEFINES) {
8227 outs() << " WEAK_DEFINES";
8228 f &= ~MachO::MH_WEAK_DEFINES;
8229 }
8230 if (f & MachO::MH_BINDS_TO_WEAK) {
8231 outs() << " BINDS_TO_WEAK";
8232 f &= ~MachO::MH_BINDS_TO_WEAK;
8233 }
8234 if (f & MachO::MH_ALLOW_STACK_EXECUTION) {
8235 outs() << " ALLOW_STACK_EXECUTION";
8236 f &= ~MachO::MH_ALLOW_STACK_EXECUTION;
8237 }
8238 if (f & MachO::MH_DEAD_STRIPPABLE_DYLIB) {
8239 outs() << " DEAD_STRIPPABLE_DYLIB";
8240 f &= ~MachO::MH_DEAD_STRIPPABLE_DYLIB;
8241 }
8242 if (f & MachO::MH_PIE) {
8243 outs() << " PIE";
8244 f &= ~MachO::MH_PIE;
8245 }
8246 if (f & MachO::MH_NO_REEXPORTED_DYLIBS) {
8247 outs() << " NO_REEXPORTED_DYLIBS";
8248 f &= ~MachO::MH_NO_REEXPORTED_DYLIBS;
8249 }
8250 if (f & MachO::MH_HAS_TLV_DESCRIPTORS) {
8251 outs() << " MH_HAS_TLV_DESCRIPTORS";
8252 f &= ~MachO::MH_HAS_TLV_DESCRIPTORS;
8253 }
8254 if (f & MachO::MH_NO_HEAP_EXECUTION) {
8255 outs() << " MH_NO_HEAP_EXECUTION";
8256 f &= ~MachO::MH_NO_HEAP_EXECUTION;
8257 }
8258 if (f & MachO::MH_APP_EXTENSION_SAFE) {
8259 outs() << " APP_EXTENSION_SAFE";
8260 f &= ~MachO::MH_APP_EXTENSION_SAFE;
8261 }
Kevin Enderbydf0d6da2017-06-19 19:38:22 +00008262 if (f & MachO::MH_NLIST_OUTOFSYNC_WITH_DYLDINFO) {
8263 outs() << " NLIST_OUTOFSYNC_WITH_DYLDINFO";
8264 f &= ~MachO::MH_NLIST_OUTOFSYNC_WITH_DYLDINFO;
8265 }
Kevin Enderbyb76d3862014-08-22 20:35:18 +00008266 if (f != 0 || flags == 0)
8267 outs() << format(" 0x%08" PRIx32, f);
8268 } else {
8269 outs() << format(" 0x%08" PRIx32, magic);
8270 outs() << format(" %7d", cputype);
8271 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
8272 outs() << format(" 0x%02" PRIx32,
8273 (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24);
8274 outs() << format(" %10u", filetype);
8275 outs() << format(" %5u", ncmds);
8276 outs() << format(" %10u", sizeofcmds);
8277 outs() << format(" 0x%08" PRIx32, flags);
8278 }
8279 outs() << "\n";
8280}
8281
Kevin Enderby956366c2014-08-29 22:30:52 +00008282static void PrintSegmentCommand(uint32_t cmd, uint32_t cmdsize,
8283 StringRef SegName, uint64_t vmaddr,
8284 uint64_t vmsize, uint64_t fileoff,
8285 uint64_t filesize, uint32_t maxprot,
8286 uint32_t initprot, uint32_t nsects,
8287 uint32_t flags, uint32_t object_size,
8288 bool verbose) {
8289 uint64_t expected_cmdsize;
8290 if (cmd == MachO::LC_SEGMENT) {
8291 outs() << " cmd LC_SEGMENT\n";
8292 expected_cmdsize = nsects;
8293 expected_cmdsize *= sizeof(struct MachO::section);
8294 expected_cmdsize += sizeof(struct MachO::segment_command);
8295 } else {
8296 outs() << " cmd LC_SEGMENT_64\n";
8297 expected_cmdsize = nsects;
8298 expected_cmdsize *= sizeof(struct MachO::section_64);
8299 expected_cmdsize += sizeof(struct MachO::segment_command_64);
8300 }
8301 outs() << " cmdsize " << cmdsize;
8302 if (cmdsize != expected_cmdsize)
8303 outs() << " Inconsistent size\n";
8304 else
8305 outs() << "\n";
8306 outs() << " segname " << SegName << "\n";
8307 if (cmd == MachO::LC_SEGMENT_64) {
8308 outs() << " vmaddr " << format("0x%016" PRIx64, vmaddr) << "\n";
8309 outs() << " vmsize " << format("0x%016" PRIx64, vmsize) << "\n";
8310 } else {
Kevin Enderbyadb7c432014-12-16 18:58:11 +00008311 outs() << " vmaddr " << format("0x%08" PRIx64, vmaddr) << "\n";
8312 outs() << " vmsize " << format("0x%08" PRIx64, vmsize) << "\n";
Kevin Enderby956366c2014-08-29 22:30:52 +00008313 }
8314 outs() << " fileoff " << fileoff;
8315 if (fileoff > object_size)
8316 outs() << " (past end of file)\n";
8317 else
8318 outs() << "\n";
8319 outs() << " filesize " << filesize;
8320 if (fileoff + filesize > object_size)
8321 outs() << " (past end of file)\n";
8322 else
8323 outs() << "\n";
8324 if (verbose) {
8325 if ((maxprot &
8326 ~(MachO::VM_PROT_READ | MachO::VM_PROT_WRITE |
8327 MachO::VM_PROT_EXECUTE)) != 0)
8328 outs() << " maxprot ?" << format("0x%08" PRIx32, maxprot) << "\n";
8329 else {
Davide Italiano37ff06a2015-09-02 16:53:25 +00008330 outs() << " maxprot ";
8331 outs() << ((maxprot & MachO::VM_PROT_READ) ? "r" : "-");
8332 outs() << ((maxprot & MachO::VM_PROT_WRITE) ? "w" : "-");
8333 outs() << ((maxprot & MachO::VM_PROT_EXECUTE) ? "x\n" : "-\n");
Kevin Enderby956366c2014-08-29 22:30:52 +00008334 }
8335 if ((initprot &
8336 ~(MachO::VM_PROT_READ | MachO::VM_PROT_WRITE |
8337 MachO::VM_PROT_EXECUTE)) != 0)
Kevin Enderby41c9c002016-10-21 18:22:35 +00008338 outs() << " initprot ?" << format("0x%08" PRIx32, initprot) << "\n";
Kevin Enderby956366c2014-08-29 22:30:52 +00008339 else {
Kevin Enderby41c9c002016-10-21 18:22:35 +00008340 outs() << " initprot ";
Davide Italiano37ff06a2015-09-02 16:53:25 +00008341 outs() << ((initprot & MachO::VM_PROT_READ) ? "r" : "-");
8342 outs() << ((initprot & MachO::VM_PROT_WRITE) ? "w" : "-");
8343 outs() << ((initprot & MachO::VM_PROT_EXECUTE) ? "x\n" : "-\n");
Kevin Enderby956366c2014-08-29 22:30:52 +00008344 }
8345 } else {
8346 outs() << " maxprot " << format("0x%08" PRIx32, maxprot) << "\n";
8347 outs() << " initprot " << format("0x%08" PRIx32, initprot) << "\n";
8348 }
8349 outs() << " nsects " << nsects << "\n";
8350 if (verbose) {
8351 outs() << " flags";
8352 if (flags == 0)
8353 outs() << " (none)\n";
8354 else {
8355 if (flags & MachO::SG_HIGHVM) {
8356 outs() << " HIGHVM";
8357 flags &= ~MachO::SG_HIGHVM;
8358 }
8359 if (flags & MachO::SG_FVMLIB) {
8360 outs() << " FVMLIB";
8361 flags &= ~MachO::SG_FVMLIB;
8362 }
8363 if (flags & MachO::SG_NORELOC) {
8364 outs() << " NORELOC";
8365 flags &= ~MachO::SG_NORELOC;
8366 }
8367 if (flags & MachO::SG_PROTECTED_VERSION_1) {
8368 outs() << " PROTECTED_VERSION_1";
8369 flags &= ~MachO::SG_PROTECTED_VERSION_1;
8370 }
8371 if (flags)
8372 outs() << format(" 0x%08" PRIx32, flags) << " (unknown flags)\n";
8373 else
8374 outs() << "\n";
8375 }
8376 } else {
8377 outs() << " flags " << format("0x%" PRIx32, flags) << "\n";
8378 }
8379}
8380
8381static void PrintSection(const char *sectname, const char *segname,
8382 uint64_t addr, uint64_t size, uint32_t offset,
8383 uint32_t align, uint32_t reloff, uint32_t nreloc,
8384 uint32_t flags, uint32_t reserved1, uint32_t reserved2,
8385 uint32_t cmd, const char *sg_segname,
8386 uint32_t filetype, uint32_t object_size,
8387 bool verbose) {
8388 outs() << "Section\n";
8389 outs() << " sectname " << format("%.16s\n", sectname);
8390 outs() << " segname " << format("%.16s", segname);
8391 if (filetype != MachO::MH_OBJECT && strncmp(sg_segname, segname, 16) != 0)
8392 outs() << " (does not match segment)\n";
8393 else
8394 outs() << "\n";
8395 if (cmd == MachO::LC_SEGMENT_64) {
8396 outs() << " addr " << format("0x%016" PRIx64, addr) << "\n";
8397 outs() << " size " << format("0x%016" PRIx64, size);
8398 } else {
Kevin Enderby75594b62014-12-16 21:00:25 +00008399 outs() << " addr " << format("0x%08" PRIx64, addr) << "\n";
8400 outs() << " size " << format("0x%08" PRIx64, size);
Kevin Enderby956366c2014-08-29 22:30:52 +00008401 }
8402 if ((flags & MachO::S_ZEROFILL) != 0 && offset + size > object_size)
8403 outs() << " (past end of file)\n";
8404 else
8405 outs() << "\n";
8406 outs() << " offset " << offset;
8407 if (offset > object_size)
8408 outs() << " (past end of file)\n";
8409 else
8410 outs() << "\n";
8411 uint32_t align_shifted = 1 << align;
8412 outs() << " align 2^" << align << " (" << align_shifted << ")\n";
8413 outs() << " reloff " << reloff;
8414 if (reloff > object_size)
8415 outs() << " (past end of file)\n";
8416 else
8417 outs() << "\n";
8418 outs() << " nreloc " << nreloc;
8419 if (reloff + nreloc * sizeof(struct MachO::relocation_info) > object_size)
8420 outs() << " (past end of file)\n";
8421 else
8422 outs() << "\n";
8423 uint32_t section_type = flags & MachO::SECTION_TYPE;
8424 if (verbose) {
8425 outs() << " type";
8426 if (section_type == MachO::S_REGULAR)
8427 outs() << " S_REGULAR\n";
8428 else if (section_type == MachO::S_ZEROFILL)
8429 outs() << " S_ZEROFILL\n";
8430 else if (section_type == MachO::S_CSTRING_LITERALS)
8431 outs() << " S_CSTRING_LITERALS\n";
8432 else if (section_type == MachO::S_4BYTE_LITERALS)
8433 outs() << " S_4BYTE_LITERALS\n";
8434 else if (section_type == MachO::S_8BYTE_LITERALS)
8435 outs() << " S_8BYTE_LITERALS\n";
8436 else if (section_type == MachO::S_16BYTE_LITERALS)
8437 outs() << " S_16BYTE_LITERALS\n";
8438 else if (section_type == MachO::S_LITERAL_POINTERS)
8439 outs() << " S_LITERAL_POINTERS\n";
8440 else if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS)
8441 outs() << " S_NON_LAZY_SYMBOL_POINTERS\n";
8442 else if (section_type == MachO::S_LAZY_SYMBOL_POINTERS)
8443 outs() << " S_LAZY_SYMBOL_POINTERS\n";
8444 else if (section_type == MachO::S_SYMBOL_STUBS)
8445 outs() << " S_SYMBOL_STUBS\n";
8446 else if (section_type == MachO::S_MOD_INIT_FUNC_POINTERS)
8447 outs() << " S_MOD_INIT_FUNC_POINTERS\n";
8448 else if (section_type == MachO::S_MOD_TERM_FUNC_POINTERS)
8449 outs() << " S_MOD_TERM_FUNC_POINTERS\n";
8450 else if (section_type == MachO::S_COALESCED)
8451 outs() << " S_COALESCED\n";
8452 else if (section_type == MachO::S_INTERPOSING)
8453 outs() << " S_INTERPOSING\n";
8454 else if (section_type == MachO::S_DTRACE_DOF)
8455 outs() << " S_DTRACE_DOF\n";
8456 else if (section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS)
8457 outs() << " S_LAZY_DYLIB_SYMBOL_POINTERS\n";
8458 else if (section_type == MachO::S_THREAD_LOCAL_REGULAR)
8459 outs() << " S_THREAD_LOCAL_REGULAR\n";
8460 else if (section_type == MachO::S_THREAD_LOCAL_ZEROFILL)
8461 outs() << " S_THREAD_LOCAL_ZEROFILL\n";
8462 else if (section_type == MachO::S_THREAD_LOCAL_VARIABLES)
8463 outs() << " S_THREAD_LOCAL_VARIABLES\n";
8464 else if (section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS)
8465 outs() << " S_THREAD_LOCAL_VARIABLE_POINTERS\n";
8466 else if (section_type == MachO::S_THREAD_LOCAL_INIT_FUNCTION_POINTERS)
8467 outs() << " S_THREAD_LOCAL_INIT_FUNCTION_POINTERS\n";
8468 else
8469 outs() << format("0x%08" PRIx32, section_type) << "\n";
8470 outs() << "attributes";
8471 uint32_t section_attributes = flags & MachO::SECTION_ATTRIBUTES;
8472 if (section_attributes & MachO::S_ATTR_PURE_INSTRUCTIONS)
8473 outs() << " PURE_INSTRUCTIONS";
8474 if (section_attributes & MachO::S_ATTR_NO_TOC)
8475 outs() << " NO_TOC";
8476 if (section_attributes & MachO::S_ATTR_STRIP_STATIC_SYMS)
8477 outs() << " STRIP_STATIC_SYMS";
8478 if (section_attributes & MachO::S_ATTR_NO_DEAD_STRIP)
8479 outs() << " NO_DEAD_STRIP";
8480 if (section_attributes & MachO::S_ATTR_LIVE_SUPPORT)
8481 outs() << " LIVE_SUPPORT";
8482 if (section_attributes & MachO::S_ATTR_SELF_MODIFYING_CODE)
8483 outs() << " SELF_MODIFYING_CODE";
8484 if (section_attributes & MachO::S_ATTR_DEBUG)
8485 outs() << " DEBUG";
8486 if (section_attributes & MachO::S_ATTR_SOME_INSTRUCTIONS)
8487 outs() << " SOME_INSTRUCTIONS";
8488 if (section_attributes & MachO::S_ATTR_EXT_RELOC)
8489 outs() << " EXT_RELOC";
8490 if (section_attributes & MachO::S_ATTR_LOC_RELOC)
8491 outs() << " LOC_RELOC";
8492 if (section_attributes == 0)
8493 outs() << " (none)";
8494 outs() << "\n";
8495 } else
8496 outs() << " flags " << format("0x%08" PRIx32, flags) << "\n";
8497 outs() << " reserved1 " << reserved1;
8498 if (section_type == MachO::S_SYMBOL_STUBS ||
8499 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
8500 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
8501 section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
8502 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS)
8503 outs() << " (index into indirect symbol table)\n";
8504 else
8505 outs() << "\n";
8506 outs() << " reserved2 " << reserved2;
8507 if (section_type == MachO::S_SYMBOL_STUBS)
8508 outs() << " (size of stubs)\n";
8509 else
8510 outs() << "\n";
8511}
8512
David Majnemer73cc6ff2014-11-13 19:48:56 +00008513static void PrintSymtabLoadCommand(MachO::symtab_command st, bool Is64Bit,
Kevin Enderby956366c2014-08-29 22:30:52 +00008514 uint32_t object_size) {
8515 outs() << " cmd LC_SYMTAB\n";
8516 outs() << " cmdsize " << st.cmdsize;
8517 if (st.cmdsize != sizeof(struct MachO::symtab_command))
8518 outs() << " Incorrect size\n";
8519 else
8520 outs() << "\n";
8521 outs() << " symoff " << st.symoff;
8522 if (st.symoff > object_size)
8523 outs() << " (past end of file)\n";
8524 else
8525 outs() << "\n";
8526 outs() << " nsyms " << st.nsyms;
8527 uint64_t big_size;
David Majnemer73cc6ff2014-11-13 19:48:56 +00008528 if (Is64Bit) {
Kevin Enderby956366c2014-08-29 22:30:52 +00008529 big_size = st.nsyms;
8530 big_size *= sizeof(struct MachO::nlist_64);
8531 big_size += st.symoff;
8532 if (big_size > object_size)
8533 outs() << " (past end of file)\n";
8534 else
8535 outs() << "\n";
8536 } else {
8537 big_size = st.nsyms;
8538 big_size *= sizeof(struct MachO::nlist);
8539 big_size += st.symoff;
8540 if (big_size > object_size)
8541 outs() << " (past end of file)\n";
8542 else
8543 outs() << "\n";
8544 }
8545 outs() << " stroff " << st.stroff;
8546 if (st.stroff > object_size)
8547 outs() << " (past end of file)\n";
8548 else
8549 outs() << "\n";
8550 outs() << " strsize " << st.strsize;
8551 big_size = st.stroff;
8552 big_size += st.strsize;
8553 if (big_size > object_size)
8554 outs() << " (past end of file)\n";
8555 else
8556 outs() << "\n";
8557}
8558
8559static void PrintDysymtabLoadCommand(MachO::dysymtab_command dyst,
8560 uint32_t nsyms, uint32_t object_size,
David Majnemer73cc6ff2014-11-13 19:48:56 +00008561 bool Is64Bit) {
Kevin Enderby956366c2014-08-29 22:30:52 +00008562 outs() << " cmd LC_DYSYMTAB\n";
8563 outs() << " cmdsize " << dyst.cmdsize;
8564 if (dyst.cmdsize != sizeof(struct MachO::dysymtab_command))
8565 outs() << " Incorrect size\n";
8566 else
8567 outs() << "\n";
8568 outs() << " ilocalsym " << dyst.ilocalsym;
8569 if (dyst.ilocalsym > nsyms)
8570 outs() << " (greater than the number of symbols)\n";
8571 else
8572 outs() << "\n";
8573 outs() << " nlocalsym " << dyst.nlocalsym;
8574 uint64_t big_size;
8575 big_size = dyst.ilocalsym;
8576 big_size += dyst.nlocalsym;
8577 if (big_size > nsyms)
8578 outs() << " (past the end of the symbol table)\n";
8579 else
8580 outs() << "\n";
8581 outs() << " iextdefsym " << dyst.iextdefsym;
8582 if (dyst.iextdefsym > nsyms)
8583 outs() << " (greater than the number of symbols)\n";
8584 else
8585 outs() << "\n";
8586 outs() << " nextdefsym " << dyst.nextdefsym;
8587 big_size = dyst.iextdefsym;
8588 big_size += dyst.nextdefsym;
8589 if (big_size > nsyms)
8590 outs() << " (past the end of the symbol table)\n";
8591 else
8592 outs() << "\n";
8593 outs() << " iundefsym " << dyst.iundefsym;
8594 if (dyst.iundefsym > nsyms)
8595 outs() << " (greater than the number of symbols)\n";
8596 else
8597 outs() << "\n";
8598 outs() << " nundefsym " << dyst.nundefsym;
8599 big_size = dyst.iundefsym;
8600 big_size += dyst.nundefsym;
8601 if (big_size > nsyms)
8602 outs() << " (past the end of the symbol table)\n";
8603 else
8604 outs() << "\n";
8605 outs() << " tocoff " << dyst.tocoff;
8606 if (dyst.tocoff > object_size)
8607 outs() << " (past end of file)\n";
8608 else
8609 outs() << "\n";
8610 outs() << " ntoc " << dyst.ntoc;
8611 big_size = dyst.ntoc;
8612 big_size *= sizeof(struct MachO::dylib_table_of_contents);
8613 big_size += dyst.tocoff;
8614 if (big_size > object_size)
8615 outs() << " (past end of file)\n";
8616 else
8617 outs() << "\n";
8618 outs() << " modtaboff " << dyst.modtaboff;
8619 if (dyst.modtaboff > object_size)
8620 outs() << " (past end of file)\n";
8621 else
8622 outs() << "\n";
8623 outs() << " nmodtab " << dyst.nmodtab;
8624 uint64_t modtabend;
David Majnemer73cc6ff2014-11-13 19:48:56 +00008625 if (Is64Bit) {
Kevin Enderby956366c2014-08-29 22:30:52 +00008626 modtabend = dyst.nmodtab;
8627 modtabend *= sizeof(struct MachO::dylib_module_64);
8628 modtabend += dyst.modtaboff;
8629 } else {
8630 modtabend = dyst.nmodtab;
8631 modtabend *= sizeof(struct MachO::dylib_module);
8632 modtabend += dyst.modtaboff;
8633 }
8634 if (modtabend > object_size)
8635 outs() << " (past end of file)\n";
8636 else
8637 outs() << "\n";
8638 outs() << " extrefsymoff " << dyst.extrefsymoff;
8639 if (dyst.extrefsymoff > object_size)
8640 outs() << " (past end of file)\n";
8641 else
8642 outs() << "\n";
8643 outs() << " nextrefsyms " << dyst.nextrefsyms;
8644 big_size = dyst.nextrefsyms;
8645 big_size *= sizeof(struct MachO::dylib_reference);
8646 big_size += dyst.extrefsymoff;
8647 if (big_size > object_size)
8648 outs() << " (past end of file)\n";
8649 else
8650 outs() << "\n";
8651 outs() << " indirectsymoff " << dyst.indirectsymoff;
8652 if (dyst.indirectsymoff > object_size)
8653 outs() << " (past end of file)\n";
8654 else
8655 outs() << "\n";
8656 outs() << " nindirectsyms " << dyst.nindirectsyms;
8657 big_size = dyst.nindirectsyms;
8658 big_size *= sizeof(uint32_t);
8659 big_size += dyst.indirectsymoff;
8660 if (big_size > object_size)
8661 outs() << " (past end of file)\n";
8662 else
8663 outs() << "\n";
8664 outs() << " extreloff " << dyst.extreloff;
8665 if (dyst.extreloff > object_size)
8666 outs() << " (past end of file)\n";
8667 else
8668 outs() << "\n";
8669 outs() << " nextrel " << dyst.nextrel;
8670 big_size = dyst.nextrel;
8671 big_size *= sizeof(struct MachO::relocation_info);
8672 big_size += dyst.extreloff;
8673 if (big_size > object_size)
8674 outs() << " (past end of file)\n";
8675 else
8676 outs() << "\n";
8677 outs() << " locreloff " << dyst.locreloff;
8678 if (dyst.locreloff > object_size)
8679 outs() << " (past end of file)\n";
8680 else
8681 outs() << "\n";
8682 outs() << " nlocrel " << dyst.nlocrel;
8683 big_size = dyst.nlocrel;
8684 big_size *= sizeof(struct MachO::relocation_info);
8685 big_size += dyst.locreloff;
8686 if (big_size > object_size)
8687 outs() << " (past end of file)\n";
8688 else
8689 outs() << "\n";
8690}
8691
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008692static void PrintDyldInfoLoadCommand(MachO::dyld_info_command dc,
8693 uint32_t object_size) {
8694 if (dc.cmd == MachO::LC_DYLD_INFO)
8695 outs() << " cmd LC_DYLD_INFO\n";
8696 else
8697 outs() << " cmd LC_DYLD_INFO_ONLY\n";
8698 outs() << " cmdsize " << dc.cmdsize;
8699 if (dc.cmdsize != sizeof(struct MachO::dyld_info_command))
8700 outs() << " Incorrect size\n";
8701 else
8702 outs() << "\n";
8703 outs() << " rebase_off " << dc.rebase_off;
8704 if (dc.rebase_off > object_size)
8705 outs() << " (past end of file)\n";
8706 else
8707 outs() << "\n";
8708 outs() << " rebase_size " << dc.rebase_size;
8709 uint64_t big_size;
8710 big_size = dc.rebase_off;
8711 big_size += dc.rebase_size;
8712 if (big_size > object_size)
8713 outs() << " (past end of file)\n";
8714 else
8715 outs() << "\n";
8716 outs() << " bind_off " << dc.bind_off;
8717 if (dc.bind_off > object_size)
8718 outs() << " (past end of file)\n";
8719 else
8720 outs() << "\n";
8721 outs() << " bind_size " << dc.bind_size;
8722 big_size = dc.bind_off;
8723 big_size += dc.bind_size;
8724 if (big_size > object_size)
8725 outs() << " (past end of file)\n";
8726 else
8727 outs() << "\n";
8728 outs() << " weak_bind_off " << dc.weak_bind_off;
8729 if (dc.weak_bind_off > object_size)
8730 outs() << " (past end of file)\n";
8731 else
8732 outs() << "\n";
8733 outs() << " weak_bind_size " << dc.weak_bind_size;
8734 big_size = dc.weak_bind_off;
8735 big_size += dc.weak_bind_size;
8736 if (big_size > object_size)
8737 outs() << " (past end of file)\n";
8738 else
8739 outs() << "\n";
8740 outs() << " lazy_bind_off " << dc.lazy_bind_off;
8741 if (dc.lazy_bind_off > object_size)
8742 outs() << " (past end of file)\n";
8743 else
8744 outs() << "\n";
8745 outs() << " lazy_bind_size " << dc.lazy_bind_size;
8746 big_size = dc.lazy_bind_off;
8747 big_size += dc.lazy_bind_size;
8748 if (big_size > object_size)
8749 outs() << " (past end of file)\n";
8750 else
8751 outs() << "\n";
8752 outs() << " export_off " << dc.export_off;
8753 if (dc.export_off > object_size)
8754 outs() << " (past end of file)\n";
8755 else
8756 outs() << "\n";
8757 outs() << " export_size " << dc.export_size;
8758 big_size = dc.export_off;
8759 big_size += dc.export_size;
8760 if (big_size > object_size)
8761 outs() << " (past end of file)\n";
8762 else
8763 outs() << "\n";
8764}
8765
8766static void PrintDyldLoadCommand(MachO::dylinker_command dyld,
8767 const char *Ptr) {
8768 if (dyld.cmd == MachO::LC_ID_DYLINKER)
8769 outs() << " cmd LC_ID_DYLINKER\n";
8770 else if (dyld.cmd == MachO::LC_LOAD_DYLINKER)
8771 outs() << " cmd LC_LOAD_DYLINKER\n";
8772 else if (dyld.cmd == MachO::LC_DYLD_ENVIRONMENT)
8773 outs() << " cmd LC_DYLD_ENVIRONMENT\n";
8774 else
8775 outs() << " cmd ?(" << dyld.cmd << ")\n";
8776 outs() << " cmdsize " << dyld.cmdsize;
8777 if (dyld.cmdsize < sizeof(struct MachO::dylinker_command))
8778 outs() << " Incorrect size\n";
8779 else
8780 outs() << "\n";
8781 if (dyld.name >= dyld.cmdsize)
8782 outs() << " name ?(bad offset " << dyld.name << ")\n";
8783 else {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00008784 const char *P = (const char *)(Ptr) + dyld.name;
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008785 outs() << " name " << P << " (offset " << dyld.name << ")\n";
8786 }
8787}
8788
8789static void PrintUuidLoadCommand(MachO::uuid_command uuid) {
8790 outs() << " cmd LC_UUID\n";
8791 outs() << " cmdsize " << uuid.cmdsize;
8792 if (uuid.cmdsize != sizeof(struct MachO::uuid_command))
8793 outs() << " Incorrect size\n";
8794 else
8795 outs() << "\n";
8796 outs() << " uuid ";
Davide Italianoc74277a2015-12-07 00:03:28 +00008797 for (int i = 0; i < 16; ++i) {
8798 outs() << format("%02" PRIX32, uuid.uuid[i]);
8799 if (i == 3 || i == 5 || i == 7 || i == 9)
8800 outs() << "-";
8801 }
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008802 outs() << "\n";
8803}
8804
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008805static void PrintRpathLoadCommand(MachO::rpath_command rpath, const char *Ptr) {
Jean-Daniel Dupas00cc1f52014-12-04 07:37:02 +00008806 outs() << " cmd LC_RPATH\n";
8807 outs() << " cmdsize " << rpath.cmdsize;
8808 if (rpath.cmdsize < sizeof(struct MachO::rpath_command))
8809 outs() << " Incorrect size\n";
8810 else
8811 outs() << "\n";
8812 if (rpath.path >= rpath.cmdsize)
8813 outs() << " path ?(bad offset " << rpath.path << ")\n";
8814 else {
8815 const char *P = (const char *)(Ptr) + rpath.path;
8816 outs() << " path " << P << " (offset " << rpath.path << ")\n";
8817 }
8818}
8819
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008820static void PrintVersionMinLoadCommand(MachO::version_min_command vd) {
Tim Northoverbfbfb122015-11-02 21:26:58 +00008821 StringRef LoadCmdName;
8822 switch (vd.cmd) {
8823 case MachO::LC_VERSION_MIN_MACOSX:
8824 LoadCmdName = "LC_VERSION_MIN_MACOSX";
8825 break;
8826 case MachO::LC_VERSION_MIN_IPHONEOS:
8827 LoadCmdName = "LC_VERSION_MIN_IPHONEOS";
8828 break;
8829 case MachO::LC_VERSION_MIN_TVOS:
8830 LoadCmdName = "LC_VERSION_MIN_TVOS";
8831 break;
8832 case MachO::LC_VERSION_MIN_WATCHOS:
8833 LoadCmdName = "LC_VERSION_MIN_WATCHOS";
8834 break;
8835 default:
8836 llvm_unreachable("Unknown version min load command");
8837 }
8838
8839 outs() << " cmd " << LoadCmdName << '\n';
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008840 outs() << " cmdsize " << vd.cmdsize;
8841 if (vd.cmdsize != sizeof(struct MachO::version_min_command))
8842 outs() << " Incorrect size\n";
8843 else
8844 outs() << "\n";
Davide Italiano56baef32015-08-26 12:26:11 +00008845 outs() << " version "
8846 << MachOObjectFile::getVersionMinMajor(vd, false) << "."
8847 << MachOObjectFile::getVersionMinMinor(vd, false);
8848 uint32_t Update = MachOObjectFile::getVersionMinUpdate(vd, false);
8849 if (Update != 0)
8850 outs() << "." << Update;
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008851 outs() << "\n";
8852 if (vd.sdk == 0)
Kevin Enderby57538292014-12-17 01:01:30 +00008853 outs() << " sdk n/a";
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008854 else {
Davide Italiano56baef32015-08-26 12:26:11 +00008855 outs() << " sdk "
8856 << MachOObjectFile::getVersionMinMajor(vd, true) << "."
8857 << MachOObjectFile::getVersionMinMinor(vd, true);
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008858 }
Davide Italiano56baef32015-08-26 12:26:11 +00008859 Update = MachOObjectFile::getVersionMinUpdate(vd, true);
8860 if (Update != 0)
8861 outs() << "." << Update;
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008862 outs() << "\n";
8863}
8864
Kevin Enderbya4579c42017-01-19 17:36:31 +00008865static void PrintNoteLoadCommand(MachO::note_command Nt) {
8866 outs() << " cmd LC_NOTE\n";
8867 outs() << " cmdsize " << Nt.cmdsize;
8868 if (Nt.cmdsize != sizeof(struct MachO::note_command))
8869 outs() << " Incorrect size\n";
8870 else
8871 outs() << "\n";
8872 const char *d = Nt.data_owner;
8873 outs() << "data_owner " << format("%.16s\n", d);
8874 outs() << " offset " << Nt.offset << "\n";
8875 outs() << " size " << Nt.size << "\n";
8876}
8877
Steven Wu5b54a422017-01-23 20:07:55 +00008878static void PrintBuildToolVersion(MachO::build_tool_version bv) {
8879 outs() << " tool " << MachOObjectFile::getBuildTool(bv.tool) << "\n";
8880 outs() << " version " << MachOObjectFile::getVersionString(bv.version)
8881 << "\n";
8882}
8883
8884static void PrintBuildVersionLoadCommand(const MachOObjectFile *obj,
8885 MachO::build_version_command bd) {
8886 outs() << " cmd LC_BUILD_VERSION\n";
8887 outs() << " cmdsize " << bd.cmdsize;
8888 if (bd.cmdsize !=
8889 sizeof(struct MachO::build_version_command) +
8890 bd.ntools * sizeof(struct MachO::build_tool_version))
8891 outs() << " Incorrect size\n";
8892 else
8893 outs() << "\n";
8894 outs() << " platform " << MachOObjectFile::getBuildPlatform(bd.platform)
8895 << "\n";
8896 if (bd.sdk)
8897 outs() << " sdk " << MachOObjectFile::getVersionString(bd.sdk)
8898 << "\n";
8899 else
8900 outs() << " sdk n/a\n";
8901 outs() << " minos " << MachOObjectFile::getVersionString(bd.minos)
8902 << "\n";
8903 outs() << " ntools " << bd.ntools << "\n";
8904 for (unsigned i = 0; i < bd.ntools; ++i) {
8905 MachO::build_tool_version bv = obj->getBuildToolVersion(i);
8906 PrintBuildToolVersion(bv);
8907 }
8908}
8909
Kevin Enderby8ae63c12014-09-04 16:54:47 +00008910static void PrintSourceVersionCommand(MachO::source_version_command sd) {
8911 outs() << " cmd LC_SOURCE_VERSION\n";
8912 outs() << " cmdsize " << sd.cmdsize;
8913 if (sd.cmdsize != sizeof(struct MachO::source_version_command))
8914 outs() << " Incorrect size\n";
8915 else
8916 outs() << "\n";
8917 uint64_t a = (sd.version >> 40) & 0xffffff;
8918 uint64_t b = (sd.version >> 30) & 0x3ff;
8919 uint64_t c = (sd.version >> 20) & 0x3ff;
8920 uint64_t d = (sd.version >> 10) & 0x3ff;
8921 uint64_t e = sd.version & 0x3ff;
8922 outs() << " version " << a << "." << b;
8923 if (e != 0)
8924 outs() << "." << c << "." << d << "." << e;
8925 else if (d != 0)
8926 outs() << "." << c << "." << d;
8927 else if (c != 0)
8928 outs() << "." << c;
8929 outs() << "\n";
8930}
8931
8932static void PrintEntryPointCommand(MachO::entry_point_command ep) {
8933 outs() << " cmd LC_MAIN\n";
8934 outs() << " cmdsize " << ep.cmdsize;
8935 if (ep.cmdsize != sizeof(struct MachO::entry_point_command))
8936 outs() << " Incorrect size\n";
8937 else
8938 outs() << "\n";
8939 outs() << " entryoff " << ep.entryoff << "\n";
8940 outs() << " stacksize " << ep.stacksize << "\n";
8941}
8942
Kevin Enderby0804f4672014-12-16 23:25:52 +00008943static void PrintEncryptionInfoCommand(MachO::encryption_info_command ec,
8944 uint32_t object_size) {
8945 outs() << " cmd LC_ENCRYPTION_INFO\n";
8946 outs() << " cmdsize " << ec.cmdsize;
8947 if (ec.cmdsize != sizeof(struct MachO::encryption_info_command))
8948 outs() << " Incorrect size\n";
8949 else
8950 outs() << "\n";
8951 outs() << " cryptoff " << ec.cryptoff;
8952 if (ec.cryptoff > object_size)
8953 outs() << " (past end of file)\n";
8954 else
8955 outs() << "\n";
8956 outs() << " cryptsize " << ec.cryptsize;
8957 if (ec.cryptsize > object_size)
8958 outs() << " (past end of file)\n";
8959 else
8960 outs() << "\n";
8961 outs() << " cryptid " << ec.cryptid << "\n";
8962}
8963
Kevin Enderby57538292014-12-17 01:01:30 +00008964static void PrintEncryptionInfoCommand64(MachO::encryption_info_command_64 ec,
Kevin Enderby66d51fc2015-01-08 00:25:24 +00008965 uint32_t object_size) {
Kevin Enderby57538292014-12-17 01:01:30 +00008966 outs() << " cmd LC_ENCRYPTION_INFO_64\n";
8967 outs() << " cmdsize " << ec.cmdsize;
8968 if (ec.cmdsize != sizeof(struct MachO::encryption_info_command_64))
8969 outs() << " Incorrect size\n";
8970 else
8971 outs() << "\n";
8972 outs() << " cryptoff " << ec.cryptoff;
8973 if (ec.cryptoff > object_size)
8974 outs() << " (past end of file)\n";
8975 else
8976 outs() << "\n";
8977 outs() << " cryptsize " << ec.cryptsize;
8978 if (ec.cryptsize > object_size)
8979 outs() << " (past end of file)\n";
8980 else
8981 outs() << "\n";
8982 outs() << " cryptid " << ec.cryptid << "\n";
8983 outs() << " pad " << ec.pad << "\n";
8984}
8985
Kevin Enderbyd0b6b7f2014-12-18 00:53:40 +00008986static void PrintLinkerOptionCommand(MachO::linker_option_command lo,
8987 const char *Ptr) {
8988 outs() << " cmd LC_LINKER_OPTION\n";
8989 outs() << " cmdsize " << lo.cmdsize;
8990 if (lo.cmdsize < sizeof(struct MachO::linker_option_command))
8991 outs() << " Incorrect size\n";
8992 else
8993 outs() << "\n";
8994 outs() << " count " << lo.count << "\n";
8995 const char *string = Ptr + sizeof(struct MachO::linker_option_command);
8996 uint32_t left = lo.cmdsize - sizeof(struct MachO::linker_option_command);
8997 uint32_t i = 0;
8998 while (left > 0) {
8999 while (*string == '\0' && left > 0) {
9000 string++;
9001 left--;
9002 }
9003 if (left > 0) {
9004 i++;
9005 outs() << " string #" << i << " " << format("%.*s\n", left, string);
David Majnemerd4449ed2014-12-20 08:24:43 +00009006 uint32_t NullPos = StringRef(string, left).find('\0');
9007 uint32_t len = std::min(NullPos, left) + 1;
Kevin Enderbyd0b6b7f2014-12-18 00:53:40 +00009008 string += len;
9009 left -= len;
9010 }
9011 }
9012 if (lo.count != i)
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009013 outs() << " count " << lo.count << " does not match number of strings "
9014 << i << "\n";
Kevin Enderbyd0b6b7f2014-12-18 00:53:40 +00009015}
9016
Kevin Enderbyb4b79312014-12-18 19:24:35 +00009017static void PrintSubFrameworkCommand(MachO::sub_framework_command sub,
9018 const char *Ptr) {
9019 outs() << " cmd LC_SUB_FRAMEWORK\n";
9020 outs() << " cmdsize " << sub.cmdsize;
9021 if (sub.cmdsize < sizeof(struct MachO::sub_framework_command))
9022 outs() << " Incorrect size\n";
9023 else
9024 outs() << "\n";
9025 if (sub.umbrella < sub.cmdsize) {
9026 const char *P = Ptr + sub.umbrella;
9027 outs() << " umbrella " << P << " (offset " << sub.umbrella << ")\n";
9028 } else {
9029 outs() << " umbrella ?(bad offset " << sub.umbrella << ")\n";
9030 }
9031}
9032
Kevin Enderbya2bd8d92014-12-18 23:13:26 +00009033static void PrintSubUmbrellaCommand(MachO::sub_umbrella_command sub,
9034 const char *Ptr) {
9035 outs() << " cmd LC_SUB_UMBRELLA\n";
9036 outs() << " cmdsize " << sub.cmdsize;
9037 if (sub.cmdsize < sizeof(struct MachO::sub_umbrella_command))
9038 outs() << " Incorrect size\n";
9039 else
9040 outs() << "\n";
9041 if (sub.sub_umbrella < sub.cmdsize) {
9042 const char *P = Ptr + sub.sub_umbrella;
9043 outs() << " sub_umbrella " << P << " (offset " << sub.sub_umbrella << ")\n";
9044 } else {
9045 outs() << " sub_umbrella ?(bad offset " << sub.sub_umbrella << ")\n";
9046 }
9047}
9048
Kevin Enderby36c8d3a2014-12-19 19:48:16 +00009049static void PrintSubLibraryCommand(MachO::sub_library_command sub,
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009050 const char *Ptr) {
Kevin Enderby36c8d3a2014-12-19 19:48:16 +00009051 outs() << " cmd LC_SUB_LIBRARY\n";
9052 outs() << " cmdsize " << sub.cmdsize;
9053 if (sub.cmdsize < sizeof(struct MachO::sub_library_command))
9054 outs() << " Incorrect size\n";
9055 else
9056 outs() << "\n";
9057 if (sub.sub_library < sub.cmdsize) {
9058 const char *P = Ptr + sub.sub_library;
9059 outs() << " sub_library " << P << " (offset " << sub.sub_library << ")\n";
9060 } else {
9061 outs() << " sub_library ?(bad offset " << sub.sub_library << ")\n";
9062 }
9063}
9064
Kevin Enderby186eac32014-12-19 21:06:24 +00009065static void PrintSubClientCommand(MachO::sub_client_command sub,
9066 const char *Ptr) {
9067 outs() << " cmd LC_SUB_CLIENT\n";
9068 outs() << " cmdsize " << sub.cmdsize;
9069 if (sub.cmdsize < sizeof(struct MachO::sub_client_command))
9070 outs() << " Incorrect size\n";
9071 else
9072 outs() << "\n";
9073 if (sub.client < sub.cmdsize) {
9074 const char *P = Ptr + sub.client;
9075 outs() << " client " << P << " (offset " << sub.client << ")\n";
9076 } else {
9077 outs() << " client ?(bad offset " << sub.client << ")\n";
9078 }
9079}
Kevin Enderby36c8d3a2014-12-19 19:48:16 +00009080
Kevin Enderby52e4ce42014-12-19 22:25:22 +00009081static void PrintRoutinesCommand(MachO::routines_command r) {
9082 outs() << " cmd LC_ROUTINES\n";
9083 outs() << " cmdsize " << r.cmdsize;
9084 if (r.cmdsize != sizeof(struct MachO::routines_command))
9085 outs() << " Incorrect size\n";
9086 else
9087 outs() << "\n";
9088 outs() << " init_address " << format("0x%08" PRIx32, r.init_address) << "\n";
9089 outs() << " init_module " << r.init_module << "\n";
9090 outs() << " reserved1 " << r.reserved1 << "\n";
9091 outs() << " reserved2 " << r.reserved2 << "\n";
9092 outs() << " reserved3 " << r.reserved3 << "\n";
9093 outs() << " reserved4 " << r.reserved4 << "\n";
9094 outs() << " reserved5 " << r.reserved5 << "\n";
9095 outs() << " reserved6 " << r.reserved6 << "\n";
9096}
9097
9098static void PrintRoutinesCommand64(MachO::routines_command_64 r) {
9099 outs() << " cmd LC_ROUTINES_64\n";
9100 outs() << " cmdsize " << r.cmdsize;
9101 if (r.cmdsize != sizeof(struct MachO::routines_command_64))
9102 outs() << " Incorrect size\n";
9103 else
9104 outs() << "\n";
9105 outs() << " init_address " << format("0x%016" PRIx64, r.init_address) << "\n";
9106 outs() << " init_module " << r.init_module << "\n";
9107 outs() << " reserved1 " << r.reserved1 << "\n";
9108 outs() << " reserved2 " << r.reserved2 << "\n";
9109 outs() << " reserved3 " << r.reserved3 << "\n";
9110 outs() << " reserved4 " << r.reserved4 << "\n";
9111 outs() << " reserved5 " << r.reserved5 << "\n";
9112 outs() << " reserved6 " << r.reserved6 << "\n";
9113}
9114
Kevin Enderbyc3a035d2017-01-23 21:13:29 +00009115static void Print_x86_thread_state32_t(MachO::x86_thread_state32_t &cpu32) {
9116 outs() << "\t eax " << format("0x%08" PRIx32, cpu32.eax);
9117 outs() << " ebx " << format("0x%08" PRIx32, cpu32.ebx);
9118 outs() << " ecx " << format("0x%08" PRIx32, cpu32.ecx);
9119 outs() << " edx " << format("0x%08" PRIx32, cpu32.edx) << "\n";
9120 outs() << "\t edi " << format("0x%08" PRIx32, cpu32.edi);
9121 outs() << " esi " << format("0x%08" PRIx32, cpu32.esi);
9122 outs() << " ebp " << format("0x%08" PRIx32, cpu32.ebp);
9123 outs() << " esp " << format("0x%08" PRIx32, cpu32.esp) << "\n";
9124 outs() << "\t ss " << format("0x%08" PRIx32, cpu32.ss);
9125 outs() << " eflags " << format("0x%08" PRIx32, cpu32.eflags);
9126 outs() << " eip " << format("0x%08" PRIx32, cpu32.eip);
9127 outs() << " cs " << format("0x%08" PRIx32, cpu32.cs) << "\n";
9128 outs() << "\t ds " << format("0x%08" PRIx32, cpu32.ds);
9129 outs() << " es " << format("0x%08" PRIx32, cpu32.es);
9130 outs() << " fs " << format("0x%08" PRIx32, cpu32.fs);
9131 outs() << " gs " << format("0x%08" PRIx32, cpu32.gs) << "\n";
9132}
9133
Kevin Enderby48ef5342014-12-23 22:56:39 +00009134static void Print_x86_thread_state64_t(MachO::x86_thread_state64_t &cpu64) {
9135 outs() << " rax " << format("0x%016" PRIx64, cpu64.rax);
9136 outs() << " rbx " << format("0x%016" PRIx64, cpu64.rbx);
9137 outs() << " rcx " << format("0x%016" PRIx64, cpu64.rcx) << "\n";
9138 outs() << " rdx " << format("0x%016" PRIx64, cpu64.rdx);
9139 outs() << " rdi " << format("0x%016" PRIx64, cpu64.rdi);
9140 outs() << " rsi " << format("0x%016" PRIx64, cpu64.rsi) << "\n";
9141 outs() << " rbp " << format("0x%016" PRIx64, cpu64.rbp);
9142 outs() << " rsp " << format("0x%016" PRIx64, cpu64.rsp);
9143 outs() << " r8 " << format("0x%016" PRIx64, cpu64.r8) << "\n";
9144 outs() << " r9 " << format("0x%016" PRIx64, cpu64.r9);
9145 outs() << " r10 " << format("0x%016" PRIx64, cpu64.r10);
9146 outs() << " r11 " << format("0x%016" PRIx64, cpu64.r11) << "\n";
9147 outs() << " r12 " << format("0x%016" PRIx64, cpu64.r12);
9148 outs() << " r13 " << format("0x%016" PRIx64, cpu64.r13);
9149 outs() << " r14 " << format("0x%016" PRIx64, cpu64.r14) << "\n";
9150 outs() << " r15 " << format("0x%016" PRIx64, cpu64.r15);
9151 outs() << " rip " << format("0x%016" PRIx64, cpu64.rip) << "\n";
9152 outs() << "rflags " << format("0x%016" PRIx64, cpu64.rflags);
9153 outs() << " cs " << format("0x%016" PRIx64, cpu64.cs);
9154 outs() << " fs " << format("0x%016" PRIx64, cpu64.fs) << "\n";
9155 outs() << " gs " << format("0x%016" PRIx64, cpu64.gs) << "\n";
9156}
9157
Kevin Enderby227df342014-12-23 23:43:59 +00009158static void Print_mmst_reg(MachO::mmst_reg_t &r) {
Kevin Enderby48ef5342014-12-23 22:56:39 +00009159 uint32_t f;
9160 outs() << "\t mmst_reg ";
9161 for (f = 0; f < 10; f++)
9162 outs() << format("%02" PRIx32, (r.mmst_reg[f] & 0xff)) << " ";
9163 outs() << "\n";
9164 outs() << "\t mmst_rsrv ";
9165 for (f = 0; f < 6; f++)
9166 outs() << format("%02" PRIx32, (r.mmst_rsrv[f] & 0xff)) << " ";
9167 outs() << "\n";
9168}
9169
Kevin Enderbyaefb0032014-12-24 00:16:51 +00009170static void Print_xmm_reg(MachO::xmm_reg_t &r) {
Kevin Enderby48ef5342014-12-23 22:56:39 +00009171 uint32_t f;
9172 outs() << "\t xmm_reg ";
9173 for (f = 0; f < 16; f++)
9174 outs() << format("%02" PRIx32, (r.xmm_reg[f] & 0xff)) << " ";
9175 outs() << "\n";
9176}
9177
9178static void Print_x86_float_state_t(MachO::x86_float_state64_t &fpu) {
9179 outs() << "\t fpu_reserved[0] " << fpu.fpu_reserved[0];
9180 outs() << " fpu_reserved[1] " << fpu.fpu_reserved[1] << "\n";
9181 outs() << "\t control: invalid " << fpu.fpu_fcw.invalid;
9182 outs() << " denorm " << fpu.fpu_fcw.denorm;
9183 outs() << " zdiv " << fpu.fpu_fcw.zdiv;
9184 outs() << " ovrfl " << fpu.fpu_fcw.ovrfl;
9185 outs() << " undfl " << fpu.fpu_fcw.undfl;
9186 outs() << " precis " << fpu.fpu_fcw.precis << "\n";
9187 outs() << "\t\t pc ";
9188 if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_24B)
9189 outs() << "FP_PREC_24B ";
9190 else if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_53B)
9191 outs() << "FP_PREC_53B ";
9192 else if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_64B)
9193 outs() << "FP_PREC_64B ";
9194 else
9195 outs() << fpu.fpu_fcw.pc << " ";
9196 outs() << "rc ";
9197 if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_NEAR)
9198 outs() << "FP_RND_NEAR ";
9199 else if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_DOWN)
9200 outs() << "FP_RND_DOWN ";
9201 else if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_UP)
9202 outs() << "FP_RND_UP ";
9203 else if (fpu.fpu_fcw.rc == MachO::x86_FP_CHOP)
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009204 outs() << "FP_CHOP ";
Kevin Enderby48ef5342014-12-23 22:56:39 +00009205 outs() << "\n";
9206 outs() << "\t status: invalid " << fpu.fpu_fsw.invalid;
9207 outs() << " denorm " << fpu.fpu_fsw.denorm;
9208 outs() << " zdiv " << fpu.fpu_fsw.zdiv;
9209 outs() << " ovrfl " << fpu.fpu_fsw.ovrfl;
9210 outs() << " undfl " << fpu.fpu_fsw.undfl;
9211 outs() << " precis " << fpu.fpu_fsw.precis;
9212 outs() << " stkflt " << fpu.fpu_fsw.stkflt << "\n";
9213 outs() << "\t errsumm " << fpu.fpu_fsw.errsumm;
9214 outs() << " c0 " << fpu.fpu_fsw.c0;
9215 outs() << " c1 " << fpu.fpu_fsw.c1;
9216 outs() << " c2 " << fpu.fpu_fsw.c2;
9217 outs() << " tos " << fpu.fpu_fsw.tos;
9218 outs() << " c3 " << fpu.fpu_fsw.c3;
9219 outs() << " busy " << fpu.fpu_fsw.busy << "\n";
9220 outs() << "\t fpu_ftw " << format("0x%02" PRIx32, fpu.fpu_ftw);
9221 outs() << " fpu_rsrv1 " << format("0x%02" PRIx32, fpu.fpu_rsrv1);
9222 outs() << " fpu_fop " << format("0x%04" PRIx32, fpu.fpu_fop);
9223 outs() << " fpu_ip " << format("0x%08" PRIx32, fpu.fpu_ip) << "\n";
9224 outs() << "\t fpu_cs " << format("0x%04" PRIx32, fpu.fpu_cs);
9225 outs() << " fpu_rsrv2 " << format("0x%04" PRIx32, fpu.fpu_rsrv2);
9226 outs() << " fpu_dp " << format("0x%08" PRIx32, fpu.fpu_dp);
9227 outs() << " fpu_ds " << format("0x%04" PRIx32, fpu.fpu_ds) << "\n";
9228 outs() << "\t fpu_rsrv3 " << format("0x%04" PRIx32, fpu.fpu_rsrv3);
9229 outs() << " fpu_mxcsr " << format("0x%08" PRIx32, fpu.fpu_mxcsr);
9230 outs() << " fpu_mxcsrmask " << format("0x%08" PRIx32, fpu.fpu_mxcsrmask);
9231 outs() << "\n";
9232 outs() << "\t fpu_stmm0:\n";
9233 Print_mmst_reg(fpu.fpu_stmm0);
9234 outs() << "\t fpu_stmm1:\n";
9235 Print_mmst_reg(fpu.fpu_stmm1);
9236 outs() << "\t fpu_stmm2:\n";
9237 Print_mmst_reg(fpu.fpu_stmm2);
9238 outs() << "\t fpu_stmm3:\n";
9239 Print_mmst_reg(fpu.fpu_stmm3);
9240 outs() << "\t fpu_stmm4:\n";
9241 Print_mmst_reg(fpu.fpu_stmm4);
9242 outs() << "\t fpu_stmm5:\n";
9243 Print_mmst_reg(fpu.fpu_stmm5);
9244 outs() << "\t fpu_stmm6:\n";
9245 Print_mmst_reg(fpu.fpu_stmm6);
9246 outs() << "\t fpu_stmm7:\n";
9247 Print_mmst_reg(fpu.fpu_stmm7);
9248 outs() << "\t fpu_xmm0:\n";
9249 Print_xmm_reg(fpu.fpu_xmm0);
9250 outs() << "\t fpu_xmm1:\n";
9251 Print_xmm_reg(fpu.fpu_xmm1);
9252 outs() << "\t fpu_xmm2:\n";
9253 Print_xmm_reg(fpu.fpu_xmm2);
9254 outs() << "\t fpu_xmm3:\n";
9255 Print_xmm_reg(fpu.fpu_xmm3);
9256 outs() << "\t fpu_xmm4:\n";
9257 Print_xmm_reg(fpu.fpu_xmm4);
9258 outs() << "\t fpu_xmm5:\n";
9259 Print_xmm_reg(fpu.fpu_xmm5);
9260 outs() << "\t fpu_xmm6:\n";
9261 Print_xmm_reg(fpu.fpu_xmm6);
9262 outs() << "\t fpu_xmm7:\n";
9263 Print_xmm_reg(fpu.fpu_xmm7);
9264 outs() << "\t fpu_xmm8:\n";
9265 Print_xmm_reg(fpu.fpu_xmm8);
9266 outs() << "\t fpu_xmm9:\n";
9267 Print_xmm_reg(fpu.fpu_xmm9);
9268 outs() << "\t fpu_xmm10:\n";
9269 Print_xmm_reg(fpu.fpu_xmm10);
9270 outs() << "\t fpu_xmm11:\n";
9271 Print_xmm_reg(fpu.fpu_xmm11);
9272 outs() << "\t fpu_xmm12:\n";
9273 Print_xmm_reg(fpu.fpu_xmm12);
9274 outs() << "\t fpu_xmm13:\n";
9275 Print_xmm_reg(fpu.fpu_xmm13);
9276 outs() << "\t fpu_xmm14:\n";
9277 Print_xmm_reg(fpu.fpu_xmm14);
9278 outs() << "\t fpu_xmm15:\n";
9279 Print_xmm_reg(fpu.fpu_xmm15);
9280 outs() << "\t fpu_rsrv4:\n";
9281 for (uint32_t f = 0; f < 6; f++) {
9282 outs() << "\t ";
9283 for (uint32_t g = 0; g < 16; g++)
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009284 outs() << format("%02" PRIx32, fpu.fpu_rsrv4[f * g]) << " ";
Kevin Enderby48ef5342014-12-23 22:56:39 +00009285 outs() << "\n";
9286 }
9287 outs() << "\t fpu_reserved1 " << format("0x%08" PRIx32, fpu.fpu_reserved1);
9288 outs() << "\n";
9289}
9290
9291static void Print_x86_exception_state_t(MachO::x86_exception_state64_t &exc64) {
9292 outs() << "\t trapno " << format("0x%08" PRIx32, exc64.trapno);
9293 outs() << " err " << format("0x%08" PRIx32, exc64.err);
9294 outs() << " faultvaddr " << format("0x%016" PRIx64, exc64.faultvaddr) << "\n";
9295}
9296
Kevin Enderby41c9c002016-10-21 18:22:35 +00009297static void Print_arm_thread_state32_t(MachO::arm_thread_state32_t &cpu32) {
9298 outs() << "\t r0 " << format("0x%08" PRIx32, cpu32.r[0]);
9299 outs() << " r1 " << format("0x%08" PRIx32, cpu32.r[1]);
9300 outs() << " r2 " << format("0x%08" PRIx32, cpu32.r[2]);
9301 outs() << " r3 " << format("0x%08" PRIx32, cpu32.r[3]) << "\n";
9302 outs() << "\t r4 " << format("0x%08" PRIx32, cpu32.r[4]);
9303 outs() << " r5 " << format("0x%08" PRIx32, cpu32.r[5]);
9304 outs() << " r6 " << format("0x%08" PRIx32, cpu32.r[6]);
9305 outs() << " r7 " << format("0x%08" PRIx32, cpu32.r[7]) << "\n";
9306 outs() << "\t r8 " << format("0x%08" PRIx32, cpu32.r[8]);
9307 outs() << " r9 " << format("0x%08" PRIx32, cpu32.r[9]);
9308 outs() << " r10 " << format("0x%08" PRIx32, cpu32.r[10]);
9309 outs() << " r11 " << format("0x%08" PRIx32, cpu32.r[11]) << "\n";
9310 outs() << "\t r12 " << format("0x%08" PRIx32, cpu32.r[12]);
9311 outs() << " sp " << format("0x%08" PRIx32, cpu32.sp);
9312 outs() << " lr " << format("0x%08" PRIx32, cpu32.lr);
9313 outs() << " pc " << format("0x%08" PRIx32, cpu32.pc) << "\n";
9314 outs() << "\t cpsr " << format("0x%08" PRIx32, cpu32.cpsr) << "\n";
9315}
9316
Kevin Enderby7747cb52016-11-03 20:51:28 +00009317static void Print_arm_thread_state64_t(MachO::arm_thread_state64_t &cpu64) {
9318 outs() << "\t x0 " << format("0x%016" PRIx64, cpu64.x[0]);
9319 outs() << " x1 " << format("0x%016" PRIx64, cpu64.x[1]);
9320 outs() << " x2 " << format("0x%016" PRIx64, cpu64.x[2]) << "\n";
9321 outs() << "\t x3 " << format("0x%016" PRIx64, cpu64.x[3]);
9322 outs() << " x4 " << format("0x%016" PRIx64, cpu64.x[4]);
9323 outs() << " x5 " << format("0x%016" PRIx64, cpu64.x[5]) << "\n";
9324 outs() << "\t x6 " << format("0x%016" PRIx64, cpu64.x[6]);
9325 outs() << " x7 " << format("0x%016" PRIx64, cpu64.x[7]);
9326 outs() << " x8 " << format("0x%016" PRIx64, cpu64.x[8]) << "\n";
9327 outs() << "\t x9 " << format("0x%016" PRIx64, cpu64.x[9]);
9328 outs() << " x10 " << format("0x%016" PRIx64, cpu64.x[10]);
9329 outs() << " x11 " << format("0x%016" PRIx64, cpu64.x[11]) << "\n";
9330 outs() << "\t x12 " << format("0x%016" PRIx64, cpu64.x[12]);
9331 outs() << " x13 " << format("0x%016" PRIx64, cpu64.x[13]);
9332 outs() << " x14 " << format("0x%016" PRIx64, cpu64.x[14]) << "\n";
9333 outs() << "\t x15 " << format("0x%016" PRIx64, cpu64.x[15]);
9334 outs() << " x16 " << format("0x%016" PRIx64, cpu64.x[16]);
9335 outs() << " x17 " << format("0x%016" PRIx64, cpu64.x[17]) << "\n";
9336 outs() << "\t x18 " << format("0x%016" PRIx64, cpu64.x[18]);
9337 outs() << " x19 " << format("0x%016" PRIx64, cpu64.x[19]);
9338 outs() << " x20 " << format("0x%016" PRIx64, cpu64.x[20]) << "\n";
9339 outs() << "\t x21 " << format("0x%016" PRIx64, cpu64.x[21]);
9340 outs() << " x22 " << format("0x%016" PRIx64, cpu64.x[22]);
9341 outs() << " x23 " << format("0x%016" PRIx64, cpu64.x[23]) << "\n";
9342 outs() << "\t x24 " << format("0x%016" PRIx64, cpu64.x[24]);
9343 outs() << " x25 " << format("0x%016" PRIx64, cpu64.x[25]);
9344 outs() << " x26 " << format("0x%016" PRIx64, cpu64.x[26]) << "\n";
9345 outs() << "\t x27 " << format("0x%016" PRIx64, cpu64.x[27]);
9346 outs() << " x28 " << format("0x%016" PRIx64, cpu64.x[28]);
9347 outs() << " fp " << format("0x%016" PRIx64, cpu64.fp) << "\n";
9348 outs() << "\t lr " << format("0x%016" PRIx64, cpu64.lr);
9349 outs() << " sp " << format("0x%016" PRIx64, cpu64.sp);
9350 outs() << " pc " << format("0x%016" PRIx64, cpu64.pc) << "\n";
9351 outs() << "\t cpsr " << format("0x%08" PRIx32, cpu64.cpsr) << "\n";
9352}
9353
Kevin Enderby48ef5342014-12-23 22:56:39 +00009354static void PrintThreadCommand(MachO::thread_command t, const char *Ptr,
9355 bool isLittleEndian, uint32_t cputype) {
9356 if (t.cmd == MachO::LC_THREAD)
9357 outs() << " cmd LC_THREAD\n";
9358 else if (t.cmd == MachO::LC_UNIXTHREAD)
9359 outs() << " cmd LC_UNIXTHREAD\n";
9360 else
9361 outs() << " cmd " << t.cmd << " (unknown)\n";
9362 outs() << " cmdsize " << t.cmdsize;
9363 if (t.cmdsize < sizeof(struct MachO::thread_command) + 2 * sizeof(uint32_t))
9364 outs() << " Incorrect size\n";
9365 else
9366 outs() << "\n";
9367
9368 const char *begin = Ptr + sizeof(struct MachO::thread_command);
9369 const char *end = Ptr + t.cmdsize;
9370 uint32_t flavor, count, left;
Kevin Enderbyc3a035d2017-01-23 21:13:29 +00009371 if (cputype == MachO::CPU_TYPE_I386) {
9372 while (begin < end) {
9373 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9374 memcpy((char *)&flavor, begin, sizeof(uint32_t));
9375 begin += sizeof(uint32_t);
9376 } else {
9377 flavor = 0;
9378 begin = end;
9379 }
9380 if (isLittleEndian != sys::IsLittleEndianHost)
9381 sys::swapByteOrder(flavor);
9382 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9383 memcpy((char *)&count, begin, sizeof(uint32_t));
9384 begin += sizeof(uint32_t);
9385 } else {
9386 count = 0;
9387 begin = end;
9388 }
9389 if (isLittleEndian != sys::IsLittleEndianHost)
9390 sys::swapByteOrder(count);
9391 if (flavor == MachO::x86_THREAD_STATE32) {
9392 outs() << " flavor i386_THREAD_STATE\n";
9393 if (count == MachO::x86_THREAD_STATE32_COUNT)
9394 outs() << " count i386_THREAD_STATE_COUNT\n";
9395 else
9396 outs() << " count " << count
9397 << " (not x86_THREAD_STATE32_COUNT)\n";
9398 MachO::x86_thread_state32_t cpu32;
9399 left = end - begin;
9400 if (left >= sizeof(MachO::x86_thread_state32_t)) {
9401 memcpy(&cpu32, begin, sizeof(MachO::x86_thread_state32_t));
9402 begin += sizeof(MachO::x86_thread_state32_t);
9403 } else {
9404 memset(&cpu32, '\0', sizeof(MachO::x86_thread_state32_t));
9405 memcpy(&cpu32, begin, left);
9406 begin += left;
9407 }
9408 if (isLittleEndian != sys::IsLittleEndianHost)
9409 swapStruct(cpu32);
9410 Print_x86_thread_state32_t(cpu32);
9411 } else if (flavor == MachO::x86_THREAD_STATE) {
9412 outs() << " flavor x86_THREAD_STATE\n";
9413 if (count == MachO::x86_THREAD_STATE_COUNT)
9414 outs() << " count x86_THREAD_STATE_COUNT\n";
9415 else
9416 outs() << " count " << count
9417 << " (not x86_THREAD_STATE_COUNT)\n";
9418 struct MachO::x86_thread_state_t ts;
9419 left = end - begin;
9420 if (left >= sizeof(MachO::x86_thread_state_t)) {
9421 memcpy(&ts, begin, sizeof(MachO::x86_thread_state_t));
9422 begin += sizeof(MachO::x86_thread_state_t);
9423 } else {
9424 memset(&ts, '\0', sizeof(MachO::x86_thread_state_t));
9425 memcpy(&ts, begin, left);
9426 begin += left;
9427 }
9428 if (isLittleEndian != sys::IsLittleEndianHost)
9429 swapStruct(ts);
9430 if (ts.tsh.flavor == MachO::x86_THREAD_STATE32) {
9431 outs() << "\t tsh.flavor x86_THREAD_STATE32 ";
9432 if (ts.tsh.count == MachO::x86_THREAD_STATE32_COUNT)
9433 outs() << "tsh.count x86_THREAD_STATE32_COUNT\n";
9434 else
9435 outs() << "tsh.count " << ts.tsh.count
9436 << " (not x86_THREAD_STATE32_COUNT\n";
9437 Print_x86_thread_state32_t(ts.uts.ts32);
9438 } else {
9439 outs() << "\t tsh.flavor " << ts.tsh.flavor << " tsh.count "
9440 << ts.tsh.count << "\n";
9441 }
9442 } else {
9443 outs() << " flavor " << flavor << " (unknown)\n";
9444 outs() << " count " << count << "\n";
9445 outs() << " state (unknown)\n";
9446 begin += count * sizeof(uint32_t);
9447 }
9448 }
9449 } else if (cputype == MachO::CPU_TYPE_X86_64) {
Kevin Enderby48ef5342014-12-23 22:56:39 +00009450 while (begin < end) {
9451 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9452 memcpy((char *)&flavor, begin, sizeof(uint32_t));
9453 begin += sizeof(uint32_t);
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009454 } else {
Kevin Enderby48ef5342014-12-23 22:56:39 +00009455 flavor = 0;
9456 begin = end;
9457 }
9458 if (isLittleEndian != sys::IsLittleEndianHost)
9459 sys::swapByteOrder(flavor);
9460 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9461 memcpy((char *)&count, begin, sizeof(uint32_t));
9462 begin += sizeof(uint32_t);
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009463 } else {
Kevin Enderby48ef5342014-12-23 22:56:39 +00009464 count = 0;
9465 begin = end;
9466 }
9467 if (isLittleEndian != sys::IsLittleEndianHost)
9468 sys::swapByteOrder(count);
9469 if (flavor == MachO::x86_THREAD_STATE64) {
9470 outs() << " flavor x86_THREAD_STATE64\n";
9471 if (count == MachO::x86_THREAD_STATE64_COUNT)
9472 outs() << " count x86_THREAD_STATE64_COUNT\n";
9473 else
9474 outs() << " count " << count
9475 << " (not x86_THREAD_STATE64_COUNT)\n";
9476 MachO::x86_thread_state64_t cpu64;
9477 left = end - begin;
9478 if (left >= sizeof(MachO::x86_thread_state64_t)) {
9479 memcpy(&cpu64, begin, sizeof(MachO::x86_thread_state64_t));
9480 begin += sizeof(MachO::x86_thread_state64_t);
9481 } else {
9482 memset(&cpu64, '\0', sizeof(MachO::x86_thread_state64_t));
9483 memcpy(&cpu64, begin, left);
9484 begin += left;
9485 }
9486 if (isLittleEndian != sys::IsLittleEndianHost)
9487 swapStruct(cpu64);
9488 Print_x86_thread_state64_t(cpu64);
9489 } else if (flavor == MachO::x86_THREAD_STATE) {
9490 outs() << " flavor x86_THREAD_STATE\n";
9491 if (count == MachO::x86_THREAD_STATE_COUNT)
9492 outs() << " count x86_THREAD_STATE_COUNT\n";
9493 else
9494 outs() << " count " << count
9495 << " (not x86_THREAD_STATE_COUNT)\n";
9496 struct MachO::x86_thread_state_t ts;
9497 left = end - begin;
9498 if (left >= sizeof(MachO::x86_thread_state_t)) {
9499 memcpy(&ts, begin, sizeof(MachO::x86_thread_state_t));
9500 begin += sizeof(MachO::x86_thread_state_t);
9501 } else {
9502 memset(&ts, '\0', sizeof(MachO::x86_thread_state_t));
9503 memcpy(&ts, begin, left);
9504 begin += left;
9505 }
9506 if (isLittleEndian != sys::IsLittleEndianHost)
9507 swapStruct(ts);
9508 if (ts.tsh.flavor == MachO::x86_THREAD_STATE64) {
9509 outs() << "\t tsh.flavor x86_THREAD_STATE64 ";
9510 if (ts.tsh.count == MachO::x86_THREAD_STATE64_COUNT)
9511 outs() << "tsh.count x86_THREAD_STATE64_COUNT\n";
9512 else
9513 outs() << "tsh.count " << ts.tsh.count
9514 << " (not x86_THREAD_STATE64_COUNT\n";
9515 Print_x86_thread_state64_t(ts.uts.ts64);
9516 } else {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009517 outs() << "\t tsh.flavor " << ts.tsh.flavor << " tsh.count "
9518 << ts.tsh.count << "\n";
Kevin Enderby48ef5342014-12-23 22:56:39 +00009519 }
9520 } else if (flavor == MachO::x86_FLOAT_STATE) {
9521 outs() << " flavor x86_FLOAT_STATE\n";
9522 if (count == MachO::x86_FLOAT_STATE_COUNT)
9523 outs() << " count x86_FLOAT_STATE_COUNT\n";
9524 else
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009525 outs() << " count " << count << " (not x86_FLOAT_STATE_COUNT)\n";
Kevin Enderby48ef5342014-12-23 22:56:39 +00009526 struct MachO::x86_float_state_t fs;
9527 left = end - begin;
9528 if (left >= sizeof(MachO::x86_float_state_t)) {
9529 memcpy(&fs, begin, sizeof(MachO::x86_float_state_t));
9530 begin += sizeof(MachO::x86_float_state_t);
9531 } else {
9532 memset(&fs, '\0', sizeof(MachO::x86_float_state_t));
9533 memcpy(&fs, begin, left);
9534 begin += left;
9535 }
9536 if (isLittleEndian != sys::IsLittleEndianHost)
9537 swapStruct(fs);
9538 if (fs.fsh.flavor == MachO::x86_FLOAT_STATE64) {
9539 outs() << "\t fsh.flavor x86_FLOAT_STATE64 ";
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009540 if (fs.fsh.count == MachO::x86_FLOAT_STATE64_COUNT)
Kevin Enderby48ef5342014-12-23 22:56:39 +00009541 outs() << "fsh.count x86_FLOAT_STATE64_COUNT\n";
9542 else
9543 outs() << "fsh.count " << fs.fsh.count
9544 << " (not x86_FLOAT_STATE64_COUNT\n";
9545 Print_x86_float_state_t(fs.ufs.fs64);
9546 } else {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009547 outs() << "\t fsh.flavor " << fs.fsh.flavor << " fsh.count "
9548 << fs.fsh.count << "\n";
Kevin Enderby48ef5342014-12-23 22:56:39 +00009549 }
9550 } else if (flavor == MachO::x86_EXCEPTION_STATE) {
9551 outs() << " flavor x86_EXCEPTION_STATE\n";
9552 if (count == MachO::x86_EXCEPTION_STATE_COUNT)
9553 outs() << " count x86_EXCEPTION_STATE_COUNT\n";
9554 else
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009555 outs() << " count " << count
Kevin Enderby48ef5342014-12-23 22:56:39 +00009556 << " (not x86_EXCEPTION_STATE_COUNT)\n";
9557 struct MachO::x86_exception_state_t es;
9558 left = end - begin;
9559 if (left >= sizeof(MachO::x86_exception_state_t)) {
9560 memcpy(&es, begin, sizeof(MachO::x86_exception_state_t));
9561 begin += sizeof(MachO::x86_exception_state_t);
9562 } else {
9563 memset(&es, '\0', sizeof(MachO::x86_exception_state_t));
9564 memcpy(&es, begin, left);
9565 begin += left;
9566 }
9567 if (isLittleEndian != sys::IsLittleEndianHost)
9568 swapStruct(es);
9569 if (es.esh.flavor == MachO::x86_EXCEPTION_STATE64) {
9570 outs() << "\t esh.flavor x86_EXCEPTION_STATE64\n";
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009571 if (es.esh.count == MachO::x86_EXCEPTION_STATE64_COUNT)
Kevin Enderby48ef5342014-12-23 22:56:39 +00009572 outs() << "\t esh.count x86_EXCEPTION_STATE64_COUNT\n";
9573 else
9574 outs() << "\t esh.count " << es.esh.count
9575 << " (not x86_EXCEPTION_STATE64_COUNT\n";
9576 Print_x86_exception_state_t(es.ues.es64);
9577 } else {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009578 outs() << "\t esh.flavor " << es.esh.flavor << " esh.count "
9579 << es.esh.count << "\n";
Kevin Enderby48ef5342014-12-23 22:56:39 +00009580 }
Kevin Enderby299cd892018-03-08 23:10:38 +00009581 } else if (flavor == MachO::x86_EXCEPTION_STATE64) {
9582 outs() << " flavor x86_EXCEPTION_STATE64\n";
9583 if (count == MachO::x86_EXCEPTION_STATE64_COUNT)
9584 outs() << " count x86_EXCEPTION_STATE64_COUNT\n";
9585 else
9586 outs() << " count " << count
9587 << " (not x86_EXCEPTION_STATE64_COUNT)\n";
9588 struct MachO::x86_exception_state64_t es64;
9589 left = end - begin;
9590 if (left >= sizeof(MachO::x86_exception_state64_t)) {
9591 memcpy(&es64, begin, sizeof(MachO::x86_exception_state64_t));
9592 begin += sizeof(MachO::x86_exception_state64_t);
9593 } else {
9594 memset(&es64, '\0', sizeof(MachO::x86_exception_state64_t));
9595 memcpy(&es64, begin, left);
9596 begin += left;
9597 }
9598 if (isLittleEndian != sys::IsLittleEndianHost)
9599 swapStruct(es64);
9600 Print_x86_exception_state_t(es64);
Kevin Enderby48ef5342014-12-23 22:56:39 +00009601 } else {
9602 outs() << " flavor " << flavor << " (unknown)\n";
9603 outs() << " count " << count << "\n";
9604 outs() << " state (unknown)\n";
9605 begin += count * sizeof(uint32_t);
9606 }
9607 }
Kevin Enderby41c9c002016-10-21 18:22:35 +00009608 } else if (cputype == MachO::CPU_TYPE_ARM) {
9609 while (begin < end) {
9610 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9611 memcpy((char *)&flavor, begin, sizeof(uint32_t));
9612 begin += sizeof(uint32_t);
9613 } else {
9614 flavor = 0;
9615 begin = end;
9616 }
9617 if (isLittleEndian != sys::IsLittleEndianHost)
9618 sys::swapByteOrder(flavor);
9619 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9620 memcpy((char *)&count, begin, sizeof(uint32_t));
9621 begin += sizeof(uint32_t);
9622 } else {
9623 count = 0;
9624 begin = end;
9625 }
9626 if (isLittleEndian != sys::IsLittleEndianHost)
9627 sys::swapByteOrder(count);
9628 if (flavor == MachO::ARM_THREAD_STATE) {
9629 outs() << " flavor ARM_THREAD_STATE\n";
9630 if (count == MachO::ARM_THREAD_STATE_COUNT)
9631 outs() << " count ARM_THREAD_STATE_COUNT\n";
9632 else
9633 outs() << " count " << count
9634 << " (not ARM_THREAD_STATE_COUNT)\n";
9635 MachO::arm_thread_state32_t cpu32;
9636 left = end - begin;
9637 if (left >= sizeof(MachO::arm_thread_state32_t)) {
9638 memcpy(&cpu32, begin, sizeof(MachO::arm_thread_state32_t));
9639 begin += sizeof(MachO::arm_thread_state32_t);
9640 } else {
9641 memset(&cpu32, '\0', sizeof(MachO::arm_thread_state32_t));
9642 memcpy(&cpu32, begin, left);
9643 begin += left;
9644 }
9645 if (isLittleEndian != sys::IsLittleEndianHost)
9646 swapStruct(cpu32);
9647 Print_arm_thread_state32_t(cpu32);
9648 } else {
9649 outs() << " flavor " << flavor << " (unknown)\n";
9650 outs() << " count " << count << "\n";
9651 outs() << " state (unknown)\n";
9652 begin += count * sizeof(uint32_t);
9653 }
9654 }
Kevin Enderby7747cb52016-11-03 20:51:28 +00009655 } else if (cputype == MachO::CPU_TYPE_ARM64) {
9656 while (begin < end) {
9657 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9658 memcpy((char *)&flavor, begin, sizeof(uint32_t));
9659 begin += sizeof(uint32_t);
9660 } else {
9661 flavor = 0;
9662 begin = end;
9663 }
9664 if (isLittleEndian != sys::IsLittleEndianHost)
9665 sys::swapByteOrder(flavor);
9666 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9667 memcpy((char *)&count, begin, sizeof(uint32_t));
9668 begin += sizeof(uint32_t);
9669 } else {
9670 count = 0;
9671 begin = end;
9672 }
9673 if (isLittleEndian != sys::IsLittleEndianHost)
9674 sys::swapByteOrder(count);
9675 if (flavor == MachO::ARM_THREAD_STATE64) {
9676 outs() << " flavor ARM_THREAD_STATE64\n";
9677 if (count == MachO::ARM_THREAD_STATE64_COUNT)
9678 outs() << " count ARM_THREAD_STATE64_COUNT\n";
9679 else
9680 outs() << " count " << count
9681 << " (not ARM_THREAD_STATE64_COUNT)\n";
9682 MachO::arm_thread_state64_t cpu64;
9683 left = end - begin;
9684 if (left >= sizeof(MachO::arm_thread_state64_t)) {
9685 memcpy(&cpu64, begin, sizeof(MachO::arm_thread_state64_t));
9686 begin += sizeof(MachO::arm_thread_state64_t);
9687 } else {
9688 memset(&cpu64, '\0', sizeof(MachO::arm_thread_state64_t));
9689 memcpy(&cpu64, begin, left);
9690 begin += left;
9691 }
9692 if (isLittleEndian != sys::IsLittleEndianHost)
9693 swapStruct(cpu64);
9694 Print_arm_thread_state64_t(cpu64);
9695 } else {
9696 outs() << " flavor " << flavor << " (unknown)\n";
9697 outs() << " count " << count << "\n";
9698 outs() << " state (unknown)\n";
9699 begin += count * sizeof(uint32_t);
9700 }
9701 }
Kevin Enderby48ef5342014-12-23 22:56:39 +00009702 } else {
9703 while (begin < end) {
9704 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9705 memcpy((char *)&flavor, begin, sizeof(uint32_t));
9706 begin += sizeof(uint32_t);
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009707 } else {
Kevin Enderby48ef5342014-12-23 22:56:39 +00009708 flavor = 0;
9709 begin = end;
9710 }
9711 if (isLittleEndian != sys::IsLittleEndianHost)
9712 sys::swapByteOrder(flavor);
9713 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9714 memcpy((char *)&count, begin, sizeof(uint32_t));
9715 begin += sizeof(uint32_t);
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009716 } else {
Kevin Enderby48ef5342014-12-23 22:56:39 +00009717 count = 0;
9718 begin = end;
9719 }
9720 if (isLittleEndian != sys::IsLittleEndianHost)
9721 sys::swapByteOrder(count);
9722 outs() << " flavor " << flavor << "\n";
9723 outs() << " count " << count << "\n";
9724 outs() << " state (Unknown cputype/cpusubtype)\n";
9725 begin += count * sizeof(uint32_t);
9726 }
9727 }
9728}
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009729
Kevin Enderby8ae63c12014-09-04 16:54:47 +00009730static void PrintDylibCommand(MachO::dylib_command dl, const char *Ptr) {
9731 if (dl.cmd == MachO::LC_ID_DYLIB)
9732 outs() << " cmd LC_ID_DYLIB\n";
9733 else if (dl.cmd == MachO::LC_LOAD_DYLIB)
9734 outs() << " cmd LC_LOAD_DYLIB\n";
9735 else if (dl.cmd == MachO::LC_LOAD_WEAK_DYLIB)
9736 outs() << " cmd LC_LOAD_WEAK_DYLIB\n";
9737 else if (dl.cmd == MachO::LC_REEXPORT_DYLIB)
9738 outs() << " cmd LC_REEXPORT_DYLIB\n";
9739 else if (dl.cmd == MachO::LC_LAZY_LOAD_DYLIB)
9740 outs() << " cmd LC_LAZY_LOAD_DYLIB\n";
9741 else if (dl.cmd == MachO::LC_LOAD_UPWARD_DYLIB)
9742 outs() << " cmd LC_LOAD_UPWARD_DYLIB\n";
9743 else
9744 outs() << " cmd " << dl.cmd << " (unknown)\n";
9745 outs() << " cmdsize " << dl.cmdsize;
9746 if (dl.cmdsize < sizeof(struct MachO::dylib_command))
9747 outs() << " Incorrect size\n";
9748 else
9749 outs() << "\n";
9750 if (dl.dylib.name < dl.cmdsize) {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00009751 const char *P = (const char *)(Ptr) + dl.dylib.name;
Kevin Enderby8ae63c12014-09-04 16:54:47 +00009752 outs() << " name " << P << " (offset " << dl.dylib.name << ")\n";
9753 } else {
9754 outs() << " name ?(bad offset " << dl.dylib.name << ")\n";
9755 }
9756 outs() << " time stamp " << dl.dylib.timestamp << " ";
9757 time_t t = dl.dylib.timestamp;
9758 outs() << ctime(&t);
9759 outs() << " current version ";
9760 if (dl.dylib.current_version == 0xffffffff)
9761 outs() << "n/a\n";
9762 else
9763 outs() << ((dl.dylib.current_version >> 16) & 0xffff) << "."
9764 << ((dl.dylib.current_version >> 8) & 0xff) << "."
9765 << (dl.dylib.current_version & 0xff) << "\n";
9766 outs() << "compatibility version ";
9767 if (dl.dylib.compatibility_version == 0xffffffff)
9768 outs() << "n/a\n";
9769 else
9770 outs() << ((dl.dylib.compatibility_version >> 16) & 0xffff) << "."
9771 << ((dl.dylib.compatibility_version >> 8) & 0xff) << "."
9772 << (dl.dylib.compatibility_version & 0xff) << "\n";
9773}
9774
9775static void PrintLinkEditDataCommand(MachO::linkedit_data_command ld,
9776 uint32_t object_size) {
9777 if (ld.cmd == MachO::LC_CODE_SIGNATURE)
Kevin Enderby1be37a32016-04-28 21:07:20 +00009778 outs() << " cmd LC_CODE_SIGNATURE\n";
Kevin Enderby8ae63c12014-09-04 16:54:47 +00009779 else if (ld.cmd == MachO::LC_SEGMENT_SPLIT_INFO)
9780 outs() << " cmd LC_SEGMENT_SPLIT_INFO\n";
9781 else if (ld.cmd == MachO::LC_FUNCTION_STARTS)
9782 outs() << " cmd LC_FUNCTION_STARTS\n";
9783 else if (ld.cmd == MachO::LC_DATA_IN_CODE)
9784 outs() << " cmd LC_DATA_IN_CODE\n";
9785 else if (ld.cmd == MachO::LC_DYLIB_CODE_SIGN_DRS)
9786 outs() << " cmd LC_DYLIB_CODE_SIGN_DRS\n";
9787 else if (ld.cmd == MachO::LC_LINKER_OPTIMIZATION_HINT)
9788 outs() << " cmd LC_LINKER_OPTIMIZATION_HINT\n";
9789 else
9790 outs() << " cmd " << ld.cmd << " (?)\n";
9791 outs() << " cmdsize " << ld.cmdsize;
9792 if (ld.cmdsize != sizeof(struct MachO::linkedit_data_command))
9793 outs() << " Incorrect size\n";
9794 else
9795 outs() << "\n";
9796 outs() << " dataoff " << ld.dataoff;
9797 if (ld.dataoff > object_size)
9798 outs() << " (past end of file)\n";
9799 else
9800 outs() << "\n";
9801 outs() << " datasize " << ld.datasize;
9802 uint64_t big_size = ld.dataoff;
9803 big_size += ld.datasize;
9804 if (big_size > object_size)
9805 outs() << " (past end of file)\n";
9806 else
9807 outs() << "\n";
9808}
9809
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00009810static void PrintLoadCommands(const MachOObjectFile *Obj, uint32_t filetype,
9811 uint32_t cputype, bool verbose) {
Kevin Enderby956366c2014-08-29 22:30:52 +00009812 StringRef Buf = Obj->getData();
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00009813 unsigned Index = 0;
9814 for (const auto &Command : Obj->load_commands()) {
9815 outs() << "Load command " << Index++ << "\n";
Kevin Enderby956366c2014-08-29 22:30:52 +00009816 if (Command.C.cmd == MachO::LC_SEGMENT) {
9817 MachO::segment_command SLC = Obj->getSegmentLoadCommand(Command);
9818 const char *sg_segname = SLC.segname;
9819 PrintSegmentCommand(SLC.cmd, SLC.cmdsize, SLC.segname, SLC.vmaddr,
9820 SLC.vmsize, SLC.fileoff, SLC.filesize, SLC.maxprot,
9821 SLC.initprot, SLC.nsects, SLC.flags, Buf.size(),
9822 verbose);
9823 for (unsigned j = 0; j < SLC.nsects; j++) {
Kevin Enderbyc9713382014-12-16 01:14:45 +00009824 MachO::section S = Obj->getSection(Command, j);
Kevin Enderby956366c2014-08-29 22:30:52 +00009825 PrintSection(S.sectname, S.segname, S.addr, S.size, S.offset, S.align,
9826 S.reloff, S.nreloc, S.flags, S.reserved1, S.reserved2,
9827 SLC.cmd, sg_segname, filetype, Buf.size(), verbose);
9828 }
9829 } else if (Command.C.cmd == MachO::LC_SEGMENT_64) {
9830 MachO::segment_command_64 SLC_64 = Obj->getSegment64LoadCommand(Command);
9831 const char *sg_segname = SLC_64.segname;
9832 PrintSegmentCommand(SLC_64.cmd, SLC_64.cmdsize, SLC_64.segname,
9833 SLC_64.vmaddr, SLC_64.vmsize, SLC_64.fileoff,
9834 SLC_64.filesize, SLC_64.maxprot, SLC_64.initprot,
9835 SLC_64.nsects, SLC_64.flags, Buf.size(), verbose);
9836 for (unsigned j = 0; j < SLC_64.nsects; j++) {
9837 MachO::section_64 S_64 = Obj->getSection64(Command, j);
9838 PrintSection(S_64.sectname, S_64.segname, S_64.addr, S_64.size,
9839 S_64.offset, S_64.align, S_64.reloff, S_64.nreloc,
9840 S_64.flags, S_64.reserved1, S_64.reserved2, SLC_64.cmd,
9841 sg_segname, filetype, Buf.size(), verbose);
9842 }
9843 } else if (Command.C.cmd == MachO::LC_SYMTAB) {
9844 MachO::symtab_command Symtab = Obj->getSymtabLoadCommand();
David Majnemer73cc6ff2014-11-13 19:48:56 +00009845 PrintSymtabLoadCommand(Symtab, Obj->is64Bit(), Buf.size());
Kevin Enderby956366c2014-08-29 22:30:52 +00009846 } else if (Command.C.cmd == MachO::LC_DYSYMTAB) {
9847 MachO::dysymtab_command Dysymtab = Obj->getDysymtabLoadCommand();
9848 MachO::symtab_command Symtab = Obj->getSymtabLoadCommand();
David Majnemer73cc6ff2014-11-13 19:48:56 +00009849 PrintDysymtabLoadCommand(Dysymtab, Symtab.nsyms, Buf.size(),
9850 Obj->is64Bit());
Kevin Enderby8ae63c12014-09-04 16:54:47 +00009851 } else if (Command.C.cmd == MachO::LC_DYLD_INFO ||
9852 Command.C.cmd == MachO::LC_DYLD_INFO_ONLY) {
9853 MachO::dyld_info_command DyldInfo = Obj->getDyldInfoLoadCommand(Command);
9854 PrintDyldInfoLoadCommand(DyldInfo, Buf.size());
9855 } else if (Command.C.cmd == MachO::LC_LOAD_DYLINKER ||
9856 Command.C.cmd == MachO::LC_ID_DYLINKER ||
9857 Command.C.cmd == MachO::LC_DYLD_ENVIRONMENT) {
9858 MachO::dylinker_command Dyld = Obj->getDylinkerCommand(Command);
9859 PrintDyldLoadCommand(Dyld, Command.Ptr);
9860 } else if (Command.C.cmd == MachO::LC_UUID) {
9861 MachO::uuid_command Uuid = Obj->getUuidCommand(Command);
9862 PrintUuidLoadCommand(Uuid);
Jean-Daniel Dupas00cc1f52014-12-04 07:37:02 +00009863 } else if (Command.C.cmd == MachO::LC_RPATH) {
9864 MachO::rpath_command Rpath = Obj->getRpathCommand(Command);
9865 PrintRpathLoadCommand(Rpath, Command.Ptr);
Kevin Enderby1ff0ecc2014-12-16 21:48:27 +00009866 } else if (Command.C.cmd == MachO::LC_VERSION_MIN_MACOSX ||
Tim Northoverbfbfb122015-11-02 21:26:58 +00009867 Command.C.cmd == MachO::LC_VERSION_MIN_IPHONEOS ||
9868 Command.C.cmd == MachO::LC_VERSION_MIN_TVOS ||
9869 Command.C.cmd == MachO::LC_VERSION_MIN_WATCHOS) {
Kevin Enderby8ae63c12014-09-04 16:54:47 +00009870 MachO::version_min_command Vd = Obj->getVersionMinLoadCommand(Command);
9871 PrintVersionMinLoadCommand(Vd);
Kevin Enderbya4579c42017-01-19 17:36:31 +00009872 } else if (Command.C.cmd == MachO::LC_NOTE) {
9873 MachO::note_command Nt = Obj->getNoteLoadCommand(Command);
9874 PrintNoteLoadCommand(Nt);
Steven Wu5b54a422017-01-23 20:07:55 +00009875 } else if (Command.C.cmd == MachO::LC_BUILD_VERSION) {
9876 MachO::build_version_command Bv =
9877 Obj->getBuildVersionLoadCommand(Command);
9878 PrintBuildVersionLoadCommand(Obj, Bv);
Kevin Enderby8ae63c12014-09-04 16:54:47 +00009879 } else if (Command.C.cmd == MachO::LC_SOURCE_VERSION) {
9880 MachO::source_version_command Sd = Obj->getSourceVersionCommand(Command);
9881 PrintSourceVersionCommand(Sd);
9882 } else if (Command.C.cmd == MachO::LC_MAIN) {
9883 MachO::entry_point_command Ep = Obj->getEntryPointCommand(Command);
9884 PrintEntryPointCommand(Ep);
Kevin Enderby0804f4672014-12-16 23:25:52 +00009885 } else if (Command.C.cmd == MachO::LC_ENCRYPTION_INFO) {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009886 MachO::encryption_info_command Ei =
9887 Obj->getEncryptionInfoCommand(Command);
Kevin Enderby0804f4672014-12-16 23:25:52 +00009888 PrintEncryptionInfoCommand(Ei, Buf.size());
Kevin Enderby57538292014-12-17 01:01:30 +00009889 } else if (Command.C.cmd == MachO::LC_ENCRYPTION_INFO_64) {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009890 MachO::encryption_info_command_64 Ei =
9891 Obj->getEncryptionInfoCommand64(Command);
Kevin Enderby57538292014-12-17 01:01:30 +00009892 PrintEncryptionInfoCommand64(Ei, Buf.size());
Kevin Enderbyd0b6b7f2014-12-18 00:53:40 +00009893 } else if (Command.C.cmd == MachO::LC_LINKER_OPTION) {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00009894 MachO::linker_option_command Lo =
9895 Obj->getLinkerOptionLoadCommand(Command);
Kevin Enderbyd0b6b7f2014-12-18 00:53:40 +00009896 PrintLinkerOptionCommand(Lo, Command.Ptr);
Kevin Enderbyb4b79312014-12-18 19:24:35 +00009897 } else if (Command.C.cmd == MachO::LC_SUB_FRAMEWORK) {
9898 MachO::sub_framework_command Sf = Obj->getSubFrameworkCommand(Command);
9899 PrintSubFrameworkCommand(Sf, Command.Ptr);
Kevin Enderbya2bd8d92014-12-18 23:13:26 +00009900 } else if (Command.C.cmd == MachO::LC_SUB_UMBRELLA) {
9901 MachO::sub_umbrella_command Sf = Obj->getSubUmbrellaCommand(Command);
9902 PrintSubUmbrellaCommand(Sf, Command.Ptr);
Kevin Enderby36c8d3a2014-12-19 19:48:16 +00009903 } else if (Command.C.cmd == MachO::LC_SUB_LIBRARY) {
9904 MachO::sub_library_command Sl = Obj->getSubLibraryCommand(Command);
9905 PrintSubLibraryCommand(Sl, Command.Ptr);
Kevin Enderby186eac32014-12-19 21:06:24 +00009906 } else if (Command.C.cmd == MachO::LC_SUB_CLIENT) {
9907 MachO::sub_client_command Sc = Obj->getSubClientCommand(Command);
9908 PrintSubClientCommand(Sc, Command.Ptr);
Kevin Enderby52e4ce42014-12-19 22:25:22 +00009909 } else if (Command.C.cmd == MachO::LC_ROUTINES) {
9910 MachO::routines_command Rc = Obj->getRoutinesCommand(Command);
9911 PrintRoutinesCommand(Rc);
9912 } else if (Command.C.cmd == MachO::LC_ROUTINES_64) {
9913 MachO::routines_command_64 Rc = Obj->getRoutinesCommand64(Command);
9914 PrintRoutinesCommand64(Rc);
Kevin Enderby48ef5342014-12-23 22:56:39 +00009915 } else if (Command.C.cmd == MachO::LC_THREAD ||
9916 Command.C.cmd == MachO::LC_UNIXTHREAD) {
9917 MachO::thread_command Tc = Obj->getThreadCommand(Command);
9918 PrintThreadCommand(Tc, Command.Ptr, Obj->isLittleEndian(), cputype);
Nick Kledzik15558912014-10-16 18:58:20 +00009919 } else if (Command.C.cmd == MachO::LC_LOAD_DYLIB ||
9920 Command.C.cmd == MachO::LC_ID_DYLIB ||
9921 Command.C.cmd == MachO::LC_LOAD_WEAK_DYLIB ||
9922 Command.C.cmd == MachO::LC_REEXPORT_DYLIB ||
9923 Command.C.cmd == MachO::LC_LAZY_LOAD_DYLIB ||
9924 Command.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB) {
Kevin Enderby8ae63c12014-09-04 16:54:47 +00009925 MachO::dylib_command Dl = Obj->getDylibIDLoadCommand(Command);
9926 PrintDylibCommand(Dl, Command.Ptr);
9927 } else if (Command.C.cmd == MachO::LC_CODE_SIGNATURE ||
9928 Command.C.cmd == MachO::LC_SEGMENT_SPLIT_INFO ||
9929 Command.C.cmd == MachO::LC_FUNCTION_STARTS ||
9930 Command.C.cmd == MachO::LC_DATA_IN_CODE ||
9931 Command.C.cmd == MachO::LC_DYLIB_CODE_SIGN_DRS ||
9932 Command.C.cmd == MachO::LC_LINKER_OPTIMIZATION_HINT) {
9933 MachO::linkedit_data_command Ld =
9934 Obj->getLinkeditDataLoadCommand(Command);
9935 PrintLinkEditDataCommand(Ld, Buf.size());
Kevin Enderby956366c2014-08-29 22:30:52 +00009936 } else {
9937 outs() << " cmd ?(" << format("0x%08" PRIx32, Command.C.cmd)
9938 << ")\n";
9939 outs() << " cmdsize " << Command.C.cmdsize << "\n";
9940 // TODO: get and print the raw bytes of the load command.
9941 }
9942 // TODO: print all the other kinds of load commands.
Kevin Enderby956366c2014-08-29 22:30:52 +00009943 }
9944}
9945
Kevin Enderby0ae163f2016-01-13 00:25:36 +00009946static void PrintMachHeader(const MachOObjectFile *Obj, bool verbose) {
Kevin Enderbyb76d3862014-08-22 20:35:18 +00009947 if (Obj->is64Bit()) {
9948 MachO::mach_header_64 H_64;
9949 H_64 = Obj->getHeader64();
9950 PrintMachHeader(H_64.magic, H_64.cputype, H_64.cpusubtype, H_64.filetype,
9951 H_64.ncmds, H_64.sizeofcmds, H_64.flags, verbose);
9952 } else {
9953 MachO::mach_header H;
9954 H = Obj->getHeader();
9955 PrintMachHeader(H.magic, H.cputype, H.cpusubtype, H.filetype, H.ncmds,
9956 H.sizeofcmds, H.flags, verbose);
9957 }
9958}
9959
9960void llvm::printMachOFileHeader(const object::ObjectFile *Obj) {
9961 const MachOObjectFile *file = dyn_cast<const MachOObjectFile>(Obj);
Kevin Enderby0ae163f2016-01-13 00:25:36 +00009962 PrintMachHeader(file, !NonVerbose);
9963}
9964
9965void llvm::printMachOLoadCommands(const object::ObjectFile *Obj) {
9966 const MachOObjectFile *file = dyn_cast<const MachOObjectFile>(Obj);
Kevin Enderby956366c2014-08-29 22:30:52 +00009967 uint32_t filetype = 0;
9968 uint32_t cputype = 0;
Kevin Enderby0ae163f2016-01-13 00:25:36 +00009969 if (file->is64Bit()) {
9970 MachO::mach_header_64 H_64;
9971 H_64 = file->getHeader64();
9972 filetype = H_64.filetype;
9973 cputype = H_64.cputype;
9974 } else {
9975 MachO::mach_header H;
9976 H = file->getHeader();
9977 filetype = H.filetype;
9978 cputype = H.cputype;
9979 }
Alexey Samsonovd319c4f2015-06-03 22:19:36 +00009980 PrintLoadCommands(file, filetype, cputype, !NonVerbose);
Kevin Enderbyb76d3862014-08-22 20:35:18 +00009981}
Nick Kledzikd04bc352014-08-30 00:20:14 +00009982
9983//===----------------------------------------------------------------------===//
9984// export trie dumping
9985//===----------------------------------------------------------------------===//
9986
9987void llvm::printMachOExportsTrie(const object::MachOObjectFile *Obj) {
Kevin Enderby0d5ec112017-06-19 21:23:07 +00009988 uint64_t BaseSegmentAddress = 0;
9989 for (const auto &Command : Obj->load_commands()) {
9990 if (Command.C.cmd == MachO::LC_SEGMENT) {
9991 MachO::segment_command Seg = Obj->getSegmentLoadCommand(Command);
9992 if (Seg.fileoff == 0 && Seg.filesize != 0) {
9993 BaseSegmentAddress = Seg.vmaddr;
9994 break;
9995 }
9996 } else if (Command.C.cmd == MachO::LC_SEGMENT_64) {
9997 MachO::segment_command_64 Seg = Obj->getSegment64LoadCommand(Command);
9998 if (Seg.fileoff == 0 && Seg.filesize != 0) {
9999 BaseSegmentAddress = Seg.vmaddr;
10000 break;
10001 }
10002 }
10003 }
Kevin Enderby3e95bd22017-07-20 23:08:41 +000010004 Error Err = Error::success();
Alexander Shaposhnikove5740342017-07-29 00:30:45 +000010005 for (const llvm::object::ExportEntry &Entry : Obj->exports(Err)) {
Nick Kledzikac7cbdc2014-09-02 18:50:24 +000010006 uint64_t Flags = Entry.flags();
Nick Kledzikd04bc352014-08-30 00:20:14 +000010007 bool ReExport = (Flags & MachO::EXPORT_SYMBOL_FLAGS_REEXPORT);
10008 bool WeakDef = (Flags & MachO::EXPORT_SYMBOL_FLAGS_WEAK_DEFINITION);
10009 bool ThreadLocal = ((Flags & MachO::EXPORT_SYMBOL_FLAGS_KIND_MASK) ==
10010 MachO::EXPORT_SYMBOL_FLAGS_KIND_THREAD_LOCAL);
10011 bool Abs = ((Flags & MachO::EXPORT_SYMBOL_FLAGS_KIND_MASK) ==
10012 MachO::EXPORT_SYMBOL_FLAGS_KIND_ABSOLUTE);
10013 bool Resolver = (Flags & MachO::EXPORT_SYMBOL_FLAGS_STUB_AND_RESOLVER);
10014 if (ReExport)
10015 outs() << "[re-export] ";
10016 else
Kevin Enderbyb28ed012014-10-29 21:28:24 +000010017 outs() << format("0x%08llX ",
Kevin Enderby0d5ec112017-06-19 21:23:07 +000010018 Entry.address() + BaseSegmentAddress);
Nick Kledzikac7cbdc2014-09-02 18:50:24 +000010019 outs() << Entry.name();
Nick Kledzikd04bc352014-08-30 00:20:14 +000010020 if (WeakDef || ThreadLocal || Resolver || Abs) {
Nick Kledzikac7cbdc2014-09-02 18:50:24 +000010021 bool NeedsComma = false;
Nick Kledzik1d1ac4b2014-09-03 01:12:52 +000010022 outs() << " [";
Nick Kledzikd04bc352014-08-30 00:20:14 +000010023 if (WeakDef) {
10024 outs() << "weak_def";
Nick Kledzikac7cbdc2014-09-02 18:50:24 +000010025 NeedsComma = true;
Nick Kledzikd04bc352014-08-30 00:20:14 +000010026 }
10027 if (ThreadLocal) {
Nick Kledzikac7cbdc2014-09-02 18:50:24 +000010028 if (NeedsComma)
Nick Kledzikd04bc352014-08-30 00:20:14 +000010029 outs() << ", ";
10030 outs() << "per-thread";
Nick Kledzikac7cbdc2014-09-02 18:50:24 +000010031 NeedsComma = true;
Nick Kledzikd04bc352014-08-30 00:20:14 +000010032 }
10033 if (Abs) {
Nick Kledzikac7cbdc2014-09-02 18:50:24 +000010034 if (NeedsComma)
Nick Kledzikd04bc352014-08-30 00:20:14 +000010035 outs() << ", ";
10036 outs() << "absolute";
Nick Kledzikac7cbdc2014-09-02 18:50:24 +000010037 NeedsComma = true;
Nick Kledzikd04bc352014-08-30 00:20:14 +000010038 }
10039 if (Resolver) {
Nick Kledzikac7cbdc2014-09-02 18:50:24 +000010040 if (NeedsComma)
Nick Kledzikd04bc352014-08-30 00:20:14 +000010041 outs() << ", ";
Nick Kledzikac7cbdc2014-09-02 18:50:24 +000010042 outs() << format("resolver=0x%08llX", Entry.other());
10043 NeedsComma = true;
Nick Kledzikd04bc352014-08-30 00:20:14 +000010044 }
10045 outs() << "]";
10046 }
10047 if (ReExport) {
10048 StringRef DylibName = "unknown";
Nick Kledzikac7cbdc2014-09-02 18:50:24 +000010049 int Ordinal = Entry.other() - 1;
10050 Obj->getLibraryShortNameByIndex(Ordinal, DylibName);
10051 if (Entry.otherName().empty())
Nick Kledzikd04bc352014-08-30 00:20:14 +000010052 outs() << " (from " << DylibName << ")";
10053 else
Nick Kledzikac7cbdc2014-09-02 18:50:24 +000010054 outs() << " (" << Entry.otherName() << " from " << DylibName << ")";
Nick Kledzikd04bc352014-08-30 00:20:14 +000010055 }
10056 outs() << "\n";
10057 }
Kevin Enderby3e95bd22017-07-20 23:08:41 +000010058 if (Err)
Fangrui Songe7834bd2019-04-07 08:19:55 +000010059 report_error(std::move(Err), Obj->getFileName());
Nick Kledzikd04bc352014-08-30 00:20:14 +000010060}
Nick Kledzikac431442014-09-12 21:34:15 +000010061
Nick Kledzikac431442014-09-12 21:34:15 +000010062//===----------------------------------------------------------------------===//
10063// rebase table dumping
10064//===----------------------------------------------------------------------===//
10065
Kevin Enderbya8d256c2017-03-20 19:46:55 +000010066void llvm::printMachORebaseTable(object::MachOObjectFile *Obj) {
Nick Kledzikac431442014-09-12 21:34:15 +000010067 outs() << "segment section address type\n";
Kevin Enderbya8d256c2017-03-20 19:46:55 +000010068 Error Err = Error::success();
10069 for (const llvm::object::MachORebaseEntry &Entry : Obj->rebaseTable(Err)) {
10070 StringRef SegmentName = Entry.segmentName();
10071 StringRef SectionName = Entry.sectionName();
10072 uint64_t Address = Entry.address();
Nick Kledzikac431442014-09-12 21:34:15 +000010073
10074 // Table lines look like: __DATA __nl_symbol_ptr 0x0000F00C pointer
Kevin Enderbyb28ed012014-10-29 21:28:24 +000010075 outs() << format("%-8s %-18s 0x%08" PRIX64 " %s\n",
10076 SegmentName.str().c_str(), SectionName.str().c_str(),
10077 Address, Entry.typeName().str().c_str());
Nick Kledzikac431442014-09-12 21:34:15 +000010078 }
Kevin Enderbya8d256c2017-03-20 19:46:55 +000010079 if (Err)
Fangrui Songe7834bd2019-04-07 08:19:55 +000010080 report_error(std::move(Err), Obj->getFileName());
Nick Kledzikac431442014-09-12 21:34:15 +000010081}
Nick Kledzik56ebef42014-09-16 01:41:51 +000010082
10083static StringRef ordinalName(const object::MachOObjectFile *Obj, int Ordinal) {
10084 StringRef DylibName;
10085 switch (Ordinal) {
10086 case MachO::BIND_SPECIAL_DYLIB_SELF:
10087 return "this-image";
10088 case MachO::BIND_SPECIAL_DYLIB_MAIN_EXECUTABLE:
10089 return "main-executable";
10090 case MachO::BIND_SPECIAL_DYLIB_FLAT_LOOKUP:
10091 return "flat-namespace";
10092 default:
Nick Kledzikabd29872014-09-16 22:03:13 +000010093 if (Ordinal > 0) {
Kevin Enderbyb28ed012014-10-29 21:28:24 +000010094 std::error_code EC =
10095 Obj->getLibraryShortNameByIndex(Ordinal - 1, DylibName);
Nick Kledzikabd29872014-09-16 22:03:13 +000010096 if (EC)
Nick Kledzik51d2c2b2014-10-14 23:29:38 +000010097 return "<<bad library ordinal>>";
Nick Kledzikabd29872014-09-16 22:03:13 +000010098 return DylibName;
10099 }
Nick Kledzik56ebef42014-09-16 01:41:51 +000010100 }
Nick Kledzikabd29872014-09-16 22:03:13 +000010101 return "<<unknown special ordinal>>";
Nick Kledzik56ebef42014-09-16 01:41:51 +000010102}
10103
10104//===----------------------------------------------------------------------===//
10105// bind table dumping
10106//===----------------------------------------------------------------------===//
10107
Kevin Enderbya8d256c2017-03-20 19:46:55 +000010108void llvm::printMachOBindTable(object::MachOObjectFile *Obj) {
Nick Kledzik56ebef42014-09-16 01:41:51 +000010109 // Build table of sections so names can used in final output.
Nick Kledzik5ffacc12014-09-30 00:19:58 +000010110 outs() << "segment section address type "
10111 "addend dylib symbol\n";
Kevin Enderbyfeb63b92017-02-28 21:47:07 +000010112 Error Err = Error::success();
10113 for (const llvm::object::MachOBindEntry &Entry : Obj->bindTable(Err)) {
Kevin Enderbya8d256c2017-03-20 19:46:55 +000010114 StringRef SegmentName = Entry.segmentName();
10115 StringRef SectionName = Entry.sectionName();
10116 uint64_t Address = Entry.address();
Nick Kledzik56ebef42014-09-16 01:41:51 +000010117
10118 // Table lines look like:
10119 // __DATA __got 0x00012010 pointer 0 libSystem ___stack_chk_guard
Nick Kledzik5ffacc12014-09-30 00:19:58 +000010120 StringRef Attr;
Nick Kledzik56ebef42014-09-16 01:41:51 +000010121 if (Entry.flags() & MachO::BIND_SYMBOL_FLAGS_WEAK_IMPORT)
Nick Kledzik5ffacc12014-09-30 00:19:58 +000010122 Attr = " (weak_import)";
Kevin Enderbyb28ed012014-10-29 21:28:24 +000010123 outs() << left_justify(SegmentName, 8) << " "
Nick Kledzik5ffacc12014-09-30 00:19:58 +000010124 << left_justify(SectionName, 18) << " "
10125 << format_hex(Address, 10, true) << " "
10126 << left_justify(Entry.typeName(), 8) << " "
Kevin Enderbyb28ed012014-10-29 21:28:24 +000010127 << format_decimal(Entry.addend(), 8) << " "
Nick Kledzik5ffacc12014-09-30 00:19:58 +000010128 << left_justify(ordinalName(Obj, Entry.ordinal()), 16) << " "
Kevin Enderbyb28ed012014-10-29 21:28:24 +000010129 << Entry.symbolName() << Attr << "\n";
Nick Kledzik56ebef42014-09-16 01:41:51 +000010130 }
Kevin Enderbyfeb63b92017-02-28 21:47:07 +000010131 if (Err)
Fangrui Songe7834bd2019-04-07 08:19:55 +000010132 report_error(std::move(Err), Obj->getFileName());
Nick Kledzik56ebef42014-09-16 01:41:51 +000010133}
10134
10135//===----------------------------------------------------------------------===//
10136// lazy bind table dumping
10137//===----------------------------------------------------------------------===//
10138
Kevin Enderbya8d256c2017-03-20 19:46:55 +000010139void llvm::printMachOLazyBindTable(object::MachOObjectFile *Obj) {
Nick Kledzik5ffacc12014-09-30 00:19:58 +000010140 outs() << "segment section address "
10141 "dylib symbol\n";
Kevin Enderbyfeb63b92017-02-28 21:47:07 +000010142 Error Err = Error::success();
10143 for (const llvm::object::MachOBindEntry &Entry : Obj->lazyBindTable(Err)) {
Kevin Enderbya8d256c2017-03-20 19:46:55 +000010144 StringRef SegmentName = Entry.segmentName();
10145 StringRef SectionName = Entry.sectionName();
10146 uint64_t Address = Entry.address();
Nick Kledzik56ebef42014-09-16 01:41:51 +000010147
10148 // Table lines look like:
10149 // __DATA __got 0x00012010 libSystem ___stack_chk_guard
Kevin Enderbyb28ed012014-10-29 21:28:24 +000010150 outs() << left_justify(SegmentName, 8) << " "
Nick Kledzik5ffacc12014-09-30 00:19:58 +000010151 << left_justify(SectionName, 18) << " "
10152 << format_hex(Address, 10, true) << " "
10153 << left_justify(ordinalName(Obj, Entry.ordinal()), 16) << " "
Nick Kledzik56ebef42014-09-16 01:41:51 +000010154 << Entry.symbolName() << "\n";
10155 }
Kevin Enderbyfeb63b92017-02-28 21:47:07 +000010156 if (Err)
Fangrui Songe7834bd2019-04-07 08:19:55 +000010157 report_error(std::move(Err), Obj->getFileName());
Nick Kledzik56ebef42014-09-16 01:41:51 +000010158}
10159
Nick Kledzik56ebef42014-09-16 01:41:51 +000010160//===----------------------------------------------------------------------===//
10161// weak bind table dumping
10162//===----------------------------------------------------------------------===//
10163
Kevin Enderbya8d256c2017-03-20 19:46:55 +000010164void llvm::printMachOWeakBindTable(object::MachOObjectFile *Obj) {
Nick Kledzik5ffacc12014-09-30 00:19:58 +000010165 outs() << "segment section address "
10166 "type addend symbol\n";
Kevin Enderbyfeb63b92017-02-28 21:47:07 +000010167 Error Err = Error::success();
10168 for (const llvm::object::MachOBindEntry &Entry : Obj->weakBindTable(Err)) {
Nick Kledzik56ebef42014-09-16 01:41:51 +000010169 // Strong symbols don't have a location to update.
10170 if (Entry.flags() & MachO::BIND_SYMBOL_FLAGS_NON_WEAK_DEFINITION) {
Nick Kledzik5ffacc12014-09-30 00:19:58 +000010171 outs() << " strong "
Nick Kledzik56ebef42014-09-16 01:41:51 +000010172 << Entry.symbolName() << "\n";
10173 continue;
10174 }
Kevin Enderbya8d256c2017-03-20 19:46:55 +000010175 StringRef SegmentName = Entry.segmentName();
10176 StringRef SectionName = Entry.sectionName();
10177 uint64_t Address = Entry.address();
Nick Kledzik56ebef42014-09-16 01:41:51 +000010178
10179 // Table lines look like:
10180 // __DATA __data 0x00001000 pointer 0 _foo
Kevin Enderbyb28ed012014-10-29 21:28:24 +000010181 outs() << left_justify(SegmentName, 8) << " "
Nick Kledzik5ffacc12014-09-30 00:19:58 +000010182 << left_justify(SectionName, 18) << " "
10183 << format_hex(Address, 10, true) << " "
10184 << left_justify(Entry.typeName(), 8) << " "
Kevin Enderbyb28ed012014-10-29 21:28:24 +000010185 << format_decimal(Entry.addend(), 8) << " " << Entry.symbolName()
10186 << "\n";
Nick Kledzik56ebef42014-09-16 01:41:51 +000010187 }
Kevin Enderbyfeb63b92017-02-28 21:47:07 +000010188 if (Err)
Fangrui Songe7834bd2019-04-07 08:19:55 +000010189 report_error(std::move(Err), Obj->getFileName());
Nick Kledzik56ebef42014-09-16 01:41:51 +000010190}
10191
Kevin Enderby6f326ce2014-10-23 19:37:31 +000010192// get_dyld_bind_info_symbolname() is used for disassembly and passed an
10193// address, ReferenceValue, in the Mach-O file and looks in the dyld bind
10194// information for that address. If the address is found its binding symbol
10195// name is returned. If not nullptr is returned.
10196static const char *get_dyld_bind_info_symbolname(uint64_t ReferenceValue,
10197 struct DisassembleInfo *info) {
Kevin Enderby078be602014-10-23 19:53:12 +000010198 if (info->bindtable == nullptr) {
Saleem Abdulrasool1d84d9a2017-01-08 19:14:15 +000010199 info->bindtable = llvm::make_unique<SymbolAddressMap>();
Kevin Enderbyfeb63b92017-02-28 21:47:07 +000010200 Error Err = Error::success();
10201 for (const llvm::object::MachOBindEntry &Entry : info->O->bindTable(Err)) {
Kevin Enderbya8d256c2017-03-20 19:46:55 +000010202 uint64_t Address = Entry.address();
Kevin Enderby6f326ce2014-10-23 19:37:31 +000010203 StringRef name = Entry.symbolName();
10204 if (!name.empty())
Saleem Abdulrasool1d84d9a2017-01-08 19:14:15 +000010205 (*info->bindtable)[Address] = name;
Kevin Enderby6f326ce2014-10-23 19:37:31 +000010206 }
Kevin Enderbyfeb63b92017-02-28 21:47:07 +000010207 if (Err)
Fangrui Songe7834bd2019-04-07 08:19:55 +000010208 report_error(std::move(Err), info->O->getFileName());
Kevin Enderby6f326ce2014-10-23 19:37:31 +000010209 }
Saleem Abdulrasool1d84d9a2017-01-08 19:14:15 +000010210 auto name = info->bindtable->lookup(ReferenceValue);
10211 return !name.empty() ? name.data() : nullptr;
Kevin Enderby6f326ce2014-10-23 19:37:31 +000010212}
Michael Trent1854ecc2017-12-05 07:50:00 +000010213