1 //===-- MachODump.cpp - Object file dumping utility for llvm --------------===//
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
7 //===----------------------------------------------------------------------===//
9 // This file implements the MachO-specific dumper for llvm-objdump.
11 //===----------------------------------------------------------------------===//
13 #include "llvm-objdump.h"
14 #include "llvm-c/Disassembler.h"
15 #include "llvm/ADT/STLExtras.h"
16 #include "llvm/ADT/StringExtras.h"
17 #include "llvm/ADT/Triple.h"
18 #include "llvm/BinaryFormat/MachO.h"
19 #include "llvm/Config/config.h"
20 #include "llvm/DebugInfo/DIContext.h"
21 #include "llvm/DebugInfo/DWARF/DWARFContext.h"
22 #include "llvm/Demangle/Demangle.h"
23 #include "llvm/MC/MCAsmInfo.h"
24 #include "llvm/MC/MCContext.h"
25 #include "llvm/MC/MCDisassembler/MCDisassembler.h"
26 #include "llvm/MC/MCInst.h"
27 #include "llvm/MC/MCInstPrinter.h"
28 #include "llvm/MC/MCInstrDesc.h"
29 #include "llvm/MC/MCInstrInfo.h"
30 #include "llvm/MC/MCRegisterInfo.h"
31 #include "llvm/MC/MCSubtargetInfo.h"
32 #include "llvm/Object/MachO.h"
33 #include "llvm/Object/MachOUniversal.h"
34 #include "llvm/Support/Casting.h"
35 #include "llvm/Support/CommandLine.h"
36 #include "llvm/Support/Debug.h"
37 #include "llvm/Support/Endian.h"
38 #include "llvm/Support/Format.h"
39 #include "llvm/Support/FormattedStream.h"
40 #include "llvm/Support/GraphWriter.h"
41 #include "llvm/Support/LEB128.h"
42 #include "llvm/Support/MemoryBuffer.h"
43 #include "llvm/Support/TargetRegistry.h"
44 #include "llvm/Support/TargetSelect.h"
45 #include "llvm/Support/ToolOutputFile.h"
46 #include "llvm/Support/WithColor.h"
47 #include "llvm/Support/raw_ostream.h"
50 #include <system_error>
58 using namespace llvm::object;
62 cl::OptionCategory MachOCat("llvm-objdump MachO Specific Options");
64 extern cl::opt<bool> ArchiveHeaders;
65 extern cl::opt<bool> Disassemble;
66 extern cl::opt<bool> DisassembleAll;
67 extern cl::opt<DIDumpType> DwarfDumpType;
68 extern cl::list<std::string> FilterSections;
69 extern cl::list<std::string> MAttrs;
70 extern cl::opt<std::string> MCPU;
71 extern cl::opt<bool> NoShowRawInsn;
72 extern cl::opt<bool> NoLeadingAddr;
73 extern cl::opt<bool> PrintImmHex;
74 extern cl::opt<bool> PrivateHeaders;
75 extern cl::opt<bool> Relocations;
76 extern cl::opt<bool> SectionHeaders;
77 extern cl::opt<bool> SectionContents;
78 extern cl::opt<bool> SymbolTable;
79 extern cl::opt<std::string> TripleName;
80 extern cl::opt<bool> UnwindInfo;
83 FirstPrivateHeader("private-header",
84 cl::desc("Display only the first format specific file "
88 cl::opt<bool> ExportsTrie("exports-trie",
89 cl::desc("Display mach-o exported symbols"),
92 cl::opt<bool> Rebase("rebase", cl::desc("Display mach-o rebasing info"),
95 cl::opt<bool> Bind("bind", cl::desc("Display mach-o binding info"),
98 cl::opt<bool> LazyBind("lazy-bind",
99 cl::desc("Display mach-o lazy binding info"),
102 cl::opt<bool> WeakBind("weak-bind",
103 cl::desc("Display mach-o weak binding info"),
107 UseDbg("g", cl::Grouping,
108 cl::desc("Print line information from debug info if available"),
111 static cl::opt<std::string> DSYMFile("dsym",
112 cl::desc("Use .dSYM file for debug info"),
115 static cl::opt<bool> FullLeadingAddr("full-leading-addr",
116 cl::desc("Print full leading address"),
119 static cl::opt<bool> NoLeadingHeaders("no-leading-headers",
120 cl::desc("Print no leading headers"),
123 cl::opt<bool> UniversalHeaders("universal-headers",
124 cl::desc("Print Mach-O universal headers "
125 "(requires -macho)"),
129 ArchiveMemberOffsets("archive-member-offsets",
130 cl::desc("Print the offset to each archive member for "
131 "Mach-O archives (requires -macho and "
132 "-archive-headers)"),
135 cl::opt<bool> IndirectSymbols("indirect-symbols",
136 cl::desc("Print indirect symbol table for Mach-O "
137 "objects (requires -macho)"),
141 DataInCode("data-in-code",
142 cl::desc("Print the data in code table for Mach-O objects "
143 "(requires -macho)"),
146 cl::opt<bool> LinkOptHints("link-opt-hints",
147 cl::desc("Print the linker optimization hints for "
148 "Mach-O objects (requires -macho)"),
151 cl::opt<bool> InfoPlist("info-plist",
152 cl::desc("Print the info plist section as strings for "
153 "Mach-O objects (requires -macho)"),
156 cl::opt<bool> DylibsUsed("dylibs-used",
157 cl::desc("Print the shared libraries used for linked "
158 "Mach-O files (requires -macho)"),
163 cl::desc("Print the shared library's id for the dylib Mach-O "
164 "file (requires -macho)"),
168 NonVerbose("non-verbose",
169 cl::desc("Print the info for Mach-O objects in "
170 "non-verbose or numeric form (requires -macho)"),
174 ObjcMetaData("objc-meta-data",
175 cl::desc("Print the Objective-C runtime meta data for "
176 "Mach-O files (requires -macho)"),
179 cl::opt<std::string> DisSymName(
181 cl::desc("disassemble just this symbol's instructions (requires -macho)"),
184 static cl::opt<bool> NoSymbolicOperands(
185 "no-symbolic-operands",
186 cl::desc("do not symbolic operands when disassembling (requires -macho)"),
189 static cl::list<std::string>
190 ArchFlags("arch", cl::desc("architecture(s) from a Mach-O file to dump"),
191 cl::ZeroOrMore, cl::cat(MachOCat));
193 bool ArchAll = false;
195 static std::string ThumbTripleName;
197 static const Target *GetTarget(const MachOObjectFile *MachOObj,
198 const char **McpuDefault,
199 const Target **ThumbTarget) {
200 // Figure out the target triple.
201 Triple TT(TripleName);
202 if (TripleName.empty()) {
203 TT = MachOObj->getArchTriple(McpuDefault);
204 TripleName = TT.str();
207 if (TT.getArch() == Triple::arm) {
208 // We've inferred a 32-bit ARM target from the object file. All MachO CPUs
209 // that support ARM are also capable of Thumb mode.
210 Triple ThumbTriple = TT;
211 std::string ThumbName = (Twine("thumb") + TT.getArchName().substr(3)).str();
212 ThumbTriple.setArchName(ThumbName);
213 ThumbTripleName = ThumbTriple.str();
216 // Get the target specific parser.
218 const Target *TheTarget = TargetRegistry::lookupTarget(TripleName, Error);
219 if (TheTarget && ThumbTripleName.empty())
222 *ThumbTarget = TargetRegistry::lookupTarget(ThumbTripleName, Error);
226 WithColor::error(errs(), "llvm-objdump") << "unable to get target for '";
228 errs() << TripleName;
230 errs() << ThumbTripleName;
231 errs() << "', see --version and --triple.\n";
235 struct SymbolSorter {
236 bool operator()(const SymbolRef &A, const SymbolRef &B) {
237 Expected<SymbolRef::Type> ATypeOrErr = A.getType();
239 report_error(ATypeOrErr.takeError(), A.getObject()->getFileName());
240 SymbolRef::Type AType = *ATypeOrErr;
241 Expected<SymbolRef::Type> BTypeOrErr = B.getType();
243 report_error(BTypeOrErr.takeError(), B.getObject()->getFileName());
244 SymbolRef::Type BType = *BTypeOrErr;
245 uint64_t AAddr = (AType != SymbolRef::ST_Function) ? 0 : A.getValue();
246 uint64_t BAddr = (BType != SymbolRef::ST_Function) ? 0 : B.getValue();
247 return AAddr < BAddr;
251 // Types for the storted data in code table that is built before disassembly
252 // and the predicate function to sort them.
253 typedef std::pair<uint64_t, DiceRef> DiceTableEntry;
254 typedef std::vector<DiceTableEntry> DiceTable;
255 typedef DiceTable::iterator dice_table_iterator;
259 struct ScopedXarFile {
261 ScopedXarFile(const char *filename, int32_t flags)
262 : xar(xar_open(filename, flags)) {}
267 ScopedXarFile(const ScopedXarFile &) = delete;
268 ScopedXarFile &operator=(const ScopedXarFile &) = delete;
269 operator xar_t() { return xar; }
272 struct ScopedXarIter {
274 ScopedXarIter() : iter(xar_iter_new()) {}
279 ScopedXarIter(const ScopedXarIter &) = delete;
280 ScopedXarIter &operator=(const ScopedXarIter &) = delete;
281 operator xar_iter_t() { return iter; }
284 #endif // defined(HAVE_LIBXAR)
286 // This is used to search for a data in code table entry for the PC being
287 // disassembled. The j parameter has the PC in j.first. A single data in code
288 // table entry can cover many bytes for each of its Kind's. So if the offset,
289 // aka the i.first value, of the data in code table entry plus its Length
290 // covers the PC being searched for this will return true. If not it will
292 static bool compareDiceTableEntries(const DiceTableEntry &i,
293 const DiceTableEntry &j) {
295 i.second.getLength(Length);
297 return j.first >= i.first && j.first < i.first + Length;
300 static uint64_t DumpDataInCode(const uint8_t *bytes, uint64_t Length,
301 unsigned short Kind) {
302 uint32_t Value, Size = 1;
306 case MachO::DICE_KIND_DATA:
309 dumpBytes(makeArrayRef(bytes, 4), outs());
310 Value = bytes[3] << 24 | bytes[2] << 16 | bytes[1] << 8 | bytes[0];
311 outs() << "\t.long " << Value;
313 } else if (Length >= 2) {
315 dumpBytes(makeArrayRef(bytes, 2), outs());
316 Value = bytes[1] << 8 | bytes[0];
317 outs() << "\t.short " << Value;
321 dumpBytes(makeArrayRef(bytes, 2), outs());
323 outs() << "\t.byte " << Value;
326 if (Kind == MachO::DICE_KIND_DATA)
327 outs() << "\t@ KIND_DATA\n";
329 outs() << "\t@ data in code kind = " << Kind << "\n";
331 case MachO::DICE_KIND_JUMP_TABLE8:
333 dumpBytes(makeArrayRef(bytes, 1), outs());
335 outs() << "\t.byte " << format("%3u", Value) << "\t@ KIND_JUMP_TABLE8\n";
338 case MachO::DICE_KIND_JUMP_TABLE16:
340 dumpBytes(makeArrayRef(bytes, 2), outs());
341 Value = bytes[1] << 8 | bytes[0];
342 outs() << "\t.short " << format("%5u", Value & 0xffff)
343 << "\t@ KIND_JUMP_TABLE16\n";
346 case MachO::DICE_KIND_JUMP_TABLE32:
347 case MachO::DICE_KIND_ABS_JUMP_TABLE32:
349 dumpBytes(makeArrayRef(bytes, 4), outs());
350 Value = bytes[3] << 24 | bytes[2] << 16 | bytes[1] << 8 | bytes[0];
351 outs() << "\t.long " << Value;
352 if (Kind == MachO::DICE_KIND_JUMP_TABLE32)
353 outs() << "\t@ KIND_JUMP_TABLE32\n";
355 outs() << "\t@ KIND_ABS_JUMP_TABLE32\n";
362 static void getSectionsAndSymbols(MachOObjectFile *MachOObj,
363 std::vector<SectionRef> &Sections,
364 std::vector<SymbolRef> &Symbols,
365 SmallVectorImpl<uint64_t> &FoundFns,
366 uint64_t &BaseSegmentAddress) {
367 const StringRef FileName = MachOObj->getFileName();
368 for (const SymbolRef &Symbol : MachOObj->symbols()) {
369 StringRef SymName = unwrapOrError(Symbol.getName(), FileName);
370 if (!SymName.startswith("ltmp"))
371 Symbols.push_back(Symbol);
374 for (const SectionRef &Section : MachOObj->sections()) {
376 Section.getName(SectName);
377 Sections.push_back(Section);
380 bool BaseSegmentAddressSet = false;
381 for (const auto &Command : MachOObj->load_commands()) {
382 if (Command.C.cmd == MachO::LC_FUNCTION_STARTS) {
383 // We found a function starts segment, parse the addresses for later
385 MachO::linkedit_data_command LLC =
386 MachOObj->getLinkeditDataLoadCommand(Command);
388 MachOObj->ReadULEB128s(LLC.dataoff, FoundFns);
389 } else if (Command.C.cmd == MachO::LC_SEGMENT) {
390 MachO::segment_command SLC = MachOObj->getSegmentLoadCommand(Command);
391 StringRef SegName = SLC.segname;
392 if (!BaseSegmentAddressSet && SegName != "__PAGEZERO") {
393 BaseSegmentAddressSet = true;
394 BaseSegmentAddress = SLC.vmaddr;
400 static void printRelocationTargetName(const MachOObjectFile *O,
401 const MachO::any_relocation_info &RE,
402 raw_string_ostream &Fmt) {
403 // Target of a scattered relocation is an address. In the interest of
404 // generating pretty output, scan through the symbol table looking for a
405 // symbol that aligns with that address. If we find one, print it.
406 // Otherwise, we just print the hex address of the target.
407 const StringRef FileName = O->getFileName();
408 if (O->isRelocationScattered(RE)) {
409 uint32_t Val = O->getPlainRelocationSymbolNum(RE);
411 for (const SymbolRef &Symbol : O->symbols()) {
412 uint64_t Addr = unwrapOrError(Symbol.getAddress(), FileName);
415 Fmt << unwrapOrError(Symbol.getName(), FileName);
419 // If we couldn't find a symbol that this relocation refers to, try
420 // to find a section beginning instead.
421 for (const SectionRef &Section : ToolSectionFilter(*O)) {
423 uint64_t Addr = Section.getAddress();
426 if (std::error_code EC = Section.getName(Name))
427 report_error(errorCodeToError(EC), O->getFileName());
432 Fmt << format("0x%x", Val);
437 bool isExtern = O->getPlainRelocationExternal(RE);
438 uint64_t Val = O->getPlainRelocationSymbolNum(RE);
440 if (O->getAnyRelocationType(RE) == MachO::ARM64_RELOC_ADDEND) {
441 Fmt << format("0x%0" PRIx64, Val);
446 symbol_iterator SI = O->symbol_begin();
448 S = unwrapOrError(SI->getName(), FileName);
450 section_iterator SI = O->section_begin();
451 // Adjust for the fact that sections are 1-indexed.
456 uint32_t I = Val - 1;
457 while (I != 0 && SI != O->section_end()) {
461 if (SI == O->section_end())
462 Fmt << Val << " (?,?)";
470 Error getMachORelocationValueString(const MachOObjectFile *Obj,
471 const RelocationRef &RelRef,
472 SmallVectorImpl<char> &Result) {
473 DataRefImpl Rel = RelRef.getRawDataRefImpl();
474 MachO::any_relocation_info RE = Obj->getRelocation(Rel);
476 unsigned Arch = Obj->getArch();
479 raw_string_ostream Fmt(FmtBuf);
480 unsigned Type = Obj->getAnyRelocationType(RE);
481 bool IsPCRel = Obj->getAnyRelocationPCRel(RE);
483 // Determine any addends that should be displayed with the relocation.
484 // These require decoding the relocation type, which is triple-specific.
486 // X86_64 has entirely custom relocation types.
487 if (Arch == Triple::x86_64) {
489 case MachO::X86_64_RELOC_GOT_LOAD:
490 case MachO::X86_64_RELOC_GOT: {
491 printRelocationTargetName(Obj, RE, Fmt);
497 case MachO::X86_64_RELOC_SUBTRACTOR: {
498 DataRefImpl RelNext = Rel;
499 Obj->moveRelocationNext(RelNext);
500 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
502 // X86_64_RELOC_SUBTRACTOR must be followed by a relocation of type
503 // X86_64_RELOC_UNSIGNED.
504 // NOTE: Scattered relocations don't exist on x86_64.
505 unsigned RType = Obj->getAnyRelocationType(RENext);
506 if (RType != MachO::X86_64_RELOC_UNSIGNED)
507 report_error(Obj->getFileName(), "Expected X86_64_RELOC_UNSIGNED after "
508 "X86_64_RELOC_SUBTRACTOR.");
510 // The X86_64_RELOC_UNSIGNED contains the minuend symbol;
511 // X86_64_RELOC_SUBTRACTOR contains the subtrahend.
512 printRelocationTargetName(Obj, RENext, Fmt);
514 printRelocationTargetName(Obj, RE, Fmt);
517 case MachO::X86_64_RELOC_TLV:
518 printRelocationTargetName(Obj, RE, Fmt);
523 case MachO::X86_64_RELOC_SIGNED_1:
524 printRelocationTargetName(Obj, RE, Fmt);
527 case MachO::X86_64_RELOC_SIGNED_2:
528 printRelocationTargetName(Obj, RE, Fmt);
531 case MachO::X86_64_RELOC_SIGNED_4:
532 printRelocationTargetName(Obj, RE, Fmt);
536 printRelocationTargetName(Obj, RE, Fmt);
539 // X86 and ARM share some relocation types in common.
540 } else if (Arch == Triple::x86 || Arch == Triple::arm ||
541 Arch == Triple::ppc) {
542 // Generic relocation types...
544 case MachO::GENERIC_RELOC_PAIR: // prints no info
545 return Error::success();
546 case MachO::GENERIC_RELOC_SECTDIFF: {
547 DataRefImpl RelNext = Rel;
548 Obj->moveRelocationNext(RelNext);
549 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
551 // X86 sect diff's must be followed by a relocation of type
552 // GENERIC_RELOC_PAIR.
553 unsigned RType = Obj->getAnyRelocationType(RENext);
555 if (RType != MachO::GENERIC_RELOC_PAIR)
556 report_error(Obj->getFileName(), "Expected GENERIC_RELOC_PAIR after "
557 "GENERIC_RELOC_SECTDIFF.");
559 printRelocationTargetName(Obj, RE, Fmt);
561 printRelocationTargetName(Obj, RENext, Fmt);
566 if (Arch == Triple::x86 || Arch == Triple::ppc) {
568 case MachO::GENERIC_RELOC_LOCAL_SECTDIFF: {
569 DataRefImpl RelNext = Rel;
570 Obj->moveRelocationNext(RelNext);
571 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
573 // X86 sect diff's must be followed by a relocation of type
574 // GENERIC_RELOC_PAIR.
575 unsigned RType = Obj->getAnyRelocationType(RENext);
576 if (RType != MachO::GENERIC_RELOC_PAIR)
577 report_error(Obj->getFileName(), "Expected GENERIC_RELOC_PAIR after "
578 "GENERIC_RELOC_LOCAL_SECTDIFF.");
580 printRelocationTargetName(Obj, RE, Fmt);
582 printRelocationTargetName(Obj, RENext, Fmt);
585 case MachO::GENERIC_RELOC_TLV: {
586 printRelocationTargetName(Obj, RE, Fmt);
593 printRelocationTargetName(Obj, RE, Fmt);
595 } else { // ARM-specific relocations
597 case MachO::ARM_RELOC_HALF:
598 case MachO::ARM_RELOC_HALF_SECTDIFF: {
599 // Half relocations steal a bit from the length field to encode
600 // whether this is an upper16 or a lower16 relocation.
601 bool isUpper = (Obj->getAnyRelocationLength(RE) & 0x1) == 1;
607 printRelocationTargetName(Obj, RE, Fmt);
609 DataRefImpl RelNext = Rel;
610 Obj->moveRelocationNext(RelNext);
611 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
613 // ARM half relocs must be followed by a relocation of type
615 unsigned RType = Obj->getAnyRelocationType(RENext);
616 if (RType != MachO::ARM_RELOC_PAIR)
617 report_error(Obj->getFileName(), "Expected ARM_RELOC_PAIR after "
620 // NOTE: The half of the target virtual address is stashed in the
621 // address field of the secondary relocation, but we can't reverse
622 // engineer the constant offset from it without decoding the movw/movt
623 // instruction to find the other half in its immediate field.
625 // ARM_RELOC_HALF_SECTDIFF encodes the second section in the
626 // symbol/section pointer of the follow-on relocation.
627 if (Type == MachO::ARM_RELOC_HALF_SECTDIFF) {
629 printRelocationTargetName(Obj, RENext, Fmt);
636 printRelocationTargetName(Obj, RE, Fmt);
641 printRelocationTargetName(Obj, RE, Fmt);
644 Result.append(FmtBuf.begin(), FmtBuf.end());
645 return Error::success();
648 static void PrintIndirectSymbolTable(MachOObjectFile *O, bool verbose,
649 uint32_t n, uint32_t count,
650 uint32_t stride, uint64_t addr) {
651 MachO::dysymtab_command Dysymtab = O->getDysymtabLoadCommand();
652 uint32_t nindirectsyms = Dysymtab.nindirectsyms;
653 if (n > nindirectsyms)
654 outs() << " (entries start past the end of the indirect symbol "
655 "table) (reserved1 field greater than the table size)";
656 else if (n + count > nindirectsyms)
657 outs() << " (entries extends past the end of the indirect symbol "
660 uint32_t cputype = O->getHeader().cputype;
661 if (cputype & MachO::CPU_ARCH_ABI64)
662 outs() << "address index";
664 outs() << "address index";
669 for (uint32_t j = 0; j < count && n + j < nindirectsyms; j++) {
670 if (cputype & MachO::CPU_ARCH_ABI64)
671 outs() << format("0x%016" PRIx64, addr + j * stride) << " ";
673 outs() << format("0x%08" PRIx32, (uint32_t)addr + j * stride) << " ";
674 MachO::dysymtab_command Dysymtab = O->getDysymtabLoadCommand();
675 uint32_t indirect_symbol = O->getIndirectSymbolTableEntry(Dysymtab, n + j);
676 if (indirect_symbol == MachO::INDIRECT_SYMBOL_LOCAL) {
680 if (indirect_symbol ==
681 (MachO::INDIRECT_SYMBOL_LOCAL | MachO::INDIRECT_SYMBOL_ABS)) {
682 outs() << "LOCAL ABSOLUTE\n";
685 if (indirect_symbol == MachO::INDIRECT_SYMBOL_ABS) {
686 outs() << "ABSOLUTE\n";
689 outs() << format("%5u ", indirect_symbol);
691 MachO::symtab_command Symtab = O->getSymtabLoadCommand();
692 if (indirect_symbol < Symtab.nsyms) {
693 symbol_iterator Sym = O->getSymbolByIndex(indirect_symbol);
694 SymbolRef Symbol = *Sym;
695 outs() << unwrapOrError(Symbol.getName(), O->getFileName());
704 static void PrintIndirectSymbols(MachOObjectFile *O, bool verbose) {
705 for (const auto &Load : O->load_commands()) {
706 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
707 MachO::segment_command_64 Seg = O->getSegment64LoadCommand(Load);
708 for (unsigned J = 0; J < Seg.nsects; ++J) {
709 MachO::section_64 Sec = O->getSection64(Load, J);
710 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
711 if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
712 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
713 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
714 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
715 section_type == MachO::S_SYMBOL_STUBS) {
717 if (section_type == MachO::S_SYMBOL_STUBS)
718 stride = Sec.reserved2;
722 outs() << "Can't print indirect symbols for (" << Sec.segname << ","
723 << Sec.sectname << ") "
724 << "(size of stubs in reserved2 field is zero)\n";
727 uint32_t count = Sec.size / stride;
728 outs() << "Indirect symbols for (" << Sec.segname << ","
729 << Sec.sectname << ") " << count << " entries";
730 uint32_t n = Sec.reserved1;
731 PrintIndirectSymbolTable(O, verbose, n, count, stride, Sec.addr);
734 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
735 MachO::segment_command Seg = O->getSegmentLoadCommand(Load);
736 for (unsigned J = 0; J < Seg.nsects; ++J) {
737 MachO::section Sec = O->getSection(Load, J);
738 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
739 if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
740 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
741 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
742 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
743 section_type == MachO::S_SYMBOL_STUBS) {
745 if (section_type == MachO::S_SYMBOL_STUBS)
746 stride = Sec.reserved2;
750 outs() << "Can't print indirect symbols for (" << Sec.segname << ","
751 << Sec.sectname << ") "
752 << "(size of stubs in reserved2 field is zero)\n";
755 uint32_t count = Sec.size / stride;
756 outs() << "Indirect symbols for (" << Sec.segname << ","
757 << Sec.sectname << ") " << count << " entries";
758 uint32_t n = Sec.reserved1;
759 PrintIndirectSymbolTable(O, verbose, n, count, stride, Sec.addr);
766 static void PrintRType(const uint64_t cputype, const unsigned r_type) {
767 static char const *generic_r_types[] = {
768 "VANILLA ", "PAIR ", "SECTDIF ", "PBLAPTR ", "LOCSDIF ", "TLV ",
769 " 6 (?) ", " 7 (?) ", " 8 (?) ", " 9 (?) ", " 10 (?) ", " 11 (?) ",
770 " 12 (?) ", " 13 (?) ", " 14 (?) ", " 15 (?) "
772 static char const *x86_64_r_types[] = {
773 "UNSIGND ", "SIGNED ", "BRANCH ", "GOT_LD ", "GOT ", "SUB ",
774 "SIGNED1 ", "SIGNED2 ", "SIGNED4 ", "TLV ", " 10 (?) ", " 11 (?) ",
775 " 12 (?) ", " 13 (?) ", " 14 (?) ", " 15 (?) "
777 static char const *arm_r_types[] = {
778 "VANILLA ", "PAIR ", "SECTDIFF", "LOCSDIF ", "PBLAPTR ",
779 "BR24 ", "T_BR22 ", "T_BR32 ", "HALF ", "HALFDIF ",
780 " 10 (?) ", " 11 (?) ", " 12 (?) ", " 13 (?) ", " 14 (?) ", " 15 (?) "
782 static char const *arm64_r_types[] = {
783 "UNSIGND ", "SUB ", "BR26 ", "PAGE21 ", "PAGOF12 ",
784 "GOTLDP ", "GOTLDPOF", "PTRTGOT ", "TLVLDP ", "TLVLDPOF",
785 "ADDEND ", " 11 (?) ", " 12 (?) ", " 13 (?) ", " 14 (?) ", " 15 (?) "
789 outs() << format("%-7u", r_type) << " ";
793 case MachO::CPU_TYPE_I386:
794 outs() << generic_r_types[r_type];
796 case MachO::CPU_TYPE_X86_64:
797 outs() << x86_64_r_types[r_type];
799 case MachO::CPU_TYPE_ARM:
800 outs() << arm_r_types[r_type];
802 case MachO::CPU_TYPE_ARM64:
803 case MachO::CPU_TYPE_ARM64_32:
804 outs() << arm64_r_types[r_type];
807 outs() << format("%-7u ", r_type);
811 static void PrintRLength(const uint64_t cputype, const unsigned r_type,
812 const unsigned r_length, const bool previous_arm_half){
813 if (cputype == MachO::CPU_TYPE_ARM &&
814 (r_type == MachO::ARM_RELOC_HALF ||
815 r_type == MachO::ARM_RELOC_HALF_SECTDIFF || previous_arm_half == true)) {
816 if ((r_length & 0x1) == 0)
820 if ((r_length & 0x1) == 0)
836 if (cputype == MachO::CPU_TYPE_X86_64)
839 outs() << format("?(%2d) ", r_length);
842 outs() << format("?(%2d) ", r_length);
847 static void PrintRelocationEntries(const MachOObjectFile *O,
848 const relocation_iterator Begin,
849 const relocation_iterator End,
850 const uint64_t cputype,
851 const bool verbose) {
852 const MachO::symtab_command Symtab = O->getSymtabLoadCommand();
853 bool previous_arm_half = false;
854 bool previous_sectdiff = false;
855 uint32_t sectdiff_r_type = 0;
857 for (relocation_iterator Reloc = Begin; Reloc != End; ++Reloc) {
858 const DataRefImpl Rel = Reloc->getRawDataRefImpl();
859 const MachO::any_relocation_info RE = O->getRelocation(Rel);
860 const unsigned r_type = O->getAnyRelocationType(RE);
861 const bool r_scattered = O->isRelocationScattered(RE);
862 const unsigned r_pcrel = O->getAnyRelocationPCRel(RE);
863 const unsigned r_length = O->getAnyRelocationLength(RE);
864 const unsigned r_address = O->getAnyRelocationAddress(RE);
865 const bool r_extern = (r_scattered ? false :
866 O->getPlainRelocationExternal(RE));
867 const uint32_t r_value = (r_scattered ?
868 O->getScatteredRelocationValue(RE) : 0);
869 const unsigned r_symbolnum = (r_scattered ? 0 :
870 O->getPlainRelocationSymbolNum(RE));
872 if (r_scattered && cputype != MachO::CPU_TYPE_X86_64) {
874 // scattered: address
875 if ((cputype == MachO::CPU_TYPE_I386 &&
876 r_type == MachO::GENERIC_RELOC_PAIR) ||
877 (cputype == MachO::CPU_TYPE_ARM && r_type == MachO::ARM_RELOC_PAIR))
880 outs() << format("%08x ", (unsigned int)r_address);
889 PrintRLength(cputype, r_type, r_length, previous_arm_half);
891 // scattered: extern & type
893 PrintRType(cputype, r_type);
895 // scattered: scattered & value
896 outs() << format("True 0x%08x", (unsigned int)r_value);
897 if (previous_sectdiff == false) {
898 if ((cputype == MachO::CPU_TYPE_ARM &&
899 r_type == MachO::ARM_RELOC_PAIR))
900 outs() << format(" half = 0x%04x ", (unsigned int)r_address);
901 } else if (cputype == MachO::CPU_TYPE_ARM &&
902 sectdiff_r_type == MachO::ARM_RELOC_HALF_SECTDIFF)
903 outs() << format(" other_half = 0x%04x ", (unsigned int)r_address);
904 if ((cputype == MachO::CPU_TYPE_I386 &&
905 (r_type == MachO::GENERIC_RELOC_SECTDIFF ||
906 r_type == MachO::GENERIC_RELOC_LOCAL_SECTDIFF)) ||
907 (cputype == MachO::CPU_TYPE_ARM &&
908 (sectdiff_r_type == MachO::ARM_RELOC_SECTDIFF ||
909 sectdiff_r_type == MachO::ARM_RELOC_LOCAL_SECTDIFF ||
910 sectdiff_r_type == MachO::ARM_RELOC_HALF_SECTDIFF))) {
911 previous_sectdiff = true;
912 sectdiff_r_type = r_type;
914 previous_sectdiff = false;
917 if (cputype == MachO::CPU_TYPE_ARM &&
918 (r_type == MachO::ARM_RELOC_HALF ||
919 r_type == MachO::ARM_RELOC_HALF_SECTDIFF))
920 previous_arm_half = true;
922 previous_arm_half = false;
926 // scattered: address pcrel length extern type scattered value
927 outs() << format("%08x %1d %-2d n/a %-7d 1 0x%08x\n",
928 (unsigned int)r_address, r_pcrel, r_length, r_type,
929 (unsigned int)r_value);
935 if (cputype == MachO::CPU_TYPE_ARM && r_type == MachO::ARM_RELOC_PAIR)
938 outs() << format("%08x ", (unsigned int)r_address);
947 PrintRLength(cputype, r_type, r_length, previous_arm_half);
950 // plain: extern & type & scattered
952 PrintRType(cputype, r_type);
955 // plain: symbolnum/value
956 if (r_symbolnum > Symtab.nsyms)
957 outs() << format("?(%d)\n", r_symbolnum);
959 SymbolRef Symbol = *O->getSymbolByIndex(r_symbolnum);
960 Expected<StringRef> SymNameNext = Symbol.getName();
961 const char *name = NULL;
963 name = SymNameNext->data();
965 outs() << format("?(%d)\n", r_symbolnum);
967 outs() << name << "\n";
971 // plain: extern & type & scattered
973 PrintRType(cputype, r_type);
976 // plain: symbolnum/value
977 if (cputype == MachO::CPU_TYPE_ARM && r_type == MachO::ARM_RELOC_PAIR)
978 outs() << format("other_half = 0x%04x\n", (unsigned int)r_address);
979 else if ((cputype == MachO::CPU_TYPE_ARM64 ||
980 cputype == MachO::CPU_TYPE_ARM64_32) &&
981 r_type == MachO::ARM64_RELOC_ADDEND)
982 outs() << format("addend = 0x%06x\n", (unsigned int)r_symbolnum);
984 outs() << format("%d ", r_symbolnum);
985 if (r_symbolnum == MachO::R_ABS)
988 // in this case, r_symbolnum is actually a 1-based section number
989 uint32_t nsects = O->section_end()->getRawDataRefImpl().d.a;
990 if (r_symbolnum > 0 && r_symbolnum <= nsects) {
991 object::DataRefImpl DRI;
992 DRI.d.a = r_symbolnum-1;
993 StringRef SegName = O->getSectionFinalSegmentName(DRI);
994 if (Expected<StringRef> NameOrErr = O->getSectionName(DRI))
995 outs() << "(" << SegName << "," << *NameOrErr << ")\n";
1000 outs() << "(?,?)\n";
1005 if (cputype == MachO::CPU_TYPE_ARM &&
1006 (r_type == MachO::ARM_RELOC_HALF ||
1007 r_type == MachO::ARM_RELOC_HALF_SECTDIFF))
1008 previous_arm_half = true;
1010 previous_arm_half = false;
1013 // plain: address pcrel length extern type scattered symbolnum/section
1014 outs() << format("%08x %1d %-2d %1d %-7d 0 %d\n",
1015 (unsigned int)r_address, r_pcrel, r_length, r_extern,
1016 r_type, r_symbolnum);
1022 static void PrintRelocations(const MachOObjectFile *O, const bool verbose) {
1023 const uint64_t cputype = O->getHeader().cputype;
1024 const MachO::dysymtab_command Dysymtab = O->getDysymtabLoadCommand();
1025 if (Dysymtab.nextrel != 0) {
1026 outs() << "External relocation information " << Dysymtab.nextrel
1028 outs() << "\naddress pcrel length extern type scattered "
1029 "symbolnum/value\n";
1030 PrintRelocationEntries(O, O->extrel_begin(), O->extrel_end(), cputype,
1033 if (Dysymtab.nlocrel != 0) {
1034 outs() << format("Local relocation information %u entries",
1036 outs() << "\naddress pcrel length extern type scattered "
1037 "symbolnum/value\n";
1038 PrintRelocationEntries(O, O->locrel_begin(), O->locrel_end(), cputype,
1041 for (const auto &Load : O->load_commands()) {
1042 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
1043 const MachO::segment_command_64 Seg = O->getSegment64LoadCommand(Load);
1044 for (unsigned J = 0; J < Seg.nsects; ++J) {
1045 const MachO::section_64 Sec = O->getSection64(Load, J);
1046 if (Sec.nreloc != 0) {
1049 const StringRef SegName = O->getSectionFinalSegmentName(DRI);
1050 if (Expected<StringRef> NameOrErr = O->getSectionName(DRI))
1051 outs() << "Relocation information (" << SegName << "," << *NameOrErr
1052 << format(") %u entries", Sec.nreloc);
1054 outs() << "Relocation information (" << SegName << ",?) "
1055 << format("%u entries", Sec.nreloc);
1056 outs() << "\naddress pcrel length extern type scattered "
1057 "symbolnum/value\n";
1058 PrintRelocationEntries(O, O->section_rel_begin(DRI),
1059 O->section_rel_end(DRI), cputype, verbose);
1062 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
1063 const MachO::segment_command Seg = O->getSegmentLoadCommand(Load);
1064 for (unsigned J = 0; J < Seg.nsects; ++J) {
1065 const MachO::section Sec = O->getSection(Load, J);
1066 if (Sec.nreloc != 0) {
1069 const StringRef SegName = O->getSectionFinalSegmentName(DRI);
1070 if (Expected<StringRef> NameOrErr = O->getSectionName(DRI))
1071 outs() << "Relocation information (" << SegName << "," << *NameOrErr
1072 << format(") %u entries", Sec.nreloc);
1074 outs() << "Relocation information (" << SegName << ",?) "
1075 << format("%u entries", Sec.nreloc);
1076 outs() << "\naddress pcrel length extern type scattered "
1077 "symbolnum/value\n";
1078 PrintRelocationEntries(O, O->section_rel_begin(DRI),
1079 O->section_rel_end(DRI), cputype, verbose);
1086 static void PrintDataInCodeTable(MachOObjectFile *O, bool verbose) {
1087 MachO::linkedit_data_command DIC = O->getDataInCodeLoadCommand();
1088 uint32_t nentries = DIC.datasize / sizeof(struct MachO::data_in_code_entry);
1089 outs() << "Data in code table (" << nentries << " entries)\n";
1090 outs() << "offset length kind\n";
1091 for (dice_iterator DI = O->begin_dices(), DE = O->end_dices(); DI != DE;
1094 DI->getOffset(Offset);
1095 outs() << format("0x%08" PRIx32, Offset) << " ";
1097 DI->getLength(Length);
1098 outs() << format("%6u", Length) << " ";
1103 case MachO::DICE_KIND_DATA:
1106 case MachO::DICE_KIND_JUMP_TABLE8:
1107 outs() << "JUMP_TABLE8";
1109 case MachO::DICE_KIND_JUMP_TABLE16:
1110 outs() << "JUMP_TABLE16";
1112 case MachO::DICE_KIND_JUMP_TABLE32:
1113 outs() << "JUMP_TABLE32";
1115 case MachO::DICE_KIND_ABS_JUMP_TABLE32:
1116 outs() << "ABS_JUMP_TABLE32";
1119 outs() << format("0x%04" PRIx32, Kind);
1123 outs() << format("0x%04" PRIx32, Kind);
1128 static void PrintLinkOptHints(MachOObjectFile *O) {
1129 MachO::linkedit_data_command LohLC = O->getLinkOptHintsLoadCommand();
1130 const char *loh = O->getData().substr(LohLC.dataoff, 1).data();
1131 uint32_t nloh = LohLC.datasize;
1132 outs() << "Linker optimiztion hints (" << nloh << " total bytes)\n";
1133 for (uint32_t i = 0; i < nloh;) {
1135 uint64_t identifier = decodeULEB128((const uint8_t *)(loh + i), &n);
1137 outs() << " identifier " << identifier << " ";
1140 switch (identifier) {
1142 outs() << "AdrpAdrp\n";
1145 outs() << "AdrpLdr\n";
1148 outs() << "AdrpAddLdr\n";
1151 outs() << "AdrpLdrGotLdr\n";
1154 outs() << "AdrpAddStr\n";
1157 outs() << "AdrpLdrGotStr\n";
1160 outs() << "AdrpAdd\n";
1163 outs() << "AdrpLdrGot\n";
1166 outs() << "Unknown identifier value\n";
1169 uint64_t narguments = decodeULEB128((const uint8_t *)(loh + i), &n);
1171 outs() << " narguments " << narguments << "\n";
1175 for (uint32_t j = 0; j < narguments; j++) {
1176 uint64_t value = decodeULEB128((const uint8_t *)(loh + i), &n);
1178 outs() << "\tvalue " << format("0x%" PRIx64, value) << "\n";
1185 static void PrintDylibs(MachOObjectFile *O, bool JustId) {
1187 for (const auto &Load : O->load_commands()) {
1188 if ((JustId && Load.C.cmd == MachO::LC_ID_DYLIB) ||
1189 (!JustId && (Load.C.cmd == MachO::LC_ID_DYLIB ||
1190 Load.C.cmd == MachO::LC_LOAD_DYLIB ||
1191 Load.C.cmd == MachO::LC_LOAD_WEAK_DYLIB ||
1192 Load.C.cmd == MachO::LC_REEXPORT_DYLIB ||
1193 Load.C.cmd == MachO::LC_LAZY_LOAD_DYLIB ||
1194 Load.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB))) {
1195 MachO::dylib_command dl = O->getDylibIDLoadCommand(Load);
1196 if (dl.dylib.name < dl.cmdsize) {
1197 const char *p = (const char *)(Load.Ptr) + dl.dylib.name;
1199 outs() << p << "\n";
1201 outs() << "\t" << p;
1202 outs() << " (compatibility version "
1203 << ((dl.dylib.compatibility_version >> 16) & 0xffff) << "."
1204 << ((dl.dylib.compatibility_version >> 8) & 0xff) << "."
1205 << (dl.dylib.compatibility_version & 0xff) << ",";
1206 outs() << " current version "
1207 << ((dl.dylib.current_version >> 16) & 0xffff) << "."
1208 << ((dl.dylib.current_version >> 8) & 0xff) << "."
1209 << (dl.dylib.current_version & 0xff);
1210 if (Load.C.cmd == MachO::LC_LOAD_WEAK_DYLIB)
1212 if (Load.C.cmd == MachO::LC_REEXPORT_DYLIB)
1213 outs() << ", reexport";
1214 if (Load.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB)
1215 outs() << ", upward";
1216 if (Load.C.cmd == MachO::LC_LAZY_LOAD_DYLIB)
1221 outs() << "\tBad offset (" << dl.dylib.name << ") for name of ";
1222 if (Load.C.cmd == MachO::LC_ID_DYLIB)
1223 outs() << "LC_ID_DYLIB ";
1224 else if (Load.C.cmd == MachO::LC_LOAD_DYLIB)
1225 outs() << "LC_LOAD_DYLIB ";
1226 else if (Load.C.cmd == MachO::LC_LOAD_WEAK_DYLIB)
1227 outs() << "LC_LOAD_WEAK_DYLIB ";
1228 else if (Load.C.cmd == MachO::LC_LAZY_LOAD_DYLIB)
1229 outs() << "LC_LAZY_LOAD_DYLIB ";
1230 else if (Load.C.cmd == MachO::LC_REEXPORT_DYLIB)
1231 outs() << "LC_REEXPORT_DYLIB ";
1232 else if (Load.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB)
1233 outs() << "LC_LOAD_UPWARD_DYLIB ";
1235 outs() << "LC_??? ";
1236 outs() << "command " << Index++ << "\n";
1242 typedef DenseMap<uint64_t, StringRef> SymbolAddressMap;
1244 static void CreateSymbolAddressMap(MachOObjectFile *O,
1245 SymbolAddressMap *AddrMap) {
1246 // Create a map of symbol addresses to symbol names.
1247 const StringRef FileName = O->getFileName();
1248 for (const SymbolRef &Symbol : O->symbols()) {
1249 SymbolRef::Type ST = unwrapOrError(Symbol.getType(), FileName);
1250 if (ST == SymbolRef::ST_Function || ST == SymbolRef::ST_Data ||
1251 ST == SymbolRef::ST_Other) {
1252 uint64_t Address = Symbol.getValue();
1253 StringRef SymName = unwrapOrError(Symbol.getName(), FileName);
1254 if (!SymName.startswith(".objc"))
1255 (*AddrMap)[Address] = SymName;
1260 // GuessSymbolName is passed the address of what might be a symbol and a
1261 // pointer to the SymbolAddressMap. It returns the name of a symbol
1262 // with that address or nullptr if no symbol is found with that address.
1263 static const char *GuessSymbolName(uint64_t value, SymbolAddressMap *AddrMap) {
1264 const char *SymbolName = nullptr;
1265 // A DenseMap can't lookup up some values.
1266 if (value != 0xffffffffffffffffULL && value != 0xfffffffffffffffeULL) {
1267 StringRef name = AddrMap->lookup(value);
1269 SymbolName = name.data();
1274 static void DumpCstringChar(const char c) {
1278 outs().write_escaped(p);
1281 static void DumpCstringSection(MachOObjectFile *O, const char *sect,
1282 uint32_t sect_size, uint64_t sect_addr,
1283 bool print_addresses) {
1284 for (uint32_t i = 0; i < sect_size; i++) {
1285 if (print_addresses) {
1287 outs() << format("%016" PRIx64, sect_addr + i) << " ";
1289 outs() << format("%08" PRIx64, sect_addr + i) << " ";
1291 for (; i < sect_size && sect[i] != '\0'; i++)
1292 DumpCstringChar(sect[i]);
1293 if (i < sect_size && sect[i] == '\0')
1298 static void DumpLiteral4(uint32_t l, float f) {
1299 outs() << format("0x%08" PRIx32, l);
1300 if ((l & 0x7f800000) != 0x7f800000)
1301 outs() << format(" (%.16e)\n", f);
1303 if (l == 0x7f800000)
1304 outs() << " (+Infinity)\n";
1305 else if (l == 0xff800000)
1306 outs() << " (-Infinity)\n";
1307 else if ((l & 0x00400000) == 0x00400000)
1308 outs() << " (non-signaling Not-a-Number)\n";
1310 outs() << " (signaling Not-a-Number)\n";
1314 static void DumpLiteral4Section(MachOObjectFile *O, const char *sect,
1315 uint32_t sect_size, uint64_t sect_addr,
1316 bool print_addresses) {
1317 for (uint32_t i = 0; i < sect_size; i += sizeof(float)) {
1318 if (print_addresses) {
1320 outs() << format("%016" PRIx64, sect_addr + i) << " ";
1322 outs() << format("%08" PRIx64, sect_addr + i) << " ";
1325 memcpy(&f, sect + i, sizeof(float));
1326 if (O->isLittleEndian() != sys::IsLittleEndianHost)
1327 sys::swapByteOrder(f);
1329 memcpy(&l, sect + i, sizeof(uint32_t));
1330 if (O->isLittleEndian() != sys::IsLittleEndianHost)
1331 sys::swapByteOrder(l);
1336 static void DumpLiteral8(MachOObjectFile *O, uint32_t l0, uint32_t l1,
1338 outs() << format("0x%08" PRIx32, l0) << " " << format("0x%08" PRIx32, l1);
1340 Hi = (O->isLittleEndian()) ? l1 : l0;
1341 Lo = (O->isLittleEndian()) ? l0 : l1;
1343 // Hi is the high word, so this is equivalent to if(isfinite(d))
1344 if ((Hi & 0x7ff00000) != 0x7ff00000)
1345 outs() << format(" (%.16e)\n", d);
1347 if (Hi == 0x7ff00000 && Lo == 0)
1348 outs() << " (+Infinity)\n";
1349 else if (Hi == 0xfff00000 && Lo == 0)
1350 outs() << " (-Infinity)\n";
1351 else if ((Hi & 0x00080000) == 0x00080000)
1352 outs() << " (non-signaling Not-a-Number)\n";
1354 outs() << " (signaling Not-a-Number)\n";
1358 static void DumpLiteral8Section(MachOObjectFile *O, const char *sect,
1359 uint32_t sect_size, uint64_t sect_addr,
1360 bool print_addresses) {
1361 for (uint32_t i = 0; i < sect_size; i += sizeof(double)) {
1362 if (print_addresses) {
1364 outs() << format("%016" PRIx64, sect_addr + i) << " ";
1366 outs() << format("%08" PRIx64, sect_addr + i) << " ";
1369 memcpy(&d, sect + i, sizeof(double));
1370 if (O->isLittleEndian() != sys::IsLittleEndianHost)
1371 sys::swapByteOrder(d);
1373 memcpy(&l0, sect + i, sizeof(uint32_t));
1374 memcpy(&l1, sect + i + sizeof(uint32_t), sizeof(uint32_t));
1375 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
1376 sys::swapByteOrder(l0);
1377 sys::swapByteOrder(l1);
1379 DumpLiteral8(O, l0, l1, d);
1383 static void DumpLiteral16(uint32_t l0, uint32_t l1, uint32_t l2, uint32_t l3) {
1384 outs() << format("0x%08" PRIx32, l0) << " ";
1385 outs() << format("0x%08" PRIx32, l1) << " ";
1386 outs() << format("0x%08" PRIx32, l2) << " ";
1387 outs() << format("0x%08" PRIx32, l3) << "\n";
1390 static void DumpLiteral16Section(MachOObjectFile *O, const char *sect,
1391 uint32_t sect_size, uint64_t sect_addr,
1392 bool print_addresses) {
1393 for (uint32_t i = 0; i < sect_size; i += 16) {
1394 if (print_addresses) {
1396 outs() << format("%016" PRIx64, sect_addr + i) << " ";
1398 outs() << format("%08" PRIx64, sect_addr + i) << " ";
1400 uint32_t l0, l1, l2, l3;
1401 memcpy(&l0, sect + i, sizeof(uint32_t));
1402 memcpy(&l1, sect + i + sizeof(uint32_t), sizeof(uint32_t));
1403 memcpy(&l2, sect + i + 2 * sizeof(uint32_t), sizeof(uint32_t));
1404 memcpy(&l3, sect + i + 3 * sizeof(uint32_t), sizeof(uint32_t));
1405 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
1406 sys::swapByteOrder(l0);
1407 sys::swapByteOrder(l1);
1408 sys::swapByteOrder(l2);
1409 sys::swapByteOrder(l3);
1411 DumpLiteral16(l0, l1, l2, l3);
1415 static void DumpLiteralPointerSection(MachOObjectFile *O,
1416 const SectionRef &Section,
1417 const char *sect, uint32_t sect_size,
1419 bool print_addresses) {
1420 // Collect the literal sections in this Mach-O file.
1421 std::vector<SectionRef> LiteralSections;
1422 for (const SectionRef &Section : O->sections()) {
1423 DataRefImpl Ref = Section.getRawDataRefImpl();
1424 uint32_t section_type;
1426 const MachO::section_64 Sec = O->getSection64(Ref);
1427 section_type = Sec.flags & MachO::SECTION_TYPE;
1429 const MachO::section Sec = O->getSection(Ref);
1430 section_type = Sec.flags & MachO::SECTION_TYPE;
1432 if (section_type == MachO::S_CSTRING_LITERALS ||
1433 section_type == MachO::S_4BYTE_LITERALS ||
1434 section_type == MachO::S_8BYTE_LITERALS ||
1435 section_type == MachO::S_16BYTE_LITERALS)
1436 LiteralSections.push_back(Section);
1439 // Set the size of the literal pointer.
1440 uint32_t lp_size = O->is64Bit() ? 8 : 4;
1442 // Collect the external relocation symbols for the literal pointers.
1443 std::vector<std::pair<uint64_t, SymbolRef>> Relocs;
1444 for (const RelocationRef &Reloc : Section.relocations()) {
1446 MachO::any_relocation_info RE;
1447 bool isExtern = false;
1448 Rel = Reloc.getRawDataRefImpl();
1449 RE = O->getRelocation(Rel);
1450 isExtern = O->getPlainRelocationExternal(RE);
1452 uint64_t RelocOffset = Reloc.getOffset();
1453 symbol_iterator RelocSym = Reloc.getSymbol();
1454 Relocs.push_back(std::make_pair(RelocOffset, *RelocSym));
1457 array_pod_sort(Relocs.begin(), Relocs.end());
1459 // Dump each literal pointer.
1460 for (uint32_t i = 0; i < sect_size; i += lp_size) {
1461 if (print_addresses) {
1463 outs() << format("%016" PRIx64, sect_addr + i) << " ";
1465 outs() << format("%08" PRIx64, sect_addr + i) << " ";
1469 memcpy(&lp, sect + i, sizeof(uint64_t));
1470 if (O->isLittleEndian() != sys::IsLittleEndianHost)
1471 sys::swapByteOrder(lp);
1474 memcpy(&li, sect + i, sizeof(uint32_t));
1475 if (O->isLittleEndian() != sys::IsLittleEndianHost)
1476 sys::swapByteOrder(li);
1480 // First look for an external relocation entry for this literal pointer.
1481 auto Reloc = find_if(Relocs, [&](const std::pair<uint64_t, SymbolRef> &P) {
1482 return P.first == i;
1484 if (Reloc != Relocs.end()) {
1485 symbol_iterator RelocSym = Reloc->second;
1486 StringRef SymName = unwrapOrError(RelocSym->getName(), O->getFileName());
1487 outs() << "external relocation entry for symbol:" << SymName << "\n";
1491 // For local references see what the section the literal pointer points to.
1492 auto Sect = find_if(LiteralSections, [&](const SectionRef &R) {
1493 return lp >= R.getAddress() && lp < R.getAddress() + R.getSize();
1495 if (Sect == LiteralSections.end()) {
1496 outs() << format("0x%" PRIx64, lp) << " (not in a literal section)\n";
1500 uint64_t SectAddress = Sect->getAddress();
1501 uint64_t SectSize = Sect->getSize();
1504 Sect->getName(SectName);
1505 DataRefImpl Ref = Sect->getRawDataRefImpl();
1506 StringRef SegmentName = O->getSectionFinalSegmentName(Ref);
1507 outs() << SegmentName << ":" << SectName << ":";
1509 uint32_t section_type;
1511 const MachO::section_64 Sec = O->getSection64(Ref);
1512 section_type = Sec.flags & MachO::SECTION_TYPE;
1514 const MachO::section Sec = O->getSection(Ref);
1515 section_type = Sec.flags & MachO::SECTION_TYPE;
1518 StringRef BytesStr = unwrapOrError(Sect->getContents(), O->getFileName());
1520 const char *Contents = reinterpret_cast<const char *>(BytesStr.data());
1522 switch (section_type) {
1523 case MachO::S_CSTRING_LITERALS:
1524 for (uint64_t i = lp - SectAddress; i < SectSize && Contents[i] != '\0';
1526 DumpCstringChar(Contents[i]);
1530 case MachO::S_4BYTE_LITERALS:
1532 memcpy(&f, Contents + (lp - SectAddress), sizeof(float));
1534 memcpy(&l, Contents + (lp - SectAddress), sizeof(uint32_t));
1535 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
1536 sys::swapByteOrder(f);
1537 sys::swapByteOrder(l);
1541 case MachO::S_8BYTE_LITERALS: {
1543 memcpy(&d, Contents + (lp - SectAddress), sizeof(double));
1545 memcpy(&l0, Contents + (lp - SectAddress), sizeof(uint32_t));
1546 memcpy(&l1, Contents + (lp - SectAddress) + sizeof(uint32_t),
1548 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
1549 sys::swapByteOrder(f);
1550 sys::swapByteOrder(l0);
1551 sys::swapByteOrder(l1);
1553 DumpLiteral8(O, l0, l1, d);
1556 case MachO::S_16BYTE_LITERALS: {
1557 uint32_t l0, l1, l2, l3;
1558 memcpy(&l0, Contents + (lp - SectAddress), sizeof(uint32_t));
1559 memcpy(&l1, Contents + (lp - SectAddress) + sizeof(uint32_t),
1561 memcpy(&l2, Contents + (lp - SectAddress) + 2 * sizeof(uint32_t),
1563 memcpy(&l3, Contents + (lp - SectAddress) + 3 * sizeof(uint32_t),
1565 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
1566 sys::swapByteOrder(l0);
1567 sys::swapByteOrder(l1);
1568 sys::swapByteOrder(l2);
1569 sys::swapByteOrder(l3);
1571 DumpLiteral16(l0, l1, l2, l3);
1578 static void DumpInitTermPointerSection(MachOObjectFile *O,
1579 const SectionRef &Section,
1581 uint32_t sect_size, uint64_t sect_addr,
1582 SymbolAddressMap *AddrMap,
1585 stride = (O->is64Bit()) ? sizeof(uint64_t) : sizeof(uint32_t);
1587 // Collect the external relocation symbols for the pointers.
1588 std::vector<std::pair<uint64_t, SymbolRef>> Relocs;
1589 for (const RelocationRef &Reloc : Section.relocations()) {
1591 MachO::any_relocation_info RE;
1592 bool isExtern = false;
1593 Rel = Reloc.getRawDataRefImpl();
1594 RE = O->getRelocation(Rel);
1595 isExtern = O->getPlainRelocationExternal(RE);
1597 uint64_t RelocOffset = Reloc.getOffset();
1598 symbol_iterator RelocSym = Reloc.getSymbol();
1599 Relocs.push_back(std::make_pair(RelocOffset, *RelocSym));
1602 array_pod_sort(Relocs.begin(), Relocs.end());
1604 for (uint32_t i = 0; i < sect_size; i += stride) {
1605 const char *SymbolName = nullptr;
1608 outs() << format("0x%016" PRIx64, sect_addr + i * stride) << " ";
1609 uint64_t pointer_value;
1610 memcpy(&pointer_value, sect + i, stride);
1611 if (O->isLittleEndian() != sys::IsLittleEndianHost)
1612 sys::swapByteOrder(pointer_value);
1613 outs() << format("0x%016" PRIx64, pointer_value);
1616 outs() << format("0x%08" PRIx64, sect_addr + i * stride) << " ";
1617 uint32_t pointer_value;
1618 memcpy(&pointer_value, sect + i, stride);
1619 if (O->isLittleEndian() != sys::IsLittleEndianHost)
1620 sys::swapByteOrder(pointer_value);
1621 outs() << format("0x%08" PRIx32, pointer_value);
1625 // First look for an external relocation entry for this pointer.
1626 auto Reloc = find_if(Relocs, [&](const std::pair<uint64_t, SymbolRef> &P) {
1627 return P.first == i;
1629 if (Reloc != Relocs.end()) {
1630 symbol_iterator RelocSym = Reloc->second;
1631 outs() << " " << unwrapOrError(RelocSym->getName(), O->getFileName());
1633 SymbolName = GuessSymbolName(p, AddrMap);
1635 outs() << " " << SymbolName;
1642 static void DumpRawSectionContents(MachOObjectFile *O, const char *sect,
1643 uint32_t size, uint64_t addr) {
1644 uint32_t cputype = O->getHeader().cputype;
1645 if (cputype == MachO::CPU_TYPE_I386 || cputype == MachO::CPU_TYPE_X86_64) {
1647 for (uint32_t i = 0; i < size; i += j, addr += j) {
1649 outs() << format("%016" PRIx64, addr) << "\t";
1651 outs() << format("%08" PRIx64, addr) << "\t";
1652 for (j = 0; j < 16 && i + j < size; j++) {
1653 uint8_t byte_word = *(sect + i + j);
1654 outs() << format("%02" PRIx32, (uint32_t)byte_word) << " ";
1660 for (uint32_t i = 0; i < size; i += j, addr += j) {
1662 outs() << format("%016" PRIx64, addr) << "\t";
1664 outs() << format("%08" PRIx64, addr) << "\t";
1665 for (j = 0; j < 4 * sizeof(int32_t) && i + j < size;
1666 j += sizeof(int32_t)) {
1667 if (i + j + sizeof(int32_t) <= size) {
1669 memcpy(&long_word, sect + i + j, sizeof(int32_t));
1670 if (O->isLittleEndian() != sys::IsLittleEndianHost)
1671 sys::swapByteOrder(long_word);
1672 outs() << format("%08" PRIx32, long_word) << " ";
1674 for (uint32_t k = 0; i + j + k < size; k++) {
1675 uint8_t byte_word = *(sect + i + j + k);
1676 outs() << format("%02" PRIx32, (uint32_t)byte_word) << " ";
1685 static void DisassembleMachO(StringRef Filename, MachOObjectFile *MachOOF,
1686 StringRef DisSegName, StringRef DisSectName);
1687 static void DumpProtocolSection(MachOObjectFile *O, const char *sect,
1688 uint32_t size, uint32_t addr);
1690 static void DumpBitcodeSection(MachOObjectFile *O, const char *sect,
1691 uint32_t size, bool verbose,
1692 bool PrintXarHeader, bool PrintXarFileHeaders,
1693 std::string XarMemberName);
1694 #endif // defined(HAVE_LIBXAR)
1696 static void DumpSectionContents(StringRef Filename, MachOObjectFile *O,
1698 SymbolAddressMap AddrMap;
1700 CreateSymbolAddressMap(O, &AddrMap);
1702 for (unsigned i = 0; i < FilterSections.size(); ++i) {
1703 StringRef DumpSection = FilterSections[i];
1704 std::pair<StringRef, StringRef> DumpSegSectName;
1705 DumpSegSectName = DumpSection.split(',');
1706 StringRef DumpSegName, DumpSectName;
1707 if (!DumpSegSectName.second.empty()) {
1708 DumpSegName = DumpSegSectName.first;
1709 DumpSectName = DumpSegSectName.second;
1712 DumpSectName = DumpSegSectName.first;
1714 for (const SectionRef &Section : O->sections()) {
1716 Section.getName(SectName);
1717 DataRefImpl Ref = Section.getRawDataRefImpl();
1718 StringRef SegName = O->getSectionFinalSegmentName(Ref);
1719 if ((DumpSegName.empty() || SegName == DumpSegName) &&
1720 (SectName == DumpSectName)) {
1722 uint32_t section_flags;
1724 const MachO::section_64 Sec = O->getSection64(Ref);
1725 section_flags = Sec.flags;
1728 const MachO::section Sec = O->getSection(Ref);
1729 section_flags = Sec.flags;
1731 uint32_t section_type = section_flags & MachO::SECTION_TYPE;
1733 StringRef BytesStr =
1734 unwrapOrError(Section.getContents(), O->getFileName());
1735 const char *sect = reinterpret_cast<const char *>(BytesStr.data());
1736 uint32_t sect_size = BytesStr.size();
1737 uint64_t sect_addr = Section.getAddress();
1739 outs() << "Contents of (" << SegName << "," << SectName
1743 if ((section_flags & MachO::S_ATTR_PURE_INSTRUCTIONS) ||
1744 (section_flags & MachO::S_ATTR_SOME_INSTRUCTIONS)) {
1745 DisassembleMachO(Filename, O, SegName, SectName);
1748 if (SegName == "__TEXT" && SectName == "__info_plist") {
1752 if (SegName == "__OBJC" && SectName == "__protocol") {
1753 DumpProtocolSection(O, sect, sect_size, sect_addr);
1757 if (SegName == "__LLVM" && SectName == "__bundle") {
1758 DumpBitcodeSection(O, sect, sect_size, verbose, !NoSymbolicOperands,
1759 ArchiveHeaders, "");
1762 #endif // defined(HAVE_LIBXAR)
1763 switch (section_type) {
1764 case MachO::S_REGULAR:
1765 DumpRawSectionContents(O, sect, sect_size, sect_addr);
1767 case MachO::S_ZEROFILL:
1768 outs() << "zerofill section and has no contents in the file\n";
1770 case MachO::S_CSTRING_LITERALS:
1771 DumpCstringSection(O, sect, sect_size, sect_addr, !NoLeadingAddr);
1773 case MachO::S_4BYTE_LITERALS:
1774 DumpLiteral4Section(O, sect, sect_size, sect_addr, !NoLeadingAddr);
1776 case MachO::S_8BYTE_LITERALS:
1777 DumpLiteral8Section(O, sect, sect_size, sect_addr, !NoLeadingAddr);
1779 case MachO::S_16BYTE_LITERALS:
1780 DumpLiteral16Section(O, sect, sect_size, sect_addr, !NoLeadingAddr);
1782 case MachO::S_LITERAL_POINTERS:
1783 DumpLiteralPointerSection(O, Section, sect, sect_size, sect_addr,
1786 case MachO::S_MOD_INIT_FUNC_POINTERS:
1787 case MachO::S_MOD_TERM_FUNC_POINTERS:
1788 DumpInitTermPointerSection(O, Section, sect, sect_size, sect_addr,
1792 outs() << "Unknown section type ("
1793 << format("0x%08" PRIx32, section_type) << ")\n";
1794 DumpRawSectionContents(O, sect, sect_size, sect_addr);
1798 if (section_type == MachO::S_ZEROFILL)
1799 outs() << "zerofill section and has no contents in the file\n";
1801 DumpRawSectionContents(O, sect, sect_size, sect_addr);
1808 static void DumpInfoPlistSectionContents(StringRef Filename,
1809 MachOObjectFile *O) {
1810 for (const SectionRef &Section : O->sections()) {
1812 Section.getName(SectName);
1813 DataRefImpl Ref = Section.getRawDataRefImpl();
1814 StringRef SegName = O->getSectionFinalSegmentName(Ref);
1815 if (SegName == "__TEXT" && SectName == "__info_plist") {
1816 if (!NoLeadingHeaders)
1817 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
1818 StringRef BytesStr =
1819 unwrapOrError(Section.getContents(), O->getFileName());
1820 const char *sect = reinterpret_cast<const char *>(BytesStr.data());
1821 outs() << format("%.*s", BytesStr.size(), sect) << "\n";
1827 // checkMachOAndArchFlags() checks to see if the ObjectFile is a Mach-O file
1828 // and if it is and there is a list of architecture flags is specified then
1829 // check to make sure this Mach-O file is one of those architectures or all
1830 // architectures were specified. If not then an error is generated and this
1831 // routine returns false. Else it returns true.
1832 static bool checkMachOAndArchFlags(ObjectFile *O, StringRef Filename) {
1833 auto *MachO = dyn_cast<MachOObjectFile>(O);
1835 if (!MachO || ArchAll || ArchFlags.empty())
1838 MachO::mach_header H;
1839 MachO::mach_header_64 H_64;
1841 const char *McpuDefault, *ArchFlag;
1842 if (MachO->is64Bit()) {
1843 H_64 = MachO->MachOObjectFile::getHeader64();
1844 T = MachOObjectFile::getArchTriple(H_64.cputype, H_64.cpusubtype,
1845 &McpuDefault, &ArchFlag);
1847 H = MachO->MachOObjectFile::getHeader();
1848 T = MachOObjectFile::getArchTriple(H.cputype, H.cpusubtype,
1849 &McpuDefault, &ArchFlag);
1851 const std::string ArchFlagName(ArchFlag);
1852 if (none_of(ArchFlags, [&](const std::string &Name) {
1853 return Name == ArchFlagName;
1855 WithColor::error(errs(), "llvm-objdump")
1856 << Filename << ": no architecture specified.\n";
1862 static void printObjcMetaData(MachOObjectFile *O, bool verbose);
1864 // ProcessMachO() is passed a single opened Mach-O file, which may be an
1865 // archive member and or in a slice of a universal file. It prints the
1866 // the file name and header info and then processes it according to the
1867 // command line options.
1868 static void ProcessMachO(StringRef Name, MachOObjectFile *MachOOF,
1869 StringRef ArchiveMemberName = StringRef(),
1870 StringRef ArchitectureName = StringRef()) {
1871 // If we are doing some processing here on the Mach-O file print the header
1872 // info. And don't print it otherwise like in the case of printing the
1873 // UniversalHeaders or ArchiveHeaders.
1874 if (Disassemble || Relocations || PrivateHeaders || ExportsTrie || Rebase ||
1875 Bind || SymbolTable || LazyBind || WeakBind || IndirectSymbols ||
1876 DataInCode || LinkOptHints || DylibsUsed || DylibId || ObjcMetaData ||
1877 (!FilterSections.empty())) {
1878 if (!NoLeadingHeaders) {
1880 if (!ArchiveMemberName.empty())
1881 outs() << '(' << ArchiveMemberName << ')';
1882 if (!ArchitectureName.empty())
1883 outs() << " (architecture " << ArchitectureName << ")";
1887 // To use the report_error() form with an ArchiveName and FileName set
1888 // these up based on what is passed for Name and ArchiveMemberName.
1889 StringRef ArchiveName;
1891 if (!ArchiveMemberName.empty()) {
1893 FileName = ArchiveMemberName;
1895 ArchiveName = StringRef();
1899 // If we need the symbol table to do the operation then check it here to
1900 // produce a good error message as to where the Mach-O file comes from in
1901 // the error message.
1902 if (Disassemble || IndirectSymbols || !FilterSections.empty() || UnwindInfo)
1903 if (Error Err = MachOOF->checkSymbolTable())
1904 report_error(std::move(Err), ArchiveName, FileName, ArchitectureName);
1906 if (DisassembleAll) {
1907 for (const SectionRef &Section : MachOOF->sections()) {
1909 Section.getName(SectName);
1910 if (SectName.equals("__text")) {
1911 DataRefImpl Ref = Section.getRawDataRefImpl();
1912 StringRef SegName = MachOOF->getSectionFinalSegmentName(Ref);
1913 DisassembleMachO(FileName, MachOOF, SegName, SectName);
1917 else if (Disassemble) {
1918 if (MachOOF->getHeader().filetype == MachO::MH_KEXT_BUNDLE &&
1919 MachOOF->getHeader().cputype == MachO::CPU_TYPE_ARM64)
1920 DisassembleMachO(FileName, MachOOF, "__TEXT_EXEC", "__text");
1922 DisassembleMachO(FileName, MachOOF, "__TEXT", "__text");
1924 if (IndirectSymbols)
1925 PrintIndirectSymbols(MachOOF, !NonVerbose);
1927 PrintDataInCodeTable(MachOOF, !NonVerbose);
1929 PrintLinkOptHints(MachOOF);
1931 PrintRelocations(MachOOF, !NonVerbose);
1933 printSectionHeaders(MachOOF);
1934 if (SectionContents)
1935 printSectionContents(MachOOF);
1936 if (!FilterSections.empty())
1937 DumpSectionContents(FileName, MachOOF, !NonVerbose);
1939 DumpInfoPlistSectionContents(FileName, MachOOF);
1941 PrintDylibs(MachOOF, false);
1943 PrintDylibs(MachOOF, true);
1945 printSymbolTable(MachOOF, ArchiveName, ArchitectureName);
1947 printMachOUnwindInfo(MachOOF);
1948 if (PrivateHeaders) {
1949 printMachOFileHeader(MachOOF);
1950 printMachOLoadCommands(MachOOF);
1952 if (FirstPrivateHeader)
1953 printMachOFileHeader(MachOOF);
1955 printObjcMetaData(MachOOF, !NonVerbose);
1957 printExportsTrie(MachOOF);
1959 printRebaseTable(MachOOF);
1961 printBindTable(MachOOF);
1963 printLazyBindTable(MachOOF);
1965 printWeakBindTable(MachOOF);
1967 if (DwarfDumpType != DIDT_Null) {
1968 std::unique_ptr<DIContext> DICtx = DWARFContext::create(*MachOOF);
1969 // Dump the complete DWARF structure.
1970 DIDumpOptions DumpOpts;
1971 DumpOpts.DumpType = DwarfDumpType;
1972 DICtx->dump(outs(), DumpOpts);
1976 // printUnknownCPUType() helps print_fat_headers for unknown CPU's.
1977 static void printUnknownCPUType(uint32_t cputype, uint32_t cpusubtype) {
1978 outs() << " cputype (" << cputype << ")\n";
1979 outs() << " cpusubtype (" << cpusubtype << ")\n";
1982 // printCPUType() helps print_fat_headers by printing the cputype and
1983 // pusubtype (symbolically for the one's it knows about).
1984 static void printCPUType(uint32_t cputype, uint32_t cpusubtype) {
1986 case MachO::CPU_TYPE_I386:
1987 switch (cpusubtype) {
1988 case MachO::CPU_SUBTYPE_I386_ALL:
1989 outs() << " cputype CPU_TYPE_I386\n";
1990 outs() << " cpusubtype CPU_SUBTYPE_I386_ALL\n";
1993 printUnknownCPUType(cputype, cpusubtype);
1997 case MachO::CPU_TYPE_X86_64:
1998 switch (cpusubtype) {
1999 case MachO::CPU_SUBTYPE_X86_64_ALL:
2000 outs() << " cputype CPU_TYPE_X86_64\n";
2001 outs() << " cpusubtype CPU_SUBTYPE_X86_64_ALL\n";
2003 case MachO::CPU_SUBTYPE_X86_64_H:
2004 outs() << " cputype CPU_TYPE_X86_64\n";
2005 outs() << " cpusubtype CPU_SUBTYPE_X86_64_H\n";
2008 printUnknownCPUType(cputype, cpusubtype);
2012 case MachO::CPU_TYPE_ARM:
2013 switch (cpusubtype) {
2014 case MachO::CPU_SUBTYPE_ARM_ALL:
2015 outs() << " cputype CPU_TYPE_ARM\n";
2016 outs() << " cpusubtype CPU_SUBTYPE_ARM_ALL\n";
2018 case MachO::CPU_SUBTYPE_ARM_V4T:
2019 outs() << " cputype CPU_TYPE_ARM\n";
2020 outs() << " cpusubtype CPU_SUBTYPE_ARM_V4T\n";
2022 case MachO::CPU_SUBTYPE_ARM_V5TEJ:
2023 outs() << " cputype CPU_TYPE_ARM\n";
2024 outs() << " cpusubtype CPU_SUBTYPE_ARM_V5TEJ\n";
2026 case MachO::CPU_SUBTYPE_ARM_XSCALE:
2027 outs() << " cputype CPU_TYPE_ARM\n";
2028 outs() << " cpusubtype CPU_SUBTYPE_ARM_XSCALE\n";
2030 case MachO::CPU_SUBTYPE_ARM_V6:
2031 outs() << " cputype CPU_TYPE_ARM\n";
2032 outs() << " cpusubtype CPU_SUBTYPE_ARM_V6\n";
2034 case MachO::CPU_SUBTYPE_ARM_V6M:
2035 outs() << " cputype CPU_TYPE_ARM\n";
2036 outs() << " cpusubtype CPU_SUBTYPE_ARM_V6M\n";
2038 case MachO::CPU_SUBTYPE_ARM_V7:
2039 outs() << " cputype CPU_TYPE_ARM\n";
2040 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7\n";
2042 case MachO::CPU_SUBTYPE_ARM_V7EM:
2043 outs() << " cputype CPU_TYPE_ARM\n";
2044 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7EM\n";
2046 case MachO::CPU_SUBTYPE_ARM_V7K:
2047 outs() << " cputype CPU_TYPE_ARM\n";
2048 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7K\n";
2050 case MachO::CPU_SUBTYPE_ARM_V7M:
2051 outs() << " cputype CPU_TYPE_ARM\n";
2052 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7M\n";
2054 case MachO::CPU_SUBTYPE_ARM_V7S:
2055 outs() << " cputype CPU_TYPE_ARM\n";
2056 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7S\n";
2059 printUnknownCPUType(cputype, cpusubtype);
2063 case MachO::CPU_TYPE_ARM64:
2064 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
2065 case MachO::CPU_SUBTYPE_ARM64_ALL:
2066 outs() << " cputype CPU_TYPE_ARM64\n";
2067 outs() << " cpusubtype CPU_SUBTYPE_ARM64_ALL\n";
2069 case MachO::CPU_SUBTYPE_ARM64E:
2070 outs() << " cputype CPU_TYPE_ARM64\n";
2071 outs() << " cpusubtype CPU_SUBTYPE_ARM64E\n";
2074 printUnknownCPUType(cputype, cpusubtype);
2078 case MachO::CPU_TYPE_ARM64_32:
2079 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
2080 case MachO::CPU_SUBTYPE_ARM64_32_V8:
2081 outs() << " cputype CPU_TYPE_ARM64_32\n";
2082 outs() << " cpusubtype CPU_SUBTYPE_ARM64_32_V8\n";
2085 printUnknownCPUType(cputype, cpusubtype);
2090 printUnknownCPUType(cputype, cpusubtype);
2095 static void printMachOUniversalHeaders(const object::MachOUniversalBinary *UB,
2097 outs() << "Fat headers\n";
2099 if (UB->getMagic() == MachO::FAT_MAGIC)
2100 outs() << "fat_magic FAT_MAGIC\n";
2101 else // UB->getMagic() == MachO::FAT_MAGIC_64
2102 outs() << "fat_magic FAT_MAGIC_64\n";
2104 outs() << "fat_magic " << format("0x%" PRIx32, MachO::FAT_MAGIC) << "\n";
2106 uint32_t nfat_arch = UB->getNumberOfObjects();
2107 StringRef Buf = UB->getData();
2108 uint64_t size = Buf.size();
2109 uint64_t big_size = sizeof(struct MachO::fat_header) +
2110 nfat_arch * sizeof(struct MachO::fat_arch);
2111 outs() << "nfat_arch " << UB->getNumberOfObjects();
2113 outs() << " (malformed, contains zero architecture types)\n";
2114 else if (big_size > size)
2115 outs() << " (malformed, architectures past end of file)\n";
2119 for (uint32_t i = 0; i < nfat_arch; ++i) {
2120 MachOUniversalBinary::ObjectForArch OFA(UB, i);
2121 uint32_t cputype = OFA.getCPUType();
2122 uint32_t cpusubtype = OFA.getCPUSubType();
2123 outs() << "architecture ";
2124 for (uint32_t j = 0; i != 0 && j <= i - 1; j++) {
2125 MachOUniversalBinary::ObjectForArch other_OFA(UB, j);
2126 uint32_t other_cputype = other_OFA.getCPUType();
2127 uint32_t other_cpusubtype = other_OFA.getCPUSubType();
2128 if (cputype != 0 && cpusubtype != 0 && cputype == other_cputype &&
2129 (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) ==
2130 (other_cpusubtype & ~MachO::CPU_SUBTYPE_MASK)) {
2131 outs() << "(illegal duplicate architecture) ";
2136 outs() << OFA.getArchFlagName() << "\n";
2137 printCPUType(cputype, cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
2139 outs() << i << "\n";
2140 outs() << " cputype " << cputype << "\n";
2141 outs() << " cpusubtype " << (cpusubtype & ~MachO::CPU_SUBTYPE_MASK)
2145 (cpusubtype & MachO::CPU_SUBTYPE_MASK) == MachO::CPU_SUBTYPE_LIB64)
2146 outs() << " capabilities CPU_SUBTYPE_LIB64\n";
2148 outs() << " capabilities "
2149 << format("0x%" PRIx32,
2150 (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24) << "\n";
2151 outs() << " offset " << OFA.getOffset();
2152 if (OFA.getOffset() > size)
2153 outs() << " (past end of file)";
2154 if (OFA.getOffset() % (1 << OFA.getAlign()) != 0)
2155 outs() << " (not aligned on it's alignment (2^" << OFA.getAlign() << ")";
2157 outs() << " size " << OFA.getSize();
2158 big_size = OFA.getOffset() + OFA.getSize();
2159 if (big_size > size)
2160 outs() << " (past end of file)";
2162 outs() << " align 2^" << OFA.getAlign() << " (" << (1 << OFA.getAlign())
2167 static void printArchiveChild(StringRef Filename, const Archive::Child &C,
2168 bool verbose, bool print_offset,
2169 StringRef ArchitectureName = StringRef()) {
2171 outs() << C.getChildOffset() << "\t";
2172 sys::fs::perms Mode =
2173 unwrapOrError(C.getAccessMode(), Filename, C, ArchitectureName);
2175 // FIXME: this first dash, "-", is for (Mode & S_IFMT) == S_IFREG.
2176 // But there is nothing in sys::fs::perms for S_IFMT or S_IFREG.
2178 outs() << ((Mode & sys::fs::owner_read) ? "r" : "-");
2179 outs() << ((Mode & sys::fs::owner_write) ? "w" : "-");
2180 outs() << ((Mode & sys::fs::owner_exe) ? "x" : "-");
2181 outs() << ((Mode & sys::fs::group_read) ? "r" : "-");
2182 outs() << ((Mode & sys::fs::group_write) ? "w" : "-");
2183 outs() << ((Mode & sys::fs::group_exe) ? "x" : "-");
2184 outs() << ((Mode & sys::fs::others_read) ? "r" : "-");
2185 outs() << ((Mode & sys::fs::others_write) ? "w" : "-");
2186 outs() << ((Mode & sys::fs::others_exe) ? "x" : "-");
2188 outs() << format("0%o ", Mode);
2192 "%3d/%-3d %5" PRId64 " ",
2193 unwrapOrError(C.getUID(), Filename, C, ArchitectureName),
2194 unwrapOrError(C.getGID(), Filename, C, ArchitectureName),
2195 unwrapOrError(C.getRawSize(), Filename, C, ArchitectureName));
2197 StringRef RawLastModified = C.getRawLastModified();
2200 if (RawLastModified.getAsInteger(10, Seconds))
2201 outs() << "(date: \"" << RawLastModified
2202 << "\" contains non-decimal chars) ";
2204 // Since cime(3) returns a 26 character string of the form:
2205 // "Sun Sep 16 01:03:52 1973\n\0"
2206 // just print 24 characters.
2208 outs() << format("%.24s ", ctime(&t));
2211 outs() << RawLastModified << " ";
2215 Expected<StringRef> NameOrErr = C.getName();
2217 consumeError(NameOrErr.takeError());
2218 outs() << unwrapOrError(C.getRawName(), Filename, C, ArchitectureName)
2221 StringRef Name = NameOrErr.get();
2222 outs() << Name << "\n";
2225 outs() << unwrapOrError(C.getRawName(), Filename, C, ArchitectureName)
2230 static void printArchiveHeaders(StringRef Filename, Archive *A, bool verbose,
2232 StringRef ArchitectureName = StringRef()) {
2233 Error Err = Error::success();
2234 for (const auto &C : A->children(Err, false))
2235 printArchiveChild(Filename, C, verbose, print_offset, ArchitectureName);
2238 report_error(std::move(Err), StringRef(), Filename, ArchitectureName);
2241 static bool ValidateArchFlags() {
2242 // Check for -arch all and verifiy the -arch flags are valid.
2243 for (unsigned i = 0; i < ArchFlags.size(); ++i) {
2244 if (ArchFlags[i] == "all") {
2247 if (!MachOObjectFile::isValidArch(ArchFlags[i])) {
2248 WithColor::error(errs(), "llvm-objdump")
2249 << "unknown architecture named '" + ArchFlags[i] +
2250 "'for the -arch option\n";
2258 // ParseInputMachO() parses the named Mach-O file in Filename and handles the
2259 // -arch flags selecting just those slices as specified by them and also parses
2260 // archive files. Then for each individual Mach-O file ProcessMachO() is
2261 // called to process the file based on the command line options.
2262 void parseInputMachO(StringRef Filename) {
2263 if (!ValidateArchFlags())
2266 // Attempt to open the binary.
2267 Expected<OwningBinary<Binary>> BinaryOrErr = createBinary(Filename);
2269 if (Error E = isNotObjectErrorInvalidFileType(BinaryOrErr.takeError()))
2270 report_error(std::move(E), Filename);
2272 outs() << Filename << ": is not an object file\n";
2275 Binary &Bin = *BinaryOrErr.get().getBinary();
2277 if (Archive *A = dyn_cast<Archive>(&Bin)) {
2278 outs() << "Archive : " << Filename << "\n";
2280 printArchiveHeaders(Filename, A, !NonVerbose, ArchiveMemberOffsets);
2282 Error Err = Error::success();
2283 for (auto &C : A->children(Err)) {
2284 Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
2286 if (Error E = isNotObjectErrorInvalidFileType(ChildOrErr.takeError()))
2287 report_error(std::move(E), Filename, C);
2290 if (MachOObjectFile *O = dyn_cast<MachOObjectFile>(&*ChildOrErr.get())) {
2291 if (!checkMachOAndArchFlags(O, Filename))
2293 ProcessMachO(Filename, O, O->getFileName());
2297 report_error(std::move(Err), Filename);
2300 if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(&Bin)) {
2301 parseInputMachO(UB);
2304 if (ObjectFile *O = dyn_cast<ObjectFile>(&Bin)) {
2305 if (!checkMachOAndArchFlags(O, Filename))
2307 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&*O))
2308 ProcessMachO(Filename, MachOOF);
2310 WithColor::error(errs(), "llvm-objdump")
2311 << Filename << "': "
2312 << "object is not a Mach-O file type.\n";
2315 llvm_unreachable("Input object can't be invalid at this point");
2318 void parseInputMachO(MachOUniversalBinary *UB) {
2319 if (!ValidateArchFlags())
2322 auto Filename = UB->getFileName();
2324 if (UniversalHeaders)
2325 printMachOUniversalHeaders(UB, !NonVerbose);
2327 // If we have a list of architecture flags specified dump only those.
2328 if (!ArchAll && !ArchFlags.empty()) {
2329 // Look for a slice in the universal binary that matches each ArchFlag.
2331 for (unsigned i = 0; i < ArchFlags.size(); ++i) {
2333 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
2334 E = UB->end_objects();
2336 if (ArchFlags[i] == I->getArchFlagName()) {
2338 Expected<std::unique_ptr<ObjectFile>> ObjOrErr =
2339 I->getAsObjectFile();
2340 std::string ArchitectureName = "";
2341 if (ArchFlags.size() > 1)
2342 ArchitectureName = I->getArchFlagName();
2344 ObjectFile &O = *ObjOrErr.get();
2345 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&O))
2346 ProcessMachO(Filename, MachOOF, "", ArchitectureName);
2347 } else if (Error E = isNotObjectErrorInvalidFileType(
2348 ObjOrErr.takeError())) {
2349 report_error(std::move(E), Filename, StringRef(), ArchitectureName);
2351 } else if (Expected<std::unique_ptr<Archive>> AOrErr =
2352 I->getAsArchive()) {
2353 std::unique_ptr<Archive> &A = *AOrErr;
2354 outs() << "Archive : " << Filename;
2355 if (!ArchitectureName.empty())
2356 outs() << " (architecture " << ArchitectureName << ")";
2359 printArchiveHeaders(Filename, A.get(), !NonVerbose,
2360 ArchiveMemberOffsets, ArchitectureName);
2361 Error Err = Error::success();
2362 for (auto &C : A->children(Err)) {
2363 Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
2365 if (Error E = isNotObjectErrorInvalidFileType(ChildOrErr.takeError()))
2366 report_error(std::move(E), Filename, C, ArchitectureName);
2369 if (MachOObjectFile *O =
2370 dyn_cast<MachOObjectFile>(&*ChildOrErr.get()))
2371 ProcessMachO(Filename, O, O->getFileName(), ArchitectureName);
2374 report_error(std::move(Err), Filename);
2376 consumeError(AOrErr.takeError());
2377 error("Mach-O universal file: " + Filename + " for " +
2378 "architecture " + StringRef(I->getArchFlagName()) +
2379 " is not a Mach-O file or an archive file");
2384 WithColor::error(errs(), "llvm-objdump")
2385 << "file: " + Filename + " does not contain "
2386 << "architecture: " + ArchFlags[i] + "\n";
2392 // No architecture flags were specified so if this contains a slice that
2393 // matches the host architecture dump only that.
2395 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
2396 E = UB->end_objects();
2398 if (MachOObjectFile::getHostArch().getArchName() ==
2399 I->getArchFlagName()) {
2400 Expected<std::unique_ptr<ObjectFile>> ObjOrErr = I->getAsObjectFile();
2401 std::string ArchiveName;
2402 ArchiveName.clear();
2404 ObjectFile &O = *ObjOrErr.get();
2405 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&O))
2406 ProcessMachO(Filename, MachOOF);
2407 } else if (Error E =
2408 isNotObjectErrorInvalidFileType(ObjOrErr.takeError())) {
2409 report_error(std::move(E), Filename);
2410 } else if (Expected<std::unique_ptr<Archive>> AOrErr =
2411 I->getAsArchive()) {
2412 std::unique_ptr<Archive> &A = *AOrErr;
2413 outs() << "Archive : " << Filename << "\n";
2415 printArchiveHeaders(Filename, A.get(), !NonVerbose,
2416 ArchiveMemberOffsets);
2417 Error Err = Error::success();
2418 for (auto &C : A->children(Err)) {
2419 Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
2422 isNotObjectErrorInvalidFileType(ChildOrErr.takeError()))
2423 report_error(std::move(E), Filename, C);
2426 if (MachOObjectFile *O =
2427 dyn_cast<MachOObjectFile>(&*ChildOrErr.get()))
2428 ProcessMachO(Filename, O, O->getFileName());
2431 report_error(std::move(Err), Filename);
2433 consumeError(AOrErr.takeError());
2434 error("Mach-O universal file: " + Filename + " for architecture " +
2435 StringRef(I->getArchFlagName()) +
2436 " is not a Mach-O file or an archive file");
2442 // Either all architectures have been specified or none have been specified
2443 // and this does not contain the host architecture so dump all the slices.
2444 bool moreThanOneArch = UB->getNumberOfObjects() > 1;
2445 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
2446 E = UB->end_objects();
2448 Expected<std::unique_ptr<ObjectFile>> ObjOrErr = I->getAsObjectFile();
2449 std::string ArchitectureName = "";
2450 if (moreThanOneArch)
2451 ArchitectureName = I->getArchFlagName();
2453 ObjectFile &Obj = *ObjOrErr.get();
2454 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&Obj))
2455 ProcessMachO(Filename, MachOOF, "", ArchitectureName);
2456 } else if (Error E =
2457 isNotObjectErrorInvalidFileType(ObjOrErr.takeError())) {
2458 report_error(std::move(E), StringRef(), Filename, ArchitectureName);
2459 } else if (Expected<std::unique_ptr<Archive>> AOrErr = I->getAsArchive()) {
2460 std::unique_ptr<Archive> &A = *AOrErr;
2461 outs() << "Archive : " << Filename;
2462 if (!ArchitectureName.empty())
2463 outs() << " (architecture " << ArchitectureName << ")";
2466 printArchiveHeaders(Filename, A.get(), !NonVerbose,
2467 ArchiveMemberOffsets, ArchitectureName);
2468 Error Err = Error::success();
2469 for (auto &C : A->children(Err)) {
2470 Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
2472 if (Error E = isNotObjectErrorInvalidFileType(ChildOrErr.takeError()))
2473 report_error(std::move(E), Filename, C, ArchitectureName);
2476 if (MachOObjectFile *O =
2477 dyn_cast<MachOObjectFile>(&*ChildOrErr.get())) {
2478 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(O))
2479 ProcessMachO(Filename, MachOOF, MachOOF->getFileName(),
2484 report_error(std::move(Err), Filename);
2486 consumeError(AOrErr.takeError());
2487 error("Mach-O universal file: " + Filename + " for architecture " +
2488 StringRef(I->getArchFlagName()) +
2489 " is not a Mach-O file or an archive file");
2494 // The block of info used by the Symbolizer call backs.
2495 struct DisassembleInfo {
2496 DisassembleInfo(MachOObjectFile *O, SymbolAddressMap *AddrMap,
2497 std::vector<SectionRef> *Sections, bool verbose)
2498 : verbose(verbose), O(O), AddrMap(AddrMap), Sections(Sections) {}
2502 SymbolAddressMap *AddrMap;
2503 std::vector<SectionRef> *Sections;
2504 const char *class_name = nullptr;
2505 const char *selector_name = nullptr;
2506 std::unique_ptr<char[]> method = nullptr;
2507 char *demangled_name = nullptr;
2508 uint64_t adrp_addr = 0;
2509 uint32_t adrp_inst = 0;
2510 std::unique_ptr<SymbolAddressMap> bindtable;
2514 // SymbolizerGetOpInfo() is the operand information call back function.
2515 // This is called to get the symbolic information for operand(s) of an
2516 // instruction when it is being done. This routine does this from
2517 // the relocation information, symbol table, etc. That block of information
2518 // is a pointer to the struct DisassembleInfo that was passed when the
2519 // disassembler context was created and passed to back to here when
2520 // called back by the disassembler for instruction operands that could have
2521 // relocation information. The address of the instruction containing operand is
2522 // at the Pc parameter. The immediate value the operand has is passed in
2523 // op_info->Value and is at Offset past the start of the instruction and has a
2524 // byte Size of 1, 2 or 4. The symbolc information is returned in TagBuf is the
2525 // LLVMOpInfo1 struct defined in the header "llvm-c/Disassembler.h" as symbol
2526 // names and addends of the symbolic expression to add for the operand. The
2527 // value of TagType is currently 1 (for the LLVMOpInfo1 struct). If symbolic
2528 // information is returned then this function returns 1 else it returns 0.
2529 static int SymbolizerGetOpInfo(void *DisInfo, uint64_t Pc, uint64_t Offset,
2530 uint64_t Size, int TagType, void *TagBuf) {
2531 struct DisassembleInfo *info = (struct DisassembleInfo *)DisInfo;
2532 struct LLVMOpInfo1 *op_info = (struct LLVMOpInfo1 *)TagBuf;
2533 uint64_t value = op_info->Value;
2535 // Make sure all fields returned are zero if we don't set them.
2536 memset((void *)op_info, '\0', sizeof(struct LLVMOpInfo1));
2537 op_info->Value = value;
2539 // If the TagType is not the value 1 which it code knows about or if no
2540 // verbose symbolic information is wanted then just return 0, indicating no
2541 // information is being returned.
2542 if (TagType != 1 || !info->verbose)
2545 unsigned int Arch = info->O->getArch();
2546 if (Arch == Triple::x86) {
2547 if (Size != 1 && Size != 2 && Size != 4 && Size != 0)
2549 if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
2551 // Search the external relocation entries of a fully linked image
2552 // (if any) for an entry that matches this segment offset.
2553 // uint32_t seg_offset = (Pc + Offset);
2556 // In MH_OBJECT filetypes search the section's relocation entries (if any)
2557 // for an entry for this section offset.
2558 uint32_t sect_addr = info->S.getAddress();
2559 uint32_t sect_offset = (Pc + Offset) - sect_addr;
2560 bool reloc_found = false;
2562 MachO::any_relocation_info RE;
2563 bool isExtern = false;
2565 bool r_scattered = false;
2566 uint32_t r_value, pair_r_value, r_type;
2567 for (const RelocationRef &Reloc : info->S.relocations()) {
2568 uint64_t RelocOffset = Reloc.getOffset();
2569 if (RelocOffset == sect_offset) {
2570 Rel = Reloc.getRawDataRefImpl();
2571 RE = info->O->getRelocation(Rel);
2572 r_type = info->O->getAnyRelocationType(RE);
2573 r_scattered = info->O->isRelocationScattered(RE);
2575 r_value = info->O->getScatteredRelocationValue(RE);
2576 if (r_type == MachO::GENERIC_RELOC_SECTDIFF ||
2577 r_type == MachO::GENERIC_RELOC_LOCAL_SECTDIFF) {
2578 DataRefImpl RelNext = Rel;
2579 info->O->moveRelocationNext(RelNext);
2580 MachO::any_relocation_info RENext;
2581 RENext = info->O->getRelocation(RelNext);
2582 if (info->O->isRelocationScattered(RENext))
2583 pair_r_value = info->O->getScatteredRelocationValue(RENext);
2588 isExtern = info->O->getPlainRelocationExternal(RE);
2590 symbol_iterator RelocSym = Reloc.getSymbol();
2598 if (reloc_found && isExtern) {
2599 op_info->AddSymbol.Present = 1;
2600 op_info->AddSymbol.Name =
2601 unwrapOrError(Symbol.getName(), info->O->getFileName()).data();
2602 // For i386 extern relocation entries the value in the instruction is
2603 // the offset from the symbol, and value is already set in op_info->Value.
2606 if (reloc_found && (r_type == MachO::GENERIC_RELOC_SECTDIFF ||
2607 r_type == MachO::GENERIC_RELOC_LOCAL_SECTDIFF)) {
2608 const char *add = GuessSymbolName(r_value, info->AddrMap);
2609 const char *sub = GuessSymbolName(pair_r_value, info->AddrMap);
2610 uint32_t offset = value - (r_value - pair_r_value);
2611 op_info->AddSymbol.Present = 1;
2613 op_info->AddSymbol.Name = add;
2615 op_info->AddSymbol.Value = r_value;
2616 op_info->SubtractSymbol.Present = 1;
2618 op_info->SubtractSymbol.Name = sub;
2620 op_info->SubtractSymbol.Value = pair_r_value;
2621 op_info->Value = offset;
2626 if (Arch == Triple::x86_64) {
2627 if (Size != 1 && Size != 2 && Size != 4 && Size != 0)
2629 // For non MH_OBJECT types, like MH_KEXT_BUNDLE, Search the external
2630 // relocation entries of a linked image (if any) for an entry that matches
2631 // this segment offset.
2632 if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
2633 uint64_t seg_offset = Pc + Offset;
2634 bool reloc_found = false;
2636 MachO::any_relocation_info RE;
2637 bool isExtern = false;
2639 for (const RelocationRef &Reloc : info->O->external_relocations()) {
2640 uint64_t RelocOffset = Reloc.getOffset();
2641 if (RelocOffset == seg_offset) {
2642 Rel = Reloc.getRawDataRefImpl();
2643 RE = info->O->getRelocation(Rel);
2644 // external relocation entries should always be external.
2645 isExtern = info->O->getPlainRelocationExternal(RE);
2647 symbol_iterator RelocSym = Reloc.getSymbol();
2654 if (reloc_found && isExtern) {
2655 // The Value passed in will be adjusted by the Pc if the instruction
2656 // adds the Pc. But for x86_64 external relocation entries the Value
2657 // is the offset from the external symbol.
2658 if (info->O->getAnyRelocationPCRel(RE))
2659 op_info->Value -= Pc + Offset + Size;
2661 unwrapOrError(Symbol.getName(), info->O->getFileName()).data();
2662 op_info->AddSymbol.Present = 1;
2663 op_info->AddSymbol.Name = name;
2668 // In MH_OBJECT filetypes search the section's relocation entries (if any)
2669 // for an entry for this section offset.
2670 uint64_t sect_addr = info->S.getAddress();
2671 uint64_t sect_offset = (Pc + Offset) - sect_addr;
2672 bool reloc_found = false;
2674 MachO::any_relocation_info RE;
2675 bool isExtern = false;
2677 for (const RelocationRef &Reloc : info->S.relocations()) {
2678 uint64_t RelocOffset = Reloc.getOffset();
2679 if (RelocOffset == sect_offset) {
2680 Rel = Reloc.getRawDataRefImpl();
2681 RE = info->O->getRelocation(Rel);
2682 // NOTE: Scattered relocations don't exist on x86_64.
2683 isExtern = info->O->getPlainRelocationExternal(RE);
2685 symbol_iterator RelocSym = Reloc.getSymbol();
2692 if (reloc_found && isExtern) {
2693 // The Value passed in will be adjusted by the Pc if the instruction
2694 // adds the Pc. But for x86_64 external relocation entries the Value
2695 // is the offset from the external symbol.
2696 if (info->O->getAnyRelocationPCRel(RE))
2697 op_info->Value -= Pc + Offset + Size;
2699 unwrapOrError(Symbol.getName(), info->O->getFileName()).data();
2700 unsigned Type = info->O->getAnyRelocationType(RE);
2701 if (Type == MachO::X86_64_RELOC_SUBTRACTOR) {
2702 DataRefImpl RelNext = Rel;
2703 info->O->moveRelocationNext(RelNext);
2704 MachO::any_relocation_info RENext = info->O->getRelocation(RelNext);
2705 unsigned TypeNext = info->O->getAnyRelocationType(RENext);
2706 bool isExternNext = info->O->getPlainRelocationExternal(RENext);
2707 unsigned SymbolNum = info->O->getPlainRelocationSymbolNum(RENext);
2708 if (TypeNext == MachO::X86_64_RELOC_UNSIGNED && isExternNext) {
2709 op_info->SubtractSymbol.Present = 1;
2710 op_info->SubtractSymbol.Name = name;
2711 symbol_iterator RelocSymNext = info->O->getSymbolByIndex(SymbolNum);
2712 Symbol = *RelocSymNext;
2713 name = unwrapOrError(Symbol.getName(), info->O->getFileName()).data();
2716 // TODO: add the VariantKinds to op_info->VariantKind for relocation types
2717 // like: X86_64_RELOC_TLV, X86_64_RELOC_GOT_LOAD and X86_64_RELOC_GOT.
2718 op_info->AddSymbol.Present = 1;
2719 op_info->AddSymbol.Name = name;
2724 if (Arch == Triple::arm) {
2725 if (Offset != 0 || (Size != 4 && Size != 2))
2727 if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
2729 // Search the external relocation entries of a fully linked image
2730 // (if any) for an entry that matches this segment offset.
2731 // uint32_t seg_offset = (Pc + Offset);
2734 // In MH_OBJECT filetypes search the section's relocation entries (if any)
2735 // for an entry for this section offset.
2736 uint32_t sect_addr = info->S.getAddress();
2737 uint32_t sect_offset = (Pc + Offset) - sect_addr;
2739 MachO::any_relocation_info RE;
2740 bool isExtern = false;
2742 bool r_scattered = false;
2743 uint32_t r_value, pair_r_value, r_type, r_length, other_half;
2745 find_if(info->S.relocations(), [&](const RelocationRef &Reloc) {
2746 uint64_t RelocOffset = Reloc.getOffset();
2747 return RelocOffset == sect_offset;
2750 if (Reloc == info->S.relocations().end())
2753 Rel = Reloc->getRawDataRefImpl();
2754 RE = info->O->getRelocation(Rel);
2755 r_length = info->O->getAnyRelocationLength(RE);
2756 r_scattered = info->O->isRelocationScattered(RE);
2758 r_value = info->O->getScatteredRelocationValue(RE);
2759 r_type = info->O->getScatteredRelocationType(RE);
2761 r_type = info->O->getAnyRelocationType(RE);
2762 isExtern = info->O->getPlainRelocationExternal(RE);
2764 symbol_iterator RelocSym = Reloc->getSymbol();
2768 if (r_type == MachO::ARM_RELOC_HALF ||
2769 r_type == MachO::ARM_RELOC_SECTDIFF ||
2770 r_type == MachO::ARM_RELOC_LOCAL_SECTDIFF ||
2771 r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
2772 DataRefImpl RelNext = Rel;
2773 info->O->moveRelocationNext(RelNext);
2774 MachO::any_relocation_info RENext;
2775 RENext = info->O->getRelocation(RelNext);
2776 other_half = info->O->getAnyRelocationAddress(RENext) & 0xffff;
2777 if (info->O->isRelocationScattered(RENext))
2778 pair_r_value = info->O->getScatteredRelocationValue(RENext);
2783 unwrapOrError(Symbol.getName(), info->O->getFileName()).data();
2784 op_info->AddSymbol.Present = 1;
2785 op_info->AddSymbol.Name = name;
2787 case MachO::ARM_RELOC_HALF:
2788 if ((r_length & 0x1) == 1) {
2789 op_info->Value = value << 16 | other_half;
2790 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
2792 op_info->Value = other_half << 16 | value;
2793 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
2801 // If we have a branch that is not an external relocation entry then
2802 // return 0 so the code in tryAddingSymbolicOperand() can use the
2803 // SymbolLookUp call back with the branch target address to look up the
2804 // symbol and possibility add an annotation for a symbol stub.
2805 if (isExtern == 0 && (r_type == MachO::ARM_RELOC_BR24 ||
2806 r_type == MachO::ARM_THUMB_RELOC_BR22))
2809 uint32_t offset = 0;
2810 if (r_type == MachO::ARM_RELOC_HALF ||
2811 r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
2812 if ((r_length & 0x1) == 1)
2813 value = value << 16 | other_half;
2815 value = other_half << 16 | value;
2817 if (r_scattered && (r_type != MachO::ARM_RELOC_HALF &&
2818 r_type != MachO::ARM_RELOC_HALF_SECTDIFF)) {
2819 offset = value - r_value;
2823 if (r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
2824 if ((r_length & 0x1) == 1)
2825 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
2827 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
2828 const char *add = GuessSymbolName(r_value, info->AddrMap);
2829 const char *sub = GuessSymbolName(pair_r_value, info->AddrMap);
2830 int32_t offset = value - (r_value - pair_r_value);
2831 op_info->AddSymbol.Present = 1;
2833 op_info->AddSymbol.Name = add;
2835 op_info->AddSymbol.Value = r_value;
2836 op_info->SubtractSymbol.Present = 1;
2838 op_info->SubtractSymbol.Name = sub;
2840 op_info->SubtractSymbol.Value = pair_r_value;
2841 op_info->Value = offset;
2845 op_info->AddSymbol.Present = 1;
2846 op_info->Value = offset;
2847 if (r_type == MachO::ARM_RELOC_HALF) {
2848 if ((r_length & 0x1) == 1)
2849 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
2851 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
2853 const char *add = GuessSymbolName(value, info->AddrMap);
2854 if (add != nullptr) {
2855 op_info->AddSymbol.Name = add;
2858 op_info->AddSymbol.Value = value;
2861 if (Arch == Triple::aarch64) {
2862 if (Offset != 0 || Size != 4)
2864 if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
2866 // Search the external relocation entries of a fully linked image
2867 // (if any) for an entry that matches this segment offset.
2868 // uint64_t seg_offset = (Pc + Offset);
2871 // In MH_OBJECT filetypes search the section's relocation entries (if any)
2872 // for an entry for this section offset.
2873 uint64_t sect_addr = info->S.getAddress();
2874 uint64_t sect_offset = (Pc + Offset) - sect_addr;
2876 find_if(info->S.relocations(), [&](const RelocationRef &Reloc) {
2877 uint64_t RelocOffset = Reloc.getOffset();
2878 return RelocOffset == sect_offset;
2881 if (Reloc == info->S.relocations().end())
2884 DataRefImpl Rel = Reloc->getRawDataRefImpl();
2885 MachO::any_relocation_info RE = info->O->getRelocation(Rel);
2886 uint32_t r_type = info->O->getAnyRelocationType(RE);
2887 if (r_type == MachO::ARM64_RELOC_ADDEND) {
2888 DataRefImpl RelNext = Rel;
2889 info->O->moveRelocationNext(RelNext);
2890 MachO::any_relocation_info RENext = info->O->getRelocation(RelNext);
2892 value = info->O->getPlainRelocationSymbolNum(RENext);
2893 op_info->Value = value;
2896 // NOTE: Scattered relocations don't exist on arm64.
2897 if (!info->O->getPlainRelocationExternal(RE))
2900 unwrapOrError(Reloc->getSymbol()->getName(), info->O->getFileName())
2902 op_info->AddSymbol.Present = 1;
2903 op_info->AddSymbol.Name = name;
2906 case MachO::ARM64_RELOC_PAGE21:
2908 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_PAGE;
2910 case MachO::ARM64_RELOC_PAGEOFF12:
2912 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_PAGEOFF;
2914 case MachO::ARM64_RELOC_GOT_LOAD_PAGE21:
2916 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_GOTPAGE;
2918 case MachO::ARM64_RELOC_GOT_LOAD_PAGEOFF12:
2920 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_GOTPAGEOFF;
2922 case MachO::ARM64_RELOC_TLVP_LOAD_PAGE21:
2923 /* @tvlppage is not implemented in llvm-mc */
2924 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_TLVP;
2926 case MachO::ARM64_RELOC_TLVP_LOAD_PAGEOFF12:
2927 /* @tvlppageoff is not implemented in llvm-mc */
2928 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_TLVOFF;
2931 case MachO::ARM64_RELOC_BRANCH26:
2932 op_info->VariantKind = LLVMDisassembler_VariantKind_None;
2940 // GuessCstringPointer is passed the address of what might be a pointer to a
2941 // literal string in a cstring section. If that address is in a cstring section
2942 // it returns a pointer to that string. Else it returns nullptr.
2943 static const char *GuessCstringPointer(uint64_t ReferenceValue,
2944 struct DisassembleInfo *info) {
2945 for (const auto &Load : info->O->load_commands()) {
2946 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
2947 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
2948 for (unsigned J = 0; J < Seg.nsects; ++J) {
2949 MachO::section_64 Sec = info->O->getSection64(Load, J);
2950 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
2951 if (section_type == MachO::S_CSTRING_LITERALS &&
2952 ReferenceValue >= Sec.addr &&
2953 ReferenceValue < Sec.addr + Sec.size) {
2954 uint64_t sect_offset = ReferenceValue - Sec.addr;
2955 uint64_t object_offset = Sec.offset + sect_offset;
2956 StringRef MachOContents = info->O->getData();
2957 uint64_t object_size = MachOContents.size();
2958 const char *object_addr = (const char *)MachOContents.data();
2959 if (object_offset < object_size) {
2960 const char *name = object_addr + object_offset;
2967 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
2968 MachO::segment_command Seg = info->O->getSegmentLoadCommand(Load);
2969 for (unsigned J = 0; J < Seg.nsects; ++J) {
2970 MachO::section Sec = info->O->getSection(Load, J);
2971 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
2972 if (section_type == MachO::S_CSTRING_LITERALS &&
2973 ReferenceValue >= Sec.addr &&
2974 ReferenceValue < Sec.addr + Sec.size) {
2975 uint64_t sect_offset = ReferenceValue - Sec.addr;
2976 uint64_t object_offset = Sec.offset + sect_offset;
2977 StringRef MachOContents = info->O->getData();
2978 uint64_t object_size = MachOContents.size();
2979 const char *object_addr = (const char *)MachOContents.data();
2980 if (object_offset < object_size) {
2981 const char *name = object_addr + object_offset;
2993 // GuessIndirectSymbol returns the name of the indirect symbol for the
2994 // ReferenceValue passed in or nullptr. This is used when ReferenceValue maybe
2995 // an address of a symbol stub or a lazy or non-lazy pointer to associate the
2996 // symbol name being referenced by the stub or pointer.
2997 static const char *GuessIndirectSymbol(uint64_t ReferenceValue,
2998 struct DisassembleInfo *info) {
2999 MachO::dysymtab_command Dysymtab = info->O->getDysymtabLoadCommand();
3000 MachO::symtab_command Symtab = info->O->getSymtabLoadCommand();
3001 for (const auto &Load : info->O->load_commands()) {
3002 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
3003 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
3004 for (unsigned J = 0; J < Seg.nsects; ++J) {
3005 MachO::section_64 Sec = info->O->getSection64(Load, J);
3006 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
3007 if ((section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
3008 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
3009 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
3010 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
3011 section_type == MachO::S_SYMBOL_STUBS) &&
3012 ReferenceValue >= Sec.addr &&
3013 ReferenceValue < Sec.addr + Sec.size) {
3015 if (section_type == MachO::S_SYMBOL_STUBS)
3016 stride = Sec.reserved2;
3021 uint32_t index = Sec.reserved1 + (ReferenceValue - Sec.addr) / stride;
3022 if (index < Dysymtab.nindirectsyms) {
3023 uint32_t indirect_symbol =
3024 info->O->getIndirectSymbolTableEntry(Dysymtab, index);
3025 if (indirect_symbol < Symtab.nsyms) {
3026 symbol_iterator Sym = info->O->getSymbolByIndex(indirect_symbol);
3027 return unwrapOrError(Sym->getName(), info->O->getFileName())
3033 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
3034 MachO::segment_command Seg = info->O->getSegmentLoadCommand(Load);
3035 for (unsigned J = 0; J < Seg.nsects; ++J) {
3036 MachO::section Sec = info->O->getSection(Load, J);
3037 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
3038 if ((section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
3039 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
3040 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
3041 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
3042 section_type == MachO::S_SYMBOL_STUBS) &&
3043 ReferenceValue >= Sec.addr &&
3044 ReferenceValue < Sec.addr + Sec.size) {
3046 if (section_type == MachO::S_SYMBOL_STUBS)
3047 stride = Sec.reserved2;
3052 uint32_t index = Sec.reserved1 + (ReferenceValue - Sec.addr) / stride;
3053 if (index < Dysymtab.nindirectsyms) {
3054 uint32_t indirect_symbol =
3055 info->O->getIndirectSymbolTableEntry(Dysymtab, index);
3056 if (indirect_symbol < Symtab.nsyms) {
3057 symbol_iterator Sym = info->O->getSymbolByIndex(indirect_symbol);
3058 return unwrapOrError(Sym->getName(), info->O->getFileName())
3069 // method_reference() is called passing it the ReferenceName that might be
3070 // a reference it to an Objective-C method call. If so then it allocates and
3071 // assembles a method call string with the values last seen and saved in
3072 // the DisassembleInfo's class_name and selector_name fields. This is saved
3073 // into the method field of the info and any previous string is free'ed.
3074 // Then the class_name field in the info is set to nullptr. The method call
3075 // string is set into ReferenceName and ReferenceType is set to
3076 // LLVMDisassembler_ReferenceType_Out_Objc_Message. If this not a method call
3077 // then both ReferenceType and ReferenceName are left unchanged.
3078 static void method_reference(struct DisassembleInfo *info,
3079 uint64_t *ReferenceType,
3080 const char **ReferenceName) {
3081 unsigned int Arch = info->O->getArch();
3082 if (*ReferenceName != nullptr) {
3083 if (strcmp(*ReferenceName, "_objc_msgSend") == 0) {
3084 if (info->selector_name != nullptr) {
3085 if (info->class_name != nullptr) {
3086 info->method = llvm::make_unique<char[]>(
3087 5 + strlen(info->class_name) + strlen(info->selector_name));
3088 char *method = info->method.get();
3089 if (method != nullptr) {
3090 strcpy(method, "+[");
3091 strcat(method, info->class_name);
3092 strcat(method, " ");
3093 strcat(method, info->selector_name);
3094 strcat(method, "]");
3095 *ReferenceName = method;
3096 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
3100 llvm::make_unique<char[]>(9 + strlen(info->selector_name));
3101 char *method = info->method.get();
3102 if (method != nullptr) {
3103 if (Arch == Triple::x86_64)
3104 strcpy(method, "-[%rdi ");
3105 else if (Arch == Triple::aarch64)
3106 strcpy(method, "-[x0 ");
3108 strcpy(method, "-[r? ");
3109 strcat(method, info->selector_name);
3110 strcat(method, "]");
3111 *ReferenceName = method;
3112 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
3115 info->class_name = nullptr;
3117 } else if (strcmp(*ReferenceName, "_objc_msgSendSuper2") == 0) {
3118 if (info->selector_name != nullptr) {
3120 llvm::make_unique<char[]>(17 + strlen(info->selector_name));
3121 char *method = info->method.get();
3122 if (method != nullptr) {
3123 if (Arch == Triple::x86_64)
3124 strcpy(method, "-[[%rdi super] ");
3125 else if (Arch == Triple::aarch64)
3126 strcpy(method, "-[[x0 super] ");
3128 strcpy(method, "-[[r? super] ");
3129 strcat(method, info->selector_name);
3130 strcat(method, "]");
3131 *ReferenceName = method;
3132 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
3134 info->class_name = nullptr;
3140 // GuessPointerPointer() is passed the address of what might be a pointer to
3141 // a reference to an Objective-C class, selector, message ref or cfstring.
3142 // If so the value of the pointer is returned and one of the booleans are set
3143 // to true. If not zero is returned and all the booleans are set to false.
3144 static uint64_t GuessPointerPointer(uint64_t ReferenceValue,
3145 struct DisassembleInfo *info,
3146 bool &classref, bool &selref, bool &msgref,
3152 for (const auto &Load : info->O->load_commands()) {
3153 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
3154 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
3155 for (unsigned J = 0; J < Seg.nsects; ++J) {
3156 MachO::section_64 Sec = info->O->getSection64(Load, J);
3157 if ((strncmp(Sec.sectname, "__objc_selrefs", 16) == 0 ||
3158 strncmp(Sec.sectname, "__objc_classrefs", 16) == 0 ||
3159 strncmp(Sec.sectname, "__objc_superrefs", 16) == 0 ||
3160 strncmp(Sec.sectname, "__objc_msgrefs", 16) == 0 ||
3161 strncmp(Sec.sectname, "__cfstring", 16) == 0) &&
3162 ReferenceValue >= Sec.addr &&
3163 ReferenceValue < Sec.addr + Sec.size) {
3164 uint64_t sect_offset = ReferenceValue - Sec.addr;
3165 uint64_t object_offset = Sec.offset + sect_offset;
3166 StringRef MachOContents = info->O->getData();
3167 uint64_t object_size = MachOContents.size();
3168 const char *object_addr = (const char *)MachOContents.data();
3169 if (object_offset < object_size) {
3170 uint64_t pointer_value;
3171 memcpy(&pointer_value, object_addr + object_offset,
3173 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3174 sys::swapByteOrder(pointer_value);
3175 if (strncmp(Sec.sectname, "__objc_selrefs", 16) == 0)
3177 else if (strncmp(Sec.sectname, "__objc_classrefs", 16) == 0 ||
3178 strncmp(Sec.sectname, "__objc_superrefs", 16) == 0)
3180 else if (strncmp(Sec.sectname, "__objc_msgrefs", 16) == 0 &&
3181 ReferenceValue + 8 < Sec.addr + Sec.size) {
3183 memcpy(&pointer_value, object_addr + object_offset + 8,
3185 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3186 sys::swapByteOrder(pointer_value);
3187 } else if (strncmp(Sec.sectname, "__cfstring", 16) == 0)
3189 return pointer_value;
3196 // TODO: Look for LC_SEGMENT for 32-bit Mach-O files.
3201 // get_pointer_64 returns a pointer to the bytes in the object file at the
3202 // Address from a section in the Mach-O file. And indirectly returns the
3203 // offset into the section, number of bytes left in the section past the offset
3204 // and which section is was being referenced. If the Address is not in a
3205 // section nullptr is returned.
3206 static const char *get_pointer_64(uint64_t Address, uint32_t &offset,
3207 uint32_t &left, SectionRef &S,
3208 DisassembleInfo *info,
3209 bool objc_only = false) {
3213 for (unsigned SectIdx = 0; SectIdx != info->Sections->size(); SectIdx++) {
3214 uint64_t SectAddress = ((*(info->Sections))[SectIdx]).getAddress();
3215 uint64_t SectSize = ((*(info->Sections))[SectIdx]).getSize();
3220 ((*(info->Sections))[SectIdx]).getName(SectName);
3221 DataRefImpl Ref = ((*(info->Sections))[SectIdx]).getRawDataRefImpl();
3222 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
3223 if (SegName != "__OBJC" && SectName != "__cstring")
3226 if (Address >= SectAddress && Address < SectAddress + SectSize) {
3227 S = (*(info->Sections))[SectIdx];
3228 offset = Address - SectAddress;
3229 left = SectSize - offset;
3230 StringRef SectContents = unwrapOrError(
3231 ((*(info->Sections))[SectIdx]).getContents(), info->O->getFileName());
3232 return SectContents.data() + offset;
3238 static const char *get_pointer_32(uint32_t Address, uint32_t &offset,
3239 uint32_t &left, SectionRef &S,
3240 DisassembleInfo *info,
3241 bool objc_only = false) {
3242 return get_pointer_64(Address, offset, left, S, info, objc_only);
3245 // get_symbol_64() returns the name of a symbol (or nullptr) and the address of
3246 // the symbol indirectly through n_value. Based on the relocation information
3247 // for the specified section offset in the specified section reference.
3248 // If no relocation information is found and a non-zero ReferenceValue for the
3249 // symbol is passed, look up that address in the info's AddrMap.
3250 static const char *get_symbol_64(uint32_t sect_offset, SectionRef S,
3251 DisassembleInfo *info, uint64_t &n_value,
3252 uint64_t ReferenceValue = 0) {
3257 // See if there is an external relocation entry at the sect_offset.
3258 bool reloc_found = false;
3260 MachO::any_relocation_info RE;
3261 bool isExtern = false;
3263 for (const RelocationRef &Reloc : S.relocations()) {
3264 uint64_t RelocOffset = Reloc.getOffset();
3265 if (RelocOffset == sect_offset) {
3266 Rel = Reloc.getRawDataRefImpl();
3267 RE = info->O->getRelocation(Rel);
3268 if (info->O->isRelocationScattered(RE))
3270 isExtern = info->O->getPlainRelocationExternal(RE);
3272 symbol_iterator RelocSym = Reloc.getSymbol();
3279 // If there is an external relocation entry for a symbol in this section
3280 // at this section_offset then use that symbol's value for the n_value
3281 // and return its name.
3282 const char *SymbolName = nullptr;
3283 if (reloc_found && isExtern) {
3284 n_value = Symbol.getValue();
3285 StringRef Name = unwrapOrError(Symbol.getName(), info->O->getFileName());
3286 if (!Name.empty()) {
3287 SymbolName = Name.data();
3292 // TODO: For fully linked images, look through the external relocation
3293 // entries off the dynamic symtab command. For these the r_offset is from the
3294 // start of the first writeable segment in the Mach-O file. So the offset
3295 // to this section from that segment is passed to this routine by the caller,
3296 // as the database_offset. Which is the difference of the section's starting
3297 // address and the first writable segment.
3299 // NOTE: need add passing the database_offset to this routine.
3301 // We did not find an external relocation entry so look up the ReferenceValue
3302 // as an address of a symbol and if found return that symbol's name.
3303 SymbolName = GuessSymbolName(ReferenceValue, info->AddrMap);
3308 static const char *get_symbol_32(uint32_t sect_offset, SectionRef S,
3309 DisassembleInfo *info,
3310 uint32_t ReferenceValue) {
3312 return get_symbol_64(sect_offset, S, info, n_value64, ReferenceValue);
3315 // These are structs in the Objective-C meta data and read to produce the
3316 // comments for disassembly. While these are part of the ABI they are no
3317 // public defintions. So the are here not in include/llvm/BinaryFormat/MachO.h
3320 // The cfstring object in a 64-bit Mach-O file.
3321 struct cfstring64_t {
3322 uint64_t isa; // class64_t * (64-bit pointer)
3323 uint64_t flags; // flag bits
3324 uint64_t characters; // char * (64-bit pointer)
3325 uint64_t length; // number of non-NULL characters in above
3328 // The class object in a 64-bit Mach-O file.
3330 uint64_t isa; // class64_t * (64-bit pointer)
3331 uint64_t superclass; // class64_t * (64-bit pointer)
3332 uint64_t cache; // Cache (64-bit pointer)
3333 uint64_t vtable; // IMP * (64-bit pointer)
3334 uint64_t data; // class_ro64_t * (64-bit pointer)
3338 uint32_t isa; /* class32_t * (32-bit pointer) */
3339 uint32_t superclass; /* class32_t * (32-bit pointer) */
3340 uint32_t cache; /* Cache (32-bit pointer) */
3341 uint32_t vtable; /* IMP * (32-bit pointer) */
3342 uint32_t data; /* class_ro32_t * (32-bit pointer) */
3345 struct class_ro64_t {
3347 uint32_t instanceStart;
3348 uint32_t instanceSize;
3350 uint64_t ivarLayout; // const uint8_t * (64-bit pointer)
3351 uint64_t name; // const char * (64-bit pointer)
3352 uint64_t baseMethods; // const method_list_t * (64-bit pointer)
3353 uint64_t baseProtocols; // const protocol_list_t * (64-bit pointer)
3354 uint64_t ivars; // const ivar_list_t * (64-bit pointer)
3355 uint64_t weakIvarLayout; // const uint8_t * (64-bit pointer)
3356 uint64_t baseProperties; // const struct objc_property_list (64-bit pointer)
3359 struct class_ro32_t {
3361 uint32_t instanceStart;
3362 uint32_t instanceSize;
3363 uint32_t ivarLayout; /* const uint8_t * (32-bit pointer) */
3364 uint32_t name; /* const char * (32-bit pointer) */
3365 uint32_t baseMethods; /* const method_list_t * (32-bit pointer) */
3366 uint32_t baseProtocols; /* const protocol_list_t * (32-bit pointer) */
3367 uint32_t ivars; /* const ivar_list_t * (32-bit pointer) */
3368 uint32_t weakIvarLayout; /* const uint8_t * (32-bit pointer) */
3369 uint32_t baseProperties; /* const struct objc_property_list *
3373 /* Values for class_ro{64,32}_t->flags */
3374 #define RO_META (1 << 0)
3375 #define RO_ROOT (1 << 1)
3376 #define RO_HAS_CXX_STRUCTORS (1 << 2)
3378 struct method_list64_t {
3381 /* struct method64_t first; These structures follow inline */
3384 struct method_list32_t {
3387 /* struct method32_t first; These structures follow inline */
3391 uint64_t name; /* SEL (64-bit pointer) */
3392 uint64_t types; /* const char * (64-bit pointer) */
3393 uint64_t imp; /* IMP (64-bit pointer) */
3397 uint32_t name; /* SEL (32-bit pointer) */
3398 uint32_t types; /* const char * (32-bit pointer) */
3399 uint32_t imp; /* IMP (32-bit pointer) */
3402 struct protocol_list64_t {
3403 uint64_t count; /* uintptr_t (a 64-bit value) */
3404 /* struct protocol64_t * list[0]; These pointers follow inline */
3407 struct protocol_list32_t {
3408 uint32_t count; /* uintptr_t (a 32-bit value) */
3409 /* struct protocol32_t * list[0]; These pointers follow inline */
3412 struct protocol64_t {
3413 uint64_t isa; /* id * (64-bit pointer) */
3414 uint64_t name; /* const char * (64-bit pointer) */
3415 uint64_t protocols; /* struct protocol_list64_t *
3417 uint64_t instanceMethods; /* method_list_t * (64-bit pointer) */
3418 uint64_t classMethods; /* method_list_t * (64-bit pointer) */
3419 uint64_t optionalInstanceMethods; /* method_list_t * (64-bit pointer) */
3420 uint64_t optionalClassMethods; /* method_list_t * (64-bit pointer) */
3421 uint64_t instanceProperties; /* struct objc_property_list *
3425 struct protocol32_t {
3426 uint32_t isa; /* id * (32-bit pointer) */
3427 uint32_t name; /* const char * (32-bit pointer) */
3428 uint32_t protocols; /* struct protocol_list_t *
3430 uint32_t instanceMethods; /* method_list_t * (32-bit pointer) */
3431 uint32_t classMethods; /* method_list_t * (32-bit pointer) */
3432 uint32_t optionalInstanceMethods; /* method_list_t * (32-bit pointer) */
3433 uint32_t optionalClassMethods; /* method_list_t * (32-bit pointer) */
3434 uint32_t instanceProperties; /* struct objc_property_list *
3438 struct ivar_list64_t {
3441 /* struct ivar64_t first; These structures follow inline */
3444 struct ivar_list32_t {
3447 /* struct ivar32_t first; These structures follow inline */
3451 uint64_t offset; /* uintptr_t * (64-bit pointer) */
3452 uint64_t name; /* const char * (64-bit pointer) */
3453 uint64_t type; /* const char * (64-bit pointer) */
3459 uint32_t offset; /* uintptr_t * (32-bit pointer) */
3460 uint32_t name; /* const char * (32-bit pointer) */
3461 uint32_t type; /* const char * (32-bit pointer) */
3466 struct objc_property_list64 {
3469 /* struct objc_property64 first; These structures follow inline */
3472 struct objc_property_list32 {
3475 /* struct objc_property32 first; These structures follow inline */
3478 struct objc_property64 {
3479 uint64_t name; /* const char * (64-bit pointer) */
3480 uint64_t attributes; /* const char * (64-bit pointer) */
3483 struct objc_property32 {
3484 uint32_t name; /* const char * (32-bit pointer) */
3485 uint32_t attributes; /* const char * (32-bit pointer) */
3488 struct category64_t {
3489 uint64_t name; /* const char * (64-bit pointer) */
3490 uint64_t cls; /* struct class_t * (64-bit pointer) */
3491 uint64_t instanceMethods; /* struct method_list_t * (64-bit pointer) */
3492 uint64_t classMethods; /* struct method_list_t * (64-bit pointer) */
3493 uint64_t protocols; /* struct protocol_list_t * (64-bit pointer) */
3494 uint64_t instanceProperties; /* struct objc_property_list *
3498 struct category32_t {
3499 uint32_t name; /* const char * (32-bit pointer) */
3500 uint32_t cls; /* struct class_t * (32-bit pointer) */
3501 uint32_t instanceMethods; /* struct method_list_t * (32-bit pointer) */
3502 uint32_t classMethods; /* struct method_list_t * (32-bit pointer) */
3503 uint32_t protocols; /* struct protocol_list_t * (32-bit pointer) */
3504 uint32_t instanceProperties; /* struct objc_property_list *
3508 struct objc_image_info64 {
3512 struct objc_image_info32 {
3516 struct imageInfo_t {
3520 /* masks for objc_image_info.flags */
3521 #define OBJC_IMAGE_IS_REPLACEMENT (1 << 0)
3522 #define OBJC_IMAGE_SUPPORTS_GC (1 << 1)
3523 #define OBJC_IMAGE_IS_SIMULATED (1 << 5)
3524 #define OBJC_IMAGE_HAS_CATEGORY_CLASS_PROPERTIES (1 << 6)
3526 struct message_ref64 {
3527 uint64_t imp; /* IMP (64-bit pointer) */
3528 uint64_t sel; /* SEL (64-bit pointer) */
3531 struct message_ref32 {
3532 uint32_t imp; /* IMP (32-bit pointer) */
3533 uint32_t sel; /* SEL (32-bit pointer) */
3536 // Objective-C 1 (32-bit only) meta data structs.
3538 struct objc_module_t {
3541 uint32_t name; /* char * (32-bit pointer) */
3542 uint32_t symtab; /* struct objc_symtab * (32-bit pointer) */
3545 struct objc_symtab_t {
3546 uint32_t sel_ref_cnt;
3547 uint32_t refs; /* SEL * (32-bit pointer) */
3548 uint16_t cls_def_cnt;
3549 uint16_t cat_def_cnt;
3550 // uint32_t defs[1]; /* void * (32-bit pointer) variable size */
3553 struct objc_class_t {
3554 uint32_t isa; /* struct objc_class * (32-bit pointer) */
3555 uint32_t super_class; /* struct objc_class * (32-bit pointer) */
3556 uint32_t name; /* const char * (32-bit pointer) */
3559 int32_t instance_size;
3560 uint32_t ivars; /* struct objc_ivar_list * (32-bit pointer) */
3561 uint32_t methodLists; /* struct objc_method_list ** (32-bit pointer) */
3562 uint32_t cache; /* struct objc_cache * (32-bit pointer) */
3563 uint32_t protocols; /* struct objc_protocol_list * (32-bit pointer) */
3566 #define CLS_GETINFO(cls, infomask) ((cls)->info & (infomask))
3567 // class is not a metaclass
3568 #define CLS_CLASS 0x1
3569 // class is a metaclass
3570 #define CLS_META 0x2
3572 struct objc_category_t {
3573 uint32_t category_name; /* char * (32-bit pointer) */
3574 uint32_t class_name; /* char * (32-bit pointer) */
3575 uint32_t instance_methods; /* struct objc_method_list * (32-bit pointer) */
3576 uint32_t class_methods; /* struct objc_method_list * (32-bit pointer) */
3577 uint32_t protocols; /* struct objc_protocol_list * (32-bit ptr) */
3580 struct objc_ivar_t {
3581 uint32_t ivar_name; /* char * (32-bit pointer) */
3582 uint32_t ivar_type; /* char * (32-bit pointer) */
3583 int32_t ivar_offset;
3586 struct objc_ivar_list_t {
3588 // struct objc_ivar_t ivar_list[1]; /* variable length structure */
3591 struct objc_method_list_t {
3592 uint32_t obsolete; /* struct objc_method_list * (32-bit pointer) */
3593 int32_t method_count;
3594 // struct objc_method_t method_list[1]; /* variable length structure */
3597 struct objc_method_t {
3598 uint32_t method_name; /* SEL, aka struct objc_selector * (32-bit pointer) */
3599 uint32_t method_types; /* char * (32-bit pointer) */
3600 uint32_t method_imp; /* IMP, aka function pointer, (*IMP)(id, SEL, ...)
3604 struct objc_protocol_list_t {
3605 uint32_t next; /* struct objc_protocol_list * (32-bit pointer) */
3607 // uint32_t list[1]; /* Protocol *, aka struct objc_protocol_t *
3608 // (32-bit pointer) */
3611 struct objc_protocol_t {
3612 uint32_t isa; /* struct objc_class * (32-bit pointer) */
3613 uint32_t protocol_name; /* char * (32-bit pointer) */
3614 uint32_t protocol_list; /* struct objc_protocol_list * (32-bit pointer) */
3615 uint32_t instance_methods; /* struct objc_method_description_list *
3617 uint32_t class_methods; /* struct objc_method_description_list *
3621 struct objc_method_description_list_t {
3623 // struct objc_method_description_t list[1];
3626 struct objc_method_description_t {
3627 uint32_t name; /* SEL, aka struct objc_selector * (32-bit pointer) */
3628 uint32_t types; /* char * (32-bit pointer) */
3631 inline void swapStruct(struct cfstring64_t &cfs) {
3632 sys::swapByteOrder(cfs.isa);
3633 sys::swapByteOrder(cfs.flags);
3634 sys::swapByteOrder(cfs.characters);
3635 sys::swapByteOrder(cfs.length);
3638 inline void swapStruct(struct class64_t &c) {
3639 sys::swapByteOrder(c.isa);
3640 sys::swapByteOrder(c.superclass);
3641 sys::swapByteOrder(c.cache);
3642 sys::swapByteOrder(c.vtable);
3643 sys::swapByteOrder(c.data);
3646 inline void swapStruct(struct class32_t &c) {
3647 sys::swapByteOrder(c.isa);
3648 sys::swapByteOrder(c.superclass);
3649 sys::swapByteOrder(c.cache);
3650 sys::swapByteOrder(c.vtable);
3651 sys::swapByteOrder(c.data);
3654 inline void swapStruct(struct class_ro64_t &cro) {
3655 sys::swapByteOrder(cro.flags);
3656 sys::swapByteOrder(cro.instanceStart);
3657 sys::swapByteOrder(cro.instanceSize);
3658 sys::swapByteOrder(cro.reserved);
3659 sys::swapByteOrder(cro.ivarLayout);
3660 sys::swapByteOrder(cro.name);
3661 sys::swapByteOrder(cro.baseMethods);
3662 sys::swapByteOrder(cro.baseProtocols);
3663 sys::swapByteOrder(cro.ivars);
3664 sys::swapByteOrder(cro.weakIvarLayout);
3665 sys::swapByteOrder(cro.baseProperties);
3668 inline void swapStruct(struct class_ro32_t &cro) {
3669 sys::swapByteOrder(cro.flags);
3670 sys::swapByteOrder(cro.instanceStart);
3671 sys::swapByteOrder(cro.instanceSize);
3672 sys::swapByteOrder(cro.ivarLayout);
3673 sys::swapByteOrder(cro.name);
3674 sys::swapByteOrder(cro.baseMethods);
3675 sys::swapByteOrder(cro.baseProtocols);
3676 sys::swapByteOrder(cro.ivars);
3677 sys::swapByteOrder(cro.weakIvarLayout);
3678 sys::swapByteOrder(cro.baseProperties);
3681 inline void swapStruct(struct method_list64_t &ml) {
3682 sys::swapByteOrder(ml.entsize);
3683 sys::swapByteOrder(ml.count);
3686 inline void swapStruct(struct method_list32_t &ml) {
3687 sys::swapByteOrder(ml.entsize);
3688 sys::swapByteOrder(ml.count);
3691 inline void swapStruct(struct method64_t &m) {
3692 sys::swapByteOrder(m.name);
3693 sys::swapByteOrder(m.types);
3694 sys::swapByteOrder(m.imp);
3697 inline void swapStruct(struct method32_t &m) {
3698 sys::swapByteOrder(m.name);
3699 sys::swapByteOrder(m.types);
3700 sys::swapByteOrder(m.imp);
3703 inline void swapStruct(struct protocol_list64_t &pl) {
3704 sys::swapByteOrder(pl.count);
3707 inline void swapStruct(struct protocol_list32_t &pl) {
3708 sys::swapByteOrder(pl.count);
3711 inline void swapStruct(struct protocol64_t &p) {
3712 sys::swapByteOrder(p.isa);
3713 sys::swapByteOrder(p.name);
3714 sys::swapByteOrder(p.protocols);
3715 sys::swapByteOrder(p.instanceMethods);
3716 sys::swapByteOrder(p.classMethods);
3717 sys::swapByteOrder(p.optionalInstanceMethods);
3718 sys::swapByteOrder(p.optionalClassMethods);
3719 sys::swapByteOrder(p.instanceProperties);
3722 inline void swapStruct(struct protocol32_t &p) {
3723 sys::swapByteOrder(p.isa);
3724 sys::swapByteOrder(p.name);
3725 sys::swapByteOrder(p.protocols);
3726 sys::swapByteOrder(p.instanceMethods);
3727 sys::swapByteOrder(p.classMethods);
3728 sys::swapByteOrder(p.optionalInstanceMethods);
3729 sys::swapByteOrder(p.optionalClassMethods);
3730 sys::swapByteOrder(p.instanceProperties);
3733 inline void swapStruct(struct ivar_list64_t &il) {
3734 sys::swapByteOrder(il.entsize);
3735 sys::swapByteOrder(il.count);
3738 inline void swapStruct(struct ivar_list32_t &il) {
3739 sys::swapByteOrder(il.entsize);
3740 sys::swapByteOrder(il.count);
3743 inline void swapStruct(struct ivar64_t &i) {
3744 sys::swapByteOrder(i.offset);
3745 sys::swapByteOrder(i.name);
3746 sys::swapByteOrder(i.type);
3747 sys::swapByteOrder(i.alignment);
3748 sys::swapByteOrder(i.size);
3751 inline void swapStruct(struct ivar32_t &i) {
3752 sys::swapByteOrder(i.offset);
3753 sys::swapByteOrder(i.name);
3754 sys::swapByteOrder(i.type);
3755 sys::swapByteOrder(i.alignment);
3756 sys::swapByteOrder(i.size);
3759 inline void swapStruct(struct objc_property_list64 &pl) {
3760 sys::swapByteOrder(pl.entsize);
3761 sys::swapByteOrder(pl.count);
3764 inline void swapStruct(struct objc_property_list32 &pl) {
3765 sys::swapByteOrder(pl.entsize);
3766 sys::swapByteOrder(pl.count);
3769 inline void swapStruct(struct objc_property64 &op) {
3770 sys::swapByteOrder(op.name);
3771 sys::swapByteOrder(op.attributes);
3774 inline void swapStruct(struct objc_property32 &op) {
3775 sys::swapByteOrder(op.name);
3776 sys::swapByteOrder(op.attributes);
3779 inline void swapStruct(struct category64_t &c) {
3780 sys::swapByteOrder(c.name);
3781 sys::swapByteOrder(c.cls);
3782 sys::swapByteOrder(c.instanceMethods);
3783 sys::swapByteOrder(c.classMethods);
3784 sys::swapByteOrder(c.protocols);
3785 sys::swapByteOrder(c.instanceProperties);
3788 inline void swapStruct(struct category32_t &c) {
3789 sys::swapByteOrder(c.name);
3790 sys::swapByteOrder(c.cls);
3791 sys::swapByteOrder(c.instanceMethods);
3792 sys::swapByteOrder(c.classMethods);
3793 sys::swapByteOrder(c.protocols);
3794 sys::swapByteOrder(c.instanceProperties);
3797 inline void swapStruct(struct objc_image_info64 &o) {
3798 sys::swapByteOrder(o.version);
3799 sys::swapByteOrder(o.flags);
3802 inline void swapStruct(struct objc_image_info32 &o) {
3803 sys::swapByteOrder(o.version);
3804 sys::swapByteOrder(o.flags);
3807 inline void swapStruct(struct imageInfo_t &o) {
3808 sys::swapByteOrder(o.version);
3809 sys::swapByteOrder(o.flags);
3812 inline void swapStruct(struct message_ref64 &mr) {
3813 sys::swapByteOrder(mr.imp);
3814 sys::swapByteOrder(mr.sel);
3817 inline void swapStruct(struct message_ref32 &mr) {
3818 sys::swapByteOrder(mr.imp);
3819 sys::swapByteOrder(mr.sel);
3822 inline void swapStruct(struct objc_module_t &module) {
3823 sys::swapByteOrder(module.version);
3824 sys::swapByteOrder(module.size);
3825 sys::swapByteOrder(module.name);
3826 sys::swapByteOrder(module.symtab);
3829 inline void swapStruct(struct objc_symtab_t &symtab) {
3830 sys::swapByteOrder(symtab.sel_ref_cnt);
3831 sys::swapByteOrder(symtab.refs);
3832 sys::swapByteOrder(symtab.cls_def_cnt);
3833 sys::swapByteOrder(symtab.cat_def_cnt);
3836 inline void swapStruct(struct objc_class_t &objc_class) {
3837 sys::swapByteOrder(objc_class.isa);
3838 sys::swapByteOrder(objc_class.super_class);
3839 sys::swapByteOrder(objc_class.name);
3840 sys::swapByteOrder(objc_class.version);
3841 sys::swapByteOrder(objc_class.info);
3842 sys::swapByteOrder(objc_class.instance_size);
3843 sys::swapByteOrder(objc_class.ivars);
3844 sys::swapByteOrder(objc_class.methodLists);
3845 sys::swapByteOrder(objc_class.cache);
3846 sys::swapByteOrder(objc_class.protocols);
3849 inline void swapStruct(struct objc_category_t &objc_category) {
3850 sys::swapByteOrder(objc_category.category_name);
3851 sys::swapByteOrder(objc_category.class_name);
3852 sys::swapByteOrder(objc_category.instance_methods);
3853 sys::swapByteOrder(objc_category.class_methods);
3854 sys::swapByteOrder(objc_category.protocols);
3857 inline void swapStruct(struct objc_ivar_list_t &objc_ivar_list) {
3858 sys::swapByteOrder(objc_ivar_list.ivar_count);
3861 inline void swapStruct(struct objc_ivar_t &objc_ivar) {
3862 sys::swapByteOrder(objc_ivar.ivar_name);
3863 sys::swapByteOrder(objc_ivar.ivar_type);
3864 sys::swapByteOrder(objc_ivar.ivar_offset);
3867 inline void swapStruct(struct objc_method_list_t &method_list) {
3868 sys::swapByteOrder(method_list.obsolete);
3869 sys::swapByteOrder(method_list.method_count);
3872 inline void swapStruct(struct objc_method_t &method) {
3873 sys::swapByteOrder(method.method_name);
3874 sys::swapByteOrder(method.method_types);
3875 sys::swapByteOrder(method.method_imp);
3878 inline void swapStruct(struct objc_protocol_list_t &protocol_list) {
3879 sys::swapByteOrder(protocol_list.next);
3880 sys::swapByteOrder(protocol_list.count);
3883 inline void swapStruct(struct objc_protocol_t &protocol) {
3884 sys::swapByteOrder(protocol.isa);
3885 sys::swapByteOrder(protocol.protocol_name);
3886 sys::swapByteOrder(protocol.protocol_list);
3887 sys::swapByteOrder(protocol.instance_methods);
3888 sys::swapByteOrder(protocol.class_methods);
3891 inline void swapStruct(struct objc_method_description_list_t &mdl) {
3892 sys::swapByteOrder(mdl.count);
3895 inline void swapStruct(struct objc_method_description_t &md) {
3896 sys::swapByteOrder(md.name);
3897 sys::swapByteOrder(md.types);
3900 static const char *get_dyld_bind_info_symbolname(uint64_t ReferenceValue,
3901 struct DisassembleInfo *info);
3903 // get_objc2_64bit_class_name() is used for disassembly and is passed a pointer
3904 // to an Objective-C class and returns the class name. It is also passed the
3905 // address of the pointer, so when the pointer is zero as it can be in an .o
3906 // file, that is used to look for an external relocation entry with a symbol
3908 static const char *get_objc2_64bit_class_name(uint64_t pointer_value,
3909 uint64_t ReferenceValue,
3910 struct DisassembleInfo *info) {
3912 uint32_t offset, left;
3915 // The pointer_value can be 0 in an object file and have a relocation
3916 // entry for the class symbol at the ReferenceValue (the address of the
3918 if (pointer_value == 0) {
3919 r = get_pointer_64(ReferenceValue, offset, left, S, info);
3920 if (r == nullptr || left < sizeof(uint64_t))
3923 const char *symbol_name = get_symbol_64(offset, S, info, n_value);
3924 if (symbol_name == nullptr)
3926 const char *class_name = strrchr(symbol_name, '$');
3927 if (class_name != nullptr && class_name[1] == '_' && class_name[2] != '\0')
3928 return class_name + 2;
3933 // The case were the pointer_value is non-zero and points to a class defined
3934 // in this Mach-O file.
3935 r = get_pointer_64(pointer_value, offset, left, S, info);
3936 if (r == nullptr || left < sizeof(struct class64_t))
3939 memcpy(&c, r, sizeof(struct class64_t));
3940 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3944 r = get_pointer_64(c.data, offset, left, S, info);
3945 if (r == nullptr || left < sizeof(struct class_ro64_t))
3947 struct class_ro64_t cro;
3948 memcpy(&cro, r, sizeof(struct class_ro64_t));
3949 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3953 const char *name = get_pointer_64(cro.name, offset, left, S, info);
3957 // get_objc2_64bit_cfstring_name is used for disassembly and is passed a
3958 // pointer to a cfstring and returns its name or nullptr.
3959 static const char *get_objc2_64bit_cfstring_name(uint64_t ReferenceValue,
3960 struct DisassembleInfo *info) {
3961 const char *r, *name;
3962 uint32_t offset, left;
3964 struct cfstring64_t cfs;
3965 uint64_t cfs_characters;
3967 r = get_pointer_64(ReferenceValue, offset, left, S, info);
3968 if (r == nullptr || left < sizeof(struct cfstring64_t))
3970 memcpy(&cfs, r, sizeof(struct cfstring64_t));
3971 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3973 if (cfs.characters == 0) {
3975 const char *symbol_name = get_symbol_64(
3976 offset + offsetof(struct cfstring64_t, characters), S, info, n_value);
3977 if (symbol_name == nullptr)
3979 cfs_characters = n_value;
3981 cfs_characters = cfs.characters;
3982 name = get_pointer_64(cfs_characters, offset, left, S, info);
3987 // get_objc2_64bit_selref() is used for disassembly and is passed a the address
3988 // of a pointer to an Objective-C selector reference when the pointer value is
3989 // zero as in a .o file and is likely to have a external relocation entry with
3990 // who's symbol's n_value is the real pointer to the selector name. If that is
3991 // the case the real pointer to the selector name is returned else 0 is
3993 static uint64_t get_objc2_64bit_selref(uint64_t ReferenceValue,
3994 struct DisassembleInfo *info) {
3995 uint32_t offset, left;
3998 const char *r = get_pointer_64(ReferenceValue, offset, left, S, info);
3999 if (r == nullptr || left < sizeof(uint64_t))
4002 const char *symbol_name = get_symbol_64(offset, S, info, n_value);
4003 if (symbol_name == nullptr)
4008 static const SectionRef get_section(MachOObjectFile *O, const char *segname,
4009 const char *sectname) {
4010 for (const SectionRef &Section : O->sections()) {
4012 Section.getName(SectName);
4013 DataRefImpl Ref = Section.getRawDataRefImpl();
4014 StringRef SegName = O->getSectionFinalSegmentName(Ref);
4015 if (SegName == segname && SectName == sectname)
4018 return SectionRef();
4022 walk_pointer_list_64(const char *listname, const SectionRef S,
4023 MachOObjectFile *O, struct DisassembleInfo *info,
4024 void (*func)(uint64_t, struct DisassembleInfo *info)) {
4025 if (S == SectionRef())
4029 S.getName(SectName);
4030 DataRefImpl Ref = S.getRawDataRefImpl();
4031 StringRef SegName = O->getSectionFinalSegmentName(Ref);
4032 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
4034 StringRef BytesStr = unwrapOrError(S.getContents(), O->getFileName());
4035 const char *Contents = reinterpret_cast<const char *>(BytesStr.data());
4037 for (uint32_t i = 0; i < S.getSize(); i += sizeof(uint64_t)) {
4038 uint32_t left = S.getSize() - i;
4039 uint32_t size = left < sizeof(uint64_t) ? left : sizeof(uint64_t);
4041 memcpy(&p, Contents + i, size);
4042 if (i + sizeof(uint64_t) > S.getSize())
4043 outs() << listname << " list pointer extends past end of (" << SegName
4044 << "," << SectName << ") section\n";
4045 outs() << format("%016" PRIx64, S.getAddress() + i) << " ";
4047 if (O->isLittleEndian() != sys::IsLittleEndianHost)
4048 sys::swapByteOrder(p);
4050 uint64_t n_value = 0;
4051 const char *name = get_symbol_64(i, S, info, n_value, p);
4052 if (name == nullptr)
4053 name = get_dyld_bind_info_symbolname(S.getAddress() + i, info);
4056 outs() << format("0x%" PRIx64, n_value);
4058 outs() << " + " << format("0x%" PRIx64, p);
4060 outs() << format("0x%" PRIx64, p);
4061 if (name != nullptr)
4062 outs() << " " << name;
4072 walk_pointer_list_32(const char *listname, const SectionRef S,
4073 MachOObjectFile *O, struct DisassembleInfo *info,
4074 void (*func)(uint32_t, struct DisassembleInfo *info)) {
4075 if (S == SectionRef())
4079 S.getName(SectName);
4080 DataRefImpl Ref = S.getRawDataRefImpl();
4081 StringRef SegName = O->getSectionFinalSegmentName(Ref);
4082 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
4084 StringRef BytesStr = unwrapOrError(S.getContents(), O->getFileName());
4085 const char *Contents = reinterpret_cast<const char *>(BytesStr.data());
4087 for (uint32_t i = 0; i < S.getSize(); i += sizeof(uint32_t)) {
4088 uint32_t left = S.getSize() - i;
4089 uint32_t size = left < sizeof(uint32_t) ? left : sizeof(uint32_t);
4091 memcpy(&p, Contents + i, size);
4092 if (i + sizeof(uint32_t) > S.getSize())
4093 outs() << listname << " list pointer extends past end of (" << SegName
4094 << "," << SectName << ") section\n";
4095 uint32_t Address = S.getAddress() + i;
4096 outs() << format("%08" PRIx32, Address) << " ";
4098 if (O->isLittleEndian() != sys::IsLittleEndianHost)
4099 sys::swapByteOrder(p);
4100 outs() << format("0x%" PRIx32, p);
4102 const char *name = get_symbol_32(i, S, info, p);
4103 if (name != nullptr)
4104 outs() << " " << name;
4112 static void print_layout_map(const char *layout_map, uint32_t left) {
4113 if (layout_map == nullptr)
4115 outs() << " layout map: ";
4117 outs() << format("0x%02" PRIx32, (*layout_map) & 0xff) << " ";
4120 } while (*layout_map != '\0' && left != 0);
4124 static void print_layout_map64(uint64_t p, struct DisassembleInfo *info) {
4125 uint32_t offset, left;
4127 const char *layout_map;
4131 layout_map = get_pointer_64(p, offset, left, S, info);
4132 print_layout_map(layout_map, left);
4135 static void print_layout_map32(uint32_t p, struct DisassembleInfo *info) {
4136 uint32_t offset, left;
4138 const char *layout_map;
4142 layout_map = get_pointer_32(p, offset, left, S, info);
4143 print_layout_map(layout_map, left);
4146 static void print_method_list64_t(uint64_t p, struct DisassembleInfo *info,
4147 const char *indent) {
4148 struct method_list64_t ml;
4149 struct method64_t m;
4151 uint32_t offset, xoffset, left, i;
4153 const char *name, *sym_name;
4156 r = get_pointer_64(p, offset, left, S, info);
4159 memset(&ml, '\0', sizeof(struct method_list64_t));
4160 if (left < sizeof(struct method_list64_t)) {
4161 memcpy(&ml, r, left);
4162 outs() << " (method_list_t entends past the end of the section)\n";
4164 memcpy(&ml, r, sizeof(struct method_list64_t));
4165 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4167 outs() << indent << "\t\t entsize " << ml.entsize << "\n";
4168 outs() << indent << "\t\t count " << ml.count << "\n";
4170 p += sizeof(struct method_list64_t);
4171 offset += sizeof(struct method_list64_t);
4172 for (i = 0; i < ml.count; i++) {
4173 r = get_pointer_64(p, offset, left, S, info);
4176 memset(&m, '\0', sizeof(struct method64_t));
4177 if (left < sizeof(struct method64_t)) {
4178 memcpy(&m, r, left);
4179 outs() << indent << " (method_t extends past the end of the section)\n";
4181 memcpy(&m, r, sizeof(struct method64_t));
4182 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4185 outs() << indent << "\t\t name ";
4186 sym_name = get_symbol_64(offset + offsetof(struct method64_t, name), S,
4187 info, n_value, m.name);
4189 if (info->verbose && sym_name != nullptr)
4192 outs() << format("0x%" PRIx64, n_value);
4194 outs() << " + " << format("0x%" PRIx64, m.name);
4196 outs() << format("0x%" PRIx64, m.name);
4197 name = get_pointer_64(m.name + n_value, xoffset, left, xS, info);
4198 if (name != nullptr)
4199 outs() << format(" %.*s", left, name);
4202 outs() << indent << "\t\t types ";
4203 sym_name = get_symbol_64(offset + offsetof(struct method64_t, types), S,
4204 info, n_value, m.types);
4206 if (info->verbose && sym_name != nullptr)
4209 outs() << format("0x%" PRIx64, n_value);
4211 outs() << " + " << format("0x%" PRIx64, m.types);
4213 outs() << format("0x%" PRIx64, m.types);
4214 name = get_pointer_64(m.types + n_value, xoffset, left, xS, info);
4215 if (name != nullptr)
4216 outs() << format(" %.*s", left, name);
4219 outs() << indent << "\t\t imp ";
4220 name = get_symbol_64(offset + offsetof(struct method64_t, imp), S, info,
4222 if (info->verbose && name == nullptr) {
4224 outs() << format("0x%" PRIx64, n_value) << " ";
4226 outs() << "+ " << format("0x%" PRIx64, m.imp) << " ";
4228 outs() << format("0x%" PRIx64, m.imp) << " ";
4230 if (name != nullptr)
4234 p += sizeof(struct method64_t);
4235 offset += sizeof(struct method64_t);
4239 static void print_method_list32_t(uint64_t p, struct DisassembleInfo *info,
4240 const char *indent) {
4241 struct method_list32_t ml;
4242 struct method32_t m;
4243 const char *r, *name;
4244 uint32_t offset, xoffset, left, i;
4247 r = get_pointer_32(p, offset, left, S, info);
4250 memset(&ml, '\0', sizeof(struct method_list32_t));
4251 if (left < sizeof(struct method_list32_t)) {
4252 memcpy(&ml, r, left);
4253 outs() << " (method_list_t entends past the end of the section)\n";
4255 memcpy(&ml, r, sizeof(struct method_list32_t));
4256 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4258 outs() << indent << "\t\t entsize " << ml.entsize << "\n";
4259 outs() << indent << "\t\t count " << ml.count << "\n";
4261 p += sizeof(struct method_list32_t);
4262 offset += sizeof(struct method_list32_t);
4263 for (i = 0; i < ml.count; i++) {
4264 r = get_pointer_32(p, offset, left, S, info);
4267 memset(&m, '\0', sizeof(struct method32_t));
4268 if (left < sizeof(struct method32_t)) {
4269 memcpy(&ml, r, left);
4270 outs() << indent << " (method_t entends past the end of the section)\n";
4272 memcpy(&m, r, sizeof(struct method32_t));
4273 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4276 outs() << indent << "\t\t name " << format("0x%" PRIx32, m.name);
4277 name = get_pointer_32(m.name, xoffset, left, xS, info);
4278 if (name != nullptr)
4279 outs() << format(" %.*s", left, name);
4282 outs() << indent << "\t\t types " << format("0x%" PRIx32, m.types);
4283 name = get_pointer_32(m.types, xoffset, left, xS, info);
4284 if (name != nullptr)
4285 outs() << format(" %.*s", left, name);
4288 outs() << indent << "\t\t imp " << format("0x%" PRIx32, m.imp);
4289 name = get_symbol_32(offset + offsetof(struct method32_t, imp), S, info,
4291 if (name != nullptr)
4292 outs() << " " << name;
4295 p += sizeof(struct method32_t);
4296 offset += sizeof(struct method32_t);
4300 static bool print_method_list(uint32_t p, struct DisassembleInfo *info) {
4301 uint32_t offset, left, xleft;
4303 struct objc_method_list_t method_list;
4304 struct objc_method_t method;
4305 const char *r, *methods, *name, *SymbolName;
4308 r = get_pointer_32(p, offset, left, S, info, true);
4313 if (left > sizeof(struct objc_method_list_t)) {
4314 memcpy(&method_list, r, sizeof(struct objc_method_list_t));
4316 outs() << "\t\t objc_method_list extends past end of the section\n";
4317 memset(&method_list, '\0', sizeof(struct objc_method_list_t));
4318 memcpy(&method_list, r, left);
4320 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4321 swapStruct(method_list);
4323 outs() << "\t\t obsolete "
4324 << format("0x%08" PRIx32, method_list.obsolete) << "\n";
4325 outs() << "\t\t method_count " << method_list.method_count << "\n";
4327 methods = r + sizeof(struct objc_method_list_t);
4328 for (i = 0; i < method_list.method_count; i++) {
4329 if ((i + 1) * sizeof(struct objc_method_t) > left) {
4330 outs() << "\t\t remaining method's extend past the of the section\n";
4333 memcpy(&method, methods + i * sizeof(struct objc_method_t),
4334 sizeof(struct objc_method_t));
4335 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4338 outs() << "\t\t method_name "
4339 << format("0x%08" PRIx32, method.method_name);
4340 if (info->verbose) {
4341 name = get_pointer_32(method.method_name, offset, xleft, S, info, true);
4342 if (name != nullptr)
4343 outs() << format(" %.*s", xleft, name);
4345 outs() << " (not in an __OBJC section)";
4349 outs() << "\t\t method_types "
4350 << format("0x%08" PRIx32, method.method_types);
4351 if (info->verbose) {
4352 name = get_pointer_32(method.method_types, offset, xleft, S, info, true);
4353 if (name != nullptr)
4354 outs() << format(" %.*s", xleft, name);
4356 outs() << " (not in an __OBJC section)";
4360 outs() << "\t\t method_imp "
4361 << format("0x%08" PRIx32, method.method_imp) << " ";
4362 if (info->verbose) {
4363 SymbolName = GuessSymbolName(method.method_imp, info->AddrMap);
4364 if (SymbolName != nullptr)
4365 outs() << SymbolName;
4372 static void print_protocol_list64_t(uint64_t p, struct DisassembleInfo *info) {
4373 struct protocol_list64_t pl;
4374 uint64_t q, n_value;
4375 struct protocol64_t pc;
4377 uint32_t offset, xoffset, left, i;
4379 const char *name, *sym_name;
4381 r = get_pointer_64(p, offset, left, S, info);
4384 memset(&pl, '\0', sizeof(struct protocol_list64_t));
4385 if (left < sizeof(struct protocol_list64_t)) {
4386 memcpy(&pl, r, left);
4387 outs() << " (protocol_list_t entends past the end of the section)\n";
4389 memcpy(&pl, r, sizeof(struct protocol_list64_t));
4390 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4392 outs() << " count " << pl.count << "\n";
4394 p += sizeof(struct protocol_list64_t);
4395 offset += sizeof(struct protocol_list64_t);
4396 for (i = 0; i < pl.count; i++) {
4397 r = get_pointer_64(p, offset, left, S, info);
4401 if (left < sizeof(uint64_t)) {
4402 memcpy(&q, r, left);
4403 outs() << " (protocol_t * entends past the end of the section)\n";
4405 memcpy(&q, r, sizeof(uint64_t));
4406 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4407 sys::swapByteOrder(q);
4409 outs() << "\t\t list[" << i << "] ";
4410 sym_name = get_symbol_64(offset, S, info, n_value, q);
4412 if (info->verbose && sym_name != nullptr)
4415 outs() << format("0x%" PRIx64, n_value);
4417 outs() << " + " << format("0x%" PRIx64, q);
4419 outs() << format("0x%" PRIx64, q);
4420 outs() << " (struct protocol_t *)\n";
4422 r = get_pointer_64(q + n_value, offset, left, S, info);
4425 memset(&pc, '\0', sizeof(struct protocol64_t));
4426 if (left < sizeof(struct protocol64_t)) {
4427 memcpy(&pc, r, left);
4428 outs() << " (protocol_t entends past the end of the section)\n";
4430 memcpy(&pc, r, sizeof(struct protocol64_t));
4431 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4434 outs() << "\t\t\t isa " << format("0x%" PRIx64, pc.isa) << "\n";
4436 outs() << "\t\t\t name ";
4437 sym_name = get_symbol_64(offset + offsetof(struct protocol64_t, name), S,
4438 info, n_value, pc.name);
4440 if (info->verbose && sym_name != nullptr)
4443 outs() << format("0x%" PRIx64, n_value);
4445 outs() << " + " << format("0x%" PRIx64, pc.name);
4447 outs() << format("0x%" PRIx64, pc.name);
4448 name = get_pointer_64(pc.name + n_value, xoffset, left, xS, info);
4449 if (name != nullptr)
4450 outs() << format(" %.*s", left, name);
4453 outs() << "\t\t\tprotocols " << format("0x%" PRIx64, pc.protocols) << "\n";
4455 outs() << "\t\t instanceMethods ";
4457 get_symbol_64(offset + offsetof(struct protocol64_t, instanceMethods),
4458 S, info, n_value, pc.instanceMethods);
4460 if (info->verbose && sym_name != nullptr)
4463 outs() << format("0x%" PRIx64, n_value);
4464 if (pc.instanceMethods != 0)
4465 outs() << " + " << format("0x%" PRIx64, pc.instanceMethods);
4467 outs() << format("0x%" PRIx64, pc.instanceMethods);
4468 outs() << " (struct method_list_t *)\n";
4469 if (pc.instanceMethods + n_value != 0)
4470 print_method_list64_t(pc.instanceMethods + n_value, info, "\t");
4472 outs() << "\t\t classMethods ";
4474 get_symbol_64(offset + offsetof(struct protocol64_t, classMethods), S,
4475 info, n_value, pc.classMethods);
4477 if (info->verbose && sym_name != nullptr)
4480 outs() << format("0x%" PRIx64, n_value);
4481 if (pc.classMethods != 0)
4482 outs() << " + " << format("0x%" PRIx64, pc.classMethods);
4484 outs() << format("0x%" PRIx64, pc.classMethods);
4485 outs() << " (struct method_list_t *)\n";
4486 if (pc.classMethods + n_value != 0)
4487 print_method_list64_t(pc.classMethods + n_value, info, "\t");
4489 outs() << "\t optionalInstanceMethods "
4490 << format("0x%" PRIx64, pc.optionalInstanceMethods) << "\n";
4491 outs() << "\t optionalClassMethods "
4492 << format("0x%" PRIx64, pc.optionalClassMethods) << "\n";
4493 outs() << "\t instanceProperties "
4494 << format("0x%" PRIx64, pc.instanceProperties) << "\n";
4496 p += sizeof(uint64_t);
4497 offset += sizeof(uint64_t);
4501 static void print_protocol_list32_t(uint32_t p, struct DisassembleInfo *info) {
4502 struct protocol_list32_t pl;
4504 struct protocol32_t pc;
4506 uint32_t offset, xoffset, left, i;
4510 r = get_pointer_32(p, offset, left, S, info);
4513 memset(&pl, '\0', sizeof(struct protocol_list32_t));
4514 if (left < sizeof(struct protocol_list32_t)) {
4515 memcpy(&pl, r, left);
4516 outs() << " (protocol_list_t entends past the end of the section)\n";
4518 memcpy(&pl, r, sizeof(struct protocol_list32_t));
4519 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4521 outs() << " count " << pl.count << "\n";
4523 p += sizeof(struct protocol_list32_t);
4524 offset += sizeof(struct protocol_list32_t);
4525 for (i = 0; i < pl.count; i++) {
4526 r = get_pointer_32(p, offset, left, S, info);
4530 if (left < sizeof(uint32_t)) {
4531 memcpy(&q, r, left);
4532 outs() << " (protocol_t * entends past the end of the section)\n";
4534 memcpy(&q, r, sizeof(uint32_t));
4535 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4536 sys::swapByteOrder(q);
4537 outs() << "\t\t list[" << i << "] " << format("0x%" PRIx32, q)
4538 << " (struct protocol_t *)\n";
4539 r = get_pointer_32(q, offset, left, S, info);
4542 memset(&pc, '\0', sizeof(struct protocol32_t));
4543 if (left < sizeof(struct protocol32_t)) {
4544 memcpy(&pc, r, left);
4545 outs() << " (protocol_t entends past the end of the section)\n";
4547 memcpy(&pc, r, sizeof(struct protocol32_t));
4548 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4550 outs() << "\t\t\t isa " << format("0x%" PRIx32, pc.isa) << "\n";
4551 outs() << "\t\t\t name " << format("0x%" PRIx32, pc.name);
4552 name = get_pointer_32(pc.name, xoffset, left, xS, info);
4553 if (name != nullptr)
4554 outs() << format(" %.*s", left, name);
4556 outs() << "\t\t\tprotocols " << format("0x%" PRIx32, pc.protocols) << "\n";
4557 outs() << "\t\t instanceMethods "
4558 << format("0x%" PRIx32, pc.instanceMethods)
4559 << " (struct method_list_t *)\n";
4560 if (pc.instanceMethods != 0)
4561 print_method_list32_t(pc.instanceMethods, info, "\t");
4562 outs() << "\t\t classMethods " << format("0x%" PRIx32, pc.classMethods)
4563 << " (struct method_list_t *)\n";
4564 if (pc.classMethods != 0)
4565 print_method_list32_t(pc.classMethods, info, "\t");
4566 outs() << "\t optionalInstanceMethods "
4567 << format("0x%" PRIx32, pc.optionalInstanceMethods) << "\n";
4568 outs() << "\t optionalClassMethods "
4569 << format("0x%" PRIx32, pc.optionalClassMethods) << "\n";
4570 outs() << "\t instanceProperties "
4571 << format("0x%" PRIx32, pc.instanceProperties) << "\n";
4572 p += sizeof(uint32_t);
4573 offset += sizeof(uint32_t);
4577 static void print_indent(uint32_t indent) {
4578 for (uint32_t i = 0; i < indent;) {
4579 if (indent - i >= 8) {
4583 for (uint32_t j = i; j < indent; j++)
4590 static bool print_method_description_list(uint32_t p, uint32_t indent,
4591 struct DisassembleInfo *info) {
4592 uint32_t offset, left, xleft;
4594 struct objc_method_description_list_t mdl;
4595 struct objc_method_description_t md;
4596 const char *r, *list, *name;
4599 r = get_pointer_32(p, offset, left, S, info, true);
4604 if (left > sizeof(struct objc_method_description_list_t)) {
4605 memcpy(&mdl, r, sizeof(struct objc_method_description_list_t));
4607 print_indent(indent);
4608 outs() << " objc_method_description_list extends past end of the section\n";
4609 memset(&mdl, '\0', sizeof(struct objc_method_description_list_t));
4610 memcpy(&mdl, r, left);
4612 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4615 print_indent(indent);
4616 outs() << " count " << mdl.count << "\n";
4618 list = r + sizeof(struct objc_method_description_list_t);
4619 for (i = 0; i < mdl.count; i++) {
4620 if ((i + 1) * sizeof(struct objc_method_description_t) > left) {
4621 print_indent(indent);
4622 outs() << " remaining list entries extend past the of the section\n";
4625 print_indent(indent);
4626 outs() << " list[" << i << "]\n";
4627 memcpy(&md, list + i * sizeof(struct objc_method_description_t),
4628 sizeof(struct objc_method_description_t));
4629 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4632 print_indent(indent);
4633 outs() << " name " << format("0x%08" PRIx32, md.name);
4634 if (info->verbose) {
4635 name = get_pointer_32(md.name, offset, xleft, S, info, true);
4636 if (name != nullptr)
4637 outs() << format(" %.*s", xleft, name);
4639 outs() << " (not in an __OBJC section)";
4643 print_indent(indent);
4644 outs() << " types " << format("0x%08" PRIx32, md.types);
4645 if (info->verbose) {
4646 name = get_pointer_32(md.types, offset, xleft, S, info, true);
4647 if (name != nullptr)
4648 outs() << format(" %.*s", xleft, name);
4650 outs() << " (not in an __OBJC section)";
4657 static bool print_protocol_list(uint32_t p, uint32_t indent,
4658 struct DisassembleInfo *info);
4660 static bool print_protocol(uint32_t p, uint32_t indent,
4661 struct DisassembleInfo *info) {
4662 uint32_t offset, left;
4664 struct objc_protocol_t protocol;
4665 const char *r, *name;
4667 r = get_pointer_32(p, offset, left, S, info, true);
4672 if (left >= sizeof(struct objc_protocol_t)) {
4673 memcpy(&protocol, r, sizeof(struct objc_protocol_t));
4675 print_indent(indent);
4676 outs() << " Protocol extends past end of the section\n";
4677 memset(&protocol, '\0', sizeof(struct objc_protocol_t));
4678 memcpy(&protocol, r, left);
4680 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4681 swapStruct(protocol);
4683 print_indent(indent);
4684 outs() << " isa " << format("0x%08" PRIx32, protocol.isa)
4687 print_indent(indent);
4688 outs() << " protocol_name "
4689 << format("0x%08" PRIx32, protocol.protocol_name);
4690 if (info->verbose) {
4691 name = get_pointer_32(protocol.protocol_name, offset, left, S, info, true);
4692 if (name != nullptr)
4693 outs() << format(" %.*s", left, name);
4695 outs() << " (not in an __OBJC section)";
4699 print_indent(indent);
4700 outs() << " protocol_list "
4701 << format("0x%08" PRIx32, protocol.protocol_list);
4702 if (print_protocol_list(protocol.protocol_list, indent + 4, info))
4703 outs() << " (not in an __OBJC section)\n";
4705 print_indent(indent);
4706 outs() << " instance_methods "
4707 << format("0x%08" PRIx32, protocol.instance_methods);
4708 if (print_method_description_list(protocol.instance_methods, indent, info))
4709 outs() << " (not in an __OBJC section)\n";
4711 print_indent(indent);
4712 outs() << " class_methods "
4713 << format("0x%08" PRIx32, protocol.class_methods);
4714 if (print_method_description_list(protocol.class_methods, indent, info))
4715 outs() << " (not in an __OBJC section)\n";
4720 static bool print_protocol_list(uint32_t p, uint32_t indent,
4721 struct DisassembleInfo *info) {
4722 uint32_t offset, left, l;
4724 struct objc_protocol_list_t protocol_list;
4725 const char *r, *list;
4728 r = get_pointer_32(p, offset, left, S, info, true);
4733 if (left > sizeof(struct objc_protocol_list_t)) {
4734 memcpy(&protocol_list, r, sizeof(struct objc_protocol_list_t));
4736 outs() << "\t\t objc_protocol_list_t extends past end of the section\n";
4737 memset(&protocol_list, '\0', sizeof(struct objc_protocol_list_t));
4738 memcpy(&protocol_list, r, left);
4740 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4741 swapStruct(protocol_list);
4743 print_indent(indent);
4744 outs() << " next " << format("0x%08" PRIx32, protocol_list.next)
4746 print_indent(indent);
4747 outs() << " count " << protocol_list.count << "\n";
4749 list = r + sizeof(struct objc_protocol_list_t);
4750 for (i = 0; i < protocol_list.count; i++) {
4751 if ((i + 1) * sizeof(uint32_t) > left) {
4752 outs() << "\t\t remaining list entries extend past the of the section\n";
4755 memcpy(&l, list + i * sizeof(uint32_t), sizeof(uint32_t));
4756 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4757 sys::swapByteOrder(l);
4759 print_indent(indent);
4760 outs() << " list[" << i << "] " << format("0x%08" PRIx32, l);
4761 if (print_protocol(l, indent, info))
4762 outs() << "(not in an __OBJC section)\n";
4767 static void print_ivar_list64_t(uint64_t p, struct DisassembleInfo *info) {
4768 struct ivar_list64_t il;
4771 uint32_t offset, xoffset, left, j;
4773 const char *name, *sym_name, *ivar_offset_p;
4774 uint64_t ivar_offset, n_value;
4776 r = get_pointer_64(p, offset, left, S, info);
4779 memset(&il, '\0', sizeof(struct ivar_list64_t));
4780 if (left < sizeof(struct ivar_list64_t)) {
4781 memcpy(&il, r, left);
4782 outs() << " (ivar_list_t entends past the end of the section)\n";
4784 memcpy(&il, r, sizeof(struct ivar_list64_t));
4785 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4787 outs() << " entsize " << il.entsize << "\n";
4788 outs() << " count " << il.count << "\n";
4790 p += sizeof(struct ivar_list64_t);
4791 offset += sizeof(struct ivar_list64_t);
4792 for (j = 0; j < il.count; j++) {
4793 r = get_pointer_64(p, offset, left, S, info);
4796 memset(&i, '\0', sizeof(struct ivar64_t));
4797 if (left < sizeof(struct ivar64_t)) {
4798 memcpy(&i, r, left);
4799 outs() << " (ivar_t entends past the end of the section)\n";
4801 memcpy(&i, r, sizeof(struct ivar64_t));
4802 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4805 outs() << "\t\t\t offset ";
4806 sym_name = get_symbol_64(offset + offsetof(struct ivar64_t, offset), S,
4807 info, n_value, i.offset);
4809 if (info->verbose && sym_name != nullptr)
4812 outs() << format("0x%" PRIx64, n_value);
4814 outs() << " + " << format("0x%" PRIx64, i.offset);
4816 outs() << format("0x%" PRIx64, i.offset);
4817 ivar_offset_p = get_pointer_64(i.offset + n_value, xoffset, left, xS, info);
4818 if (ivar_offset_p != nullptr && left >= sizeof(*ivar_offset_p)) {
4819 memcpy(&ivar_offset, ivar_offset_p, sizeof(ivar_offset));
4820 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4821 sys::swapByteOrder(ivar_offset);
4822 outs() << " " << ivar_offset << "\n";
4826 outs() << "\t\t\t name ";
4827 sym_name = get_symbol_64(offset + offsetof(struct ivar64_t, name), S, info,
4830 if (info->verbose && sym_name != nullptr)
4833 outs() << format("0x%" PRIx64, n_value);
4835 outs() << " + " << format("0x%" PRIx64, i.name);
4837 outs() << format("0x%" PRIx64, i.name);
4838 name = get_pointer_64(i.name + n_value, xoffset, left, xS, info);
4839 if (name != nullptr)
4840 outs() << format(" %.*s", left, name);
4843 outs() << "\t\t\t type ";
4844 sym_name = get_symbol_64(offset + offsetof(struct ivar64_t, type), S, info,
4846 name = get_pointer_64(i.type + n_value, xoffset, left, xS, info);
4848 if (info->verbose && sym_name != nullptr)
4851 outs() << format("0x%" PRIx64, n_value);
4853 outs() << " + " << format("0x%" PRIx64, i.type);
4855 outs() << format("0x%" PRIx64, i.type);
4856 if (name != nullptr)
4857 outs() << format(" %.*s", left, name);
4860 outs() << "\t\t\talignment " << i.alignment << "\n";
4861 outs() << "\t\t\t size " << i.size << "\n";
4863 p += sizeof(struct ivar64_t);
4864 offset += sizeof(struct ivar64_t);
4868 static void print_ivar_list32_t(uint32_t p, struct DisassembleInfo *info) {
4869 struct ivar_list32_t il;
4872 uint32_t offset, xoffset, left, j;
4874 const char *name, *ivar_offset_p;
4875 uint32_t ivar_offset;
4877 r = get_pointer_32(p, offset, left, S, info);
4880 memset(&il, '\0', sizeof(struct ivar_list32_t));
4881 if (left < sizeof(struct ivar_list32_t)) {
4882 memcpy(&il, r, left);
4883 outs() << " (ivar_list_t entends past the end of the section)\n";
4885 memcpy(&il, r, sizeof(struct ivar_list32_t));
4886 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4888 outs() << " entsize " << il.entsize << "\n";
4889 outs() << " count " << il.count << "\n";
4891 p += sizeof(struct ivar_list32_t);
4892 offset += sizeof(struct ivar_list32_t);
4893 for (j = 0; j < il.count; j++) {
4894 r = get_pointer_32(p, offset, left, S, info);
4897 memset(&i, '\0', sizeof(struct ivar32_t));
4898 if (left < sizeof(struct ivar32_t)) {
4899 memcpy(&i, r, left);
4900 outs() << " (ivar_t entends past the end of the section)\n";
4902 memcpy(&i, r, sizeof(struct ivar32_t));
4903 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4906 outs() << "\t\t\t offset " << format("0x%" PRIx32, i.offset);
4907 ivar_offset_p = get_pointer_32(i.offset, xoffset, left, xS, info);
4908 if (ivar_offset_p != nullptr && left >= sizeof(*ivar_offset_p)) {
4909 memcpy(&ivar_offset, ivar_offset_p, sizeof(ivar_offset));
4910 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4911 sys::swapByteOrder(ivar_offset);
4912 outs() << " " << ivar_offset << "\n";
4916 outs() << "\t\t\t name " << format("0x%" PRIx32, i.name);
4917 name = get_pointer_32(i.name, xoffset, left, xS, info);
4918 if (name != nullptr)
4919 outs() << format(" %.*s", left, name);
4922 outs() << "\t\t\t type " << format("0x%" PRIx32, i.type);
4923 name = get_pointer_32(i.type, xoffset, left, xS, info);
4924 if (name != nullptr)
4925 outs() << format(" %.*s", left, name);
4928 outs() << "\t\t\talignment " << i.alignment << "\n";
4929 outs() << "\t\t\t size " << i.size << "\n";
4931 p += sizeof(struct ivar32_t);
4932 offset += sizeof(struct ivar32_t);
4936 static void print_objc_property_list64(uint64_t p,
4937 struct DisassembleInfo *info) {
4938 struct objc_property_list64 opl;
4939 struct objc_property64 op;
4941 uint32_t offset, xoffset, left, j;
4943 const char *name, *sym_name;
4946 r = get_pointer_64(p, offset, left, S, info);
4949 memset(&opl, '\0', sizeof(struct objc_property_list64));
4950 if (left < sizeof(struct objc_property_list64)) {
4951 memcpy(&opl, r, left);
4952 outs() << " (objc_property_list entends past the end of the section)\n";
4954 memcpy(&opl, r, sizeof(struct objc_property_list64));
4955 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4957 outs() << " entsize " << opl.entsize << "\n";
4958 outs() << " count " << opl.count << "\n";
4960 p += sizeof(struct objc_property_list64);
4961 offset += sizeof(struct objc_property_list64);
4962 for (j = 0; j < opl.count; j++) {
4963 r = get_pointer_64(p, offset, left, S, info);
4966 memset(&op, '\0', sizeof(struct objc_property64));
4967 if (left < sizeof(struct objc_property64)) {
4968 memcpy(&op, r, left);
4969 outs() << " (objc_property entends past the end of the section)\n";
4971 memcpy(&op, r, sizeof(struct objc_property64));
4972 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4975 outs() << "\t\t\t name ";
4976 sym_name = get_symbol_64(offset + offsetof(struct objc_property64, name), S,
4977 info, n_value, op.name);
4979 if (info->verbose && sym_name != nullptr)
4982 outs() << format("0x%" PRIx64, n_value);
4984 outs() << " + " << format("0x%" PRIx64, op.name);
4986 outs() << format("0x%" PRIx64, op.name);
4987 name = get_pointer_64(op.name + n_value, xoffset, left, xS, info);
4988 if (name != nullptr)
4989 outs() << format(" %.*s", left, name);
4992 outs() << "\t\t\tattributes ";
4994 get_symbol_64(offset + offsetof(struct objc_property64, attributes), S,
4995 info, n_value, op.attributes);
4997 if (info->verbose && sym_name != nullptr)
5000 outs() << format("0x%" PRIx64, n_value);
5001 if (op.attributes != 0)
5002 outs() << " + " << format("0x%" PRIx64, op.attributes);
5004 outs() << format("0x%" PRIx64, op.attributes);
5005 name = get_pointer_64(op.attributes + n_value, xoffset, left, xS, info);
5006 if (name != nullptr)
5007 outs() << format(" %.*s", left, name);
5010 p += sizeof(struct objc_property64);
5011 offset += sizeof(struct objc_property64);
5015 static void print_objc_property_list32(uint32_t p,
5016 struct DisassembleInfo *info) {
5017 struct objc_property_list32 opl;
5018 struct objc_property32 op;
5020 uint32_t offset, xoffset, left, j;
5024 r = get_pointer_32(p, offset, left, S, info);
5027 memset(&opl, '\0', sizeof(struct objc_property_list32));
5028 if (left < sizeof(struct objc_property_list32)) {
5029 memcpy(&opl, r, left);
5030 outs() << " (objc_property_list entends past the end of the section)\n";
5032 memcpy(&opl, r, sizeof(struct objc_property_list32));
5033 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5035 outs() << " entsize " << opl.entsize << "\n";
5036 outs() << " count " << opl.count << "\n";
5038 p += sizeof(struct objc_property_list32);
5039 offset += sizeof(struct objc_property_list32);
5040 for (j = 0; j < opl.count; j++) {
5041 r = get_pointer_32(p, offset, left, S, info);
5044 memset(&op, '\0', sizeof(struct objc_property32));
5045 if (left < sizeof(struct objc_property32)) {
5046 memcpy(&op, r, left);
5047 outs() << " (objc_property entends past the end of the section)\n";
5049 memcpy(&op, r, sizeof(struct objc_property32));
5050 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5053 outs() << "\t\t\t name " << format("0x%" PRIx32, op.name);
5054 name = get_pointer_32(op.name, xoffset, left, xS, info);
5055 if (name != nullptr)
5056 outs() << format(" %.*s", left, name);
5059 outs() << "\t\t\tattributes " << format("0x%" PRIx32, op.attributes);
5060 name = get_pointer_32(op.attributes, xoffset, left, xS, info);
5061 if (name != nullptr)
5062 outs() << format(" %.*s", left, name);
5065 p += sizeof(struct objc_property32);
5066 offset += sizeof(struct objc_property32);
5070 static bool print_class_ro64_t(uint64_t p, struct DisassembleInfo *info,
5071 bool &is_meta_class) {
5072 struct class_ro64_t cro;
5074 uint32_t offset, xoffset, left;
5076 const char *name, *sym_name;
5079 r = get_pointer_64(p, offset, left, S, info);
5080 if (r == nullptr || left < sizeof(struct class_ro64_t))
5082 memcpy(&cro, r, sizeof(struct class_ro64_t));
5083 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5085 outs() << " flags " << format("0x%" PRIx32, cro.flags);
5086 if (cro.flags & RO_META)
5087 outs() << " RO_META";
5088 if (cro.flags & RO_ROOT)
5089 outs() << " RO_ROOT";
5090 if (cro.flags & RO_HAS_CXX_STRUCTORS)
5091 outs() << " RO_HAS_CXX_STRUCTORS";
5093 outs() << " instanceStart " << cro.instanceStart << "\n";
5094 outs() << " instanceSize " << cro.instanceSize << "\n";
5095 outs() << " reserved " << format("0x%" PRIx32, cro.reserved)
5097 outs() << " ivarLayout " << format("0x%" PRIx64, cro.ivarLayout)
5099 print_layout_map64(cro.ivarLayout, info);
5102 sym_name = get_symbol_64(offset + offsetof(struct class_ro64_t, name), S,
5103 info, n_value, cro.name);
5105 if (info->verbose && sym_name != nullptr)
5108 outs() << format("0x%" PRIx64, n_value);
5110 outs() << " + " << format("0x%" PRIx64, cro.name);
5112 outs() << format("0x%" PRIx64, cro.name);
5113 name = get_pointer_64(cro.name + n_value, xoffset, left, xS, info);
5114 if (name != nullptr)
5115 outs() << format(" %.*s", left, name);
5118 outs() << " baseMethods ";
5119 sym_name = get_symbol_64(offset + offsetof(struct class_ro64_t, baseMethods),
5120 S, info, n_value, cro.baseMethods);
5122 if (info->verbose && sym_name != nullptr)
5125 outs() << format("0x%" PRIx64, n_value);
5126 if (cro.baseMethods != 0)
5127 outs() << " + " << format("0x%" PRIx64, cro.baseMethods);
5129 outs() << format("0x%" PRIx64, cro.baseMethods);
5130 outs() << " (struct method_list_t *)\n";
5131 if (cro.baseMethods + n_value != 0)
5132 print_method_list64_t(cro.baseMethods + n_value, info, "");
5134 outs() << " baseProtocols ";
5136 get_symbol_64(offset + offsetof(struct class_ro64_t, baseProtocols), S,
5137 info, n_value, cro.baseProtocols);
5139 if (info->verbose && sym_name != nullptr)
5142 outs() << format("0x%" PRIx64, n_value);
5143 if (cro.baseProtocols != 0)
5144 outs() << " + " << format("0x%" PRIx64, cro.baseProtocols);
5146 outs() << format("0x%" PRIx64, cro.baseProtocols);
5148 if (cro.baseProtocols + n_value != 0)
5149 print_protocol_list64_t(cro.baseProtocols + n_value, info);
5151 outs() << " ivars ";
5152 sym_name = get_symbol_64(offset + offsetof(struct class_ro64_t, ivars), S,
5153 info, n_value, cro.ivars);
5155 if (info->verbose && sym_name != nullptr)
5158 outs() << format("0x%" PRIx64, n_value);
5160 outs() << " + " << format("0x%" PRIx64, cro.ivars);
5162 outs() << format("0x%" PRIx64, cro.ivars);
5164 if (cro.ivars + n_value != 0)
5165 print_ivar_list64_t(cro.ivars + n_value, info);
5167 outs() << " weakIvarLayout ";
5169 get_symbol_64(offset + offsetof(struct class_ro64_t, weakIvarLayout), S,
5170 info, n_value, cro.weakIvarLayout);
5172 if (info->verbose && sym_name != nullptr)
5175 outs() << format("0x%" PRIx64, n_value);
5176 if (cro.weakIvarLayout != 0)
5177 outs() << " + " << format("0x%" PRIx64, cro.weakIvarLayout);
5179 outs() << format("0x%" PRIx64, cro.weakIvarLayout);
5181 print_layout_map64(cro.weakIvarLayout + n_value, info);
5183 outs() << " baseProperties ";
5185 get_symbol_64(offset + offsetof(struct class_ro64_t, baseProperties), S,
5186 info, n_value, cro.baseProperties);
5188 if (info->verbose && sym_name != nullptr)
5191 outs() << format("0x%" PRIx64, n_value);
5192 if (cro.baseProperties != 0)
5193 outs() << " + " << format("0x%" PRIx64, cro.baseProperties);
5195 outs() << format("0x%" PRIx64, cro.baseProperties);
5197 if (cro.baseProperties + n_value != 0)
5198 print_objc_property_list64(cro.baseProperties + n_value, info);
5200 is_meta_class = (cro.flags & RO_META) != 0;
5204 static bool print_class_ro32_t(uint32_t p, struct DisassembleInfo *info,
5205 bool &is_meta_class) {
5206 struct class_ro32_t cro;
5208 uint32_t offset, xoffset, left;
5212 r = get_pointer_32(p, offset, left, S, info);
5215 memset(&cro, '\0', sizeof(struct class_ro32_t));
5216 if (left < sizeof(struct class_ro32_t)) {
5217 memcpy(&cro, r, left);
5218 outs() << " (class_ro_t entends past the end of the section)\n";
5220 memcpy(&cro, r, sizeof(struct class_ro32_t));
5221 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5223 outs() << " flags " << format("0x%" PRIx32, cro.flags);
5224 if (cro.flags & RO_META)
5225 outs() << " RO_META";
5226 if (cro.flags & RO_ROOT)
5227 outs() << " RO_ROOT";
5228 if (cro.flags & RO_HAS_CXX_STRUCTORS)
5229 outs() << " RO_HAS_CXX_STRUCTORS";
5231 outs() << " instanceStart " << cro.instanceStart << "\n";
5232 outs() << " instanceSize " << cro.instanceSize << "\n";
5233 outs() << " ivarLayout " << format("0x%" PRIx32, cro.ivarLayout)
5235 print_layout_map32(cro.ivarLayout, info);
5237 outs() << " name " << format("0x%" PRIx32, cro.name);
5238 name = get_pointer_32(cro.name, xoffset, left, xS, info);
5239 if (name != nullptr)
5240 outs() << format(" %.*s", left, name);
5243 outs() << " baseMethods "
5244 << format("0x%" PRIx32, cro.baseMethods)
5245 << " (struct method_list_t *)\n";
5246 if (cro.baseMethods != 0)
5247 print_method_list32_t(cro.baseMethods, info, "");
5249 outs() << " baseProtocols "
5250 << format("0x%" PRIx32, cro.baseProtocols) << "\n";
5251 if (cro.baseProtocols != 0)
5252 print_protocol_list32_t(cro.baseProtocols, info);
5253 outs() << " ivars " << format("0x%" PRIx32, cro.ivars)
5256 print_ivar_list32_t(cro.ivars, info);
5257 outs() << " weakIvarLayout "
5258 << format("0x%" PRIx32, cro.weakIvarLayout) << "\n";
5259 print_layout_map32(cro.weakIvarLayout, info);
5260 outs() << " baseProperties "
5261 << format("0x%" PRIx32, cro.baseProperties) << "\n";
5262 if (cro.baseProperties != 0)
5263 print_objc_property_list32(cro.baseProperties, info);
5264 is_meta_class = (cro.flags & RO_META) != 0;
5268 static void print_class64_t(uint64_t p, struct DisassembleInfo *info) {
5271 uint32_t offset, left;
5274 uint64_t isa_n_value, n_value;
5276 r = get_pointer_64(p, offset, left, S, info);
5277 if (r == nullptr || left < sizeof(struct class64_t))
5279 memcpy(&c, r, sizeof(struct class64_t));
5280 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5283 outs() << " isa " << format("0x%" PRIx64, c.isa);
5284 name = get_symbol_64(offset + offsetof(struct class64_t, isa), S, info,
5285 isa_n_value, c.isa);
5286 if (name != nullptr)
5287 outs() << " " << name;
5290 outs() << " superclass " << format("0x%" PRIx64, c.superclass);
5291 name = get_symbol_64(offset + offsetof(struct class64_t, superclass), S, info,
5292 n_value, c.superclass);
5293 if (name != nullptr)
5294 outs() << " " << name;
5296 name = get_dyld_bind_info_symbolname(S.getAddress() +
5297 offset + offsetof(struct class64_t, superclass), info);
5298 if (name != nullptr)
5299 outs() << " " << name;
5303 outs() << " cache " << format("0x%" PRIx64, c.cache);
5304 name = get_symbol_64(offset + offsetof(struct class64_t, cache), S, info,
5306 if (name != nullptr)
5307 outs() << " " << name;
5310 outs() << " vtable " << format("0x%" PRIx64, c.vtable);
5311 name = get_symbol_64(offset + offsetof(struct class64_t, vtable), S, info,
5313 if (name != nullptr)
5314 outs() << " " << name;
5317 name = get_symbol_64(offset + offsetof(struct class64_t, data), S, info,
5321 if (info->verbose && name != nullptr)
5324 outs() << format("0x%" PRIx64, n_value);
5326 outs() << " + " << format("0x%" PRIx64, c.data);
5328 outs() << format("0x%" PRIx64, c.data);
5329 outs() << " (struct class_ro_t *)";
5331 // This is a Swift class if some of the low bits of the pointer are set.
5332 if ((c.data + n_value) & 0x7)
5333 outs() << " Swift class";
5336 if (!print_class_ro64_t((c.data + n_value) & ~0x7, info, is_meta_class))
5339 if (!is_meta_class &&
5340 c.isa + isa_n_value != p &&
5341 c.isa + isa_n_value != 0 &&
5342 info->depth < 100) {
5344 outs() << "Meta Class\n";
5345 print_class64_t(c.isa + isa_n_value, info);
5349 static void print_class32_t(uint32_t p, struct DisassembleInfo *info) {
5352 uint32_t offset, left;
5356 r = get_pointer_32(p, offset, left, S, info);
5359 memset(&c, '\0', sizeof(struct class32_t));
5360 if (left < sizeof(struct class32_t)) {
5361 memcpy(&c, r, left);
5362 outs() << " (class_t entends past the end of the section)\n";
5364 memcpy(&c, r, sizeof(struct class32_t));
5365 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5368 outs() << " isa " << format("0x%" PRIx32, c.isa);
5370 get_symbol_32(offset + offsetof(struct class32_t, isa), S, info, c.isa);
5371 if (name != nullptr)
5372 outs() << " " << name;
5375 outs() << " superclass " << format("0x%" PRIx32, c.superclass);
5376 name = get_symbol_32(offset + offsetof(struct class32_t, superclass), S, info,
5378 if (name != nullptr)
5379 outs() << " " << name;
5382 outs() << " cache " << format("0x%" PRIx32, c.cache);
5383 name = get_symbol_32(offset + offsetof(struct class32_t, cache), S, info,
5385 if (name != nullptr)
5386 outs() << " " << name;
5389 outs() << " vtable " << format("0x%" PRIx32, c.vtable);
5390 name = get_symbol_32(offset + offsetof(struct class32_t, vtable), S, info,
5392 if (name != nullptr)
5393 outs() << " " << name;
5397 get_symbol_32(offset + offsetof(struct class32_t, data), S, info, c.data);
5398 outs() << " data " << format("0x%" PRIx32, c.data)
5399 << " (struct class_ro_t *)";
5401 // This is a Swift class if some of the low bits of the pointer are set.
5403 outs() << " Swift class";
5406 if (!print_class_ro32_t(c.data & ~0x3, info, is_meta_class))
5409 if (!is_meta_class) {
5410 outs() << "Meta Class\n";
5411 print_class32_t(c.isa, info);
5415 static void print_objc_class_t(struct objc_class_t *objc_class,
5416 struct DisassembleInfo *info) {
5417 uint32_t offset, left, xleft;
5418 const char *name, *p, *ivar_list;
5421 struct objc_ivar_list_t objc_ivar_list;
5422 struct objc_ivar_t ivar;
5424 outs() << "\t\t isa " << format("0x%08" PRIx32, objc_class->isa);
5425 if (info->verbose && CLS_GETINFO(objc_class, CLS_META)) {
5426 name = get_pointer_32(objc_class->isa, offset, left, S, info, true);
5427 if (name != nullptr)
5428 outs() << format(" %.*s", left, name);
5430 outs() << " (not in an __OBJC section)";
5434 outs() << "\t super_class "
5435 << format("0x%08" PRIx32, objc_class->super_class);
5436 if (info->verbose) {
5437 name = get_pointer_32(objc_class->super_class, offset, left, S, info, true);
5438 if (name != nullptr)
5439 outs() << format(" %.*s", left, name);
5441 outs() << " (not in an __OBJC section)";
5445 outs() << "\t\t name " << format("0x%08" PRIx32, objc_class->name);
5446 if (info->verbose) {
5447 name = get_pointer_32(objc_class->name, offset, left, S, info, true);
5448 if (name != nullptr)
5449 outs() << format(" %.*s", left, name);
5451 outs() << " (not in an __OBJC section)";
5455 outs() << "\t\t version " << format("0x%08" PRIx32, objc_class->version)
5458 outs() << "\t\t info " << format("0x%08" PRIx32, objc_class->info);
5459 if (info->verbose) {
5460 if (CLS_GETINFO(objc_class, CLS_CLASS))
5461 outs() << " CLS_CLASS";
5462 else if (CLS_GETINFO(objc_class, CLS_META))
5463 outs() << " CLS_META";
5467 outs() << "\t instance_size "
5468 << format("0x%08" PRIx32, objc_class->instance_size) << "\n";
5470 p = get_pointer_32(objc_class->ivars, offset, left, S, info, true);
5471 outs() << "\t\t ivars " << format("0x%08" PRIx32, objc_class->ivars);
5473 if (left > sizeof(struct objc_ivar_list_t)) {
5475 memcpy(&objc_ivar_list, p, sizeof(struct objc_ivar_list_t));
5477 outs() << " (entends past the end of the section)\n";
5478 memset(&objc_ivar_list, '\0', sizeof(struct objc_ivar_list_t));
5479 memcpy(&objc_ivar_list, p, left);
5481 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5482 swapStruct(objc_ivar_list);
5483 outs() << "\t\t ivar_count " << objc_ivar_list.ivar_count << "\n";
5484 ivar_list = p + sizeof(struct objc_ivar_list_t);
5485 for (i = 0; i < objc_ivar_list.ivar_count; i++) {
5486 if ((i + 1) * sizeof(struct objc_ivar_t) > left) {
5487 outs() << "\t\t remaining ivar's extend past the of the section\n";
5490 memcpy(&ivar, ivar_list + i * sizeof(struct objc_ivar_t),
5491 sizeof(struct objc_ivar_t));
5492 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5495 outs() << "\t\t\tivar_name " << format("0x%08" PRIx32, ivar.ivar_name);
5496 if (info->verbose) {
5497 name = get_pointer_32(ivar.ivar_name, offset, xleft, S, info, true);
5498 if (name != nullptr)
5499 outs() << format(" %.*s", xleft, name);
5501 outs() << " (not in an __OBJC section)";
5505 outs() << "\t\t\tivar_type " << format("0x%08" PRIx32, ivar.ivar_type);
5506 if (info->verbose) {
5507 name = get_pointer_32(ivar.ivar_type, offset, xleft, S, info, true);
5508 if (name != nullptr)
5509 outs() << format(" %.*s", xleft, name);
5511 outs() << " (not in an __OBJC section)";
5515 outs() << "\t\t ivar_offset "
5516 << format("0x%08" PRIx32, ivar.ivar_offset) << "\n";
5519 outs() << " (not in an __OBJC section)\n";
5522 outs() << "\t\t methods " << format("0x%08" PRIx32, objc_class->methodLists);
5523 if (print_method_list(objc_class->methodLists, info))
5524 outs() << " (not in an __OBJC section)\n";
5526 outs() << "\t\t cache " << format("0x%08" PRIx32, objc_class->cache)
5529 outs() << "\t\tprotocols " << format("0x%08" PRIx32, objc_class->protocols);
5530 if (print_protocol_list(objc_class->protocols, 16, info))
5531 outs() << " (not in an __OBJC section)\n";
5534 static void print_objc_objc_category_t(struct objc_category_t *objc_category,
5535 struct DisassembleInfo *info) {
5536 uint32_t offset, left;
5540 outs() << "\t category name "
5541 << format("0x%08" PRIx32, objc_category->category_name);
5542 if (info->verbose) {
5543 name = get_pointer_32(objc_category->category_name, offset, left, S, info,
5545 if (name != nullptr)
5546 outs() << format(" %.*s", left, name);
5548 outs() << " (not in an __OBJC section)";
5552 outs() << "\t\t class name "
5553 << format("0x%08" PRIx32, objc_category->class_name);
5554 if (info->verbose) {
5556 get_pointer_32(objc_category->class_name, offset, left, S, info, true);
5557 if (name != nullptr)
5558 outs() << format(" %.*s", left, name);
5560 outs() << " (not in an __OBJC section)";
5564 outs() << "\t instance methods "
5565 << format("0x%08" PRIx32, objc_category->instance_methods);
5566 if (print_method_list(objc_category->instance_methods, info))
5567 outs() << " (not in an __OBJC section)\n";
5569 outs() << "\t class methods "
5570 << format("0x%08" PRIx32, objc_category->class_methods);
5571 if (print_method_list(objc_category->class_methods, info))
5572 outs() << " (not in an __OBJC section)\n";
5575 static void print_category64_t(uint64_t p, struct DisassembleInfo *info) {
5576 struct category64_t c;
5578 uint32_t offset, xoffset, left;
5580 const char *name, *sym_name;
5583 r = get_pointer_64(p, offset, left, S, info);
5586 memset(&c, '\0', sizeof(struct category64_t));
5587 if (left < sizeof(struct category64_t)) {
5588 memcpy(&c, r, left);
5589 outs() << " (category_t entends past the end of the section)\n";
5591 memcpy(&c, r, sizeof(struct category64_t));
5592 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5596 sym_name = get_symbol_64(offset + offsetof(struct category64_t, name), S,
5597 info, n_value, c.name);
5599 if (info->verbose && sym_name != nullptr)
5602 outs() << format("0x%" PRIx64, n_value);
5604 outs() << " + " << format("0x%" PRIx64, c.name);
5606 outs() << format("0x%" PRIx64, c.name);
5607 name = get_pointer_64(c.name + n_value, xoffset, left, xS, info);
5608 if (name != nullptr)
5609 outs() << format(" %.*s", left, name);
5613 sym_name = get_symbol_64(offset + offsetof(struct category64_t, cls), S, info,
5616 if (info->verbose && sym_name != nullptr)
5619 outs() << format("0x%" PRIx64, n_value);
5621 outs() << " + " << format("0x%" PRIx64, c.cls);
5623 outs() << format("0x%" PRIx64, c.cls);
5625 if (c.cls + n_value != 0)
5626 print_class64_t(c.cls + n_value, info);
5628 outs() << " instanceMethods ";
5630 get_symbol_64(offset + offsetof(struct category64_t, instanceMethods), S,
5631 info, n_value, c.instanceMethods);
5633 if (info->verbose && sym_name != nullptr)
5636 outs() << format("0x%" PRIx64, n_value);
5637 if (c.instanceMethods != 0)
5638 outs() << " + " << format("0x%" PRIx64, c.instanceMethods);
5640 outs() << format("0x%" PRIx64, c.instanceMethods);
5642 if (c.instanceMethods + n_value != 0)
5643 print_method_list64_t(c.instanceMethods + n_value, info, "");
5645 outs() << " classMethods ";
5646 sym_name = get_symbol_64(offset + offsetof(struct category64_t, classMethods),
5647 S, info, n_value, c.classMethods);
5649 if (info->verbose && sym_name != nullptr)
5652 outs() << format("0x%" PRIx64, n_value);
5653 if (c.classMethods != 0)
5654 outs() << " + " << format("0x%" PRIx64, c.classMethods);
5656 outs() << format("0x%" PRIx64, c.classMethods);
5658 if (c.classMethods + n_value != 0)
5659 print_method_list64_t(c.classMethods + n_value, info, "");
5661 outs() << " protocols ";
5662 sym_name = get_symbol_64(offset + offsetof(struct category64_t, protocols), S,
5663 info, n_value, c.protocols);
5665 if (info->verbose && sym_name != nullptr)
5668 outs() << format("0x%" PRIx64, n_value);
5669 if (c.protocols != 0)
5670 outs() << " + " << format("0x%" PRIx64, c.protocols);
5672 outs() << format("0x%" PRIx64, c.protocols);
5674 if (c.protocols + n_value != 0)
5675 print_protocol_list64_t(c.protocols + n_value, info);
5677 outs() << "instanceProperties ";
5679 get_symbol_64(offset + offsetof(struct category64_t, instanceProperties),
5680 S, info, n_value, c.instanceProperties);
5682 if (info->verbose && sym_name != nullptr)
5685 outs() << format("0x%" PRIx64, n_value);
5686 if (c.instanceProperties != 0)
5687 outs() << " + " << format("0x%" PRIx64, c.instanceProperties);
5689 outs() << format("0x%" PRIx64, c.instanceProperties);
5691 if (c.instanceProperties + n_value != 0)
5692 print_objc_property_list64(c.instanceProperties + n_value, info);
5695 static void print_category32_t(uint32_t p, struct DisassembleInfo *info) {
5696 struct category32_t c;
5698 uint32_t offset, left;
5702 r = get_pointer_32(p, offset, left, S, info);
5705 memset(&c, '\0', sizeof(struct category32_t));
5706 if (left < sizeof(struct category32_t)) {
5707 memcpy(&c, r, left);
5708 outs() << " (category_t entends past the end of the section)\n";
5710 memcpy(&c, r, sizeof(struct category32_t));
5711 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5714 outs() << " name " << format("0x%" PRIx32, c.name);
5715 name = get_symbol_32(offset + offsetof(struct category32_t, name), S, info,
5718 outs() << " " << name;
5721 outs() << " cls " << format("0x%" PRIx32, c.cls) << "\n";
5723 print_class32_t(c.cls, info);
5724 outs() << " instanceMethods " << format("0x%" PRIx32, c.instanceMethods)
5726 if (c.instanceMethods != 0)
5727 print_method_list32_t(c.instanceMethods, info, "");
5728 outs() << " classMethods " << format("0x%" PRIx32, c.classMethods)
5730 if (c.classMethods != 0)
5731 print_method_list32_t(c.classMethods, info, "");
5732 outs() << " protocols " << format("0x%" PRIx32, c.protocols) << "\n";
5733 if (c.protocols != 0)
5734 print_protocol_list32_t(c.protocols, info);
5735 outs() << "instanceProperties " << format("0x%" PRIx32, c.instanceProperties)
5737 if (c.instanceProperties != 0)
5738 print_objc_property_list32(c.instanceProperties, info);
5741 static void print_message_refs64(SectionRef S, struct DisassembleInfo *info) {
5742 uint32_t i, left, offset, xoffset;
5743 uint64_t p, n_value;
5744 struct message_ref64 mr;
5745 const char *name, *sym_name;
5749 if (S == SectionRef())
5753 S.getName(SectName);
5754 DataRefImpl Ref = S.getRawDataRefImpl();
5755 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5756 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5758 for (i = 0; i < S.getSize(); i += sizeof(struct message_ref64)) {
5759 p = S.getAddress() + i;
5760 r = get_pointer_64(p, offset, left, S, info);
5763 memset(&mr, '\0', sizeof(struct message_ref64));
5764 if (left < sizeof(struct message_ref64)) {
5765 memcpy(&mr, r, left);
5766 outs() << " (message_ref entends past the end of the section)\n";
5768 memcpy(&mr, r, sizeof(struct message_ref64));
5769 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5773 name = get_symbol_64(offset + offsetof(struct message_ref64, imp), S, info,
5776 outs() << format("0x%" PRIx64, n_value) << " ";
5778 outs() << "+ " << format("0x%" PRIx64, mr.imp) << " ";
5780 outs() << format("0x%" PRIx64, mr.imp) << " ";
5781 if (name != nullptr)
5782 outs() << " " << name;
5786 sym_name = get_symbol_64(offset + offsetof(struct message_ref64, sel), S,
5787 info, n_value, mr.sel);
5789 if (info->verbose && sym_name != nullptr)
5792 outs() << format("0x%" PRIx64, n_value);
5794 outs() << " + " << format("0x%" PRIx64, mr.sel);
5796 outs() << format("0x%" PRIx64, mr.sel);
5797 name = get_pointer_64(mr.sel + n_value, xoffset, left, xS, info);
5798 if (name != nullptr)
5799 outs() << format(" %.*s", left, name);
5802 offset += sizeof(struct message_ref64);
5806 static void print_message_refs32(SectionRef S, struct DisassembleInfo *info) {
5807 uint32_t i, left, offset, xoffset, p;
5808 struct message_ref32 mr;
5809 const char *name, *r;
5812 if (S == SectionRef())
5816 S.getName(SectName);
5817 DataRefImpl Ref = S.getRawDataRefImpl();
5818 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5819 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5821 for (i = 0; i < S.getSize(); i += sizeof(struct message_ref64)) {
5822 p = S.getAddress() + i;
5823 r = get_pointer_32(p, offset, left, S, info);
5826 memset(&mr, '\0', sizeof(struct message_ref32));
5827 if (left < sizeof(struct message_ref32)) {
5828 memcpy(&mr, r, left);
5829 outs() << " (message_ref entends past the end of the section)\n";
5831 memcpy(&mr, r, sizeof(struct message_ref32));
5832 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5835 outs() << " imp " << format("0x%" PRIx32, mr.imp);
5836 name = get_symbol_32(offset + offsetof(struct message_ref32, imp), S, info,
5838 if (name != nullptr)
5839 outs() << " " << name;
5842 outs() << " sel " << format("0x%" PRIx32, mr.sel);
5843 name = get_pointer_32(mr.sel, xoffset, left, xS, info);
5844 if (name != nullptr)
5845 outs() << " " << name;
5848 offset += sizeof(struct message_ref32);
5852 static void print_image_info64(SectionRef S, struct DisassembleInfo *info) {
5853 uint32_t left, offset, swift_version;
5855 struct objc_image_info64 o;
5858 if (S == SectionRef())
5862 S.getName(SectName);
5863 DataRefImpl Ref = S.getRawDataRefImpl();
5864 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5865 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5867 r = get_pointer_64(p, offset, left, S, info);
5870 memset(&o, '\0', sizeof(struct objc_image_info64));
5871 if (left < sizeof(struct objc_image_info64)) {
5872 memcpy(&o, r, left);
5873 outs() << " (objc_image_info entends past the end of the section)\n";
5875 memcpy(&o, r, sizeof(struct objc_image_info64));
5876 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5878 outs() << " version " << o.version << "\n";
5879 outs() << " flags " << format("0x%" PRIx32, o.flags);
5880 if (o.flags & OBJC_IMAGE_IS_REPLACEMENT)
5881 outs() << " OBJC_IMAGE_IS_REPLACEMENT";
5882 if (o.flags & OBJC_IMAGE_SUPPORTS_GC)
5883 outs() << " OBJC_IMAGE_SUPPORTS_GC";
5884 if (o.flags & OBJC_IMAGE_IS_SIMULATED)
5885 outs() << " OBJC_IMAGE_IS_SIMULATED";
5886 if (o.flags & OBJC_IMAGE_HAS_CATEGORY_CLASS_PROPERTIES)
5887 outs() << " OBJC_IMAGE_HAS_CATEGORY_CLASS_PROPERTIES";
5888 swift_version = (o.flags >> 8) & 0xff;
5889 if (swift_version != 0) {
5890 if (swift_version == 1)
5891 outs() << " Swift 1.0";
5892 else if (swift_version == 2)
5893 outs() << " Swift 1.1";
5894 else if(swift_version == 3)
5895 outs() << " Swift 2.0";
5896 else if(swift_version == 4)
5897 outs() << " Swift 3.0";
5898 else if(swift_version == 5)
5899 outs() << " Swift 4.0";
5900 else if(swift_version == 6)
5901 outs() << " Swift 4.1/Swift 4.2";
5902 else if(swift_version == 7)
5903 outs() << " Swift 5 or later";
5905 outs() << " unknown future Swift version (" << swift_version << ")";
5910 static void print_image_info32(SectionRef S, struct DisassembleInfo *info) {
5911 uint32_t left, offset, swift_version, p;
5912 struct objc_image_info32 o;
5915 if (S == SectionRef())
5919 S.getName(SectName);
5920 DataRefImpl Ref = S.getRawDataRefImpl();
5921 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5922 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5924 r = get_pointer_32(p, offset, left, S, info);
5927 memset(&o, '\0', sizeof(struct objc_image_info32));
5928 if (left < sizeof(struct objc_image_info32)) {
5929 memcpy(&o, r, left);
5930 outs() << " (objc_image_info entends past the end of the section)\n";
5932 memcpy(&o, r, sizeof(struct objc_image_info32));
5933 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5935 outs() << " version " << o.version << "\n";
5936 outs() << " flags " << format("0x%" PRIx32, o.flags);
5937 if (o.flags & OBJC_IMAGE_IS_REPLACEMENT)
5938 outs() << " OBJC_IMAGE_IS_REPLACEMENT";
5939 if (o.flags & OBJC_IMAGE_SUPPORTS_GC)
5940 outs() << " OBJC_IMAGE_SUPPORTS_GC";
5941 swift_version = (o.flags >> 8) & 0xff;
5942 if (swift_version != 0) {
5943 if (swift_version == 1)
5944 outs() << " Swift 1.0";
5945 else if (swift_version == 2)
5946 outs() << " Swift 1.1";
5947 else if(swift_version == 3)
5948 outs() << " Swift 2.0";
5949 else if(swift_version == 4)
5950 outs() << " Swift 3.0";
5951 else if(swift_version == 5)
5952 outs() << " Swift 4.0";
5953 else if(swift_version == 6)
5954 outs() << " Swift 4.1/Swift 4.2";
5955 else if(swift_version == 7)
5956 outs() << " Swift 5 or later";
5958 outs() << " unknown future Swift version (" << swift_version << ")";
5963 static void print_image_info(SectionRef S, struct DisassembleInfo *info) {
5964 uint32_t left, offset, p;
5965 struct imageInfo_t o;
5969 S.getName(SectName);
5970 DataRefImpl Ref = S.getRawDataRefImpl();
5971 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5972 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5974 r = get_pointer_32(p, offset, left, S, info);
5977 memset(&o, '\0', sizeof(struct imageInfo_t));
5978 if (left < sizeof(struct imageInfo_t)) {
5979 memcpy(&o, r, left);
5980 outs() << " (imageInfo entends past the end of the section)\n";
5982 memcpy(&o, r, sizeof(struct imageInfo_t));
5983 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5985 outs() << " version " << o.version << "\n";
5986 outs() << " flags " << format("0x%" PRIx32, o.flags);
5992 outs() << " GC-only";
5998 static void printObjc2_64bit_MetaData(MachOObjectFile *O, bool verbose) {
5999 SymbolAddressMap AddrMap;
6001 CreateSymbolAddressMap(O, &AddrMap);
6003 std::vector<SectionRef> Sections;
6004 for (const SectionRef &Section : O->sections()) {
6006 Section.getName(SectName);
6007 Sections.push_back(Section);
6010 struct DisassembleInfo info(O, &AddrMap, &Sections, verbose);
6012 SectionRef CL = get_section(O, "__OBJC2", "__class_list");
6013 if (CL == SectionRef())
6014 CL = get_section(O, "__DATA", "__objc_classlist");
6015 if (CL == SectionRef())
6016 CL = get_section(O, "__DATA_CONST", "__objc_classlist");
6017 if (CL == SectionRef())
6018 CL = get_section(O, "__DATA_DIRTY", "__objc_classlist");
6020 walk_pointer_list_64("class", CL, O, &info, print_class64_t);
6022 SectionRef CR = get_section(O, "__OBJC2", "__class_refs");
6023 if (CR == SectionRef())
6024 CR = get_section(O, "__DATA", "__objc_classrefs");
6025 if (CR == SectionRef())
6026 CR = get_section(O, "__DATA_CONST", "__objc_classrefs");
6027 if (CR == SectionRef())
6028 CR = get_section(O, "__DATA_DIRTY", "__objc_classrefs");
6030 walk_pointer_list_64("class refs", CR, O, &info, nullptr);
6032 SectionRef SR = get_section(O, "__OBJC2", "__super_refs");
6033 if (SR == SectionRef())
6034 SR = get_section(O, "__DATA", "__objc_superrefs");
6035 if (SR == SectionRef())
6036 SR = get_section(O, "__DATA_CONST", "__objc_superrefs");
6037 if (SR == SectionRef())
6038 SR = get_section(O, "__DATA_DIRTY", "__objc_superrefs");
6040 walk_pointer_list_64("super refs", SR, O, &info, nullptr);
6042 SectionRef CA = get_section(O, "__OBJC2", "__category_list");
6043 if (CA == SectionRef())
6044 CA = get_section(O, "__DATA", "__objc_catlist");
6045 if (CA == SectionRef())
6046 CA = get_section(O, "__DATA_CONST", "__objc_catlist");
6047 if (CA == SectionRef())
6048 CA = get_section(O, "__DATA_DIRTY", "__objc_catlist");
6050 walk_pointer_list_64("category", CA, O, &info, print_category64_t);
6052 SectionRef PL = get_section(O, "__OBJC2", "__protocol_list");
6053 if (PL == SectionRef())
6054 PL = get_section(O, "__DATA", "__objc_protolist");
6055 if (PL == SectionRef())
6056 PL = get_section(O, "__DATA_CONST", "__objc_protolist");
6057 if (PL == SectionRef())
6058 PL = get_section(O, "__DATA_DIRTY", "__objc_protolist");
6060 walk_pointer_list_64("protocol", PL, O, &info, nullptr);
6062 SectionRef MR = get_section(O, "__OBJC2", "__message_refs");
6063 if (MR == SectionRef())
6064 MR = get_section(O, "__DATA", "__objc_msgrefs");
6065 if (MR == SectionRef())
6066 MR = get_section(O, "__DATA_CONST", "__objc_msgrefs");
6067 if (MR == SectionRef())
6068 MR = get_section(O, "__DATA_DIRTY", "__objc_msgrefs");
6070 print_message_refs64(MR, &info);
6072 SectionRef II = get_section(O, "__OBJC2", "__image_info");
6073 if (II == SectionRef())
6074 II = get_section(O, "__DATA", "__objc_imageinfo");
6075 if (II == SectionRef())
6076 II = get_section(O, "__DATA_CONST", "__objc_imageinfo");
6077 if (II == SectionRef())
6078 II = get_section(O, "__DATA_DIRTY", "__objc_imageinfo");
6080 print_image_info64(II, &info);
6083 static void printObjc2_32bit_MetaData(MachOObjectFile *O, bool verbose) {
6084 SymbolAddressMap AddrMap;
6086 CreateSymbolAddressMap(O, &AddrMap);
6088 std::vector<SectionRef> Sections;
6089 for (const SectionRef &Section : O->sections()) {
6091 Section.getName(SectName);
6092 Sections.push_back(Section);
6095 struct DisassembleInfo info(O, &AddrMap, &Sections, verbose);
6097 SectionRef CL = get_section(O, "__OBJC2", "__class_list");
6098 if (CL == SectionRef())
6099 CL = get_section(O, "__DATA", "__objc_classlist");
6100 if (CL == SectionRef())
6101 CL = get_section(O, "__DATA_CONST", "__objc_classlist");
6102 if (CL == SectionRef())
6103 CL = get_section(O, "__DATA_DIRTY", "__objc_classlist");
6105 walk_pointer_list_32("class", CL, O, &info, print_class32_t);
6107 SectionRef CR = get_section(O, "__OBJC2", "__class_refs");
6108 if (CR == SectionRef())
6109 CR = get_section(O, "__DATA", "__objc_classrefs");
6110 if (CR == SectionRef())
6111 CR = get_section(O, "__DATA_CONST", "__objc_classrefs");
6112 if (CR == SectionRef())
6113 CR = get_section(O, "__DATA_DIRTY", "__objc_classrefs");
6115 walk_pointer_list_32("class refs", CR, O, &info, nullptr);
6117 SectionRef SR = get_section(O, "__OBJC2", "__super_refs");
6118 if (SR == SectionRef())
6119 SR = get_section(O, "__DATA", "__objc_superrefs");
6120 if (SR == SectionRef())
6121 SR = get_section(O, "__DATA_CONST", "__objc_superrefs");
6122 if (SR == SectionRef())
6123 SR = get_section(O, "__DATA_DIRTY", "__objc_superrefs");
6125 walk_pointer_list_32("super refs", SR, O, &info, nullptr);
6127 SectionRef CA = get_section(O, "__OBJC2", "__category_list");
6128 if (CA == SectionRef())
6129 CA = get_section(O, "__DATA", "__objc_catlist");
6130 if (CA == SectionRef())
6131 CA = get_section(O, "__DATA_CONST", "__objc_catlist");
6132 if (CA == SectionRef())
6133 CA = get_section(O, "__DATA_DIRTY", "__objc_catlist");
6135 walk_pointer_list_32("category", CA, O, &info, print_category32_t);
6137 SectionRef PL = get_section(O, "__OBJC2", "__protocol_list");
6138 if (PL == SectionRef())
6139 PL = get_section(O, "__DATA", "__objc_protolist");
6140 if (PL == SectionRef())
6141 PL = get_section(O, "__DATA_CONST", "__objc_protolist");
6142 if (PL == SectionRef())
6143 PL = get_section(O, "__DATA_DIRTY", "__objc_protolist");
6145 walk_pointer_list_32("protocol", PL, O, &info, nullptr);
6147 SectionRef MR = get_section(O, "__OBJC2", "__message_refs");
6148 if (MR == SectionRef())
6149 MR = get_section(O, "__DATA", "__objc_msgrefs");
6150 if (MR == SectionRef())
6151 MR = get_section(O, "__DATA_CONST", "__objc_msgrefs");
6152 if (MR == SectionRef())
6153 MR = get_section(O, "__DATA_DIRTY", "__objc_msgrefs");
6155 print_message_refs32(MR, &info);
6157 SectionRef II = get_section(O, "__OBJC2", "__image_info");
6158 if (II == SectionRef())
6159 II = get_section(O, "__DATA", "__objc_imageinfo");
6160 if (II == SectionRef())
6161 II = get_section(O, "__DATA_CONST", "__objc_imageinfo");
6162 if (II == SectionRef())
6163 II = get_section(O, "__DATA_DIRTY", "__objc_imageinfo");
6165 print_image_info32(II, &info);
6168 static bool printObjc1_32bit_MetaData(MachOObjectFile *O, bool verbose) {
6169 uint32_t i, j, p, offset, xoffset, left, defs_left, def;
6170 const char *r, *name, *defs;
6171 struct objc_module_t module;
6173 struct objc_symtab_t symtab;
6174 struct objc_class_t objc_class;
6175 struct objc_category_t objc_category;
6177 outs() << "Objective-C segment\n";
6178 S = get_section(O, "__OBJC", "__module_info");
6179 if (S == SectionRef())
6182 SymbolAddressMap AddrMap;
6184 CreateSymbolAddressMap(O, &AddrMap);
6186 std::vector<SectionRef> Sections;
6187 for (const SectionRef &Section : O->sections()) {
6189 Section.getName(SectName);
6190 Sections.push_back(Section);
6193 struct DisassembleInfo info(O, &AddrMap, &Sections, verbose);
6195 for (i = 0; i < S.getSize(); i += sizeof(struct objc_module_t)) {
6196 p = S.getAddress() + i;
6197 r = get_pointer_32(p, offset, left, S, &info, true);
6200 memset(&module, '\0', sizeof(struct objc_module_t));
6201 if (left < sizeof(struct objc_module_t)) {
6202 memcpy(&module, r, left);
6203 outs() << " (module extends past end of __module_info section)\n";
6205 memcpy(&module, r, sizeof(struct objc_module_t));
6206 if (O->isLittleEndian() != sys::IsLittleEndianHost)
6209 outs() << "Module " << format("0x%" PRIx32, p) << "\n";
6210 outs() << " version " << module.version << "\n";
6211 outs() << " size " << module.size << "\n";
6213 name = get_pointer_32(module.name, xoffset, left, xS, &info, true);
6214 if (name != nullptr)
6215 outs() << format("%.*s", left, name);
6217 outs() << format("0x%08" PRIx32, module.name)
6218 << "(not in an __OBJC section)";
6221 r = get_pointer_32(module.symtab, xoffset, left, xS, &info, true);
6222 if (module.symtab == 0 || r == nullptr) {
6223 outs() << " symtab " << format("0x%08" PRIx32, module.symtab)
6224 << " (not in an __OBJC section)\n";
6227 outs() << " symtab " << format("0x%08" PRIx32, module.symtab) << "\n";
6228 memset(&symtab, '\0', sizeof(struct objc_symtab_t));
6231 if (left < sizeof(struct objc_symtab_t)) {
6232 memcpy(&symtab, r, left);
6233 outs() << "\tsymtab extends past end of an __OBJC section)\n";
6235 memcpy(&symtab, r, sizeof(struct objc_symtab_t));
6236 if (left > sizeof(struct objc_symtab_t)) {
6237 defs_left = left - sizeof(struct objc_symtab_t);
6238 defs = r + sizeof(struct objc_symtab_t);
6241 if (O->isLittleEndian() != sys::IsLittleEndianHost)
6244 outs() << "\tsel_ref_cnt " << symtab.sel_ref_cnt << "\n";
6245 r = get_pointer_32(symtab.refs, xoffset, left, xS, &info, true);
6246 outs() << "\trefs " << format("0x%08" PRIx32, symtab.refs);
6248 outs() << " (not in an __OBJC section)";
6250 outs() << "\tcls_def_cnt " << symtab.cls_def_cnt << "\n";
6251 outs() << "\tcat_def_cnt " << symtab.cat_def_cnt << "\n";
6252 if (symtab.cls_def_cnt > 0)
6253 outs() << "\tClass Definitions\n";
6254 for (j = 0; j < symtab.cls_def_cnt; j++) {
6255 if ((j + 1) * sizeof(uint32_t) > defs_left) {
6256 outs() << "\t(remaining class defs entries entends past the end of the "
6260 memcpy(&def, defs + j * sizeof(uint32_t), sizeof(uint32_t));
6261 if (O->isLittleEndian() != sys::IsLittleEndianHost)
6262 sys::swapByteOrder(def);
6264 r = get_pointer_32(def, xoffset, left, xS, &info, true);
6265 outs() << "\tdefs[" << j << "] " << format("0x%08" PRIx32, def);
6267 if (left > sizeof(struct objc_class_t)) {
6269 memcpy(&objc_class, r, sizeof(struct objc_class_t));
6271 outs() << " (entends past the end of the section)\n";
6272 memset(&objc_class, '\0', sizeof(struct objc_class_t));
6273 memcpy(&objc_class, r, left);
6275 if (O->isLittleEndian() != sys::IsLittleEndianHost)
6276 swapStruct(objc_class);
6277 print_objc_class_t(&objc_class, &info);
6279 outs() << "(not in an __OBJC section)\n";
6282 if (CLS_GETINFO(&objc_class, CLS_CLASS)) {
6283 outs() << "\tMeta Class";
6284 r = get_pointer_32(objc_class.isa, xoffset, left, xS, &info, true);
6286 if (left > sizeof(struct objc_class_t)) {
6288 memcpy(&objc_class, r, sizeof(struct objc_class_t));
6290 outs() << " (entends past the end of the section)\n";
6291 memset(&objc_class, '\0', sizeof(struct objc_class_t));
6292 memcpy(&objc_class, r, left);
6294 if (O->isLittleEndian() != sys::IsLittleEndianHost)
6295 swapStruct(objc_class);
6296 print_objc_class_t(&objc_class, &info);
6298 outs() << "(not in an __OBJC section)\n";
6302 if (symtab.cat_def_cnt > 0)
6303 outs() << "\tCategory Definitions\n";
6304 for (j = 0; j < symtab.cat_def_cnt; j++) {
6305 if ((j + symtab.cls_def_cnt + 1) * sizeof(uint32_t) > defs_left) {
6306 outs() << "\t(remaining category defs entries entends past the end of "
6307 << "the section)\n";
6310 memcpy(&def, defs + (j + symtab.cls_def_cnt) * sizeof(uint32_t),
6312 if (O->isLittleEndian() != sys::IsLittleEndianHost)
6313 sys::swapByteOrder(def);
6315 r = get_pointer_32(def, xoffset, left, xS, &info, true);
6316 outs() << "\tdefs[" << j + symtab.cls_def_cnt << "] "
6317 << format("0x%08" PRIx32, def);
6319 if (left > sizeof(struct objc_category_t)) {
6321 memcpy(&objc_category, r, sizeof(struct objc_category_t));
6323 outs() << " (entends past the end of the section)\n";
6324 memset(&objc_category, '\0', sizeof(struct objc_category_t));
6325 memcpy(&objc_category, r, left);
6327 if (O->isLittleEndian() != sys::IsLittleEndianHost)
6328 swapStruct(objc_category);
6329 print_objc_objc_category_t(&objc_category, &info);
6331 outs() << "(not in an __OBJC section)\n";
6335 const SectionRef II = get_section(O, "__OBJC", "__image_info");
6336 if (II != SectionRef())
6337 print_image_info(II, &info);
6342 static void DumpProtocolSection(MachOObjectFile *O, const char *sect,
6343 uint32_t size, uint32_t addr) {
6344 SymbolAddressMap AddrMap;
6345 CreateSymbolAddressMap(O, &AddrMap);
6347 std::vector<SectionRef> Sections;
6348 for (const SectionRef &Section : O->sections()) {
6350 Section.getName(SectName);
6351 Sections.push_back(Section);
6354 struct DisassembleInfo info(O, &AddrMap, &Sections, true);
6357 struct objc_protocol_t protocol;
6358 uint32_t left, paddr;
6359 for (p = sect; p < sect + size; p += sizeof(struct objc_protocol_t)) {
6360 memset(&protocol, '\0', sizeof(struct objc_protocol_t));
6361 left = size - (p - sect);
6362 if (left < sizeof(struct objc_protocol_t)) {
6363 outs() << "Protocol extends past end of __protocol section\n";
6364 memcpy(&protocol, p, left);
6366 memcpy(&protocol, p, sizeof(struct objc_protocol_t));
6367 if (O->isLittleEndian() != sys::IsLittleEndianHost)
6368 swapStruct(protocol);
6369 paddr = addr + (p - sect);
6370 outs() << "Protocol " << format("0x%" PRIx32, paddr);
6371 if (print_protocol(paddr, 0, &info))
6372 outs() << "(not in an __OBJC section)\n";
6377 inline void swapStruct(struct xar_header &xar) {
6378 sys::swapByteOrder(xar.magic);
6379 sys::swapByteOrder(xar.size);
6380 sys::swapByteOrder(xar.version);
6381 sys::swapByteOrder(xar.toc_length_compressed);
6382 sys::swapByteOrder(xar.toc_length_uncompressed);
6383 sys::swapByteOrder(xar.cksum_alg);
6386 static void PrintModeVerbose(uint32_t mode) {
6387 switch(mode & S_IFMT){
6411 /* owner permissions */
6422 else if(mode & S_IEXEC)
6427 /* group permissions */
6428 if(mode & (S_IREAD >> 3))
6432 if(mode & (S_IWRITE >> 3))
6438 else if(mode & (S_IEXEC >> 3))
6443 /* other permissions */
6444 if(mode & (S_IREAD >> 6))
6448 if(mode & (S_IWRITE >> 6))
6454 else if(mode & (S_IEXEC >> 6))
6460 static void PrintXarFilesSummary(const char *XarFilename, xar_t xar) {
6462 const char *key, *type, *mode, *user, *group, *size, *mtime, *name, *m;
6464 uint32_t mode_value;
6468 WithColor::error(errs(), "llvm-objdump")
6469 << "can't obtain an xar iterator for xar archive " << XarFilename
6474 // Go through the xar's files.
6475 for (xf = xar_file_first(xar, xi); xf; xf = xar_file_next(xi)) {
6478 WithColor::error(errs(), "llvm-objdump")
6479 << "can't obtain an xar iterator for xar archive " << XarFilename
6490 for(key = xar_prop_first(xf, xp); key; key = xar_prop_next(xp)){
6491 const char *val = nullptr;
6492 xar_prop_get(xf, key, &val);
6493 #if 0 // Useful for debugging.
6494 outs() << "key: " << key << " value: " << val << "\n";
6496 if(strcmp(key, "type") == 0)
6498 if(strcmp(key, "mode") == 0)
6500 if(strcmp(key, "user") == 0)
6502 if(strcmp(key, "group") == 0)
6504 if(strcmp(key, "data/size") == 0)
6506 if(strcmp(key, "mtime") == 0)
6508 if(strcmp(key, "name") == 0)
6511 if(mode != nullptr){
6512 mode_value = strtoul(mode, &endp, 8);
6514 outs() << "(mode: \"" << mode << "\" contains non-octal chars) ";
6515 if(strcmp(type, "file") == 0)
6516 mode_value |= S_IFREG;
6517 PrintModeVerbose(mode_value);
6521 outs() << format("%10s/", user);
6522 if(group != nullptr)
6523 outs() << format("%-10s ", group);
6525 outs() << format("%7s ", size);
6526 if(mtime != nullptr){
6527 for(m = mtime; *m != 'T' && *m != '\0'; m++)
6532 for( ; *m != 'Z' && *m != '\0'; m++)
6542 static void DumpBitcodeSection(MachOObjectFile *O, const char *sect,
6543 uint32_t size, bool verbose,
6544 bool PrintXarHeader, bool PrintXarFileHeaders,
6545 std::string XarMemberName) {
6546 if(size < sizeof(struct xar_header)) {
6547 outs() << "size of (__LLVM,__bundle) section too small (smaller than size "
6548 "of struct xar_header)\n";
6551 struct xar_header XarHeader;
6552 memcpy(&XarHeader, sect, sizeof(struct xar_header));
6553 if (sys::IsLittleEndianHost)
6554 swapStruct(XarHeader);
6555 if (PrintXarHeader) {
6556 if (!XarMemberName.empty())
6557 outs() << "In xar member " << XarMemberName << ": ";
6559 outs() << "For (__LLVM,__bundle) section: ";
6560 outs() << "xar header\n";
6561 if (XarHeader.magic == XAR_HEADER_MAGIC)
6562 outs() << " magic XAR_HEADER_MAGIC\n";
6565 << format_hex(XarHeader.magic, 10, true)
6566 << " (not XAR_HEADER_MAGIC)\n";
6567 outs() << " size " << XarHeader.size << "\n";
6568 outs() << " version " << XarHeader.version << "\n";
6569 outs() << " toc_length_compressed " << XarHeader.toc_length_compressed
6571 outs() << "toc_length_uncompressed " << XarHeader.toc_length_uncompressed
6573 outs() << " cksum_alg ";
6574 switch (XarHeader.cksum_alg) {
6575 case XAR_CKSUM_NONE:
6576 outs() << "XAR_CKSUM_NONE\n";
6578 case XAR_CKSUM_SHA1:
6579 outs() << "XAR_CKSUM_SHA1\n";
6582 outs() << "XAR_CKSUM_MD5\n";
6584 #ifdef XAR_CKSUM_SHA256
6585 case XAR_CKSUM_SHA256:
6586 outs() << "XAR_CKSUM_SHA256\n";
6589 #ifdef XAR_CKSUM_SHA512
6590 case XAR_CKSUM_SHA512:
6591 outs() << "XAR_CKSUM_SHA512\n";
6595 outs() << XarHeader.cksum_alg << "\n";
6599 SmallString<128> XarFilename;
6601 std::error_code XarEC =
6602 sys::fs::createTemporaryFile("llvm-objdump", "xar", FD, XarFilename);
6604 WithColor::error(errs(), "llvm-objdump") << XarEC.message() << "\n";
6607 ToolOutputFile XarFile(XarFilename, FD);
6608 raw_fd_ostream &XarOut = XarFile.os();
6609 StringRef XarContents(sect, size);
6610 XarOut << XarContents;
6612 if (XarOut.has_error())
6615 ScopedXarFile xar(XarFilename.c_str(), READ);
6617 WithColor::error(errs(), "llvm-objdump")
6618 << "can't create temporary xar archive " << XarFilename << "\n";
6622 SmallString<128> TocFilename;
6623 std::error_code TocEC =
6624 sys::fs::createTemporaryFile("llvm-objdump", "toc", TocFilename);
6626 WithColor::error(errs(), "llvm-objdump") << TocEC.message() << "\n";
6629 xar_serialize(xar, TocFilename.c_str());
6631 if (PrintXarFileHeaders) {
6632 if (!XarMemberName.empty())
6633 outs() << "In xar member " << XarMemberName << ": ";
6635 outs() << "For (__LLVM,__bundle) section: ";
6636 outs() << "xar archive files:\n";
6637 PrintXarFilesSummary(XarFilename.c_str(), xar);
6640 ErrorOr<std::unique_ptr<MemoryBuffer>> FileOrErr =
6641 MemoryBuffer::getFileOrSTDIN(TocFilename.c_str());
6642 if (std::error_code EC = FileOrErr.getError()) {
6643 WithColor::error(errs(), "llvm-objdump") << EC.message() << "\n";
6646 std::unique_ptr<MemoryBuffer> &Buffer = FileOrErr.get();
6648 if (!XarMemberName.empty())
6649 outs() << "In xar member " << XarMemberName << ": ";
6651 outs() << "For (__LLVM,__bundle) section: ";
6652 outs() << "xar table of contents:\n";
6653 outs() << Buffer->getBuffer() << "\n";
6655 // TODO: Go through the xar's files.
6658 WithColor::error(errs(), "llvm-objdump")
6659 << "can't obtain an xar iterator for xar archive "
6660 << XarFilename.c_str() << "\n";
6663 for(xar_file_t xf = xar_file_first(xar, xi); xf; xf = xar_file_next(xi)){
6665 const char *member_name, *member_type, *member_size_string;
6670 WithColor::error(errs(), "llvm-objdump")
6671 << "can't obtain an xar iterator for xar archive "
6672 << XarFilename.c_str() << "\n";
6677 member_size_string = NULL;
6678 for(key = xar_prop_first(xf, xp); key; key = xar_prop_next(xp)){
6679 const char *val = nullptr;
6680 xar_prop_get(xf, key, &val);
6681 #if 0 // Useful for debugging.
6682 outs() << "key: " << key << " value: " << val << "\n";
6684 if (strcmp(key, "name") == 0)
6686 if (strcmp(key, "type") == 0)
6688 if (strcmp(key, "data/size") == 0)
6689 member_size_string = val;
6692 * If we find a file with a name, date/size and type properties
6693 * and with the type being "file" see if that is a xar file.
6695 if (member_name != NULL && member_type != NULL &&
6696 strcmp(member_type, "file") == 0 &&
6697 member_size_string != NULL){
6698 // Extract the file into a buffer.
6700 member_size = strtoul(member_size_string, &endptr, 10);
6701 if (*endptr == '\0' && member_size != 0) {
6703 if (xar_extract_tobuffersz(xar, xf, &buffer, &member_size) == 0) {
6704 #if 0 // Useful for debugging.
6705 outs() << "xar member: " << member_name << " extracted\n";
6707 // Set the XarMemberName we want to see printed in the header.
6708 std::string OldXarMemberName;
6709 // If XarMemberName is already set this is nested. So
6710 // save the old name and create the nested name.
6711 if (!XarMemberName.empty()) {
6712 OldXarMemberName = XarMemberName;
6714 (Twine("[") + XarMemberName + "]" + member_name).str();
6716 OldXarMemberName = "";
6717 XarMemberName = member_name;
6719 // See if this is could be a xar file (nested).
6720 if (member_size >= sizeof(struct xar_header)) {
6721 #if 0 // Useful for debugging.
6722 outs() << "could be a xar file: " << member_name << "\n";
6724 memcpy((char *)&XarHeader, buffer, sizeof(struct xar_header));
6725 if (sys::IsLittleEndianHost)
6726 swapStruct(XarHeader);
6727 if (XarHeader.magic == XAR_HEADER_MAGIC)
6728 DumpBitcodeSection(O, buffer, member_size, verbose,
6729 PrintXarHeader, PrintXarFileHeaders,
6732 XarMemberName = OldXarMemberName;
6739 #endif // defined(HAVE_LIBXAR)
6741 static void printObjcMetaData(MachOObjectFile *O, bool verbose) {
6743 printObjc2_64bit_MetaData(O, verbose);
6745 MachO::mach_header H;
6747 if (H.cputype == MachO::CPU_TYPE_ARM)
6748 printObjc2_32bit_MetaData(O, verbose);
6750 // This is the 32-bit non-arm cputype case. Which is normally
6751 // the first Objective-C ABI. But it may be the case of a
6752 // binary for the iOS simulator which is the second Objective-C
6753 // ABI. In that case printObjc1_32bit_MetaData() will determine that
6754 // and return false.
6755 if (!printObjc1_32bit_MetaData(O, verbose))
6756 printObjc2_32bit_MetaData(O, verbose);
6761 // GuessLiteralPointer returns a string which for the item in the Mach-O file
6762 // for the address passed in as ReferenceValue for printing as a comment with
6763 // the instruction and also returns the corresponding type of that item
6764 // indirectly through ReferenceType.
6766 // If ReferenceValue is an address of literal cstring then a pointer to the
6767 // cstring is returned and ReferenceType is set to
6768 // LLVMDisassembler_ReferenceType_Out_LitPool_CstrAddr .
6770 // If ReferenceValue is an address of an Objective-C CFString, Selector ref or
6771 // Class ref that name is returned and the ReferenceType is set accordingly.
6773 // Lastly, literals which are Symbol address in a literal pool are looked for
6774 // and if found the symbol name is returned and ReferenceType is set to
6775 // LLVMDisassembler_ReferenceType_Out_LitPool_SymAddr .
6777 // If there is no item in the Mach-O file for the address passed in as
6778 // ReferenceValue nullptr is returned and ReferenceType is unchanged.
6779 static const char *GuessLiteralPointer(uint64_t ReferenceValue,
6780 uint64_t ReferencePC,
6781 uint64_t *ReferenceType,
6782 struct DisassembleInfo *info) {
6783 // First see if there is an external relocation entry at the ReferencePC.
6784 if (info->O->getHeader().filetype == MachO::MH_OBJECT) {
6785 uint64_t sect_addr = info->S.getAddress();
6786 uint64_t sect_offset = ReferencePC - sect_addr;
6787 bool reloc_found = false;
6789 MachO::any_relocation_info RE;
6790 bool isExtern = false;
6792 for (const RelocationRef &Reloc : info->S.relocations()) {
6793 uint64_t RelocOffset = Reloc.getOffset();
6794 if (RelocOffset == sect_offset) {
6795 Rel = Reloc.getRawDataRefImpl();
6796 RE = info->O->getRelocation(Rel);
6797 if (info->O->isRelocationScattered(RE))
6799 isExtern = info->O->getPlainRelocationExternal(RE);
6801 symbol_iterator RelocSym = Reloc.getSymbol();
6808 // If there is an external relocation entry for a symbol in a section
6809 // then used that symbol's value for the value of the reference.
6810 if (reloc_found && isExtern) {
6811 if (info->O->getAnyRelocationPCRel(RE)) {
6812 unsigned Type = info->O->getAnyRelocationType(RE);
6813 if (Type == MachO::X86_64_RELOC_SIGNED) {
6814 ReferenceValue = Symbol.getValue();
6820 // Look for literals such as Objective-C CFStrings refs, Selector refs,
6821 // Message refs and Class refs.
6822 bool classref, selref, msgref, cfstring;
6823 uint64_t pointer_value = GuessPointerPointer(ReferenceValue, info, classref,
6824 selref, msgref, cfstring);
6825 if (classref && pointer_value == 0) {
6826 // Note the ReferenceValue is a pointer into the __objc_classrefs section.
6827 // And the pointer_value in that section is typically zero as it will be
6828 // set by dyld as part of the "bind information".
6829 const char *name = get_dyld_bind_info_symbolname(ReferenceValue, info);
6830 if (name != nullptr) {
6831 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Class_Ref;
6832 const char *class_name = strrchr(name, '$');
6833 if (class_name != nullptr && class_name[1] == '_' &&
6834 class_name[2] != '\0') {
6835 info->class_name = class_name + 2;
6842 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Class_Ref;
6844 get_objc2_64bit_class_name(pointer_value, ReferenceValue, info);
6845 if (name != nullptr)
6846 info->class_name = name;
6848 name = "bad class ref";
6853 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_CFString_Ref;
6854 const char *name = get_objc2_64bit_cfstring_name(ReferenceValue, info);
6858 if (selref && pointer_value == 0)
6859 pointer_value = get_objc2_64bit_selref(ReferenceValue, info);
6861 if (pointer_value != 0)
6862 ReferenceValue = pointer_value;
6864 const char *name = GuessCstringPointer(ReferenceValue, info);
6866 if (pointer_value != 0 && selref) {
6867 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Selector_Ref;
6868 info->selector_name = name;
6869 } else if (pointer_value != 0 && msgref) {
6870 info->class_name = nullptr;
6871 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message_Ref;
6872 info->selector_name = name;
6874 *ReferenceType = LLVMDisassembler_ReferenceType_Out_LitPool_CstrAddr;
6878 // Lastly look for an indirect symbol with this ReferenceValue which is in
6879 // a literal pool. If found return that symbol name.
6880 name = GuessIndirectSymbol(ReferenceValue, info);
6882 *ReferenceType = LLVMDisassembler_ReferenceType_Out_LitPool_SymAddr;
6889 // SymbolizerSymbolLookUp is the symbol lookup function passed when creating
6890 // the Symbolizer. It looks up the ReferenceValue using the info passed via the
6891 // pointer to the struct DisassembleInfo that was passed when MCSymbolizer
6892 // is created and returns the symbol name that matches the ReferenceValue or
6893 // nullptr if none. The ReferenceType is passed in for the IN type of
6894 // reference the instruction is making from the values in defined in the header
6895 // "llvm-c/Disassembler.h". On return the ReferenceType can set to a specific
6896 // Out type and the ReferenceName will also be set which is added as a comment
6897 // to the disassembled instruction.
6899 // If the symbol name is a C++ mangled name then the demangled name is
6900 // returned through ReferenceName and ReferenceType is set to
6901 // LLVMDisassembler_ReferenceType_DeMangled_Name .
6903 // When this is called to get a symbol name for a branch target then the
6904 // ReferenceType will be LLVMDisassembler_ReferenceType_In_Branch and then
6905 // SymbolValue will be looked for in the indirect symbol table to determine if
6906 // it is an address for a symbol stub. If so then the symbol name for that
6907 // stub is returned indirectly through ReferenceName and then ReferenceType is
6908 // set to LLVMDisassembler_ReferenceType_Out_SymbolStub.
6910 // When this is called with an value loaded via a PC relative load then
6911 // ReferenceType will be LLVMDisassembler_ReferenceType_In_PCrel_Load then the
6912 // SymbolValue is checked to be an address of literal pointer, symbol pointer,
6913 // or an Objective-C meta data reference. If so the output ReferenceType is
6914 // set to correspond to that as well as setting the ReferenceName.
6915 static const char *SymbolizerSymbolLookUp(void *DisInfo,
6916 uint64_t ReferenceValue,
6917 uint64_t *ReferenceType,
6918 uint64_t ReferencePC,
6919 const char **ReferenceName) {
6920 struct DisassembleInfo *info = (struct DisassembleInfo *)DisInfo;
6921 // If no verbose symbolic information is wanted then just return nullptr.
6922 if (!info->verbose) {
6923 *ReferenceName = nullptr;
6924 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
6928 const char *SymbolName = GuessSymbolName(ReferenceValue, info->AddrMap);
6930 if (*ReferenceType == LLVMDisassembler_ReferenceType_In_Branch) {
6931 *ReferenceName = GuessIndirectSymbol(ReferenceValue, info);
6932 if (*ReferenceName != nullptr) {
6933 method_reference(info, ReferenceType, ReferenceName);
6934 if (*ReferenceType != LLVMDisassembler_ReferenceType_Out_Objc_Message)
6935 *ReferenceType = LLVMDisassembler_ReferenceType_Out_SymbolStub;
6936 } else if (SymbolName != nullptr && strncmp(SymbolName, "__Z", 3) == 0) {
6937 if (info->demangled_name != nullptr)
6938 free(info->demangled_name);
6940 info->demangled_name =
6941 itaniumDemangle(SymbolName + 1, nullptr, nullptr, &status);
6942 if (info->demangled_name != nullptr) {
6943 *ReferenceName = info->demangled_name;
6944 *ReferenceType = LLVMDisassembler_ReferenceType_DeMangled_Name;
6946 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
6948 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
6949 } else if (*ReferenceType == LLVMDisassembler_ReferenceType_In_PCrel_Load) {
6951 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
6953 method_reference(info, ReferenceType, ReferenceName);
6955 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
6956 // If this is arm64 and the reference is an adrp instruction save the
6957 // instruction, passed in ReferenceValue and the address of the instruction
6958 // for use later if we see and add immediate instruction.
6959 } else if (info->O->getArch() == Triple::aarch64 &&
6960 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADRP) {
6961 info->adrp_inst = ReferenceValue;
6962 info->adrp_addr = ReferencePC;
6963 SymbolName = nullptr;
6964 *ReferenceName = nullptr;
6965 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
6966 // If this is arm64 and reference is an add immediate instruction and we
6968 // seen an adrp instruction just before it and the adrp's Xd register
6970 // this add's Xn register reconstruct the value being referenced and look to
6971 // see if it is a literal pointer. Note the add immediate instruction is
6972 // passed in ReferenceValue.
6973 } else if (info->O->getArch() == Triple::aarch64 &&
6974 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADDXri &&
6975 ReferencePC - 4 == info->adrp_addr &&
6976 (info->adrp_inst & 0x9f000000) == 0x90000000 &&
6977 (info->adrp_inst & 0x1f) == ((ReferenceValue >> 5) & 0x1f)) {
6978 uint32_t addxri_inst;
6979 uint64_t adrp_imm, addxri_imm;
6982 ((info->adrp_inst & 0x00ffffe0) >> 3) | ((info->adrp_inst >> 29) & 0x3);
6983 if (info->adrp_inst & 0x0200000)
6984 adrp_imm |= 0xfffffffffc000000LL;
6986 addxri_inst = ReferenceValue;
6987 addxri_imm = (addxri_inst >> 10) & 0xfff;
6988 if (((addxri_inst >> 22) & 0x3) == 1)
6991 ReferenceValue = (info->adrp_addr & 0xfffffffffffff000LL) +
6992 (adrp_imm << 12) + addxri_imm;
6995 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
6996 if (*ReferenceName == nullptr)
6997 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
6998 // If this is arm64 and the reference is a load register instruction and we
6999 // have seen an adrp instruction just before it and the adrp's Xd register
7000 // matches this add's Xn register reconstruct the value being referenced and
7001 // look to see if it is a literal pointer. Note the load register
7002 // instruction is passed in ReferenceValue.
7003 } else if (info->O->getArch() == Triple::aarch64 &&
7004 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_LDRXui &&
7005 ReferencePC - 4 == info->adrp_addr &&
7006 (info->adrp_inst & 0x9f000000) == 0x90000000 &&
7007 (info->adrp_inst & 0x1f) == ((ReferenceValue >> 5) & 0x1f)) {
7008 uint32_t ldrxui_inst;
7009 uint64_t adrp_imm, ldrxui_imm;
7012 ((info->adrp_inst & 0x00ffffe0) >> 3) | ((info->adrp_inst >> 29) & 0x3);
7013 if (info->adrp_inst & 0x0200000)
7014 adrp_imm |= 0xfffffffffc000000LL;
7016 ldrxui_inst = ReferenceValue;
7017 ldrxui_imm = (ldrxui_inst >> 10) & 0xfff;
7019 ReferenceValue = (info->adrp_addr & 0xfffffffffffff000LL) +
7020 (adrp_imm << 12) + (ldrxui_imm << 3);
7023 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
7024 if (*ReferenceName == nullptr)
7025 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
7027 // If this arm64 and is an load register (PC-relative) instruction the
7028 // ReferenceValue is the PC plus the immediate value.
7029 else if (info->O->getArch() == Triple::aarch64 &&
7030 (*ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_LDRXl ||
7031 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADR)) {
7033 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
7034 if (*ReferenceName == nullptr)
7035 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
7036 } else if (SymbolName != nullptr && strncmp(SymbolName, "__Z", 3) == 0) {
7037 if (info->demangled_name != nullptr)
7038 free(info->demangled_name);
7040 info->demangled_name =
7041 itaniumDemangle(SymbolName + 1, nullptr, nullptr, &status);
7042 if (info->demangled_name != nullptr) {
7043 *ReferenceName = info->demangled_name;
7044 *ReferenceType = LLVMDisassembler_ReferenceType_DeMangled_Name;
7048 *ReferenceName = nullptr;
7049 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
7055 /// Emits the comments that are stored in the CommentStream.
7056 /// Each comment in the CommentStream must end with a newline.
7057 static void emitComments(raw_svector_ostream &CommentStream,
7058 SmallString<128> &CommentsToEmit,
7059 formatted_raw_ostream &FormattedOS,
7060 const MCAsmInfo &MAI) {
7061 // Flush the stream before taking its content.
7062 StringRef Comments = CommentsToEmit.str();
7063 // Get the default information for printing a comment.
7064 StringRef CommentBegin = MAI.getCommentString();
7065 unsigned CommentColumn = MAI.getCommentColumn();
7066 bool IsFirst = true;
7067 while (!Comments.empty()) {
7069 FormattedOS << '\n';
7070 // Emit a line of comments.
7071 FormattedOS.PadToColumn(CommentColumn);
7072 size_t Position = Comments.find('\n');
7073 FormattedOS << CommentBegin << ' ' << Comments.substr(0, Position);
7074 // Move after the newline character.
7075 Comments = Comments.substr(Position + 1);
7078 FormattedOS.flush();
7080 // Tell the comment stream that the vector changed underneath it.
7081 CommentsToEmit.clear();
7084 static void DisassembleMachO(StringRef Filename, MachOObjectFile *MachOOF,
7085 StringRef DisSegName, StringRef DisSectName) {
7086 const char *McpuDefault = nullptr;
7087 const Target *ThumbTarget = nullptr;
7088 const Target *TheTarget = GetTarget(MachOOF, &McpuDefault, &ThumbTarget);
7090 // GetTarget prints out stuff.
7093 std::string MachOMCPU;
7094 if (MCPU.empty() && McpuDefault)
7095 MachOMCPU = McpuDefault;
7099 std::unique_ptr<const MCInstrInfo> InstrInfo(TheTarget->createMCInstrInfo());
7100 std::unique_ptr<const MCInstrInfo> ThumbInstrInfo;
7102 ThumbInstrInfo.reset(ThumbTarget->createMCInstrInfo());
7104 // Package up features to be passed to target/subtarget
7105 std::string FeaturesStr;
7106 if (!MAttrs.empty()) {
7107 SubtargetFeatures Features;
7108 for (unsigned i = 0; i != MAttrs.size(); ++i)
7109 Features.AddFeature(MAttrs[i]);
7110 FeaturesStr = Features.getString();
7113 // Set up disassembler.
7114 std::unique_ptr<const MCRegisterInfo> MRI(
7115 TheTarget->createMCRegInfo(TripleName));
7116 std::unique_ptr<const MCAsmInfo> AsmInfo(
7117 TheTarget->createMCAsmInfo(*MRI, TripleName));
7118 std::unique_ptr<const MCSubtargetInfo> STI(
7119 TheTarget->createMCSubtargetInfo(TripleName, MachOMCPU, FeaturesStr));
7120 MCContext Ctx(AsmInfo.get(), MRI.get(), nullptr);
7121 std::unique_ptr<MCDisassembler> DisAsm(
7122 TheTarget->createMCDisassembler(*STI, Ctx));
7123 std::unique_ptr<MCSymbolizer> Symbolizer;
7124 struct DisassembleInfo SymbolizerInfo(nullptr, nullptr, nullptr, false);
7125 std::unique_ptr<MCRelocationInfo> RelInfo(
7126 TheTarget->createMCRelocationInfo(TripleName, Ctx));
7128 Symbolizer.reset(TheTarget->createMCSymbolizer(
7129 TripleName, SymbolizerGetOpInfo, SymbolizerSymbolLookUp,
7130 &SymbolizerInfo, &Ctx, std::move(RelInfo)));
7131 DisAsm->setSymbolizer(std::move(Symbolizer));
7133 int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
7134 std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
7135 Triple(TripleName), AsmPrinterVariant, *AsmInfo, *InstrInfo, *MRI));
7136 // Set the display preference for hex vs. decimal immediates.
7137 IP->setPrintImmHex(PrintImmHex);
7138 // Comment stream and backing vector.
7139 SmallString<128> CommentsToEmit;
7140 raw_svector_ostream CommentStream(CommentsToEmit);
7141 // FIXME: Setting the CommentStream in the InstPrinter is problematic in that
7142 // if it is done then arm64 comments for string literals don't get printed
7143 // and some constant get printed instead and not setting it causes intel
7144 // (32-bit and 64-bit) comments printed with different spacing before the
7145 // comment causing different diffs with the 'C' disassembler library API.
7146 // IP->setCommentStream(CommentStream);
7148 if (!AsmInfo || !STI || !DisAsm || !IP) {
7149 WithColor::error(errs(), "llvm-objdump")
7150 << "couldn't initialize disassembler for target " << TripleName << '\n';
7154 // Set up separate thumb disassembler if needed.
7155 std::unique_ptr<const MCRegisterInfo> ThumbMRI;
7156 std::unique_ptr<const MCAsmInfo> ThumbAsmInfo;
7157 std::unique_ptr<const MCSubtargetInfo> ThumbSTI;
7158 std::unique_ptr<MCDisassembler> ThumbDisAsm;
7159 std::unique_ptr<MCInstPrinter> ThumbIP;
7160 std::unique_ptr<MCContext> ThumbCtx;
7161 std::unique_ptr<MCSymbolizer> ThumbSymbolizer;
7162 struct DisassembleInfo ThumbSymbolizerInfo(nullptr, nullptr, nullptr, false);
7163 std::unique_ptr<MCRelocationInfo> ThumbRelInfo;
7165 ThumbMRI.reset(ThumbTarget->createMCRegInfo(ThumbTripleName));
7167 ThumbTarget->createMCAsmInfo(*ThumbMRI, ThumbTripleName));
7169 ThumbTarget->createMCSubtargetInfo(ThumbTripleName, MachOMCPU,
7171 ThumbCtx.reset(new MCContext(ThumbAsmInfo.get(), ThumbMRI.get(), nullptr));
7172 ThumbDisAsm.reset(ThumbTarget->createMCDisassembler(*ThumbSTI, *ThumbCtx));
7173 MCContext *PtrThumbCtx = ThumbCtx.get();
7175 ThumbTarget->createMCRelocationInfo(ThumbTripleName, *PtrThumbCtx));
7177 ThumbSymbolizer.reset(ThumbTarget->createMCSymbolizer(
7178 ThumbTripleName, SymbolizerGetOpInfo, SymbolizerSymbolLookUp,
7179 &ThumbSymbolizerInfo, PtrThumbCtx, std::move(ThumbRelInfo)));
7180 ThumbDisAsm->setSymbolizer(std::move(ThumbSymbolizer));
7182 int ThumbAsmPrinterVariant = ThumbAsmInfo->getAssemblerDialect();
7183 ThumbIP.reset(ThumbTarget->createMCInstPrinter(
7184 Triple(ThumbTripleName), ThumbAsmPrinterVariant, *ThumbAsmInfo,
7185 *ThumbInstrInfo, *ThumbMRI));
7186 // Set the display preference for hex vs. decimal immediates.
7187 ThumbIP->setPrintImmHex(PrintImmHex);
7190 if (ThumbTarget && (!ThumbAsmInfo || !ThumbSTI || !ThumbDisAsm || !ThumbIP)) {
7191 WithColor::error(errs(), "llvm-objdump")
7192 << "couldn't initialize disassembler for target " << ThumbTripleName
7197 MachO::mach_header Header = MachOOF->getHeader();
7199 // FIXME: Using the -cfg command line option, this code used to be able to
7200 // annotate relocations with the referenced symbol's name, and if this was
7201 // inside a __[cf]string section, the data it points to. This is now replaced
7202 // by the upcoming MCSymbolizer, which needs the appropriate setup done above.
7203 std::vector<SectionRef> Sections;
7204 std::vector<SymbolRef> Symbols;
7205 SmallVector<uint64_t, 8> FoundFns;
7206 uint64_t BaseSegmentAddress;
7208 getSectionsAndSymbols(MachOOF, Sections, Symbols, FoundFns,
7209 BaseSegmentAddress);
7211 // Sort the symbols by address, just in case they didn't come in that way.
7212 llvm::sort(Symbols, SymbolSorter());
7214 // Build a data in code table that is sorted on by the address of each entry.
7215 uint64_t BaseAddress = 0;
7216 if (Header.filetype == MachO::MH_OBJECT)
7217 BaseAddress = Sections[0].getAddress();
7219 BaseAddress = BaseSegmentAddress;
7221 for (dice_iterator DI = MachOOF->begin_dices(), DE = MachOOF->end_dices();
7224 DI->getOffset(Offset);
7225 Dices.push_back(std::make_pair(BaseAddress + Offset, *DI));
7227 array_pod_sort(Dices.begin(), Dices.end());
7230 raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls();
7232 raw_ostream &DebugOut = nulls();
7235 // Try to find debug info and set up the DIContext for it.
7236 std::unique_ptr<DIContext> diContext;
7237 std::unique_ptr<Binary> DSYMBinary;
7238 std::unique_ptr<MemoryBuffer> DSYMBuf;
7240 ObjectFile *DbgObj = MachOOF;
7242 // A separate DSym file path was specified, parse it as a macho file,
7243 // get the sections and supply it to the section name parsing machinery.
7244 if (!DSYMFile.empty()) {
7245 ErrorOr<std::unique_ptr<MemoryBuffer>> BufOrErr =
7246 MemoryBuffer::getFileOrSTDIN(DSYMFile);
7247 if (std::error_code EC = BufOrErr.getError()) {
7248 report_error(errorCodeToError(EC), DSYMFile);
7252 // We need to keep the file alive, because we're replacing DbgObj with it.
7253 DSYMBuf = std::move(BufOrErr.get());
7255 Expected<std::unique_ptr<Binary>> BinaryOrErr =
7256 createBinary(DSYMBuf.get()->getMemBufferRef());
7258 report_error(BinaryOrErr.takeError(), DSYMFile);
7262 // We need to keep the Binary elive with the buffer
7263 DSYMBinary = std::move(BinaryOrErr.get());
7265 if (ObjectFile *O = dyn_cast<ObjectFile>(DSYMBinary.get())) {
7266 // this is a Mach-O object file, use it
7267 if (MachOObjectFile *MachDSYM = dyn_cast<MachOObjectFile>(&*O)) {
7271 WithColor::error(errs(), "llvm-objdump")
7272 << DSYMFile << " is not a Mach-O file type.\n";
7276 else if (auto UB = dyn_cast<MachOUniversalBinary>(DSYMBinary.get())){
7277 // this is a Universal Binary, find a Mach-O for this architecture
7278 uint32_t CPUType, CPUSubType;
7279 const char *ArchFlag;
7280 if (MachOOF->is64Bit()) {
7281 const MachO::mach_header_64 H_64 = MachOOF->getHeader64();
7282 CPUType = H_64.cputype;
7283 CPUSubType = H_64.cpusubtype;
7285 const MachO::mach_header H = MachOOF->getHeader();
7286 CPUType = H.cputype;
7287 CPUSubType = H.cpusubtype;
7289 Triple T = MachOObjectFile::getArchTriple(CPUType, CPUSubType, nullptr,
7291 Expected<std::unique_ptr<MachOObjectFile>> MachDSYM =
7292 UB->getObjectForArch(ArchFlag);
7294 report_error(MachDSYM.takeError(), DSYMFile);
7298 // We need to keep the Binary elive with the buffer
7299 DbgObj = &*MachDSYM.get();
7300 DSYMBinary = std::move(*MachDSYM);
7303 WithColor::error(errs(), "llvm-objdump")
7304 << DSYMFile << " is not a Mach-O or Universal file type.\n";
7309 // Setup the DIContext
7310 diContext = DWARFContext::create(*DbgObj);
7313 if (FilterSections.empty())
7314 outs() << "(" << DisSegName << "," << DisSectName << ") section\n";
7316 for (unsigned SectIdx = 0; SectIdx != Sections.size(); SectIdx++) {
7318 if (Sections[SectIdx].getName(SectName) || SectName != DisSectName)
7321 DataRefImpl DR = Sections[SectIdx].getRawDataRefImpl();
7323 StringRef SegmentName = MachOOF->getSectionFinalSegmentName(DR);
7324 if (SegmentName != DisSegName)
7327 StringRef BytesStr =
7328 unwrapOrError(Sections[SectIdx].getContents(), Filename);
7329 ArrayRef<uint8_t> Bytes = arrayRefFromStringRef(BytesStr);
7330 uint64_t SectAddress = Sections[SectIdx].getAddress();
7332 bool symbolTableWorked = false;
7334 // Create a map of symbol addresses to symbol names for use by
7335 // the SymbolizerSymbolLookUp() routine.
7336 SymbolAddressMap AddrMap;
7337 bool DisSymNameFound = false;
7338 for (const SymbolRef &Symbol : MachOOF->symbols()) {
7339 SymbolRef::Type ST =
7340 unwrapOrError(Symbol.getType(), MachOOF->getFileName());
7341 if (ST == SymbolRef::ST_Function || ST == SymbolRef::ST_Data ||
7342 ST == SymbolRef::ST_Other) {
7343 uint64_t Address = Symbol.getValue();
7345 unwrapOrError(Symbol.getName(), MachOOF->getFileName());
7346 AddrMap[Address] = SymName;
7347 if (!DisSymName.empty() && DisSymName == SymName)
7348 DisSymNameFound = true;
7351 if (!DisSymName.empty() && !DisSymNameFound) {
7352 outs() << "Can't find -dis-symname: " << DisSymName << "\n";
7355 // Set up the block of info used by the Symbolizer call backs.
7356 SymbolizerInfo.verbose = !NoSymbolicOperands;
7357 SymbolizerInfo.O = MachOOF;
7358 SymbolizerInfo.S = Sections[SectIdx];
7359 SymbolizerInfo.AddrMap = &AddrMap;
7360 SymbolizerInfo.Sections = &Sections;
7361 // Same for the ThumbSymbolizer
7362 ThumbSymbolizerInfo.verbose = !NoSymbolicOperands;
7363 ThumbSymbolizerInfo.O = MachOOF;
7364 ThumbSymbolizerInfo.S = Sections[SectIdx];
7365 ThumbSymbolizerInfo.AddrMap = &AddrMap;
7366 ThumbSymbolizerInfo.Sections = &Sections;
7368 unsigned int Arch = MachOOF->getArch();
7370 // Skip all symbols if this is a stubs file.
7374 // If the section has symbols but no symbol at the start of the section
7375 // these are used to make sure the bytes before the first symbol are
7377 bool FirstSymbol = true;
7378 bool FirstSymbolAtSectionStart = true;
7380 // Disassemble symbol by symbol.
7381 for (unsigned SymIdx = 0; SymIdx != Symbols.size(); SymIdx++) {
7383 unwrapOrError(Symbols[SymIdx].getName(), MachOOF->getFileName());
7384 SymbolRef::Type ST =
7385 unwrapOrError(Symbols[SymIdx].getType(), MachOOF->getFileName());
7386 if (ST != SymbolRef::ST_Function && ST != SymbolRef::ST_Data)
7389 // Make sure the symbol is defined in this section.
7390 bool containsSym = Sections[SectIdx].containsSymbol(Symbols[SymIdx]);
7392 if (!DisSymName.empty() && DisSymName == SymName) {
7393 outs() << "-dis-symname: " << DisSymName << " not in the section\n";
7398 // The __mh_execute_header is special and we need to deal with that fact
7399 // this symbol is before the start of the (__TEXT,__text) section and at the
7400 // address of the start of the __TEXT segment. This is because this symbol
7401 // is an N_SECT symbol in the (__TEXT,__text) but its address is before the
7402 // start of the section in a standard MH_EXECUTE filetype.
7403 if (!DisSymName.empty() && DisSymName == "__mh_execute_header") {
7404 outs() << "-dis-symname: __mh_execute_header not in any section\n";
7407 // When this code is trying to disassemble a symbol at a time and in the
7408 // case there is only the __mh_execute_header symbol left as in a stripped
7409 // executable, we need to deal with this by ignoring this symbol so the
7410 // whole section is disassembled and this symbol is then not displayed.
7411 if (SymName == "__mh_execute_header" || SymName == "__mh_dylib_header" ||
7412 SymName == "__mh_bundle_header" || SymName == "__mh_object_header" ||
7413 SymName == "__mh_preload_header" || SymName == "__mh_dylinker_header")
7416 // If we are only disassembling one symbol see if this is that symbol.
7417 if (!DisSymName.empty() && DisSymName != SymName)
7420 // Start at the address of the symbol relative to the section's address.
7421 uint64_t SectSize = Sections[SectIdx].getSize();
7422 uint64_t Start = Symbols[SymIdx].getValue();
7423 uint64_t SectionAddress = Sections[SectIdx].getAddress();
7424 Start -= SectionAddress;
7426 if (Start > SectSize) {
7427 outs() << "section data ends, " << SymName
7428 << " lies outside valid range\n";
7432 // Stop disassembling either at the beginning of the next symbol or at
7433 // the end of the section.
7434 bool containsNextSym = false;
7435 uint64_t NextSym = 0;
7436 uint64_t NextSymIdx = SymIdx + 1;
7437 while (Symbols.size() > NextSymIdx) {
7438 SymbolRef::Type NextSymType = unwrapOrError(
7439 Symbols[NextSymIdx].getType(), MachOOF->getFileName());
7440 if (NextSymType == SymbolRef::ST_Function) {
7442 Sections[SectIdx].containsSymbol(Symbols[NextSymIdx]);
7443 NextSym = Symbols[NextSymIdx].getValue();
7444 NextSym -= SectionAddress;
7450 uint64_t End = containsNextSym ? std::min(NextSym, SectSize) : SectSize;
7453 symbolTableWorked = true;
7455 DataRefImpl Symb = Symbols[SymIdx].getRawDataRefImpl();
7456 bool IsThumb = MachOOF->getSymbolFlags(Symb) & SymbolRef::SF_Thumb;
7458 // We only need the dedicated Thumb target if there's a real choice
7459 // (i.e. we're not targeting M-class) and the function is Thumb.
7460 bool UseThumbTarget = IsThumb && ThumbTarget;
7462 // If we are not specifying a symbol to start disassembly with and this
7463 // is the first symbol in the section but not at the start of the section
7464 // then move the disassembly index to the start of the section and
7465 // don't print the symbol name just yet. This is so the bytes before the
7466 // first symbol are disassembled.
7467 uint64_t SymbolStart = Start;
7468 if (DisSymName.empty() && FirstSymbol && Start != 0) {
7469 FirstSymbolAtSectionStart = false;
7473 outs() << SymName << ":\n";
7475 DILineInfo lastLine;
7476 for (uint64_t Index = Start; Index < End; Index += Size) {
7479 // If this is the first symbol in the section and it was not at the
7480 // start of the section, see if we are at its Index now and if so print
7482 if (FirstSymbol && !FirstSymbolAtSectionStart && Index == SymbolStart)
7483 outs() << SymName << ":\n";
7485 uint64_t PC = SectAddress + Index;
7486 if (!NoLeadingAddr) {
7487 if (FullLeadingAddr) {
7488 if (MachOOF->is64Bit())
7489 outs() << format("%016" PRIx64, PC);
7491 outs() << format("%08" PRIx64, PC);
7493 outs() << format("%8" PRIx64 ":", PC);
7496 if (!NoShowRawInsn || Arch == Triple::arm)
7499 // Check the data in code table here to see if this is data not an
7500 // instruction to be disassembled.
7502 Dice.push_back(std::make_pair(PC, DiceRef()));
7503 dice_table_iterator DTI =
7504 std::search(Dices.begin(), Dices.end(), Dice.begin(), Dice.end(),
7505 compareDiceTableEntries);
7506 if (DTI != Dices.end()) {
7508 DTI->second.getLength(Length);
7510 DTI->second.getKind(Kind);
7511 Size = DumpDataInCode(Bytes.data() + Index, Length, Kind);
7512 if ((Kind == MachO::DICE_KIND_JUMP_TABLE8) &&
7513 (PC == (DTI->first + Length - 1)) && (Length & 1))
7518 SmallVector<char, 64> AnnotationsBytes;
7519 raw_svector_ostream Annotations(AnnotationsBytes);
7523 gotInst = ThumbDisAsm->getInstruction(Inst, Size, Bytes.slice(Index),
7524 PC, DebugOut, Annotations);
7526 gotInst = DisAsm->getInstruction(Inst, Size, Bytes.slice(Index), PC,
7527 DebugOut, Annotations);
7529 if (!NoShowRawInsn || Arch == Triple::arm) {
7530 dumpBytes(makeArrayRef(Bytes.data() + Index, Size), outs());
7532 formatted_raw_ostream FormattedOS(outs());
7533 StringRef AnnotationsStr = Annotations.str();
7535 ThumbIP->printInst(&Inst, FormattedOS, AnnotationsStr, *ThumbSTI);
7537 IP->printInst(&Inst, FormattedOS, AnnotationsStr, *STI);
7538 emitComments(CommentStream, CommentsToEmit, FormattedOS, *AsmInfo);
7540 // Print debug info.
7542 DILineInfo dli = diContext->getLineInfoForAddress({PC, SectIdx});
7543 // Print valid line info if it changed.
7544 if (dli != lastLine && dli.Line != 0)
7545 outs() << "\t## " << dli.FileName << ':' << dli.Line << ':'
7551 unsigned int Arch = MachOOF->getArch();
7552 if (Arch == Triple::x86_64 || Arch == Triple::x86) {
7553 outs() << format("\t.byte 0x%02x #bad opcode\n",
7554 *(Bytes.data() + Index) & 0xff);
7555 Size = 1; // skip exactly one illegible byte and move on.
7556 } else if (Arch == Triple::aarch64 ||
7557 (Arch == Triple::arm && !IsThumb)) {
7558 uint32_t opcode = (*(Bytes.data() + Index) & 0xff) |
7559 (*(Bytes.data() + Index + 1) & 0xff) << 8 |
7560 (*(Bytes.data() + Index + 2) & 0xff) << 16 |
7561 (*(Bytes.data() + Index + 3) & 0xff) << 24;
7562 outs() << format("\t.long\t0x%08x\n", opcode);
7564 } else if (Arch == Triple::arm) {
7565 assert(IsThumb && "ARM mode should have been dealt with above");
7566 uint32_t opcode = (*(Bytes.data() + Index) & 0xff) |
7567 (*(Bytes.data() + Index + 1) & 0xff) << 8;
7568 outs() << format("\t.short\t0x%04x\n", opcode);
7571 WithColor::warning(errs(), "llvm-objdump")
7572 << "invalid instruction encoding\n";
7574 Size = 1; // skip illegible bytes
7578 // Now that we are done disassembled the first symbol set the bool that
7579 // were doing this to false.
7580 FirstSymbol = false;
7582 if (!symbolTableWorked) {
7583 // Reading the symbol table didn't work, disassemble the whole section.
7584 uint64_t SectAddress = Sections[SectIdx].getAddress();
7585 uint64_t SectSize = Sections[SectIdx].getSize();
7587 for (uint64_t Index = 0; Index < SectSize; Index += InstSize) {
7590 uint64_t PC = SectAddress + Index;
7591 SmallVector<char, 64> AnnotationsBytes;
7592 raw_svector_ostream Annotations(AnnotationsBytes);
7593 if (DisAsm->getInstruction(Inst, InstSize, Bytes.slice(Index), PC,
7594 DebugOut, Annotations)) {
7595 if (!NoLeadingAddr) {
7596 if (FullLeadingAddr) {
7597 if (MachOOF->is64Bit())
7598 outs() << format("%016" PRIx64, PC);
7600 outs() << format("%08" PRIx64, PC);
7602 outs() << format("%8" PRIx64 ":", PC);
7605 if (!NoShowRawInsn || Arch == Triple::arm) {
7607 dumpBytes(makeArrayRef(Bytes.data() + Index, InstSize), outs());
7609 StringRef AnnotationsStr = Annotations.str();
7610 IP->printInst(&Inst, outs(), AnnotationsStr, *STI);
7613 unsigned int Arch = MachOOF->getArch();
7614 if (Arch == Triple::x86_64 || Arch == Triple::x86) {
7615 outs() << format("\t.byte 0x%02x #bad opcode\n",
7616 *(Bytes.data() + Index) & 0xff);
7617 InstSize = 1; // skip exactly one illegible byte and move on.
7619 WithColor::warning(errs(), "llvm-objdump")
7620 << "invalid instruction encoding\n";
7622 InstSize = 1; // skip illegible bytes
7627 // The TripleName's need to be reset if we are called again for a different
7630 ThumbTripleName = "";
7632 if (SymbolizerInfo.demangled_name != nullptr)
7633 free(SymbolizerInfo.demangled_name);
7634 if (ThumbSymbolizerInfo.demangled_name != nullptr)
7635 free(ThumbSymbolizerInfo.demangled_name);
7639 //===----------------------------------------------------------------------===//
7640 // __compact_unwind section dumping
7641 //===----------------------------------------------------------------------===//
7645 template <typename T>
7646 static uint64_t read(StringRef Contents, ptrdiff_t Offset) {
7647 using llvm::support::little;
7648 using llvm::support::unaligned;
7650 if (Offset + sizeof(T) > Contents.size()) {
7651 outs() << "warning: attempt to read past end of buffer\n";
7656 support::endian::read<T, little, unaligned>(Contents.data() + Offset);
7660 template <typename T>
7661 static uint64_t readNext(StringRef Contents, ptrdiff_t &Offset) {
7662 T Val = read<T>(Contents, Offset);
7663 Offset += sizeof(T);
7667 struct CompactUnwindEntry {
7668 uint32_t OffsetInSection;
7670 uint64_t FunctionAddr;
7672 uint32_t CompactEncoding;
7673 uint64_t PersonalityAddr;
7676 RelocationRef FunctionReloc;
7677 RelocationRef PersonalityReloc;
7678 RelocationRef LSDAReloc;
7680 CompactUnwindEntry(StringRef Contents, unsigned Offset, bool Is64)
7681 : OffsetInSection(Offset) {
7683 read<uint64_t>(Contents, Offset);
7685 read<uint32_t>(Contents, Offset);
7689 template <typename UIntPtr> void read(StringRef Contents, ptrdiff_t Offset) {
7690 FunctionAddr = readNext<UIntPtr>(Contents, Offset);
7691 Length = readNext<uint32_t>(Contents, Offset);
7692 CompactEncoding = readNext<uint32_t>(Contents, Offset);
7693 PersonalityAddr = readNext<UIntPtr>(Contents, Offset);
7694 LSDAAddr = readNext<UIntPtr>(Contents, Offset);
7699 /// Given a relocation from __compact_unwind, consisting of the RelocationRef
7700 /// and data being relocated, determine the best base Name and Addend to use for
7701 /// display purposes.
7703 /// 1. An Extern relocation will directly reference a symbol (and the data is
7704 /// then already an addend), so use that.
7705 /// 2. Otherwise the data is an offset in the object file's layout; try to find
7706 // a symbol before it in the same section, and use the offset from there.
7707 /// 3. Finally, if all that fails, fall back to an offset from the start of the
7708 /// referenced section.
7709 static void findUnwindRelocNameAddend(const MachOObjectFile *Obj,
7710 std::map<uint64_t, SymbolRef> &Symbols,
7711 const RelocationRef &Reloc, uint64_t Addr,
7712 StringRef &Name, uint64_t &Addend) {
7713 if (Reloc.getSymbol() != Obj->symbol_end()) {
7714 Name = unwrapOrError(Reloc.getSymbol()->getName(), Obj->getFileName());
7719 auto RE = Obj->getRelocation(Reloc.getRawDataRefImpl());
7720 SectionRef RelocSection = Obj->getAnyRelocationSection(RE);
7722 uint64_t SectionAddr = RelocSection.getAddress();
7724 auto Sym = Symbols.upper_bound(Addr);
7725 if (Sym == Symbols.begin()) {
7726 // The first symbol in the object is after this reference, the best we can
7727 // do is section-relative notation.
7728 RelocSection.getName(Name);
7729 Addend = Addr - SectionAddr;
7733 // Go back one so that SymbolAddress <= Addr.
7736 section_iterator SymSection =
7737 unwrapOrError(Sym->second.getSection(), Obj->getFileName());
7738 if (RelocSection == *SymSection) {
7739 // There's a valid symbol in the same section before this reference.
7740 Name = unwrapOrError(Sym->second.getName(), Obj->getFileName());
7741 Addend = Addr - Sym->first;
7745 // There is a symbol before this reference, but it's in a different
7746 // section. Probably not helpful to mention it, so use the section name.
7747 RelocSection.getName(Name);
7748 Addend = Addr - SectionAddr;
7751 static void printUnwindRelocDest(const MachOObjectFile *Obj,
7752 std::map<uint64_t, SymbolRef> &Symbols,
7753 const RelocationRef &Reloc, uint64_t Addr) {
7757 if (!Reloc.getObject())
7760 findUnwindRelocNameAddend(Obj, Symbols, Reloc, Addr, Name, Addend);
7764 outs() << " + " << format("0x%" PRIx64, Addend);
7768 printMachOCompactUnwindSection(const MachOObjectFile *Obj,
7769 std::map<uint64_t, SymbolRef> &Symbols,
7770 const SectionRef &CompactUnwind) {
7772 if (!Obj->isLittleEndian()) {
7773 outs() << "Skipping big-endian __compact_unwind section\n";
7777 bool Is64 = Obj->is64Bit();
7778 uint32_t PointerSize = Is64 ? sizeof(uint64_t) : sizeof(uint32_t);
7779 uint32_t EntrySize = 3 * PointerSize + 2 * sizeof(uint32_t);
7781 StringRef Contents =
7782 unwrapOrError(CompactUnwind.getContents(), Obj->getFileName());
7783 SmallVector<CompactUnwindEntry, 4> CompactUnwinds;
7785 // First populate the initial raw offsets, encodings and so on from the entry.
7786 for (unsigned Offset = 0; Offset < Contents.size(); Offset += EntrySize) {
7787 CompactUnwindEntry Entry(Contents, Offset, Is64);
7788 CompactUnwinds.push_back(Entry);
7791 // Next we need to look at the relocations to find out what objects are
7792 // actually being referred to.
7793 for (const RelocationRef &Reloc : CompactUnwind.relocations()) {
7794 uint64_t RelocAddress = Reloc.getOffset();
7796 uint32_t EntryIdx = RelocAddress / EntrySize;
7797 uint32_t OffsetInEntry = RelocAddress - EntryIdx * EntrySize;
7798 CompactUnwindEntry &Entry = CompactUnwinds[EntryIdx];
7800 if (OffsetInEntry == 0)
7801 Entry.FunctionReloc = Reloc;
7802 else if (OffsetInEntry == PointerSize + 2 * sizeof(uint32_t))
7803 Entry.PersonalityReloc = Reloc;
7804 else if (OffsetInEntry == 2 * PointerSize + 2 * sizeof(uint32_t))
7805 Entry.LSDAReloc = Reloc;
7807 outs() << "Invalid relocation in __compact_unwind section\n";
7812 // Finally, we're ready to print the data we've gathered.
7813 outs() << "Contents of __compact_unwind section:\n";
7814 for (auto &Entry : CompactUnwinds) {
7815 outs() << " Entry at offset "
7816 << format("0x%" PRIx32, Entry.OffsetInSection) << ":\n";
7818 // 1. Start of the region this entry applies to.
7819 outs() << " start: " << format("0x%" PRIx64,
7820 Entry.FunctionAddr) << ' ';
7821 printUnwindRelocDest(Obj, Symbols, Entry.FunctionReloc, Entry.FunctionAddr);
7824 // 2. Length of the region this entry applies to.
7825 outs() << " length: " << format("0x%" PRIx32, Entry.Length)
7827 // 3. The 32-bit compact encoding.
7828 outs() << " compact encoding: "
7829 << format("0x%08" PRIx32, Entry.CompactEncoding) << '\n';
7831 // 4. The personality function, if present.
7832 if (Entry.PersonalityReloc.getObject()) {
7833 outs() << " personality function: "
7834 << format("0x%" PRIx64, Entry.PersonalityAddr) << ' ';
7835 printUnwindRelocDest(Obj, Symbols, Entry.PersonalityReloc,
7836 Entry.PersonalityAddr);
7840 // 5. This entry's language-specific data area.
7841 if (Entry.LSDAReloc.getObject()) {
7842 outs() << " LSDA: " << format("0x%" PRIx64,
7843 Entry.LSDAAddr) << ' ';
7844 printUnwindRelocDest(Obj, Symbols, Entry.LSDAReloc, Entry.LSDAAddr);
7850 //===----------------------------------------------------------------------===//
7851 // __unwind_info section dumping
7852 //===----------------------------------------------------------------------===//
7854 static void printRegularSecondLevelUnwindPage(StringRef PageData) {
7856 uint32_t Kind = readNext<uint32_t>(PageData, Pos);
7858 assert(Kind == 2 && "kind for a regular 2nd level index should be 2");
7860 uint16_t EntriesStart = readNext<uint16_t>(PageData, Pos);
7861 uint16_t NumEntries = readNext<uint16_t>(PageData, Pos);
7864 for (unsigned i = 0; i < NumEntries; ++i) {
7865 uint32_t FunctionOffset = readNext<uint32_t>(PageData, Pos);
7866 uint32_t Encoding = readNext<uint32_t>(PageData, Pos);
7868 outs() << " [" << i << "]: "
7869 << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
7871 << "encoding=" << format("0x%08" PRIx32, Encoding) << '\n';
7875 static void printCompressedSecondLevelUnwindPage(
7876 StringRef PageData, uint32_t FunctionBase,
7877 const SmallVectorImpl<uint32_t> &CommonEncodings) {
7879 uint32_t Kind = readNext<uint32_t>(PageData, Pos);
7881 assert(Kind == 3 && "kind for a compressed 2nd level index should be 3");
7883 uint16_t EntriesStart = readNext<uint16_t>(PageData, Pos);
7884 uint16_t NumEntries = readNext<uint16_t>(PageData, Pos);
7886 uint16_t EncodingsStart = readNext<uint16_t>(PageData, Pos);
7887 readNext<uint16_t>(PageData, Pos);
7888 StringRef PageEncodings = PageData.substr(EncodingsStart, StringRef::npos);
7891 for (unsigned i = 0; i < NumEntries; ++i) {
7892 uint32_t Entry = readNext<uint32_t>(PageData, Pos);
7893 uint32_t FunctionOffset = FunctionBase + (Entry & 0xffffff);
7894 uint32_t EncodingIdx = Entry >> 24;
7897 if (EncodingIdx < CommonEncodings.size())
7898 Encoding = CommonEncodings[EncodingIdx];
7900 Encoding = read<uint32_t>(PageEncodings,
7902 (EncodingIdx - CommonEncodings.size()));
7904 outs() << " [" << i << "]: "
7905 << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
7907 << "encoding[" << EncodingIdx
7908 << "]=" << format("0x%08" PRIx32, Encoding) << '\n';
7912 static void printMachOUnwindInfoSection(const MachOObjectFile *Obj,
7913 std::map<uint64_t, SymbolRef> &Symbols,
7914 const SectionRef &UnwindInfo) {
7916 if (!Obj->isLittleEndian()) {
7917 outs() << "Skipping big-endian __unwind_info section\n";
7921 outs() << "Contents of __unwind_info section:\n";
7923 StringRef Contents =
7924 unwrapOrError(UnwindInfo.getContents(), Obj->getFileName());
7927 //===----------------------------------
7929 //===----------------------------------
7931 uint32_t Version = readNext<uint32_t>(Contents, Pos);
7932 outs() << " Version: "
7933 << format("0x%" PRIx32, Version) << '\n';
7935 outs() << " Skipping section with unknown version\n";
7939 uint32_t CommonEncodingsStart = readNext<uint32_t>(Contents, Pos);
7940 outs() << " Common encodings array section offset: "
7941 << format("0x%" PRIx32, CommonEncodingsStart) << '\n';
7942 uint32_t NumCommonEncodings = readNext<uint32_t>(Contents, Pos);
7943 outs() << " Number of common encodings in array: "
7944 << format("0x%" PRIx32, NumCommonEncodings) << '\n';
7946 uint32_t PersonalitiesStart = readNext<uint32_t>(Contents, Pos);
7947 outs() << " Personality function array section offset: "
7948 << format("0x%" PRIx32, PersonalitiesStart) << '\n';
7949 uint32_t NumPersonalities = readNext<uint32_t>(Contents, Pos);
7950 outs() << " Number of personality functions in array: "
7951 << format("0x%" PRIx32, NumPersonalities) << '\n';
7953 uint32_t IndicesStart = readNext<uint32_t>(Contents, Pos);
7954 outs() << " Index array section offset: "
7955 << format("0x%" PRIx32, IndicesStart) << '\n';
7956 uint32_t NumIndices = readNext<uint32_t>(Contents, Pos);
7957 outs() << " Number of indices in array: "
7958 << format("0x%" PRIx32, NumIndices) << '\n';
7960 //===----------------------------------
7961 // A shared list of common encodings
7962 //===----------------------------------
7964 // These occupy indices in the range [0, N] whenever an encoding is referenced
7965 // from a compressed 2nd level index table. In practice the linker only
7966 // creates ~128 of these, so that indices are available to embed encodings in
7967 // the 2nd level index.
7969 SmallVector<uint32_t, 64> CommonEncodings;
7970 outs() << " Common encodings: (count = " << NumCommonEncodings << ")\n";
7971 Pos = CommonEncodingsStart;
7972 for (unsigned i = 0; i < NumCommonEncodings; ++i) {
7973 uint32_t Encoding = readNext<uint32_t>(Contents, Pos);
7974 CommonEncodings.push_back(Encoding);
7976 outs() << " encoding[" << i << "]: " << format("0x%08" PRIx32, Encoding)
7980 //===----------------------------------
7981 // Personality functions used in this executable
7982 //===----------------------------------
7984 // There should be only a handful of these (one per source language,
7985 // roughly). Particularly since they only get 2 bits in the compact encoding.
7987 outs() << " Personality functions: (count = " << NumPersonalities << ")\n";
7988 Pos = PersonalitiesStart;
7989 for (unsigned i = 0; i < NumPersonalities; ++i) {
7990 uint32_t PersonalityFn = readNext<uint32_t>(Contents, Pos);
7991 outs() << " personality[" << i + 1
7992 << "]: " << format("0x%08" PRIx32, PersonalityFn) << '\n';
7995 //===----------------------------------
7996 // The level 1 index entries
7997 //===----------------------------------
7999 // These specify an approximate place to start searching for the more detailed
8000 // information, sorted by PC.
8003 uint32_t FunctionOffset;
8004 uint32_t SecondLevelPageStart;
8008 SmallVector<IndexEntry, 4> IndexEntries;
8010 outs() << " Top level indices: (count = " << NumIndices << ")\n";
8012 for (unsigned i = 0; i < NumIndices; ++i) {
8015 Entry.FunctionOffset = readNext<uint32_t>(Contents, Pos);
8016 Entry.SecondLevelPageStart = readNext<uint32_t>(Contents, Pos);
8017 Entry.LSDAStart = readNext<uint32_t>(Contents, Pos);
8018 IndexEntries.push_back(Entry);
8020 outs() << " [" << i << "]: "
8021 << "function offset=" << format("0x%08" PRIx32, Entry.FunctionOffset)
8023 << "2nd level page offset="
8024 << format("0x%08" PRIx32, Entry.SecondLevelPageStart) << ", "
8025 << "LSDA offset=" << format("0x%08" PRIx32, Entry.LSDAStart) << '\n';
8028 //===----------------------------------
8029 // Next come the LSDA tables
8030 //===----------------------------------
8032 // The LSDA layout is rather implicit: it's a contiguous array of entries from
8033 // the first top-level index's LSDAOffset to the last (sentinel).
8035 outs() << " LSDA descriptors:\n";
8036 Pos = IndexEntries[0].LSDAStart;
8037 const uint32_t LSDASize = 2 * sizeof(uint32_t);
8039 (IndexEntries.back().LSDAStart - IndexEntries[0].LSDAStart) / LSDASize;
8041 for (int i = 0; i < NumLSDAs; ++i) {
8042 uint32_t FunctionOffset = readNext<uint32_t>(Contents, Pos);
8043 uint32_t LSDAOffset = readNext<uint32_t>(Contents, Pos);
8044 outs() << " [" << i << "]: "
8045 << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
8047 << "LSDA offset=" << format("0x%08" PRIx32, LSDAOffset) << '\n';
8050 //===----------------------------------
8051 // Finally, the 2nd level indices
8052 //===----------------------------------
8054 // Generally these are 4K in size, and have 2 possible forms:
8055 // + Regular stores up to 511 entries with disparate encodings
8056 // + Compressed stores up to 1021 entries if few enough compact encoding
8058 outs() << " Second level indices:\n";
8059 for (unsigned i = 0; i < IndexEntries.size() - 1; ++i) {
8060 // The final sentinel top-level index has no associated 2nd level page
8061 if (IndexEntries[i].SecondLevelPageStart == 0)
8064 outs() << " Second level index[" << i << "]: "
8065 << "offset in section="
8066 << format("0x%08" PRIx32, IndexEntries[i].SecondLevelPageStart)
8068 << "base function offset="
8069 << format("0x%08" PRIx32, IndexEntries[i].FunctionOffset) << '\n';
8071 Pos = IndexEntries[i].SecondLevelPageStart;
8072 if (Pos + sizeof(uint32_t) > Contents.size()) {
8073 outs() << "warning: invalid offset for second level page: " << Pos << '\n';
8078 *reinterpret_cast<const support::ulittle32_t *>(Contents.data() + Pos);
8080 printRegularSecondLevelUnwindPage(Contents.substr(Pos, 4096));
8082 printCompressedSecondLevelUnwindPage(Contents.substr(Pos, 4096),
8083 IndexEntries[i].FunctionOffset,
8086 outs() << " Skipping 2nd level page with unknown kind " << Kind
8091 void printMachOUnwindInfo(const MachOObjectFile *Obj) {
8092 std::map<uint64_t, SymbolRef> Symbols;
8093 for (const SymbolRef &SymRef : Obj->symbols()) {
8094 // Discard any undefined or absolute symbols. They're not going to take part
8095 // in the convenience lookup for unwind info and just take up resources.
8096 auto SectOrErr = SymRef.getSection();
8098 // TODO: Actually report errors helpfully.
8099 consumeError(SectOrErr.takeError());
8102 section_iterator Section = *SectOrErr;
8103 if (Section == Obj->section_end())
8106 uint64_t Addr = SymRef.getValue();
8107 Symbols.insert(std::make_pair(Addr, SymRef));
8110 for (const SectionRef &Section : Obj->sections()) {
8112 Section.getName(SectName);
8113 if (SectName == "__compact_unwind")
8114 printMachOCompactUnwindSection(Obj, Symbols, Section);
8115 else if (SectName == "__unwind_info")
8116 printMachOUnwindInfoSection(Obj, Symbols, Section);
8120 static void PrintMachHeader(uint32_t magic, uint32_t cputype,
8121 uint32_t cpusubtype, uint32_t filetype,
8122 uint32_t ncmds, uint32_t sizeofcmds, uint32_t flags,
8124 outs() << "Mach header\n";
8125 outs() << " magic cputype cpusubtype caps filetype ncmds "
8126 "sizeofcmds flags\n";
8128 if (magic == MachO::MH_MAGIC)
8129 outs() << " MH_MAGIC";
8130 else if (magic == MachO::MH_MAGIC_64)
8131 outs() << "MH_MAGIC_64";
8133 outs() << format(" 0x%08" PRIx32, magic);
8135 case MachO::CPU_TYPE_I386:
8137 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
8138 case MachO::CPU_SUBTYPE_I386_ALL:
8142 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
8146 case MachO::CPU_TYPE_X86_64:
8147 outs() << " X86_64";
8148 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
8149 case MachO::CPU_SUBTYPE_X86_64_ALL:
8152 case MachO::CPU_SUBTYPE_X86_64_H:
8153 outs() << " Haswell";
8156 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
8160 case MachO::CPU_TYPE_ARM:
8162 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
8163 case MachO::CPU_SUBTYPE_ARM_ALL:
8166 case MachO::CPU_SUBTYPE_ARM_V4T:
8169 case MachO::CPU_SUBTYPE_ARM_V5TEJ:
8172 case MachO::CPU_SUBTYPE_ARM_XSCALE:
8173 outs() << " XSCALE";
8175 case MachO::CPU_SUBTYPE_ARM_V6:
8178 case MachO::CPU_SUBTYPE_ARM_V6M:
8181 case MachO::CPU_SUBTYPE_ARM_V7:
8184 case MachO::CPU_SUBTYPE_ARM_V7EM:
8187 case MachO::CPU_SUBTYPE_ARM_V7K:
8190 case MachO::CPU_SUBTYPE_ARM_V7M:
8193 case MachO::CPU_SUBTYPE_ARM_V7S:
8197 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
8201 case MachO::CPU_TYPE_ARM64:
8203 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
8204 case MachO::CPU_SUBTYPE_ARM64_ALL:
8207 case MachO::CPU_SUBTYPE_ARM64E:
8211 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
8215 case MachO::CPU_TYPE_ARM64_32:
8216 outs() << " ARM64_32";
8217 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
8218 case MachO::CPU_SUBTYPE_ARM64_32_V8:
8222 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
8226 case MachO::CPU_TYPE_POWERPC:
8228 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
8229 case MachO::CPU_SUBTYPE_POWERPC_ALL:
8233 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
8237 case MachO::CPU_TYPE_POWERPC64:
8239 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
8240 case MachO::CPU_SUBTYPE_POWERPC_ALL:
8244 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
8249 outs() << format(" %7d", cputype);
8250 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
8253 if ((cpusubtype & MachO::CPU_SUBTYPE_MASK) == MachO::CPU_SUBTYPE_LIB64) {
8256 outs() << format(" 0x%02" PRIx32,
8257 (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24);
8260 case MachO::MH_OBJECT:
8261 outs() << " OBJECT";
8263 case MachO::MH_EXECUTE:
8264 outs() << " EXECUTE";
8266 case MachO::MH_FVMLIB:
8267 outs() << " FVMLIB";
8269 case MachO::MH_CORE:
8272 case MachO::MH_PRELOAD:
8273 outs() << " PRELOAD";
8275 case MachO::MH_DYLIB:
8278 case MachO::MH_DYLIB_STUB:
8279 outs() << " DYLIB_STUB";
8281 case MachO::MH_DYLINKER:
8282 outs() << " DYLINKER";
8284 case MachO::MH_BUNDLE:
8285 outs() << " BUNDLE";
8287 case MachO::MH_DSYM:
8290 case MachO::MH_KEXT_BUNDLE:
8291 outs() << " KEXTBUNDLE";
8294 outs() << format(" %10u", filetype);
8297 outs() << format(" %5u", ncmds);
8298 outs() << format(" %10u", sizeofcmds);
8300 if (f & MachO::MH_NOUNDEFS) {
8301 outs() << " NOUNDEFS";
8302 f &= ~MachO::MH_NOUNDEFS;
8304 if (f & MachO::MH_INCRLINK) {
8305 outs() << " INCRLINK";
8306 f &= ~MachO::MH_INCRLINK;
8308 if (f & MachO::MH_DYLDLINK) {
8309 outs() << " DYLDLINK";
8310 f &= ~MachO::MH_DYLDLINK;
8312 if (f & MachO::MH_BINDATLOAD) {
8313 outs() << " BINDATLOAD";
8314 f &= ~MachO::MH_BINDATLOAD;
8316 if (f & MachO::MH_PREBOUND) {
8317 outs() << " PREBOUND";
8318 f &= ~MachO::MH_PREBOUND;
8320 if (f & MachO::MH_SPLIT_SEGS) {
8321 outs() << " SPLIT_SEGS";
8322 f &= ~MachO::MH_SPLIT_SEGS;
8324 if (f & MachO::MH_LAZY_INIT) {
8325 outs() << " LAZY_INIT";
8326 f &= ~MachO::MH_LAZY_INIT;
8328 if (f & MachO::MH_TWOLEVEL) {
8329 outs() << " TWOLEVEL";
8330 f &= ~MachO::MH_TWOLEVEL;
8332 if (f & MachO::MH_FORCE_FLAT) {
8333 outs() << " FORCE_FLAT";
8334 f &= ~MachO::MH_FORCE_FLAT;
8336 if (f & MachO::MH_NOMULTIDEFS) {
8337 outs() << " NOMULTIDEFS";
8338 f &= ~MachO::MH_NOMULTIDEFS;
8340 if (f & MachO::MH_NOFIXPREBINDING) {
8341 outs() << " NOFIXPREBINDING";
8342 f &= ~MachO::MH_NOFIXPREBINDING;
8344 if (f & MachO::MH_PREBINDABLE) {
8345 outs() << " PREBINDABLE";
8346 f &= ~MachO::MH_PREBINDABLE;
8348 if (f & MachO::MH_ALLMODSBOUND) {
8349 outs() << " ALLMODSBOUND";
8350 f &= ~MachO::MH_ALLMODSBOUND;
8352 if (f & MachO::MH_SUBSECTIONS_VIA_SYMBOLS) {
8353 outs() << " SUBSECTIONS_VIA_SYMBOLS";
8354 f &= ~MachO::MH_SUBSECTIONS_VIA_SYMBOLS;
8356 if (f & MachO::MH_CANONICAL) {
8357 outs() << " CANONICAL";
8358 f &= ~MachO::MH_CANONICAL;
8360 if (f & MachO::MH_WEAK_DEFINES) {
8361 outs() << " WEAK_DEFINES";
8362 f &= ~MachO::MH_WEAK_DEFINES;
8364 if (f & MachO::MH_BINDS_TO_WEAK) {
8365 outs() << " BINDS_TO_WEAK";
8366 f &= ~MachO::MH_BINDS_TO_WEAK;
8368 if (f & MachO::MH_ALLOW_STACK_EXECUTION) {
8369 outs() << " ALLOW_STACK_EXECUTION";
8370 f &= ~MachO::MH_ALLOW_STACK_EXECUTION;
8372 if (f & MachO::MH_DEAD_STRIPPABLE_DYLIB) {
8373 outs() << " DEAD_STRIPPABLE_DYLIB";
8374 f &= ~MachO::MH_DEAD_STRIPPABLE_DYLIB;
8376 if (f & MachO::MH_PIE) {
8378 f &= ~MachO::MH_PIE;
8380 if (f & MachO::MH_NO_REEXPORTED_DYLIBS) {
8381 outs() << " NO_REEXPORTED_DYLIBS";
8382 f &= ~MachO::MH_NO_REEXPORTED_DYLIBS;
8384 if (f & MachO::MH_HAS_TLV_DESCRIPTORS) {
8385 outs() << " MH_HAS_TLV_DESCRIPTORS";
8386 f &= ~MachO::MH_HAS_TLV_DESCRIPTORS;
8388 if (f & MachO::MH_NO_HEAP_EXECUTION) {
8389 outs() << " MH_NO_HEAP_EXECUTION";
8390 f &= ~MachO::MH_NO_HEAP_EXECUTION;
8392 if (f & MachO::MH_APP_EXTENSION_SAFE) {
8393 outs() << " APP_EXTENSION_SAFE";
8394 f &= ~MachO::MH_APP_EXTENSION_SAFE;
8396 if (f & MachO::MH_NLIST_OUTOFSYNC_WITH_DYLDINFO) {
8397 outs() << " NLIST_OUTOFSYNC_WITH_DYLDINFO";
8398 f &= ~MachO::MH_NLIST_OUTOFSYNC_WITH_DYLDINFO;
8400 if (f != 0 || flags == 0)
8401 outs() << format(" 0x%08" PRIx32, f);
8403 outs() << format(" 0x%08" PRIx32, magic);
8404 outs() << format(" %7d", cputype);
8405 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
8406 outs() << format(" 0x%02" PRIx32,
8407 (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24);
8408 outs() << format(" %10u", filetype);
8409 outs() << format(" %5u", ncmds);
8410 outs() << format(" %10u", sizeofcmds);
8411 outs() << format(" 0x%08" PRIx32, flags);
8416 static void PrintSegmentCommand(uint32_t cmd, uint32_t cmdsize,
8417 StringRef SegName, uint64_t vmaddr,
8418 uint64_t vmsize, uint64_t fileoff,
8419 uint64_t filesize, uint32_t maxprot,
8420 uint32_t initprot, uint32_t nsects,
8421 uint32_t flags, uint32_t object_size,
8423 uint64_t expected_cmdsize;
8424 if (cmd == MachO::LC_SEGMENT) {
8425 outs() << " cmd LC_SEGMENT\n";
8426 expected_cmdsize = nsects;
8427 expected_cmdsize *= sizeof(struct MachO::section);
8428 expected_cmdsize += sizeof(struct MachO::segment_command);
8430 outs() << " cmd LC_SEGMENT_64\n";
8431 expected_cmdsize = nsects;
8432 expected_cmdsize *= sizeof(struct MachO::section_64);
8433 expected_cmdsize += sizeof(struct MachO::segment_command_64);
8435 outs() << " cmdsize " << cmdsize;
8436 if (cmdsize != expected_cmdsize)
8437 outs() << " Inconsistent size\n";
8440 outs() << " segname " << SegName << "\n";
8441 if (cmd == MachO::LC_SEGMENT_64) {
8442 outs() << " vmaddr " << format("0x%016" PRIx64, vmaddr) << "\n";
8443 outs() << " vmsize " << format("0x%016" PRIx64, vmsize) << "\n";
8445 outs() << " vmaddr " << format("0x%08" PRIx64, vmaddr) << "\n";
8446 outs() << " vmsize " << format("0x%08" PRIx64, vmsize) << "\n";
8448 outs() << " fileoff " << fileoff;
8449 if (fileoff > object_size)
8450 outs() << " (past end of file)\n";
8453 outs() << " filesize " << filesize;
8454 if (fileoff + filesize > object_size)
8455 outs() << " (past end of file)\n";
8460 ~(MachO::VM_PROT_READ | MachO::VM_PROT_WRITE |
8461 MachO::VM_PROT_EXECUTE)) != 0)
8462 outs() << " maxprot ?" << format("0x%08" PRIx32, maxprot) << "\n";
8464 outs() << " maxprot ";
8465 outs() << ((maxprot & MachO::VM_PROT_READ) ? "r" : "-");
8466 outs() << ((maxprot & MachO::VM_PROT_WRITE) ? "w" : "-");
8467 outs() << ((maxprot & MachO::VM_PROT_EXECUTE) ? "x\n" : "-\n");
8470 ~(MachO::VM_PROT_READ | MachO::VM_PROT_WRITE |
8471 MachO::VM_PROT_EXECUTE)) != 0)
8472 outs() << " initprot ?" << format("0x%08" PRIx32, initprot) << "\n";
8474 outs() << " initprot ";
8475 outs() << ((initprot & MachO::VM_PROT_READ) ? "r" : "-");
8476 outs() << ((initprot & MachO::VM_PROT_WRITE) ? "w" : "-");
8477 outs() << ((initprot & MachO::VM_PROT_EXECUTE) ? "x\n" : "-\n");
8480 outs() << " maxprot " << format("0x%08" PRIx32, maxprot) << "\n";
8481 outs() << " initprot " << format("0x%08" PRIx32, initprot) << "\n";
8483 outs() << " nsects " << nsects << "\n";
8487 outs() << " (none)\n";
8489 if (flags & MachO::SG_HIGHVM) {
8490 outs() << " HIGHVM";
8491 flags &= ~MachO::SG_HIGHVM;
8493 if (flags & MachO::SG_FVMLIB) {
8494 outs() << " FVMLIB";
8495 flags &= ~MachO::SG_FVMLIB;
8497 if (flags & MachO::SG_NORELOC) {
8498 outs() << " NORELOC";
8499 flags &= ~MachO::SG_NORELOC;
8501 if (flags & MachO::SG_PROTECTED_VERSION_1) {
8502 outs() << " PROTECTED_VERSION_1";
8503 flags &= ~MachO::SG_PROTECTED_VERSION_1;
8506 outs() << format(" 0x%08" PRIx32, flags) << " (unknown flags)\n";
8511 outs() << " flags " << format("0x%" PRIx32, flags) << "\n";
8515 static void PrintSection(const char *sectname, const char *segname,
8516 uint64_t addr, uint64_t size, uint32_t offset,
8517 uint32_t align, uint32_t reloff, uint32_t nreloc,
8518 uint32_t flags, uint32_t reserved1, uint32_t reserved2,
8519 uint32_t cmd, const char *sg_segname,
8520 uint32_t filetype, uint32_t object_size,
8522 outs() << "Section\n";
8523 outs() << " sectname " << format("%.16s\n", sectname);
8524 outs() << " segname " << format("%.16s", segname);
8525 if (filetype != MachO::MH_OBJECT && strncmp(sg_segname, segname, 16) != 0)
8526 outs() << " (does not match segment)\n";
8529 if (cmd == MachO::LC_SEGMENT_64) {
8530 outs() << " addr " << format("0x%016" PRIx64, addr) << "\n";
8531 outs() << " size " << format("0x%016" PRIx64, size);
8533 outs() << " addr " << format("0x%08" PRIx64, addr) << "\n";
8534 outs() << " size " << format("0x%08" PRIx64, size);
8536 if ((flags & MachO::S_ZEROFILL) != 0 && offset + size > object_size)
8537 outs() << " (past end of file)\n";
8540 outs() << " offset " << offset;
8541 if (offset > object_size)
8542 outs() << " (past end of file)\n";
8545 uint32_t align_shifted = 1 << align;
8546 outs() << " align 2^" << align << " (" << align_shifted << ")\n";
8547 outs() << " reloff " << reloff;
8548 if (reloff > object_size)
8549 outs() << " (past end of file)\n";
8552 outs() << " nreloc " << nreloc;
8553 if (reloff + nreloc * sizeof(struct MachO::relocation_info) > object_size)
8554 outs() << " (past end of file)\n";
8557 uint32_t section_type = flags & MachO::SECTION_TYPE;
8560 if (section_type == MachO::S_REGULAR)
8561 outs() << " S_REGULAR\n";
8562 else if (section_type == MachO::S_ZEROFILL)
8563 outs() << " S_ZEROFILL\n";
8564 else if (section_type == MachO::S_CSTRING_LITERALS)
8565 outs() << " S_CSTRING_LITERALS\n";
8566 else if (section_type == MachO::S_4BYTE_LITERALS)
8567 outs() << " S_4BYTE_LITERALS\n";
8568 else if (section_type == MachO::S_8BYTE_LITERALS)
8569 outs() << " S_8BYTE_LITERALS\n";
8570 else if (section_type == MachO::S_16BYTE_LITERALS)
8571 outs() << " S_16BYTE_LITERALS\n";
8572 else if (section_type == MachO::S_LITERAL_POINTERS)
8573 outs() << " S_LITERAL_POINTERS\n";
8574 else if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS)
8575 outs() << " S_NON_LAZY_SYMBOL_POINTERS\n";
8576 else if (section_type == MachO::S_LAZY_SYMBOL_POINTERS)
8577 outs() << " S_LAZY_SYMBOL_POINTERS\n";
8578 else if (section_type == MachO::S_SYMBOL_STUBS)
8579 outs() << " S_SYMBOL_STUBS\n";
8580 else if (section_type == MachO::S_MOD_INIT_FUNC_POINTERS)
8581 outs() << " S_MOD_INIT_FUNC_POINTERS\n";
8582 else if (section_type == MachO::S_MOD_TERM_FUNC_POINTERS)
8583 outs() << " S_MOD_TERM_FUNC_POINTERS\n";
8584 else if (section_type == MachO::S_COALESCED)
8585 outs() << " S_COALESCED\n";
8586 else if (section_type == MachO::S_INTERPOSING)
8587 outs() << " S_INTERPOSING\n";
8588 else if (section_type == MachO::S_DTRACE_DOF)
8589 outs() << " S_DTRACE_DOF\n";
8590 else if (section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS)
8591 outs() << " S_LAZY_DYLIB_SYMBOL_POINTERS\n";
8592 else if (section_type == MachO::S_THREAD_LOCAL_REGULAR)
8593 outs() << " S_THREAD_LOCAL_REGULAR\n";
8594 else if (section_type == MachO::S_THREAD_LOCAL_ZEROFILL)
8595 outs() << " S_THREAD_LOCAL_ZEROFILL\n";
8596 else if (section_type == MachO::S_THREAD_LOCAL_VARIABLES)
8597 outs() << " S_THREAD_LOCAL_VARIABLES\n";
8598 else if (section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS)
8599 outs() << " S_THREAD_LOCAL_VARIABLE_POINTERS\n";
8600 else if (section_type == MachO::S_THREAD_LOCAL_INIT_FUNCTION_POINTERS)
8601 outs() << " S_THREAD_LOCAL_INIT_FUNCTION_POINTERS\n";
8603 outs() << format("0x%08" PRIx32, section_type) << "\n";
8604 outs() << "attributes";
8605 uint32_t section_attributes = flags & MachO::SECTION_ATTRIBUTES;
8606 if (section_attributes & MachO::S_ATTR_PURE_INSTRUCTIONS)
8607 outs() << " PURE_INSTRUCTIONS";
8608 if (section_attributes & MachO::S_ATTR_NO_TOC)
8609 outs() << " NO_TOC";
8610 if (section_attributes & MachO::S_ATTR_STRIP_STATIC_SYMS)
8611 outs() << " STRIP_STATIC_SYMS";
8612 if (section_attributes & MachO::S_ATTR_NO_DEAD_STRIP)
8613 outs() << " NO_DEAD_STRIP";
8614 if (section_attributes & MachO::S_ATTR_LIVE_SUPPORT)
8615 outs() << " LIVE_SUPPORT";
8616 if (section_attributes & MachO::S_ATTR_SELF_MODIFYING_CODE)
8617 outs() << " SELF_MODIFYING_CODE";
8618 if (section_attributes & MachO::S_ATTR_DEBUG)
8620 if (section_attributes & MachO::S_ATTR_SOME_INSTRUCTIONS)
8621 outs() << " SOME_INSTRUCTIONS";
8622 if (section_attributes & MachO::S_ATTR_EXT_RELOC)
8623 outs() << " EXT_RELOC";
8624 if (section_attributes & MachO::S_ATTR_LOC_RELOC)
8625 outs() << " LOC_RELOC";
8626 if (section_attributes == 0)
8627 outs() << " (none)";
8630 outs() << " flags " << format("0x%08" PRIx32, flags) << "\n";
8631 outs() << " reserved1 " << reserved1;
8632 if (section_type == MachO::S_SYMBOL_STUBS ||
8633 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
8634 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
8635 section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
8636 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS)
8637 outs() << " (index into indirect symbol table)\n";
8640 outs() << " reserved2 " << reserved2;
8641 if (section_type == MachO::S_SYMBOL_STUBS)
8642 outs() << " (size of stubs)\n";
8647 static void PrintSymtabLoadCommand(MachO::symtab_command st, bool Is64Bit,
8648 uint32_t object_size) {
8649 outs() << " cmd LC_SYMTAB\n";
8650 outs() << " cmdsize " << st.cmdsize;
8651 if (st.cmdsize != sizeof(struct MachO::symtab_command))
8652 outs() << " Incorrect size\n";
8655 outs() << " symoff " << st.symoff;
8656 if (st.symoff > object_size)
8657 outs() << " (past end of file)\n";
8660 outs() << " nsyms " << st.nsyms;
8663 big_size = st.nsyms;
8664 big_size *= sizeof(struct MachO::nlist_64);
8665 big_size += st.symoff;
8666 if (big_size > object_size)
8667 outs() << " (past end of file)\n";
8671 big_size = st.nsyms;
8672 big_size *= sizeof(struct MachO::nlist);
8673 big_size += st.symoff;
8674 if (big_size > object_size)
8675 outs() << " (past end of file)\n";
8679 outs() << " stroff " << st.stroff;
8680 if (st.stroff > object_size)
8681 outs() << " (past end of file)\n";
8684 outs() << " strsize " << st.strsize;
8685 big_size = st.stroff;
8686 big_size += st.strsize;
8687 if (big_size > object_size)
8688 outs() << " (past end of file)\n";
8693 static void PrintDysymtabLoadCommand(MachO::dysymtab_command dyst,
8694 uint32_t nsyms, uint32_t object_size,
8696 outs() << " cmd LC_DYSYMTAB\n";
8697 outs() << " cmdsize " << dyst.cmdsize;
8698 if (dyst.cmdsize != sizeof(struct MachO::dysymtab_command))
8699 outs() << " Incorrect size\n";
8702 outs() << " ilocalsym " << dyst.ilocalsym;
8703 if (dyst.ilocalsym > nsyms)
8704 outs() << " (greater than the number of symbols)\n";
8707 outs() << " nlocalsym " << dyst.nlocalsym;
8709 big_size = dyst.ilocalsym;
8710 big_size += dyst.nlocalsym;
8711 if (big_size > nsyms)
8712 outs() << " (past the end of the symbol table)\n";
8715 outs() << " iextdefsym " << dyst.iextdefsym;
8716 if (dyst.iextdefsym > nsyms)
8717 outs() << " (greater than the number of symbols)\n";
8720 outs() << " nextdefsym " << dyst.nextdefsym;
8721 big_size = dyst.iextdefsym;
8722 big_size += dyst.nextdefsym;
8723 if (big_size > nsyms)
8724 outs() << " (past the end of the symbol table)\n";
8727 outs() << " iundefsym " << dyst.iundefsym;
8728 if (dyst.iundefsym > nsyms)
8729 outs() << " (greater than the number of symbols)\n";
8732 outs() << " nundefsym " << dyst.nundefsym;
8733 big_size = dyst.iundefsym;
8734 big_size += dyst.nundefsym;
8735 if (big_size > nsyms)
8736 outs() << " (past the end of the symbol table)\n";
8739 outs() << " tocoff " << dyst.tocoff;
8740 if (dyst.tocoff > object_size)
8741 outs() << " (past end of file)\n";
8744 outs() << " ntoc " << dyst.ntoc;
8745 big_size = dyst.ntoc;
8746 big_size *= sizeof(struct MachO::dylib_table_of_contents);
8747 big_size += dyst.tocoff;
8748 if (big_size > object_size)
8749 outs() << " (past end of file)\n";
8752 outs() << " modtaboff " << dyst.modtaboff;
8753 if (dyst.modtaboff > object_size)
8754 outs() << " (past end of file)\n";
8757 outs() << " nmodtab " << dyst.nmodtab;
8760 modtabend = dyst.nmodtab;
8761 modtabend *= sizeof(struct MachO::dylib_module_64);
8762 modtabend += dyst.modtaboff;
8764 modtabend = dyst.nmodtab;
8765 modtabend *= sizeof(struct MachO::dylib_module);
8766 modtabend += dyst.modtaboff;
8768 if (modtabend > object_size)
8769 outs() << " (past end of file)\n";
8772 outs() << " extrefsymoff " << dyst.extrefsymoff;
8773 if (dyst.extrefsymoff > object_size)
8774 outs() << " (past end of file)\n";
8777 outs() << " nextrefsyms " << dyst.nextrefsyms;
8778 big_size = dyst.nextrefsyms;
8779 big_size *= sizeof(struct MachO::dylib_reference);
8780 big_size += dyst.extrefsymoff;
8781 if (big_size > object_size)
8782 outs() << " (past end of file)\n";
8785 outs() << " indirectsymoff " << dyst.indirectsymoff;
8786 if (dyst.indirectsymoff > object_size)
8787 outs() << " (past end of file)\n";
8790 outs() << " nindirectsyms " << dyst.nindirectsyms;
8791 big_size = dyst.nindirectsyms;
8792 big_size *= sizeof(uint32_t);
8793 big_size += dyst.indirectsymoff;
8794 if (big_size > object_size)
8795 outs() << " (past end of file)\n";
8798 outs() << " extreloff " << dyst.extreloff;
8799 if (dyst.extreloff > object_size)
8800 outs() << " (past end of file)\n";
8803 outs() << " nextrel " << dyst.nextrel;
8804 big_size = dyst.nextrel;
8805 big_size *= sizeof(struct MachO::relocation_info);
8806 big_size += dyst.extreloff;
8807 if (big_size > object_size)
8808 outs() << " (past end of file)\n";
8811 outs() << " locreloff " << dyst.locreloff;
8812 if (dyst.locreloff > object_size)
8813 outs() << " (past end of file)\n";
8816 outs() << " nlocrel " << dyst.nlocrel;
8817 big_size = dyst.nlocrel;
8818 big_size *= sizeof(struct MachO::relocation_info);
8819 big_size += dyst.locreloff;
8820 if (big_size > object_size)
8821 outs() << " (past end of file)\n";
8826 static void PrintDyldInfoLoadCommand(MachO::dyld_info_command dc,
8827 uint32_t object_size) {
8828 if (dc.cmd == MachO::LC_DYLD_INFO)
8829 outs() << " cmd LC_DYLD_INFO\n";
8831 outs() << " cmd LC_DYLD_INFO_ONLY\n";
8832 outs() << " cmdsize " << dc.cmdsize;
8833 if (dc.cmdsize != sizeof(struct MachO::dyld_info_command))
8834 outs() << " Incorrect size\n";
8837 outs() << " rebase_off " << dc.rebase_off;
8838 if (dc.rebase_off > object_size)
8839 outs() << " (past end of file)\n";
8842 outs() << " rebase_size " << dc.rebase_size;
8844 big_size = dc.rebase_off;
8845 big_size += dc.rebase_size;
8846 if (big_size > object_size)
8847 outs() << " (past end of file)\n";
8850 outs() << " bind_off " << dc.bind_off;
8851 if (dc.bind_off > object_size)
8852 outs() << " (past end of file)\n";
8855 outs() << " bind_size " << dc.bind_size;
8856 big_size = dc.bind_off;
8857 big_size += dc.bind_size;
8858 if (big_size > object_size)
8859 outs() << " (past end of file)\n";
8862 outs() << " weak_bind_off " << dc.weak_bind_off;
8863 if (dc.weak_bind_off > object_size)
8864 outs() << " (past end of file)\n";
8867 outs() << " weak_bind_size " << dc.weak_bind_size;
8868 big_size = dc.weak_bind_off;
8869 big_size += dc.weak_bind_size;
8870 if (big_size > object_size)
8871 outs() << " (past end of file)\n";
8874 outs() << " lazy_bind_off " << dc.lazy_bind_off;
8875 if (dc.lazy_bind_off > object_size)
8876 outs() << " (past end of file)\n";
8879 outs() << " lazy_bind_size " << dc.lazy_bind_size;
8880 big_size = dc.lazy_bind_off;
8881 big_size += dc.lazy_bind_size;
8882 if (big_size > object_size)
8883 outs() << " (past end of file)\n";
8886 outs() << " export_off " << dc.export_off;
8887 if (dc.export_off > object_size)
8888 outs() << " (past end of file)\n";
8891 outs() << " export_size " << dc.export_size;
8892 big_size = dc.export_off;
8893 big_size += dc.export_size;
8894 if (big_size > object_size)
8895 outs() << " (past end of file)\n";
8900 static void PrintDyldLoadCommand(MachO::dylinker_command dyld,
8902 if (dyld.cmd == MachO::LC_ID_DYLINKER)
8903 outs() << " cmd LC_ID_DYLINKER\n";
8904 else if (dyld.cmd == MachO::LC_LOAD_DYLINKER)
8905 outs() << " cmd LC_LOAD_DYLINKER\n";
8906 else if (dyld.cmd == MachO::LC_DYLD_ENVIRONMENT)
8907 outs() << " cmd LC_DYLD_ENVIRONMENT\n";
8909 outs() << " cmd ?(" << dyld.cmd << ")\n";
8910 outs() << " cmdsize " << dyld.cmdsize;
8911 if (dyld.cmdsize < sizeof(struct MachO::dylinker_command))
8912 outs() << " Incorrect size\n";
8915 if (dyld.name >= dyld.cmdsize)
8916 outs() << " name ?(bad offset " << dyld.name << ")\n";
8918 const char *P = (const char *)(Ptr) + dyld.name;
8919 outs() << " name " << P << " (offset " << dyld.name << ")\n";
8923 static void PrintUuidLoadCommand(MachO::uuid_command uuid) {
8924 outs() << " cmd LC_UUID\n";
8925 outs() << " cmdsize " << uuid.cmdsize;
8926 if (uuid.cmdsize != sizeof(struct MachO::uuid_command))
8927 outs() << " Incorrect size\n";
8931 for (int i = 0; i < 16; ++i) {
8932 outs() << format("%02" PRIX32, uuid.uuid[i]);
8933 if (i == 3 || i == 5 || i == 7 || i == 9)
8939 static void PrintRpathLoadCommand(MachO::rpath_command rpath, const char *Ptr) {
8940 outs() << " cmd LC_RPATH\n";
8941 outs() << " cmdsize " << rpath.cmdsize;
8942 if (rpath.cmdsize < sizeof(struct MachO::rpath_command))
8943 outs() << " Incorrect size\n";
8946 if (rpath.path >= rpath.cmdsize)
8947 outs() << " path ?(bad offset " << rpath.path << ")\n";
8949 const char *P = (const char *)(Ptr) + rpath.path;
8950 outs() << " path " << P << " (offset " << rpath.path << ")\n";
8954 static void PrintVersionMinLoadCommand(MachO::version_min_command vd) {
8955 StringRef LoadCmdName;
8957 case MachO::LC_VERSION_MIN_MACOSX:
8958 LoadCmdName = "LC_VERSION_MIN_MACOSX";
8960 case MachO::LC_VERSION_MIN_IPHONEOS:
8961 LoadCmdName = "LC_VERSION_MIN_IPHONEOS";
8963 case MachO::LC_VERSION_MIN_TVOS:
8964 LoadCmdName = "LC_VERSION_MIN_TVOS";
8966 case MachO::LC_VERSION_MIN_WATCHOS:
8967 LoadCmdName = "LC_VERSION_MIN_WATCHOS";
8970 llvm_unreachable("Unknown version min load command");
8973 outs() << " cmd " << LoadCmdName << '\n';
8974 outs() << " cmdsize " << vd.cmdsize;
8975 if (vd.cmdsize != sizeof(struct MachO::version_min_command))
8976 outs() << " Incorrect size\n";
8979 outs() << " version "
8980 << MachOObjectFile::getVersionMinMajor(vd, false) << "."
8981 << MachOObjectFile::getVersionMinMinor(vd, false);
8982 uint32_t Update = MachOObjectFile::getVersionMinUpdate(vd, false);
8984 outs() << "." << Update;
8987 outs() << " sdk n/a";
8990 << MachOObjectFile::getVersionMinMajor(vd, true) << "."
8991 << MachOObjectFile::getVersionMinMinor(vd, true);
8993 Update = MachOObjectFile::getVersionMinUpdate(vd, true);
8995 outs() << "." << Update;
8999 static void PrintNoteLoadCommand(MachO::note_command Nt) {
9000 outs() << " cmd LC_NOTE\n";
9001 outs() << " cmdsize " << Nt.cmdsize;
9002 if (Nt.cmdsize != sizeof(struct MachO::note_command))
9003 outs() << " Incorrect size\n";
9006 const char *d = Nt.data_owner;
9007 outs() << "data_owner " << format("%.16s\n", d);
9008 outs() << " offset " << Nt.offset << "\n";
9009 outs() << " size " << Nt.size << "\n";
9012 static void PrintBuildToolVersion(MachO::build_tool_version bv) {
9013 outs() << " tool " << MachOObjectFile::getBuildTool(bv.tool) << "\n";
9014 outs() << " version " << MachOObjectFile::getVersionString(bv.version)
9018 static void PrintBuildVersionLoadCommand(const MachOObjectFile *obj,
9019 MachO::build_version_command bd) {
9020 outs() << " cmd LC_BUILD_VERSION\n";
9021 outs() << " cmdsize " << bd.cmdsize;
9023 sizeof(struct MachO::build_version_command) +
9024 bd.ntools * sizeof(struct MachO::build_tool_version))
9025 outs() << " Incorrect size\n";
9028 outs() << " platform " << MachOObjectFile::getBuildPlatform(bd.platform)
9031 outs() << " sdk " << MachOObjectFile::getVersionString(bd.sdk)
9034 outs() << " sdk n/a\n";
9035 outs() << " minos " << MachOObjectFile::getVersionString(bd.minos)
9037 outs() << " ntools " << bd.ntools << "\n";
9038 for (unsigned i = 0; i < bd.ntools; ++i) {
9039 MachO::build_tool_version bv = obj->getBuildToolVersion(i);
9040 PrintBuildToolVersion(bv);
9044 static void PrintSourceVersionCommand(MachO::source_version_command sd) {
9045 outs() << " cmd LC_SOURCE_VERSION\n";
9046 outs() << " cmdsize " << sd.cmdsize;
9047 if (sd.cmdsize != sizeof(struct MachO::source_version_command))
9048 outs() << " Incorrect size\n";
9051 uint64_t a = (sd.version >> 40) & 0xffffff;
9052 uint64_t b = (sd.version >> 30) & 0x3ff;
9053 uint64_t c = (sd.version >> 20) & 0x3ff;
9054 uint64_t d = (sd.version >> 10) & 0x3ff;
9055 uint64_t e = sd.version & 0x3ff;
9056 outs() << " version " << a << "." << b;
9058 outs() << "." << c << "." << d << "." << e;
9060 outs() << "." << c << "." << d;
9066 static void PrintEntryPointCommand(MachO::entry_point_command ep) {
9067 outs() << " cmd LC_MAIN\n";
9068 outs() << " cmdsize " << ep.cmdsize;
9069 if (ep.cmdsize != sizeof(struct MachO::entry_point_command))
9070 outs() << " Incorrect size\n";
9073 outs() << " entryoff " << ep.entryoff << "\n";
9074 outs() << " stacksize " << ep.stacksize << "\n";
9077 static void PrintEncryptionInfoCommand(MachO::encryption_info_command ec,
9078 uint32_t object_size) {
9079 outs() << " cmd LC_ENCRYPTION_INFO\n";
9080 outs() << " cmdsize " << ec.cmdsize;
9081 if (ec.cmdsize != sizeof(struct MachO::encryption_info_command))
9082 outs() << " Incorrect size\n";
9085 outs() << " cryptoff " << ec.cryptoff;
9086 if (ec.cryptoff > object_size)
9087 outs() << " (past end of file)\n";
9090 outs() << " cryptsize " << ec.cryptsize;
9091 if (ec.cryptsize > object_size)
9092 outs() << " (past end of file)\n";
9095 outs() << " cryptid " << ec.cryptid << "\n";
9098 static void PrintEncryptionInfoCommand64(MachO::encryption_info_command_64 ec,
9099 uint32_t object_size) {
9100 outs() << " cmd LC_ENCRYPTION_INFO_64\n";
9101 outs() << " cmdsize " << ec.cmdsize;
9102 if (ec.cmdsize != sizeof(struct MachO::encryption_info_command_64))
9103 outs() << " Incorrect size\n";
9106 outs() << " cryptoff " << ec.cryptoff;
9107 if (ec.cryptoff > object_size)
9108 outs() << " (past end of file)\n";
9111 outs() << " cryptsize " << ec.cryptsize;
9112 if (ec.cryptsize > object_size)
9113 outs() << " (past end of file)\n";
9116 outs() << " cryptid " << ec.cryptid << "\n";
9117 outs() << " pad " << ec.pad << "\n";
9120 static void PrintLinkerOptionCommand(MachO::linker_option_command lo,
9122 outs() << " cmd LC_LINKER_OPTION\n";
9123 outs() << " cmdsize " << lo.cmdsize;
9124 if (lo.cmdsize < sizeof(struct MachO::linker_option_command))
9125 outs() << " Incorrect size\n";
9128 outs() << " count " << lo.count << "\n";
9129 const char *string = Ptr + sizeof(struct MachO::linker_option_command);
9130 uint32_t left = lo.cmdsize - sizeof(struct MachO::linker_option_command);
9133 while (*string == '\0' && left > 0) {
9139 outs() << " string #" << i << " " << format("%.*s\n", left, string);
9140 uint32_t NullPos = StringRef(string, left).find('\0');
9141 uint32_t len = std::min(NullPos, left) + 1;
9147 outs() << " count " << lo.count << " does not match number of strings "
9151 static void PrintSubFrameworkCommand(MachO::sub_framework_command sub,
9153 outs() << " cmd LC_SUB_FRAMEWORK\n";
9154 outs() << " cmdsize " << sub.cmdsize;
9155 if (sub.cmdsize < sizeof(struct MachO::sub_framework_command))
9156 outs() << " Incorrect size\n";
9159 if (sub.umbrella < sub.cmdsize) {
9160 const char *P = Ptr + sub.umbrella;
9161 outs() << " umbrella " << P << " (offset " << sub.umbrella << ")\n";
9163 outs() << " umbrella ?(bad offset " << sub.umbrella << ")\n";
9167 static void PrintSubUmbrellaCommand(MachO::sub_umbrella_command sub,
9169 outs() << " cmd LC_SUB_UMBRELLA\n";
9170 outs() << " cmdsize " << sub.cmdsize;
9171 if (sub.cmdsize < sizeof(struct MachO::sub_umbrella_command))
9172 outs() << " Incorrect size\n";
9175 if (sub.sub_umbrella < sub.cmdsize) {
9176 const char *P = Ptr + sub.sub_umbrella;
9177 outs() << " sub_umbrella " << P << " (offset " << sub.sub_umbrella << ")\n";
9179 outs() << " sub_umbrella ?(bad offset " << sub.sub_umbrella << ")\n";
9183 static void PrintSubLibraryCommand(MachO::sub_library_command sub,
9185 outs() << " cmd LC_SUB_LIBRARY\n";
9186 outs() << " cmdsize " << sub.cmdsize;
9187 if (sub.cmdsize < sizeof(struct MachO::sub_library_command))
9188 outs() << " Incorrect size\n";
9191 if (sub.sub_library < sub.cmdsize) {
9192 const char *P = Ptr + sub.sub_library;
9193 outs() << " sub_library " << P << " (offset " << sub.sub_library << ")\n";
9195 outs() << " sub_library ?(bad offset " << sub.sub_library << ")\n";
9199 static void PrintSubClientCommand(MachO::sub_client_command sub,
9201 outs() << " cmd LC_SUB_CLIENT\n";
9202 outs() << " cmdsize " << sub.cmdsize;
9203 if (sub.cmdsize < sizeof(struct MachO::sub_client_command))
9204 outs() << " Incorrect size\n";
9207 if (sub.client < sub.cmdsize) {
9208 const char *P = Ptr + sub.client;
9209 outs() << " client " << P << " (offset " << sub.client << ")\n";
9211 outs() << " client ?(bad offset " << sub.client << ")\n";
9215 static void PrintRoutinesCommand(MachO::routines_command r) {
9216 outs() << " cmd LC_ROUTINES\n";
9217 outs() << " cmdsize " << r.cmdsize;
9218 if (r.cmdsize != sizeof(struct MachO::routines_command))
9219 outs() << " Incorrect size\n";
9222 outs() << " init_address " << format("0x%08" PRIx32, r.init_address) << "\n";
9223 outs() << " init_module " << r.init_module << "\n";
9224 outs() << " reserved1 " << r.reserved1 << "\n";
9225 outs() << " reserved2 " << r.reserved2 << "\n";
9226 outs() << " reserved3 " << r.reserved3 << "\n";
9227 outs() << " reserved4 " << r.reserved4 << "\n";
9228 outs() << " reserved5 " << r.reserved5 << "\n";
9229 outs() << " reserved6 " << r.reserved6 << "\n";
9232 static void PrintRoutinesCommand64(MachO::routines_command_64 r) {
9233 outs() << " cmd LC_ROUTINES_64\n";
9234 outs() << " cmdsize " << r.cmdsize;
9235 if (r.cmdsize != sizeof(struct MachO::routines_command_64))
9236 outs() << " Incorrect size\n";
9239 outs() << " init_address " << format("0x%016" PRIx64, r.init_address) << "\n";
9240 outs() << " init_module " << r.init_module << "\n";
9241 outs() << " reserved1 " << r.reserved1 << "\n";
9242 outs() << " reserved2 " << r.reserved2 << "\n";
9243 outs() << " reserved3 " << r.reserved3 << "\n";
9244 outs() << " reserved4 " << r.reserved4 << "\n";
9245 outs() << " reserved5 " << r.reserved5 << "\n";
9246 outs() << " reserved6 " << r.reserved6 << "\n";
9249 static void Print_x86_thread_state32_t(MachO::x86_thread_state32_t &cpu32) {
9250 outs() << "\t eax " << format("0x%08" PRIx32, cpu32.eax);
9251 outs() << " ebx " << format("0x%08" PRIx32, cpu32.ebx);
9252 outs() << " ecx " << format("0x%08" PRIx32, cpu32.ecx);
9253 outs() << " edx " << format("0x%08" PRIx32, cpu32.edx) << "\n";
9254 outs() << "\t edi " << format("0x%08" PRIx32, cpu32.edi);
9255 outs() << " esi " << format("0x%08" PRIx32, cpu32.esi);
9256 outs() << " ebp " << format("0x%08" PRIx32, cpu32.ebp);
9257 outs() << " esp " << format("0x%08" PRIx32, cpu32.esp) << "\n";
9258 outs() << "\t ss " << format("0x%08" PRIx32, cpu32.ss);
9259 outs() << " eflags " << format("0x%08" PRIx32, cpu32.eflags);
9260 outs() << " eip " << format("0x%08" PRIx32, cpu32.eip);
9261 outs() << " cs " << format("0x%08" PRIx32, cpu32.cs) << "\n";
9262 outs() << "\t ds " << format("0x%08" PRIx32, cpu32.ds);
9263 outs() << " es " << format("0x%08" PRIx32, cpu32.es);
9264 outs() << " fs " << format("0x%08" PRIx32, cpu32.fs);
9265 outs() << " gs " << format("0x%08" PRIx32, cpu32.gs) << "\n";
9268 static void Print_x86_thread_state64_t(MachO::x86_thread_state64_t &cpu64) {
9269 outs() << " rax " << format("0x%016" PRIx64, cpu64.rax);
9270 outs() << " rbx " << format("0x%016" PRIx64, cpu64.rbx);
9271 outs() << " rcx " << format("0x%016" PRIx64, cpu64.rcx) << "\n";
9272 outs() << " rdx " << format("0x%016" PRIx64, cpu64.rdx);
9273 outs() << " rdi " << format("0x%016" PRIx64, cpu64.rdi);
9274 outs() << " rsi " << format("0x%016" PRIx64, cpu64.rsi) << "\n";
9275 outs() << " rbp " << format("0x%016" PRIx64, cpu64.rbp);
9276 outs() << " rsp " << format("0x%016" PRIx64, cpu64.rsp);
9277 outs() << " r8 " << format("0x%016" PRIx64, cpu64.r8) << "\n";
9278 outs() << " r9 " << format("0x%016" PRIx64, cpu64.r9);
9279 outs() << " r10 " << format("0x%016" PRIx64, cpu64.r10);
9280 outs() << " r11 " << format("0x%016" PRIx64, cpu64.r11) << "\n";
9281 outs() << " r12 " << format("0x%016" PRIx64, cpu64.r12);
9282 outs() << " r13 " << format("0x%016" PRIx64, cpu64.r13);
9283 outs() << " r14 " << format("0x%016" PRIx64, cpu64.r14) << "\n";
9284 outs() << " r15 " << format("0x%016" PRIx64, cpu64.r15);
9285 outs() << " rip " << format("0x%016" PRIx64, cpu64.rip) << "\n";
9286 outs() << "rflags " << format("0x%016" PRIx64, cpu64.rflags);
9287 outs() << " cs " << format("0x%016" PRIx64, cpu64.cs);
9288 outs() << " fs " << format("0x%016" PRIx64, cpu64.fs) << "\n";
9289 outs() << " gs " << format("0x%016" PRIx64, cpu64.gs) << "\n";
9292 static void Print_mmst_reg(MachO::mmst_reg_t &r) {
9294 outs() << "\t mmst_reg ";
9295 for (f = 0; f < 10; f++)
9296 outs() << format("%02" PRIx32, (r.mmst_reg[f] & 0xff)) << " ";
9298 outs() << "\t mmst_rsrv ";
9299 for (f = 0; f < 6; f++)
9300 outs() << format("%02" PRIx32, (r.mmst_rsrv[f] & 0xff)) << " ";
9304 static void Print_xmm_reg(MachO::xmm_reg_t &r) {
9306 outs() << "\t xmm_reg ";
9307 for (f = 0; f < 16; f++)
9308 outs() << format("%02" PRIx32, (r.xmm_reg[f] & 0xff)) << " ";
9312 static void Print_x86_float_state_t(MachO::x86_float_state64_t &fpu) {
9313 outs() << "\t fpu_reserved[0] " << fpu.fpu_reserved[0];
9314 outs() << " fpu_reserved[1] " << fpu.fpu_reserved[1] << "\n";
9315 outs() << "\t control: invalid " << fpu.fpu_fcw.invalid;
9316 outs() << " denorm " << fpu.fpu_fcw.denorm;
9317 outs() << " zdiv " << fpu.fpu_fcw.zdiv;
9318 outs() << " ovrfl " << fpu.fpu_fcw.ovrfl;
9319 outs() << " undfl " << fpu.fpu_fcw.undfl;
9320 outs() << " precis " << fpu.fpu_fcw.precis << "\n";
9321 outs() << "\t\t pc ";
9322 if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_24B)
9323 outs() << "FP_PREC_24B ";
9324 else if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_53B)
9325 outs() << "FP_PREC_53B ";
9326 else if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_64B)
9327 outs() << "FP_PREC_64B ";
9329 outs() << fpu.fpu_fcw.pc << " ";
9331 if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_NEAR)
9332 outs() << "FP_RND_NEAR ";
9333 else if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_DOWN)
9334 outs() << "FP_RND_DOWN ";
9335 else if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_UP)
9336 outs() << "FP_RND_UP ";
9337 else if (fpu.fpu_fcw.rc == MachO::x86_FP_CHOP)
9338 outs() << "FP_CHOP ";
9340 outs() << "\t status: invalid " << fpu.fpu_fsw.invalid;
9341 outs() << " denorm " << fpu.fpu_fsw.denorm;
9342 outs() << " zdiv " << fpu.fpu_fsw.zdiv;
9343 outs() << " ovrfl " << fpu.fpu_fsw.ovrfl;
9344 outs() << " undfl " << fpu.fpu_fsw.undfl;
9345 outs() << " precis " << fpu.fpu_fsw.precis;
9346 outs() << " stkflt " << fpu.fpu_fsw.stkflt << "\n";
9347 outs() << "\t errsumm " << fpu.fpu_fsw.errsumm;
9348 outs() << " c0 " << fpu.fpu_fsw.c0;
9349 outs() << " c1 " << fpu.fpu_fsw.c1;
9350 outs() << " c2 " << fpu.fpu_fsw.c2;
9351 outs() << " tos " << fpu.fpu_fsw.tos;
9352 outs() << " c3 " << fpu.fpu_fsw.c3;
9353 outs() << " busy " << fpu.fpu_fsw.busy << "\n";
9354 outs() << "\t fpu_ftw " << format("0x%02" PRIx32, fpu.fpu_ftw);
9355 outs() << " fpu_rsrv1 " << format("0x%02" PRIx32, fpu.fpu_rsrv1);
9356 outs() << " fpu_fop " << format("0x%04" PRIx32, fpu.fpu_fop);
9357 outs() << " fpu_ip " << format("0x%08" PRIx32, fpu.fpu_ip) << "\n";
9358 outs() << "\t fpu_cs " << format("0x%04" PRIx32, fpu.fpu_cs);
9359 outs() << " fpu_rsrv2 " << format("0x%04" PRIx32, fpu.fpu_rsrv2);
9360 outs() << " fpu_dp " << format("0x%08" PRIx32, fpu.fpu_dp);
9361 outs() << " fpu_ds " << format("0x%04" PRIx32, fpu.fpu_ds) << "\n";
9362 outs() << "\t fpu_rsrv3 " << format("0x%04" PRIx32, fpu.fpu_rsrv3);
9363 outs() << " fpu_mxcsr " << format("0x%08" PRIx32, fpu.fpu_mxcsr);
9364 outs() << " fpu_mxcsrmask " << format("0x%08" PRIx32, fpu.fpu_mxcsrmask);
9366 outs() << "\t fpu_stmm0:\n";
9367 Print_mmst_reg(fpu.fpu_stmm0);
9368 outs() << "\t fpu_stmm1:\n";
9369 Print_mmst_reg(fpu.fpu_stmm1);
9370 outs() << "\t fpu_stmm2:\n";
9371 Print_mmst_reg(fpu.fpu_stmm2);
9372 outs() << "\t fpu_stmm3:\n";
9373 Print_mmst_reg(fpu.fpu_stmm3);
9374 outs() << "\t fpu_stmm4:\n";
9375 Print_mmst_reg(fpu.fpu_stmm4);
9376 outs() << "\t fpu_stmm5:\n";
9377 Print_mmst_reg(fpu.fpu_stmm5);
9378 outs() << "\t fpu_stmm6:\n";
9379 Print_mmst_reg(fpu.fpu_stmm6);
9380 outs() << "\t fpu_stmm7:\n";
9381 Print_mmst_reg(fpu.fpu_stmm7);
9382 outs() << "\t fpu_xmm0:\n";
9383 Print_xmm_reg(fpu.fpu_xmm0);
9384 outs() << "\t fpu_xmm1:\n";
9385 Print_xmm_reg(fpu.fpu_xmm1);
9386 outs() << "\t fpu_xmm2:\n";
9387 Print_xmm_reg(fpu.fpu_xmm2);
9388 outs() << "\t fpu_xmm3:\n";
9389 Print_xmm_reg(fpu.fpu_xmm3);
9390 outs() << "\t fpu_xmm4:\n";
9391 Print_xmm_reg(fpu.fpu_xmm4);
9392 outs() << "\t fpu_xmm5:\n";
9393 Print_xmm_reg(fpu.fpu_xmm5);
9394 outs() << "\t fpu_xmm6:\n";
9395 Print_xmm_reg(fpu.fpu_xmm6);
9396 outs() << "\t fpu_xmm7:\n";
9397 Print_xmm_reg(fpu.fpu_xmm7);
9398 outs() << "\t fpu_xmm8:\n";
9399 Print_xmm_reg(fpu.fpu_xmm8);
9400 outs() << "\t fpu_xmm9:\n";
9401 Print_xmm_reg(fpu.fpu_xmm9);
9402 outs() << "\t fpu_xmm10:\n";
9403 Print_xmm_reg(fpu.fpu_xmm10);
9404 outs() << "\t fpu_xmm11:\n";
9405 Print_xmm_reg(fpu.fpu_xmm11);
9406 outs() << "\t fpu_xmm12:\n";
9407 Print_xmm_reg(fpu.fpu_xmm12);
9408 outs() << "\t fpu_xmm13:\n";
9409 Print_xmm_reg(fpu.fpu_xmm13);
9410 outs() << "\t fpu_xmm14:\n";
9411 Print_xmm_reg(fpu.fpu_xmm14);
9412 outs() << "\t fpu_xmm15:\n";
9413 Print_xmm_reg(fpu.fpu_xmm15);
9414 outs() << "\t fpu_rsrv4:\n";
9415 for (uint32_t f = 0; f < 6; f++) {
9417 for (uint32_t g = 0; g < 16; g++)
9418 outs() << format("%02" PRIx32, fpu.fpu_rsrv4[f * g]) << " ";
9421 outs() << "\t fpu_reserved1 " << format("0x%08" PRIx32, fpu.fpu_reserved1);
9425 static void Print_x86_exception_state_t(MachO::x86_exception_state64_t &exc64) {
9426 outs() << "\t trapno " << format("0x%08" PRIx32, exc64.trapno);
9427 outs() << " err " << format("0x%08" PRIx32, exc64.err);
9428 outs() << " faultvaddr " << format("0x%016" PRIx64, exc64.faultvaddr) << "\n";
9431 static void Print_arm_thread_state32_t(MachO::arm_thread_state32_t &cpu32) {
9432 outs() << "\t r0 " << format("0x%08" PRIx32, cpu32.r[0]);
9433 outs() << " r1 " << format("0x%08" PRIx32, cpu32.r[1]);
9434 outs() << " r2 " << format("0x%08" PRIx32, cpu32.r[2]);
9435 outs() << " r3 " << format("0x%08" PRIx32, cpu32.r[3]) << "\n";
9436 outs() << "\t r4 " << format("0x%08" PRIx32, cpu32.r[4]);
9437 outs() << " r5 " << format("0x%08" PRIx32, cpu32.r[5]);
9438 outs() << " r6 " << format("0x%08" PRIx32, cpu32.r[6]);
9439 outs() << " r7 " << format("0x%08" PRIx32, cpu32.r[7]) << "\n";
9440 outs() << "\t r8 " << format("0x%08" PRIx32, cpu32.r[8]);
9441 outs() << " r9 " << format("0x%08" PRIx32, cpu32.r[9]);
9442 outs() << " r10 " << format("0x%08" PRIx32, cpu32.r[10]);
9443 outs() << " r11 " << format("0x%08" PRIx32, cpu32.r[11]) << "\n";
9444 outs() << "\t r12 " << format("0x%08" PRIx32, cpu32.r[12]);
9445 outs() << " sp " << format("0x%08" PRIx32, cpu32.sp);
9446 outs() << " lr " << format("0x%08" PRIx32, cpu32.lr);
9447 outs() << " pc " << format("0x%08" PRIx32, cpu32.pc) << "\n";
9448 outs() << "\t cpsr " << format("0x%08" PRIx32, cpu32.cpsr) << "\n";
9451 static void Print_arm_thread_state64_t(MachO::arm_thread_state64_t &cpu64) {
9452 outs() << "\t x0 " << format("0x%016" PRIx64, cpu64.x[0]);
9453 outs() << " x1 " << format("0x%016" PRIx64, cpu64.x[1]);
9454 outs() << " x2 " << format("0x%016" PRIx64, cpu64.x[2]) << "\n";
9455 outs() << "\t x3 " << format("0x%016" PRIx64, cpu64.x[3]);
9456 outs() << " x4 " << format("0x%016" PRIx64, cpu64.x[4]);
9457 outs() << " x5 " << format("0x%016" PRIx64, cpu64.x[5]) << "\n";
9458 outs() << "\t x6 " << format("0x%016" PRIx64, cpu64.x[6]);
9459 outs() << " x7 " << format("0x%016" PRIx64, cpu64.x[7]);
9460 outs() << " x8 " << format("0x%016" PRIx64, cpu64.x[8]) << "\n";
9461 outs() << "\t x9 " << format("0x%016" PRIx64, cpu64.x[9]);
9462 outs() << " x10 " << format("0x%016" PRIx64, cpu64.x[10]);
9463 outs() << " x11 " << format("0x%016" PRIx64, cpu64.x[11]) << "\n";
9464 outs() << "\t x12 " << format("0x%016" PRIx64, cpu64.x[12]);
9465 outs() << " x13 " << format("0x%016" PRIx64, cpu64.x[13]);
9466 outs() << " x14 " << format("0x%016" PRIx64, cpu64.x[14]) << "\n";
9467 outs() << "\t x15 " << format("0x%016" PRIx64, cpu64.x[15]);
9468 outs() << " x16 " << format("0x%016" PRIx64, cpu64.x[16]);
9469 outs() << " x17 " << format("0x%016" PRIx64, cpu64.x[17]) << "\n";
9470 outs() << "\t x18 " << format("0x%016" PRIx64, cpu64.x[18]);
9471 outs() << " x19 " << format("0x%016" PRIx64, cpu64.x[19]);
9472 outs() << " x20 " << format("0x%016" PRIx64, cpu64.x[20]) << "\n";
9473 outs() << "\t x21 " << format("0x%016" PRIx64, cpu64.x[21]);
9474 outs() << " x22 " << format("0x%016" PRIx64, cpu64.x[22]);
9475 outs() << " x23 " << format("0x%016" PRIx64, cpu64.x[23]) << "\n";
9476 outs() << "\t x24 " << format("0x%016" PRIx64, cpu64.x[24]);
9477 outs() << " x25 " << format("0x%016" PRIx64, cpu64.x[25]);
9478 outs() << " x26 " << format("0x%016" PRIx64, cpu64.x[26]) << "\n";
9479 outs() << "\t x27 " << format("0x%016" PRIx64, cpu64.x[27]);
9480 outs() << " x28 " << format("0x%016" PRIx64, cpu64.x[28]);
9481 outs() << " fp " << format("0x%016" PRIx64, cpu64.fp) << "\n";
9482 outs() << "\t lr " << format("0x%016" PRIx64, cpu64.lr);
9483 outs() << " sp " << format("0x%016" PRIx64, cpu64.sp);
9484 outs() << " pc " << format("0x%016" PRIx64, cpu64.pc) << "\n";
9485 outs() << "\t cpsr " << format("0x%08" PRIx32, cpu64.cpsr) << "\n";
9488 static void PrintThreadCommand(MachO::thread_command t, const char *Ptr,
9489 bool isLittleEndian, uint32_t cputype) {
9490 if (t.cmd == MachO::LC_THREAD)
9491 outs() << " cmd LC_THREAD\n";
9492 else if (t.cmd == MachO::LC_UNIXTHREAD)
9493 outs() << " cmd LC_UNIXTHREAD\n";
9495 outs() << " cmd " << t.cmd << " (unknown)\n";
9496 outs() << " cmdsize " << t.cmdsize;
9497 if (t.cmdsize < sizeof(struct MachO::thread_command) + 2 * sizeof(uint32_t))
9498 outs() << " Incorrect size\n";
9502 const char *begin = Ptr + sizeof(struct MachO::thread_command);
9503 const char *end = Ptr + t.cmdsize;
9504 uint32_t flavor, count, left;
9505 if (cputype == MachO::CPU_TYPE_I386) {
9506 while (begin < end) {
9507 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9508 memcpy((char *)&flavor, begin, sizeof(uint32_t));
9509 begin += sizeof(uint32_t);
9514 if (isLittleEndian != sys::IsLittleEndianHost)
9515 sys::swapByteOrder(flavor);
9516 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9517 memcpy((char *)&count, begin, sizeof(uint32_t));
9518 begin += sizeof(uint32_t);
9523 if (isLittleEndian != sys::IsLittleEndianHost)
9524 sys::swapByteOrder(count);
9525 if (flavor == MachO::x86_THREAD_STATE32) {
9526 outs() << " flavor i386_THREAD_STATE\n";
9527 if (count == MachO::x86_THREAD_STATE32_COUNT)
9528 outs() << " count i386_THREAD_STATE_COUNT\n";
9530 outs() << " count " << count
9531 << " (not x86_THREAD_STATE32_COUNT)\n";
9532 MachO::x86_thread_state32_t cpu32;
9534 if (left >= sizeof(MachO::x86_thread_state32_t)) {
9535 memcpy(&cpu32, begin, sizeof(MachO::x86_thread_state32_t));
9536 begin += sizeof(MachO::x86_thread_state32_t);
9538 memset(&cpu32, '\0', sizeof(MachO::x86_thread_state32_t));
9539 memcpy(&cpu32, begin, left);
9542 if (isLittleEndian != sys::IsLittleEndianHost)
9544 Print_x86_thread_state32_t(cpu32);
9545 } else if (flavor == MachO::x86_THREAD_STATE) {
9546 outs() << " flavor x86_THREAD_STATE\n";
9547 if (count == MachO::x86_THREAD_STATE_COUNT)
9548 outs() << " count x86_THREAD_STATE_COUNT\n";
9550 outs() << " count " << count
9551 << " (not x86_THREAD_STATE_COUNT)\n";
9552 struct MachO::x86_thread_state_t ts;
9554 if (left >= sizeof(MachO::x86_thread_state_t)) {
9555 memcpy(&ts, begin, sizeof(MachO::x86_thread_state_t));
9556 begin += sizeof(MachO::x86_thread_state_t);
9558 memset(&ts, '\0', sizeof(MachO::x86_thread_state_t));
9559 memcpy(&ts, begin, left);
9562 if (isLittleEndian != sys::IsLittleEndianHost)
9564 if (ts.tsh.flavor == MachO::x86_THREAD_STATE32) {
9565 outs() << "\t tsh.flavor x86_THREAD_STATE32 ";
9566 if (ts.tsh.count == MachO::x86_THREAD_STATE32_COUNT)
9567 outs() << "tsh.count x86_THREAD_STATE32_COUNT\n";
9569 outs() << "tsh.count " << ts.tsh.count
9570 << " (not x86_THREAD_STATE32_COUNT\n";
9571 Print_x86_thread_state32_t(ts.uts.ts32);
9573 outs() << "\t tsh.flavor " << ts.tsh.flavor << " tsh.count "
9574 << ts.tsh.count << "\n";
9577 outs() << " flavor " << flavor << " (unknown)\n";
9578 outs() << " count " << count << "\n";
9579 outs() << " state (unknown)\n";
9580 begin += count * sizeof(uint32_t);
9583 } else if (cputype == MachO::CPU_TYPE_X86_64) {
9584 while (begin < end) {
9585 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9586 memcpy((char *)&flavor, begin, sizeof(uint32_t));
9587 begin += sizeof(uint32_t);
9592 if (isLittleEndian != sys::IsLittleEndianHost)
9593 sys::swapByteOrder(flavor);
9594 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9595 memcpy((char *)&count, begin, sizeof(uint32_t));
9596 begin += sizeof(uint32_t);
9601 if (isLittleEndian != sys::IsLittleEndianHost)
9602 sys::swapByteOrder(count);
9603 if (flavor == MachO::x86_THREAD_STATE64) {
9604 outs() << " flavor x86_THREAD_STATE64\n";
9605 if (count == MachO::x86_THREAD_STATE64_COUNT)
9606 outs() << " count x86_THREAD_STATE64_COUNT\n";
9608 outs() << " count " << count
9609 << " (not x86_THREAD_STATE64_COUNT)\n";
9610 MachO::x86_thread_state64_t cpu64;
9612 if (left >= sizeof(MachO::x86_thread_state64_t)) {
9613 memcpy(&cpu64, begin, sizeof(MachO::x86_thread_state64_t));
9614 begin += sizeof(MachO::x86_thread_state64_t);
9616 memset(&cpu64, '\0', sizeof(MachO::x86_thread_state64_t));
9617 memcpy(&cpu64, begin, left);
9620 if (isLittleEndian != sys::IsLittleEndianHost)
9622 Print_x86_thread_state64_t(cpu64);
9623 } else if (flavor == MachO::x86_THREAD_STATE) {
9624 outs() << " flavor x86_THREAD_STATE\n";
9625 if (count == MachO::x86_THREAD_STATE_COUNT)
9626 outs() << " count x86_THREAD_STATE_COUNT\n";
9628 outs() << " count " << count
9629 << " (not x86_THREAD_STATE_COUNT)\n";
9630 struct MachO::x86_thread_state_t ts;
9632 if (left >= sizeof(MachO::x86_thread_state_t)) {
9633 memcpy(&ts, begin, sizeof(MachO::x86_thread_state_t));
9634 begin += sizeof(MachO::x86_thread_state_t);
9636 memset(&ts, '\0', sizeof(MachO::x86_thread_state_t));
9637 memcpy(&ts, begin, left);
9640 if (isLittleEndian != sys::IsLittleEndianHost)
9642 if (ts.tsh.flavor == MachO::x86_THREAD_STATE64) {
9643 outs() << "\t tsh.flavor x86_THREAD_STATE64 ";
9644 if (ts.tsh.count == MachO::x86_THREAD_STATE64_COUNT)
9645 outs() << "tsh.count x86_THREAD_STATE64_COUNT\n";
9647 outs() << "tsh.count " << ts.tsh.count
9648 << " (not x86_THREAD_STATE64_COUNT\n";
9649 Print_x86_thread_state64_t(ts.uts.ts64);
9651 outs() << "\t tsh.flavor " << ts.tsh.flavor << " tsh.count "
9652 << ts.tsh.count << "\n";
9654 } else if (flavor == MachO::x86_FLOAT_STATE) {
9655 outs() << " flavor x86_FLOAT_STATE\n";
9656 if (count == MachO::x86_FLOAT_STATE_COUNT)
9657 outs() << " count x86_FLOAT_STATE_COUNT\n";
9659 outs() << " count " << count << " (not x86_FLOAT_STATE_COUNT)\n";
9660 struct MachO::x86_float_state_t fs;
9662 if (left >= sizeof(MachO::x86_float_state_t)) {
9663 memcpy(&fs, begin, sizeof(MachO::x86_float_state_t));
9664 begin += sizeof(MachO::x86_float_state_t);
9666 memset(&fs, '\0', sizeof(MachO::x86_float_state_t));
9667 memcpy(&fs, begin, left);
9670 if (isLittleEndian != sys::IsLittleEndianHost)
9672 if (fs.fsh.flavor == MachO::x86_FLOAT_STATE64) {
9673 outs() << "\t fsh.flavor x86_FLOAT_STATE64 ";
9674 if (fs.fsh.count == MachO::x86_FLOAT_STATE64_COUNT)
9675 outs() << "fsh.count x86_FLOAT_STATE64_COUNT\n";
9677 outs() << "fsh.count " << fs.fsh.count
9678 << " (not x86_FLOAT_STATE64_COUNT\n";
9679 Print_x86_float_state_t(fs.ufs.fs64);
9681 outs() << "\t fsh.flavor " << fs.fsh.flavor << " fsh.count "
9682 << fs.fsh.count << "\n";
9684 } else if (flavor == MachO::x86_EXCEPTION_STATE) {
9685 outs() << " flavor x86_EXCEPTION_STATE\n";
9686 if (count == MachO::x86_EXCEPTION_STATE_COUNT)
9687 outs() << " count x86_EXCEPTION_STATE_COUNT\n";
9689 outs() << " count " << count
9690 << " (not x86_EXCEPTION_STATE_COUNT)\n";
9691 struct MachO::x86_exception_state_t es;
9693 if (left >= sizeof(MachO::x86_exception_state_t)) {
9694 memcpy(&es, begin, sizeof(MachO::x86_exception_state_t));
9695 begin += sizeof(MachO::x86_exception_state_t);
9697 memset(&es, '\0', sizeof(MachO::x86_exception_state_t));
9698 memcpy(&es, begin, left);
9701 if (isLittleEndian != sys::IsLittleEndianHost)
9703 if (es.esh.flavor == MachO::x86_EXCEPTION_STATE64) {
9704 outs() << "\t esh.flavor x86_EXCEPTION_STATE64\n";
9705 if (es.esh.count == MachO::x86_EXCEPTION_STATE64_COUNT)
9706 outs() << "\t esh.count x86_EXCEPTION_STATE64_COUNT\n";
9708 outs() << "\t esh.count " << es.esh.count
9709 << " (not x86_EXCEPTION_STATE64_COUNT\n";
9710 Print_x86_exception_state_t(es.ues.es64);
9712 outs() << "\t esh.flavor " << es.esh.flavor << " esh.count "
9713 << es.esh.count << "\n";
9715 } else if (flavor == MachO::x86_EXCEPTION_STATE64) {
9716 outs() << " flavor x86_EXCEPTION_STATE64\n";
9717 if (count == MachO::x86_EXCEPTION_STATE64_COUNT)
9718 outs() << " count x86_EXCEPTION_STATE64_COUNT\n";
9720 outs() << " count " << count
9721 << " (not x86_EXCEPTION_STATE64_COUNT)\n";
9722 struct MachO::x86_exception_state64_t es64;
9724 if (left >= sizeof(MachO::x86_exception_state64_t)) {
9725 memcpy(&es64, begin, sizeof(MachO::x86_exception_state64_t));
9726 begin += sizeof(MachO::x86_exception_state64_t);
9728 memset(&es64, '\0', sizeof(MachO::x86_exception_state64_t));
9729 memcpy(&es64, begin, left);
9732 if (isLittleEndian != sys::IsLittleEndianHost)
9734 Print_x86_exception_state_t(es64);
9736 outs() << " flavor " << flavor << " (unknown)\n";
9737 outs() << " count " << count << "\n";
9738 outs() << " state (unknown)\n";
9739 begin += count * sizeof(uint32_t);
9742 } else if (cputype == MachO::CPU_TYPE_ARM) {
9743 while (begin < end) {
9744 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9745 memcpy((char *)&flavor, begin, sizeof(uint32_t));
9746 begin += sizeof(uint32_t);
9751 if (isLittleEndian != sys::IsLittleEndianHost)
9752 sys::swapByteOrder(flavor);
9753 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9754 memcpy((char *)&count, begin, sizeof(uint32_t));
9755 begin += sizeof(uint32_t);
9760 if (isLittleEndian != sys::IsLittleEndianHost)
9761 sys::swapByteOrder(count);
9762 if (flavor == MachO::ARM_THREAD_STATE) {
9763 outs() << " flavor ARM_THREAD_STATE\n";
9764 if (count == MachO::ARM_THREAD_STATE_COUNT)
9765 outs() << " count ARM_THREAD_STATE_COUNT\n";
9767 outs() << " count " << count
9768 << " (not ARM_THREAD_STATE_COUNT)\n";
9769 MachO::arm_thread_state32_t cpu32;
9771 if (left >= sizeof(MachO::arm_thread_state32_t)) {
9772 memcpy(&cpu32, begin, sizeof(MachO::arm_thread_state32_t));
9773 begin += sizeof(MachO::arm_thread_state32_t);
9775 memset(&cpu32, '\0', sizeof(MachO::arm_thread_state32_t));
9776 memcpy(&cpu32, begin, left);
9779 if (isLittleEndian != sys::IsLittleEndianHost)
9781 Print_arm_thread_state32_t(cpu32);
9783 outs() << " flavor " << flavor << " (unknown)\n";
9784 outs() << " count " << count << "\n";
9785 outs() << " state (unknown)\n";
9786 begin += count * sizeof(uint32_t);
9789 } else if (cputype == MachO::CPU_TYPE_ARM64 ||
9790 cputype == MachO::CPU_TYPE_ARM64_32) {
9791 while (begin < end) {
9792 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9793 memcpy((char *)&flavor, begin, sizeof(uint32_t));
9794 begin += sizeof(uint32_t);
9799 if (isLittleEndian != sys::IsLittleEndianHost)
9800 sys::swapByteOrder(flavor);
9801 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9802 memcpy((char *)&count, begin, sizeof(uint32_t));
9803 begin += sizeof(uint32_t);
9808 if (isLittleEndian != sys::IsLittleEndianHost)
9809 sys::swapByteOrder(count);
9810 if (flavor == MachO::ARM_THREAD_STATE64) {
9811 outs() << " flavor ARM_THREAD_STATE64\n";
9812 if (count == MachO::ARM_THREAD_STATE64_COUNT)
9813 outs() << " count ARM_THREAD_STATE64_COUNT\n";
9815 outs() << " count " << count
9816 << " (not ARM_THREAD_STATE64_COUNT)\n";
9817 MachO::arm_thread_state64_t cpu64;
9819 if (left >= sizeof(MachO::arm_thread_state64_t)) {
9820 memcpy(&cpu64, begin, sizeof(MachO::arm_thread_state64_t));
9821 begin += sizeof(MachO::arm_thread_state64_t);
9823 memset(&cpu64, '\0', sizeof(MachO::arm_thread_state64_t));
9824 memcpy(&cpu64, begin, left);
9827 if (isLittleEndian != sys::IsLittleEndianHost)
9829 Print_arm_thread_state64_t(cpu64);
9831 outs() << " flavor " << flavor << " (unknown)\n";
9832 outs() << " count " << count << "\n";
9833 outs() << " state (unknown)\n";
9834 begin += count * sizeof(uint32_t);
9838 while (begin < end) {
9839 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9840 memcpy((char *)&flavor, begin, sizeof(uint32_t));
9841 begin += sizeof(uint32_t);
9846 if (isLittleEndian != sys::IsLittleEndianHost)
9847 sys::swapByteOrder(flavor);
9848 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9849 memcpy((char *)&count, begin, sizeof(uint32_t));
9850 begin += sizeof(uint32_t);
9855 if (isLittleEndian != sys::IsLittleEndianHost)
9856 sys::swapByteOrder(count);
9857 outs() << " flavor " << flavor << "\n";
9858 outs() << " count " << count << "\n";
9859 outs() << " state (Unknown cputype/cpusubtype)\n";
9860 begin += count * sizeof(uint32_t);
9865 static void PrintDylibCommand(MachO::dylib_command dl, const char *Ptr) {
9866 if (dl.cmd == MachO::LC_ID_DYLIB)
9867 outs() << " cmd LC_ID_DYLIB\n";
9868 else if (dl.cmd == MachO::LC_LOAD_DYLIB)
9869 outs() << " cmd LC_LOAD_DYLIB\n";
9870 else if (dl.cmd == MachO::LC_LOAD_WEAK_DYLIB)
9871 outs() << " cmd LC_LOAD_WEAK_DYLIB\n";
9872 else if (dl.cmd == MachO::LC_REEXPORT_DYLIB)
9873 outs() << " cmd LC_REEXPORT_DYLIB\n";
9874 else if (dl.cmd == MachO::LC_LAZY_LOAD_DYLIB)
9875 outs() << " cmd LC_LAZY_LOAD_DYLIB\n";
9876 else if (dl.cmd == MachO::LC_LOAD_UPWARD_DYLIB)
9877 outs() << " cmd LC_LOAD_UPWARD_DYLIB\n";
9879 outs() << " cmd " << dl.cmd << " (unknown)\n";
9880 outs() << " cmdsize " << dl.cmdsize;
9881 if (dl.cmdsize < sizeof(struct MachO::dylib_command))
9882 outs() << " Incorrect size\n";
9885 if (dl.dylib.name < dl.cmdsize) {
9886 const char *P = (const char *)(Ptr) + dl.dylib.name;
9887 outs() << " name " << P << " (offset " << dl.dylib.name << ")\n";
9889 outs() << " name ?(bad offset " << dl.dylib.name << ")\n";
9891 outs() << " time stamp " << dl.dylib.timestamp << " ";
9892 time_t t = dl.dylib.timestamp;
9893 outs() << ctime(&t);
9894 outs() << " current version ";
9895 if (dl.dylib.current_version == 0xffffffff)
9898 outs() << ((dl.dylib.current_version >> 16) & 0xffff) << "."
9899 << ((dl.dylib.current_version >> 8) & 0xff) << "."
9900 << (dl.dylib.current_version & 0xff) << "\n";
9901 outs() << "compatibility version ";
9902 if (dl.dylib.compatibility_version == 0xffffffff)
9905 outs() << ((dl.dylib.compatibility_version >> 16) & 0xffff) << "."
9906 << ((dl.dylib.compatibility_version >> 8) & 0xff) << "."
9907 << (dl.dylib.compatibility_version & 0xff) << "\n";
9910 static void PrintLinkEditDataCommand(MachO::linkedit_data_command ld,
9911 uint32_t object_size) {
9912 if (ld.cmd == MachO::LC_CODE_SIGNATURE)
9913 outs() << " cmd LC_CODE_SIGNATURE\n";
9914 else if (ld.cmd == MachO::LC_SEGMENT_SPLIT_INFO)
9915 outs() << " cmd LC_SEGMENT_SPLIT_INFO\n";
9916 else if (ld.cmd == MachO::LC_FUNCTION_STARTS)
9917 outs() << " cmd LC_FUNCTION_STARTS\n";
9918 else if (ld.cmd == MachO::LC_DATA_IN_CODE)
9919 outs() << " cmd LC_DATA_IN_CODE\n";
9920 else if (ld.cmd == MachO::LC_DYLIB_CODE_SIGN_DRS)
9921 outs() << " cmd LC_DYLIB_CODE_SIGN_DRS\n";
9922 else if (ld.cmd == MachO::LC_LINKER_OPTIMIZATION_HINT)
9923 outs() << " cmd LC_LINKER_OPTIMIZATION_HINT\n";
9925 outs() << " cmd " << ld.cmd << " (?)\n";
9926 outs() << " cmdsize " << ld.cmdsize;
9927 if (ld.cmdsize != sizeof(struct MachO::linkedit_data_command))
9928 outs() << " Incorrect size\n";
9931 outs() << " dataoff " << ld.dataoff;
9932 if (ld.dataoff > object_size)
9933 outs() << " (past end of file)\n";
9936 outs() << " datasize " << ld.datasize;
9937 uint64_t big_size = ld.dataoff;
9938 big_size += ld.datasize;
9939 if (big_size > object_size)
9940 outs() << " (past end of file)\n";
9945 static void PrintLoadCommands(const MachOObjectFile *Obj, uint32_t filetype,
9946 uint32_t cputype, bool verbose) {
9947 StringRef Buf = Obj->getData();
9949 for (const auto &Command : Obj->load_commands()) {
9950 outs() << "Load command " << Index++ << "\n";
9951 if (Command.C.cmd == MachO::LC_SEGMENT) {
9952 MachO::segment_command SLC = Obj->getSegmentLoadCommand(Command);
9953 const char *sg_segname = SLC.segname;
9954 PrintSegmentCommand(SLC.cmd, SLC.cmdsize, SLC.segname, SLC.vmaddr,
9955 SLC.vmsize, SLC.fileoff, SLC.filesize, SLC.maxprot,
9956 SLC.initprot, SLC.nsects, SLC.flags, Buf.size(),
9958 for (unsigned j = 0; j < SLC.nsects; j++) {
9959 MachO::section S = Obj->getSection(Command, j);
9960 PrintSection(S.sectname, S.segname, S.addr, S.size, S.offset, S.align,
9961 S.reloff, S.nreloc, S.flags, S.reserved1, S.reserved2,
9962 SLC.cmd, sg_segname, filetype, Buf.size(), verbose);
9964 } else if (Command.C.cmd == MachO::LC_SEGMENT_64) {
9965 MachO::segment_command_64 SLC_64 = Obj->getSegment64LoadCommand(Command);
9966 const char *sg_segname = SLC_64.segname;
9967 PrintSegmentCommand(SLC_64.cmd, SLC_64.cmdsize, SLC_64.segname,
9968 SLC_64.vmaddr, SLC_64.vmsize, SLC_64.fileoff,
9969 SLC_64.filesize, SLC_64.maxprot, SLC_64.initprot,
9970 SLC_64.nsects, SLC_64.flags, Buf.size(), verbose);
9971 for (unsigned j = 0; j < SLC_64.nsects; j++) {
9972 MachO::section_64 S_64 = Obj->getSection64(Command, j);
9973 PrintSection(S_64.sectname, S_64.segname, S_64.addr, S_64.size,
9974 S_64.offset, S_64.align, S_64.reloff, S_64.nreloc,
9975 S_64.flags, S_64.reserved1, S_64.reserved2, SLC_64.cmd,
9976 sg_segname, filetype, Buf.size(), verbose);
9978 } else if (Command.C.cmd == MachO::LC_SYMTAB) {
9979 MachO::symtab_command Symtab = Obj->getSymtabLoadCommand();
9980 PrintSymtabLoadCommand(Symtab, Obj->is64Bit(), Buf.size());
9981 } else if (Command.C.cmd == MachO::LC_DYSYMTAB) {
9982 MachO::dysymtab_command Dysymtab = Obj->getDysymtabLoadCommand();
9983 MachO::symtab_command Symtab = Obj->getSymtabLoadCommand();
9984 PrintDysymtabLoadCommand(Dysymtab, Symtab.nsyms, Buf.size(),
9986 } else if (Command.C.cmd == MachO::LC_DYLD_INFO ||
9987 Command.C.cmd == MachO::LC_DYLD_INFO_ONLY) {
9988 MachO::dyld_info_command DyldInfo = Obj->getDyldInfoLoadCommand(Command);
9989 PrintDyldInfoLoadCommand(DyldInfo, Buf.size());
9990 } else if (Command.C.cmd == MachO::LC_LOAD_DYLINKER ||
9991 Command.C.cmd == MachO::LC_ID_DYLINKER ||
9992 Command.C.cmd == MachO::LC_DYLD_ENVIRONMENT) {
9993 MachO::dylinker_command Dyld = Obj->getDylinkerCommand(Command);
9994 PrintDyldLoadCommand(Dyld, Command.Ptr);
9995 } else if (Command.C.cmd == MachO::LC_UUID) {
9996 MachO::uuid_command Uuid = Obj->getUuidCommand(Command);
9997 PrintUuidLoadCommand(Uuid);
9998 } else if (Command.C.cmd == MachO::LC_RPATH) {
9999 MachO::rpath_command Rpath = Obj->getRpathCommand(Command);
10000 PrintRpathLoadCommand(Rpath, Command.Ptr);
10001 } else if (Command.C.cmd == MachO::LC_VERSION_MIN_MACOSX ||
10002 Command.C.cmd == MachO::LC_VERSION_MIN_IPHONEOS ||
10003 Command.C.cmd == MachO::LC_VERSION_MIN_TVOS ||
10004 Command.C.cmd == MachO::LC_VERSION_MIN_WATCHOS) {
10005 MachO::version_min_command Vd = Obj->getVersionMinLoadCommand(Command);
10006 PrintVersionMinLoadCommand(Vd);
10007 } else if (Command.C.cmd == MachO::LC_NOTE) {
10008 MachO::note_command Nt = Obj->getNoteLoadCommand(Command);
10009 PrintNoteLoadCommand(Nt);
10010 } else if (Command.C.cmd == MachO::LC_BUILD_VERSION) {
10011 MachO::build_version_command Bv =
10012 Obj->getBuildVersionLoadCommand(Command);
10013 PrintBuildVersionLoadCommand(Obj, Bv);
10014 } else if (Command.C.cmd == MachO::LC_SOURCE_VERSION) {
10015 MachO::source_version_command Sd = Obj->getSourceVersionCommand(Command);
10016 PrintSourceVersionCommand(Sd);
10017 } else if (Command.C.cmd == MachO::LC_MAIN) {
10018 MachO::entry_point_command Ep = Obj->getEntryPointCommand(Command);
10019 PrintEntryPointCommand(Ep);
10020 } else if (Command.C.cmd == MachO::LC_ENCRYPTION_INFO) {
10021 MachO::encryption_info_command Ei =
10022 Obj->getEncryptionInfoCommand(Command);
10023 PrintEncryptionInfoCommand(Ei, Buf.size());
10024 } else if (Command.C.cmd == MachO::LC_ENCRYPTION_INFO_64) {
10025 MachO::encryption_info_command_64 Ei =
10026 Obj->getEncryptionInfoCommand64(Command);
10027 PrintEncryptionInfoCommand64(Ei, Buf.size());
10028 } else if (Command.C.cmd == MachO::LC_LINKER_OPTION) {
10029 MachO::linker_option_command Lo =
10030 Obj->getLinkerOptionLoadCommand(Command);
10031 PrintLinkerOptionCommand(Lo, Command.Ptr);
10032 } else if (Command.C.cmd == MachO::LC_SUB_FRAMEWORK) {
10033 MachO::sub_framework_command Sf = Obj->getSubFrameworkCommand(Command);
10034 PrintSubFrameworkCommand(Sf, Command.Ptr);
10035 } else if (Command.C.cmd == MachO::LC_SUB_UMBRELLA) {
10036 MachO::sub_umbrella_command Sf = Obj->getSubUmbrellaCommand(Command);
10037 PrintSubUmbrellaCommand(Sf, Command.Ptr);
10038 } else if (Command.C.cmd == MachO::LC_SUB_LIBRARY) {
10039 MachO::sub_library_command Sl = Obj->getSubLibraryCommand(Command);
10040 PrintSubLibraryCommand(Sl, Command.Ptr);
10041 } else if (Command.C.cmd == MachO::LC_SUB_CLIENT) {
10042 MachO::sub_client_command Sc = Obj->getSubClientCommand(Command);
10043 PrintSubClientCommand(Sc, Command.Ptr);
10044 } else if (Command.C.cmd == MachO::LC_ROUTINES) {
10045 MachO::routines_command Rc = Obj->getRoutinesCommand(Command);
10046 PrintRoutinesCommand(Rc);
10047 } else if (Command.C.cmd == MachO::LC_ROUTINES_64) {
10048 MachO::routines_command_64 Rc = Obj->getRoutinesCommand64(Command);
10049 PrintRoutinesCommand64(Rc);
10050 } else if (Command.C.cmd == MachO::LC_THREAD ||
10051 Command.C.cmd == MachO::LC_UNIXTHREAD) {
10052 MachO::thread_command Tc = Obj->getThreadCommand(Command);
10053 PrintThreadCommand(Tc, Command.Ptr, Obj->isLittleEndian(), cputype);
10054 } else if (Command.C.cmd == MachO::LC_LOAD_DYLIB ||
10055 Command.C.cmd == MachO::LC_ID_DYLIB ||
10056 Command.C.cmd == MachO::LC_LOAD_WEAK_DYLIB ||
10057 Command.C.cmd == MachO::LC_REEXPORT_DYLIB ||
10058 Command.C.cmd == MachO::LC_LAZY_LOAD_DYLIB ||
10059 Command.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB) {
10060 MachO::dylib_command Dl = Obj->getDylibIDLoadCommand(Command);
10061 PrintDylibCommand(Dl, Command.Ptr);
10062 } else if (Command.C.cmd == MachO::LC_CODE_SIGNATURE ||
10063 Command.C.cmd == MachO::LC_SEGMENT_SPLIT_INFO ||
10064 Command.C.cmd == MachO::LC_FUNCTION_STARTS ||
10065 Command.C.cmd == MachO::LC_DATA_IN_CODE ||
10066 Command.C.cmd == MachO::LC_DYLIB_CODE_SIGN_DRS ||
10067 Command.C.cmd == MachO::LC_LINKER_OPTIMIZATION_HINT) {
10068 MachO::linkedit_data_command Ld =
10069 Obj->getLinkeditDataLoadCommand(Command);
10070 PrintLinkEditDataCommand(Ld, Buf.size());
10072 outs() << " cmd ?(" << format("0x%08" PRIx32, Command.C.cmd)
10074 outs() << " cmdsize " << Command.C.cmdsize << "\n";
10075 // TODO: get and print the raw bytes of the load command.
10077 // TODO: print all the other kinds of load commands.
10081 static void PrintMachHeader(const MachOObjectFile *Obj, bool verbose) {
10082 if (Obj->is64Bit()) {
10083 MachO::mach_header_64 H_64;
10084 H_64 = Obj->getHeader64();
10085 PrintMachHeader(H_64.magic, H_64.cputype, H_64.cpusubtype, H_64.filetype,
10086 H_64.ncmds, H_64.sizeofcmds, H_64.flags, verbose);
10088 MachO::mach_header H;
10089 H = Obj->getHeader();
10090 PrintMachHeader(H.magic, H.cputype, H.cpusubtype, H.filetype, H.ncmds,
10091 H.sizeofcmds, H.flags, verbose);
10095 void printMachOFileHeader(const object::ObjectFile *Obj) {
10096 const MachOObjectFile *file = dyn_cast<const MachOObjectFile>(Obj);
10097 PrintMachHeader(file, !NonVerbose);
10100 void printMachOLoadCommands(const object::ObjectFile *Obj) {
10101 const MachOObjectFile *file = dyn_cast<const MachOObjectFile>(Obj);
10102 uint32_t filetype = 0;
10103 uint32_t cputype = 0;
10104 if (file->is64Bit()) {
10105 MachO::mach_header_64 H_64;
10106 H_64 = file->getHeader64();
10107 filetype = H_64.filetype;
10108 cputype = H_64.cputype;
10110 MachO::mach_header H;
10111 H = file->getHeader();
10112 filetype = H.filetype;
10113 cputype = H.cputype;
10115 PrintLoadCommands(file, filetype, cputype, !NonVerbose);
10118 //===----------------------------------------------------------------------===//
10119 // export trie dumping
10120 //===----------------------------------------------------------------------===//
10122 void printMachOExportsTrie(const object::MachOObjectFile *Obj) {
10123 uint64_t BaseSegmentAddress = 0;
10124 for (const auto &Command : Obj->load_commands()) {
10125 if (Command.C.cmd == MachO::LC_SEGMENT) {
10126 MachO::segment_command Seg = Obj->getSegmentLoadCommand(Command);
10127 if (Seg.fileoff == 0 && Seg.filesize != 0) {
10128 BaseSegmentAddress = Seg.vmaddr;
10131 } else if (Command.C.cmd == MachO::LC_SEGMENT_64) {
10132 MachO::segment_command_64 Seg = Obj->getSegment64LoadCommand(Command);
10133 if (Seg.fileoff == 0 && Seg.filesize != 0) {
10134 BaseSegmentAddress = Seg.vmaddr;
10139 Error Err = Error::success();
10140 for (const object::ExportEntry &Entry : Obj->exports(Err)) {
10141 uint64_t Flags = Entry.flags();
10142 bool ReExport = (Flags & MachO::EXPORT_SYMBOL_FLAGS_REEXPORT);
10143 bool WeakDef = (Flags & MachO::EXPORT_SYMBOL_FLAGS_WEAK_DEFINITION);
10144 bool ThreadLocal = ((Flags & MachO::EXPORT_SYMBOL_FLAGS_KIND_MASK) ==
10145 MachO::EXPORT_SYMBOL_FLAGS_KIND_THREAD_LOCAL);
10146 bool Abs = ((Flags & MachO::EXPORT_SYMBOL_FLAGS_KIND_MASK) ==
10147 MachO::EXPORT_SYMBOL_FLAGS_KIND_ABSOLUTE);
10148 bool Resolver = (Flags & MachO::EXPORT_SYMBOL_FLAGS_STUB_AND_RESOLVER);
10150 outs() << "[re-export] ";
10152 outs() << format("0x%08llX ",
10153 Entry.address() + BaseSegmentAddress);
10154 outs() << Entry.name();
10155 if (WeakDef || ThreadLocal || Resolver || Abs) {
10156 bool NeedsComma = false;
10159 outs() << "weak_def";
10165 outs() << "per-thread";
10171 outs() << "absolute";
10177 outs() << format("resolver=0x%08llX", Entry.other());
10183 StringRef DylibName = "unknown";
10184 int Ordinal = Entry.other() - 1;
10185 Obj->getLibraryShortNameByIndex(Ordinal, DylibName);
10186 if (Entry.otherName().empty())
10187 outs() << " (from " << DylibName << ")";
10189 outs() << " (" << Entry.otherName() << " from " << DylibName << ")";
10194 report_error(std::move(Err), Obj->getFileName());
10197 //===----------------------------------------------------------------------===//
10198 // rebase table dumping
10199 //===----------------------------------------------------------------------===//
10201 void printMachORebaseTable(object::MachOObjectFile *Obj) {
10202 outs() << "segment section address type\n";
10203 Error Err = Error::success();
10204 for (const object::MachORebaseEntry &Entry : Obj->rebaseTable(Err)) {
10205 StringRef SegmentName = Entry.segmentName();
10206 StringRef SectionName = Entry.sectionName();
10207 uint64_t Address = Entry.address();
10209 // Table lines look like: __DATA __nl_symbol_ptr 0x0000F00C pointer
10210 outs() << format("%-8s %-18s 0x%08" PRIX64 " %s\n",
10211 SegmentName.str().c_str(), SectionName.str().c_str(),
10212 Address, Entry.typeName().str().c_str());
10215 report_error(std::move(Err), Obj->getFileName());
10218 static StringRef ordinalName(const object::MachOObjectFile *Obj, int Ordinal) {
10219 StringRef DylibName;
10221 case MachO::BIND_SPECIAL_DYLIB_SELF:
10222 return "this-image";
10223 case MachO::BIND_SPECIAL_DYLIB_MAIN_EXECUTABLE:
10224 return "main-executable";
10225 case MachO::BIND_SPECIAL_DYLIB_FLAT_LOOKUP:
10226 return "flat-namespace";
10229 std::error_code EC =
10230 Obj->getLibraryShortNameByIndex(Ordinal - 1, DylibName);
10232 return "<<bad library ordinal>>";
10236 return "<<unknown special ordinal>>";
10239 //===----------------------------------------------------------------------===//
10240 // bind table dumping
10241 //===----------------------------------------------------------------------===//
10243 void printMachOBindTable(object::MachOObjectFile *Obj) {
10244 // Build table of sections so names can used in final output.
10245 outs() << "segment section address type "
10246 "addend dylib symbol\n";
10247 Error Err = Error::success();
10248 for (const object::MachOBindEntry &Entry : Obj->bindTable(Err)) {
10249 StringRef SegmentName = Entry.segmentName();
10250 StringRef SectionName = Entry.sectionName();
10251 uint64_t Address = Entry.address();
10253 // Table lines look like:
10254 // __DATA __got 0x00012010 pointer 0 libSystem ___stack_chk_guard
10256 if (Entry.flags() & MachO::BIND_SYMBOL_FLAGS_WEAK_IMPORT)
10257 Attr = " (weak_import)";
10258 outs() << left_justify(SegmentName, 8) << " "
10259 << left_justify(SectionName, 18) << " "
10260 << format_hex(Address, 10, true) << " "
10261 << left_justify(Entry.typeName(), 8) << " "
10262 << format_decimal(Entry.addend(), 8) << " "
10263 << left_justify(ordinalName(Obj, Entry.ordinal()), 16) << " "
10264 << Entry.symbolName() << Attr << "\n";
10267 report_error(std::move(Err), Obj->getFileName());
10270 //===----------------------------------------------------------------------===//
10271 // lazy bind table dumping
10272 //===----------------------------------------------------------------------===//
10274 void printMachOLazyBindTable(object::MachOObjectFile *Obj) {
10275 outs() << "segment section address "
10277 Error Err = Error::success();
10278 for (const object::MachOBindEntry &Entry : Obj->lazyBindTable(Err)) {
10279 StringRef SegmentName = Entry.segmentName();
10280 StringRef SectionName = Entry.sectionName();
10281 uint64_t Address = Entry.address();
10283 // Table lines look like:
10284 // __DATA __got 0x00012010 libSystem ___stack_chk_guard
10285 outs() << left_justify(SegmentName, 8) << " "
10286 << left_justify(SectionName, 18) << " "
10287 << format_hex(Address, 10, true) << " "
10288 << left_justify(ordinalName(Obj, Entry.ordinal()), 16) << " "
10289 << Entry.symbolName() << "\n";
10292 report_error(std::move(Err), Obj->getFileName());
10295 //===----------------------------------------------------------------------===//
10296 // weak bind table dumping
10297 //===----------------------------------------------------------------------===//
10299 void printMachOWeakBindTable(object::MachOObjectFile *Obj) {
10300 outs() << "segment section address "
10301 "type addend symbol\n";
10302 Error Err = Error::success();
10303 for (const object::MachOBindEntry &Entry : Obj->weakBindTable(Err)) {
10304 // Strong symbols don't have a location to update.
10305 if (Entry.flags() & MachO::BIND_SYMBOL_FLAGS_NON_WEAK_DEFINITION) {
10306 outs() << " strong "
10307 << Entry.symbolName() << "\n";
10310 StringRef SegmentName = Entry.segmentName();
10311 StringRef SectionName = Entry.sectionName();
10312 uint64_t Address = Entry.address();
10314 // Table lines look like:
10315 // __DATA __data 0x00001000 pointer 0 _foo
10316 outs() << left_justify(SegmentName, 8) << " "
10317 << left_justify(SectionName, 18) << " "
10318 << format_hex(Address, 10, true) << " "
10319 << left_justify(Entry.typeName(), 8) << " "
10320 << format_decimal(Entry.addend(), 8) << " " << Entry.symbolName()
10324 report_error(std::move(Err), Obj->getFileName());
10327 // get_dyld_bind_info_symbolname() is used for disassembly and passed an
10328 // address, ReferenceValue, in the Mach-O file and looks in the dyld bind
10329 // information for that address. If the address is found its binding symbol
10330 // name is returned. If not nullptr is returned.
10331 static const char *get_dyld_bind_info_symbolname(uint64_t ReferenceValue,
10332 struct DisassembleInfo *info) {
10333 if (info->bindtable == nullptr) {
10334 info->bindtable = llvm::make_unique<SymbolAddressMap>();
10335 Error Err = Error::success();
10336 for (const object::MachOBindEntry &Entry : info->O->bindTable(Err)) {
10337 uint64_t Address = Entry.address();
10338 StringRef name = Entry.symbolName();
10340 (*info->bindtable)[Address] = name;
10343 report_error(std::move(Err), info->O->getFileName());
10345 auto name = info->bindtable->lookup(ReferenceValue);
10346 return !name.empty() ? name.data() : nullptr;
10349 void printLazyBindTable(ObjectFile *o) {
10350 outs() << "Lazy bind table:\n";
10351 if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
10352 printMachOLazyBindTable(MachO);
10355 << "This operation is only currently supported "
10356 "for Mach-O executable files.\n";
10359 void printWeakBindTable(ObjectFile *o) {
10360 outs() << "Weak bind table:\n";
10361 if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
10362 printMachOWeakBindTable(MachO);
10365 << "This operation is only currently supported "
10366 "for Mach-O executable files.\n";
10369 void printExportsTrie(const ObjectFile *o) {
10370 outs() << "Exports trie:\n";
10371 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
10372 printMachOExportsTrie(MachO);
10375 << "This operation is only currently supported "
10376 "for Mach-O executable files.\n";
10379 void printRebaseTable(ObjectFile *o) {
10380 outs() << "Rebase table:\n";
10381 if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
10382 printMachORebaseTable(MachO);
10385 << "This operation is only currently supported "
10386 "for Mach-O executable files.\n";
10389 void printBindTable(ObjectFile *o) {
10390 outs() << "Bind table:\n";
10391 if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
10392 printMachOBindTable(MachO);
10395 << "This operation is only currently supported "
10396 "for Mach-O executable files.\n";
10398 } // namespace llvm