Bug Summary

File:build/llvm-toolchain-snapshot-15~++20220420111733+e13d2efed663/llvm/tools/llvm-objdump/MachODump.cpp
Warning:line 2910, column 25
1st function call argument is an uninitialized value

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -clear-ast-before-backend -disable-llvm-verifier -discard-value-names -main-file-name MachODump.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -setup-static-analyzer -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mframe-pointer=none -fmath-errno -ffp-contract=on -fno-rounding-math -mconstructor-aliases -funwind-tables=2 -target-cpu x86-64 -tune-cpu generic -debugger-tuning=gdb -ffunction-sections -fdata-sections -fcoverage-compilation-dir=/build/llvm-toolchain-snapshot-15~++20220420111733+e13d2efed663/build-llvm -resource-dir /usr/lib/llvm-15/lib/clang/15.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I tools/llvm-objdump -I /build/llvm-toolchain-snapshot-15~++20220420111733+e13d2efed663/llvm/tools/llvm-objdump -I include -I /build/llvm-toolchain-snapshot-15~++20220420111733+e13d2efed663/llvm/include -D _FORTIFY_SOURCE=2 -D NDEBUG -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/x86_64-linux-gnu/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10/backward -internal-isystem /usr/lib/llvm-15/lib/clang/15.0.0/include -internal-isystem /usr/local/include -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../x86_64-linux-gnu/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -fmacro-prefix-map=/build/llvm-toolchain-snapshot-15~++20220420111733+e13d2efed663/build-llvm=build-llvm -fmacro-prefix-map=/build/llvm-toolchain-snapshot-15~++20220420111733+e13d2efed663/= -fcoverage-prefix-map=/build/llvm-toolchain-snapshot-15~++20220420111733+e13d2efed663/build-llvm=build-llvm -fcoverage-prefix-map=/build/llvm-toolchain-snapshot-15~++20220420111733+e13d2efed663/= -O3 -Wno-unused-command-line-argument -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-class-memaccess -Wno-redundant-move -Wno-pessimizing-move -Wno-noexcept-type -Wno-comment -std=c++14 -fdeprecated-macro -fdebug-compilation-dir=/build/llvm-toolchain-snapshot-15~++20220420111733+e13d2efed663/build-llvm -fdebug-prefix-map=/build/llvm-toolchain-snapshot-15~++20220420111733+e13d2efed663/build-llvm=build-llvm -fdebug-prefix-map=/build/llvm-toolchain-snapshot-15~++20220420111733+e13d2efed663/= -ferror-limit 19 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -fcolor-diagnostics -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -D__GCC_HAVE_DWARF2_CFI_ASM=1 -o /tmp/scan-build-2022-04-20-140412-16051-1 -x c++ /build/llvm-toolchain-snapshot-15~++20220420111733+e13d2efed663/llvm/tools/llvm-objdump/MachODump.cpp
1//===-- MachODump.cpp - Object file dumping utility for llvm --------------===//
2//
3// 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
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements the MachO-specific dumper for llvm-objdump.
10//
11//===----------------------------------------------------------------------===//
12
13#include "MachODump.h"
14
15#include "ObjdumpOptID.h"
16#include "llvm-objdump.h"
17#include "llvm-c/Disassembler.h"
18#include "llvm/ADT/STLExtras.h"
19#include "llvm/ADT/StringExtras.h"
20#include "llvm/ADT/Triple.h"
21#include "llvm/BinaryFormat/MachO.h"
22#include "llvm/Config/config.h"
23#include "llvm/DebugInfo/DIContext.h"
24#include "llvm/DebugInfo/DWARF/DWARFContext.h"
25#include "llvm/Demangle/Demangle.h"
26#include "llvm/MC/MCAsmInfo.h"
27#include "llvm/MC/MCContext.h"
28#include "llvm/MC/MCDisassembler/MCDisassembler.h"
29#include "llvm/MC/MCInst.h"
30#include "llvm/MC/MCInstPrinter.h"
31#include "llvm/MC/MCInstrDesc.h"
32#include "llvm/MC/MCInstrInfo.h"
33#include "llvm/MC/MCRegisterInfo.h"
34#include "llvm/MC/MCSubtargetInfo.h"
35#include "llvm/MC/MCTargetOptions.h"
36#include "llvm/MC/TargetRegistry.h"
37#include "llvm/Object/MachO.h"
38#include "llvm/Object/MachOUniversal.h"
39#include "llvm/Option/ArgList.h"
40#include "llvm/Support/Casting.h"
41#include "llvm/Support/Debug.h"
42#include "llvm/Support/Endian.h"
43#include "llvm/Support/Format.h"
44#include "llvm/Support/FormattedStream.h"
45#include "llvm/Support/GraphWriter.h"
46#include "llvm/Support/LEB128.h"
47#include "llvm/Support/MemoryBuffer.h"
48#include "llvm/Support/TargetSelect.h"
49#include "llvm/Support/ToolOutputFile.h"
50#include "llvm/Support/WithColor.h"
51#include "llvm/Support/raw_ostream.h"
52#include <algorithm>
53#include <cstring>
54#include <system_error>
55
56#ifdef LLVM_HAVE_LIBXAR
57extern "C" {
58#include <xar/xar.h>
59}
60#endif
61
62using namespace llvm;
63using namespace llvm::object;
64using namespace llvm::objdump;
65
66bool objdump::FirstPrivateHeader;
67bool objdump::ExportsTrie;
68bool objdump::Rebase;
69bool objdump::Rpaths;
70bool objdump::Bind;
71bool objdump::LazyBind;
72bool objdump::WeakBind;
73static bool UseDbg;
74static std::string DSYMFile;
75bool objdump::FullLeadingAddr;
76bool objdump::LeadingHeaders;
77bool objdump::UniversalHeaders;
78static bool ArchiveMemberOffsets;
79bool objdump::IndirectSymbols;
80bool objdump::DataInCode;
81bool objdump::FunctionStarts;
82bool objdump::LinkOptHints;
83bool objdump::InfoPlist;
84bool objdump::DyldInfo;
85bool objdump::DylibsUsed;
86bool objdump::DylibId;
87bool objdump::Verbose;
88bool objdump::ObjcMetaData;
89std::string objdump::DisSymName;
90bool objdump::SymbolicOperands;
91static std::vector<std::string> ArchFlags;
92
93static bool ArchAll = false;
94static std::string ThumbTripleName;
95
96void objdump::parseMachOOptions(const llvm::opt::InputArgList &InputArgs) {
97 FirstPrivateHeader = InputArgs.hasArg(OBJDUMP_private_header);
98 ExportsTrie = InputArgs.hasArg(OBJDUMP_exports_trie);
99 Rebase = InputArgs.hasArg(OBJDUMP_rebase);
100 Rpaths = InputArgs.hasArg(OBJDUMP_rpaths);
101 Bind = InputArgs.hasArg(OBJDUMP_bind);
102 LazyBind = InputArgs.hasArg(OBJDUMP_lazy_bind);
103 WeakBind = InputArgs.hasArg(OBJDUMP_weak_bind);
104 UseDbg = InputArgs.hasArg(OBJDUMP_g);
105 DSYMFile = InputArgs.getLastArgValue(OBJDUMP_dsym_EQ).str();
106 FullLeadingAddr = InputArgs.hasArg(OBJDUMP_full_leading_addr);
107 LeadingHeaders = !InputArgs.hasArg(OBJDUMP_no_leading_headers);
108 UniversalHeaders = InputArgs.hasArg(OBJDUMP_universal_headers);
109 ArchiveMemberOffsets = InputArgs.hasArg(OBJDUMP_archive_member_offsets);
110 IndirectSymbols = InputArgs.hasArg(OBJDUMP_indirect_symbols);
111 DataInCode = InputArgs.hasArg(OBJDUMP_data_in_code);
112 FunctionStarts = InputArgs.hasArg(OBJDUMP_function_starts);
113 LinkOptHints = InputArgs.hasArg(OBJDUMP_link_opt_hints);
114 InfoPlist = InputArgs.hasArg(OBJDUMP_info_plist);
115 DyldInfo = InputArgs.hasArg(OBJDUMP_dyld_info);
116 DylibsUsed = InputArgs.hasArg(OBJDUMP_dylibs_used);
117 DylibId = InputArgs.hasArg(OBJDUMP_dylib_id);
118 Verbose = !InputArgs.hasArg(OBJDUMP_non_verbose);
119 ObjcMetaData = InputArgs.hasArg(OBJDUMP_objc_meta_data);
120 DisSymName = InputArgs.getLastArgValue(OBJDUMP_dis_symname).str();
121 SymbolicOperands = !InputArgs.hasArg(OBJDUMP_no_symbolic_operands);
122 ArchFlags = InputArgs.getAllArgValues(OBJDUMP_arch_EQ);
123}
124
125static const Target *GetTarget(const MachOObjectFile *MachOObj,
126 const char **McpuDefault,
127 const Target **ThumbTarget) {
128 // Figure out the target triple.
129 Triple TT(TripleName);
130 if (TripleName.empty()) {
131 TT = MachOObj->getArchTriple(McpuDefault);
132 TripleName = TT.str();
133 }
134
135 if (TT.getArch() == Triple::arm) {
136 // We've inferred a 32-bit ARM target from the object file. All MachO CPUs
137 // that support ARM are also capable of Thumb mode.
138 Triple ThumbTriple = TT;
139 std::string ThumbName = (Twine("thumb") + TT.getArchName().substr(3)).str();
140 ThumbTriple.setArchName(ThumbName);
141 ThumbTripleName = ThumbTriple.str();
142 }
143
144 // Get the target specific parser.
145 std::string Error;
146 const Target *TheTarget = TargetRegistry::lookupTarget(TripleName, Error);
147 if (TheTarget && ThumbTripleName.empty())
148 return TheTarget;
149
150 *ThumbTarget = TargetRegistry::lookupTarget(ThumbTripleName, Error);
151 if (*ThumbTarget)
152 return TheTarget;
153
154 WithColor::error(errs(), "llvm-objdump") << "unable to get target for '";
155 if (!TheTarget)
156 errs() << TripleName;
157 else
158 errs() << ThumbTripleName;
159 errs() << "', see --version and --triple.\n";
160 return nullptr;
161}
162
163namespace {
164struct SymbolSorter {
165 bool operator()(const SymbolRef &A, const SymbolRef &B) {
166 Expected<SymbolRef::Type> ATypeOrErr = A.getType();
167 if (!ATypeOrErr)
168 reportError(ATypeOrErr.takeError(), A.getObject()->getFileName());
169 SymbolRef::Type AType = *ATypeOrErr;
170 Expected<SymbolRef::Type> BTypeOrErr = B.getType();
171 if (!BTypeOrErr)
172 reportError(BTypeOrErr.takeError(), B.getObject()->getFileName());
173 SymbolRef::Type BType = *BTypeOrErr;
174 uint64_t AAddr =
175 (AType != SymbolRef::ST_Function) ? 0 : cantFail(A.getValue());
176 uint64_t BAddr =
177 (BType != SymbolRef::ST_Function) ? 0 : cantFail(B.getValue());
178 return AAddr < BAddr;
179 }
180};
181} // namespace
182
183// Types for the storted data in code table that is built before disassembly
184// and the predicate function to sort them.
185typedef std::pair<uint64_t, DiceRef> DiceTableEntry;
186typedef std::vector<DiceTableEntry> DiceTable;
187typedef DiceTable::iterator dice_table_iterator;
188
189#ifdef LLVM_HAVE_LIBXAR
190namespace {
191struct ScopedXarFile {
192 xar_t xar;
193 ScopedXarFile(const char *filename, int32_t flags) {
194#pragma clang diagnostic push
195#pragma clang diagnostic ignored "-Wdeprecated-declarations"
196 xar = xar_open(filename, flags);
197#pragma clang diagnostic pop
198 }
199 ~ScopedXarFile() {
200 if (xar)
201 xar_close(xar);
202 }
203 ScopedXarFile(const ScopedXarFile &) = delete;
204 ScopedXarFile &operator=(const ScopedXarFile &) = delete;
205 operator xar_t() { return xar; }
206};
207
208struct ScopedXarIter {
209 xar_iter_t iter;
210 ScopedXarIter() : iter(xar_iter_new()) {}
211 ~ScopedXarIter() {
212 if (iter)
213 xar_iter_free(iter);
214 }
215 ScopedXarIter(const ScopedXarIter &) = delete;
216 ScopedXarIter &operator=(const ScopedXarIter &) = delete;
217 operator xar_iter_t() { return iter; }
218};
219} // namespace
220#endif // defined(LLVM_HAVE_LIBXAR)
221
222// This is used to search for a data in code table entry for the PC being
223// disassembled. The j parameter has the PC in j.first. A single data in code
224// table entry can cover many bytes for each of its Kind's. So if the offset,
225// aka the i.first value, of the data in code table entry plus its Length
226// covers the PC being searched for this will return true. If not it will
227// return false.
228static bool compareDiceTableEntries(const DiceTableEntry &i,
229 const DiceTableEntry &j) {
230 uint16_t Length;
231 i.second.getLength(Length);
232
233 return j.first >= i.first && j.first < i.first + Length;
234}
235
236static uint64_t DumpDataInCode(const uint8_t *bytes, uint64_t Length,
237 unsigned short Kind) {
238 uint32_t Value, Size = 1;
239
240 switch (Kind) {
241 default:
242 case MachO::DICE_KIND_DATA:
243 if (Length >= 4) {
244 if (ShowRawInsn)
245 dumpBytes(makeArrayRef(bytes, 4), outs());
246 Value = bytes[3] << 24 | bytes[2] << 16 | bytes[1] << 8 | bytes[0];
247 outs() << "\t.long " << Value;
248 Size = 4;
249 } else if (Length >= 2) {
250 if (ShowRawInsn)
251 dumpBytes(makeArrayRef(bytes, 2), outs());
252 Value = bytes[1] << 8 | bytes[0];
253 outs() << "\t.short " << Value;
254 Size = 2;
255 } else {
256 if (ShowRawInsn)
257 dumpBytes(makeArrayRef(bytes, 2), outs());
258 Value = bytes[0];
259 outs() << "\t.byte " << Value;
260 Size = 1;
261 }
262 if (Kind == MachO::DICE_KIND_DATA)
263 outs() << "\t@ KIND_DATA\n";
264 else
265 outs() << "\t@ data in code kind = " << Kind << "\n";
266 break;
267 case MachO::DICE_KIND_JUMP_TABLE8:
268 if (ShowRawInsn)
269 dumpBytes(makeArrayRef(bytes, 1), outs());
270 Value = bytes[0];
271 outs() << "\t.byte " << format("%3u", Value) << "\t@ KIND_JUMP_TABLE8\n";
272 Size = 1;
273 break;
274 case MachO::DICE_KIND_JUMP_TABLE16:
275 if (ShowRawInsn)
276 dumpBytes(makeArrayRef(bytes, 2), outs());
277 Value = bytes[1] << 8 | bytes[0];
278 outs() << "\t.short " << format("%5u", Value & 0xffff)
279 << "\t@ KIND_JUMP_TABLE16\n";
280 Size = 2;
281 break;
282 case MachO::DICE_KIND_JUMP_TABLE32:
283 case MachO::DICE_KIND_ABS_JUMP_TABLE32:
284 if (ShowRawInsn)
285 dumpBytes(makeArrayRef(bytes, 4), outs());
286 Value = bytes[3] << 24 | bytes[2] << 16 | bytes[1] << 8 | bytes[0];
287 outs() << "\t.long " << Value;
288 if (Kind == MachO::DICE_KIND_JUMP_TABLE32)
289 outs() << "\t@ KIND_JUMP_TABLE32\n";
290 else
291 outs() << "\t@ KIND_ABS_JUMP_TABLE32\n";
292 Size = 4;
293 break;
294 }
295 return Size;
296}
297
298static void getSectionsAndSymbols(MachOObjectFile *MachOObj,
299 std::vector<SectionRef> &Sections,
300 std::vector<SymbolRef> &Symbols,
301 SmallVectorImpl<uint64_t> &FoundFns,
302 uint64_t &BaseSegmentAddress) {
303 const StringRef FileName = MachOObj->getFileName();
304 for (const SymbolRef &Symbol : MachOObj->symbols()) {
305 StringRef SymName = unwrapOrError(Symbol.getName(), FileName);
306 if (!SymName.startswith("ltmp"))
307 Symbols.push_back(Symbol);
308 }
309
310 append_range(Sections, MachOObj->sections());
311
312 bool BaseSegmentAddressSet = false;
313 for (const auto &Command : MachOObj->load_commands()) {
314 if (Command.C.cmd == MachO::LC_FUNCTION_STARTS) {
315 // We found a function starts segment, parse the addresses for later
316 // consumption.
317 MachO::linkedit_data_command LLC =
318 MachOObj->getLinkeditDataLoadCommand(Command);
319
320 MachOObj->ReadULEB128s(LLC.dataoff, FoundFns);
321 } else if (Command.C.cmd == MachO::LC_SEGMENT) {
322 MachO::segment_command SLC = MachOObj->getSegmentLoadCommand(Command);
323 StringRef SegName = SLC.segname;
324 if (!BaseSegmentAddressSet && SegName != "__PAGEZERO") {
325 BaseSegmentAddressSet = true;
326 BaseSegmentAddress = SLC.vmaddr;
327 }
328 } else if (Command.C.cmd == MachO::LC_SEGMENT_64) {
329 MachO::segment_command_64 SLC = MachOObj->getSegment64LoadCommand(Command);
330 StringRef SegName = SLC.segname;
331 if (!BaseSegmentAddressSet && SegName != "__PAGEZERO") {
332 BaseSegmentAddressSet = true;
333 BaseSegmentAddress = SLC.vmaddr;
334 }
335 }
336 }
337}
338
339static bool DumpAndSkipDataInCode(uint64_t PC, const uint8_t *bytes,
340 DiceTable &Dices, uint64_t &InstSize) {
341 // Check the data in code table here to see if this is data not an
342 // instruction to be disassembled.
343 DiceTable Dice;
344 Dice.push_back(std::make_pair(PC, DiceRef()));
345 dice_table_iterator DTI =
346 std::search(Dices.begin(), Dices.end(), Dice.begin(), Dice.end(),
347 compareDiceTableEntries);
348 if (DTI != Dices.end()) {
349 uint16_t Length;
350 DTI->second.getLength(Length);
351 uint16_t Kind;
352 DTI->second.getKind(Kind);
353 InstSize = DumpDataInCode(bytes, Length, Kind);
354 if ((Kind == MachO::DICE_KIND_JUMP_TABLE8) &&
355 (PC == (DTI->first + Length - 1)) && (Length & 1))
356 InstSize++;
357 return true;
358 }
359 return false;
360}
361
362static void printRelocationTargetName(const MachOObjectFile *O,
363 const MachO::any_relocation_info &RE,
364 raw_string_ostream &Fmt) {
365 // Target of a scattered relocation is an address. In the interest of
366 // generating pretty output, scan through the symbol table looking for a
367 // symbol that aligns with that address. If we find one, print it.
368 // Otherwise, we just print the hex address of the target.
369 const StringRef FileName = O->getFileName();
370 if (O->isRelocationScattered(RE)) {
371 uint32_t Val = O->getPlainRelocationSymbolNum(RE);
372
373 for (const SymbolRef &Symbol : O->symbols()) {
374 uint64_t Addr = unwrapOrError(Symbol.getAddress(), FileName);
375 if (Addr != Val)
376 continue;
377 Fmt << unwrapOrError(Symbol.getName(), FileName);
378 return;
379 }
380
381 // If we couldn't find a symbol that this relocation refers to, try
382 // to find a section beginning instead.
383 for (const SectionRef &Section : ToolSectionFilter(*O)) {
384 uint64_t Addr = Section.getAddress();
385 if (Addr != Val)
386 continue;
387 StringRef NameOrErr = unwrapOrError(Section.getName(), O->getFileName());
388 Fmt << NameOrErr;
389 return;
390 }
391
392 Fmt << format("0x%x", Val);
393 return;
394 }
395
396 StringRef S;
397 bool isExtern = O->getPlainRelocationExternal(RE);
398 uint64_t Val = O->getPlainRelocationSymbolNum(RE);
399
400 if (O->getAnyRelocationType(RE) == MachO::ARM64_RELOC_ADDEND &&
401 (O->getArch() == Triple::aarch64 || O->getArch() == Triple::aarch64_be)) {
402 Fmt << format("0x%0" PRIx64"l" "x", Val);
403 return;
404 }
405
406 if (isExtern) {
407 symbol_iterator SI = O->symbol_begin();
408 std::advance(SI, Val);
409 S = unwrapOrError(SI->getName(), FileName);
410 } else {
411 section_iterator SI = O->section_begin();
412 // Adjust for the fact that sections are 1-indexed.
413 if (Val == 0) {
414 Fmt << "0 (?,?)";
415 return;
416 }
417 uint32_t I = Val - 1;
418 while (I != 0 && SI != O->section_end()) {
419 --I;
420 std::advance(SI, 1);
421 }
422 if (SI == O->section_end()) {
423 Fmt << Val << " (?,?)";
424 } else {
425 if (Expected<StringRef> NameOrErr = SI->getName())
426 S = *NameOrErr;
427 else
428 consumeError(NameOrErr.takeError());
429 }
430 }
431
432 Fmt << S;
433}
434
435Error objdump::getMachORelocationValueString(const MachOObjectFile *Obj,
436 const RelocationRef &RelRef,
437 SmallVectorImpl<char> &Result) {
438 DataRefImpl Rel = RelRef.getRawDataRefImpl();
439 MachO::any_relocation_info RE = Obj->getRelocation(Rel);
440
441 unsigned Arch = Obj->getArch();
442
443 std::string FmtBuf;
444 raw_string_ostream Fmt(FmtBuf);
445 unsigned Type = Obj->getAnyRelocationType(RE);
446 bool IsPCRel = Obj->getAnyRelocationPCRel(RE);
447
448 // Determine any addends that should be displayed with the relocation.
449 // These require decoding the relocation type, which is triple-specific.
450
451 // X86_64 has entirely custom relocation types.
452 if (Arch == Triple::x86_64) {
453 switch (Type) {
454 case MachO::X86_64_RELOC_GOT_LOAD:
455 case MachO::X86_64_RELOC_GOT: {
456 printRelocationTargetName(Obj, RE, Fmt);
457 Fmt << "@GOT";
458 if (IsPCRel)
459 Fmt << "PCREL";
460 break;
461 }
462 case MachO::X86_64_RELOC_SUBTRACTOR: {
463 DataRefImpl RelNext = Rel;
464 Obj->moveRelocationNext(RelNext);
465 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
466
467 // X86_64_RELOC_SUBTRACTOR must be followed by a relocation of type
468 // X86_64_RELOC_UNSIGNED.
469 // NOTE: Scattered relocations don't exist on x86_64.
470 unsigned RType = Obj->getAnyRelocationType(RENext);
471 if (RType != MachO::X86_64_RELOC_UNSIGNED)
472 reportError(Obj->getFileName(), "Expected X86_64_RELOC_UNSIGNED after "
473 "X86_64_RELOC_SUBTRACTOR.");
474
475 // The X86_64_RELOC_UNSIGNED contains the minuend symbol;
476 // X86_64_RELOC_SUBTRACTOR contains the subtrahend.
477 printRelocationTargetName(Obj, RENext, Fmt);
478 Fmt << "-";
479 printRelocationTargetName(Obj, RE, Fmt);
480 break;
481 }
482 case MachO::X86_64_RELOC_TLV:
483 printRelocationTargetName(Obj, RE, Fmt);
484 Fmt << "@TLV";
485 if (IsPCRel)
486 Fmt << "P";
487 break;
488 case MachO::X86_64_RELOC_SIGNED_1:
489 printRelocationTargetName(Obj, RE, Fmt);
490 Fmt << "-1";
491 break;
492 case MachO::X86_64_RELOC_SIGNED_2:
493 printRelocationTargetName(Obj, RE, Fmt);
494 Fmt << "-2";
495 break;
496 case MachO::X86_64_RELOC_SIGNED_4:
497 printRelocationTargetName(Obj, RE, Fmt);
498 Fmt << "-4";
499 break;
500 default:
501 printRelocationTargetName(Obj, RE, Fmt);
502 break;
503 }
504 // X86 and ARM share some relocation types in common.
505 } else if (Arch == Triple::x86 || Arch == Triple::arm ||
506 Arch == Triple::ppc) {
507 // Generic relocation types...
508 switch (Type) {
509 case MachO::GENERIC_RELOC_PAIR: // prints no info
510 return Error::success();
511 case MachO::GENERIC_RELOC_SECTDIFF: {
512 DataRefImpl RelNext = Rel;
513 Obj->moveRelocationNext(RelNext);
514 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
515
516 // X86 sect diff's must be followed by a relocation of type
517 // GENERIC_RELOC_PAIR.
518 unsigned RType = Obj->getAnyRelocationType(RENext);
519
520 if (RType != MachO::GENERIC_RELOC_PAIR)
521 reportError(Obj->getFileName(), "Expected GENERIC_RELOC_PAIR after "
522 "GENERIC_RELOC_SECTDIFF.");
523
524 printRelocationTargetName(Obj, RE, Fmt);
525 Fmt << "-";
526 printRelocationTargetName(Obj, RENext, Fmt);
527 break;
528 }
529 }
530
531 if (Arch == Triple::x86 || Arch == Triple::ppc) {
532 switch (Type) {
533 case MachO::GENERIC_RELOC_LOCAL_SECTDIFF: {
534 DataRefImpl RelNext = Rel;
535 Obj->moveRelocationNext(RelNext);
536 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
537
538 // X86 sect diff's must be followed by a relocation of type
539 // GENERIC_RELOC_PAIR.
540 unsigned RType = Obj->getAnyRelocationType(RENext);
541 if (RType != MachO::GENERIC_RELOC_PAIR)
542 reportError(Obj->getFileName(), "Expected GENERIC_RELOC_PAIR after "
543 "GENERIC_RELOC_LOCAL_SECTDIFF.");
544
545 printRelocationTargetName(Obj, RE, Fmt);
546 Fmt << "-";
547 printRelocationTargetName(Obj, RENext, Fmt);
548 break;
549 }
550 case MachO::GENERIC_RELOC_TLV: {
551 printRelocationTargetName(Obj, RE, Fmt);
552 Fmt << "@TLV";
553 if (IsPCRel)
554 Fmt << "P";
555 break;
556 }
557 default:
558 printRelocationTargetName(Obj, RE, Fmt);
559 }
560 } else { // ARM-specific relocations
561 switch (Type) {
562 case MachO::ARM_RELOC_HALF:
563 case MachO::ARM_RELOC_HALF_SECTDIFF: {
564 // Half relocations steal a bit from the length field to encode
565 // whether this is an upper16 or a lower16 relocation.
566 bool isUpper = (Obj->getAnyRelocationLength(RE) & 0x1) == 1;
567
568 if (isUpper)
569 Fmt << ":upper16:(";
570 else
571 Fmt << ":lower16:(";
572 printRelocationTargetName(Obj, RE, Fmt);
573
574 DataRefImpl RelNext = Rel;
575 Obj->moveRelocationNext(RelNext);
576 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
577
578 // ARM half relocs must be followed by a relocation of type
579 // ARM_RELOC_PAIR.
580 unsigned RType = Obj->getAnyRelocationType(RENext);
581 if (RType != MachO::ARM_RELOC_PAIR)
582 reportError(Obj->getFileName(), "Expected ARM_RELOC_PAIR after "
583 "ARM_RELOC_HALF");
584
585 // NOTE: The half of the target virtual address is stashed in the
586 // address field of the secondary relocation, but we can't reverse
587 // engineer the constant offset from it without decoding the movw/movt
588 // instruction to find the other half in its immediate field.
589
590 // ARM_RELOC_HALF_SECTDIFF encodes the second section in the
591 // symbol/section pointer of the follow-on relocation.
592 if (Type == MachO::ARM_RELOC_HALF_SECTDIFF) {
593 Fmt << "-";
594 printRelocationTargetName(Obj, RENext, Fmt);
595 }
596
597 Fmt << ")";
598 break;
599 }
600 default: {
601 printRelocationTargetName(Obj, RE, Fmt);
602 }
603 }
604 }
605 } else
606 printRelocationTargetName(Obj, RE, Fmt);
607
608 Fmt.flush();
609 Result.append(FmtBuf.begin(), FmtBuf.end());
610 return Error::success();
611}
612
613static void PrintIndirectSymbolTable(MachOObjectFile *O, bool verbose,
614 uint32_t n, uint32_t count,
615 uint32_t stride, uint64_t addr) {
616 MachO::dysymtab_command Dysymtab = O->getDysymtabLoadCommand();
617 uint32_t nindirectsyms = Dysymtab.nindirectsyms;
618 if (n > nindirectsyms)
619 outs() << " (entries start past the end of the indirect symbol "
620 "table) (reserved1 field greater than the table size)";
621 else if (n + count > nindirectsyms)
622 outs() << " (entries extends past the end of the indirect symbol "
623 "table)";
624 outs() << "\n";
625 uint32_t cputype = O->getHeader().cputype;
626 if (cputype & MachO::CPU_ARCH_ABI64)
627 outs() << "address index";
628 else
629 outs() << "address index";
630 if (verbose)
631 outs() << " name\n";
632 else
633 outs() << "\n";
634 for (uint32_t j = 0; j < count && n + j < nindirectsyms; j++) {
635 if (cputype & MachO::CPU_ARCH_ABI64)
636 outs() << format("0x%016" PRIx64"l" "x", addr + j * stride) << " ";
637 else
638 outs() << format("0x%08" PRIx32"x", (uint32_t)addr + j * stride) << " ";
639 MachO::dysymtab_command Dysymtab = O->getDysymtabLoadCommand();
640 uint32_t indirect_symbol = O->getIndirectSymbolTableEntry(Dysymtab, n + j);
641 if (indirect_symbol == MachO::INDIRECT_SYMBOL_LOCAL) {
642 outs() << "LOCAL\n";
643 continue;
644 }
645 if (indirect_symbol ==
646 (MachO::INDIRECT_SYMBOL_LOCAL | MachO::INDIRECT_SYMBOL_ABS)) {
647 outs() << "LOCAL ABSOLUTE\n";
648 continue;
649 }
650 if (indirect_symbol == MachO::INDIRECT_SYMBOL_ABS) {
651 outs() << "ABSOLUTE\n";
652 continue;
653 }
654 outs() << format("%5u ", indirect_symbol);
655 if (verbose) {
656 MachO::symtab_command Symtab = O->getSymtabLoadCommand();
657 if (indirect_symbol < Symtab.nsyms) {
658 symbol_iterator Sym = O->getSymbolByIndex(indirect_symbol);
659 SymbolRef Symbol = *Sym;
660 outs() << unwrapOrError(Symbol.getName(), O->getFileName());
661 } else {
662 outs() << "?";
663 }
664 }
665 outs() << "\n";
666 }
667}
668
669static void PrintIndirectSymbols(MachOObjectFile *O, bool verbose) {
670 for (const auto &Load : O->load_commands()) {
671 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
672 MachO::segment_command_64 Seg = O->getSegment64LoadCommand(Load);
673 for (unsigned J = 0; J < Seg.nsects; ++J) {
674 MachO::section_64 Sec = O->getSection64(Load, J);
675 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
676 if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
677 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
678 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
679 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
680 section_type == MachO::S_SYMBOL_STUBS) {
681 uint32_t stride;
682 if (section_type == MachO::S_SYMBOL_STUBS)
683 stride = Sec.reserved2;
684 else
685 stride = 8;
686 if (stride == 0) {
687 outs() << "Can't print indirect symbols for (" << Sec.segname << ","
688 << Sec.sectname << ") "
689 << "(size of stubs in reserved2 field is zero)\n";
690 continue;
691 }
692 uint32_t count = Sec.size / stride;
693 outs() << "Indirect symbols for (" << Sec.segname << ","
694 << Sec.sectname << ") " << count << " entries";
695 uint32_t n = Sec.reserved1;
696 PrintIndirectSymbolTable(O, verbose, n, count, stride, Sec.addr);
697 }
698 }
699 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
700 MachO::segment_command Seg = O->getSegmentLoadCommand(Load);
701 for (unsigned J = 0; J < Seg.nsects; ++J) {
702 MachO::section Sec = O->getSection(Load, J);
703 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
704 if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
705 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
706 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
707 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
708 section_type == MachO::S_SYMBOL_STUBS) {
709 uint32_t stride;
710 if (section_type == MachO::S_SYMBOL_STUBS)
711 stride = Sec.reserved2;
712 else
713 stride = 4;
714 if (stride == 0) {
715 outs() << "Can't print indirect symbols for (" << Sec.segname << ","
716 << Sec.sectname << ") "
717 << "(size of stubs in reserved2 field is zero)\n";
718 continue;
719 }
720 uint32_t count = Sec.size / stride;
721 outs() << "Indirect symbols for (" << Sec.segname << ","
722 << Sec.sectname << ") " << count << " entries";
723 uint32_t n = Sec.reserved1;
724 PrintIndirectSymbolTable(O, verbose, n, count, stride, Sec.addr);
725 }
726 }
727 }
728 }
729}
730
731static void PrintRType(const uint64_t cputype, const unsigned r_type) {
732 static char const *generic_r_types[] = {
733 "VANILLA ", "PAIR ", "SECTDIF ", "PBLAPTR ", "LOCSDIF ", "TLV ",
734 " 6 (?) ", " 7 (?) ", " 8 (?) ", " 9 (?) ", " 10 (?) ", " 11 (?) ",
735 " 12 (?) ", " 13 (?) ", " 14 (?) ", " 15 (?) "
736 };
737 static char const *x86_64_r_types[] = {
738 "UNSIGND ", "SIGNED ", "BRANCH ", "GOT_LD ", "GOT ", "SUB ",
739 "SIGNED1 ", "SIGNED2 ", "SIGNED4 ", "TLV ", " 10 (?) ", " 11 (?) ",
740 " 12 (?) ", " 13 (?) ", " 14 (?) ", " 15 (?) "
741 };
742 static char const *arm_r_types[] = {
743 "VANILLA ", "PAIR ", "SECTDIFF", "LOCSDIF ", "PBLAPTR ",
744 "BR24 ", "T_BR22 ", "T_BR32 ", "HALF ", "HALFDIF ",
745 " 10 (?) ", " 11 (?) ", " 12 (?) ", " 13 (?) ", " 14 (?) ", " 15 (?) "
746 };
747 static char const *arm64_r_types[] = {
748 "UNSIGND ", "SUB ", "BR26 ", "PAGE21 ", "PAGOF12 ",
749 "GOTLDP ", "GOTLDPOF", "PTRTGOT ", "TLVLDP ", "TLVLDPOF",
750 "ADDEND ", " 11 (?) ", " 12 (?) ", " 13 (?) ", " 14 (?) ", " 15 (?) "
751 };
752
753 if (r_type > 0xf){
754 outs() << format("%-7u", r_type) << " ";
755 return;
756 }
757 switch (cputype) {
758 case MachO::CPU_TYPE_I386:
759 outs() << generic_r_types[r_type];
760 break;
761 case MachO::CPU_TYPE_X86_64:
762 outs() << x86_64_r_types[r_type];
763 break;
764 case MachO::CPU_TYPE_ARM:
765 outs() << arm_r_types[r_type];
766 break;
767 case MachO::CPU_TYPE_ARM64:
768 case MachO::CPU_TYPE_ARM64_32:
769 outs() << arm64_r_types[r_type];
770 break;
771 default:
772 outs() << format("%-7u ", r_type);
773 }
774}
775
776static void PrintRLength(const uint64_t cputype, const unsigned r_type,
777 const unsigned r_length, const bool previous_arm_half){
778 if (cputype == MachO::CPU_TYPE_ARM &&
779 (r_type == MachO::ARM_RELOC_HALF ||
780 r_type == MachO::ARM_RELOC_HALF_SECTDIFF || previous_arm_half == true)) {
781 if ((r_length & 0x1) == 0)
782 outs() << "lo/";
783 else
784 outs() << "hi/";
785 if ((r_length & 0x1) == 0)
786 outs() << "arm ";
787 else
788 outs() << "thm ";
789 } else {
790 switch (r_length) {
791 case 0:
792 outs() << "byte ";
793 break;
794 case 1:
795 outs() << "word ";
796 break;
797 case 2:
798 outs() << "long ";
799 break;
800 case 3:
801 if (cputype == MachO::CPU_TYPE_X86_64)
802 outs() << "quad ";
803 else
804 outs() << format("?(%2d) ", r_length);
805 break;
806 default:
807 outs() << format("?(%2d) ", r_length);
808 }
809 }
810}
811
812static void PrintRelocationEntries(const MachOObjectFile *O,
813 const relocation_iterator Begin,
814 const relocation_iterator End,
815 const uint64_t cputype,
816 const bool verbose) {
817 const MachO::symtab_command Symtab = O->getSymtabLoadCommand();
818 bool previous_arm_half = false;
819 bool previous_sectdiff = false;
820 uint32_t sectdiff_r_type = 0;
821
822 for (relocation_iterator Reloc = Begin; Reloc != End; ++Reloc) {
823 const DataRefImpl Rel = Reloc->getRawDataRefImpl();
824 const MachO::any_relocation_info RE = O->getRelocation(Rel);
825 const unsigned r_type = O->getAnyRelocationType(RE);
826 const bool r_scattered = O->isRelocationScattered(RE);
827 const unsigned r_pcrel = O->getAnyRelocationPCRel(RE);
828 const unsigned r_length = O->getAnyRelocationLength(RE);
829 const unsigned r_address = O->getAnyRelocationAddress(RE);
830 const bool r_extern = (r_scattered ? false :
831 O->getPlainRelocationExternal(RE));
832 const uint32_t r_value = (r_scattered ?
833 O->getScatteredRelocationValue(RE) : 0);
834 const unsigned r_symbolnum = (r_scattered ? 0 :
835 O->getPlainRelocationSymbolNum(RE));
836
837 if (r_scattered && cputype != MachO::CPU_TYPE_X86_64) {
838 if (verbose) {
839 // scattered: address
840 if ((cputype == MachO::CPU_TYPE_I386 &&
841 r_type == MachO::GENERIC_RELOC_PAIR) ||
842 (cputype == MachO::CPU_TYPE_ARM && r_type == MachO::ARM_RELOC_PAIR))
843 outs() << " ";
844 else
845 outs() << format("%08x ", (unsigned int)r_address);
846
847 // scattered: pcrel
848 if (r_pcrel)
849 outs() << "True ";
850 else
851 outs() << "False ";
852
853 // scattered: length
854 PrintRLength(cputype, r_type, r_length, previous_arm_half);
855
856 // scattered: extern & type
857 outs() << "n/a ";
858 PrintRType(cputype, r_type);
859
860 // scattered: scattered & value
861 outs() << format("True 0x%08x", (unsigned int)r_value);
862 if (previous_sectdiff == false) {
863 if ((cputype == MachO::CPU_TYPE_ARM &&
864 r_type == MachO::ARM_RELOC_PAIR))
865 outs() << format(" half = 0x%04x ", (unsigned int)r_address);
866 } else if (cputype == MachO::CPU_TYPE_ARM &&
867 sectdiff_r_type == MachO::ARM_RELOC_HALF_SECTDIFF)
868 outs() << format(" other_half = 0x%04x ", (unsigned int)r_address);
869 if ((cputype == MachO::CPU_TYPE_I386 &&
870 (r_type == MachO::GENERIC_RELOC_SECTDIFF ||
871 r_type == MachO::GENERIC_RELOC_LOCAL_SECTDIFF)) ||
872 (cputype == MachO::CPU_TYPE_ARM &&
873 (sectdiff_r_type == MachO::ARM_RELOC_SECTDIFF ||
874 sectdiff_r_type == MachO::ARM_RELOC_LOCAL_SECTDIFF ||
875 sectdiff_r_type == MachO::ARM_RELOC_HALF_SECTDIFF))) {
876 previous_sectdiff = true;
877 sectdiff_r_type = r_type;
878 } else {
879 previous_sectdiff = false;
880 sectdiff_r_type = 0;
881 }
882 if (cputype == MachO::CPU_TYPE_ARM &&
883 (r_type == MachO::ARM_RELOC_HALF ||
884 r_type == MachO::ARM_RELOC_HALF_SECTDIFF))
885 previous_arm_half = true;
886 else
887 previous_arm_half = false;
888 outs() << "\n";
889 }
890 else {
891 // scattered: address pcrel length extern type scattered value
892 outs() << format("%08x %1d %-2d n/a %-7d 1 0x%08x\n",
893 (unsigned int)r_address, r_pcrel, r_length, r_type,
894 (unsigned int)r_value);
895 }
896 }
897 else {
898 if (verbose) {
899 // plain: address
900 if (cputype == MachO::CPU_TYPE_ARM && r_type == MachO::ARM_RELOC_PAIR)
901 outs() << " ";
902 else
903 outs() << format("%08x ", (unsigned int)r_address);
904
905 // plain: pcrel
906 if (r_pcrel)
907 outs() << "True ";
908 else
909 outs() << "False ";
910
911 // plain: length
912 PrintRLength(cputype, r_type, r_length, previous_arm_half);
913
914 if (r_extern) {
915 // plain: extern & type & scattered
916 outs() << "True ";
917 PrintRType(cputype, r_type);
918 outs() << "False ";
919
920 // plain: symbolnum/value
921 if (r_symbolnum > Symtab.nsyms)
922 outs() << format("?(%d)\n", r_symbolnum);
923 else {
924 SymbolRef Symbol = *O->getSymbolByIndex(r_symbolnum);
925 Expected<StringRef> SymNameNext = Symbol.getName();
926 const char *name = nullptr;
927 if (SymNameNext)
928 name = SymNameNext->data();
929 if (name == nullptr)
930 outs() << format("?(%d)\n", r_symbolnum);
931 else
932 outs() << name << "\n";
933 }
934 }
935 else {
936 // plain: extern & type & scattered
937 outs() << "False ";
938 PrintRType(cputype, r_type);
939 outs() << "False ";
940
941 // plain: symbolnum/value
942 if (cputype == MachO::CPU_TYPE_ARM && r_type == MachO::ARM_RELOC_PAIR)
943 outs() << format("other_half = 0x%04x\n", (unsigned int)r_address);
944 else if ((cputype == MachO::CPU_TYPE_ARM64 ||
945 cputype == MachO::CPU_TYPE_ARM64_32) &&
946 r_type == MachO::ARM64_RELOC_ADDEND)
947 outs() << format("addend = 0x%06x\n", (unsigned int)r_symbolnum);
948 else {
949 outs() << format("%d ", r_symbolnum);
950 if (r_symbolnum == MachO::R_ABS)
951 outs() << "R_ABS\n";
952 else {
953 // in this case, r_symbolnum is actually a 1-based section number
954 uint32_t nsects = O->section_end()->getRawDataRefImpl().d.a;
955 if (r_symbolnum > 0 && r_symbolnum <= nsects) {
956 object::DataRefImpl DRI;
957 DRI.d.a = r_symbolnum-1;
958 StringRef SegName = O->getSectionFinalSegmentName(DRI);
959 if (Expected<StringRef> NameOrErr = O->getSectionName(DRI))
960 outs() << "(" << SegName << "," << *NameOrErr << ")\n";
961 else
962 outs() << "(?,?)\n";
963 }
964 else {
965 outs() << "(?,?)\n";
966 }
967 }
968 }
969 }
970 if (cputype == MachO::CPU_TYPE_ARM &&
971 (r_type == MachO::ARM_RELOC_HALF ||
972 r_type == MachO::ARM_RELOC_HALF_SECTDIFF))
973 previous_arm_half = true;
974 else
975 previous_arm_half = false;
976 }
977 else {
978 // plain: address pcrel length extern type scattered symbolnum/section
979 outs() << format("%08x %1d %-2d %1d %-7d 0 %d\n",
980 (unsigned int)r_address, r_pcrel, r_length, r_extern,
981 r_type, r_symbolnum);
982 }
983 }
984 }
985}
986
987static void PrintRelocations(const MachOObjectFile *O, const bool verbose) {
988 const uint64_t cputype = O->getHeader().cputype;
989 const MachO::dysymtab_command Dysymtab = O->getDysymtabLoadCommand();
990 if (Dysymtab.nextrel != 0) {
991 outs() << "External relocation information " << Dysymtab.nextrel
992 << " entries";
993 outs() << "\naddress pcrel length extern type scattered "
994 "symbolnum/value\n";
995 PrintRelocationEntries(O, O->extrel_begin(), O->extrel_end(), cputype,
996 verbose);
997 }
998 if (Dysymtab.nlocrel != 0) {
999 outs() << format("Local relocation information %u entries",
1000 Dysymtab.nlocrel);
1001 outs() << "\naddress pcrel length extern type scattered "
1002 "symbolnum/value\n";
1003 PrintRelocationEntries(O, O->locrel_begin(), O->locrel_end(), cputype,
1004 verbose);
1005 }
1006 for (const auto &Load : O->load_commands()) {
1007 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
1008 const MachO::segment_command_64 Seg = O->getSegment64LoadCommand(Load);
1009 for (unsigned J = 0; J < Seg.nsects; ++J) {
1010 const MachO::section_64 Sec = O->getSection64(Load, J);
1011 if (Sec.nreloc != 0) {
1012 DataRefImpl DRI;
1013 DRI.d.a = J;
1014 const StringRef SegName = O->getSectionFinalSegmentName(DRI);
1015 if (Expected<StringRef> NameOrErr = O->getSectionName(DRI))
1016 outs() << "Relocation information (" << SegName << "," << *NameOrErr
1017 << format(") %u entries", Sec.nreloc);
1018 else
1019 outs() << "Relocation information (" << SegName << ",?) "
1020 << format("%u entries", Sec.nreloc);
1021 outs() << "\naddress pcrel length extern type scattered "
1022 "symbolnum/value\n";
1023 PrintRelocationEntries(O, O->section_rel_begin(DRI),
1024 O->section_rel_end(DRI), cputype, verbose);
1025 }
1026 }
1027 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
1028 const MachO::segment_command Seg = O->getSegmentLoadCommand(Load);
1029 for (unsigned J = 0; J < Seg.nsects; ++J) {
1030 const MachO::section Sec = O->getSection(Load, J);
1031 if (Sec.nreloc != 0) {
1032 DataRefImpl DRI;
1033 DRI.d.a = J;
1034 const StringRef SegName = O->getSectionFinalSegmentName(DRI);
1035 if (Expected<StringRef> NameOrErr = O->getSectionName(DRI))
1036 outs() << "Relocation information (" << SegName << "," << *NameOrErr
1037 << format(") %u entries", Sec.nreloc);
1038 else
1039 outs() << "Relocation information (" << SegName << ",?) "
1040 << format("%u entries", Sec.nreloc);
1041 outs() << "\naddress pcrel length extern type scattered "
1042 "symbolnum/value\n";
1043 PrintRelocationEntries(O, O->section_rel_begin(DRI),
1044 O->section_rel_end(DRI), cputype, verbose);
1045 }
1046 }
1047 }
1048 }
1049}
1050
1051static void PrintFunctionStarts(MachOObjectFile *O) {
1052 uint64_t BaseSegmentAddress = 0;
1053 for (const MachOObjectFile::LoadCommandInfo &Command : O->load_commands()) {
1054 if (Command.C.cmd == MachO::LC_SEGMENT) {
1055 MachO::segment_command SLC = O->getSegmentLoadCommand(Command);
1056 if (StringRef(SLC.segname) == "__TEXT") {
1057 BaseSegmentAddress = SLC.vmaddr;
1058 break;
1059 }
1060 } else if (Command.C.cmd == MachO::LC_SEGMENT_64) {
1061 MachO::segment_command_64 SLC = O->getSegment64LoadCommand(Command);
1062 if (StringRef(SLC.segname) == "__TEXT") {
1063 BaseSegmentAddress = SLC.vmaddr;
1064 break;
1065 }
1066 }
1067 }
1068
1069 SmallVector<uint64_t, 8> FunctionStarts;
1070 for (const MachOObjectFile::LoadCommandInfo &LC : O->load_commands()) {
1071 if (LC.C.cmd == MachO::LC_FUNCTION_STARTS) {
1072 MachO::linkedit_data_command FunctionStartsLC =
1073 O->getLinkeditDataLoadCommand(LC);
1074 O->ReadULEB128s(FunctionStartsLC.dataoff, FunctionStarts);
1075 break;
1076 }
1077 }
1078
1079 for (uint64_t S : FunctionStarts) {
1080 uint64_t Addr = BaseSegmentAddress + S;
1081 if (O->is64Bit())
1082 outs() << format("%016" PRIx64"l" "x", Addr) << "\n";
1083 else
1084 outs() << format("%08" PRIx32"x", static_cast<uint32_t>(Addr)) << "\n";
1085 }
1086}
1087
1088static void PrintDataInCodeTable(MachOObjectFile *O, bool verbose) {
1089 MachO::linkedit_data_command DIC = O->getDataInCodeLoadCommand();
1090 uint32_t nentries = DIC.datasize / sizeof(struct MachO::data_in_code_entry);
1091 outs() << "Data in code table (" << nentries << " entries)\n";
1092 outs() << "offset length kind\n";
1093 for (dice_iterator DI = O->begin_dices(), DE = O->end_dices(); DI != DE;
1094 ++DI) {
1095 uint32_t Offset;
1096 DI->getOffset(Offset);
1097 outs() << format("0x%08" PRIx32"x", Offset) << " ";
1098 uint16_t Length;
1099 DI->getLength(Length);
1100 outs() << format("%6u", Length) << " ";
1101 uint16_t Kind;
1102 DI->getKind(Kind);
1103 if (verbose) {
1104 switch (Kind) {
1105 case MachO::DICE_KIND_DATA:
1106 outs() << "DATA";
1107 break;
1108 case MachO::DICE_KIND_JUMP_TABLE8:
1109 outs() << "JUMP_TABLE8";
1110 break;
1111 case MachO::DICE_KIND_JUMP_TABLE16:
1112 outs() << "JUMP_TABLE16";
1113 break;
1114 case MachO::DICE_KIND_JUMP_TABLE32:
1115 outs() << "JUMP_TABLE32";
1116 break;
1117 case MachO::DICE_KIND_ABS_JUMP_TABLE32:
1118 outs() << "ABS_JUMP_TABLE32";
1119 break;
1120 default:
1121 outs() << format("0x%04" PRIx32"x", Kind);
1122 break;
1123 }
1124 } else
1125 outs() << format("0x%04" PRIx32"x", Kind);
1126 outs() << "\n";
1127 }
1128}
1129
1130static void PrintLinkOptHints(MachOObjectFile *O) {
1131 MachO::linkedit_data_command LohLC = O->getLinkOptHintsLoadCommand();
1132 const char *loh = O->getData().substr(LohLC.dataoff, 1).data();
1133 uint32_t nloh = LohLC.datasize;
1134 outs() << "Linker optimiztion hints (" << nloh << " total bytes)\n";
1135 for (uint32_t i = 0; i < nloh;) {
1136 unsigned n;
1137 uint64_t identifier = decodeULEB128((const uint8_t *)(loh + i), &n);
1138 i += n;
1139 outs() << " identifier " << identifier << " ";
1140 if (i >= nloh)
1141 return;
1142 switch (identifier) {
1143 case 1:
1144 outs() << "AdrpAdrp\n";
1145 break;
1146 case 2:
1147 outs() << "AdrpLdr\n";
1148 break;
1149 case 3:
1150 outs() << "AdrpAddLdr\n";
1151 break;
1152 case 4:
1153 outs() << "AdrpLdrGotLdr\n";
1154 break;
1155 case 5:
1156 outs() << "AdrpAddStr\n";
1157 break;
1158 case 6:
1159 outs() << "AdrpLdrGotStr\n";
1160 break;
1161 case 7:
1162 outs() << "AdrpAdd\n";
1163 break;
1164 case 8:
1165 outs() << "AdrpLdrGot\n";
1166 break;
1167 default:
1168 outs() << "Unknown identifier value\n";
1169 break;
1170 }
1171 uint64_t narguments = decodeULEB128((const uint8_t *)(loh + i), &n);
1172 i += n;
1173 outs() << " narguments " << narguments << "\n";
1174 if (i >= nloh)
1175 return;
1176
1177 for (uint32_t j = 0; j < narguments; j++) {
1178 uint64_t value = decodeULEB128((const uint8_t *)(loh + i), &n);
1179 i += n;
1180 outs() << "\tvalue " << format("0x%" PRIx64"l" "x", value) << "\n";
1181 if (i >= nloh)
1182 return;
1183 }
1184 }
1185}
1186
1187static void printMachOChainedFixups(object::MachOObjectFile *Obj) {
1188 Error Err = Error::success();
1189 for (const object::MachOChainedFixupEntry &Entry : Obj->fixupTable(Err)) {
1190 (void)Entry;
1191 }
1192 if (Err)
1193 reportError(std::move(Err), Obj->getFileName());
1194}
1195
1196static void PrintDyldInfo(MachOObjectFile *O) {
1197 outs() << "dyld information:" << '\n';
1198 printMachOChainedFixups(O);
1199}
1200
1201static void PrintDylibs(MachOObjectFile *O, bool JustId) {
1202 unsigned Index = 0;
1203 for (const auto &Load : O->load_commands()) {
1204 if ((JustId && Load.C.cmd == MachO::LC_ID_DYLIB) ||
1205 (!JustId && (Load.C.cmd == MachO::LC_ID_DYLIB ||
1206 Load.C.cmd == MachO::LC_LOAD_DYLIB ||
1207 Load.C.cmd == MachO::LC_LOAD_WEAK_DYLIB ||
1208 Load.C.cmd == MachO::LC_REEXPORT_DYLIB ||
1209 Load.C.cmd == MachO::LC_LAZY_LOAD_DYLIB ||
1210 Load.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB))) {
1211 MachO::dylib_command dl = O->getDylibIDLoadCommand(Load);
1212 if (dl.dylib.name < dl.cmdsize) {
1213 const char *p = (const char *)(Load.Ptr) + dl.dylib.name;
1214 if (JustId)
1215 outs() << p << "\n";
1216 else {
1217 outs() << "\t" << p;
1218 outs() << " (compatibility version "
1219 << ((dl.dylib.compatibility_version >> 16) & 0xffff) << "."
1220 << ((dl.dylib.compatibility_version >> 8) & 0xff) << "."
1221 << (dl.dylib.compatibility_version & 0xff) << ",";
1222 outs() << " current version "
1223 << ((dl.dylib.current_version >> 16) & 0xffff) << "."
1224 << ((dl.dylib.current_version >> 8) & 0xff) << "."
1225 << (dl.dylib.current_version & 0xff);
1226 if (Load.C.cmd == MachO::LC_LOAD_WEAK_DYLIB)
1227 outs() << ", weak";
1228 if (Load.C.cmd == MachO::LC_REEXPORT_DYLIB)
1229 outs() << ", reexport";
1230 if (Load.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB)
1231 outs() << ", upward";
1232 if (Load.C.cmd == MachO::LC_LAZY_LOAD_DYLIB)
1233 outs() << ", lazy";
1234 outs() << ")\n";
1235 }
1236 } else {
1237 outs() << "\tBad offset (" << dl.dylib.name << ") for name of ";
1238 if (Load.C.cmd == MachO::LC_ID_DYLIB)
1239 outs() << "LC_ID_DYLIB ";
1240 else if (Load.C.cmd == MachO::LC_LOAD_DYLIB)
1241 outs() << "LC_LOAD_DYLIB ";
1242 else if (Load.C.cmd == MachO::LC_LOAD_WEAK_DYLIB)
1243 outs() << "LC_LOAD_WEAK_DYLIB ";
1244 else if (Load.C.cmd == MachO::LC_LAZY_LOAD_DYLIB)
1245 outs() << "LC_LAZY_LOAD_DYLIB ";
1246 else if (Load.C.cmd == MachO::LC_REEXPORT_DYLIB)
1247 outs() << "LC_REEXPORT_DYLIB ";
1248 else if (Load.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB)
1249 outs() << "LC_LOAD_UPWARD_DYLIB ";
1250 else
1251 outs() << "LC_??? ";
1252 outs() << "command " << Index++ << "\n";
1253 }
1254 }
1255 }
1256}
1257
1258static void printRpaths(MachOObjectFile *O) {
1259 for (const auto &Command : O->load_commands()) {
1260 if (Command.C.cmd == MachO::LC_RPATH) {
1261 auto Rpath = O->getRpathCommand(Command);
1262 const char *P = (const char *)(Command.Ptr) + Rpath.path;
1263 outs() << P << "\n";
1264 }
1265 }
1266}
1267
1268typedef DenseMap<uint64_t, StringRef> SymbolAddressMap;
1269
1270static void CreateSymbolAddressMap(MachOObjectFile *O,
1271 SymbolAddressMap *AddrMap) {
1272 // Create a map of symbol addresses to symbol names.
1273 const StringRef FileName = O->getFileName();
1274 for (const SymbolRef &Symbol : O->symbols()) {
1275 SymbolRef::Type ST = unwrapOrError(Symbol.getType(), FileName);
1276 if (ST == SymbolRef::ST_Function || ST == SymbolRef::ST_Data ||
1277 ST == SymbolRef::ST_Other) {
1278 uint64_t Address = cantFail(Symbol.getValue());
1279 StringRef SymName = unwrapOrError(Symbol.getName(), FileName);
1280 if (!SymName.startswith(".objc"))
1281 (*AddrMap)[Address] = SymName;
1282 }
1283 }
1284}
1285
1286// GuessSymbolName is passed the address of what might be a symbol and a
1287// pointer to the SymbolAddressMap. It returns the name of a symbol
1288// with that address or nullptr if no symbol is found with that address.
1289static const char *GuessSymbolName(uint64_t value, SymbolAddressMap *AddrMap) {
1290 const char *SymbolName = nullptr;
1291 // A DenseMap can't lookup up some values.
1292 if (value != 0xffffffffffffffffULL && value != 0xfffffffffffffffeULL) {
1293 StringRef name = AddrMap->lookup(value);
1294 if (!name.empty())
1295 SymbolName = name.data();
1296 }
1297 return SymbolName;
1298}
1299
1300static void DumpCstringChar(const char c) {
1301 char p[2];
1302 p[0] = c;
1303 p[1] = '\0';
1304 outs().write_escaped(p);
1305}
1306
1307static void DumpCstringSection(MachOObjectFile *O, const char *sect,
1308 uint32_t sect_size, uint64_t sect_addr,
1309 bool print_addresses) {
1310 for (uint32_t i = 0; i < sect_size; i++) {
1311 if (print_addresses) {
1312 if (O->is64Bit())
1313 outs() << format("%016" PRIx64"l" "x", sect_addr + i) << " ";
1314 else
1315 outs() << format("%08" PRIx64"l" "x", sect_addr + i) << " ";
1316 }
1317 for (; i < sect_size && sect[i] != '\0'; i++)
1318 DumpCstringChar(sect[i]);
1319 if (i < sect_size && sect[i] == '\0')
1320 outs() << "\n";
1321 }
1322}
1323
1324static void DumpLiteral4(uint32_t l, float f) {
1325 outs() << format("0x%08" PRIx32"x", l);
1326 if ((l & 0x7f800000) != 0x7f800000)
1327 outs() << format(" (%.16e)\n", f);
1328 else {
1329 if (l == 0x7f800000)
1330 outs() << " (+Infinity)\n";
1331 else if (l == 0xff800000)
1332 outs() << " (-Infinity)\n";
1333 else if ((l & 0x00400000) == 0x00400000)
1334 outs() << " (non-signaling Not-a-Number)\n";
1335 else
1336 outs() << " (signaling Not-a-Number)\n";
1337 }
1338}
1339
1340static void DumpLiteral4Section(MachOObjectFile *O, const char *sect,
1341 uint32_t sect_size, uint64_t sect_addr,
1342 bool print_addresses) {
1343 for (uint32_t i = 0; i < sect_size; i += sizeof(float)) {
1344 if (print_addresses) {
1345 if (O->is64Bit())
1346 outs() << format("%016" PRIx64"l" "x", sect_addr + i) << " ";
1347 else
1348 outs() << format("%08" PRIx64"l" "x", sect_addr + i) << " ";
1349 }
1350 float f;
1351 memcpy(&f, sect + i, sizeof(float));
1352 if (O->isLittleEndian() != sys::IsLittleEndianHost)
1353 sys::swapByteOrder(f);
1354 uint32_t l;
1355 memcpy(&l, sect + i, sizeof(uint32_t));
1356 if (O->isLittleEndian() != sys::IsLittleEndianHost)
1357 sys::swapByteOrder(l);
1358 DumpLiteral4(l, f);
1359 }
1360}
1361
1362static void DumpLiteral8(MachOObjectFile *O, uint32_t l0, uint32_t l1,
1363 double d) {
1364 outs() << format("0x%08" PRIx32"x", l0) << " " << format("0x%08" PRIx32"x", l1);
1365 uint32_t Hi, Lo;
1366 Hi = (O->isLittleEndian()) ? l1 : l0;
1367 Lo = (O->isLittleEndian()) ? l0 : l1;
1368
1369 // Hi is the high word, so this is equivalent to if(isfinite(d))
1370 if ((Hi & 0x7ff00000) != 0x7ff00000)
1371 outs() << format(" (%.16e)\n", d);
1372 else {
1373 if (Hi == 0x7ff00000 && Lo == 0)
1374 outs() << " (+Infinity)\n";
1375 else if (Hi == 0xfff00000 && Lo == 0)
1376 outs() << " (-Infinity)\n";
1377 else if ((Hi & 0x00080000) == 0x00080000)
1378 outs() << " (non-signaling Not-a-Number)\n";
1379 else
1380 outs() << " (signaling Not-a-Number)\n";
1381 }
1382}
1383
1384static void DumpLiteral8Section(MachOObjectFile *O, const char *sect,
1385 uint32_t sect_size, uint64_t sect_addr,
1386 bool print_addresses) {
1387 for (uint32_t i = 0; i < sect_size; i += sizeof(double)) {
1388 if (print_addresses) {
1389 if (O->is64Bit())
1390 outs() << format("%016" PRIx64"l" "x", sect_addr + i) << " ";
1391 else
1392 outs() << format("%08" PRIx64"l" "x", sect_addr + i) << " ";
1393 }
1394 double d;
1395 memcpy(&d, sect + i, sizeof(double));
1396 if (O->isLittleEndian() != sys::IsLittleEndianHost)
1397 sys::swapByteOrder(d);
1398 uint32_t l0, l1;
1399 memcpy(&l0, sect + i, sizeof(uint32_t));
1400 memcpy(&l1, sect + i + sizeof(uint32_t), sizeof(uint32_t));
1401 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
1402 sys::swapByteOrder(l0);
1403 sys::swapByteOrder(l1);
1404 }
1405 DumpLiteral8(O, l0, l1, d);
1406 }
1407}
1408
1409static void DumpLiteral16(uint32_t l0, uint32_t l1, uint32_t l2, uint32_t l3) {
1410 outs() << format("0x%08" PRIx32"x", l0) << " ";
1411 outs() << format("0x%08" PRIx32"x", l1) << " ";
1412 outs() << format("0x%08" PRIx32"x", l2) << " ";
1413 outs() << format("0x%08" PRIx32"x", l3) << "\n";
1414}
1415
1416static void DumpLiteral16Section(MachOObjectFile *O, const char *sect,
1417 uint32_t sect_size, uint64_t sect_addr,
1418 bool print_addresses) {
1419 for (uint32_t i = 0; i < sect_size; i += 16) {
1420 if (print_addresses) {
1421 if (O->is64Bit())
1422 outs() << format("%016" PRIx64"l" "x", sect_addr + i) << " ";
1423 else
1424 outs() << format("%08" PRIx64"l" "x", sect_addr + i) << " ";
1425 }
1426 uint32_t l0, l1, l2, l3;
1427 memcpy(&l0, sect + i, sizeof(uint32_t));
1428 memcpy(&l1, sect + i + sizeof(uint32_t), sizeof(uint32_t));
1429 memcpy(&l2, sect + i + 2 * sizeof(uint32_t), sizeof(uint32_t));
1430 memcpy(&l3, sect + i + 3 * sizeof(uint32_t), sizeof(uint32_t));
1431 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
1432 sys::swapByteOrder(l0);
1433 sys::swapByteOrder(l1);
1434 sys::swapByteOrder(l2);
1435 sys::swapByteOrder(l3);
1436 }
1437 DumpLiteral16(l0, l1, l2, l3);
1438 }
1439}
1440
1441static void DumpLiteralPointerSection(MachOObjectFile *O,
1442 const SectionRef &Section,
1443 const char *sect, uint32_t sect_size,
1444 uint64_t sect_addr,
1445 bool print_addresses) {
1446 // Collect the literal sections in this Mach-O file.
1447 std::vector<SectionRef> LiteralSections;
1448 for (const SectionRef &Section : O->sections()) {
1449 DataRefImpl Ref = Section.getRawDataRefImpl();
1450 uint32_t section_type;
1451 if (O->is64Bit()) {
1452 const MachO::section_64 Sec = O->getSection64(Ref);
1453 section_type = Sec.flags & MachO::SECTION_TYPE;
1454 } else {
1455 const MachO::section Sec = O->getSection(Ref);
1456 section_type = Sec.flags & MachO::SECTION_TYPE;
1457 }
1458 if (section_type == MachO::S_CSTRING_LITERALS ||
1459 section_type == MachO::S_4BYTE_LITERALS ||
1460 section_type == MachO::S_8BYTE_LITERALS ||
1461 section_type == MachO::S_16BYTE_LITERALS)
1462 LiteralSections.push_back(Section);
1463 }
1464
1465 // Set the size of the literal pointer.
1466 uint32_t lp_size = O->is64Bit() ? 8 : 4;
1467
1468 // Collect the external relocation symbols for the literal pointers.
1469 std::vector<std::pair<uint64_t, SymbolRef>> Relocs;
1470 for (const RelocationRef &Reloc : Section.relocations()) {
1471 DataRefImpl Rel;
1472 MachO::any_relocation_info RE;
1473 bool isExtern = false;
1474 Rel = Reloc.getRawDataRefImpl();
1475 RE = O->getRelocation(Rel);
1476 isExtern = O->getPlainRelocationExternal(RE);
1477 if (isExtern) {
1478 uint64_t RelocOffset = Reloc.getOffset();
1479 symbol_iterator RelocSym = Reloc.getSymbol();
1480 Relocs.push_back(std::make_pair(RelocOffset, *RelocSym));
1481 }
1482 }
1483 array_pod_sort(Relocs.begin(), Relocs.end());
1484
1485 // Dump each literal pointer.
1486 for (uint32_t i = 0; i < sect_size; i += lp_size) {
1487 if (print_addresses) {
1488 if (O->is64Bit())
1489 outs() << format("%016" PRIx64"l" "x", sect_addr + i) << " ";
1490 else
1491 outs() << format("%08" PRIx64"l" "x", sect_addr + i) << " ";
1492 }
1493 uint64_t lp;
1494 if (O->is64Bit()) {
1495 memcpy(&lp, sect + i, sizeof(uint64_t));
1496 if (O->isLittleEndian() != sys::IsLittleEndianHost)
1497 sys::swapByteOrder(lp);
1498 } else {
1499 uint32_t li;
1500 memcpy(&li, sect + i, sizeof(uint32_t));
1501 if (O->isLittleEndian() != sys::IsLittleEndianHost)
1502 sys::swapByteOrder(li);
1503 lp = li;
1504 }
1505
1506 // First look for an external relocation entry for this literal pointer.
1507 auto Reloc = find_if(Relocs, [&](const std::pair<uint64_t, SymbolRef> &P) {
1508 return P.first == i;
1509 });
1510 if (Reloc != Relocs.end()) {
1511 symbol_iterator RelocSym = Reloc->second;
1512 StringRef SymName = unwrapOrError(RelocSym->getName(), O->getFileName());
1513 outs() << "external relocation entry for symbol:" << SymName << "\n";
1514 continue;
1515 }
1516
1517 // For local references see what the section the literal pointer points to.
1518 auto Sect = find_if(LiteralSections, [&](const SectionRef &R) {
1519 return lp >= R.getAddress() && lp < R.getAddress() + R.getSize();
1520 });
1521 if (Sect == LiteralSections.end()) {
1522 outs() << format("0x%" PRIx64"l" "x", lp) << " (not in a literal section)\n";
1523 continue;
1524 }
1525
1526 uint64_t SectAddress = Sect->getAddress();
1527 uint64_t SectSize = Sect->getSize();
1528
1529 StringRef SectName;
1530 Expected<StringRef> SectNameOrErr = Sect->getName();
1531 if (SectNameOrErr)
1532 SectName = *SectNameOrErr;
1533 else
1534 consumeError(SectNameOrErr.takeError());
1535
1536 DataRefImpl Ref = Sect->getRawDataRefImpl();
1537 StringRef SegmentName = O->getSectionFinalSegmentName(Ref);
1538 outs() << SegmentName << ":" << SectName << ":";
1539
1540 uint32_t section_type;
1541 if (O->is64Bit()) {
1542 const MachO::section_64 Sec = O->getSection64(Ref);
1543 section_type = Sec.flags & MachO::SECTION_TYPE;
1544 } else {
1545 const MachO::section Sec = O->getSection(Ref);
1546 section_type = Sec.flags & MachO::SECTION_TYPE;
1547 }
1548
1549 StringRef BytesStr = unwrapOrError(Sect->getContents(), O->getFileName());
1550
1551 const char *Contents = reinterpret_cast<const char *>(BytesStr.data());
1552
1553 switch (section_type) {
1554 case MachO::S_CSTRING_LITERALS:
1555 for (uint64_t i = lp - SectAddress; i < SectSize && Contents[i] != '\0';
1556 i++) {
1557 DumpCstringChar(Contents[i]);
1558 }
1559 outs() << "\n";
1560 break;
1561 case MachO::S_4BYTE_LITERALS:
1562 float f;
1563 memcpy(&f, Contents + (lp - SectAddress), sizeof(float));
1564 uint32_t l;
1565 memcpy(&l, Contents + (lp - SectAddress), sizeof(uint32_t));
1566 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
1567 sys::swapByteOrder(f);
1568 sys::swapByteOrder(l);
1569 }
1570 DumpLiteral4(l, f);
1571 break;
1572 case MachO::S_8BYTE_LITERALS: {
1573 double d;
1574 memcpy(&d, Contents + (lp - SectAddress), sizeof(double));
1575 uint32_t l0, l1;
1576 memcpy(&l0, Contents + (lp - SectAddress), sizeof(uint32_t));
1577 memcpy(&l1, Contents + (lp - SectAddress) + sizeof(uint32_t),
1578 sizeof(uint32_t));
1579 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
1580 sys::swapByteOrder(f);
1581 sys::swapByteOrder(l0);
1582 sys::swapByteOrder(l1);
1583 }
1584 DumpLiteral8(O, l0, l1, d);
1585 break;
1586 }
1587 case MachO::S_16BYTE_LITERALS: {
1588 uint32_t l0, l1, l2, l3;
1589 memcpy(&l0, Contents + (lp - SectAddress), sizeof(uint32_t));
1590 memcpy(&l1, Contents + (lp - SectAddress) + sizeof(uint32_t),
1591 sizeof(uint32_t));
1592 memcpy(&l2, Contents + (lp - SectAddress) + 2 * sizeof(uint32_t),
1593 sizeof(uint32_t));
1594 memcpy(&l3, Contents + (lp - SectAddress) + 3 * sizeof(uint32_t),
1595 sizeof(uint32_t));
1596 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
1597 sys::swapByteOrder(l0);
1598 sys::swapByteOrder(l1);
1599 sys::swapByteOrder(l2);
1600 sys::swapByteOrder(l3);
1601 }
1602 DumpLiteral16(l0, l1, l2, l3);
1603 break;
1604 }
1605 }
1606 }
1607}
1608
1609static void DumpInitTermPointerSection(MachOObjectFile *O,
1610 const SectionRef &Section,
1611 const char *sect,
1612 uint32_t sect_size, uint64_t sect_addr,
1613 SymbolAddressMap *AddrMap,
1614 bool verbose) {
1615 uint32_t stride;
1616 stride = (O->is64Bit()) ? sizeof(uint64_t) : sizeof(uint32_t);
1617
1618 // Collect the external relocation symbols for the pointers.
1619 std::vector<std::pair<uint64_t, SymbolRef>> Relocs;
1620 for (const RelocationRef &Reloc : Section.relocations()) {
1621 DataRefImpl Rel;
1622 MachO::any_relocation_info RE;
1623 bool isExtern = false;
1624 Rel = Reloc.getRawDataRefImpl();
1625 RE = O->getRelocation(Rel);
1626 isExtern = O->getPlainRelocationExternal(RE);
1627 if (isExtern) {
1628 uint64_t RelocOffset = Reloc.getOffset();
1629 symbol_iterator RelocSym = Reloc.getSymbol();
1630 Relocs.push_back(std::make_pair(RelocOffset, *RelocSym));
1631 }
1632 }
1633 array_pod_sort(Relocs.begin(), Relocs.end());
1634
1635 for (uint32_t i = 0; i < sect_size; i += stride) {
1636 const char *SymbolName = nullptr;
1637 uint64_t p;
1638 if (O->is64Bit()) {
1639 outs() << format("0x%016" PRIx64"l" "x", sect_addr + i * stride) << " ";
1640 uint64_t pointer_value;
1641 memcpy(&pointer_value, sect + i, stride);
1642 if (O->isLittleEndian() != sys::IsLittleEndianHost)
1643 sys::swapByteOrder(pointer_value);
1644 outs() << format("0x%016" PRIx64"l" "x", pointer_value);
1645 p = pointer_value;
1646 } else {
1647 outs() << format("0x%08" PRIx64"l" "x", sect_addr + i * stride) << " ";
1648 uint32_t pointer_value;
1649 memcpy(&pointer_value, sect + i, stride);
1650 if (O->isLittleEndian() != sys::IsLittleEndianHost)
1651 sys::swapByteOrder(pointer_value);
1652 outs() << format("0x%08" PRIx32"x", pointer_value);
1653 p = pointer_value;
1654 }
1655 if (verbose) {
1656 // First look for an external relocation entry for this pointer.
1657 auto Reloc = find_if(Relocs, [&](const std::pair<uint64_t, SymbolRef> &P) {
1658 return P.first == i;
1659 });
1660 if (Reloc != Relocs.end()) {
1661 symbol_iterator RelocSym = Reloc->second;
1662 outs() << " " << unwrapOrError(RelocSym->getName(), O->getFileName());
1663 } else {
1664 SymbolName = GuessSymbolName(p, AddrMap);
1665 if (SymbolName)
1666 outs() << " " << SymbolName;
1667 }
1668 }
1669 outs() << "\n";
1670 }
1671}
1672
1673static void DumpRawSectionContents(MachOObjectFile *O, const char *sect,
1674 uint32_t size, uint64_t addr) {
1675 uint32_t cputype = O->getHeader().cputype;
1676 if (cputype == MachO::CPU_TYPE_I386 || cputype == MachO::CPU_TYPE_X86_64) {
1677 uint32_t j;
1678 for (uint32_t i = 0; i < size; i += j, addr += j) {
1679 if (O->is64Bit())
1680 outs() << format("%016" PRIx64"l" "x", addr) << "\t";
1681 else
1682 outs() << format("%08" PRIx64"l" "x", addr) << "\t";
1683 for (j = 0; j < 16 && i + j < size; j++) {
1684 uint8_t byte_word = *(sect + i + j);
1685 outs() << format("%02" PRIx32"x", (uint32_t)byte_word) << " ";
1686 }
1687 outs() << "\n";
1688 }
1689 } else {
1690 uint32_t j;
1691 for (uint32_t i = 0; i < size; i += j, addr += j) {
1692 if (O->is64Bit())
1693 outs() << format("%016" PRIx64"l" "x", addr) << "\t";
1694 else
1695 outs() << format("%08" PRIx64"l" "x", addr) << "\t";
1696 for (j = 0; j < 4 * sizeof(int32_t) && i + j < size;
1697 j += sizeof(int32_t)) {
1698 if (i + j + sizeof(int32_t) <= size) {
1699 uint32_t long_word;
1700 memcpy(&long_word, sect + i + j, sizeof(int32_t));
1701 if (O->isLittleEndian() != sys::IsLittleEndianHost)
1702 sys::swapByteOrder(long_word);
1703 outs() << format("%08" PRIx32"x", long_word) << " ";
1704 } else {
1705 for (uint32_t k = 0; i + j + k < size; k++) {
1706 uint8_t byte_word = *(sect + i + j + k);
1707 outs() << format("%02" PRIx32"x", (uint32_t)byte_word) << " ";
1708 }
1709 }
1710 }
1711 outs() << "\n";
1712 }
1713 }
1714}
1715
1716static void DisassembleMachO(StringRef Filename, MachOObjectFile *MachOOF,
1717 StringRef DisSegName, StringRef DisSectName);
1718static void DumpProtocolSection(MachOObjectFile *O, const char *sect,
1719 uint32_t size, uint32_t addr);
1720#ifdef LLVM_HAVE_LIBXAR
1721static void DumpBitcodeSection(MachOObjectFile *O, const char *sect,
1722 uint32_t size, bool verbose,
1723 bool PrintXarHeader, bool PrintXarFileHeaders,
1724 std::string XarMemberName);
1725#endif // defined(LLVM_HAVE_LIBXAR)
1726
1727static void DumpSectionContents(StringRef Filename, MachOObjectFile *O,
1728 bool verbose) {
1729 SymbolAddressMap AddrMap;
1730 if (verbose)
1731 CreateSymbolAddressMap(O, &AddrMap);
1732
1733 for (unsigned i = 0; i < FilterSections.size(); ++i) {
1734 StringRef DumpSection = FilterSections[i];
1735 std::pair<StringRef, StringRef> DumpSegSectName;
1736 DumpSegSectName = DumpSection.split(',');
1737 StringRef DumpSegName, DumpSectName;
1738 if (!DumpSegSectName.second.empty()) {
1739 DumpSegName = DumpSegSectName.first;
1740 DumpSectName = DumpSegSectName.second;
1741 } else {
1742 DumpSegName = "";
1743 DumpSectName = DumpSegSectName.first;
1744 }
1745 for (const SectionRef &Section : O->sections()) {
1746 StringRef SectName;
1747 Expected<StringRef> SecNameOrErr = Section.getName();
1748 if (SecNameOrErr)
1749 SectName = *SecNameOrErr;
1750 else
1751 consumeError(SecNameOrErr.takeError());
1752
1753 if (!DumpSection.empty())
1754 FoundSectionSet.insert(DumpSection);
1755
1756 DataRefImpl Ref = Section.getRawDataRefImpl();
1757 StringRef SegName = O->getSectionFinalSegmentName(Ref);
1758 if ((DumpSegName.empty() || SegName == DumpSegName) &&
1759 (SectName == DumpSectName)) {
1760
1761 uint32_t section_flags;
1762 if (O->is64Bit()) {
1763 const MachO::section_64 Sec = O->getSection64(Ref);
1764 section_flags = Sec.flags;
1765
1766 } else {
1767 const MachO::section Sec = O->getSection(Ref);
1768 section_flags = Sec.flags;
1769 }
1770 uint32_t section_type = section_flags & MachO::SECTION_TYPE;
1771
1772 StringRef BytesStr =
1773 unwrapOrError(Section.getContents(), O->getFileName());
1774 const char *sect = reinterpret_cast<const char *>(BytesStr.data());
1775 uint32_t sect_size = BytesStr.size();
1776 uint64_t sect_addr = Section.getAddress();
1777
1778 if (LeadingHeaders)
1779 outs() << "Contents of (" << SegName << "," << SectName
1780 << ") section\n";
1781
1782 if (verbose) {
1783 if ((section_flags & MachO::S_ATTR_PURE_INSTRUCTIONS) ||
1784 (section_flags & MachO::S_ATTR_SOME_INSTRUCTIONS)) {
1785 DisassembleMachO(Filename, O, SegName, SectName);
1786 continue;
1787 }
1788 if (SegName == "__TEXT" && SectName == "__info_plist") {
1789 outs() << sect;
1790 continue;
1791 }
1792 if (SegName == "__OBJC" && SectName == "__protocol") {
1793 DumpProtocolSection(O, sect, sect_size, sect_addr);
1794 continue;
1795 }
1796#ifdef LLVM_HAVE_LIBXAR
1797 if (SegName == "__LLVM" && SectName == "__bundle") {
1798 DumpBitcodeSection(O, sect, sect_size, verbose, SymbolicOperands,
1799 ArchiveHeaders, "");
1800 continue;
1801 }
1802#endif // defined(LLVM_HAVE_LIBXAR)
1803 switch (section_type) {
1804 case MachO::S_REGULAR:
1805 DumpRawSectionContents(O, sect, sect_size, sect_addr);
1806 break;
1807 case MachO::S_ZEROFILL:
1808 outs() << "zerofill section and has no contents in the file\n";
1809 break;
1810 case MachO::S_CSTRING_LITERALS:
1811 DumpCstringSection(O, sect, sect_size, sect_addr, LeadingAddr);
1812 break;
1813 case MachO::S_4BYTE_LITERALS:
1814 DumpLiteral4Section(O, sect, sect_size, sect_addr, LeadingAddr);
1815 break;
1816 case MachO::S_8BYTE_LITERALS:
1817 DumpLiteral8Section(O, sect, sect_size, sect_addr, LeadingAddr);
1818 break;
1819 case MachO::S_16BYTE_LITERALS:
1820 DumpLiteral16Section(O, sect, sect_size, sect_addr, LeadingAddr);
1821 break;
1822 case MachO::S_LITERAL_POINTERS:
1823 DumpLiteralPointerSection(O, Section, sect, sect_size, sect_addr,
1824 LeadingAddr);
1825 break;
1826 case MachO::S_MOD_INIT_FUNC_POINTERS:
1827 case MachO::S_MOD_TERM_FUNC_POINTERS:
1828 DumpInitTermPointerSection(O, Section, sect, sect_size, sect_addr,
1829 &AddrMap, verbose);
1830 break;
1831 default:
1832 outs() << "Unknown section type ("
1833 << format("0x%08" PRIx32"x", section_type) << ")\n";
1834 DumpRawSectionContents(O, sect, sect_size, sect_addr);
1835 break;
1836 }
1837 } else {
1838 if (section_type == MachO::S_ZEROFILL)
1839 outs() << "zerofill section and has no contents in the file\n";
1840 else
1841 DumpRawSectionContents(O, sect, sect_size, sect_addr);
1842 }
1843 }
1844 }
1845 }
1846}
1847
1848static void DumpInfoPlistSectionContents(StringRef Filename,
1849 MachOObjectFile *O) {
1850 for (const SectionRef &Section : O->sections()) {
1851 StringRef SectName;
1852 Expected<StringRef> SecNameOrErr = Section.getName();
1853 if (SecNameOrErr)
1854 SectName = *SecNameOrErr;
1855 else
1856 consumeError(SecNameOrErr.takeError());
1857
1858 DataRefImpl Ref = Section.getRawDataRefImpl();
1859 StringRef SegName = O->getSectionFinalSegmentName(Ref);
1860 if (SegName == "__TEXT" && SectName == "__info_plist") {
1861 if (LeadingHeaders)
1862 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
1863 StringRef BytesStr =
1864 unwrapOrError(Section.getContents(), O->getFileName());
1865 const char *sect = reinterpret_cast<const char *>(BytesStr.data());
1866 outs() << format("%.*s", BytesStr.size(), sect) << "\n";
1867 return;
1868 }
1869 }
1870}
1871
1872// checkMachOAndArchFlags() checks to see if the ObjectFile is a Mach-O file
1873// and if it is and there is a list of architecture flags is specified then
1874// check to make sure this Mach-O file is one of those architectures or all
1875// architectures were specified. If not then an error is generated and this
1876// routine returns false. Else it returns true.
1877static bool checkMachOAndArchFlags(ObjectFile *O, StringRef Filename) {
1878 auto *MachO = dyn_cast<MachOObjectFile>(O);
1879
1880 if (!MachO || ArchAll || ArchFlags.empty())
1881 return true;
1882
1883 MachO::mach_header H;
1884 MachO::mach_header_64 H_64;
1885 Triple T;
1886 const char *McpuDefault, *ArchFlag;
1887 if (MachO->is64Bit()) {
1888 H_64 = MachO->MachOObjectFile::getHeader64();
1889 T = MachOObjectFile::getArchTriple(H_64.cputype, H_64.cpusubtype,
1890 &McpuDefault, &ArchFlag);
1891 } else {
1892 H = MachO->MachOObjectFile::getHeader();
1893 T = MachOObjectFile::getArchTriple(H.cputype, H.cpusubtype,
1894 &McpuDefault, &ArchFlag);
1895 }
1896 const std::string ArchFlagName(ArchFlag);
1897 if (!llvm::is_contained(ArchFlags, ArchFlagName)) {
1898 WithColor::error(errs(), "llvm-objdump")
1899 << Filename << ": no architecture specified.\n";
1900 return false;
1901 }
1902 return true;
1903}
1904
1905static void printObjcMetaData(MachOObjectFile *O, bool verbose);
1906
1907// ProcessMachO() is passed a single opened Mach-O file, which may be an
1908// archive member and or in a slice of a universal file. It prints the
1909// the file name and header info and then processes it according to the
1910// command line options.
1911static void ProcessMachO(StringRef Name, MachOObjectFile *MachOOF,
1912 StringRef ArchiveMemberName = StringRef(),
1913 StringRef ArchitectureName = StringRef()) {
1914 // If we are doing some processing here on the Mach-O file print the header
1915 // info. And don't print it otherwise like in the case of printing the
1916 // UniversalHeaders or ArchiveHeaders.
1917 if (Disassemble || Relocations || PrivateHeaders || ExportsTrie || Rebase ||
1918 Bind || SymbolTable || LazyBind || WeakBind || IndirectSymbols ||
1919 DataInCode || FunctionStarts || LinkOptHints || DyldInfo || DylibsUsed ||
1920 DylibId || Rpaths || ObjcMetaData || (!FilterSections.empty())) {
1921 if (LeadingHeaders) {
1922 outs() << Name;
1923 if (!ArchiveMemberName.empty())
1924 outs() << '(' << ArchiveMemberName << ')';
1925 if (!ArchitectureName.empty())
1926 outs() << " (architecture " << ArchitectureName << ")";
1927 outs() << ":\n";
1928 }
1929 }
1930 // To use the report_error() form with an ArchiveName and FileName set
1931 // these up based on what is passed for Name and ArchiveMemberName.
1932 StringRef ArchiveName;
1933 StringRef FileName;
1934 if (!ArchiveMemberName.empty()) {
1935 ArchiveName = Name;
1936 FileName = ArchiveMemberName;
1937 } else {
1938 ArchiveName = StringRef();
1939 FileName = Name;
1940 }
1941
1942 // If we need the symbol table to do the operation then check it here to
1943 // produce a good error message as to where the Mach-O file comes from in
1944 // the error message.
1945 if (Disassemble || IndirectSymbols || !FilterSections.empty() || UnwindInfo)
1946 if (Error Err = MachOOF->checkSymbolTable())
1947 reportError(std::move(Err), FileName, ArchiveName, ArchitectureName);
1948
1949 if (DisassembleAll) {
1950 for (const SectionRef &Section : MachOOF->sections()) {
1951 StringRef SectName;
1952 if (Expected<StringRef> NameOrErr = Section.getName())
1953 SectName = *NameOrErr;
1954 else
1955 consumeError(NameOrErr.takeError());
1956
1957 if (SectName.equals("__text")) {
1958 DataRefImpl Ref = Section.getRawDataRefImpl();
1959 StringRef SegName = MachOOF->getSectionFinalSegmentName(Ref);
1960 DisassembleMachO(FileName, MachOOF, SegName, SectName);
1961 }
1962 }
1963 }
1964 else if (Disassemble) {
1965 if (MachOOF->getHeader().filetype == MachO::MH_KEXT_BUNDLE &&
1966 MachOOF->getHeader().cputype == MachO::CPU_TYPE_ARM64)
1967 DisassembleMachO(FileName, MachOOF, "__TEXT_EXEC", "__text");
1968 else
1969 DisassembleMachO(FileName, MachOOF, "__TEXT", "__text");
1970 }
1971 if (IndirectSymbols)
1972 PrintIndirectSymbols(MachOOF, Verbose);
1973 if (DataInCode)
1974 PrintDataInCodeTable(MachOOF, Verbose);
1975 if (FunctionStarts)
1976 PrintFunctionStarts(MachOOF);
1977 if (LinkOptHints)
1978 PrintLinkOptHints(MachOOF);
1979 if (Relocations)
1980 PrintRelocations(MachOOF, Verbose);
1981 if (SectionHeaders)
1982 printSectionHeaders(MachOOF);
1983 if (SectionContents)
1984 printSectionContents(MachOOF);
1985 if (!FilterSections.empty())
1986 DumpSectionContents(FileName, MachOOF, Verbose);
1987 if (InfoPlist)
1988 DumpInfoPlistSectionContents(FileName, MachOOF);
1989 if (DyldInfo)
1990 PrintDyldInfo(MachOOF);
1991 if (DylibsUsed)
1992 PrintDylibs(MachOOF, false);
1993 if (DylibId)
1994 PrintDylibs(MachOOF, true);
1995 if (SymbolTable)
1996 printSymbolTable(MachOOF, ArchiveName, ArchitectureName);
1997 if (UnwindInfo)
1998 printMachOUnwindInfo(MachOOF);
1999 if (PrivateHeaders) {
2000 printMachOFileHeader(MachOOF);
2001 printMachOLoadCommands(MachOOF);
2002 }
2003 if (FirstPrivateHeader)
2004 printMachOFileHeader(MachOOF);
2005 if (ObjcMetaData)
2006 printObjcMetaData(MachOOF, Verbose);
2007 if (ExportsTrie)
2008 printExportsTrie(MachOOF);
2009 if (Rebase)
2010 printRebaseTable(MachOOF);
2011 if (Rpaths)
2012 printRpaths(MachOOF);
2013 if (Bind)
2014 printBindTable(MachOOF);
2015 if (LazyBind)
2016 printLazyBindTable(MachOOF);
2017 if (WeakBind)
2018 printWeakBindTable(MachOOF);
2019
2020 if (DwarfDumpType != DIDT_Null) {
2021 std::unique_ptr<DIContext> DICtx = DWARFContext::create(*MachOOF);
2022 // Dump the complete DWARF structure.
2023 DIDumpOptions DumpOpts;
2024 DumpOpts.DumpType = DwarfDumpType;
2025 DICtx->dump(outs(), DumpOpts);
2026 }
2027}
2028
2029// printUnknownCPUType() helps print_fat_headers for unknown CPU's.
2030static void printUnknownCPUType(uint32_t cputype, uint32_t cpusubtype) {
2031 outs() << " cputype (" << cputype << ")\n";
2032 outs() << " cpusubtype (" << cpusubtype << ")\n";
2033}
2034
2035// printCPUType() helps print_fat_headers by printing the cputype and
2036// pusubtype (symbolically for the one's it knows about).
2037static void printCPUType(uint32_t cputype, uint32_t cpusubtype) {
2038 switch (cputype) {
2039 case MachO::CPU_TYPE_I386:
2040 switch (cpusubtype) {
2041 case MachO::CPU_SUBTYPE_I386_ALL:
2042 outs() << " cputype CPU_TYPE_I386\n";
2043 outs() << " cpusubtype CPU_SUBTYPE_I386_ALL\n";
2044 break;
2045 default:
2046 printUnknownCPUType(cputype, cpusubtype);
2047 break;
2048 }
2049 break;
2050 case MachO::CPU_TYPE_X86_64:
2051 switch (cpusubtype) {
2052 case MachO::CPU_SUBTYPE_X86_64_ALL:
2053 outs() << " cputype CPU_TYPE_X86_64\n";
2054 outs() << " cpusubtype CPU_SUBTYPE_X86_64_ALL\n";
2055 break;
2056 case MachO::CPU_SUBTYPE_X86_64_H:
2057 outs() << " cputype CPU_TYPE_X86_64\n";
2058 outs() << " cpusubtype CPU_SUBTYPE_X86_64_H\n";
2059 break;
2060 default:
2061 printUnknownCPUType(cputype, cpusubtype);
2062 break;
2063 }
2064 break;
2065 case MachO::CPU_TYPE_ARM:
2066 switch (cpusubtype) {
2067 case MachO::CPU_SUBTYPE_ARM_ALL:
2068 outs() << " cputype CPU_TYPE_ARM\n";
2069 outs() << " cpusubtype CPU_SUBTYPE_ARM_ALL\n";
2070 break;
2071 case MachO::CPU_SUBTYPE_ARM_V4T:
2072 outs() << " cputype CPU_TYPE_ARM\n";
2073 outs() << " cpusubtype CPU_SUBTYPE_ARM_V4T\n";
2074 break;
2075 case MachO::CPU_SUBTYPE_ARM_V5TEJ:
2076 outs() << " cputype CPU_TYPE_ARM\n";
2077 outs() << " cpusubtype CPU_SUBTYPE_ARM_V5TEJ\n";
2078 break;
2079 case MachO::CPU_SUBTYPE_ARM_XSCALE:
2080 outs() << " cputype CPU_TYPE_ARM\n";
2081 outs() << " cpusubtype CPU_SUBTYPE_ARM_XSCALE\n";
2082 break;
2083 case MachO::CPU_SUBTYPE_ARM_V6:
2084 outs() << " cputype CPU_TYPE_ARM\n";
2085 outs() << " cpusubtype CPU_SUBTYPE_ARM_V6\n";
2086 break;
2087 case MachO::CPU_SUBTYPE_ARM_V6M:
2088 outs() << " cputype CPU_TYPE_ARM\n";
2089 outs() << " cpusubtype CPU_SUBTYPE_ARM_V6M\n";
2090 break;
2091 case MachO::CPU_SUBTYPE_ARM_V7:
2092 outs() << " cputype CPU_TYPE_ARM\n";
2093 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7\n";
2094 break;
2095 case MachO::CPU_SUBTYPE_ARM_V7EM:
2096 outs() << " cputype CPU_TYPE_ARM\n";
2097 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7EM\n";
2098 break;
2099 case MachO::CPU_SUBTYPE_ARM_V7K:
2100 outs() << " cputype CPU_TYPE_ARM\n";
2101 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7K\n";
2102 break;
2103 case MachO::CPU_SUBTYPE_ARM_V7M:
2104 outs() << " cputype CPU_TYPE_ARM\n";
2105 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7M\n";
2106 break;
2107 case MachO::CPU_SUBTYPE_ARM_V7S:
2108 outs() << " cputype CPU_TYPE_ARM\n";
2109 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7S\n";
2110 break;
2111 default:
2112 printUnknownCPUType(cputype, cpusubtype);
2113 break;
2114 }
2115 break;
2116 case MachO::CPU_TYPE_ARM64:
2117 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
2118 case MachO::CPU_SUBTYPE_ARM64_ALL:
2119 outs() << " cputype CPU_TYPE_ARM64\n";
2120 outs() << " cpusubtype CPU_SUBTYPE_ARM64_ALL\n";
2121 break;
2122 case MachO::CPU_SUBTYPE_ARM64_V8:
2123 outs() << " cputype CPU_TYPE_ARM64\n";
2124 outs() << " cpusubtype CPU_SUBTYPE_ARM64_V8\n";
2125 break;
2126 case MachO::CPU_SUBTYPE_ARM64E:
2127 outs() << " cputype CPU_TYPE_ARM64\n";
2128 outs() << " cpusubtype CPU_SUBTYPE_ARM64E\n";
2129 break;
2130 default:
2131 printUnknownCPUType(cputype, cpusubtype);
2132 break;
2133 }
2134 break;
2135 case MachO::CPU_TYPE_ARM64_32:
2136 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
2137 case MachO::CPU_SUBTYPE_ARM64_32_V8:
2138 outs() << " cputype CPU_TYPE_ARM64_32\n";
2139 outs() << " cpusubtype CPU_SUBTYPE_ARM64_32_V8\n";
2140 break;
2141 default:
2142 printUnknownCPUType(cputype, cpusubtype);
2143 break;
2144 }
2145 break;
2146 default:
2147 printUnknownCPUType(cputype, cpusubtype);
2148 break;
2149 }
2150}
2151
2152static void printMachOUniversalHeaders(const object::MachOUniversalBinary *UB,
2153 bool verbose) {
2154 outs() << "Fat headers\n";
2155 if (verbose) {
2156 if (UB->getMagic() == MachO::FAT_MAGIC)
2157 outs() << "fat_magic FAT_MAGIC\n";
2158 else // UB->getMagic() == MachO::FAT_MAGIC_64
2159 outs() << "fat_magic FAT_MAGIC_64\n";
2160 } else
2161 outs() << "fat_magic " << format("0x%" PRIx32"x", MachO::FAT_MAGIC) << "\n";
2162
2163 uint32_t nfat_arch = UB->getNumberOfObjects();
2164 StringRef Buf = UB->getData();
2165 uint64_t size = Buf.size();
2166 uint64_t big_size = sizeof(struct MachO::fat_header) +
2167 nfat_arch * sizeof(struct MachO::fat_arch);
2168 outs() << "nfat_arch " << UB->getNumberOfObjects();
2169 if (nfat_arch == 0)
2170 outs() << " (malformed, contains zero architecture types)\n";
2171 else if (big_size > size)
2172 outs() << " (malformed, architectures past end of file)\n";
2173 else
2174 outs() << "\n";
2175
2176 for (uint32_t i = 0; i < nfat_arch; ++i) {
2177 MachOUniversalBinary::ObjectForArch OFA(UB, i);
2178 uint32_t cputype = OFA.getCPUType();
2179 uint32_t cpusubtype = OFA.getCPUSubType();
2180 outs() << "architecture ";
2181 for (uint32_t j = 0; i != 0 && j <= i - 1; j++) {
2182 MachOUniversalBinary::ObjectForArch other_OFA(UB, j);
2183 uint32_t other_cputype = other_OFA.getCPUType();
2184 uint32_t other_cpusubtype = other_OFA.getCPUSubType();
2185 if (cputype != 0 && cpusubtype != 0 && cputype == other_cputype &&
2186 (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) ==
2187 (other_cpusubtype & ~MachO::CPU_SUBTYPE_MASK)) {
2188 outs() << "(illegal duplicate architecture) ";
2189 break;
2190 }
2191 }
2192 if (verbose) {
2193 outs() << OFA.getArchFlagName() << "\n";
2194 printCPUType(cputype, cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
2195 } else {
2196 outs() << i << "\n";
2197 outs() << " cputype " << cputype << "\n";
2198 outs() << " cpusubtype " << (cpusubtype & ~MachO::CPU_SUBTYPE_MASK)
2199 << "\n";
2200 }
2201 if (verbose &&
2202 (cpusubtype & MachO::CPU_SUBTYPE_MASK) == MachO::CPU_SUBTYPE_LIB64)
2203 outs() << " capabilities CPU_SUBTYPE_LIB64\n";
2204 else
2205 outs() << " capabilities "
2206 << format("0x%" PRIx32"x",
2207 (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24) << "\n";
2208 outs() << " offset " << OFA.getOffset();
2209 if (OFA.getOffset() > size)
2210 outs() << " (past end of file)";
2211 if (OFA.getOffset() % (1ull << OFA.getAlign()) != 0)
2212 outs() << " (not aligned on it's alignment (2^" << OFA.getAlign() << ")";
2213 outs() << "\n";
2214 outs() << " size " << OFA.getSize();
2215 big_size = OFA.getOffset() + OFA.getSize();
2216 if (big_size > size)
2217 outs() << " (past end of file)";
2218 outs() << "\n";
2219 outs() << " align 2^" << OFA.getAlign() << " (" << (1 << OFA.getAlign())
2220 << ")\n";
2221 }
2222}
2223
2224static void printArchiveChild(StringRef Filename, const Archive::Child &C,
2225 size_t ChildIndex, bool verbose,
2226 bool print_offset,
2227 StringRef ArchitectureName = StringRef()) {
2228 if (print_offset)
2229 outs() << C.getChildOffset() << "\t";
2230 sys::fs::perms Mode =
2231 unwrapOrError(C.getAccessMode(), getFileNameForError(C, ChildIndex),
2232 Filename, ArchitectureName);
2233 if (verbose) {
2234 // FIXME: this first dash, "-", is for (Mode & S_IFMT) == S_IFREG.
2235 // But there is nothing in sys::fs::perms for S_IFMT or S_IFREG.
2236 outs() << "-";
2237 outs() << ((Mode & sys::fs::owner_read) ? "r" : "-");
2238 outs() << ((Mode & sys::fs::owner_write) ? "w" : "-");
2239 outs() << ((Mode & sys::fs::owner_exe) ? "x" : "-");
2240 outs() << ((Mode & sys::fs::group_read) ? "r" : "-");
2241 outs() << ((Mode & sys::fs::group_write) ? "w" : "-");
2242 outs() << ((Mode & sys::fs::group_exe) ? "x" : "-");
2243 outs() << ((Mode & sys::fs::others_read) ? "r" : "-");
2244 outs() << ((Mode & sys::fs::others_write) ? "w" : "-");
2245 outs() << ((Mode & sys::fs::others_exe) ? "x" : "-");
2246 } else {
2247 outs() << format("0%o ", Mode);
2248 }
2249
2250 outs() << format("%3d/%-3d %5" PRId64"l" "d" " ",
2251 unwrapOrError(C.getUID(), getFileNameForError(C, ChildIndex),
2252 Filename, ArchitectureName),
2253 unwrapOrError(C.getGID(), getFileNameForError(C, ChildIndex),
2254 Filename, ArchitectureName),
2255 unwrapOrError(C.getRawSize(),
2256 getFileNameForError(C, ChildIndex), Filename,
2257 ArchitectureName));
2258
2259 StringRef RawLastModified = C.getRawLastModified();
2260 if (verbose) {
2261 unsigned Seconds;
2262 if (RawLastModified.getAsInteger(10, Seconds))
2263 outs() << "(date: \"" << RawLastModified
2264 << "\" contains non-decimal chars) ";
2265 else {
2266 // Since cime(3) returns a 26 character string of the form:
2267 // "Sun Sep 16 01:03:52 1973\n\0"
2268 // just print 24 characters.
2269 time_t t = Seconds;
2270 outs() << format("%.24s ", ctime(&t));
2271 }
2272 } else {
2273 outs() << RawLastModified << " ";
2274 }
2275
2276 if (verbose) {
2277 Expected<StringRef> NameOrErr = C.getName();
2278 if (!NameOrErr) {
2279 consumeError(NameOrErr.takeError());
2280 outs() << unwrapOrError(C.getRawName(),
2281 getFileNameForError(C, ChildIndex), Filename,
2282 ArchitectureName)
2283 << "\n";
2284 } else {
2285 StringRef Name = NameOrErr.get();
2286 outs() << Name << "\n";
2287 }
2288 } else {
2289 outs() << unwrapOrError(C.getRawName(), getFileNameForError(C, ChildIndex),
2290 Filename, ArchitectureName)
2291 << "\n";
2292 }
2293}
2294
2295static void printArchiveHeaders(StringRef Filename, Archive *A, bool verbose,
2296 bool print_offset,
2297 StringRef ArchitectureName = StringRef()) {
2298 Error Err = Error::success();
2299 size_t I = 0;
2300 for (const auto &C : A->children(Err, false))
2301 printArchiveChild(Filename, C, I++, verbose, print_offset,
2302 ArchitectureName);
2303
2304 if (Err)
2305 reportError(std::move(Err), Filename, "", ArchitectureName);
2306}
2307
2308static bool ValidateArchFlags() {
2309 // Check for -arch all and verifiy the -arch flags are valid.
2310 for (unsigned i = 0; i < ArchFlags.size(); ++i) {
2311 if (ArchFlags[i] == "all") {
2312 ArchAll = true;
2313 } else {
2314 if (!MachOObjectFile::isValidArch(ArchFlags[i])) {
2315 WithColor::error(errs(), "llvm-objdump")
2316 << "unknown architecture named '" + ArchFlags[i] +
2317 "'for the -arch option\n";
2318 return false;
2319 }
2320 }
2321 }
2322 return true;
2323}
2324
2325// ParseInputMachO() parses the named Mach-O file in Filename and handles the
2326// -arch flags selecting just those slices as specified by them and also parses
2327// archive files. Then for each individual Mach-O file ProcessMachO() is
2328// called to process the file based on the command line options.
2329void objdump::parseInputMachO(StringRef Filename) {
2330 if (!ValidateArchFlags())
2331 return;
2332
2333 // Attempt to open the binary.
2334 Expected<OwningBinary<Binary>> BinaryOrErr = createBinary(Filename);
2335 if (!BinaryOrErr) {
2336 if (Error E = isNotObjectErrorInvalidFileType(BinaryOrErr.takeError()))
2337 reportError(std::move(E), Filename);
2338 else
2339 outs() << Filename << ": is not an object file\n";
2340 return;
2341 }
2342 Binary &Bin = *BinaryOrErr.get().getBinary();
2343
2344 if (Archive *A = dyn_cast<Archive>(&Bin)) {
2345 outs() << "Archive : " << Filename << "\n";
2346 if (ArchiveHeaders)
2347 printArchiveHeaders(Filename, A, Verbose, ArchiveMemberOffsets);
2348
2349 Error Err = Error::success();
2350 unsigned I = -1;
2351 for (auto &C : A->children(Err)) {
2352 ++I;
2353 Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
2354 if (!ChildOrErr) {
2355 if (Error E = isNotObjectErrorInvalidFileType(ChildOrErr.takeError()))
2356 reportError(std::move(E), getFileNameForError(C, I), Filename);
2357 continue;
2358 }
2359 if (MachOObjectFile *O = dyn_cast<MachOObjectFile>(&*ChildOrErr.get())) {
2360 if (!checkMachOAndArchFlags(O, Filename))
2361 return;
2362 ProcessMachO(Filename, O, O->getFileName());
2363 }
2364 }
2365 if (Err)
2366 reportError(std::move(Err), Filename);
2367 return;
2368 }
2369 if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(&Bin)) {
2370 parseInputMachO(UB);
2371 return;
2372 }
2373 if (ObjectFile *O = dyn_cast<ObjectFile>(&Bin)) {
2374 if (!checkMachOAndArchFlags(O, Filename))
2375 return;
2376 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&*O))
2377 ProcessMachO(Filename, MachOOF);
2378 else
2379 WithColor::error(errs(), "llvm-objdump")
2380 << Filename << "': "
2381 << "object is not a Mach-O file type.\n";
2382 return;
2383 }
2384 llvm_unreachable("Input object can't be invalid at this point")::llvm::llvm_unreachable_internal("Input object can't be invalid at this point"
, "llvm/tools/llvm-objdump/MachODump.cpp", 2384)
;
2385}
2386
2387void objdump::parseInputMachO(MachOUniversalBinary *UB) {
2388 if (!ValidateArchFlags())
2389 return;
2390
2391 auto Filename = UB->getFileName();
2392
2393 if (UniversalHeaders)
2394 printMachOUniversalHeaders(UB, Verbose);
2395
2396 // If we have a list of architecture flags specified dump only those.
2397 if (!ArchAll && !ArchFlags.empty()) {
2398 // Look for a slice in the universal binary that matches each ArchFlag.
2399 bool ArchFound;
2400 for (unsigned i = 0; i < ArchFlags.size(); ++i) {
2401 ArchFound = false;
2402 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
2403 E = UB->end_objects();
2404 I != E; ++I) {
2405 if (ArchFlags[i] == I->getArchFlagName()) {
2406 ArchFound = true;
2407 Expected<std::unique_ptr<ObjectFile>> ObjOrErr =
2408 I->getAsObjectFile();
2409 std::string ArchitectureName;
2410 if (ArchFlags.size() > 1)
2411 ArchitectureName = I->getArchFlagName();
2412 if (ObjOrErr) {
2413 ObjectFile &O = *ObjOrErr.get();
2414 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&O))
2415 ProcessMachO(Filename, MachOOF, "", ArchitectureName);
2416 } else if (Error E = isNotObjectErrorInvalidFileType(
2417 ObjOrErr.takeError())) {
2418 reportError(std::move(E), "", Filename, ArchitectureName);
2419 continue;
2420 } else if (Expected<std::unique_ptr<Archive>> AOrErr =
2421 I->getAsArchive()) {
2422 std::unique_ptr<Archive> &A = *AOrErr;
2423 outs() << "Archive : " << Filename;
2424 if (!ArchitectureName.empty())
2425 outs() << " (architecture " << ArchitectureName << ")";
2426 outs() << "\n";
2427 if (ArchiveHeaders)
2428 printArchiveHeaders(Filename, A.get(), Verbose,
2429 ArchiveMemberOffsets, ArchitectureName);
2430 Error Err = Error::success();
2431 unsigned I = -1;
2432 for (auto &C : A->children(Err)) {
2433 ++I;
2434 Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
2435 if (!ChildOrErr) {
2436 if (Error E =
2437 isNotObjectErrorInvalidFileType(ChildOrErr.takeError()))
2438 reportError(std::move(E), getFileNameForError(C, I), Filename,
2439 ArchitectureName);
2440 continue;
2441 }
2442 if (MachOObjectFile *O =
2443 dyn_cast<MachOObjectFile>(&*ChildOrErr.get()))
2444 ProcessMachO(Filename, O, O->getFileName(), ArchitectureName);
2445 }
2446 if (Err)
2447 reportError(std::move(Err), Filename);
2448 } else {
2449 consumeError(AOrErr.takeError());
2450 reportError(Filename,
2451 "Mach-O universal file for architecture " +
2452 StringRef(I->getArchFlagName()) +
2453 " is not a Mach-O file or an archive file");
2454 }
2455 }
2456 }
2457 if (!ArchFound) {
2458 WithColor::error(errs(), "llvm-objdump")
2459 << "file: " + Filename + " does not contain "
2460 << "architecture: " + ArchFlags[i] + "\n";
2461 return;
2462 }
2463 }
2464 return;
2465 }
2466 // No architecture flags were specified so if this contains a slice that
2467 // matches the host architecture dump only that.
2468 if (!ArchAll) {
2469 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
2470 E = UB->end_objects();
2471 I != E; ++I) {
2472 if (MachOObjectFile::getHostArch().getArchName() ==
2473 I->getArchFlagName()) {
2474 Expected<std::unique_ptr<ObjectFile>> ObjOrErr = I->getAsObjectFile();
2475 std::string ArchiveName;
2476 ArchiveName.clear();
2477 if (ObjOrErr) {
2478 ObjectFile &O = *ObjOrErr.get();
2479 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&O))
2480 ProcessMachO(Filename, MachOOF);
2481 } else if (Error E =
2482 isNotObjectErrorInvalidFileType(ObjOrErr.takeError())) {
2483 reportError(std::move(E), Filename);
2484 } else if (Expected<std::unique_ptr<Archive>> AOrErr =
2485 I->getAsArchive()) {
2486 std::unique_ptr<Archive> &A = *AOrErr;
2487 outs() << "Archive : " << Filename << "\n";
2488 if (ArchiveHeaders)
2489 printArchiveHeaders(Filename, A.get(), Verbose,
2490 ArchiveMemberOffsets);
2491 Error Err = Error::success();
2492 unsigned I = -1;
2493 for (auto &C : A->children(Err)) {
2494 ++I;
2495 Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
2496 if (!ChildOrErr) {
2497 if (Error E =
2498 isNotObjectErrorInvalidFileType(ChildOrErr.takeError()))
2499 reportError(std::move(E), getFileNameForError(C, I), Filename);
2500 continue;
2501 }
2502 if (MachOObjectFile *O =
2503 dyn_cast<MachOObjectFile>(&*ChildOrErr.get()))
2504 ProcessMachO(Filename, O, O->getFileName());
2505 }
2506 if (Err)
2507 reportError(std::move(Err), Filename);
2508 } else {
2509 consumeError(AOrErr.takeError());
2510 reportError(Filename, "Mach-O universal file for architecture " +
2511 StringRef(I->getArchFlagName()) +
2512 " is not a Mach-O file or an archive file");
2513 }
2514 return;
2515 }
2516 }
2517 }
2518 // Either all architectures have been specified or none have been specified
2519 // and this does not contain the host architecture so dump all the slices.
2520 bool moreThanOneArch = UB->getNumberOfObjects() > 1;
2521 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
2522 E = UB->end_objects();
2523 I != E; ++I) {
2524 Expected<std::unique_ptr<ObjectFile>> ObjOrErr = I->getAsObjectFile();
2525 std::string ArchitectureName;
2526 if (moreThanOneArch)
2527 ArchitectureName = I->getArchFlagName();
2528 if (ObjOrErr) {
2529 ObjectFile &Obj = *ObjOrErr.get();
2530 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&Obj))
2531 ProcessMachO(Filename, MachOOF, "", ArchitectureName);
2532 } else if (Error E =
2533 isNotObjectErrorInvalidFileType(ObjOrErr.takeError())) {
2534 reportError(std::move(E), Filename, "", ArchitectureName);
2535 } else if (Expected<std::unique_ptr<Archive>> AOrErr = I->getAsArchive()) {
2536 std::unique_ptr<Archive> &A = *AOrErr;
2537 outs() << "Archive : " << Filename;
2538 if (!ArchitectureName.empty())
2539 outs() << " (architecture " << ArchitectureName << ")";
2540 outs() << "\n";
2541 if (ArchiveHeaders)
2542 printArchiveHeaders(Filename, A.get(), Verbose, ArchiveMemberOffsets,
2543 ArchitectureName);
2544 Error Err = Error::success();
2545 unsigned I = -1;
2546 for (auto &C : A->children(Err)) {
2547 ++I;
2548 Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
2549 if (!ChildOrErr) {
2550 if (Error E = isNotObjectErrorInvalidFileType(ChildOrErr.takeError()))
2551 reportError(std::move(E), getFileNameForError(C, I), Filename,
2552 ArchitectureName);
2553 continue;
2554 }
2555 if (MachOObjectFile *O =
2556 dyn_cast<MachOObjectFile>(&*ChildOrErr.get())) {
2557 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(O))
2558 ProcessMachO(Filename, MachOOF, MachOOF->getFileName(),
2559 ArchitectureName);
2560 }
2561 }
2562 if (Err)
2563 reportError(std::move(Err), Filename);
2564 } else {
2565 consumeError(AOrErr.takeError());
2566 reportError(Filename, "Mach-O universal file for architecture " +
2567 StringRef(I->getArchFlagName()) +
2568 " is not a Mach-O file or an archive file");
2569 }
2570 }
2571}
2572
2573namespace {
2574// The block of info used by the Symbolizer call backs.
2575struct DisassembleInfo {
2576 DisassembleInfo(MachOObjectFile *O, SymbolAddressMap *AddrMap,
2577 std::vector<SectionRef> *Sections, bool verbose)
2578 : verbose(verbose), O(O), AddrMap(AddrMap), Sections(Sections) {}
2579 bool verbose;
2580 MachOObjectFile *O;
2581 SectionRef S;
2582 SymbolAddressMap *AddrMap;
2583 std::vector<SectionRef> *Sections;
2584 const char *class_name = nullptr;
2585 const char *selector_name = nullptr;
2586 std::unique_ptr<char[]> method = nullptr;
2587 char *demangled_name = nullptr;
2588 uint64_t adrp_addr = 0;
2589 uint32_t adrp_inst = 0;
2590 std::unique_ptr<SymbolAddressMap> bindtable;
2591 uint32_t depth = 0;
2592};
2593} // namespace
2594
2595// SymbolizerGetOpInfo() is the operand information call back function.
2596// This is called to get the symbolic information for operand(s) of an
2597// instruction when it is being done. This routine does this from
2598// the relocation information, symbol table, etc. That block of information
2599// is a pointer to the struct DisassembleInfo that was passed when the
2600// disassembler context was created and passed to back to here when
2601// called back by the disassembler for instruction operands that could have
2602// relocation information. The address of the instruction containing operand is
2603// at the Pc parameter. The immediate value the operand has is passed in
2604// op_info->Value and is at Offset past the start of the instruction and has a
2605// byte Size of 1, 2 or 4. The symbolc information is returned in TagBuf is the
2606// LLVMOpInfo1 struct defined in the header "llvm-c/Disassembler.h" as symbol
2607// names and addends of the symbolic expression to add for the operand. The
2608// value of TagType is currently 1 (for the LLVMOpInfo1 struct). If symbolic
2609// information is returned then this function returns 1 else it returns 0.
2610static int SymbolizerGetOpInfo(void *DisInfo, uint64_t Pc, uint64_t Offset,
2611 uint64_t Size, int TagType, void *TagBuf) {
2612 struct DisassembleInfo *info = (struct DisassembleInfo *)DisInfo;
2613 struct LLVMOpInfo1 *op_info = (struct LLVMOpInfo1 *)TagBuf;
2614 uint64_t value = op_info->Value;
2615
2616 // Make sure all fields returned are zero if we don't set them.
2617 memset((void *)op_info, '\0', sizeof(struct LLVMOpInfo1));
2618 op_info->Value = value;
2619
2620 // If the TagType is not the value 1 which it code knows about or if no
2621 // verbose symbolic information is wanted then just return 0, indicating no
2622 // information is being returned.
2623 if (TagType != 1 || !info->verbose)
1
Assuming 'TagType' is equal to 1
2
Assuming field 'verbose' is true
3
Taking false branch
2624 return 0;
2625
2626 unsigned int Arch = info->O->getArch();
2627 if (Arch == Triple::x86) {
4
Assuming 'Arch' is not equal to x86
5
Taking false branch
2628 if (Size != 1 && Size != 2 && Size != 4 && Size != 0)
2629 return 0;
2630 if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
2631 // TODO:
2632 // Search the external relocation entries of a fully linked image
2633 // (if any) for an entry that matches this segment offset.
2634 // uint32_t seg_offset = (Pc + Offset);
2635 return 0;
2636 }
2637 // In MH_OBJECT filetypes search the section's relocation entries (if any)
2638 // for an entry for this section offset.
2639 uint32_t sect_addr = info->S.getAddress();
2640 uint32_t sect_offset = (Pc + Offset) - sect_addr;
2641 bool reloc_found = false;
2642 DataRefImpl Rel;
2643 MachO::any_relocation_info RE;
2644 bool isExtern = false;
2645 SymbolRef Symbol;
2646 bool r_scattered = false;
2647 uint32_t r_value, pair_r_value, r_type;
2648 for (const RelocationRef &Reloc : info->S.relocations()) {
2649 uint64_t RelocOffset = Reloc.getOffset();
2650 if (RelocOffset == sect_offset) {
2651 Rel = Reloc.getRawDataRefImpl();
2652 RE = info->O->getRelocation(Rel);
2653 r_type = info->O->getAnyRelocationType(RE);
2654 r_scattered = info->O->isRelocationScattered(RE);
2655 if (r_scattered) {
2656 r_value = info->O->getScatteredRelocationValue(RE);
2657 if (r_type == MachO::GENERIC_RELOC_SECTDIFF ||
2658 r_type == MachO::GENERIC_RELOC_LOCAL_SECTDIFF) {
2659 DataRefImpl RelNext = Rel;
2660 info->O->moveRelocationNext(RelNext);
2661 MachO::any_relocation_info RENext;
2662 RENext = info->O->getRelocation(RelNext);
2663 if (info->O->isRelocationScattered(RENext))
2664 pair_r_value = info->O->getScatteredRelocationValue(RENext);
2665 else
2666 return 0;
2667 }
2668 } else {
2669 isExtern = info->O->getPlainRelocationExternal(RE);
2670 if (isExtern) {
2671 symbol_iterator RelocSym = Reloc.getSymbol();
2672 Symbol = *RelocSym;
2673 }
2674 }
2675 reloc_found = true;
2676 break;
2677 }
2678 }
2679 if (reloc_found && isExtern) {
2680 op_info->AddSymbol.Present = 1;
2681 op_info->AddSymbol.Name =
2682 unwrapOrError(Symbol.getName(), info->O->getFileName()).data();
2683 // For i386 extern relocation entries the value in the instruction is
2684 // the offset from the symbol, and value is already set in op_info->Value.
2685 return 1;
2686 }
2687 if (reloc_found && (r_type == MachO::GENERIC_RELOC_SECTDIFF ||
2688 r_type == MachO::GENERIC_RELOC_LOCAL_SECTDIFF)) {
2689 const char *add = GuessSymbolName(r_value, info->AddrMap);
2690 const char *sub = GuessSymbolName(pair_r_value, info->AddrMap);
2691 uint32_t offset = value - (r_value - pair_r_value);
2692 op_info->AddSymbol.Present = 1;
2693 if (add != nullptr)
2694 op_info->AddSymbol.Name = add;
2695 else
2696 op_info->AddSymbol.Value = r_value;
2697 op_info->SubtractSymbol.Present = 1;
2698 if (sub != nullptr)
2699 op_info->SubtractSymbol.Name = sub;
2700 else
2701 op_info->SubtractSymbol.Value = pair_r_value;
2702 op_info->Value = offset;
2703 return 1;
2704 }
2705 return 0;
2706 }
2707 if (Arch == Triple::x86_64) {
6
Assuming 'Arch' is not equal to x86_64
7
Taking false branch
2708 if (Size != 1 && Size != 2 && Size != 4 && Size != 0)
2709 return 0;
2710 // For non MH_OBJECT types, like MH_KEXT_BUNDLE, Search the external
2711 // relocation entries of a linked image (if any) for an entry that matches
2712 // this segment offset.
2713 if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
2714 uint64_t seg_offset = Pc + Offset;
2715 bool reloc_found = false;
2716 DataRefImpl Rel;
2717 MachO::any_relocation_info RE;
2718 bool isExtern = false;
2719 SymbolRef Symbol;
2720 for (const RelocationRef &Reloc : info->O->external_relocations()) {
2721 uint64_t RelocOffset = Reloc.getOffset();
2722 if (RelocOffset == seg_offset) {
2723 Rel = Reloc.getRawDataRefImpl();
2724 RE = info->O->getRelocation(Rel);
2725 // external relocation entries should always be external.
2726 isExtern = info->O->getPlainRelocationExternal(RE);
2727 if (isExtern) {
2728 symbol_iterator RelocSym = Reloc.getSymbol();
2729 Symbol = *RelocSym;
2730 }
2731 reloc_found = true;
2732 break;
2733 }
2734 }
2735 if (reloc_found && isExtern) {
2736 // The Value passed in will be adjusted by the Pc if the instruction
2737 // adds the Pc. But for x86_64 external relocation entries the Value
2738 // is the offset from the external symbol.
2739 if (info->O->getAnyRelocationPCRel(RE))
2740 op_info->Value -= Pc + Offset + Size;
2741 const char *name =
2742 unwrapOrError(Symbol.getName(), info->O->getFileName()).data();
2743 op_info->AddSymbol.Present = 1;
2744 op_info->AddSymbol.Name = name;
2745 return 1;
2746 }
2747 return 0;
2748 }
2749 // In MH_OBJECT filetypes search the section's relocation entries (if any)
2750 // for an entry for this section offset.
2751 uint64_t sect_addr = info->S.getAddress();
2752 uint64_t sect_offset = (Pc + Offset) - sect_addr;
2753 bool reloc_found = false;
2754 DataRefImpl Rel;
2755 MachO::any_relocation_info RE;
2756 bool isExtern = false;
2757 SymbolRef Symbol;
2758 for (const RelocationRef &Reloc : info->S.relocations()) {
2759 uint64_t RelocOffset = Reloc.getOffset();
2760 if (RelocOffset == sect_offset) {
2761 Rel = Reloc.getRawDataRefImpl();
2762 RE = info->O->getRelocation(Rel);
2763 // NOTE: Scattered relocations don't exist on x86_64.
2764 isExtern = info->O->getPlainRelocationExternal(RE);
2765 if (isExtern) {
2766 symbol_iterator RelocSym = Reloc.getSymbol();
2767 Symbol = *RelocSym;
2768 }
2769 reloc_found = true;
2770 break;
2771 }
2772 }
2773 if (reloc_found && isExtern) {
2774 // The Value passed in will be adjusted by the Pc if the instruction
2775 // adds the Pc. But for x86_64 external relocation entries the Value
2776 // is the offset from the external symbol.
2777 if (info->O->getAnyRelocationPCRel(RE))
2778 op_info->Value -= Pc + Offset + Size;
2779 const char *name =
2780 unwrapOrError(Symbol.getName(), info->O->getFileName()).data();
2781 unsigned Type = info->O->getAnyRelocationType(RE);
2782 if (Type == MachO::X86_64_RELOC_SUBTRACTOR) {
2783 DataRefImpl RelNext = Rel;
2784 info->O->moveRelocationNext(RelNext);
2785 MachO::any_relocation_info RENext = info->O->getRelocation(RelNext);
2786 unsigned TypeNext = info->O->getAnyRelocationType(RENext);
2787 bool isExternNext = info->O->getPlainRelocationExternal(RENext);
2788 unsigned SymbolNum = info->O->getPlainRelocationSymbolNum(RENext);
2789 if (TypeNext == MachO::X86_64_RELOC_UNSIGNED && isExternNext) {
2790 op_info->SubtractSymbol.Present = 1;
2791 op_info->SubtractSymbol.Name = name;
2792 symbol_iterator RelocSymNext = info->O->getSymbolByIndex(SymbolNum);
2793 Symbol = *RelocSymNext;
2794 name = unwrapOrError(Symbol.getName(), info->O->getFileName()).data();
2795 }
2796 }
2797 // TODO: add the VariantKinds to op_info->VariantKind for relocation types
2798 // like: X86_64_RELOC_TLV, X86_64_RELOC_GOT_LOAD and X86_64_RELOC_GOT.
2799 op_info->AddSymbol.Present = 1;
2800 op_info->AddSymbol.Name = name;
2801 return 1;
2802 }
2803 return 0;
2804 }
2805 if (Arch == Triple::arm) {
8
Assuming 'Arch' is equal to arm
2806 if (Offset != 0 || (Size != 4 && Size != 2))
9
Assuming 'Offset' is equal to 0
10
Assuming 'Size' is equal to 4
2807 return 0;
2808 if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
11
Assuming field 'filetype' is equal to MH_OBJECT
12
Taking false branch
2809 // TODO:
2810 // Search the external relocation entries of a fully linked image
2811 // (if any) for an entry that matches this segment offset.
2812 // uint32_t seg_offset = (Pc + Offset);
2813 return 0;
2814 }
2815 // In MH_OBJECT filetypes search the section's relocation entries (if any)
2816 // for an entry for this section offset.
2817 uint32_t sect_addr = info->S.getAddress();
2818 uint32_t sect_offset = (Pc + Offset) - sect_addr;
2819 DataRefImpl Rel;
2820 MachO::any_relocation_info RE;
2821 bool isExtern = false;
2822 SymbolRef Symbol;
2823 bool r_scattered = false;
2824 uint32_t r_value, pair_r_value, r_type, r_length, other_half;
13
'pair_r_value' declared without an initial value
2825 auto Reloc =
2826 find_if(info->S.relocations(), [&](const RelocationRef &Reloc) {
2827 uint64_t RelocOffset = Reloc.getOffset();
2828 return RelocOffset == sect_offset;
2829 });
2830
2831 if (Reloc == info->S.relocations().end())
14
Assuming the condition is false
15
Taking false branch
2832 return 0;
2833
2834 Rel = Reloc->getRawDataRefImpl();
2835 RE = info->O->getRelocation(Rel);
2836 r_length = info->O->getAnyRelocationLength(RE);
2837 r_scattered = info->O->isRelocationScattered(RE);
2838 if (r_scattered) {
16
Assuming 'r_scattered' is true
17
Taking true branch
2839 r_value = info->O->getScatteredRelocationValue(RE);
2840 r_type = info->O->getScatteredRelocationType(RE);
2841 } else {
2842 r_type = info->O->getAnyRelocationType(RE);
2843 isExtern = info->O->getPlainRelocationExternal(RE);
2844 if (isExtern) {
2845 symbol_iterator RelocSym = Reloc->getSymbol();
2846 Symbol = *RelocSym;
2847 }
2848 }
2849 if (r_type == MachO::ARM_RELOC_HALF ||
18
Assuming 'r_type' is not equal to ARM_RELOC_HALF
22
Taking true branch
2850 r_type == MachO::ARM_RELOC_SECTDIFF ||
19
Assuming 'r_type' is not equal to ARM_RELOC_SECTDIFF
2851 r_type == MachO::ARM_RELOC_LOCAL_SECTDIFF ||
20
Assuming 'r_type' is not equal to ARM_RELOC_LOCAL_SECTDIFF
2852 r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
21
Assuming 'r_type' is equal to ARM_RELOC_HALF_SECTDIFF
2853 DataRefImpl RelNext = Rel;
2854 info->O->moveRelocationNext(RelNext);
2855 MachO::any_relocation_info RENext;
2856 RENext = info->O->getRelocation(RelNext);
2857 other_half = info->O->getAnyRelocationAddress(RENext) & 0xffff;
2858 if (info->O->isRelocationScattered(RENext))
23
Assuming the condition is false
24
Taking false branch
2859 pair_r_value = info->O->getScatteredRelocationValue(RENext);
2860 }
2861
2862 if (isExtern
24.1
'isExtern' is false
) {
2863 const char *name =
2864 unwrapOrError(Symbol.getName(), info->O->getFileName()).data();
2865 op_info->AddSymbol.Present = 1;
2866 op_info->AddSymbol.Name = name;
2867 switch (r_type) {
2868 case MachO::ARM_RELOC_HALF:
2869 if ((r_length & 0x1) == 1) {
2870 op_info->Value = value << 16 | other_half;
2871 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI161;
2872 } else {
2873 op_info->Value = other_half << 16 | value;
2874 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO162;
2875 }
2876 break;
2877 default:
2878 break;
2879 }
2880 return 1;
2881 }
2882 // If we have a branch that is not an external relocation entry then
2883 // return 0 so the code in tryAddingSymbolicOperand() can use the
2884 // SymbolLookUp call back with the branch target address to look up the
2885 // symbol and possibility add an annotation for a symbol stub.
2886 if (isExtern
24.2
'isExtern' is equal to 0
== 0 && (r_type
24.3
'r_type' is not equal to ARM_RELOC_BR24
== MachO::ARM_RELOC_BR24 ||
25
Taking false branch
2887 r_type
24.4
'r_type' is not equal to ARM_THUMB_RELOC_BR22
== MachO::ARM_THUMB_RELOC_BR22))
2888 return 0;
2889
2890 uint32_t offset = 0;
2891 if (r_type
25.1
'r_type' is not equal to ARM_RELOC_HALF
== MachO::ARM_RELOC_HALF ||
26
Taking true branch
2892 r_type
25.2
'r_type' is equal to ARM_RELOC_HALF_SECTDIFF
== MachO::ARM_RELOC_HALF_SECTDIFF) {
2893 if ((r_length & 0x1) == 1)
27
Assuming the condition is true
28
Taking true branch
2894 value = value << 16 | other_half;
2895 else
2896 value = other_half << 16 | value;
2897 }
2898 if (r_scattered
28.1
'r_scattered' is true
&& (r_type
28.2
'r_type' is not equal to ARM_RELOC_HALF
!= MachO::ARM_RELOC_HALF &&
29
Taking false branch
2899 r_type
28.3
'r_type' is equal to ARM_RELOC_HALF_SECTDIFF
!= MachO::ARM_RELOC_HALF_SECTDIFF)) {
2900 offset = value - r_value;
2901 value = r_value;
2902 }
2903
2904 if (r_type
29.1
'r_type' is equal to ARM_RELOC_HALF_SECTDIFF
== MachO::ARM_RELOC_HALF_SECTDIFF) {
30
Taking true branch
2905 if ((r_length & 0x1) == 1)
31
Taking true branch
2906 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI161;
2907 else
2908 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO162;
2909 const char *add = GuessSymbolName(r_value, info->AddrMap);
2910 const char *sub = GuessSymbolName(pair_r_value, info->AddrMap);
32
1st function call argument is an uninitialized value
2911 int32_t offset = value - (r_value - pair_r_value);
2912 op_info->AddSymbol.Present = 1;
2913 if (add != nullptr)
2914 op_info->AddSymbol.Name = add;
2915 else
2916 op_info->AddSymbol.Value = r_value;
2917 op_info->SubtractSymbol.Present = 1;
2918 if (sub != nullptr)
2919 op_info->SubtractSymbol.Name = sub;
2920 else
2921 op_info->SubtractSymbol.Value = pair_r_value;
2922 op_info->Value = offset;
2923 return 1;
2924 }
2925
2926 op_info->AddSymbol.Present = 1;
2927 op_info->Value = offset;
2928 if (r_type == MachO::ARM_RELOC_HALF) {
2929 if ((r_length & 0x1) == 1)
2930 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI161;
2931 else
2932 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO162;
2933 }
2934 const char *add = GuessSymbolName(value, info->AddrMap);
2935 if (add != nullptr) {
2936 op_info->AddSymbol.Name = add;
2937 return 1;
2938 }
2939 op_info->AddSymbol.Value = value;
2940 return 1;
2941 }
2942 if (Arch == Triple::aarch64) {
2943 if (Offset != 0 || Size != 4)
2944 return 0;
2945 if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
2946 // TODO:
2947 // Search the external relocation entries of a fully linked image
2948 // (if any) for an entry that matches this segment offset.
2949 // uint64_t seg_offset = (Pc + Offset);
2950 return 0;
2951 }
2952 // In MH_OBJECT filetypes search the section's relocation entries (if any)
2953 // for an entry for this section offset.
2954 uint64_t sect_addr = info->S.getAddress();
2955 uint64_t sect_offset = (Pc + Offset) - sect_addr;
2956 auto Reloc =
2957 find_if(info->S.relocations(), [&](const RelocationRef &Reloc) {
2958 uint64_t RelocOffset = Reloc.getOffset();
2959 return RelocOffset == sect_offset;
2960 });
2961
2962 if (Reloc == info->S.relocations().end())
2963 return 0;
2964
2965 DataRefImpl Rel = Reloc->getRawDataRefImpl();
2966 MachO::any_relocation_info RE = info->O->getRelocation(Rel);
2967 uint32_t r_type = info->O->getAnyRelocationType(RE);
2968 if (r_type == MachO::ARM64_RELOC_ADDEND) {
2969 DataRefImpl RelNext = Rel;
2970 info->O->moveRelocationNext(RelNext);
2971 MachO::any_relocation_info RENext = info->O->getRelocation(RelNext);
2972 if (value == 0) {
2973 value = info->O->getPlainRelocationSymbolNum(RENext);
2974 op_info->Value = value;
2975 }
2976 }
2977 // NOTE: Scattered relocations don't exist on arm64.
2978 if (!info->O->getPlainRelocationExternal(RE))
2979 return 0;
2980 const char *name =
2981 unwrapOrError(Reloc->getSymbol()->getName(), info->O->getFileName())
2982 .data();
2983 op_info->AddSymbol.Present = 1;
2984 op_info->AddSymbol.Name = name;
2985
2986 switch (r_type) {
2987 case MachO::ARM64_RELOC_PAGE21:
2988 /* @page */
2989 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_PAGE1;
2990 break;
2991 case MachO::ARM64_RELOC_PAGEOFF12:
2992 /* @pageoff */
2993 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_PAGEOFF2;
2994 break;
2995 case MachO::ARM64_RELOC_GOT_LOAD_PAGE21:
2996 /* @gotpage */
2997 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_GOTPAGE3;
2998 break;
2999 case MachO::ARM64_RELOC_GOT_LOAD_PAGEOFF12:
3000 /* @gotpageoff */
3001 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_GOTPAGEOFF4;
3002 break;
3003 case MachO::ARM64_RELOC_TLVP_LOAD_PAGE21:
3004 /* @tvlppage is not implemented in llvm-mc */
3005 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_TLVP5;
3006 break;
3007 case MachO::ARM64_RELOC_TLVP_LOAD_PAGEOFF12:
3008 /* @tvlppageoff is not implemented in llvm-mc */
3009 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_TLVOFF6;
3010 break;
3011 default:
3012 case MachO::ARM64_RELOC_BRANCH26:
3013 op_info->VariantKind = LLVMDisassembler_VariantKind_None0;
3014 break;
3015 }
3016 return 1;
3017 }
3018 return 0;
3019}
3020
3021// GuessCstringPointer is passed the address of what might be a pointer to a
3022// literal string in a cstring section. If that address is in a cstring section
3023// it returns a pointer to that string. Else it returns nullptr.
3024static const char *GuessCstringPointer(uint64_t ReferenceValue,
3025 struct DisassembleInfo *info) {
3026 for (const auto &Load : info->O->load_commands()) {
3027 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
3028 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
3029 for (unsigned J = 0; J < Seg.nsects; ++J) {
3030 MachO::section_64 Sec = info->O->getSection64(Load, J);
3031 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
3032 if (section_type == MachO::S_CSTRING_LITERALS &&
3033 ReferenceValue >= Sec.addr &&
3034 ReferenceValue < Sec.addr + Sec.size) {
3035 uint64_t sect_offset = ReferenceValue - Sec.addr;
3036 uint64_t object_offset = Sec.offset + sect_offset;
3037 StringRef MachOContents = info->O->getData();
3038 uint64_t object_size = MachOContents.size();
3039 const char *object_addr = (const char *)MachOContents.data();
3040 if (object_offset < object_size) {
3041 const char *name = object_addr + object_offset;
3042 return name;
3043 } else {
3044 return nullptr;
3045 }
3046 }
3047 }
3048 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
3049 MachO::segment_command Seg = info->O->getSegmentLoadCommand(Load);
3050 for (unsigned J = 0; J < Seg.nsects; ++J) {
3051 MachO::section Sec = info->O->getSection(Load, J);
3052 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
3053 if (section_type == MachO::S_CSTRING_LITERALS &&
3054 ReferenceValue >= Sec.addr &&
3055 ReferenceValue < Sec.addr + Sec.size) {
3056 uint64_t sect_offset = ReferenceValue - Sec.addr;
3057 uint64_t object_offset = Sec.offset + sect_offset;
3058 StringRef MachOContents = info->O->getData();
3059 uint64_t object_size = MachOContents.size();
3060 const char *object_addr = (const char *)MachOContents.data();
3061 if (object_offset < object_size) {
3062 const char *name = object_addr + object_offset;
3063 return name;
3064 } else {
3065 return nullptr;
3066 }
3067 }
3068 }
3069 }
3070 }
3071 return nullptr;
3072}
3073
3074// GuessIndirectSymbol returns the name of the indirect symbol for the
3075// ReferenceValue passed in or nullptr. This is used when ReferenceValue maybe
3076// an address of a symbol stub or a lazy or non-lazy pointer to associate the
3077// symbol name being referenced by the stub or pointer.
3078static const char *GuessIndirectSymbol(uint64_t ReferenceValue,
3079 struct DisassembleInfo *info) {
3080 MachO::dysymtab_command Dysymtab = info->O->getDysymtabLoadCommand();
3081 MachO::symtab_command Symtab = info->O->getSymtabLoadCommand();
3082 for (const auto &Load : info->O->load_commands()) {
3083 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
3084 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
3085 for (unsigned J = 0; J < Seg.nsects; ++J) {
3086 MachO::section_64 Sec = info->O->getSection64(Load, J);
3087 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
3088 if ((section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
3089 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
3090 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
3091 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
3092 section_type == MachO::S_SYMBOL_STUBS) &&
3093 ReferenceValue >= Sec.addr &&
3094 ReferenceValue < Sec.addr + Sec.size) {
3095 uint32_t stride;
3096 if (section_type == MachO::S_SYMBOL_STUBS)
3097 stride = Sec.reserved2;
3098 else
3099 stride = 8;
3100 if (stride == 0)
3101 return nullptr;
3102 uint32_t index = Sec.reserved1 + (ReferenceValue - Sec.addr) / stride;
3103 if (index < Dysymtab.nindirectsyms) {
3104 uint32_t indirect_symbol =
3105 info->O->getIndirectSymbolTableEntry(Dysymtab, index);
3106 if (indirect_symbol < Symtab.nsyms) {
3107 symbol_iterator Sym = info->O->getSymbolByIndex(indirect_symbol);
3108 return unwrapOrError(Sym->getName(), info->O->getFileName())
3109 .data();
3110 }
3111 }
3112 }
3113 }
3114 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
3115 MachO::segment_command Seg = info->O->getSegmentLoadCommand(Load);
3116 for (unsigned J = 0; J < Seg.nsects; ++J) {
3117 MachO::section Sec = info->O->getSection(Load, J);
3118 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
3119 if ((section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
3120 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
3121 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
3122 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
3123 section_type == MachO::S_SYMBOL_STUBS) &&
3124 ReferenceValue >= Sec.addr &&
3125 ReferenceValue < Sec.addr + Sec.size) {
3126 uint32_t stride;
3127 if (section_type == MachO::S_SYMBOL_STUBS)
3128 stride = Sec.reserved2;
3129 else
3130 stride = 4;
3131 if (stride == 0)
3132 return nullptr;
3133 uint32_t index = Sec.reserved1 + (ReferenceValue - Sec.addr) / stride;
3134 if (index < Dysymtab.nindirectsyms) {
3135 uint32_t indirect_symbol =
3136 info->O->getIndirectSymbolTableEntry(Dysymtab, index);
3137 if (indirect_symbol < Symtab.nsyms) {
3138 symbol_iterator Sym = info->O->getSymbolByIndex(indirect_symbol);
3139 return unwrapOrError(Sym->getName(), info->O->getFileName())
3140 .data();
3141 }
3142 }
3143 }
3144 }
3145 }
3146 }
3147 return nullptr;
3148}
3149
3150// method_reference() is called passing it the ReferenceName that might be
3151// a reference it to an Objective-C method call. If so then it allocates and
3152// assembles a method call string with the values last seen and saved in
3153// the DisassembleInfo's class_name and selector_name fields. This is saved
3154// into the method field of the info and any previous string is free'ed.
3155// Then the class_name field in the info is set to nullptr. The method call
3156// string is set into ReferenceName and ReferenceType is set to
3157// LLVMDisassembler_ReferenceType_Out_Objc_Message. If this not a method call
3158// then both ReferenceType and ReferenceName are left unchanged.
3159static void method_reference(struct DisassembleInfo *info,
3160 uint64_t *ReferenceType,
3161 const char **ReferenceName) {
3162 unsigned int Arch = info->O->getArch();
3163 if (*ReferenceName != nullptr) {
3164 if (strcmp(*ReferenceName, "_objc_msgSend") == 0) {
3165 if (info->selector_name != nullptr) {
3166 if (info->class_name != nullptr) {
3167 info->method = std::make_unique<char[]>(
3168 5 + strlen(info->class_name) + strlen(info->selector_name));
3169 char *method = info->method.get();
3170 if (method != nullptr) {
3171 strcpy(method, "+[");
3172 strcat(method, info->class_name);
3173 strcat(method, " ");
3174 strcat(method, info->selector_name);
3175 strcat(method, "]");
3176 *ReferenceName = method;
3177 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message5;
3178 }
3179 } else {
3180 info->method =
3181 std::make_unique<char[]>(9 + strlen(info->selector_name));
3182 char *method = info->method.get();
3183 if (method != nullptr) {
3184 if (Arch == Triple::x86_64)
3185 strcpy(method, "-[%rdi ");
3186 else if (Arch == Triple::aarch64)
3187 strcpy(method, "-[x0 ");
3188 else
3189 strcpy(method, "-[r? ");
3190 strcat(method, info->selector_name);
3191 strcat(method, "]");
3192 *ReferenceName = method;
3193 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message5;
3194 }
3195 }
3196 info->class_name = nullptr;
3197 }
3198 } else if (strcmp(*ReferenceName, "_objc_msgSendSuper2") == 0) {
3199 if (info->selector_name != nullptr) {
3200 info->method =
3201 std::make_unique<char[]>(17 + strlen(info->selector_name));
3202 char *method = info->method.get();
3203 if (method != nullptr) {
3204 if (Arch == Triple::x86_64)
3205 strcpy(method, "-[[%rdi super] ");
3206 else if (Arch == Triple::aarch64)
3207 strcpy(method, "-[[x0 super] ");
3208 else
3209 strcpy(method, "-[[r? super] ");
3210 strcat(method, info->selector_name);
3211 strcat(method, "]");
3212 *ReferenceName = method;
3213 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message5;
3214 }
3215 info->class_name = nullptr;
3216 }
3217 }
3218 }
3219}
3220
3221// GuessPointerPointer() is passed the address of what might be a pointer to
3222// a reference to an Objective-C class, selector, message ref or cfstring.
3223// If so the value of the pointer is returned and one of the booleans are set
3224// to true. If not zero is returned and all the booleans are set to false.
3225static uint64_t GuessPointerPointer(uint64_t ReferenceValue,
3226 struct DisassembleInfo *info,
3227 bool &classref, bool &selref, bool &msgref,
3228 bool &cfstring) {
3229 classref = false;
3230 selref = false;
3231 msgref = false;
3232 cfstring = false;
3233 for (const auto &Load : info->O->load_commands()) {
3234 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
3235 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
3236 for (unsigned J = 0; J < Seg.nsects; ++J) {
3237 MachO::section_64 Sec = info->O->getSection64(Load, J);
3238 if ((strncmp(Sec.sectname, "__objc_selrefs", 16) == 0 ||
3239 strncmp(Sec.sectname, "__objc_classrefs", 16) == 0 ||
3240 strncmp(Sec.sectname, "__objc_superrefs", 16) == 0 ||
3241 strncmp(Sec.sectname, "__objc_msgrefs", 16) == 0 ||
3242 strncmp(Sec.sectname, "__cfstring", 16) == 0) &&
3243 ReferenceValue >= Sec.addr &&
3244 ReferenceValue < Sec.addr + Sec.size) {
3245 uint64_t sect_offset = ReferenceValue - Sec.addr;
3246 uint64_t object_offset = Sec.offset + sect_offset;
3247 StringRef MachOContents = info->O->getData();
3248 uint64_t object_size = MachOContents.size();
3249 const char *object_addr = (const char *)MachOContents.data();
3250 if (object_offset < object_size) {
3251 uint64_t pointer_value;
3252 memcpy(&pointer_value, object_addr + object_offset,
3253 sizeof(uint64_t));
3254 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3255 sys::swapByteOrder(pointer_value);
3256 if (strncmp(Sec.sectname, "__objc_selrefs", 16) == 0)
3257 selref = true;
3258 else if (strncmp(Sec.sectname, "__objc_classrefs", 16) == 0 ||
3259 strncmp(Sec.sectname, "__objc_superrefs", 16) == 0)
3260 classref = true;
3261 else if (strncmp(Sec.sectname, "__objc_msgrefs", 16) == 0 &&
3262 ReferenceValue + 8 < Sec.addr + Sec.size) {
3263 msgref = true;
3264 memcpy(&pointer_value, object_addr + object_offset + 8,
3265 sizeof(uint64_t));
3266 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3267 sys::swapByteOrder(pointer_value);
3268 } else if (strncmp(Sec.sectname, "__cfstring", 16) == 0)
3269 cfstring = true;
3270 return pointer_value;
3271 } else {
3272 return 0;
3273 }
3274 }
3275 }
3276 }
3277 // TODO: Look for LC_SEGMENT for 32-bit Mach-O files.
3278 }
3279 return 0;
3280}
3281
3282// get_pointer_64 returns a pointer to the bytes in the object file at the
3283// Address from a section in the Mach-O file. And indirectly returns the
3284// offset into the section, number of bytes left in the section past the offset
3285// and which section is was being referenced. If the Address is not in a
3286// section nullptr is returned.
3287static const char *get_pointer_64(uint64_t Address, uint32_t &offset,
3288 uint32_t &left, SectionRef &S,
3289 DisassembleInfo *info,
3290 bool objc_only = false) {
3291 offset = 0;
3292 left = 0;
3293 S = SectionRef();
3294 for (unsigned SectIdx = 0; SectIdx != info->Sections->size(); SectIdx++) {
3295 uint64_t SectAddress = ((*(info->Sections))[SectIdx]).getAddress();
3296 uint64_t SectSize = ((*(info->Sections))[SectIdx]).getSize();
3297 if (SectSize == 0)
3298 continue;
3299 if (objc_only) {
3300 StringRef SectName;
3301 Expected<StringRef> SecNameOrErr =
3302 ((*(info->Sections))[SectIdx]).getName();
3303 if (SecNameOrErr)
3304 SectName = *SecNameOrErr;
3305 else
3306 consumeError(SecNameOrErr.takeError());
3307
3308 DataRefImpl Ref = ((*(info->Sections))[SectIdx]).getRawDataRefImpl();
3309 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
3310 if (SegName != "__OBJC" && SectName != "__cstring")
3311 continue;
3312 }
3313 if (Address >= SectAddress && Address < SectAddress + SectSize) {
3314 S = (*(info->Sections))[SectIdx];
3315 offset = Address - SectAddress;
3316 left = SectSize - offset;
3317 StringRef SectContents = unwrapOrError(
3318 ((*(info->Sections))[SectIdx]).getContents(), info->O->getFileName());
3319 return SectContents.data() + offset;
3320 }
3321 }
3322 return nullptr;
3323}
3324
3325static const char *get_pointer_32(uint32_t Address, uint32_t &offset,
3326 uint32_t &left, SectionRef &S,
3327 DisassembleInfo *info,
3328 bool objc_only = false) {
3329 return get_pointer_64(Address, offset, left, S, info, objc_only);
3330}
3331
3332// get_symbol_64() returns the name of a symbol (or nullptr) and the address of
3333// the symbol indirectly through n_value. Based on the relocation information
3334// for the specified section offset in the specified section reference.
3335// If no relocation information is found and a non-zero ReferenceValue for the
3336// symbol is passed, look up that address in the info's AddrMap.
3337static const char *get_symbol_64(uint32_t sect_offset, SectionRef S,
3338 DisassembleInfo *info, uint64_t &n_value,
3339 uint64_t ReferenceValue = 0) {
3340 n_value = 0;
3341 if (!info->verbose)
3342 return nullptr;
3343
3344 // See if there is an external relocation entry at the sect_offset.
3345 bool reloc_found = false;
3346 DataRefImpl Rel;
3347 MachO::any_relocation_info RE;
3348 bool isExtern = false;
3349 SymbolRef Symbol;
3350 for (const RelocationRef &Reloc : S.relocations()) {
3351 uint64_t RelocOffset = Reloc.getOffset();
3352 if (RelocOffset == sect_offset) {
3353 Rel = Reloc.getRawDataRefImpl();
3354 RE = info->O->getRelocation(Rel);
3355 if (info->O->isRelocationScattered(RE))
3356 continue;
3357 isExtern = info->O->getPlainRelocationExternal(RE);
3358 if (isExtern) {
3359 symbol_iterator RelocSym = Reloc.getSymbol();
3360 Symbol = *RelocSym;
3361 }
3362 reloc_found = true;
3363 break;
3364 }
3365 }
3366 // If there is an external relocation entry for a symbol in this section
3367 // at this section_offset then use that symbol's value for the n_value
3368 // and return its name.
3369 const char *SymbolName = nullptr;
3370 if (reloc_found && isExtern) {
3371 n_value = cantFail(Symbol.getValue());
3372 StringRef Name = unwrapOrError(Symbol.getName(), info->O->getFileName());
3373 if (!Name.empty()) {
3374 SymbolName = Name.data();
3375 return SymbolName;
3376 }
3377 }
3378
3379 // TODO: For fully linked images, look through the external relocation
3380 // entries off the dynamic symtab command. For these the r_offset is from the
3381 // start of the first writeable segment in the Mach-O file. So the offset
3382 // to this section from that segment is passed to this routine by the caller,
3383 // as the database_offset. Which is the difference of the section's starting
3384 // address and the first writable segment.
3385 //
3386 // NOTE: need add passing the database_offset to this routine.
3387
3388 // We did not find an external relocation entry so look up the ReferenceValue
3389 // as an address of a symbol and if found return that symbol's name.
3390 SymbolName = GuessSymbolName(ReferenceValue, info->AddrMap);
3391
3392 return SymbolName;
3393}
3394
3395static const char *get_symbol_32(uint32_t sect_offset, SectionRef S,
3396 DisassembleInfo *info,
3397 uint32_t ReferenceValue) {
3398 uint64_t n_value64;
3399 return get_symbol_64(sect_offset, S, info, n_value64, ReferenceValue);
3400}
3401
3402namespace {
3403
3404// These are structs in the Objective-C meta data and read to produce the
3405// comments for disassembly. While these are part of the ABI they are no
3406// public defintions. So the are here not in include/llvm/BinaryFormat/MachO.h
3407// .
3408
3409// The cfstring object in a 64-bit Mach-O file.
3410struct cfstring64_t {
3411 uint64_t isa; // class64_t * (64-bit pointer)
3412 uint64_t flags; // flag bits
3413 uint64_t characters; // char * (64-bit pointer)
3414 uint64_t length; // number of non-NULL characters in above
3415};
3416
3417// The class object in a 64-bit Mach-O file.
3418struct class64_t {
3419 uint64_t isa; // class64_t * (64-bit pointer)
3420 uint64_t superclass; // class64_t * (64-bit pointer)
3421 uint64_t cache; // Cache (64-bit pointer)
3422 uint64_t vtable; // IMP * (64-bit pointer)
3423 uint64_t data; // class_ro64_t * (64-bit pointer)
3424};
3425
3426struct class32_t {
3427 uint32_t isa; /* class32_t * (32-bit pointer) */
3428 uint32_t superclass; /* class32_t * (32-bit pointer) */
3429 uint32_t cache; /* Cache (32-bit pointer) */
3430 uint32_t vtable; /* IMP * (32-bit pointer) */
3431 uint32_t data; /* class_ro32_t * (32-bit pointer) */
3432};
3433
3434struct class_ro64_t {
3435 uint32_t flags;
3436 uint32_t instanceStart;
3437 uint32_t instanceSize;
3438 uint32_t reserved;
3439 uint64_t ivarLayout; // const uint8_t * (64-bit pointer)
3440 uint64_t name; // const char * (64-bit pointer)
3441 uint64_t baseMethods; // const method_list_t * (64-bit pointer)
3442 uint64_t baseProtocols; // const protocol_list_t * (64-bit pointer)
3443 uint64_t ivars; // const ivar_list_t * (64-bit pointer)
3444 uint64_t weakIvarLayout; // const uint8_t * (64-bit pointer)
3445 uint64_t baseProperties; // const struct objc_property_list (64-bit pointer)
3446};
3447
3448struct class_ro32_t {
3449 uint32_t flags;
3450 uint32_t instanceStart;
3451 uint32_t instanceSize;
3452 uint32_t ivarLayout; /* const uint8_t * (32-bit pointer) */
3453 uint32_t name; /* const char * (32-bit pointer) */
3454 uint32_t baseMethods; /* const method_list_t * (32-bit pointer) */
3455 uint32_t baseProtocols; /* const protocol_list_t * (32-bit pointer) */
3456 uint32_t ivars; /* const ivar_list_t * (32-bit pointer) */
3457 uint32_t weakIvarLayout; /* const uint8_t * (32-bit pointer) */
3458 uint32_t baseProperties; /* const struct objc_property_list *
3459 (32-bit pointer) */
3460};
3461
3462/* Values for class_ro{64,32}_t->flags */
3463#define RO_META(1 << 0) (1 << 0)
3464#define RO_ROOT(1 << 1) (1 << 1)
3465#define RO_HAS_CXX_STRUCTORS(1 << 2) (1 << 2)
3466
3467struct method_list64_t {
3468 uint32_t entsize;
3469 uint32_t count;
3470 /* struct method64_t first; These structures follow inline */
3471};
3472
3473struct method_list32_t {
3474 uint32_t entsize;
3475 uint32_t count;
3476 /* struct method32_t first; These structures follow inline */
3477};
3478
3479struct method64_t {
3480 uint64_t name; /* SEL (64-bit pointer) */
3481 uint64_t types; /* const char * (64-bit pointer) */
3482 uint64_t imp; /* IMP (64-bit pointer) */
3483};
3484
3485struct method32_t {
3486 uint32_t name; /* SEL (32-bit pointer) */
3487 uint32_t types; /* const char * (32-bit pointer) */
3488 uint32_t imp; /* IMP (32-bit pointer) */
3489};
3490
3491struct protocol_list64_t {
3492 uint64_t count; /* uintptr_t (a 64-bit value) */
3493 /* struct protocol64_t * list[0]; These pointers follow inline */
3494};
3495
3496struct protocol_list32_t {
3497 uint32_t count; /* uintptr_t (a 32-bit value) */
3498 /* struct protocol32_t * list[0]; These pointers follow inline */
3499};
3500
3501struct protocol64_t {
3502 uint64_t isa; /* id * (64-bit pointer) */
3503 uint64_t name; /* const char * (64-bit pointer) */
3504 uint64_t protocols; /* struct protocol_list64_t *
3505 (64-bit pointer) */
3506 uint64_t instanceMethods; /* method_list_t * (64-bit pointer) */
3507 uint64_t classMethods; /* method_list_t * (64-bit pointer) */
3508 uint64_t optionalInstanceMethods; /* method_list_t * (64-bit pointer) */
3509 uint64_t optionalClassMethods; /* method_list_t * (64-bit pointer) */
3510 uint64_t instanceProperties; /* struct objc_property_list *
3511 (64-bit pointer) */
3512};
3513
3514struct protocol32_t {
3515 uint32_t isa; /* id * (32-bit pointer) */
3516 uint32_t name; /* const char * (32-bit pointer) */
3517 uint32_t protocols; /* struct protocol_list_t *
3518 (32-bit pointer) */
3519 uint32_t instanceMethods; /* method_list_t * (32-bit pointer) */
3520 uint32_t classMethods; /* method_list_t * (32-bit pointer) */
3521 uint32_t optionalInstanceMethods; /* method_list_t * (32-bit pointer) */
3522 uint32_t optionalClassMethods; /* method_list_t * (32-bit pointer) */
3523 uint32_t instanceProperties; /* struct objc_property_list *
3524 (32-bit pointer) */
3525};
3526
3527struct ivar_list64_t {
3528 uint32_t entsize;
3529 uint32_t count;
3530 /* struct ivar64_t first; These structures follow inline */
3531};
3532
3533struct ivar_list32_t {
3534 uint32_t entsize;
3535 uint32_t count;
3536 /* struct ivar32_t first; These structures follow inline */
3537};
3538
3539struct ivar64_t {
3540 uint64_t offset; /* uintptr_t * (64-bit pointer) */
3541 uint64_t name; /* const char * (64-bit pointer) */
3542 uint64_t type; /* const char * (64-bit pointer) */
3543 uint32_t alignment;
3544 uint32_t size;
3545};
3546
3547struct ivar32_t {
3548 uint32_t offset; /* uintptr_t * (32-bit pointer) */
3549 uint32_t name; /* const char * (32-bit pointer) */
3550 uint32_t type; /* const char * (32-bit pointer) */
3551 uint32_t alignment;
3552 uint32_t size;
3553};
3554
3555struct objc_property_list64 {
3556 uint32_t entsize;
3557 uint32_t count;
3558 /* struct objc_property64 first; These structures follow inline */
3559};
3560
3561struct objc_property_list32 {
3562 uint32_t entsize;
3563 uint32_t count;
3564 /* struct objc_property32 first; These structures follow inline */
3565};
3566
3567struct objc_property64 {
3568 uint64_t name; /* const char * (64-bit pointer) */
3569 uint64_t attributes; /* const char * (64-bit pointer) */
3570};
3571
3572struct objc_property32 {
3573 uint32_t name; /* const char * (32-bit pointer) */
3574 uint32_t attributes; /* const char * (32-bit pointer) */
3575};
3576
3577struct category64_t {
3578 uint64_t name; /* const char * (64-bit pointer) */
3579 uint64_t cls; /* struct class_t * (64-bit pointer) */
3580 uint64_t instanceMethods; /* struct method_list_t * (64-bit pointer) */
3581 uint64_t classMethods; /* struct method_list_t * (64-bit pointer) */
3582 uint64_t protocols; /* struct protocol_list_t * (64-bit pointer) */
3583 uint64_t instanceProperties; /* struct objc_property_list *
3584 (64-bit pointer) */
3585};
3586
3587struct category32_t {
3588 uint32_t name; /* const char * (32-bit pointer) */
3589 uint32_t cls; /* struct class_t * (32-bit pointer) */
3590 uint32_t instanceMethods; /* struct method_list_t * (32-bit pointer) */
3591 uint32_t classMethods; /* struct method_list_t * (32-bit pointer) */
3592 uint32_t protocols; /* struct protocol_list_t * (32-bit pointer) */
3593 uint32_t instanceProperties; /* struct objc_property_list *
3594 (32-bit pointer) */
3595};
3596
3597struct objc_image_info64 {
3598 uint32_t version;
3599 uint32_t flags;
3600};
3601struct objc_image_info32 {
3602 uint32_t version;
3603 uint32_t flags;
3604};
3605struct imageInfo_t {
3606 uint32_t version;
3607 uint32_t flags;
3608};
3609/* masks for objc_image_info.flags */
3610#define OBJC_IMAGE_IS_REPLACEMENT(1 << 0) (1 << 0)
3611#define OBJC_IMAGE_SUPPORTS_GC(1 << 1) (1 << 1)
3612#define OBJC_IMAGE_IS_SIMULATED(1 << 5) (1 << 5)
3613#define OBJC_IMAGE_HAS_CATEGORY_CLASS_PROPERTIES(1 << 6) (1 << 6)
3614
3615struct message_ref64 {
3616 uint64_t imp; /* IMP (64-bit pointer) */
3617 uint64_t sel; /* SEL (64-bit pointer) */
3618};
3619
3620struct message_ref32 {
3621 uint32_t imp; /* IMP (32-bit pointer) */
3622 uint32_t sel; /* SEL (32-bit pointer) */
3623};
3624
3625// Objective-C 1 (32-bit only) meta data structs.
3626
3627struct objc_module_t {
3628 uint32_t version;
3629 uint32_t size;
3630 uint32_t name; /* char * (32-bit pointer) */
3631 uint32_t symtab; /* struct objc_symtab * (32-bit pointer) */
3632};
3633
3634struct objc_symtab_t {
3635 uint32_t sel_ref_cnt;
3636 uint32_t refs; /* SEL * (32-bit pointer) */
3637 uint16_t cls_def_cnt;
3638 uint16_t cat_def_cnt;
3639 // uint32_t defs[1]; /* void * (32-bit pointer) variable size */
3640};
3641
3642struct objc_class_t {
3643 uint32_t isa; /* struct objc_class * (32-bit pointer) */
3644 uint32_t super_class; /* struct objc_class * (32-bit pointer) */
3645 uint32_t name; /* const char * (32-bit pointer) */
3646 int32_t version;
3647 int32_t info;
3648 int32_t instance_size;
3649 uint32_t ivars; /* struct objc_ivar_list * (32-bit pointer) */
3650 uint32_t methodLists; /* struct objc_method_list ** (32-bit pointer) */
3651 uint32_t cache; /* struct objc_cache * (32-bit pointer) */
3652 uint32_t protocols; /* struct objc_protocol_list * (32-bit pointer) */
3653};
3654
3655#define CLS_GETINFO(cls, infomask)((cls)->info & (infomask)) ((cls)->info & (infomask))
3656// class is not a metaclass
3657#define CLS_CLASS0x1 0x1
3658// class is a metaclass
3659#define CLS_META0x2 0x2
3660
3661struct objc_category_t {
3662 uint32_t category_name; /* char * (32-bit pointer) */
3663 uint32_t class_name; /* char * (32-bit pointer) */
3664 uint32_t instance_methods; /* struct objc_method_list * (32-bit pointer) */
3665 uint32_t class_methods; /* struct objc_method_list * (32-bit pointer) */
3666 uint32_t protocols; /* struct objc_protocol_list * (32-bit ptr) */
3667};
3668
3669struct objc_ivar_t {
3670 uint32_t ivar_name; /* char * (32-bit pointer) */
3671 uint32_t ivar_type; /* char * (32-bit pointer) */
3672 int32_t ivar_offset;
3673};
3674
3675struct objc_ivar_list_t {
3676 int32_t ivar_count;
3677 // struct objc_ivar_t ivar_list[1]; /* variable length structure */
3678};
3679
3680struct objc_method_list_t {
3681 uint32_t obsolete; /* struct objc_method_list * (32-bit pointer) */
3682 int32_t method_count;
3683 // struct objc_method_t method_list[1]; /* variable length structure */
3684};
3685
3686struct objc_method_t {
3687 uint32_t method_name; /* SEL, aka struct objc_selector * (32-bit pointer) */
3688 uint32_t method_types; /* char * (32-bit pointer) */
3689 uint32_t method_imp; /* IMP, aka function pointer, (*IMP)(id, SEL, ...)
3690 (32-bit pointer) */
3691};
3692
3693struct objc_protocol_list_t {
3694 uint32_t next; /* struct objc_protocol_list * (32-bit pointer) */
3695 int32_t count;
3696 // uint32_t list[1]; /* Protocol *, aka struct objc_protocol_t *
3697 // (32-bit pointer) */
3698};
3699
3700struct objc_protocol_t {
3701 uint32_t isa; /* struct objc_class * (32-bit pointer) */
3702 uint32_t protocol_name; /* char * (32-bit pointer) */
3703 uint32_t protocol_list; /* struct objc_protocol_list * (32-bit pointer) */
3704 uint32_t instance_methods; /* struct objc_method_description_list *
3705 (32-bit pointer) */
3706 uint32_t class_methods; /* struct objc_method_description_list *
3707 (32-bit pointer) */
3708};
3709
3710struct objc_method_description_list_t {
3711 int32_t count;
3712 // struct objc_method_description_t list[1];
3713};
3714
3715struct objc_method_description_t {
3716 uint32_t name; /* SEL, aka struct objc_selector * (32-bit pointer) */
3717 uint32_t types; /* char * (32-bit pointer) */
3718};
3719
3720inline void swapStruct(struct cfstring64_t &cfs) {
3721 sys::swapByteOrder(cfs.isa);
3722 sys::swapByteOrder(cfs.flags);
3723 sys::swapByteOrder(cfs.characters);
3724 sys::swapByteOrder(cfs.length);
3725}
3726
3727inline void swapStruct(struct class64_t &c) {
3728 sys::swapByteOrder(c.isa);
3729 sys::swapByteOrder(c.superclass);
3730 sys::swapByteOrder(c.cache);
3731 sys::swapByteOrder(c.vtable);
3732 sys::swapByteOrder(c.data);
3733}
3734
3735inline void swapStruct(struct class32_t &c) {
3736 sys::swapByteOrder(c.isa);
3737 sys::swapByteOrder(c.superclass);
3738 sys::swapByteOrder(c.cache);
3739 sys::swapByteOrder(c.vtable);
3740 sys::swapByteOrder(c.data);
3741}
3742
3743inline void swapStruct(struct class_ro64_t &cro) {
3744 sys::swapByteOrder(cro.flags);
3745 sys::swapByteOrder(cro.instanceStart);
3746 sys::swapByteOrder(cro.instanceSize);
3747 sys::swapByteOrder(cro.reserved);
3748 sys::swapByteOrder(cro.ivarLayout);
3749 sys::swapByteOrder(cro.name);
3750 sys::swapByteOrder(cro.baseMethods);
3751 sys::swapByteOrder(cro.baseProtocols);
3752 sys::swapByteOrder(cro.ivars);
3753 sys::swapByteOrder(cro.weakIvarLayout);
3754 sys::swapByteOrder(cro.baseProperties);
3755}
3756
3757inline void swapStruct(struct class_ro32_t &cro) {
3758 sys::swapByteOrder(cro.flags);
3759 sys::swapByteOrder(cro.instanceStart);
3760 sys::swapByteOrder(cro.instanceSize);
3761 sys::swapByteOrder(cro.ivarLayout);
3762 sys::swapByteOrder(cro.name);
3763 sys::swapByteOrder(cro.baseMethods);
3764 sys::swapByteOrder(cro.baseProtocols);
3765 sys::swapByteOrder(cro.ivars);
3766 sys::swapByteOrder(cro.weakIvarLayout);
3767 sys::swapByteOrder(cro.baseProperties);
3768}
3769
3770inline void swapStruct(struct method_list64_t &ml) {
3771 sys::swapByteOrder(ml.entsize);
3772 sys::swapByteOrder(ml.count);
3773}
3774
3775inline void swapStruct(struct method_list32_t &ml) {
3776 sys::swapByteOrder(ml.entsize);
3777 sys::swapByteOrder(ml.count);
3778}
3779
3780inline void swapStruct(struct method64_t &m) {
3781 sys::swapByteOrder(m.name);
3782 sys::swapByteOrder(m.types);
3783 sys::swapByteOrder(m.imp);
3784}
3785
3786inline void swapStruct(struct method32_t &m) {
3787 sys::swapByteOrder(m.name);
3788 sys::swapByteOrder(m.types);
3789 sys::swapByteOrder(m.imp);
3790}
3791
3792inline void swapStruct(struct protocol_list64_t &pl) {
3793 sys::swapByteOrder(pl.count);
3794}
3795
3796inline void swapStruct(struct protocol_list32_t &pl) {
3797 sys::swapByteOrder(pl.count);
3798}
3799
3800inline void swapStruct(struct protocol64_t &p) {
3801 sys::swapByteOrder(p.isa);
3802 sys::swapByteOrder(p.name);
3803 sys::swapByteOrder(p.protocols);
3804 sys::swapByteOrder(p.instanceMethods);
3805 sys::swapByteOrder(p.classMethods);
3806 sys::swapByteOrder(p.optionalInstanceMethods);
3807 sys::swapByteOrder(p.optionalClassMethods);
3808 sys::swapByteOrder(p.instanceProperties);
3809}
3810
3811inline void swapStruct(struct protocol32_t &p) {
3812 sys::swapByteOrder(p.isa);
3813 sys::swapByteOrder(p.name);
3814 sys::swapByteOrder(p.protocols);
3815 sys::swapByteOrder(p.instanceMethods);
3816 sys::swapByteOrder(p.classMethods);
3817 sys::swapByteOrder(p.optionalInstanceMethods);
3818 sys::swapByteOrder(p.optionalClassMethods);
3819 sys::swapByteOrder(p.instanceProperties);
3820}
3821
3822inline void swapStruct(struct ivar_list64_t &il) {
3823 sys::swapByteOrder(il.entsize);
3824 sys::swapByteOrder(il.count);
3825}
3826
3827inline void swapStruct(struct ivar_list32_t &il) {
3828 sys::swapByteOrder(il.entsize);
3829 sys::swapByteOrder(il.count);
3830}
3831
3832inline void swapStruct(struct ivar64_t &i) {
3833 sys::swapByteOrder(i.offset);
3834 sys::swapByteOrder(i.name);
3835 sys::swapByteOrder(i.type);
3836 sys::swapByteOrder(i.alignment);
3837 sys::swapByteOrder(i.size);
3838}
3839
3840inline void swapStruct(struct ivar32_t &i) {
3841 sys::swapByteOrder(i.offset);
3842 sys::swapByteOrder(i.name);
3843 sys::swapByteOrder(i.type);
3844 sys::swapByteOrder(i.alignment);
3845 sys::swapByteOrder(i.size);
3846}
3847
3848inline void swapStruct(struct objc_property_list64 &pl) {
3849 sys::swapByteOrder(pl.entsize);
3850 sys::swapByteOrder(pl.count);
3851}
3852
3853inline void swapStruct(struct objc_property_list32 &pl) {
3854 sys::swapByteOrder(pl.entsize);
3855 sys::swapByteOrder(pl.count);
3856}
3857
3858inline void swapStruct(struct objc_property64 &op) {
3859 sys::swapByteOrder(op.name);
3860 sys::swapByteOrder(op.attributes);
3861}
3862
3863inline void swapStruct(struct objc_property32 &op) {
3864 sys::swapByteOrder(op.name);
3865 sys::swapByteOrder(op.attributes);
3866}
3867
3868inline void swapStruct(struct category64_t &c) {
3869 sys::swapByteOrder(c.name);
3870 sys::swapByteOrder(c.cls);
3871 sys::swapByteOrder(c.instanceMethods);
3872 sys::swapByteOrder(c.classMethods);
3873 sys::swapByteOrder(c.protocols);
3874 sys::swapByteOrder(c.instanceProperties);
3875}
3876
3877inline void swapStruct(struct category32_t &c) {
3878 sys::swapByteOrder(c.name);
3879 sys::swapByteOrder(c.cls);
3880 sys::swapByteOrder(c.instanceMethods);
3881 sys::swapByteOrder(c.classMethods);
3882 sys::swapByteOrder(c.protocols);
3883 sys::swapByteOrder(c.instanceProperties);
3884}
3885
3886inline void swapStruct(struct objc_image_info64 &o) {
3887 sys::swapByteOrder(o.version);
3888 sys::swapByteOrder(o.flags);
3889}
3890
3891inline void swapStruct(struct objc_image_info32 &o) {
3892 sys::swapByteOrder(o.version);
3893 sys::swapByteOrder(o.flags);
3894}
3895
3896inline void swapStruct(struct imageInfo_t &o) {
3897 sys::swapByteOrder(o.version);
3898 sys::swapByteOrder(o.flags);
3899}
3900
3901inline void swapStruct(struct message_ref64 &mr) {
3902 sys::swapByteOrder(mr.imp);
3903 sys::swapByteOrder(mr.sel);
3904}
3905
3906inline void swapStruct(struct message_ref32 &mr) {
3907 sys::swapByteOrder(mr.imp);
3908 sys::swapByteOrder(mr.sel);
3909}
3910
3911inline void swapStruct(struct objc_module_t &module) {
3912 sys::swapByteOrder(module.version);
3913 sys::swapByteOrder(module.size);
3914 sys::swapByteOrder(module.name);
3915 sys::swapByteOrder(module.symtab);
3916}
3917
3918inline void swapStruct(struct objc_symtab_t &symtab) {
3919 sys::swapByteOrder(symtab.sel_ref_cnt);
3920 sys::swapByteOrder(symtab.refs);
3921 sys::swapByteOrder(symtab.cls_def_cnt);
3922 sys::swapByteOrder(symtab.cat_def_cnt);
3923}
3924
3925inline void swapStruct(struct objc_class_t &objc_class) {
3926 sys::swapByteOrder(objc_class.isa);
3927 sys::swapByteOrder(objc_class.super_class);
3928 sys::swapByteOrder(objc_class.name);
3929 sys::swapByteOrder(objc_class.version);
3930 sys::swapByteOrder(objc_class.info);
3931 sys::swapByteOrder(objc_class.instance_size);
3932 sys::swapByteOrder(objc_class.ivars);
3933 sys::swapByteOrder(objc_class.methodLists);
3934 sys::swapByteOrder(objc_class.cache);
3935 sys::swapByteOrder(objc_class.protocols);
3936}
3937
3938inline void swapStruct(struct objc_category_t &objc_category) {
3939 sys::swapByteOrder(objc_category.category_name);
3940 sys::swapByteOrder(objc_category.class_name);
3941 sys::swapByteOrder(objc_category.instance_methods);
3942 sys::swapByteOrder(objc_category.class_methods);
3943 sys::swapByteOrder(objc_category.protocols);
3944}
3945
3946inline void swapStruct(struct objc_ivar_list_t &objc_ivar_list) {
3947 sys::swapByteOrder(objc_ivar_list.ivar_count);
3948}
3949
3950inline void swapStruct(struct objc_ivar_t &objc_ivar) {
3951 sys::swapByteOrder(objc_ivar.ivar_name);
3952 sys::swapByteOrder(objc_ivar.ivar_type);
3953 sys::swapByteOrder(objc_ivar.ivar_offset);
3954}
3955
3956inline void swapStruct(struct objc_method_list_t &method_list) {
3957 sys::swapByteOrder(method_list.obsolete);
3958 sys::swapByteOrder(method_list.method_count);
3959}
3960
3961inline void swapStruct(struct objc_method_t &method) {
3962 sys::swapByteOrder(method.method_name);
3963 sys::swapByteOrder(method.method_types);
3964 sys::swapByteOrder(method.method_imp);
3965}
3966
3967inline void swapStruct(struct objc_protocol_list_t &protocol_list) {
3968 sys::swapByteOrder(protocol_list.next);
3969 sys::swapByteOrder(protocol_list.count);
3970}
3971
3972inline void swapStruct(struct objc_protocol_t &protocol) {
3973 sys::swapByteOrder(protocol.isa);
3974 sys::swapByteOrder(protocol.protocol_name);
3975 sys::swapByteOrder(protocol.protocol_list);
3976 sys::swapByteOrder(protocol.instance_methods);
3977 sys::swapByteOrder(protocol.class_methods);
3978}
3979
3980inline void swapStruct(struct objc_method_description_list_t &mdl) {
3981 sys::swapByteOrder(mdl.count);
3982}
3983
3984inline void swapStruct(struct objc_method_description_t &md) {
3985 sys::swapByteOrder(md.name);
3986 sys::swapByteOrder(md.types);
3987}
3988
3989} // namespace
3990
3991static const char *get_dyld_bind_info_symbolname(uint64_t ReferenceValue,
3992 struct DisassembleInfo *info);
3993
3994// get_objc2_64bit_class_name() is used for disassembly and is passed a pointer
3995// to an Objective-C class and returns the class name. It is also passed the
3996// address of the pointer, so when the pointer is zero as it can be in an .o
3997// file, that is used to look for an external relocation entry with a symbol
3998// name.
3999static const char *get_objc2_64bit_class_name(uint64_t pointer_value,
4000 uint64_t ReferenceValue,
4001 struct DisassembleInfo *info) {
4002 const char *r;
4003 uint32_t offset, left;
4004 SectionRef S;
4005
4006 // The pointer_value can be 0 in an object file and have a relocation
4007 // entry for the class symbol at the ReferenceValue (the address of the
4008 // pointer).
4009 if (pointer_value == 0) {
4010 r = get_pointer_64(ReferenceValue, offset, left, S, info);
4011 if (r == nullptr || left < sizeof(uint64_t))
4012 return nullptr;
4013 uint64_t n_value;
4014 const char *symbol_name = get_symbol_64(offset, S, info, n_value);
4015 if (symbol_name == nullptr)
4016 return nullptr;
4017 const char *class_name = strrchr(symbol_name, '$');
4018 if (class_name != nullptr && class_name[1] == '_' && class_name[2] != '\0')
4019 return class_name + 2;
4020 else
4021 return nullptr;
4022 }
4023
4024 // The case were the pointer_value is non-zero and points to a class defined
4025 // in this Mach-O file.
4026 r = get_pointer_64(pointer_value, offset, left, S, info);
4027 if (r == nullptr || left < sizeof(struct class64_t))
4028 return nullptr;
4029 struct class64_t c;
4030 memcpy(&c, r, sizeof(struct class64_t));
4031 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4032 swapStruct(c);
4033 if (c.data == 0)
4034 return nullptr;
4035 r = get_pointer_64(c.data, offset, left, S, info);
4036 if (r == nullptr || left < sizeof(struct class_ro64_t))
4037 return nullptr;
4038 struct class_ro64_t cro;
4039 memcpy(&cro, r, sizeof(struct class_ro64_t));
4040 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4041 swapStruct(cro);
4042 if (cro.name == 0)
4043 return nullptr;
4044 const char *name = get_pointer_64(cro.name, offset, left, S, info);
4045 return name;
4046}
4047
4048// get_objc2_64bit_cfstring_name is used for disassembly and is passed a
4049// pointer to a cfstring and returns its name or nullptr.
4050static const char *get_objc2_64bit_cfstring_name(uint64_t ReferenceValue,
4051 struct DisassembleInfo *info) {
4052 const char *r, *name;
4053 uint32_t offset, left;
4054 SectionRef S;
4055 struct cfstring64_t cfs;
4056 uint64_t cfs_characters;
4057
4058 r = get_pointer_64(ReferenceValue, offset, left, S, info);
4059 if (r == nullptr || left < sizeof(struct cfstring64_t))
4060 return nullptr;
4061 memcpy(&cfs, r, sizeof(struct cfstring64_t));
4062 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4063 swapStruct(cfs);
4064 if (cfs.characters == 0) {
4065 uint64_t n_value;
4066 const char *symbol_name = get_symbol_64(
4067 offset + offsetof(struct cfstring64_t, characters)__builtin_offsetof(struct cfstring64_t, characters), S, info, n_value);
4068 if (symbol_name == nullptr)
4069 return nullptr;
4070 cfs_characters = n_value;
4071 } else
4072 cfs_characters = cfs.characters;
4073 name = get_pointer_64(cfs_characters, offset, left, S, info);
4074
4075 return name;
4076}
4077
4078// get_objc2_64bit_selref() is used for disassembly and is passed a the address
4079// of a pointer to an Objective-C selector reference when the pointer value is
4080// zero as in a .o file and is likely to have a external relocation entry with
4081// who's symbol's n_value is the real pointer to the selector name. If that is
4082// the case the real pointer to the selector name is returned else 0 is
4083// returned
4084static uint64_t get_objc2_64bit_selref(uint64_t ReferenceValue,
4085 struct DisassembleInfo *info) {
4086 uint32_t offset, left;
4087 SectionRef S;
4088
4089 const char *r = get_pointer_64(ReferenceValue, offset, left, S, info);
4090 if (r == nullptr || left < sizeof(uint64_t))
4091 return 0;
4092 uint64_t n_value;
4093 const char *symbol_name = get_symbol_64(offset, S, info, n_value);
4094 if (symbol_name == nullptr)
4095 return 0;
4096 return n_value;
4097}
4098
4099static const SectionRef get_section(MachOObjectFile *O, const char *segname,
4100 const char *sectname) {
4101 for (const SectionRef &Section : O->sections()) {
4102 StringRef SectName;
4103 Expected<StringRef> SecNameOrErr = Section.getName();
4104 if (SecNameOrErr)
4105 SectName = *SecNameOrErr;
4106 else
4107 consumeError(SecNameOrErr.takeError());
4108
4109 DataRefImpl Ref = Section.getRawDataRefImpl();
4110 StringRef SegName = O->getSectionFinalSegmentName(Ref);
4111 if (SegName == segname && SectName == sectname)
4112 return Section;
4113 }
4114 return SectionRef();
4115}
4116
4117static void
4118walk_pointer_list_64(const char *listname, const SectionRef S,
4119 MachOObjectFile *O, struct DisassembleInfo *info,
4120 void (*func)(uint64_t, struct DisassembleInfo *info)) {
4121 if (S == SectionRef())
4122 return;
4123
4124 StringRef SectName;
4125 Expected<StringRef> SecNameOrErr = S.getName();
4126 if (SecNameOrErr)
4127 SectName = *SecNameOrErr;
4128 else
4129 consumeError(SecNameOrErr.takeError());
4130
4131 DataRefImpl Ref = S.getRawDataRefImpl();
4132 StringRef SegName = O->getSectionFinalSegmentName(Ref);
4133 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
4134
4135 StringRef BytesStr = unwrapOrError(S.getContents(), O->getFileName());
4136 const char *Contents = reinterpret_cast<const char *>(BytesStr.data());
4137
4138 for (uint32_t i = 0; i < S.getSize(); i += sizeof(uint64_t)) {
4139 uint32_t left = S.getSize() - i;
4140 uint32_t size = left < sizeof(uint64_t) ? left : sizeof(uint64_t);
4141 uint64_t p = 0;
4142 memcpy(&p, Contents + i, size);
4143 if (i + sizeof(uint64_t) > S.getSize())
4144 outs() << listname << " list pointer extends past end of (" << SegName
4145 << "," << SectName << ") section\n";
4146 outs() << format("%016" PRIx64"l" "x", S.getAddress() + i) << " ";
4147
4148 if (O->isLittleEndian() != sys::IsLittleEndianHost)
4149 sys::swapByteOrder(p);
4150
4151 uint64_t n_value = 0;
4152 const char *name = get_symbol_64(i, S, info, n_value, p);
4153 if (name == nullptr)
4154 name = get_dyld_bind_info_symbolname(S.getAddress() + i, info);
4155
4156 if (n_value != 0) {
4157 outs() << format("0x%" PRIx64"l" "x", n_value);
4158 if (p != 0)
4159 outs() << " + " << format("0x%" PRIx64"l" "x", p);
4160 } else
4161 outs() << format("0x%" PRIx64"l" "x", p);
4162 if (name != nullptr)
4163 outs() << " " << name;
4164 outs() << "\n";
4165
4166 p += n_value;
4167 if (func)
4168 func(p, info);
4169 }
4170}
4171
4172static void
4173walk_pointer_list_32(const char *listname, const SectionRef S,
4174 MachOObjectFile *O, struct DisassembleInfo *info,
4175 void (*func)(uint32_t, struct DisassembleInfo *info)) {
4176 if (S == SectionRef())
4177 return;
4178
4179 StringRef SectName = unwrapOrError(S.getName(), O->getFileName());
4180 DataRefImpl Ref = S.getRawDataRefImpl();
4181 StringRef SegName = O->getSectionFinalSegmentName(Ref);
4182 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
4183
4184 StringRef BytesStr = unwrapOrError(S.getContents(), O->getFileName());
4185 const char *Contents = reinterpret_cast<const char *>(BytesStr.data());
4186
4187 for (uint32_t i = 0; i < S.getSize(); i += sizeof(uint32_t)) {
4188 uint32_t left = S.getSize() - i;
4189 uint32_t size = left < sizeof(uint32_t) ? left : sizeof(uint32_t);
4190 uint32_t p = 0;
4191 memcpy(&p, Contents + i, size);
4192 if (i + sizeof(uint32_t) > S.getSize())
4193 outs() << listname << " list pointer extends past end of (" << SegName
4194 << "," << SectName << ") section\n";
4195 uint32_t Address = S.getAddress() + i;
4196 outs() << format("%08" PRIx32"x", Address) << " ";
4197
4198 if (O->isLittleEndian() != sys::IsLittleEndianHost)
4199 sys::swapByteOrder(p);
4200 outs() << format("0x%" PRIx32"x", p);
4201
4202 const char *name = get_symbol_32(i, S, info, p);
4203 if (name != nullptr)
4204 outs() << " " << name;
4205 outs() << "\n";
4206
4207 if (func)
4208 func(p, info);
4209 }
4210}
4211
4212static void print_layout_map(const char *layout_map, uint32_t left) {
4213 if (layout_map == nullptr)
4214 return;
4215 outs() << " layout map: ";
4216 do {
4217 outs() << format("0x%02" PRIx32"x", (*layout_map) & 0xff) << " ";
4218 left--;
4219 layout_map++;
4220 } while (*layout_map != '\0' && left != 0);
4221 outs() << "\n";
4222}
4223
4224static void print_layout_map64(uint64_t p, struct DisassembleInfo *info) {
4225 uint32_t offset, left;
4226 SectionRef S;
4227 const char *layout_map;
4228
4229 if (p == 0)
4230 return;
4231 layout_map = get_pointer_64(p, offset, left, S, info);
4232 print_layout_map(layout_map, left);
4233}
4234
4235static void print_layout_map32(uint32_t p, struct DisassembleInfo *info) {
4236 uint32_t offset, left;
4237 SectionRef S;
4238 const char *layout_map;
4239
4240 if (p == 0)
4241 return;
4242 layout_map = get_pointer_32(p, offset, left, S, info);
4243 print_layout_map(layout_map, left);
4244}
4245
4246static void print_method_list64_t(uint64_t p, struct DisassembleInfo *info,
4247 const char *indent) {
4248 struct method_list64_t ml;
4249 struct method64_t m;
4250 const char *r;
4251 uint32_t offset, xoffset, left, i;
4252 SectionRef S, xS;
4253 const char *name, *sym_name;
4254 uint64_t n_value;
4255
4256 r = get_pointer_64(p, offset, left, S, info);
4257 if (r == nullptr)
4258 return;
4259 memset(&ml, '\0', sizeof(struct method_list64_t));
4260 if (left < sizeof(struct method_list64_t)) {
4261 memcpy(&ml, r, left);
4262 outs() << " (method_list_t entends past the end of the section)\n";
4263 } else
4264 memcpy(&ml, r, sizeof(struct method_list64_t));
4265 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4266 swapStruct(ml);
4267 outs() << indent << "\t\t entsize " << ml.entsize << "\n";
4268 outs() << indent << "\t\t count " << ml.count << "\n";
4269
4270 p += sizeof(struct method_list64_t);
4271 offset += sizeof(struct method_list64_t);
4272 for (i = 0; i < ml.count; i++) {
4273 r = get_pointer_64(p, offset, left, S, info);
4274 if (r == nullptr)
4275 return;
4276 memset(&m, '\0', sizeof(struct method64_t));
4277 if (left < sizeof(struct method64_t)) {
4278 memcpy(&m, r, left);
4279 outs() << indent << " (method_t extends past the end of the section)\n";
4280 } else
4281 memcpy(&m, r, sizeof(struct method64_t));
4282 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4283 swapStruct(m);
4284
4285 outs() << indent << "\t\t name ";
4286 sym_name = get_symbol_64(offset + offsetof(struct method64_t, name)__builtin_offsetof(struct method64_t, name), S,
4287 info, n_value, m.name);
4288 if (n_value != 0) {
4289 if (info->verbose && sym_name != nullptr)
4290 outs() << sym_name;
4291 else
4292 outs() << format("0x%" PRIx64"l" "x", n_value);
4293 if (m.name != 0)
4294 outs() << " + " << format("0x%" PRIx64"l" "x", m.name);
4295 } else
4296 outs() << format("0x%" PRIx64"l" "x", m.name);
4297 name = get_pointer_64(m.name + n_value, xoffset, left, xS, info);
4298 if (name != nullptr)
4299 outs() << format(" %.*s", left, name);
4300 outs() << "\n";
4301
4302 outs() << indent << "\t\t types ";
4303 sym_name = get_symbol_64(offset + offsetof(struct method64_t, types)__builtin_offsetof(struct method64_t, types), S,
4304 info, n_value, m.types);
4305 if (n_value != 0) {
4306 if (info->verbose && sym_name != nullptr)
4307 outs() << sym_name;
4308 else
4309 outs() << format("0x%" PRIx64"l" "x", n_value);
4310 if (m.types != 0)
4311 outs() << " + " << format("0x%" PRIx64"l" "x", m.types);
4312 } else
4313 outs() << format("0x%" PRIx64"l" "x", m.types);
4314 name = get_pointer_64(m.types + n_value, xoffset, left, xS, info);
4315 if (name != nullptr)
4316 outs() << format(" %.*s", left, name);
4317 outs() << "\n";
4318
4319 outs() << indent << "\t\t imp ";
4320 name = get_symbol_64(offset + offsetof(struct method64_t, imp)__builtin_offsetof(struct method64_t, imp), S, info,
4321 n_value, m.imp);
4322 if (info->verbose && name == nullptr) {
4323 if (n_value != 0) {
4324 outs() << format("0x%" PRIx64"l" "x", n_value) << " ";
4325 if (m.imp != 0)
4326 outs() << "+ " << format("0x%" PRIx64"l" "x", m.imp) << " ";
4327 } else
4328 outs() << format("0x%" PRIx64"l" "x", m.imp) << " ";
4329 }
4330 if (name != nullptr)
4331 outs() << name;
4332 outs() << "\n";
4333
4334 p += sizeof(struct method64_t);
4335 offset += sizeof(struct method64_t);
4336 }
4337}
4338
4339static void print_method_list32_t(uint64_t p, struct DisassembleInfo *info,
4340 const char *indent) {
4341 struct method_list32_t ml;
4342 struct method32_t m;
4343 const char *r, *name;
4344 uint32_t offset, xoffset, left, i;
4345 SectionRef S, xS;
4346
4347 r = get_pointer_32(p, offset, left, S, info);
4348 if (r == nullptr)
4349 return;
4350 memset(&ml, '\0', sizeof(struct method_list32_t));
4351 if (left < sizeof(struct method_list32_t)) {
4352 memcpy(&ml, r, left);
4353 outs() << " (method_list_t entends past the end of the section)\n";
4354 } else
4355 memcpy(&ml, r, sizeof(struct method_list32_t));
4356 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4357 swapStruct(ml);
4358 outs() << indent << "\t\t entsize " << ml.entsize << "\n";
4359 outs() << indent << "\t\t count " << ml.count << "\n";
4360
4361 p += sizeof(struct method_list32_t);
4362 offset += sizeof(struct method_list32_t);
4363 for (i = 0; i < ml.count; i++) {
4364 r = get_pointer_32(p, offset, left, S, info);
4365 if (r == nullptr)
4366 return;
4367 memset(&m, '\0', sizeof(struct method32_t));
4368 if (left < sizeof(struct method32_t)) {
4369 memcpy(&ml, r, left);
4370 outs() << indent << " (method_t entends past the end of the section)\n";
4371 } else
4372 memcpy(&m, r, sizeof(struct method32_t));
4373 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4374 swapStruct(m);
4375
4376 outs() << indent << "\t\t name " << format("0x%" PRIx32"x", m.name);
4377 name = get_pointer_32(m.name, xoffset, left, xS, info);
4378 if (name != nullptr)
4379 outs() << format(" %.*s", left, name);
4380 outs() << "\n";
4381
4382 outs() << indent << "\t\t types " << format("0x%" PRIx32"x", m.types);
4383 name = get_pointer_32(m.types, xoffset, left, xS, info);
4384 if (name != nullptr)
4385 outs() << format(" %.*s", left, name);
4386 outs() << "\n";
4387
4388 outs() << indent << "\t\t imp " << format("0x%" PRIx32"x", m.imp);
4389 name = get_symbol_32(offset + offsetof(struct method32_t, imp)__builtin_offsetof(struct method32_t, imp), S, info,
4390 m.imp);
4391 if (name != nullptr)
4392 outs() << " " << name;
4393 outs() << "\n";
4394
4395 p += sizeof(struct method32_t);
4396 offset += sizeof(struct method32_t);
4397 }
4398}
4399
4400static bool print_method_list(uint32_t p, struct DisassembleInfo *info) {
4401 uint32_t offset, left, xleft;
4402 SectionRef S;
4403 struct objc_method_list_t method_list;
4404 struct objc_method_t method;
4405 const char *r, *methods, *name, *SymbolName;
4406 int32_t i;
4407
4408 r = get_pointer_32(p, offset, left, S, info, true);
4409 if (r == nullptr)
4410 return true;
4411
4412 outs() << "\n";
4413 if (left > sizeof(struct objc_method_list_t)) {
4414 memcpy(&method_list, r, sizeof(struct objc_method_list_t));
4415 } else {
4416 outs() << "\t\t objc_method_list extends past end of the section\n";
4417 memset(&method_list, '\0', sizeof(struct objc_method_list_t));
4418 memcpy(&method_list, r, left);
4419 }
4420 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4421 swapStruct(method_list);
4422
4423 outs() << "\t\t obsolete "
4424 << format("0x%08" PRIx32"x", method_list.obsolete) << "\n";
4425 outs() << "\t\t method_count " << method_list.method_count << "\n";
4426
4427 methods = r + sizeof(struct objc_method_list_t);
4428 for (i = 0; i < method_list.method_count; i++) {
4429 if ((i + 1) * sizeof(struct objc_method_t) > left) {
4430 outs() << "\t\t remaining method's extend past the of the section\n";
4431 break;
4432 }
4433 memcpy(&method, methods + i * sizeof(struct objc_method_t),
4434 sizeof(struct objc_method_t));
4435 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4436 swapStruct(method);
4437
4438 outs() << "\t\t method_name "
4439 << format("0x%08" PRIx32"x", method.method_name);
4440 if (info->verbose) {
4441 name = get_pointer_32(method.method_name, offset, xleft, S, info, true);
4442 if (name != nullptr)
4443 outs() << format(" %.*s", xleft, name);
4444 else
4445 outs() << " (not in an __OBJC section)";
4446 }
4447 outs() << "\n";
4448
4449 outs() << "\t\t method_types "
4450 << format("0x%08" PRIx32"x", method.method_types);
4451 if (info->verbose) {
4452 name = get_pointer_32(method.method_types, offset, xleft, S, info, true);
4453 if (name != nullptr)
4454 outs() << format(" %.*s", xleft, name);
4455 else
4456 outs() << " (not in an __OBJC section)";
4457 }
4458 outs() << "\n";
4459
4460 outs() << "\t\t method_imp "
4461 << format("0x%08" PRIx32"x", method.method_imp) << " ";
4462 if (info->verbose) {
4463 SymbolName = GuessSymbolName(method.method_imp, info->AddrMap);
4464 if (SymbolName != nullptr)
4465 outs() << SymbolName;
4466 }
4467 outs() << "\n";
4468 }
4469 return false;
4470}
4471
4472static void print_protocol_list64_t(uint64_t p, struct DisassembleInfo *info) {
4473 struct protocol_list64_t pl;
4474 uint64_t q, n_value;
4475 struct protocol64_t pc;
4476 const char *r;
4477 uint32_t offset, xoffset, left, i;
4478 SectionRef S, xS;
4479 const char *name, *sym_name;
4480
4481 r = get_pointer_64(p, offset, left, S, info);
4482 if (r == nullptr)
4483 return;
4484 memset(&pl, '\0', sizeof(struct protocol_list64_t));
4485 if (left < sizeof(struct protocol_list64_t)) {
4486 memcpy(&pl, r, left);
4487 outs() << " (protocol_list_t entends past the end of the section)\n";
4488 } else
4489 memcpy(&pl, r, sizeof(struct protocol_list64_t));
4490 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4491 swapStruct(pl);
4492 outs() << " count " << pl.count << "\n";
4493
4494 p += sizeof(struct protocol_list64_t);
4495 offset += sizeof(struct protocol_list64_t);
4496 for (i = 0; i < pl.count; i++) {
4497 r = get_pointer_64(p, offset, left, S, info);
4498 if (r == nullptr)
4499 return;
4500 q = 0;
4501 if (left < sizeof(uint64_t)) {
4502 memcpy(&q, r, left);
4503 outs() << " (protocol_t * entends past the end of the section)\n";
4504 } else
4505 memcpy(&q, r, sizeof(uint64_t));
4506 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4507 sys::swapByteOrder(q);
4508
4509 outs() << "\t\t list[" << i << "] ";
4510 sym_name = get_symbol_64(offset, S, info, n_value, q);
4511 if (n_value != 0) {
4512 if (info->verbose && sym_name != nullptr)
4513 outs() << sym_name;
4514 else
4515 outs() << format("0x%" PRIx64"l" "x", n_value);
4516 if (q != 0)
4517 outs() << " + " << format("0x%" PRIx64"l" "x", q);
4518 } else
4519 outs() << format("0x%" PRIx64"l" "x", q);
4520 outs() << " (struct protocol_t *)\n";
4521
4522 r = get_pointer_64(q + n_value, offset, left, S, info);
4523 if (r == nullptr)
4524 return;
4525 memset(&pc, '\0', sizeof(struct protocol64_t));
4526 if (left < sizeof(struct protocol64_t)) {
4527 memcpy(&pc, r, left);
4528 outs() << " (protocol_t entends past the end of the section)\n";
4529 } else
4530 memcpy(&pc, r, sizeof(struct protocol64_t));
4531 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4532 swapStruct(pc);
4533
4534 outs() << "\t\t\t isa " << format("0x%" PRIx64"l" "x", pc.isa) << "\n";
4535
4536 outs() << "\t\t\t name ";
4537 sym_name = get_symbol_64(offset + offsetof(struct protocol64_t, name)__builtin_offsetof(struct protocol64_t, name), S,
4538 info, n_value, pc.name);
4539 if (n_value != 0) {
4540 if (info->verbose && sym_name != nullptr)
4541 outs() << sym_name;
4542 else
4543 outs() << format("0x%" PRIx64"l" "x", n_value);
4544 if (pc.name != 0)
4545 outs() << " + " << format("0x%" PRIx64"l" "x", pc.name);
4546 } else
4547 outs() << format("0x%" PRIx64"l" "x", pc.name);
4548 name = get_pointer_64(pc.name + n_value, xoffset, left, xS, info);
4549 if (name != nullptr)
4550 outs() << format(" %.*s", left, name);
4551 outs() << "\n";
4552
4553 outs() << "\t\t\tprotocols " << format("0x%" PRIx64"l" "x", pc.protocols) << "\n";
4554
4555 outs() << "\t\t instanceMethods ";
4556 sym_name =
4557 get_symbol_64(offset + offsetof(struct protocol64_t, instanceMethods)__builtin_offsetof(struct protocol64_t, instanceMethods),
4558 S, info, n_value, pc.instanceMethods);
4559 if (n_value != 0) {
4560 if (info->verbose && sym_name != nullptr)
4561 outs() << sym_name;
4562 else
4563 outs() << format("0x%" PRIx64"l" "x", n_value);
4564 if (pc.instanceMethods != 0)
4565 outs() << " + " << format("0x%" PRIx64"l" "x", pc.instanceMethods);
4566 } else
4567 outs() << format("0x%" PRIx64"l" "x", pc.instanceMethods);
4568 outs() << " (struct method_list_t *)\n";
4569 if (pc.instanceMethods + n_value != 0)
4570 print_method_list64_t(pc.instanceMethods + n_value, info, "\t");
4571
4572 outs() << "\t\t classMethods ";
4573 sym_name =
4574 get_symbol_64(offset + offsetof(struct protocol64_t, classMethods)__builtin_offsetof(struct protocol64_t, classMethods), S,
4575 info, n_value, pc.classMethods);
4576 if (n_value != 0) {
4577 if (info->verbose && sym_name != nullptr)
4578 outs() << sym_name;
4579 else
4580 outs() << format("0x%" PRIx64"l" "x", n_value);
4581 if (pc.classMethods != 0)
4582 outs() << " + " << format("0x%" PRIx64"l" "x", pc.classMethods);
4583 } else
4584 outs() << format("0x%" PRIx64"l" "x", pc.classMethods);
4585 outs() << " (struct method_list_t *)\n";
4586 if (pc.classMethods + n_value != 0)
4587 print_method_list64_t(pc.classMethods + n_value, info, "\t");
4588
4589 outs() << "\t optionalInstanceMethods "
4590 << format("0x%" PRIx64"l" "x", pc.optionalInstanceMethods) << "\n";
4591 outs() << "\t optionalClassMethods "
4592 << format("0x%" PRIx64"l" "x", pc.optionalClassMethods) << "\n";
4593 outs() << "\t instanceProperties "
4594 << format("0x%" PRIx64"l" "x", pc.instanceProperties) << "\n";
4595
4596 p += sizeof(uint64_t);
4597 offset += sizeof(uint64_t);
4598 }
4599}
4600
4601static void print_protocol_list32_t(uint32_t p, struct DisassembleInfo *info) {
4602 struct protocol_list32_t pl;
4603 uint32_t q;
4604 struct protocol32_t pc;
4605 const char *r;
4606 uint32_t offset, xoffset, left, i;
4607 SectionRef S, xS;
4608 const char *name;
4609
4610 r = get_pointer_32(p, offset, left, S, info);
4611 if (r == nullptr)
4612 return;
4613 memset(&pl, '\0', sizeof(struct protocol_list32_t));
4614 if (left < sizeof(struct protocol_list32_t)) {
4615 memcpy(&pl, r, left);
4616 outs() << " (protocol_list_t entends past the end of the section)\n";
4617 } else
4618 memcpy(&pl, r, sizeof(struct protocol_list32_t));
4619 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4620 swapStruct(pl);
4621 outs() << " count " << pl.count << "\n";
4622
4623 p += sizeof(struct protocol_list32_t);
4624 offset += sizeof(struct protocol_list32_t);
4625 for (i = 0; i < pl.count; i++) {
4626 r = get_pointer_32(p, offset, left, S, info);
4627 if (r == nullptr)
4628 return;
4629 q = 0;
4630 if (left < sizeof(uint32_t)) {
4631 memcpy(&q, r, left);
4632 outs() << " (protocol_t * entends past the end of the section)\n";
4633 } else
4634 memcpy(&q, r, sizeof(uint32_t));
4635 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4636 sys::swapByteOrder(q);
4637 outs() << "\t\t list[" << i << "] " << format("0x%" PRIx32"x", q)
4638 << " (struct protocol_t *)\n";
4639 r = get_pointer_32(q, offset, left, S, info);
4640 if (r == nullptr)
4641 return;
4642 memset(&pc, '\0', sizeof(struct protocol32_t));
4643 if (left < sizeof(struct protocol32_t)) {
4644 memcpy(&pc, r, left);
4645 outs() << " (protocol_t entends past the end of the section)\n";
4646 } else
4647 memcpy(&pc, r, sizeof(struct protocol32_t));
4648 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4649 swapStruct(pc);
4650 outs() << "\t\t\t isa " << format("0x%" PRIx32"x", pc.isa) << "\n";
4651 outs() << "\t\t\t name " << format("0x%" PRIx32"x", pc.name);
4652 name = get_pointer_32(pc.name, xoffset, left, xS, info);
4653 if (name != nullptr)
4654 outs() << format(" %.*s", left, name);
4655 outs() << "\n";
4656 outs() << "\t\t\tprotocols " << format("0x%" PRIx32"x", pc.protocols) << "\n";
4657 outs() << "\t\t instanceMethods "
4658 << format("0x%" PRIx32"x", pc.instanceMethods)
4659 << " (struct method_list_t *)\n";
4660 if (pc.instanceMethods != 0)
4661 print_method_list32_t(pc.instanceMethods, info, "\t");
4662 outs() << "\t\t classMethods " << format("0x%" PRIx32"x", pc.classMethods)
4663 << " (struct method_list_t *)\n";
4664 if (pc.classMethods != 0)
4665 print_method_list32_t(pc.classMethods, info, "\t");
4666 outs() << "\t optionalInstanceMethods "
4667 << format("0x%" PRIx32"x", pc.optionalInstanceMethods) << "\n";
4668 outs() << "\t optionalClassMethods "
4669 << format("0x%" PRIx32"x", pc.optionalClassMethods) << "\n";
4670 outs() << "\t instanceProperties "
4671 << format("0x%" PRIx32"x", pc.instanceProperties) << "\n";
4672 p += sizeof(uint32_t);
4673 offset += sizeof(uint32_t);
4674 }
4675}
4676
4677static void print_indent(uint32_t indent) {
4678 for (uint32_t i = 0; i < indent;) {
4679 if (indent - i >= 8) {
4680 outs() << "\t";
4681 i += 8;
4682 } else {
4683 for (uint32_t j = i; j < indent; j++)
4684 outs() << " ";
4685 return;
4686 }
4687 }
4688}
4689
4690static bool print_method_description_list(uint32_t p, uint32_t indent,
4691 struct DisassembleInfo *info) {
4692 uint32_t offset, left, xleft;
4693 SectionRef S;
4694 struct objc_method_description_list_t mdl;
4695 struct objc_method_description_t md;
4696 const char *r, *list, *name;
4697 int32_t i;
4698
4699 r = get_pointer_32(p, offset, left, S, info, true);
4700 if (r == nullptr)
4701 return true;
4702
4703 outs() << "\n";
4704 if (left > sizeof(struct objc_method_description_list_t)) {
4705 memcpy(&mdl, r, sizeof(struct objc_method_description_list_t));
4706 } else {
4707 print_indent(indent);
4708 outs() << " objc_method_description_list extends past end of the section\n";
4709 memset(&mdl, '\0', sizeof(struct objc_method_description_list_t));
4710 memcpy(&mdl, r, left);
4711 }
4712 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4713 swapStruct(mdl);
4714
4715 print_indent(indent);
4716 outs() << " count " << mdl.count << "\n";
4717
4718 list = r + sizeof(struct objc_method_description_list_t);
4719 for (i = 0; i < mdl.count; i++) {
4720 if ((i + 1) * sizeof(struct objc_method_description_t) > left) {
4721 print_indent(indent);
4722 outs() << " remaining list entries extend past the of the section\n";
4723 break;
4724 }
4725 print_indent(indent);
4726 outs() << " list[" << i << "]\n";
4727 memcpy(&md, list + i * sizeof(struct objc_method_description_t),
4728 sizeof(struct objc_method_description_t));
4729 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4730 swapStruct(md);
4731
4732 print_indent(indent);
4733 outs() << " name " << format("0x%08" PRIx32"x", md.name);
4734 if (info->verbose) {
4735 name = get_pointer_32(md.name, offset, xleft, S, info, true);
4736 if (name != nullptr)
4737 outs() << format(" %.*s", xleft, name);
4738 else
4739 outs() << " (not in an __OBJC section)";
4740 }
4741 outs() << "\n";
4742
4743 print_indent(indent);
4744 outs() << " types " << format("0x%08" PRIx32"x", md.types);
4745 if (info->verbose) {
4746 name = get_pointer_32(md.types, offset, xleft, S, info, true);
4747 if (name != nullptr)
4748 outs() << format(" %.*s", xleft, name);
4749 else
4750 outs() << " (not in an __OBJC section)";
4751 }
4752 outs() << "\n";
4753 }
4754 return false;
4755}
4756
4757static bool print_protocol_list(uint32_t p, uint32_t indent,
4758 struct DisassembleInfo *info);
4759
4760static bool print_protocol(uint32_t p, uint32_t indent,
4761 struct DisassembleInfo *info) {
4762 uint32_t offset, left;
4763 SectionRef S;
4764 struct objc_protocol_t protocol;
4765 const char *r, *name;
4766
4767 r = get_pointer_32(p, offset, left, S, info, true);
4768 if (r == nullptr)
4769 return true;
4770
4771 outs() << "\n";
4772 if (left >= sizeof(struct objc_protocol_t)) {
4773 memcpy(&protocol, r, sizeof(struct objc_protocol_t));
4774 } else {
4775 print_indent(indent);
4776 outs() << " Protocol extends past end of the section\n";
4777 memset(&protocol, '\0', sizeof(struct objc_protocol_t));
4778 memcpy(&protocol, r, left);
4779 }
4780 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4781 swapStruct(protocol);
4782
4783 print_indent(indent);
4784 outs() << " isa " << format("0x%08" PRIx32"x", protocol.isa)
4785 << "\n";
4786
4787 print_indent(indent);
4788 outs() << " protocol_name "
4789 << format("0x%08" PRIx32"x", protocol.protocol_name);
4790 if (info->verbose) {
4791 name = get_pointer_32(protocol.protocol_name, offset, left, S, info, true);
4792 if (name != nullptr)
4793 outs() << format(" %.*s", left, name);
4794 else
4795 outs() << " (not in an __OBJC section)";
4796 }
4797 outs() << "\n";
4798
4799 print_indent(indent);
4800 outs() << " protocol_list "
4801 << format("0x%08" PRIx32"x", protocol.protocol_list);
4802 if (print_protocol_list(protocol.protocol_list, indent + 4, info))
4803 outs() << " (not in an __OBJC section)\n";
4804
4805 print_indent(indent);
4806 outs() << " instance_methods "
4807 << format("0x%08" PRIx32"x", protocol.instance_methods);
4808 if (print_method_description_list(protocol.instance_methods, indent, info))
4809 outs() << " (not in an __OBJC section)\n";
4810
4811 print_indent(indent);
4812 outs() << " class_methods "
4813 << format("0x%08" PRIx32"x", protocol.class_methods);
4814 if (print_method_description_list(protocol.class_methods, indent, info))
4815 outs() << " (not in an __OBJC section)\n";
4816
4817 return false;
4818}
4819
4820static bool print_protocol_list(uint32_t p, uint32_t indent,
4821 struct DisassembleInfo *info) {
4822 uint32_t offset, left, l;
4823 SectionRef S;
4824 struct objc_protocol_list_t protocol_list;
4825 const char *r, *list;
4826 int32_t i;
4827
4828 r = get_pointer_32(p, offset, left, S, info, true);
4829 if (r == nullptr)
4830 return true;
4831
4832 outs() << "\n";
4833 if (left > sizeof(struct objc_protocol_list_t)) {
4834 memcpy(&protocol_list, r, sizeof(struct objc_protocol_list_t));
4835 } else {
4836 outs() << "\t\t objc_protocol_list_t extends past end of the section\n";
4837 memset(&protocol_list, '\0', sizeof(struct objc_protocol_list_t));
4838 memcpy(&protocol_list, r, left);
4839 }
4840 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4841 swapStruct(protocol_list);
4842
4843 print_indent(indent);
4844 outs() << " next " << format("0x%08" PRIx32"x", protocol_list.next)
4845 << "\n";
4846 print_indent(indent);
4847 outs() << " count " << protocol_list.count << "\n";
4848
4849 list = r + sizeof(struct objc_protocol_list_t);
4850 for (i = 0; i < protocol_list.count; i++) {
4851 if ((i + 1) * sizeof(uint32_t) > left) {
4852 outs() << "\t\t remaining list entries extend past the of the section\n";
4853 break;
4854 }
4855 memcpy(&l, list + i * sizeof(uint32_t), sizeof(uint32_t));
4856 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4857 sys::swapByteOrder(l);
4858
4859 print_indent(indent);
4860 outs() << " list[" << i << "] " << format("0x%08" PRIx32"x", l);
4861 if (print_protocol(l, indent, info))
4862 outs() << "(not in an __OBJC section)\n";
4863 }
4864 return false;
4865}
4866
4867static void print_ivar_list64_t(uint64_t p, struct DisassembleInfo *info) {
4868 struct ivar_list64_t il;
4869 struct ivar64_t i;
4870 const char *r;
4871 uint32_t offset, xoffset, left, j;
4872 SectionRef S, xS;
4873 const char *name, *sym_name, *ivar_offset_p;
4874 uint64_t ivar_offset, n_value;
4875
4876 r = get_pointer_64(p, offset, left, S, info);
4877 if (r == nullptr)
4878 return;
4879 memset(&il, '\0', sizeof(struct ivar_list64_t));
4880 if (left < sizeof(struct ivar_list64_t)) {
4881 memcpy(&il, r, left);
4882 outs() << " (ivar_list_t entends past the end of the section)\n";
4883 } else
4884 memcpy(&il, r, sizeof(struct ivar_list64_t));
4885 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4886 swapStruct(il);
4887 outs() << " entsize " << il.entsize << "\n";
4888 outs() << " count " << il.count << "\n";
4889
4890 p += sizeof(struct ivar_list64_t);
4891 offset += sizeof(struct ivar_list64_t);
4892 for (j = 0; j < il.count; j++) {
4893 r = get_pointer_64(p, offset, left, S, info);
4894 if (r == nullptr)
4895 return;
4896 memset(&i, '\0', sizeof(struct ivar64_t));
4897 if (left < sizeof(struct ivar64_t)) {
4898 memcpy(&i, r, left);
4899 outs() << " (ivar_t entends past the end of the section)\n";
4900 } else
4901 memcpy(&i, r, sizeof(struct ivar64_t));
4902 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4903 swapStruct(i);
4904
4905 outs() << "\t\t\t offset ";
4906 sym_name = get_symbol_64(offset + offsetof(struct ivar64_t, offset)__builtin_offsetof(struct ivar64_t, offset), S,
4907 info, n_value, i.offset);
4908 if (n_value != 0) {
4909 if (info->verbose && sym_name != nullptr)
4910 outs() << sym_name;
4911 else
4912 outs() << format("0x%" PRIx64"l" "x", n_value);
4913 if (i.offset != 0)
4914 outs() << " + " << format("0x%" PRIx64"l" "x", i.offset);
4915 } else
4916 outs() << format("0x%" PRIx64"l" "x", i.offset);
4917 ivar_offset_p = get_pointer_64(i.offset + n_value, xoffset, left, xS, info);
4918 if (ivar_offset_p != nullptr && left >= sizeof(*ivar_offset_p)) {
4919 memcpy(&ivar_offset, ivar_offset_p, sizeof(ivar_offset));
4920 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4921 sys::swapByteOrder(ivar_offset);
4922 outs() << " " << ivar_offset << "\n";
4923 } else
4924 outs() << "\n";
4925
4926 outs() << "\t\t\t name ";
4927 sym_name = get_symbol_64(offset + offsetof(struct ivar64_t, name)__builtin_offsetof(struct ivar64_t, name), S, info,
4928 n_value, i.name);
4929 if (n_value != 0) {
4930 if (info->verbose && sym_name != nullptr)
4931 outs() << sym_name;
4932 else
4933 outs() << format("0x%" PRIx64"l" "x", n_value);
4934 if (i.name != 0)
4935 outs() << " + " << format("0x%" PRIx64"l" "x", i.name);
4936 } else
4937 outs() << format("0x%" PRIx64"l" "x", i.name);
4938 name = get_pointer_64(i.name + n_value, xoffset, left, xS, info);
4939 if (name != nullptr)
4940 outs() << format(" %.*s", left, name);
4941 outs() << "\n";
4942
4943 outs() << "\t\t\t type ";
4944 sym_name = get_symbol_64(offset + offsetof(struct ivar64_t, type)__builtin_offsetof(struct ivar64_t, type), S, info,
4945 n_value, i.name);
4946 name = get_pointer_64(i.type + n_value, xoffset, left, xS, info);
4947 if (n_value != 0) {
4948 if (info->verbose && sym_name != nullptr)
4949 outs() << sym_name;
4950 else
4951 outs() << format("0x%" PRIx64"l" "x", n_value);
4952 if (i.type != 0)
4953 outs() << " + " << format("0x%" PRIx64"l" "x", i.type);
4954 } else
4955 outs() << format("0x%" PRIx64"l" "x", i.type);
4956 if (name != nullptr)
4957 outs() << format(" %.*s", left, name);
4958 outs() << "\n";
4959
4960 outs() << "\t\t\talignment " << i.alignment << "\n";
4961 outs() << "\t\t\t size " << i.size << "\n";
4962
4963 p += sizeof(struct ivar64_t);
4964 offset += sizeof(struct ivar64_t);
4965 }
4966}
4967
4968static void print_ivar_list32_t(uint32_t p, struct DisassembleInfo *info) {
4969 struct ivar_list32_t il;
4970 struct ivar32_t i;
4971 const char *r;
4972 uint32_t offset, xoffset, left, j;
4973 SectionRef S, xS;
4974 const char *name, *ivar_offset_p;
4975 uint32_t ivar_offset;
4976
4977 r = get_pointer_32(p, offset, left, S, info);
4978 if (r == nullptr)
4979 return;
4980 memset(&il, '\0', sizeof(struct ivar_list32_t));
4981 if (left < sizeof(struct ivar_list32_t)) {
4982 memcpy(&il, r, left);
4983 outs() << " (ivar_list_t entends past the end of the section)\n";
4984 } else
4985 memcpy(&il, r, sizeof(struct ivar_list32_t));
4986 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4987 swapStruct(il);
4988 outs() << " entsize " << il.entsize << "\n";
4989 outs() << " count " << il.count << "\n";
4990
4991 p += sizeof(struct ivar_list32_t);
4992 offset += sizeof(struct ivar_list32_t);
4993 for (j = 0; j < il.count; j++) {
4994 r = get_pointer_32(p, offset, left, S, info);
4995 if (r == nullptr)
4996 return;
4997 memset(&i, '\0', sizeof(struct ivar32_t));
4998 if (left < sizeof(struct ivar32_t)) {
4999 memcpy(&i, r, left);
5000 outs() << " (ivar_t entends past the end of the section)\n";
5001 } else
5002 memcpy(&i, r, sizeof(struct ivar32_t));
5003 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5004 swapStruct(i);
5005
5006 outs() << "\t\t\t offset " << format("0x%" PRIx32"x", i.offset);
5007 ivar_offset_p = get_pointer_32(i.offset, xoffset, left, xS, info);
5008 if (ivar_offset_p != nullptr && left >= sizeof(*ivar_offset_p)) {
5009 memcpy(&ivar_offset, ivar_offset_p, sizeof(ivar_offset));
5010 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5011 sys::swapByteOrder(ivar_offset);
5012 outs() << " " << ivar_offset << "\n";
5013 } else
5014 outs() << "\n";
5015
5016 outs() << "\t\t\t name " << format("0x%" PRIx32"x", i.name);
5017 name = get_pointer_32(i.name, xoffset, left, xS, info);
5018 if (name != nullptr)
5019 outs() << format(" %.*s", left, name);
5020 outs() << "\n";
5021
5022 outs() << "\t\t\t type " << format("0x%" PRIx32"x", i.type);
5023 name = get_pointer_32(i.type, xoffset, left, xS, info);
5024 if (name != nullptr)
5025 outs() << format(" %.*s", left, name);
5026 outs() << "\n";
5027
5028 outs() << "\t\t\talignment " << i.alignment << "\n";
5029 outs() << "\t\t\t size " << i.size << "\n";
5030
5031 p += sizeof(struct ivar32_t);
5032 offset += sizeof(struct ivar32_t);
5033 }
5034}
5035
5036static void print_objc_property_list64(uint64_t p,
5037 struct DisassembleInfo *info) {
5038 struct objc_property_list64 opl;
5039 struct objc_property64 op;
5040 const char *r;
5041 uint32_t offset, xoffset, left, j;
5042 SectionRef S, xS;
5043 const char *name, *sym_name;
5044 uint64_t n_value;
5045
5046 r = get_pointer_64(p, offset, left, S, info);
5047 if (r == nullptr)
5048 return;
5049 memset(&opl, '\0', sizeof(struct objc_property_list64));
5050 if (left < sizeof(struct objc_property_list64)) {
5051 memcpy(&opl, r, left);
5052 outs() << " (objc_property_list entends past the end of the section)\n";
5053 } else
5054 memcpy(&opl, r, sizeof(struct objc_property_list64));
5055 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5056 swapStruct(opl);
5057 outs() << " entsize " << opl.entsize << "\n";
5058 outs() << " count " << opl.count << "\n";
5059
5060 p += sizeof(struct objc_property_list64);
5061 offset += sizeof(struct objc_property_list64);
5062 for (j = 0; j < opl.count; j++) {
5063 r = get_pointer_64(p, offset, left, S, info);
5064 if (r == nullptr)
5065 return;
5066 memset(&op, '\0', sizeof(struct objc_property64));
5067 if (left < sizeof(struct objc_property64)) {
5068 memcpy(&op, r, left);
5069 outs() << " (objc_property entends past the end of the section)\n";
5070 } else
5071 memcpy(&op, r, sizeof(struct objc_property64));
5072 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5073 swapStruct(op);
5074
5075 outs() << "\t\t\t name ";
5076 sym_name = get_symbol_64(offset + offsetof(struct objc_property64, name)__builtin_offsetof(struct objc_property64, name), S,
5077 info, n_value, op.name);
5078 if (n_value != 0) {
5079 if (info->verbose && sym_name != nullptr)
5080 outs() << sym_name;
5081 else
5082 outs() << format("0x%" PRIx64"l" "x", n_value);
5083 if (op.name != 0)
5084 outs() << " + " << format("0x%" PRIx64"l" "x", op.name);
5085 } else
5086 outs() << format("0x%" PRIx64"l" "x", op.name);
5087 name = get_pointer_64(op.name + n_value, xoffset, left, xS, info);
5088 if (name != nullptr)
5089 outs() << format(" %.*s", left, name);
5090 outs() << "\n";
5091
5092 outs() << "\t\t\tattributes ";
5093 sym_name =
5094 get_symbol_64(offset + offsetof(struct objc_property64, attributes)__builtin_offsetof(struct objc_property64, attributes), S,
5095 info, n_value, op.attributes);
5096 if (n_value != 0) {
5097 if (info->verbose && sym_name != nullptr)
5098 outs() << sym_name;
5099 else
5100 outs() << format("0x%" PRIx64"l" "x", n_value);
5101 if (op.attributes != 0)
5102 outs() << " + " << format("0x%" PRIx64"l" "x", op.attributes);
5103 } else
5104 outs() << format("0x%" PRIx64"l" "x", op.attributes);
5105 name = get_pointer_64(op.attributes + n_value, xoffset, left, xS, info);
5106 if (name != nullptr)
5107 outs() << format(" %.*s", left, name);
5108 outs() << "\n";
5109
5110 p += sizeof(struct objc_property64);
5111 offset += sizeof(struct objc_property64);
5112 }
5113}
5114
5115static void print_objc_property_list32(uint32_t p,
5116 struct DisassembleInfo *info) {
5117 struct objc_property_list32 opl;
5118 struct objc_property32 op;
5119 const char *r;
5120 uint32_t offset, xoffset, left, j;
5121 SectionRef S, xS;
5122 const char *name;
5123
5124 r = get_pointer_32(p, offset, left, S, info);
5125 if (r == nullptr)
5126 return;
5127 memset(&opl, '\0', sizeof(struct objc_property_list32));
5128 if (left < sizeof(struct objc_property_list32)) {
5129 memcpy(&opl, r, left);
5130 outs() << " (objc_property_list entends past the end of the section)\n";
5131 } else
5132 memcpy(&opl, r, sizeof(struct objc_property_list32));
5133 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5134 swapStruct(opl);
5135 outs() << " entsize " << opl.entsize << "\n";
5136 outs() << " count " << opl.count << "\n";
5137
5138 p += sizeof(struct objc_property_list32);
5139 offset += sizeof(struct objc_property_list32);
5140 for (j = 0; j < opl.count; j++) {
5141 r = get_pointer_32(p, offset, left, S, info);
5142 if (r == nullptr)
5143 return;
5144 memset(&op, '\0', sizeof(struct objc_property32));
5145 if (left < sizeof(struct objc_property32)) {
5146 memcpy(&op, r, left);
5147 outs() << " (objc_property entends past the end of the section)\n";
5148 } else
5149 memcpy(&op, r, sizeof(struct objc_property32));
5150 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5151 swapStruct(op);
5152
5153 outs() << "\t\t\t name " << format("0x%" PRIx32"x", op.name);
5154 name = get_pointer_32(op.name, xoffset, left, xS, info);
5155 if (name != nullptr)
5156 outs() << format(" %.*s", left, name);
5157 outs() << "\n";
5158
5159 outs() << "\t\t\tattributes " << format("0x%" PRIx32"x", op.attributes);
5160 name = get_pointer_32(op.attributes, xoffset, left, xS, info);
5161 if (name != nullptr)
5162 outs() << format(" %.*s", left, name);
5163 outs() << "\n";
5164
5165 p += sizeof(struct objc_property32);
5166 offset += sizeof(struct objc_property32);
5167 }
5168}
5169
5170static bool print_class_ro64_t(uint64_t p, struct DisassembleInfo *info,
5171 bool &is_meta_class) {
5172 struct class_ro64_t cro;
5173 const char *r;
5174 uint32_t offset, xoffset, left;
5175 SectionRef S, xS;
5176 const char *name, *sym_name;
5177 uint64_t n_value;
5178
5179 r = get_pointer_64(p, offset, left, S, info);
5180 if (r == nullptr || left < sizeof(struct class_ro64_t))
5181 return false;
5182 memcpy(&cro, r, sizeof(struct class_ro64_t));
5183 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5184 swapStruct(cro);
5185 outs() << " flags " << format("0x%" PRIx32"x", cro.flags);
5186 if (cro.flags & RO_META(1 << 0))
5187 outs() << " RO_META";
5188 if (cro.flags & RO_ROOT(1 << 1))
5189 outs() << " RO_ROOT";
5190 if (cro.flags & RO_HAS_CXX_STRUCTORS(1 << 2))
5191 outs() << " RO_HAS_CXX_STRUCTORS";
5192 outs() << "\n";
5193 outs() << " instanceStart " << cro.instanceStart << "\n";
5194 outs() << " instanceSize " << cro.instanceSize << "\n";
5195 outs() << " reserved " << format("0x%" PRIx32"x", cro.reserved)
5196 << "\n";
5197 outs() << " ivarLayout " << format("0x%" PRIx64"l" "x", cro.ivarLayout)
5198 << "\n";
5199 print_layout_map64(cro.ivarLayout, info);
5200
5201 outs() << " name ";
5202 sym_name = get_symbol_64(offset + offsetof(struct class_ro64_t, name)__builtin_offsetof(struct class_ro64_t, name), S,
5203 info, n_value, cro.name);
5204 if (n_value != 0) {
5205 if (info->verbose && sym_name != nullptr)
5206 outs() << sym_name;
5207 else
5208 outs() << format("0x%" PRIx64"l" "x", n_value);
5209 if (cro.name != 0)
5210 outs() << " + " << format("0x%" PRIx64"l" "x", cro.name);
5211 } else
5212 outs() << format("0x%" PRIx64"l" "x", cro.name);
5213 name = get_pointer_64(cro.name + n_value, xoffset, left, xS, info);
5214 if (name != nullptr)
5215 outs() << format(" %.*s", left, name);
5216 outs() << "\n";
5217
5218 outs() << " baseMethods ";
5219 sym_name = get_symbol_64(offset + offsetof(struct class_ro64_t, baseMethods)__builtin_offsetof(struct class_ro64_t, baseMethods),
5220 S, info, n_value, cro.baseMethods);
5221 if (n_value != 0) {
5222 if (info->verbose && sym_name != nullptr)
5223 outs() << sym_name;
5224 else
5225 outs() << format("0x%" PRIx64"l" "x", n_value);
5226 if (cro.baseMethods != 0)
5227 outs() << " + " << format("0x%" PRIx64"l" "x", cro.baseMethods);
5228 } else
5229 outs() << format("0x%" PRIx64"l" "x", cro.baseMethods);
5230 outs() << " (struct method_list_t *)\n";
5231 if (cro.baseMethods + n_value != 0)
5232 print_method_list64_t(cro.baseMethods + n_value, info, "");
5233
5234 outs() << " baseProtocols ";
5235 sym_name =
5236 get_symbol_64(offset + offsetof(struct class_ro64_t, baseProtocols)__builtin_offsetof(struct class_ro64_t, baseProtocols), S,
5237 info, n_value, cro.baseProtocols);
5238 if (n_value != 0) {
5239 if (info->verbose && sym_name != nullptr)
5240 outs() << sym_name;
5241 else
5242 outs() << format("0x%" PRIx64"l" "x", n_value);
5243 if (cro.baseProtocols != 0)
5244 outs() << " + " << format("0x%" PRIx64"l" "x", cro.baseProtocols);
5245 } else
5246 outs() << format("0x%" PRIx64"l" "x", cro.baseProtocols);
5247 outs() << "\n";
5248 if (cro.baseProtocols + n_value != 0)
5249 print_protocol_list64_t(cro.baseProtocols + n_value, info);
5250
5251 outs() << " ivars ";
5252 sym_name = get_symbol_64(offset + offsetof(struct class_ro64_t, ivars)__builtin_offsetof(struct class_ro64_t, ivars), S,
5253 info, n_value, cro.ivars);
5254 if (n_value != 0) {
5255 if (info->verbose && sym_name != nullptr)
5256 outs() << sym_name;
5257 else
5258 outs() << format("0x%" PRIx64"l" "x", n_value);
5259 if (cro.ivars != 0)
5260 outs() << " + " << format("0x%" PRIx64"l" "x", cro.ivars);
5261 } else
5262 outs() << format("0x%" PRIx64"l" "x", cro.ivars);
5263 outs() << "\n";
5264 if (cro.ivars + n_value != 0)
5265 print_ivar_list64_t(cro.ivars + n_value, info);
5266
5267 outs() << " weakIvarLayout ";
5268 sym_name =
5269 get_symbol_64(offset + offsetof(struct class_ro64_t, weakIvarLayout)__builtin_offsetof(struct class_ro64_t, weakIvarLayout), S,
5270 info, n_value, cro.weakIvarLayout);
5271 if (n_value != 0) {
5272 if (info->verbose && sym_name != nullptr)
5273 outs() << sym_name;
5274 else
5275 outs() << format("0x%" PRIx64"l" "x", n_value);
5276 if (cro.weakIvarLayout != 0)
5277 outs() << " + " << format("0x%" PRIx64"l" "x", cro.weakIvarLayout);
5278 } else
5279 outs() << format("0x%" PRIx64"l" "x", cro.weakIvarLayout);
5280 outs() << "\n";
5281 print_layout_map64(cro.weakIvarLayout + n_value, info);
5282
5283 outs() << " baseProperties ";
5284 sym_name =
5285 get_symbol_64(offset + offsetof(struct class_ro64_t, baseProperties)__builtin_offsetof(struct class_ro64_t, baseProperties), S,
5286 info, n_value, cro.baseProperties);
5287 if (n_value != 0) {
5288 if (info->verbose && sym_name != nullptr)
5289 outs() << sym_name;
5290 else
5291 outs() << format("0x%" PRIx64"l" "x", n_value);
5292 if (cro.baseProperties != 0)
5293 outs() << " + " << format("0x%" PRIx64"l" "x", cro.baseProperties);
5294 } else
5295 outs() << format("0x%" PRIx64"l" "x", cro.baseProperties);
5296 outs() << "\n";
5297 if (cro.baseProperties + n_value != 0)
5298 print_objc_property_list64(cro.baseProperties + n_value, info);
5299
5300 is_meta_class = (cro.flags & RO_META(1 << 0)) != 0;
5301 return true;
5302}
5303
5304static bool print_class_ro32_t(uint32_t p, struct DisassembleInfo *info,
5305 bool &is_meta_class) {
5306 struct class_ro32_t cro;
5307 const char *r;
5308 uint32_t offset, xoffset, left;
5309 SectionRef S, xS;
5310 const char *name;
5311
5312 r = get_pointer_32(p, offset, left, S, info);
5313 if (r == nullptr)
5314 return false;
5315 memset(&cro, '\0', sizeof(struct class_ro32_t));
5316 if (left < sizeof(struct class_ro32_t)) {
5317 memcpy(&cro, r, left);
5318 outs() << " (class_ro_t entends past the end of the section)\n";
5319 } else
5320 memcpy(&cro, r, sizeof(struct class_ro32_t));
5321 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5322 swapStruct(cro);
5323 outs() << " flags " << format("0x%" PRIx32"x", cro.flags);
5324 if (cro.flags & RO_META(1 << 0))
5325 outs() << " RO_META";
5326 if (cro.flags & RO_ROOT(1 << 1))
5327 outs() << " RO_ROOT";
5328 if (cro.flags & RO_HAS_CXX_STRUCTORS(1 << 2))
5329 outs() << " RO_HAS_CXX_STRUCTORS";
5330 outs() << "\n";
5331 outs() << " instanceStart " << cro.instanceStart << "\n";
5332 outs() << " instanceSize " << cro.instanceSize << "\n";
5333 outs() << " ivarLayout " << format("0x%" PRIx32"x", cro.ivarLayout)
5334 << "\n";
5335 print_layout_map32(cro.ivarLayout, info);
5336
5337 outs() << " name " << format("0x%" PRIx32"x", cro.name);
5338 name = get_pointer_32(cro.name, xoffset, left, xS, info);
5339 if (name != nullptr)
5340 outs() << format(" %.*s", left, name);
5341 outs() << "\n";
5342
5343 outs() << " baseMethods "
5344 << format("0x%" PRIx32"x", cro.baseMethods)
5345 << " (struct method_list_t *)\n";
5346 if (cro.baseMethods != 0)
5347 print_method_list32_t(cro.baseMethods, info, "");
5348
5349 outs() << " baseProtocols "
5350 << format("0x%" PRIx32"x", cro.baseProtocols) << "\n";
5351 if (cro.baseProtocols != 0)
5352 print_protocol_list32_t(cro.baseProtocols, info);
5353 outs() << " ivars " << format("0x%" PRIx32"x", cro.ivars)
5354 << "\n";
5355 if (cro.ivars != 0)
5356 print_ivar_list32_t(cro.ivars, info);
5357 outs() << " weakIvarLayout "
5358 << format("0x%" PRIx32"x", cro.weakIvarLayout) << "\n";
5359 print_layout_map32(cro.weakIvarLayout, info);
5360 outs() << " baseProperties "
5361 << format("0x%" PRIx32"x", cro.baseProperties) << "\n";
5362 if (cro.baseProperties != 0)
5363 print_objc_property_list32(cro.baseProperties, info);
5364 is_meta_class = (cro.flags & RO_META(1 << 0)) != 0;
5365 return true;
5366}
5367
5368static void print_class64_t(uint64_t p, struct DisassembleInfo *info) {
5369 struct class64_t c;
5370 const char *r;
5371 uint32_t offset, left;
5372 SectionRef S;
5373 const char *name;
5374 uint64_t isa_n_value, n_value;
5375
5376 r = get_pointer_64(p, offset, left, S, info);
5377 if (r == nullptr || left < sizeof(struct class64_t))
5378 return;
5379 memcpy(&c, r, sizeof(struct class64_t));
5380 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5381 swapStruct(c);
5382
5383 outs() << " isa " << format("0x%" PRIx64"l" "x", c.isa);
5384 name = get_symbol_64(offset + offsetof(struct class64_t, isa)__builtin_offsetof(struct class64_t, isa), S, info,
5385 isa_n_value, c.isa);
5386 if (name != nullptr)
5387 outs() << " " << name;
5388 outs() << "\n";
5389
5390 outs() << " superclass " << format("0x%" PRIx64"l" "x", c.superclass);
5391 name = get_symbol_64(offset + offsetof(struct class64_t, superclass)__builtin_offsetof(struct class64_t, superclass), S, info,
5392 n_value, c.superclass);
5393 if (name != nullptr)
5394 outs() << " " << name;
5395 else {
5396 name = get_dyld_bind_info_symbolname(S.getAddress() +
5397 offset + offsetof(struct class64_t, superclass)__builtin_offsetof(struct class64_t, superclass), info);
5398 if (name != nullptr)
5399 outs() << " " << name;
5400 }
5401 outs() << "\n";
5402
5403 outs() << " cache " << format("0x%" PRIx64"l" "x", c.cache);
5404 name = get_symbol_64(offset + offsetof(struct class64_t, cache)__builtin_offsetof(struct class64_t, cache), S, info,
5405 n_value, c.cache);
5406 if (name != nullptr)
5407 outs() << " " << name;
5408 outs() << "\n";
5409
5410 outs() << " vtable " << format("0x%" PRIx64"l" "x", c.vtable);
5411 name = get_symbol_64(offset + offsetof(struct class64_t, vtable)__builtin_offsetof(struct class64_t, vtable), S, info,
5412 n_value, c.vtable);
5413 if (name != nullptr)
5414 outs() << " " << name;
5415 outs() << "\n";
5416
5417 name = get_symbol_64(offset + offsetof(struct class64_t, data)__builtin_offsetof(struct class64_t, data), S, info,
5418 n_value, c.data);
5419 outs() << " data ";
5420 if (n_value != 0) {
5421 if (info->verbose && name != nullptr)
5422 outs() << name;
5423 else
5424 outs() << format("0x%" PRIx64"l" "x", n_value);
5425 if (c.data != 0)
5426 outs() << " + " << format("0x%" PRIx64"l" "x", c.data);
5427 } else
5428 outs() << format("0x%" PRIx64"l" "x", c.data);
5429 outs() << " (struct class_ro_t *)";
5430
5431 // This is a Swift class if some of the low bits of the pointer are set.
5432 if ((c.data + n_value) & 0x7)
5433 outs() << " Swift class";
5434 outs() << "\n";
5435 bool is_meta_class;
5436 if (!print_class_ro64_t((c.data + n_value) & ~0x7, info, is_meta_class))
5437 return;
5438
5439 if (!is_meta_class &&
5440 c.isa + isa_n_value != p &&
5441 c.isa + isa_n_value != 0 &&
5442 info->depth < 100) {
5443 info->depth++;
5444 outs() << "Meta Class\n";
5445 print_class64_t(c.isa + isa_n_value, info);
5446 }
5447}
5448
5449static void print_class32_t(uint32_t p, struct DisassembleInfo *info) {
5450 struct class32_t c;
5451 const char *r;
5452 uint32_t offset, left;
5453 SectionRef S;
5454 const char *name;
5455
5456 r = get_pointer_32(p, offset, left, S, info);
5457 if (r == nullptr)
5458 return;
5459 memset(&c, '\0', sizeof(struct class32_t));
5460 if (left < sizeof(struct class32_t)) {
5461 memcpy(&c, r, left);
5462 outs() << " (class_t entends past the end of the section)\n";
5463 } else
5464 memcpy(&c, r, sizeof(struct class32_t));
5465 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5466 swapStruct(c);
5467
5468 outs() << " isa " << format("0x%" PRIx32"x", c.isa);
5469 name =
5470 get_symbol_32(offset + offsetof(struct class32_t, isa)__builtin_offsetof(struct class32_t, isa), S, info, c.isa);
5471 if (name != nullptr)
5472 outs() << " " << name;
5473 outs() << "\n";
5474
5475 outs() << " superclass " << format("0x%" PRIx32"x", c.superclass);
5476 name = get_symbol_32(offset + offsetof(struct class32_t, superclass)__builtin_offsetof(struct class32_t, superclass), S, info,
5477 c.superclass);
5478 if (name != nullptr)
5479 outs() << " " << name;
5480 outs() << "\n";
5481
5482 outs() << " cache " << format("0x%" PRIx32"x", c.cache);
5483 name = get_symbol_32(offset + offsetof(struct class32_t, cache)__builtin_offsetof(struct class32_t, cache), S, info,
5484 c.cache);
5485 if (name != nullptr)
5486 outs() << " " << name;
5487 outs() << "\n";
5488
5489 outs() << " vtable " << format("0x%" PRIx32"x", c.vtable);
5490 name = get_symbol_32(offset + offsetof(struct class32_t, vtable)__builtin_offsetof(struct class32_t, vtable), S, info,
5491 c.vtable);
5492 if (name != nullptr)
5493 outs() << " " << name;
5494 outs() << "\n";
5495
5496 name =
5497 get_symbol_32(offset + offsetof(struct class32_t, data)__builtin_offsetof(struct class32_t, data), S, info, c.data);
5498 outs() << " data " << format("0x%" PRIx32"x", c.data)
5499 << " (struct class_ro_t *)";
5500
5501 // This is a Swift class if some of the low bits of the pointer are set.
5502 if (c.data & 0x3)
5503 outs() << " Swift class";
5504 outs() << "\n";
5505 bool is_meta_class;
5506 if (!print_class_ro32_t(c.data & ~0x3, info, is_meta_class))
5507 return;
5508
5509 if (!is_meta_class) {
5510 outs() << "Meta Class\n";
5511 print_class32_t(c.isa, info);
5512 }
5513}
5514
5515static void print_objc_class_t(struct objc_class_t *objc_class,
5516 struct DisassembleInfo *info) {
5517 uint32_t offset, left, xleft;
5518 const char *name, *p, *ivar_list;
5519 SectionRef S;
5520 int32_t i;
5521 struct objc_ivar_list_t objc_ivar_list;
5522 struct objc_ivar_t ivar;
5523
5524 outs() << "\t\t isa " << format("0x%08" PRIx32"x", objc_class->isa);
5525 if (info->verbose && CLS_GETINFO(objc_class, CLS_META)((objc_class)->info & (0x2))) {
5526 name = get_pointer_32(objc_class->isa, offset, left, S, info, true);
5527 if (name != nullptr)
5528 outs() << format(" %.*s", left, name);
5529 else
5530 outs() << " (not in an __OBJC section)";
5531 }
5532 outs() << "\n";
5533
5534 outs() << "\t super_class "
5535 << format("0x%08" PRIx32"x", objc_class->super_class);
5536 if (info->verbose) {
5537 name = get_pointer_32(objc_class->super_class, offset, left, S, info, true);
5538 if (name != nullptr)
5539 outs() << format(" %.*s", left, name);
5540 else
5541 outs() << " (not in an __OBJC section)";
5542 }
5543 outs() << "\n";
5544
5545 outs() << "\t\t name " << format("0x%08" PRIx32"x", objc_class->name);
5546 if (info->verbose) {
5547 name = get_pointer_32(objc_class->name, offset, left, S, info, true);
5548 if (name != nullptr)
5549 outs() << format(" %.*s", left, name);
5550 else
5551 outs() << " (not in an __OBJC section)";
5552 }
5553 outs() << "\n";
5554
5555 outs() << "\t\t version " << format("0x%08" PRIx32"x", objc_class->version)
5556 << "\n";
5557
5558 outs() << "\t\t info " << format("0x%08" PRIx32"x", objc_class->info);
5559 if (info->verbose) {
5560 if (CLS_GETINFO(objc_class, CLS_CLASS)((objc_class)->info & (0x1)))
5561 outs() << " CLS_CLASS";
5562 else if (CLS_GETINFO(objc_class, CLS_META)((objc_class)->info & (0x2)))
5563 outs() << " CLS_META";
5564 }
5565 outs() << "\n";
5566
5567 outs() << "\t instance_size "
5568 << format("0x%08" PRIx32"x", objc_class->instance_size) << "\n";
5569
5570 p = get_pointer_32(objc_class->ivars, offset, left, S, info, true);
5571 outs() << "\t\t ivars " << format("0x%08" PRIx32"x", objc_class->ivars);
5572 if (p != nullptr) {
5573 if (left > sizeof(struct objc_ivar_list_t)) {
5574 outs() << "\n";
5575 memcpy(&objc_ivar_list, p, sizeof(struct objc_ivar_list_t));
5576 } else {
5577 outs() << " (entends past the end of the section)\n";
5578 memset(&objc_ivar_list, '\0', sizeof(struct objc_ivar_list_t));
5579 memcpy(&objc_ivar_list, p, left);
5580 }
5581 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5582 swapStruct(objc_ivar_list);
5583 outs() << "\t\t ivar_count " << objc_ivar_list.ivar_count << "\n";
5584 ivar_list = p + sizeof(struct objc_ivar_list_t);
5585 for (i = 0; i < objc_ivar_list.ivar_count; i++) {
5586 if ((i + 1) * sizeof(struct objc_ivar_t) > left) {
5587 outs() << "\t\t remaining ivar's extend past the of the section\n";
5588 break;
5589 }
5590 memcpy(&ivar, ivar_list + i * sizeof(struct objc_ivar_t),
5591 sizeof(struct objc_ivar_t));
5592 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5593 swapStruct(ivar);
5594
5595 outs() << "\t\t\tivar_name " << format("0x%08" PRIx32"x", ivar.ivar_name);
5596 if (info->verbose) {
5597 name = get_pointer_32(ivar.ivar_name, offset, xleft, S, info, true);
5598 if (name != nullptr)
5599 outs() << format(" %.*s", xleft, name);
5600 else
5601 outs() << " (not in an __OBJC section)";
5602 }
5603 outs() << "\n";
5604
5605 outs() << "\t\t\tivar_type " << format("0x%08" PRIx32"x", ivar.ivar_type);
5606 if (info->verbose) {
5607 name = get_pointer_32(ivar.ivar_type, offset, xleft, S, info, true);
5608 if (name != nullptr)
5609 outs() << format(" %.*s", xleft, name);
5610 else
5611 outs() << " (not in an __OBJC section)";
5612 }
5613 outs() << "\n";
5614
5615 outs() << "\t\t ivar_offset "
5616 << format("0x%08" PRIx32"x", ivar.ivar_offset) << "\n";
5617 }
5618 } else {
5619 outs() << " (not in an __OBJC section)\n";
5620 }
5621
5622 outs() << "\t\t methods " << format("0x%08" PRIx32"x", objc_class->methodLists);
5623 if (print_method_list(objc_class->methodLists, info))
5624 outs() << " (not in an __OBJC section)\n";
5625
5626 outs() << "\t\t cache " << format("0x%08" PRIx32"x", objc_class->cache)
5627 << "\n";
5628
5629 outs() << "\t\tprotocols " << format("0x%08" PRIx32"x", objc_class->protocols);
5630 if (print_protocol_list(objc_class->protocols, 16, info))
5631 outs() << " (not in an __OBJC section)\n";
5632}
5633
5634static void print_objc_objc_category_t(struct objc_category_t *objc_category,
5635 struct DisassembleInfo *info) {
5636 uint32_t offset, left;
5637 const char *name;
5638 SectionRef S;
5639
5640 outs() << "\t category name "
5641 << format("0x%08" PRIx32"x", objc_category->category_name);
5642 if (info->verbose) {
5643 name = get_pointer_32(objc_category->category_name, offset, left, S, info,
5644 true);
5645 if (name != nullptr)
5646 outs() << format(" %.*s", left, name);
5647 else
5648 outs() << " (not in an __OBJC section)";
5649 }
5650 outs() << "\n";
5651
5652 outs() << "\t\t class name "
5653 << format("0x%08" PRIx32"x", objc_category->class_name);
5654 if (info->verbose) {
5655 name =
5656 get_pointer_32(objc_category->class_name, offset, left, S, info, true);
5657 if (name != nullptr)
5658 outs() << format(" %.*s", left, name);
5659 else
5660 outs() << " (not in an __OBJC section)";
5661 }
5662 outs() << "\n";
5663
5664 outs() << "\t instance methods "
5665 << format("0x%08" PRIx32"x", objc_category->instance_methods);
5666 if (print_method_list(objc_category->instance_methods, info))
5667 outs() << " (not in an __OBJC section)\n";
5668
5669 outs() << "\t class methods "
5670 << format("0x%08" PRIx32"x", objc_category->class_methods);
5671 if (print_method_list(objc_category->class_methods, info))
5672 outs() << " (not in an __OBJC section)\n";
5673}
5674
5675static void print_category64_t(uint64_t p, struct DisassembleInfo *info) {
5676 struct category64_t c;
5677 const char *r;
5678 uint32_t offset, xoffset, left;
5679 SectionRef S, xS;
5680 const char *name, *sym_name;
5681 uint64_t n_value;
5682
5683 r = get_pointer_64(p, offset, left, S, info);
5684 if (r == nullptr)
5685 return;
5686 memset(&c, '\0', sizeof(struct category64_t));
5687 if (left < sizeof(struct category64_t)) {
5688 memcpy(&c, r, left);
5689 outs() << " (category_t entends past the end of the section)\n";
5690 } else
5691 memcpy(&c, r, sizeof(struct category64_t));
5692 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5693 swapStruct(c);
5694
5695 outs() << " name ";
5696 sym_name = get_symbol_64(offset + offsetof(struct category64_t, name)__builtin_offsetof(struct category64_t, name), S,
5697 info, n_value, c.name);
5698 if (n_value != 0) {
5699 if (info->verbose && sym_name != nullptr)
5700 outs() << sym_name;
5701 else
5702 outs() << format("0x%" PRIx64"l" "x", n_value);
5703 if (c.name != 0)
5704 outs() << " + " << format("0x%" PRIx64"l" "x", c.name);
5705 } else
5706 outs() << format("0x%" PRIx64"l" "x", c.name);
5707 name = get_pointer_64(c.name + n_value, xoffset, left, xS, info);
5708 if (name != nullptr)
5709 outs() << format(" %.*s", left, name);
5710 outs() << "\n";
5711
5712 outs() << " cls ";
5713 sym_name = get_symbol_64(offset + offsetof(struct category64_t, cls)__builtin_offsetof(struct category64_t, cls), S, info,
5714 n_value, c.cls);
5715 if (n_value != 0) {
5716 if (info->verbose && sym_name != nullptr)
5717 outs() << sym_name;
5718 else
5719 outs() << format("0x%" PRIx64"l" "x", n_value);
5720 if (c.cls != 0)
5721 outs() << " + " << format("0x%" PRIx64"l" "x", c.cls);
5722 } else
5723 outs() << format("0x%" PRIx64"l" "x", c.cls);
5724 outs() << "\n";
5725 if (c.cls + n_value != 0)
5726 print_class64_t(c.cls + n_value, info);
5727
5728 outs() << " instanceMethods ";
5729 sym_name =
5730 get_symbol_64(offset + offsetof(struct category64_t, instanceMethods)__builtin_offsetof(struct category64_t, instanceMethods), S,
5731 info, n_value, c.instanceMethods);
5732 if (n_value != 0) {
5733 if (info->verbose && sym_name != nullptr)
5734 outs() << sym_name;
5735 else
5736 outs() << format("0x%" PRIx64"l" "x", n_value);
5737 if (c.instanceMethods != 0)
5738 outs() << " + " << format("0x%" PRIx64"l" "x", c.instanceMethods);
5739 } else
5740 outs() << format("0x%" PRIx64"l" "x", c.instanceMethods);
5741 outs() << "\n";
5742 if (c.instanceMethods + n_value != 0)
5743 print_method_list64_t(c.instanceMethods + n_value, info, "");
5744
5745 outs() << " classMethods ";
5746 sym_name = get_symbol_64(offset + offsetof(struct category64_t, classMethods)__builtin_offsetof(struct category64_t, classMethods),
5747 S, info, n_value, c.classMethods);
5748 if (n_value != 0) {
5749 if (info->verbose && sym_name != nullptr)
5750 outs() << sym_name;
5751 else
5752 outs() << format("0x%" PRIx64"l" "x", n_value);
5753 if (c.classMethods != 0)
5754 outs() << " + " << format("0x%" PRIx64"l" "x", c.classMethods);
5755 } else
5756 outs() << format("0x%" PRIx64"l" "x", c.classMethods);
5757 outs() << "\n";
5758 if (c.classMethods + n_value != 0)
5759 print_method_list64_t(c.classMethods + n_value, info, "");
5760
5761 outs() << " protocols ";
5762 sym_name = get_symbol_64(offset + offsetof(struct category64_t, protocols)__builtin_offsetof(struct category64_t, protocols), S,
5763 info, n_value, c.protocols);
5764 if (n_value != 0) {