Clang] Fix expansion of response files in -Wp after integrated-cc1 change
[llvm-project.git] / llvm / tools / llvm-objdump / MachODump.cpp
blob87c7a92933f1d17bf0b4fc636c52fd4811eca1e6
1 //===-- MachODump.cpp - Object file dumping utility for llvm --------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements the MachO-specific dumper for llvm-objdump.
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/MC/MCTargetOptions.h"
33 #include "llvm/Object/MachO.h"
34 #include "llvm/Object/MachOUniversal.h"
35 #include "llvm/Support/Casting.h"
36 #include "llvm/Support/CommandLine.h"
37 #include "llvm/Support/Debug.h"
38 #include "llvm/Support/Endian.h"
39 #include "llvm/Support/Format.h"
40 #include "llvm/Support/FormattedStream.h"
41 #include "llvm/Support/GraphWriter.h"
42 #include "llvm/Support/LEB128.h"
43 #include "llvm/Support/MemoryBuffer.h"
44 #include "llvm/Support/TargetRegistry.h"
45 #include "llvm/Support/TargetSelect.h"
46 #include "llvm/Support/ToolOutputFile.h"
47 #include "llvm/Support/WithColor.h"
48 #include "llvm/Support/raw_ostream.h"
49 #include <algorithm>
50 #include <cstring>
51 #include <system_error>
53 #ifdef HAVE_LIBXAR
54 extern "C" {
55 #include <xar/xar.h>
57 #endif
59 using namespace llvm::object;
61 namespace llvm {
63 cl::OptionCategory MachOCat("llvm-objdump MachO Specific Options");
65 extern cl::opt<bool> ArchiveHeaders;
66 extern cl::opt<bool> Disassemble;
67 extern cl::opt<bool> DisassembleAll;
68 extern cl::opt<DIDumpType> DwarfDumpType;
69 extern cl::list<std::string> FilterSections;
70 extern cl::list<std::string> MAttrs;
71 extern cl::opt<std::string> MCPU;
72 extern cl::opt<bool> NoShowRawInsn;
73 extern cl::opt<bool> NoLeadingAddr;
74 extern cl::opt<bool> PrintImmHex;
75 extern cl::opt<bool> PrivateHeaders;
76 extern cl::opt<bool> Relocations;
77 extern cl::opt<bool> SectionHeaders;
78 extern cl::opt<bool> SectionContents;
79 extern cl::opt<bool> SymbolTable;
80 extern cl::opt<std::string> TripleName;
81 extern cl::opt<bool> UnwindInfo;
83 cl::opt<bool>
84 FirstPrivateHeader("private-header",
85 cl::desc("Display only the first format specific file "
86 "header"),
87 cl::cat(MachOCat));
89 cl::opt<bool> ExportsTrie("exports-trie",
90 cl::desc("Display mach-o exported symbols"),
91 cl::cat(MachOCat));
93 cl::opt<bool> Rebase("rebase", cl::desc("Display mach-o rebasing info"),
94 cl::cat(MachOCat));
96 cl::opt<bool> Bind("bind", cl::desc("Display mach-o binding info"),
97 cl::cat(MachOCat));
99 cl::opt<bool> LazyBind("lazy-bind",
100 cl::desc("Display mach-o lazy binding info"),
101 cl::cat(MachOCat));
103 cl::opt<bool> WeakBind("weak-bind",
104 cl::desc("Display mach-o weak binding info"),
105 cl::cat(MachOCat));
107 static cl::opt<bool>
108 UseDbg("g", cl::Grouping,
109 cl::desc("Print line information from debug info if available"),
110 cl::cat(MachOCat));
112 static cl::opt<std::string> DSYMFile("dsym",
113 cl::desc("Use .dSYM file for debug info"),
114 cl::cat(MachOCat));
116 static cl::opt<bool> FullLeadingAddr("full-leading-addr",
117 cl::desc("Print full leading address"),
118 cl::cat(MachOCat));
120 static cl::opt<bool> NoLeadingHeaders("no-leading-headers",
121 cl::desc("Print no leading headers"),
122 cl::cat(MachOCat));
124 cl::opt<bool> UniversalHeaders("universal-headers",
125 cl::desc("Print Mach-O universal headers "
126 "(requires -macho)"),
127 cl::cat(MachOCat));
129 cl::opt<bool>
130 ArchiveMemberOffsets("archive-member-offsets",
131 cl::desc("Print the offset to each archive member for "
132 "Mach-O archives (requires -macho and "
133 "-archive-headers)"),
134 cl::cat(MachOCat));
136 cl::opt<bool> IndirectSymbols("indirect-symbols",
137 cl::desc("Print indirect symbol table for Mach-O "
138 "objects (requires -macho)"),
139 cl::cat(MachOCat));
141 cl::opt<bool>
142 DataInCode("data-in-code",
143 cl::desc("Print the data in code table for Mach-O objects "
144 "(requires -macho)"),
145 cl::cat(MachOCat));
147 cl::opt<bool> LinkOptHints("link-opt-hints",
148 cl::desc("Print the linker optimization hints for "
149 "Mach-O objects (requires -macho)"),
150 cl::cat(MachOCat));
152 cl::opt<bool> InfoPlist("info-plist",
153 cl::desc("Print the info plist section as strings for "
154 "Mach-O objects (requires -macho)"),
155 cl::cat(MachOCat));
157 cl::opt<bool> DylibsUsed("dylibs-used",
158 cl::desc("Print the shared libraries used for linked "
159 "Mach-O files (requires -macho)"),
160 cl::cat(MachOCat));
162 cl::opt<bool>
163 DylibId("dylib-id",
164 cl::desc("Print the shared library's id for the dylib Mach-O "
165 "file (requires -macho)"),
166 cl::cat(MachOCat));
168 cl::opt<bool>
169 NonVerbose("non-verbose",
170 cl::desc("Print the info for Mach-O objects in "
171 "non-verbose or numeric form (requires -macho)"),
172 cl::cat(MachOCat));
174 cl::opt<bool>
175 ObjcMetaData("objc-meta-data",
176 cl::desc("Print the Objective-C runtime meta data for "
177 "Mach-O files (requires -macho)"),
178 cl::cat(MachOCat));
180 cl::opt<std::string> DisSymName(
181 "dis-symname",
182 cl::desc("disassemble just this symbol's instructions (requires -macho)"),
183 cl::cat(MachOCat));
185 static cl::opt<bool> NoSymbolicOperands(
186 "no-symbolic-operands",
187 cl::desc("do not symbolic operands when disassembling (requires -macho)"),
188 cl::cat(MachOCat));
190 static cl::list<std::string>
191 ArchFlags("arch", cl::desc("architecture(s) from a Mach-O file to dump"),
192 cl::ZeroOrMore, cl::cat(MachOCat));
194 bool ArchAll = false;
196 static std::string ThumbTripleName;
198 static const Target *GetTarget(const MachOObjectFile *MachOObj,
199 const char **McpuDefault,
200 const Target **ThumbTarget) {
201 // Figure out the target triple.
202 Triple TT(TripleName);
203 if (TripleName.empty()) {
204 TT = MachOObj->getArchTriple(McpuDefault);
205 TripleName = TT.str();
208 if (TT.getArch() == Triple::arm) {
209 // We've inferred a 32-bit ARM target from the object file. All MachO CPUs
210 // that support ARM are also capable of Thumb mode.
211 Triple ThumbTriple = TT;
212 std::string ThumbName = (Twine("thumb") + TT.getArchName().substr(3)).str();
213 ThumbTriple.setArchName(ThumbName);
214 ThumbTripleName = ThumbTriple.str();
217 // Get the target specific parser.
218 std::string Error;
219 const Target *TheTarget = TargetRegistry::lookupTarget(TripleName, Error);
220 if (TheTarget && ThumbTripleName.empty())
221 return TheTarget;
223 *ThumbTarget = TargetRegistry::lookupTarget(ThumbTripleName, Error);
224 if (*ThumbTarget)
225 return TheTarget;
227 WithColor::error(errs(), "llvm-objdump") << "unable to get target for '";
228 if (!TheTarget)
229 errs() << TripleName;
230 else
231 errs() << ThumbTripleName;
232 errs() << "', see --version and --triple.\n";
233 return nullptr;
236 struct SymbolSorter {
237 bool operator()(const SymbolRef &A, const SymbolRef &B) {
238 Expected<SymbolRef::Type> ATypeOrErr = A.getType();
239 if (!ATypeOrErr)
240 reportError(ATypeOrErr.takeError(), A.getObject()->getFileName());
241 SymbolRef::Type AType = *ATypeOrErr;
242 Expected<SymbolRef::Type> BTypeOrErr = B.getType();
243 if (!BTypeOrErr)
244 reportError(BTypeOrErr.takeError(), B.getObject()->getFileName());
245 SymbolRef::Type BType = *BTypeOrErr;
246 uint64_t AAddr = (AType != SymbolRef::ST_Function) ? 0 : A.getValue();
247 uint64_t BAddr = (BType != SymbolRef::ST_Function) ? 0 : B.getValue();
248 return AAddr < BAddr;
252 // Types for the storted data in code table that is built before disassembly
253 // and the predicate function to sort them.
254 typedef std::pair<uint64_t, DiceRef> DiceTableEntry;
255 typedef std::vector<DiceTableEntry> DiceTable;
256 typedef DiceTable::iterator dice_table_iterator;
258 #ifdef HAVE_LIBXAR
259 namespace {
260 struct ScopedXarFile {
261 xar_t xar;
262 ScopedXarFile(const char *filename, int32_t flags)
263 : xar(xar_open(filename, flags)) {}
264 ~ScopedXarFile() {
265 if (xar)
266 xar_close(xar);
268 ScopedXarFile(const ScopedXarFile &) = delete;
269 ScopedXarFile &operator=(const ScopedXarFile &) = delete;
270 operator xar_t() { return xar; }
273 struct ScopedXarIter {
274 xar_iter_t iter;
275 ScopedXarIter() : iter(xar_iter_new()) {}
276 ~ScopedXarIter() {
277 if (iter)
278 xar_iter_free(iter);
280 ScopedXarIter(const ScopedXarIter &) = delete;
281 ScopedXarIter &operator=(const ScopedXarIter &) = delete;
282 operator xar_iter_t() { return iter; }
284 } // namespace
285 #endif // defined(HAVE_LIBXAR)
287 // This is used to search for a data in code table entry for the PC being
288 // disassembled. The j parameter has the PC in j.first. A single data in code
289 // table entry can cover many bytes for each of its Kind's. So if the offset,
290 // aka the i.first value, of the data in code table entry plus its Length
291 // covers the PC being searched for this will return true. If not it will
292 // return false.
293 static bool compareDiceTableEntries(const DiceTableEntry &i,
294 const DiceTableEntry &j) {
295 uint16_t Length;
296 i.second.getLength(Length);
298 return j.first >= i.first && j.first < i.first + Length;
301 static uint64_t DumpDataInCode(const uint8_t *bytes, uint64_t Length,
302 unsigned short Kind) {
303 uint32_t Value, Size = 1;
305 switch (Kind) {
306 default:
307 case MachO::DICE_KIND_DATA:
308 if (Length >= 4) {
309 if (!NoShowRawInsn)
310 dumpBytes(makeArrayRef(bytes, 4), outs());
311 Value = bytes[3] << 24 | bytes[2] << 16 | bytes[1] << 8 | bytes[0];
312 outs() << "\t.long " << Value;
313 Size = 4;
314 } else if (Length >= 2) {
315 if (!NoShowRawInsn)
316 dumpBytes(makeArrayRef(bytes, 2), outs());
317 Value = bytes[1] << 8 | bytes[0];
318 outs() << "\t.short " << Value;
319 Size = 2;
320 } else {
321 if (!NoShowRawInsn)
322 dumpBytes(makeArrayRef(bytes, 2), outs());
323 Value = bytes[0];
324 outs() << "\t.byte " << Value;
325 Size = 1;
327 if (Kind == MachO::DICE_KIND_DATA)
328 outs() << "\t@ KIND_DATA\n";
329 else
330 outs() << "\t@ data in code kind = " << Kind << "\n";
331 break;
332 case MachO::DICE_KIND_JUMP_TABLE8:
333 if (!NoShowRawInsn)
334 dumpBytes(makeArrayRef(bytes, 1), outs());
335 Value = bytes[0];
336 outs() << "\t.byte " << format("%3u", Value) << "\t@ KIND_JUMP_TABLE8\n";
337 Size = 1;
338 break;
339 case MachO::DICE_KIND_JUMP_TABLE16:
340 if (!NoShowRawInsn)
341 dumpBytes(makeArrayRef(bytes, 2), outs());
342 Value = bytes[1] << 8 | bytes[0];
343 outs() << "\t.short " << format("%5u", Value & 0xffff)
344 << "\t@ KIND_JUMP_TABLE16\n";
345 Size = 2;
346 break;
347 case MachO::DICE_KIND_JUMP_TABLE32:
348 case MachO::DICE_KIND_ABS_JUMP_TABLE32:
349 if (!NoShowRawInsn)
350 dumpBytes(makeArrayRef(bytes, 4), outs());
351 Value = bytes[3] << 24 | bytes[2] << 16 | bytes[1] << 8 | bytes[0];
352 outs() << "\t.long " << Value;
353 if (Kind == MachO::DICE_KIND_JUMP_TABLE32)
354 outs() << "\t@ KIND_JUMP_TABLE32\n";
355 else
356 outs() << "\t@ KIND_ABS_JUMP_TABLE32\n";
357 Size = 4;
358 break;
360 return Size;
363 static void getSectionsAndSymbols(MachOObjectFile *MachOObj,
364 std::vector<SectionRef> &Sections,
365 std::vector<SymbolRef> &Symbols,
366 SmallVectorImpl<uint64_t> &FoundFns,
367 uint64_t &BaseSegmentAddress) {
368 const StringRef FileName = MachOObj->getFileName();
369 for (const SymbolRef &Symbol : MachOObj->symbols()) {
370 StringRef SymName = unwrapOrError(Symbol.getName(), FileName);
371 if (!SymName.startswith("ltmp"))
372 Symbols.push_back(Symbol);
375 for (const SectionRef &Section : MachOObj->sections())
376 Sections.push_back(Section);
378 bool BaseSegmentAddressSet = false;
379 for (const auto &Command : MachOObj->load_commands()) {
380 if (Command.C.cmd == MachO::LC_FUNCTION_STARTS) {
381 // We found a function starts segment, parse the addresses for later
382 // consumption.
383 MachO::linkedit_data_command LLC =
384 MachOObj->getLinkeditDataLoadCommand(Command);
386 MachOObj->ReadULEB128s(LLC.dataoff, FoundFns);
387 } else if (Command.C.cmd == MachO::LC_SEGMENT) {
388 MachO::segment_command SLC = MachOObj->getSegmentLoadCommand(Command);
389 StringRef SegName = SLC.segname;
390 if (!BaseSegmentAddressSet && SegName != "__PAGEZERO") {
391 BaseSegmentAddressSet = true;
392 BaseSegmentAddress = SLC.vmaddr;
394 } else if (Command.C.cmd == MachO::LC_SEGMENT_64) {
395 MachO::segment_command_64 SLC = MachOObj->getSegment64LoadCommand(Command);
396 StringRef SegName = SLC.segname;
397 if (!BaseSegmentAddressSet && SegName != "__PAGEZERO") {
398 BaseSegmentAddressSet = true;
399 BaseSegmentAddress = SLC.vmaddr;
405 static bool DumpAndSkipDataInCode(uint64_t PC, const uint8_t *bytes,
406 DiceTable &Dices, uint64_t &InstSize) {
407 // Check the data in code table here to see if this is data not an
408 // instruction to be disassembled.
409 DiceTable Dice;
410 Dice.push_back(std::make_pair(PC, DiceRef()));
411 dice_table_iterator DTI =
412 std::search(Dices.begin(), Dices.end(), Dice.begin(), Dice.end(),
413 compareDiceTableEntries);
414 if (DTI != Dices.end()) {
415 uint16_t Length;
416 DTI->second.getLength(Length);
417 uint16_t Kind;
418 DTI->second.getKind(Kind);
419 InstSize = DumpDataInCode(bytes, Length, Kind);
420 if ((Kind == MachO::DICE_KIND_JUMP_TABLE8) &&
421 (PC == (DTI->first + Length - 1)) && (Length & 1))
422 InstSize++;
423 return true;
425 return false;
428 static void printRelocationTargetName(const MachOObjectFile *O,
429 const MachO::any_relocation_info &RE,
430 raw_string_ostream &Fmt) {
431 // Target of a scattered relocation is an address. In the interest of
432 // generating pretty output, scan through the symbol table looking for a
433 // symbol that aligns with that address. If we find one, print it.
434 // Otherwise, we just print the hex address of the target.
435 const StringRef FileName = O->getFileName();
436 if (O->isRelocationScattered(RE)) {
437 uint32_t Val = O->getPlainRelocationSymbolNum(RE);
439 for (const SymbolRef &Symbol : O->symbols()) {
440 uint64_t Addr = unwrapOrError(Symbol.getAddress(), FileName);
441 if (Addr != Val)
442 continue;
443 Fmt << unwrapOrError(Symbol.getName(), FileName);
444 return;
447 // If we couldn't find a symbol that this relocation refers to, try
448 // to find a section beginning instead.
449 for (const SectionRef &Section : ToolSectionFilter(*O)) {
450 uint64_t Addr = Section.getAddress();
451 if (Addr != Val)
452 continue;
453 StringRef NameOrErr = unwrapOrError(Section.getName(), O->getFileName());
454 Fmt << NameOrErr;
455 return;
458 Fmt << format("0x%x", Val);
459 return;
462 StringRef S;
463 bool isExtern = O->getPlainRelocationExternal(RE);
464 uint64_t Val = O->getPlainRelocationSymbolNum(RE);
466 if (O->getAnyRelocationType(RE) == MachO::ARM64_RELOC_ADDEND) {
467 Fmt << format("0x%0" PRIx64, Val);
468 return;
471 if (isExtern) {
472 symbol_iterator SI = O->symbol_begin();
473 advance(SI, Val);
474 S = unwrapOrError(SI->getName(), FileName);
475 } else {
476 section_iterator SI = O->section_begin();
477 // Adjust for the fact that sections are 1-indexed.
478 if (Val == 0) {
479 Fmt << "0 (?,?)";
480 return;
482 uint32_t I = Val - 1;
483 while (I != 0 && SI != O->section_end()) {
484 --I;
485 advance(SI, 1);
487 if (SI == O->section_end()) {
488 Fmt << Val << " (?,?)";
489 } else {
490 if (Expected<StringRef> NameOrErr = SI->getName())
491 S = *NameOrErr;
492 else
493 consumeError(NameOrErr.takeError());
497 Fmt << S;
500 Error getMachORelocationValueString(const MachOObjectFile *Obj,
501 const RelocationRef &RelRef,
502 SmallVectorImpl<char> &Result) {
503 DataRefImpl Rel = RelRef.getRawDataRefImpl();
504 MachO::any_relocation_info RE = Obj->getRelocation(Rel);
506 unsigned Arch = Obj->getArch();
508 std::string FmtBuf;
509 raw_string_ostream Fmt(FmtBuf);
510 unsigned Type = Obj->getAnyRelocationType(RE);
511 bool IsPCRel = Obj->getAnyRelocationPCRel(RE);
513 // Determine any addends that should be displayed with the relocation.
514 // These require decoding the relocation type, which is triple-specific.
516 // X86_64 has entirely custom relocation types.
517 if (Arch == Triple::x86_64) {
518 switch (Type) {
519 case MachO::X86_64_RELOC_GOT_LOAD:
520 case MachO::X86_64_RELOC_GOT: {
521 printRelocationTargetName(Obj, RE, Fmt);
522 Fmt << "@GOT";
523 if (IsPCRel)
524 Fmt << "PCREL";
525 break;
527 case MachO::X86_64_RELOC_SUBTRACTOR: {
528 DataRefImpl RelNext = Rel;
529 Obj->moveRelocationNext(RelNext);
530 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
532 // X86_64_RELOC_SUBTRACTOR must be followed by a relocation of type
533 // X86_64_RELOC_UNSIGNED.
534 // NOTE: Scattered relocations don't exist on x86_64.
535 unsigned RType = Obj->getAnyRelocationType(RENext);
536 if (RType != MachO::X86_64_RELOC_UNSIGNED)
537 reportError(Obj->getFileName(), "Expected X86_64_RELOC_UNSIGNED after "
538 "X86_64_RELOC_SUBTRACTOR.");
540 // The X86_64_RELOC_UNSIGNED contains the minuend symbol;
541 // X86_64_RELOC_SUBTRACTOR contains the subtrahend.
542 printRelocationTargetName(Obj, RENext, Fmt);
543 Fmt << "-";
544 printRelocationTargetName(Obj, RE, Fmt);
545 break;
547 case MachO::X86_64_RELOC_TLV:
548 printRelocationTargetName(Obj, RE, Fmt);
549 Fmt << "@TLV";
550 if (IsPCRel)
551 Fmt << "P";
552 break;
553 case MachO::X86_64_RELOC_SIGNED_1:
554 printRelocationTargetName(Obj, RE, Fmt);
555 Fmt << "-1";
556 break;
557 case MachO::X86_64_RELOC_SIGNED_2:
558 printRelocationTargetName(Obj, RE, Fmt);
559 Fmt << "-2";
560 break;
561 case MachO::X86_64_RELOC_SIGNED_4:
562 printRelocationTargetName(Obj, RE, Fmt);
563 Fmt << "-4";
564 break;
565 default:
566 printRelocationTargetName(Obj, RE, Fmt);
567 break;
569 // X86 and ARM share some relocation types in common.
570 } else if (Arch == Triple::x86 || Arch == Triple::arm ||
571 Arch == Triple::ppc) {
572 // Generic relocation types...
573 switch (Type) {
574 case MachO::GENERIC_RELOC_PAIR: // prints no info
575 return Error::success();
576 case MachO::GENERIC_RELOC_SECTDIFF: {
577 DataRefImpl RelNext = Rel;
578 Obj->moveRelocationNext(RelNext);
579 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
581 // X86 sect diff's must be followed by a relocation of type
582 // GENERIC_RELOC_PAIR.
583 unsigned RType = Obj->getAnyRelocationType(RENext);
585 if (RType != MachO::GENERIC_RELOC_PAIR)
586 reportError(Obj->getFileName(), "Expected GENERIC_RELOC_PAIR after "
587 "GENERIC_RELOC_SECTDIFF.");
589 printRelocationTargetName(Obj, RE, Fmt);
590 Fmt << "-";
591 printRelocationTargetName(Obj, RENext, Fmt);
592 break;
596 if (Arch == Triple::x86 || Arch == Triple::ppc) {
597 switch (Type) {
598 case MachO::GENERIC_RELOC_LOCAL_SECTDIFF: {
599 DataRefImpl RelNext = Rel;
600 Obj->moveRelocationNext(RelNext);
601 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
603 // X86 sect diff's must be followed by a relocation of type
604 // GENERIC_RELOC_PAIR.
605 unsigned RType = Obj->getAnyRelocationType(RENext);
606 if (RType != MachO::GENERIC_RELOC_PAIR)
607 reportError(Obj->getFileName(), "Expected GENERIC_RELOC_PAIR after "
608 "GENERIC_RELOC_LOCAL_SECTDIFF.");
610 printRelocationTargetName(Obj, RE, Fmt);
611 Fmt << "-";
612 printRelocationTargetName(Obj, RENext, Fmt);
613 break;
615 case MachO::GENERIC_RELOC_TLV: {
616 printRelocationTargetName(Obj, RE, Fmt);
617 Fmt << "@TLV";
618 if (IsPCRel)
619 Fmt << "P";
620 break;
622 default:
623 printRelocationTargetName(Obj, RE, Fmt);
625 } else { // ARM-specific relocations
626 switch (Type) {
627 case MachO::ARM_RELOC_HALF:
628 case MachO::ARM_RELOC_HALF_SECTDIFF: {
629 // Half relocations steal a bit from the length field to encode
630 // whether this is an upper16 or a lower16 relocation.
631 bool isUpper = (Obj->getAnyRelocationLength(RE) & 0x1) == 1;
633 if (isUpper)
634 Fmt << ":upper16:(";
635 else
636 Fmt << ":lower16:(";
637 printRelocationTargetName(Obj, RE, Fmt);
639 DataRefImpl RelNext = Rel;
640 Obj->moveRelocationNext(RelNext);
641 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
643 // ARM half relocs must be followed by a relocation of type
644 // ARM_RELOC_PAIR.
645 unsigned RType = Obj->getAnyRelocationType(RENext);
646 if (RType != MachO::ARM_RELOC_PAIR)
647 reportError(Obj->getFileName(), "Expected ARM_RELOC_PAIR after "
648 "ARM_RELOC_HALF");
650 // NOTE: The half of the target virtual address is stashed in the
651 // address field of the secondary relocation, but we can't reverse
652 // engineer the constant offset from it without decoding the movw/movt
653 // instruction to find the other half in its immediate field.
655 // ARM_RELOC_HALF_SECTDIFF encodes the second section in the
656 // symbol/section pointer of the follow-on relocation.
657 if (Type == MachO::ARM_RELOC_HALF_SECTDIFF) {
658 Fmt << "-";
659 printRelocationTargetName(Obj, RENext, Fmt);
662 Fmt << ")";
663 break;
665 default: {
666 printRelocationTargetName(Obj, RE, Fmt);
670 } else
671 printRelocationTargetName(Obj, RE, Fmt);
673 Fmt.flush();
674 Result.append(FmtBuf.begin(), FmtBuf.end());
675 return Error::success();
678 static void PrintIndirectSymbolTable(MachOObjectFile *O, bool verbose,
679 uint32_t n, uint32_t count,
680 uint32_t stride, uint64_t addr) {
681 MachO::dysymtab_command Dysymtab = O->getDysymtabLoadCommand();
682 uint32_t nindirectsyms = Dysymtab.nindirectsyms;
683 if (n > nindirectsyms)
684 outs() << " (entries start past the end of the indirect symbol "
685 "table) (reserved1 field greater than the table size)";
686 else if (n + count > nindirectsyms)
687 outs() << " (entries extends past the end of the indirect symbol "
688 "table)";
689 outs() << "\n";
690 uint32_t cputype = O->getHeader().cputype;
691 if (cputype & MachO::CPU_ARCH_ABI64)
692 outs() << "address index";
693 else
694 outs() << "address index";
695 if (verbose)
696 outs() << " name\n";
697 else
698 outs() << "\n";
699 for (uint32_t j = 0; j < count && n + j < nindirectsyms; j++) {
700 if (cputype & MachO::CPU_ARCH_ABI64)
701 outs() << format("0x%016" PRIx64, addr + j * stride) << " ";
702 else
703 outs() << format("0x%08" PRIx32, (uint32_t)addr + j * stride) << " ";
704 MachO::dysymtab_command Dysymtab = O->getDysymtabLoadCommand();
705 uint32_t indirect_symbol = O->getIndirectSymbolTableEntry(Dysymtab, n + j);
706 if (indirect_symbol == MachO::INDIRECT_SYMBOL_LOCAL) {
707 outs() << "LOCAL\n";
708 continue;
710 if (indirect_symbol ==
711 (MachO::INDIRECT_SYMBOL_LOCAL | MachO::INDIRECT_SYMBOL_ABS)) {
712 outs() << "LOCAL ABSOLUTE\n";
713 continue;
715 if (indirect_symbol == MachO::INDIRECT_SYMBOL_ABS) {
716 outs() << "ABSOLUTE\n";
717 continue;
719 outs() << format("%5u ", indirect_symbol);
720 if (verbose) {
721 MachO::symtab_command Symtab = O->getSymtabLoadCommand();
722 if (indirect_symbol < Symtab.nsyms) {
723 symbol_iterator Sym = O->getSymbolByIndex(indirect_symbol);
724 SymbolRef Symbol = *Sym;
725 outs() << unwrapOrError(Symbol.getName(), O->getFileName());
726 } else {
727 outs() << "?";
730 outs() << "\n";
734 static void PrintIndirectSymbols(MachOObjectFile *O, bool verbose) {
735 for (const auto &Load : O->load_commands()) {
736 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
737 MachO::segment_command_64 Seg = O->getSegment64LoadCommand(Load);
738 for (unsigned J = 0; J < Seg.nsects; ++J) {
739 MachO::section_64 Sec = O->getSection64(Load, J);
740 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
741 if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
742 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
743 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
744 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
745 section_type == MachO::S_SYMBOL_STUBS) {
746 uint32_t stride;
747 if (section_type == MachO::S_SYMBOL_STUBS)
748 stride = Sec.reserved2;
749 else
750 stride = 8;
751 if (stride == 0) {
752 outs() << "Can't print indirect symbols for (" << Sec.segname << ","
753 << Sec.sectname << ") "
754 << "(size of stubs in reserved2 field is zero)\n";
755 continue;
757 uint32_t count = Sec.size / stride;
758 outs() << "Indirect symbols for (" << Sec.segname << ","
759 << Sec.sectname << ") " << count << " entries";
760 uint32_t n = Sec.reserved1;
761 PrintIndirectSymbolTable(O, verbose, n, count, stride, Sec.addr);
764 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
765 MachO::segment_command Seg = O->getSegmentLoadCommand(Load);
766 for (unsigned J = 0; J < Seg.nsects; ++J) {
767 MachO::section Sec = O->getSection(Load, J);
768 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
769 if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
770 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
771 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
772 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
773 section_type == MachO::S_SYMBOL_STUBS) {
774 uint32_t stride;
775 if (section_type == MachO::S_SYMBOL_STUBS)
776 stride = Sec.reserved2;
777 else
778 stride = 4;
779 if (stride == 0) {
780 outs() << "Can't print indirect symbols for (" << Sec.segname << ","
781 << Sec.sectname << ") "
782 << "(size of stubs in reserved2 field is zero)\n";
783 continue;
785 uint32_t count = Sec.size / stride;
786 outs() << "Indirect symbols for (" << Sec.segname << ","
787 << Sec.sectname << ") " << count << " entries";
788 uint32_t n = Sec.reserved1;
789 PrintIndirectSymbolTable(O, verbose, n, count, stride, Sec.addr);
796 static void PrintRType(const uint64_t cputype, const unsigned r_type) {
797 static char const *generic_r_types[] = {
798 "VANILLA ", "PAIR ", "SECTDIF ", "PBLAPTR ", "LOCSDIF ", "TLV ",
799 " 6 (?) ", " 7 (?) ", " 8 (?) ", " 9 (?) ", " 10 (?) ", " 11 (?) ",
800 " 12 (?) ", " 13 (?) ", " 14 (?) ", " 15 (?) "
802 static char const *x86_64_r_types[] = {
803 "UNSIGND ", "SIGNED ", "BRANCH ", "GOT_LD ", "GOT ", "SUB ",
804 "SIGNED1 ", "SIGNED2 ", "SIGNED4 ", "TLV ", " 10 (?) ", " 11 (?) ",
805 " 12 (?) ", " 13 (?) ", " 14 (?) ", " 15 (?) "
807 static char const *arm_r_types[] = {
808 "VANILLA ", "PAIR ", "SECTDIFF", "LOCSDIF ", "PBLAPTR ",
809 "BR24 ", "T_BR22 ", "T_BR32 ", "HALF ", "HALFDIF ",
810 " 10 (?) ", " 11 (?) ", " 12 (?) ", " 13 (?) ", " 14 (?) ", " 15 (?) "
812 static char const *arm64_r_types[] = {
813 "UNSIGND ", "SUB ", "BR26 ", "PAGE21 ", "PAGOF12 ",
814 "GOTLDP ", "GOTLDPOF", "PTRTGOT ", "TLVLDP ", "TLVLDPOF",
815 "ADDEND ", " 11 (?) ", " 12 (?) ", " 13 (?) ", " 14 (?) ", " 15 (?) "
818 if (r_type > 0xf){
819 outs() << format("%-7u", r_type) << " ";
820 return;
822 switch (cputype) {
823 case MachO::CPU_TYPE_I386:
824 outs() << generic_r_types[r_type];
825 break;
826 case MachO::CPU_TYPE_X86_64:
827 outs() << x86_64_r_types[r_type];
828 break;
829 case MachO::CPU_TYPE_ARM:
830 outs() << arm_r_types[r_type];
831 break;
832 case MachO::CPU_TYPE_ARM64:
833 case MachO::CPU_TYPE_ARM64_32:
834 outs() << arm64_r_types[r_type];
835 break;
836 default:
837 outs() << format("%-7u ", r_type);
841 static void PrintRLength(const uint64_t cputype, const unsigned r_type,
842 const unsigned r_length, const bool previous_arm_half){
843 if (cputype == MachO::CPU_TYPE_ARM &&
844 (r_type == MachO::ARM_RELOC_HALF ||
845 r_type == MachO::ARM_RELOC_HALF_SECTDIFF || previous_arm_half == true)) {
846 if ((r_length & 0x1) == 0)
847 outs() << "lo/";
848 else
849 outs() << "hi/";
850 if ((r_length & 0x1) == 0)
851 outs() << "arm ";
852 else
853 outs() << "thm ";
854 } else {
855 switch (r_length) {
856 case 0:
857 outs() << "byte ";
858 break;
859 case 1:
860 outs() << "word ";
861 break;
862 case 2:
863 outs() << "long ";
864 break;
865 case 3:
866 if (cputype == MachO::CPU_TYPE_X86_64)
867 outs() << "quad ";
868 else
869 outs() << format("?(%2d) ", r_length);
870 break;
871 default:
872 outs() << format("?(%2d) ", r_length);
877 static void PrintRelocationEntries(const MachOObjectFile *O,
878 const relocation_iterator Begin,
879 const relocation_iterator End,
880 const uint64_t cputype,
881 const bool verbose) {
882 const MachO::symtab_command Symtab = O->getSymtabLoadCommand();
883 bool previous_arm_half = false;
884 bool previous_sectdiff = false;
885 uint32_t sectdiff_r_type = 0;
887 for (relocation_iterator Reloc = Begin; Reloc != End; ++Reloc) {
888 const DataRefImpl Rel = Reloc->getRawDataRefImpl();
889 const MachO::any_relocation_info RE = O->getRelocation(Rel);
890 const unsigned r_type = O->getAnyRelocationType(RE);
891 const bool r_scattered = O->isRelocationScattered(RE);
892 const unsigned r_pcrel = O->getAnyRelocationPCRel(RE);
893 const unsigned r_length = O->getAnyRelocationLength(RE);
894 const unsigned r_address = O->getAnyRelocationAddress(RE);
895 const bool r_extern = (r_scattered ? false :
896 O->getPlainRelocationExternal(RE));
897 const uint32_t r_value = (r_scattered ?
898 O->getScatteredRelocationValue(RE) : 0);
899 const unsigned r_symbolnum = (r_scattered ? 0 :
900 O->getPlainRelocationSymbolNum(RE));
902 if (r_scattered && cputype != MachO::CPU_TYPE_X86_64) {
903 if (verbose) {
904 // scattered: address
905 if ((cputype == MachO::CPU_TYPE_I386 &&
906 r_type == MachO::GENERIC_RELOC_PAIR) ||
907 (cputype == MachO::CPU_TYPE_ARM && r_type == MachO::ARM_RELOC_PAIR))
908 outs() << " ";
909 else
910 outs() << format("%08x ", (unsigned int)r_address);
912 // scattered: pcrel
913 if (r_pcrel)
914 outs() << "True ";
915 else
916 outs() << "False ";
918 // scattered: length
919 PrintRLength(cputype, r_type, r_length, previous_arm_half);
921 // scattered: extern & type
922 outs() << "n/a ";
923 PrintRType(cputype, r_type);
925 // scattered: scattered & value
926 outs() << format("True 0x%08x", (unsigned int)r_value);
927 if (previous_sectdiff == false) {
928 if ((cputype == MachO::CPU_TYPE_ARM &&
929 r_type == MachO::ARM_RELOC_PAIR))
930 outs() << format(" half = 0x%04x ", (unsigned int)r_address);
931 } else if (cputype == MachO::CPU_TYPE_ARM &&
932 sectdiff_r_type == MachO::ARM_RELOC_HALF_SECTDIFF)
933 outs() << format(" other_half = 0x%04x ", (unsigned int)r_address);
934 if ((cputype == MachO::CPU_TYPE_I386 &&
935 (r_type == MachO::GENERIC_RELOC_SECTDIFF ||
936 r_type == MachO::GENERIC_RELOC_LOCAL_SECTDIFF)) ||
937 (cputype == MachO::CPU_TYPE_ARM &&
938 (sectdiff_r_type == MachO::ARM_RELOC_SECTDIFF ||
939 sectdiff_r_type == MachO::ARM_RELOC_LOCAL_SECTDIFF ||
940 sectdiff_r_type == MachO::ARM_RELOC_HALF_SECTDIFF))) {
941 previous_sectdiff = true;
942 sectdiff_r_type = r_type;
943 } else {
944 previous_sectdiff = false;
945 sectdiff_r_type = 0;
947 if (cputype == MachO::CPU_TYPE_ARM &&
948 (r_type == MachO::ARM_RELOC_HALF ||
949 r_type == MachO::ARM_RELOC_HALF_SECTDIFF))
950 previous_arm_half = true;
951 else
952 previous_arm_half = false;
953 outs() << "\n";
955 else {
956 // scattered: address pcrel length extern type scattered value
957 outs() << format("%08x %1d %-2d n/a %-7d 1 0x%08x\n",
958 (unsigned int)r_address, r_pcrel, r_length, r_type,
959 (unsigned int)r_value);
962 else {
963 if (verbose) {
964 // plain: address
965 if (cputype == MachO::CPU_TYPE_ARM && r_type == MachO::ARM_RELOC_PAIR)
966 outs() << " ";
967 else
968 outs() << format("%08x ", (unsigned int)r_address);
970 // plain: pcrel
971 if (r_pcrel)
972 outs() << "True ";
973 else
974 outs() << "False ";
976 // plain: length
977 PrintRLength(cputype, r_type, r_length, previous_arm_half);
979 if (r_extern) {
980 // plain: extern & type & scattered
981 outs() << "True ";
982 PrintRType(cputype, r_type);
983 outs() << "False ";
985 // plain: symbolnum/value
986 if (r_symbolnum > Symtab.nsyms)
987 outs() << format("?(%d)\n", r_symbolnum);
988 else {
989 SymbolRef Symbol = *O->getSymbolByIndex(r_symbolnum);
990 Expected<StringRef> SymNameNext = Symbol.getName();
991 const char *name = NULL;
992 if (SymNameNext)
993 name = SymNameNext->data();
994 if (name == NULL)
995 outs() << format("?(%d)\n", r_symbolnum);
996 else
997 outs() << name << "\n";
1000 else {
1001 // plain: extern & type & scattered
1002 outs() << "False ";
1003 PrintRType(cputype, r_type);
1004 outs() << "False ";
1006 // plain: symbolnum/value
1007 if (cputype == MachO::CPU_TYPE_ARM && r_type == MachO::ARM_RELOC_PAIR)
1008 outs() << format("other_half = 0x%04x\n", (unsigned int)r_address);
1009 else if ((cputype == MachO::CPU_TYPE_ARM64 ||
1010 cputype == MachO::CPU_TYPE_ARM64_32) &&
1011 r_type == MachO::ARM64_RELOC_ADDEND)
1012 outs() << format("addend = 0x%06x\n", (unsigned int)r_symbolnum);
1013 else {
1014 outs() << format("%d ", r_symbolnum);
1015 if (r_symbolnum == MachO::R_ABS)
1016 outs() << "R_ABS\n";
1017 else {
1018 // in this case, r_symbolnum is actually a 1-based section number
1019 uint32_t nsects = O->section_end()->getRawDataRefImpl().d.a;
1020 if (r_symbolnum > 0 && r_symbolnum <= nsects) {
1021 object::DataRefImpl DRI;
1022 DRI.d.a = r_symbolnum-1;
1023 StringRef SegName = O->getSectionFinalSegmentName(DRI);
1024 if (Expected<StringRef> NameOrErr = O->getSectionName(DRI))
1025 outs() << "(" << SegName << "," << *NameOrErr << ")\n";
1026 else
1027 outs() << "(?,?)\n";
1029 else {
1030 outs() << "(?,?)\n";
1035 if (cputype == MachO::CPU_TYPE_ARM &&
1036 (r_type == MachO::ARM_RELOC_HALF ||
1037 r_type == MachO::ARM_RELOC_HALF_SECTDIFF))
1038 previous_arm_half = true;
1039 else
1040 previous_arm_half = false;
1042 else {
1043 // plain: address pcrel length extern type scattered symbolnum/section
1044 outs() << format("%08x %1d %-2d %1d %-7d 0 %d\n",
1045 (unsigned int)r_address, r_pcrel, r_length, r_extern,
1046 r_type, r_symbolnum);
1052 static void PrintRelocations(const MachOObjectFile *O, const bool verbose) {
1053 const uint64_t cputype = O->getHeader().cputype;
1054 const MachO::dysymtab_command Dysymtab = O->getDysymtabLoadCommand();
1055 if (Dysymtab.nextrel != 0) {
1056 outs() << "External relocation information " << Dysymtab.nextrel
1057 << " entries";
1058 outs() << "\naddress pcrel length extern type scattered "
1059 "symbolnum/value\n";
1060 PrintRelocationEntries(O, O->extrel_begin(), O->extrel_end(), cputype,
1061 verbose);
1063 if (Dysymtab.nlocrel != 0) {
1064 outs() << format("Local relocation information %u entries",
1065 Dysymtab.nlocrel);
1066 outs() << "\naddress pcrel length extern type scattered "
1067 "symbolnum/value\n";
1068 PrintRelocationEntries(O, O->locrel_begin(), O->locrel_end(), cputype,
1069 verbose);
1071 for (const auto &Load : O->load_commands()) {
1072 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
1073 const MachO::segment_command_64 Seg = O->getSegment64LoadCommand(Load);
1074 for (unsigned J = 0; J < Seg.nsects; ++J) {
1075 const MachO::section_64 Sec = O->getSection64(Load, J);
1076 if (Sec.nreloc != 0) {
1077 DataRefImpl DRI;
1078 DRI.d.a = J;
1079 const StringRef SegName = O->getSectionFinalSegmentName(DRI);
1080 if (Expected<StringRef> NameOrErr = O->getSectionName(DRI))
1081 outs() << "Relocation information (" << SegName << "," << *NameOrErr
1082 << format(") %u entries", Sec.nreloc);
1083 else
1084 outs() << "Relocation information (" << SegName << ",?) "
1085 << format("%u entries", Sec.nreloc);
1086 outs() << "\naddress pcrel length extern type scattered "
1087 "symbolnum/value\n";
1088 PrintRelocationEntries(O, O->section_rel_begin(DRI),
1089 O->section_rel_end(DRI), cputype, verbose);
1092 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
1093 const MachO::segment_command Seg = O->getSegmentLoadCommand(Load);
1094 for (unsigned J = 0; J < Seg.nsects; ++J) {
1095 const MachO::section Sec = O->getSection(Load, J);
1096 if (Sec.nreloc != 0) {
1097 DataRefImpl DRI;
1098 DRI.d.a = J;
1099 const StringRef SegName = O->getSectionFinalSegmentName(DRI);
1100 if (Expected<StringRef> NameOrErr = O->getSectionName(DRI))
1101 outs() << "Relocation information (" << SegName << "," << *NameOrErr
1102 << format(") %u entries", Sec.nreloc);
1103 else
1104 outs() << "Relocation information (" << SegName << ",?) "
1105 << format("%u entries", Sec.nreloc);
1106 outs() << "\naddress pcrel length extern type scattered "
1107 "symbolnum/value\n";
1108 PrintRelocationEntries(O, O->section_rel_begin(DRI),
1109 O->section_rel_end(DRI), cputype, verbose);
1116 static void PrintDataInCodeTable(MachOObjectFile *O, bool verbose) {
1117 MachO::linkedit_data_command DIC = O->getDataInCodeLoadCommand();
1118 uint32_t nentries = DIC.datasize / sizeof(struct MachO::data_in_code_entry);
1119 outs() << "Data in code table (" << nentries << " entries)\n";
1120 outs() << "offset length kind\n";
1121 for (dice_iterator DI = O->begin_dices(), DE = O->end_dices(); DI != DE;
1122 ++DI) {
1123 uint32_t Offset;
1124 DI->getOffset(Offset);
1125 outs() << format("0x%08" PRIx32, Offset) << " ";
1126 uint16_t Length;
1127 DI->getLength(Length);
1128 outs() << format("%6u", Length) << " ";
1129 uint16_t Kind;
1130 DI->getKind(Kind);
1131 if (verbose) {
1132 switch (Kind) {
1133 case MachO::DICE_KIND_DATA:
1134 outs() << "DATA";
1135 break;
1136 case MachO::DICE_KIND_JUMP_TABLE8:
1137 outs() << "JUMP_TABLE8";
1138 break;
1139 case MachO::DICE_KIND_JUMP_TABLE16:
1140 outs() << "JUMP_TABLE16";
1141 break;
1142 case MachO::DICE_KIND_JUMP_TABLE32:
1143 outs() << "JUMP_TABLE32";
1144 break;
1145 case MachO::DICE_KIND_ABS_JUMP_TABLE32:
1146 outs() << "ABS_JUMP_TABLE32";
1147 break;
1148 default:
1149 outs() << format("0x%04" PRIx32, Kind);
1150 break;
1152 } else
1153 outs() << format("0x%04" PRIx32, Kind);
1154 outs() << "\n";
1158 static void PrintLinkOptHints(MachOObjectFile *O) {
1159 MachO::linkedit_data_command LohLC = O->getLinkOptHintsLoadCommand();
1160 const char *loh = O->getData().substr(LohLC.dataoff, 1).data();
1161 uint32_t nloh = LohLC.datasize;
1162 outs() << "Linker optimiztion hints (" << nloh << " total bytes)\n";
1163 for (uint32_t i = 0; i < nloh;) {
1164 unsigned n;
1165 uint64_t identifier = decodeULEB128((const uint8_t *)(loh + i), &n);
1166 i += n;
1167 outs() << " identifier " << identifier << " ";
1168 if (i >= nloh)
1169 return;
1170 switch (identifier) {
1171 case 1:
1172 outs() << "AdrpAdrp\n";
1173 break;
1174 case 2:
1175 outs() << "AdrpLdr\n";
1176 break;
1177 case 3:
1178 outs() << "AdrpAddLdr\n";
1179 break;
1180 case 4:
1181 outs() << "AdrpLdrGotLdr\n";
1182 break;
1183 case 5:
1184 outs() << "AdrpAddStr\n";
1185 break;
1186 case 6:
1187 outs() << "AdrpLdrGotStr\n";
1188 break;
1189 case 7:
1190 outs() << "AdrpAdd\n";
1191 break;
1192 case 8:
1193 outs() << "AdrpLdrGot\n";
1194 break;
1195 default:
1196 outs() << "Unknown identifier value\n";
1197 break;
1199 uint64_t narguments = decodeULEB128((const uint8_t *)(loh + i), &n);
1200 i += n;
1201 outs() << " narguments " << narguments << "\n";
1202 if (i >= nloh)
1203 return;
1205 for (uint32_t j = 0; j < narguments; j++) {
1206 uint64_t value = decodeULEB128((const uint8_t *)(loh + i), &n);
1207 i += n;
1208 outs() << "\tvalue " << format("0x%" PRIx64, value) << "\n";
1209 if (i >= nloh)
1210 return;
1215 static void PrintDylibs(MachOObjectFile *O, bool JustId) {
1216 unsigned Index = 0;
1217 for (const auto &Load : O->load_commands()) {
1218 if ((JustId && Load.C.cmd == MachO::LC_ID_DYLIB) ||
1219 (!JustId && (Load.C.cmd == MachO::LC_ID_DYLIB ||
1220 Load.C.cmd == MachO::LC_LOAD_DYLIB ||
1221 Load.C.cmd == MachO::LC_LOAD_WEAK_DYLIB ||
1222 Load.C.cmd == MachO::LC_REEXPORT_DYLIB ||
1223 Load.C.cmd == MachO::LC_LAZY_LOAD_DYLIB ||
1224 Load.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB))) {
1225 MachO::dylib_command dl = O->getDylibIDLoadCommand(Load);
1226 if (dl.dylib.name < dl.cmdsize) {
1227 const char *p = (const char *)(Load.Ptr) + dl.dylib.name;
1228 if (JustId)
1229 outs() << p << "\n";
1230 else {
1231 outs() << "\t" << p;
1232 outs() << " (compatibility version "
1233 << ((dl.dylib.compatibility_version >> 16) & 0xffff) << "."
1234 << ((dl.dylib.compatibility_version >> 8) & 0xff) << "."
1235 << (dl.dylib.compatibility_version & 0xff) << ",";
1236 outs() << " current version "
1237 << ((dl.dylib.current_version >> 16) & 0xffff) << "."
1238 << ((dl.dylib.current_version >> 8) & 0xff) << "."
1239 << (dl.dylib.current_version & 0xff);
1240 if (Load.C.cmd == MachO::LC_LOAD_WEAK_DYLIB)
1241 outs() << ", weak";
1242 if (Load.C.cmd == MachO::LC_REEXPORT_DYLIB)
1243 outs() << ", reexport";
1244 if (Load.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB)
1245 outs() << ", upward";
1246 if (Load.C.cmd == MachO::LC_LAZY_LOAD_DYLIB)
1247 outs() << ", lazy";
1248 outs() << ")\n";
1250 } else {
1251 outs() << "\tBad offset (" << dl.dylib.name << ") for name of ";
1252 if (Load.C.cmd == MachO::LC_ID_DYLIB)
1253 outs() << "LC_ID_DYLIB ";
1254 else if (Load.C.cmd == MachO::LC_LOAD_DYLIB)
1255 outs() << "LC_LOAD_DYLIB ";
1256 else if (Load.C.cmd == MachO::LC_LOAD_WEAK_DYLIB)
1257 outs() << "LC_LOAD_WEAK_DYLIB ";
1258 else if (Load.C.cmd == MachO::LC_LAZY_LOAD_DYLIB)
1259 outs() << "LC_LAZY_LOAD_DYLIB ";
1260 else if (Load.C.cmd == MachO::LC_REEXPORT_DYLIB)
1261 outs() << "LC_REEXPORT_DYLIB ";
1262 else if (Load.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB)
1263 outs() << "LC_LOAD_UPWARD_DYLIB ";
1264 else
1265 outs() << "LC_??? ";
1266 outs() << "command " << Index++ << "\n";
1272 typedef DenseMap<uint64_t, StringRef> SymbolAddressMap;
1274 static void CreateSymbolAddressMap(MachOObjectFile *O,
1275 SymbolAddressMap *AddrMap) {
1276 // Create a map of symbol addresses to symbol names.
1277 const StringRef FileName = O->getFileName();
1278 for (const SymbolRef &Symbol : O->symbols()) {
1279 SymbolRef::Type ST = unwrapOrError(Symbol.getType(), FileName);
1280 if (ST == SymbolRef::ST_Function || ST == SymbolRef::ST_Data ||
1281 ST == SymbolRef::ST_Other) {
1282 uint64_t Address = Symbol.getValue();
1283 StringRef SymName = unwrapOrError(Symbol.getName(), FileName);
1284 if (!SymName.startswith(".objc"))
1285 (*AddrMap)[Address] = SymName;
1290 // GuessSymbolName is passed the address of what might be a symbol and a
1291 // pointer to the SymbolAddressMap. It returns the name of a symbol
1292 // with that address or nullptr if no symbol is found with that address.
1293 static const char *GuessSymbolName(uint64_t value, SymbolAddressMap *AddrMap) {
1294 const char *SymbolName = nullptr;
1295 // A DenseMap can't lookup up some values.
1296 if (value != 0xffffffffffffffffULL && value != 0xfffffffffffffffeULL) {
1297 StringRef name = AddrMap->lookup(value);
1298 if (!name.empty())
1299 SymbolName = name.data();
1301 return SymbolName;
1304 static void DumpCstringChar(const char c) {
1305 char p[2];
1306 p[0] = c;
1307 p[1] = '\0';
1308 outs().write_escaped(p);
1311 static void DumpCstringSection(MachOObjectFile *O, const char *sect,
1312 uint32_t sect_size, uint64_t sect_addr,
1313 bool print_addresses) {
1314 for (uint32_t i = 0; i < sect_size; i++) {
1315 if (print_addresses) {
1316 if (O->is64Bit())
1317 outs() << format("%016" PRIx64, sect_addr + i) << " ";
1318 else
1319 outs() << format("%08" PRIx64, sect_addr + i) << " ";
1321 for (; i < sect_size && sect[i] != '\0'; i++)
1322 DumpCstringChar(sect[i]);
1323 if (i < sect_size && sect[i] == '\0')
1324 outs() << "\n";
1328 static void DumpLiteral4(uint32_t l, float f) {
1329 outs() << format("0x%08" PRIx32, l);
1330 if ((l & 0x7f800000) != 0x7f800000)
1331 outs() << format(" (%.16e)\n", f);
1332 else {
1333 if (l == 0x7f800000)
1334 outs() << " (+Infinity)\n";
1335 else if (l == 0xff800000)
1336 outs() << " (-Infinity)\n";
1337 else if ((l & 0x00400000) == 0x00400000)
1338 outs() << " (non-signaling Not-a-Number)\n";
1339 else
1340 outs() << " (signaling Not-a-Number)\n";
1344 static void DumpLiteral4Section(MachOObjectFile *O, const char *sect,
1345 uint32_t sect_size, uint64_t sect_addr,
1346 bool print_addresses) {
1347 for (uint32_t i = 0; i < sect_size; i += sizeof(float)) {
1348 if (print_addresses) {
1349 if (O->is64Bit())
1350 outs() << format("%016" PRIx64, sect_addr + i) << " ";
1351 else
1352 outs() << format("%08" PRIx64, sect_addr + i) << " ";
1354 float f;
1355 memcpy(&f, sect + i, sizeof(float));
1356 if (O->isLittleEndian() != sys::IsLittleEndianHost)
1357 sys::swapByteOrder(f);
1358 uint32_t l;
1359 memcpy(&l, sect + i, sizeof(uint32_t));
1360 if (O->isLittleEndian() != sys::IsLittleEndianHost)
1361 sys::swapByteOrder(l);
1362 DumpLiteral4(l, f);
1366 static void DumpLiteral8(MachOObjectFile *O, uint32_t l0, uint32_t l1,
1367 double d) {
1368 outs() << format("0x%08" PRIx32, l0) << " " << format("0x%08" PRIx32, l1);
1369 uint32_t Hi, Lo;
1370 Hi = (O->isLittleEndian()) ? l1 : l0;
1371 Lo = (O->isLittleEndian()) ? l0 : l1;
1373 // Hi is the high word, so this is equivalent to if(isfinite(d))
1374 if ((Hi & 0x7ff00000) != 0x7ff00000)
1375 outs() << format(" (%.16e)\n", d);
1376 else {
1377 if (Hi == 0x7ff00000 && Lo == 0)
1378 outs() << " (+Infinity)\n";
1379 else if (Hi == 0xfff00000 && Lo == 0)
1380 outs() << " (-Infinity)\n";
1381 else if ((Hi & 0x00080000) == 0x00080000)
1382 outs() << " (non-signaling Not-a-Number)\n";
1383 else
1384 outs() << " (signaling Not-a-Number)\n";
1388 static void DumpLiteral8Section(MachOObjectFile *O, const char *sect,
1389 uint32_t sect_size, uint64_t sect_addr,
1390 bool print_addresses) {
1391 for (uint32_t i = 0; i < sect_size; i += sizeof(double)) {
1392 if (print_addresses) {
1393 if (O->is64Bit())
1394 outs() << format("%016" PRIx64, sect_addr + i) << " ";
1395 else
1396 outs() << format("%08" PRIx64, sect_addr + i) << " ";
1398 double d;
1399 memcpy(&d, sect + i, sizeof(double));
1400 if (O->isLittleEndian() != sys::IsLittleEndianHost)
1401 sys::swapByteOrder(d);
1402 uint32_t l0, l1;
1403 memcpy(&l0, sect + i, sizeof(uint32_t));
1404 memcpy(&l1, sect + i + sizeof(uint32_t), sizeof(uint32_t));
1405 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
1406 sys::swapByteOrder(l0);
1407 sys::swapByteOrder(l1);
1409 DumpLiteral8(O, l0, l1, d);
1413 static void DumpLiteral16(uint32_t l0, uint32_t l1, uint32_t l2, uint32_t l3) {
1414 outs() << format("0x%08" PRIx32, l0) << " ";
1415 outs() << format("0x%08" PRIx32, l1) << " ";
1416 outs() << format("0x%08" PRIx32, l2) << " ";
1417 outs() << format("0x%08" PRIx32, l3) << "\n";
1420 static void DumpLiteral16Section(MachOObjectFile *O, const char *sect,
1421 uint32_t sect_size, uint64_t sect_addr,
1422 bool print_addresses) {
1423 for (uint32_t i = 0; i < sect_size; i += 16) {
1424 if (print_addresses) {
1425 if (O->is64Bit())
1426 outs() << format("%016" PRIx64, sect_addr + i) << " ";
1427 else
1428 outs() << format("%08" PRIx64, sect_addr + i) << " ";
1430 uint32_t l0, l1, l2, l3;
1431 memcpy(&l0, sect + i, sizeof(uint32_t));
1432 memcpy(&l1, sect + i + sizeof(uint32_t), sizeof(uint32_t));
1433 memcpy(&l2, sect + i + 2 * sizeof(uint32_t), sizeof(uint32_t));
1434 memcpy(&l3, sect + i + 3 * sizeof(uint32_t), sizeof(uint32_t));
1435 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
1436 sys::swapByteOrder(l0);
1437 sys::swapByteOrder(l1);
1438 sys::swapByteOrder(l2);
1439 sys::swapByteOrder(l3);
1441 DumpLiteral16(l0, l1, l2, l3);
1445 static void DumpLiteralPointerSection(MachOObjectFile *O,
1446 const SectionRef &Section,
1447 const char *sect, uint32_t sect_size,
1448 uint64_t sect_addr,
1449 bool print_addresses) {
1450 // Collect the literal sections in this Mach-O file.
1451 std::vector<SectionRef> LiteralSections;
1452 for (const SectionRef &Section : O->sections()) {
1453 DataRefImpl Ref = Section.getRawDataRefImpl();
1454 uint32_t section_type;
1455 if (O->is64Bit()) {
1456 const MachO::section_64 Sec = O->getSection64(Ref);
1457 section_type = Sec.flags & MachO::SECTION_TYPE;
1458 } else {
1459 const MachO::section Sec = O->getSection(Ref);
1460 section_type = Sec.flags & MachO::SECTION_TYPE;
1462 if (section_type == MachO::S_CSTRING_LITERALS ||
1463 section_type == MachO::S_4BYTE_LITERALS ||
1464 section_type == MachO::S_8BYTE_LITERALS ||
1465 section_type == MachO::S_16BYTE_LITERALS)
1466 LiteralSections.push_back(Section);
1469 // Set the size of the literal pointer.
1470 uint32_t lp_size = O->is64Bit() ? 8 : 4;
1472 // Collect the external relocation symbols for the literal pointers.
1473 std::vector<std::pair<uint64_t, SymbolRef>> Relocs;
1474 for (const RelocationRef &Reloc : Section.relocations()) {
1475 DataRefImpl Rel;
1476 MachO::any_relocation_info RE;
1477 bool isExtern = false;
1478 Rel = Reloc.getRawDataRefImpl();
1479 RE = O->getRelocation(Rel);
1480 isExtern = O->getPlainRelocationExternal(RE);
1481 if (isExtern) {
1482 uint64_t RelocOffset = Reloc.getOffset();
1483 symbol_iterator RelocSym = Reloc.getSymbol();
1484 Relocs.push_back(std::make_pair(RelocOffset, *RelocSym));
1487 array_pod_sort(Relocs.begin(), Relocs.end());
1489 // Dump each literal pointer.
1490 for (uint32_t i = 0; i < sect_size; i += lp_size) {
1491 if (print_addresses) {
1492 if (O->is64Bit())
1493 outs() << format("%016" PRIx64, sect_addr + i) << " ";
1494 else
1495 outs() << format("%08" PRIx64, sect_addr + i) << " ";
1497 uint64_t lp;
1498 if (O->is64Bit()) {
1499 memcpy(&lp, sect + i, sizeof(uint64_t));
1500 if (O->isLittleEndian() != sys::IsLittleEndianHost)
1501 sys::swapByteOrder(lp);
1502 } else {
1503 uint32_t li;
1504 memcpy(&li, sect + i, sizeof(uint32_t));
1505 if (O->isLittleEndian() != sys::IsLittleEndianHost)
1506 sys::swapByteOrder(li);
1507 lp = li;
1510 // First look for an external relocation entry for this literal pointer.
1511 auto Reloc = find_if(Relocs, [&](const std::pair<uint64_t, SymbolRef> &P) {
1512 return P.first == i;
1514 if (Reloc != Relocs.end()) {
1515 symbol_iterator RelocSym = Reloc->second;
1516 StringRef SymName = unwrapOrError(RelocSym->getName(), O->getFileName());
1517 outs() << "external relocation entry for symbol:" << SymName << "\n";
1518 continue;
1521 // For local references see what the section the literal pointer points to.
1522 auto Sect = find_if(LiteralSections, [&](const SectionRef &R) {
1523 return lp >= R.getAddress() && lp < R.getAddress() + R.getSize();
1525 if (Sect == LiteralSections.end()) {
1526 outs() << format("0x%" PRIx64, lp) << " (not in a literal section)\n";
1527 continue;
1530 uint64_t SectAddress = Sect->getAddress();
1531 uint64_t SectSize = Sect->getSize();
1533 StringRef SectName;
1534 Expected<StringRef> SectNameOrErr = Sect->getName();
1535 if (SectNameOrErr)
1536 SectName = *SectNameOrErr;
1537 else
1538 consumeError(SectNameOrErr.takeError());
1540 DataRefImpl Ref = Sect->getRawDataRefImpl();
1541 StringRef SegmentName = O->getSectionFinalSegmentName(Ref);
1542 outs() << SegmentName << ":" << SectName << ":";
1544 uint32_t section_type;
1545 if (O->is64Bit()) {
1546 const MachO::section_64 Sec = O->getSection64(Ref);
1547 section_type = Sec.flags & MachO::SECTION_TYPE;
1548 } else {
1549 const MachO::section Sec = O->getSection(Ref);
1550 section_type = Sec.flags & MachO::SECTION_TYPE;
1553 StringRef BytesStr = unwrapOrError(Sect->getContents(), O->getFileName());
1555 const char *Contents = reinterpret_cast<const char *>(BytesStr.data());
1557 switch (section_type) {
1558 case MachO::S_CSTRING_LITERALS:
1559 for (uint64_t i = lp - SectAddress; i < SectSize && Contents[i] != '\0';
1560 i++) {
1561 DumpCstringChar(Contents[i]);
1563 outs() << "\n";
1564 break;
1565 case MachO::S_4BYTE_LITERALS:
1566 float f;
1567 memcpy(&f, Contents + (lp - SectAddress), sizeof(float));
1568 uint32_t l;
1569 memcpy(&l, Contents + (lp - SectAddress), sizeof(uint32_t));
1570 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
1571 sys::swapByteOrder(f);
1572 sys::swapByteOrder(l);
1574 DumpLiteral4(l, f);
1575 break;
1576 case MachO::S_8BYTE_LITERALS: {
1577 double d;
1578 memcpy(&d, Contents + (lp - SectAddress), sizeof(double));
1579 uint32_t l0, l1;
1580 memcpy(&l0, Contents + (lp - SectAddress), sizeof(uint32_t));
1581 memcpy(&l1, Contents + (lp - SectAddress) + sizeof(uint32_t),
1582 sizeof(uint32_t));
1583 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
1584 sys::swapByteOrder(f);
1585 sys::swapByteOrder(l0);
1586 sys::swapByteOrder(l1);
1588 DumpLiteral8(O, l0, l1, d);
1589 break;
1591 case MachO::S_16BYTE_LITERALS: {
1592 uint32_t l0, l1, l2, l3;
1593 memcpy(&l0, Contents + (lp - SectAddress), sizeof(uint32_t));
1594 memcpy(&l1, Contents + (lp - SectAddress) + sizeof(uint32_t),
1595 sizeof(uint32_t));
1596 memcpy(&l2, Contents + (lp - SectAddress) + 2 * sizeof(uint32_t),
1597 sizeof(uint32_t));
1598 memcpy(&l3, Contents + (lp - SectAddress) + 3 * sizeof(uint32_t),
1599 sizeof(uint32_t));
1600 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
1601 sys::swapByteOrder(l0);
1602 sys::swapByteOrder(l1);
1603 sys::swapByteOrder(l2);
1604 sys::swapByteOrder(l3);
1606 DumpLiteral16(l0, l1, l2, l3);
1607 break;
1613 static void DumpInitTermPointerSection(MachOObjectFile *O,
1614 const SectionRef &Section,
1615 const char *sect,
1616 uint32_t sect_size, uint64_t sect_addr,
1617 SymbolAddressMap *AddrMap,
1618 bool verbose) {
1619 uint32_t stride;
1620 stride = (O->is64Bit()) ? sizeof(uint64_t) : sizeof(uint32_t);
1622 // Collect the external relocation symbols for the pointers.
1623 std::vector<std::pair<uint64_t, SymbolRef>> Relocs;
1624 for (const RelocationRef &Reloc : Section.relocations()) {
1625 DataRefImpl Rel;
1626 MachO::any_relocation_info RE;
1627 bool isExtern = false;
1628 Rel = Reloc.getRawDataRefImpl();
1629 RE = O->getRelocation(Rel);
1630 isExtern = O->getPlainRelocationExternal(RE);
1631 if (isExtern) {
1632 uint64_t RelocOffset = Reloc.getOffset();
1633 symbol_iterator RelocSym = Reloc.getSymbol();
1634 Relocs.push_back(std::make_pair(RelocOffset, *RelocSym));
1637 array_pod_sort(Relocs.begin(), Relocs.end());
1639 for (uint32_t i = 0; i < sect_size; i += stride) {
1640 const char *SymbolName = nullptr;
1641 uint64_t p;
1642 if (O->is64Bit()) {
1643 outs() << format("0x%016" PRIx64, sect_addr + i * stride) << " ";
1644 uint64_t pointer_value;
1645 memcpy(&pointer_value, sect + i, stride);
1646 if (O->isLittleEndian() != sys::IsLittleEndianHost)
1647 sys::swapByteOrder(pointer_value);
1648 outs() << format("0x%016" PRIx64, pointer_value);
1649 p = pointer_value;
1650 } else {
1651 outs() << format("0x%08" PRIx64, sect_addr + i * stride) << " ";
1652 uint32_t pointer_value;
1653 memcpy(&pointer_value, sect + i, stride);
1654 if (O->isLittleEndian() != sys::IsLittleEndianHost)
1655 sys::swapByteOrder(pointer_value);
1656 outs() << format("0x%08" PRIx32, pointer_value);
1657 p = pointer_value;
1659 if (verbose) {
1660 // First look for an external relocation entry for this pointer.
1661 auto Reloc = find_if(Relocs, [&](const std::pair<uint64_t, SymbolRef> &P) {
1662 return P.first == i;
1664 if (Reloc != Relocs.end()) {
1665 symbol_iterator RelocSym = Reloc->second;
1666 outs() << " " << unwrapOrError(RelocSym->getName(), O->getFileName());
1667 } else {
1668 SymbolName = GuessSymbolName(p, AddrMap);
1669 if (SymbolName)
1670 outs() << " " << SymbolName;
1673 outs() << "\n";
1677 static void DumpRawSectionContents(MachOObjectFile *O, const char *sect,
1678 uint32_t size, uint64_t addr) {
1679 uint32_t cputype = O->getHeader().cputype;
1680 if (cputype == MachO::CPU_TYPE_I386 || cputype == MachO::CPU_TYPE_X86_64) {
1681 uint32_t j;
1682 for (uint32_t i = 0; i < size; i += j, addr += j) {
1683 if (O->is64Bit())
1684 outs() << format("%016" PRIx64, addr) << "\t";
1685 else
1686 outs() << format("%08" PRIx64, addr) << "\t";
1687 for (j = 0; j < 16 && i + j < size; j++) {
1688 uint8_t byte_word = *(sect + i + j);
1689 outs() << format("%02" PRIx32, (uint32_t)byte_word) << " ";
1691 outs() << "\n";
1693 } else {
1694 uint32_t j;
1695 for (uint32_t i = 0; i < size; i += j, addr += j) {
1696 if (O->is64Bit())
1697 outs() << format("%016" PRIx64, addr) << "\t";
1698 else
1699 outs() << format("%08" PRIx64, addr) << "\t";
1700 for (j = 0; j < 4 * sizeof(int32_t) && i + j < size;
1701 j += sizeof(int32_t)) {
1702 if (i + j + sizeof(int32_t) <= size) {
1703 uint32_t long_word;
1704 memcpy(&long_word, sect + i + j, sizeof(int32_t));
1705 if (O->isLittleEndian() != sys::IsLittleEndianHost)
1706 sys::swapByteOrder(long_word);
1707 outs() << format("%08" PRIx32, long_word) << " ";
1708 } else {
1709 for (uint32_t k = 0; i + j + k < size; k++) {
1710 uint8_t byte_word = *(sect + i + j + k);
1711 outs() << format("%02" PRIx32, (uint32_t)byte_word) << " ";
1715 outs() << "\n";
1720 static void DisassembleMachO(StringRef Filename, MachOObjectFile *MachOOF,
1721 StringRef DisSegName, StringRef DisSectName);
1722 static void DumpProtocolSection(MachOObjectFile *O, const char *sect,
1723 uint32_t size, uint32_t addr);
1724 #ifdef HAVE_LIBXAR
1725 static void DumpBitcodeSection(MachOObjectFile *O, const char *sect,
1726 uint32_t size, bool verbose,
1727 bool PrintXarHeader, bool PrintXarFileHeaders,
1728 std::string XarMemberName);
1729 #endif // defined(HAVE_LIBXAR)
1731 static void DumpSectionContents(StringRef Filename, MachOObjectFile *O,
1732 bool verbose) {
1733 SymbolAddressMap AddrMap;
1734 if (verbose)
1735 CreateSymbolAddressMap(O, &AddrMap);
1737 for (unsigned i = 0; i < FilterSections.size(); ++i) {
1738 StringRef DumpSection = FilterSections[i];
1739 std::pair<StringRef, StringRef> DumpSegSectName;
1740 DumpSegSectName = DumpSection.split(',');
1741 StringRef DumpSegName, DumpSectName;
1742 if (!DumpSegSectName.second.empty()) {
1743 DumpSegName = DumpSegSectName.first;
1744 DumpSectName = DumpSegSectName.second;
1745 } else {
1746 DumpSegName = "";
1747 DumpSectName = DumpSegSectName.first;
1749 for (const SectionRef &Section : O->sections()) {
1750 StringRef SectName;
1751 Expected<StringRef> SecNameOrErr = Section.getName();
1752 if (SecNameOrErr)
1753 SectName = *SecNameOrErr;
1754 else
1755 consumeError(SecNameOrErr.takeError());
1757 DataRefImpl Ref = Section.getRawDataRefImpl();
1758 StringRef SegName = O->getSectionFinalSegmentName(Ref);
1759 if ((DumpSegName.empty() || SegName == DumpSegName) &&
1760 (SectName == DumpSectName)) {
1762 uint32_t section_flags;
1763 if (O->is64Bit()) {
1764 const MachO::section_64 Sec = O->getSection64(Ref);
1765 section_flags = Sec.flags;
1767 } else {
1768 const MachO::section Sec = O->getSection(Ref);
1769 section_flags = Sec.flags;
1771 uint32_t section_type = section_flags & MachO::SECTION_TYPE;
1773 StringRef BytesStr =
1774 unwrapOrError(Section.getContents(), O->getFileName());
1775 const char *sect = reinterpret_cast<const char *>(BytesStr.data());
1776 uint32_t sect_size = BytesStr.size();
1777 uint64_t sect_addr = Section.getAddress();
1779 outs() << "Contents of (" << SegName << "," << SectName
1780 << ") section\n";
1782 if (verbose) {
1783 if ((section_flags & MachO::S_ATTR_PURE_INSTRUCTIONS) ||
1784 (section_flags & MachO::S_ATTR_SOME_INSTRUCTIONS)) {
1785 DisassembleMachO(Filename, O, SegName, SectName);
1786 continue;
1788 if (SegName == "__TEXT" && SectName == "__info_plist") {
1789 outs() << sect;
1790 continue;
1792 if (SegName == "__OBJC" && SectName == "__protocol") {
1793 DumpProtocolSection(O, sect, sect_size, sect_addr);
1794 continue;
1796 #ifdef HAVE_LIBXAR
1797 if (SegName == "__LLVM" && SectName == "__bundle") {
1798 DumpBitcodeSection(O, sect, sect_size, verbose, !NoSymbolicOperands,
1799 ArchiveHeaders, "");
1800 continue;
1802 #endif // defined(HAVE_LIBXAR)
1803 switch (section_type) {
1804 case MachO::S_REGULAR:
1805 DumpRawSectionContents(O, sect, sect_size, sect_addr);
1806 break;
1807 case MachO::S_ZEROFILL:
1808 outs() << "zerofill section and has no contents in the file\n";
1809 break;
1810 case MachO::S_CSTRING_LITERALS:
1811 DumpCstringSection(O, sect, sect_size, sect_addr, !NoLeadingAddr);
1812 break;
1813 case MachO::S_4BYTE_LITERALS:
1814 DumpLiteral4Section(O, sect, sect_size, sect_addr, !NoLeadingAddr);
1815 break;
1816 case MachO::S_8BYTE_LITERALS:
1817 DumpLiteral8Section(O, sect, sect_size, sect_addr, !NoLeadingAddr);
1818 break;
1819 case MachO::S_16BYTE_LITERALS:
1820 DumpLiteral16Section(O, sect, sect_size, sect_addr, !NoLeadingAddr);
1821 break;
1822 case MachO::S_LITERAL_POINTERS:
1823 DumpLiteralPointerSection(O, Section, sect, sect_size, sect_addr,
1824 !NoLeadingAddr);
1825 break;
1826 case MachO::S_MOD_INIT_FUNC_POINTERS:
1827 case MachO::S_MOD_TERM_FUNC_POINTERS:
1828 DumpInitTermPointerSection(O, Section, sect, sect_size, sect_addr,
1829 &AddrMap, verbose);
1830 break;
1831 default:
1832 outs() << "Unknown section type ("
1833 << format("0x%08" PRIx32, section_type) << ")\n";
1834 DumpRawSectionContents(O, sect, sect_size, sect_addr);
1835 break;
1837 } else {
1838 if (section_type == MachO::S_ZEROFILL)
1839 outs() << "zerofill section and has no contents in the file\n";
1840 else
1841 DumpRawSectionContents(O, sect, sect_size, sect_addr);
1848 static void DumpInfoPlistSectionContents(StringRef Filename,
1849 MachOObjectFile *O) {
1850 for (const SectionRef &Section : O->sections()) {
1851 StringRef SectName;
1852 Expected<StringRef> SecNameOrErr = Section.getName();
1853 if (SecNameOrErr)
1854 SectName = *SecNameOrErr;
1855 else
1856 consumeError(SecNameOrErr.takeError());
1858 DataRefImpl Ref = Section.getRawDataRefImpl();
1859 StringRef SegName = O->getSectionFinalSegmentName(Ref);
1860 if (SegName == "__TEXT" && SectName == "__info_plist") {
1861 if (!NoLeadingHeaders)
1862 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
1863 StringRef BytesStr =
1864 unwrapOrError(Section.getContents(), O->getFileName());
1865 const char *sect = reinterpret_cast<const char *>(BytesStr.data());
1866 outs() << format("%.*s", BytesStr.size(), sect) << "\n";
1867 return;
1872 // checkMachOAndArchFlags() checks to see if the ObjectFile is a Mach-O file
1873 // and if it is and there is a list of architecture flags is specified then
1874 // check to make sure this Mach-O file is one of those architectures or all
1875 // architectures were specified. If not then an error is generated and this
1876 // routine returns false. Else it returns true.
1877 static bool checkMachOAndArchFlags(ObjectFile *O, StringRef Filename) {
1878 auto *MachO = dyn_cast<MachOObjectFile>(O);
1880 if (!MachO || ArchAll || ArchFlags.empty())
1881 return true;
1883 MachO::mach_header H;
1884 MachO::mach_header_64 H_64;
1885 Triple T;
1886 const char *McpuDefault, *ArchFlag;
1887 if (MachO->is64Bit()) {
1888 H_64 = MachO->MachOObjectFile::getHeader64();
1889 T = MachOObjectFile::getArchTriple(H_64.cputype, H_64.cpusubtype,
1890 &McpuDefault, &ArchFlag);
1891 } else {
1892 H = MachO->MachOObjectFile::getHeader();
1893 T = MachOObjectFile::getArchTriple(H.cputype, H.cpusubtype,
1894 &McpuDefault, &ArchFlag);
1896 const std::string ArchFlagName(ArchFlag);
1897 if (none_of(ArchFlags, [&](const std::string &Name) {
1898 return Name == ArchFlagName;
1899 })) {
1900 WithColor::error(errs(), "llvm-objdump")
1901 << Filename << ": no architecture specified.\n";
1902 return false;
1904 return true;
1907 static void printObjcMetaData(MachOObjectFile *O, bool verbose);
1909 // ProcessMachO() is passed a single opened Mach-O file, which may be an
1910 // archive member and or in a slice of a universal file. It prints the
1911 // the file name and header info and then processes it according to the
1912 // command line options.
1913 static void ProcessMachO(StringRef Name, MachOObjectFile *MachOOF,
1914 StringRef ArchiveMemberName = StringRef(),
1915 StringRef ArchitectureName = StringRef()) {
1916 // If we are doing some processing here on the Mach-O file print the header
1917 // info. And don't print it otherwise like in the case of printing the
1918 // UniversalHeaders or ArchiveHeaders.
1919 if (Disassemble || Relocations || PrivateHeaders || ExportsTrie || Rebase ||
1920 Bind || SymbolTable || LazyBind || WeakBind || IndirectSymbols ||
1921 DataInCode || LinkOptHints || DylibsUsed || DylibId || ObjcMetaData ||
1922 (!FilterSections.empty())) {
1923 if (!NoLeadingHeaders) {
1924 outs() << Name;
1925 if (!ArchiveMemberName.empty())
1926 outs() << '(' << ArchiveMemberName << ')';
1927 if (!ArchitectureName.empty())
1928 outs() << " (architecture " << ArchitectureName << ")";
1929 outs() << ":\n";
1932 // To use the report_error() form with an ArchiveName and FileName set
1933 // these up based on what is passed for Name and ArchiveMemberName.
1934 StringRef ArchiveName;
1935 StringRef FileName;
1936 if (!ArchiveMemberName.empty()) {
1937 ArchiveName = Name;
1938 FileName = ArchiveMemberName;
1939 } else {
1940 ArchiveName = StringRef();
1941 FileName = Name;
1944 // If we need the symbol table to do the operation then check it here to
1945 // produce a good error message as to where the Mach-O file comes from in
1946 // the error message.
1947 if (Disassemble || IndirectSymbols || !FilterSections.empty() || UnwindInfo)
1948 if (Error Err = MachOOF->checkSymbolTable())
1949 reportError(std::move(Err), FileName, ArchiveName, ArchitectureName);
1951 if (DisassembleAll) {
1952 for (const SectionRef &Section : MachOOF->sections()) {
1953 StringRef SectName;
1954 if (Expected<StringRef> NameOrErr = Section.getName())
1955 SectName = *NameOrErr;
1956 else
1957 consumeError(NameOrErr.takeError());
1959 if (SectName.equals("__text")) {
1960 DataRefImpl Ref = Section.getRawDataRefImpl();
1961 StringRef SegName = MachOOF->getSectionFinalSegmentName(Ref);
1962 DisassembleMachO(FileName, MachOOF, SegName, SectName);
1966 else if (Disassemble) {
1967 if (MachOOF->getHeader().filetype == MachO::MH_KEXT_BUNDLE &&
1968 MachOOF->getHeader().cputype == MachO::CPU_TYPE_ARM64)
1969 DisassembleMachO(FileName, MachOOF, "__TEXT_EXEC", "__text");
1970 else
1971 DisassembleMachO(FileName, MachOOF, "__TEXT", "__text");
1973 if (IndirectSymbols)
1974 PrintIndirectSymbols(MachOOF, !NonVerbose);
1975 if (DataInCode)
1976 PrintDataInCodeTable(MachOOF, !NonVerbose);
1977 if (LinkOptHints)
1978 PrintLinkOptHints(MachOOF);
1979 if (Relocations)
1980 PrintRelocations(MachOOF, !NonVerbose);
1981 if (SectionHeaders)
1982 printSectionHeaders(MachOOF);
1983 if (SectionContents)
1984 printSectionContents(MachOOF);
1985 if (!FilterSections.empty())
1986 DumpSectionContents(FileName, MachOOF, !NonVerbose);
1987 if (InfoPlist)
1988 DumpInfoPlistSectionContents(FileName, MachOOF);
1989 if (DylibsUsed)
1990 PrintDylibs(MachOOF, false);
1991 if (DylibId)
1992 PrintDylibs(MachOOF, true);
1993 if (SymbolTable)
1994 printSymbolTable(MachOOF, ArchiveName, ArchitectureName);
1995 if (UnwindInfo)
1996 printMachOUnwindInfo(MachOOF);
1997 if (PrivateHeaders) {
1998 printMachOFileHeader(MachOOF);
1999 printMachOLoadCommands(MachOOF);
2001 if (FirstPrivateHeader)
2002 printMachOFileHeader(MachOOF);
2003 if (ObjcMetaData)
2004 printObjcMetaData(MachOOF, !NonVerbose);
2005 if (ExportsTrie)
2006 printExportsTrie(MachOOF);
2007 if (Rebase)
2008 printRebaseTable(MachOOF);
2009 if (Bind)
2010 printBindTable(MachOOF);
2011 if (LazyBind)
2012 printLazyBindTable(MachOOF);
2013 if (WeakBind)
2014 printWeakBindTable(MachOOF);
2016 if (DwarfDumpType != DIDT_Null) {
2017 std::unique_ptr<DIContext> DICtx = DWARFContext::create(*MachOOF);
2018 // Dump the complete DWARF structure.
2019 DIDumpOptions DumpOpts;
2020 DumpOpts.DumpType = DwarfDumpType;
2021 DICtx->dump(outs(), DumpOpts);
2025 // printUnknownCPUType() helps print_fat_headers for unknown CPU's.
2026 static void printUnknownCPUType(uint32_t cputype, uint32_t cpusubtype) {
2027 outs() << " cputype (" << cputype << ")\n";
2028 outs() << " cpusubtype (" << cpusubtype << ")\n";
2031 // printCPUType() helps print_fat_headers by printing the cputype and
2032 // pusubtype (symbolically for the one's it knows about).
2033 static void printCPUType(uint32_t cputype, uint32_t cpusubtype) {
2034 switch (cputype) {
2035 case MachO::CPU_TYPE_I386:
2036 switch (cpusubtype) {
2037 case MachO::CPU_SUBTYPE_I386_ALL:
2038 outs() << " cputype CPU_TYPE_I386\n";
2039 outs() << " cpusubtype CPU_SUBTYPE_I386_ALL\n";
2040 break;
2041 default:
2042 printUnknownCPUType(cputype, cpusubtype);
2043 break;
2045 break;
2046 case MachO::CPU_TYPE_X86_64:
2047 switch (cpusubtype) {
2048 case MachO::CPU_SUBTYPE_X86_64_ALL:
2049 outs() << " cputype CPU_TYPE_X86_64\n";
2050 outs() << " cpusubtype CPU_SUBTYPE_X86_64_ALL\n";
2051 break;
2052 case MachO::CPU_SUBTYPE_X86_64_H:
2053 outs() << " cputype CPU_TYPE_X86_64\n";
2054 outs() << " cpusubtype CPU_SUBTYPE_X86_64_H\n";
2055 break;
2056 default:
2057 printUnknownCPUType(cputype, cpusubtype);
2058 break;
2060 break;
2061 case MachO::CPU_TYPE_ARM:
2062 switch (cpusubtype) {
2063 case MachO::CPU_SUBTYPE_ARM_ALL:
2064 outs() << " cputype CPU_TYPE_ARM\n";
2065 outs() << " cpusubtype CPU_SUBTYPE_ARM_ALL\n";
2066 break;
2067 case MachO::CPU_SUBTYPE_ARM_V4T:
2068 outs() << " cputype CPU_TYPE_ARM\n";
2069 outs() << " cpusubtype CPU_SUBTYPE_ARM_V4T\n";
2070 break;
2071 case MachO::CPU_SUBTYPE_ARM_V5TEJ:
2072 outs() << " cputype CPU_TYPE_ARM\n";
2073 outs() << " cpusubtype CPU_SUBTYPE_ARM_V5TEJ\n";
2074 break;
2075 case MachO::CPU_SUBTYPE_ARM_XSCALE:
2076 outs() << " cputype CPU_TYPE_ARM\n";
2077 outs() << " cpusubtype CPU_SUBTYPE_ARM_XSCALE\n";
2078 break;
2079 case MachO::CPU_SUBTYPE_ARM_V6:
2080 outs() << " cputype CPU_TYPE_ARM\n";
2081 outs() << " cpusubtype CPU_SUBTYPE_ARM_V6\n";
2082 break;
2083 case MachO::CPU_SUBTYPE_ARM_V6M:
2084 outs() << " cputype CPU_TYPE_ARM\n";
2085 outs() << " cpusubtype CPU_SUBTYPE_ARM_V6M\n";
2086 break;
2087 case MachO::CPU_SUBTYPE_ARM_V7:
2088 outs() << " cputype CPU_TYPE_ARM\n";
2089 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7\n";
2090 break;
2091 case MachO::CPU_SUBTYPE_ARM_V7EM:
2092 outs() << " cputype CPU_TYPE_ARM\n";
2093 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7EM\n";
2094 break;
2095 case MachO::CPU_SUBTYPE_ARM_V7K:
2096 outs() << " cputype CPU_TYPE_ARM\n";
2097 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7K\n";
2098 break;
2099 case MachO::CPU_SUBTYPE_ARM_V7M:
2100 outs() << " cputype CPU_TYPE_ARM\n";
2101 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7M\n";
2102 break;
2103 case MachO::CPU_SUBTYPE_ARM_V7S:
2104 outs() << " cputype CPU_TYPE_ARM\n";
2105 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7S\n";
2106 break;
2107 default:
2108 printUnknownCPUType(cputype, cpusubtype);
2109 break;
2111 break;
2112 case MachO::CPU_TYPE_ARM64:
2113 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
2114 case MachO::CPU_SUBTYPE_ARM64_ALL:
2115 outs() << " cputype CPU_TYPE_ARM64\n";
2116 outs() << " cpusubtype CPU_SUBTYPE_ARM64_ALL\n";
2117 break;
2118 case MachO::CPU_SUBTYPE_ARM64E:
2119 outs() << " cputype CPU_TYPE_ARM64\n";
2120 outs() << " cpusubtype CPU_SUBTYPE_ARM64E\n";
2121 break;
2122 default:
2123 printUnknownCPUType(cputype, cpusubtype);
2124 break;
2126 break;
2127 case MachO::CPU_TYPE_ARM64_32:
2128 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
2129 case MachO::CPU_SUBTYPE_ARM64_32_V8:
2130 outs() << " cputype CPU_TYPE_ARM64_32\n";
2131 outs() << " cpusubtype CPU_SUBTYPE_ARM64_32_V8\n";
2132 break;
2133 default:
2134 printUnknownCPUType(cputype, cpusubtype);
2135 break;
2137 break;
2138 default:
2139 printUnknownCPUType(cputype, cpusubtype);
2140 break;
2144 static void printMachOUniversalHeaders(const object::MachOUniversalBinary *UB,
2145 bool verbose) {
2146 outs() << "Fat headers\n";
2147 if (verbose) {
2148 if (UB->getMagic() == MachO::FAT_MAGIC)
2149 outs() << "fat_magic FAT_MAGIC\n";
2150 else // UB->getMagic() == MachO::FAT_MAGIC_64
2151 outs() << "fat_magic FAT_MAGIC_64\n";
2152 } else
2153 outs() << "fat_magic " << format("0x%" PRIx32, MachO::FAT_MAGIC) << "\n";
2155 uint32_t nfat_arch = UB->getNumberOfObjects();
2156 StringRef Buf = UB->getData();
2157 uint64_t size = Buf.size();
2158 uint64_t big_size = sizeof(struct MachO::fat_header) +
2159 nfat_arch * sizeof(struct MachO::fat_arch);
2160 outs() << "nfat_arch " << UB->getNumberOfObjects();
2161 if (nfat_arch == 0)
2162 outs() << " (malformed, contains zero architecture types)\n";
2163 else if (big_size > size)
2164 outs() << " (malformed, architectures past end of file)\n";
2165 else
2166 outs() << "\n";
2168 for (uint32_t i = 0; i < nfat_arch; ++i) {
2169 MachOUniversalBinary::ObjectForArch OFA(UB, i);
2170 uint32_t cputype = OFA.getCPUType();
2171 uint32_t cpusubtype = OFA.getCPUSubType();
2172 outs() << "architecture ";
2173 for (uint32_t j = 0; i != 0 && j <= i - 1; j++) {
2174 MachOUniversalBinary::ObjectForArch other_OFA(UB, j);
2175 uint32_t other_cputype = other_OFA.getCPUType();
2176 uint32_t other_cpusubtype = other_OFA.getCPUSubType();
2177 if (cputype != 0 && cpusubtype != 0 && cputype == other_cputype &&
2178 (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) ==
2179 (other_cpusubtype & ~MachO::CPU_SUBTYPE_MASK)) {
2180 outs() << "(illegal duplicate architecture) ";
2181 break;
2184 if (verbose) {
2185 outs() << OFA.getArchFlagName() << "\n";
2186 printCPUType(cputype, cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
2187 } else {
2188 outs() << i << "\n";
2189 outs() << " cputype " << cputype << "\n";
2190 outs() << " cpusubtype " << (cpusubtype & ~MachO::CPU_SUBTYPE_MASK)
2191 << "\n";
2193 if (verbose &&
2194 (cpusubtype & MachO::CPU_SUBTYPE_MASK) == MachO::CPU_SUBTYPE_LIB64)
2195 outs() << " capabilities CPU_SUBTYPE_LIB64\n";
2196 else
2197 outs() << " capabilities "
2198 << format("0x%" PRIx32,
2199 (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24) << "\n";
2200 outs() << " offset " << OFA.getOffset();
2201 if (OFA.getOffset() > size)
2202 outs() << " (past end of file)";
2203 if (OFA.getOffset() % (1ull << OFA.getAlign()) != 0)
2204 outs() << " (not aligned on it's alignment (2^" << OFA.getAlign() << ")";
2205 outs() << "\n";
2206 outs() << " size " << OFA.getSize();
2207 big_size = OFA.getOffset() + OFA.getSize();
2208 if (big_size > size)
2209 outs() << " (past end of file)";
2210 outs() << "\n";
2211 outs() << " align 2^" << OFA.getAlign() << " (" << (1 << OFA.getAlign())
2212 << ")\n";
2216 static void printArchiveChild(StringRef Filename, const Archive::Child &C,
2217 size_t ChildIndex, bool verbose,
2218 bool print_offset,
2219 StringRef ArchitectureName = StringRef()) {
2220 if (print_offset)
2221 outs() << C.getChildOffset() << "\t";
2222 sys::fs::perms Mode =
2223 unwrapOrError(C.getAccessMode(), getFileNameForError(C, ChildIndex),
2224 Filename, ArchitectureName);
2225 if (verbose) {
2226 // FIXME: this first dash, "-", is for (Mode & S_IFMT) == S_IFREG.
2227 // But there is nothing in sys::fs::perms for S_IFMT or S_IFREG.
2228 outs() << "-";
2229 outs() << ((Mode & sys::fs::owner_read) ? "r" : "-");
2230 outs() << ((Mode & sys::fs::owner_write) ? "w" : "-");
2231 outs() << ((Mode & sys::fs::owner_exe) ? "x" : "-");
2232 outs() << ((Mode & sys::fs::group_read) ? "r" : "-");
2233 outs() << ((Mode & sys::fs::group_write) ? "w" : "-");
2234 outs() << ((Mode & sys::fs::group_exe) ? "x" : "-");
2235 outs() << ((Mode & sys::fs::others_read) ? "r" : "-");
2236 outs() << ((Mode & sys::fs::others_write) ? "w" : "-");
2237 outs() << ((Mode & sys::fs::others_exe) ? "x" : "-");
2238 } else {
2239 outs() << format("0%o ", Mode);
2242 outs() << format("%3d/%-3d %5" PRId64 " ",
2243 unwrapOrError(C.getUID(), getFileNameForError(C, ChildIndex),
2244 Filename, ArchitectureName),
2245 unwrapOrError(C.getGID(), getFileNameForError(C, ChildIndex),
2246 Filename, ArchitectureName),
2247 unwrapOrError(C.getRawSize(),
2248 getFileNameForError(C, ChildIndex), Filename,
2249 ArchitectureName));
2251 StringRef RawLastModified = C.getRawLastModified();
2252 if (verbose) {
2253 unsigned Seconds;
2254 if (RawLastModified.getAsInteger(10, Seconds))
2255 outs() << "(date: \"" << RawLastModified
2256 << "\" contains non-decimal chars) ";
2257 else {
2258 // Since cime(3) returns a 26 character string of the form:
2259 // "Sun Sep 16 01:03:52 1973\n\0"
2260 // just print 24 characters.
2261 time_t t = Seconds;
2262 outs() << format("%.24s ", ctime(&t));
2264 } else {
2265 outs() << RawLastModified << " ";
2268 if (verbose) {
2269 Expected<StringRef> NameOrErr = C.getName();
2270 if (!NameOrErr) {
2271 consumeError(NameOrErr.takeError());
2272 outs() << unwrapOrError(C.getRawName(),
2273 getFileNameForError(C, ChildIndex), Filename,
2274 ArchitectureName)
2275 << "\n";
2276 } else {
2277 StringRef Name = NameOrErr.get();
2278 outs() << Name << "\n";
2280 } else {
2281 outs() << unwrapOrError(C.getRawName(), getFileNameForError(C, ChildIndex),
2282 Filename, ArchitectureName)
2283 << "\n";
2287 static void printArchiveHeaders(StringRef Filename, Archive *A, bool verbose,
2288 bool print_offset,
2289 StringRef ArchitectureName = StringRef()) {
2290 Error Err = Error::success();
2291 size_t I = 0;
2292 for (const auto &C : A->children(Err, false))
2293 printArchiveChild(Filename, C, I++, verbose, print_offset,
2294 ArchitectureName);
2296 if (Err)
2297 reportError(std::move(Err), Filename, "", ArchitectureName);
2300 static bool ValidateArchFlags() {
2301 // Check for -arch all and verifiy the -arch flags are valid.
2302 for (unsigned i = 0; i < ArchFlags.size(); ++i) {
2303 if (ArchFlags[i] == "all") {
2304 ArchAll = true;
2305 } else {
2306 if (!MachOObjectFile::isValidArch(ArchFlags[i])) {
2307 WithColor::error(errs(), "llvm-objdump")
2308 << "unknown architecture named '" + ArchFlags[i] +
2309 "'for the -arch option\n";
2310 return false;
2314 return true;
2317 // ParseInputMachO() parses the named Mach-O file in Filename and handles the
2318 // -arch flags selecting just those slices as specified by them and also parses
2319 // archive files. Then for each individual Mach-O file ProcessMachO() is
2320 // called to process the file based on the command line options.
2321 void parseInputMachO(StringRef Filename) {
2322 if (!ValidateArchFlags())
2323 return;
2325 // Attempt to open the binary.
2326 Expected<OwningBinary<Binary>> BinaryOrErr = createBinary(Filename);
2327 if (!BinaryOrErr) {
2328 if (Error E = isNotObjectErrorInvalidFileType(BinaryOrErr.takeError()))
2329 reportError(std::move(E), Filename);
2330 else
2331 outs() << Filename << ": is not an object file\n";
2332 return;
2334 Binary &Bin = *BinaryOrErr.get().getBinary();
2336 if (Archive *A = dyn_cast<Archive>(&Bin)) {
2337 outs() << "Archive : " << Filename << "\n";
2338 if (ArchiveHeaders)
2339 printArchiveHeaders(Filename, A, !NonVerbose, ArchiveMemberOffsets);
2341 Error Err = Error::success();
2342 unsigned I = -1;
2343 for (auto &C : A->children(Err)) {
2344 ++I;
2345 Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
2346 if (!ChildOrErr) {
2347 if (Error E = isNotObjectErrorInvalidFileType(ChildOrErr.takeError()))
2348 reportError(std::move(E), getFileNameForError(C, I), Filename);
2349 continue;
2351 if (MachOObjectFile *O = dyn_cast<MachOObjectFile>(&*ChildOrErr.get())) {
2352 if (!checkMachOAndArchFlags(O, Filename))
2353 return;
2354 ProcessMachO(Filename, O, O->getFileName());
2357 if (Err)
2358 reportError(std::move(Err), Filename);
2359 return;
2361 if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(&Bin)) {
2362 parseInputMachO(UB);
2363 return;
2365 if (ObjectFile *O = dyn_cast<ObjectFile>(&Bin)) {
2366 if (!checkMachOAndArchFlags(O, Filename))
2367 return;
2368 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&*O))
2369 ProcessMachO(Filename, MachOOF);
2370 else
2371 WithColor::error(errs(), "llvm-objdump")
2372 << Filename << "': "
2373 << "object is not a Mach-O file type.\n";
2374 return;
2376 llvm_unreachable("Input object can't be invalid at this point");
2379 void parseInputMachO(MachOUniversalBinary *UB) {
2380 if (!ValidateArchFlags())
2381 return;
2383 auto Filename = UB->getFileName();
2385 if (UniversalHeaders)
2386 printMachOUniversalHeaders(UB, !NonVerbose);
2388 // If we have a list of architecture flags specified dump only those.
2389 if (!ArchAll && !ArchFlags.empty()) {
2390 // Look for a slice in the universal binary that matches each ArchFlag.
2391 bool ArchFound;
2392 for (unsigned i = 0; i < ArchFlags.size(); ++i) {
2393 ArchFound = false;
2394 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
2395 E = UB->end_objects();
2396 I != E; ++I) {
2397 if (ArchFlags[i] == I->getArchFlagName()) {
2398 ArchFound = true;
2399 Expected<std::unique_ptr<ObjectFile>> ObjOrErr =
2400 I->getAsObjectFile();
2401 std::string ArchitectureName = "";
2402 if (ArchFlags.size() > 1)
2403 ArchitectureName = I->getArchFlagName();
2404 if (ObjOrErr) {
2405 ObjectFile &O = *ObjOrErr.get();
2406 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&O))
2407 ProcessMachO(Filename, MachOOF, "", ArchitectureName);
2408 } else if (Error E = isNotObjectErrorInvalidFileType(
2409 ObjOrErr.takeError())) {
2410 reportError(std::move(E), "", Filename, ArchitectureName);
2411 continue;
2412 } else if (Expected<std::unique_ptr<Archive>> AOrErr =
2413 I->getAsArchive()) {
2414 std::unique_ptr<Archive> &A = *AOrErr;
2415 outs() << "Archive : " << Filename;
2416 if (!ArchitectureName.empty())
2417 outs() << " (architecture " << ArchitectureName << ")";
2418 outs() << "\n";
2419 if (ArchiveHeaders)
2420 printArchiveHeaders(Filename, A.get(), !NonVerbose,
2421 ArchiveMemberOffsets, ArchitectureName);
2422 Error Err = Error::success();
2423 unsigned I = -1;
2424 for (auto &C : A->children(Err)) {
2425 ++I;
2426 Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
2427 if (!ChildOrErr) {
2428 if (Error E =
2429 isNotObjectErrorInvalidFileType(ChildOrErr.takeError()))
2430 reportError(std::move(E), getFileNameForError(C, I), Filename,
2431 ArchitectureName);
2432 continue;
2434 if (MachOObjectFile *O =
2435 dyn_cast<MachOObjectFile>(&*ChildOrErr.get()))
2436 ProcessMachO(Filename, O, O->getFileName(), ArchitectureName);
2438 if (Err)
2439 reportError(std::move(Err), Filename);
2440 } else {
2441 consumeError(AOrErr.takeError());
2442 reportError(Filename,
2443 "Mach-O universal file for architecture " +
2444 StringRef(I->getArchFlagName()) +
2445 " is not a Mach-O file or an archive file");
2449 if (!ArchFound) {
2450 WithColor::error(errs(), "llvm-objdump")
2451 << "file: " + Filename + " does not contain "
2452 << "architecture: " + ArchFlags[i] + "\n";
2453 return;
2456 return;
2458 // No architecture flags were specified so if this contains a slice that
2459 // matches the host architecture dump only that.
2460 if (!ArchAll) {
2461 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
2462 E = UB->end_objects();
2463 I != E; ++I) {
2464 if (MachOObjectFile::getHostArch().getArchName() ==
2465 I->getArchFlagName()) {
2466 Expected<std::unique_ptr<ObjectFile>> ObjOrErr = I->getAsObjectFile();
2467 std::string ArchiveName;
2468 ArchiveName.clear();
2469 if (ObjOrErr) {
2470 ObjectFile &O = *ObjOrErr.get();
2471 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&O))
2472 ProcessMachO(Filename, MachOOF);
2473 } else if (Error E =
2474 isNotObjectErrorInvalidFileType(ObjOrErr.takeError())) {
2475 reportError(std::move(E), Filename);
2476 } else if (Expected<std::unique_ptr<Archive>> AOrErr =
2477 I->getAsArchive()) {
2478 std::unique_ptr<Archive> &A = *AOrErr;
2479 outs() << "Archive : " << Filename << "\n";
2480 if (ArchiveHeaders)
2481 printArchiveHeaders(Filename, A.get(), !NonVerbose,
2482 ArchiveMemberOffsets);
2483 Error Err = Error::success();
2484 unsigned I = -1;
2485 for (auto &C : A->children(Err)) {
2486 ++I;
2487 Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
2488 if (!ChildOrErr) {
2489 if (Error E =
2490 isNotObjectErrorInvalidFileType(ChildOrErr.takeError()))
2491 reportError(std::move(E), getFileNameForError(C, I), Filename);
2492 continue;
2494 if (MachOObjectFile *O =
2495 dyn_cast<MachOObjectFile>(&*ChildOrErr.get()))
2496 ProcessMachO(Filename, O, O->getFileName());
2498 if (Err)
2499 reportError(std::move(Err), Filename);
2500 } else {
2501 consumeError(AOrErr.takeError());
2502 reportError(Filename, "Mach-O universal file for architecture " +
2503 StringRef(I->getArchFlagName()) +
2504 " is not a Mach-O file or an archive file");
2506 return;
2510 // Either all architectures have been specified or none have been specified
2511 // and this does not contain the host architecture so dump all the slices.
2512 bool moreThanOneArch = UB->getNumberOfObjects() > 1;
2513 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
2514 E = UB->end_objects();
2515 I != E; ++I) {
2516 Expected<std::unique_ptr<ObjectFile>> ObjOrErr = I->getAsObjectFile();
2517 std::string ArchitectureName = "";
2518 if (moreThanOneArch)
2519 ArchitectureName = I->getArchFlagName();
2520 if (ObjOrErr) {
2521 ObjectFile &Obj = *ObjOrErr.get();
2522 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&Obj))
2523 ProcessMachO(Filename, MachOOF, "", ArchitectureName);
2524 } else if (Error E =
2525 isNotObjectErrorInvalidFileType(ObjOrErr.takeError())) {
2526 reportError(std::move(E), Filename, "", ArchitectureName);
2527 } else if (Expected<std::unique_ptr<Archive>> AOrErr = I->getAsArchive()) {
2528 std::unique_ptr<Archive> &A = *AOrErr;
2529 outs() << "Archive : " << Filename;
2530 if (!ArchitectureName.empty())
2531 outs() << " (architecture " << ArchitectureName << ")";
2532 outs() << "\n";
2533 if (ArchiveHeaders)
2534 printArchiveHeaders(Filename, A.get(), !NonVerbose,
2535 ArchiveMemberOffsets, ArchitectureName);
2536 Error Err = Error::success();
2537 unsigned I = -1;
2538 for (auto &C : A->children(Err)) {
2539 ++I;
2540 Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
2541 if (!ChildOrErr) {
2542 if (Error E = isNotObjectErrorInvalidFileType(ChildOrErr.takeError()))
2543 reportError(std::move(E), getFileNameForError(C, I), Filename,
2544 ArchitectureName);
2545 continue;
2547 if (MachOObjectFile *O =
2548 dyn_cast<MachOObjectFile>(&*ChildOrErr.get())) {
2549 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(O))
2550 ProcessMachO(Filename, MachOOF, MachOOF->getFileName(),
2551 ArchitectureName);
2554 if (Err)
2555 reportError(std::move(Err), Filename);
2556 } else {
2557 consumeError(AOrErr.takeError());
2558 reportError(Filename, "Mach-O universal file for architecture " +
2559 StringRef(I->getArchFlagName()) +
2560 " is not a Mach-O file or an archive file");
2565 // The block of info used by the Symbolizer call backs.
2566 struct DisassembleInfo {
2567 DisassembleInfo(MachOObjectFile *O, SymbolAddressMap *AddrMap,
2568 std::vector<SectionRef> *Sections, bool verbose)
2569 : verbose(verbose), O(O), AddrMap(AddrMap), Sections(Sections) {}
2570 bool verbose;
2571 MachOObjectFile *O;
2572 SectionRef S;
2573 SymbolAddressMap *AddrMap;
2574 std::vector<SectionRef> *Sections;
2575 const char *class_name = nullptr;
2576 const char *selector_name = nullptr;
2577 std::unique_ptr<char[]> method = nullptr;
2578 char *demangled_name = nullptr;
2579 uint64_t adrp_addr = 0;
2580 uint32_t adrp_inst = 0;
2581 std::unique_ptr<SymbolAddressMap> bindtable;
2582 uint32_t depth = 0;
2585 // SymbolizerGetOpInfo() is the operand information call back function.
2586 // This is called to get the symbolic information for operand(s) of an
2587 // instruction when it is being done. This routine does this from
2588 // the relocation information, symbol table, etc. That block of information
2589 // is a pointer to the struct DisassembleInfo that was passed when the
2590 // disassembler context was created and passed to back to here when
2591 // called back by the disassembler for instruction operands that could have
2592 // relocation information. The address of the instruction containing operand is
2593 // at the Pc parameter. The immediate value the operand has is passed in
2594 // op_info->Value and is at Offset past the start of the instruction and has a
2595 // byte Size of 1, 2 or 4. The symbolc information is returned in TagBuf is the
2596 // LLVMOpInfo1 struct defined in the header "llvm-c/Disassembler.h" as symbol
2597 // names and addends of the symbolic expression to add for the operand. The
2598 // value of TagType is currently 1 (for the LLVMOpInfo1 struct). If symbolic
2599 // information is returned then this function returns 1 else it returns 0.
2600 static int SymbolizerGetOpInfo(void *DisInfo, uint64_t Pc, uint64_t Offset,
2601 uint64_t Size, int TagType, void *TagBuf) {
2602 struct DisassembleInfo *info = (struct DisassembleInfo *)DisInfo;
2603 struct LLVMOpInfo1 *op_info = (struct LLVMOpInfo1 *)TagBuf;
2604 uint64_t value = op_info->Value;
2606 // Make sure all fields returned are zero if we don't set them.
2607 memset((void *)op_info, '\0', sizeof(struct LLVMOpInfo1));
2608 op_info->Value = value;
2610 // If the TagType is not the value 1 which it code knows about or if no
2611 // verbose symbolic information is wanted then just return 0, indicating no
2612 // information is being returned.
2613 if (TagType != 1 || !info->verbose)
2614 return 0;
2616 unsigned int Arch = info->O->getArch();
2617 if (Arch == Triple::x86) {
2618 if (Size != 1 && Size != 2 && Size != 4 && Size != 0)
2619 return 0;
2620 if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
2621 // TODO:
2622 // Search the external relocation entries of a fully linked image
2623 // (if any) for an entry that matches this segment offset.
2624 // uint32_t seg_offset = (Pc + Offset);
2625 return 0;
2627 // In MH_OBJECT filetypes search the section's relocation entries (if any)
2628 // for an entry for this section offset.
2629 uint32_t sect_addr = info->S.getAddress();
2630 uint32_t sect_offset = (Pc + Offset) - sect_addr;
2631 bool reloc_found = false;
2632 DataRefImpl Rel;
2633 MachO::any_relocation_info RE;
2634 bool isExtern = false;
2635 SymbolRef Symbol;
2636 bool r_scattered = false;
2637 uint32_t r_value, pair_r_value, r_type;
2638 for (const RelocationRef &Reloc : info->S.relocations()) {
2639 uint64_t RelocOffset = Reloc.getOffset();
2640 if (RelocOffset == sect_offset) {
2641 Rel = Reloc.getRawDataRefImpl();
2642 RE = info->O->getRelocation(Rel);
2643 r_type = info->O->getAnyRelocationType(RE);
2644 r_scattered = info->O->isRelocationScattered(RE);
2645 if (r_scattered) {
2646 r_value = info->O->getScatteredRelocationValue(RE);
2647 if (r_type == MachO::GENERIC_RELOC_SECTDIFF ||
2648 r_type == MachO::GENERIC_RELOC_LOCAL_SECTDIFF) {
2649 DataRefImpl RelNext = Rel;
2650 info->O->moveRelocationNext(RelNext);
2651 MachO::any_relocation_info RENext;
2652 RENext = info->O->getRelocation(RelNext);
2653 if (info->O->isRelocationScattered(RENext))
2654 pair_r_value = info->O->getScatteredRelocationValue(RENext);
2655 else
2656 return 0;
2658 } else {
2659 isExtern = info->O->getPlainRelocationExternal(RE);
2660 if (isExtern) {
2661 symbol_iterator RelocSym = Reloc.getSymbol();
2662 Symbol = *RelocSym;
2665 reloc_found = true;
2666 break;
2669 if (reloc_found && isExtern) {
2670 op_info->AddSymbol.Present = 1;
2671 op_info->AddSymbol.Name =
2672 unwrapOrError(Symbol.getName(), info->O->getFileName()).data();
2673 // For i386 extern relocation entries the value in the instruction is
2674 // the offset from the symbol, and value is already set in op_info->Value.
2675 return 1;
2677 if (reloc_found && (r_type == MachO::GENERIC_RELOC_SECTDIFF ||
2678 r_type == MachO::GENERIC_RELOC_LOCAL_SECTDIFF)) {
2679 const char *add = GuessSymbolName(r_value, info->AddrMap);
2680 const char *sub = GuessSymbolName(pair_r_value, info->AddrMap);
2681 uint32_t offset = value - (r_value - pair_r_value);
2682 op_info->AddSymbol.Present = 1;
2683 if (add != nullptr)
2684 op_info->AddSymbol.Name = add;
2685 else
2686 op_info->AddSymbol.Value = r_value;
2687 op_info->SubtractSymbol.Present = 1;
2688 if (sub != nullptr)
2689 op_info->SubtractSymbol.Name = sub;
2690 else
2691 op_info->SubtractSymbol.Value = pair_r_value;
2692 op_info->Value = offset;
2693 return 1;
2695 return 0;
2697 if (Arch == Triple::x86_64) {
2698 if (Size != 1 && Size != 2 && Size != 4 && Size != 0)
2699 return 0;
2700 // For non MH_OBJECT types, like MH_KEXT_BUNDLE, Search the external
2701 // relocation entries of a linked image (if any) for an entry that matches
2702 // this segment offset.
2703 if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
2704 uint64_t seg_offset = Pc + Offset;
2705 bool reloc_found = false;
2706 DataRefImpl Rel;
2707 MachO::any_relocation_info RE;
2708 bool isExtern = false;
2709 SymbolRef Symbol;
2710 for (const RelocationRef &Reloc : info->O->external_relocations()) {
2711 uint64_t RelocOffset = Reloc.getOffset();
2712 if (RelocOffset == seg_offset) {
2713 Rel = Reloc.getRawDataRefImpl();
2714 RE = info->O->getRelocation(Rel);
2715 // external relocation entries should always be external.
2716 isExtern = info->O->getPlainRelocationExternal(RE);
2717 if (isExtern) {
2718 symbol_iterator RelocSym = Reloc.getSymbol();
2719 Symbol = *RelocSym;
2721 reloc_found = true;
2722 break;
2725 if (reloc_found && isExtern) {
2726 // The Value passed in will be adjusted by the Pc if the instruction
2727 // adds the Pc. But for x86_64 external relocation entries the Value
2728 // is the offset from the external symbol.
2729 if (info->O->getAnyRelocationPCRel(RE))
2730 op_info->Value -= Pc + Offset + Size;
2731 const char *name =
2732 unwrapOrError(Symbol.getName(), info->O->getFileName()).data();
2733 op_info->AddSymbol.Present = 1;
2734 op_info->AddSymbol.Name = name;
2735 return 1;
2737 return 0;
2739 // In MH_OBJECT filetypes search the section's relocation entries (if any)
2740 // for an entry for this section offset.
2741 uint64_t sect_addr = info->S.getAddress();
2742 uint64_t sect_offset = (Pc + Offset) - sect_addr;
2743 bool reloc_found = false;
2744 DataRefImpl Rel;
2745 MachO::any_relocation_info RE;
2746 bool isExtern = false;
2747 SymbolRef Symbol;
2748 for (const RelocationRef &Reloc : info->S.relocations()) {
2749 uint64_t RelocOffset = Reloc.getOffset();
2750 if (RelocOffset == sect_offset) {
2751 Rel = Reloc.getRawDataRefImpl();
2752 RE = info->O->getRelocation(Rel);
2753 // NOTE: Scattered relocations don't exist on x86_64.
2754 isExtern = info->O->getPlainRelocationExternal(RE);
2755 if (isExtern) {
2756 symbol_iterator RelocSym = Reloc.getSymbol();
2757 Symbol = *RelocSym;
2759 reloc_found = true;
2760 break;
2763 if (reloc_found && isExtern) {
2764 // The Value passed in will be adjusted by the Pc if the instruction
2765 // adds the Pc. But for x86_64 external relocation entries the Value
2766 // is the offset from the external symbol.
2767 if (info->O->getAnyRelocationPCRel(RE))
2768 op_info->Value -= Pc + Offset + Size;
2769 const char *name =
2770 unwrapOrError(Symbol.getName(), info->O->getFileName()).data();
2771 unsigned Type = info->O->getAnyRelocationType(RE);
2772 if (Type == MachO::X86_64_RELOC_SUBTRACTOR) {
2773 DataRefImpl RelNext = Rel;
2774 info->O->moveRelocationNext(RelNext);
2775 MachO::any_relocation_info RENext = info->O->getRelocation(RelNext);
2776 unsigned TypeNext = info->O->getAnyRelocationType(RENext);
2777 bool isExternNext = info->O->getPlainRelocationExternal(RENext);
2778 unsigned SymbolNum = info->O->getPlainRelocationSymbolNum(RENext);
2779 if (TypeNext == MachO::X86_64_RELOC_UNSIGNED && isExternNext) {
2780 op_info->SubtractSymbol.Present = 1;
2781 op_info->SubtractSymbol.Name = name;
2782 symbol_iterator RelocSymNext = info->O->getSymbolByIndex(SymbolNum);
2783 Symbol = *RelocSymNext;
2784 name = unwrapOrError(Symbol.getName(), info->O->getFileName()).data();
2787 // TODO: add the VariantKinds to op_info->VariantKind for relocation types
2788 // like: X86_64_RELOC_TLV, X86_64_RELOC_GOT_LOAD and X86_64_RELOC_GOT.
2789 op_info->AddSymbol.Present = 1;
2790 op_info->AddSymbol.Name = name;
2791 return 1;
2793 return 0;
2795 if (Arch == Triple::arm) {
2796 if (Offset != 0 || (Size != 4 && Size != 2))
2797 return 0;
2798 if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
2799 // TODO:
2800 // Search the external relocation entries of a fully linked image
2801 // (if any) for an entry that matches this segment offset.
2802 // uint32_t seg_offset = (Pc + Offset);
2803 return 0;
2805 // In MH_OBJECT filetypes search the section's relocation entries (if any)
2806 // for an entry for this section offset.
2807 uint32_t sect_addr = info->S.getAddress();
2808 uint32_t sect_offset = (Pc + Offset) - sect_addr;
2809 DataRefImpl Rel;
2810 MachO::any_relocation_info RE;
2811 bool isExtern = false;
2812 SymbolRef Symbol;
2813 bool r_scattered = false;
2814 uint32_t r_value, pair_r_value, r_type, r_length, other_half;
2815 auto Reloc =
2816 find_if(info->S.relocations(), [&](const RelocationRef &Reloc) {
2817 uint64_t RelocOffset = Reloc.getOffset();
2818 return RelocOffset == sect_offset;
2821 if (Reloc == info->S.relocations().end())
2822 return 0;
2824 Rel = Reloc->getRawDataRefImpl();
2825 RE = info->O->getRelocation(Rel);
2826 r_length = info->O->getAnyRelocationLength(RE);
2827 r_scattered = info->O->isRelocationScattered(RE);
2828 if (r_scattered) {
2829 r_value = info->O->getScatteredRelocationValue(RE);
2830 r_type = info->O->getScatteredRelocationType(RE);
2831 } else {
2832 r_type = info->O->getAnyRelocationType(RE);
2833 isExtern = info->O->getPlainRelocationExternal(RE);
2834 if (isExtern) {
2835 symbol_iterator RelocSym = Reloc->getSymbol();
2836 Symbol = *RelocSym;
2839 if (r_type == MachO::ARM_RELOC_HALF ||
2840 r_type == MachO::ARM_RELOC_SECTDIFF ||
2841 r_type == MachO::ARM_RELOC_LOCAL_SECTDIFF ||
2842 r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
2843 DataRefImpl RelNext = Rel;
2844 info->O->moveRelocationNext(RelNext);
2845 MachO::any_relocation_info RENext;
2846 RENext = info->O->getRelocation(RelNext);
2847 other_half = info->O->getAnyRelocationAddress(RENext) & 0xffff;
2848 if (info->O->isRelocationScattered(RENext))
2849 pair_r_value = info->O->getScatteredRelocationValue(RENext);
2852 if (isExtern) {
2853 const char *name =
2854 unwrapOrError(Symbol.getName(), info->O->getFileName()).data();
2855 op_info->AddSymbol.Present = 1;
2856 op_info->AddSymbol.Name = name;
2857 switch (r_type) {
2858 case MachO::ARM_RELOC_HALF:
2859 if ((r_length & 0x1) == 1) {
2860 op_info->Value = value << 16 | other_half;
2861 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
2862 } else {
2863 op_info->Value = other_half << 16 | value;
2864 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
2866 break;
2867 default:
2868 break;
2870 return 1;
2872 // If we have a branch that is not an external relocation entry then
2873 // return 0 so the code in tryAddingSymbolicOperand() can use the
2874 // SymbolLookUp call back with the branch target address to look up the
2875 // symbol and possibility add an annotation for a symbol stub.
2876 if (isExtern == 0 && (r_type == MachO::ARM_RELOC_BR24 ||
2877 r_type == MachO::ARM_THUMB_RELOC_BR22))
2878 return 0;
2880 uint32_t offset = 0;
2881 if (r_type == MachO::ARM_RELOC_HALF ||
2882 r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
2883 if ((r_length & 0x1) == 1)
2884 value = value << 16 | other_half;
2885 else
2886 value = other_half << 16 | value;
2888 if (r_scattered && (r_type != MachO::ARM_RELOC_HALF &&
2889 r_type != MachO::ARM_RELOC_HALF_SECTDIFF)) {
2890 offset = value - r_value;
2891 value = r_value;
2894 if (r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
2895 if ((r_length & 0x1) == 1)
2896 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
2897 else
2898 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
2899 const char *add = GuessSymbolName(r_value, info->AddrMap);
2900 const char *sub = GuessSymbolName(pair_r_value, info->AddrMap);
2901 int32_t offset = value - (r_value - pair_r_value);
2902 op_info->AddSymbol.Present = 1;
2903 if (add != nullptr)
2904 op_info->AddSymbol.Name = add;
2905 else
2906 op_info->AddSymbol.Value = r_value;
2907 op_info->SubtractSymbol.Present = 1;
2908 if (sub != nullptr)
2909 op_info->SubtractSymbol.Name = sub;
2910 else
2911 op_info->SubtractSymbol.Value = pair_r_value;
2912 op_info->Value = offset;
2913 return 1;
2916 op_info->AddSymbol.Present = 1;
2917 op_info->Value = offset;
2918 if (r_type == MachO::ARM_RELOC_HALF) {
2919 if ((r_length & 0x1) == 1)
2920 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
2921 else
2922 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
2924 const char *add = GuessSymbolName(value, info->AddrMap);
2925 if (add != nullptr) {
2926 op_info->AddSymbol.Name = add;
2927 return 1;
2929 op_info->AddSymbol.Value = value;
2930 return 1;
2932 if (Arch == Triple::aarch64) {
2933 if (Offset != 0 || Size != 4)
2934 return 0;
2935 if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
2936 // TODO:
2937 // Search the external relocation entries of a fully linked image
2938 // (if any) for an entry that matches this segment offset.
2939 // uint64_t seg_offset = (Pc + Offset);
2940 return 0;
2942 // In MH_OBJECT filetypes search the section's relocation entries (if any)
2943 // for an entry for this section offset.
2944 uint64_t sect_addr = info->S.getAddress();
2945 uint64_t sect_offset = (Pc + Offset) - sect_addr;
2946 auto Reloc =
2947 find_if(info->S.relocations(), [&](const RelocationRef &Reloc) {
2948 uint64_t RelocOffset = Reloc.getOffset();
2949 return RelocOffset == sect_offset;
2952 if (Reloc == info->S.relocations().end())
2953 return 0;
2955 DataRefImpl Rel = Reloc->getRawDataRefImpl();
2956 MachO::any_relocation_info RE = info->O->getRelocation(Rel);
2957 uint32_t r_type = info->O->getAnyRelocationType(RE);
2958 if (r_type == MachO::ARM64_RELOC_ADDEND) {
2959 DataRefImpl RelNext = Rel;
2960 info->O->moveRelocationNext(RelNext);
2961 MachO::any_relocation_info RENext = info->O->getRelocation(RelNext);
2962 if (value == 0) {
2963 value = info->O->getPlainRelocationSymbolNum(RENext);
2964 op_info->Value = value;
2967 // NOTE: Scattered relocations don't exist on arm64.
2968 if (!info->O->getPlainRelocationExternal(RE))
2969 return 0;
2970 const char *name =
2971 unwrapOrError(Reloc->getSymbol()->getName(), info->O->getFileName())
2972 .data();
2973 op_info->AddSymbol.Present = 1;
2974 op_info->AddSymbol.Name = name;
2976 switch (r_type) {
2977 case MachO::ARM64_RELOC_PAGE21:
2978 /* @page */
2979 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_PAGE;
2980 break;
2981 case MachO::ARM64_RELOC_PAGEOFF12:
2982 /* @pageoff */
2983 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_PAGEOFF;
2984 break;
2985 case MachO::ARM64_RELOC_GOT_LOAD_PAGE21:
2986 /* @gotpage */
2987 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_GOTPAGE;
2988 break;
2989 case MachO::ARM64_RELOC_GOT_LOAD_PAGEOFF12:
2990 /* @gotpageoff */
2991 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_GOTPAGEOFF;
2992 break;
2993 case MachO::ARM64_RELOC_TLVP_LOAD_PAGE21:
2994 /* @tvlppage is not implemented in llvm-mc */
2995 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_TLVP;
2996 break;
2997 case MachO::ARM64_RELOC_TLVP_LOAD_PAGEOFF12:
2998 /* @tvlppageoff is not implemented in llvm-mc */
2999 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_TLVOFF;
3000 break;
3001 default:
3002 case MachO::ARM64_RELOC_BRANCH26:
3003 op_info->VariantKind = LLVMDisassembler_VariantKind_None;
3004 break;
3006 return 1;
3008 return 0;
3011 // GuessCstringPointer is passed the address of what might be a pointer to a
3012 // literal string in a cstring section. If that address is in a cstring section
3013 // it returns a pointer to that string. Else it returns nullptr.
3014 static const char *GuessCstringPointer(uint64_t ReferenceValue,
3015 struct DisassembleInfo *info) {
3016 for (const auto &Load : info->O->load_commands()) {
3017 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
3018 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
3019 for (unsigned J = 0; J < Seg.nsects; ++J) {
3020 MachO::section_64 Sec = info->O->getSection64(Load, J);
3021 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
3022 if (section_type == MachO::S_CSTRING_LITERALS &&
3023 ReferenceValue >= Sec.addr &&
3024 ReferenceValue < Sec.addr + Sec.size) {
3025 uint64_t sect_offset = ReferenceValue - Sec.addr;
3026 uint64_t object_offset = Sec.offset + sect_offset;
3027 StringRef MachOContents = info->O->getData();
3028 uint64_t object_size = MachOContents.size();
3029 const char *object_addr = (const char *)MachOContents.data();
3030 if (object_offset < object_size) {
3031 const char *name = object_addr + object_offset;
3032 return name;
3033 } else {
3034 return nullptr;
3038 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
3039 MachO::segment_command Seg = info->O->getSegmentLoadCommand(Load);
3040 for (unsigned J = 0; J < Seg.nsects; ++J) {
3041 MachO::section Sec = info->O->getSection(Load, J);
3042 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
3043 if (section_type == MachO::S_CSTRING_LITERALS &&
3044 ReferenceValue >= Sec.addr &&
3045 ReferenceValue < Sec.addr + Sec.size) {
3046 uint64_t sect_offset = ReferenceValue - Sec.addr;
3047 uint64_t object_offset = Sec.offset + sect_offset;
3048 StringRef MachOContents = info->O->getData();
3049 uint64_t object_size = MachOContents.size();
3050 const char *object_addr = (const char *)MachOContents.data();
3051 if (object_offset < object_size) {
3052 const char *name = object_addr + object_offset;
3053 return name;
3054 } else {
3055 return nullptr;
3061 return nullptr;
3064 // GuessIndirectSymbol returns the name of the indirect symbol for the
3065 // ReferenceValue passed in or nullptr. This is used when ReferenceValue maybe
3066 // an address of a symbol stub or a lazy or non-lazy pointer to associate the
3067 // symbol name being referenced by the stub or pointer.
3068 static const char *GuessIndirectSymbol(uint64_t ReferenceValue,
3069 struct DisassembleInfo *info) {
3070 MachO::dysymtab_command Dysymtab = info->O->getDysymtabLoadCommand();
3071 MachO::symtab_command Symtab = info->O->getSymtabLoadCommand();
3072 for (const auto &Load : info->O->load_commands()) {
3073 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
3074 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
3075 for (unsigned J = 0; J < Seg.nsects; ++J) {
3076 MachO::section_64 Sec = info->O->getSection64(Load, J);
3077 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
3078 if ((section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
3079 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
3080 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
3081 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
3082 section_type == MachO::S_SYMBOL_STUBS) &&
3083 ReferenceValue >= Sec.addr &&
3084 ReferenceValue < Sec.addr + Sec.size) {
3085 uint32_t stride;
3086 if (section_type == MachO::S_SYMBOL_STUBS)
3087 stride = Sec.reserved2;
3088 else
3089 stride = 8;
3090 if (stride == 0)
3091 return nullptr;
3092 uint32_t index = Sec.reserved1 + (ReferenceValue - Sec.addr) / stride;
3093 if (index < Dysymtab.nindirectsyms) {
3094 uint32_t indirect_symbol =
3095 info->O->getIndirectSymbolTableEntry(Dysymtab, index);
3096 if (indirect_symbol < Symtab.nsyms) {
3097 symbol_iterator Sym = info->O->getSymbolByIndex(indirect_symbol);
3098 return unwrapOrError(Sym->getName(), info->O->getFileName())
3099 .data();
3104 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
3105 MachO::segment_command Seg = info->O->getSegmentLoadCommand(Load);
3106 for (unsigned J = 0; J < Seg.nsects; ++J) {
3107 MachO::section Sec = info->O->getSection(Load, J);
3108 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
3109 if ((section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
3110 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
3111 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
3112 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
3113 section_type == MachO::S_SYMBOL_STUBS) &&
3114 ReferenceValue >= Sec.addr &&
3115 ReferenceValue < Sec.addr + Sec.size) {
3116 uint32_t stride;
3117 if (section_type == MachO::S_SYMBOL_STUBS)
3118 stride = Sec.reserved2;
3119 else
3120 stride = 4;
3121 if (stride == 0)
3122 return nullptr;
3123 uint32_t index = Sec.reserved1 + (ReferenceValue - Sec.addr) / stride;
3124 if (index < Dysymtab.nindirectsyms) {
3125 uint32_t indirect_symbol =
3126 info->O->getIndirectSymbolTableEntry(Dysymtab, index);
3127 if (indirect_symbol < Symtab.nsyms) {
3128 symbol_iterator Sym = info->O->getSymbolByIndex(indirect_symbol);
3129 return unwrapOrError(Sym->getName(), info->O->getFileName())
3130 .data();
3137 return nullptr;
3140 // method_reference() is called passing it the ReferenceName that might be
3141 // a reference it to an Objective-C method call. If so then it allocates and
3142 // assembles a method call string with the values last seen and saved in
3143 // the DisassembleInfo's class_name and selector_name fields. This is saved
3144 // into the method field of the info and any previous string is free'ed.
3145 // Then the class_name field in the info is set to nullptr. The method call
3146 // string is set into ReferenceName and ReferenceType is set to
3147 // LLVMDisassembler_ReferenceType_Out_Objc_Message. If this not a method call
3148 // then both ReferenceType and ReferenceName are left unchanged.
3149 static void method_reference(struct DisassembleInfo *info,
3150 uint64_t *ReferenceType,
3151 const char **ReferenceName) {
3152 unsigned int Arch = info->O->getArch();
3153 if (*ReferenceName != nullptr) {
3154 if (strcmp(*ReferenceName, "_objc_msgSend") == 0) {
3155 if (info->selector_name != nullptr) {
3156 if (info->class_name != nullptr) {
3157 info->method = std::make_unique<char[]>(
3158 5 + strlen(info->class_name) + strlen(info->selector_name));
3159 char *method = info->method.get();
3160 if (method != nullptr) {
3161 strcpy(method, "+[");
3162 strcat(method, info->class_name);
3163 strcat(method, " ");
3164 strcat(method, info->selector_name);
3165 strcat(method, "]");
3166 *ReferenceName = method;
3167 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
3169 } else {
3170 info->method =
3171 std::make_unique<char[]>(9 + strlen(info->selector_name));
3172 char *method = info->method.get();
3173 if (method != nullptr) {
3174 if (Arch == Triple::x86_64)
3175 strcpy(method, "-[%rdi ");
3176 else if (Arch == Triple::aarch64)
3177 strcpy(method, "-[x0 ");
3178 else
3179 strcpy(method, "-[r? ");
3180 strcat(method, info->selector_name);
3181 strcat(method, "]");
3182 *ReferenceName = method;
3183 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
3186 info->class_name = nullptr;
3188 } else if (strcmp(*ReferenceName, "_objc_msgSendSuper2") == 0) {
3189 if (info->selector_name != nullptr) {
3190 info->method =
3191 std::make_unique<char[]>(17 + strlen(info->selector_name));
3192 char *method = info->method.get();
3193 if (method != nullptr) {
3194 if (Arch == Triple::x86_64)
3195 strcpy(method, "-[[%rdi super] ");
3196 else if (Arch == Triple::aarch64)
3197 strcpy(method, "-[[x0 super] ");
3198 else
3199 strcpy(method, "-[[r? super] ");
3200 strcat(method, info->selector_name);
3201 strcat(method, "]");
3202 *ReferenceName = method;
3203 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
3205 info->class_name = nullptr;
3211 // GuessPointerPointer() is passed the address of what might be a pointer to
3212 // a reference to an Objective-C class, selector, message ref or cfstring.
3213 // If so the value of the pointer is returned and one of the booleans are set
3214 // to true. If not zero is returned and all the booleans are set to false.
3215 static uint64_t GuessPointerPointer(uint64_t ReferenceValue,
3216 struct DisassembleInfo *info,
3217 bool &classref, bool &selref, bool &msgref,
3218 bool &cfstring) {
3219 classref = false;
3220 selref = false;
3221 msgref = false;
3222 cfstring = false;
3223 for (const auto &Load : info->O->load_commands()) {
3224 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
3225 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
3226 for (unsigned J = 0; J < Seg.nsects; ++J) {
3227 MachO::section_64 Sec = info->O->getSection64(Load, J);
3228 if ((strncmp(Sec.sectname, "__objc_selrefs", 16) == 0 ||
3229 strncmp(Sec.sectname, "__objc_classrefs", 16) == 0 ||
3230 strncmp(Sec.sectname, "__objc_superrefs", 16) == 0 ||
3231 strncmp(Sec.sectname, "__objc_msgrefs", 16) == 0 ||
3232 strncmp(Sec.sectname, "__cfstring", 16) == 0) &&
3233 ReferenceValue >= Sec.addr &&
3234 ReferenceValue < Sec.addr + Sec.size) {
3235 uint64_t sect_offset = ReferenceValue - Sec.addr;
3236 uint64_t object_offset = Sec.offset + sect_offset;
3237 StringRef MachOContents = info->O->getData();
3238 uint64_t object_size = MachOContents.size();
3239 const char *object_addr = (const char *)MachOContents.data();
3240 if (object_offset < object_size) {
3241 uint64_t pointer_value;
3242 memcpy(&pointer_value, object_addr + object_offset,
3243 sizeof(uint64_t));
3244 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3245 sys::swapByteOrder(pointer_value);
3246 if (strncmp(Sec.sectname, "__objc_selrefs", 16) == 0)
3247 selref = true;
3248 else if (strncmp(Sec.sectname, "__objc_classrefs", 16) == 0 ||
3249 strncmp(Sec.sectname, "__objc_superrefs", 16) == 0)
3250 classref = true;
3251 else if (strncmp(Sec.sectname, "__objc_msgrefs", 16) == 0 &&
3252 ReferenceValue + 8 < Sec.addr + Sec.size) {
3253 msgref = true;
3254 memcpy(&pointer_value, object_addr + object_offset + 8,
3255 sizeof(uint64_t));
3256 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3257 sys::swapByteOrder(pointer_value);
3258 } else if (strncmp(Sec.sectname, "__cfstring", 16) == 0)
3259 cfstring = true;
3260 return pointer_value;
3261 } else {
3262 return 0;
3267 // TODO: Look for LC_SEGMENT for 32-bit Mach-O files.
3269 return 0;
3272 // get_pointer_64 returns a pointer to the bytes in the object file at the
3273 // Address from a section in the Mach-O file. And indirectly returns the
3274 // offset into the section, number of bytes left in the section past the offset
3275 // and which section is was being referenced. If the Address is not in a
3276 // section nullptr is returned.
3277 static const char *get_pointer_64(uint64_t Address, uint32_t &offset,
3278 uint32_t &left, SectionRef &S,
3279 DisassembleInfo *info,
3280 bool objc_only = false) {
3281 offset = 0;
3282 left = 0;
3283 S = SectionRef();
3284 for (unsigned SectIdx = 0; SectIdx != info->Sections->size(); SectIdx++) {
3285 uint64_t SectAddress = ((*(info->Sections))[SectIdx]).getAddress();
3286 uint64_t SectSize = ((*(info->Sections))[SectIdx]).getSize();
3287 if (SectSize == 0)
3288 continue;
3289 if (objc_only) {
3290 StringRef SectName;
3291 Expected<StringRef> SecNameOrErr =
3292 ((*(info->Sections))[SectIdx]).getName();
3293 if (SecNameOrErr)
3294 SectName = *SecNameOrErr;
3295 else
3296 consumeError(SecNameOrErr.takeError());
3298 DataRefImpl Ref = ((*(info->Sections))[SectIdx]).getRawDataRefImpl();
3299 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
3300 if (SegName != "__OBJC" && SectName != "__cstring")
3301 continue;
3303 if (Address >= SectAddress && Address < SectAddress + SectSize) {
3304 S = (*(info->Sections))[SectIdx];
3305 offset = Address - SectAddress;
3306 left = SectSize - offset;
3307 StringRef SectContents = unwrapOrError(
3308 ((*(info->Sections))[SectIdx]).getContents(), info->O->getFileName());
3309 return SectContents.data() + offset;
3312 return nullptr;
3315 static const char *get_pointer_32(uint32_t Address, uint32_t &offset,
3316 uint32_t &left, SectionRef &S,
3317 DisassembleInfo *info,
3318 bool objc_only = false) {
3319 return get_pointer_64(Address, offset, left, S, info, objc_only);
3322 // get_symbol_64() returns the name of a symbol (or nullptr) and the address of
3323 // the symbol indirectly through n_value. Based on the relocation information
3324 // for the specified section offset in the specified section reference.
3325 // If no relocation information is found and a non-zero ReferenceValue for the
3326 // symbol is passed, look up that address in the info's AddrMap.
3327 static const char *get_symbol_64(uint32_t sect_offset, SectionRef S,
3328 DisassembleInfo *info, uint64_t &n_value,
3329 uint64_t ReferenceValue = 0) {
3330 n_value = 0;
3331 if (!info->verbose)
3332 return nullptr;
3334 // See if there is an external relocation entry at the sect_offset.
3335 bool reloc_found = false;
3336 DataRefImpl Rel;
3337 MachO::any_relocation_info RE;
3338 bool isExtern = false;
3339 SymbolRef Symbol;
3340 for (const RelocationRef &Reloc : S.relocations()) {
3341 uint64_t RelocOffset = Reloc.getOffset();
3342 if (RelocOffset == sect_offset) {
3343 Rel = Reloc.getRawDataRefImpl();
3344 RE = info->O->getRelocation(Rel);
3345 if (info->O->isRelocationScattered(RE))
3346 continue;
3347 isExtern = info->O->getPlainRelocationExternal(RE);
3348 if (isExtern) {
3349 symbol_iterator RelocSym = Reloc.getSymbol();
3350 Symbol = *RelocSym;
3352 reloc_found = true;
3353 break;
3356 // If there is an external relocation entry for a symbol in this section
3357 // at this section_offset then use that symbol's value for the n_value
3358 // and return its name.
3359 const char *SymbolName = nullptr;
3360 if (reloc_found && isExtern) {
3361 n_value = Symbol.getValue();
3362 StringRef Name = unwrapOrError(Symbol.getName(), info->O->getFileName());
3363 if (!Name.empty()) {
3364 SymbolName = Name.data();
3365 return SymbolName;
3369 // TODO: For fully linked images, look through the external relocation
3370 // entries off the dynamic symtab command. For these the r_offset is from the
3371 // start of the first writeable segment in the Mach-O file. So the offset
3372 // to this section from that segment is passed to this routine by the caller,
3373 // as the database_offset. Which is the difference of the section's starting
3374 // address and the first writable segment.
3376 // NOTE: need add passing the database_offset to this routine.
3378 // We did not find an external relocation entry so look up the ReferenceValue
3379 // as an address of a symbol and if found return that symbol's name.
3380 SymbolName = GuessSymbolName(ReferenceValue, info->AddrMap);
3382 return SymbolName;
3385 static const char *get_symbol_32(uint32_t sect_offset, SectionRef S,
3386 DisassembleInfo *info,
3387 uint32_t ReferenceValue) {
3388 uint64_t n_value64;
3389 return get_symbol_64(sect_offset, S, info, n_value64, ReferenceValue);
3392 // These are structs in the Objective-C meta data and read to produce the
3393 // comments for disassembly. While these are part of the ABI they are no
3394 // public defintions. So the are here not in include/llvm/BinaryFormat/MachO.h
3395 // .
3397 // The cfstring object in a 64-bit Mach-O file.
3398 struct cfstring64_t {
3399 uint64_t isa; // class64_t * (64-bit pointer)
3400 uint64_t flags; // flag bits
3401 uint64_t characters; // char * (64-bit pointer)
3402 uint64_t length; // number of non-NULL characters in above
3405 // The class object in a 64-bit Mach-O file.
3406 struct class64_t {
3407 uint64_t isa; // class64_t * (64-bit pointer)
3408 uint64_t superclass; // class64_t * (64-bit pointer)
3409 uint64_t cache; // Cache (64-bit pointer)
3410 uint64_t vtable; // IMP * (64-bit pointer)
3411 uint64_t data; // class_ro64_t * (64-bit pointer)
3414 struct class32_t {
3415 uint32_t isa; /* class32_t * (32-bit pointer) */
3416 uint32_t superclass; /* class32_t * (32-bit pointer) */
3417 uint32_t cache; /* Cache (32-bit pointer) */
3418 uint32_t vtable; /* IMP * (32-bit pointer) */
3419 uint32_t data; /* class_ro32_t * (32-bit pointer) */
3422 struct class_ro64_t {
3423 uint32_t flags;
3424 uint32_t instanceStart;
3425 uint32_t instanceSize;
3426 uint32_t reserved;
3427 uint64_t ivarLayout; // const uint8_t * (64-bit pointer)
3428 uint64_t name; // const char * (64-bit pointer)
3429 uint64_t baseMethods; // const method_list_t * (64-bit pointer)
3430 uint64_t baseProtocols; // const protocol_list_t * (64-bit pointer)
3431 uint64_t ivars; // const ivar_list_t * (64-bit pointer)
3432 uint64_t weakIvarLayout; // const uint8_t * (64-bit pointer)
3433 uint64_t baseProperties; // const struct objc_property_list (64-bit pointer)
3436 struct class_ro32_t {
3437 uint32_t flags;
3438 uint32_t instanceStart;
3439 uint32_t instanceSize;
3440 uint32_t ivarLayout; /* const uint8_t * (32-bit pointer) */
3441 uint32_t name; /* const char * (32-bit pointer) */
3442 uint32_t baseMethods; /* const method_list_t * (32-bit pointer) */
3443 uint32_t baseProtocols; /* const protocol_list_t * (32-bit pointer) */
3444 uint32_t ivars; /* const ivar_list_t * (32-bit pointer) */
3445 uint32_t weakIvarLayout; /* const uint8_t * (32-bit pointer) */
3446 uint32_t baseProperties; /* const struct objc_property_list *
3447 (32-bit pointer) */
3450 /* Values for class_ro{64,32}_t->flags */
3451 #define RO_META (1 << 0)
3452 #define RO_ROOT (1 << 1)
3453 #define RO_HAS_CXX_STRUCTORS (1 << 2)
3455 struct method_list64_t {
3456 uint32_t entsize;
3457 uint32_t count;
3458 /* struct method64_t first; These structures follow inline */
3461 struct method_list32_t {
3462 uint32_t entsize;
3463 uint32_t count;
3464 /* struct method32_t first; These structures follow inline */
3467 struct method64_t {
3468 uint64_t name; /* SEL (64-bit pointer) */
3469 uint64_t types; /* const char * (64-bit pointer) */
3470 uint64_t imp; /* IMP (64-bit pointer) */
3473 struct method32_t {
3474 uint32_t name; /* SEL (32-bit pointer) */
3475 uint32_t types; /* const char * (32-bit pointer) */
3476 uint32_t imp; /* IMP (32-bit pointer) */
3479 struct protocol_list64_t {
3480 uint64_t count; /* uintptr_t (a 64-bit value) */
3481 /* struct protocol64_t * list[0]; These pointers follow inline */
3484 struct protocol_list32_t {
3485 uint32_t count; /* uintptr_t (a 32-bit value) */
3486 /* struct protocol32_t * list[0]; These pointers follow inline */
3489 struct protocol64_t {
3490 uint64_t isa; /* id * (64-bit pointer) */
3491 uint64_t name; /* const char * (64-bit pointer) */
3492 uint64_t protocols; /* struct protocol_list64_t *
3493 (64-bit pointer) */
3494 uint64_t instanceMethods; /* method_list_t * (64-bit pointer) */
3495 uint64_t classMethods; /* method_list_t * (64-bit pointer) */
3496 uint64_t optionalInstanceMethods; /* method_list_t * (64-bit pointer) */
3497 uint64_t optionalClassMethods; /* method_list_t * (64-bit pointer) */
3498 uint64_t instanceProperties; /* struct objc_property_list *
3499 (64-bit pointer) */
3502 struct protocol32_t {
3503 uint32_t isa; /* id * (32-bit pointer) */
3504 uint32_t name; /* const char * (32-bit pointer) */
3505 uint32_t protocols; /* struct protocol_list_t *
3506 (32-bit pointer) */
3507 uint32_t instanceMethods; /* method_list_t * (32-bit pointer) */
3508 uint32_t classMethods; /* method_list_t * (32-bit pointer) */
3509 uint32_t optionalInstanceMethods; /* method_list_t * (32-bit pointer) */
3510 uint32_t optionalClassMethods; /* method_list_t * (32-bit pointer) */
3511 uint32_t instanceProperties; /* struct objc_property_list *
3512 (32-bit pointer) */
3515 struct ivar_list64_t {
3516 uint32_t entsize;
3517 uint32_t count;
3518 /* struct ivar64_t first; These structures follow inline */
3521 struct ivar_list32_t {
3522 uint32_t entsize;
3523 uint32_t count;
3524 /* struct ivar32_t first; These structures follow inline */
3527 struct ivar64_t {
3528 uint64_t offset; /* uintptr_t * (64-bit pointer) */
3529 uint64_t name; /* const char * (64-bit pointer) */
3530 uint64_t type; /* const char * (64-bit pointer) */
3531 uint32_t alignment;
3532 uint32_t size;
3535 struct ivar32_t {
3536 uint32_t offset; /* uintptr_t * (32-bit pointer) */
3537 uint32_t name; /* const char * (32-bit pointer) */
3538 uint32_t type; /* const char * (32-bit pointer) */
3539 uint32_t alignment;
3540 uint32_t size;
3543 struct objc_property_list64 {
3544 uint32_t entsize;
3545 uint32_t count;
3546 /* struct objc_property64 first; These structures follow inline */
3549 struct objc_property_list32 {
3550 uint32_t entsize;
3551 uint32_t count;
3552 /* struct objc_property32 first; These structures follow inline */
3555 struct objc_property64 {
3556 uint64_t name; /* const char * (64-bit pointer) */
3557 uint64_t attributes; /* const char * (64-bit pointer) */
3560 struct objc_property32 {
3561 uint32_t name; /* const char * (32-bit pointer) */
3562 uint32_t attributes; /* const char * (32-bit pointer) */
3565 struct category64_t {
3566 uint64_t name; /* const char * (64-bit pointer) */
3567 uint64_t cls; /* struct class_t * (64-bit pointer) */
3568 uint64_t instanceMethods; /* struct method_list_t * (64-bit pointer) */
3569 uint64_t classMethods; /* struct method_list_t * (64-bit pointer) */
3570 uint64_t protocols; /* struct protocol_list_t * (64-bit pointer) */
3571 uint64_t instanceProperties; /* struct objc_property_list *
3572 (64-bit pointer) */
3575 struct category32_t {
3576 uint32_t name; /* const char * (32-bit pointer) */
3577 uint32_t cls; /* struct class_t * (32-bit pointer) */
3578 uint32_t instanceMethods; /* struct method_list_t * (32-bit pointer) */
3579 uint32_t classMethods; /* struct method_list_t * (32-bit pointer) */
3580 uint32_t protocols; /* struct protocol_list_t * (32-bit pointer) */
3581 uint32_t instanceProperties; /* struct objc_property_list *
3582 (32-bit pointer) */
3585 struct objc_image_info64 {
3586 uint32_t version;
3587 uint32_t flags;
3589 struct objc_image_info32 {
3590 uint32_t version;
3591 uint32_t flags;
3593 struct imageInfo_t {
3594 uint32_t version;
3595 uint32_t flags;
3597 /* masks for objc_image_info.flags */
3598 #define OBJC_IMAGE_IS_REPLACEMENT (1 << 0)
3599 #define OBJC_IMAGE_SUPPORTS_GC (1 << 1)
3600 #define OBJC_IMAGE_IS_SIMULATED (1 << 5)
3601 #define OBJC_IMAGE_HAS_CATEGORY_CLASS_PROPERTIES (1 << 6)
3603 struct message_ref64 {
3604 uint64_t imp; /* IMP (64-bit pointer) */
3605 uint64_t sel; /* SEL (64-bit pointer) */
3608 struct message_ref32 {
3609 uint32_t imp; /* IMP (32-bit pointer) */
3610 uint32_t sel; /* SEL (32-bit pointer) */
3613 // Objective-C 1 (32-bit only) meta data structs.
3615 struct objc_module_t {
3616 uint32_t version;
3617 uint32_t size;
3618 uint32_t name; /* char * (32-bit pointer) */
3619 uint32_t symtab; /* struct objc_symtab * (32-bit pointer) */
3622 struct objc_symtab_t {
3623 uint32_t sel_ref_cnt;
3624 uint32_t refs; /* SEL * (32-bit pointer) */
3625 uint16_t cls_def_cnt;
3626 uint16_t cat_def_cnt;
3627 // uint32_t defs[1]; /* void * (32-bit pointer) variable size */
3630 struct objc_class_t {
3631 uint32_t isa; /* struct objc_class * (32-bit pointer) */
3632 uint32_t super_class; /* struct objc_class * (32-bit pointer) */
3633 uint32_t name; /* const char * (32-bit pointer) */
3634 int32_t version;
3635 int32_t info;
3636 int32_t instance_size;
3637 uint32_t ivars; /* struct objc_ivar_list * (32-bit pointer) */
3638 uint32_t methodLists; /* struct objc_method_list ** (32-bit pointer) */
3639 uint32_t cache; /* struct objc_cache * (32-bit pointer) */
3640 uint32_t protocols; /* struct objc_protocol_list * (32-bit pointer) */
3643 #define CLS_GETINFO(cls, infomask) ((cls)->info & (infomask))
3644 // class is not a metaclass
3645 #define CLS_CLASS 0x1
3646 // class is a metaclass
3647 #define CLS_META 0x2
3649 struct objc_category_t {
3650 uint32_t category_name; /* char * (32-bit pointer) */
3651 uint32_t class_name; /* char * (32-bit pointer) */
3652 uint32_t instance_methods; /* struct objc_method_list * (32-bit pointer) */
3653 uint32_t class_methods; /* struct objc_method_list * (32-bit pointer) */
3654 uint32_t protocols; /* struct objc_protocol_list * (32-bit ptr) */
3657 struct objc_ivar_t {
3658 uint32_t ivar_name; /* char * (32-bit pointer) */
3659 uint32_t ivar_type; /* char * (32-bit pointer) */
3660 int32_t ivar_offset;
3663 struct objc_ivar_list_t {
3664 int32_t ivar_count;
3665 // struct objc_ivar_t ivar_list[1]; /* variable length structure */
3668 struct objc_method_list_t {
3669 uint32_t obsolete; /* struct objc_method_list * (32-bit pointer) */
3670 int32_t method_count;
3671 // struct objc_method_t method_list[1]; /* variable length structure */
3674 struct objc_method_t {
3675 uint32_t method_name; /* SEL, aka struct objc_selector * (32-bit pointer) */
3676 uint32_t method_types; /* char * (32-bit pointer) */
3677 uint32_t method_imp; /* IMP, aka function pointer, (*IMP)(id, SEL, ...)
3678 (32-bit pointer) */
3681 struct objc_protocol_list_t {
3682 uint32_t next; /* struct objc_protocol_list * (32-bit pointer) */
3683 int32_t count;
3684 // uint32_t list[1]; /* Protocol *, aka struct objc_protocol_t *
3685 // (32-bit pointer) */
3688 struct objc_protocol_t {
3689 uint32_t isa; /* struct objc_class * (32-bit pointer) */
3690 uint32_t protocol_name; /* char * (32-bit pointer) */
3691 uint32_t protocol_list; /* struct objc_protocol_list * (32-bit pointer) */
3692 uint32_t instance_methods; /* struct objc_method_description_list *
3693 (32-bit pointer) */
3694 uint32_t class_methods; /* struct objc_method_description_list *
3695 (32-bit pointer) */
3698 struct objc_method_description_list_t {
3699 int32_t count;
3700 // struct objc_method_description_t list[1];
3703 struct objc_method_description_t {
3704 uint32_t name; /* SEL, aka struct objc_selector * (32-bit pointer) */
3705 uint32_t types; /* char * (32-bit pointer) */
3708 inline void swapStruct(struct cfstring64_t &cfs) {
3709 sys::swapByteOrder(cfs.isa);
3710 sys::swapByteOrder(cfs.flags);
3711 sys::swapByteOrder(cfs.characters);
3712 sys::swapByteOrder(cfs.length);
3715 inline void swapStruct(struct class64_t &c) {
3716 sys::swapByteOrder(c.isa);
3717 sys::swapByteOrder(c.superclass);
3718 sys::swapByteOrder(c.cache);
3719 sys::swapByteOrder(c.vtable);
3720 sys::swapByteOrder(c.data);
3723 inline void swapStruct(struct class32_t &c) {
3724 sys::swapByteOrder(c.isa);
3725 sys::swapByteOrder(c.superclass);
3726 sys::swapByteOrder(c.cache);
3727 sys::swapByteOrder(c.vtable);
3728 sys::swapByteOrder(c.data);
3731 inline void swapStruct(struct class_ro64_t &cro) {
3732 sys::swapByteOrder(cro.flags);
3733 sys::swapByteOrder(cro.instanceStart);
3734 sys::swapByteOrder(cro.instanceSize);
3735 sys::swapByteOrder(cro.reserved);
3736 sys::swapByteOrder(cro.ivarLayout);
3737 sys::swapByteOrder(cro.name);
3738 sys::swapByteOrder(cro.baseMethods);
3739 sys::swapByteOrder(cro.baseProtocols);
3740 sys::swapByteOrder(cro.ivars);
3741 sys::swapByteOrder(cro.weakIvarLayout);
3742 sys::swapByteOrder(cro.baseProperties);
3745 inline void swapStruct(struct class_ro32_t &cro) {
3746 sys::swapByteOrder(cro.flags);
3747 sys::swapByteOrder(cro.instanceStart);
3748 sys::swapByteOrder(cro.instanceSize);
3749 sys::swapByteOrder(cro.ivarLayout);
3750 sys::swapByteOrder(cro.name);
3751 sys::swapByteOrder(cro.baseMethods);
3752 sys::swapByteOrder(cro.baseProtocols);
3753 sys::swapByteOrder(cro.ivars);
3754 sys::swapByteOrder(cro.weakIvarLayout);
3755 sys::swapByteOrder(cro.baseProperties);
3758 inline void swapStruct(struct method_list64_t &ml) {
3759 sys::swapByteOrder(ml.entsize);
3760 sys::swapByteOrder(ml.count);
3763 inline void swapStruct(struct method_list32_t &ml) {
3764 sys::swapByteOrder(ml.entsize);
3765 sys::swapByteOrder(ml.count);
3768 inline void swapStruct(struct method64_t &m) {
3769 sys::swapByteOrder(m.name);
3770 sys::swapByteOrder(m.types);
3771 sys::swapByteOrder(m.imp);
3774 inline void swapStruct(struct method32_t &m) {
3775 sys::swapByteOrder(m.name);
3776 sys::swapByteOrder(m.types);
3777 sys::swapByteOrder(m.imp);
3780 inline void swapStruct(struct protocol_list64_t &pl) {
3781 sys::swapByteOrder(pl.count);
3784 inline void swapStruct(struct protocol_list32_t &pl) {
3785 sys::swapByteOrder(pl.count);
3788 inline void swapStruct(struct protocol64_t &p) {
3789 sys::swapByteOrder(p.isa);
3790 sys::swapByteOrder(p.name);
3791 sys::swapByteOrder(p.protocols);
3792 sys::swapByteOrder(p.instanceMethods);
3793 sys::swapByteOrder(p.classMethods);
3794 sys::swapByteOrder(p.optionalInstanceMethods);
3795 sys::swapByteOrder(p.optionalClassMethods);
3796 sys::swapByteOrder(p.instanceProperties);
3799 inline void swapStruct(struct protocol32_t &p) {
3800 sys::swapByteOrder(p.isa);
3801 sys::swapByteOrder(p.name);
3802 sys::swapByteOrder(p.protocols);
3803 sys::swapByteOrder(p.instanceMethods);
3804 sys::swapByteOrder(p.classMethods);
3805 sys::swapByteOrder(p.optionalInstanceMethods);
3806 sys::swapByteOrder(p.optionalClassMethods);
3807 sys::swapByteOrder(p.instanceProperties);
3810 inline void swapStruct(struct ivar_list64_t &il) {
3811 sys::swapByteOrder(il.entsize);
3812 sys::swapByteOrder(il.count);
3815 inline void swapStruct(struct ivar_list32_t &il) {
3816 sys::swapByteOrder(il.entsize);
3817 sys::swapByteOrder(il.count);
3820 inline void swapStruct(struct ivar64_t &i) {
3821 sys::swapByteOrder(i.offset);
3822 sys::swapByteOrder(i.name);
3823 sys::swapByteOrder(i.type);
3824 sys::swapByteOrder(i.alignment);
3825 sys::swapByteOrder(i.size);
3828 inline void swapStruct(struct ivar32_t &i) {
3829 sys::swapByteOrder(i.offset);
3830 sys::swapByteOrder(i.name);
3831 sys::swapByteOrder(i.type);
3832 sys::swapByteOrder(i.alignment);
3833 sys::swapByteOrder(i.size);
3836 inline void swapStruct(struct objc_property_list64 &pl) {
3837 sys::swapByteOrder(pl.entsize);
3838 sys::swapByteOrder(pl.count);
3841 inline void swapStruct(struct objc_property_list32 &pl) {
3842 sys::swapByteOrder(pl.entsize);
3843 sys::swapByteOrder(pl.count);
3846 inline void swapStruct(struct objc_property64 &op) {
3847 sys::swapByteOrder(op.name);
3848 sys::swapByteOrder(op.attributes);
3851 inline void swapStruct(struct objc_property32 &op) {
3852 sys::swapByteOrder(op.name);
3853 sys::swapByteOrder(op.attributes);
3856 inline void swapStruct(struct category64_t &c) {
3857 sys::swapByteOrder(c.name);
3858 sys::swapByteOrder(c.cls);
3859 sys::swapByteOrder(c.instanceMethods);
3860 sys::swapByteOrder(c.classMethods);
3861 sys::swapByteOrder(c.protocols);
3862 sys::swapByteOrder(c.instanceProperties);
3865 inline void swapStruct(struct category32_t &c) {
3866 sys::swapByteOrder(c.name);
3867 sys::swapByteOrder(c.cls);
3868 sys::swapByteOrder(c.instanceMethods);
3869 sys::swapByteOrder(c.classMethods);
3870 sys::swapByteOrder(c.protocols);
3871 sys::swapByteOrder(c.instanceProperties);
3874 inline void swapStruct(struct objc_image_info64 &o) {
3875 sys::swapByteOrder(o.version);
3876 sys::swapByteOrder(o.flags);
3879 inline void swapStruct(struct objc_image_info32 &o) {
3880 sys::swapByteOrder(o.version);
3881 sys::swapByteOrder(o.flags);
3884 inline void swapStruct(struct imageInfo_t &o) {
3885 sys::swapByteOrder(o.version);
3886 sys::swapByteOrder(o.flags);
3889 inline void swapStruct(struct message_ref64 &mr) {
3890 sys::swapByteOrder(mr.imp);
3891 sys::swapByteOrder(mr.sel);
3894 inline void swapStruct(struct message_ref32 &mr) {
3895 sys::swapByteOrder(mr.imp);
3896 sys::swapByteOrder(mr.sel);
3899 inline void swapStruct(struct objc_module_t &module) {
3900 sys::swapByteOrder(module.version);
3901 sys::swapByteOrder(module.size);
3902 sys::swapByteOrder(module.name);
3903 sys::swapByteOrder(module.symtab);
3906 inline void swapStruct(struct objc_symtab_t &symtab) {
3907 sys::swapByteOrder(symtab.sel_ref_cnt);
3908 sys::swapByteOrder(symtab.refs);
3909 sys::swapByteOrder(symtab.cls_def_cnt);
3910 sys::swapByteOrder(symtab.cat_def_cnt);
3913 inline void swapStruct(struct objc_class_t &objc_class) {
3914 sys::swapByteOrder(objc_class.isa);
3915 sys::swapByteOrder(objc_class.super_class);
3916 sys::swapByteOrder(objc_class.name);
3917 sys::swapByteOrder(objc_class.version);
3918 sys::swapByteOrder(objc_class.info);
3919 sys::swapByteOrder(objc_class.instance_size);
3920 sys::swapByteOrder(objc_class.ivars);
3921 sys::swapByteOrder(objc_class.methodLists);
3922 sys::swapByteOrder(objc_class.cache);
3923 sys::swapByteOrder(objc_class.protocols);
3926 inline void swapStruct(struct objc_category_t &objc_category) {
3927 sys::swapByteOrder(objc_category.category_name);
3928 sys::swapByteOrder(objc_category.class_name);
3929 sys::swapByteOrder(objc_category.instance_methods);
3930 sys::swapByteOrder(objc_category.class_methods);
3931 sys::swapByteOrder(objc_category.protocols);
3934 inline void swapStruct(struct objc_ivar_list_t &objc_ivar_list) {
3935 sys::swapByteOrder(objc_ivar_list.ivar_count);
3938 inline void swapStruct(struct objc_ivar_t &objc_ivar) {
3939 sys::swapByteOrder(objc_ivar.ivar_name);
3940 sys::swapByteOrder(objc_ivar.ivar_type);
3941 sys::swapByteOrder(objc_ivar.ivar_offset);
3944 inline void swapStruct(struct objc_method_list_t &method_list) {
3945 sys::swapByteOrder(method_list.obsolete);
3946 sys::swapByteOrder(method_list.method_count);
3949 inline void swapStruct(struct objc_method_t &method) {
3950 sys::swapByteOrder(method.method_name);
3951 sys::swapByteOrder(method.method_types);
3952 sys::swapByteOrder(method.method_imp);
3955 inline void swapStruct(struct objc_protocol_list_t &protocol_list) {
3956 sys::swapByteOrder(protocol_list.next);
3957 sys::swapByteOrder(protocol_list.count);
3960 inline void swapStruct(struct objc_protocol_t &protocol) {
3961 sys::swapByteOrder(protocol.isa);
3962 sys::swapByteOrder(protocol.protocol_name);
3963 sys::swapByteOrder(protocol.protocol_list);
3964 sys::swapByteOrder(protocol.instance_methods);
3965 sys::swapByteOrder(protocol.class_methods);
3968 inline void swapStruct(struct objc_method_description_list_t &mdl) {
3969 sys::swapByteOrder(mdl.count);
3972 inline void swapStruct(struct objc_method_description_t &md) {
3973 sys::swapByteOrder(md.name);
3974 sys::swapByteOrder(md.types);
3977 static const char *get_dyld_bind_info_symbolname(uint64_t ReferenceValue,
3978 struct DisassembleInfo *info);
3980 // get_objc2_64bit_class_name() is used for disassembly and is passed a pointer
3981 // to an Objective-C class and returns the class name. It is also passed the
3982 // address of the pointer, so when the pointer is zero as it can be in an .o
3983 // file, that is used to look for an external relocation entry with a symbol
3984 // name.
3985 static const char *get_objc2_64bit_class_name(uint64_t pointer_value,
3986 uint64_t ReferenceValue,
3987 struct DisassembleInfo *info) {
3988 const char *r;
3989 uint32_t offset, left;
3990 SectionRef S;
3992 // The pointer_value can be 0 in an object file and have a relocation
3993 // entry for the class symbol at the ReferenceValue (the address of the
3994 // pointer).
3995 if (pointer_value == 0) {
3996 r = get_pointer_64(ReferenceValue, offset, left, S, info);
3997 if (r == nullptr || left < sizeof(uint64_t))
3998 return nullptr;
3999 uint64_t n_value;
4000 const char *symbol_name = get_symbol_64(offset, S, info, n_value);
4001 if (symbol_name == nullptr)
4002 return nullptr;
4003 const char *class_name = strrchr(symbol_name, '$');
4004 if (class_name != nullptr && class_name[1] == '_' && class_name[2] != '\0')
4005 return class_name + 2;
4006 else
4007 return nullptr;
4010 // The case were the pointer_value is non-zero and points to a class defined
4011 // in this Mach-O file.
4012 r = get_pointer_64(pointer_value, offset, left, S, info);
4013 if (r == nullptr || left < sizeof(struct class64_t))
4014 return nullptr;
4015 struct class64_t c;
4016 memcpy(&c, r, sizeof(struct class64_t));
4017 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4018 swapStruct(c);
4019 if (c.data == 0)
4020 return nullptr;
4021 r = get_pointer_64(c.data, offset, left, S, info);
4022 if (r == nullptr || left < sizeof(struct class_ro64_t))
4023 return nullptr;
4024 struct class_ro64_t cro;
4025 memcpy(&cro, r, sizeof(struct class_ro64_t));
4026 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4027 swapStruct(cro);
4028 if (cro.name == 0)
4029 return nullptr;
4030 const char *name = get_pointer_64(cro.name, offset, left, S, info);
4031 return name;
4034 // get_objc2_64bit_cfstring_name is used for disassembly and is passed a
4035 // pointer to a cfstring and returns its name or nullptr.
4036 static const char *get_objc2_64bit_cfstring_name(uint64_t ReferenceValue,
4037 struct DisassembleInfo *info) {
4038 const char *r, *name;
4039 uint32_t offset, left;
4040 SectionRef S;
4041 struct cfstring64_t cfs;
4042 uint64_t cfs_characters;
4044 r = get_pointer_64(ReferenceValue, offset, left, S, info);
4045 if (r == nullptr || left < sizeof(struct cfstring64_t))
4046 return nullptr;
4047 memcpy(&cfs, r, sizeof(struct cfstring64_t));
4048 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4049 swapStruct(cfs);
4050 if (cfs.characters == 0) {
4051 uint64_t n_value;
4052 const char *symbol_name = get_symbol_64(
4053 offset + offsetof(struct cfstring64_t, characters), S, info, n_value);
4054 if (symbol_name == nullptr)
4055 return nullptr;
4056 cfs_characters = n_value;
4057 } else
4058 cfs_characters = cfs.characters;
4059 name = get_pointer_64(cfs_characters, offset, left, S, info);
4061 return name;
4064 // get_objc2_64bit_selref() is used for disassembly and is passed a the address
4065 // of a pointer to an Objective-C selector reference when the pointer value is
4066 // zero as in a .o file and is likely to have a external relocation entry with
4067 // who's symbol's n_value is the real pointer to the selector name. If that is
4068 // the case the real pointer to the selector name is returned else 0 is
4069 // returned
4070 static uint64_t get_objc2_64bit_selref(uint64_t ReferenceValue,
4071 struct DisassembleInfo *info) {
4072 uint32_t offset, left;
4073 SectionRef S;
4075 const char *r = get_pointer_64(ReferenceValue, offset, left, S, info);
4076 if (r == nullptr || left < sizeof(uint64_t))
4077 return 0;
4078 uint64_t n_value;
4079 const char *symbol_name = get_symbol_64(offset, S, info, n_value);
4080 if (symbol_name == nullptr)
4081 return 0;
4082 return n_value;
4085 static const SectionRef get_section(MachOObjectFile *O, const char *segname,
4086 const char *sectname) {
4087 for (const SectionRef &Section : O->sections()) {
4088 StringRef SectName;
4089 Expected<StringRef> SecNameOrErr = Section.getName();
4090 if (SecNameOrErr)
4091 SectName = *SecNameOrErr;
4092 else
4093 consumeError(SecNameOrErr.takeError());
4095 DataRefImpl Ref = Section.getRawDataRefImpl();
4096 StringRef SegName = O->getSectionFinalSegmentName(Ref);
4097 if (SegName == segname && SectName == sectname)
4098 return Section;
4100 return SectionRef();
4103 static void
4104 walk_pointer_list_64(const char *listname, const SectionRef S,
4105 MachOObjectFile *O, struct DisassembleInfo *info,
4106 void (*func)(uint64_t, struct DisassembleInfo *info)) {
4107 if (S == SectionRef())
4108 return;
4110 StringRef SectName;
4111 Expected<StringRef> SecNameOrErr = S.getName();
4112 if (SecNameOrErr)
4113 SectName = *SecNameOrErr;
4114 else
4115 consumeError(SecNameOrErr.takeError());
4117 DataRefImpl Ref = S.getRawDataRefImpl();
4118 StringRef SegName = O->getSectionFinalSegmentName(Ref);
4119 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
4121 StringRef BytesStr = unwrapOrError(S.getContents(), O->getFileName());
4122 const char *Contents = reinterpret_cast<const char *>(BytesStr.data());
4124 for (uint32_t i = 0; i < S.getSize(); i += sizeof(uint64_t)) {
4125 uint32_t left = S.getSize() - i;
4126 uint32_t size = left < sizeof(uint64_t) ? left : sizeof(uint64_t);
4127 uint64_t p = 0;
4128 memcpy(&p, Contents + i, size);
4129 if (i + sizeof(uint64_t) > S.getSize())
4130 outs() << listname << " list pointer extends past end of (" << SegName
4131 << "," << SectName << ") section\n";
4132 outs() << format("%016" PRIx64, S.getAddress() + i) << " ";
4134 if (O->isLittleEndian() != sys::IsLittleEndianHost)
4135 sys::swapByteOrder(p);
4137 uint64_t n_value = 0;
4138 const char *name = get_symbol_64(i, S, info, n_value, p);
4139 if (name == nullptr)
4140 name = get_dyld_bind_info_symbolname(S.getAddress() + i, info);
4142 if (n_value != 0) {
4143 outs() << format("0x%" PRIx64, n_value);
4144 if (p != 0)
4145 outs() << " + " << format("0x%" PRIx64, p);
4146 } else
4147 outs() << format("0x%" PRIx64, p);
4148 if (name != nullptr)
4149 outs() << " " << name;
4150 outs() << "\n";
4152 p += n_value;
4153 if (func)
4154 func(p, info);
4158 static void
4159 walk_pointer_list_32(const char *listname, const SectionRef S,
4160 MachOObjectFile *O, struct DisassembleInfo *info,
4161 void (*func)(uint32_t, struct DisassembleInfo *info)) {
4162 if (S == SectionRef())
4163 return;
4165 StringRef SectName = unwrapOrError(S.getName(), O->getFileName());
4166 DataRefImpl Ref = S.getRawDataRefImpl();
4167 StringRef SegName = O->getSectionFinalSegmentName(Ref);
4168 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
4170 StringRef BytesStr = unwrapOrError(S.getContents(), O->getFileName());
4171 const char *Contents = reinterpret_cast<const char *>(BytesStr.data());
4173 for (uint32_t i = 0; i < S.getSize(); i += sizeof(uint32_t)) {
4174 uint32_t left = S.getSize() - i;
4175 uint32_t size = left < sizeof(uint32_t) ? left : sizeof(uint32_t);
4176 uint32_t p = 0;
4177 memcpy(&p, Contents + i, size);
4178 if (i + sizeof(uint32_t) > S.getSize())
4179 outs() << listname << " list pointer extends past end of (" << SegName
4180 << "," << SectName << ") section\n";
4181 uint32_t Address = S.getAddress() + i;
4182 outs() << format("%08" PRIx32, Address) << " ";
4184 if (O->isLittleEndian() != sys::IsLittleEndianHost)
4185 sys::swapByteOrder(p);
4186 outs() << format("0x%" PRIx32, p);
4188 const char *name = get_symbol_32(i, S, info, p);
4189 if (name != nullptr)
4190 outs() << " " << name;
4191 outs() << "\n";
4193 if (func)
4194 func(p, info);
4198 static void print_layout_map(const char *layout_map, uint32_t left) {
4199 if (layout_map == nullptr)
4200 return;
4201 outs() << " layout map: ";
4202 do {
4203 outs() << format("0x%02" PRIx32, (*layout_map) & 0xff) << " ";
4204 left--;
4205 layout_map++;
4206 } while (*layout_map != '\0' && left != 0);
4207 outs() << "\n";
4210 static void print_layout_map64(uint64_t p, struct DisassembleInfo *info) {
4211 uint32_t offset, left;
4212 SectionRef S;
4213 const char *layout_map;
4215 if (p == 0)
4216 return;
4217 layout_map = get_pointer_64(p, offset, left, S, info);
4218 print_layout_map(layout_map, left);
4221 static void print_layout_map32(uint32_t p, struct DisassembleInfo *info) {
4222 uint32_t offset, left;
4223 SectionRef S;
4224 const char *layout_map;
4226 if (p == 0)
4227 return;
4228 layout_map = get_pointer_32(p, offset, left, S, info);
4229 print_layout_map(layout_map, left);
4232 static void print_method_list64_t(uint64_t p, struct DisassembleInfo *info,
4233 const char *indent) {
4234 struct method_list64_t ml;
4235 struct method64_t m;
4236 const char *r;
4237 uint32_t offset, xoffset, left, i;
4238 SectionRef S, xS;
4239 const char *name, *sym_name;
4240 uint64_t n_value;
4242 r = get_pointer_64(p, offset, left, S, info);
4243 if (r == nullptr)
4244 return;
4245 memset(&ml, '\0', sizeof(struct method_list64_t));
4246 if (left < sizeof(struct method_list64_t)) {
4247 memcpy(&ml, r, left);
4248 outs() << " (method_list_t entends past the end of the section)\n";
4249 } else
4250 memcpy(&ml, r, sizeof(struct method_list64_t));
4251 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4252 swapStruct(ml);
4253 outs() << indent << "\t\t entsize " << ml.entsize << "\n";
4254 outs() << indent << "\t\t count " << ml.count << "\n";
4256 p += sizeof(struct method_list64_t);
4257 offset += sizeof(struct method_list64_t);
4258 for (i = 0; i < ml.count; i++) {
4259 r = get_pointer_64(p, offset, left, S, info);
4260 if (r == nullptr)
4261 return;
4262 memset(&m, '\0', sizeof(struct method64_t));
4263 if (left < sizeof(struct method64_t)) {
4264 memcpy(&m, r, left);
4265 outs() << indent << " (method_t extends past the end of the section)\n";
4266 } else
4267 memcpy(&m, r, sizeof(struct method64_t));
4268 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4269 swapStruct(m);
4271 outs() << indent << "\t\t name ";
4272 sym_name = get_symbol_64(offset + offsetof(struct method64_t, name), S,
4273 info, n_value, m.name);
4274 if (n_value != 0) {
4275 if (info->verbose && sym_name != nullptr)
4276 outs() << sym_name;
4277 else
4278 outs() << format("0x%" PRIx64, n_value);
4279 if (m.name != 0)
4280 outs() << " + " << format("0x%" PRIx64, m.name);
4281 } else
4282 outs() << format("0x%" PRIx64, m.name);
4283 name = get_pointer_64(m.name + n_value, xoffset, left, xS, info);
4284 if (name != nullptr)
4285 outs() << format(" %.*s", left, name);
4286 outs() << "\n";
4288 outs() << indent << "\t\t types ";
4289 sym_name = get_symbol_64(offset + offsetof(struct method64_t, types), S,
4290 info, n_value, m.types);
4291 if (n_value != 0) {
4292 if (info->verbose && sym_name != nullptr)
4293 outs() << sym_name;
4294 else
4295 outs() << format("0x%" PRIx64, n_value);
4296 if (m.types != 0)
4297 outs() << " + " << format("0x%" PRIx64, m.types);
4298 } else
4299 outs() << format("0x%" PRIx64, m.types);
4300 name = get_pointer_64(m.types + n_value, xoffset, left, xS, info);
4301 if (name != nullptr)
4302 outs() << format(" %.*s", left, name);
4303 outs() << "\n";
4305 outs() << indent << "\t\t imp ";
4306 name = get_symbol_64(offset + offsetof(struct method64_t, imp), S, info,
4307 n_value, m.imp);
4308 if (info->verbose && name == nullptr) {
4309 if (n_value != 0) {
4310 outs() << format("0x%" PRIx64, n_value) << " ";
4311 if (m.imp != 0)
4312 outs() << "+ " << format("0x%" PRIx64, m.imp) << " ";
4313 } else
4314 outs() << format("0x%" PRIx64, m.imp) << " ";
4316 if (name != nullptr)
4317 outs() << name;
4318 outs() << "\n";
4320 p += sizeof(struct method64_t);
4321 offset += sizeof(struct method64_t);
4325 static void print_method_list32_t(uint64_t p, struct DisassembleInfo *info,
4326 const char *indent) {
4327 struct method_list32_t ml;
4328 struct method32_t m;
4329 const char *r, *name;
4330 uint32_t offset, xoffset, left, i;
4331 SectionRef S, xS;
4333 r = get_pointer_32(p, offset, left, S, info);
4334 if (r == nullptr)
4335 return;
4336 memset(&ml, '\0', sizeof(struct method_list32_t));
4337 if (left < sizeof(struct method_list32_t)) {
4338 memcpy(&ml, r, left);
4339 outs() << " (method_list_t entends past the end of the section)\n";
4340 } else
4341 memcpy(&ml, r, sizeof(struct method_list32_t));
4342 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4343 swapStruct(ml);
4344 outs() << indent << "\t\t entsize " << ml.entsize << "\n";
4345 outs() << indent << "\t\t count " << ml.count << "\n";
4347 p += sizeof(struct method_list32_t);
4348 offset += sizeof(struct method_list32_t);
4349 for (i = 0; i < ml.count; i++) {
4350 r = get_pointer_32(p, offset, left, S, info);
4351 if (r == nullptr)
4352 return;
4353 memset(&m, '\0', sizeof(struct method32_t));
4354 if (left < sizeof(struct method32_t)) {
4355 memcpy(&ml, r, left);
4356 outs() << indent << " (method_t entends past the end of the section)\n";
4357 } else
4358 memcpy(&m, r, sizeof(struct method32_t));
4359 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4360 swapStruct(m);
4362 outs() << indent << "\t\t name " << format("0x%" PRIx32, m.name);
4363 name = get_pointer_32(m.name, xoffset, left, xS, info);
4364 if (name != nullptr)
4365 outs() << format(" %.*s", left, name);
4366 outs() << "\n";
4368 outs() << indent << "\t\t types " << format("0x%" PRIx32, m.types);
4369 name = get_pointer_32(m.types, xoffset, left, xS, info);
4370 if (name != nullptr)
4371 outs() << format(" %.*s", left, name);
4372 outs() << "\n";
4374 outs() << indent << "\t\t imp " << format("0x%" PRIx32, m.imp);
4375 name = get_symbol_32(offset + offsetof(struct method32_t, imp), S, info,
4376 m.imp);
4377 if (name != nullptr)
4378 outs() << " " << name;
4379 outs() << "\n";
4381 p += sizeof(struct method32_t);
4382 offset += sizeof(struct method32_t);
4386 static bool print_method_list(uint32_t p, struct DisassembleInfo *info) {
4387 uint32_t offset, left, xleft;
4388 SectionRef S;
4389 struct objc_method_list_t method_list;
4390 struct objc_method_t method;
4391 const char *r, *methods, *name, *SymbolName;
4392 int32_t i;
4394 r = get_pointer_32(p, offset, left, S, info, true);
4395 if (r == nullptr)
4396 return true;
4398 outs() << "\n";
4399 if (left > sizeof(struct objc_method_list_t)) {
4400 memcpy(&method_list, r, sizeof(struct objc_method_list_t));
4401 } else {
4402 outs() << "\t\t objc_method_list extends past end of the section\n";
4403 memset(&method_list, '\0', sizeof(struct objc_method_list_t));
4404 memcpy(&method_list, r, left);
4406 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4407 swapStruct(method_list);
4409 outs() << "\t\t obsolete "
4410 << format("0x%08" PRIx32, method_list.obsolete) << "\n";
4411 outs() << "\t\t method_count " << method_list.method_count << "\n";
4413 methods = r + sizeof(struct objc_method_list_t);
4414 for (i = 0; i < method_list.method_count; i++) {
4415 if ((i + 1) * sizeof(struct objc_method_t) > left) {
4416 outs() << "\t\t remaining method's extend past the of the section\n";
4417 break;
4419 memcpy(&method, methods + i * sizeof(struct objc_method_t),
4420 sizeof(struct objc_method_t));
4421 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4422 swapStruct(method);
4424 outs() << "\t\t method_name "
4425 << format("0x%08" PRIx32, method.method_name);
4426 if (info->verbose) {
4427 name = get_pointer_32(method.method_name, offset, xleft, S, info, true);
4428 if (name != nullptr)
4429 outs() << format(" %.*s", xleft, name);
4430 else
4431 outs() << " (not in an __OBJC section)";
4433 outs() << "\n";
4435 outs() << "\t\t method_types "
4436 << format("0x%08" PRIx32, method.method_types);
4437 if (info->verbose) {
4438 name = get_pointer_32(method.method_types, offset, xleft, S, info, true);
4439 if (name != nullptr)
4440 outs() << format(" %.*s", xleft, name);
4441 else
4442 outs() << " (not in an __OBJC section)";
4444 outs() << "\n";
4446 outs() << "\t\t method_imp "
4447 << format("0x%08" PRIx32, method.method_imp) << " ";
4448 if (info->verbose) {
4449 SymbolName = GuessSymbolName(method.method_imp, info->AddrMap);
4450 if (SymbolName != nullptr)
4451 outs() << SymbolName;
4453 outs() << "\n";
4455 return false;
4458 static void print_protocol_list64_t(uint64_t p, struct DisassembleInfo *info) {
4459 struct protocol_list64_t pl;
4460 uint64_t q, n_value;
4461 struct protocol64_t pc;
4462 const char *r;
4463 uint32_t offset, xoffset, left, i;
4464 SectionRef S, xS;
4465 const char *name, *sym_name;
4467 r = get_pointer_64(p, offset, left, S, info);
4468 if (r == nullptr)
4469 return;
4470 memset(&pl, '\0', sizeof(struct protocol_list64_t));
4471 if (left < sizeof(struct protocol_list64_t)) {
4472 memcpy(&pl, r, left);
4473 outs() << " (protocol_list_t entends past the end of the section)\n";
4474 } else
4475 memcpy(&pl, r, sizeof(struct protocol_list64_t));
4476 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4477 swapStruct(pl);
4478 outs() << " count " << pl.count << "\n";
4480 p += sizeof(struct protocol_list64_t);
4481 offset += sizeof(struct protocol_list64_t);
4482 for (i = 0; i < pl.count; i++) {
4483 r = get_pointer_64(p, offset, left, S, info);
4484 if (r == nullptr)
4485 return;
4486 q = 0;
4487 if (left < sizeof(uint64_t)) {
4488 memcpy(&q, r, left);
4489 outs() << " (protocol_t * entends past the end of the section)\n";
4490 } else
4491 memcpy(&q, r, sizeof(uint64_t));
4492 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4493 sys::swapByteOrder(q);
4495 outs() << "\t\t list[" << i << "] ";
4496 sym_name = get_symbol_64(offset, S, info, n_value, q);
4497 if (n_value != 0) {
4498 if (info->verbose && sym_name != nullptr)
4499 outs() << sym_name;
4500 else
4501 outs() << format("0x%" PRIx64, n_value);
4502 if (q != 0)
4503 outs() << " + " << format("0x%" PRIx64, q);
4504 } else
4505 outs() << format("0x%" PRIx64, q);
4506 outs() << " (struct protocol_t *)\n";
4508 r = get_pointer_64(q + n_value, offset, left, S, info);
4509 if (r == nullptr)
4510 return;
4511 memset(&pc, '\0', sizeof(struct protocol64_t));
4512 if (left < sizeof(struct protocol64_t)) {
4513 memcpy(&pc, r, left);
4514 outs() << " (protocol_t entends past the end of the section)\n";
4515 } else
4516 memcpy(&pc, r, sizeof(struct protocol64_t));
4517 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4518 swapStruct(pc);
4520 outs() << "\t\t\t isa " << format("0x%" PRIx64, pc.isa) << "\n";
4522 outs() << "\t\t\t name ";
4523 sym_name = get_symbol_64(offset + offsetof(struct protocol64_t, name), S,
4524 info, n_value, pc.name);
4525 if (n_value != 0) {
4526 if (info->verbose && sym_name != nullptr)
4527 outs() << sym_name;
4528 else
4529 outs() << format("0x%" PRIx64, n_value);
4530 if (pc.name != 0)
4531 outs() << " + " << format("0x%" PRIx64, pc.name);
4532 } else
4533 outs() << format("0x%" PRIx64, pc.name);
4534 name = get_pointer_64(pc.name + n_value, xoffset, left, xS, info);
4535 if (name != nullptr)
4536 outs() << format(" %.*s", left, name);
4537 outs() << "\n";
4539 outs() << "\t\t\tprotocols " << format("0x%" PRIx64, pc.protocols) << "\n";
4541 outs() << "\t\t instanceMethods ";
4542 sym_name =
4543 get_symbol_64(offset + offsetof(struct protocol64_t, instanceMethods),
4544 S, info, n_value, pc.instanceMethods);
4545 if (n_value != 0) {
4546 if (info->verbose && sym_name != nullptr)
4547 outs() << sym_name;
4548 else
4549 outs() << format("0x%" PRIx64, n_value);
4550 if (pc.instanceMethods != 0)
4551 outs() << " + " << format("0x%" PRIx64, pc.instanceMethods);
4552 } else
4553 outs() << format("0x%" PRIx64, pc.instanceMethods);
4554 outs() << " (struct method_list_t *)\n";
4555 if (pc.instanceMethods + n_value != 0)
4556 print_method_list64_t(pc.instanceMethods + n_value, info, "\t");
4558 outs() << "\t\t classMethods ";
4559 sym_name =
4560 get_symbol_64(offset + offsetof(struct protocol64_t, classMethods), S,
4561 info, n_value, pc.classMethods);
4562 if (n_value != 0) {
4563 if (info->verbose && sym_name != nullptr)
4564 outs() << sym_name;
4565 else
4566 outs() << format("0x%" PRIx64, n_value);
4567 if (pc.classMethods != 0)
4568 outs() << " + " << format("0x%" PRIx64, pc.classMethods);
4569 } else
4570 outs() << format("0x%" PRIx64, pc.classMethods);
4571 outs() << " (struct method_list_t *)\n";
4572 if (pc.classMethods + n_value != 0)
4573 print_method_list64_t(pc.classMethods + n_value, info, "\t");
4575 outs() << "\t optionalInstanceMethods "
4576 << format("0x%" PRIx64, pc.optionalInstanceMethods) << "\n";
4577 outs() << "\t optionalClassMethods "
4578 << format("0x%" PRIx64, pc.optionalClassMethods) << "\n";
4579 outs() << "\t instanceProperties "
4580 << format("0x%" PRIx64, pc.instanceProperties) << "\n";
4582 p += sizeof(uint64_t);
4583 offset += sizeof(uint64_t);
4587 static void print_protocol_list32_t(uint32_t p, struct DisassembleInfo *info) {
4588 struct protocol_list32_t pl;
4589 uint32_t q;
4590 struct protocol32_t pc;
4591 const char *r;
4592 uint32_t offset, xoffset, left, i;
4593 SectionRef S, xS;
4594 const char *name;
4596 r = get_pointer_32(p, offset, left, S, info);
4597 if (r == nullptr)
4598 return;
4599 memset(&pl, '\0', sizeof(struct protocol_list32_t));
4600 if (left < sizeof(struct protocol_list32_t)) {
4601 memcpy(&pl, r, left);
4602 outs() << " (protocol_list_t entends past the end of the section)\n";
4603 } else
4604 memcpy(&pl, r, sizeof(struct protocol_list32_t));
4605 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4606 swapStruct(pl);
4607 outs() << " count " << pl.count << "\n";
4609 p += sizeof(struct protocol_list32_t);
4610 offset += sizeof(struct protocol_list32_t);
4611 for (i = 0; i < pl.count; i++) {
4612 r = get_pointer_32(p, offset, left, S, info);
4613 if (r == nullptr)
4614 return;
4615 q = 0;
4616 if (left < sizeof(uint32_t)) {
4617 memcpy(&q, r, left);
4618 outs() << " (protocol_t * entends past the end of the section)\n";
4619 } else
4620 memcpy(&q, r, sizeof(uint32_t));
4621 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4622 sys::swapByteOrder(q);
4623 outs() << "\t\t list[" << i << "] " << format("0x%" PRIx32, q)
4624 << " (struct protocol_t *)\n";
4625 r = get_pointer_32(q, offset, left, S, info);
4626 if (r == nullptr)
4627 return;
4628 memset(&pc, '\0', sizeof(struct protocol32_t));
4629 if (left < sizeof(struct protocol32_t)) {
4630 memcpy(&pc, r, left);
4631 outs() << " (protocol_t entends past the end of the section)\n";
4632 } else
4633 memcpy(&pc, r, sizeof(struct protocol32_t));
4634 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4635 swapStruct(pc);
4636 outs() << "\t\t\t isa " << format("0x%" PRIx32, pc.isa) << "\n";
4637 outs() << "\t\t\t name " << format("0x%" PRIx32, pc.name);
4638 name = get_pointer_32(pc.name, xoffset, left, xS, info);
4639 if (name != nullptr)
4640 outs() << format(" %.*s", left, name);
4641 outs() << "\n";
4642 outs() << "\t\t\tprotocols " << format("0x%" PRIx32, pc.protocols) << "\n";
4643 outs() << "\t\t instanceMethods "
4644 << format("0x%" PRIx32, pc.instanceMethods)
4645 << " (struct method_list_t *)\n";
4646 if (pc.instanceMethods != 0)
4647 print_method_list32_t(pc.instanceMethods, info, "\t");
4648 outs() << "\t\t classMethods " << format("0x%" PRIx32, pc.classMethods)
4649 << " (struct method_list_t *)\n";
4650 if (pc.classMethods != 0)
4651 print_method_list32_t(pc.classMethods, info, "\t");
4652 outs() << "\t optionalInstanceMethods "
4653 << format("0x%" PRIx32, pc.optionalInstanceMethods) << "\n";
4654 outs() << "\t optionalClassMethods "
4655 << format("0x%" PRIx32, pc.optionalClassMethods) << "\n";
4656 outs() << "\t instanceProperties "
4657 << format("0x%" PRIx32, pc.instanceProperties) << "\n";
4658 p += sizeof(uint32_t);
4659 offset += sizeof(uint32_t);
4663 static void print_indent(uint32_t indent) {
4664 for (uint32_t i = 0; i < indent;) {
4665 if (indent - i >= 8) {
4666 outs() << "\t";
4667 i += 8;
4668 } else {
4669 for (uint32_t j = i; j < indent; j++)
4670 outs() << " ";
4671 return;
4676 static bool print_method_description_list(uint32_t p, uint32_t indent,
4677 struct DisassembleInfo *info) {
4678 uint32_t offset, left, xleft;
4679 SectionRef S;
4680 struct objc_method_description_list_t mdl;
4681 struct objc_method_description_t md;
4682 const char *r, *list, *name;
4683 int32_t i;
4685 r = get_pointer_32(p, offset, left, S, info, true);
4686 if (r == nullptr)
4687 return true;
4689 outs() << "\n";
4690 if (left > sizeof(struct objc_method_description_list_t)) {
4691 memcpy(&mdl, r, sizeof(struct objc_method_description_list_t));
4692 } else {
4693 print_indent(indent);
4694 outs() << " objc_method_description_list extends past end of the section\n";
4695 memset(&mdl, '\0', sizeof(struct objc_method_description_list_t));
4696 memcpy(&mdl, r, left);
4698 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4699 swapStruct(mdl);
4701 print_indent(indent);
4702 outs() << " count " << mdl.count << "\n";
4704 list = r + sizeof(struct objc_method_description_list_t);
4705 for (i = 0; i < mdl.count; i++) {
4706 if ((i + 1) * sizeof(struct objc_method_description_t) > left) {
4707 print_indent(indent);
4708 outs() << " remaining list entries extend past the of the section\n";
4709 break;
4711 print_indent(indent);
4712 outs() << " list[" << i << "]\n";
4713 memcpy(&md, list + i * sizeof(struct objc_method_description_t),
4714 sizeof(struct objc_method_description_t));
4715 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4716 swapStruct(md);
4718 print_indent(indent);
4719 outs() << " name " << format("0x%08" PRIx32, md.name);
4720 if (info->verbose) {
4721 name = get_pointer_32(md.name, offset, xleft, S, info, true);
4722 if (name != nullptr)
4723 outs() << format(" %.*s", xleft, name);
4724 else
4725 outs() << " (not in an __OBJC section)";
4727 outs() << "\n";
4729 print_indent(indent);
4730 outs() << " types " << format("0x%08" PRIx32, md.types);
4731 if (info->verbose) {
4732 name = get_pointer_32(md.types, offset, xleft, S, info, true);
4733 if (name != nullptr)
4734 outs() << format(" %.*s", xleft, name);
4735 else
4736 outs() << " (not in an __OBJC section)";
4738 outs() << "\n";
4740 return false;
4743 static bool print_protocol_list(uint32_t p, uint32_t indent,
4744 struct DisassembleInfo *info);
4746 static bool print_protocol(uint32_t p, uint32_t indent,
4747 struct DisassembleInfo *info) {
4748 uint32_t offset, left;
4749 SectionRef S;
4750 struct objc_protocol_t protocol;
4751 const char *r, *name;
4753 r = get_pointer_32(p, offset, left, S, info, true);
4754 if (r == nullptr)
4755 return true;
4757 outs() << "\n";
4758 if (left >= sizeof(struct objc_protocol_t)) {
4759 memcpy(&protocol, r, sizeof(struct objc_protocol_t));
4760 } else {
4761 print_indent(indent);
4762 outs() << " Protocol extends past end of the section\n";
4763 memset(&protocol, '\0', sizeof(struct objc_protocol_t));
4764 memcpy(&protocol, r, left);
4766 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4767 swapStruct(protocol);
4769 print_indent(indent);
4770 outs() << " isa " << format("0x%08" PRIx32, protocol.isa)
4771 << "\n";
4773 print_indent(indent);
4774 outs() << " protocol_name "
4775 << format("0x%08" PRIx32, protocol.protocol_name);
4776 if (info->verbose) {
4777 name = get_pointer_32(protocol.protocol_name, offset, left, S, info, true);
4778 if (name != nullptr)
4779 outs() << format(" %.*s", left, name);
4780 else
4781 outs() << " (not in an __OBJC section)";
4783 outs() << "\n";
4785 print_indent(indent);
4786 outs() << " protocol_list "
4787 << format("0x%08" PRIx32, protocol.protocol_list);
4788 if (print_protocol_list(protocol.protocol_list, indent + 4, info))
4789 outs() << " (not in an __OBJC section)\n";
4791 print_indent(indent);
4792 outs() << " instance_methods "
4793 << format("0x%08" PRIx32, protocol.instance_methods);
4794 if (print_method_description_list(protocol.instance_methods, indent, info))
4795 outs() << " (not in an __OBJC section)\n";
4797 print_indent(indent);
4798 outs() << " class_methods "
4799 << format("0x%08" PRIx32, protocol.class_methods);
4800 if (print_method_description_list(protocol.class_methods, indent, info))
4801 outs() << " (not in an __OBJC section)\n";
4803 return false;
4806 static bool print_protocol_list(uint32_t p, uint32_t indent,
4807 struct DisassembleInfo *info) {
4808 uint32_t offset, left, l;
4809 SectionRef S;
4810 struct objc_protocol_list_t protocol_list;
4811 const char *r, *list;
4812 int32_t i;
4814 r = get_pointer_32(p, offset, left, S, info, true);
4815 if (r == nullptr)
4816 return true;
4818 outs() << "\n";
4819 if (left > sizeof(struct objc_protocol_list_t)) {
4820 memcpy(&protocol_list, r, sizeof(struct objc_protocol_list_t));
4821 } else {
4822 outs() << "\t\t objc_protocol_list_t extends past end of the section\n";
4823 memset(&protocol_list, '\0', sizeof(struct objc_protocol_list_t));
4824 memcpy(&protocol_list, r, left);
4826 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4827 swapStruct(protocol_list);
4829 print_indent(indent);
4830 outs() << " next " << format("0x%08" PRIx32, protocol_list.next)
4831 << "\n";
4832 print_indent(indent);
4833 outs() << " count " << protocol_list.count << "\n";
4835 list = r + sizeof(struct objc_protocol_list_t);
4836 for (i = 0; i < protocol_list.count; i++) {
4837 if ((i + 1) * sizeof(uint32_t) > left) {
4838 outs() << "\t\t remaining list entries extend past the of the section\n";
4839 break;
4841 memcpy(&l, list + i * sizeof(uint32_t), sizeof(uint32_t));
4842 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4843 sys::swapByteOrder(l);
4845 print_indent(indent);
4846 outs() << " list[" << i << "] " << format("0x%08" PRIx32, l);
4847 if (print_protocol(l, indent, info))
4848 outs() << "(not in an __OBJC section)\n";
4850 return false;
4853 static void print_ivar_list64_t(uint64_t p, struct DisassembleInfo *info) {
4854 struct ivar_list64_t il;
4855 struct ivar64_t i;
4856 const char *r;
4857 uint32_t offset, xoffset, left, j;
4858 SectionRef S, xS;
4859 const char *name, *sym_name, *ivar_offset_p;
4860 uint64_t ivar_offset, n_value;
4862 r = get_pointer_64(p, offset, left, S, info);
4863 if (r == nullptr)
4864 return;
4865 memset(&il, '\0', sizeof(struct ivar_list64_t));
4866 if (left < sizeof(struct ivar_list64_t)) {
4867 memcpy(&il, r, left);
4868 outs() << " (ivar_list_t entends past the end of the section)\n";
4869 } else
4870 memcpy(&il, r, sizeof(struct ivar_list64_t));
4871 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4872 swapStruct(il);
4873 outs() << " entsize " << il.entsize << "\n";
4874 outs() << " count " << il.count << "\n";
4876 p += sizeof(struct ivar_list64_t);
4877 offset += sizeof(struct ivar_list64_t);
4878 for (j = 0; j < il.count; j++) {
4879 r = get_pointer_64(p, offset, left, S, info);
4880 if (r == nullptr)
4881 return;
4882 memset(&i, '\0', sizeof(struct ivar64_t));
4883 if (left < sizeof(struct ivar64_t)) {
4884 memcpy(&i, r, left);
4885 outs() << " (ivar_t entends past the end of the section)\n";
4886 } else
4887 memcpy(&i, r, sizeof(struct ivar64_t));
4888 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4889 swapStruct(i);
4891 outs() << "\t\t\t offset ";
4892 sym_name = get_symbol_64(offset + offsetof(struct ivar64_t, offset), S,
4893 info, n_value, i.offset);
4894 if (n_value != 0) {
4895 if (info->verbose && sym_name != nullptr)
4896 outs() << sym_name;
4897 else
4898 outs() << format("0x%" PRIx64, n_value);
4899 if (i.offset != 0)
4900 outs() << " + " << format("0x%" PRIx64, i.offset);
4901 } else
4902 outs() << format("0x%" PRIx64, i.offset);
4903 ivar_offset_p = get_pointer_64(i.offset + n_value, xoffset, left, xS, info);
4904 if (ivar_offset_p != nullptr && left >= sizeof(*ivar_offset_p)) {
4905 memcpy(&ivar_offset, ivar_offset_p, sizeof(ivar_offset));
4906 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4907 sys::swapByteOrder(ivar_offset);
4908 outs() << " " << ivar_offset << "\n";
4909 } else
4910 outs() << "\n";
4912 outs() << "\t\t\t name ";
4913 sym_name = get_symbol_64(offset + offsetof(struct ivar64_t, name), S, info,
4914 n_value, i.name);
4915 if (n_value != 0) {
4916 if (info->verbose && sym_name != nullptr)
4917 outs() << sym_name;
4918 else
4919 outs() << format("0x%" PRIx64, n_value);
4920 if (i.name != 0)
4921 outs() << " + " << format("0x%" PRIx64, i.name);
4922 } else
4923 outs() << format("0x%" PRIx64, i.name);
4924 name = get_pointer_64(i.name + n_value, xoffset, left, xS, info);
4925 if (name != nullptr)
4926 outs() << format(" %.*s", left, name);
4927 outs() << "\n";
4929 outs() << "\t\t\t type ";
4930 sym_name = get_symbol_64(offset + offsetof(struct ivar64_t, type), S, info,
4931 n_value, i.name);
4932 name = get_pointer_64(i.type + n_value, xoffset, left, xS, info);
4933 if (n_value != 0) {
4934 if (info->verbose && sym_name != nullptr)
4935 outs() << sym_name;
4936 else
4937 outs() << format("0x%" PRIx64, n_value);
4938 if (i.type != 0)
4939 outs() << " + " << format("0x%" PRIx64, i.type);
4940 } else
4941 outs() << format("0x%" PRIx64, i.type);
4942 if (name != nullptr)
4943 outs() << format(" %.*s", left, name);
4944 outs() << "\n";
4946 outs() << "\t\t\talignment " << i.alignment << "\n";
4947 outs() << "\t\t\t size " << i.size << "\n";
4949 p += sizeof(struct ivar64_t);
4950 offset += sizeof(struct ivar64_t);
4954 static void print_ivar_list32_t(uint32_t p, struct DisassembleInfo *info) {
4955 struct ivar_list32_t il;
4956 struct ivar32_t i;
4957 const char *r;
4958 uint32_t offset, xoffset, left, j;
4959 SectionRef S, xS;
4960 const char *name, *ivar_offset_p;
4961 uint32_t ivar_offset;
4963 r = get_pointer_32(p, offset, left, S, info);
4964 if (r == nullptr)
4965 return;
4966 memset(&il, '\0', sizeof(struct ivar_list32_t));
4967 if (left < sizeof(struct ivar_list32_t)) {
4968 memcpy(&il, r, left);
4969 outs() << " (ivar_list_t entends past the end of the section)\n";
4970 } else
4971 memcpy(&il, r, sizeof(struct ivar_list32_t));
4972 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4973 swapStruct(il);
4974 outs() << " entsize " << il.entsize << "\n";
4975 outs() << " count " << il.count << "\n";
4977 p += sizeof(struct ivar_list32_t);
4978 offset += sizeof(struct ivar_list32_t);
4979 for (j = 0; j < il.count; j++) {
4980 r = get_pointer_32(p, offset, left, S, info);
4981 if (r == nullptr)
4982 return;
4983 memset(&i, '\0', sizeof(struct ivar32_t));
4984 if (left < sizeof(struct ivar32_t)) {
4985 memcpy(&i, r, left);
4986 outs() << " (ivar_t entends past the end of the section)\n";
4987 } else
4988 memcpy(&i, r, sizeof(struct ivar32_t));
4989 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4990 swapStruct(i);
4992 outs() << "\t\t\t offset " << format("0x%" PRIx32, i.offset);
4993 ivar_offset_p = get_pointer_32(i.offset, xoffset, left, xS, info);
4994 if (ivar_offset_p != nullptr && left >= sizeof(*ivar_offset_p)) {
4995 memcpy(&ivar_offset, ivar_offset_p, sizeof(ivar_offset));
4996 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4997 sys::swapByteOrder(ivar_offset);
4998 outs() << " " << ivar_offset << "\n";
4999 } else
5000 outs() << "\n";
5002 outs() << "\t\t\t name " << format("0x%" PRIx32, i.name);
5003 name = get_pointer_32(i.name, xoffset, left, xS, info);
5004 if (name != nullptr)
5005 outs() << format(" %.*s", left, name);
5006 outs() << "\n";
5008 outs() << "\t\t\t type " << format("0x%" PRIx32, i.type);
5009 name = get_pointer_32(i.type, xoffset, left, xS, info);
5010 if (name != nullptr)
5011 outs() << format(" %.*s", left, name);
5012 outs() << "\n";
5014 outs() << "\t\t\talignment " << i.alignment << "\n";
5015 outs() << "\t\t\t size " << i.size << "\n";
5017 p += sizeof(struct ivar32_t);
5018 offset += sizeof(struct ivar32_t);
5022 static void print_objc_property_list64(uint64_t p,
5023 struct DisassembleInfo *info) {
5024 struct objc_property_list64 opl;
5025 struct objc_property64 op;
5026 const char *r;
5027 uint32_t offset, xoffset, left, j;
5028 SectionRef S, xS;
5029 const char *name, *sym_name;
5030 uint64_t n_value;
5032 r = get_pointer_64(p, offset, left, S, info);
5033 if (r == nullptr)
5034 return;
5035 memset(&opl, '\0', sizeof(struct objc_property_list64));
5036 if (left < sizeof(struct objc_property_list64)) {
5037 memcpy(&opl, r, left);
5038 outs() << " (objc_property_list entends past the end of the section)\n";
5039 } else
5040 memcpy(&opl, r, sizeof(struct objc_property_list64));
5041 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5042 swapStruct(opl);
5043 outs() << " entsize " << opl.entsize << "\n";
5044 outs() << " count " << opl.count << "\n";
5046 p += sizeof(struct objc_property_list64);
5047 offset += sizeof(struct objc_property_list64);
5048 for (j = 0; j < opl.count; j++) {
5049 r = get_pointer_64(p, offset, left, S, info);
5050 if (r == nullptr)
5051 return;
5052 memset(&op, '\0', sizeof(struct objc_property64));
5053 if (left < sizeof(struct objc_property64)) {
5054 memcpy(&op, r, left);
5055 outs() << " (objc_property entends past the end of the section)\n";
5056 } else
5057 memcpy(&op, r, sizeof(struct objc_property64));
5058 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5059 swapStruct(op);
5061 outs() << "\t\t\t name ";
5062 sym_name = get_symbol_64(offset + offsetof(struct objc_property64, name), S,
5063 info, n_value, op.name);
5064 if (n_value != 0) {
5065 if (info->verbose && sym_name != nullptr)
5066 outs() << sym_name;
5067 else
5068 outs() << format("0x%" PRIx64, n_value);
5069 if (op.name != 0)
5070 outs() << " + " << format("0x%" PRIx64, op.name);
5071 } else
5072 outs() << format("0x%" PRIx64, op.name);
5073 name = get_pointer_64(op.name + n_value, xoffset, left, xS, info);
5074 if (name != nullptr)
5075 outs() << format(" %.*s", left, name);
5076 outs() << "\n";
5078 outs() << "\t\t\tattributes ";
5079 sym_name =
5080 get_symbol_64(offset + offsetof(struct objc_property64, attributes), S,
5081 info, n_value, op.attributes);
5082 if (n_value != 0) {
5083 if (info->verbose && sym_name != nullptr)
5084 outs() << sym_name;
5085 else
5086 outs() << format("0x%" PRIx64, n_value);
5087 if (op.attributes != 0)
5088 outs() << " + " << format("0x%" PRIx64, op.attributes);
5089 } else
5090 outs() << format("0x%" PRIx64, op.attributes);
5091 name = get_pointer_64(op.attributes + n_value, xoffset, left, xS, info);
5092 if (name != nullptr)
5093 outs() << format(" %.*s", left, name);
5094 outs() << "\n";
5096 p += sizeof(struct objc_property64);
5097 offset += sizeof(struct objc_property64);
5101 static void print_objc_property_list32(uint32_t p,
5102 struct DisassembleInfo *info) {
5103 struct objc_property_list32 opl;
5104 struct objc_property32 op;
5105 const char *r;
5106 uint32_t offset, xoffset, left, j;
5107 SectionRef S, xS;
5108 const char *name;
5110 r = get_pointer_32(p, offset, left, S, info);
5111 if (r == nullptr)
5112 return;
5113 memset(&opl, '\0', sizeof(struct objc_property_list32));
5114 if (left < sizeof(struct objc_property_list32)) {
5115 memcpy(&opl, r, left);
5116 outs() << " (objc_property_list entends past the end of the section)\n";
5117 } else
5118 memcpy(&opl, r, sizeof(struct objc_property_list32));
5119 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5120 swapStruct(opl);
5121 outs() << " entsize " << opl.entsize << "\n";
5122 outs() << " count " << opl.count << "\n";
5124 p += sizeof(struct objc_property_list32);
5125 offset += sizeof(struct objc_property_list32);
5126 for (j = 0; j < opl.count; j++) {
5127 r = get_pointer_32(p, offset, left, S, info);
5128 if (r == nullptr)
5129 return;
5130 memset(&op, '\0', sizeof(struct objc_property32));
5131 if (left < sizeof(struct objc_property32)) {
5132 memcpy(&op, r, left);
5133 outs() << " (objc_property entends past the end of the section)\n";
5134 } else
5135 memcpy(&op, r, sizeof(struct objc_property32));
5136 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5137 swapStruct(op);
5139 outs() << "\t\t\t name " << format("0x%" PRIx32, op.name);
5140 name = get_pointer_32(op.name, xoffset, left, xS, info);
5141 if (name != nullptr)
5142 outs() << format(" %.*s", left, name);
5143 outs() << "\n";
5145 outs() << "\t\t\tattributes " << format("0x%" PRIx32, op.attributes);
5146 name = get_pointer_32(op.attributes, xoffset, left, xS, info);
5147 if (name != nullptr)
5148 outs() << format(" %.*s", left, name);
5149 outs() << "\n";
5151 p += sizeof(struct objc_property32);
5152 offset += sizeof(struct objc_property32);
5156 static bool print_class_ro64_t(uint64_t p, struct DisassembleInfo *info,
5157 bool &is_meta_class) {
5158 struct class_ro64_t cro;
5159 const char *r;
5160 uint32_t offset, xoffset, left;
5161 SectionRef S, xS;
5162 const char *name, *sym_name;
5163 uint64_t n_value;
5165 r = get_pointer_64(p, offset, left, S, info);
5166 if (r == nullptr || left < sizeof(struct class_ro64_t))
5167 return false;
5168 memcpy(&cro, r, sizeof(struct class_ro64_t));
5169 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5170 swapStruct(cro);
5171 outs() << " flags " << format("0x%" PRIx32, cro.flags);
5172 if (cro.flags & RO_META)
5173 outs() << " RO_META";
5174 if (cro.flags & RO_ROOT)
5175 outs() << " RO_ROOT";
5176 if (cro.flags & RO_HAS_CXX_STRUCTORS)
5177 outs() << " RO_HAS_CXX_STRUCTORS";
5178 outs() << "\n";
5179 outs() << " instanceStart " << cro.instanceStart << "\n";
5180 outs() << " instanceSize " << cro.instanceSize << "\n";
5181 outs() << " reserved " << format("0x%" PRIx32, cro.reserved)
5182 << "\n";
5183 outs() << " ivarLayout " << format("0x%" PRIx64, cro.ivarLayout)
5184 << "\n";
5185 print_layout_map64(cro.ivarLayout, info);
5187 outs() << " name ";
5188 sym_name = get_symbol_64(offset + offsetof(struct class_ro64_t, name), S,
5189 info, n_value, cro.name);
5190 if (n_value != 0) {
5191 if (info->verbose && sym_name != nullptr)
5192 outs() << sym_name;
5193 else
5194 outs() << format("0x%" PRIx64, n_value);
5195 if (cro.name != 0)
5196 outs() << " + " << format("0x%" PRIx64, cro.name);
5197 } else
5198 outs() << format("0x%" PRIx64, cro.name);
5199 name = get_pointer_64(cro.name + n_value, xoffset, left, xS, info);
5200 if (name != nullptr)
5201 outs() << format(" %.*s", left, name);
5202 outs() << "\n";
5204 outs() << " baseMethods ";
5205 sym_name = get_symbol_64(offset + offsetof(struct class_ro64_t, baseMethods),
5206 S, info, n_value, cro.baseMethods);
5207 if (n_value != 0) {
5208 if (info->verbose && sym_name != nullptr)
5209 outs() << sym_name;
5210 else
5211 outs() << format("0x%" PRIx64, n_value);
5212 if (cro.baseMethods != 0)
5213 outs() << " + " << format("0x%" PRIx64, cro.baseMethods);
5214 } else
5215 outs() << format("0x%" PRIx64, cro.baseMethods);
5216 outs() << " (struct method_list_t *)\n";
5217 if (cro.baseMethods + n_value != 0)
5218 print_method_list64_t(cro.baseMethods + n_value, info, "");
5220 outs() << " baseProtocols ";
5221 sym_name =
5222 get_symbol_64(offset + offsetof(struct class_ro64_t, baseProtocols), S,
5223 info, n_value, cro.baseProtocols);
5224 if (n_value != 0) {
5225 if (info->verbose && sym_name != nullptr)
5226 outs() << sym_name;
5227 else
5228 outs() << format("0x%" PRIx64, n_value);
5229 if (cro.baseProtocols != 0)
5230 outs() << " + " << format("0x%" PRIx64, cro.baseProtocols);
5231 } else
5232 outs() << format("0x%" PRIx64, cro.baseProtocols);
5233 outs() << "\n";
5234 if (cro.baseProtocols + n_value != 0)
5235 print_protocol_list64_t(cro.baseProtocols + n_value, info);
5237 outs() << " ivars ";
5238 sym_name = get_symbol_64(offset + offsetof(struct class_ro64_t, ivars), S,
5239 info, n_value, cro.ivars);
5240 if (n_value != 0) {
5241 if (info->verbose && sym_name != nullptr)
5242 outs() << sym_name;
5243 else
5244 outs() << format("0x%" PRIx64, n_value);
5245 if (cro.ivars != 0)
5246 outs() << " + " << format("0x%" PRIx64, cro.ivars);
5247 } else
5248 outs() << format("0x%" PRIx64, cro.ivars);
5249 outs() << "\n";
5250 if (cro.ivars + n_value != 0)
5251 print_ivar_list64_t(cro.ivars + n_value, info);
5253 outs() << " weakIvarLayout ";
5254 sym_name =
5255 get_symbol_64(offset + offsetof(struct class_ro64_t, weakIvarLayout), S,
5256 info, n_value, cro.weakIvarLayout);
5257 if (n_value != 0) {
5258 if (info->verbose && sym_name != nullptr)
5259 outs() << sym_name;
5260 else
5261 outs() << format("0x%" PRIx64, n_value);
5262 if (cro.weakIvarLayout != 0)
5263 outs() << " + " << format("0x%" PRIx64, cro.weakIvarLayout);
5264 } else
5265 outs() << format("0x%" PRIx64, cro.weakIvarLayout);
5266 outs() << "\n";
5267 print_layout_map64(cro.weakIvarLayout + n_value, info);
5269 outs() << " baseProperties ";
5270 sym_name =
5271 get_symbol_64(offset + offsetof(struct class_ro64_t, baseProperties), S,
5272 info, n_value, cro.baseProperties);
5273 if (n_value != 0) {
5274 if (info->verbose && sym_name != nullptr)
5275 outs() << sym_name;
5276 else
5277 outs() << format("0x%" PRIx64, n_value);
5278 if (cro.baseProperties != 0)
5279 outs() << " + " << format("0x%" PRIx64, cro.baseProperties);
5280 } else
5281 outs() << format("0x%" PRIx64, cro.baseProperties);
5282 outs() << "\n";
5283 if (cro.baseProperties + n_value != 0)
5284 print_objc_property_list64(cro.baseProperties + n_value, info);
5286 is_meta_class = (cro.flags & RO_META) != 0;
5287 return true;
5290 static bool print_class_ro32_t(uint32_t p, struct DisassembleInfo *info,
5291 bool &is_meta_class) {
5292 struct class_ro32_t cro;
5293 const char *r;
5294 uint32_t offset, xoffset, left;
5295 SectionRef S, xS;
5296 const char *name;
5298 r = get_pointer_32(p, offset, left, S, info);
5299 if (r == nullptr)
5300 return false;
5301 memset(&cro, '\0', sizeof(struct class_ro32_t));
5302 if (left < sizeof(struct class_ro32_t)) {
5303 memcpy(&cro, r, left);
5304 outs() << " (class_ro_t entends past the end of the section)\n";
5305 } else
5306 memcpy(&cro, r, sizeof(struct class_ro32_t));
5307 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5308 swapStruct(cro);
5309 outs() << " flags " << format("0x%" PRIx32, cro.flags);
5310 if (cro.flags & RO_META)
5311 outs() << " RO_META";
5312 if (cro.flags & RO_ROOT)
5313 outs() << " RO_ROOT";
5314 if (cro.flags & RO_HAS_CXX_STRUCTORS)
5315 outs() << " RO_HAS_CXX_STRUCTORS";
5316 outs() << "\n";
5317 outs() << " instanceStart " << cro.instanceStart << "\n";
5318 outs() << " instanceSize " << cro.instanceSize << "\n";
5319 outs() << " ivarLayout " << format("0x%" PRIx32, cro.ivarLayout)
5320 << "\n";
5321 print_layout_map32(cro.ivarLayout, info);
5323 outs() << " name " << format("0x%" PRIx32, cro.name);
5324 name = get_pointer_32(cro.name, xoffset, left, xS, info);
5325 if (name != nullptr)
5326 outs() << format(" %.*s", left, name);
5327 outs() << "\n";
5329 outs() << " baseMethods "
5330 << format("0x%" PRIx32, cro.baseMethods)
5331 << " (struct method_list_t *)\n";
5332 if (cro.baseMethods != 0)
5333 print_method_list32_t(cro.baseMethods, info, "");
5335 outs() << " baseProtocols "
5336 << format("0x%" PRIx32, cro.baseProtocols) << "\n";
5337 if (cro.baseProtocols != 0)
5338 print_protocol_list32_t(cro.baseProtocols, info);
5339 outs() << " ivars " << format("0x%" PRIx32, cro.ivars)
5340 << "\n";
5341 if (cro.ivars != 0)
5342 print_ivar_list32_t(cro.ivars, info);
5343 outs() << " weakIvarLayout "
5344 << format("0x%" PRIx32, cro.weakIvarLayout) << "\n";
5345 print_layout_map32(cro.weakIvarLayout, info);
5346 outs() << " baseProperties "
5347 << format("0x%" PRIx32, cro.baseProperties) << "\n";
5348 if (cro.baseProperties != 0)
5349 print_objc_property_list32(cro.baseProperties, info);
5350 is_meta_class = (cro.flags & RO_META) != 0;
5351 return true;
5354 static void print_class64_t(uint64_t p, struct DisassembleInfo *info) {
5355 struct class64_t c;
5356 const char *r;
5357 uint32_t offset, left;
5358 SectionRef S;
5359 const char *name;
5360 uint64_t isa_n_value, n_value;
5362 r = get_pointer_64(p, offset, left, S, info);
5363 if (r == nullptr || left < sizeof(struct class64_t))
5364 return;
5365 memcpy(&c, r, sizeof(struct class64_t));
5366 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5367 swapStruct(c);
5369 outs() << " isa " << format("0x%" PRIx64, c.isa);
5370 name = get_symbol_64(offset + offsetof(struct class64_t, isa), S, info,
5371 isa_n_value, c.isa);
5372 if (name != nullptr)
5373 outs() << " " << name;
5374 outs() << "\n";
5376 outs() << " superclass " << format("0x%" PRIx64, c.superclass);
5377 name = get_symbol_64(offset + offsetof(struct class64_t, superclass), S, info,
5378 n_value, c.superclass);
5379 if (name != nullptr)
5380 outs() << " " << name;
5381 else {
5382 name = get_dyld_bind_info_symbolname(S.getAddress() +
5383 offset + offsetof(struct class64_t, superclass), info);
5384 if (name != nullptr)
5385 outs() << " " << name;
5387 outs() << "\n";
5389 outs() << " cache " << format("0x%" PRIx64, c.cache);
5390 name = get_symbol_64(offset + offsetof(struct class64_t, cache), S, info,
5391 n_value, c.cache);
5392 if (name != nullptr)
5393 outs() << " " << name;
5394 outs() << "\n";
5396 outs() << " vtable " << format("0x%" PRIx64, c.vtable);
5397 name = get_symbol_64(offset + offsetof(struct class64_t, vtable), S, info,
5398 n_value, c.vtable);
5399 if (name != nullptr)
5400 outs() << " " << name;
5401 outs() << "\n";
5403 name = get_symbol_64(offset + offsetof(struct class64_t, data), S, info,
5404 n_value, c.data);
5405 outs() << " data ";
5406 if (n_value != 0) {
5407 if (info->verbose && name != nullptr)
5408 outs() << name;
5409 else
5410 outs() << format("0x%" PRIx64, n_value);
5411 if (c.data != 0)
5412 outs() << " + " << format("0x%" PRIx64, c.data);
5413 } else
5414 outs() << format("0x%" PRIx64, c.data);
5415 outs() << " (struct class_ro_t *)";
5417 // This is a Swift class if some of the low bits of the pointer are set.
5418 if ((c.data + n_value) & 0x7)
5419 outs() << " Swift class";
5420 outs() << "\n";
5421 bool is_meta_class;
5422 if (!print_class_ro64_t((c.data + n_value) & ~0x7, info, is_meta_class))
5423 return;
5425 if (!is_meta_class &&
5426 c.isa + isa_n_value != p &&
5427 c.isa + isa_n_value != 0 &&
5428 info->depth < 100) {
5429 info->depth++;
5430 outs() << "Meta Class\n";
5431 print_class64_t(c.isa + isa_n_value, info);
5435 static void print_class32_t(uint32_t p, struct DisassembleInfo *info) {
5436 struct class32_t c;
5437 const char *r;
5438 uint32_t offset, left;
5439 SectionRef S;
5440 const char *name;
5442 r = get_pointer_32(p, offset, left, S, info);
5443 if (r == nullptr)
5444 return;
5445 memset(&c, '\0', sizeof(struct class32_t));
5446 if (left < sizeof(struct class32_t)) {
5447 memcpy(&c, r, left);
5448 outs() << " (class_t entends past the end of the section)\n";
5449 } else
5450 memcpy(&c, r, sizeof(struct class32_t));
5451 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5452 swapStruct(c);
5454 outs() << " isa " << format("0x%" PRIx32, c.isa);
5455 name =
5456 get_symbol_32(offset + offsetof(struct class32_t, isa), S, info, c.isa);
5457 if (name != nullptr)
5458 outs() << " " << name;
5459 outs() << "\n";
5461 outs() << " superclass " << format("0x%" PRIx32, c.superclass);
5462 name = get_symbol_32(offset + offsetof(struct class32_t, superclass), S, info,
5463 c.superclass);
5464 if (name != nullptr)
5465 outs() << " " << name;
5466 outs() << "\n";
5468 outs() << " cache " << format("0x%" PRIx32, c.cache);
5469 name = get_symbol_32(offset + offsetof(struct class32_t, cache), S, info,
5470 c.cache);
5471 if (name != nullptr)
5472 outs() << " " << name;
5473 outs() << "\n";
5475 outs() << " vtable " << format("0x%" PRIx32, c.vtable);
5476 name = get_symbol_32(offset + offsetof(struct class32_t, vtable), S, info,
5477 c.vtable);
5478 if (name != nullptr)
5479 outs() << " " << name;
5480 outs() << "\n";
5482 name =
5483 get_symbol_32(offset + offsetof(struct class32_t, data), S, info, c.data);
5484 outs() << " data " << format("0x%" PRIx32, c.data)
5485 << " (struct class_ro_t *)";
5487 // This is a Swift class if some of the low bits of the pointer are set.
5488 if (c.data & 0x3)
5489 outs() << " Swift class";
5490 outs() << "\n";
5491 bool is_meta_class;
5492 if (!print_class_ro32_t(c.data & ~0x3, info, is_meta_class))
5493 return;
5495 if (!is_meta_class) {
5496 outs() << "Meta Class\n";
5497 print_class32_t(c.isa, info);
5501 static void print_objc_class_t(struct objc_class_t *objc_class,
5502 struct DisassembleInfo *info) {
5503 uint32_t offset, left, xleft;
5504 const char *name, *p, *ivar_list;
5505 SectionRef S;
5506 int32_t i;
5507 struct objc_ivar_list_t objc_ivar_list;
5508 struct objc_ivar_t ivar;
5510 outs() << "\t\t isa " << format("0x%08" PRIx32, objc_class->isa);
5511 if (info->verbose && CLS_GETINFO(objc_class, CLS_META)) {
5512 name = get_pointer_32(objc_class->isa, offset, left, S, info, true);
5513 if (name != nullptr)
5514 outs() << format(" %.*s", left, name);
5515 else
5516 outs() << " (not in an __OBJC section)";
5518 outs() << "\n";
5520 outs() << "\t super_class "
5521 << format("0x%08" PRIx32, objc_class->super_class);
5522 if (info->verbose) {
5523 name = get_pointer_32(objc_class->super_class, offset, left, S, info, true);
5524 if (name != nullptr)
5525 outs() << format(" %.*s", left, name);
5526 else
5527 outs() << " (not in an __OBJC section)";
5529 outs() << "\n";
5531 outs() << "\t\t name " << format("0x%08" PRIx32, objc_class->name);
5532 if (info->verbose) {
5533 name = get_pointer_32(objc_class->name, offset, left, S, info, true);
5534 if (name != nullptr)
5535 outs() << format(" %.*s", left, name);
5536 else
5537 outs() << " (not in an __OBJC section)";
5539 outs() << "\n";
5541 outs() << "\t\t version " << format("0x%08" PRIx32, objc_class->version)
5542 << "\n";
5544 outs() << "\t\t info " << format("0x%08" PRIx32, objc_class->info);
5545 if (info->verbose) {
5546 if (CLS_GETINFO(objc_class, CLS_CLASS))
5547 outs() << " CLS_CLASS";
5548 else if (CLS_GETINFO(objc_class, CLS_META))
5549 outs() << " CLS_META";
5551 outs() << "\n";
5553 outs() << "\t instance_size "
5554 << format("0x%08" PRIx32, objc_class->instance_size) << "\n";
5556 p = get_pointer_32(objc_class->ivars, offset, left, S, info, true);
5557 outs() << "\t\t ivars " << format("0x%08" PRIx32, objc_class->ivars);
5558 if (p != nullptr) {
5559 if (left > sizeof(struct objc_ivar_list_t)) {
5560 outs() << "\n";
5561 memcpy(&objc_ivar_list, p, sizeof(struct objc_ivar_list_t));
5562 } else {
5563 outs() << " (entends past the end of the section)\n";
5564 memset(&objc_ivar_list, '\0', sizeof(struct objc_ivar_list_t));
5565 memcpy(&objc_ivar_list, p, left);
5567 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5568 swapStruct(objc_ivar_list);
5569 outs() << "\t\t ivar_count " << objc_ivar_list.ivar_count << "\n";
5570 ivar_list = p + sizeof(struct objc_ivar_list_t);
5571 for (i = 0; i < objc_ivar_list.ivar_count; i++) {
5572 if ((i + 1) * sizeof(struct objc_ivar_t) > left) {
5573 outs() << "\t\t remaining ivar's extend past the of the section\n";
5574 break;
5576 memcpy(&ivar, ivar_list + i * sizeof(struct objc_ivar_t),
5577 sizeof(struct objc_ivar_t));
5578 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5579 swapStruct(ivar);
5581 outs() << "\t\t\tivar_name " << format("0x%08" PRIx32, ivar.ivar_name);
5582 if (info->verbose) {
5583 name = get_pointer_32(ivar.ivar_name, offset, xleft, S, info, true);
5584 if (name != nullptr)
5585 outs() << format(" %.*s", xleft, name);
5586 else
5587 outs() << " (not in an __OBJC section)";
5589 outs() << "\n";
5591 outs() << "\t\t\tivar_type " << format("0x%08" PRIx32, ivar.ivar_type);
5592 if (info->verbose) {
5593 name = get_pointer_32(ivar.ivar_type, offset, xleft, S, info, true);
5594 if (name != nullptr)
5595 outs() << format(" %.*s", xleft, name);
5596 else
5597 outs() << " (not in an __OBJC section)";
5599 outs() << "\n";
5601 outs() << "\t\t ivar_offset "
5602 << format("0x%08" PRIx32, ivar.ivar_offset) << "\n";
5604 } else {
5605 outs() << " (not in an __OBJC section)\n";
5608 outs() << "\t\t methods " << format("0x%08" PRIx32, objc_class->methodLists);
5609 if (print_method_list(objc_class->methodLists, info))
5610 outs() << " (not in an __OBJC section)\n";
5612 outs() << "\t\t cache " << format("0x%08" PRIx32, objc_class->cache)
5613 << "\n";
5615 outs() << "\t\tprotocols " << format("0x%08" PRIx32, objc_class->protocols);
5616 if (print_protocol_list(objc_class->protocols, 16, info))
5617 outs() << " (not in an __OBJC section)\n";
5620 static void print_objc_objc_category_t(struct objc_category_t *objc_category,
5621 struct DisassembleInfo *info) {
5622 uint32_t offset, left;
5623 const char *name;
5624 SectionRef S;
5626 outs() << "\t category name "
5627 << format("0x%08" PRIx32, objc_category->category_name);
5628 if (info->verbose) {
5629 name = get_pointer_32(objc_category->category_name, offset, left, S, info,
5630 true);
5631 if (name != nullptr)
5632 outs() << format(" %.*s", left, name);
5633 else
5634 outs() << " (not in an __OBJC section)";
5636 outs() << "\n";
5638 outs() << "\t\t class name "
5639 << format("0x%08" PRIx32, objc_category->class_name);
5640 if (info->verbose) {
5641 name =
5642 get_pointer_32(objc_category->class_name, offset, left, S, info, true);
5643 if (name != nullptr)
5644 outs() << format(" %.*s", left, name);
5645 else
5646 outs() << " (not in an __OBJC section)";
5648 outs() << "\n";
5650 outs() << "\t instance methods "
5651 << format("0x%08" PRIx32, objc_category->instance_methods);
5652 if (print_method_list(objc_category->instance_methods, info))
5653 outs() << " (not in an __OBJC section)\n";
5655 outs() << "\t class methods "
5656 << format("0x%08" PRIx32, objc_category->class_methods);
5657 if (print_method_list(objc_category->class_methods, info))
5658 outs() << " (not in an __OBJC section)\n";
5661 static void print_category64_t(uint64_t p, struct DisassembleInfo *info) {
5662 struct category64_t c;
5663 const char *r;
5664 uint32_t offset, xoffset, left;
5665 SectionRef S, xS;
5666 const char *name, *sym_name;
5667 uint64_t n_value;
5669 r = get_pointer_64(p, offset, left, S, info);
5670 if (r == nullptr)
5671 return;
5672 memset(&c, '\0', sizeof(struct category64_t));
5673 if (left < sizeof(struct category64_t)) {
5674 memcpy(&c, r, left);
5675 outs() << " (category_t entends past the end of the section)\n";
5676 } else
5677 memcpy(&c, r, sizeof(struct category64_t));
5678 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5679 swapStruct(c);
5681 outs() << " name ";
5682 sym_name = get_symbol_64(offset + offsetof(struct category64_t, name), S,
5683 info, n_value, c.name);
5684 if (n_value != 0) {
5685 if (info->verbose && sym_name != nullptr)
5686 outs() << sym_name;
5687 else
5688 outs() << format("0x%" PRIx64, n_value);
5689 if (c.name != 0)
5690 outs() << " + " << format("0x%" PRIx64, c.name);
5691 } else
5692 outs() << format("0x%" PRIx64, c.name);
5693 name = get_pointer_64(c.name + n_value, xoffset, left, xS, info);
5694 if (name != nullptr)
5695 outs() << format(" %.*s", left, name);
5696 outs() << "\n";
5698 outs() << " cls ";
5699 sym_name = get_symbol_64(offset + offsetof(struct category64_t, cls), S, info,
5700 n_value, c.cls);
5701 if (n_value != 0) {
5702 if (info->verbose && sym_name != nullptr)
5703 outs() << sym_name;
5704 else
5705 outs() << format("0x%" PRIx64, n_value);
5706 if (c.cls != 0)
5707 outs() << " + " << format("0x%" PRIx64, c.cls);
5708 } else
5709 outs() << format("0x%" PRIx64, c.cls);
5710 outs() << "\n";
5711 if (c.cls + n_value != 0)
5712 print_class64_t(c.cls + n_value, info);
5714 outs() << " instanceMethods ";
5715 sym_name =
5716 get_symbol_64(offset + offsetof(struct category64_t, instanceMethods), S,
5717 info, n_value, c.instanceMethods);
5718 if (n_value != 0) {
5719 if (info->verbose && sym_name != nullptr)
5720 outs() << sym_name;
5721 else
5722 outs() << format("0x%" PRIx64, n_value);
5723 if (c.instanceMethods != 0)
5724 outs() << " + " << format("0x%" PRIx64, c.instanceMethods);
5725 } else
5726 outs() << format("0x%" PRIx64, c.instanceMethods);
5727 outs() << "\n";
5728 if (c.instanceMethods + n_value != 0)
5729 print_method_list64_t(c.instanceMethods + n_value, info, "");
5731 outs() << " classMethods ";
5732 sym_name = get_symbol_64(offset + offsetof(struct category64_t, classMethods),
5733 S, info, n_value, c.classMethods);
5734 if (n_value != 0) {
5735 if (info->verbose && sym_name != nullptr)
5736 outs() << sym_name;
5737 else
5738 outs() << format("0x%" PRIx64, n_value);
5739 if (c.classMethods != 0)
5740 outs() << " + " << format("0x%" PRIx64, c.classMethods);
5741 } else
5742 outs() << format("0x%" PRIx64, c.classMethods);
5743 outs() << "\n";
5744 if (c.classMethods + n_value != 0)
5745 print_method_list64_t(c.classMethods + n_value, info, "");
5747 outs() << " protocols ";
5748 sym_name = get_symbol_64(offset + offsetof(struct category64_t, protocols), S,
5749 info, n_value, c.protocols);
5750 if (n_value != 0) {
5751 if (info->verbose && sym_name != nullptr)
5752 outs() << sym_name;
5753 else
5754 outs() << format("0x%" PRIx64, n_value);
5755 if (c.protocols != 0)
5756 outs() << " + " << format("0x%" PRIx64, c.protocols);
5757 } else
5758 outs() << format("0x%" PRIx64, c.protocols);
5759 outs() << "\n";
5760 if (c.protocols + n_value != 0)
5761 print_protocol_list64_t(c.protocols + n_value, info);
5763 outs() << "instanceProperties ";
5764 sym_name =
5765 get_symbol_64(offset + offsetof(struct category64_t, instanceProperties),
5766 S, info, n_value, c.instanceProperties);
5767 if (n_value != 0) {
5768 if (info->verbose && sym_name != nullptr)
5769 outs() << sym_name;
5770 else
5771 outs() << format("0x%" PRIx64, n_value);
5772 if (c.instanceProperties != 0)
5773 outs() << " + " << format("0x%" PRIx64, c.instanceProperties);
5774 } else
5775 outs() << format("0x%" PRIx64, c.instanceProperties);
5776 outs() << "\n";
5777 if (c.instanceProperties + n_value != 0)
5778 print_objc_property_list64(c.instanceProperties + n_value, info);
5781 static void print_category32_t(uint32_t p, struct DisassembleInfo *info) {
5782 struct category32_t c;
5783 const char *r;
5784 uint32_t offset, left;
5785 SectionRef S, xS;
5786 const char *name;
5788 r = get_pointer_32(p, offset, left, S, info);
5789 if (r == nullptr)
5790 return;
5791 memset(&c, '\0', sizeof(struct category32_t));
5792 if (left < sizeof(struct category32_t)) {
5793 memcpy(&c, r, left);
5794 outs() << " (category_t entends past the end of the section)\n";
5795 } else
5796 memcpy(&c, r, sizeof(struct category32_t));
5797 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5798 swapStruct(c);
5800 outs() << " name " << format("0x%" PRIx32, c.name);
5801 name = get_symbol_32(offset + offsetof(struct category32_t, name), S, info,
5802 c.name);
5803 if (name)
5804 outs() << " " << name;
5805 outs() << "\n";
5807 outs() << " cls " << format("0x%" PRIx32, c.cls) << "\n";
5808 if (c.cls != 0)
5809 print_class32_t(c.cls, info);
5810 outs() << " instanceMethods " << format("0x%" PRIx32, c.instanceMethods)
5811 << "\n";
5812 if (c.instanceMethods != 0)
5813 print_method_list32_t(c.instanceMethods, info, "");
5814 outs() << " classMethods " << format("0x%" PRIx32, c.classMethods)
5815 << "\n";
5816 if (c.classMethods != 0)
5817 print_method_list32_t(c.classMethods, info, "");
5818 outs() << " protocols " << format("0x%" PRIx32, c.protocols) << "\n";
5819 if (c.protocols != 0)
5820 print_protocol_list32_t(c.protocols, info);
5821 outs() << "instanceProperties " << format("0x%" PRIx32, c.instanceProperties)
5822 << "\n";
5823 if (c.instanceProperties != 0)
5824 print_objc_property_list32(c.instanceProperties, info);
5827 static void print_message_refs64(SectionRef S, struct DisassembleInfo *info) {
5828 uint32_t i, left, offset, xoffset;
5829 uint64_t p, n_value;
5830 struct message_ref64 mr;
5831 const char *name, *sym_name;
5832 const char *r;
5833 SectionRef xS;
5835 if (S == SectionRef())
5836 return;
5838 StringRef SectName;
5839 Expected<StringRef> SecNameOrErr = S.getName();
5840 if (SecNameOrErr)
5841 SectName = *SecNameOrErr;
5842 else
5843 consumeError(SecNameOrErr.takeError());
5845 DataRefImpl Ref = S.getRawDataRefImpl();
5846 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5847 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5848 offset = 0;
5849 for (i = 0; i < S.getSize(); i += sizeof(struct message_ref64)) {
5850 p = S.getAddress() + i;
5851 r = get_pointer_64(p, offset, left, S, info);
5852 if (r == nullptr)
5853 return;
5854 memset(&mr, '\0', sizeof(struct message_ref64));
5855 if (left < sizeof(struct message_ref64)) {
5856 memcpy(&mr, r, left);
5857 outs() << " (message_ref entends past the end of the section)\n";
5858 } else
5859 memcpy(&mr, r, sizeof(struct message_ref64));
5860 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5861 swapStruct(mr);
5863 outs() << " imp ";
5864 name = get_symbol_64(offset + offsetof(struct message_ref64, imp), S, info,
5865 n_value, mr.imp);
5866 if (n_value != 0) {
5867 outs() << format("0x%" PRIx64, n_value) << " ";
5868 if (mr.imp != 0)
5869 outs() << "+ " << format("0x%" PRIx64, mr.imp) << " ";
5870 } else
5871 outs() << format("0x%" PRIx64, mr.imp) << " ";
5872 if (name != nullptr)
5873 outs() << " " << name;
5874 outs() << "\n";
5876 outs() << " sel ";
5877 sym_name = get_symbol_64(offset + offsetof(struct message_ref64, sel), S,
5878 info, n_value, mr.sel);
5879 if (n_value != 0) {
5880 if (info->verbose && sym_name != nullptr)
5881 outs() << sym_name;
5882 else
5883 outs() << format("0x%" PRIx64, n_value);
5884 if (mr.sel != 0)
5885 outs() << " + " << format("0x%" PRIx64, mr.sel);
5886 } else
5887 outs() << format("0x%" PRIx64, mr.sel);
5888 name = get_pointer_64(mr.sel + n_value, xoffset, left, xS, info);
5889 if (name != nullptr)
5890 outs() << format(" %.*s", left, name);
5891 outs() << "\n";
5893 offset += sizeof(struct message_ref64);
5897 static void print_message_refs32(SectionRef S, struct DisassembleInfo *info) {
5898 uint32_t i, left, offset, xoffset, p;
5899 struct message_ref32 mr;
5900 const char *name, *r;
5901 SectionRef xS;
5903 if (S == SectionRef())
5904 return;
5906 StringRef SectName;
5907 Expected<StringRef> SecNameOrErr = S.getName();
5908 if (SecNameOrErr)
5909 SectName = *SecNameOrErr;
5910 else
5911 consumeError(SecNameOrErr.takeError());
5913 DataRefImpl Ref = S.getRawDataRefImpl();
5914 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5915 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5916 offset = 0;
5917 for (i = 0; i < S.getSize(); i += sizeof(struct message_ref64)) {
5918 p = S.getAddress() + i;
5919 r = get_pointer_32(p, offset, left, S, info);
5920 if (r == nullptr)
5921 return;
5922 memset(&mr, '\0', sizeof(struct message_ref32));
5923 if (left < sizeof(struct message_ref32)) {
5924 memcpy(&mr, r, left);
5925 outs() << " (message_ref entends past the end of the section)\n";
5926 } else
5927 memcpy(&mr, r, sizeof(struct message_ref32));
5928 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5929 swapStruct(mr);
5931 outs() << " imp " << format("0x%" PRIx32, mr.imp);
5932 name = get_symbol_32(offset + offsetof(struct message_ref32, imp), S, info,
5933 mr.imp);
5934 if (name != nullptr)
5935 outs() << " " << name;
5936 outs() << "\n";
5938 outs() << " sel " << format("0x%" PRIx32, mr.sel);
5939 name = get_pointer_32(mr.sel, xoffset, left, xS, info);
5940 if (name != nullptr)
5941 outs() << " " << name;
5942 outs() << "\n";
5944 offset += sizeof(struct message_ref32);
5948 static void print_image_info64(SectionRef S, struct DisassembleInfo *info) {
5949 uint32_t left, offset, swift_version;
5950 uint64_t p;
5951 struct objc_image_info64 o;
5952 const char *r;
5954 if (S == SectionRef())
5955 return;
5957 StringRef SectName;
5958 Expected<StringRef> SecNameOrErr = S.getName();
5959 if (SecNameOrErr)
5960 SectName = *SecNameOrErr;
5961 else
5962 consumeError(SecNameOrErr.takeError());
5964 DataRefImpl Ref = S.getRawDataRefImpl();
5965 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5966 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5967 p = S.getAddress();
5968 r = get_pointer_64(p, offset, left, S, info);
5969 if (r == nullptr)
5970 return;
5971 memset(&o, '\0', sizeof(struct objc_image_info64));
5972 if (left < sizeof(struct objc_image_info64)) {
5973 memcpy(&o, r, left);
5974 outs() << " (objc_image_info entends past the end of the section)\n";
5975 } else
5976 memcpy(&o, r, sizeof(struct objc_image_info64));
5977 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5978 swapStruct(o);
5979 outs() << " version " << o.version << "\n";
5980 outs() << " flags " << format("0x%" PRIx32, o.flags);
5981 if (o.flags & OBJC_IMAGE_IS_REPLACEMENT)
5982 outs() << " OBJC_IMAGE_IS_REPLACEMENT";
5983 if (o.flags & OBJC_IMAGE_SUPPORTS_GC)
5984 outs() << " OBJC_IMAGE_SUPPORTS_GC";
5985 if (o.flags & OBJC_IMAGE_IS_SIMULATED)
5986 outs() << " OBJC_IMAGE_IS_SIMULATED";
5987 if (o.flags & OBJC_IMAGE_HAS_CATEGORY_CLASS_PROPERTIES)
5988 outs() << " OBJC_IMAGE_HAS_CATEGORY_CLASS_PROPERTIES";
5989 swift_version = (o.flags >> 8) & 0xff;
5990 if (swift_version != 0) {
5991 if (swift_version == 1)
5992 outs() << " Swift 1.0";
5993 else if (swift_version == 2)
5994 outs() << " Swift 1.1";
5995 else if(swift_version == 3)
5996 outs() << " Swift 2.0";
5997 else if(swift_version == 4)
5998 outs() << " Swift 3.0";
5999 else if(swift_version == 5)
6000 outs() << " Swift 4.0";
6001 else if(swift_version == 6)
6002 outs() << " Swift 4.1/Swift 4.2";
6003 else if(swift_version == 7)
6004 outs() << " Swift 5 or later";
6005 else
6006 outs() << " unknown future Swift version (" << swift_version << ")";
6008 outs() << "\n";
6011 static void print_image_info32(SectionRef S, struct DisassembleInfo *info) {
6012 uint32_t left, offset, swift_version, p;
6013 struct objc_image_info32 o;
6014 const char *r;
6016 if (S == SectionRef())
6017 return;
6019 StringRef SectName;
6020 Expected<StringRef> SecNameOrErr = S.getName();
6021 if (SecNameOrErr)
6022 SectName = *SecNameOrErr;
6023 else
6024 consumeError(SecNameOrErr.takeError());
6026 DataRefImpl Ref = S.getRawDataRefImpl();
6027 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
6028 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
6029 p = S.getAddress();
6030 r = get_pointer_32(p, offset, left, S, info);
6031 if (r == nullptr)
6032 return;
6033 memset(&o, '\0', sizeof(struct objc_image_info32));
6034 if (left < sizeof(struct objc_image_info32)) {
6035 memcpy(&o, r, left);
6036 outs() << " (objc_image_info entends past the end of the section)\n";
6037 } else
6038 memcpy(&o, r, sizeof(struct objc_image_info32));
6039 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
6040 swapStruct(o);
6041 outs() << " version " << o.version << "\n";
6042 outs() << " flags " << format("0x%" PRIx32, o.flags);
6043 if (o.flags & OBJC_IMAGE_IS_REPLACEMENT)
6044 outs() << " OBJC_IMAGE_IS_REPLACEMENT";
6045 if (o.flags & OBJC_IMAGE_SUPPORTS_GC)
6046 outs() << " OBJC_IMAGE_SUPPORTS_GC";
6047 swift_version = (o.flags >> 8) & 0xff;
6048 if (swift_version != 0) {
6049 if (swift_version == 1)
6050 outs() << " Swift 1.0";
6051 else if (swift_version == 2)
6052 outs() << " Swift 1.1";
6053 else if(swift_version == 3)
6054 outs() << " Swift 2.0";
6055 else if(swift_version == 4)
6056 outs() << " Swift 3.0";
6057 else if(swift_version == 5)
6058 outs() << " Swift 4.0";
6059 else if(swift_version == 6)
6060 outs() << " Swift 4.1/Swift 4.2";
6061 else if(swift_version == 7)
6062 outs() << " Swift 5 or later";
6063 else
6064 outs() << " unknown future Swift version (" << swift_version << ")";
6066 outs() << "\n";
6069 static void print_image_info(SectionRef S, struct DisassembleInfo *info) {
6070 uint32_t left, offset, p;
6071 struct imageInfo_t o;
6072 const char *r;
6074 StringRef SectName;
6075 Expected<StringRef> SecNameOrErr = S.getName();
6076 if (SecNameOrErr)
6077 SectName = *SecNameOrErr;
6078 else
6079 consumeError(SecNameOrErr.takeError());
6081 DataRefImpl Ref = S.getRawDataRefImpl();
6082 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
6083 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
6084 p = S.getAddress();
6085 r = get_pointer_32(p, offset, left, S, info);
6086 if (r == nullptr)
6087 return;
6088 memset(&o, '\0', sizeof(struct imageInfo_t));
6089 if (left < sizeof(struct imageInfo_t)) {
6090 memcpy(&o, r, left);
6091 outs() << " (imageInfo entends past the end of the section)\n";
6092 } else
6093 memcpy(&o, r, sizeof(struct imageInfo_t));
6094 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
6095 swapStruct(o);
6096 outs() << " version " << o.version << "\n";
6097 outs() << " flags " << format("0x%" PRIx32, o.flags);
6098 if (o.flags & 0x1)
6099 outs() << " F&C";
6100 if (o.flags & 0x2)
6101 outs() << " GC";
6102 if (o.flags & 0x4)
6103 outs() << " GC-only";
6104 else
6105 outs() << " RR";
6106 outs() << "\n";
6109 static void printObjc2_64bit_MetaData(MachOObjectFile *O, bool verbose) {
6110 SymbolAddressMap AddrMap;
6111 if (verbose)
6112 CreateSymbolAddressMap(O, &AddrMap);
6114 std::vector<SectionRef> Sections;
6115 for (const SectionRef &Section : O->sections())
6116 Sections.push_back(Section);
6118 struct DisassembleInfo info(O, &AddrMap, &Sections, verbose);
6120 SectionRef CL = get_section(O, "__OBJC2", "__class_list");
6121 if (CL == SectionRef())
6122 CL = get_section(O, "__DATA", "__objc_classlist");
6123 if (CL == SectionRef())
6124 CL = get_section(O, "__DATA_CONST", "__objc_classlist");
6125 if (CL == SectionRef())
6126 CL = get_section(O, "__DATA_DIRTY", "__objc_classlist");
6127 info.S = CL;
6128 walk_pointer_list_64("class", CL, O, &info, print_class64_t);
6130 SectionRef CR = get_section(O, "__OBJC2", "__class_refs");
6131 if (CR == SectionRef())
6132 CR = get_section(O, "__DATA", "__objc_classrefs");
6133 if (CR == SectionRef())
6134 CR = get_section(O, "__DATA_CONST", "__objc_classrefs");
6135 if (CR == SectionRef())
6136 CR = get_section(O, "__DATA_DIRTY", "__objc_classrefs");
6137 info.S = CR;
6138 walk_pointer_list_64("class refs", CR, O, &info, nullptr);
6140 SectionRef SR = get_section(O, "__OBJC2", "__super_refs");
6141 if (SR == SectionRef())
6142 SR = get_section(O, "__DATA", "__objc_superrefs");
6143 if (SR == SectionRef())
6144 SR = get_section(O, "__DATA_CONST", "__objc_superrefs");
6145 if (SR == SectionRef())
6146 SR = get_section(O, "__DATA_DIRTY", "__objc_superrefs");
6147 info.S = SR;
6148 walk_pointer_list_64("super refs", SR, O, &info, nullptr);
6150 SectionRef CA = get_section(O, "__OBJC2", "__category_list");
6151 if (CA == SectionRef())
6152 CA = get_section(O, "__DATA", "__objc_catlist");
6153 if (CA == SectionRef())
6154 CA = get_section(O, "__DATA_CONST", "__objc_catlist");
6155 if (CA == SectionRef())
6156 CA = get_section(O, "__DATA_DIRTY", "__objc_catlist");
6157 info.S = CA;
6158 walk_pointer_list_64("category", CA, O, &info, print_category64_t);
6160 SectionRef PL = get_section(O, "__OBJC2", "__protocol_list");
6161 if (PL == SectionRef())
6162 PL = get_section(O, "__DATA", "__objc_protolist");
6163 if (PL == SectionRef())
6164 PL = get_section(O, "__DATA_CONST", "__objc_protolist");
6165 if (PL == SectionRef())
6166 PL = get_section(O, "__DATA_DIRTY", "__objc_protolist");
6167 info.S = PL;
6168 walk_pointer_list_64("protocol", PL, O, &info, nullptr);
6170 SectionRef MR = get_section(O, "__OBJC2", "__message_refs");
6171 if (MR == SectionRef())
6172 MR = get_section(O, "__DATA", "__objc_msgrefs");
6173 if (MR == SectionRef())
6174 MR = get_section(O, "__DATA_CONST", "__objc_msgrefs");
6175 if (MR == SectionRef())
6176 MR = get_section(O, "__DATA_DIRTY", "__objc_msgrefs");
6177 info.S = MR;
6178 print_message_refs64(MR, &info);
6180 SectionRef II = get_section(O, "__OBJC2", "__image_info");
6181 if (II == SectionRef())
6182 II = get_section(O, "__DATA", "__objc_imageinfo");
6183 if (II == SectionRef())
6184 II = get_section(O, "__DATA_CONST", "__objc_imageinfo");
6185 if (II == SectionRef())
6186 II = get_section(O, "__DATA_DIRTY", "__objc_imageinfo");
6187 info.S = II;
6188 print_image_info64(II, &info);
6191 static void printObjc2_32bit_MetaData(MachOObjectFile *O, bool verbose) {
6192 SymbolAddressMap AddrMap;
6193 if (verbose)
6194 CreateSymbolAddressMap(O, &AddrMap);
6196 std::vector<SectionRef> Sections;
6197 for (const SectionRef &Section : O->sections())
6198 Sections.push_back(Section);
6200 struct DisassembleInfo info(O, &AddrMap, &Sections, verbose);
6202 SectionRef CL = get_section(O, "__OBJC2", "__class_list");
6203 if (CL == SectionRef())
6204 CL = get_section(O, "__DATA", "__objc_classlist");
6205 if (CL == SectionRef())
6206 CL = get_section(O, "__DATA_CONST", "__objc_classlist");
6207 if (CL == SectionRef())
6208 CL = get_section(O, "__DATA_DIRTY", "__objc_classlist");
6209 info.S = CL;
6210 walk_pointer_list_32("class", CL, O, &info, print_class32_t);
6212 SectionRef CR = get_section(O, "__OBJC2", "__class_refs");
6213 if (CR == SectionRef())
6214 CR = get_section(O, "__DATA", "__objc_classrefs");
6215 if (CR == SectionRef())
6216 CR = get_section(O, "__DATA_CONST", "__objc_classrefs");
6217 if (CR == SectionRef())
6218 CR = get_section(O, "__DATA_DIRTY", "__objc_classrefs");
6219 info.S = CR;
6220 walk_pointer_list_32("class refs", CR, O, &info, nullptr);
6222 SectionRef SR = get_section(O, "__OBJC2", "__super_refs");
6223 if (SR == SectionRef())
6224 SR = get_section(O, "__DATA", "__objc_superrefs");
6225 if (SR == SectionRef())
6226 SR = get_section(O, "__DATA_CONST", "__objc_superrefs");
6227 if (SR == SectionRef())
6228 SR = get_section(O, "__DATA_DIRTY", "__objc_superrefs");
6229 info.S = SR;
6230 walk_pointer_list_32("super refs", SR, O, &info, nullptr);
6232 SectionRef CA = get_section(O, "__OBJC2", "__category_list");
6233 if (CA == SectionRef())
6234 CA = get_section(O, "__DATA", "__objc_catlist");
6235 if (CA == SectionRef())
6236 CA = get_section(O, "__DATA_CONST", "__objc_catlist");
6237 if (CA == SectionRef())
6238 CA = get_section(O, "__DATA_DIRTY", "__objc_catlist");
6239 info.S = CA;
6240 walk_pointer_list_32("category", CA, O, &info, print_category32_t);
6242 SectionRef PL = get_section(O, "__OBJC2", "__protocol_list");
6243 if (PL == SectionRef())
6244 PL = get_section(O, "__DATA", "__objc_protolist");
6245 if (PL == SectionRef())
6246 PL = get_section(O, "__DATA_CONST", "__objc_protolist");
6247 if (PL == SectionRef())
6248 PL = get_section(O, "__DATA_DIRTY", "__objc_protolist");
6249 info.S = PL;
6250 walk_pointer_list_32("protocol", PL, O, &info, nullptr);
6252 SectionRef MR = get_section(O, "__OBJC2", "__message_refs");
6253 if (MR == SectionRef())
6254 MR = get_section(O, "__DATA", "__objc_msgrefs");
6255 if (MR == SectionRef())
6256 MR = get_section(O, "__DATA_CONST", "__objc_msgrefs");
6257 if (MR == SectionRef())
6258 MR = get_section(O, "__DATA_DIRTY", "__objc_msgrefs");
6259 info.S = MR;
6260 print_message_refs32(MR, &info);
6262 SectionRef II = get_section(O, "__OBJC2", "__image_info");
6263 if (II == SectionRef())
6264 II = get_section(O, "__DATA", "__objc_imageinfo");
6265 if (II == SectionRef())
6266 II = get_section(O, "__DATA_CONST", "__objc_imageinfo");
6267 if (II == SectionRef())
6268 II = get_section(O, "__DATA_DIRTY", "__objc_imageinfo");
6269 info.S = II;
6270 print_image_info32(II, &info);
6273 static bool printObjc1_32bit_MetaData(MachOObjectFile *O, bool verbose) {
6274 uint32_t i, j, p, offset, xoffset, left, defs_left, def;
6275 const char *r, *name, *defs;
6276 struct objc_module_t module;
6277 SectionRef S, xS;
6278 struct objc_symtab_t symtab;
6279 struct objc_class_t objc_class;
6280 struct objc_category_t objc_category;
6282 outs() << "Objective-C segment\n";
6283 S = get_section(O, "__OBJC", "__module_info");
6284 if (S == SectionRef())
6285 return false;
6287 SymbolAddressMap AddrMap;
6288 if (verbose)
6289 CreateSymbolAddressMap(O, &AddrMap);
6291 std::vector<SectionRef> Sections;
6292 for (const SectionRef &Section : O->sections())
6293 Sections.push_back(Section);
6295 struct DisassembleInfo info(O, &AddrMap, &Sections, verbose);
6297 for (i = 0; i < S.getSize(); i += sizeof(struct objc_module_t)) {
6298 p = S.getAddress() + i;
6299 r = get_pointer_32(p, offset, left, S, &info, true);
6300 if (r == nullptr)
6301 return true;
6302 memset(&module, '\0', sizeof(struct objc_module_t));
6303 if (left < sizeof(struct objc_module_t)) {
6304 memcpy(&module, r, left);
6305 outs() << " (module extends past end of __module_info section)\n";
6306 } else
6307 memcpy(&module, r, sizeof(struct objc_module_t));
6308 if (O->isLittleEndian() != sys::IsLittleEndianHost)
6309 swapStruct(module);
6311 outs() << "Module " << format("0x%" PRIx32, p) << "\n";
6312 outs() << " version " << module.version << "\n";
6313 outs() << " size " << module.size << "\n";
6314 outs() << " name ";
6315 name = get_pointer_32(module.name, xoffset, left, xS, &info, true);
6316 if (name != nullptr)
6317 outs() << format("%.*s", left, name);
6318 else
6319 outs() << format("0x%08" PRIx32, module.name)
6320 << "(not in an __OBJC section)";
6321 outs() << "\n";
6323 r = get_pointer_32(module.symtab, xoffset, left, xS, &info, true);
6324 if (module.symtab == 0 || r == nullptr) {
6325 outs() << " symtab " << format("0x%08" PRIx32, module.symtab)
6326 << " (not in an __OBJC section)\n";
6327 continue;
6329 outs() << " symtab " << format("0x%08" PRIx32, module.symtab) << "\n";
6330 memset(&symtab, '\0', sizeof(struct objc_symtab_t));
6331 defs_left = 0;
6332 defs = nullptr;
6333 if (left < sizeof(struct objc_symtab_t)) {
6334 memcpy(&symtab, r, left);
6335 outs() << "\tsymtab extends past end of an __OBJC section)\n";
6336 } else {
6337 memcpy(&symtab, r, sizeof(struct objc_symtab_t));
6338 if (left > sizeof(struct objc_symtab_t)) {
6339 defs_left = left - sizeof(struct objc_symtab_t);
6340 defs = r + sizeof(struct objc_symtab_t);
6343 if (O->isLittleEndian() != sys::IsLittleEndianHost)
6344 swapStruct(symtab);
6346 outs() << "\tsel_ref_cnt " << symtab.sel_ref_cnt << "\n";
6347 r = get_pointer_32(symtab.refs, xoffset, left, xS, &info, true);
6348 outs() << "\trefs " << format("0x%08" PRIx32, symtab.refs);
6349 if (r == nullptr)
6350 outs() << " (not in an __OBJC section)";
6351 outs() << "\n";
6352 outs() << "\tcls_def_cnt " << symtab.cls_def_cnt << "\n";
6353 outs() << "\tcat_def_cnt " << symtab.cat_def_cnt << "\n";
6354 if (symtab.cls_def_cnt > 0)
6355 outs() << "\tClass Definitions\n";
6356 for (j = 0; j < symtab.cls_def_cnt; j++) {
6357 if ((j + 1) * sizeof(uint32_t) > defs_left) {
6358 outs() << "\t(remaining class defs entries entends past the end of the "
6359 << "section)\n";
6360 break;
6362 memcpy(&def, defs + j * sizeof(uint32_t), sizeof(uint32_t));
6363 if (O->isLittleEndian() != sys::IsLittleEndianHost)
6364 sys::swapByteOrder(def);
6366 r = get_pointer_32(def, xoffset, left, xS, &info, true);
6367 outs() << "\tdefs[" << j << "] " << format("0x%08" PRIx32, def);
6368 if (r != nullptr) {
6369 if (left > sizeof(struct objc_class_t)) {
6370 outs() << "\n";
6371 memcpy(&objc_class, r, sizeof(struct objc_class_t));
6372 } else {
6373 outs() << " (entends past the end of the section)\n";
6374 memset(&objc_class, '\0', sizeof(struct objc_class_t));
6375 memcpy(&objc_class, r, left);
6377 if (O->isLittleEndian() != sys::IsLittleEndianHost)
6378 swapStruct(objc_class);
6379 print_objc_class_t(&objc_class, &info);
6380 } else {
6381 outs() << "(not in an __OBJC section)\n";
6384 if (CLS_GETINFO(&objc_class, CLS_CLASS)) {
6385 outs() << "\tMeta Class";
6386 r = get_pointer_32(objc_class.isa, xoffset, left, xS, &info, true);
6387 if (r != nullptr) {
6388 if (left > sizeof(struct objc_class_t)) {
6389 outs() << "\n";
6390 memcpy(&objc_class, r, sizeof(struct objc_class_t));
6391 } else {
6392 outs() << " (entends past the end of the section)\n";
6393 memset(&objc_class, '\0', sizeof(struct objc_class_t));
6394 memcpy(&objc_class, r, left);
6396 if (O->isLittleEndian() != sys::IsLittleEndianHost)
6397 swapStruct(objc_class);
6398 print_objc_class_t(&objc_class, &info);
6399 } else {
6400 outs() << "(not in an __OBJC section)\n";
6404 if (symtab.cat_def_cnt > 0)
6405 outs() << "\tCategory Definitions\n";
6406 for (j = 0; j < symtab.cat_def_cnt; j++) {
6407 if ((j + symtab.cls_def_cnt + 1) * sizeof(uint32_t) > defs_left) {
6408 outs() << "\t(remaining category defs entries entends past the end of "
6409 << "the section)\n";
6410 break;
6412 memcpy(&def, defs + (j + symtab.cls_def_cnt) * sizeof(uint32_t),
6413 sizeof(uint32_t));
6414 if (O->isLittleEndian() != sys::IsLittleEndianHost)
6415 sys::swapByteOrder(def);
6417 r = get_pointer_32(def, xoffset, left, xS, &info, true);
6418 outs() << "\tdefs[" << j + symtab.cls_def_cnt << "] "
6419 << format("0x%08" PRIx32, def);
6420 if (r != nullptr) {
6421 if (left > sizeof(struct objc_category_t)) {
6422 outs() << "\n";
6423 memcpy(&objc_category, r, sizeof(struct objc_category_t));
6424 } else {
6425 outs() << " (entends past the end of the section)\n";
6426 memset(&objc_category, '\0', sizeof(struct objc_category_t));
6427 memcpy(&objc_category, r, left);
6429 if (O->isLittleEndian() != sys::IsLittleEndianHost)
6430 swapStruct(objc_category);
6431 print_objc_objc_category_t(&objc_category, &info);
6432 } else {
6433 outs() << "(not in an __OBJC section)\n";
6437 const SectionRef II = get_section(O, "__OBJC", "__image_info");
6438 if (II != SectionRef())
6439 print_image_info(II, &info);
6441 return true;
6444 static void DumpProtocolSection(MachOObjectFile *O, const char *sect,
6445 uint32_t size, uint32_t addr) {
6446 SymbolAddressMap AddrMap;
6447 CreateSymbolAddressMap(O, &AddrMap);
6449 std::vector<SectionRef> Sections;
6450 for (const SectionRef &Section : O->sections())
6451 Sections.push_back(Section);
6453 struct DisassembleInfo info(O, &AddrMap, &Sections, true);
6455 const char *p;
6456 struct objc_protocol_t protocol;
6457 uint32_t left, paddr;
6458 for (p = sect; p < sect + size; p += sizeof(struct objc_protocol_t)) {
6459 memset(&protocol, '\0', sizeof(struct objc_protocol_t));
6460 left = size - (p - sect);
6461 if (left < sizeof(struct objc_protocol_t)) {
6462 outs() << "Protocol extends past end of __protocol section\n";
6463 memcpy(&protocol, p, left);
6464 } else
6465 memcpy(&protocol, p, sizeof(struct objc_protocol_t));
6466 if (O->isLittleEndian() != sys::IsLittleEndianHost)
6467 swapStruct(protocol);
6468 paddr = addr + (p - sect);
6469 outs() << "Protocol " << format("0x%" PRIx32, paddr);
6470 if (print_protocol(paddr, 0, &info))
6471 outs() << "(not in an __OBJC section)\n";
6475 #ifdef HAVE_LIBXAR
6476 inline void swapStruct(struct xar_header &xar) {
6477 sys::swapByteOrder(xar.magic);
6478 sys::swapByteOrder(xar.size);
6479 sys::swapByteOrder(xar.version);
6480 sys::swapByteOrder(xar.toc_length_compressed);
6481 sys::swapByteOrder(xar.toc_length_uncompressed);
6482 sys::swapByteOrder(xar.cksum_alg);
6485 static void PrintModeVerbose(uint32_t mode) {
6486 switch(mode & S_IFMT){
6487 case S_IFDIR:
6488 outs() << "d";
6489 break;
6490 case S_IFCHR:
6491 outs() << "c";
6492 break;
6493 case S_IFBLK:
6494 outs() << "b";
6495 break;
6496 case S_IFREG:
6497 outs() << "-";
6498 break;
6499 case S_IFLNK:
6500 outs() << "l";
6501 break;
6502 case S_IFSOCK:
6503 outs() << "s";
6504 break;
6505 default:
6506 outs() << "?";
6507 break;
6510 /* owner permissions */
6511 if(mode & S_IREAD)
6512 outs() << "r";
6513 else
6514 outs() << "-";
6515 if(mode & S_IWRITE)
6516 outs() << "w";
6517 else
6518 outs() << "-";
6519 if(mode & S_ISUID)
6520 outs() << "s";
6521 else if(mode & S_IEXEC)
6522 outs() << "x";
6523 else
6524 outs() << "-";
6526 /* group permissions */
6527 if(mode & (S_IREAD >> 3))
6528 outs() << "r";
6529 else
6530 outs() << "-";
6531 if(mode & (S_IWRITE >> 3))
6532 outs() << "w";
6533 else
6534 outs() << "-";
6535 if(mode & S_ISGID)
6536 outs() << "s";
6537 else if(mode & (S_IEXEC >> 3))
6538 outs() << "x";
6539 else
6540 outs() << "-";
6542 /* other permissions */
6543 if(mode & (S_IREAD >> 6))
6544 outs() << "r";
6545 else
6546 outs() << "-";
6547 if(mode & (S_IWRITE >> 6))
6548 outs() << "w";
6549 else
6550 outs() << "-";
6551 if(mode & S_ISVTX)
6552 outs() << "t";
6553 else if(mode & (S_IEXEC >> 6))
6554 outs() << "x";
6555 else
6556 outs() << "-";
6559 static void PrintXarFilesSummary(const char *XarFilename, xar_t xar) {
6560 xar_file_t xf;
6561 const char *key, *type, *mode, *user, *group, *size, *mtime, *name, *m;
6562 char *endp;
6563 uint32_t mode_value;
6565 ScopedXarIter xi;
6566 if (!xi) {
6567 WithColor::error(errs(), "llvm-objdump")
6568 << "can't obtain an xar iterator for xar archive " << XarFilename
6569 << "\n";
6570 return;
6573 // Go through the xar's files.
6574 for (xf = xar_file_first(xar, xi); xf; xf = xar_file_next(xi)) {
6575 ScopedXarIter xp;
6576 if(!xp){
6577 WithColor::error(errs(), "llvm-objdump")
6578 << "can't obtain an xar iterator for xar archive " << XarFilename
6579 << "\n";
6580 return;
6582 type = nullptr;
6583 mode = nullptr;
6584 user = nullptr;
6585 group = nullptr;
6586 size = nullptr;
6587 mtime = nullptr;
6588 name = nullptr;
6589 for(key = xar_prop_first(xf, xp); key; key = xar_prop_next(xp)){
6590 const char *val = nullptr;
6591 xar_prop_get(xf, key, &val);
6592 #if 0 // Useful for debugging.
6593 outs() << "key: " << key << " value: " << val << "\n";
6594 #endif
6595 if(strcmp(key, "type") == 0)
6596 type = val;
6597 if(strcmp(key, "mode") == 0)
6598 mode = val;
6599 if(strcmp(key, "user") == 0)
6600 user = val;
6601 if(strcmp(key, "group") == 0)
6602 group = val;
6603 if(strcmp(key, "data/size") == 0)
6604 size = val;
6605 if(strcmp(key, "mtime") == 0)
6606 mtime = val;
6607 if(strcmp(key, "name") == 0)
6608 name = val;
6610 if(mode != nullptr){
6611 mode_value = strtoul(mode, &endp, 8);
6612 if(*endp != '\0')
6613 outs() << "(mode: \"" << mode << "\" contains non-octal chars) ";
6614 if(strcmp(type, "file") == 0)
6615 mode_value |= S_IFREG;
6616 PrintModeVerbose(mode_value);
6617 outs() << " ";
6619 if(user != nullptr)
6620 outs() << format("%10s/", user);
6621 if(group != nullptr)
6622 outs() << format("%-10s ", group);
6623 if(size != nullptr)
6624 outs() << format("%7s ", size);
6625 if(mtime != nullptr){
6626 for(m = mtime; *m != 'T' && *m != '\0'; m++)
6627 outs() << *m;
6628 if(*m == 'T')
6629 m++;
6630 outs() << " ";
6631 for( ; *m != 'Z' && *m != '\0'; m++)
6632 outs() << *m;
6633 outs() << " ";
6635 if(name != nullptr)
6636 outs() << name;
6637 outs() << "\n";
6641 static void DumpBitcodeSection(MachOObjectFile *O, const char *sect,
6642 uint32_t size, bool verbose,
6643 bool PrintXarHeader, bool PrintXarFileHeaders,
6644 std::string XarMemberName) {
6645 if(size < sizeof(struct xar_header)) {
6646 outs() << "size of (__LLVM,__bundle) section too small (smaller than size "
6647 "of struct xar_header)\n";
6648 return;
6650 struct xar_header XarHeader;
6651 memcpy(&XarHeader, sect, sizeof(struct xar_header));
6652 if (sys::IsLittleEndianHost)
6653 swapStruct(XarHeader);
6654 if (PrintXarHeader) {
6655 if (!XarMemberName.empty())
6656 outs() << "In xar member " << XarMemberName << ": ";
6657 else
6658 outs() << "For (__LLVM,__bundle) section: ";
6659 outs() << "xar header\n";
6660 if (XarHeader.magic == XAR_HEADER_MAGIC)
6661 outs() << " magic XAR_HEADER_MAGIC\n";
6662 else
6663 outs() << " magic "
6664 << format_hex(XarHeader.magic, 10, true)
6665 << " (not XAR_HEADER_MAGIC)\n";
6666 outs() << " size " << XarHeader.size << "\n";
6667 outs() << " version " << XarHeader.version << "\n";
6668 outs() << " toc_length_compressed " << XarHeader.toc_length_compressed
6669 << "\n";
6670 outs() << "toc_length_uncompressed " << XarHeader.toc_length_uncompressed
6671 << "\n";
6672 outs() << " cksum_alg ";
6673 switch (XarHeader.cksum_alg) {
6674 case XAR_CKSUM_NONE:
6675 outs() << "XAR_CKSUM_NONE\n";
6676 break;
6677 case XAR_CKSUM_SHA1:
6678 outs() << "XAR_CKSUM_SHA1\n";
6679 break;
6680 case XAR_CKSUM_MD5:
6681 outs() << "XAR_CKSUM_MD5\n";
6682 break;
6683 #ifdef XAR_CKSUM_SHA256
6684 case XAR_CKSUM_SHA256:
6685 outs() << "XAR_CKSUM_SHA256\n";
6686 break;
6687 #endif
6688 #ifdef XAR_CKSUM_SHA512
6689 case XAR_CKSUM_SHA512:
6690 outs() << "XAR_CKSUM_SHA512\n";
6691 break;
6692 #endif
6693 default:
6694 outs() << XarHeader.cksum_alg << "\n";
6698 SmallString<128> XarFilename;
6699 int FD;
6700 std::error_code XarEC =
6701 sys::fs::createTemporaryFile("llvm-objdump", "xar", FD, XarFilename);
6702 if (XarEC) {
6703 WithColor::error(errs(), "llvm-objdump") << XarEC.message() << "\n";
6704 return;
6706 ToolOutputFile XarFile(XarFilename, FD);
6707 raw_fd_ostream &XarOut = XarFile.os();
6708 StringRef XarContents(sect, size);
6709 XarOut << XarContents;
6710 XarOut.close();
6711 if (XarOut.has_error())
6712 return;
6714 ScopedXarFile xar(XarFilename.c_str(), READ);
6715 if (!xar) {
6716 WithColor::error(errs(), "llvm-objdump")
6717 << "can't create temporary xar archive " << XarFilename << "\n";
6718 return;
6721 SmallString<128> TocFilename;
6722 std::error_code TocEC =
6723 sys::fs::createTemporaryFile("llvm-objdump", "toc", TocFilename);
6724 if (TocEC) {
6725 WithColor::error(errs(), "llvm-objdump") << TocEC.message() << "\n";
6726 return;
6728 xar_serialize(xar, TocFilename.c_str());
6730 if (PrintXarFileHeaders) {
6731 if (!XarMemberName.empty())
6732 outs() << "In xar member " << XarMemberName << ": ";
6733 else
6734 outs() << "For (__LLVM,__bundle) section: ";
6735 outs() << "xar archive files:\n";
6736 PrintXarFilesSummary(XarFilename.c_str(), xar);
6739 ErrorOr<std::unique_ptr<MemoryBuffer>> FileOrErr =
6740 MemoryBuffer::getFileOrSTDIN(TocFilename.c_str());
6741 if (std::error_code EC = FileOrErr.getError()) {
6742 WithColor::error(errs(), "llvm-objdump") << EC.message() << "\n";
6743 return;
6745 std::unique_ptr<MemoryBuffer> &Buffer = FileOrErr.get();
6747 if (!XarMemberName.empty())
6748 outs() << "In xar member " << XarMemberName << ": ";
6749 else
6750 outs() << "For (__LLVM,__bundle) section: ";
6751 outs() << "xar table of contents:\n";
6752 outs() << Buffer->getBuffer() << "\n";
6754 // TODO: Go through the xar's files.
6755 ScopedXarIter xi;
6756 if(!xi){
6757 WithColor::error(errs(), "llvm-objdump")
6758 << "can't obtain an xar iterator for xar archive "
6759 << XarFilename.c_str() << "\n";
6760 return;
6762 for(xar_file_t xf = xar_file_first(xar, xi); xf; xf = xar_file_next(xi)){
6763 const char *key;
6764 const char *member_name, *member_type, *member_size_string;
6765 size_t member_size;
6767 ScopedXarIter xp;
6768 if(!xp){
6769 WithColor::error(errs(), "llvm-objdump")
6770 << "can't obtain an xar iterator for xar archive "
6771 << XarFilename.c_str() << "\n";
6772 return;
6774 member_name = NULL;
6775 member_type = NULL;
6776 member_size_string = NULL;
6777 for(key = xar_prop_first(xf, xp); key; key = xar_prop_next(xp)){
6778 const char *val = nullptr;
6779 xar_prop_get(xf, key, &val);
6780 #if 0 // Useful for debugging.
6781 outs() << "key: " << key << " value: " << val << "\n";
6782 #endif
6783 if (strcmp(key, "name") == 0)
6784 member_name = val;
6785 if (strcmp(key, "type") == 0)
6786 member_type = val;
6787 if (strcmp(key, "data/size") == 0)
6788 member_size_string = val;
6791 * If we find a file with a name, date/size and type properties
6792 * and with the type being "file" see if that is a xar file.
6794 if (member_name != NULL && member_type != NULL &&
6795 strcmp(member_type, "file") == 0 &&
6796 member_size_string != NULL){
6797 // Extract the file into a buffer.
6798 char *endptr;
6799 member_size = strtoul(member_size_string, &endptr, 10);
6800 if (*endptr == '\0' && member_size != 0) {
6801 char *buffer;
6802 if (xar_extract_tobuffersz(xar, xf, &buffer, &member_size) == 0) {
6803 #if 0 // Useful for debugging.
6804 outs() << "xar member: " << member_name << " extracted\n";
6805 #endif
6806 // Set the XarMemberName we want to see printed in the header.
6807 std::string OldXarMemberName;
6808 // If XarMemberName is already set this is nested. So
6809 // save the old name and create the nested name.
6810 if (!XarMemberName.empty()) {
6811 OldXarMemberName = XarMemberName;
6812 XarMemberName =
6813 (Twine("[") + XarMemberName + "]" + member_name).str();
6814 } else {
6815 OldXarMemberName = "";
6816 XarMemberName = member_name;
6818 // See if this is could be a xar file (nested).
6819 if (member_size >= sizeof(struct xar_header)) {
6820 #if 0 // Useful for debugging.
6821 outs() << "could be a xar file: " << member_name << "\n";
6822 #endif
6823 memcpy((char *)&XarHeader, buffer, sizeof(struct xar_header));
6824 if (sys::IsLittleEndianHost)
6825 swapStruct(XarHeader);
6826 if (XarHeader.magic == XAR_HEADER_MAGIC)
6827 DumpBitcodeSection(O, buffer, member_size, verbose,
6828 PrintXarHeader, PrintXarFileHeaders,
6829 XarMemberName);
6831 XarMemberName = OldXarMemberName;
6832 delete buffer;
6838 #endif // defined(HAVE_LIBXAR)
6840 static void printObjcMetaData(MachOObjectFile *O, bool verbose) {
6841 if (O->is64Bit())
6842 printObjc2_64bit_MetaData(O, verbose);
6843 else {
6844 MachO::mach_header H;
6845 H = O->getHeader();
6846 if (H.cputype == MachO::CPU_TYPE_ARM)
6847 printObjc2_32bit_MetaData(O, verbose);
6848 else {
6849 // This is the 32-bit non-arm cputype case. Which is normally
6850 // the first Objective-C ABI. But it may be the case of a
6851 // binary for the iOS simulator which is the second Objective-C
6852 // ABI. In that case printObjc1_32bit_MetaData() will determine that
6853 // and return false.
6854 if (!printObjc1_32bit_MetaData(O, verbose))
6855 printObjc2_32bit_MetaData(O, verbose);
6860 // GuessLiteralPointer returns a string which for the item in the Mach-O file
6861 // for the address passed in as ReferenceValue for printing as a comment with
6862 // the instruction and also returns the corresponding type of that item
6863 // indirectly through ReferenceType.
6865 // If ReferenceValue is an address of literal cstring then a pointer to the
6866 // cstring is returned and ReferenceType is set to
6867 // LLVMDisassembler_ReferenceType_Out_LitPool_CstrAddr .
6869 // If ReferenceValue is an address of an Objective-C CFString, Selector ref or
6870 // Class ref that name is returned and the ReferenceType is set accordingly.
6872 // Lastly, literals which are Symbol address in a literal pool are looked for
6873 // and if found the symbol name is returned and ReferenceType is set to
6874 // LLVMDisassembler_ReferenceType_Out_LitPool_SymAddr .
6876 // If there is no item in the Mach-O file for the address passed in as
6877 // ReferenceValue nullptr is returned and ReferenceType is unchanged.
6878 static const char *GuessLiteralPointer(uint64_t ReferenceValue,
6879 uint64_t ReferencePC,
6880 uint64_t *ReferenceType,
6881 struct DisassembleInfo *info) {
6882 // First see if there is an external relocation entry at the ReferencePC.
6883 if (info->O->getHeader().filetype == MachO::MH_OBJECT) {
6884 uint64_t sect_addr = info->S.getAddress();
6885 uint64_t sect_offset = ReferencePC - sect_addr;
6886 bool reloc_found = false;
6887 DataRefImpl Rel;
6888 MachO::any_relocation_info RE;
6889 bool isExtern = false;
6890 SymbolRef Symbol;
6891 for (const RelocationRef &Reloc : info->S.relocations()) {
6892 uint64_t RelocOffset = Reloc.getOffset();
6893 if (RelocOffset == sect_offset) {
6894 Rel = Reloc.getRawDataRefImpl();
6895 RE = info->O->getRelocation(Rel);
6896 if (info->O->isRelocationScattered(RE))
6897 continue;
6898 isExtern = info->O->getPlainRelocationExternal(RE);
6899 if (isExtern) {
6900 symbol_iterator RelocSym = Reloc.getSymbol();
6901 Symbol = *RelocSym;
6903 reloc_found = true;
6904 break;
6907 // If there is an external relocation entry for a symbol in a section
6908 // then used that symbol's value for the value of the reference.
6909 if (reloc_found && isExtern) {
6910 if (info->O->getAnyRelocationPCRel(RE)) {
6911 unsigned Type = info->O->getAnyRelocationType(RE);
6912 if (Type == MachO::X86_64_RELOC_SIGNED) {
6913 ReferenceValue = Symbol.getValue();
6919 // Look for literals such as Objective-C CFStrings refs, Selector refs,
6920 // Message refs and Class refs.
6921 bool classref, selref, msgref, cfstring;
6922 uint64_t pointer_value = GuessPointerPointer(ReferenceValue, info, classref,
6923 selref, msgref, cfstring);
6924 if (classref && pointer_value == 0) {
6925 // Note the ReferenceValue is a pointer into the __objc_classrefs section.
6926 // And the pointer_value in that section is typically zero as it will be
6927 // set by dyld as part of the "bind information".
6928 const char *name = get_dyld_bind_info_symbolname(ReferenceValue, info);
6929 if (name != nullptr) {
6930 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Class_Ref;
6931 const char *class_name = strrchr(name, '$');
6932 if (class_name != nullptr && class_name[1] == '_' &&
6933 class_name[2] != '\0') {
6934 info->class_name = class_name + 2;
6935 return name;
6940 if (classref) {
6941 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Class_Ref;
6942 const char *name =
6943 get_objc2_64bit_class_name(pointer_value, ReferenceValue, info);
6944 if (name != nullptr)
6945 info->class_name = name;
6946 else
6947 name = "bad class ref";
6948 return name;
6951 if (cfstring) {
6952 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_CFString_Ref;
6953 const char *name = get_objc2_64bit_cfstring_name(ReferenceValue, info);
6954 return name;
6957 if (selref && pointer_value == 0)
6958 pointer_value = get_objc2_64bit_selref(ReferenceValue, info);
6960 if (pointer_value != 0)
6961 ReferenceValue = pointer_value;
6963 const char *name = GuessCstringPointer(ReferenceValue, info);
6964 if (name) {
6965 if (pointer_value != 0 && selref) {
6966 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Selector_Ref;
6967 info->selector_name = name;
6968 } else if (pointer_value != 0 && msgref) {
6969 info->class_name = nullptr;
6970 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message_Ref;
6971 info->selector_name = name;
6972 } else
6973 *ReferenceType = LLVMDisassembler_ReferenceType_Out_LitPool_CstrAddr;
6974 return name;
6977 // Lastly look for an indirect symbol with this ReferenceValue which is in
6978 // a literal pool. If found return that symbol name.
6979 name = GuessIndirectSymbol(ReferenceValue, info);
6980 if (name) {
6981 *ReferenceType = LLVMDisassembler_ReferenceType_Out_LitPool_SymAddr;
6982 return name;
6985 return nullptr;
6988 // SymbolizerSymbolLookUp is the symbol lookup function passed when creating
6989 // the Symbolizer. It looks up the ReferenceValue using the info passed via the
6990 // pointer to the struct DisassembleInfo that was passed when MCSymbolizer
6991 // is created and returns the symbol name that matches the ReferenceValue or
6992 // nullptr if none. The ReferenceType is passed in for the IN type of
6993 // reference the instruction is making from the values in defined in the header
6994 // "llvm-c/Disassembler.h". On return the ReferenceType can set to a specific
6995 // Out type and the ReferenceName will also be set which is added as a comment
6996 // to the disassembled instruction.
6998 // If the symbol name is a C++ mangled name then the demangled name is
6999 // returned through ReferenceName and ReferenceType is set to
7000 // LLVMDisassembler_ReferenceType_DeMangled_Name .
7002 // When this is called to get a symbol name for a branch target then the
7003 // ReferenceType will be LLVMDisassembler_ReferenceType_In_Branch and then
7004 // SymbolValue will be looked for in the indirect symbol table to determine if
7005 // it is an address for a symbol stub. If so then the symbol name for that
7006 // stub is returned indirectly through ReferenceName and then ReferenceType is
7007 // set to LLVMDisassembler_ReferenceType_Out_SymbolStub.
7009 // When this is called with an value loaded via a PC relative load then
7010 // ReferenceType will be LLVMDisassembler_ReferenceType_In_PCrel_Load then the
7011 // SymbolValue is checked to be an address of literal pointer, symbol pointer,
7012 // or an Objective-C meta data reference. If so the output ReferenceType is
7013 // set to correspond to that as well as setting the ReferenceName.
7014 static const char *SymbolizerSymbolLookUp(void *DisInfo,
7015 uint64_t ReferenceValue,
7016 uint64_t *ReferenceType,
7017 uint64_t ReferencePC,
7018 const char **ReferenceName) {
7019 struct DisassembleInfo *info = (struct DisassembleInfo *)DisInfo;
7020 // If no verbose symbolic information is wanted then just return nullptr.
7021 if (!info->verbose) {
7022 *ReferenceName = nullptr;
7023 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
7024 return nullptr;
7027 const char *SymbolName = GuessSymbolName(ReferenceValue, info->AddrMap);
7029 if (*ReferenceType == LLVMDisassembler_ReferenceType_In_Branch) {
7030 *ReferenceName = GuessIndirectSymbol(ReferenceValue, info);
7031 if (*ReferenceName != nullptr) {
7032 method_reference(info, ReferenceType, ReferenceName);
7033 if (*ReferenceType != LLVMDisassembler_ReferenceType_Out_Objc_Message)
7034 *ReferenceType = LLVMDisassembler_ReferenceType_Out_SymbolStub;
7035 } else if (SymbolName != nullptr && strncmp(SymbolName, "__Z", 3) == 0) {
7036 if (info->demangled_name != nullptr)
7037 free(info->demangled_name);
7038 int status;
7039 info->demangled_name =
7040 itaniumDemangle(SymbolName + 1, nullptr, nullptr, &status);
7041 if (info->demangled_name != nullptr) {
7042 *ReferenceName = info->demangled_name;
7043 *ReferenceType = LLVMDisassembler_ReferenceType_DeMangled_Name;
7044 } else
7045 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
7046 } else
7047 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
7048 } else if (*ReferenceType == LLVMDisassembler_ReferenceType_In_PCrel_Load) {
7049 *ReferenceName =
7050 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
7051 if (*ReferenceName)
7052 method_reference(info, ReferenceType, ReferenceName);
7053 else
7054 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
7055 // If this is arm64 and the reference is an adrp instruction save the
7056 // instruction, passed in ReferenceValue and the address of the instruction
7057 // for use later if we see and add immediate instruction.
7058 } else if (info->O->getArch() == Triple::aarch64 &&
7059 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADRP) {
7060 info->adrp_inst = ReferenceValue;
7061 info->adrp_addr = ReferencePC;
7062 SymbolName = nullptr;
7063 *ReferenceName = nullptr;
7064 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
7065 // If this is arm64 and reference is an add immediate instruction and we
7066 // have
7067 // seen an adrp instruction just before it and the adrp's Xd register
7068 // matches
7069 // this add's Xn register reconstruct the value being referenced and look to
7070 // see if it is a literal pointer. Note the add immediate instruction is
7071 // passed in ReferenceValue.
7072 } else if (info->O->getArch() == Triple::aarch64 &&
7073 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADDXri &&
7074 ReferencePC - 4 == info->adrp_addr &&
7075 (info->adrp_inst & 0x9f000000) == 0x90000000 &&
7076 (info->adrp_inst & 0x1f) == ((ReferenceValue >> 5) & 0x1f)) {
7077 uint32_t addxri_inst;
7078 uint64_t adrp_imm, addxri_imm;
7080 adrp_imm =
7081 ((info->adrp_inst & 0x00ffffe0) >> 3) | ((info->adrp_inst >> 29) & 0x3);
7082 if (info->adrp_inst & 0x0200000)
7083 adrp_imm |= 0xfffffffffc000000LL;
7085 addxri_inst = ReferenceValue;
7086 addxri_imm = (addxri_inst >> 10) & 0xfff;
7087 if (((addxri_inst >> 22) & 0x3) == 1)
7088 addxri_imm <<= 12;
7090 ReferenceValue = (info->adrp_addr & 0xfffffffffffff000LL) +
7091 (adrp_imm << 12) + addxri_imm;
7093 *ReferenceName =
7094 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
7095 if (*ReferenceName == nullptr)
7096 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
7097 // If this is arm64 and the reference is a load register instruction and we
7098 // have seen an adrp instruction just before it and the adrp's Xd register
7099 // matches this add's Xn register reconstruct the value being referenced and
7100 // look to see if it is a literal pointer. Note the load register
7101 // instruction is passed in ReferenceValue.
7102 } else if (info->O->getArch() == Triple::aarch64 &&
7103 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_LDRXui &&
7104 ReferencePC - 4 == info->adrp_addr &&
7105 (info->adrp_inst & 0x9f000000) == 0x90000000 &&
7106 (info->adrp_inst & 0x1f) == ((ReferenceValue >> 5) & 0x1f)) {
7107 uint32_t ldrxui_inst;
7108 uint64_t adrp_imm, ldrxui_imm;
7110 adrp_imm =
7111 ((info->adrp_inst & 0x00ffffe0) >> 3) | ((info->adrp_inst >> 29) & 0x3);
7112 if (info->adrp_inst & 0x0200000)
7113 adrp_imm |= 0xfffffffffc000000LL;
7115 ldrxui_inst = ReferenceValue;
7116 ldrxui_imm = (ldrxui_inst >> 10) & 0xfff;
7118 ReferenceValue = (info->adrp_addr & 0xfffffffffffff000LL) +
7119 (adrp_imm << 12) + (ldrxui_imm << 3);
7121 *ReferenceName =
7122 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
7123 if (*ReferenceName == nullptr)
7124 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
7126 // If this arm64 and is an load register (PC-relative) instruction the
7127 // ReferenceValue is the PC plus the immediate value.
7128 else if (info->O->getArch() == Triple::aarch64 &&
7129 (*ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_LDRXl ||
7130 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADR)) {
7131 *ReferenceName =
7132 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
7133 if (*ReferenceName == nullptr)
7134 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
7135 } else if (SymbolName != nullptr && strncmp(SymbolName, "__Z", 3) == 0) {
7136 if (info->demangled_name != nullptr)
7137 free(info->demangled_name);
7138 int status;
7139 info->demangled_name =
7140 itaniumDemangle(SymbolName + 1, nullptr, nullptr, &status);
7141 if (info->demangled_name != nullptr) {
7142 *ReferenceName = info->demangled_name;
7143 *ReferenceType = LLVMDisassembler_ReferenceType_DeMangled_Name;
7146 else {
7147 *ReferenceName = nullptr;
7148 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
7151 return SymbolName;
7154 /// Emits the comments that are stored in the CommentStream.
7155 /// Each comment in the CommentStream must end with a newline.
7156 static void emitComments(raw_svector_ostream &CommentStream,
7157 SmallString<128> &CommentsToEmit,
7158 formatted_raw_ostream &FormattedOS,
7159 const MCAsmInfo &MAI) {
7160 // Flush the stream before taking its content.
7161 StringRef Comments = CommentsToEmit.str();
7162 // Get the default information for printing a comment.
7163 StringRef CommentBegin = MAI.getCommentString();
7164 unsigned CommentColumn = MAI.getCommentColumn();
7165 bool IsFirst = true;
7166 while (!Comments.empty()) {
7167 if (!IsFirst)
7168 FormattedOS << '\n';
7169 // Emit a line of comments.
7170 FormattedOS.PadToColumn(CommentColumn);
7171 size_t Position = Comments.find('\n');
7172 FormattedOS << CommentBegin << ' ' << Comments.substr(0, Position);
7173 // Move after the newline character.
7174 Comments = Comments.substr(Position + 1);
7175 IsFirst = false;
7177 FormattedOS.flush();
7179 // Tell the comment stream that the vector changed underneath it.
7180 CommentsToEmit.clear();
7183 static void DisassembleMachO(StringRef Filename, MachOObjectFile *MachOOF,
7184 StringRef DisSegName, StringRef DisSectName) {
7185 const char *McpuDefault = nullptr;
7186 const Target *ThumbTarget = nullptr;
7187 const Target *TheTarget = GetTarget(MachOOF, &McpuDefault, &ThumbTarget);
7188 if (!TheTarget) {
7189 // GetTarget prints out stuff.
7190 return;
7192 std::string MachOMCPU;
7193 if (MCPU.empty() && McpuDefault)
7194 MachOMCPU = McpuDefault;
7195 else
7196 MachOMCPU = MCPU;
7198 std::unique_ptr<const MCInstrInfo> InstrInfo(TheTarget->createMCInstrInfo());
7199 std::unique_ptr<const MCInstrInfo> ThumbInstrInfo;
7200 if (ThumbTarget)
7201 ThumbInstrInfo.reset(ThumbTarget->createMCInstrInfo());
7203 // Package up features to be passed to target/subtarget
7204 std::string FeaturesStr;
7205 if (!MAttrs.empty()) {
7206 SubtargetFeatures Features;
7207 for (unsigned i = 0; i != MAttrs.size(); ++i)
7208 Features.AddFeature(MAttrs[i]);
7209 FeaturesStr = Features.getString();
7212 MCTargetOptions MCOptions;
7213 // Set up disassembler.
7214 std::unique_ptr<const MCRegisterInfo> MRI(
7215 TheTarget->createMCRegInfo(TripleName));
7216 std::unique_ptr<const MCAsmInfo> AsmInfo(
7217 TheTarget->createMCAsmInfo(*MRI, TripleName, MCOptions));
7218 std::unique_ptr<const MCSubtargetInfo> STI(
7219 TheTarget->createMCSubtargetInfo(TripleName, MachOMCPU, FeaturesStr));
7220 MCContext Ctx(AsmInfo.get(), MRI.get(), nullptr);
7221 std::unique_ptr<MCDisassembler> DisAsm(
7222 TheTarget->createMCDisassembler(*STI, Ctx));
7223 std::unique_ptr<MCSymbolizer> Symbolizer;
7224 struct DisassembleInfo SymbolizerInfo(nullptr, nullptr, nullptr, false);
7225 std::unique_ptr<MCRelocationInfo> RelInfo(
7226 TheTarget->createMCRelocationInfo(TripleName, Ctx));
7227 if (RelInfo) {
7228 Symbolizer.reset(TheTarget->createMCSymbolizer(
7229 TripleName, SymbolizerGetOpInfo, SymbolizerSymbolLookUp,
7230 &SymbolizerInfo, &Ctx, std::move(RelInfo)));
7231 DisAsm->setSymbolizer(std::move(Symbolizer));
7233 int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
7234 std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
7235 Triple(TripleName), AsmPrinterVariant, *AsmInfo, *InstrInfo, *MRI));
7236 // Set the display preference for hex vs. decimal immediates.
7237 IP->setPrintImmHex(PrintImmHex);
7238 // Comment stream and backing vector.
7239 SmallString<128> CommentsToEmit;
7240 raw_svector_ostream CommentStream(CommentsToEmit);
7241 // FIXME: Setting the CommentStream in the InstPrinter is problematic in that
7242 // if it is done then arm64 comments for string literals don't get printed
7243 // and some constant get printed instead and not setting it causes intel
7244 // (32-bit and 64-bit) comments printed with different spacing before the
7245 // comment causing different diffs with the 'C' disassembler library API.
7246 // IP->setCommentStream(CommentStream);
7248 if (!AsmInfo || !STI || !DisAsm || !IP) {
7249 WithColor::error(errs(), "llvm-objdump")
7250 << "couldn't initialize disassembler for target " << TripleName << '\n';
7251 return;
7254 // Set up separate thumb disassembler if needed.
7255 std::unique_ptr<const MCRegisterInfo> ThumbMRI;
7256 std::unique_ptr<const MCAsmInfo> ThumbAsmInfo;
7257 std::unique_ptr<const MCSubtargetInfo> ThumbSTI;
7258 std::unique_ptr<MCDisassembler> ThumbDisAsm;
7259 std::unique_ptr<MCInstPrinter> ThumbIP;
7260 std::unique_ptr<MCContext> ThumbCtx;
7261 std::unique_ptr<MCSymbolizer> ThumbSymbolizer;
7262 struct DisassembleInfo ThumbSymbolizerInfo(nullptr, nullptr, nullptr, false);
7263 std::unique_ptr<MCRelocationInfo> ThumbRelInfo;
7264 if (ThumbTarget) {
7265 ThumbMRI.reset(ThumbTarget->createMCRegInfo(ThumbTripleName));
7266 ThumbAsmInfo.reset(
7267 ThumbTarget->createMCAsmInfo(*ThumbMRI, ThumbTripleName, MCOptions));
7268 ThumbSTI.reset(
7269 ThumbTarget->createMCSubtargetInfo(ThumbTripleName, MachOMCPU,
7270 FeaturesStr));
7271 ThumbCtx.reset(new MCContext(ThumbAsmInfo.get(), ThumbMRI.get(), nullptr));
7272 ThumbDisAsm.reset(ThumbTarget->createMCDisassembler(*ThumbSTI, *ThumbCtx));
7273 MCContext *PtrThumbCtx = ThumbCtx.get();
7274 ThumbRelInfo.reset(
7275 ThumbTarget->createMCRelocationInfo(ThumbTripleName, *PtrThumbCtx));
7276 if (ThumbRelInfo) {
7277 ThumbSymbolizer.reset(ThumbTarget->createMCSymbolizer(
7278 ThumbTripleName, SymbolizerGetOpInfo, SymbolizerSymbolLookUp,
7279 &ThumbSymbolizerInfo, PtrThumbCtx, std::move(ThumbRelInfo)));
7280 ThumbDisAsm->setSymbolizer(std::move(ThumbSymbolizer));
7282 int ThumbAsmPrinterVariant = ThumbAsmInfo->getAssemblerDialect();
7283 ThumbIP.reset(ThumbTarget->createMCInstPrinter(
7284 Triple(ThumbTripleName), ThumbAsmPrinterVariant, *ThumbAsmInfo,
7285 *ThumbInstrInfo, *ThumbMRI));
7286 // Set the display preference for hex vs. decimal immediates.
7287 ThumbIP->setPrintImmHex(PrintImmHex);
7290 if (ThumbTarget && (!ThumbAsmInfo || !ThumbSTI || !ThumbDisAsm || !ThumbIP)) {
7291 WithColor::error(errs(), "llvm-objdump")
7292 << "couldn't initialize disassembler for target " << ThumbTripleName
7293 << '\n';
7294 return;
7297 MachO::mach_header Header = MachOOF->getHeader();
7299 // FIXME: Using the -cfg command line option, this code used to be able to
7300 // annotate relocations with the referenced symbol's name, and if this was
7301 // inside a __[cf]string section, the data it points to. This is now replaced
7302 // by the upcoming MCSymbolizer, which needs the appropriate setup done above.
7303 std::vector<SectionRef> Sections;
7304 std::vector<SymbolRef> Symbols;
7305 SmallVector<uint64_t, 8> FoundFns;
7306 uint64_t BaseSegmentAddress = 0;
7308 getSectionsAndSymbols(MachOOF, Sections, Symbols, FoundFns,
7309 BaseSegmentAddress);
7311 // Sort the symbols by address, just in case they didn't come in that way.
7312 llvm::sort(Symbols, SymbolSorter());
7314 // Build a data in code table that is sorted on by the address of each entry.
7315 uint64_t BaseAddress = 0;
7316 if (Header.filetype == MachO::MH_OBJECT)
7317 BaseAddress = Sections[0].getAddress();
7318 else
7319 BaseAddress = BaseSegmentAddress;
7320 DiceTable Dices;
7321 for (dice_iterator DI = MachOOF->begin_dices(), DE = MachOOF->end_dices();
7322 DI != DE; ++DI) {
7323 uint32_t Offset;
7324 DI->getOffset(Offset);
7325 Dices.push_back(std::make_pair(BaseAddress + Offset, *DI));
7327 array_pod_sort(Dices.begin(), Dices.end());
7329 // Try to find debug info and set up the DIContext for it.
7330 std::unique_ptr<DIContext> diContext;
7331 std::unique_ptr<Binary> DSYMBinary;
7332 std::unique_ptr<MemoryBuffer> DSYMBuf;
7333 if (UseDbg) {
7334 ObjectFile *DbgObj = MachOOF;
7336 // A separate DSym file path was specified, parse it as a macho file,
7337 // get the sections and supply it to the section name parsing machinery.
7338 if (!DSYMFile.empty()) {
7339 std::string DSYMPath(DSYMFile);
7341 // If DSYMPath is a .dSYM directory, append the Mach-O file.
7342 if (llvm::sys::fs::is_directory(DSYMPath) &&
7343 llvm::sys::path::extension(DSYMPath) == ".dSYM") {
7344 SmallString<128> ShortName(llvm::sys::path::filename(DSYMPath));
7345 llvm::sys::path::replace_extension(ShortName, "");
7346 SmallString<1024> FullPath(DSYMPath);
7347 llvm::sys::path::append(FullPath, "Contents", "Resources", "DWARF",
7348 ShortName);
7349 DSYMPath = FullPath.str();
7352 // Load the file.
7353 ErrorOr<std::unique_ptr<MemoryBuffer>> BufOrErr =
7354 MemoryBuffer::getFileOrSTDIN(DSYMPath);
7355 if (std::error_code EC = BufOrErr.getError()) {
7356 reportError(errorCodeToError(EC), DSYMPath);
7357 return;
7360 // We need to keep the file alive, because we're replacing DbgObj with it.
7361 DSYMBuf = std::move(BufOrErr.get());
7363 Expected<std::unique_ptr<Binary>> BinaryOrErr =
7364 createBinary(DSYMBuf.get()->getMemBufferRef());
7365 if (!BinaryOrErr) {
7366 reportError(BinaryOrErr.takeError(), DSYMPath);
7367 return;
7370 // We need to keep the Binary alive with the buffer
7371 DSYMBinary = std::move(BinaryOrErr.get());
7372 if (ObjectFile *O = dyn_cast<ObjectFile>(DSYMBinary.get())) {
7373 // this is a Mach-O object file, use it
7374 if (MachOObjectFile *MachDSYM = dyn_cast<MachOObjectFile>(&*O)) {
7375 DbgObj = MachDSYM;
7377 else {
7378 WithColor::error(errs(), "llvm-objdump")
7379 << DSYMPath << " is not a Mach-O file type.\n";
7380 return;
7383 else if (auto UB = dyn_cast<MachOUniversalBinary>(DSYMBinary.get())){
7384 // this is a Universal Binary, find a Mach-O for this architecture
7385 uint32_t CPUType, CPUSubType;
7386 const char *ArchFlag;
7387 if (MachOOF->is64Bit()) {
7388 const MachO::mach_header_64 H_64 = MachOOF->getHeader64();
7389 CPUType = H_64.cputype;
7390 CPUSubType = H_64.cpusubtype;
7391 } else {
7392 const MachO::mach_header H = MachOOF->getHeader();
7393 CPUType = H.cputype;
7394 CPUSubType = H.cpusubtype;
7396 Triple T = MachOObjectFile::getArchTriple(CPUType, CPUSubType, nullptr,
7397 &ArchFlag);
7398 Expected<std::unique_ptr<MachOObjectFile>> MachDSYM =
7399 UB->getMachOObjectForArch(ArchFlag);
7400 if (!MachDSYM) {
7401 reportError(MachDSYM.takeError(), DSYMPath);
7402 return;
7405 // We need to keep the Binary alive with the buffer
7406 DbgObj = &*MachDSYM.get();
7407 DSYMBinary = std::move(*MachDSYM);
7409 else {
7410 WithColor::error(errs(), "llvm-objdump")
7411 << DSYMPath << " is not a Mach-O or Universal file type.\n";
7412 return;
7416 // Setup the DIContext
7417 diContext = DWARFContext::create(*DbgObj);
7420 if (FilterSections.empty())
7421 outs() << "(" << DisSegName << "," << DisSectName << ") section\n";
7423 for (unsigned SectIdx = 0; SectIdx != Sections.size(); SectIdx++) {
7424 Expected<StringRef> SecNameOrErr = Sections[SectIdx].getName();
7425 if (!SecNameOrErr) {
7426 consumeError(SecNameOrErr.takeError());
7427 continue;
7429 if (*SecNameOrErr != DisSectName)
7430 continue;
7432 DataRefImpl DR = Sections[SectIdx].getRawDataRefImpl();
7434 StringRef SegmentName = MachOOF->getSectionFinalSegmentName(DR);
7435 if (SegmentName != DisSegName)
7436 continue;
7438 StringRef BytesStr =
7439 unwrapOrError(Sections[SectIdx].getContents(), Filename);
7440 ArrayRef<uint8_t> Bytes = arrayRefFromStringRef(BytesStr);
7441 uint64_t SectAddress = Sections[SectIdx].getAddress();
7443 bool symbolTableWorked = false;
7445 // Create a map of symbol addresses to symbol names for use by
7446 // the SymbolizerSymbolLookUp() routine.
7447 SymbolAddressMap AddrMap;
7448 bool DisSymNameFound = false;
7449 for (const SymbolRef &Symbol : MachOOF->symbols()) {
7450 SymbolRef::Type ST =
7451 unwrapOrError(Symbol.getType(), MachOOF->getFileName());
7452 if (ST == SymbolRef::ST_Function || ST == SymbolRef::ST_Data ||
7453 ST == SymbolRef::ST_Other) {
7454 uint64_t Address = Symbol.getValue();
7455 StringRef SymName =
7456 unwrapOrError(Symbol.getName(), MachOOF->getFileName());
7457 AddrMap[Address] = SymName;
7458 if (!DisSymName.empty() && DisSymName == SymName)
7459 DisSymNameFound = true;
7462 if (!DisSymName.empty() && !DisSymNameFound) {
7463 outs() << "Can't find -dis-symname: " << DisSymName << "\n";
7464 return;
7466 // Set up the block of info used by the Symbolizer call backs.
7467 SymbolizerInfo.verbose = !NoSymbolicOperands;
7468 SymbolizerInfo.O = MachOOF;
7469 SymbolizerInfo.S = Sections[SectIdx];
7470 SymbolizerInfo.AddrMap = &AddrMap;
7471 SymbolizerInfo.Sections = &Sections;
7472 // Same for the ThumbSymbolizer
7473 ThumbSymbolizerInfo.verbose = !NoSymbolicOperands;
7474 ThumbSymbolizerInfo.O = MachOOF;
7475 ThumbSymbolizerInfo.S = Sections[SectIdx];
7476 ThumbSymbolizerInfo.AddrMap = &AddrMap;
7477 ThumbSymbolizerInfo.Sections = &Sections;
7479 unsigned int Arch = MachOOF->getArch();
7481 // Skip all symbols if this is a stubs file.
7482 if (Bytes.empty())
7483 return;
7485 // If the section has symbols but no symbol at the start of the section
7486 // these are used to make sure the bytes before the first symbol are
7487 // disassembled.
7488 bool FirstSymbol = true;
7489 bool FirstSymbolAtSectionStart = true;
7491 // Disassemble symbol by symbol.
7492 for (unsigned SymIdx = 0; SymIdx != Symbols.size(); SymIdx++) {
7493 StringRef SymName =
7494 unwrapOrError(Symbols[SymIdx].getName(), MachOOF->getFileName());
7495 SymbolRef::Type ST =
7496 unwrapOrError(Symbols[SymIdx].getType(), MachOOF->getFileName());
7497 if (ST != SymbolRef::ST_Function && ST != SymbolRef::ST_Data)
7498 continue;
7500 // Make sure the symbol is defined in this section.
7501 bool containsSym = Sections[SectIdx].containsSymbol(Symbols[SymIdx]);
7502 if (!containsSym) {
7503 if (!DisSymName.empty() && DisSymName == SymName) {
7504 outs() << "-dis-symname: " << DisSymName << " not in the section\n";
7505 return;
7507 continue;
7509 // The __mh_execute_header is special and we need to deal with that fact
7510 // this symbol is before the start of the (__TEXT,__text) section and at the
7511 // address of the start of the __TEXT segment. This is because this symbol
7512 // is an N_SECT symbol in the (__TEXT,__text) but its address is before the
7513 // start of the section in a standard MH_EXECUTE filetype.
7514 if (!DisSymName.empty() && DisSymName == "__mh_execute_header") {
7515 outs() << "-dis-symname: __mh_execute_header not in any section\n";
7516 return;
7518 // When this code is trying to disassemble a symbol at a time and in the
7519 // case there is only the __mh_execute_header symbol left as in a stripped
7520 // executable, we need to deal with this by ignoring this symbol so the
7521 // whole section is disassembled and this symbol is then not displayed.
7522 if (SymName == "__mh_execute_header" || SymName == "__mh_dylib_header" ||
7523 SymName == "__mh_bundle_header" || SymName == "__mh_object_header" ||
7524 SymName == "__mh_preload_header" || SymName == "__mh_dylinker_header")
7525 continue;
7527 // If we are only disassembling one symbol see if this is that symbol.
7528 if (!DisSymName.empty() && DisSymName != SymName)
7529 continue;
7531 // Start at the address of the symbol relative to the section's address.
7532 uint64_t SectSize = Sections[SectIdx].getSize();
7533 uint64_t Start = Symbols[SymIdx].getValue();
7534 uint64_t SectionAddress = Sections[SectIdx].getAddress();
7535 Start -= SectionAddress;
7537 if (Start > SectSize) {
7538 outs() << "section data ends, " << SymName
7539 << " lies outside valid range\n";
7540 return;
7543 // Stop disassembling either at the beginning of the next symbol or at
7544 // the end of the section.
7545 bool containsNextSym = false;
7546 uint64_t NextSym = 0;
7547 uint64_t NextSymIdx = SymIdx + 1;
7548 while (Symbols.size() > NextSymIdx) {
7549 SymbolRef::Type NextSymType = unwrapOrError(
7550 Symbols[NextSymIdx].getType(), MachOOF->getFileName());
7551 if (NextSymType == SymbolRef::ST_Function) {
7552 containsNextSym =
7553 Sections[SectIdx].containsSymbol(Symbols[NextSymIdx]);
7554 NextSym = Symbols[NextSymIdx].getValue();
7555 NextSym -= SectionAddress;
7556 break;
7558 ++NextSymIdx;
7561 uint64_t End = containsNextSym ? std::min(NextSym, SectSize) : SectSize;
7562 uint64_t Size;
7564 symbolTableWorked = true;
7566 DataRefImpl Symb = Symbols[SymIdx].getRawDataRefImpl();
7567 bool IsThumb = MachOOF->getSymbolFlags(Symb) & SymbolRef::SF_Thumb;
7569 // We only need the dedicated Thumb target if there's a real choice
7570 // (i.e. we're not targeting M-class) and the function is Thumb.
7571 bool UseThumbTarget = IsThumb && ThumbTarget;
7573 // If we are not specifying a symbol to start disassembly with and this
7574 // is the first symbol in the section but not at the start of the section
7575 // then move the disassembly index to the start of the section and
7576 // don't print the symbol name just yet. This is so the bytes before the
7577 // first symbol are disassembled.
7578 uint64_t SymbolStart = Start;
7579 if (DisSymName.empty() && FirstSymbol && Start != 0) {
7580 FirstSymbolAtSectionStart = false;
7581 Start = 0;
7583 else
7584 outs() << SymName << ":\n";
7586 DILineInfo lastLine;
7587 for (uint64_t Index = Start; Index < End; Index += Size) {
7588 MCInst Inst;
7590 // If this is the first symbol in the section and it was not at the
7591 // start of the section, see if we are at its Index now and if so print
7592 // the symbol name.
7593 if (FirstSymbol && !FirstSymbolAtSectionStart && Index == SymbolStart)
7594 outs() << SymName << ":\n";
7596 uint64_t PC = SectAddress + Index;
7597 if (!NoLeadingAddr) {
7598 if (FullLeadingAddr) {
7599 if (MachOOF->is64Bit())
7600 outs() << format("%016" PRIx64, PC);
7601 else
7602 outs() << format("%08" PRIx64, PC);
7603 } else {
7604 outs() << format("%8" PRIx64 ":", PC);
7607 if (!NoShowRawInsn || Arch == Triple::arm)
7608 outs() << "\t";
7610 if (DumpAndSkipDataInCode(PC, Bytes.data() + Index, Dices, Size))
7611 continue;
7613 SmallVector<char, 64> AnnotationsBytes;
7614 raw_svector_ostream Annotations(AnnotationsBytes);
7616 bool gotInst;
7617 if (UseThumbTarget)
7618 gotInst = ThumbDisAsm->getInstruction(Inst, Size, Bytes.slice(Index),
7619 PC, Annotations);
7620 else
7621 gotInst = DisAsm->getInstruction(Inst, Size, Bytes.slice(Index), PC,
7622 Annotations);
7623 if (gotInst) {
7624 if (!NoShowRawInsn || Arch == Triple::arm) {
7625 dumpBytes(makeArrayRef(Bytes.data() + Index, Size), outs());
7627 formatted_raw_ostream FormattedOS(outs());
7628 StringRef AnnotationsStr = Annotations.str();
7629 if (UseThumbTarget)
7630 ThumbIP->printInst(&Inst, PC, AnnotationsStr, *ThumbSTI,
7631 FormattedOS);
7632 else
7633 IP->printInst(&Inst, PC, AnnotationsStr, *STI, FormattedOS);
7634 emitComments(CommentStream, CommentsToEmit, FormattedOS, *AsmInfo);
7636 // Print debug info.
7637 if (diContext) {
7638 DILineInfo dli = diContext->getLineInfoForAddress({PC, SectIdx});
7639 // Print valid line info if it changed.
7640 if (dli != lastLine && dli.Line != 0)
7641 outs() << "\t## " << dli.FileName << ':' << dli.Line << ':'
7642 << dli.Column;
7643 lastLine = dli;
7645 outs() << "\n";
7646 } else {
7647 if (MachOOF->getArchTriple().isX86()) {
7648 outs() << format("\t.byte 0x%02x #bad opcode\n",
7649 *(Bytes.data() + Index) & 0xff);
7650 Size = 1; // skip exactly one illegible byte and move on.
7651 } else if (Arch == Triple::aarch64 ||
7652 (Arch == Triple::arm && !IsThumb)) {
7653 uint32_t opcode = (*(Bytes.data() + Index) & 0xff) |
7654 (*(Bytes.data() + Index + 1) & 0xff) << 8 |
7655 (*(Bytes.data() + Index + 2) & 0xff) << 16 |
7656 (*(Bytes.data() + Index + 3) & 0xff) << 24;
7657 outs() << format("\t.long\t0x%08x\n", opcode);
7658 Size = 4;
7659 } else if (Arch == Triple::arm) {
7660 assert(IsThumb && "ARM mode should have been dealt with above");
7661 uint32_t opcode = (*(Bytes.data() + Index) & 0xff) |
7662 (*(Bytes.data() + Index + 1) & 0xff) << 8;
7663 outs() << format("\t.short\t0x%04x\n", opcode);
7664 Size = 2;
7665 } else{
7666 WithColor::warning(errs(), "llvm-objdump")
7667 << "invalid instruction encoding\n";
7668 if (Size == 0)
7669 Size = 1; // skip illegible bytes
7673 // Now that we are done disassembled the first symbol set the bool that
7674 // were doing this to false.
7675 FirstSymbol = false;
7677 if (!symbolTableWorked) {
7678 // Reading the symbol table didn't work, disassemble the whole section.
7679 uint64_t SectAddress = Sections[SectIdx].getAddress();
7680 uint64_t SectSize = Sections[SectIdx].getSize();
7681 uint64_t InstSize;
7682 for (uint64_t Index = 0; Index < SectSize; Index += InstSize) {
7683 MCInst Inst;
7685 uint64_t PC = SectAddress + Index;
7687 if (DumpAndSkipDataInCode(PC, Bytes.data() + Index, Dices, InstSize))
7688 continue;
7690 SmallVector<char, 64> AnnotationsBytes;
7691 raw_svector_ostream Annotations(AnnotationsBytes);
7692 if (DisAsm->getInstruction(Inst, InstSize, Bytes.slice(Index), PC,
7693 Annotations)) {
7694 if (!NoLeadingAddr) {
7695 if (FullLeadingAddr) {
7696 if (MachOOF->is64Bit())
7697 outs() << format("%016" PRIx64, PC);
7698 else
7699 outs() << format("%08" PRIx64, PC);
7700 } else {
7701 outs() << format("%8" PRIx64 ":", PC);
7704 if (!NoShowRawInsn || Arch == Triple::arm) {
7705 outs() << "\t";
7706 dumpBytes(makeArrayRef(Bytes.data() + Index, InstSize), outs());
7708 StringRef AnnotationsStr = Annotations.str();
7709 IP->printInst(&Inst, PC, AnnotationsStr, *STI, outs());
7710 outs() << "\n";
7711 } else {
7712 if (MachOOF->getArchTriple().isX86()) {
7713 outs() << format("\t.byte 0x%02x #bad opcode\n",
7714 *(Bytes.data() + Index) & 0xff);
7715 InstSize = 1; // skip exactly one illegible byte and move on.
7716 } else {
7717 WithColor::warning(errs(), "llvm-objdump")
7718 << "invalid instruction encoding\n";
7719 if (InstSize == 0)
7720 InstSize = 1; // skip illegible bytes
7725 // The TripleName's need to be reset if we are called again for a different
7726 // architecture.
7727 TripleName = "";
7728 ThumbTripleName = "";
7730 if (SymbolizerInfo.demangled_name != nullptr)
7731 free(SymbolizerInfo.demangled_name);
7732 if (ThumbSymbolizerInfo.demangled_name != nullptr)
7733 free(ThumbSymbolizerInfo.demangled_name);
7737 //===----------------------------------------------------------------------===//
7738 // __compact_unwind section dumping
7739 //===----------------------------------------------------------------------===//
7741 namespace {
7743 template <typename T>
7744 static uint64_t read(StringRef Contents, ptrdiff_t Offset) {
7745 using llvm::support::little;
7746 using llvm::support::unaligned;
7748 if (Offset + sizeof(T) > Contents.size()) {
7749 outs() << "warning: attempt to read past end of buffer\n";
7750 return T();
7753 uint64_t Val =
7754 support::endian::read<T, little, unaligned>(Contents.data() + Offset);
7755 return Val;
7758 template <typename T>
7759 static uint64_t readNext(StringRef Contents, ptrdiff_t &Offset) {
7760 T Val = read<T>(Contents, Offset);
7761 Offset += sizeof(T);
7762 return Val;
7765 struct CompactUnwindEntry {
7766 uint32_t OffsetInSection;
7768 uint64_t FunctionAddr;
7769 uint32_t Length;
7770 uint32_t CompactEncoding;
7771 uint64_t PersonalityAddr;
7772 uint64_t LSDAAddr;
7774 RelocationRef FunctionReloc;
7775 RelocationRef PersonalityReloc;
7776 RelocationRef LSDAReloc;
7778 CompactUnwindEntry(StringRef Contents, unsigned Offset, bool Is64)
7779 : OffsetInSection(Offset) {
7780 if (Is64)
7781 read<uint64_t>(Contents, Offset);
7782 else
7783 read<uint32_t>(Contents, Offset);
7786 private:
7787 template <typename UIntPtr> void read(StringRef Contents, ptrdiff_t Offset) {
7788 FunctionAddr = readNext<UIntPtr>(Contents, Offset);
7789 Length = readNext<uint32_t>(Contents, Offset);
7790 CompactEncoding = readNext<uint32_t>(Contents, Offset);
7791 PersonalityAddr = readNext<UIntPtr>(Contents, Offset);
7792 LSDAAddr = readNext<UIntPtr>(Contents, Offset);
7797 /// Given a relocation from __compact_unwind, consisting of the RelocationRef
7798 /// and data being relocated, determine the best base Name and Addend to use for
7799 /// display purposes.
7801 /// 1. An Extern relocation will directly reference a symbol (and the data is
7802 /// then already an addend), so use that.
7803 /// 2. Otherwise the data is an offset in the object file's layout; try to find
7804 // a symbol before it in the same section, and use the offset from there.
7805 /// 3. Finally, if all that fails, fall back to an offset from the start of the
7806 /// referenced section.
7807 static void findUnwindRelocNameAddend(const MachOObjectFile *Obj,
7808 std::map<uint64_t, SymbolRef> &Symbols,
7809 const RelocationRef &Reloc, uint64_t Addr,
7810 StringRef &Name, uint64_t &Addend) {
7811 if (Reloc.getSymbol() != Obj->symbol_end()) {
7812 Name = unwrapOrError(Reloc.getSymbol()->getName(), Obj->getFileName());
7813 Addend = Addr;
7814 return;
7817 auto RE = Obj->getRelocation(Reloc.getRawDataRefImpl());
7818 SectionRef RelocSection = Obj->getAnyRelocationSection(RE);
7820 uint64_t SectionAddr = RelocSection.getAddress();
7822 auto Sym = Symbols.upper_bound(Addr);
7823 if (Sym == Symbols.begin()) {
7824 // The first symbol in the object is after this reference, the best we can
7825 // do is section-relative notation.
7826 if (Expected<StringRef> NameOrErr = RelocSection.getName())
7827 Name = *NameOrErr;
7828 else
7829 consumeError(NameOrErr.takeError());
7831 Addend = Addr - SectionAddr;
7832 return;
7835 // Go back one so that SymbolAddress <= Addr.
7836 --Sym;
7838 section_iterator SymSection =
7839 unwrapOrError(Sym->second.getSection(), Obj->getFileName());
7840 if (RelocSection == *SymSection) {
7841 // There's a valid symbol in the same section before this reference.
7842 Name = unwrapOrError(Sym->second.getName(), Obj->getFileName());
7843 Addend = Addr - Sym->first;
7844 return;
7847 // There is a symbol before this reference, but it's in a different
7848 // section. Probably not helpful to mention it, so use the section name.
7849 if (Expected<StringRef> NameOrErr = RelocSection.getName())
7850 Name = *NameOrErr;
7851 else
7852 consumeError(NameOrErr.takeError());
7854 Addend = Addr - SectionAddr;
7857 static void printUnwindRelocDest(const MachOObjectFile *Obj,
7858 std::map<uint64_t, SymbolRef> &Symbols,
7859 const RelocationRef &Reloc, uint64_t Addr) {
7860 StringRef Name;
7861 uint64_t Addend;
7863 if (!Reloc.getObject())
7864 return;
7866 findUnwindRelocNameAddend(Obj, Symbols, Reloc, Addr, Name, Addend);
7868 outs() << Name;
7869 if (Addend)
7870 outs() << " + " << format("0x%" PRIx64, Addend);
7873 static void
7874 printMachOCompactUnwindSection(const MachOObjectFile *Obj,
7875 std::map<uint64_t, SymbolRef> &Symbols,
7876 const SectionRef &CompactUnwind) {
7878 if (!Obj->isLittleEndian()) {
7879 outs() << "Skipping big-endian __compact_unwind section\n";
7880 return;
7883 bool Is64 = Obj->is64Bit();
7884 uint32_t PointerSize = Is64 ? sizeof(uint64_t) : sizeof(uint32_t);
7885 uint32_t EntrySize = 3 * PointerSize + 2 * sizeof(uint32_t);
7887 StringRef Contents =
7888 unwrapOrError(CompactUnwind.getContents(), Obj->getFileName());
7889 SmallVector<CompactUnwindEntry, 4> CompactUnwinds;
7891 // First populate the initial raw offsets, encodings and so on from the entry.
7892 for (unsigned Offset = 0; Offset < Contents.size(); Offset += EntrySize) {
7893 CompactUnwindEntry Entry(Contents, Offset, Is64);
7894 CompactUnwinds.push_back(Entry);
7897 // Next we need to look at the relocations to find out what objects are
7898 // actually being referred to.
7899 for (const RelocationRef &Reloc : CompactUnwind.relocations()) {
7900 uint64_t RelocAddress = Reloc.getOffset();
7902 uint32_t EntryIdx = RelocAddress / EntrySize;
7903 uint32_t OffsetInEntry = RelocAddress - EntryIdx * EntrySize;
7904 CompactUnwindEntry &Entry = CompactUnwinds[EntryIdx];
7906 if (OffsetInEntry == 0)
7907 Entry.FunctionReloc = Reloc;
7908 else if (OffsetInEntry == PointerSize + 2 * sizeof(uint32_t))
7909 Entry.PersonalityReloc = Reloc;
7910 else if (OffsetInEntry == 2 * PointerSize + 2 * sizeof(uint32_t))
7911 Entry.LSDAReloc = Reloc;
7912 else {
7913 outs() << "Invalid relocation in __compact_unwind section\n";
7914 return;
7918 // Finally, we're ready to print the data we've gathered.
7919 outs() << "Contents of __compact_unwind section:\n";
7920 for (auto &Entry : CompactUnwinds) {
7921 outs() << " Entry at offset "
7922 << format("0x%" PRIx32, Entry.OffsetInSection) << ":\n";
7924 // 1. Start of the region this entry applies to.
7925 outs() << " start: " << format("0x%" PRIx64,
7926 Entry.FunctionAddr) << ' ';
7927 printUnwindRelocDest(Obj, Symbols, Entry.FunctionReloc, Entry.FunctionAddr);
7928 outs() << '\n';
7930 // 2. Length of the region this entry applies to.
7931 outs() << " length: " << format("0x%" PRIx32, Entry.Length)
7932 << '\n';
7933 // 3. The 32-bit compact encoding.
7934 outs() << " compact encoding: "
7935 << format("0x%08" PRIx32, Entry.CompactEncoding) << '\n';
7937 // 4. The personality function, if present.
7938 if (Entry.PersonalityReloc.getObject()) {
7939 outs() << " personality function: "
7940 << format("0x%" PRIx64, Entry.PersonalityAddr) << ' ';
7941 printUnwindRelocDest(Obj, Symbols, Entry.PersonalityReloc,
7942 Entry.PersonalityAddr);
7943 outs() << '\n';
7946 // 5. This entry's language-specific data area.
7947 if (Entry.LSDAReloc.getObject()) {
7948 outs() << " LSDA: " << format("0x%" PRIx64,
7949 Entry.LSDAAddr) << ' ';
7950 printUnwindRelocDest(Obj, Symbols, Entry.LSDAReloc, Entry.LSDAAddr);
7951 outs() << '\n';
7956 //===----------------------------------------------------------------------===//
7957 // __unwind_info section dumping
7958 //===----------------------------------------------------------------------===//
7960 static void printRegularSecondLevelUnwindPage(StringRef PageData) {
7961 ptrdiff_t Pos = 0;
7962 uint32_t Kind = readNext<uint32_t>(PageData, Pos);
7963 (void)Kind;
7964 assert(Kind == 2 && "kind for a regular 2nd level index should be 2");
7966 uint16_t EntriesStart = readNext<uint16_t>(PageData, Pos);
7967 uint16_t NumEntries = readNext<uint16_t>(PageData, Pos);
7969 Pos = EntriesStart;
7970 for (unsigned i = 0; i < NumEntries; ++i) {
7971 uint32_t FunctionOffset = readNext<uint32_t>(PageData, Pos);
7972 uint32_t Encoding = readNext<uint32_t>(PageData, Pos);
7974 outs() << " [" << i << "]: "
7975 << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
7976 << ", "
7977 << "encoding=" << format("0x%08" PRIx32, Encoding) << '\n';
7981 static void printCompressedSecondLevelUnwindPage(
7982 StringRef PageData, uint32_t FunctionBase,
7983 const SmallVectorImpl<uint32_t> &CommonEncodings) {
7984 ptrdiff_t Pos = 0;
7985 uint32_t Kind = readNext<uint32_t>(PageData, Pos);
7986 (void)Kind;
7987 assert(Kind == 3 && "kind for a compressed 2nd level index should be 3");
7989 uint16_t EntriesStart = readNext<uint16_t>(PageData, Pos);
7990 uint16_t NumEntries = readNext<uint16_t>(PageData, Pos);
7992 uint16_t EncodingsStart = readNext<uint16_t>(PageData, Pos);
7993 readNext<uint16_t>(PageData, Pos);
7994 StringRef PageEncodings = PageData.substr(EncodingsStart, StringRef::npos);
7996 Pos = EntriesStart;
7997 for (unsigned i = 0; i < NumEntries; ++i) {
7998 uint32_t Entry = readNext<uint32_t>(PageData, Pos);
7999 uint32_t FunctionOffset = FunctionBase + (Entry & 0xffffff);
8000 uint32_t EncodingIdx = Entry >> 24;
8002 uint32_t Encoding;
8003 if (EncodingIdx < CommonEncodings.size())
8004 Encoding = CommonEncodings[EncodingIdx];
8005 else
8006 Encoding = read<uint32_t>(PageEncodings,
8007 sizeof(uint32_t) *
8008 (EncodingIdx - CommonEncodings.size()));
8010 outs() << " [" << i << "]: "
8011 << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
8012 << ", "
8013 << "encoding[" << EncodingIdx
8014 << "]=" << format("0x%08" PRIx32, Encoding) << '\n';
8018 static void printMachOUnwindInfoSection(const MachOObjectFile *Obj,
8019 std::map<uint64_t, SymbolRef> &Symbols,
8020 const SectionRef &UnwindInfo) {
8022 if (!Obj->isLittleEndian()) {
8023 outs() << "Skipping big-endian __unwind_info section\n";
8024 return;
8027 outs() << "Contents of __unwind_info section:\n";
8029 StringRef Contents =
8030 unwrapOrError(UnwindInfo.getContents(), Obj->getFileName());
8031 ptrdiff_t Pos = 0;
8033 //===----------------------------------
8034 // Section header
8035 //===----------------------------------
8037 uint32_t Version = readNext<uint32_t>(Contents, Pos);
8038 outs() << " Version: "
8039 << format("0x%" PRIx32, Version) << '\n';
8040 if (Version != 1) {
8041 outs() << " Skipping section with unknown version\n";
8042 return;
8045 uint32_t CommonEncodingsStart = readNext<uint32_t>(Contents, Pos);
8046 outs() << " Common encodings array section offset: "
8047 << format("0x%" PRIx32, CommonEncodingsStart) << '\n';
8048 uint32_t NumCommonEncodings = readNext<uint32_t>(Contents, Pos);
8049 outs() << " Number of common encodings in array: "
8050 << format("0x%" PRIx32, NumCommonEncodings) << '\n';
8052 uint32_t PersonalitiesStart = readNext<uint32_t>(Contents, Pos);
8053 outs() << " Personality function array section offset: "
8054 << format("0x%" PRIx32, PersonalitiesStart) << '\n';
8055 uint32_t NumPersonalities = readNext<uint32_t>(Contents, Pos);
8056 outs() << " Number of personality functions in array: "
8057 << format("0x%" PRIx32, NumPersonalities) << '\n';
8059 uint32_t IndicesStart = readNext<uint32_t>(Contents, Pos);
8060 outs() << " Index array section offset: "
8061 << format("0x%" PRIx32, IndicesStart) << '\n';
8062 uint32_t NumIndices = readNext<uint32_t>(Contents, Pos);
8063 outs() << " Number of indices in array: "
8064 << format("0x%" PRIx32, NumIndices) << '\n';
8066 //===----------------------------------
8067 // A shared list of common encodings
8068 //===----------------------------------
8070 // These occupy indices in the range [0, N] whenever an encoding is referenced
8071 // from a compressed 2nd level index table. In practice the linker only
8072 // creates ~128 of these, so that indices are available to embed encodings in
8073 // the 2nd level index.
8075 SmallVector<uint32_t, 64> CommonEncodings;
8076 outs() << " Common encodings: (count = " << NumCommonEncodings << ")\n";
8077 Pos = CommonEncodingsStart;
8078 for (unsigned i = 0; i < NumCommonEncodings; ++i) {
8079 uint32_t Encoding = readNext<uint32_t>(Contents, Pos);
8080 CommonEncodings.push_back(Encoding);
8082 outs() << " encoding[" << i << "]: " << format("0x%08" PRIx32, Encoding)
8083 << '\n';
8086 //===----------------------------------
8087 // Personality functions used in this executable
8088 //===----------------------------------
8090 // There should be only a handful of these (one per source language,
8091 // roughly). Particularly since they only get 2 bits in the compact encoding.
8093 outs() << " Personality functions: (count = " << NumPersonalities << ")\n";
8094 Pos = PersonalitiesStart;
8095 for (unsigned i = 0; i < NumPersonalities; ++i) {
8096 uint32_t PersonalityFn = readNext<uint32_t>(Contents, Pos);
8097 outs() << " personality[" << i + 1
8098 << "]: " << format("0x%08" PRIx32, PersonalityFn) << '\n';
8101 //===----------------------------------
8102 // The level 1 index entries
8103 //===----------------------------------
8105 // These specify an approximate place to start searching for the more detailed
8106 // information, sorted by PC.
8108 struct IndexEntry {
8109 uint32_t FunctionOffset;
8110 uint32_t SecondLevelPageStart;
8111 uint32_t LSDAStart;
8114 SmallVector<IndexEntry, 4> IndexEntries;
8116 outs() << " Top level indices: (count = " << NumIndices << ")\n";
8117 Pos = IndicesStart;
8118 for (unsigned i = 0; i < NumIndices; ++i) {
8119 IndexEntry Entry;
8121 Entry.FunctionOffset = readNext<uint32_t>(Contents, Pos);
8122 Entry.SecondLevelPageStart = readNext<uint32_t>(Contents, Pos);
8123 Entry.LSDAStart = readNext<uint32_t>(Contents, Pos);
8124 IndexEntries.push_back(Entry);
8126 outs() << " [" << i << "]: "
8127 << "function offset=" << format("0x%08" PRIx32, Entry.FunctionOffset)
8128 << ", "
8129 << "2nd level page offset="
8130 << format("0x%08" PRIx32, Entry.SecondLevelPageStart) << ", "
8131 << "LSDA offset=" << format("0x%08" PRIx32, Entry.LSDAStart) << '\n';
8134 //===----------------------------------
8135 // Next come the LSDA tables
8136 //===----------------------------------
8138 // The LSDA layout is rather implicit: it's a contiguous array of entries from
8139 // the first top-level index's LSDAOffset to the last (sentinel).
8141 outs() << " LSDA descriptors:\n";
8142 Pos = IndexEntries[0].LSDAStart;
8143 const uint32_t LSDASize = 2 * sizeof(uint32_t);
8144 int NumLSDAs =
8145 (IndexEntries.back().LSDAStart - IndexEntries[0].LSDAStart) / LSDASize;
8147 for (int i = 0; i < NumLSDAs; ++i) {
8148 uint32_t FunctionOffset = readNext<uint32_t>(Contents, Pos);
8149 uint32_t LSDAOffset = readNext<uint32_t>(Contents, Pos);
8150 outs() << " [" << i << "]: "
8151 << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
8152 << ", "
8153 << "LSDA offset=" << format("0x%08" PRIx32, LSDAOffset) << '\n';
8156 //===----------------------------------
8157 // Finally, the 2nd level indices
8158 //===----------------------------------
8160 // Generally these are 4K in size, and have 2 possible forms:
8161 // + Regular stores up to 511 entries with disparate encodings
8162 // + Compressed stores up to 1021 entries if few enough compact encoding
8163 // values are used.
8164 outs() << " Second level indices:\n";
8165 for (unsigned i = 0; i < IndexEntries.size() - 1; ++i) {
8166 // The final sentinel top-level index has no associated 2nd level page
8167 if (IndexEntries[i].SecondLevelPageStart == 0)
8168 break;
8170 outs() << " Second level index[" << i << "]: "
8171 << "offset in section="
8172 << format("0x%08" PRIx32, IndexEntries[i].SecondLevelPageStart)
8173 << ", "
8174 << "base function offset="
8175 << format("0x%08" PRIx32, IndexEntries[i].FunctionOffset) << '\n';
8177 Pos = IndexEntries[i].SecondLevelPageStart;
8178 if (Pos + sizeof(uint32_t) > Contents.size()) {
8179 outs() << "warning: invalid offset for second level page: " << Pos << '\n';
8180 continue;
8183 uint32_t Kind =
8184 *reinterpret_cast<const support::ulittle32_t *>(Contents.data() + Pos);
8185 if (Kind == 2)
8186 printRegularSecondLevelUnwindPage(Contents.substr(Pos, 4096));
8187 else if (Kind == 3)
8188 printCompressedSecondLevelUnwindPage(Contents.substr(Pos, 4096),
8189 IndexEntries[i].FunctionOffset,
8190 CommonEncodings);
8191 else
8192 outs() << " Skipping 2nd level page with unknown kind " << Kind
8193 << '\n';
8197 void printMachOUnwindInfo(const MachOObjectFile *Obj) {
8198 std::map<uint64_t, SymbolRef> Symbols;
8199 for (const SymbolRef &SymRef : Obj->symbols()) {
8200 // Discard any undefined or absolute symbols. They're not going to take part
8201 // in the convenience lookup for unwind info and just take up resources.
8202 auto SectOrErr = SymRef.getSection();
8203 if (!SectOrErr) {
8204 // TODO: Actually report errors helpfully.
8205 consumeError(SectOrErr.takeError());
8206 continue;
8208 section_iterator Section = *SectOrErr;
8209 if (Section == Obj->section_end())
8210 continue;
8212 uint64_t Addr = SymRef.getValue();
8213 Symbols.insert(std::make_pair(Addr, SymRef));
8216 for (const SectionRef &Section : Obj->sections()) {
8217 StringRef SectName;
8218 if (Expected<StringRef> NameOrErr = Section.getName())
8219 SectName = *NameOrErr;
8220 else
8221 consumeError(NameOrErr.takeError());
8223 if (SectName == "__compact_unwind")
8224 printMachOCompactUnwindSection(Obj, Symbols, Section);
8225 else if (SectName == "__unwind_info")
8226 printMachOUnwindInfoSection(Obj, Symbols, Section);
8230 static void PrintMachHeader(uint32_t magic, uint32_t cputype,
8231 uint32_t cpusubtype, uint32_t filetype,
8232 uint32_t ncmds, uint32_t sizeofcmds, uint32_t flags,
8233 bool verbose) {
8234 outs() << "Mach header\n";
8235 outs() << " magic cputype cpusubtype caps filetype ncmds "
8236 "sizeofcmds flags\n";
8237 if (verbose) {
8238 if (magic == MachO::MH_MAGIC)
8239 outs() << " MH_MAGIC";
8240 else if (magic == MachO::MH_MAGIC_64)
8241 outs() << "MH_MAGIC_64";
8242 else
8243 outs() << format(" 0x%08" PRIx32, magic);
8244 switch (cputype) {
8245 case MachO::CPU_TYPE_I386:
8246 outs() << " I386";
8247 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
8248 case MachO::CPU_SUBTYPE_I386_ALL:
8249 outs() << " ALL";
8250 break;
8251 default:
8252 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
8253 break;
8255 break;
8256 case MachO::CPU_TYPE_X86_64:
8257 outs() << " X86_64";
8258 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
8259 case MachO::CPU_SUBTYPE_X86_64_ALL:
8260 outs() << " ALL";
8261 break;
8262 case MachO::CPU_SUBTYPE_X86_64_H:
8263 outs() << " Haswell";
8264 break;
8265 default:
8266 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
8267 break;
8269 break;
8270 case MachO::CPU_TYPE_ARM:
8271 outs() << " ARM";
8272 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
8273 case MachO::CPU_SUBTYPE_ARM_ALL:
8274 outs() << " ALL";
8275 break;
8276 case MachO::CPU_SUBTYPE_ARM_V4T:
8277 outs() << " V4T";
8278 break;
8279 case MachO::CPU_SUBTYPE_ARM_V5TEJ:
8280 outs() << " V5TEJ";
8281 break;
8282 case MachO::CPU_SUBTYPE_ARM_XSCALE:
8283 outs() << " XSCALE";
8284 break;
8285 case MachO::CPU_SUBTYPE_ARM_V6:
8286 outs() << " V6";
8287 break;
8288 case MachO::CPU_SUBTYPE_ARM_V6M:
8289 outs() << " V6M";
8290 break;
8291 case MachO::CPU_SUBTYPE_ARM_V7:
8292 outs() << " V7";
8293 break;
8294 case MachO::CPU_SUBTYPE_ARM_V7EM:
8295 outs() << " V7EM";
8296 break;
8297 case MachO::CPU_SUBTYPE_ARM_V7K:
8298 outs() << " V7K";
8299 break;
8300 case MachO::CPU_SUBTYPE_ARM_V7M:
8301 outs() << " V7M";
8302 break;
8303 case MachO::CPU_SUBTYPE_ARM_V7S:
8304 outs() << " V7S";
8305 break;
8306 default:
8307 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
8308 break;
8310 break;
8311 case MachO::CPU_TYPE_ARM64:
8312 outs() << " ARM64";
8313 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
8314 case MachO::CPU_SUBTYPE_ARM64_ALL:
8315 outs() << " ALL";
8316 break;
8317 case MachO::CPU_SUBTYPE_ARM64E:
8318 outs() << " E";
8319 break;
8320 default:
8321 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
8322 break;
8324 break;
8325 case MachO::CPU_TYPE_ARM64_32:
8326 outs() << " ARM64_32";
8327 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
8328 case MachO::CPU_SUBTYPE_ARM64_32_V8:
8329 outs() << " V8";
8330 break;
8331 default:
8332 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
8333 break;
8335 break;
8336 case MachO::CPU_TYPE_POWERPC:
8337 outs() << " PPC";
8338 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
8339 case MachO::CPU_SUBTYPE_POWERPC_ALL:
8340 outs() << " ALL";
8341 break;
8342 default:
8343 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
8344 break;
8346 break;
8347 case MachO::CPU_TYPE_POWERPC64:
8348 outs() << " PPC64";
8349 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
8350 case MachO::CPU_SUBTYPE_POWERPC_ALL:
8351 outs() << " ALL";
8352 break;
8353 default:
8354 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
8355 break;
8357 break;
8358 default:
8359 outs() << format(" %7d", cputype);
8360 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
8361 break;
8363 if ((cpusubtype & MachO::CPU_SUBTYPE_MASK) == MachO::CPU_SUBTYPE_LIB64) {
8364 outs() << " LIB64";
8365 } else {
8366 outs() << format(" 0x%02" PRIx32,
8367 (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24);
8369 switch (filetype) {
8370 case MachO::MH_OBJECT:
8371 outs() << " OBJECT";
8372 break;
8373 case MachO::MH_EXECUTE:
8374 outs() << " EXECUTE";
8375 break;
8376 case MachO::MH_FVMLIB:
8377 outs() << " FVMLIB";
8378 break;
8379 case MachO::MH_CORE:
8380 outs() << " CORE";
8381 break;
8382 case MachO::MH_PRELOAD:
8383 outs() << " PRELOAD";
8384 break;
8385 case MachO::MH_DYLIB:
8386 outs() << " DYLIB";
8387 break;
8388 case MachO::MH_DYLIB_STUB:
8389 outs() << " DYLIB_STUB";
8390 break;
8391 case MachO::MH_DYLINKER:
8392 outs() << " DYLINKER";
8393 break;
8394 case MachO::MH_BUNDLE:
8395 outs() << " BUNDLE";
8396 break;
8397 case MachO::MH_DSYM:
8398 outs() << " DSYM";
8399 break;
8400 case MachO::MH_KEXT_BUNDLE:
8401 outs() << " KEXTBUNDLE";
8402 break;
8403 default:
8404 outs() << format(" %10u", filetype);
8405 break;
8407 outs() << format(" %5u", ncmds);
8408 outs() << format(" %10u", sizeofcmds);
8409 uint32_t f = flags;
8410 if (f & MachO::MH_NOUNDEFS) {
8411 outs() << " NOUNDEFS";
8412 f &= ~MachO::MH_NOUNDEFS;
8414 if (f & MachO::MH_INCRLINK) {
8415 outs() << " INCRLINK";
8416 f &= ~MachO::MH_INCRLINK;
8418 if (f & MachO::MH_DYLDLINK) {
8419 outs() << " DYLDLINK";
8420 f &= ~MachO::MH_DYLDLINK;
8422 if (f & MachO::MH_BINDATLOAD) {
8423 outs() << " BINDATLOAD";
8424 f &= ~MachO::MH_BINDATLOAD;
8426 if (f & MachO::MH_PREBOUND) {
8427 outs() << " PREBOUND";
8428 f &= ~MachO::MH_PREBOUND;
8430 if (f & MachO::MH_SPLIT_SEGS) {
8431 outs() << " SPLIT_SEGS";
8432 f &= ~MachO::MH_SPLIT_SEGS;
8434 if (f & MachO::MH_LAZY_INIT) {
8435 outs() << " LAZY_INIT";
8436 f &= ~MachO::MH_LAZY_INIT;
8438 if (f & MachO::MH_TWOLEVEL) {
8439 outs() << " TWOLEVEL";
8440 f &= ~MachO::MH_TWOLEVEL;
8442 if (f & MachO::MH_FORCE_FLAT) {
8443 outs() << " FORCE_FLAT";
8444 f &= ~MachO::MH_FORCE_FLAT;
8446 if (f & MachO::MH_NOMULTIDEFS) {
8447 outs() << " NOMULTIDEFS";
8448 f &= ~MachO::MH_NOMULTIDEFS;
8450 if (f & MachO::MH_NOFIXPREBINDING) {
8451 outs() << " NOFIXPREBINDING";
8452 f &= ~MachO::MH_NOFIXPREBINDING;
8454 if (f & MachO::MH_PREBINDABLE) {
8455 outs() << " PREBINDABLE";
8456 f &= ~MachO::MH_PREBINDABLE;
8458 if (f & MachO::MH_ALLMODSBOUND) {
8459 outs() << " ALLMODSBOUND";
8460 f &= ~MachO::MH_ALLMODSBOUND;
8462 if (f & MachO::MH_SUBSECTIONS_VIA_SYMBOLS) {
8463 outs() << " SUBSECTIONS_VIA_SYMBOLS";
8464 f &= ~MachO::MH_SUBSECTIONS_VIA_SYMBOLS;
8466 if (f & MachO::MH_CANONICAL) {
8467 outs() << " CANONICAL";
8468 f &= ~MachO::MH_CANONICAL;
8470 if (f & MachO::MH_WEAK_DEFINES) {
8471 outs() << " WEAK_DEFINES";
8472 f &= ~MachO::MH_WEAK_DEFINES;
8474 if (f & MachO::MH_BINDS_TO_WEAK) {
8475 outs() << " BINDS_TO_WEAK";
8476 f &= ~MachO::MH_BINDS_TO_WEAK;
8478 if (f & MachO::MH_ALLOW_STACK_EXECUTION) {
8479 outs() << " ALLOW_STACK_EXECUTION";
8480 f &= ~MachO::MH_ALLOW_STACK_EXECUTION;
8482 if (f & MachO::MH_DEAD_STRIPPABLE_DYLIB) {
8483 outs() << " DEAD_STRIPPABLE_DYLIB";
8484 f &= ~MachO::MH_DEAD_STRIPPABLE_DYLIB;
8486 if (f & MachO::MH_PIE) {
8487 outs() << " PIE";
8488 f &= ~MachO::MH_PIE;
8490 if (f & MachO::MH_NO_REEXPORTED_DYLIBS) {
8491 outs() << " NO_REEXPORTED_DYLIBS";
8492 f &= ~MachO::MH_NO_REEXPORTED_DYLIBS;
8494 if (f & MachO::MH_HAS_TLV_DESCRIPTORS) {
8495 outs() << " MH_HAS_TLV_DESCRIPTORS";
8496 f &= ~MachO::MH_HAS_TLV_DESCRIPTORS;
8498 if (f & MachO::MH_NO_HEAP_EXECUTION) {
8499 outs() << " MH_NO_HEAP_EXECUTION";
8500 f &= ~MachO::MH_NO_HEAP_EXECUTION;
8502 if (f & MachO::MH_APP_EXTENSION_SAFE) {
8503 outs() << " APP_EXTENSION_SAFE";
8504 f &= ~MachO::MH_APP_EXTENSION_SAFE;
8506 if (f & MachO::MH_NLIST_OUTOFSYNC_WITH_DYLDINFO) {
8507 outs() << " NLIST_OUTOFSYNC_WITH_DYLDINFO";
8508 f &= ~MachO::MH_NLIST_OUTOFSYNC_WITH_DYLDINFO;
8510 if (f != 0 || flags == 0)
8511 outs() << format(" 0x%08" PRIx32, f);
8512 } else {
8513 outs() << format(" 0x%08" PRIx32, magic);
8514 outs() << format(" %7d", cputype);
8515 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
8516 outs() << format(" 0x%02" PRIx32,
8517 (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24);
8518 outs() << format(" %10u", filetype);
8519 outs() << format(" %5u", ncmds);
8520 outs() << format(" %10u", sizeofcmds);
8521 outs() << format(" 0x%08" PRIx32, flags);
8523 outs() << "\n";
8526 static void PrintSegmentCommand(uint32_t cmd, uint32_t cmdsize,
8527 StringRef SegName, uint64_t vmaddr,
8528 uint64_t vmsize, uint64_t fileoff,
8529 uint64_t filesize, uint32_t maxprot,
8530 uint32_t initprot, uint32_t nsects,
8531 uint32_t flags, uint32_t object_size,
8532 bool verbose) {
8533 uint64_t expected_cmdsize;
8534 if (cmd == MachO::LC_SEGMENT) {
8535 outs() << " cmd LC_SEGMENT\n";
8536 expected_cmdsize = nsects;
8537 expected_cmdsize *= sizeof(struct MachO::section);
8538 expected_cmdsize += sizeof(struct MachO::segment_command);
8539 } else {
8540 outs() << " cmd LC_SEGMENT_64\n";
8541 expected_cmdsize = nsects;
8542 expected_cmdsize *= sizeof(struct MachO::section_64);
8543 expected_cmdsize += sizeof(struct MachO::segment_command_64);
8545 outs() << " cmdsize " << cmdsize;
8546 if (cmdsize != expected_cmdsize)
8547 outs() << " Inconsistent size\n";
8548 else
8549 outs() << "\n";
8550 outs() << " segname " << SegName << "\n";
8551 if (cmd == MachO::LC_SEGMENT_64) {
8552 outs() << " vmaddr " << format("0x%016" PRIx64, vmaddr) << "\n";
8553 outs() << " vmsize " << format("0x%016" PRIx64, vmsize) << "\n";
8554 } else {
8555 outs() << " vmaddr " << format("0x%08" PRIx64, vmaddr) << "\n";
8556 outs() << " vmsize " << format("0x%08" PRIx64, vmsize) << "\n";
8558 outs() << " fileoff " << fileoff;
8559 if (fileoff > object_size)
8560 outs() << " (past end of file)\n";
8561 else
8562 outs() << "\n";
8563 outs() << " filesize " << filesize;
8564 if (fileoff + filesize > object_size)
8565 outs() << " (past end of file)\n";
8566 else
8567 outs() << "\n";
8568 if (verbose) {
8569 if ((maxprot &
8570 ~(MachO::VM_PROT_READ | MachO::VM_PROT_WRITE |
8571 MachO::VM_PROT_EXECUTE)) != 0)
8572 outs() << " maxprot ?" << format("0x%08" PRIx32, maxprot) << "\n";
8573 else {
8574 outs() << " maxprot ";
8575 outs() << ((maxprot & MachO::VM_PROT_READ) ? "r" : "-");
8576 outs() << ((maxprot & MachO::VM_PROT_WRITE) ? "w" : "-");
8577 outs() << ((maxprot & MachO::VM_PROT_EXECUTE) ? "x\n" : "-\n");
8579 if ((initprot &
8580 ~(MachO::VM_PROT_READ | MachO::VM_PROT_WRITE |
8581 MachO::VM_PROT_EXECUTE)) != 0)
8582 outs() << " initprot ?" << format("0x%08" PRIx32, initprot) << "\n";
8583 else {
8584 outs() << " initprot ";
8585 outs() << ((initprot & MachO::VM_PROT_READ) ? "r" : "-");
8586 outs() << ((initprot & MachO::VM_PROT_WRITE) ? "w" : "-");
8587 outs() << ((initprot & MachO::VM_PROT_EXECUTE) ? "x\n" : "-\n");
8589 } else {
8590 outs() << " maxprot " << format("0x%08" PRIx32, maxprot) << "\n";
8591 outs() << " initprot " << format("0x%08" PRIx32, initprot) << "\n";
8593 outs() << " nsects " << nsects << "\n";
8594 if (verbose) {
8595 outs() << " flags";
8596 if (flags == 0)
8597 outs() << " (none)\n";
8598 else {
8599 if (flags & MachO::SG_HIGHVM) {
8600 outs() << " HIGHVM";
8601 flags &= ~MachO::SG_HIGHVM;
8603 if (flags & MachO::SG_FVMLIB) {
8604 outs() << " FVMLIB";
8605 flags &= ~MachO::SG_FVMLIB;
8607 if (flags & MachO::SG_NORELOC) {
8608 outs() << " NORELOC";
8609 flags &= ~MachO::SG_NORELOC;
8611 if (flags & MachO::SG_PROTECTED_VERSION_1) {
8612 outs() << " PROTECTED_VERSION_1";
8613 flags &= ~MachO::SG_PROTECTED_VERSION_1;
8615 if (flags)
8616 outs() << format(" 0x%08" PRIx32, flags) << " (unknown flags)\n";
8617 else
8618 outs() << "\n";
8620 } else {
8621 outs() << " flags " << format("0x%" PRIx32, flags) << "\n";
8625 static void PrintSection(const char *sectname, const char *segname,
8626 uint64_t addr, uint64_t size, uint32_t offset,
8627 uint32_t align, uint32_t reloff, uint32_t nreloc,
8628 uint32_t flags, uint32_t reserved1, uint32_t reserved2,
8629 uint32_t cmd, const char *sg_segname,
8630 uint32_t filetype, uint32_t object_size,
8631 bool verbose) {
8632 outs() << "Section\n";
8633 outs() << " sectname " << format("%.16s\n", sectname);
8634 outs() << " segname " << format("%.16s", segname);
8635 if (filetype != MachO::MH_OBJECT && strncmp(sg_segname, segname, 16) != 0)
8636 outs() << " (does not match segment)\n";
8637 else
8638 outs() << "\n";
8639 if (cmd == MachO::LC_SEGMENT_64) {
8640 outs() << " addr " << format("0x%016" PRIx64, addr) << "\n";
8641 outs() << " size " << format("0x%016" PRIx64, size);
8642 } else {
8643 outs() << " addr " << format("0x%08" PRIx64, addr) << "\n";
8644 outs() << " size " << format("0x%08" PRIx64, size);
8646 if ((flags & MachO::S_ZEROFILL) != 0 && offset + size > object_size)
8647 outs() << " (past end of file)\n";
8648 else
8649 outs() << "\n";
8650 outs() << " offset " << offset;
8651 if (offset > object_size)
8652 outs() << " (past end of file)\n";
8653 else
8654 outs() << "\n";
8655 uint32_t align_shifted = 1 << align;
8656 outs() << " align 2^" << align << " (" << align_shifted << ")\n";
8657 outs() << " reloff " << reloff;
8658 if (reloff > object_size)
8659 outs() << " (past end of file)\n";
8660 else
8661 outs() << "\n";
8662 outs() << " nreloc " << nreloc;
8663 if (reloff + nreloc * sizeof(struct MachO::relocation_info) > object_size)
8664 outs() << " (past end of file)\n";
8665 else
8666 outs() << "\n";
8667 uint32_t section_type = flags & MachO::SECTION_TYPE;
8668 if (verbose) {
8669 outs() << " type";
8670 if (section_type == MachO::S_REGULAR)
8671 outs() << " S_REGULAR\n";
8672 else if (section_type == MachO::S_ZEROFILL)
8673 outs() << " S_ZEROFILL\n";
8674 else if (section_type == MachO::S_CSTRING_LITERALS)
8675 outs() << " S_CSTRING_LITERALS\n";
8676 else if (section_type == MachO::S_4BYTE_LITERALS)
8677 outs() << " S_4BYTE_LITERALS\n";
8678 else if (section_type == MachO::S_8BYTE_LITERALS)
8679 outs() << " S_8BYTE_LITERALS\n";
8680 else if (section_type == MachO::S_16BYTE_LITERALS)
8681 outs() << " S_16BYTE_LITERALS\n";
8682 else if (section_type == MachO::S_LITERAL_POINTERS)
8683 outs() << " S_LITERAL_POINTERS\n";
8684 else if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS)
8685 outs() << " S_NON_LAZY_SYMBOL_POINTERS\n";
8686 else if (section_type == MachO::S_LAZY_SYMBOL_POINTERS)
8687 outs() << " S_LAZY_SYMBOL_POINTERS\n";
8688 else if (section_type == MachO::S_SYMBOL_STUBS)
8689 outs() << " S_SYMBOL_STUBS\n";
8690 else if (section_type == MachO::S_MOD_INIT_FUNC_POINTERS)
8691 outs() << " S_MOD_INIT_FUNC_POINTERS\n";
8692 else if (section_type == MachO::S_MOD_TERM_FUNC_POINTERS)
8693 outs() << " S_MOD_TERM_FUNC_POINTERS\n";
8694 else if (section_type == MachO::S_COALESCED)
8695 outs() << " S_COALESCED\n";
8696 else if (section_type == MachO::S_INTERPOSING)
8697 outs() << " S_INTERPOSING\n";
8698 else if (section_type == MachO::S_DTRACE_DOF)
8699 outs() << " S_DTRACE_DOF\n";
8700 else if (section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS)
8701 outs() << " S_LAZY_DYLIB_SYMBOL_POINTERS\n";
8702 else if (section_type == MachO::S_THREAD_LOCAL_REGULAR)
8703 outs() << " S_THREAD_LOCAL_REGULAR\n";
8704 else if (section_type == MachO::S_THREAD_LOCAL_ZEROFILL)
8705 outs() << " S_THREAD_LOCAL_ZEROFILL\n";
8706 else if (section_type == MachO::S_THREAD_LOCAL_VARIABLES)
8707 outs() << " S_THREAD_LOCAL_VARIABLES\n";
8708 else if (section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS)
8709 outs() << " S_THREAD_LOCAL_VARIABLE_POINTERS\n";
8710 else if (section_type == MachO::S_THREAD_LOCAL_INIT_FUNCTION_POINTERS)
8711 outs() << " S_THREAD_LOCAL_INIT_FUNCTION_POINTERS\n";
8712 else
8713 outs() << format("0x%08" PRIx32, section_type) << "\n";
8714 outs() << "attributes";
8715 uint32_t section_attributes = flags & MachO::SECTION_ATTRIBUTES;
8716 if (section_attributes & MachO::S_ATTR_PURE_INSTRUCTIONS)
8717 outs() << " PURE_INSTRUCTIONS";
8718 if (section_attributes & MachO::S_ATTR_NO_TOC)
8719 outs() << " NO_TOC";
8720 if (section_attributes & MachO::S_ATTR_STRIP_STATIC_SYMS)
8721 outs() << " STRIP_STATIC_SYMS";
8722 if (section_attributes & MachO::S_ATTR_NO_DEAD_STRIP)
8723 outs() << " NO_DEAD_STRIP";
8724 if (section_attributes & MachO::S_ATTR_LIVE_SUPPORT)
8725 outs() << " LIVE_SUPPORT";
8726 if (section_attributes & MachO::S_ATTR_SELF_MODIFYING_CODE)
8727 outs() << " SELF_MODIFYING_CODE";
8728 if (section_attributes & MachO::S_ATTR_DEBUG)
8729 outs() << " DEBUG";
8730 if (section_attributes & MachO::S_ATTR_SOME_INSTRUCTIONS)
8731 outs() << " SOME_INSTRUCTIONS";
8732 if (section_attributes & MachO::S_ATTR_EXT_RELOC)
8733 outs() << " EXT_RELOC";
8734 if (section_attributes & MachO::S_ATTR_LOC_RELOC)
8735 outs() << " LOC_RELOC";
8736 if (section_attributes == 0)
8737 outs() << " (none)";
8738 outs() << "\n";
8739 } else
8740 outs() << " flags " << format("0x%08" PRIx32, flags) << "\n";
8741 outs() << " reserved1 " << reserved1;
8742 if (section_type == MachO::S_SYMBOL_STUBS ||
8743 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
8744 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
8745 section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
8746 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS)
8747 outs() << " (index into indirect symbol table)\n";
8748 else
8749 outs() << "\n";
8750 outs() << " reserved2 " << reserved2;
8751 if (section_type == MachO::S_SYMBOL_STUBS)
8752 outs() << " (size of stubs)\n";
8753 else
8754 outs() << "\n";
8757 static void PrintSymtabLoadCommand(MachO::symtab_command st, bool Is64Bit,
8758 uint32_t object_size) {
8759 outs() << " cmd LC_SYMTAB\n";
8760 outs() << " cmdsize " << st.cmdsize;
8761 if (st.cmdsize != sizeof(struct MachO::symtab_command))
8762 outs() << " Incorrect size\n";
8763 else
8764 outs() << "\n";
8765 outs() << " symoff " << st.symoff;
8766 if (st.symoff > object_size)
8767 outs() << " (past end of file)\n";
8768 else
8769 outs() << "\n";
8770 outs() << " nsyms " << st.nsyms;
8771 uint64_t big_size;
8772 if (Is64Bit) {
8773 big_size = st.nsyms;
8774 big_size *= sizeof(struct MachO::nlist_64);
8775 big_size += st.symoff;
8776 if (big_size > object_size)
8777 outs() << " (past end of file)\n";
8778 else
8779 outs() << "\n";
8780 } else {
8781 big_size = st.nsyms;
8782 big_size *= sizeof(struct MachO::nlist);
8783 big_size += st.symoff;
8784 if (big_size > object_size)
8785 outs() << " (past end of file)\n";
8786 else
8787 outs() << "\n";
8789 outs() << " stroff " << st.stroff;
8790 if (st.stroff > object_size)
8791 outs() << " (past end of file)\n";
8792 else
8793 outs() << "\n";
8794 outs() << " strsize " << st.strsize;
8795 big_size = st.stroff;
8796 big_size += st.strsize;
8797 if (big_size > object_size)
8798 outs() << " (past end of file)\n";
8799 else
8800 outs() << "\n";
8803 static void PrintDysymtabLoadCommand(MachO::dysymtab_command dyst,
8804 uint32_t nsyms, uint32_t object_size,
8805 bool Is64Bit) {
8806 outs() << " cmd LC_DYSYMTAB\n";
8807 outs() << " cmdsize " << dyst.cmdsize;
8808 if (dyst.cmdsize != sizeof(struct MachO::dysymtab_command))
8809 outs() << " Incorrect size\n";
8810 else
8811 outs() << "\n";
8812 outs() << " ilocalsym " << dyst.ilocalsym;
8813 if (dyst.ilocalsym > nsyms)
8814 outs() << " (greater than the number of symbols)\n";
8815 else
8816 outs() << "\n";
8817 outs() << " nlocalsym " << dyst.nlocalsym;
8818 uint64_t big_size;
8819 big_size = dyst.ilocalsym;
8820 big_size += dyst.nlocalsym;
8821 if (big_size > nsyms)
8822 outs() << " (past the end of the symbol table)\n";
8823 else
8824 outs() << "\n";
8825 outs() << " iextdefsym " << dyst.iextdefsym;
8826 if (dyst.iextdefsym > nsyms)
8827 outs() << " (greater than the number of symbols)\n";
8828 else
8829 outs() << "\n";
8830 outs() << " nextdefsym " << dyst.nextdefsym;
8831 big_size = dyst.iextdefsym;
8832 big_size += dyst.nextdefsym;
8833 if (big_size > nsyms)
8834 outs() << " (past the end of the symbol table)\n";
8835 else
8836 outs() << "\n";
8837 outs() << " iundefsym " << dyst.iundefsym;
8838 if (dyst.iundefsym > nsyms)
8839 outs() << " (greater than the number of symbols)\n";
8840 else
8841 outs() << "\n";
8842 outs() << " nundefsym " << dyst.nundefsym;
8843 big_size = dyst.iundefsym;
8844 big_size += dyst.nundefsym;
8845 if (big_size > nsyms)
8846 outs() << " (past the end of the symbol table)\n";
8847 else
8848 outs() << "\n";
8849 outs() << " tocoff " << dyst.tocoff;
8850 if (dyst.tocoff > object_size)
8851 outs() << " (past end of file)\n";
8852 else
8853 outs() << "\n";
8854 outs() << " ntoc " << dyst.ntoc;
8855 big_size = dyst.ntoc;
8856 big_size *= sizeof(struct MachO::dylib_table_of_contents);
8857 big_size += dyst.tocoff;
8858 if (big_size > object_size)
8859 outs() << " (past end of file)\n";
8860 else
8861 outs() << "\n";
8862 outs() << " modtaboff " << dyst.modtaboff;
8863 if (dyst.modtaboff > object_size)
8864 outs() << " (past end of file)\n";
8865 else
8866 outs() << "\n";
8867 outs() << " nmodtab " << dyst.nmodtab;
8868 uint64_t modtabend;
8869 if (Is64Bit) {
8870 modtabend = dyst.nmodtab;
8871 modtabend *= sizeof(struct MachO::dylib_module_64);
8872 modtabend += dyst.modtaboff;
8873 } else {
8874 modtabend = dyst.nmodtab;
8875 modtabend *= sizeof(struct MachO::dylib_module);
8876 modtabend += dyst.modtaboff;
8878 if (modtabend > object_size)
8879 outs() << " (past end of file)\n";
8880 else
8881 outs() << "\n";
8882 outs() << " extrefsymoff " << dyst.extrefsymoff;
8883 if (dyst.extrefsymoff > object_size)
8884 outs() << " (past end of file)\n";
8885 else
8886 outs() << "\n";
8887 outs() << " nextrefsyms " << dyst.nextrefsyms;
8888 big_size = dyst.nextrefsyms;
8889 big_size *= sizeof(struct MachO::dylib_reference);
8890 big_size += dyst.extrefsymoff;
8891 if (big_size > object_size)
8892 outs() << " (past end of file)\n";
8893 else
8894 outs() << "\n";
8895 outs() << " indirectsymoff " << dyst.indirectsymoff;
8896 if (dyst.indirectsymoff > object_size)
8897 outs() << " (past end of file)\n";
8898 else
8899 outs() << "\n";
8900 outs() << " nindirectsyms " << dyst.nindirectsyms;
8901 big_size = dyst.nindirectsyms;
8902 big_size *= sizeof(uint32_t);
8903 big_size += dyst.indirectsymoff;
8904 if (big_size > object_size)
8905 outs() << " (past end of file)\n";
8906 else
8907 outs() << "\n";
8908 outs() << " extreloff " << dyst.extreloff;
8909 if (dyst.extreloff > object_size)
8910 outs() << " (past end of file)\n";
8911 else
8912 outs() << "\n";
8913 outs() << " nextrel " << dyst.nextrel;
8914 big_size = dyst.nextrel;
8915 big_size *= sizeof(struct MachO::relocation_info);
8916 big_size += dyst.extreloff;
8917 if (big_size > object_size)
8918 outs() << " (past end of file)\n";
8919 else
8920 outs() << "\n";
8921 outs() << " locreloff " << dyst.locreloff;
8922 if (dyst.locreloff > object_size)
8923 outs() << " (past end of file)\n";
8924 else
8925 outs() << "\n";
8926 outs() << " nlocrel " << dyst.nlocrel;
8927 big_size = dyst.nlocrel;
8928 big_size *= sizeof(struct MachO::relocation_info);
8929 big_size += dyst.locreloff;
8930 if (big_size > object_size)
8931 outs() << " (past end of file)\n";
8932 else
8933 outs() << "\n";
8936 static void PrintDyldInfoLoadCommand(MachO::dyld_info_command dc,
8937 uint32_t object_size) {
8938 if (dc.cmd == MachO::LC_DYLD_INFO)
8939 outs() << " cmd LC_DYLD_INFO\n";
8940 else
8941 outs() << " cmd LC_DYLD_INFO_ONLY\n";
8942 outs() << " cmdsize " << dc.cmdsize;
8943 if (dc.cmdsize != sizeof(struct MachO::dyld_info_command))
8944 outs() << " Incorrect size\n";
8945 else
8946 outs() << "\n";
8947 outs() << " rebase_off " << dc.rebase_off;
8948 if (dc.rebase_off > object_size)
8949 outs() << " (past end of file)\n";
8950 else
8951 outs() << "\n";
8952 outs() << " rebase_size " << dc.rebase_size;
8953 uint64_t big_size;
8954 big_size = dc.rebase_off;
8955 big_size += dc.rebase_size;
8956 if (big_size > object_size)
8957 outs() << " (past end of file)\n";
8958 else
8959 outs() << "\n";
8960 outs() << " bind_off " << dc.bind_off;
8961 if (dc.bind_off > object_size)
8962 outs() << " (past end of file)\n";
8963 else
8964 outs() << "\n";
8965 outs() << " bind_size " << dc.bind_size;
8966 big_size = dc.bind_off;
8967 big_size += dc.bind_size;
8968 if (big_size > object_size)
8969 outs() << " (past end of file)\n";
8970 else
8971 outs() << "\n";
8972 outs() << " weak_bind_off " << dc.weak_bind_off;
8973 if (dc.weak_bind_off > object_size)
8974 outs() << " (past end of file)\n";
8975 else
8976 outs() << "\n";
8977 outs() << " weak_bind_size " << dc.weak_bind_size;
8978 big_size = dc.weak_bind_off;
8979 big_size += dc.weak_bind_size;
8980 if (big_size > object_size)
8981 outs() << " (past end of file)\n";
8982 else
8983 outs() << "\n";
8984 outs() << " lazy_bind_off " << dc.lazy_bind_off;
8985 if (dc.lazy_bind_off > object_size)
8986 outs() << " (past end of file)\n";
8987 else
8988 outs() << "\n";
8989 outs() << " lazy_bind_size " << dc.lazy_bind_size;
8990 big_size = dc.lazy_bind_off;
8991 big_size += dc.lazy_bind_size;
8992 if (big_size > object_size)
8993 outs() << " (past end of file)\n";
8994 else
8995 outs() << "\n";
8996 outs() << " export_off " << dc.export_off;
8997 if (dc.export_off > object_size)
8998 outs() << " (past end of file)\n";
8999 else
9000 outs() << "\n";
9001 outs() << " export_size " << dc.export_size;
9002 big_size = dc.export_off;
9003 big_size += dc.export_size;
9004 if (big_size > object_size)
9005 outs() << " (past end of file)\n";
9006 else
9007 outs() << "\n";
9010 static void PrintDyldLoadCommand(MachO::dylinker_command dyld,
9011 const char *Ptr) {
9012 if (dyld.cmd == MachO::LC_ID_DYLINKER)
9013 outs() << " cmd LC_ID_DYLINKER\n";
9014 else if (dyld.cmd == MachO::LC_LOAD_DYLINKER)
9015 outs() << " cmd LC_LOAD_DYLINKER\n";
9016 else if (dyld.cmd == MachO::LC_DYLD_ENVIRONMENT)
9017 outs() << " cmd LC_DYLD_ENVIRONMENT\n";
9018 else
9019 outs() << " cmd ?(" << dyld.cmd << ")\n";
9020 outs() << " cmdsize " << dyld.cmdsize;
9021 if (dyld.cmdsize < sizeof(struct MachO::dylinker_command))
9022 outs() << " Incorrect size\n";
9023 else
9024 outs() << "\n";
9025 if (dyld.name >= dyld.cmdsize)
9026 outs() << " name ?(bad offset " << dyld.name << ")\n";
9027 else {
9028 const char *P = (const char *)(Ptr) + dyld.name;
9029 outs() << " name " << P << " (offset " << dyld.name << ")\n";
9033 static void PrintUuidLoadCommand(MachO::uuid_command uuid) {
9034 outs() << " cmd LC_UUID\n";
9035 outs() << " cmdsize " << uuid.cmdsize;
9036 if (uuid.cmdsize != sizeof(struct MachO::uuid_command))
9037 outs() << " Incorrect size\n";
9038 else
9039 outs() << "\n";
9040 outs() << " uuid ";
9041 for (int i = 0; i < 16; ++i) {
9042 outs() << format("%02" PRIX32, uuid.uuid[i]);
9043 if (i == 3 || i == 5 || i == 7 || i == 9)
9044 outs() << "-";
9046 outs() << "\n";
9049 static void PrintRpathLoadCommand(MachO::rpath_command rpath, const char *Ptr) {
9050 outs() << " cmd LC_RPATH\n";
9051 outs() << " cmdsize " << rpath.cmdsize;
9052 if (rpath.cmdsize < sizeof(struct MachO::rpath_command))
9053 outs() << " Incorrect size\n";
9054 else
9055 outs() << "\n";
9056 if (rpath.path >= rpath.cmdsize)
9057 outs() << " path ?(bad offset " << rpath.path << ")\n";
9058 else {
9059 const char *P = (const char *)(Ptr) + rpath.path;
9060 outs() << " path " << P << " (offset " << rpath.path << ")\n";
9064 static void PrintVersionMinLoadCommand(MachO::version_min_command vd) {
9065 StringRef LoadCmdName;
9066 switch (vd.cmd) {
9067 case MachO::LC_VERSION_MIN_MACOSX:
9068 LoadCmdName = "LC_VERSION_MIN_MACOSX";
9069 break;
9070 case MachO::LC_VERSION_MIN_IPHONEOS:
9071 LoadCmdName = "LC_VERSION_MIN_IPHONEOS";
9072 break;
9073 case MachO::LC_VERSION_MIN_TVOS:
9074 LoadCmdName = "LC_VERSION_MIN_TVOS";
9075 break;
9076 case MachO::LC_VERSION_MIN_WATCHOS:
9077 LoadCmdName = "LC_VERSION_MIN_WATCHOS";
9078 break;
9079 default:
9080 llvm_unreachable("Unknown version min load command");
9083 outs() << " cmd " << LoadCmdName << '\n';
9084 outs() << " cmdsize " << vd.cmdsize;
9085 if (vd.cmdsize != sizeof(struct MachO::version_min_command))
9086 outs() << " Incorrect size\n";
9087 else
9088 outs() << "\n";
9089 outs() << " version "
9090 << MachOObjectFile::getVersionMinMajor(vd, false) << "."
9091 << MachOObjectFile::getVersionMinMinor(vd, false);
9092 uint32_t Update = MachOObjectFile::getVersionMinUpdate(vd, false);
9093 if (Update != 0)
9094 outs() << "." << Update;
9095 outs() << "\n";
9096 if (vd.sdk == 0)
9097 outs() << " sdk n/a";
9098 else {
9099 outs() << " sdk "
9100 << MachOObjectFile::getVersionMinMajor(vd, true) << "."
9101 << MachOObjectFile::getVersionMinMinor(vd, true);
9103 Update = MachOObjectFile::getVersionMinUpdate(vd, true);
9104 if (Update != 0)
9105 outs() << "." << Update;
9106 outs() << "\n";
9109 static void PrintNoteLoadCommand(MachO::note_command Nt) {
9110 outs() << " cmd LC_NOTE\n";
9111 outs() << " cmdsize " << Nt.cmdsize;
9112 if (Nt.cmdsize != sizeof(struct MachO::note_command))
9113 outs() << " Incorrect size\n";
9114 else
9115 outs() << "\n";
9116 const char *d = Nt.data_owner;
9117 outs() << "data_owner " << format("%.16s\n", d);
9118 outs() << " offset " << Nt.offset << "\n";
9119 outs() << " size " << Nt.size << "\n";
9122 static void PrintBuildToolVersion(MachO::build_tool_version bv) {
9123 outs() << " tool " << MachOObjectFile::getBuildTool(bv.tool) << "\n";
9124 outs() << " version " << MachOObjectFile::getVersionString(bv.version)
9125 << "\n";
9128 static void PrintBuildVersionLoadCommand(const MachOObjectFile *obj,
9129 MachO::build_version_command bd) {
9130 outs() << " cmd LC_BUILD_VERSION\n";
9131 outs() << " cmdsize " << bd.cmdsize;
9132 if (bd.cmdsize !=
9133 sizeof(struct MachO::build_version_command) +
9134 bd.ntools * sizeof(struct MachO::build_tool_version))
9135 outs() << " Incorrect size\n";
9136 else
9137 outs() << "\n";
9138 outs() << " platform " << MachOObjectFile::getBuildPlatform(bd.platform)
9139 << "\n";
9140 if (bd.sdk)
9141 outs() << " sdk " << MachOObjectFile::getVersionString(bd.sdk)
9142 << "\n";
9143 else
9144 outs() << " sdk n/a\n";
9145 outs() << " minos " << MachOObjectFile::getVersionString(bd.minos)
9146 << "\n";
9147 outs() << " ntools " << bd.ntools << "\n";
9148 for (unsigned i = 0; i < bd.ntools; ++i) {
9149 MachO::build_tool_version bv = obj->getBuildToolVersion(i);
9150 PrintBuildToolVersion(bv);
9154 static void PrintSourceVersionCommand(MachO::source_version_command sd) {
9155 outs() << " cmd LC_SOURCE_VERSION\n";
9156 outs() << " cmdsize " << sd.cmdsize;
9157 if (sd.cmdsize != sizeof(struct MachO::source_version_command))
9158 outs() << " Incorrect size\n";
9159 else
9160 outs() << "\n";
9161 uint64_t a = (sd.version >> 40) & 0xffffff;
9162 uint64_t b = (sd.version >> 30) & 0x3ff;
9163 uint64_t c = (sd.version >> 20) & 0x3ff;
9164 uint64_t d = (sd.version >> 10) & 0x3ff;
9165 uint64_t e = sd.version & 0x3ff;
9166 outs() << " version " << a << "." << b;
9167 if (e != 0)
9168 outs() << "." << c << "." << d << "." << e;
9169 else if (d != 0)
9170 outs() << "." << c << "." << d;
9171 else if (c != 0)
9172 outs() << "." << c;
9173 outs() << "\n";
9176 static void PrintEntryPointCommand(MachO::entry_point_command ep) {
9177 outs() << " cmd LC_MAIN\n";
9178 outs() << " cmdsize " << ep.cmdsize;
9179 if (ep.cmdsize != sizeof(struct MachO::entry_point_command))
9180 outs() << " Incorrect size\n";
9181 else
9182 outs() << "\n";
9183 outs() << " entryoff " << ep.entryoff << "\n";
9184 outs() << " stacksize " << ep.stacksize << "\n";
9187 static void PrintEncryptionInfoCommand(MachO::encryption_info_command ec,
9188 uint32_t object_size) {
9189 outs() << " cmd LC_ENCRYPTION_INFO\n";
9190 outs() << " cmdsize " << ec.cmdsize;
9191 if (ec.cmdsize != sizeof(struct MachO::encryption_info_command))
9192 outs() << " Incorrect size\n";
9193 else
9194 outs() << "\n";
9195 outs() << " cryptoff " << ec.cryptoff;
9196 if (ec.cryptoff > object_size)
9197 outs() << " (past end of file)\n";
9198 else
9199 outs() << "\n";
9200 outs() << " cryptsize " << ec.cryptsize;
9201 if (ec.cryptsize > object_size)
9202 outs() << " (past end of file)\n";
9203 else
9204 outs() << "\n";
9205 outs() << " cryptid " << ec.cryptid << "\n";
9208 static void PrintEncryptionInfoCommand64(MachO::encryption_info_command_64 ec,
9209 uint32_t object_size) {
9210 outs() << " cmd LC_ENCRYPTION_INFO_64\n";
9211 outs() << " cmdsize " << ec.cmdsize;
9212 if (ec.cmdsize != sizeof(struct MachO::encryption_info_command_64))
9213 outs() << " Incorrect size\n";
9214 else
9215 outs() << "\n";
9216 outs() << " cryptoff " << ec.cryptoff;
9217 if (ec.cryptoff > object_size)
9218 outs() << " (past end of file)\n";
9219 else
9220 outs() << "\n";
9221 outs() << " cryptsize " << ec.cryptsize;
9222 if (ec.cryptsize > object_size)
9223 outs() << " (past end of file)\n";
9224 else
9225 outs() << "\n";
9226 outs() << " cryptid " << ec.cryptid << "\n";
9227 outs() << " pad " << ec.pad << "\n";
9230 static void PrintLinkerOptionCommand(MachO::linker_option_command lo,
9231 const char *Ptr) {
9232 outs() << " cmd LC_LINKER_OPTION\n";
9233 outs() << " cmdsize " << lo.cmdsize;
9234 if (lo.cmdsize < sizeof(struct MachO::linker_option_command))
9235 outs() << " Incorrect size\n";
9236 else
9237 outs() << "\n";
9238 outs() << " count " << lo.count << "\n";
9239 const char *string = Ptr + sizeof(struct MachO::linker_option_command);
9240 uint32_t left = lo.cmdsize - sizeof(struct MachO::linker_option_command);
9241 uint32_t i = 0;
9242 while (left > 0) {
9243 while (*string == '\0' && left > 0) {
9244 string++;
9245 left--;
9247 if (left > 0) {
9248 i++;
9249 outs() << " string #" << i << " " << format("%.*s\n", left, string);
9250 uint32_t NullPos = StringRef(string, left).find('\0');
9251 uint32_t len = std::min(NullPos, left) + 1;
9252 string += len;
9253 left -= len;
9256 if (lo.count != i)
9257 outs() << " count " << lo.count << " does not match number of strings "
9258 << i << "\n";
9261 static void PrintSubFrameworkCommand(MachO::sub_framework_command sub,
9262 const char *Ptr) {
9263 outs() << " cmd LC_SUB_FRAMEWORK\n";
9264 outs() << " cmdsize " << sub.cmdsize;
9265 if (sub.cmdsize < sizeof(struct MachO::sub_framework_command))
9266 outs() << " Incorrect size\n";
9267 else
9268 outs() << "\n";
9269 if (sub.umbrella < sub.cmdsize) {
9270 const char *P = Ptr + sub.umbrella;
9271 outs() << " umbrella " << P << " (offset " << sub.umbrella << ")\n";
9272 } else {
9273 outs() << " umbrella ?(bad offset " << sub.umbrella << ")\n";
9277 static void PrintSubUmbrellaCommand(MachO::sub_umbrella_command sub,
9278 const char *Ptr) {
9279 outs() << " cmd LC_SUB_UMBRELLA\n";
9280 outs() << " cmdsize " << sub.cmdsize;
9281 if (sub.cmdsize < sizeof(struct MachO::sub_umbrella_command))
9282 outs() << " Incorrect size\n";
9283 else
9284 outs() << "\n";
9285 if (sub.sub_umbrella < sub.cmdsize) {
9286 const char *P = Ptr + sub.sub_umbrella;
9287 outs() << " sub_umbrella " << P << " (offset " << sub.sub_umbrella << ")\n";
9288 } else {
9289 outs() << " sub_umbrella ?(bad offset " << sub.sub_umbrella << ")\n";
9293 static void PrintSubLibraryCommand(MachO::sub_library_command sub,
9294 const char *Ptr) {
9295 outs() << " cmd LC_SUB_LIBRARY\n";
9296 outs() << " cmdsize " << sub.cmdsize;
9297 if (sub.cmdsize < sizeof(struct MachO::sub_library_command))
9298 outs() << " Incorrect size\n";
9299 else
9300 outs() << "\n";
9301 if (sub.sub_library < sub.cmdsize) {
9302 const char *P = Ptr + sub.sub_library;
9303 outs() << " sub_library " << P << " (offset " << sub.sub_library << ")\n";
9304 } else {
9305 outs() << " sub_library ?(bad offset " << sub.sub_library << ")\n";
9309 static void PrintSubClientCommand(MachO::sub_client_command sub,
9310 const char *Ptr) {
9311 outs() << " cmd LC_SUB_CLIENT\n";
9312 outs() << " cmdsize " << sub.cmdsize;
9313 if (sub.cmdsize < sizeof(struct MachO::sub_client_command))
9314 outs() << " Incorrect size\n";
9315 else
9316 outs() << "\n";
9317 if (sub.client < sub.cmdsize) {
9318 const char *P = Ptr + sub.client;
9319 outs() << " client " << P << " (offset " << sub.client << ")\n";
9320 } else {
9321 outs() << " client ?(bad offset " << sub.client << ")\n";
9325 static void PrintRoutinesCommand(MachO::routines_command r) {
9326 outs() << " cmd LC_ROUTINES\n";
9327 outs() << " cmdsize " << r.cmdsize;
9328 if (r.cmdsize != sizeof(struct MachO::routines_command))
9329 outs() << " Incorrect size\n";
9330 else
9331 outs() << "\n";
9332 outs() << " init_address " << format("0x%08" PRIx32, r.init_address) << "\n";
9333 outs() << " init_module " << r.init_module << "\n";
9334 outs() << " reserved1 " << r.reserved1 << "\n";
9335 outs() << " reserved2 " << r.reserved2 << "\n";
9336 outs() << " reserved3 " << r.reserved3 << "\n";
9337 outs() << " reserved4 " << r.reserved4 << "\n";
9338 outs() << " reserved5 " << r.reserved5 << "\n";
9339 outs() << " reserved6 " << r.reserved6 << "\n";
9342 static void PrintRoutinesCommand64(MachO::routines_command_64 r) {
9343 outs() << " cmd LC_ROUTINES_64\n";
9344 outs() << " cmdsize " << r.cmdsize;
9345 if (r.cmdsize != sizeof(struct MachO::routines_command_64))
9346 outs() << " Incorrect size\n";
9347 else
9348 outs() << "\n";
9349 outs() << " init_address " << format("0x%016" PRIx64, r.init_address) << "\n";
9350 outs() << " init_module " << r.init_module << "\n";
9351 outs() << " reserved1 " << r.reserved1 << "\n";
9352 outs() << " reserved2 " << r.reserved2 << "\n";
9353 outs() << " reserved3 " << r.reserved3 << "\n";
9354 outs() << " reserved4 " << r.reserved4 << "\n";
9355 outs() << " reserved5 " << r.reserved5 << "\n";
9356 outs() << " reserved6 " << r.reserved6 << "\n";
9359 static void Print_x86_thread_state32_t(MachO::x86_thread_state32_t &cpu32) {
9360 outs() << "\t eax " << format("0x%08" PRIx32, cpu32.eax);
9361 outs() << " ebx " << format("0x%08" PRIx32, cpu32.ebx);
9362 outs() << " ecx " << format("0x%08" PRIx32, cpu32.ecx);
9363 outs() << " edx " << format("0x%08" PRIx32, cpu32.edx) << "\n";
9364 outs() << "\t edi " << format("0x%08" PRIx32, cpu32.edi);
9365 outs() << " esi " << format("0x%08" PRIx32, cpu32.esi);
9366 outs() << " ebp " << format("0x%08" PRIx32, cpu32.ebp);
9367 outs() << " esp " << format("0x%08" PRIx32, cpu32.esp) << "\n";
9368 outs() << "\t ss " << format("0x%08" PRIx32, cpu32.ss);
9369 outs() << " eflags " << format("0x%08" PRIx32, cpu32.eflags);
9370 outs() << " eip " << format("0x%08" PRIx32, cpu32.eip);
9371 outs() << " cs " << format("0x%08" PRIx32, cpu32.cs) << "\n";
9372 outs() << "\t ds " << format("0x%08" PRIx32, cpu32.ds);
9373 outs() << " es " << format("0x%08" PRIx32, cpu32.es);
9374 outs() << " fs " << format("0x%08" PRIx32, cpu32.fs);
9375 outs() << " gs " << format("0x%08" PRIx32, cpu32.gs) << "\n";
9378 static void Print_x86_thread_state64_t(MachO::x86_thread_state64_t &cpu64) {
9379 outs() << " rax " << format("0x%016" PRIx64, cpu64.rax);
9380 outs() << " rbx " << format("0x%016" PRIx64, cpu64.rbx);
9381 outs() << " rcx " << format("0x%016" PRIx64, cpu64.rcx) << "\n";
9382 outs() << " rdx " << format("0x%016" PRIx64, cpu64.rdx);
9383 outs() << " rdi " << format("0x%016" PRIx64, cpu64.rdi);
9384 outs() << " rsi " << format("0x%016" PRIx64, cpu64.rsi) << "\n";
9385 outs() << " rbp " << format("0x%016" PRIx64, cpu64.rbp);
9386 outs() << " rsp " << format("0x%016" PRIx64, cpu64.rsp);
9387 outs() << " r8 " << format("0x%016" PRIx64, cpu64.r8) << "\n";
9388 outs() << " r9 " << format("0x%016" PRIx64, cpu64.r9);
9389 outs() << " r10 " << format("0x%016" PRIx64, cpu64.r10);
9390 outs() << " r11 " << format("0x%016" PRIx64, cpu64.r11) << "\n";
9391 outs() << " r12 " << format("0x%016" PRIx64, cpu64.r12);
9392 outs() << " r13 " << format("0x%016" PRIx64, cpu64.r13);
9393 outs() << " r14 " << format("0x%016" PRIx64, cpu64.r14) << "\n";
9394 outs() << " r15 " << format("0x%016" PRIx64, cpu64.r15);
9395 outs() << " rip " << format("0x%016" PRIx64, cpu64.rip) << "\n";
9396 outs() << "rflags " << format("0x%016" PRIx64, cpu64.rflags);
9397 outs() << " cs " << format("0x%016" PRIx64, cpu64.cs);
9398 outs() << " fs " << format("0x%016" PRIx64, cpu64.fs) << "\n";
9399 outs() << " gs " << format("0x%016" PRIx64, cpu64.gs) << "\n";
9402 static void Print_mmst_reg(MachO::mmst_reg_t &r) {
9403 uint32_t f;
9404 outs() << "\t mmst_reg ";
9405 for (f = 0; f < 10; f++)
9406 outs() << format("%02" PRIx32, (r.mmst_reg[f] & 0xff)) << " ";
9407 outs() << "\n";
9408 outs() << "\t mmst_rsrv ";
9409 for (f = 0; f < 6; f++)
9410 outs() << format("%02" PRIx32, (r.mmst_rsrv[f] & 0xff)) << " ";
9411 outs() << "\n";
9414 static void Print_xmm_reg(MachO::xmm_reg_t &r) {
9415 uint32_t f;
9416 outs() << "\t xmm_reg ";
9417 for (f = 0; f < 16; f++)
9418 outs() << format("%02" PRIx32, (r.xmm_reg[f] & 0xff)) << " ";
9419 outs() << "\n";
9422 static void Print_x86_float_state_t(MachO::x86_float_state64_t &fpu) {
9423 outs() << "\t fpu_reserved[0] " << fpu.fpu_reserved[0];
9424 outs() << " fpu_reserved[1] " << fpu.fpu_reserved[1] << "\n";
9425 outs() << "\t control: invalid " << fpu.fpu_fcw.invalid;
9426 outs() << " denorm " << fpu.fpu_fcw.denorm;
9427 outs() << " zdiv " << fpu.fpu_fcw.zdiv;
9428 outs() << " ovrfl " << fpu.fpu_fcw.ovrfl;
9429 outs() << " undfl " << fpu.fpu_fcw.undfl;
9430 outs() << " precis " << fpu.fpu_fcw.precis << "\n";
9431 outs() << "\t\t pc ";
9432 if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_24B)
9433 outs() << "FP_PREC_24B ";
9434 else if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_53B)
9435 outs() << "FP_PREC_53B ";
9436 else if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_64B)
9437 outs() << "FP_PREC_64B ";
9438 else
9439 outs() << fpu.fpu_fcw.pc << " ";
9440 outs() << "rc ";
9441 if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_NEAR)
9442 outs() << "FP_RND_NEAR ";
9443 else if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_DOWN)
9444 outs() << "FP_RND_DOWN ";
9445 else if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_UP)
9446 outs() << "FP_RND_UP ";
9447 else if (fpu.fpu_fcw.rc == MachO::x86_FP_CHOP)
9448 outs() << "FP_CHOP ";
9449 outs() << "\n";
9450 outs() << "\t status: invalid " << fpu.fpu_fsw.invalid;
9451 outs() << " denorm " << fpu.fpu_fsw.denorm;
9452 outs() << " zdiv " << fpu.fpu_fsw.zdiv;
9453 outs() << " ovrfl " << fpu.fpu_fsw.ovrfl;
9454 outs() << " undfl " << fpu.fpu_fsw.undfl;
9455 outs() << " precis " << fpu.fpu_fsw.precis;
9456 outs() << " stkflt " << fpu.fpu_fsw.stkflt << "\n";
9457 outs() << "\t errsumm " << fpu.fpu_fsw.errsumm;
9458 outs() << " c0 " << fpu.fpu_fsw.c0;
9459 outs() << " c1 " << fpu.fpu_fsw.c1;
9460 outs() << " c2 " << fpu.fpu_fsw.c2;
9461 outs() << " tos " << fpu.fpu_fsw.tos;
9462 outs() << " c3 " << fpu.fpu_fsw.c3;
9463 outs() << " busy " << fpu.fpu_fsw.busy << "\n";
9464 outs() << "\t fpu_ftw " << format("0x%02" PRIx32, fpu.fpu_ftw);
9465 outs() << " fpu_rsrv1 " << format("0x%02" PRIx32, fpu.fpu_rsrv1);
9466 outs() << " fpu_fop " << format("0x%04" PRIx32, fpu.fpu_fop);
9467 outs() << " fpu_ip " << format("0x%08" PRIx32, fpu.fpu_ip) << "\n";
9468 outs() << "\t fpu_cs " << format("0x%04" PRIx32, fpu.fpu_cs);
9469 outs() << " fpu_rsrv2 " << format("0x%04" PRIx32, fpu.fpu_rsrv2);
9470 outs() << " fpu_dp " << format("0x%08" PRIx32, fpu.fpu_dp);
9471 outs() << " fpu_ds " << format("0x%04" PRIx32, fpu.fpu_ds) << "\n";
9472 outs() << "\t fpu_rsrv3 " << format("0x%04" PRIx32, fpu.fpu_rsrv3);
9473 outs() << " fpu_mxcsr " << format("0x%08" PRIx32, fpu.fpu_mxcsr);
9474 outs() << " fpu_mxcsrmask " << format("0x%08" PRIx32, fpu.fpu_mxcsrmask);
9475 outs() << "\n";
9476 outs() << "\t fpu_stmm0:\n";
9477 Print_mmst_reg(fpu.fpu_stmm0);
9478 outs() << "\t fpu_stmm1:\n";
9479 Print_mmst_reg(fpu.fpu_stmm1);
9480 outs() << "\t fpu_stmm2:\n";
9481 Print_mmst_reg(fpu.fpu_stmm2);
9482 outs() << "\t fpu_stmm3:\n";
9483 Print_mmst_reg(fpu.fpu_stmm3);
9484 outs() << "\t fpu_stmm4:\n";
9485 Print_mmst_reg(fpu.fpu_stmm4);
9486 outs() << "\t fpu_stmm5:\n";
9487 Print_mmst_reg(fpu.fpu_stmm5);
9488 outs() << "\t fpu_stmm6:\n";
9489 Print_mmst_reg(fpu.fpu_stmm6);
9490 outs() << "\t fpu_stmm7:\n";
9491 Print_mmst_reg(fpu.fpu_stmm7);
9492 outs() << "\t fpu_xmm0:\n";
9493 Print_xmm_reg(fpu.fpu_xmm0);
9494 outs() << "\t fpu_xmm1:\n";
9495 Print_xmm_reg(fpu.fpu_xmm1);
9496 outs() << "\t fpu_xmm2:\n";
9497 Print_xmm_reg(fpu.fpu_xmm2);
9498 outs() << "\t fpu_xmm3:\n";
9499 Print_xmm_reg(fpu.fpu_xmm3);
9500 outs() << "\t fpu_xmm4:\n";
9501 Print_xmm_reg(fpu.fpu_xmm4);
9502 outs() << "\t fpu_xmm5:\n";
9503 Print_xmm_reg(fpu.fpu_xmm5);
9504 outs() << "\t fpu_xmm6:\n";
9505 Print_xmm_reg(fpu.fpu_xmm6);
9506 outs() << "\t fpu_xmm7:\n";
9507 Print_xmm_reg(fpu.fpu_xmm7);
9508 outs() << "\t fpu_xmm8:\n";
9509 Print_xmm_reg(fpu.fpu_xmm8);
9510 outs() << "\t fpu_xmm9:\n";
9511 Print_xmm_reg(fpu.fpu_xmm9);
9512 outs() << "\t fpu_xmm10:\n";
9513 Print_xmm_reg(fpu.fpu_xmm10);
9514 outs() << "\t fpu_xmm11:\n";
9515 Print_xmm_reg(fpu.fpu_xmm11);
9516 outs() << "\t fpu_xmm12:\n";
9517 Print_xmm_reg(fpu.fpu_xmm12);
9518 outs() << "\t fpu_xmm13:\n";
9519 Print_xmm_reg(fpu.fpu_xmm13);
9520 outs() << "\t fpu_xmm14:\n";
9521 Print_xmm_reg(fpu.fpu_xmm14);
9522 outs() << "\t fpu_xmm15:\n";
9523 Print_xmm_reg(fpu.fpu_xmm15);
9524 outs() << "\t fpu_rsrv4:\n";
9525 for (uint32_t f = 0; f < 6; f++) {
9526 outs() << "\t ";
9527 for (uint32_t g = 0; g < 16; g++)
9528 outs() << format("%02" PRIx32, fpu.fpu_rsrv4[f * g]) << " ";
9529 outs() << "\n";
9531 outs() << "\t fpu_reserved1 " << format("0x%08" PRIx32, fpu.fpu_reserved1);
9532 outs() << "\n";
9535 static void Print_x86_exception_state_t(MachO::x86_exception_state64_t &exc64) {
9536 outs() << "\t trapno " << format("0x%08" PRIx32, exc64.trapno);
9537 outs() << " err " << format("0x%08" PRIx32, exc64.err);
9538 outs() << " faultvaddr " << format("0x%016" PRIx64, exc64.faultvaddr) << "\n";
9541 static void Print_arm_thread_state32_t(MachO::arm_thread_state32_t &cpu32) {
9542 outs() << "\t r0 " << format("0x%08" PRIx32, cpu32.r[0]);
9543 outs() << " r1 " << format("0x%08" PRIx32, cpu32.r[1]);
9544 outs() << " r2 " << format("0x%08" PRIx32, cpu32.r[2]);
9545 outs() << " r3 " << format("0x%08" PRIx32, cpu32.r[3]) << "\n";
9546 outs() << "\t r4 " << format("0x%08" PRIx32, cpu32.r[4]);
9547 outs() << " r5 " << format("0x%08" PRIx32, cpu32.r[5]);
9548 outs() << " r6 " << format("0x%08" PRIx32, cpu32.r[6]);
9549 outs() << " r7 " << format("0x%08" PRIx32, cpu32.r[7]) << "\n";
9550 outs() << "\t r8 " << format("0x%08" PRIx32, cpu32.r[8]);
9551 outs() << " r9 " << format("0x%08" PRIx32, cpu32.r[9]);
9552 outs() << " r10 " << format("0x%08" PRIx32, cpu32.r[10]);
9553 outs() << " r11 " << format("0x%08" PRIx32, cpu32.r[11]) << "\n";
9554 outs() << "\t r12 " << format("0x%08" PRIx32, cpu32.r[12]);
9555 outs() << " sp " << format("0x%08" PRIx32, cpu32.sp);
9556 outs() << " lr " << format("0x%08" PRIx32, cpu32.lr);
9557 outs() << " pc " << format("0x%08" PRIx32, cpu32.pc) << "\n";
9558 outs() << "\t cpsr " << format("0x%08" PRIx32, cpu32.cpsr) << "\n";
9561 static void Print_arm_thread_state64_t(MachO::arm_thread_state64_t &cpu64) {
9562 outs() << "\t x0 " << format("0x%016" PRIx64, cpu64.x[0]);
9563 outs() << " x1 " << format("0x%016" PRIx64, cpu64.x[1]);
9564 outs() << " x2 " << format("0x%016" PRIx64, cpu64.x[2]) << "\n";
9565 outs() << "\t x3 " << format("0x%016" PRIx64, cpu64.x[3]);
9566 outs() << " x4 " << format("0x%016" PRIx64, cpu64.x[4]);
9567 outs() << " x5 " << format("0x%016" PRIx64, cpu64.x[5]) << "\n";
9568 outs() << "\t x6 " << format("0x%016" PRIx64, cpu64.x[6]);
9569 outs() << " x7 " << format("0x%016" PRIx64, cpu64.x[7]);
9570 outs() << " x8 " << format("0x%016" PRIx64, cpu64.x[8]) << "\n";
9571 outs() << "\t x9 " << format("0x%016" PRIx64, cpu64.x[9]);
9572 outs() << " x10 " << format("0x%016" PRIx64, cpu64.x[10]);
9573 outs() << " x11 " << format("0x%016" PRIx64, cpu64.x[11]) << "\n";
9574 outs() << "\t x12 " << format("0x%016" PRIx64, cpu64.x[12]);
9575 outs() << " x13 " << format("0x%016" PRIx64, cpu64.x[13]);
9576 outs() << " x14 " << format("0x%016" PRIx64, cpu64.x[14]) << "\n";
9577 outs() << "\t x15 " << format("0x%016" PRIx64, cpu64.x[15]);
9578 outs() << " x16 " << format("0x%016" PRIx64, cpu64.x[16]);
9579 outs() << " x17 " << format("0x%016" PRIx64, cpu64.x[17]) << "\n";
9580 outs() << "\t x18 " << format("0x%016" PRIx64, cpu64.x[18]);
9581 outs() << " x19 " << format("0x%016" PRIx64, cpu64.x[19]);
9582 outs() << " x20 " << format("0x%016" PRIx64, cpu64.x[20]) << "\n";
9583 outs() << "\t x21 " << format("0x%016" PRIx64, cpu64.x[21]);
9584 outs() << " x22 " << format("0x%016" PRIx64, cpu64.x[22]);
9585 outs() << " x23 " << format("0x%016" PRIx64, cpu64.x[23]) << "\n";
9586 outs() << "\t x24 " << format("0x%016" PRIx64, cpu64.x[24]);
9587 outs() << " x25 " << format("0x%016" PRIx64, cpu64.x[25]);
9588 outs() << " x26 " << format("0x%016" PRIx64, cpu64.x[26]) << "\n";
9589 outs() << "\t x27 " << format("0x%016" PRIx64, cpu64.x[27]);
9590 outs() << " x28 " << format("0x%016" PRIx64, cpu64.x[28]);
9591 outs() << " fp " << format("0x%016" PRIx64, cpu64.fp) << "\n";
9592 outs() << "\t lr " << format("0x%016" PRIx64, cpu64.lr);
9593 outs() << " sp " << format("0x%016" PRIx64, cpu64.sp);
9594 outs() << " pc " << format("0x%016" PRIx64, cpu64.pc) << "\n";
9595 outs() << "\t cpsr " << format("0x%08" PRIx32, cpu64.cpsr) << "\n";
9598 static void PrintThreadCommand(MachO::thread_command t, const char *Ptr,
9599 bool isLittleEndian, uint32_t cputype) {
9600 if (t.cmd == MachO::LC_THREAD)
9601 outs() << " cmd LC_THREAD\n";
9602 else if (t.cmd == MachO::LC_UNIXTHREAD)
9603 outs() << " cmd LC_UNIXTHREAD\n";
9604 else
9605 outs() << " cmd " << t.cmd << " (unknown)\n";
9606 outs() << " cmdsize " << t.cmdsize;
9607 if (t.cmdsize < sizeof(struct MachO::thread_command) + 2 * sizeof(uint32_t))
9608 outs() << " Incorrect size\n";
9609 else
9610 outs() << "\n";
9612 const char *begin = Ptr + sizeof(struct MachO::thread_command);
9613 const char *end = Ptr + t.cmdsize;
9614 uint32_t flavor, count, left;
9615 if (cputype == MachO::CPU_TYPE_I386) {
9616 while (begin < end) {
9617 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9618 memcpy((char *)&flavor, begin, sizeof(uint32_t));
9619 begin += sizeof(uint32_t);
9620 } else {
9621 flavor = 0;
9622 begin = end;
9624 if (isLittleEndian != sys::IsLittleEndianHost)
9625 sys::swapByteOrder(flavor);
9626 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9627 memcpy((char *)&count, begin, sizeof(uint32_t));
9628 begin += sizeof(uint32_t);
9629 } else {
9630 count = 0;
9631 begin = end;
9633 if (isLittleEndian != sys::IsLittleEndianHost)
9634 sys::swapByteOrder(count);
9635 if (flavor == MachO::x86_THREAD_STATE32) {
9636 outs() << " flavor i386_THREAD_STATE\n";
9637 if (count == MachO::x86_THREAD_STATE32_COUNT)
9638 outs() << " count i386_THREAD_STATE_COUNT\n";
9639 else
9640 outs() << " count " << count
9641 << " (not x86_THREAD_STATE32_COUNT)\n";
9642 MachO::x86_thread_state32_t cpu32;
9643 left = end - begin;
9644 if (left >= sizeof(MachO::x86_thread_state32_t)) {
9645 memcpy(&cpu32, begin, sizeof(MachO::x86_thread_state32_t));
9646 begin += sizeof(MachO::x86_thread_state32_t);
9647 } else {
9648 memset(&cpu32, '\0', sizeof(MachO::x86_thread_state32_t));
9649 memcpy(&cpu32, begin, left);
9650 begin += left;
9652 if (isLittleEndian != sys::IsLittleEndianHost)
9653 swapStruct(cpu32);
9654 Print_x86_thread_state32_t(cpu32);
9655 } else if (flavor == MachO::x86_THREAD_STATE) {
9656 outs() << " flavor x86_THREAD_STATE\n";
9657 if (count == MachO::x86_THREAD_STATE_COUNT)
9658 outs() << " count x86_THREAD_STATE_COUNT\n";
9659 else
9660 outs() << " count " << count
9661 << " (not x86_THREAD_STATE_COUNT)\n";
9662 struct MachO::x86_thread_state_t ts;
9663 left = end - begin;
9664 if (left >= sizeof(MachO::x86_thread_state_t)) {
9665 memcpy(&ts, begin, sizeof(MachO::x86_thread_state_t));
9666 begin += sizeof(MachO::x86_thread_state_t);
9667 } else {
9668 memset(&ts, '\0', sizeof(MachO::x86_thread_state_t));
9669 memcpy(&ts, begin, left);
9670 begin += left;
9672 if (isLittleEndian != sys::IsLittleEndianHost)
9673 swapStruct(ts);
9674 if (ts.tsh.flavor == MachO::x86_THREAD_STATE32) {
9675 outs() << "\t tsh.flavor x86_THREAD_STATE32 ";
9676 if (ts.tsh.count == MachO::x86_THREAD_STATE32_COUNT)
9677 outs() << "tsh.count x86_THREAD_STATE32_COUNT\n";
9678 else
9679 outs() << "tsh.count " << ts.tsh.count
9680 << " (not x86_THREAD_STATE32_COUNT\n";
9681 Print_x86_thread_state32_t(ts.uts.ts32);
9682 } else {
9683 outs() << "\t tsh.flavor " << ts.tsh.flavor << " tsh.count "
9684 << ts.tsh.count << "\n";
9686 } else {
9687 outs() << " flavor " << flavor << " (unknown)\n";
9688 outs() << " count " << count << "\n";
9689 outs() << " state (unknown)\n";
9690 begin += count * sizeof(uint32_t);
9693 } else if (cputype == MachO::CPU_TYPE_X86_64) {
9694 while (begin < end) {
9695 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9696 memcpy((char *)&flavor, begin, sizeof(uint32_t));
9697 begin += sizeof(uint32_t);
9698 } else {
9699 flavor = 0;
9700 begin = end;
9702 if (isLittleEndian != sys::IsLittleEndianHost)
9703 sys::swapByteOrder(flavor);
9704 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9705 memcpy((char *)&count, begin, sizeof(uint32_t));
9706 begin += sizeof(uint32_t);
9707 } else {
9708 count = 0;
9709 begin = end;
9711 if (isLittleEndian != sys::IsLittleEndianHost)
9712 sys::swapByteOrder(count);
9713 if (flavor == MachO::x86_THREAD_STATE64) {
9714 outs() << " flavor x86_THREAD_STATE64\n";
9715 if (count == MachO::x86_THREAD_STATE64_COUNT)
9716 outs() << " count x86_THREAD_STATE64_COUNT\n";
9717 else
9718 outs() << " count " << count
9719 << " (not x86_THREAD_STATE64_COUNT)\n";
9720 MachO::x86_thread_state64_t cpu64;
9721 left = end - begin;
9722 if (left >= sizeof(MachO::x86_thread_state64_t)) {
9723 memcpy(&cpu64, begin, sizeof(MachO::x86_thread_state64_t));
9724 begin += sizeof(MachO::x86_thread_state64_t);
9725 } else {
9726 memset(&cpu64, '\0', sizeof(MachO::x86_thread_state64_t));
9727 memcpy(&cpu64, begin, left);
9728 begin += left;
9730 if (isLittleEndian != sys::IsLittleEndianHost)
9731 swapStruct(cpu64);
9732 Print_x86_thread_state64_t(cpu64);
9733 } else if (flavor == MachO::x86_THREAD_STATE) {
9734 outs() << " flavor x86_THREAD_STATE\n";
9735 if (count == MachO::x86_THREAD_STATE_COUNT)
9736 outs() << " count x86_THREAD_STATE_COUNT\n";
9737 else
9738 outs() << " count " << count
9739 << " (not x86_THREAD_STATE_COUNT)\n";
9740 struct MachO::x86_thread_state_t ts;
9741 left = end - begin;
9742 if (left >= sizeof(MachO::x86_thread_state_t)) {
9743 memcpy(&ts, begin, sizeof(MachO::x86_thread_state_t));
9744 begin += sizeof(MachO::x86_thread_state_t);
9745 } else {
9746 memset(&ts, '\0', sizeof(MachO::x86_thread_state_t));
9747 memcpy(&ts, begin, left);
9748 begin += left;
9750 if (isLittleEndian != sys::IsLittleEndianHost)
9751 swapStruct(ts);
9752 if (ts.tsh.flavor == MachO::x86_THREAD_STATE64) {
9753 outs() << "\t tsh.flavor x86_THREAD_STATE64 ";
9754 if (ts.tsh.count == MachO::x86_THREAD_STATE64_COUNT)
9755 outs() << "tsh.count x86_THREAD_STATE64_COUNT\n";
9756 else
9757 outs() << "tsh.count " << ts.tsh.count
9758 << " (not x86_THREAD_STATE64_COUNT\n";
9759 Print_x86_thread_state64_t(ts.uts.ts64);
9760 } else {
9761 outs() << "\t tsh.flavor " << ts.tsh.flavor << " tsh.count "
9762 << ts.tsh.count << "\n";
9764 } else if (flavor == MachO::x86_FLOAT_STATE) {
9765 outs() << " flavor x86_FLOAT_STATE\n";
9766 if (count == MachO::x86_FLOAT_STATE_COUNT)
9767 outs() << " count x86_FLOAT_STATE_COUNT\n";
9768 else
9769 outs() << " count " << count << " (not x86_FLOAT_STATE_COUNT)\n";
9770 struct MachO::x86_float_state_t fs;
9771 left = end - begin;
9772 if (left >= sizeof(MachO::x86_float_state_t)) {
9773 memcpy(&fs, begin, sizeof(MachO::x86_float_state_t));
9774 begin += sizeof(MachO::x86_float_state_t);
9775 } else {
9776 memset(&fs, '\0', sizeof(MachO::x86_float_state_t));
9777 memcpy(&fs, begin, left);
9778 begin += left;
9780 if (isLittleEndian != sys::IsLittleEndianHost)
9781 swapStruct(fs);
9782 if (fs.fsh.flavor == MachO::x86_FLOAT_STATE64) {
9783 outs() << "\t fsh.flavor x86_FLOAT_STATE64 ";
9784 if (fs.fsh.count == MachO::x86_FLOAT_STATE64_COUNT)
9785 outs() << "fsh.count x86_FLOAT_STATE64_COUNT\n";
9786 else
9787 outs() << "fsh.count " << fs.fsh.count
9788 << " (not x86_FLOAT_STATE64_COUNT\n";
9789 Print_x86_float_state_t(fs.ufs.fs64);
9790 } else {
9791 outs() << "\t fsh.flavor " << fs.fsh.flavor << " fsh.count "
9792 << fs.fsh.count << "\n";
9794 } else if (flavor == MachO::x86_EXCEPTION_STATE) {
9795 outs() << " flavor x86_EXCEPTION_STATE\n";
9796 if (count == MachO::x86_EXCEPTION_STATE_COUNT)
9797 outs() << " count x86_EXCEPTION_STATE_COUNT\n";
9798 else
9799 outs() << " count " << count
9800 << " (not x86_EXCEPTION_STATE_COUNT)\n";
9801 struct MachO::x86_exception_state_t es;
9802 left = end - begin;
9803 if (left >= sizeof(MachO::x86_exception_state_t)) {
9804 memcpy(&es, begin, sizeof(MachO::x86_exception_state_t));
9805 begin += sizeof(MachO::x86_exception_state_t);
9806 } else {
9807 memset(&es, '\0', sizeof(MachO::x86_exception_state_t));
9808 memcpy(&es, begin, left);
9809 begin += left;
9811 if (isLittleEndian != sys::IsLittleEndianHost)
9812 swapStruct(es);
9813 if (es.esh.flavor == MachO::x86_EXCEPTION_STATE64) {
9814 outs() << "\t esh.flavor x86_EXCEPTION_STATE64\n";
9815 if (es.esh.count == MachO::x86_EXCEPTION_STATE64_COUNT)
9816 outs() << "\t esh.count x86_EXCEPTION_STATE64_COUNT\n";
9817 else
9818 outs() << "\t esh.count " << es.esh.count
9819 << " (not x86_EXCEPTION_STATE64_COUNT\n";
9820 Print_x86_exception_state_t(es.ues.es64);
9821 } else {
9822 outs() << "\t esh.flavor " << es.esh.flavor << " esh.count "
9823 << es.esh.count << "\n";
9825 } else if (flavor == MachO::x86_EXCEPTION_STATE64) {
9826 outs() << " flavor x86_EXCEPTION_STATE64\n";
9827 if (count == MachO::x86_EXCEPTION_STATE64_COUNT)
9828 outs() << " count x86_EXCEPTION_STATE64_COUNT\n";
9829 else
9830 outs() << " count " << count
9831 << " (not x86_EXCEPTION_STATE64_COUNT)\n";
9832 struct MachO::x86_exception_state64_t es64;
9833 left = end - begin;
9834 if (left >= sizeof(MachO::x86_exception_state64_t)) {
9835 memcpy(&es64, begin, sizeof(MachO::x86_exception_state64_t));
9836 begin += sizeof(MachO::x86_exception_state64_t);
9837 } else {
9838 memset(&es64, '\0', sizeof(MachO::x86_exception_state64_t));
9839 memcpy(&es64, begin, left);
9840 begin += left;
9842 if (isLittleEndian != sys::IsLittleEndianHost)
9843 swapStruct(es64);
9844 Print_x86_exception_state_t(es64);
9845 } else {
9846 outs() << " flavor " << flavor << " (unknown)\n";
9847 outs() << " count " << count << "\n";
9848 outs() << " state (unknown)\n";
9849 begin += count * sizeof(uint32_t);
9852 } else if (cputype == MachO::CPU_TYPE_ARM) {
9853 while (begin < end) {
9854 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9855 memcpy((char *)&flavor, begin, sizeof(uint32_t));
9856 begin += sizeof(uint32_t);
9857 } else {
9858 flavor = 0;
9859 begin = end;
9861 if (isLittleEndian != sys::IsLittleEndianHost)
9862 sys::swapByteOrder(flavor);
9863 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9864 memcpy((char *)&count, begin, sizeof(uint32_t));
9865 begin += sizeof(uint32_t);
9866 } else {
9867 count = 0;
9868 begin = end;
9870 if (isLittleEndian != sys::IsLittleEndianHost)
9871 sys::swapByteOrder(count);
9872 if (flavor == MachO::ARM_THREAD_STATE) {
9873 outs() << " flavor ARM_THREAD_STATE\n";
9874 if (count == MachO::ARM_THREAD_STATE_COUNT)
9875 outs() << " count ARM_THREAD_STATE_COUNT\n";
9876 else
9877 outs() << " count " << count
9878 << " (not ARM_THREAD_STATE_COUNT)\n";
9879 MachO::arm_thread_state32_t cpu32;
9880 left = end - begin;
9881 if (left >= sizeof(MachO::arm_thread_state32_t)) {
9882 memcpy(&cpu32, begin, sizeof(MachO::arm_thread_state32_t));
9883 begin += sizeof(MachO::arm_thread_state32_t);
9884 } else {
9885 memset(&cpu32, '\0', sizeof(MachO::arm_thread_state32_t));
9886 memcpy(&cpu32, begin, left);
9887 begin += left;
9889 if (isLittleEndian != sys::IsLittleEndianHost)
9890 swapStruct(cpu32);
9891 Print_arm_thread_state32_t(cpu32);
9892 } else {
9893 outs() << " flavor " << flavor << " (unknown)\n";
9894 outs() << " count " << count << "\n";
9895 outs() << " state (unknown)\n";
9896 begin += count * sizeof(uint32_t);
9899 } else if (cputype == MachO::CPU_TYPE_ARM64 ||
9900 cputype == MachO::CPU_TYPE_ARM64_32) {
9901 while (begin < end) {
9902 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9903 memcpy((char *)&flavor, begin, sizeof(uint32_t));
9904 begin += sizeof(uint32_t);
9905 } else {
9906 flavor = 0;
9907 begin = end;
9909 if (isLittleEndian != sys::IsLittleEndianHost)
9910 sys::swapByteOrder(flavor);
9911 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9912 memcpy((char *)&count, begin, sizeof(uint32_t));
9913 begin += sizeof(uint32_t);
9914 } else {
9915 count = 0;
9916 begin = end;
9918 if (isLittleEndian != sys::IsLittleEndianHost)
9919 sys::swapByteOrder(count);
9920 if (flavor == MachO::ARM_THREAD_STATE64) {
9921 outs() << " flavor ARM_THREAD_STATE64\n";
9922 if (count == MachO::ARM_THREAD_STATE64_COUNT)
9923 outs() << " count ARM_THREAD_STATE64_COUNT\n";
9924 else
9925 outs() << " count " << count
9926 << " (not ARM_THREAD_STATE64_COUNT)\n";
9927 MachO::arm_thread_state64_t cpu64;
9928 left = end - begin;
9929 if (left >= sizeof(MachO::arm_thread_state64_t)) {
9930 memcpy(&cpu64, begin, sizeof(MachO::arm_thread_state64_t));
9931 begin += sizeof(MachO::arm_thread_state64_t);
9932 } else {
9933 memset(&cpu64, '\0', sizeof(MachO::arm_thread_state64_t));
9934 memcpy(&cpu64, begin, left);
9935 begin += left;
9937 if (isLittleEndian != sys::IsLittleEndianHost)
9938 swapStruct(cpu64);
9939 Print_arm_thread_state64_t(cpu64);
9940 } else {
9941 outs() << " flavor " << flavor << " (unknown)\n";
9942 outs() << " count " << count << "\n";
9943 outs() << " state (unknown)\n";
9944 begin += count * sizeof(uint32_t);
9947 } else {
9948 while (begin < end) {
9949 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9950 memcpy((char *)&flavor, begin, sizeof(uint32_t));
9951 begin += sizeof(uint32_t);
9952 } else {
9953 flavor = 0;
9954 begin = end;
9956 if (isLittleEndian != sys::IsLittleEndianHost)
9957 sys::swapByteOrder(flavor);
9958 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9959 memcpy((char *)&count, begin, sizeof(uint32_t));
9960 begin += sizeof(uint32_t);
9961 } else {
9962 count = 0;
9963 begin = end;
9965 if (isLittleEndian != sys::IsLittleEndianHost)
9966 sys::swapByteOrder(count);
9967 outs() << " flavor " << flavor << "\n";
9968 outs() << " count " << count << "\n";
9969 outs() << " state (Unknown cputype/cpusubtype)\n";
9970 begin += count * sizeof(uint32_t);
9975 static void PrintDylibCommand(MachO::dylib_command dl, const char *Ptr) {
9976 if (dl.cmd == MachO::LC_ID_DYLIB)
9977 outs() << " cmd LC_ID_DYLIB\n";
9978 else if (dl.cmd == MachO::LC_LOAD_DYLIB)
9979 outs() << " cmd LC_LOAD_DYLIB\n";
9980 else if (dl.cmd == MachO::LC_LOAD_WEAK_DYLIB)
9981 outs() << " cmd LC_LOAD_WEAK_DYLIB\n";
9982 else if (dl.cmd == MachO::LC_REEXPORT_DYLIB)
9983 outs() << " cmd LC_REEXPORT_DYLIB\n";
9984 else if (dl.cmd == MachO::LC_LAZY_LOAD_DYLIB)
9985 outs() << " cmd LC_LAZY_LOAD_DYLIB\n";
9986 else if (dl.cmd == MachO::LC_LOAD_UPWARD_DYLIB)
9987 outs() << " cmd LC_LOAD_UPWARD_DYLIB\n";
9988 else
9989 outs() << " cmd " << dl.cmd << " (unknown)\n";
9990 outs() << " cmdsize " << dl.cmdsize;
9991 if (dl.cmdsize < sizeof(struct MachO::dylib_command))
9992 outs() << " Incorrect size\n";
9993 else
9994 outs() << "\n";
9995 if (dl.dylib.name < dl.cmdsize) {
9996 const char *P = (const char *)(Ptr) + dl.dylib.name;
9997 outs() << " name " << P << " (offset " << dl.dylib.name << ")\n";
9998 } else {
9999 outs() << " name ?(bad offset " << dl.dylib.name << ")\n";
10001 outs() << " time stamp " << dl.dylib.timestamp << " ";
10002 time_t t = dl.dylib.timestamp;
10003 outs() << ctime(&t);
10004 outs() << " current version ";
10005 if (dl.dylib.current_version == 0xffffffff)
10006 outs() << "n/a\n";
10007 else
10008 outs() << ((dl.dylib.current_version >> 16) & 0xffff) << "."
10009 << ((dl.dylib.current_version >> 8) & 0xff) << "."
10010 << (dl.dylib.current_version & 0xff) << "\n";
10011 outs() << "compatibility version ";
10012 if (dl.dylib.compatibility_version == 0xffffffff)
10013 outs() << "n/a\n";
10014 else
10015 outs() << ((dl.dylib.compatibility_version >> 16) & 0xffff) << "."
10016 << ((dl.dylib.compatibility_version >> 8) & 0xff) << "."
10017 << (dl.dylib.compatibility_version & 0xff) << "\n";
10020 static void PrintLinkEditDataCommand(MachO::linkedit_data_command ld,
10021 uint32_t object_size) {
10022 if (ld.cmd == MachO::LC_CODE_SIGNATURE)
10023 outs() << " cmd LC_CODE_SIGNATURE\n";
10024 else if (ld.cmd == MachO::LC_SEGMENT_SPLIT_INFO)
10025 outs() << " cmd LC_SEGMENT_SPLIT_INFO\n";
10026 else if (ld.cmd == MachO::LC_FUNCTION_STARTS)
10027 outs() << " cmd LC_FUNCTION_STARTS\n";
10028 else if (ld.cmd == MachO::LC_DATA_IN_CODE)
10029 outs() << " cmd LC_DATA_IN_CODE\n";
10030 else if (ld.cmd == MachO::LC_DYLIB_CODE_SIGN_DRS)
10031 outs() << " cmd LC_DYLIB_CODE_SIGN_DRS\n";
10032 else if (ld.cmd == MachO::LC_LINKER_OPTIMIZATION_HINT)
10033 outs() << " cmd LC_LINKER_OPTIMIZATION_HINT\n";
10034 else
10035 outs() << " cmd " << ld.cmd << " (?)\n";
10036 outs() << " cmdsize " << ld.cmdsize;
10037 if (ld.cmdsize != sizeof(struct MachO::linkedit_data_command))
10038 outs() << " Incorrect size\n";
10039 else
10040 outs() << "\n";
10041 outs() << " dataoff " << ld.dataoff;
10042 if (ld.dataoff > object_size)
10043 outs() << " (past end of file)\n";
10044 else
10045 outs() << "\n";
10046 outs() << " datasize " << ld.datasize;
10047 uint64_t big_size = ld.dataoff;
10048 big_size += ld.datasize;
10049 if (big_size > object_size)
10050 outs() << " (past end of file)\n";
10051 else
10052 outs() << "\n";
10055 static void PrintLoadCommands(const MachOObjectFile *Obj, uint32_t filetype,
10056 uint32_t cputype, bool verbose) {
10057 StringRef Buf = Obj->getData();
10058 unsigned Index = 0;
10059 for (const auto &Command : Obj->load_commands()) {
10060 outs() << "Load command " << Index++ << "\n";
10061 if (Command.C.cmd == MachO::LC_SEGMENT) {
10062 MachO::segment_command SLC = Obj->getSegmentLoadCommand(Command);
10063 const char *sg_segname = SLC.segname;
10064 PrintSegmentCommand(SLC.cmd, SLC.cmdsize, SLC.segname, SLC.vmaddr,
10065 SLC.vmsize, SLC.fileoff, SLC.filesize, SLC.maxprot,
10066 SLC.initprot, SLC.nsects, SLC.flags, Buf.size(),
10067 verbose);
10068 for (unsigned j = 0; j < SLC.nsects; j++) {
10069 MachO::section S = Obj->getSection(Command, j);
10070 PrintSection(S.sectname, S.segname, S.addr, S.size, S.offset, S.align,
10071 S.reloff, S.nreloc, S.flags, S.reserved1, S.reserved2,
10072 SLC.cmd, sg_segname, filetype, Buf.size(), verbose);
10074 } else if (Command.C.cmd == MachO::LC_SEGMENT_64) {
10075 MachO::segment_command_64 SLC_64 = Obj->getSegment64LoadCommand(Command);
10076 const char *sg_segname = SLC_64.segname;
10077 PrintSegmentCommand(SLC_64.cmd, SLC_64.cmdsize, SLC_64.segname,
10078 SLC_64.vmaddr, SLC_64.vmsize, SLC_64.fileoff,
10079 SLC_64.filesize, SLC_64.maxprot, SLC_64.initprot,
10080 SLC_64.nsects, SLC_64.flags, Buf.size(), verbose);
10081 for (unsigned j = 0; j < SLC_64.nsects; j++) {
10082 MachO::section_64 S_64 = Obj->getSection64(Command, j);
10083 PrintSection(S_64.sectname, S_64.segname, S_64.addr, S_64.size,
10084 S_64.offset, S_64.align, S_64.reloff, S_64.nreloc,
10085 S_64.flags, S_64.reserved1, S_64.reserved2, SLC_64.cmd,
10086 sg_segname, filetype, Buf.size(), verbose);
10088 } else if (Command.C.cmd == MachO::LC_SYMTAB) {
10089 MachO::symtab_command Symtab = Obj->getSymtabLoadCommand();
10090 PrintSymtabLoadCommand(Symtab, Obj->is64Bit(), Buf.size());
10091 } else if (Command.C.cmd == MachO::LC_DYSYMTAB) {
10092 MachO::dysymtab_command Dysymtab = Obj->getDysymtabLoadCommand();
10093 MachO::symtab_command Symtab = Obj->getSymtabLoadCommand();
10094 PrintDysymtabLoadCommand(Dysymtab, Symtab.nsyms, Buf.size(),
10095 Obj->is64Bit());
10096 } else if (Command.C.cmd == MachO::LC_DYLD_INFO ||
10097 Command.C.cmd == MachO::LC_DYLD_INFO_ONLY) {
10098 MachO::dyld_info_command DyldInfo = Obj->getDyldInfoLoadCommand(Command);
10099 PrintDyldInfoLoadCommand(DyldInfo, Buf.size());
10100 } else if (Command.C.cmd == MachO::LC_LOAD_DYLINKER ||
10101 Command.C.cmd == MachO::LC_ID_DYLINKER ||
10102 Command.C.cmd == MachO::LC_DYLD_ENVIRONMENT) {
10103 MachO::dylinker_command Dyld = Obj->getDylinkerCommand(Command);
10104 PrintDyldLoadCommand(Dyld, Command.Ptr);
10105 } else if (Command.C.cmd == MachO::LC_UUID) {
10106 MachO::uuid_command Uuid = Obj->getUuidCommand(Command);
10107 PrintUuidLoadCommand(Uuid);
10108 } else if (Command.C.cmd == MachO::LC_RPATH) {
10109 MachO::rpath_command Rpath = Obj->getRpathCommand(Command);
10110 PrintRpathLoadCommand(Rpath, Command.Ptr);
10111 } else if (Command.C.cmd == MachO::LC_VERSION_MIN_MACOSX ||
10112 Command.C.cmd == MachO::LC_VERSION_MIN_IPHONEOS ||
10113 Command.C.cmd == MachO::LC_VERSION_MIN_TVOS ||
10114 Command.C.cmd == MachO::LC_VERSION_MIN_WATCHOS) {
10115 MachO::version_min_command Vd = Obj->getVersionMinLoadCommand(Command);
10116 PrintVersionMinLoadCommand(Vd);
10117 } else if (Command.C.cmd == MachO::LC_NOTE) {
10118 MachO::note_command Nt = Obj->getNoteLoadCommand(Command);
10119 PrintNoteLoadCommand(Nt);
10120 } else if (Command.C.cmd == MachO::LC_BUILD_VERSION) {
10121 MachO::build_version_command Bv =
10122 Obj->getBuildVersionLoadCommand(Command);
10123 PrintBuildVersionLoadCommand(Obj, Bv);
10124 } else if (Command.C.cmd == MachO::LC_SOURCE_VERSION) {
10125 MachO::source_version_command Sd = Obj->getSourceVersionCommand(Command);
10126 PrintSourceVersionCommand(Sd);
10127 } else if (Command.C.cmd == MachO::LC_MAIN) {
10128 MachO::entry_point_command Ep = Obj->getEntryPointCommand(Command);
10129 PrintEntryPointCommand(Ep);
10130 } else if (Command.C.cmd == MachO::LC_ENCRYPTION_INFO) {
10131 MachO::encryption_info_command Ei =
10132 Obj->getEncryptionInfoCommand(Command);
10133 PrintEncryptionInfoCommand(Ei, Buf.size());
10134 } else if (Command.C.cmd == MachO::LC_ENCRYPTION_INFO_64) {
10135 MachO::encryption_info_command_64 Ei =
10136 Obj->getEncryptionInfoCommand64(Command);
10137 PrintEncryptionInfoCommand64(Ei, Buf.size());
10138 } else if (Command.C.cmd == MachO::LC_LINKER_OPTION) {
10139 MachO::linker_option_command Lo =
10140 Obj->getLinkerOptionLoadCommand(Command);
10141 PrintLinkerOptionCommand(Lo, Command.Ptr);
10142 } else if (Command.C.cmd == MachO::LC_SUB_FRAMEWORK) {
10143 MachO::sub_framework_command Sf = Obj->getSubFrameworkCommand(Command);
10144 PrintSubFrameworkCommand(Sf, Command.Ptr);
10145 } else if (Command.C.cmd == MachO::LC_SUB_UMBRELLA) {
10146 MachO::sub_umbrella_command Sf = Obj->getSubUmbrellaCommand(Command);
10147 PrintSubUmbrellaCommand(Sf, Command.Ptr);
10148 } else if (Command.C.cmd == MachO::LC_SUB_LIBRARY) {
10149 MachO::sub_library_command Sl = Obj->getSubLibraryCommand(Command);
10150 PrintSubLibraryCommand(Sl, Command.Ptr);
10151 } else if (Command.C.cmd == MachO::LC_SUB_CLIENT) {
10152 MachO::sub_client_command Sc = Obj->getSubClientCommand(Command);
10153 PrintSubClientCommand(Sc, Command.Ptr);
10154 } else if (Command.C.cmd == MachO::LC_ROUTINES) {
10155 MachO::routines_command Rc = Obj->getRoutinesCommand(Command);
10156 PrintRoutinesCommand(Rc);
10157 } else if (Command.C.cmd == MachO::LC_ROUTINES_64) {
10158 MachO::routines_command_64 Rc = Obj->getRoutinesCommand64(Command);
10159 PrintRoutinesCommand64(Rc);
10160 } else if (Command.C.cmd == MachO::LC_THREAD ||
10161 Command.C.cmd == MachO::LC_UNIXTHREAD) {
10162 MachO::thread_command Tc = Obj->getThreadCommand(Command);
10163 PrintThreadCommand(Tc, Command.Ptr, Obj->isLittleEndian(), cputype);
10164 } else if (Command.C.cmd == MachO::LC_LOAD_DYLIB ||
10165 Command.C.cmd == MachO::LC_ID_DYLIB ||
10166 Command.C.cmd == MachO::LC_LOAD_WEAK_DYLIB ||
10167 Command.C.cmd == MachO::LC_REEXPORT_DYLIB ||
10168 Command.C.cmd == MachO::LC_LAZY_LOAD_DYLIB ||
10169 Command.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB) {
10170 MachO::dylib_command Dl = Obj->getDylibIDLoadCommand(Command);
10171 PrintDylibCommand(Dl, Command.Ptr);
10172 } else if (Command.C.cmd == MachO::LC_CODE_SIGNATURE ||
10173 Command.C.cmd == MachO::LC_SEGMENT_SPLIT_INFO ||
10174 Command.C.cmd == MachO::LC_FUNCTION_STARTS ||
10175 Command.C.cmd == MachO::LC_DATA_IN_CODE ||
10176 Command.C.cmd == MachO::LC_DYLIB_CODE_SIGN_DRS ||
10177 Command.C.cmd == MachO::LC_LINKER_OPTIMIZATION_HINT) {
10178 MachO::linkedit_data_command Ld =
10179 Obj->getLinkeditDataLoadCommand(Command);
10180 PrintLinkEditDataCommand(Ld, Buf.size());
10181 } else {
10182 outs() << " cmd ?(" << format("0x%08" PRIx32, Command.C.cmd)
10183 << ")\n";
10184 outs() << " cmdsize " << Command.C.cmdsize << "\n";
10185 // TODO: get and print the raw bytes of the load command.
10187 // TODO: print all the other kinds of load commands.
10191 static void PrintMachHeader(const MachOObjectFile *Obj, bool verbose) {
10192 if (Obj->is64Bit()) {
10193 MachO::mach_header_64 H_64;
10194 H_64 = Obj->getHeader64();
10195 PrintMachHeader(H_64.magic, H_64.cputype, H_64.cpusubtype, H_64.filetype,
10196 H_64.ncmds, H_64.sizeofcmds, H_64.flags, verbose);
10197 } else {
10198 MachO::mach_header H;
10199 H = Obj->getHeader();
10200 PrintMachHeader(H.magic, H.cputype, H.cpusubtype, H.filetype, H.ncmds,
10201 H.sizeofcmds, H.flags, verbose);
10205 void printMachOFileHeader(const object::ObjectFile *Obj) {
10206 const MachOObjectFile *file = dyn_cast<const MachOObjectFile>(Obj);
10207 PrintMachHeader(file, !NonVerbose);
10210 void printMachOLoadCommands(const object::ObjectFile *Obj) {
10211 const MachOObjectFile *file = dyn_cast<const MachOObjectFile>(Obj);
10212 uint32_t filetype = 0;
10213 uint32_t cputype = 0;
10214 if (file->is64Bit()) {
10215 MachO::mach_header_64 H_64;
10216 H_64 = file->getHeader64();
10217 filetype = H_64.filetype;
10218 cputype = H_64.cputype;
10219 } else {
10220 MachO::mach_header H;
10221 H = file->getHeader();
10222 filetype = H.filetype;
10223 cputype = H.cputype;
10225 PrintLoadCommands(file, filetype, cputype, !NonVerbose);
10228 //===----------------------------------------------------------------------===//
10229 // export trie dumping
10230 //===----------------------------------------------------------------------===//
10232 void printMachOExportsTrie(const object::MachOObjectFile *Obj) {
10233 uint64_t BaseSegmentAddress = 0;
10234 for (const auto &Command : Obj->load_commands()) {
10235 if (Command.C.cmd == MachO::LC_SEGMENT) {
10236 MachO::segment_command Seg = Obj->getSegmentLoadCommand(Command);
10237 if (Seg.fileoff == 0 && Seg.filesize != 0) {
10238 BaseSegmentAddress = Seg.vmaddr;
10239 break;
10241 } else if (Command.C.cmd == MachO::LC_SEGMENT_64) {
10242 MachO::segment_command_64 Seg = Obj->getSegment64LoadCommand(Command);
10243 if (Seg.fileoff == 0 && Seg.filesize != 0) {
10244 BaseSegmentAddress = Seg.vmaddr;
10245 break;
10249 Error Err = Error::success();
10250 for (const object::ExportEntry &Entry : Obj->exports(Err)) {
10251 uint64_t Flags = Entry.flags();
10252 bool ReExport = (Flags & MachO::EXPORT_SYMBOL_FLAGS_REEXPORT);
10253 bool WeakDef = (Flags & MachO::EXPORT_SYMBOL_FLAGS_WEAK_DEFINITION);
10254 bool ThreadLocal = ((Flags & MachO::EXPORT_SYMBOL_FLAGS_KIND_MASK) ==
10255 MachO::EXPORT_SYMBOL_FLAGS_KIND_THREAD_LOCAL);
10256 bool Abs = ((Flags & MachO::EXPORT_SYMBOL_FLAGS_KIND_MASK) ==
10257 MachO::EXPORT_SYMBOL_FLAGS_KIND_ABSOLUTE);
10258 bool Resolver = (Flags & MachO::EXPORT_SYMBOL_FLAGS_STUB_AND_RESOLVER);
10259 if (ReExport)
10260 outs() << "[re-export] ";
10261 else
10262 outs() << format("0x%08llX ",
10263 Entry.address() + BaseSegmentAddress);
10264 outs() << Entry.name();
10265 if (WeakDef || ThreadLocal || Resolver || Abs) {
10266 bool NeedsComma = false;
10267 outs() << " [";
10268 if (WeakDef) {
10269 outs() << "weak_def";
10270 NeedsComma = true;
10272 if (ThreadLocal) {
10273 if (NeedsComma)
10274 outs() << ", ";
10275 outs() << "per-thread";
10276 NeedsComma = true;
10278 if (Abs) {
10279 if (NeedsComma)
10280 outs() << ", ";
10281 outs() << "absolute";
10282 NeedsComma = true;
10284 if (Resolver) {
10285 if (NeedsComma)
10286 outs() << ", ";
10287 outs() << format("resolver=0x%08llX", Entry.other());
10288 NeedsComma = true;
10290 outs() << "]";
10292 if (ReExport) {
10293 StringRef DylibName = "unknown";
10294 int Ordinal = Entry.other() - 1;
10295 Obj->getLibraryShortNameByIndex(Ordinal, DylibName);
10296 if (Entry.otherName().empty())
10297 outs() << " (from " << DylibName << ")";
10298 else
10299 outs() << " (" << Entry.otherName() << " from " << DylibName << ")";
10301 outs() << "\n";
10303 if (Err)
10304 reportError(std::move(Err), Obj->getFileName());
10307 //===----------------------------------------------------------------------===//
10308 // rebase table dumping
10309 //===----------------------------------------------------------------------===//
10311 void printMachORebaseTable(object::MachOObjectFile *Obj) {
10312 outs() << "segment section address type\n";
10313 Error Err = Error::success();
10314 for (const object::MachORebaseEntry &Entry : Obj->rebaseTable(Err)) {
10315 StringRef SegmentName = Entry.segmentName();
10316 StringRef SectionName = Entry.sectionName();
10317 uint64_t Address = Entry.address();
10319 // Table lines look like: __DATA __nl_symbol_ptr 0x0000F00C pointer
10320 outs() << format("%-8s %-18s 0x%08" PRIX64 " %s\n",
10321 SegmentName.str().c_str(), SectionName.str().c_str(),
10322 Address, Entry.typeName().str().c_str());
10324 if (Err)
10325 reportError(std::move(Err), Obj->getFileName());
10328 static StringRef ordinalName(const object::MachOObjectFile *Obj, int Ordinal) {
10329 StringRef DylibName;
10330 switch (Ordinal) {
10331 case MachO::BIND_SPECIAL_DYLIB_SELF:
10332 return "this-image";
10333 case MachO::BIND_SPECIAL_DYLIB_MAIN_EXECUTABLE:
10334 return "main-executable";
10335 case MachO::BIND_SPECIAL_DYLIB_FLAT_LOOKUP:
10336 return "flat-namespace";
10337 default:
10338 if (Ordinal > 0) {
10339 std::error_code EC =
10340 Obj->getLibraryShortNameByIndex(Ordinal - 1, DylibName);
10341 if (EC)
10342 return "<<bad library ordinal>>";
10343 return DylibName;
10346 return "<<unknown special ordinal>>";
10349 //===----------------------------------------------------------------------===//
10350 // bind table dumping
10351 //===----------------------------------------------------------------------===//
10353 void printMachOBindTable(object::MachOObjectFile *Obj) {
10354 // Build table of sections so names can used in final output.
10355 outs() << "segment section address type "
10356 "addend dylib symbol\n";
10357 Error Err = Error::success();
10358 for (const object::MachOBindEntry &Entry : Obj->bindTable(Err)) {
10359 StringRef SegmentName = Entry.segmentName();
10360 StringRef SectionName = Entry.sectionName();
10361 uint64_t Address = Entry.address();
10363 // Table lines look like:
10364 // __DATA __got 0x00012010 pointer 0 libSystem ___stack_chk_guard
10365 StringRef Attr;
10366 if (Entry.flags() & MachO::BIND_SYMBOL_FLAGS_WEAK_IMPORT)
10367 Attr = " (weak_import)";
10368 outs() << left_justify(SegmentName, 8) << " "
10369 << left_justify(SectionName, 18) << " "
10370 << format_hex(Address, 10, true) << " "
10371 << left_justify(Entry.typeName(), 8) << " "
10372 << format_decimal(Entry.addend(), 8) << " "
10373 << left_justify(ordinalName(Obj, Entry.ordinal()), 16) << " "
10374 << Entry.symbolName() << Attr << "\n";
10376 if (Err)
10377 reportError(std::move(Err), Obj->getFileName());
10380 //===----------------------------------------------------------------------===//
10381 // lazy bind table dumping
10382 //===----------------------------------------------------------------------===//
10384 void printMachOLazyBindTable(object::MachOObjectFile *Obj) {
10385 outs() << "segment section address "
10386 "dylib symbol\n";
10387 Error Err = Error::success();
10388 for (const object::MachOBindEntry &Entry : Obj->lazyBindTable(Err)) {
10389 StringRef SegmentName = Entry.segmentName();
10390 StringRef SectionName = Entry.sectionName();
10391 uint64_t Address = Entry.address();
10393 // Table lines look like:
10394 // __DATA __got 0x00012010 libSystem ___stack_chk_guard
10395 outs() << left_justify(SegmentName, 8) << " "
10396 << left_justify(SectionName, 18) << " "
10397 << format_hex(Address, 10, true) << " "
10398 << left_justify(ordinalName(Obj, Entry.ordinal()), 16) << " "
10399 << Entry.symbolName() << "\n";
10401 if (Err)
10402 reportError(std::move(Err), Obj->getFileName());
10405 //===----------------------------------------------------------------------===//
10406 // weak bind table dumping
10407 //===----------------------------------------------------------------------===//
10409 void printMachOWeakBindTable(object::MachOObjectFile *Obj) {
10410 outs() << "segment section address "
10411 "type addend symbol\n";
10412 Error Err = Error::success();
10413 for (const object::MachOBindEntry &Entry : Obj->weakBindTable(Err)) {
10414 // Strong symbols don't have a location to update.
10415 if (Entry.flags() & MachO::BIND_SYMBOL_FLAGS_NON_WEAK_DEFINITION) {
10416 outs() << " strong "
10417 << Entry.symbolName() << "\n";
10418 continue;
10420 StringRef SegmentName = Entry.segmentName();
10421 StringRef SectionName = Entry.sectionName();
10422 uint64_t Address = Entry.address();
10424 // Table lines look like:
10425 // __DATA __data 0x00001000 pointer 0 _foo
10426 outs() << left_justify(SegmentName, 8) << " "
10427 << left_justify(SectionName, 18) << " "
10428 << format_hex(Address, 10, true) << " "
10429 << left_justify(Entry.typeName(), 8) << " "
10430 << format_decimal(Entry.addend(), 8) << " " << Entry.symbolName()
10431 << "\n";
10433 if (Err)
10434 reportError(std::move(Err), Obj->getFileName());
10437 // get_dyld_bind_info_symbolname() is used for disassembly and passed an
10438 // address, ReferenceValue, in the Mach-O file and looks in the dyld bind
10439 // information for that address. If the address is found its binding symbol
10440 // name is returned. If not nullptr is returned.
10441 static const char *get_dyld_bind_info_symbolname(uint64_t ReferenceValue,
10442 struct DisassembleInfo *info) {
10443 if (info->bindtable == nullptr) {
10444 info->bindtable = std::make_unique<SymbolAddressMap>();
10445 Error Err = Error::success();
10446 for (const object::MachOBindEntry &Entry : info->O->bindTable(Err)) {
10447 uint64_t Address = Entry.address();
10448 StringRef name = Entry.symbolName();
10449 if (!name.empty())
10450 (*info->bindtable)[Address] = name;
10452 if (Err)
10453 reportError(std::move(Err), info->O->getFileName());
10455 auto name = info->bindtable->lookup(ReferenceValue);
10456 return !name.empty() ? name.data() : nullptr;
10459 void printLazyBindTable(ObjectFile *o) {
10460 outs() << "Lazy bind table:\n";
10461 if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
10462 printMachOLazyBindTable(MachO);
10463 else
10464 WithColor::error()
10465 << "This operation is only currently supported "
10466 "for Mach-O executable files.\n";
10469 void printWeakBindTable(ObjectFile *o) {
10470 outs() << "Weak bind table:\n";
10471 if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
10472 printMachOWeakBindTable(MachO);
10473 else
10474 WithColor::error()
10475 << "This operation is only currently supported "
10476 "for Mach-O executable files.\n";
10479 void printExportsTrie(const ObjectFile *o) {
10480 outs() << "Exports trie:\n";
10481 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
10482 printMachOExportsTrie(MachO);
10483 else
10484 WithColor::error()
10485 << "This operation is only currently supported "
10486 "for Mach-O executable files.\n";
10489 void printRebaseTable(ObjectFile *o) {
10490 outs() << "Rebase table:\n";
10491 if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
10492 printMachORebaseTable(MachO);
10493 else
10494 WithColor::error()
10495 << "This operation is only currently supported "
10496 "for Mach-O executable files.\n";
10499 void printBindTable(ObjectFile *o) {
10500 outs() << "Bind table:\n";
10501 if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
10502 printMachOBindTable(MachO);
10503 else
10504 WithColor::error()
10505 << "This operation is only currently supported "
10506 "for Mach-O executable files.\n";
10508 } // namespace llvm