[llvm-objcopy] [COFF] Fix warnings abuilt missing field initialization. NFC.
[llvm-complete.git] / tools / llvm-objdump / MachODump.cpp
blob397573e2a481873c032f9661f2d0e6d32d057d4e
1 //===-- MachODump.cpp - Object file dumping utility for llvm --------------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the MachO-specific dumper for llvm-objdump.
12 //===----------------------------------------------------------------------===//
14 #include "llvm-objdump.h"
15 #include "llvm-c/Disassembler.h"
16 #include "llvm/ADT/STLExtras.h"
17 #include "llvm/ADT/StringExtras.h"
18 #include "llvm/ADT/Triple.h"
19 #include "llvm/BinaryFormat/MachO.h"
20 #include "llvm/Config/config.h"
21 #include "llvm/DebugInfo/DIContext.h"
22 #include "llvm/DebugInfo/DWARF/DWARFContext.h"
23 #include "llvm/Demangle/Demangle.h"
24 #include "llvm/MC/MCAsmInfo.h"
25 #include "llvm/MC/MCContext.h"
26 #include "llvm/MC/MCDisassembler/MCDisassembler.h"
27 #include "llvm/MC/MCInst.h"
28 #include "llvm/MC/MCInstPrinter.h"
29 #include "llvm/MC/MCInstrDesc.h"
30 #include "llvm/MC/MCInstrInfo.h"
31 #include "llvm/MC/MCRegisterInfo.h"
32 #include "llvm/MC/MCSubtargetInfo.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;
60 using namespace object;
62 static cl::opt<bool>
63 UseDbg("g",
64 cl::desc("Print line information from debug info if available"));
66 static cl::opt<std::string> DSYMFile("dsym",
67 cl::desc("Use .dSYM file for debug info"));
69 static cl::opt<bool> FullLeadingAddr("full-leading-addr",
70 cl::desc("Print full leading address"));
72 static cl::opt<bool> NoLeadingHeaders("no-leading-headers",
73 cl::desc("Print no leading headers"));
75 cl::opt<bool> llvm::UniversalHeaders("universal-headers",
76 cl::desc("Print Mach-O universal headers "
77 "(requires -macho)"));
79 cl::opt<bool>
80 ArchiveMemberOffsets("archive-member-offsets",
81 cl::desc("Print the offset to each archive member for "
82 "Mach-O archives (requires -macho and "
83 "-archive-headers)"));
85 cl::opt<bool>
86 llvm::IndirectSymbols("indirect-symbols",
87 cl::desc("Print indirect symbol table for Mach-O "
88 "objects (requires -macho)"));
90 cl::opt<bool>
91 llvm::DataInCode("data-in-code",
92 cl::desc("Print the data in code table for Mach-O objects "
93 "(requires -macho)"));
95 cl::opt<bool>
96 llvm::LinkOptHints("link-opt-hints",
97 cl::desc("Print the linker optimization hints for "
98 "Mach-O objects (requires -macho)"));
100 cl::opt<bool>
101 llvm::InfoPlist("info-plist",
102 cl::desc("Print the info plist section as strings for "
103 "Mach-O objects (requires -macho)"));
105 cl::opt<bool>
106 llvm::DylibsUsed("dylibs-used",
107 cl::desc("Print the shared libraries used for linked "
108 "Mach-O files (requires -macho)"));
110 cl::opt<bool>
111 llvm::DylibId("dylib-id",
112 cl::desc("Print the shared library's id for the dylib Mach-O "
113 "file (requires -macho)"));
115 cl::opt<bool>
116 llvm::NonVerbose("non-verbose",
117 cl::desc("Print the info for Mach-O objects in "
118 "non-verbose or numeric form (requires -macho)"));
120 cl::opt<bool>
121 llvm::ObjcMetaData("objc-meta-data",
122 cl::desc("Print the Objective-C runtime meta data for "
123 "Mach-O files (requires -macho)"));
125 cl::opt<std::string> llvm::DisSymName(
126 "dis-symname",
127 cl::desc("disassemble just this symbol's instructions (requires -macho)"));
129 static cl::opt<bool> NoSymbolicOperands(
130 "no-symbolic-operands",
131 cl::desc("do not symbolic operands when disassembling (requires -macho)"));
133 static cl::list<std::string>
134 ArchFlags("arch", cl::desc("architecture(s) from a Mach-O file to dump"),
135 cl::ZeroOrMore);
137 bool ArchAll = false;
139 static std::string ThumbTripleName;
141 static const Target *GetTarget(const MachOObjectFile *MachOObj,
142 const char **McpuDefault,
143 const Target **ThumbTarget) {
144 // Figure out the target triple.
145 llvm::Triple TT(TripleName);
146 if (TripleName.empty()) {
147 TT = MachOObj->getArchTriple(McpuDefault);
148 TripleName = TT.str();
151 if (TT.getArch() == Triple::arm) {
152 // We've inferred a 32-bit ARM target from the object file. All MachO CPUs
153 // that support ARM are also capable of Thumb mode.
154 llvm::Triple ThumbTriple = TT;
155 std::string ThumbName = (Twine("thumb") + TT.getArchName().substr(3)).str();
156 ThumbTriple.setArchName(ThumbName);
157 ThumbTripleName = ThumbTriple.str();
160 // Get the target specific parser.
161 std::string Error;
162 const Target *TheTarget = TargetRegistry::lookupTarget(TripleName, Error);
163 if (TheTarget && ThumbTripleName.empty())
164 return TheTarget;
166 *ThumbTarget = TargetRegistry::lookupTarget(ThumbTripleName, Error);
167 if (*ThumbTarget)
168 return TheTarget;
170 WithColor::error(errs(), "llvm-objdump") << "unable to get target for '";
171 if (!TheTarget)
172 errs() << TripleName;
173 else
174 errs() << ThumbTripleName;
175 errs() << "', see --version and --triple.\n";
176 return nullptr;
179 struct SymbolSorter {
180 bool operator()(const SymbolRef &A, const SymbolRef &B) {
181 Expected<SymbolRef::Type> ATypeOrErr = A.getType();
182 if (!ATypeOrErr)
183 report_error(A.getObject()->getFileName(), ATypeOrErr.takeError());
184 SymbolRef::Type AType = *ATypeOrErr;
185 Expected<SymbolRef::Type> BTypeOrErr = B.getType();
186 if (!BTypeOrErr)
187 report_error(B.getObject()->getFileName(), BTypeOrErr.takeError());
188 SymbolRef::Type BType = *BTypeOrErr;
189 uint64_t AAddr = (AType != SymbolRef::ST_Function) ? 0 : A.getValue();
190 uint64_t BAddr = (BType != SymbolRef::ST_Function) ? 0 : B.getValue();
191 return AAddr < BAddr;
195 // Types for the storted data in code table that is built before disassembly
196 // and the predicate function to sort them.
197 typedef std::pair<uint64_t, DiceRef> DiceTableEntry;
198 typedef std::vector<DiceTableEntry> DiceTable;
199 typedef DiceTable::iterator dice_table_iterator;
201 #ifdef HAVE_LIBXAR
202 namespace {
203 struct ScopedXarFile {
204 xar_t xar;
205 ScopedXarFile(const char *filename, int32_t flags)
206 : xar(xar_open(filename, flags)) {}
207 ~ScopedXarFile() {
208 if (xar)
209 xar_close(xar);
211 ScopedXarFile(const ScopedXarFile &) = delete;
212 ScopedXarFile &operator=(const ScopedXarFile &) = delete;
213 operator xar_t() { return xar; }
216 struct ScopedXarIter {
217 xar_iter_t iter;
218 ScopedXarIter() : iter(xar_iter_new()) {}
219 ~ScopedXarIter() {
220 if (iter)
221 xar_iter_free(iter);
223 ScopedXarIter(const ScopedXarIter &) = delete;
224 ScopedXarIter &operator=(const ScopedXarIter &) = delete;
225 operator xar_iter_t() { return iter; }
227 } // namespace
228 #endif // defined(HAVE_LIBXAR)
230 // This is used to search for a data in code table entry for the PC being
231 // disassembled. The j parameter has the PC in j.first. A single data in code
232 // table entry can cover many bytes for each of its Kind's. So if the offset,
233 // aka the i.first value, of the data in code table entry plus its Length
234 // covers the PC being searched for this will return true. If not it will
235 // return false.
236 static bool compareDiceTableEntries(const DiceTableEntry &i,
237 const DiceTableEntry &j) {
238 uint16_t Length;
239 i.second.getLength(Length);
241 return j.first >= i.first && j.first < i.first + Length;
244 static uint64_t DumpDataInCode(const uint8_t *bytes, uint64_t Length,
245 unsigned short Kind) {
246 uint32_t Value, Size = 1;
248 switch (Kind) {
249 default:
250 case MachO::DICE_KIND_DATA:
251 if (Length >= 4) {
252 if (!NoShowRawInsn)
253 dumpBytes(makeArrayRef(bytes, 4), outs());
254 Value = bytes[3] << 24 | bytes[2] << 16 | bytes[1] << 8 | bytes[0];
255 outs() << "\t.long " << Value;
256 Size = 4;
257 } else if (Length >= 2) {
258 if (!NoShowRawInsn)
259 dumpBytes(makeArrayRef(bytes, 2), outs());
260 Value = bytes[1] << 8 | bytes[0];
261 outs() << "\t.short " << Value;
262 Size = 2;
263 } else {
264 if (!NoShowRawInsn)
265 dumpBytes(makeArrayRef(bytes, 2), outs());
266 Value = bytes[0];
267 outs() << "\t.byte " << Value;
268 Size = 1;
270 if (Kind == MachO::DICE_KIND_DATA)
271 outs() << "\t@ KIND_DATA\n";
272 else
273 outs() << "\t@ data in code kind = " << Kind << "\n";
274 break;
275 case MachO::DICE_KIND_JUMP_TABLE8:
276 if (!NoShowRawInsn)
277 dumpBytes(makeArrayRef(bytes, 1), outs());
278 Value = bytes[0];
279 outs() << "\t.byte " << format("%3u", Value) << "\t@ KIND_JUMP_TABLE8\n";
280 Size = 1;
281 break;
282 case MachO::DICE_KIND_JUMP_TABLE16:
283 if (!NoShowRawInsn)
284 dumpBytes(makeArrayRef(bytes, 2), outs());
285 Value = bytes[1] << 8 | bytes[0];
286 outs() << "\t.short " << format("%5u", Value & 0xffff)
287 << "\t@ KIND_JUMP_TABLE16\n";
288 Size = 2;
289 break;
290 case MachO::DICE_KIND_JUMP_TABLE32:
291 case MachO::DICE_KIND_ABS_JUMP_TABLE32:
292 if (!NoShowRawInsn)
293 dumpBytes(makeArrayRef(bytes, 4), outs());
294 Value = bytes[3] << 24 | bytes[2] << 16 | bytes[1] << 8 | bytes[0];
295 outs() << "\t.long " << Value;
296 if (Kind == MachO::DICE_KIND_JUMP_TABLE32)
297 outs() << "\t@ KIND_JUMP_TABLE32\n";
298 else
299 outs() << "\t@ KIND_ABS_JUMP_TABLE32\n";
300 Size = 4;
301 break;
303 return Size;
306 static void getSectionsAndSymbols(MachOObjectFile *MachOObj,
307 std::vector<SectionRef> &Sections,
308 std::vector<SymbolRef> &Symbols,
309 SmallVectorImpl<uint64_t> &FoundFns,
310 uint64_t &BaseSegmentAddress) {
311 for (const SymbolRef &Symbol : MachOObj->symbols()) {
312 Expected<StringRef> SymName = Symbol.getName();
313 if (!SymName)
314 report_error(MachOObj->getFileName(), SymName.takeError());
315 if (!SymName->startswith("ltmp"))
316 Symbols.push_back(Symbol);
319 for (const SectionRef &Section : MachOObj->sections()) {
320 StringRef SectName;
321 Section.getName(SectName);
322 Sections.push_back(Section);
325 bool BaseSegmentAddressSet = false;
326 for (const auto &Command : MachOObj->load_commands()) {
327 if (Command.C.cmd == MachO::LC_FUNCTION_STARTS) {
328 // We found a function starts segment, parse the addresses for later
329 // consumption.
330 MachO::linkedit_data_command LLC =
331 MachOObj->getLinkeditDataLoadCommand(Command);
333 MachOObj->ReadULEB128s(LLC.dataoff, FoundFns);
334 } else if (Command.C.cmd == MachO::LC_SEGMENT) {
335 MachO::segment_command SLC = MachOObj->getSegmentLoadCommand(Command);
336 StringRef SegName = SLC.segname;
337 if (!BaseSegmentAddressSet && SegName != "__PAGEZERO") {
338 BaseSegmentAddressSet = true;
339 BaseSegmentAddress = SLC.vmaddr;
345 static void PrintIndirectSymbolTable(MachOObjectFile *O, bool verbose,
346 uint32_t n, uint32_t count,
347 uint32_t stride, uint64_t addr) {
348 MachO::dysymtab_command Dysymtab = O->getDysymtabLoadCommand();
349 uint32_t nindirectsyms = Dysymtab.nindirectsyms;
350 if (n > nindirectsyms)
351 outs() << " (entries start past the end of the indirect symbol "
352 "table) (reserved1 field greater than the table size)";
353 else if (n + count > nindirectsyms)
354 outs() << " (entries extends past the end of the indirect symbol "
355 "table)";
356 outs() << "\n";
357 uint32_t cputype = O->getHeader().cputype;
358 if (cputype & MachO::CPU_ARCH_ABI64)
359 outs() << "address index";
360 else
361 outs() << "address index";
362 if (verbose)
363 outs() << " name\n";
364 else
365 outs() << "\n";
366 for (uint32_t j = 0; j < count && n + j < nindirectsyms; j++) {
367 if (cputype & MachO::CPU_ARCH_ABI64)
368 outs() << format("0x%016" PRIx64, addr + j * stride) << " ";
369 else
370 outs() << format("0x%08" PRIx32, (uint32_t)addr + j * stride) << " ";
371 MachO::dysymtab_command Dysymtab = O->getDysymtabLoadCommand();
372 uint32_t indirect_symbol = O->getIndirectSymbolTableEntry(Dysymtab, n + j);
373 if (indirect_symbol == MachO::INDIRECT_SYMBOL_LOCAL) {
374 outs() << "LOCAL\n";
375 continue;
377 if (indirect_symbol ==
378 (MachO::INDIRECT_SYMBOL_LOCAL | MachO::INDIRECT_SYMBOL_ABS)) {
379 outs() << "LOCAL ABSOLUTE\n";
380 continue;
382 if (indirect_symbol == MachO::INDIRECT_SYMBOL_ABS) {
383 outs() << "ABSOLUTE\n";
384 continue;
386 outs() << format("%5u ", indirect_symbol);
387 if (verbose) {
388 MachO::symtab_command Symtab = O->getSymtabLoadCommand();
389 if (indirect_symbol < Symtab.nsyms) {
390 symbol_iterator Sym = O->getSymbolByIndex(indirect_symbol);
391 SymbolRef Symbol = *Sym;
392 Expected<StringRef> SymName = Symbol.getName();
393 if (!SymName)
394 report_error(O->getFileName(), SymName.takeError());
395 outs() << *SymName;
396 } else {
397 outs() << "?";
400 outs() << "\n";
404 static void PrintIndirectSymbols(MachOObjectFile *O, bool verbose) {
405 for (const auto &Load : O->load_commands()) {
406 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
407 MachO::segment_command_64 Seg = O->getSegment64LoadCommand(Load);
408 for (unsigned J = 0; J < Seg.nsects; ++J) {
409 MachO::section_64 Sec = O->getSection64(Load, J);
410 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
411 if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
412 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
413 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
414 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
415 section_type == MachO::S_SYMBOL_STUBS) {
416 uint32_t stride;
417 if (section_type == MachO::S_SYMBOL_STUBS)
418 stride = Sec.reserved2;
419 else
420 stride = 8;
421 if (stride == 0) {
422 outs() << "Can't print indirect symbols for (" << Sec.segname << ","
423 << Sec.sectname << ") "
424 << "(size of stubs in reserved2 field is zero)\n";
425 continue;
427 uint32_t count = Sec.size / stride;
428 outs() << "Indirect symbols for (" << Sec.segname << ","
429 << Sec.sectname << ") " << count << " entries";
430 uint32_t n = Sec.reserved1;
431 PrintIndirectSymbolTable(O, verbose, n, count, stride, Sec.addr);
434 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
435 MachO::segment_command Seg = O->getSegmentLoadCommand(Load);
436 for (unsigned J = 0; J < Seg.nsects; ++J) {
437 MachO::section Sec = O->getSection(Load, J);
438 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
439 if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
440 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
441 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
442 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
443 section_type == MachO::S_SYMBOL_STUBS) {
444 uint32_t stride;
445 if (section_type == MachO::S_SYMBOL_STUBS)
446 stride = Sec.reserved2;
447 else
448 stride = 4;
449 if (stride == 0) {
450 outs() << "Can't print indirect symbols for (" << Sec.segname << ","
451 << Sec.sectname << ") "
452 << "(size of stubs in reserved2 field is zero)\n";
453 continue;
455 uint32_t count = Sec.size / stride;
456 outs() << "Indirect symbols for (" << Sec.segname << ","
457 << Sec.sectname << ") " << count << " entries";
458 uint32_t n = Sec.reserved1;
459 PrintIndirectSymbolTable(O, verbose, n, count, stride, Sec.addr);
466 static void PrintRType(const uint64_t cputype, const unsigned r_type) {
467 static char const *generic_r_types[] = {
468 "VANILLA ", "PAIR ", "SECTDIF ", "PBLAPTR ", "LOCSDIF ", "TLV ",
469 " 6 (?) ", " 7 (?) ", " 8 (?) ", " 9 (?) ", " 10 (?) ", " 11 (?) ",
470 " 12 (?) ", " 13 (?) ", " 14 (?) ", " 15 (?) "
472 static char const *x86_64_r_types[] = {
473 "UNSIGND ", "SIGNED ", "BRANCH ", "GOT_LD ", "GOT ", "SUB ",
474 "SIGNED1 ", "SIGNED2 ", "SIGNED4 ", "TLV ", " 10 (?) ", " 11 (?) ",
475 " 12 (?) ", " 13 (?) ", " 14 (?) ", " 15 (?) "
477 static char const *arm_r_types[] = {
478 "VANILLA ", "PAIR ", "SECTDIFF", "LOCSDIF ", "PBLAPTR ",
479 "BR24 ", "T_BR22 ", "T_BR32 ", "HALF ", "HALFDIF ",
480 " 10 (?) ", " 11 (?) ", " 12 (?) ", " 13 (?) ", " 14 (?) ", " 15 (?) "
482 static char const *arm64_r_types[] = {
483 "UNSIGND ", "SUB ", "BR26 ", "PAGE21 ", "PAGOF12 ",
484 "GOTLDP ", "GOTLDPOF", "PTRTGOT ", "TLVLDP ", "TLVLDPOF",
485 "ADDEND ", " 11 (?) ", " 12 (?) ", " 13 (?) ", " 14 (?) ", " 15 (?) "
488 if (r_type > 0xf){
489 outs() << format("%-7u", r_type) << " ";
490 return;
492 switch (cputype) {
493 case MachO::CPU_TYPE_I386:
494 outs() << generic_r_types[r_type];
495 break;
496 case MachO::CPU_TYPE_X86_64:
497 outs() << x86_64_r_types[r_type];
498 break;
499 case MachO::CPU_TYPE_ARM:
500 outs() << arm_r_types[r_type];
501 break;
502 case MachO::CPU_TYPE_ARM64:
503 outs() << arm64_r_types[r_type];
504 break;
505 default:
506 outs() << format("%-7u ", r_type);
510 static void PrintRLength(const uint64_t cputype, const unsigned r_type,
511 const unsigned r_length, const bool previous_arm_half){
512 if (cputype == MachO::CPU_TYPE_ARM &&
513 (r_type == llvm::MachO::ARM_RELOC_HALF ||
514 r_type == llvm::MachO::ARM_RELOC_HALF_SECTDIFF ||
515 previous_arm_half == true)) {
516 if ((r_length & 0x1) == 0)
517 outs() << "lo/";
518 else
519 outs() << "hi/";
520 if ((r_length & 0x1) == 0)
521 outs() << "arm ";
522 else
523 outs() << "thm ";
524 } else {
525 switch (r_length) {
526 case 0:
527 outs() << "byte ";
528 break;
529 case 1:
530 outs() << "word ";
531 break;
532 case 2:
533 outs() << "long ";
534 break;
535 case 3:
536 if (cputype == MachO::CPU_TYPE_X86_64)
537 outs() << "quad ";
538 else
539 outs() << format("?(%2d) ", r_length);
540 break;
541 default:
542 outs() << format("?(%2d) ", r_length);
547 static void PrintRelocationEntries(const MachOObjectFile *O,
548 const relocation_iterator Begin,
549 const relocation_iterator End,
550 const uint64_t cputype,
551 const bool verbose) {
552 const MachO::symtab_command Symtab = O->getSymtabLoadCommand();
553 bool previous_arm_half = false;
554 bool previous_sectdiff = false;
555 uint32_t sectdiff_r_type = 0;
557 for (relocation_iterator Reloc = Begin; Reloc != End; ++Reloc) {
558 const DataRefImpl Rel = Reloc->getRawDataRefImpl();
559 const MachO::any_relocation_info RE = O->getRelocation(Rel);
560 const unsigned r_type = O->getAnyRelocationType(RE);
561 const bool r_scattered = O->isRelocationScattered(RE);
562 const unsigned r_pcrel = O->getAnyRelocationPCRel(RE);
563 const unsigned r_length = O->getAnyRelocationLength(RE);
564 const unsigned r_address = O->getAnyRelocationAddress(RE);
565 const bool r_extern = (r_scattered ? false :
566 O->getPlainRelocationExternal(RE));
567 const uint32_t r_value = (r_scattered ?
568 O->getScatteredRelocationValue(RE) : 0);
569 const unsigned r_symbolnum = (r_scattered ? 0 :
570 O->getPlainRelocationSymbolNum(RE));
572 if (r_scattered && cputype != MachO::CPU_TYPE_X86_64) {
573 if (verbose) {
574 // scattered: address
575 if ((cputype == MachO::CPU_TYPE_I386 &&
576 r_type == llvm::MachO::GENERIC_RELOC_PAIR) ||
577 (cputype == MachO::CPU_TYPE_ARM &&
578 r_type == llvm::MachO::ARM_RELOC_PAIR))
579 outs() << " ";
580 else
581 outs() << format("%08x ", (unsigned int)r_address);
583 // scattered: pcrel
584 if (r_pcrel)
585 outs() << "True ";
586 else
587 outs() << "False ";
589 // scattered: length
590 PrintRLength(cputype, r_type, r_length, previous_arm_half);
592 // scattered: extern & type
593 outs() << "n/a ";
594 PrintRType(cputype, r_type);
596 // scattered: scattered & value
597 outs() << format("True 0x%08x", (unsigned int)r_value);
598 if (previous_sectdiff == false) {
599 if ((cputype == MachO::CPU_TYPE_ARM &&
600 r_type == llvm::MachO::ARM_RELOC_PAIR))
601 outs() << format(" half = 0x%04x ", (unsigned int)r_address);
603 else if (cputype == MachO::CPU_TYPE_ARM &&
604 sectdiff_r_type == llvm::MachO::ARM_RELOC_HALF_SECTDIFF)
605 outs() << format(" other_half = 0x%04x ", (unsigned int)r_address);
606 if ((cputype == MachO::CPU_TYPE_I386 &&
607 (r_type == llvm::MachO::GENERIC_RELOC_SECTDIFF ||
608 r_type == llvm::MachO::GENERIC_RELOC_LOCAL_SECTDIFF)) ||
609 (cputype == MachO::CPU_TYPE_ARM &&
610 (sectdiff_r_type == llvm::MachO::ARM_RELOC_SECTDIFF ||
611 sectdiff_r_type == llvm::MachO::ARM_RELOC_LOCAL_SECTDIFF ||
612 sectdiff_r_type == llvm::MachO::ARM_RELOC_HALF_SECTDIFF))) {
613 previous_sectdiff = true;
614 sectdiff_r_type = r_type;
616 else {
617 previous_sectdiff = false;
618 sectdiff_r_type = 0;
620 if (cputype == MachO::CPU_TYPE_ARM &&
621 (r_type == llvm::MachO::ARM_RELOC_HALF ||
622 r_type == llvm::MachO::ARM_RELOC_HALF_SECTDIFF))
623 previous_arm_half = true;
624 else
625 previous_arm_half = false;
626 outs() << "\n";
628 else {
629 // scattered: address pcrel length extern type scattered value
630 outs() << format("%08x %1d %-2d n/a %-7d 1 0x%08x\n",
631 (unsigned int)r_address, r_pcrel, r_length, r_type,
632 (unsigned int)r_value);
635 else {
636 if (verbose) {
637 // plain: address
638 if (cputype == MachO::CPU_TYPE_ARM &&
639 r_type == llvm::MachO::ARM_RELOC_PAIR)
640 outs() << " ";
641 else
642 outs() << format("%08x ", (unsigned int)r_address);
644 // plain: pcrel
645 if (r_pcrel)
646 outs() << "True ";
647 else
648 outs() << "False ";
650 // plain: length
651 PrintRLength(cputype, r_type, r_length, previous_arm_half);
653 if (r_extern) {
654 // plain: extern & type & scattered
655 outs() << "True ";
656 PrintRType(cputype, r_type);
657 outs() << "False ";
659 // plain: symbolnum/value
660 if (r_symbolnum > Symtab.nsyms)
661 outs() << format("?(%d)\n", r_symbolnum);
662 else {
663 SymbolRef Symbol = *O->getSymbolByIndex(r_symbolnum);
664 Expected<StringRef> SymNameNext = Symbol.getName();
665 const char *name = NULL;
666 if (SymNameNext)
667 name = SymNameNext->data();
668 if (name == NULL)
669 outs() << format("?(%d)\n", r_symbolnum);
670 else
671 outs() << name << "\n";
674 else {
675 // plain: extern & type & scattered
676 outs() << "False ";
677 PrintRType(cputype, r_type);
678 outs() << "False ";
680 // plain: symbolnum/value
681 if (cputype == MachO::CPU_TYPE_ARM &&
682 r_type == llvm::MachO::ARM_RELOC_PAIR)
683 outs() << format("other_half = 0x%04x\n", (unsigned int)r_address);
684 else if (cputype == MachO::CPU_TYPE_ARM64 &&
685 r_type == llvm::MachO::ARM64_RELOC_ADDEND)
686 outs() << format("addend = 0x%06x\n", (unsigned int)r_symbolnum);
687 else {
688 outs() << format("%d ", r_symbolnum);
689 if (r_symbolnum == llvm::MachO::R_ABS)
690 outs() << "R_ABS\n";
691 else {
692 // in this case, r_symbolnum is actually a 1-based section number
693 uint32_t nsects = O->section_end()->getRawDataRefImpl().d.a;
694 if (r_symbolnum > 0 && r_symbolnum <= nsects) {
695 llvm::object::DataRefImpl DRI;
696 DRI.d.a = r_symbolnum-1;
697 StringRef SegName = O->getSectionFinalSegmentName(DRI);
698 StringRef SectName;
699 if (O->getSectionName(DRI, SectName))
700 outs() << "(?,?)\n";
701 else
702 outs() << "(" << SegName << "," << SectName << ")\n";
704 else {
705 outs() << "(?,?)\n";
710 if (cputype == MachO::CPU_TYPE_ARM &&
711 (r_type == llvm::MachO::ARM_RELOC_HALF ||
712 r_type == llvm::MachO::ARM_RELOC_HALF_SECTDIFF))
713 previous_arm_half = true;
714 else
715 previous_arm_half = false;
717 else {
718 // plain: address pcrel length extern type scattered symbolnum/section
719 outs() << format("%08x %1d %-2d %1d %-7d 0 %d\n",
720 (unsigned int)r_address, r_pcrel, r_length, r_extern,
721 r_type, r_symbolnum);
727 static void PrintRelocations(const MachOObjectFile *O, const bool verbose) {
728 const uint64_t cputype = O->getHeader().cputype;
729 const MachO::dysymtab_command Dysymtab = O->getDysymtabLoadCommand();
730 if (Dysymtab.nextrel != 0) {
731 outs() << "External relocation information " << Dysymtab.nextrel
732 << " entries";
733 outs() << "\naddress pcrel length extern type scattered "
734 "symbolnum/value\n";
735 PrintRelocationEntries(O, O->extrel_begin(), O->extrel_end(), cputype,
736 verbose);
738 if (Dysymtab.nlocrel != 0) {
739 outs() << format("Local relocation information %u entries",
740 Dysymtab.nlocrel);
741 outs() << "\naddress pcrel length extern type scattered "
742 "symbolnum/value\n";
743 PrintRelocationEntries(O, O->locrel_begin(), O->locrel_end(), cputype,
744 verbose);
746 for (const auto &Load : O->load_commands()) {
747 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
748 const MachO::segment_command_64 Seg = O->getSegment64LoadCommand(Load);
749 for (unsigned J = 0; J < Seg.nsects; ++J) {
750 const MachO::section_64 Sec = O->getSection64(Load, J);
751 if (Sec.nreloc != 0) {
752 DataRefImpl DRI;
753 DRI.d.a = J;
754 const StringRef SegName = O->getSectionFinalSegmentName(DRI);
755 StringRef SectName;
756 if (O->getSectionName(DRI, SectName))
757 outs() << "Relocation information (" << SegName << ",?) "
758 << format("%u entries", Sec.nreloc);
759 else
760 outs() << "Relocation information (" << SegName << ","
761 << SectName << format(") %u entries", Sec.nreloc);
762 outs() << "\naddress pcrel length extern type scattered "
763 "symbolnum/value\n";
764 PrintRelocationEntries(O, O->section_rel_begin(DRI),
765 O->section_rel_end(DRI), cputype, verbose);
768 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
769 const MachO::segment_command Seg = O->getSegmentLoadCommand(Load);
770 for (unsigned J = 0; J < Seg.nsects; ++J) {
771 const MachO::section Sec = O->getSection(Load, J);
772 if (Sec.nreloc != 0) {
773 DataRefImpl DRI;
774 DRI.d.a = J;
775 const StringRef SegName = O->getSectionFinalSegmentName(DRI);
776 StringRef SectName;
777 if (O->getSectionName(DRI, SectName))
778 outs() << "Relocation information (" << SegName << ",?) "
779 << format("%u entries", Sec.nreloc);
780 else
781 outs() << "Relocation information (" << SegName << ","
782 << SectName << format(") %u entries", Sec.nreloc);
783 outs() << "\naddress pcrel length extern type scattered "
784 "symbolnum/value\n";
785 PrintRelocationEntries(O, O->section_rel_begin(DRI),
786 O->section_rel_end(DRI), cputype, verbose);
793 static void PrintDataInCodeTable(MachOObjectFile *O, bool verbose) {
794 MachO::linkedit_data_command DIC = O->getDataInCodeLoadCommand();
795 uint32_t nentries = DIC.datasize / sizeof(struct MachO::data_in_code_entry);
796 outs() << "Data in code table (" << nentries << " entries)\n";
797 outs() << "offset length kind\n";
798 for (dice_iterator DI = O->begin_dices(), DE = O->end_dices(); DI != DE;
799 ++DI) {
800 uint32_t Offset;
801 DI->getOffset(Offset);
802 outs() << format("0x%08" PRIx32, Offset) << " ";
803 uint16_t Length;
804 DI->getLength(Length);
805 outs() << format("%6u", Length) << " ";
806 uint16_t Kind;
807 DI->getKind(Kind);
808 if (verbose) {
809 switch (Kind) {
810 case MachO::DICE_KIND_DATA:
811 outs() << "DATA";
812 break;
813 case MachO::DICE_KIND_JUMP_TABLE8:
814 outs() << "JUMP_TABLE8";
815 break;
816 case MachO::DICE_KIND_JUMP_TABLE16:
817 outs() << "JUMP_TABLE16";
818 break;
819 case MachO::DICE_KIND_JUMP_TABLE32:
820 outs() << "JUMP_TABLE32";
821 break;
822 case MachO::DICE_KIND_ABS_JUMP_TABLE32:
823 outs() << "ABS_JUMP_TABLE32";
824 break;
825 default:
826 outs() << format("0x%04" PRIx32, Kind);
827 break;
829 } else
830 outs() << format("0x%04" PRIx32, Kind);
831 outs() << "\n";
835 static void PrintLinkOptHints(MachOObjectFile *O) {
836 MachO::linkedit_data_command LohLC = O->getLinkOptHintsLoadCommand();
837 const char *loh = O->getData().substr(LohLC.dataoff, 1).data();
838 uint32_t nloh = LohLC.datasize;
839 outs() << "Linker optimiztion hints (" << nloh << " total bytes)\n";
840 for (uint32_t i = 0; i < nloh;) {
841 unsigned n;
842 uint64_t identifier = decodeULEB128((const uint8_t *)(loh + i), &n);
843 i += n;
844 outs() << " identifier " << identifier << " ";
845 if (i >= nloh)
846 return;
847 switch (identifier) {
848 case 1:
849 outs() << "AdrpAdrp\n";
850 break;
851 case 2:
852 outs() << "AdrpLdr\n";
853 break;
854 case 3:
855 outs() << "AdrpAddLdr\n";
856 break;
857 case 4:
858 outs() << "AdrpLdrGotLdr\n";
859 break;
860 case 5:
861 outs() << "AdrpAddStr\n";
862 break;
863 case 6:
864 outs() << "AdrpLdrGotStr\n";
865 break;
866 case 7:
867 outs() << "AdrpAdd\n";
868 break;
869 case 8:
870 outs() << "AdrpLdrGot\n";
871 break;
872 default:
873 outs() << "Unknown identifier value\n";
874 break;
876 uint64_t narguments = decodeULEB128((const uint8_t *)(loh + i), &n);
877 i += n;
878 outs() << " narguments " << narguments << "\n";
879 if (i >= nloh)
880 return;
882 for (uint32_t j = 0; j < narguments; j++) {
883 uint64_t value = decodeULEB128((const uint8_t *)(loh + i), &n);
884 i += n;
885 outs() << "\tvalue " << format("0x%" PRIx64, value) << "\n";
886 if (i >= nloh)
887 return;
892 static void PrintDylibs(MachOObjectFile *O, bool JustId) {
893 unsigned Index = 0;
894 for (const auto &Load : O->load_commands()) {
895 if ((JustId && Load.C.cmd == MachO::LC_ID_DYLIB) ||
896 (!JustId && (Load.C.cmd == MachO::LC_ID_DYLIB ||
897 Load.C.cmd == MachO::LC_LOAD_DYLIB ||
898 Load.C.cmd == MachO::LC_LOAD_WEAK_DYLIB ||
899 Load.C.cmd == MachO::LC_REEXPORT_DYLIB ||
900 Load.C.cmd == MachO::LC_LAZY_LOAD_DYLIB ||
901 Load.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB))) {
902 MachO::dylib_command dl = O->getDylibIDLoadCommand(Load);
903 if (dl.dylib.name < dl.cmdsize) {
904 const char *p = (const char *)(Load.Ptr) + dl.dylib.name;
905 if (JustId)
906 outs() << p << "\n";
907 else {
908 outs() << "\t" << p;
909 outs() << " (compatibility version "
910 << ((dl.dylib.compatibility_version >> 16) & 0xffff) << "."
911 << ((dl.dylib.compatibility_version >> 8) & 0xff) << "."
912 << (dl.dylib.compatibility_version & 0xff) << ",";
913 outs() << " current version "
914 << ((dl.dylib.current_version >> 16) & 0xffff) << "."
915 << ((dl.dylib.current_version >> 8) & 0xff) << "."
916 << (dl.dylib.current_version & 0xff) << ")\n";
918 } else {
919 outs() << "\tBad offset (" << dl.dylib.name << ") for name of ";
920 if (Load.C.cmd == MachO::LC_ID_DYLIB)
921 outs() << "LC_ID_DYLIB ";
922 else if (Load.C.cmd == MachO::LC_LOAD_DYLIB)
923 outs() << "LC_LOAD_DYLIB ";
924 else if (Load.C.cmd == MachO::LC_LOAD_WEAK_DYLIB)
925 outs() << "LC_LOAD_WEAK_DYLIB ";
926 else if (Load.C.cmd == MachO::LC_LAZY_LOAD_DYLIB)
927 outs() << "LC_LAZY_LOAD_DYLIB ";
928 else if (Load.C.cmd == MachO::LC_REEXPORT_DYLIB)
929 outs() << "LC_REEXPORT_DYLIB ";
930 else if (Load.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB)
931 outs() << "LC_LOAD_UPWARD_DYLIB ";
932 else
933 outs() << "LC_??? ";
934 outs() << "command " << Index++ << "\n";
940 typedef DenseMap<uint64_t, StringRef> SymbolAddressMap;
942 static void CreateSymbolAddressMap(MachOObjectFile *O,
943 SymbolAddressMap *AddrMap) {
944 // Create a map of symbol addresses to symbol names.
945 for (const SymbolRef &Symbol : O->symbols()) {
946 Expected<SymbolRef::Type> STOrErr = Symbol.getType();
947 if (!STOrErr)
948 report_error(O->getFileName(), STOrErr.takeError());
949 SymbolRef::Type ST = *STOrErr;
950 if (ST == SymbolRef::ST_Function || ST == SymbolRef::ST_Data ||
951 ST == SymbolRef::ST_Other) {
952 uint64_t Address = Symbol.getValue();
953 Expected<StringRef> SymNameOrErr = Symbol.getName();
954 if (!SymNameOrErr)
955 report_error(O->getFileName(), SymNameOrErr.takeError());
956 StringRef SymName = *SymNameOrErr;
957 if (!SymName.startswith(".objc"))
958 (*AddrMap)[Address] = SymName;
963 // GuessSymbolName is passed the address of what might be a symbol and a
964 // pointer to the SymbolAddressMap. It returns the name of a symbol
965 // with that address or nullptr if no symbol is found with that address.
966 static const char *GuessSymbolName(uint64_t value, SymbolAddressMap *AddrMap) {
967 const char *SymbolName = nullptr;
968 // A DenseMap can't lookup up some values.
969 if (value != 0xffffffffffffffffULL && value != 0xfffffffffffffffeULL) {
970 StringRef name = AddrMap->lookup(value);
971 if (!name.empty())
972 SymbolName = name.data();
974 return SymbolName;
977 static void DumpCstringChar(const char c) {
978 char p[2];
979 p[0] = c;
980 p[1] = '\0';
981 outs().write_escaped(p);
984 static void DumpCstringSection(MachOObjectFile *O, const char *sect,
985 uint32_t sect_size, uint64_t sect_addr,
986 bool print_addresses) {
987 for (uint32_t i = 0; i < sect_size; i++) {
988 if (print_addresses) {
989 if (O->is64Bit())
990 outs() << format("%016" PRIx64, sect_addr + i) << " ";
991 else
992 outs() << format("%08" PRIx64, sect_addr + i) << " ";
994 for (; i < sect_size && sect[i] != '\0'; i++)
995 DumpCstringChar(sect[i]);
996 if (i < sect_size && sect[i] == '\0')
997 outs() << "\n";
1001 static void DumpLiteral4(uint32_t l, float f) {
1002 outs() << format("0x%08" PRIx32, l);
1003 if ((l & 0x7f800000) != 0x7f800000)
1004 outs() << format(" (%.16e)\n", f);
1005 else {
1006 if (l == 0x7f800000)
1007 outs() << " (+Infinity)\n";
1008 else if (l == 0xff800000)
1009 outs() << " (-Infinity)\n";
1010 else if ((l & 0x00400000) == 0x00400000)
1011 outs() << " (non-signaling Not-a-Number)\n";
1012 else
1013 outs() << " (signaling Not-a-Number)\n";
1017 static void DumpLiteral4Section(MachOObjectFile *O, const char *sect,
1018 uint32_t sect_size, uint64_t sect_addr,
1019 bool print_addresses) {
1020 for (uint32_t i = 0; i < sect_size; i += sizeof(float)) {
1021 if (print_addresses) {
1022 if (O->is64Bit())
1023 outs() << format("%016" PRIx64, sect_addr + i) << " ";
1024 else
1025 outs() << format("%08" PRIx64, sect_addr + i) << " ";
1027 float f;
1028 memcpy(&f, sect + i, sizeof(float));
1029 if (O->isLittleEndian() != sys::IsLittleEndianHost)
1030 sys::swapByteOrder(f);
1031 uint32_t l;
1032 memcpy(&l, sect + i, sizeof(uint32_t));
1033 if (O->isLittleEndian() != sys::IsLittleEndianHost)
1034 sys::swapByteOrder(l);
1035 DumpLiteral4(l, f);
1039 static void DumpLiteral8(MachOObjectFile *O, uint32_t l0, uint32_t l1,
1040 double d) {
1041 outs() << format("0x%08" PRIx32, l0) << " " << format("0x%08" PRIx32, l1);
1042 uint32_t Hi, Lo;
1043 Hi = (O->isLittleEndian()) ? l1 : l0;
1044 Lo = (O->isLittleEndian()) ? l0 : l1;
1046 // Hi is the high word, so this is equivalent to if(isfinite(d))
1047 if ((Hi & 0x7ff00000) != 0x7ff00000)
1048 outs() << format(" (%.16e)\n", d);
1049 else {
1050 if (Hi == 0x7ff00000 && Lo == 0)
1051 outs() << " (+Infinity)\n";
1052 else if (Hi == 0xfff00000 && Lo == 0)
1053 outs() << " (-Infinity)\n";
1054 else if ((Hi & 0x00080000) == 0x00080000)
1055 outs() << " (non-signaling Not-a-Number)\n";
1056 else
1057 outs() << " (signaling Not-a-Number)\n";
1061 static void DumpLiteral8Section(MachOObjectFile *O, const char *sect,
1062 uint32_t sect_size, uint64_t sect_addr,
1063 bool print_addresses) {
1064 for (uint32_t i = 0; i < sect_size; i += sizeof(double)) {
1065 if (print_addresses) {
1066 if (O->is64Bit())
1067 outs() << format("%016" PRIx64, sect_addr + i) << " ";
1068 else
1069 outs() << format("%08" PRIx64, sect_addr + i) << " ";
1071 double d;
1072 memcpy(&d, sect + i, sizeof(double));
1073 if (O->isLittleEndian() != sys::IsLittleEndianHost)
1074 sys::swapByteOrder(d);
1075 uint32_t l0, l1;
1076 memcpy(&l0, sect + i, sizeof(uint32_t));
1077 memcpy(&l1, sect + i + sizeof(uint32_t), sizeof(uint32_t));
1078 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
1079 sys::swapByteOrder(l0);
1080 sys::swapByteOrder(l1);
1082 DumpLiteral8(O, l0, l1, d);
1086 static void DumpLiteral16(uint32_t l0, uint32_t l1, uint32_t l2, uint32_t l3) {
1087 outs() << format("0x%08" PRIx32, l0) << " ";
1088 outs() << format("0x%08" PRIx32, l1) << " ";
1089 outs() << format("0x%08" PRIx32, l2) << " ";
1090 outs() << format("0x%08" PRIx32, l3) << "\n";
1093 static void DumpLiteral16Section(MachOObjectFile *O, const char *sect,
1094 uint32_t sect_size, uint64_t sect_addr,
1095 bool print_addresses) {
1096 for (uint32_t i = 0; i < sect_size; i += 16) {
1097 if (print_addresses) {
1098 if (O->is64Bit())
1099 outs() << format("%016" PRIx64, sect_addr + i) << " ";
1100 else
1101 outs() << format("%08" PRIx64, sect_addr + i) << " ";
1103 uint32_t l0, l1, l2, l3;
1104 memcpy(&l0, sect + i, sizeof(uint32_t));
1105 memcpy(&l1, sect + i + sizeof(uint32_t), sizeof(uint32_t));
1106 memcpy(&l2, sect + i + 2 * sizeof(uint32_t), sizeof(uint32_t));
1107 memcpy(&l3, sect + i + 3 * sizeof(uint32_t), sizeof(uint32_t));
1108 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
1109 sys::swapByteOrder(l0);
1110 sys::swapByteOrder(l1);
1111 sys::swapByteOrder(l2);
1112 sys::swapByteOrder(l3);
1114 DumpLiteral16(l0, l1, l2, l3);
1118 static void DumpLiteralPointerSection(MachOObjectFile *O,
1119 const SectionRef &Section,
1120 const char *sect, uint32_t sect_size,
1121 uint64_t sect_addr,
1122 bool print_addresses) {
1123 // Collect the literal sections in this Mach-O file.
1124 std::vector<SectionRef> LiteralSections;
1125 for (const SectionRef &Section : O->sections()) {
1126 DataRefImpl Ref = Section.getRawDataRefImpl();
1127 uint32_t section_type;
1128 if (O->is64Bit()) {
1129 const MachO::section_64 Sec = O->getSection64(Ref);
1130 section_type = Sec.flags & MachO::SECTION_TYPE;
1131 } else {
1132 const MachO::section Sec = O->getSection(Ref);
1133 section_type = Sec.flags & MachO::SECTION_TYPE;
1135 if (section_type == MachO::S_CSTRING_LITERALS ||
1136 section_type == MachO::S_4BYTE_LITERALS ||
1137 section_type == MachO::S_8BYTE_LITERALS ||
1138 section_type == MachO::S_16BYTE_LITERALS)
1139 LiteralSections.push_back(Section);
1142 // Set the size of the literal pointer.
1143 uint32_t lp_size = O->is64Bit() ? 8 : 4;
1145 // Collect the external relocation symbols for the literal pointers.
1146 std::vector<std::pair<uint64_t, SymbolRef>> Relocs;
1147 for (const RelocationRef &Reloc : Section.relocations()) {
1148 DataRefImpl Rel;
1149 MachO::any_relocation_info RE;
1150 bool isExtern = false;
1151 Rel = Reloc.getRawDataRefImpl();
1152 RE = O->getRelocation(Rel);
1153 isExtern = O->getPlainRelocationExternal(RE);
1154 if (isExtern) {
1155 uint64_t RelocOffset = Reloc.getOffset();
1156 symbol_iterator RelocSym = Reloc.getSymbol();
1157 Relocs.push_back(std::make_pair(RelocOffset, *RelocSym));
1160 array_pod_sort(Relocs.begin(), Relocs.end());
1162 // Dump each literal pointer.
1163 for (uint32_t i = 0; i < sect_size; i += lp_size) {
1164 if (print_addresses) {
1165 if (O->is64Bit())
1166 outs() << format("%016" PRIx64, sect_addr + i) << " ";
1167 else
1168 outs() << format("%08" PRIx64, sect_addr + i) << " ";
1170 uint64_t lp;
1171 if (O->is64Bit()) {
1172 memcpy(&lp, sect + i, sizeof(uint64_t));
1173 if (O->isLittleEndian() != sys::IsLittleEndianHost)
1174 sys::swapByteOrder(lp);
1175 } else {
1176 uint32_t li;
1177 memcpy(&li, sect + i, sizeof(uint32_t));
1178 if (O->isLittleEndian() != sys::IsLittleEndianHost)
1179 sys::swapByteOrder(li);
1180 lp = li;
1183 // First look for an external relocation entry for this literal pointer.
1184 auto Reloc = find_if(Relocs, [&](const std::pair<uint64_t, SymbolRef> &P) {
1185 return P.first == i;
1187 if (Reloc != Relocs.end()) {
1188 symbol_iterator RelocSym = Reloc->second;
1189 Expected<StringRef> SymName = RelocSym->getName();
1190 if (!SymName)
1191 report_error(O->getFileName(), SymName.takeError());
1192 outs() << "external relocation entry for symbol:" << *SymName << "\n";
1193 continue;
1196 // For local references see what the section the literal pointer points to.
1197 auto Sect = find_if(LiteralSections, [&](const SectionRef &R) {
1198 return lp >= R.getAddress() && lp < R.getAddress() + R.getSize();
1200 if (Sect == LiteralSections.end()) {
1201 outs() << format("0x%" PRIx64, lp) << " (not in a literal section)\n";
1202 continue;
1205 uint64_t SectAddress = Sect->getAddress();
1206 uint64_t SectSize = Sect->getSize();
1208 StringRef SectName;
1209 Sect->getName(SectName);
1210 DataRefImpl Ref = Sect->getRawDataRefImpl();
1211 StringRef SegmentName = O->getSectionFinalSegmentName(Ref);
1212 outs() << SegmentName << ":" << SectName << ":";
1214 uint32_t section_type;
1215 if (O->is64Bit()) {
1216 const MachO::section_64 Sec = O->getSection64(Ref);
1217 section_type = Sec.flags & MachO::SECTION_TYPE;
1218 } else {
1219 const MachO::section Sec = O->getSection(Ref);
1220 section_type = Sec.flags & MachO::SECTION_TYPE;
1223 StringRef BytesStr;
1224 Sect->getContents(BytesStr);
1225 const char *Contents = reinterpret_cast<const char *>(BytesStr.data());
1227 switch (section_type) {
1228 case MachO::S_CSTRING_LITERALS:
1229 for (uint64_t i = lp - SectAddress; i < SectSize && Contents[i] != '\0';
1230 i++) {
1231 DumpCstringChar(Contents[i]);
1233 outs() << "\n";
1234 break;
1235 case MachO::S_4BYTE_LITERALS:
1236 float f;
1237 memcpy(&f, Contents + (lp - SectAddress), sizeof(float));
1238 uint32_t l;
1239 memcpy(&l, Contents + (lp - SectAddress), sizeof(uint32_t));
1240 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
1241 sys::swapByteOrder(f);
1242 sys::swapByteOrder(l);
1244 DumpLiteral4(l, f);
1245 break;
1246 case MachO::S_8BYTE_LITERALS: {
1247 double d;
1248 memcpy(&d, Contents + (lp - SectAddress), sizeof(double));
1249 uint32_t l0, l1;
1250 memcpy(&l0, Contents + (lp - SectAddress), sizeof(uint32_t));
1251 memcpy(&l1, Contents + (lp - SectAddress) + sizeof(uint32_t),
1252 sizeof(uint32_t));
1253 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
1254 sys::swapByteOrder(f);
1255 sys::swapByteOrder(l0);
1256 sys::swapByteOrder(l1);
1258 DumpLiteral8(O, l0, l1, d);
1259 break;
1261 case MachO::S_16BYTE_LITERALS: {
1262 uint32_t l0, l1, l2, l3;
1263 memcpy(&l0, Contents + (lp - SectAddress), sizeof(uint32_t));
1264 memcpy(&l1, Contents + (lp - SectAddress) + sizeof(uint32_t),
1265 sizeof(uint32_t));
1266 memcpy(&l2, Contents + (lp - SectAddress) + 2 * sizeof(uint32_t),
1267 sizeof(uint32_t));
1268 memcpy(&l3, Contents + (lp - SectAddress) + 3 * sizeof(uint32_t),
1269 sizeof(uint32_t));
1270 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
1271 sys::swapByteOrder(l0);
1272 sys::swapByteOrder(l1);
1273 sys::swapByteOrder(l2);
1274 sys::swapByteOrder(l3);
1276 DumpLiteral16(l0, l1, l2, l3);
1277 break;
1283 static void DumpInitTermPointerSection(MachOObjectFile *O,
1284 const SectionRef &Section,
1285 const char *sect,
1286 uint32_t sect_size, uint64_t sect_addr,
1287 SymbolAddressMap *AddrMap,
1288 bool verbose) {
1289 uint32_t stride;
1290 stride = (O->is64Bit()) ? sizeof(uint64_t) : sizeof(uint32_t);
1292 // Collect the external relocation symbols for the pointers.
1293 std::vector<std::pair<uint64_t, SymbolRef>> Relocs;
1294 for (const RelocationRef &Reloc : Section.relocations()) {
1295 DataRefImpl Rel;
1296 MachO::any_relocation_info RE;
1297 bool isExtern = false;
1298 Rel = Reloc.getRawDataRefImpl();
1299 RE = O->getRelocation(Rel);
1300 isExtern = O->getPlainRelocationExternal(RE);
1301 if (isExtern) {
1302 uint64_t RelocOffset = Reloc.getOffset();
1303 symbol_iterator RelocSym = Reloc.getSymbol();
1304 Relocs.push_back(std::make_pair(RelocOffset, *RelocSym));
1307 array_pod_sort(Relocs.begin(), Relocs.end());
1309 for (uint32_t i = 0; i < sect_size; i += stride) {
1310 const char *SymbolName = nullptr;
1311 uint64_t p;
1312 if (O->is64Bit()) {
1313 outs() << format("0x%016" PRIx64, sect_addr + i * stride) << " ";
1314 uint64_t pointer_value;
1315 memcpy(&pointer_value, sect + i, stride);
1316 if (O->isLittleEndian() != sys::IsLittleEndianHost)
1317 sys::swapByteOrder(pointer_value);
1318 outs() << format("0x%016" PRIx64, pointer_value);
1319 p = pointer_value;
1320 } else {
1321 outs() << format("0x%08" PRIx64, sect_addr + i * stride) << " ";
1322 uint32_t pointer_value;
1323 memcpy(&pointer_value, sect + i, stride);
1324 if (O->isLittleEndian() != sys::IsLittleEndianHost)
1325 sys::swapByteOrder(pointer_value);
1326 outs() << format("0x%08" PRIx32, pointer_value);
1327 p = pointer_value;
1329 if (verbose) {
1330 // First look for an external relocation entry for this pointer.
1331 auto Reloc = find_if(Relocs, [&](const std::pair<uint64_t, SymbolRef> &P) {
1332 return P.first == i;
1334 if (Reloc != Relocs.end()) {
1335 symbol_iterator RelocSym = Reloc->second;
1336 Expected<StringRef> SymName = RelocSym->getName();
1337 if (!SymName)
1338 report_error(O->getFileName(), SymName.takeError());
1339 outs() << " " << *SymName;
1340 } else {
1341 SymbolName = GuessSymbolName(p, AddrMap);
1342 if (SymbolName)
1343 outs() << " " << SymbolName;
1346 outs() << "\n";
1350 static void DumpRawSectionContents(MachOObjectFile *O, const char *sect,
1351 uint32_t size, uint64_t addr) {
1352 uint32_t cputype = O->getHeader().cputype;
1353 if (cputype == MachO::CPU_TYPE_I386 || cputype == MachO::CPU_TYPE_X86_64) {
1354 uint32_t j;
1355 for (uint32_t i = 0; i < size; i += j, addr += j) {
1356 if (O->is64Bit())
1357 outs() << format("%016" PRIx64, addr) << "\t";
1358 else
1359 outs() << format("%08" PRIx64, addr) << "\t";
1360 for (j = 0; j < 16 && i + j < size; j++) {
1361 uint8_t byte_word = *(sect + i + j);
1362 outs() << format("%02" PRIx32, (uint32_t)byte_word) << " ";
1364 outs() << "\n";
1366 } else {
1367 uint32_t j;
1368 for (uint32_t i = 0; i < size; i += j, addr += j) {
1369 if (O->is64Bit())
1370 outs() << format("%016" PRIx64, addr) << "\t";
1371 else
1372 outs() << format("%08" PRIx64, addr) << "\t";
1373 for (j = 0; j < 4 * sizeof(int32_t) && i + j < size;
1374 j += sizeof(int32_t)) {
1375 if (i + j + sizeof(int32_t) <= size) {
1376 uint32_t long_word;
1377 memcpy(&long_word, sect + i + j, sizeof(int32_t));
1378 if (O->isLittleEndian() != sys::IsLittleEndianHost)
1379 sys::swapByteOrder(long_word);
1380 outs() << format("%08" PRIx32, long_word) << " ";
1381 } else {
1382 for (uint32_t k = 0; i + j + k < size; k++) {
1383 uint8_t byte_word = *(sect + i + j + k);
1384 outs() << format("%02" PRIx32, (uint32_t)byte_word) << " ";
1388 outs() << "\n";
1393 static void DisassembleMachO(StringRef Filename, MachOObjectFile *MachOOF,
1394 StringRef DisSegName, StringRef DisSectName);
1395 static void DumpProtocolSection(MachOObjectFile *O, const char *sect,
1396 uint32_t size, uint32_t addr);
1397 #ifdef HAVE_LIBXAR
1398 static void DumpBitcodeSection(MachOObjectFile *O, const char *sect,
1399 uint32_t size, bool verbose,
1400 bool PrintXarHeader, bool PrintXarFileHeaders,
1401 std::string XarMemberName);
1402 #endif // defined(HAVE_LIBXAR)
1404 static void DumpSectionContents(StringRef Filename, MachOObjectFile *O,
1405 bool verbose) {
1406 SymbolAddressMap AddrMap;
1407 if (verbose)
1408 CreateSymbolAddressMap(O, &AddrMap);
1410 for (unsigned i = 0; i < FilterSections.size(); ++i) {
1411 StringRef DumpSection = FilterSections[i];
1412 std::pair<StringRef, StringRef> DumpSegSectName;
1413 DumpSegSectName = DumpSection.split(',');
1414 StringRef DumpSegName, DumpSectName;
1415 if (!DumpSegSectName.second.empty()) {
1416 DumpSegName = DumpSegSectName.first;
1417 DumpSectName = DumpSegSectName.second;
1418 } else {
1419 DumpSegName = "";
1420 DumpSectName = DumpSegSectName.first;
1422 for (const SectionRef &Section : O->sections()) {
1423 StringRef SectName;
1424 Section.getName(SectName);
1425 DataRefImpl Ref = Section.getRawDataRefImpl();
1426 StringRef SegName = O->getSectionFinalSegmentName(Ref);
1427 if ((DumpSegName.empty() || SegName == DumpSegName) &&
1428 (SectName == DumpSectName)) {
1430 uint32_t section_flags;
1431 if (O->is64Bit()) {
1432 const MachO::section_64 Sec = O->getSection64(Ref);
1433 section_flags = Sec.flags;
1435 } else {
1436 const MachO::section Sec = O->getSection(Ref);
1437 section_flags = Sec.flags;
1439 uint32_t section_type = section_flags & MachO::SECTION_TYPE;
1441 StringRef BytesStr;
1442 Section.getContents(BytesStr);
1443 const char *sect = reinterpret_cast<const char *>(BytesStr.data());
1444 uint32_t sect_size = BytesStr.size();
1445 uint64_t sect_addr = Section.getAddress();
1447 outs() << "Contents of (" << SegName << "," << SectName
1448 << ") section\n";
1450 if (verbose) {
1451 if ((section_flags & MachO::S_ATTR_PURE_INSTRUCTIONS) ||
1452 (section_flags & MachO::S_ATTR_SOME_INSTRUCTIONS)) {
1453 DisassembleMachO(Filename, O, SegName, SectName);
1454 continue;
1456 if (SegName == "__TEXT" && SectName == "__info_plist") {
1457 outs() << sect;
1458 continue;
1460 if (SegName == "__OBJC" && SectName == "__protocol") {
1461 DumpProtocolSection(O, sect, sect_size, sect_addr);
1462 continue;
1464 #ifdef HAVE_LIBXAR
1465 if (SegName == "__LLVM" && SectName == "__bundle") {
1466 DumpBitcodeSection(O, sect, sect_size, verbose, !NoSymbolicOperands,
1467 ArchiveHeaders, "");
1468 continue;
1470 #endif // defined(HAVE_LIBXAR)
1471 switch (section_type) {
1472 case MachO::S_REGULAR:
1473 DumpRawSectionContents(O, sect, sect_size, sect_addr);
1474 break;
1475 case MachO::S_ZEROFILL:
1476 outs() << "zerofill section and has no contents in the file\n";
1477 break;
1478 case MachO::S_CSTRING_LITERALS:
1479 DumpCstringSection(O, sect, sect_size, sect_addr, !NoLeadingAddr);
1480 break;
1481 case MachO::S_4BYTE_LITERALS:
1482 DumpLiteral4Section(O, sect, sect_size, sect_addr, !NoLeadingAddr);
1483 break;
1484 case MachO::S_8BYTE_LITERALS:
1485 DumpLiteral8Section(O, sect, sect_size, sect_addr, !NoLeadingAddr);
1486 break;
1487 case MachO::S_16BYTE_LITERALS:
1488 DumpLiteral16Section(O, sect, sect_size, sect_addr, !NoLeadingAddr);
1489 break;
1490 case MachO::S_LITERAL_POINTERS:
1491 DumpLiteralPointerSection(O, Section, sect, sect_size, sect_addr,
1492 !NoLeadingAddr);
1493 break;
1494 case MachO::S_MOD_INIT_FUNC_POINTERS:
1495 case MachO::S_MOD_TERM_FUNC_POINTERS:
1496 DumpInitTermPointerSection(O, Section, sect, sect_size, sect_addr,
1497 &AddrMap, verbose);
1498 break;
1499 default:
1500 outs() << "Unknown section type ("
1501 << format("0x%08" PRIx32, section_type) << ")\n";
1502 DumpRawSectionContents(O, sect, sect_size, sect_addr);
1503 break;
1505 } else {
1506 if (section_type == MachO::S_ZEROFILL)
1507 outs() << "zerofill section and has no contents in the file\n";
1508 else
1509 DumpRawSectionContents(O, sect, sect_size, sect_addr);
1516 static void DumpInfoPlistSectionContents(StringRef Filename,
1517 MachOObjectFile *O) {
1518 for (const SectionRef &Section : O->sections()) {
1519 StringRef SectName;
1520 Section.getName(SectName);
1521 DataRefImpl Ref = Section.getRawDataRefImpl();
1522 StringRef SegName = O->getSectionFinalSegmentName(Ref);
1523 if (SegName == "__TEXT" && SectName == "__info_plist") {
1524 if (!NoLeadingHeaders)
1525 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
1526 StringRef BytesStr;
1527 Section.getContents(BytesStr);
1528 const char *sect = reinterpret_cast<const char *>(BytesStr.data());
1529 outs() << format("%.*s", BytesStr.size(), sect) << "\n";
1530 return;
1535 // checkMachOAndArchFlags() checks to see if the ObjectFile is a Mach-O file
1536 // and if it is and there is a list of architecture flags is specified then
1537 // check to make sure this Mach-O file is one of those architectures or all
1538 // architectures were specified. If not then an error is generated and this
1539 // routine returns false. Else it returns true.
1540 static bool checkMachOAndArchFlags(ObjectFile *O, StringRef Filename) {
1541 auto *MachO = dyn_cast<MachOObjectFile>(O);
1543 if (!MachO || ArchAll || ArchFlags.empty())
1544 return true;
1546 MachO::mach_header H;
1547 MachO::mach_header_64 H_64;
1548 Triple T;
1549 const char *McpuDefault, *ArchFlag;
1550 if (MachO->is64Bit()) {
1551 H_64 = MachO->MachOObjectFile::getHeader64();
1552 T = MachOObjectFile::getArchTriple(H_64.cputype, H_64.cpusubtype,
1553 &McpuDefault, &ArchFlag);
1554 } else {
1555 H = MachO->MachOObjectFile::getHeader();
1556 T = MachOObjectFile::getArchTriple(H.cputype, H.cpusubtype,
1557 &McpuDefault, &ArchFlag);
1559 const std::string ArchFlagName(ArchFlag);
1560 if (none_of(ArchFlags, [&](const std::string &Name) {
1561 return Name == ArchFlagName;
1562 })) {
1563 WithColor::error(errs(), "llvm-objdump")
1564 << Filename << ": no architecture specified.\n";
1565 return false;
1567 return true;
1570 static void printObjcMetaData(MachOObjectFile *O, bool verbose);
1572 // ProcessMachO() is passed a single opened Mach-O file, which may be an
1573 // archive member and or in a slice of a universal file. It prints the
1574 // the file name and header info and then processes it according to the
1575 // command line options.
1576 static void ProcessMachO(StringRef Name, MachOObjectFile *MachOOF,
1577 StringRef ArchiveMemberName = StringRef(),
1578 StringRef ArchitectureName = StringRef()) {
1579 // If we are doing some processing here on the Mach-O file print the header
1580 // info. And don't print it otherwise like in the case of printing the
1581 // UniversalHeaders or ArchiveHeaders.
1582 if (Disassemble || Relocations || PrivateHeaders || ExportsTrie || Rebase ||
1583 Bind || SymbolTable || LazyBind || WeakBind || IndirectSymbols ||
1584 DataInCode || LinkOptHints || DylibsUsed || DylibId || ObjcMetaData ||
1585 (!FilterSections.empty())) {
1586 if (!NoLeadingHeaders) {
1587 outs() << Name;
1588 if (!ArchiveMemberName.empty())
1589 outs() << '(' << ArchiveMemberName << ')';
1590 if (!ArchitectureName.empty())
1591 outs() << " (architecture " << ArchitectureName << ")";
1592 outs() << ":\n";
1595 // To use the report_error() form with an ArchiveName and FileName set
1596 // these up based on what is passed for Name and ArchiveMemberName.
1597 StringRef ArchiveName;
1598 StringRef FileName;
1599 if (!ArchiveMemberName.empty()) {
1600 ArchiveName = Name;
1601 FileName = ArchiveMemberName;
1602 } else {
1603 ArchiveName = StringRef();
1604 FileName = Name;
1607 // If we need the symbol table to do the operation then check it here to
1608 // produce a good error message as to where the Mach-O file comes from in
1609 // the error message.
1610 if (Disassemble || IndirectSymbols || !FilterSections.empty() || UnwindInfo)
1611 if (Error Err = MachOOF->checkSymbolTable())
1612 report_error(ArchiveName, FileName, std::move(Err), ArchitectureName);
1614 if (Disassemble) {
1615 if (MachOOF->getHeader().filetype == MachO::MH_KEXT_BUNDLE &&
1616 MachOOF->getHeader().cputype == MachO::CPU_TYPE_ARM64)
1617 DisassembleMachO(FileName, MachOOF, "__TEXT_EXEC", "__text");
1618 else
1619 DisassembleMachO(FileName, MachOOF, "__TEXT", "__text");
1621 if (IndirectSymbols)
1622 PrintIndirectSymbols(MachOOF, !NonVerbose);
1623 if (DataInCode)
1624 PrintDataInCodeTable(MachOOF, !NonVerbose);
1625 if (LinkOptHints)
1626 PrintLinkOptHints(MachOOF);
1627 if (Relocations)
1628 PrintRelocations(MachOOF, !NonVerbose);
1629 if (SectionHeaders)
1630 PrintSectionHeaders(MachOOF);
1631 if (SectionContents)
1632 PrintSectionContents(MachOOF);
1633 if (!FilterSections.empty())
1634 DumpSectionContents(FileName, MachOOF, !NonVerbose);
1635 if (InfoPlist)
1636 DumpInfoPlistSectionContents(FileName, MachOOF);
1637 if (DylibsUsed)
1638 PrintDylibs(MachOOF, false);
1639 if (DylibId)
1640 PrintDylibs(MachOOF, true);
1641 if (SymbolTable)
1642 PrintSymbolTable(MachOOF, ArchiveName, ArchitectureName);
1643 if (UnwindInfo)
1644 printMachOUnwindInfo(MachOOF);
1645 if (PrivateHeaders) {
1646 printMachOFileHeader(MachOOF);
1647 printMachOLoadCommands(MachOOF);
1649 if (FirstPrivateHeader)
1650 printMachOFileHeader(MachOOF);
1651 if (ObjcMetaData)
1652 printObjcMetaData(MachOOF, !NonVerbose);
1653 if (ExportsTrie)
1654 printExportsTrie(MachOOF);
1655 if (Rebase)
1656 printRebaseTable(MachOOF);
1657 if (Bind)
1658 printBindTable(MachOOF);
1659 if (LazyBind)
1660 printLazyBindTable(MachOOF);
1661 if (WeakBind)
1662 printWeakBindTable(MachOOF);
1664 if (DwarfDumpType != DIDT_Null) {
1665 std::unique_ptr<DIContext> DICtx = DWARFContext::create(*MachOOF);
1666 // Dump the complete DWARF structure.
1667 DIDumpOptions DumpOpts;
1668 DumpOpts.DumpType = DwarfDumpType;
1669 DICtx->dump(outs(), DumpOpts);
1673 // printUnknownCPUType() helps print_fat_headers for unknown CPU's.
1674 static void printUnknownCPUType(uint32_t cputype, uint32_t cpusubtype) {
1675 outs() << " cputype (" << cputype << ")\n";
1676 outs() << " cpusubtype (" << cpusubtype << ")\n";
1679 // printCPUType() helps print_fat_headers by printing the cputype and
1680 // pusubtype (symbolically for the one's it knows about).
1681 static void printCPUType(uint32_t cputype, uint32_t cpusubtype) {
1682 switch (cputype) {
1683 case MachO::CPU_TYPE_I386:
1684 switch (cpusubtype) {
1685 case MachO::CPU_SUBTYPE_I386_ALL:
1686 outs() << " cputype CPU_TYPE_I386\n";
1687 outs() << " cpusubtype CPU_SUBTYPE_I386_ALL\n";
1688 break;
1689 default:
1690 printUnknownCPUType(cputype, cpusubtype);
1691 break;
1693 break;
1694 case MachO::CPU_TYPE_X86_64:
1695 switch (cpusubtype) {
1696 case MachO::CPU_SUBTYPE_X86_64_ALL:
1697 outs() << " cputype CPU_TYPE_X86_64\n";
1698 outs() << " cpusubtype CPU_SUBTYPE_X86_64_ALL\n";
1699 break;
1700 case MachO::CPU_SUBTYPE_X86_64_H:
1701 outs() << " cputype CPU_TYPE_X86_64\n";
1702 outs() << " cpusubtype CPU_SUBTYPE_X86_64_H\n";
1703 break;
1704 default:
1705 printUnknownCPUType(cputype, cpusubtype);
1706 break;
1708 break;
1709 case MachO::CPU_TYPE_ARM:
1710 switch (cpusubtype) {
1711 case MachO::CPU_SUBTYPE_ARM_ALL:
1712 outs() << " cputype CPU_TYPE_ARM\n";
1713 outs() << " cpusubtype CPU_SUBTYPE_ARM_ALL\n";
1714 break;
1715 case MachO::CPU_SUBTYPE_ARM_V4T:
1716 outs() << " cputype CPU_TYPE_ARM\n";
1717 outs() << " cpusubtype CPU_SUBTYPE_ARM_V4T\n";
1718 break;
1719 case MachO::CPU_SUBTYPE_ARM_V5TEJ:
1720 outs() << " cputype CPU_TYPE_ARM\n";
1721 outs() << " cpusubtype CPU_SUBTYPE_ARM_V5TEJ\n";
1722 break;
1723 case MachO::CPU_SUBTYPE_ARM_XSCALE:
1724 outs() << " cputype CPU_TYPE_ARM\n";
1725 outs() << " cpusubtype CPU_SUBTYPE_ARM_XSCALE\n";
1726 break;
1727 case MachO::CPU_SUBTYPE_ARM_V6:
1728 outs() << " cputype CPU_TYPE_ARM\n";
1729 outs() << " cpusubtype CPU_SUBTYPE_ARM_V6\n";
1730 break;
1731 case MachO::CPU_SUBTYPE_ARM_V6M:
1732 outs() << " cputype CPU_TYPE_ARM\n";
1733 outs() << " cpusubtype CPU_SUBTYPE_ARM_V6M\n";
1734 break;
1735 case MachO::CPU_SUBTYPE_ARM_V7:
1736 outs() << " cputype CPU_TYPE_ARM\n";
1737 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7\n";
1738 break;
1739 case MachO::CPU_SUBTYPE_ARM_V7EM:
1740 outs() << " cputype CPU_TYPE_ARM\n";
1741 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7EM\n";
1742 break;
1743 case MachO::CPU_SUBTYPE_ARM_V7K:
1744 outs() << " cputype CPU_TYPE_ARM\n";
1745 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7K\n";
1746 break;
1747 case MachO::CPU_SUBTYPE_ARM_V7M:
1748 outs() << " cputype CPU_TYPE_ARM\n";
1749 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7M\n";
1750 break;
1751 case MachO::CPU_SUBTYPE_ARM_V7S:
1752 outs() << " cputype CPU_TYPE_ARM\n";
1753 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7S\n";
1754 break;
1755 default:
1756 printUnknownCPUType(cputype, cpusubtype);
1757 break;
1759 break;
1760 case MachO::CPU_TYPE_ARM64:
1761 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
1762 case MachO::CPU_SUBTYPE_ARM64_ALL:
1763 outs() << " cputype CPU_TYPE_ARM64\n";
1764 outs() << " cpusubtype CPU_SUBTYPE_ARM64_ALL\n";
1765 break;
1766 default:
1767 printUnknownCPUType(cputype, cpusubtype);
1768 break;
1770 break;
1771 default:
1772 printUnknownCPUType(cputype, cpusubtype);
1773 break;
1777 static void printMachOUniversalHeaders(const object::MachOUniversalBinary *UB,
1778 bool verbose) {
1779 outs() << "Fat headers\n";
1780 if (verbose) {
1781 if (UB->getMagic() == MachO::FAT_MAGIC)
1782 outs() << "fat_magic FAT_MAGIC\n";
1783 else // UB->getMagic() == MachO::FAT_MAGIC_64
1784 outs() << "fat_magic FAT_MAGIC_64\n";
1785 } else
1786 outs() << "fat_magic " << format("0x%" PRIx32, MachO::FAT_MAGIC) << "\n";
1788 uint32_t nfat_arch = UB->getNumberOfObjects();
1789 StringRef Buf = UB->getData();
1790 uint64_t size = Buf.size();
1791 uint64_t big_size = sizeof(struct MachO::fat_header) +
1792 nfat_arch * sizeof(struct MachO::fat_arch);
1793 outs() << "nfat_arch " << UB->getNumberOfObjects();
1794 if (nfat_arch == 0)
1795 outs() << " (malformed, contains zero architecture types)\n";
1796 else if (big_size > size)
1797 outs() << " (malformed, architectures past end of file)\n";
1798 else
1799 outs() << "\n";
1801 for (uint32_t i = 0; i < nfat_arch; ++i) {
1802 MachOUniversalBinary::ObjectForArch OFA(UB, i);
1803 uint32_t cputype = OFA.getCPUType();
1804 uint32_t cpusubtype = OFA.getCPUSubType();
1805 outs() << "architecture ";
1806 for (uint32_t j = 0; i != 0 && j <= i - 1; j++) {
1807 MachOUniversalBinary::ObjectForArch other_OFA(UB, j);
1808 uint32_t other_cputype = other_OFA.getCPUType();
1809 uint32_t other_cpusubtype = other_OFA.getCPUSubType();
1810 if (cputype != 0 && cpusubtype != 0 && cputype == other_cputype &&
1811 (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) ==
1812 (other_cpusubtype & ~MachO::CPU_SUBTYPE_MASK)) {
1813 outs() << "(illegal duplicate architecture) ";
1814 break;
1817 if (verbose) {
1818 outs() << OFA.getArchFlagName() << "\n";
1819 printCPUType(cputype, cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
1820 } else {
1821 outs() << i << "\n";
1822 outs() << " cputype " << cputype << "\n";
1823 outs() << " cpusubtype " << (cpusubtype & ~MachO::CPU_SUBTYPE_MASK)
1824 << "\n";
1826 if (verbose &&
1827 (cpusubtype & MachO::CPU_SUBTYPE_MASK) == MachO::CPU_SUBTYPE_LIB64)
1828 outs() << " capabilities CPU_SUBTYPE_LIB64\n";
1829 else
1830 outs() << " capabilities "
1831 << format("0x%" PRIx32,
1832 (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24) << "\n";
1833 outs() << " offset " << OFA.getOffset();
1834 if (OFA.getOffset() > size)
1835 outs() << " (past end of file)";
1836 if (OFA.getOffset() % (1 << OFA.getAlign()) != 0)
1837 outs() << " (not aligned on it's alignment (2^" << OFA.getAlign() << ")";
1838 outs() << "\n";
1839 outs() << " size " << OFA.getSize();
1840 big_size = OFA.getOffset() + OFA.getSize();
1841 if (big_size > size)
1842 outs() << " (past end of file)";
1843 outs() << "\n";
1844 outs() << " align 2^" << OFA.getAlign() << " (" << (1 << OFA.getAlign())
1845 << ")\n";
1849 static void printArchiveChild(StringRef Filename, const Archive::Child &C,
1850 bool verbose, bool print_offset,
1851 StringRef ArchitectureName = StringRef()) {
1852 if (print_offset)
1853 outs() << C.getChildOffset() << "\t";
1854 Expected<sys::fs::perms> ModeOrErr = C.getAccessMode();
1855 if (!ModeOrErr)
1856 report_error(Filename, C, ModeOrErr.takeError(), ArchitectureName);
1857 sys::fs::perms Mode = ModeOrErr.get();
1858 if (verbose) {
1859 // FIXME: this first dash, "-", is for (Mode & S_IFMT) == S_IFREG.
1860 // But there is nothing in sys::fs::perms for S_IFMT or S_IFREG.
1861 outs() << "-";
1862 outs() << ((Mode & sys::fs::owner_read) ? "r" : "-");
1863 outs() << ((Mode & sys::fs::owner_write) ? "w" : "-");
1864 outs() << ((Mode & sys::fs::owner_exe) ? "x" : "-");
1865 outs() << ((Mode & sys::fs::group_read) ? "r" : "-");
1866 outs() << ((Mode & sys::fs::group_write) ? "w" : "-");
1867 outs() << ((Mode & sys::fs::group_exe) ? "x" : "-");
1868 outs() << ((Mode & sys::fs::others_read) ? "r" : "-");
1869 outs() << ((Mode & sys::fs::others_write) ? "w" : "-");
1870 outs() << ((Mode & sys::fs::others_exe) ? "x" : "-");
1871 } else {
1872 outs() << format("0%o ", Mode);
1875 Expected<unsigned> UIDOrErr = C.getUID();
1876 if (!UIDOrErr)
1877 report_error(Filename, C, UIDOrErr.takeError(), ArchitectureName);
1878 unsigned UID = UIDOrErr.get();
1879 outs() << format("%3d/", UID);
1880 Expected<unsigned> GIDOrErr = C.getGID();
1881 if (!GIDOrErr)
1882 report_error(Filename, C, GIDOrErr.takeError(), ArchitectureName);
1883 unsigned GID = GIDOrErr.get();
1884 outs() << format("%-3d ", GID);
1885 Expected<uint64_t> Size = C.getRawSize();
1886 if (!Size)
1887 report_error(Filename, C, Size.takeError(), ArchitectureName);
1888 outs() << format("%5" PRId64, Size.get()) << " ";
1890 StringRef RawLastModified = C.getRawLastModified();
1891 if (verbose) {
1892 unsigned Seconds;
1893 if (RawLastModified.getAsInteger(10, Seconds))
1894 outs() << "(date: \"" << RawLastModified
1895 << "\" contains non-decimal chars) ";
1896 else {
1897 // Since cime(3) returns a 26 character string of the form:
1898 // "Sun Sep 16 01:03:52 1973\n\0"
1899 // just print 24 characters.
1900 time_t t = Seconds;
1901 outs() << format("%.24s ", ctime(&t));
1903 } else {
1904 outs() << RawLastModified << " ";
1907 if (verbose) {
1908 Expected<StringRef> NameOrErr = C.getName();
1909 if (!NameOrErr) {
1910 consumeError(NameOrErr.takeError());
1911 Expected<StringRef> NameOrErr = C.getRawName();
1912 if (!NameOrErr)
1913 report_error(Filename, C, NameOrErr.takeError(), ArchitectureName);
1914 StringRef RawName = NameOrErr.get();
1915 outs() << RawName << "\n";
1916 } else {
1917 StringRef Name = NameOrErr.get();
1918 outs() << Name << "\n";
1920 } else {
1921 Expected<StringRef> NameOrErr = C.getRawName();
1922 if (!NameOrErr)
1923 report_error(Filename, C, NameOrErr.takeError(), ArchitectureName);
1924 StringRef RawName = NameOrErr.get();
1925 outs() << RawName << "\n";
1929 static void printArchiveHeaders(StringRef Filename, Archive *A, bool verbose,
1930 bool print_offset,
1931 StringRef ArchitectureName = StringRef()) {
1932 Error Err = Error::success();
1934 for (const auto &C : A->children(Err, false))
1935 printArchiveChild(Filename, C, verbose, print_offset, ArchitectureName);
1937 if (Err)
1938 report_error(StringRef(), Filename, std::move(Err), ArchitectureName);
1941 static bool ValidateArchFlags() {
1942 // Check for -arch all and verifiy the -arch flags are valid.
1943 for (unsigned i = 0; i < ArchFlags.size(); ++i) {
1944 if (ArchFlags[i] == "all") {
1945 ArchAll = true;
1946 } else {
1947 if (!MachOObjectFile::isValidArch(ArchFlags[i])) {
1948 WithColor::error(errs(), "llvm-objdump")
1949 << "unknown architecture named '" + ArchFlags[i] +
1950 "'for the -arch option\n";
1951 return false;
1955 return true;
1958 // ParseInputMachO() parses the named Mach-O file in Filename and handles the
1959 // -arch flags selecting just those slices as specified by them and also parses
1960 // archive files. Then for each individual Mach-O file ProcessMachO() is
1961 // called to process the file based on the command line options.
1962 void llvm::ParseInputMachO(StringRef Filename) {
1963 if (!ValidateArchFlags())
1964 return;
1966 // Attempt to open the binary.
1967 Expected<OwningBinary<Binary>> BinaryOrErr = createBinary(Filename);
1968 if (!BinaryOrErr) {
1969 if (auto E = isNotObjectErrorInvalidFileType(BinaryOrErr.takeError()))
1970 report_error(Filename, std::move(E));
1971 else
1972 outs() << Filename << ": is not an object file\n";
1973 return;
1975 Binary &Bin = *BinaryOrErr.get().getBinary();
1977 if (Archive *A = dyn_cast<Archive>(&Bin)) {
1978 outs() << "Archive : " << Filename << "\n";
1979 if (ArchiveHeaders)
1980 printArchiveHeaders(Filename, A, !NonVerbose, ArchiveMemberOffsets);
1982 Error Err = Error::success();
1983 for (auto &C : A->children(Err)) {
1984 Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
1985 if (!ChildOrErr) {
1986 if (auto E = isNotObjectErrorInvalidFileType(ChildOrErr.takeError()))
1987 report_error(Filename, C, std::move(E));
1988 continue;
1990 if (MachOObjectFile *O = dyn_cast<MachOObjectFile>(&*ChildOrErr.get())) {
1991 if (!checkMachOAndArchFlags(O, Filename))
1992 return;
1993 ProcessMachO(Filename, O, O->getFileName());
1996 if (Err)
1997 report_error(Filename, std::move(Err));
1998 return;
2000 if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(&Bin)) {
2001 ParseInputMachO(UB);
2002 return;
2004 if (ObjectFile *O = dyn_cast<ObjectFile>(&Bin)) {
2005 if (!checkMachOAndArchFlags(O, Filename))
2006 return;
2007 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&*O))
2008 ProcessMachO(Filename, MachOOF);
2009 else
2010 WithColor::error(errs(), "llvm-objdump")
2011 << Filename << "': "
2012 << "object is not a Mach-O file type.\n";
2013 return;
2015 llvm_unreachable("Input object can't be invalid at this point");
2018 void llvm::ParseInputMachO(MachOUniversalBinary *UB) {
2019 if (!ValidateArchFlags())
2020 return;
2022 auto Filename = UB->getFileName();
2024 if (UniversalHeaders)
2025 printMachOUniversalHeaders(UB, !NonVerbose);
2027 // If we have a list of architecture flags specified dump only those.
2028 if (!ArchAll && !ArchFlags.empty()) {
2029 // Look for a slice in the universal binary that matches each ArchFlag.
2030 bool ArchFound;
2031 for (unsigned i = 0; i < ArchFlags.size(); ++i) {
2032 ArchFound = false;
2033 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
2034 E = UB->end_objects();
2035 I != E; ++I) {
2036 if (ArchFlags[i] == I->getArchFlagName()) {
2037 ArchFound = true;
2038 Expected<std::unique_ptr<ObjectFile>> ObjOrErr =
2039 I->getAsObjectFile();
2040 std::string ArchitectureName = "";
2041 if (ArchFlags.size() > 1)
2042 ArchitectureName = I->getArchFlagName();
2043 if (ObjOrErr) {
2044 ObjectFile &O = *ObjOrErr.get();
2045 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&O))
2046 ProcessMachO(Filename, MachOOF, "", ArchitectureName);
2047 } else if (auto E = isNotObjectErrorInvalidFileType(
2048 ObjOrErr.takeError())) {
2049 report_error(Filename, StringRef(), std::move(E),
2050 ArchitectureName);
2051 continue;
2052 } else if (Expected<std::unique_ptr<Archive>> AOrErr =
2053 I->getAsArchive()) {
2054 std::unique_ptr<Archive> &A = *AOrErr;
2055 outs() << "Archive : " << Filename;
2056 if (!ArchitectureName.empty())
2057 outs() << " (architecture " << ArchitectureName << ")";
2058 outs() << "\n";
2059 if (ArchiveHeaders)
2060 printArchiveHeaders(Filename, A.get(), !NonVerbose,
2061 ArchiveMemberOffsets, ArchitectureName);
2062 Error Err = Error::success();
2063 for (auto &C : A->children(Err)) {
2064 Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
2065 if (!ChildOrErr) {
2066 if (auto E = isNotObjectErrorInvalidFileType(ChildOrErr.takeError()))
2067 report_error(Filename, C, std::move(E), ArchitectureName);
2068 continue;
2070 if (MachOObjectFile *O =
2071 dyn_cast<MachOObjectFile>(&*ChildOrErr.get()))
2072 ProcessMachO(Filename, O, O->getFileName(), ArchitectureName);
2074 if (Err)
2075 report_error(Filename, std::move(Err));
2076 } else {
2077 consumeError(AOrErr.takeError());
2078 error("Mach-O universal file: " + Filename + " for " +
2079 "architecture " + StringRef(I->getArchFlagName()) +
2080 " is not a Mach-O file or an archive file");
2084 if (!ArchFound) {
2085 WithColor::error(errs(), "llvm-objdump")
2086 << "file: " + Filename + " does not contain "
2087 << "architecture: " + ArchFlags[i] + "\n";
2088 return;
2091 return;
2093 // No architecture flags were specified so if this contains a slice that
2094 // matches the host architecture dump only that.
2095 if (!ArchAll) {
2096 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
2097 E = UB->end_objects();
2098 I != E; ++I) {
2099 if (MachOObjectFile::getHostArch().getArchName() ==
2100 I->getArchFlagName()) {
2101 Expected<std::unique_ptr<ObjectFile>> ObjOrErr = I->getAsObjectFile();
2102 std::string ArchiveName;
2103 ArchiveName.clear();
2104 if (ObjOrErr) {
2105 ObjectFile &O = *ObjOrErr.get();
2106 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&O))
2107 ProcessMachO(Filename, MachOOF);
2108 } else if (auto E = isNotObjectErrorInvalidFileType(
2109 ObjOrErr.takeError())) {
2110 report_error(Filename, std::move(E));
2111 } else if (Expected<std::unique_ptr<Archive>> AOrErr =
2112 I->getAsArchive()) {
2113 std::unique_ptr<Archive> &A = *AOrErr;
2114 outs() << "Archive : " << Filename << "\n";
2115 if (ArchiveHeaders)
2116 printArchiveHeaders(Filename, A.get(), !NonVerbose,
2117 ArchiveMemberOffsets);
2118 Error Err = Error::success();
2119 for (auto &C : A->children(Err)) {
2120 Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
2121 if (!ChildOrErr) {
2122 if (auto E = isNotObjectErrorInvalidFileType(ChildOrErr.takeError()))
2123 report_error(Filename, C, std::move(E));
2124 continue;
2126 if (MachOObjectFile *O =
2127 dyn_cast<MachOObjectFile>(&*ChildOrErr.get()))
2128 ProcessMachO(Filename, O, O->getFileName());
2130 if (Err)
2131 report_error(Filename, std::move(Err));
2132 } else {
2133 consumeError(AOrErr.takeError());
2134 error("Mach-O universal file: " + Filename + " for architecture " +
2135 StringRef(I->getArchFlagName()) +
2136 " is not a Mach-O file or an archive file");
2138 return;
2142 // Either all architectures have been specified or none have been specified
2143 // and this does not contain the host architecture so dump all the slices.
2144 bool moreThanOneArch = UB->getNumberOfObjects() > 1;
2145 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
2146 E = UB->end_objects();
2147 I != E; ++I) {
2148 Expected<std::unique_ptr<ObjectFile>> ObjOrErr = I->getAsObjectFile();
2149 std::string ArchitectureName = "";
2150 if (moreThanOneArch)
2151 ArchitectureName = I->getArchFlagName();
2152 if (ObjOrErr) {
2153 ObjectFile &Obj = *ObjOrErr.get();
2154 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&Obj))
2155 ProcessMachO(Filename, MachOOF, "", ArchitectureName);
2156 } else if (auto E = isNotObjectErrorInvalidFileType(
2157 ObjOrErr.takeError())) {
2158 report_error(StringRef(), Filename, std::move(E), ArchitectureName);
2159 } else if (Expected<std::unique_ptr<Archive>> AOrErr =
2160 I->getAsArchive()) {
2161 std::unique_ptr<Archive> &A = *AOrErr;
2162 outs() << "Archive : " << Filename;
2163 if (!ArchitectureName.empty())
2164 outs() << " (architecture " << ArchitectureName << ")";
2165 outs() << "\n";
2166 if (ArchiveHeaders)
2167 printArchiveHeaders(Filename, A.get(), !NonVerbose,
2168 ArchiveMemberOffsets, ArchitectureName);
2169 Error Err = Error::success();
2170 for (auto &C : A->children(Err)) {
2171 Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
2172 if (!ChildOrErr) {
2173 if (auto E = isNotObjectErrorInvalidFileType(ChildOrErr.takeError()))
2174 report_error(Filename, C, std::move(E), ArchitectureName);
2175 continue;
2177 if (MachOObjectFile *O =
2178 dyn_cast<MachOObjectFile>(&*ChildOrErr.get())) {
2179 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(O))
2180 ProcessMachO(Filename, MachOOF, MachOOF->getFileName(),
2181 ArchitectureName);
2184 if (Err)
2185 report_error(Filename, std::move(Err));
2186 } else {
2187 consumeError(AOrErr.takeError());
2188 error("Mach-O universal file: " + Filename + " for architecture " +
2189 StringRef(I->getArchFlagName()) +
2190 " is not a Mach-O file or an archive file");
2195 // The block of info used by the Symbolizer call backs.
2196 struct DisassembleInfo {
2197 DisassembleInfo(MachOObjectFile *O, SymbolAddressMap *AddrMap,
2198 std::vector<SectionRef> *Sections, bool verbose)
2199 : verbose(verbose), O(O), AddrMap(AddrMap), Sections(Sections) {}
2200 bool verbose;
2201 MachOObjectFile *O;
2202 SectionRef S;
2203 SymbolAddressMap *AddrMap;
2204 std::vector<SectionRef> *Sections;
2205 const char *class_name = nullptr;
2206 const char *selector_name = nullptr;
2207 std::unique_ptr<char[]> method = nullptr;
2208 char *demangled_name = nullptr;
2209 uint64_t adrp_addr = 0;
2210 uint32_t adrp_inst = 0;
2211 std::unique_ptr<SymbolAddressMap> bindtable;
2212 uint32_t depth = 0;
2215 // SymbolizerGetOpInfo() is the operand information call back function.
2216 // This is called to get the symbolic information for operand(s) of an
2217 // instruction when it is being done. This routine does this from
2218 // the relocation information, symbol table, etc. That block of information
2219 // is a pointer to the struct DisassembleInfo that was passed when the
2220 // disassembler context was created and passed to back to here when
2221 // called back by the disassembler for instruction operands that could have
2222 // relocation information. The address of the instruction containing operand is
2223 // at the Pc parameter. The immediate value the operand has is passed in
2224 // op_info->Value and is at Offset past the start of the instruction and has a
2225 // byte Size of 1, 2 or 4. The symbolc information is returned in TagBuf is the
2226 // LLVMOpInfo1 struct defined in the header "llvm-c/Disassembler.h" as symbol
2227 // names and addends of the symbolic expression to add for the operand. The
2228 // value of TagType is currently 1 (for the LLVMOpInfo1 struct). If symbolic
2229 // information is returned then this function returns 1 else it returns 0.
2230 static int SymbolizerGetOpInfo(void *DisInfo, uint64_t Pc, uint64_t Offset,
2231 uint64_t Size, int TagType, void *TagBuf) {
2232 struct DisassembleInfo *info = (struct DisassembleInfo *)DisInfo;
2233 struct LLVMOpInfo1 *op_info = (struct LLVMOpInfo1 *)TagBuf;
2234 uint64_t value = op_info->Value;
2236 // Make sure all fields returned are zero if we don't set them.
2237 memset((void *)op_info, '\0', sizeof(struct LLVMOpInfo1));
2238 op_info->Value = value;
2240 // If the TagType is not the value 1 which it code knows about or if no
2241 // verbose symbolic information is wanted then just return 0, indicating no
2242 // information is being returned.
2243 if (TagType != 1 || !info->verbose)
2244 return 0;
2246 unsigned int Arch = info->O->getArch();
2247 if (Arch == Triple::x86) {
2248 if (Size != 1 && Size != 2 && Size != 4 && Size != 0)
2249 return 0;
2250 if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
2251 // TODO:
2252 // Search the external relocation entries of a fully linked image
2253 // (if any) for an entry that matches this segment offset.
2254 // uint32_t seg_offset = (Pc + Offset);
2255 return 0;
2257 // In MH_OBJECT filetypes search the section's relocation entries (if any)
2258 // for an entry for this section offset.
2259 uint32_t sect_addr = info->S.getAddress();
2260 uint32_t sect_offset = (Pc + Offset) - sect_addr;
2261 bool reloc_found = false;
2262 DataRefImpl Rel;
2263 MachO::any_relocation_info RE;
2264 bool isExtern = false;
2265 SymbolRef Symbol;
2266 bool r_scattered = false;
2267 uint32_t r_value, pair_r_value, r_type;
2268 for (const RelocationRef &Reloc : info->S.relocations()) {
2269 uint64_t RelocOffset = Reloc.getOffset();
2270 if (RelocOffset == sect_offset) {
2271 Rel = Reloc.getRawDataRefImpl();
2272 RE = info->O->getRelocation(Rel);
2273 r_type = info->O->getAnyRelocationType(RE);
2274 r_scattered = info->O->isRelocationScattered(RE);
2275 if (r_scattered) {
2276 r_value = info->O->getScatteredRelocationValue(RE);
2277 if (r_type == MachO::GENERIC_RELOC_SECTDIFF ||
2278 r_type == MachO::GENERIC_RELOC_LOCAL_SECTDIFF) {
2279 DataRefImpl RelNext = Rel;
2280 info->O->moveRelocationNext(RelNext);
2281 MachO::any_relocation_info RENext;
2282 RENext = info->O->getRelocation(RelNext);
2283 if (info->O->isRelocationScattered(RENext))
2284 pair_r_value = info->O->getScatteredRelocationValue(RENext);
2285 else
2286 return 0;
2288 } else {
2289 isExtern = info->O->getPlainRelocationExternal(RE);
2290 if (isExtern) {
2291 symbol_iterator RelocSym = Reloc.getSymbol();
2292 Symbol = *RelocSym;
2295 reloc_found = true;
2296 break;
2299 if (reloc_found && isExtern) {
2300 Expected<StringRef> SymName = Symbol.getName();
2301 if (!SymName)
2302 report_error(info->O->getFileName(), SymName.takeError());
2303 const char *name = SymName->data();
2304 op_info->AddSymbol.Present = 1;
2305 op_info->AddSymbol.Name = name;
2306 // For i386 extern relocation entries the value in the instruction is
2307 // the offset from the symbol, and value is already set in op_info->Value.
2308 return 1;
2310 if (reloc_found && (r_type == MachO::GENERIC_RELOC_SECTDIFF ||
2311 r_type == MachO::GENERIC_RELOC_LOCAL_SECTDIFF)) {
2312 const char *add = GuessSymbolName(r_value, info->AddrMap);
2313 const char *sub = GuessSymbolName(pair_r_value, info->AddrMap);
2314 uint32_t offset = value - (r_value - pair_r_value);
2315 op_info->AddSymbol.Present = 1;
2316 if (add != nullptr)
2317 op_info->AddSymbol.Name = add;
2318 else
2319 op_info->AddSymbol.Value = r_value;
2320 op_info->SubtractSymbol.Present = 1;
2321 if (sub != nullptr)
2322 op_info->SubtractSymbol.Name = sub;
2323 else
2324 op_info->SubtractSymbol.Value = pair_r_value;
2325 op_info->Value = offset;
2326 return 1;
2328 return 0;
2330 if (Arch == Triple::x86_64) {
2331 if (Size != 1 && Size != 2 && Size != 4 && Size != 0)
2332 return 0;
2333 // For non MH_OBJECT types, like MH_KEXT_BUNDLE, Search the external
2334 // relocation entries of a linked image (if any) for an entry that matches
2335 // this segment offset.
2336 if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
2337 uint64_t seg_offset = Pc + Offset;
2338 bool reloc_found = false;
2339 DataRefImpl Rel;
2340 MachO::any_relocation_info RE;
2341 bool isExtern = false;
2342 SymbolRef Symbol;
2343 for (const RelocationRef &Reloc : info->O->external_relocations()) {
2344 uint64_t RelocOffset = Reloc.getOffset();
2345 if (RelocOffset == seg_offset) {
2346 Rel = Reloc.getRawDataRefImpl();
2347 RE = info->O->getRelocation(Rel);
2348 // external relocation entries should always be external.
2349 isExtern = info->O->getPlainRelocationExternal(RE);
2350 if (isExtern) {
2351 symbol_iterator RelocSym = Reloc.getSymbol();
2352 Symbol = *RelocSym;
2354 reloc_found = true;
2355 break;
2358 if (reloc_found && isExtern) {
2359 // The Value passed in will be adjusted by the Pc if the instruction
2360 // adds the Pc. But for x86_64 external relocation entries the Value
2361 // is the offset from the external symbol.
2362 if (info->O->getAnyRelocationPCRel(RE))
2363 op_info->Value -= Pc + Offset + Size;
2364 Expected<StringRef> SymName = Symbol.getName();
2365 if (!SymName)
2366 report_error(info->O->getFileName(), SymName.takeError());
2367 const char *name = SymName->data();
2368 op_info->AddSymbol.Present = 1;
2369 op_info->AddSymbol.Name = name;
2370 return 1;
2372 return 0;
2374 // In MH_OBJECT filetypes search the section's relocation entries (if any)
2375 // for an entry for this section offset.
2376 uint64_t sect_addr = info->S.getAddress();
2377 uint64_t sect_offset = (Pc + Offset) - sect_addr;
2378 bool reloc_found = false;
2379 DataRefImpl Rel;
2380 MachO::any_relocation_info RE;
2381 bool isExtern = false;
2382 SymbolRef Symbol;
2383 for (const RelocationRef &Reloc : info->S.relocations()) {
2384 uint64_t RelocOffset = Reloc.getOffset();
2385 if (RelocOffset == sect_offset) {
2386 Rel = Reloc.getRawDataRefImpl();
2387 RE = info->O->getRelocation(Rel);
2388 // NOTE: Scattered relocations don't exist on x86_64.
2389 isExtern = info->O->getPlainRelocationExternal(RE);
2390 if (isExtern) {
2391 symbol_iterator RelocSym = Reloc.getSymbol();
2392 Symbol = *RelocSym;
2394 reloc_found = true;
2395 break;
2398 if (reloc_found && isExtern) {
2399 // The Value passed in will be adjusted by the Pc if the instruction
2400 // adds the Pc. But for x86_64 external relocation entries the Value
2401 // is the offset from the external symbol.
2402 if (info->O->getAnyRelocationPCRel(RE))
2403 op_info->Value -= Pc + Offset + Size;
2404 Expected<StringRef> SymName = Symbol.getName();
2405 if (!SymName)
2406 report_error(info->O->getFileName(), SymName.takeError());
2407 const char *name = SymName->data();
2408 unsigned Type = info->O->getAnyRelocationType(RE);
2409 if (Type == MachO::X86_64_RELOC_SUBTRACTOR) {
2410 DataRefImpl RelNext = Rel;
2411 info->O->moveRelocationNext(RelNext);
2412 MachO::any_relocation_info RENext = info->O->getRelocation(RelNext);
2413 unsigned TypeNext = info->O->getAnyRelocationType(RENext);
2414 bool isExternNext = info->O->getPlainRelocationExternal(RENext);
2415 unsigned SymbolNum = info->O->getPlainRelocationSymbolNum(RENext);
2416 if (TypeNext == MachO::X86_64_RELOC_UNSIGNED && isExternNext) {
2417 op_info->SubtractSymbol.Present = 1;
2418 op_info->SubtractSymbol.Name = name;
2419 symbol_iterator RelocSymNext = info->O->getSymbolByIndex(SymbolNum);
2420 Symbol = *RelocSymNext;
2421 Expected<StringRef> SymNameNext = Symbol.getName();
2422 if (!SymNameNext)
2423 report_error(info->O->getFileName(), SymNameNext.takeError());
2424 name = SymNameNext->data();
2427 // TODO: add the VariantKinds to op_info->VariantKind for relocation types
2428 // like: X86_64_RELOC_TLV, X86_64_RELOC_GOT_LOAD and X86_64_RELOC_GOT.
2429 op_info->AddSymbol.Present = 1;
2430 op_info->AddSymbol.Name = name;
2431 return 1;
2433 return 0;
2435 if (Arch == Triple::arm) {
2436 if (Offset != 0 || (Size != 4 && Size != 2))
2437 return 0;
2438 if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
2439 // TODO:
2440 // Search the external relocation entries of a fully linked image
2441 // (if any) for an entry that matches this segment offset.
2442 // uint32_t seg_offset = (Pc + Offset);
2443 return 0;
2445 // In MH_OBJECT filetypes search the section's relocation entries (if any)
2446 // for an entry for this section offset.
2447 uint32_t sect_addr = info->S.getAddress();
2448 uint32_t sect_offset = (Pc + Offset) - sect_addr;
2449 DataRefImpl Rel;
2450 MachO::any_relocation_info RE;
2451 bool isExtern = false;
2452 SymbolRef Symbol;
2453 bool r_scattered = false;
2454 uint32_t r_value, pair_r_value, r_type, r_length, other_half;
2455 auto Reloc =
2456 find_if(info->S.relocations(), [&](const RelocationRef &Reloc) {
2457 uint64_t RelocOffset = Reloc.getOffset();
2458 return RelocOffset == sect_offset;
2461 if (Reloc == info->S.relocations().end())
2462 return 0;
2464 Rel = Reloc->getRawDataRefImpl();
2465 RE = info->O->getRelocation(Rel);
2466 r_length = info->O->getAnyRelocationLength(RE);
2467 r_scattered = info->O->isRelocationScattered(RE);
2468 if (r_scattered) {
2469 r_value = info->O->getScatteredRelocationValue(RE);
2470 r_type = info->O->getScatteredRelocationType(RE);
2471 } else {
2472 r_type = info->O->getAnyRelocationType(RE);
2473 isExtern = info->O->getPlainRelocationExternal(RE);
2474 if (isExtern) {
2475 symbol_iterator RelocSym = Reloc->getSymbol();
2476 Symbol = *RelocSym;
2479 if (r_type == MachO::ARM_RELOC_HALF ||
2480 r_type == MachO::ARM_RELOC_SECTDIFF ||
2481 r_type == MachO::ARM_RELOC_LOCAL_SECTDIFF ||
2482 r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
2483 DataRefImpl RelNext = Rel;
2484 info->O->moveRelocationNext(RelNext);
2485 MachO::any_relocation_info RENext;
2486 RENext = info->O->getRelocation(RelNext);
2487 other_half = info->O->getAnyRelocationAddress(RENext) & 0xffff;
2488 if (info->O->isRelocationScattered(RENext))
2489 pair_r_value = info->O->getScatteredRelocationValue(RENext);
2492 if (isExtern) {
2493 Expected<StringRef> SymName = Symbol.getName();
2494 if (!SymName)
2495 report_error(info->O->getFileName(), SymName.takeError());
2496 const char *name = SymName->data();
2497 op_info->AddSymbol.Present = 1;
2498 op_info->AddSymbol.Name = name;
2499 switch (r_type) {
2500 case MachO::ARM_RELOC_HALF:
2501 if ((r_length & 0x1) == 1) {
2502 op_info->Value = value << 16 | other_half;
2503 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
2504 } else {
2505 op_info->Value = other_half << 16 | value;
2506 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
2508 break;
2509 default:
2510 break;
2512 return 1;
2514 // If we have a branch that is not an external relocation entry then
2515 // return 0 so the code in tryAddingSymbolicOperand() can use the
2516 // SymbolLookUp call back with the branch target address to look up the
2517 // symbol and possibility add an annotation for a symbol stub.
2518 if (isExtern == 0 && (r_type == MachO::ARM_RELOC_BR24 ||
2519 r_type == MachO::ARM_THUMB_RELOC_BR22))
2520 return 0;
2522 uint32_t offset = 0;
2523 if (r_type == MachO::ARM_RELOC_HALF ||
2524 r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
2525 if ((r_length & 0x1) == 1)
2526 value = value << 16 | other_half;
2527 else
2528 value = other_half << 16 | value;
2530 if (r_scattered && (r_type != MachO::ARM_RELOC_HALF &&
2531 r_type != MachO::ARM_RELOC_HALF_SECTDIFF)) {
2532 offset = value - r_value;
2533 value = r_value;
2536 if (r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
2537 if ((r_length & 0x1) == 1)
2538 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
2539 else
2540 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
2541 const char *add = GuessSymbolName(r_value, info->AddrMap);
2542 const char *sub = GuessSymbolName(pair_r_value, info->AddrMap);
2543 int32_t offset = value - (r_value - pair_r_value);
2544 op_info->AddSymbol.Present = 1;
2545 if (add != nullptr)
2546 op_info->AddSymbol.Name = add;
2547 else
2548 op_info->AddSymbol.Value = r_value;
2549 op_info->SubtractSymbol.Present = 1;
2550 if (sub != nullptr)
2551 op_info->SubtractSymbol.Name = sub;
2552 else
2553 op_info->SubtractSymbol.Value = pair_r_value;
2554 op_info->Value = offset;
2555 return 1;
2558 op_info->AddSymbol.Present = 1;
2559 op_info->Value = offset;
2560 if (r_type == MachO::ARM_RELOC_HALF) {
2561 if ((r_length & 0x1) == 1)
2562 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
2563 else
2564 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
2566 const char *add = GuessSymbolName(value, info->AddrMap);
2567 if (add != nullptr) {
2568 op_info->AddSymbol.Name = add;
2569 return 1;
2571 op_info->AddSymbol.Value = value;
2572 return 1;
2574 if (Arch == Triple::aarch64) {
2575 if (Offset != 0 || Size != 4)
2576 return 0;
2577 if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
2578 // TODO:
2579 // Search the external relocation entries of a fully linked image
2580 // (if any) for an entry that matches this segment offset.
2581 // uint64_t seg_offset = (Pc + Offset);
2582 return 0;
2584 // In MH_OBJECT filetypes search the section's relocation entries (if any)
2585 // for an entry for this section offset.
2586 uint64_t sect_addr = info->S.getAddress();
2587 uint64_t sect_offset = (Pc + Offset) - sect_addr;
2588 auto Reloc =
2589 find_if(info->S.relocations(), [&](const RelocationRef &Reloc) {
2590 uint64_t RelocOffset = Reloc.getOffset();
2591 return RelocOffset == sect_offset;
2594 if (Reloc == info->S.relocations().end())
2595 return 0;
2597 DataRefImpl Rel = Reloc->getRawDataRefImpl();
2598 MachO::any_relocation_info RE = info->O->getRelocation(Rel);
2599 uint32_t r_type = info->O->getAnyRelocationType(RE);
2600 if (r_type == MachO::ARM64_RELOC_ADDEND) {
2601 DataRefImpl RelNext = Rel;
2602 info->O->moveRelocationNext(RelNext);
2603 MachO::any_relocation_info RENext = info->O->getRelocation(RelNext);
2604 if (value == 0) {
2605 value = info->O->getPlainRelocationSymbolNum(RENext);
2606 op_info->Value = value;
2609 // NOTE: Scattered relocations don't exist on arm64.
2610 if (!info->O->getPlainRelocationExternal(RE))
2611 return 0;
2612 Expected<StringRef> SymName = Reloc->getSymbol()->getName();
2613 if (!SymName)
2614 report_error(info->O->getFileName(), SymName.takeError());
2615 const char *name = SymName->data();
2616 op_info->AddSymbol.Present = 1;
2617 op_info->AddSymbol.Name = name;
2619 switch (r_type) {
2620 case MachO::ARM64_RELOC_PAGE21:
2621 /* @page */
2622 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_PAGE;
2623 break;
2624 case MachO::ARM64_RELOC_PAGEOFF12:
2625 /* @pageoff */
2626 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_PAGEOFF;
2627 break;
2628 case MachO::ARM64_RELOC_GOT_LOAD_PAGE21:
2629 /* @gotpage */
2630 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_GOTPAGE;
2631 break;
2632 case MachO::ARM64_RELOC_GOT_LOAD_PAGEOFF12:
2633 /* @gotpageoff */
2634 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_GOTPAGEOFF;
2635 break;
2636 case MachO::ARM64_RELOC_TLVP_LOAD_PAGE21:
2637 /* @tvlppage is not implemented in llvm-mc */
2638 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_TLVP;
2639 break;
2640 case MachO::ARM64_RELOC_TLVP_LOAD_PAGEOFF12:
2641 /* @tvlppageoff is not implemented in llvm-mc */
2642 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_TLVOFF;
2643 break;
2644 default:
2645 case MachO::ARM64_RELOC_BRANCH26:
2646 op_info->VariantKind = LLVMDisassembler_VariantKind_None;
2647 break;
2649 return 1;
2651 return 0;
2654 // GuessCstringPointer is passed the address of what might be a pointer to a
2655 // literal string in a cstring section. If that address is in a cstring section
2656 // it returns a pointer to that string. Else it returns nullptr.
2657 static const char *GuessCstringPointer(uint64_t ReferenceValue,
2658 struct DisassembleInfo *info) {
2659 for (const auto &Load : info->O->load_commands()) {
2660 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
2661 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
2662 for (unsigned J = 0; J < Seg.nsects; ++J) {
2663 MachO::section_64 Sec = info->O->getSection64(Load, J);
2664 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
2665 if (section_type == MachO::S_CSTRING_LITERALS &&
2666 ReferenceValue >= Sec.addr &&
2667 ReferenceValue < Sec.addr + Sec.size) {
2668 uint64_t sect_offset = ReferenceValue - Sec.addr;
2669 uint64_t object_offset = Sec.offset + sect_offset;
2670 StringRef MachOContents = info->O->getData();
2671 uint64_t object_size = MachOContents.size();
2672 const char *object_addr = (const char *)MachOContents.data();
2673 if (object_offset < object_size) {
2674 const char *name = object_addr + object_offset;
2675 return name;
2676 } else {
2677 return nullptr;
2681 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
2682 MachO::segment_command Seg = info->O->getSegmentLoadCommand(Load);
2683 for (unsigned J = 0; J < Seg.nsects; ++J) {
2684 MachO::section Sec = info->O->getSection(Load, J);
2685 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
2686 if (section_type == MachO::S_CSTRING_LITERALS &&
2687 ReferenceValue >= Sec.addr &&
2688 ReferenceValue < Sec.addr + Sec.size) {
2689 uint64_t sect_offset = ReferenceValue - Sec.addr;
2690 uint64_t object_offset = Sec.offset + sect_offset;
2691 StringRef MachOContents = info->O->getData();
2692 uint64_t object_size = MachOContents.size();
2693 const char *object_addr = (const char *)MachOContents.data();
2694 if (object_offset < object_size) {
2695 const char *name = object_addr + object_offset;
2696 return name;
2697 } else {
2698 return nullptr;
2704 return nullptr;
2707 // GuessIndirectSymbol returns the name of the indirect symbol for the
2708 // ReferenceValue passed in or nullptr. This is used when ReferenceValue maybe
2709 // an address of a symbol stub or a lazy or non-lazy pointer to associate the
2710 // symbol name being referenced by the stub or pointer.
2711 static const char *GuessIndirectSymbol(uint64_t ReferenceValue,
2712 struct DisassembleInfo *info) {
2713 MachO::dysymtab_command Dysymtab = info->O->getDysymtabLoadCommand();
2714 MachO::symtab_command Symtab = info->O->getSymtabLoadCommand();
2715 for (const auto &Load : info->O->load_commands()) {
2716 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
2717 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
2718 for (unsigned J = 0; J < Seg.nsects; ++J) {
2719 MachO::section_64 Sec = info->O->getSection64(Load, J);
2720 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
2721 if ((section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
2722 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
2723 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
2724 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
2725 section_type == MachO::S_SYMBOL_STUBS) &&
2726 ReferenceValue >= Sec.addr &&
2727 ReferenceValue < Sec.addr + Sec.size) {
2728 uint32_t stride;
2729 if (section_type == MachO::S_SYMBOL_STUBS)
2730 stride = Sec.reserved2;
2731 else
2732 stride = 8;
2733 if (stride == 0)
2734 return nullptr;
2735 uint32_t index = Sec.reserved1 + (ReferenceValue - Sec.addr) / stride;
2736 if (index < Dysymtab.nindirectsyms) {
2737 uint32_t indirect_symbol =
2738 info->O->getIndirectSymbolTableEntry(Dysymtab, index);
2739 if (indirect_symbol < Symtab.nsyms) {
2740 symbol_iterator Sym = info->O->getSymbolByIndex(indirect_symbol);
2741 SymbolRef Symbol = *Sym;
2742 Expected<StringRef> SymName = Symbol.getName();
2743 if (!SymName)
2744 report_error(info->O->getFileName(), SymName.takeError());
2745 const char *name = SymName->data();
2746 return name;
2751 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
2752 MachO::segment_command Seg = info->O->getSegmentLoadCommand(Load);
2753 for (unsigned J = 0; J < Seg.nsects; ++J) {
2754 MachO::section Sec = info->O->getSection(Load, J);
2755 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
2756 if ((section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
2757 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
2758 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
2759 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
2760 section_type == MachO::S_SYMBOL_STUBS) &&
2761 ReferenceValue >= Sec.addr &&
2762 ReferenceValue < Sec.addr + Sec.size) {
2763 uint32_t stride;
2764 if (section_type == MachO::S_SYMBOL_STUBS)
2765 stride = Sec.reserved2;
2766 else
2767 stride = 4;
2768 if (stride == 0)
2769 return nullptr;
2770 uint32_t index = Sec.reserved1 + (ReferenceValue - Sec.addr) / stride;
2771 if (index < Dysymtab.nindirectsyms) {
2772 uint32_t indirect_symbol =
2773 info->O->getIndirectSymbolTableEntry(Dysymtab, index);
2774 if (indirect_symbol < Symtab.nsyms) {
2775 symbol_iterator Sym = info->O->getSymbolByIndex(indirect_symbol);
2776 SymbolRef Symbol = *Sym;
2777 Expected<StringRef> SymName = Symbol.getName();
2778 if (!SymName)
2779 report_error(info->O->getFileName(), SymName.takeError());
2780 const char *name = SymName->data();
2781 return name;
2788 return nullptr;
2791 // method_reference() is called passing it the ReferenceName that might be
2792 // a reference it to an Objective-C method call. If so then it allocates and
2793 // assembles a method call string with the values last seen and saved in
2794 // the DisassembleInfo's class_name and selector_name fields. This is saved
2795 // into the method field of the info and any previous string is free'ed.
2796 // Then the class_name field in the info is set to nullptr. The method call
2797 // string is set into ReferenceName and ReferenceType is set to
2798 // LLVMDisassembler_ReferenceType_Out_Objc_Message. If this not a method call
2799 // then both ReferenceType and ReferenceName are left unchanged.
2800 static void method_reference(struct DisassembleInfo *info,
2801 uint64_t *ReferenceType,
2802 const char **ReferenceName) {
2803 unsigned int Arch = info->O->getArch();
2804 if (*ReferenceName != nullptr) {
2805 if (strcmp(*ReferenceName, "_objc_msgSend") == 0) {
2806 if (info->selector_name != nullptr) {
2807 if (info->class_name != nullptr) {
2808 info->method = llvm::make_unique<char[]>(
2809 5 + strlen(info->class_name) + strlen(info->selector_name));
2810 char *method = info->method.get();
2811 if (method != nullptr) {
2812 strcpy(method, "+[");
2813 strcat(method, info->class_name);
2814 strcat(method, " ");
2815 strcat(method, info->selector_name);
2816 strcat(method, "]");
2817 *ReferenceName = method;
2818 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
2820 } else {
2821 info->method =
2822 llvm::make_unique<char[]>(9 + strlen(info->selector_name));
2823 char *method = info->method.get();
2824 if (method != nullptr) {
2825 if (Arch == Triple::x86_64)
2826 strcpy(method, "-[%rdi ");
2827 else if (Arch == Triple::aarch64)
2828 strcpy(method, "-[x0 ");
2829 else
2830 strcpy(method, "-[r? ");
2831 strcat(method, info->selector_name);
2832 strcat(method, "]");
2833 *ReferenceName = method;
2834 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
2837 info->class_name = nullptr;
2839 } else if (strcmp(*ReferenceName, "_objc_msgSendSuper2") == 0) {
2840 if (info->selector_name != nullptr) {
2841 info->method =
2842 llvm::make_unique<char[]>(17 + strlen(info->selector_name));
2843 char *method = info->method.get();
2844 if (method != nullptr) {
2845 if (Arch == Triple::x86_64)
2846 strcpy(method, "-[[%rdi super] ");
2847 else if (Arch == Triple::aarch64)
2848 strcpy(method, "-[[x0 super] ");
2849 else
2850 strcpy(method, "-[[r? super] ");
2851 strcat(method, info->selector_name);
2852 strcat(method, "]");
2853 *ReferenceName = method;
2854 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
2856 info->class_name = nullptr;
2862 // GuessPointerPointer() is passed the address of what might be a pointer to
2863 // a reference to an Objective-C class, selector, message ref or cfstring.
2864 // If so the value of the pointer is returned and one of the booleans are set
2865 // to true. If not zero is returned and all the booleans are set to false.
2866 static uint64_t GuessPointerPointer(uint64_t ReferenceValue,
2867 struct DisassembleInfo *info,
2868 bool &classref, bool &selref, bool &msgref,
2869 bool &cfstring) {
2870 classref = false;
2871 selref = false;
2872 msgref = false;
2873 cfstring = false;
2874 for (const auto &Load : info->O->load_commands()) {
2875 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
2876 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
2877 for (unsigned J = 0; J < Seg.nsects; ++J) {
2878 MachO::section_64 Sec = info->O->getSection64(Load, J);
2879 if ((strncmp(Sec.sectname, "__objc_selrefs", 16) == 0 ||
2880 strncmp(Sec.sectname, "__objc_classrefs", 16) == 0 ||
2881 strncmp(Sec.sectname, "__objc_superrefs", 16) == 0 ||
2882 strncmp(Sec.sectname, "__objc_msgrefs", 16) == 0 ||
2883 strncmp(Sec.sectname, "__cfstring", 16) == 0) &&
2884 ReferenceValue >= Sec.addr &&
2885 ReferenceValue < Sec.addr + Sec.size) {
2886 uint64_t sect_offset = ReferenceValue - Sec.addr;
2887 uint64_t object_offset = Sec.offset + sect_offset;
2888 StringRef MachOContents = info->O->getData();
2889 uint64_t object_size = MachOContents.size();
2890 const char *object_addr = (const char *)MachOContents.data();
2891 if (object_offset < object_size) {
2892 uint64_t pointer_value;
2893 memcpy(&pointer_value, object_addr + object_offset,
2894 sizeof(uint64_t));
2895 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
2896 sys::swapByteOrder(pointer_value);
2897 if (strncmp(Sec.sectname, "__objc_selrefs", 16) == 0)
2898 selref = true;
2899 else if (strncmp(Sec.sectname, "__objc_classrefs", 16) == 0 ||
2900 strncmp(Sec.sectname, "__objc_superrefs", 16) == 0)
2901 classref = true;
2902 else if (strncmp(Sec.sectname, "__objc_msgrefs", 16) == 0 &&
2903 ReferenceValue + 8 < Sec.addr + Sec.size) {
2904 msgref = true;
2905 memcpy(&pointer_value, object_addr + object_offset + 8,
2906 sizeof(uint64_t));
2907 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
2908 sys::swapByteOrder(pointer_value);
2909 } else if (strncmp(Sec.sectname, "__cfstring", 16) == 0)
2910 cfstring = true;
2911 return pointer_value;
2912 } else {
2913 return 0;
2918 // TODO: Look for LC_SEGMENT for 32-bit Mach-O files.
2920 return 0;
2923 // get_pointer_64 returns a pointer to the bytes in the object file at the
2924 // Address from a section in the Mach-O file. And indirectly returns the
2925 // offset into the section, number of bytes left in the section past the offset
2926 // and which section is was being referenced. If the Address is not in a
2927 // section nullptr is returned.
2928 static const char *get_pointer_64(uint64_t Address, uint32_t &offset,
2929 uint32_t &left, SectionRef &S,
2930 DisassembleInfo *info,
2931 bool objc_only = false) {
2932 offset = 0;
2933 left = 0;
2934 S = SectionRef();
2935 for (unsigned SectIdx = 0; SectIdx != info->Sections->size(); SectIdx++) {
2936 uint64_t SectAddress = ((*(info->Sections))[SectIdx]).getAddress();
2937 uint64_t SectSize = ((*(info->Sections))[SectIdx]).getSize();
2938 if (SectSize == 0)
2939 continue;
2940 if (objc_only) {
2941 StringRef SectName;
2942 ((*(info->Sections))[SectIdx]).getName(SectName);
2943 DataRefImpl Ref = ((*(info->Sections))[SectIdx]).getRawDataRefImpl();
2944 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
2945 if (SegName != "__OBJC" && SectName != "__cstring")
2946 continue;
2948 if (Address >= SectAddress && Address < SectAddress + SectSize) {
2949 S = (*(info->Sections))[SectIdx];
2950 offset = Address - SectAddress;
2951 left = SectSize - offset;
2952 StringRef SectContents;
2953 ((*(info->Sections))[SectIdx]).getContents(SectContents);
2954 return SectContents.data() + offset;
2957 return nullptr;
2960 static const char *get_pointer_32(uint32_t Address, uint32_t &offset,
2961 uint32_t &left, SectionRef &S,
2962 DisassembleInfo *info,
2963 bool objc_only = false) {
2964 return get_pointer_64(Address, offset, left, S, info, objc_only);
2967 // get_symbol_64() returns the name of a symbol (or nullptr) and the address of
2968 // the symbol indirectly through n_value. Based on the relocation information
2969 // for the specified section offset in the specified section reference.
2970 // If no relocation information is found and a non-zero ReferenceValue for the
2971 // symbol is passed, look up that address in the info's AddrMap.
2972 static const char *get_symbol_64(uint32_t sect_offset, SectionRef S,
2973 DisassembleInfo *info, uint64_t &n_value,
2974 uint64_t ReferenceValue = 0) {
2975 n_value = 0;
2976 if (!info->verbose)
2977 return nullptr;
2979 // See if there is an external relocation entry at the sect_offset.
2980 bool reloc_found = false;
2981 DataRefImpl Rel;
2982 MachO::any_relocation_info RE;
2983 bool isExtern = false;
2984 SymbolRef Symbol;
2985 for (const RelocationRef &Reloc : S.relocations()) {
2986 uint64_t RelocOffset = Reloc.getOffset();
2987 if (RelocOffset == sect_offset) {
2988 Rel = Reloc.getRawDataRefImpl();
2989 RE = info->O->getRelocation(Rel);
2990 if (info->O->isRelocationScattered(RE))
2991 continue;
2992 isExtern = info->O->getPlainRelocationExternal(RE);
2993 if (isExtern) {
2994 symbol_iterator RelocSym = Reloc.getSymbol();
2995 Symbol = *RelocSym;
2997 reloc_found = true;
2998 break;
3001 // If there is an external relocation entry for a symbol in this section
3002 // at this section_offset then use that symbol's value for the n_value
3003 // and return its name.
3004 const char *SymbolName = nullptr;
3005 if (reloc_found && isExtern) {
3006 n_value = Symbol.getValue();
3007 Expected<StringRef> NameOrError = Symbol.getName();
3008 if (!NameOrError)
3009 report_error(info->O->getFileName(), NameOrError.takeError());
3010 StringRef Name = *NameOrError;
3011 if (!Name.empty()) {
3012 SymbolName = Name.data();
3013 return SymbolName;
3017 // TODO: For fully linked images, look through the external relocation
3018 // entries off the dynamic symtab command. For these the r_offset is from the
3019 // start of the first writeable segment in the Mach-O file. So the offset
3020 // to this section from that segment is passed to this routine by the caller,
3021 // as the database_offset. Which is the difference of the section's starting
3022 // address and the first writable segment.
3024 // NOTE: need add passing the database_offset to this routine.
3026 // We did not find an external relocation entry so look up the ReferenceValue
3027 // as an address of a symbol and if found return that symbol's name.
3028 SymbolName = GuessSymbolName(ReferenceValue, info->AddrMap);
3030 return SymbolName;
3033 static const char *get_symbol_32(uint32_t sect_offset, SectionRef S,
3034 DisassembleInfo *info,
3035 uint32_t ReferenceValue) {
3036 uint64_t n_value64;
3037 return get_symbol_64(sect_offset, S, info, n_value64, ReferenceValue);
3040 // These are structs in the Objective-C meta data and read to produce the
3041 // comments for disassembly. While these are part of the ABI they are no
3042 // public defintions. So the are here not in include/llvm/BinaryFormat/MachO.h
3043 // .
3045 // The cfstring object in a 64-bit Mach-O file.
3046 struct cfstring64_t {
3047 uint64_t isa; // class64_t * (64-bit pointer)
3048 uint64_t flags; // flag bits
3049 uint64_t characters; // char * (64-bit pointer)
3050 uint64_t length; // number of non-NULL characters in above
3053 // The class object in a 64-bit Mach-O file.
3054 struct class64_t {
3055 uint64_t isa; // class64_t * (64-bit pointer)
3056 uint64_t superclass; // class64_t * (64-bit pointer)
3057 uint64_t cache; // Cache (64-bit pointer)
3058 uint64_t vtable; // IMP * (64-bit pointer)
3059 uint64_t data; // class_ro64_t * (64-bit pointer)
3062 struct class32_t {
3063 uint32_t isa; /* class32_t * (32-bit pointer) */
3064 uint32_t superclass; /* class32_t * (32-bit pointer) */
3065 uint32_t cache; /* Cache (32-bit pointer) */
3066 uint32_t vtable; /* IMP * (32-bit pointer) */
3067 uint32_t data; /* class_ro32_t * (32-bit pointer) */
3070 struct class_ro64_t {
3071 uint32_t flags;
3072 uint32_t instanceStart;
3073 uint32_t instanceSize;
3074 uint32_t reserved;
3075 uint64_t ivarLayout; // const uint8_t * (64-bit pointer)
3076 uint64_t name; // const char * (64-bit pointer)
3077 uint64_t baseMethods; // const method_list_t * (64-bit pointer)
3078 uint64_t baseProtocols; // const protocol_list_t * (64-bit pointer)
3079 uint64_t ivars; // const ivar_list_t * (64-bit pointer)
3080 uint64_t weakIvarLayout; // const uint8_t * (64-bit pointer)
3081 uint64_t baseProperties; // const struct objc_property_list (64-bit pointer)
3084 struct class_ro32_t {
3085 uint32_t flags;
3086 uint32_t instanceStart;
3087 uint32_t instanceSize;
3088 uint32_t ivarLayout; /* const uint8_t * (32-bit pointer) */
3089 uint32_t name; /* const char * (32-bit pointer) */
3090 uint32_t baseMethods; /* const method_list_t * (32-bit pointer) */
3091 uint32_t baseProtocols; /* const protocol_list_t * (32-bit pointer) */
3092 uint32_t ivars; /* const ivar_list_t * (32-bit pointer) */
3093 uint32_t weakIvarLayout; /* const uint8_t * (32-bit pointer) */
3094 uint32_t baseProperties; /* const struct objc_property_list *
3095 (32-bit pointer) */
3098 /* Values for class_ro{64,32}_t->flags */
3099 #define RO_META (1 << 0)
3100 #define RO_ROOT (1 << 1)
3101 #define RO_HAS_CXX_STRUCTORS (1 << 2)
3103 struct method_list64_t {
3104 uint32_t entsize;
3105 uint32_t count;
3106 /* struct method64_t first; These structures follow inline */
3109 struct method_list32_t {
3110 uint32_t entsize;
3111 uint32_t count;
3112 /* struct method32_t first; These structures follow inline */
3115 struct method64_t {
3116 uint64_t name; /* SEL (64-bit pointer) */
3117 uint64_t types; /* const char * (64-bit pointer) */
3118 uint64_t imp; /* IMP (64-bit pointer) */
3121 struct method32_t {
3122 uint32_t name; /* SEL (32-bit pointer) */
3123 uint32_t types; /* const char * (32-bit pointer) */
3124 uint32_t imp; /* IMP (32-bit pointer) */
3127 struct protocol_list64_t {
3128 uint64_t count; /* uintptr_t (a 64-bit value) */
3129 /* struct protocol64_t * list[0]; These pointers follow inline */
3132 struct protocol_list32_t {
3133 uint32_t count; /* uintptr_t (a 32-bit value) */
3134 /* struct protocol32_t * list[0]; These pointers follow inline */
3137 struct protocol64_t {
3138 uint64_t isa; /* id * (64-bit pointer) */
3139 uint64_t name; /* const char * (64-bit pointer) */
3140 uint64_t protocols; /* struct protocol_list64_t *
3141 (64-bit pointer) */
3142 uint64_t instanceMethods; /* method_list_t * (64-bit pointer) */
3143 uint64_t classMethods; /* method_list_t * (64-bit pointer) */
3144 uint64_t optionalInstanceMethods; /* method_list_t * (64-bit pointer) */
3145 uint64_t optionalClassMethods; /* method_list_t * (64-bit pointer) */
3146 uint64_t instanceProperties; /* struct objc_property_list *
3147 (64-bit pointer) */
3150 struct protocol32_t {
3151 uint32_t isa; /* id * (32-bit pointer) */
3152 uint32_t name; /* const char * (32-bit pointer) */
3153 uint32_t protocols; /* struct protocol_list_t *
3154 (32-bit pointer) */
3155 uint32_t instanceMethods; /* method_list_t * (32-bit pointer) */
3156 uint32_t classMethods; /* method_list_t * (32-bit pointer) */
3157 uint32_t optionalInstanceMethods; /* method_list_t * (32-bit pointer) */
3158 uint32_t optionalClassMethods; /* method_list_t * (32-bit pointer) */
3159 uint32_t instanceProperties; /* struct objc_property_list *
3160 (32-bit pointer) */
3163 struct ivar_list64_t {
3164 uint32_t entsize;
3165 uint32_t count;
3166 /* struct ivar64_t first; These structures follow inline */
3169 struct ivar_list32_t {
3170 uint32_t entsize;
3171 uint32_t count;
3172 /* struct ivar32_t first; These structures follow inline */
3175 struct ivar64_t {
3176 uint64_t offset; /* uintptr_t * (64-bit pointer) */
3177 uint64_t name; /* const char * (64-bit pointer) */
3178 uint64_t type; /* const char * (64-bit pointer) */
3179 uint32_t alignment;
3180 uint32_t size;
3183 struct ivar32_t {
3184 uint32_t offset; /* uintptr_t * (32-bit pointer) */
3185 uint32_t name; /* const char * (32-bit pointer) */
3186 uint32_t type; /* const char * (32-bit pointer) */
3187 uint32_t alignment;
3188 uint32_t size;
3191 struct objc_property_list64 {
3192 uint32_t entsize;
3193 uint32_t count;
3194 /* struct objc_property64 first; These structures follow inline */
3197 struct objc_property_list32 {
3198 uint32_t entsize;
3199 uint32_t count;
3200 /* struct objc_property32 first; These structures follow inline */
3203 struct objc_property64 {
3204 uint64_t name; /* const char * (64-bit pointer) */
3205 uint64_t attributes; /* const char * (64-bit pointer) */
3208 struct objc_property32 {
3209 uint32_t name; /* const char * (32-bit pointer) */
3210 uint32_t attributes; /* const char * (32-bit pointer) */
3213 struct category64_t {
3214 uint64_t name; /* const char * (64-bit pointer) */
3215 uint64_t cls; /* struct class_t * (64-bit pointer) */
3216 uint64_t instanceMethods; /* struct method_list_t * (64-bit pointer) */
3217 uint64_t classMethods; /* struct method_list_t * (64-bit pointer) */
3218 uint64_t protocols; /* struct protocol_list_t * (64-bit pointer) */
3219 uint64_t instanceProperties; /* struct objc_property_list *
3220 (64-bit pointer) */
3223 struct category32_t {
3224 uint32_t name; /* const char * (32-bit pointer) */
3225 uint32_t cls; /* struct class_t * (32-bit pointer) */
3226 uint32_t instanceMethods; /* struct method_list_t * (32-bit pointer) */
3227 uint32_t classMethods; /* struct method_list_t * (32-bit pointer) */
3228 uint32_t protocols; /* struct protocol_list_t * (32-bit pointer) */
3229 uint32_t instanceProperties; /* struct objc_property_list *
3230 (32-bit pointer) */
3233 struct objc_image_info64 {
3234 uint32_t version;
3235 uint32_t flags;
3237 struct objc_image_info32 {
3238 uint32_t version;
3239 uint32_t flags;
3241 struct imageInfo_t {
3242 uint32_t version;
3243 uint32_t flags;
3245 /* masks for objc_image_info.flags */
3246 #define OBJC_IMAGE_IS_REPLACEMENT (1 << 0)
3247 #define OBJC_IMAGE_SUPPORTS_GC (1 << 1)
3248 #define OBJC_IMAGE_IS_SIMULATED (1 << 5)
3249 #define OBJC_IMAGE_HAS_CATEGORY_CLASS_PROPERTIES (1 << 6)
3251 struct message_ref64 {
3252 uint64_t imp; /* IMP (64-bit pointer) */
3253 uint64_t sel; /* SEL (64-bit pointer) */
3256 struct message_ref32 {
3257 uint32_t imp; /* IMP (32-bit pointer) */
3258 uint32_t sel; /* SEL (32-bit pointer) */
3261 // Objective-C 1 (32-bit only) meta data structs.
3263 struct objc_module_t {
3264 uint32_t version;
3265 uint32_t size;
3266 uint32_t name; /* char * (32-bit pointer) */
3267 uint32_t symtab; /* struct objc_symtab * (32-bit pointer) */
3270 struct objc_symtab_t {
3271 uint32_t sel_ref_cnt;
3272 uint32_t refs; /* SEL * (32-bit pointer) */
3273 uint16_t cls_def_cnt;
3274 uint16_t cat_def_cnt;
3275 // uint32_t defs[1]; /* void * (32-bit pointer) variable size */
3278 struct objc_class_t {
3279 uint32_t isa; /* struct objc_class * (32-bit pointer) */
3280 uint32_t super_class; /* struct objc_class * (32-bit pointer) */
3281 uint32_t name; /* const char * (32-bit pointer) */
3282 int32_t version;
3283 int32_t info;
3284 int32_t instance_size;
3285 uint32_t ivars; /* struct objc_ivar_list * (32-bit pointer) */
3286 uint32_t methodLists; /* struct objc_method_list ** (32-bit pointer) */
3287 uint32_t cache; /* struct objc_cache * (32-bit pointer) */
3288 uint32_t protocols; /* struct objc_protocol_list * (32-bit pointer) */
3291 #define CLS_GETINFO(cls, infomask) ((cls)->info & (infomask))
3292 // class is not a metaclass
3293 #define CLS_CLASS 0x1
3294 // class is a metaclass
3295 #define CLS_META 0x2
3297 struct objc_category_t {
3298 uint32_t category_name; /* char * (32-bit pointer) */
3299 uint32_t class_name; /* char * (32-bit pointer) */
3300 uint32_t instance_methods; /* struct objc_method_list * (32-bit pointer) */
3301 uint32_t class_methods; /* struct objc_method_list * (32-bit pointer) */
3302 uint32_t protocols; /* struct objc_protocol_list * (32-bit ptr) */
3305 struct objc_ivar_t {
3306 uint32_t ivar_name; /* char * (32-bit pointer) */
3307 uint32_t ivar_type; /* char * (32-bit pointer) */
3308 int32_t ivar_offset;
3311 struct objc_ivar_list_t {
3312 int32_t ivar_count;
3313 // struct objc_ivar_t ivar_list[1]; /* variable length structure */
3316 struct objc_method_list_t {
3317 uint32_t obsolete; /* struct objc_method_list * (32-bit pointer) */
3318 int32_t method_count;
3319 // struct objc_method_t method_list[1]; /* variable length structure */
3322 struct objc_method_t {
3323 uint32_t method_name; /* SEL, aka struct objc_selector * (32-bit pointer) */
3324 uint32_t method_types; /* char * (32-bit pointer) */
3325 uint32_t method_imp; /* IMP, aka function pointer, (*IMP)(id, SEL, ...)
3326 (32-bit pointer) */
3329 struct objc_protocol_list_t {
3330 uint32_t next; /* struct objc_protocol_list * (32-bit pointer) */
3331 int32_t count;
3332 // uint32_t list[1]; /* Protocol *, aka struct objc_protocol_t *
3333 // (32-bit pointer) */
3336 struct objc_protocol_t {
3337 uint32_t isa; /* struct objc_class * (32-bit pointer) */
3338 uint32_t protocol_name; /* char * (32-bit pointer) */
3339 uint32_t protocol_list; /* struct objc_protocol_list * (32-bit pointer) */
3340 uint32_t instance_methods; /* struct objc_method_description_list *
3341 (32-bit pointer) */
3342 uint32_t class_methods; /* struct objc_method_description_list *
3343 (32-bit pointer) */
3346 struct objc_method_description_list_t {
3347 int32_t count;
3348 // struct objc_method_description_t list[1];
3351 struct objc_method_description_t {
3352 uint32_t name; /* SEL, aka struct objc_selector * (32-bit pointer) */
3353 uint32_t types; /* char * (32-bit pointer) */
3356 inline void swapStruct(struct cfstring64_t &cfs) {
3357 sys::swapByteOrder(cfs.isa);
3358 sys::swapByteOrder(cfs.flags);
3359 sys::swapByteOrder(cfs.characters);
3360 sys::swapByteOrder(cfs.length);
3363 inline void swapStruct(struct class64_t &c) {
3364 sys::swapByteOrder(c.isa);
3365 sys::swapByteOrder(c.superclass);
3366 sys::swapByteOrder(c.cache);
3367 sys::swapByteOrder(c.vtable);
3368 sys::swapByteOrder(c.data);
3371 inline void swapStruct(struct class32_t &c) {
3372 sys::swapByteOrder(c.isa);
3373 sys::swapByteOrder(c.superclass);
3374 sys::swapByteOrder(c.cache);
3375 sys::swapByteOrder(c.vtable);
3376 sys::swapByteOrder(c.data);
3379 inline void swapStruct(struct class_ro64_t &cro) {
3380 sys::swapByteOrder(cro.flags);
3381 sys::swapByteOrder(cro.instanceStart);
3382 sys::swapByteOrder(cro.instanceSize);
3383 sys::swapByteOrder(cro.reserved);
3384 sys::swapByteOrder(cro.ivarLayout);
3385 sys::swapByteOrder(cro.name);
3386 sys::swapByteOrder(cro.baseMethods);
3387 sys::swapByteOrder(cro.baseProtocols);
3388 sys::swapByteOrder(cro.ivars);
3389 sys::swapByteOrder(cro.weakIvarLayout);
3390 sys::swapByteOrder(cro.baseProperties);
3393 inline void swapStruct(struct class_ro32_t &cro) {
3394 sys::swapByteOrder(cro.flags);
3395 sys::swapByteOrder(cro.instanceStart);
3396 sys::swapByteOrder(cro.instanceSize);
3397 sys::swapByteOrder(cro.ivarLayout);
3398 sys::swapByteOrder(cro.name);
3399 sys::swapByteOrder(cro.baseMethods);
3400 sys::swapByteOrder(cro.baseProtocols);
3401 sys::swapByteOrder(cro.ivars);
3402 sys::swapByteOrder(cro.weakIvarLayout);
3403 sys::swapByteOrder(cro.baseProperties);
3406 inline void swapStruct(struct method_list64_t &ml) {
3407 sys::swapByteOrder(ml.entsize);
3408 sys::swapByteOrder(ml.count);
3411 inline void swapStruct(struct method_list32_t &ml) {
3412 sys::swapByteOrder(ml.entsize);
3413 sys::swapByteOrder(ml.count);
3416 inline void swapStruct(struct method64_t &m) {
3417 sys::swapByteOrder(m.name);
3418 sys::swapByteOrder(m.types);
3419 sys::swapByteOrder(m.imp);
3422 inline void swapStruct(struct method32_t &m) {
3423 sys::swapByteOrder(m.name);
3424 sys::swapByteOrder(m.types);
3425 sys::swapByteOrder(m.imp);
3428 inline void swapStruct(struct protocol_list64_t &pl) {
3429 sys::swapByteOrder(pl.count);
3432 inline void swapStruct(struct protocol_list32_t &pl) {
3433 sys::swapByteOrder(pl.count);
3436 inline void swapStruct(struct protocol64_t &p) {
3437 sys::swapByteOrder(p.isa);
3438 sys::swapByteOrder(p.name);
3439 sys::swapByteOrder(p.protocols);
3440 sys::swapByteOrder(p.instanceMethods);
3441 sys::swapByteOrder(p.classMethods);
3442 sys::swapByteOrder(p.optionalInstanceMethods);
3443 sys::swapByteOrder(p.optionalClassMethods);
3444 sys::swapByteOrder(p.instanceProperties);
3447 inline void swapStruct(struct protocol32_t &p) {
3448 sys::swapByteOrder(p.isa);
3449 sys::swapByteOrder(p.name);
3450 sys::swapByteOrder(p.protocols);
3451 sys::swapByteOrder(p.instanceMethods);
3452 sys::swapByteOrder(p.classMethods);
3453 sys::swapByteOrder(p.optionalInstanceMethods);
3454 sys::swapByteOrder(p.optionalClassMethods);
3455 sys::swapByteOrder(p.instanceProperties);
3458 inline void swapStruct(struct ivar_list64_t &il) {
3459 sys::swapByteOrder(il.entsize);
3460 sys::swapByteOrder(il.count);
3463 inline void swapStruct(struct ivar_list32_t &il) {
3464 sys::swapByteOrder(il.entsize);
3465 sys::swapByteOrder(il.count);
3468 inline void swapStruct(struct ivar64_t &i) {
3469 sys::swapByteOrder(i.offset);
3470 sys::swapByteOrder(i.name);
3471 sys::swapByteOrder(i.type);
3472 sys::swapByteOrder(i.alignment);
3473 sys::swapByteOrder(i.size);
3476 inline void swapStruct(struct ivar32_t &i) {
3477 sys::swapByteOrder(i.offset);
3478 sys::swapByteOrder(i.name);
3479 sys::swapByteOrder(i.type);
3480 sys::swapByteOrder(i.alignment);
3481 sys::swapByteOrder(i.size);
3484 inline void swapStruct(struct objc_property_list64 &pl) {
3485 sys::swapByteOrder(pl.entsize);
3486 sys::swapByteOrder(pl.count);
3489 inline void swapStruct(struct objc_property_list32 &pl) {
3490 sys::swapByteOrder(pl.entsize);
3491 sys::swapByteOrder(pl.count);
3494 inline void swapStruct(struct objc_property64 &op) {
3495 sys::swapByteOrder(op.name);
3496 sys::swapByteOrder(op.attributes);
3499 inline void swapStruct(struct objc_property32 &op) {
3500 sys::swapByteOrder(op.name);
3501 sys::swapByteOrder(op.attributes);
3504 inline void swapStruct(struct category64_t &c) {
3505 sys::swapByteOrder(c.name);
3506 sys::swapByteOrder(c.cls);
3507 sys::swapByteOrder(c.instanceMethods);
3508 sys::swapByteOrder(c.classMethods);
3509 sys::swapByteOrder(c.protocols);
3510 sys::swapByteOrder(c.instanceProperties);
3513 inline void swapStruct(struct category32_t &c) {
3514 sys::swapByteOrder(c.name);
3515 sys::swapByteOrder(c.cls);
3516 sys::swapByteOrder(c.instanceMethods);
3517 sys::swapByteOrder(c.classMethods);
3518 sys::swapByteOrder(c.protocols);
3519 sys::swapByteOrder(c.instanceProperties);
3522 inline void swapStruct(struct objc_image_info64 &o) {
3523 sys::swapByteOrder(o.version);
3524 sys::swapByteOrder(o.flags);
3527 inline void swapStruct(struct objc_image_info32 &o) {
3528 sys::swapByteOrder(o.version);
3529 sys::swapByteOrder(o.flags);
3532 inline void swapStruct(struct imageInfo_t &o) {
3533 sys::swapByteOrder(o.version);
3534 sys::swapByteOrder(o.flags);
3537 inline void swapStruct(struct message_ref64 &mr) {
3538 sys::swapByteOrder(mr.imp);
3539 sys::swapByteOrder(mr.sel);
3542 inline void swapStruct(struct message_ref32 &mr) {
3543 sys::swapByteOrder(mr.imp);
3544 sys::swapByteOrder(mr.sel);
3547 inline void swapStruct(struct objc_module_t &module) {
3548 sys::swapByteOrder(module.version);
3549 sys::swapByteOrder(module.size);
3550 sys::swapByteOrder(module.name);
3551 sys::swapByteOrder(module.symtab);
3554 inline void swapStruct(struct objc_symtab_t &symtab) {
3555 sys::swapByteOrder(symtab.sel_ref_cnt);
3556 sys::swapByteOrder(symtab.refs);
3557 sys::swapByteOrder(symtab.cls_def_cnt);
3558 sys::swapByteOrder(symtab.cat_def_cnt);
3561 inline void swapStruct(struct objc_class_t &objc_class) {
3562 sys::swapByteOrder(objc_class.isa);
3563 sys::swapByteOrder(objc_class.super_class);
3564 sys::swapByteOrder(objc_class.name);
3565 sys::swapByteOrder(objc_class.version);
3566 sys::swapByteOrder(objc_class.info);
3567 sys::swapByteOrder(objc_class.instance_size);
3568 sys::swapByteOrder(objc_class.ivars);
3569 sys::swapByteOrder(objc_class.methodLists);
3570 sys::swapByteOrder(objc_class.cache);
3571 sys::swapByteOrder(objc_class.protocols);
3574 inline void swapStruct(struct objc_category_t &objc_category) {
3575 sys::swapByteOrder(objc_category.category_name);
3576 sys::swapByteOrder(objc_category.class_name);
3577 sys::swapByteOrder(objc_category.instance_methods);
3578 sys::swapByteOrder(objc_category.class_methods);
3579 sys::swapByteOrder(objc_category.protocols);
3582 inline void swapStruct(struct objc_ivar_list_t &objc_ivar_list) {
3583 sys::swapByteOrder(objc_ivar_list.ivar_count);
3586 inline void swapStruct(struct objc_ivar_t &objc_ivar) {
3587 sys::swapByteOrder(objc_ivar.ivar_name);
3588 sys::swapByteOrder(objc_ivar.ivar_type);
3589 sys::swapByteOrder(objc_ivar.ivar_offset);
3592 inline void swapStruct(struct objc_method_list_t &method_list) {
3593 sys::swapByteOrder(method_list.obsolete);
3594 sys::swapByteOrder(method_list.method_count);
3597 inline void swapStruct(struct objc_method_t &method) {
3598 sys::swapByteOrder(method.method_name);
3599 sys::swapByteOrder(method.method_types);
3600 sys::swapByteOrder(method.method_imp);
3603 inline void swapStruct(struct objc_protocol_list_t &protocol_list) {
3604 sys::swapByteOrder(protocol_list.next);
3605 sys::swapByteOrder(protocol_list.count);
3608 inline void swapStruct(struct objc_protocol_t &protocol) {
3609 sys::swapByteOrder(protocol.isa);
3610 sys::swapByteOrder(protocol.protocol_name);
3611 sys::swapByteOrder(protocol.protocol_list);
3612 sys::swapByteOrder(protocol.instance_methods);
3613 sys::swapByteOrder(protocol.class_methods);
3616 inline void swapStruct(struct objc_method_description_list_t &mdl) {
3617 sys::swapByteOrder(mdl.count);
3620 inline void swapStruct(struct objc_method_description_t &md) {
3621 sys::swapByteOrder(md.name);
3622 sys::swapByteOrder(md.types);
3625 static const char *get_dyld_bind_info_symbolname(uint64_t ReferenceValue,
3626 struct DisassembleInfo *info);
3628 // get_objc2_64bit_class_name() is used for disassembly and is passed a pointer
3629 // to an Objective-C class and returns the class name. It is also passed the
3630 // address of the pointer, so when the pointer is zero as it can be in an .o
3631 // file, that is used to look for an external relocation entry with a symbol
3632 // name.
3633 static const char *get_objc2_64bit_class_name(uint64_t pointer_value,
3634 uint64_t ReferenceValue,
3635 struct DisassembleInfo *info) {
3636 const char *r;
3637 uint32_t offset, left;
3638 SectionRef S;
3640 // The pointer_value can be 0 in an object file and have a relocation
3641 // entry for the class symbol at the ReferenceValue (the address of the
3642 // pointer).
3643 if (pointer_value == 0) {
3644 r = get_pointer_64(ReferenceValue, offset, left, S, info);
3645 if (r == nullptr || left < sizeof(uint64_t))
3646 return nullptr;
3647 uint64_t n_value;
3648 const char *symbol_name = get_symbol_64(offset, S, info, n_value);
3649 if (symbol_name == nullptr)
3650 return nullptr;
3651 const char *class_name = strrchr(symbol_name, '$');
3652 if (class_name != nullptr && class_name[1] == '_' && class_name[2] != '\0')
3653 return class_name + 2;
3654 else
3655 return nullptr;
3658 // The case were the pointer_value is non-zero and points to a class defined
3659 // in this Mach-O file.
3660 r = get_pointer_64(pointer_value, offset, left, S, info);
3661 if (r == nullptr || left < sizeof(struct class64_t))
3662 return nullptr;
3663 struct class64_t c;
3664 memcpy(&c, r, sizeof(struct class64_t));
3665 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3666 swapStruct(c);
3667 if (c.data == 0)
3668 return nullptr;
3669 r = get_pointer_64(c.data, offset, left, S, info);
3670 if (r == nullptr || left < sizeof(struct class_ro64_t))
3671 return nullptr;
3672 struct class_ro64_t cro;
3673 memcpy(&cro, r, sizeof(struct class_ro64_t));
3674 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3675 swapStruct(cro);
3676 if (cro.name == 0)
3677 return nullptr;
3678 const char *name = get_pointer_64(cro.name, offset, left, S, info);
3679 return name;
3682 // get_objc2_64bit_cfstring_name is used for disassembly and is passed a
3683 // pointer to a cfstring and returns its name or nullptr.
3684 static const char *get_objc2_64bit_cfstring_name(uint64_t ReferenceValue,
3685 struct DisassembleInfo *info) {
3686 const char *r, *name;
3687 uint32_t offset, left;
3688 SectionRef S;
3689 struct cfstring64_t cfs;
3690 uint64_t cfs_characters;
3692 r = get_pointer_64(ReferenceValue, offset, left, S, info);
3693 if (r == nullptr || left < sizeof(struct cfstring64_t))
3694 return nullptr;
3695 memcpy(&cfs, r, sizeof(struct cfstring64_t));
3696 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3697 swapStruct(cfs);
3698 if (cfs.characters == 0) {
3699 uint64_t n_value;
3700 const char *symbol_name = get_symbol_64(
3701 offset + offsetof(struct cfstring64_t, characters), S, info, n_value);
3702 if (symbol_name == nullptr)
3703 return nullptr;
3704 cfs_characters = n_value;
3705 } else
3706 cfs_characters = cfs.characters;
3707 name = get_pointer_64(cfs_characters, offset, left, S, info);
3709 return name;
3712 // get_objc2_64bit_selref() is used for disassembly and is passed a the address
3713 // of a pointer to an Objective-C selector reference when the pointer value is
3714 // zero as in a .o file and is likely to have a external relocation entry with
3715 // who's symbol's n_value is the real pointer to the selector name. If that is
3716 // the case the real pointer to the selector name is returned else 0 is
3717 // returned
3718 static uint64_t get_objc2_64bit_selref(uint64_t ReferenceValue,
3719 struct DisassembleInfo *info) {
3720 uint32_t offset, left;
3721 SectionRef S;
3723 const char *r = get_pointer_64(ReferenceValue, offset, left, S, info);
3724 if (r == nullptr || left < sizeof(uint64_t))
3725 return 0;
3726 uint64_t n_value;
3727 const char *symbol_name = get_symbol_64(offset, S, info, n_value);
3728 if (symbol_name == nullptr)
3729 return 0;
3730 return n_value;
3733 static const SectionRef get_section(MachOObjectFile *O, const char *segname,
3734 const char *sectname) {
3735 for (const SectionRef &Section : O->sections()) {
3736 StringRef SectName;
3737 Section.getName(SectName);
3738 DataRefImpl Ref = Section.getRawDataRefImpl();
3739 StringRef SegName = O->getSectionFinalSegmentName(Ref);
3740 if (SegName == segname && SectName == sectname)
3741 return Section;
3743 return SectionRef();
3746 static void
3747 walk_pointer_list_64(const char *listname, const SectionRef S,
3748 MachOObjectFile *O, struct DisassembleInfo *info,
3749 void (*func)(uint64_t, struct DisassembleInfo *info)) {
3750 if (S == SectionRef())
3751 return;
3753 StringRef SectName;
3754 S.getName(SectName);
3755 DataRefImpl Ref = S.getRawDataRefImpl();
3756 StringRef SegName = O->getSectionFinalSegmentName(Ref);
3757 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
3759 StringRef BytesStr;
3760 S.getContents(BytesStr);
3761 const char *Contents = reinterpret_cast<const char *>(BytesStr.data());
3763 for (uint32_t i = 0; i < S.getSize(); i += sizeof(uint64_t)) {
3764 uint32_t left = S.getSize() - i;
3765 uint32_t size = left < sizeof(uint64_t) ? left : sizeof(uint64_t);
3766 uint64_t p = 0;
3767 memcpy(&p, Contents + i, size);
3768 if (i + sizeof(uint64_t) > S.getSize())
3769 outs() << listname << " list pointer extends past end of (" << SegName
3770 << "," << SectName << ") section\n";
3771 outs() << format("%016" PRIx64, S.getAddress() + i) << " ";
3773 if (O->isLittleEndian() != sys::IsLittleEndianHost)
3774 sys::swapByteOrder(p);
3776 uint64_t n_value = 0;
3777 const char *name = get_symbol_64(i, S, info, n_value, p);
3778 if (name == nullptr)
3779 name = get_dyld_bind_info_symbolname(S.getAddress() + i, info);
3781 if (n_value != 0) {
3782 outs() << format("0x%" PRIx64, n_value);
3783 if (p != 0)
3784 outs() << " + " << format("0x%" PRIx64, p);
3785 } else
3786 outs() << format("0x%" PRIx64, p);
3787 if (name != nullptr)
3788 outs() << " " << name;
3789 outs() << "\n";
3791 p += n_value;
3792 if (func)
3793 func(p, info);
3797 static void
3798 walk_pointer_list_32(const char *listname, const SectionRef S,
3799 MachOObjectFile *O, struct DisassembleInfo *info,
3800 void (*func)(uint32_t, struct DisassembleInfo *info)) {
3801 if (S == SectionRef())
3802 return;
3804 StringRef SectName;
3805 S.getName(SectName);
3806 DataRefImpl Ref = S.getRawDataRefImpl();
3807 StringRef SegName = O->getSectionFinalSegmentName(Ref);
3808 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
3810 StringRef BytesStr;
3811 S.getContents(BytesStr);
3812 const char *Contents = reinterpret_cast<const char *>(BytesStr.data());
3814 for (uint32_t i = 0; i < S.getSize(); i += sizeof(uint32_t)) {
3815 uint32_t left = S.getSize() - i;
3816 uint32_t size = left < sizeof(uint32_t) ? left : sizeof(uint32_t);
3817 uint32_t p = 0;
3818 memcpy(&p, Contents + i, size);
3819 if (i + sizeof(uint32_t) > S.getSize())
3820 outs() << listname << " list pointer extends past end of (" << SegName
3821 << "," << SectName << ") section\n";
3822 uint32_t Address = S.getAddress() + i;
3823 outs() << format("%08" PRIx32, Address) << " ";
3825 if (O->isLittleEndian() != sys::IsLittleEndianHost)
3826 sys::swapByteOrder(p);
3827 outs() << format("0x%" PRIx32, p);
3829 const char *name = get_symbol_32(i, S, info, p);
3830 if (name != nullptr)
3831 outs() << " " << name;
3832 outs() << "\n";
3834 if (func)
3835 func(p, info);
3839 static void print_layout_map(const char *layout_map, uint32_t left) {
3840 if (layout_map == nullptr)
3841 return;
3842 outs() << " layout map: ";
3843 do {
3844 outs() << format("0x%02" PRIx32, (*layout_map) & 0xff) << " ";
3845 left--;
3846 layout_map++;
3847 } while (*layout_map != '\0' && left != 0);
3848 outs() << "\n";
3851 static void print_layout_map64(uint64_t p, struct DisassembleInfo *info) {
3852 uint32_t offset, left;
3853 SectionRef S;
3854 const char *layout_map;
3856 if (p == 0)
3857 return;
3858 layout_map = get_pointer_64(p, offset, left, S, info);
3859 print_layout_map(layout_map, left);
3862 static void print_layout_map32(uint32_t p, struct DisassembleInfo *info) {
3863 uint32_t offset, left;
3864 SectionRef S;
3865 const char *layout_map;
3867 if (p == 0)
3868 return;
3869 layout_map = get_pointer_32(p, offset, left, S, info);
3870 print_layout_map(layout_map, left);
3873 static void print_method_list64_t(uint64_t p, struct DisassembleInfo *info,
3874 const char *indent) {
3875 struct method_list64_t ml;
3876 struct method64_t m;
3877 const char *r;
3878 uint32_t offset, xoffset, left, i;
3879 SectionRef S, xS;
3880 const char *name, *sym_name;
3881 uint64_t n_value;
3883 r = get_pointer_64(p, offset, left, S, info);
3884 if (r == nullptr)
3885 return;
3886 memset(&ml, '\0', sizeof(struct method_list64_t));
3887 if (left < sizeof(struct method_list64_t)) {
3888 memcpy(&ml, r, left);
3889 outs() << " (method_list_t entends past the end of the section)\n";
3890 } else
3891 memcpy(&ml, r, sizeof(struct method_list64_t));
3892 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3893 swapStruct(ml);
3894 outs() << indent << "\t\t entsize " << ml.entsize << "\n";
3895 outs() << indent << "\t\t count " << ml.count << "\n";
3897 p += sizeof(struct method_list64_t);
3898 offset += sizeof(struct method_list64_t);
3899 for (i = 0; i < ml.count; i++) {
3900 r = get_pointer_64(p, offset, left, S, info);
3901 if (r == nullptr)
3902 return;
3903 memset(&m, '\0', sizeof(struct method64_t));
3904 if (left < sizeof(struct method64_t)) {
3905 memcpy(&m, r, left);
3906 outs() << indent << " (method_t extends past the end of the section)\n";
3907 } else
3908 memcpy(&m, r, sizeof(struct method64_t));
3909 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3910 swapStruct(m);
3912 outs() << indent << "\t\t name ";
3913 sym_name = get_symbol_64(offset + offsetof(struct method64_t, name), S,
3914 info, n_value, m.name);
3915 if (n_value != 0) {
3916 if (info->verbose && sym_name != nullptr)
3917 outs() << sym_name;
3918 else
3919 outs() << format("0x%" PRIx64, n_value);
3920 if (m.name != 0)
3921 outs() << " + " << format("0x%" PRIx64, m.name);
3922 } else
3923 outs() << format("0x%" PRIx64, m.name);
3924 name = get_pointer_64(m.name + n_value, xoffset, left, xS, info);
3925 if (name != nullptr)
3926 outs() << format(" %.*s", left, name);
3927 outs() << "\n";
3929 outs() << indent << "\t\t types ";
3930 sym_name = get_symbol_64(offset + offsetof(struct method64_t, types), S,
3931 info, n_value, m.types);
3932 if (n_value != 0) {
3933 if (info->verbose && sym_name != nullptr)
3934 outs() << sym_name;
3935 else
3936 outs() << format("0x%" PRIx64, n_value);
3937 if (m.types != 0)
3938 outs() << " + " << format("0x%" PRIx64, m.types);
3939 } else
3940 outs() << format("0x%" PRIx64, m.types);
3941 name = get_pointer_64(m.types + n_value, xoffset, left, xS, info);
3942 if (name != nullptr)
3943 outs() << format(" %.*s", left, name);
3944 outs() << "\n";
3946 outs() << indent << "\t\t imp ";
3947 name = get_symbol_64(offset + offsetof(struct method64_t, imp), S, info,
3948 n_value, m.imp);
3949 if (info->verbose && name == nullptr) {
3950 if (n_value != 0) {
3951 outs() << format("0x%" PRIx64, n_value) << " ";
3952 if (m.imp != 0)
3953 outs() << "+ " << format("0x%" PRIx64, m.imp) << " ";
3954 } else
3955 outs() << format("0x%" PRIx64, m.imp) << " ";
3957 if (name != nullptr)
3958 outs() << name;
3959 outs() << "\n";
3961 p += sizeof(struct method64_t);
3962 offset += sizeof(struct method64_t);
3966 static void print_method_list32_t(uint64_t p, struct DisassembleInfo *info,
3967 const char *indent) {
3968 struct method_list32_t ml;
3969 struct method32_t m;
3970 const char *r, *name;
3971 uint32_t offset, xoffset, left, i;
3972 SectionRef S, xS;
3974 r = get_pointer_32(p, offset, left, S, info);
3975 if (r == nullptr)
3976 return;
3977 memset(&ml, '\0', sizeof(struct method_list32_t));
3978 if (left < sizeof(struct method_list32_t)) {
3979 memcpy(&ml, r, left);
3980 outs() << " (method_list_t entends past the end of the section)\n";
3981 } else
3982 memcpy(&ml, r, sizeof(struct method_list32_t));
3983 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3984 swapStruct(ml);
3985 outs() << indent << "\t\t entsize " << ml.entsize << "\n";
3986 outs() << indent << "\t\t count " << ml.count << "\n";
3988 p += sizeof(struct method_list32_t);
3989 offset += sizeof(struct method_list32_t);
3990 for (i = 0; i < ml.count; i++) {
3991 r = get_pointer_32(p, offset, left, S, info);
3992 if (r == nullptr)
3993 return;
3994 memset(&m, '\0', sizeof(struct method32_t));
3995 if (left < sizeof(struct method32_t)) {
3996 memcpy(&ml, r, left);
3997 outs() << indent << " (method_t entends past the end of the section)\n";
3998 } else
3999 memcpy(&m, r, sizeof(struct method32_t));
4000 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4001 swapStruct(m);
4003 outs() << indent << "\t\t name " << format("0x%" PRIx32, m.name);
4004 name = get_pointer_32(m.name, xoffset, left, xS, info);
4005 if (name != nullptr)
4006 outs() << format(" %.*s", left, name);
4007 outs() << "\n";
4009 outs() << indent << "\t\t types " << format("0x%" PRIx32, m.types);
4010 name = get_pointer_32(m.types, xoffset, left, xS, info);
4011 if (name != nullptr)
4012 outs() << format(" %.*s", left, name);
4013 outs() << "\n";
4015 outs() << indent << "\t\t imp " << format("0x%" PRIx32, m.imp);
4016 name = get_symbol_32(offset + offsetof(struct method32_t, imp), S, info,
4017 m.imp);
4018 if (name != nullptr)
4019 outs() << " " << name;
4020 outs() << "\n";
4022 p += sizeof(struct method32_t);
4023 offset += sizeof(struct method32_t);
4027 static bool print_method_list(uint32_t p, struct DisassembleInfo *info) {
4028 uint32_t offset, left, xleft;
4029 SectionRef S;
4030 struct objc_method_list_t method_list;
4031 struct objc_method_t method;
4032 const char *r, *methods, *name, *SymbolName;
4033 int32_t i;
4035 r = get_pointer_32(p, offset, left, S, info, true);
4036 if (r == nullptr)
4037 return true;
4039 outs() << "\n";
4040 if (left > sizeof(struct objc_method_list_t)) {
4041 memcpy(&method_list, r, sizeof(struct objc_method_list_t));
4042 } else {
4043 outs() << "\t\t objc_method_list extends past end of the section\n";
4044 memset(&method_list, '\0', sizeof(struct objc_method_list_t));
4045 memcpy(&method_list, r, left);
4047 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4048 swapStruct(method_list);
4050 outs() << "\t\t obsolete "
4051 << format("0x%08" PRIx32, method_list.obsolete) << "\n";
4052 outs() << "\t\t method_count " << method_list.method_count << "\n";
4054 methods = r + sizeof(struct objc_method_list_t);
4055 for (i = 0; i < method_list.method_count; i++) {
4056 if ((i + 1) * sizeof(struct objc_method_t) > left) {
4057 outs() << "\t\t remaining method's extend past the of the section\n";
4058 break;
4060 memcpy(&method, methods + i * sizeof(struct objc_method_t),
4061 sizeof(struct objc_method_t));
4062 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4063 swapStruct(method);
4065 outs() << "\t\t method_name "
4066 << format("0x%08" PRIx32, method.method_name);
4067 if (info->verbose) {
4068 name = get_pointer_32(method.method_name, offset, xleft, S, info, true);
4069 if (name != nullptr)
4070 outs() << format(" %.*s", xleft, name);
4071 else
4072 outs() << " (not in an __OBJC section)";
4074 outs() << "\n";
4076 outs() << "\t\t method_types "
4077 << format("0x%08" PRIx32, method.method_types);
4078 if (info->verbose) {
4079 name = get_pointer_32(method.method_types, offset, xleft, S, info, true);
4080 if (name != nullptr)
4081 outs() << format(" %.*s", xleft, name);
4082 else
4083 outs() << " (not in an __OBJC section)";
4085 outs() << "\n";
4087 outs() << "\t\t method_imp "
4088 << format("0x%08" PRIx32, method.method_imp) << " ";
4089 if (info->verbose) {
4090 SymbolName = GuessSymbolName(method.method_imp, info->AddrMap);
4091 if (SymbolName != nullptr)
4092 outs() << SymbolName;
4094 outs() << "\n";
4096 return false;
4099 static void print_protocol_list64_t(uint64_t p, struct DisassembleInfo *info) {
4100 struct protocol_list64_t pl;
4101 uint64_t q, n_value;
4102 struct protocol64_t pc;
4103 const char *r;
4104 uint32_t offset, xoffset, left, i;
4105 SectionRef S, xS;
4106 const char *name, *sym_name;
4108 r = get_pointer_64(p, offset, left, S, info);
4109 if (r == nullptr)
4110 return;
4111 memset(&pl, '\0', sizeof(struct protocol_list64_t));
4112 if (left < sizeof(struct protocol_list64_t)) {
4113 memcpy(&pl, r, left);
4114 outs() << " (protocol_list_t entends past the end of the section)\n";
4115 } else
4116 memcpy(&pl, r, sizeof(struct protocol_list64_t));
4117 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4118 swapStruct(pl);
4119 outs() << " count " << pl.count << "\n";
4121 p += sizeof(struct protocol_list64_t);
4122 offset += sizeof(struct protocol_list64_t);
4123 for (i = 0; i < pl.count; i++) {
4124 r = get_pointer_64(p, offset, left, S, info);
4125 if (r == nullptr)
4126 return;
4127 q = 0;
4128 if (left < sizeof(uint64_t)) {
4129 memcpy(&q, r, left);
4130 outs() << " (protocol_t * entends past the end of the section)\n";
4131 } else
4132 memcpy(&q, r, sizeof(uint64_t));
4133 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4134 sys::swapByteOrder(q);
4136 outs() << "\t\t list[" << i << "] ";
4137 sym_name = get_symbol_64(offset, S, info, n_value, q);
4138 if (n_value != 0) {
4139 if (info->verbose && sym_name != nullptr)
4140 outs() << sym_name;
4141 else
4142 outs() << format("0x%" PRIx64, n_value);
4143 if (q != 0)
4144 outs() << " + " << format("0x%" PRIx64, q);
4145 } else
4146 outs() << format("0x%" PRIx64, q);
4147 outs() << " (struct protocol_t *)\n";
4149 r = get_pointer_64(q + n_value, offset, left, S, info);
4150 if (r == nullptr)
4151 return;
4152 memset(&pc, '\0', sizeof(struct protocol64_t));
4153 if (left < sizeof(struct protocol64_t)) {
4154 memcpy(&pc, r, left);
4155 outs() << " (protocol_t entends past the end of the section)\n";
4156 } else
4157 memcpy(&pc, r, sizeof(struct protocol64_t));
4158 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4159 swapStruct(pc);
4161 outs() << "\t\t\t isa " << format("0x%" PRIx64, pc.isa) << "\n";
4163 outs() << "\t\t\t name ";
4164 sym_name = get_symbol_64(offset + offsetof(struct protocol64_t, name), S,
4165 info, n_value, pc.name);
4166 if (n_value != 0) {
4167 if (info->verbose && sym_name != nullptr)
4168 outs() << sym_name;
4169 else
4170 outs() << format("0x%" PRIx64, n_value);
4171 if (pc.name != 0)
4172 outs() << " + " << format("0x%" PRIx64, pc.name);
4173 } else
4174 outs() << format("0x%" PRIx64, pc.name);
4175 name = get_pointer_64(pc.name + n_value, xoffset, left, xS, info);
4176 if (name != nullptr)
4177 outs() << format(" %.*s", left, name);
4178 outs() << "\n";
4180 outs() << "\t\t\tprotocols " << format("0x%" PRIx64, pc.protocols) << "\n";
4182 outs() << "\t\t instanceMethods ";
4183 sym_name =
4184 get_symbol_64(offset + offsetof(struct protocol64_t, instanceMethods),
4185 S, info, n_value, pc.instanceMethods);
4186 if (n_value != 0) {
4187 if (info->verbose && sym_name != nullptr)
4188 outs() << sym_name;
4189 else
4190 outs() << format("0x%" PRIx64, n_value);
4191 if (pc.instanceMethods != 0)
4192 outs() << " + " << format("0x%" PRIx64, pc.instanceMethods);
4193 } else
4194 outs() << format("0x%" PRIx64, pc.instanceMethods);
4195 outs() << " (struct method_list_t *)\n";
4196 if (pc.instanceMethods + n_value != 0)
4197 print_method_list64_t(pc.instanceMethods + n_value, info, "\t");
4199 outs() << "\t\t classMethods ";
4200 sym_name =
4201 get_symbol_64(offset + offsetof(struct protocol64_t, classMethods), S,
4202 info, n_value, pc.classMethods);
4203 if (n_value != 0) {
4204 if (info->verbose && sym_name != nullptr)
4205 outs() << sym_name;
4206 else
4207 outs() << format("0x%" PRIx64, n_value);
4208 if (pc.classMethods != 0)
4209 outs() << " + " << format("0x%" PRIx64, pc.classMethods);
4210 } else
4211 outs() << format("0x%" PRIx64, pc.classMethods);
4212 outs() << " (struct method_list_t *)\n";
4213 if (pc.classMethods + n_value != 0)
4214 print_method_list64_t(pc.classMethods + n_value, info, "\t");
4216 outs() << "\t optionalInstanceMethods "
4217 << format("0x%" PRIx64, pc.optionalInstanceMethods) << "\n";
4218 outs() << "\t optionalClassMethods "
4219 << format("0x%" PRIx64, pc.optionalClassMethods) << "\n";
4220 outs() << "\t instanceProperties "
4221 << format("0x%" PRIx64, pc.instanceProperties) << "\n";
4223 p += sizeof(uint64_t);
4224 offset += sizeof(uint64_t);
4228 static void print_protocol_list32_t(uint32_t p, struct DisassembleInfo *info) {
4229 struct protocol_list32_t pl;
4230 uint32_t q;
4231 struct protocol32_t pc;
4232 const char *r;
4233 uint32_t offset, xoffset, left, i;
4234 SectionRef S, xS;
4235 const char *name;
4237 r = get_pointer_32(p, offset, left, S, info);
4238 if (r == nullptr)
4239 return;
4240 memset(&pl, '\0', sizeof(struct protocol_list32_t));
4241 if (left < sizeof(struct protocol_list32_t)) {
4242 memcpy(&pl, r, left);
4243 outs() << " (protocol_list_t entends past the end of the section)\n";
4244 } else
4245 memcpy(&pl, r, sizeof(struct protocol_list32_t));
4246 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4247 swapStruct(pl);
4248 outs() << " count " << pl.count << "\n";
4250 p += sizeof(struct protocol_list32_t);
4251 offset += sizeof(struct protocol_list32_t);
4252 for (i = 0; i < pl.count; i++) {
4253 r = get_pointer_32(p, offset, left, S, info);
4254 if (r == nullptr)
4255 return;
4256 q = 0;
4257 if (left < sizeof(uint32_t)) {
4258 memcpy(&q, r, left);
4259 outs() << " (protocol_t * entends past the end of the section)\n";
4260 } else
4261 memcpy(&q, r, sizeof(uint32_t));
4262 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4263 sys::swapByteOrder(q);
4264 outs() << "\t\t list[" << i << "] " << format("0x%" PRIx32, q)
4265 << " (struct protocol_t *)\n";
4266 r = get_pointer_32(q, offset, left, S, info);
4267 if (r == nullptr)
4268 return;
4269 memset(&pc, '\0', sizeof(struct protocol32_t));
4270 if (left < sizeof(struct protocol32_t)) {
4271 memcpy(&pc, r, left);
4272 outs() << " (protocol_t entends past the end of the section)\n";
4273 } else
4274 memcpy(&pc, r, sizeof(struct protocol32_t));
4275 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4276 swapStruct(pc);
4277 outs() << "\t\t\t isa " << format("0x%" PRIx32, pc.isa) << "\n";
4278 outs() << "\t\t\t name " << format("0x%" PRIx32, pc.name);
4279 name = get_pointer_32(pc.name, xoffset, left, xS, info);
4280 if (name != nullptr)
4281 outs() << format(" %.*s", left, name);
4282 outs() << "\n";
4283 outs() << "\t\t\tprotocols " << format("0x%" PRIx32, pc.protocols) << "\n";
4284 outs() << "\t\t instanceMethods "
4285 << format("0x%" PRIx32, pc.instanceMethods)
4286 << " (struct method_list_t *)\n";
4287 if (pc.instanceMethods != 0)
4288 print_method_list32_t(pc.instanceMethods, info, "\t");
4289 outs() << "\t\t classMethods " << format("0x%" PRIx32, pc.classMethods)
4290 << " (struct method_list_t *)\n";
4291 if (pc.classMethods != 0)
4292 print_method_list32_t(pc.classMethods, info, "\t");
4293 outs() << "\t optionalInstanceMethods "
4294 << format("0x%" PRIx32, pc.optionalInstanceMethods) << "\n";
4295 outs() << "\t optionalClassMethods "
4296 << format("0x%" PRIx32, pc.optionalClassMethods) << "\n";
4297 outs() << "\t instanceProperties "
4298 << format("0x%" PRIx32, pc.instanceProperties) << "\n";
4299 p += sizeof(uint32_t);
4300 offset += sizeof(uint32_t);
4304 static void print_indent(uint32_t indent) {
4305 for (uint32_t i = 0; i < indent;) {
4306 if (indent - i >= 8) {
4307 outs() << "\t";
4308 i += 8;
4309 } else {
4310 for (uint32_t j = i; j < indent; j++)
4311 outs() << " ";
4312 return;
4317 static bool print_method_description_list(uint32_t p, uint32_t indent,
4318 struct DisassembleInfo *info) {
4319 uint32_t offset, left, xleft;
4320 SectionRef S;
4321 struct objc_method_description_list_t mdl;
4322 struct objc_method_description_t md;
4323 const char *r, *list, *name;
4324 int32_t i;
4326 r = get_pointer_32(p, offset, left, S, info, true);
4327 if (r == nullptr)
4328 return true;
4330 outs() << "\n";
4331 if (left > sizeof(struct objc_method_description_list_t)) {
4332 memcpy(&mdl, r, sizeof(struct objc_method_description_list_t));
4333 } else {
4334 print_indent(indent);
4335 outs() << " objc_method_description_list extends past end of the section\n";
4336 memset(&mdl, '\0', sizeof(struct objc_method_description_list_t));
4337 memcpy(&mdl, r, left);
4339 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4340 swapStruct(mdl);
4342 print_indent(indent);
4343 outs() << " count " << mdl.count << "\n";
4345 list = r + sizeof(struct objc_method_description_list_t);
4346 for (i = 0; i < mdl.count; i++) {
4347 if ((i + 1) * sizeof(struct objc_method_description_t) > left) {
4348 print_indent(indent);
4349 outs() << " remaining list entries extend past the of the section\n";
4350 break;
4352 print_indent(indent);
4353 outs() << " list[" << i << "]\n";
4354 memcpy(&md, list + i * sizeof(struct objc_method_description_t),
4355 sizeof(struct objc_method_description_t));
4356 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4357 swapStruct(md);
4359 print_indent(indent);
4360 outs() << " name " << format("0x%08" PRIx32, md.name);
4361 if (info->verbose) {
4362 name = get_pointer_32(md.name, offset, xleft, S, info, true);
4363 if (name != nullptr)
4364 outs() << format(" %.*s", xleft, name);
4365 else
4366 outs() << " (not in an __OBJC section)";
4368 outs() << "\n";
4370 print_indent(indent);
4371 outs() << " types " << format("0x%08" PRIx32, md.types);
4372 if (info->verbose) {
4373 name = get_pointer_32(md.types, offset, xleft, S, info, true);
4374 if (name != nullptr)
4375 outs() << format(" %.*s", xleft, name);
4376 else
4377 outs() << " (not in an __OBJC section)";
4379 outs() << "\n";
4381 return false;
4384 static bool print_protocol_list(uint32_t p, uint32_t indent,
4385 struct DisassembleInfo *info);
4387 static bool print_protocol(uint32_t p, uint32_t indent,
4388 struct DisassembleInfo *info) {
4389 uint32_t offset, left;
4390 SectionRef S;
4391 struct objc_protocol_t protocol;
4392 const char *r, *name;
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_protocol_t)) {
4400 memcpy(&protocol, r, sizeof(struct objc_protocol_t));
4401 } else {
4402 print_indent(indent);
4403 outs() << " Protocol extends past end of the section\n";
4404 memset(&protocol, '\0', sizeof(struct objc_protocol_t));
4405 memcpy(&protocol, r, left);
4407 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4408 swapStruct(protocol);
4410 print_indent(indent);
4411 outs() << " isa " << format("0x%08" PRIx32, protocol.isa)
4412 << "\n";
4414 print_indent(indent);
4415 outs() << " protocol_name "
4416 << format("0x%08" PRIx32, protocol.protocol_name);
4417 if (info->verbose) {
4418 name = get_pointer_32(protocol.protocol_name, offset, left, S, info, true);
4419 if (name != nullptr)
4420 outs() << format(" %.*s", left, name);
4421 else
4422 outs() << " (not in an __OBJC section)";
4424 outs() << "\n";
4426 print_indent(indent);
4427 outs() << " protocol_list "
4428 << format("0x%08" PRIx32, protocol.protocol_list);
4429 if (print_protocol_list(protocol.protocol_list, indent + 4, info))
4430 outs() << " (not in an __OBJC section)\n";
4432 print_indent(indent);
4433 outs() << " instance_methods "
4434 << format("0x%08" PRIx32, protocol.instance_methods);
4435 if (print_method_description_list(protocol.instance_methods, indent, info))
4436 outs() << " (not in an __OBJC section)\n";
4438 print_indent(indent);
4439 outs() << " class_methods "
4440 << format("0x%08" PRIx32, protocol.class_methods);
4441 if (print_method_description_list(protocol.class_methods, indent, info))
4442 outs() << " (not in an __OBJC section)\n";
4444 return false;
4447 static bool print_protocol_list(uint32_t p, uint32_t indent,
4448 struct DisassembleInfo *info) {
4449 uint32_t offset, left, l;
4450 SectionRef S;
4451 struct objc_protocol_list_t protocol_list;
4452 const char *r, *list;
4453 int32_t i;
4455 r = get_pointer_32(p, offset, left, S, info, true);
4456 if (r == nullptr)
4457 return true;
4459 outs() << "\n";
4460 if (left > sizeof(struct objc_protocol_list_t)) {
4461 memcpy(&protocol_list, r, sizeof(struct objc_protocol_list_t));
4462 } else {
4463 outs() << "\t\t objc_protocol_list_t extends past end of the section\n";
4464 memset(&protocol_list, '\0', sizeof(struct objc_protocol_list_t));
4465 memcpy(&protocol_list, r, left);
4467 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4468 swapStruct(protocol_list);
4470 print_indent(indent);
4471 outs() << " next " << format("0x%08" PRIx32, protocol_list.next)
4472 << "\n";
4473 print_indent(indent);
4474 outs() << " count " << protocol_list.count << "\n";
4476 list = r + sizeof(struct objc_protocol_list_t);
4477 for (i = 0; i < protocol_list.count; i++) {
4478 if ((i + 1) * sizeof(uint32_t) > left) {
4479 outs() << "\t\t remaining list entries extend past the of the section\n";
4480 break;
4482 memcpy(&l, list + i * sizeof(uint32_t), sizeof(uint32_t));
4483 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4484 sys::swapByteOrder(l);
4486 print_indent(indent);
4487 outs() << " list[" << i << "] " << format("0x%08" PRIx32, l);
4488 if (print_protocol(l, indent, info))
4489 outs() << "(not in an __OBJC section)\n";
4491 return false;
4494 static void print_ivar_list64_t(uint64_t p, struct DisassembleInfo *info) {
4495 struct ivar_list64_t il;
4496 struct ivar64_t i;
4497 const char *r;
4498 uint32_t offset, xoffset, left, j;
4499 SectionRef S, xS;
4500 const char *name, *sym_name, *ivar_offset_p;
4501 uint64_t ivar_offset, n_value;
4503 r = get_pointer_64(p, offset, left, S, info);
4504 if (r == nullptr)
4505 return;
4506 memset(&il, '\0', sizeof(struct ivar_list64_t));
4507 if (left < sizeof(struct ivar_list64_t)) {
4508 memcpy(&il, r, left);
4509 outs() << " (ivar_list_t entends past the end of the section)\n";
4510 } else
4511 memcpy(&il, r, sizeof(struct ivar_list64_t));
4512 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4513 swapStruct(il);
4514 outs() << " entsize " << il.entsize << "\n";
4515 outs() << " count " << il.count << "\n";
4517 p += sizeof(struct ivar_list64_t);
4518 offset += sizeof(struct ivar_list64_t);
4519 for (j = 0; j < il.count; j++) {
4520 r = get_pointer_64(p, offset, left, S, info);
4521 if (r == nullptr)
4522 return;
4523 memset(&i, '\0', sizeof(struct ivar64_t));
4524 if (left < sizeof(struct ivar64_t)) {
4525 memcpy(&i, r, left);
4526 outs() << " (ivar_t entends past the end of the section)\n";
4527 } else
4528 memcpy(&i, r, sizeof(struct ivar64_t));
4529 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4530 swapStruct(i);
4532 outs() << "\t\t\t offset ";
4533 sym_name = get_symbol_64(offset + offsetof(struct ivar64_t, offset), S,
4534 info, n_value, i.offset);
4535 if (n_value != 0) {
4536 if (info->verbose && sym_name != nullptr)
4537 outs() << sym_name;
4538 else
4539 outs() << format("0x%" PRIx64, n_value);
4540 if (i.offset != 0)
4541 outs() << " + " << format("0x%" PRIx64, i.offset);
4542 } else
4543 outs() << format("0x%" PRIx64, i.offset);
4544 ivar_offset_p = get_pointer_64(i.offset + n_value, xoffset, left, xS, info);
4545 if (ivar_offset_p != nullptr && left >= sizeof(*ivar_offset_p)) {
4546 memcpy(&ivar_offset, ivar_offset_p, sizeof(ivar_offset));
4547 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4548 sys::swapByteOrder(ivar_offset);
4549 outs() << " " << ivar_offset << "\n";
4550 } else
4551 outs() << "\n";
4553 outs() << "\t\t\t name ";
4554 sym_name = get_symbol_64(offset + offsetof(struct ivar64_t, name), S, info,
4555 n_value, i.name);
4556 if (n_value != 0) {
4557 if (info->verbose && sym_name != nullptr)
4558 outs() << sym_name;
4559 else
4560 outs() << format("0x%" PRIx64, n_value);
4561 if (i.name != 0)
4562 outs() << " + " << format("0x%" PRIx64, i.name);
4563 } else
4564 outs() << format("0x%" PRIx64, i.name);
4565 name = get_pointer_64(i.name + n_value, xoffset, left, xS, info);
4566 if (name != nullptr)
4567 outs() << format(" %.*s", left, name);
4568 outs() << "\n";
4570 outs() << "\t\t\t type ";
4571 sym_name = get_symbol_64(offset + offsetof(struct ivar64_t, type), S, info,
4572 n_value, i.name);
4573 name = get_pointer_64(i.type + n_value, xoffset, left, xS, info);
4574 if (n_value != 0) {
4575 if (info->verbose && sym_name != nullptr)
4576 outs() << sym_name;
4577 else
4578 outs() << format("0x%" PRIx64, n_value);
4579 if (i.type != 0)
4580 outs() << " + " << format("0x%" PRIx64, i.type);
4581 } else
4582 outs() << format("0x%" PRIx64, i.type);
4583 if (name != nullptr)
4584 outs() << format(" %.*s", left, name);
4585 outs() << "\n";
4587 outs() << "\t\t\talignment " << i.alignment << "\n";
4588 outs() << "\t\t\t size " << i.size << "\n";
4590 p += sizeof(struct ivar64_t);
4591 offset += sizeof(struct ivar64_t);
4595 static void print_ivar_list32_t(uint32_t p, struct DisassembleInfo *info) {
4596 struct ivar_list32_t il;
4597 struct ivar32_t i;
4598 const char *r;
4599 uint32_t offset, xoffset, left, j;
4600 SectionRef S, xS;
4601 const char *name, *ivar_offset_p;
4602 uint32_t ivar_offset;
4604 r = get_pointer_32(p, offset, left, S, info);
4605 if (r == nullptr)
4606 return;
4607 memset(&il, '\0', sizeof(struct ivar_list32_t));
4608 if (left < sizeof(struct ivar_list32_t)) {
4609 memcpy(&il, r, left);
4610 outs() << " (ivar_list_t entends past the end of the section)\n";
4611 } else
4612 memcpy(&il, r, sizeof(struct ivar_list32_t));
4613 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4614 swapStruct(il);
4615 outs() << " entsize " << il.entsize << "\n";
4616 outs() << " count " << il.count << "\n";
4618 p += sizeof(struct ivar_list32_t);
4619 offset += sizeof(struct ivar_list32_t);
4620 for (j = 0; j < il.count; j++) {
4621 r = get_pointer_32(p, offset, left, S, info);
4622 if (r == nullptr)
4623 return;
4624 memset(&i, '\0', sizeof(struct ivar32_t));
4625 if (left < sizeof(struct ivar32_t)) {
4626 memcpy(&i, r, left);
4627 outs() << " (ivar_t entends past the end of the section)\n";
4628 } else
4629 memcpy(&i, r, sizeof(struct ivar32_t));
4630 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4631 swapStruct(i);
4633 outs() << "\t\t\t offset " << format("0x%" PRIx32, i.offset);
4634 ivar_offset_p = get_pointer_32(i.offset, xoffset, left, xS, info);
4635 if (ivar_offset_p != nullptr && left >= sizeof(*ivar_offset_p)) {
4636 memcpy(&ivar_offset, ivar_offset_p, sizeof(ivar_offset));
4637 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4638 sys::swapByteOrder(ivar_offset);
4639 outs() << " " << ivar_offset << "\n";
4640 } else
4641 outs() << "\n";
4643 outs() << "\t\t\t name " << format("0x%" PRIx32, i.name);
4644 name = get_pointer_32(i.name, xoffset, left, xS, info);
4645 if (name != nullptr)
4646 outs() << format(" %.*s", left, name);
4647 outs() << "\n";
4649 outs() << "\t\t\t type " << format("0x%" PRIx32, i.type);
4650 name = get_pointer_32(i.type, xoffset, left, xS, info);
4651 if (name != nullptr)
4652 outs() << format(" %.*s", left, name);
4653 outs() << "\n";
4655 outs() << "\t\t\talignment " << i.alignment << "\n";
4656 outs() << "\t\t\t size " << i.size << "\n";
4658 p += sizeof(struct ivar32_t);
4659 offset += sizeof(struct ivar32_t);
4663 static void print_objc_property_list64(uint64_t p,
4664 struct DisassembleInfo *info) {
4665 struct objc_property_list64 opl;
4666 struct objc_property64 op;
4667 const char *r;
4668 uint32_t offset, xoffset, left, j;
4669 SectionRef S, xS;
4670 const char *name, *sym_name;
4671 uint64_t n_value;
4673 r = get_pointer_64(p, offset, left, S, info);
4674 if (r == nullptr)
4675 return;
4676 memset(&opl, '\0', sizeof(struct objc_property_list64));
4677 if (left < sizeof(struct objc_property_list64)) {
4678 memcpy(&opl, r, left);
4679 outs() << " (objc_property_list entends past the end of the section)\n";
4680 } else
4681 memcpy(&opl, r, sizeof(struct objc_property_list64));
4682 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4683 swapStruct(opl);
4684 outs() << " entsize " << opl.entsize << "\n";
4685 outs() << " count " << opl.count << "\n";
4687 p += sizeof(struct objc_property_list64);
4688 offset += sizeof(struct objc_property_list64);
4689 for (j = 0; j < opl.count; j++) {
4690 r = get_pointer_64(p, offset, left, S, info);
4691 if (r == nullptr)
4692 return;
4693 memset(&op, '\0', sizeof(struct objc_property64));
4694 if (left < sizeof(struct objc_property64)) {
4695 memcpy(&op, r, left);
4696 outs() << " (objc_property entends past the end of the section)\n";
4697 } else
4698 memcpy(&op, r, sizeof(struct objc_property64));
4699 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4700 swapStruct(op);
4702 outs() << "\t\t\t name ";
4703 sym_name = get_symbol_64(offset + offsetof(struct objc_property64, name), S,
4704 info, n_value, op.name);
4705 if (n_value != 0) {
4706 if (info->verbose && sym_name != nullptr)
4707 outs() << sym_name;
4708 else
4709 outs() << format("0x%" PRIx64, n_value);
4710 if (op.name != 0)
4711 outs() << " + " << format("0x%" PRIx64, op.name);
4712 } else
4713 outs() << format("0x%" PRIx64, op.name);
4714 name = get_pointer_64(op.name + n_value, xoffset, left, xS, info);
4715 if (name != nullptr)
4716 outs() << format(" %.*s", left, name);
4717 outs() << "\n";
4719 outs() << "\t\t\tattributes ";
4720 sym_name =
4721 get_symbol_64(offset + offsetof(struct objc_property64, attributes), S,
4722 info, n_value, op.attributes);
4723 if (n_value != 0) {
4724 if (info->verbose && sym_name != nullptr)
4725 outs() << sym_name;
4726 else
4727 outs() << format("0x%" PRIx64, n_value);
4728 if (op.attributes != 0)
4729 outs() << " + " << format("0x%" PRIx64, op.attributes);
4730 } else
4731 outs() << format("0x%" PRIx64, op.attributes);
4732 name = get_pointer_64(op.attributes + n_value, xoffset, left, xS, info);
4733 if (name != nullptr)
4734 outs() << format(" %.*s", left, name);
4735 outs() << "\n";
4737 p += sizeof(struct objc_property64);
4738 offset += sizeof(struct objc_property64);
4742 static void print_objc_property_list32(uint32_t p,
4743 struct DisassembleInfo *info) {
4744 struct objc_property_list32 opl;
4745 struct objc_property32 op;
4746 const char *r;
4747 uint32_t offset, xoffset, left, j;
4748 SectionRef S, xS;
4749 const char *name;
4751 r = get_pointer_32(p, offset, left, S, info);
4752 if (r == nullptr)
4753 return;
4754 memset(&opl, '\0', sizeof(struct objc_property_list32));
4755 if (left < sizeof(struct objc_property_list32)) {
4756 memcpy(&opl, r, left);
4757 outs() << " (objc_property_list entends past the end of the section)\n";
4758 } else
4759 memcpy(&opl, r, sizeof(struct objc_property_list32));
4760 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4761 swapStruct(opl);
4762 outs() << " entsize " << opl.entsize << "\n";
4763 outs() << " count " << opl.count << "\n";
4765 p += sizeof(struct objc_property_list32);
4766 offset += sizeof(struct objc_property_list32);
4767 for (j = 0; j < opl.count; j++) {
4768 r = get_pointer_32(p, offset, left, S, info);
4769 if (r == nullptr)
4770 return;
4771 memset(&op, '\0', sizeof(struct objc_property32));
4772 if (left < sizeof(struct objc_property32)) {
4773 memcpy(&op, r, left);
4774 outs() << " (objc_property entends past the end of the section)\n";
4775 } else
4776 memcpy(&op, r, sizeof(struct objc_property32));
4777 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4778 swapStruct(op);
4780 outs() << "\t\t\t name " << format("0x%" PRIx32, op.name);
4781 name = get_pointer_32(op.name, xoffset, left, xS, info);
4782 if (name != nullptr)
4783 outs() << format(" %.*s", left, name);
4784 outs() << "\n";
4786 outs() << "\t\t\tattributes " << format("0x%" PRIx32, op.attributes);
4787 name = get_pointer_32(op.attributes, xoffset, left, xS, info);
4788 if (name != nullptr)
4789 outs() << format(" %.*s", left, name);
4790 outs() << "\n";
4792 p += sizeof(struct objc_property32);
4793 offset += sizeof(struct objc_property32);
4797 static bool print_class_ro64_t(uint64_t p, struct DisassembleInfo *info,
4798 bool &is_meta_class) {
4799 struct class_ro64_t cro;
4800 const char *r;
4801 uint32_t offset, xoffset, left;
4802 SectionRef S, xS;
4803 const char *name, *sym_name;
4804 uint64_t n_value;
4806 r = get_pointer_64(p, offset, left, S, info);
4807 if (r == nullptr || left < sizeof(struct class_ro64_t))
4808 return false;
4809 memcpy(&cro, r, sizeof(struct class_ro64_t));
4810 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4811 swapStruct(cro);
4812 outs() << " flags " << format("0x%" PRIx32, cro.flags);
4813 if (cro.flags & RO_META)
4814 outs() << " RO_META";
4815 if (cro.flags & RO_ROOT)
4816 outs() << " RO_ROOT";
4817 if (cro.flags & RO_HAS_CXX_STRUCTORS)
4818 outs() << " RO_HAS_CXX_STRUCTORS";
4819 outs() << "\n";
4820 outs() << " instanceStart " << cro.instanceStart << "\n";
4821 outs() << " instanceSize " << cro.instanceSize << "\n";
4822 outs() << " reserved " << format("0x%" PRIx32, cro.reserved)
4823 << "\n";
4824 outs() << " ivarLayout " << format("0x%" PRIx64, cro.ivarLayout)
4825 << "\n";
4826 print_layout_map64(cro.ivarLayout, info);
4828 outs() << " name ";
4829 sym_name = get_symbol_64(offset + offsetof(struct class_ro64_t, name), S,
4830 info, n_value, cro.name);
4831 if (n_value != 0) {
4832 if (info->verbose && sym_name != nullptr)
4833 outs() << sym_name;
4834 else
4835 outs() << format("0x%" PRIx64, n_value);
4836 if (cro.name != 0)
4837 outs() << " + " << format("0x%" PRIx64, cro.name);
4838 } else
4839 outs() << format("0x%" PRIx64, cro.name);
4840 name = get_pointer_64(cro.name + n_value, xoffset, left, xS, info);
4841 if (name != nullptr)
4842 outs() << format(" %.*s", left, name);
4843 outs() << "\n";
4845 outs() << " baseMethods ";
4846 sym_name = get_symbol_64(offset + offsetof(struct class_ro64_t, baseMethods),
4847 S, info, n_value, cro.baseMethods);
4848 if (n_value != 0) {
4849 if (info->verbose && sym_name != nullptr)
4850 outs() << sym_name;
4851 else
4852 outs() << format("0x%" PRIx64, n_value);
4853 if (cro.baseMethods != 0)
4854 outs() << " + " << format("0x%" PRIx64, cro.baseMethods);
4855 } else
4856 outs() << format("0x%" PRIx64, cro.baseMethods);
4857 outs() << " (struct method_list_t *)\n";
4858 if (cro.baseMethods + n_value != 0)
4859 print_method_list64_t(cro.baseMethods + n_value, info, "");
4861 outs() << " baseProtocols ";
4862 sym_name =
4863 get_symbol_64(offset + offsetof(struct class_ro64_t, baseProtocols), S,
4864 info, n_value, cro.baseProtocols);
4865 if (n_value != 0) {
4866 if (info->verbose && sym_name != nullptr)
4867 outs() << sym_name;
4868 else
4869 outs() << format("0x%" PRIx64, n_value);
4870 if (cro.baseProtocols != 0)
4871 outs() << " + " << format("0x%" PRIx64, cro.baseProtocols);
4872 } else
4873 outs() << format("0x%" PRIx64, cro.baseProtocols);
4874 outs() << "\n";
4875 if (cro.baseProtocols + n_value != 0)
4876 print_protocol_list64_t(cro.baseProtocols + n_value, info);
4878 outs() << " ivars ";
4879 sym_name = get_symbol_64(offset + offsetof(struct class_ro64_t, ivars), S,
4880 info, n_value, cro.ivars);
4881 if (n_value != 0) {
4882 if (info->verbose && sym_name != nullptr)
4883 outs() << sym_name;
4884 else
4885 outs() << format("0x%" PRIx64, n_value);
4886 if (cro.ivars != 0)
4887 outs() << " + " << format("0x%" PRIx64, cro.ivars);
4888 } else
4889 outs() << format("0x%" PRIx64, cro.ivars);
4890 outs() << "\n";
4891 if (cro.ivars + n_value != 0)
4892 print_ivar_list64_t(cro.ivars + n_value, info);
4894 outs() << " weakIvarLayout ";
4895 sym_name =
4896 get_symbol_64(offset + offsetof(struct class_ro64_t, weakIvarLayout), S,
4897 info, n_value, cro.weakIvarLayout);
4898 if (n_value != 0) {
4899 if (info->verbose && sym_name != nullptr)
4900 outs() << sym_name;
4901 else
4902 outs() << format("0x%" PRIx64, n_value);
4903 if (cro.weakIvarLayout != 0)
4904 outs() << " + " << format("0x%" PRIx64, cro.weakIvarLayout);
4905 } else
4906 outs() << format("0x%" PRIx64, cro.weakIvarLayout);
4907 outs() << "\n";
4908 print_layout_map64(cro.weakIvarLayout + n_value, info);
4910 outs() << " baseProperties ";
4911 sym_name =
4912 get_symbol_64(offset + offsetof(struct class_ro64_t, baseProperties), S,
4913 info, n_value, cro.baseProperties);
4914 if (n_value != 0) {
4915 if (info->verbose && sym_name != nullptr)
4916 outs() << sym_name;
4917 else
4918 outs() << format("0x%" PRIx64, n_value);
4919 if (cro.baseProperties != 0)
4920 outs() << " + " << format("0x%" PRIx64, cro.baseProperties);
4921 } else
4922 outs() << format("0x%" PRIx64, cro.baseProperties);
4923 outs() << "\n";
4924 if (cro.baseProperties + n_value != 0)
4925 print_objc_property_list64(cro.baseProperties + n_value, info);
4927 is_meta_class = (cro.flags & RO_META) != 0;
4928 return true;
4931 static bool print_class_ro32_t(uint32_t p, struct DisassembleInfo *info,
4932 bool &is_meta_class) {
4933 struct class_ro32_t cro;
4934 const char *r;
4935 uint32_t offset, xoffset, left;
4936 SectionRef S, xS;
4937 const char *name;
4939 r = get_pointer_32(p, offset, left, S, info);
4940 if (r == nullptr)
4941 return false;
4942 memset(&cro, '\0', sizeof(struct class_ro32_t));
4943 if (left < sizeof(struct class_ro32_t)) {
4944 memcpy(&cro, r, left);
4945 outs() << " (class_ro_t entends past the end of the section)\n";
4946 } else
4947 memcpy(&cro, r, sizeof(struct class_ro32_t));
4948 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4949 swapStruct(cro);
4950 outs() << " flags " << format("0x%" PRIx32, cro.flags);
4951 if (cro.flags & RO_META)
4952 outs() << " RO_META";
4953 if (cro.flags & RO_ROOT)
4954 outs() << " RO_ROOT";
4955 if (cro.flags & RO_HAS_CXX_STRUCTORS)
4956 outs() << " RO_HAS_CXX_STRUCTORS";
4957 outs() << "\n";
4958 outs() << " instanceStart " << cro.instanceStart << "\n";
4959 outs() << " instanceSize " << cro.instanceSize << "\n";
4960 outs() << " ivarLayout " << format("0x%" PRIx32, cro.ivarLayout)
4961 << "\n";
4962 print_layout_map32(cro.ivarLayout, info);
4964 outs() << " name " << format("0x%" PRIx32, cro.name);
4965 name = get_pointer_32(cro.name, xoffset, left, xS, info);
4966 if (name != nullptr)
4967 outs() << format(" %.*s", left, name);
4968 outs() << "\n";
4970 outs() << " baseMethods "
4971 << format("0x%" PRIx32, cro.baseMethods)
4972 << " (struct method_list_t *)\n";
4973 if (cro.baseMethods != 0)
4974 print_method_list32_t(cro.baseMethods, info, "");
4976 outs() << " baseProtocols "
4977 << format("0x%" PRIx32, cro.baseProtocols) << "\n";
4978 if (cro.baseProtocols != 0)
4979 print_protocol_list32_t(cro.baseProtocols, info);
4980 outs() << " ivars " << format("0x%" PRIx32, cro.ivars)
4981 << "\n";
4982 if (cro.ivars != 0)
4983 print_ivar_list32_t(cro.ivars, info);
4984 outs() << " weakIvarLayout "
4985 << format("0x%" PRIx32, cro.weakIvarLayout) << "\n";
4986 print_layout_map32(cro.weakIvarLayout, info);
4987 outs() << " baseProperties "
4988 << format("0x%" PRIx32, cro.baseProperties) << "\n";
4989 if (cro.baseProperties != 0)
4990 print_objc_property_list32(cro.baseProperties, info);
4991 is_meta_class = (cro.flags & RO_META) != 0;
4992 return true;
4995 static void print_class64_t(uint64_t p, struct DisassembleInfo *info) {
4996 struct class64_t c;
4997 const char *r;
4998 uint32_t offset, left;
4999 SectionRef S;
5000 const char *name;
5001 uint64_t isa_n_value, n_value;
5003 r = get_pointer_64(p, offset, left, S, info);
5004 if (r == nullptr || left < sizeof(struct class64_t))
5005 return;
5006 memcpy(&c, r, sizeof(struct class64_t));
5007 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5008 swapStruct(c);
5010 outs() << " isa " << format("0x%" PRIx64, c.isa);
5011 name = get_symbol_64(offset + offsetof(struct class64_t, isa), S, info,
5012 isa_n_value, c.isa);
5013 if (name != nullptr)
5014 outs() << " " << name;
5015 outs() << "\n";
5017 outs() << " superclass " << format("0x%" PRIx64, c.superclass);
5018 name = get_symbol_64(offset + offsetof(struct class64_t, superclass), S, info,
5019 n_value, c.superclass);
5020 if (name != nullptr)
5021 outs() << " " << name;
5022 else {
5023 name = get_dyld_bind_info_symbolname(S.getAddress() +
5024 offset + offsetof(struct class64_t, superclass), info);
5025 if (name != nullptr)
5026 outs() << " " << name;
5028 outs() << "\n";
5030 outs() << " cache " << format("0x%" PRIx64, c.cache);
5031 name = get_symbol_64(offset + offsetof(struct class64_t, cache), S, info,
5032 n_value, c.cache);
5033 if (name != nullptr)
5034 outs() << " " << name;
5035 outs() << "\n";
5037 outs() << " vtable " << format("0x%" PRIx64, c.vtable);
5038 name = get_symbol_64(offset + offsetof(struct class64_t, vtable), S, info,
5039 n_value, c.vtable);
5040 if (name != nullptr)
5041 outs() << " " << name;
5042 outs() << "\n";
5044 name = get_symbol_64(offset + offsetof(struct class64_t, data), S, info,
5045 n_value, c.data);
5046 outs() << " data ";
5047 if (n_value != 0) {
5048 if (info->verbose && name != nullptr)
5049 outs() << name;
5050 else
5051 outs() << format("0x%" PRIx64, n_value);
5052 if (c.data != 0)
5053 outs() << " + " << format("0x%" PRIx64, c.data);
5054 } else
5055 outs() << format("0x%" PRIx64, c.data);
5056 outs() << " (struct class_ro_t *)";
5058 // This is a Swift class if some of the low bits of the pointer are set.
5059 if ((c.data + n_value) & 0x7)
5060 outs() << " Swift class";
5061 outs() << "\n";
5062 bool is_meta_class;
5063 if (!print_class_ro64_t((c.data + n_value) & ~0x7, info, is_meta_class))
5064 return;
5066 if (!is_meta_class &&
5067 c.isa + isa_n_value != p &&
5068 c.isa + isa_n_value != 0 &&
5069 info->depth < 100) {
5070 info->depth++;
5071 outs() << "Meta Class\n";
5072 print_class64_t(c.isa + isa_n_value, info);
5076 static void print_class32_t(uint32_t p, struct DisassembleInfo *info) {
5077 struct class32_t c;
5078 const char *r;
5079 uint32_t offset, left;
5080 SectionRef S;
5081 const char *name;
5083 r = get_pointer_32(p, offset, left, S, info);
5084 if (r == nullptr)
5085 return;
5086 memset(&c, '\0', sizeof(struct class32_t));
5087 if (left < sizeof(struct class32_t)) {
5088 memcpy(&c, r, left);
5089 outs() << " (class_t entends past the end of the section)\n";
5090 } else
5091 memcpy(&c, r, sizeof(struct class32_t));
5092 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5093 swapStruct(c);
5095 outs() << " isa " << format("0x%" PRIx32, c.isa);
5096 name =
5097 get_symbol_32(offset + offsetof(struct class32_t, isa), S, info, c.isa);
5098 if (name != nullptr)
5099 outs() << " " << name;
5100 outs() << "\n";
5102 outs() << " superclass " << format("0x%" PRIx32, c.superclass);
5103 name = get_symbol_32(offset + offsetof(struct class32_t, superclass), S, info,
5104 c.superclass);
5105 if (name != nullptr)
5106 outs() << " " << name;
5107 outs() << "\n";
5109 outs() << " cache " << format("0x%" PRIx32, c.cache);
5110 name = get_symbol_32(offset + offsetof(struct class32_t, cache), S, info,
5111 c.cache);
5112 if (name != nullptr)
5113 outs() << " " << name;
5114 outs() << "\n";
5116 outs() << " vtable " << format("0x%" PRIx32, c.vtable);
5117 name = get_symbol_32(offset + offsetof(struct class32_t, vtable), S, info,
5118 c.vtable);
5119 if (name != nullptr)
5120 outs() << " " << name;
5121 outs() << "\n";
5123 name =
5124 get_symbol_32(offset + offsetof(struct class32_t, data), S, info, c.data);
5125 outs() << " data " << format("0x%" PRIx32, c.data)
5126 << " (struct class_ro_t *)";
5128 // This is a Swift class if some of the low bits of the pointer are set.
5129 if (c.data & 0x3)
5130 outs() << " Swift class";
5131 outs() << "\n";
5132 bool is_meta_class;
5133 if (!print_class_ro32_t(c.data & ~0x3, info, is_meta_class))
5134 return;
5136 if (!is_meta_class) {
5137 outs() << "Meta Class\n";
5138 print_class32_t(c.isa, info);
5142 static void print_objc_class_t(struct objc_class_t *objc_class,
5143 struct DisassembleInfo *info) {
5144 uint32_t offset, left, xleft;
5145 const char *name, *p, *ivar_list;
5146 SectionRef S;
5147 int32_t i;
5148 struct objc_ivar_list_t objc_ivar_list;
5149 struct objc_ivar_t ivar;
5151 outs() << "\t\t isa " << format("0x%08" PRIx32, objc_class->isa);
5152 if (info->verbose && CLS_GETINFO(objc_class, CLS_META)) {
5153 name = get_pointer_32(objc_class->isa, offset, left, S, info, true);
5154 if (name != nullptr)
5155 outs() << format(" %.*s", left, name);
5156 else
5157 outs() << " (not in an __OBJC section)";
5159 outs() << "\n";
5161 outs() << "\t super_class "
5162 << format("0x%08" PRIx32, objc_class->super_class);
5163 if (info->verbose) {
5164 name = get_pointer_32(objc_class->super_class, offset, left, S, info, true);
5165 if (name != nullptr)
5166 outs() << format(" %.*s", left, name);
5167 else
5168 outs() << " (not in an __OBJC section)";
5170 outs() << "\n";
5172 outs() << "\t\t name " << format("0x%08" PRIx32, objc_class->name);
5173 if (info->verbose) {
5174 name = get_pointer_32(objc_class->name, offset, left, S, info, true);
5175 if (name != nullptr)
5176 outs() << format(" %.*s", left, name);
5177 else
5178 outs() << " (not in an __OBJC section)";
5180 outs() << "\n";
5182 outs() << "\t\t version " << format("0x%08" PRIx32, objc_class->version)
5183 << "\n";
5185 outs() << "\t\t info " << format("0x%08" PRIx32, objc_class->info);
5186 if (info->verbose) {
5187 if (CLS_GETINFO(objc_class, CLS_CLASS))
5188 outs() << " CLS_CLASS";
5189 else if (CLS_GETINFO(objc_class, CLS_META))
5190 outs() << " CLS_META";
5192 outs() << "\n";
5194 outs() << "\t instance_size "
5195 << format("0x%08" PRIx32, objc_class->instance_size) << "\n";
5197 p = get_pointer_32(objc_class->ivars, offset, left, S, info, true);
5198 outs() << "\t\t ivars " << format("0x%08" PRIx32, objc_class->ivars);
5199 if (p != nullptr) {
5200 if (left > sizeof(struct objc_ivar_list_t)) {
5201 outs() << "\n";
5202 memcpy(&objc_ivar_list, p, sizeof(struct objc_ivar_list_t));
5203 } else {
5204 outs() << " (entends past the end of the section)\n";
5205 memset(&objc_ivar_list, '\0', sizeof(struct objc_ivar_list_t));
5206 memcpy(&objc_ivar_list, p, left);
5208 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5209 swapStruct(objc_ivar_list);
5210 outs() << "\t\t ivar_count " << objc_ivar_list.ivar_count << "\n";
5211 ivar_list = p + sizeof(struct objc_ivar_list_t);
5212 for (i = 0; i < objc_ivar_list.ivar_count; i++) {
5213 if ((i + 1) * sizeof(struct objc_ivar_t) > left) {
5214 outs() << "\t\t remaining ivar's extend past the of the section\n";
5215 break;
5217 memcpy(&ivar, ivar_list + i * sizeof(struct objc_ivar_t),
5218 sizeof(struct objc_ivar_t));
5219 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5220 swapStruct(ivar);
5222 outs() << "\t\t\tivar_name " << format("0x%08" PRIx32, ivar.ivar_name);
5223 if (info->verbose) {
5224 name = get_pointer_32(ivar.ivar_name, offset, xleft, S, info, true);
5225 if (name != nullptr)
5226 outs() << format(" %.*s", xleft, name);
5227 else
5228 outs() << " (not in an __OBJC section)";
5230 outs() << "\n";
5232 outs() << "\t\t\tivar_type " << format("0x%08" PRIx32, ivar.ivar_type);
5233 if (info->verbose) {
5234 name = get_pointer_32(ivar.ivar_type, offset, xleft, S, info, true);
5235 if (name != nullptr)
5236 outs() << format(" %.*s", xleft, name);
5237 else
5238 outs() << " (not in an __OBJC section)";
5240 outs() << "\n";
5242 outs() << "\t\t ivar_offset "
5243 << format("0x%08" PRIx32, ivar.ivar_offset) << "\n";
5245 } else {
5246 outs() << " (not in an __OBJC section)\n";
5249 outs() << "\t\t methods " << format("0x%08" PRIx32, objc_class->methodLists);
5250 if (print_method_list(objc_class->methodLists, info))
5251 outs() << " (not in an __OBJC section)\n";
5253 outs() << "\t\t cache " << format("0x%08" PRIx32, objc_class->cache)
5254 << "\n";
5256 outs() << "\t\tprotocols " << format("0x%08" PRIx32, objc_class->protocols);
5257 if (print_protocol_list(objc_class->protocols, 16, info))
5258 outs() << " (not in an __OBJC section)\n";
5261 static void print_objc_objc_category_t(struct objc_category_t *objc_category,
5262 struct DisassembleInfo *info) {
5263 uint32_t offset, left;
5264 const char *name;
5265 SectionRef S;
5267 outs() << "\t category name "
5268 << format("0x%08" PRIx32, objc_category->category_name);
5269 if (info->verbose) {
5270 name = get_pointer_32(objc_category->category_name, offset, left, S, info,
5271 true);
5272 if (name != nullptr)
5273 outs() << format(" %.*s", left, name);
5274 else
5275 outs() << " (not in an __OBJC section)";
5277 outs() << "\n";
5279 outs() << "\t\t class name "
5280 << format("0x%08" PRIx32, objc_category->class_name);
5281 if (info->verbose) {
5282 name =
5283 get_pointer_32(objc_category->class_name, offset, left, S, info, true);
5284 if (name != nullptr)
5285 outs() << format(" %.*s", left, name);
5286 else
5287 outs() << " (not in an __OBJC section)";
5289 outs() << "\n";
5291 outs() << "\t instance methods "
5292 << format("0x%08" PRIx32, objc_category->instance_methods);
5293 if (print_method_list(objc_category->instance_methods, info))
5294 outs() << " (not in an __OBJC section)\n";
5296 outs() << "\t class methods "
5297 << format("0x%08" PRIx32, objc_category->class_methods);
5298 if (print_method_list(objc_category->class_methods, info))
5299 outs() << " (not in an __OBJC section)\n";
5302 static void print_category64_t(uint64_t p, struct DisassembleInfo *info) {
5303 struct category64_t c;
5304 const char *r;
5305 uint32_t offset, xoffset, left;
5306 SectionRef S, xS;
5307 const char *name, *sym_name;
5308 uint64_t n_value;
5310 r = get_pointer_64(p, offset, left, S, info);
5311 if (r == nullptr)
5312 return;
5313 memset(&c, '\0', sizeof(struct category64_t));
5314 if (left < sizeof(struct category64_t)) {
5315 memcpy(&c, r, left);
5316 outs() << " (category_t entends past the end of the section)\n";
5317 } else
5318 memcpy(&c, r, sizeof(struct category64_t));
5319 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5320 swapStruct(c);
5322 outs() << " name ";
5323 sym_name = get_symbol_64(offset + offsetof(struct category64_t, name), S,
5324 info, n_value, c.name);
5325 if (n_value != 0) {
5326 if (info->verbose && sym_name != nullptr)
5327 outs() << sym_name;
5328 else
5329 outs() << format("0x%" PRIx64, n_value);
5330 if (c.name != 0)
5331 outs() << " + " << format("0x%" PRIx64, c.name);
5332 } else
5333 outs() << format("0x%" PRIx64, c.name);
5334 name = get_pointer_64(c.name + n_value, xoffset, left, xS, info);
5335 if (name != nullptr)
5336 outs() << format(" %.*s", left, name);
5337 outs() << "\n";
5339 outs() << " cls ";
5340 sym_name = get_symbol_64(offset + offsetof(struct category64_t, cls), S, info,
5341 n_value, c.cls);
5342 if (n_value != 0) {
5343 if (info->verbose && sym_name != nullptr)
5344 outs() << sym_name;
5345 else
5346 outs() << format("0x%" PRIx64, n_value);
5347 if (c.cls != 0)
5348 outs() << " + " << format("0x%" PRIx64, c.cls);
5349 } else
5350 outs() << format("0x%" PRIx64, c.cls);
5351 outs() << "\n";
5352 if (c.cls + n_value != 0)
5353 print_class64_t(c.cls + n_value, info);
5355 outs() << " instanceMethods ";
5356 sym_name =
5357 get_symbol_64(offset + offsetof(struct category64_t, instanceMethods), S,
5358 info, n_value, c.instanceMethods);
5359 if (n_value != 0) {
5360 if (info->verbose && sym_name != nullptr)
5361 outs() << sym_name;
5362 else
5363 outs() << format("0x%" PRIx64, n_value);
5364 if (c.instanceMethods != 0)
5365 outs() << " + " << format("0x%" PRIx64, c.instanceMethods);
5366 } else
5367 outs() << format("0x%" PRIx64, c.instanceMethods);
5368 outs() << "\n";
5369 if (c.instanceMethods + n_value != 0)
5370 print_method_list64_t(c.instanceMethods + n_value, info, "");
5372 outs() << " classMethods ";
5373 sym_name = get_symbol_64(offset + offsetof(struct category64_t, classMethods),
5374 S, info, n_value, c.classMethods);
5375 if (n_value != 0) {
5376 if (info->verbose && sym_name != nullptr)
5377 outs() << sym_name;
5378 else
5379 outs() << format("0x%" PRIx64, n_value);
5380 if (c.classMethods != 0)
5381 outs() << " + " << format("0x%" PRIx64, c.classMethods);
5382 } else
5383 outs() << format("0x%" PRIx64, c.classMethods);
5384 outs() << "\n";
5385 if (c.classMethods + n_value != 0)
5386 print_method_list64_t(c.classMethods + n_value, info, "");
5388 outs() << " protocols ";
5389 sym_name = get_symbol_64(offset + offsetof(struct category64_t, protocols), S,
5390 info, n_value, c.protocols);
5391 if (n_value != 0) {
5392 if (info->verbose && sym_name != nullptr)
5393 outs() << sym_name;
5394 else
5395 outs() << format("0x%" PRIx64, n_value);
5396 if (c.protocols != 0)
5397 outs() << " + " << format("0x%" PRIx64, c.protocols);
5398 } else
5399 outs() << format("0x%" PRIx64, c.protocols);
5400 outs() << "\n";
5401 if (c.protocols + n_value != 0)
5402 print_protocol_list64_t(c.protocols + n_value, info);
5404 outs() << "instanceProperties ";
5405 sym_name =
5406 get_symbol_64(offset + offsetof(struct category64_t, instanceProperties),
5407 S, info, n_value, c.instanceProperties);
5408 if (n_value != 0) {
5409 if (info->verbose && sym_name != nullptr)
5410 outs() << sym_name;
5411 else
5412 outs() << format("0x%" PRIx64, n_value);
5413 if (c.instanceProperties != 0)
5414 outs() << " + " << format("0x%" PRIx64, c.instanceProperties);
5415 } else
5416 outs() << format("0x%" PRIx64, c.instanceProperties);
5417 outs() << "\n";
5418 if (c.instanceProperties + n_value != 0)
5419 print_objc_property_list64(c.instanceProperties + n_value, info);
5422 static void print_category32_t(uint32_t p, struct DisassembleInfo *info) {
5423 struct category32_t c;
5424 const char *r;
5425 uint32_t offset, left;
5426 SectionRef S, xS;
5427 const char *name;
5429 r = get_pointer_32(p, offset, left, S, info);
5430 if (r == nullptr)
5431 return;
5432 memset(&c, '\0', sizeof(struct category32_t));
5433 if (left < sizeof(struct category32_t)) {
5434 memcpy(&c, r, left);
5435 outs() << " (category_t entends past the end of the section)\n";
5436 } else
5437 memcpy(&c, r, sizeof(struct category32_t));
5438 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5439 swapStruct(c);
5441 outs() << " name " << format("0x%" PRIx32, c.name);
5442 name = get_symbol_32(offset + offsetof(struct category32_t, name), S, info,
5443 c.name);
5444 if (name)
5445 outs() << " " << name;
5446 outs() << "\n";
5448 outs() << " cls " << format("0x%" PRIx32, c.cls) << "\n";
5449 if (c.cls != 0)
5450 print_class32_t(c.cls, info);
5451 outs() << " instanceMethods " << format("0x%" PRIx32, c.instanceMethods)
5452 << "\n";
5453 if (c.instanceMethods != 0)
5454 print_method_list32_t(c.instanceMethods, info, "");
5455 outs() << " classMethods " << format("0x%" PRIx32, c.classMethods)
5456 << "\n";
5457 if (c.classMethods != 0)
5458 print_method_list32_t(c.classMethods, info, "");
5459 outs() << " protocols " << format("0x%" PRIx32, c.protocols) << "\n";
5460 if (c.protocols != 0)
5461 print_protocol_list32_t(c.protocols, info);
5462 outs() << "instanceProperties " << format("0x%" PRIx32, c.instanceProperties)
5463 << "\n";
5464 if (c.instanceProperties != 0)
5465 print_objc_property_list32(c.instanceProperties, info);
5468 static void print_message_refs64(SectionRef S, struct DisassembleInfo *info) {
5469 uint32_t i, left, offset, xoffset;
5470 uint64_t p, n_value;
5471 struct message_ref64 mr;
5472 const char *name, *sym_name;
5473 const char *r;
5474 SectionRef xS;
5476 if (S == SectionRef())
5477 return;
5479 StringRef SectName;
5480 S.getName(SectName);
5481 DataRefImpl Ref = S.getRawDataRefImpl();
5482 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5483 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5484 offset = 0;
5485 for (i = 0; i < S.getSize(); i += sizeof(struct message_ref64)) {
5486 p = S.getAddress() + i;
5487 r = get_pointer_64(p, offset, left, S, info);
5488 if (r == nullptr)
5489 return;
5490 memset(&mr, '\0', sizeof(struct message_ref64));
5491 if (left < sizeof(struct message_ref64)) {
5492 memcpy(&mr, r, left);
5493 outs() << " (message_ref entends past the end of the section)\n";
5494 } else
5495 memcpy(&mr, r, sizeof(struct message_ref64));
5496 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5497 swapStruct(mr);
5499 outs() << " imp ";
5500 name = get_symbol_64(offset + offsetof(struct message_ref64, imp), S, info,
5501 n_value, mr.imp);
5502 if (n_value != 0) {
5503 outs() << format("0x%" PRIx64, n_value) << " ";
5504 if (mr.imp != 0)
5505 outs() << "+ " << format("0x%" PRIx64, mr.imp) << " ";
5506 } else
5507 outs() << format("0x%" PRIx64, mr.imp) << " ";
5508 if (name != nullptr)
5509 outs() << " " << name;
5510 outs() << "\n";
5512 outs() << " sel ";
5513 sym_name = get_symbol_64(offset + offsetof(struct message_ref64, sel), S,
5514 info, n_value, mr.sel);
5515 if (n_value != 0) {
5516 if (info->verbose && sym_name != nullptr)
5517 outs() << sym_name;
5518 else
5519 outs() << format("0x%" PRIx64, n_value);
5520 if (mr.sel != 0)
5521 outs() << " + " << format("0x%" PRIx64, mr.sel);
5522 } else
5523 outs() << format("0x%" PRIx64, mr.sel);
5524 name = get_pointer_64(mr.sel + n_value, xoffset, left, xS, info);
5525 if (name != nullptr)
5526 outs() << format(" %.*s", left, name);
5527 outs() << "\n";
5529 offset += sizeof(struct message_ref64);
5533 static void print_message_refs32(SectionRef S, struct DisassembleInfo *info) {
5534 uint32_t i, left, offset, xoffset, p;
5535 struct message_ref32 mr;
5536 const char *name, *r;
5537 SectionRef xS;
5539 if (S == SectionRef())
5540 return;
5542 StringRef SectName;
5543 S.getName(SectName);
5544 DataRefImpl Ref = S.getRawDataRefImpl();
5545 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5546 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5547 offset = 0;
5548 for (i = 0; i < S.getSize(); i += sizeof(struct message_ref64)) {
5549 p = S.getAddress() + i;
5550 r = get_pointer_32(p, offset, left, S, info);
5551 if (r == nullptr)
5552 return;
5553 memset(&mr, '\0', sizeof(struct message_ref32));
5554 if (left < sizeof(struct message_ref32)) {
5555 memcpy(&mr, r, left);
5556 outs() << " (message_ref entends past the end of the section)\n";
5557 } else
5558 memcpy(&mr, r, sizeof(struct message_ref32));
5559 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5560 swapStruct(mr);
5562 outs() << " imp " << format("0x%" PRIx32, mr.imp);
5563 name = get_symbol_32(offset + offsetof(struct message_ref32, imp), S, info,
5564 mr.imp);
5565 if (name != nullptr)
5566 outs() << " " << name;
5567 outs() << "\n";
5569 outs() << " sel " << format("0x%" PRIx32, mr.sel);
5570 name = get_pointer_32(mr.sel, xoffset, left, xS, info);
5571 if (name != nullptr)
5572 outs() << " " << name;
5573 outs() << "\n";
5575 offset += sizeof(struct message_ref32);
5579 static void print_image_info64(SectionRef S, struct DisassembleInfo *info) {
5580 uint32_t left, offset, swift_version;
5581 uint64_t p;
5582 struct objc_image_info64 o;
5583 const char *r;
5585 if (S == SectionRef())
5586 return;
5588 StringRef SectName;
5589 S.getName(SectName);
5590 DataRefImpl Ref = S.getRawDataRefImpl();
5591 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5592 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5593 p = S.getAddress();
5594 r = get_pointer_64(p, offset, left, S, info);
5595 if (r == nullptr)
5596 return;
5597 memset(&o, '\0', sizeof(struct objc_image_info64));
5598 if (left < sizeof(struct objc_image_info64)) {
5599 memcpy(&o, r, left);
5600 outs() << " (objc_image_info entends past the end of the section)\n";
5601 } else
5602 memcpy(&o, r, sizeof(struct objc_image_info64));
5603 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5604 swapStruct(o);
5605 outs() << " version " << o.version << "\n";
5606 outs() << " flags " << format("0x%" PRIx32, o.flags);
5607 if (o.flags & OBJC_IMAGE_IS_REPLACEMENT)
5608 outs() << " OBJC_IMAGE_IS_REPLACEMENT";
5609 if (o.flags & OBJC_IMAGE_SUPPORTS_GC)
5610 outs() << " OBJC_IMAGE_SUPPORTS_GC";
5611 if (o.flags & OBJC_IMAGE_IS_SIMULATED)
5612 outs() << " OBJC_IMAGE_IS_SIMULATED";
5613 if (o.flags & OBJC_IMAGE_HAS_CATEGORY_CLASS_PROPERTIES)
5614 outs() << " OBJC_IMAGE_HAS_CATEGORY_CLASS_PROPERTIES";
5615 swift_version = (o.flags >> 8) & 0xff;
5616 if (swift_version != 0) {
5617 if (swift_version == 1)
5618 outs() << " Swift 1.0";
5619 else if (swift_version == 2)
5620 outs() << " Swift 1.1";
5621 else if(swift_version == 3)
5622 outs() << " Swift 2.0";
5623 else if(swift_version == 4)
5624 outs() << " Swift 3.0";
5625 else if(swift_version == 5)
5626 outs() << " Swift 4.0";
5627 else if(swift_version == 6)
5628 outs() << " Swift 4.1/Swift 4.2";
5629 else if(swift_version == 7)
5630 outs() << " Swift 5 or later";
5631 else
5632 outs() << " unknown future Swift version (" << swift_version << ")";
5634 outs() << "\n";
5637 static void print_image_info32(SectionRef S, struct DisassembleInfo *info) {
5638 uint32_t left, offset, swift_version, p;
5639 struct objc_image_info32 o;
5640 const char *r;
5642 if (S == SectionRef())
5643 return;
5645 StringRef SectName;
5646 S.getName(SectName);
5647 DataRefImpl Ref = S.getRawDataRefImpl();
5648 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5649 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5650 p = S.getAddress();
5651 r = get_pointer_32(p, offset, left, S, info);
5652 if (r == nullptr)
5653 return;
5654 memset(&o, '\0', sizeof(struct objc_image_info32));
5655 if (left < sizeof(struct objc_image_info32)) {
5656 memcpy(&o, r, left);
5657 outs() << " (objc_image_info entends past the end of the section)\n";
5658 } else
5659 memcpy(&o, r, sizeof(struct objc_image_info32));
5660 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5661 swapStruct(o);
5662 outs() << " version " << o.version << "\n";
5663 outs() << " flags " << format("0x%" PRIx32, o.flags);
5664 if (o.flags & OBJC_IMAGE_IS_REPLACEMENT)
5665 outs() << " OBJC_IMAGE_IS_REPLACEMENT";
5666 if (o.flags & OBJC_IMAGE_SUPPORTS_GC)
5667 outs() << " OBJC_IMAGE_SUPPORTS_GC";
5668 swift_version = (o.flags >> 8) & 0xff;
5669 if (swift_version != 0) {
5670 if (swift_version == 1)
5671 outs() << " Swift 1.0";
5672 else if (swift_version == 2)
5673 outs() << " Swift 1.1";
5674 else if(swift_version == 3)
5675 outs() << " Swift 2.0";
5676 else if(swift_version == 4)
5677 outs() << " Swift 3.0";
5678 else if(swift_version == 5)
5679 outs() << " Swift 4.0";
5680 else if(swift_version == 6)
5681 outs() << " Swift 4.1/Swift 4.2";
5682 else if(swift_version == 7)
5683 outs() << " Swift 5 or later";
5684 else
5685 outs() << " unknown future Swift version (" << swift_version << ")";
5687 outs() << "\n";
5690 static void print_image_info(SectionRef S, struct DisassembleInfo *info) {
5691 uint32_t left, offset, p;
5692 struct imageInfo_t o;
5693 const char *r;
5695 StringRef SectName;
5696 S.getName(SectName);
5697 DataRefImpl Ref = S.getRawDataRefImpl();
5698 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5699 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5700 p = S.getAddress();
5701 r = get_pointer_32(p, offset, left, S, info);
5702 if (r == nullptr)
5703 return;
5704 memset(&o, '\0', sizeof(struct imageInfo_t));
5705 if (left < sizeof(struct imageInfo_t)) {
5706 memcpy(&o, r, left);
5707 outs() << " (imageInfo entends past the end of the section)\n";
5708 } else
5709 memcpy(&o, r, sizeof(struct imageInfo_t));
5710 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5711 swapStruct(o);
5712 outs() << " version " << o.version << "\n";
5713 outs() << " flags " << format("0x%" PRIx32, o.flags);
5714 if (o.flags & 0x1)
5715 outs() << " F&C";
5716 if (o.flags & 0x2)
5717 outs() << " GC";
5718 if (o.flags & 0x4)
5719 outs() << " GC-only";
5720 else
5721 outs() << " RR";
5722 outs() << "\n";
5725 static void printObjc2_64bit_MetaData(MachOObjectFile *O, bool verbose) {
5726 SymbolAddressMap AddrMap;
5727 if (verbose)
5728 CreateSymbolAddressMap(O, &AddrMap);
5730 std::vector<SectionRef> Sections;
5731 for (const SectionRef &Section : O->sections()) {
5732 StringRef SectName;
5733 Section.getName(SectName);
5734 Sections.push_back(Section);
5737 struct DisassembleInfo info(O, &AddrMap, &Sections, verbose);
5739 SectionRef CL = get_section(O, "__OBJC2", "__class_list");
5740 if (CL == SectionRef())
5741 CL = get_section(O, "__DATA", "__objc_classlist");
5742 if (CL == SectionRef())
5743 CL = get_section(O, "__DATA_CONST", "__objc_classlist");
5744 if (CL == SectionRef())
5745 CL = get_section(O, "__DATA_DIRTY", "__objc_classlist");
5746 info.S = CL;
5747 walk_pointer_list_64("class", CL, O, &info, print_class64_t);
5749 SectionRef CR = get_section(O, "__OBJC2", "__class_refs");
5750 if (CR == SectionRef())
5751 CR = get_section(O, "__DATA", "__objc_classrefs");
5752 if (CR == SectionRef())
5753 CR = get_section(O, "__DATA_CONST", "__objc_classrefs");
5754 if (CR == SectionRef())
5755 CR = get_section(O, "__DATA_DIRTY", "__objc_classrefs");
5756 info.S = CR;
5757 walk_pointer_list_64("class refs", CR, O, &info, nullptr);
5759 SectionRef SR = get_section(O, "__OBJC2", "__super_refs");
5760 if (SR == SectionRef())
5761 SR = get_section(O, "__DATA", "__objc_superrefs");
5762 if (SR == SectionRef())
5763 SR = get_section(O, "__DATA_CONST", "__objc_superrefs");
5764 if (SR == SectionRef())
5765 SR = get_section(O, "__DATA_DIRTY", "__objc_superrefs");
5766 info.S = SR;
5767 walk_pointer_list_64("super refs", SR, O, &info, nullptr);
5769 SectionRef CA = get_section(O, "__OBJC2", "__category_list");
5770 if (CA == SectionRef())
5771 CA = get_section(O, "__DATA", "__objc_catlist");
5772 if (CA == SectionRef())
5773 CA = get_section(O, "__DATA_CONST", "__objc_catlist");
5774 if (CA == SectionRef())
5775 CA = get_section(O, "__DATA_DIRTY", "__objc_catlist");
5776 info.S = CA;
5777 walk_pointer_list_64("category", CA, O, &info, print_category64_t);
5779 SectionRef PL = get_section(O, "__OBJC2", "__protocol_list");
5780 if (PL == SectionRef())
5781 PL = get_section(O, "__DATA", "__objc_protolist");
5782 if (PL == SectionRef())
5783 PL = get_section(O, "__DATA_CONST", "__objc_protolist");
5784 if (PL == SectionRef())
5785 PL = get_section(O, "__DATA_DIRTY", "__objc_protolist");
5786 info.S = PL;
5787 walk_pointer_list_64("protocol", PL, O, &info, nullptr);
5789 SectionRef MR = get_section(O, "__OBJC2", "__message_refs");
5790 if (MR == SectionRef())
5791 MR = get_section(O, "__DATA", "__objc_msgrefs");
5792 if (MR == SectionRef())
5793 MR = get_section(O, "__DATA_CONST", "__objc_msgrefs");
5794 if (MR == SectionRef())
5795 MR = get_section(O, "__DATA_DIRTY", "__objc_msgrefs");
5796 info.S = MR;
5797 print_message_refs64(MR, &info);
5799 SectionRef II = get_section(O, "__OBJC2", "__image_info");
5800 if (II == SectionRef())
5801 II = get_section(O, "__DATA", "__objc_imageinfo");
5802 if (II == SectionRef())
5803 II = get_section(O, "__DATA_CONST", "__objc_imageinfo");
5804 if (II == SectionRef())
5805 II = get_section(O, "__DATA_DIRTY", "__objc_imageinfo");
5806 info.S = II;
5807 print_image_info64(II, &info);
5810 static void printObjc2_32bit_MetaData(MachOObjectFile *O, bool verbose) {
5811 SymbolAddressMap AddrMap;
5812 if (verbose)
5813 CreateSymbolAddressMap(O, &AddrMap);
5815 std::vector<SectionRef> Sections;
5816 for (const SectionRef &Section : O->sections()) {
5817 StringRef SectName;
5818 Section.getName(SectName);
5819 Sections.push_back(Section);
5822 struct DisassembleInfo info(O, &AddrMap, &Sections, verbose);
5824 SectionRef CL = get_section(O, "__OBJC2", "__class_list");
5825 if (CL == SectionRef())
5826 CL = get_section(O, "__DATA", "__objc_classlist");
5827 if (CL == SectionRef())
5828 CL = get_section(O, "__DATA_CONST", "__objc_classlist");
5829 if (CL == SectionRef())
5830 CL = get_section(O, "__DATA_DIRTY", "__objc_classlist");
5831 info.S = CL;
5832 walk_pointer_list_32("class", CL, O, &info, print_class32_t);
5834 SectionRef CR = get_section(O, "__OBJC2", "__class_refs");
5835 if (CR == SectionRef())
5836 CR = get_section(O, "__DATA", "__objc_classrefs");
5837 if (CR == SectionRef())
5838 CR = get_section(O, "__DATA_CONST", "__objc_classrefs");
5839 if (CR == SectionRef())
5840 CR = get_section(O, "__DATA_DIRTY", "__objc_classrefs");
5841 info.S = CR;
5842 walk_pointer_list_32("class refs", CR, O, &info, nullptr);
5844 SectionRef SR = get_section(O, "__OBJC2", "__super_refs");
5845 if (SR == SectionRef())
5846 SR = get_section(O, "__DATA", "__objc_superrefs");
5847 if (SR == SectionRef())
5848 SR = get_section(O, "__DATA_CONST", "__objc_superrefs");
5849 if (SR == SectionRef())
5850 SR = get_section(O, "__DATA_DIRTY", "__objc_superrefs");
5851 info.S = SR;
5852 walk_pointer_list_32("super refs", SR, O, &info, nullptr);
5854 SectionRef CA = get_section(O, "__OBJC2", "__category_list");
5855 if (CA == SectionRef())
5856 CA = get_section(O, "__DATA", "__objc_catlist");
5857 if (CA == SectionRef())
5858 CA = get_section(O, "__DATA_CONST", "__objc_catlist");
5859 if (CA == SectionRef())
5860 CA = get_section(O, "__DATA_DIRTY", "__objc_catlist");
5861 info.S = CA;
5862 walk_pointer_list_32("category", CA, O, &info, print_category32_t);
5864 SectionRef PL = get_section(O, "__OBJC2", "__protocol_list");
5865 if (PL == SectionRef())
5866 PL = get_section(O, "__DATA", "__objc_protolist");
5867 if (PL == SectionRef())
5868 PL = get_section(O, "__DATA_CONST", "__objc_protolist");
5869 if (PL == SectionRef())
5870 PL = get_section(O, "__DATA_DIRTY", "__objc_protolist");
5871 info.S = PL;
5872 walk_pointer_list_32("protocol", PL, O, &info, nullptr);
5874 SectionRef MR = get_section(O, "__OBJC2", "__message_refs");
5875 if (MR == SectionRef())
5876 MR = get_section(O, "__DATA", "__objc_msgrefs");
5877 if (MR == SectionRef())
5878 MR = get_section(O, "__DATA_CONST", "__objc_msgrefs");
5879 if (MR == SectionRef())
5880 MR = get_section(O, "__DATA_DIRTY", "__objc_msgrefs");
5881 info.S = MR;
5882 print_message_refs32(MR, &info);
5884 SectionRef II = get_section(O, "__OBJC2", "__image_info");
5885 if (II == SectionRef())
5886 II = get_section(O, "__DATA", "__objc_imageinfo");
5887 if (II == SectionRef())
5888 II = get_section(O, "__DATA_CONST", "__objc_imageinfo");
5889 if (II == SectionRef())
5890 II = get_section(O, "__DATA_DIRTY", "__objc_imageinfo");
5891 info.S = II;
5892 print_image_info32(II, &info);
5895 static bool printObjc1_32bit_MetaData(MachOObjectFile *O, bool verbose) {
5896 uint32_t i, j, p, offset, xoffset, left, defs_left, def;
5897 const char *r, *name, *defs;
5898 struct objc_module_t module;
5899 SectionRef S, xS;
5900 struct objc_symtab_t symtab;
5901 struct objc_class_t objc_class;
5902 struct objc_category_t objc_category;
5904 outs() << "Objective-C segment\n";
5905 S = get_section(O, "__OBJC", "__module_info");
5906 if (S == SectionRef())
5907 return false;
5909 SymbolAddressMap AddrMap;
5910 if (verbose)
5911 CreateSymbolAddressMap(O, &AddrMap);
5913 std::vector<SectionRef> Sections;
5914 for (const SectionRef &Section : O->sections()) {
5915 StringRef SectName;
5916 Section.getName(SectName);
5917 Sections.push_back(Section);
5920 struct DisassembleInfo info(O, &AddrMap, &Sections, verbose);
5922 for (i = 0; i < S.getSize(); i += sizeof(struct objc_module_t)) {
5923 p = S.getAddress() + i;
5924 r = get_pointer_32(p, offset, left, S, &info, true);
5925 if (r == nullptr)
5926 return true;
5927 memset(&module, '\0', sizeof(struct objc_module_t));
5928 if (left < sizeof(struct objc_module_t)) {
5929 memcpy(&module, r, left);
5930 outs() << " (module extends past end of __module_info section)\n";
5931 } else
5932 memcpy(&module, r, sizeof(struct objc_module_t));
5933 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5934 swapStruct(module);
5936 outs() << "Module " << format("0x%" PRIx32, p) << "\n";
5937 outs() << " version " << module.version << "\n";
5938 outs() << " size " << module.size << "\n";
5939 outs() << " name ";
5940 name = get_pointer_32(module.name, xoffset, left, xS, &info, true);
5941 if (name != nullptr)
5942 outs() << format("%.*s", left, name);
5943 else
5944 outs() << format("0x%08" PRIx32, module.name)
5945 << "(not in an __OBJC section)";
5946 outs() << "\n";
5948 r = get_pointer_32(module.symtab, xoffset, left, xS, &info, true);
5949 if (module.symtab == 0 || r == nullptr) {
5950 outs() << " symtab " << format("0x%08" PRIx32, module.symtab)
5951 << " (not in an __OBJC section)\n";
5952 continue;
5954 outs() << " symtab " << format("0x%08" PRIx32, module.symtab) << "\n";
5955 memset(&symtab, '\0', sizeof(struct objc_symtab_t));
5956 defs_left = 0;
5957 defs = nullptr;
5958 if (left < sizeof(struct objc_symtab_t)) {
5959 memcpy(&symtab, r, left);
5960 outs() << "\tsymtab extends past end of an __OBJC section)\n";
5961 } else {
5962 memcpy(&symtab, r, sizeof(struct objc_symtab_t));
5963 if (left > sizeof(struct objc_symtab_t)) {
5964 defs_left = left - sizeof(struct objc_symtab_t);
5965 defs = r + sizeof(struct objc_symtab_t);
5968 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5969 swapStruct(symtab);
5971 outs() << "\tsel_ref_cnt " << symtab.sel_ref_cnt << "\n";
5972 r = get_pointer_32(symtab.refs, xoffset, left, xS, &info, true);
5973 outs() << "\trefs " << format("0x%08" PRIx32, symtab.refs);
5974 if (r == nullptr)
5975 outs() << " (not in an __OBJC section)";
5976 outs() << "\n";
5977 outs() << "\tcls_def_cnt " << symtab.cls_def_cnt << "\n";
5978 outs() << "\tcat_def_cnt " << symtab.cat_def_cnt << "\n";
5979 if (symtab.cls_def_cnt > 0)
5980 outs() << "\tClass Definitions\n";
5981 for (j = 0; j < symtab.cls_def_cnt; j++) {
5982 if ((j + 1) * sizeof(uint32_t) > defs_left) {
5983 outs() << "\t(remaining class defs entries entends past the end of the "
5984 << "section)\n";
5985 break;
5987 memcpy(&def, defs + j * sizeof(uint32_t), sizeof(uint32_t));
5988 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5989 sys::swapByteOrder(def);
5991 r = get_pointer_32(def, xoffset, left, xS, &info, true);
5992 outs() << "\tdefs[" << j << "] " << format("0x%08" PRIx32, def);
5993 if (r != nullptr) {
5994 if (left > sizeof(struct objc_class_t)) {
5995 outs() << "\n";
5996 memcpy(&objc_class, r, sizeof(struct objc_class_t));
5997 } else {
5998 outs() << " (entends past the end of the section)\n";
5999 memset(&objc_class, '\0', sizeof(struct objc_class_t));
6000 memcpy(&objc_class, r, left);
6002 if (O->isLittleEndian() != sys::IsLittleEndianHost)
6003 swapStruct(objc_class);
6004 print_objc_class_t(&objc_class, &info);
6005 } else {
6006 outs() << "(not in an __OBJC section)\n";
6009 if (CLS_GETINFO(&objc_class, CLS_CLASS)) {
6010 outs() << "\tMeta Class";
6011 r = get_pointer_32(objc_class.isa, xoffset, left, xS, &info, true);
6012 if (r != nullptr) {
6013 if (left > sizeof(struct objc_class_t)) {
6014 outs() << "\n";
6015 memcpy(&objc_class, r, sizeof(struct objc_class_t));
6016 } else {
6017 outs() << " (entends past the end of the section)\n";
6018 memset(&objc_class, '\0', sizeof(struct objc_class_t));
6019 memcpy(&objc_class, r, left);
6021 if (O->isLittleEndian() != sys::IsLittleEndianHost)
6022 swapStruct(objc_class);
6023 print_objc_class_t(&objc_class, &info);
6024 } else {
6025 outs() << "(not in an __OBJC section)\n";
6029 if (symtab.cat_def_cnt > 0)
6030 outs() << "\tCategory Definitions\n";
6031 for (j = 0; j < symtab.cat_def_cnt; j++) {
6032 if ((j + symtab.cls_def_cnt + 1) * sizeof(uint32_t) > defs_left) {
6033 outs() << "\t(remaining category defs entries entends past the end of "
6034 << "the section)\n";
6035 break;
6037 memcpy(&def, defs + (j + symtab.cls_def_cnt) * sizeof(uint32_t),
6038 sizeof(uint32_t));
6039 if (O->isLittleEndian() != sys::IsLittleEndianHost)
6040 sys::swapByteOrder(def);
6042 r = get_pointer_32(def, xoffset, left, xS, &info, true);
6043 outs() << "\tdefs[" << j + symtab.cls_def_cnt << "] "
6044 << format("0x%08" PRIx32, def);
6045 if (r != nullptr) {
6046 if (left > sizeof(struct objc_category_t)) {
6047 outs() << "\n";
6048 memcpy(&objc_category, r, sizeof(struct objc_category_t));
6049 } else {
6050 outs() << " (entends past the end of the section)\n";
6051 memset(&objc_category, '\0', sizeof(struct objc_category_t));
6052 memcpy(&objc_category, r, left);
6054 if (O->isLittleEndian() != sys::IsLittleEndianHost)
6055 swapStruct(objc_category);
6056 print_objc_objc_category_t(&objc_category, &info);
6057 } else {
6058 outs() << "(not in an __OBJC section)\n";
6062 const SectionRef II = get_section(O, "__OBJC", "__image_info");
6063 if (II != SectionRef())
6064 print_image_info(II, &info);
6066 return true;
6069 static void DumpProtocolSection(MachOObjectFile *O, const char *sect,
6070 uint32_t size, uint32_t addr) {
6071 SymbolAddressMap AddrMap;
6072 CreateSymbolAddressMap(O, &AddrMap);
6074 std::vector<SectionRef> Sections;
6075 for (const SectionRef &Section : O->sections()) {
6076 StringRef SectName;
6077 Section.getName(SectName);
6078 Sections.push_back(Section);
6081 struct DisassembleInfo info(O, &AddrMap, &Sections, true);
6083 const char *p;
6084 struct objc_protocol_t protocol;
6085 uint32_t left, paddr;
6086 for (p = sect; p < sect + size; p += sizeof(struct objc_protocol_t)) {
6087 memset(&protocol, '\0', sizeof(struct objc_protocol_t));
6088 left = size - (p - sect);
6089 if (left < sizeof(struct objc_protocol_t)) {
6090 outs() << "Protocol extends past end of __protocol section\n";
6091 memcpy(&protocol, p, left);
6092 } else
6093 memcpy(&protocol, p, sizeof(struct objc_protocol_t));
6094 if (O->isLittleEndian() != sys::IsLittleEndianHost)
6095 swapStruct(protocol);
6096 paddr = addr + (p - sect);
6097 outs() << "Protocol " << format("0x%" PRIx32, paddr);
6098 if (print_protocol(paddr, 0, &info))
6099 outs() << "(not in an __OBJC section)\n";
6103 #ifdef HAVE_LIBXAR
6104 inline void swapStruct(struct xar_header &xar) {
6105 sys::swapByteOrder(xar.magic);
6106 sys::swapByteOrder(xar.size);
6107 sys::swapByteOrder(xar.version);
6108 sys::swapByteOrder(xar.toc_length_compressed);
6109 sys::swapByteOrder(xar.toc_length_uncompressed);
6110 sys::swapByteOrder(xar.cksum_alg);
6113 static void PrintModeVerbose(uint32_t mode) {
6114 switch(mode & S_IFMT){
6115 case S_IFDIR:
6116 outs() << "d";
6117 break;
6118 case S_IFCHR:
6119 outs() << "c";
6120 break;
6121 case S_IFBLK:
6122 outs() << "b";
6123 break;
6124 case S_IFREG:
6125 outs() << "-";
6126 break;
6127 case S_IFLNK:
6128 outs() << "l";
6129 break;
6130 case S_IFSOCK:
6131 outs() << "s";
6132 break;
6133 default:
6134 outs() << "?";
6135 break;
6138 /* owner permissions */
6139 if(mode & S_IREAD)
6140 outs() << "r";
6141 else
6142 outs() << "-";
6143 if(mode & S_IWRITE)
6144 outs() << "w";
6145 else
6146 outs() << "-";
6147 if(mode & S_ISUID)
6148 outs() << "s";
6149 else if(mode & S_IEXEC)
6150 outs() << "x";
6151 else
6152 outs() << "-";
6154 /* group permissions */
6155 if(mode & (S_IREAD >> 3))
6156 outs() << "r";
6157 else
6158 outs() << "-";
6159 if(mode & (S_IWRITE >> 3))
6160 outs() << "w";
6161 else
6162 outs() << "-";
6163 if(mode & S_ISGID)
6164 outs() << "s";
6165 else if(mode & (S_IEXEC >> 3))
6166 outs() << "x";
6167 else
6168 outs() << "-";
6170 /* other permissions */
6171 if(mode & (S_IREAD >> 6))
6172 outs() << "r";
6173 else
6174 outs() << "-";
6175 if(mode & (S_IWRITE >> 6))
6176 outs() << "w";
6177 else
6178 outs() << "-";
6179 if(mode & S_ISVTX)
6180 outs() << "t";
6181 else if(mode & (S_IEXEC >> 6))
6182 outs() << "x";
6183 else
6184 outs() << "-";
6187 static void PrintXarFilesSummary(const char *XarFilename, xar_t xar) {
6188 xar_file_t xf;
6189 const char *key, *type, *mode, *user, *group, *size, *mtime, *name, *m;
6190 char *endp;
6191 uint32_t mode_value;
6193 ScopedXarIter xi;
6194 if (!xi) {
6195 WithColor::error(errs(), "llvm-objdump")
6196 << "can't obtain an xar iterator for xar archive " << XarFilename
6197 << "\n";
6198 return;
6201 // Go through the xar's files.
6202 for (xf = xar_file_first(xar, xi); xf; xf = xar_file_next(xi)) {
6203 ScopedXarIter xp;
6204 if(!xp){
6205 WithColor::error(errs(), "llvm-objdump")
6206 << "can't obtain an xar iterator for xar archive " << XarFilename
6207 << "\n";
6208 return;
6210 type = nullptr;
6211 mode = nullptr;
6212 user = nullptr;
6213 group = nullptr;
6214 size = nullptr;
6215 mtime = nullptr;
6216 name = nullptr;
6217 for(key = xar_prop_first(xf, xp); key; key = xar_prop_next(xp)){
6218 const char *val = nullptr;
6219 xar_prop_get(xf, key, &val);
6220 #if 0 // Useful for debugging.
6221 outs() << "key: " << key << " value: " << val << "\n";
6222 #endif
6223 if(strcmp(key, "type") == 0)
6224 type = val;
6225 if(strcmp(key, "mode") == 0)
6226 mode = val;
6227 if(strcmp(key, "user") == 0)
6228 user = val;
6229 if(strcmp(key, "group") == 0)
6230 group = val;
6231 if(strcmp(key, "data/size") == 0)
6232 size = val;
6233 if(strcmp(key, "mtime") == 0)
6234 mtime = val;
6235 if(strcmp(key, "name") == 0)
6236 name = val;
6238 if(mode != nullptr){
6239 mode_value = strtoul(mode, &endp, 8);
6240 if(*endp != '\0')
6241 outs() << "(mode: \"" << mode << "\" contains non-octal chars) ";
6242 if(strcmp(type, "file") == 0)
6243 mode_value |= S_IFREG;
6244 PrintModeVerbose(mode_value);
6245 outs() << " ";
6247 if(user != nullptr)
6248 outs() << format("%10s/", user);
6249 if(group != nullptr)
6250 outs() << format("%-10s ", group);
6251 if(size != nullptr)
6252 outs() << format("%7s ", size);
6253 if(mtime != nullptr){
6254 for(m = mtime; *m != 'T' && *m != '\0'; m++)
6255 outs() << *m;
6256 if(*m == 'T')
6257 m++;
6258 outs() << " ";
6259 for( ; *m != 'Z' && *m != '\0'; m++)
6260 outs() << *m;
6261 outs() << " ";
6263 if(name != nullptr)
6264 outs() << name;
6265 outs() << "\n";
6269 static void DumpBitcodeSection(MachOObjectFile *O, const char *sect,
6270 uint32_t size, bool verbose,
6271 bool PrintXarHeader, bool PrintXarFileHeaders,
6272 std::string XarMemberName) {
6273 if(size < sizeof(struct xar_header)) {
6274 outs() << "size of (__LLVM,__bundle) section too small (smaller than size "
6275 "of struct xar_header)\n";
6276 return;
6278 struct xar_header XarHeader;
6279 memcpy(&XarHeader, sect, sizeof(struct xar_header));
6280 if (sys::IsLittleEndianHost)
6281 swapStruct(XarHeader);
6282 if (PrintXarHeader) {
6283 if (!XarMemberName.empty())
6284 outs() << "In xar member " << XarMemberName << ": ";
6285 else
6286 outs() << "For (__LLVM,__bundle) section: ";
6287 outs() << "xar header\n";
6288 if (XarHeader.magic == XAR_HEADER_MAGIC)
6289 outs() << " magic XAR_HEADER_MAGIC\n";
6290 else
6291 outs() << " magic "
6292 << format_hex(XarHeader.magic, 10, true)
6293 << " (not XAR_HEADER_MAGIC)\n";
6294 outs() << " size " << XarHeader.size << "\n";
6295 outs() << " version " << XarHeader.version << "\n";
6296 outs() << " toc_length_compressed " << XarHeader.toc_length_compressed
6297 << "\n";
6298 outs() << "toc_length_uncompressed " << XarHeader.toc_length_uncompressed
6299 << "\n";
6300 outs() << " cksum_alg ";
6301 switch (XarHeader.cksum_alg) {
6302 case XAR_CKSUM_NONE:
6303 outs() << "XAR_CKSUM_NONE\n";
6304 break;
6305 case XAR_CKSUM_SHA1:
6306 outs() << "XAR_CKSUM_SHA1\n";
6307 break;
6308 case XAR_CKSUM_MD5:
6309 outs() << "XAR_CKSUM_MD5\n";
6310 break;
6311 #ifdef XAR_CKSUM_SHA256
6312 case XAR_CKSUM_SHA256:
6313 outs() << "XAR_CKSUM_SHA256\n";
6314 break;
6315 #endif
6316 #ifdef XAR_CKSUM_SHA512
6317 case XAR_CKSUM_SHA512:
6318 outs() << "XAR_CKSUM_SHA512\n";
6319 break;
6320 #endif
6321 default:
6322 outs() << XarHeader.cksum_alg << "\n";
6326 SmallString<128> XarFilename;
6327 int FD;
6328 std::error_code XarEC =
6329 sys::fs::createTemporaryFile("llvm-objdump", "xar", FD, XarFilename);
6330 if (XarEC) {
6331 WithColor::error(errs(), "llvm-objdump") << XarEC.message() << "\n";
6332 return;
6334 ToolOutputFile XarFile(XarFilename, FD);
6335 raw_fd_ostream &XarOut = XarFile.os();
6336 StringRef XarContents(sect, size);
6337 XarOut << XarContents;
6338 XarOut.close();
6339 if (XarOut.has_error())
6340 return;
6342 ScopedXarFile xar(XarFilename.c_str(), READ);
6343 if (!xar) {
6344 WithColor::error(errs(), "llvm-objdump")
6345 << "can't create temporary xar archive " << XarFilename << "\n";
6346 return;
6349 SmallString<128> TocFilename;
6350 std::error_code TocEC =
6351 sys::fs::createTemporaryFile("llvm-objdump", "toc", TocFilename);
6352 if (TocEC) {
6353 WithColor::error(errs(), "llvm-objdump") << TocEC.message() << "\n";
6354 return;
6356 xar_serialize(xar, TocFilename.c_str());
6358 if (PrintXarFileHeaders) {
6359 if (!XarMemberName.empty())
6360 outs() << "In xar member " << XarMemberName << ": ";
6361 else
6362 outs() << "For (__LLVM,__bundle) section: ";
6363 outs() << "xar archive files:\n";
6364 PrintXarFilesSummary(XarFilename.c_str(), xar);
6367 ErrorOr<std::unique_ptr<MemoryBuffer>> FileOrErr =
6368 MemoryBuffer::getFileOrSTDIN(TocFilename.c_str());
6369 if (std::error_code EC = FileOrErr.getError()) {
6370 WithColor::error(errs(), "llvm-objdump") << EC.message() << "\n";
6371 return;
6373 std::unique_ptr<MemoryBuffer> &Buffer = FileOrErr.get();
6375 if (!XarMemberName.empty())
6376 outs() << "In xar member " << XarMemberName << ": ";
6377 else
6378 outs() << "For (__LLVM,__bundle) section: ";
6379 outs() << "xar table of contents:\n";
6380 outs() << Buffer->getBuffer() << "\n";
6382 // TODO: Go through the xar's files.
6383 ScopedXarIter xi;
6384 if(!xi){
6385 WithColor::error(errs(), "llvm-objdump")
6386 << "can't obtain an xar iterator for xar archive "
6387 << XarFilename.c_str() << "\n";
6388 return;
6390 for(xar_file_t xf = xar_file_first(xar, xi); xf; xf = xar_file_next(xi)){
6391 const char *key;
6392 const char *member_name, *member_type, *member_size_string;
6393 size_t member_size;
6395 ScopedXarIter xp;
6396 if(!xp){
6397 WithColor::error(errs(), "llvm-objdump")
6398 << "can't obtain an xar iterator for xar archive "
6399 << XarFilename.c_str() << "\n";
6400 return;
6402 member_name = NULL;
6403 member_type = NULL;
6404 member_size_string = NULL;
6405 for(key = xar_prop_first(xf, xp); key; key = xar_prop_next(xp)){
6406 const char *val = nullptr;
6407 xar_prop_get(xf, key, &val);
6408 #if 0 // Useful for debugging.
6409 outs() << "key: " << key << " value: " << val << "\n";
6410 #endif
6411 if (strcmp(key, "name") == 0)
6412 member_name = val;
6413 if (strcmp(key, "type") == 0)
6414 member_type = val;
6415 if (strcmp(key, "data/size") == 0)
6416 member_size_string = val;
6419 * If we find a file with a name, date/size and type properties
6420 * and with the type being "file" see if that is a xar file.
6422 if (member_name != NULL && member_type != NULL &&
6423 strcmp(member_type, "file") == 0 &&
6424 member_size_string != NULL){
6425 // Extract the file into a buffer.
6426 char *endptr;
6427 member_size = strtoul(member_size_string, &endptr, 10);
6428 if (*endptr == '\0' && member_size != 0) {
6429 char *buffer;
6430 if (xar_extract_tobuffersz(xar, xf, &buffer, &member_size) == 0) {
6431 #if 0 // Useful for debugging.
6432 outs() << "xar member: " << member_name << " extracted\n";
6433 #endif
6434 // Set the XarMemberName we want to see printed in the header.
6435 std::string OldXarMemberName;
6436 // If XarMemberName is already set this is nested. So
6437 // save the old name and create the nested name.
6438 if (!XarMemberName.empty()) {
6439 OldXarMemberName = XarMemberName;
6440 XarMemberName =
6441 (Twine("[") + XarMemberName + "]" + member_name).str();
6442 } else {
6443 OldXarMemberName = "";
6444 XarMemberName = member_name;
6446 // See if this is could be a xar file (nested).
6447 if (member_size >= sizeof(struct xar_header)) {
6448 #if 0 // Useful for debugging.
6449 outs() << "could be a xar file: " << member_name << "\n";
6450 #endif
6451 memcpy((char *)&XarHeader, buffer, sizeof(struct xar_header));
6452 if (sys::IsLittleEndianHost)
6453 swapStruct(XarHeader);
6454 if (XarHeader.magic == XAR_HEADER_MAGIC)
6455 DumpBitcodeSection(O, buffer, member_size, verbose,
6456 PrintXarHeader, PrintXarFileHeaders,
6457 XarMemberName);
6459 XarMemberName = OldXarMemberName;
6460 delete buffer;
6466 #endif // defined(HAVE_LIBXAR)
6468 static void printObjcMetaData(MachOObjectFile *O, bool verbose) {
6469 if (O->is64Bit())
6470 printObjc2_64bit_MetaData(O, verbose);
6471 else {
6472 MachO::mach_header H;
6473 H = O->getHeader();
6474 if (H.cputype == MachO::CPU_TYPE_ARM)
6475 printObjc2_32bit_MetaData(O, verbose);
6476 else {
6477 // This is the 32-bit non-arm cputype case. Which is normally
6478 // the first Objective-C ABI. But it may be the case of a
6479 // binary for the iOS simulator which is the second Objective-C
6480 // ABI. In that case printObjc1_32bit_MetaData() will determine that
6481 // and return false.
6482 if (!printObjc1_32bit_MetaData(O, verbose))
6483 printObjc2_32bit_MetaData(O, verbose);
6488 // GuessLiteralPointer returns a string which for the item in the Mach-O file
6489 // for the address passed in as ReferenceValue for printing as a comment with
6490 // the instruction and also returns the corresponding type of that item
6491 // indirectly through ReferenceType.
6493 // If ReferenceValue is an address of literal cstring then a pointer to the
6494 // cstring is returned and ReferenceType is set to
6495 // LLVMDisassembler_ReferenceType_Out_LitPool_CstrAddr .
6497 // If ReferenceValue is an address of an Objective-C CFString, Selector ref or
6498 // Class ref that name is returned and the ReferenceType is set accordingly.
6500 // Lastly, literals which are Symbol address in a literal pool are looked for
6501 // and if found the symbol name is returned and ReferenceType is set to
6502 // LLVMDisassembler_ReferenceType_Out_LitPool_SymAddr .
6504 // If there is no item in the Mach-O file for the address passed in as
6505 // ReferenceValue nullptr is returned and ReferenceType is unchanged.
6506 static const char *GuessLiteralPointer(uint64_t ReferenceValue,
6507 uint64_t ReferencePC,
6508 uint64_t *ReferenceType,
6509 struct DisassembleInfo *info) {
6510 // First see if there is an external relocation entry at the ReferencePC.
6511 if (info->O->getHeader().filetype == MachO::MH_OBJECT) {
6512 uint64_t sect_addr = info->S.getAddress();
6513 uint64_t sect_offset = ReferencePC - sect_addr;
6514 bool reloc_found = false;
6515 DataRefImpl Rel;
6516 MachO::any_relocation_info RE;
6517 bool isExtern = false;
6518 SymbolRef Symbol;
6519 for (const RelocationRef &Reloc : info->S.relocations()) {
6520 uint64_t RelocOffset = Reloc.getOffset();
6521 if (RelocOffset == sect_offset) {
6522 Rel = Reloc.getRawDataRefImpl();
6523 RE = info->O->getRelocation(Rel);
6524 if (info->O->isRelocationScattered(RE))
6525 continue;
6526 isExtern = info->O->getPlainRelocationExternal(RE);
6527 if (isExtern) {
6528 symbol_iterator RelocSym = Reloc.getSymbol();
6529 Symbol = *RelocSym;
6531 reloc_found = true;
6532 break;
6535 // If there is an external relocation entry for a symbol in a section
6536 // then used that symbol's value for the value of the reference.
6537 if (reloc_found && isExtern) {
6538 if (info->O->getAnyRelocationPCRel(RE)) {
6539 unsigned Type = info->O->getAnyRelocationType(RE);
6540 if (Type == MachO::X86_64_RELOC_SIGNED) {
6541 ReferenceValue = Symbol.getValue();
6547 // Look for literals such as Objective-C CFStrings refs, Selector refs,
6548 // Message refs and Class refs.
6549 bool classref, selref, msgref, cfstring;
6550 uint64_t pointer_value = GuessPointerPointer(ReferenceValue, info, classref,
6551 selref, msgref, cfstring);
6552 if (classref && pointer_value == 0) {
6553 // Note the ReferenceValue is a pointer into the __objc_classrefs section.
6554 // And the pointer_value in that section is typically zero as it will be
6555 // set by dyld as part of the "bind information".
6556 const char *name = get_dyld_bind_info_symbolname(ReferenceValue, info);
6557 if (name != nullptr) {
6558 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Class_Ref;
6559 const char *class_name = strrchr(name, '$');
6560 if (class_name != nullptr && class_name[1] == '_' &&
6561 class_name[2] != '\0') {
6562 info->class_name = class_name + 2;
6563 return name;
6568 if (classref) {
6569 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Class_Ref;
6570 const char *name =
6571 get_objc2_64bit_class_name(pointer_value, ReferenceValue, info);
6572 if (name != nullptr)
6573 info->class_name = name;
6574 else
6575 name = "bad class ref";
6576 return name;
6579 if (cfstring) {
6580 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_CFString_Ref;
6581 const char *name = get_objc2_64bit_cfstring_name(ReferenceValue, info);
6582 return name;
6585 if (selref && pointer_value == 0)
6586 pointer_value = get_objc2_64bit_selref(ReferenceValue, info);
6588 if (pointer_value != 0)
6589 ReferenceValue = pointer_value;
6591 const char *name = GuessCstringPointer(ReferenceValue, info);
6592 if (name) {
6593 if (pointer_value != 0 && selref) {
6594 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Selector_Ref;
6595 info->selector_name = name;
6596 } else if (pointer_value != 0 && msgref) {
6597 info->class_name = nullptr;
6598 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message_Ref;
6599 info->selector_name = name;
6600 } else
6601 *ReferenceType = LLVMDisassembler_ReferenceType_Out_LitPool_CstrAddr;
6602 return name;
6605 // Lastly look for an indirect symbol with this ReferenceValue which is in
6606 // a literal pool. If found return that symbol name.
6607 name = GuessIndirectSymbol(ReferenceValue, info);
6608 if (name) {
6609 *ReferenceType = LLVMDisassembler_ReferenceType_Out_LitPool_SymAddr;
6610 return name;
6613 return nullptr;
6616 // SymbolizerSymbolLookUp is the symbol lookup function passed when creating
6617 // the Symbolizer. It looks up the ReferenceValue using the info passed via the
6618 // pointer to the struct DisassembleInfo that was passed when MCSymbolizer
6619 // is created and returns the symbol name that matches the ReferenceValue or
6620 // nullptr if none. The ReferenceType is passed in for the IN type of
6621 // reference the instruction is making from the values in defined in the header
6622 // "llvm-c/Disassembler.h". On return the ReferenceType can set to a specific
6623 // Out type and the ReferenceName will also be set which is added as a comment
6624 // to the disassembled instruction.
6626 // If the symbol name is a C++ mangled name then the demangled name is
6627 // returned through ReferenceName and ReferenceType is set to
6628 // LLVMDisassembler_ReferenceType_DeMangled_Name .
6630 // When this is called to get a symbol name for a branch target then the
6631 // ReferenceType will be LLVMDisassembler_ReferenceType_In_Branch and then
6632 // SymbolValue will be looked for in the indirect symbol table to determine if
6633 // it is an address for a symbol stub. If so then the symbol name for that
6634 // stub is returned indirectly through ReferenceName and then ReferenceType is
6635 // set to LLVMDisassembler_ReferenceType_Out_SymbolStub.
6637 // When this is called with an value loaded via a PC relative load then
6638 // ReferenceType will be LLVMDisassembler_ReferenceType_In_PCrel_Load then the
6639 // SymbolValue is checked to be an address of literal pointer, symbol pointer,
6640 // or an Objective-C meta data reference. If so the output ReferenceType is
6641 // set to correspond to that as well as setting the ReferenceName.
6642 static const char *SymbolizerSymbolLookUp(void *DisInfo,
6643 uint64_t ReferenceValue,
6644 uint64_t *ReferenceType,
6645 uint64_t ReferencePC,
6646 const char **ReferenceName) {
6647 struct DisassembleInfo *info = (struct DisassembleInfo *)DisInfo;
6648 // If no verbose symbolic information is wanted then just return nullptr.
6649 if (!info->verbose) {
6650 *ReferenceName = nullptr;
6651 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
6652 return nullptr;
6655 const char *SymbolName = GuessSymbolName(ReferenceValue, info->AddrMap);
6657 if (*ReferenceType == LLVMDisassembler_ReferenceType_In_Branch) {
6658 *ReferenceName = GuessIndirectSymbol(ReferenceValue, info);
6659 if (*ReferenceName != nullptr) {
6660 method_reference(info, ReferenceType, ReferenceName);
6661 if (*ReferenceType != LLVMDisassembler_ReferenceType_Out_Objc_Message)
6662 *ReferenceType = LLVMDisassembler_ReferenceType_Out_SymbolStub;
6663 } else if (SymbolName != nullptr && strncmp(SymbolName, "__Z", 3) == 0) {
6664 if (info->demangled_name != nullptr)
6665 free(info->demangled_name);
6666 int status;
6667 info->demangled_name =
6668 itaniumDemangle(SymbolName + 1, nullptr, nullptr, &status);
6669 if (info->demangled_name != nullptr) {
6670 *ReferenceName = info->demangled_name;
6671 *ReferenceType = LLVMDisassembler_ReferenceType_DeMangled_Name;
6672 } else
6673 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
6674 } else
6675 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
6676 } else if (*ReferenceType == LLVMDisassembler_ReferenceType_In_PCrel_Load) {
6677 *ReferenceName =
6678 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
6679 if (*ReferenceName)
6680 method_reference(info, ReferenceType, ReferenceName);
6681 else
6682 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
6683 // If this is arm64 and the reference is an adrp instruction save the
6684 // instruction, passed in ReferenceValue and the address of the instruction
6685 // for use later if we see and add immediate instruction.
6686 } else if (info->O->getArch() == Triple::aarch64 &&
6687 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADRP) {
6688 info->adrp_inst = ReferenceValue;
6689 info->adrp_addr = ReferencePC;
6690 SymbolName = nullptr;
6691 *ReferenceName = nullptr;
6692 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
6693 // If this is arm64 and reference is an add immediate instruction and we
6694 // have
6695 // seen an adrp instruction just before it and the adrp's Xd register
6696 // matches
6697 // this add's Xn register reconstruct the value being referenced and look to
6698 // see if it is a literal pointer. Note the add immediate instruction is
6699 // passed in ReferenceValue.
6700 } else if (info->O->getArch() == Triple::aarch64 &&
6701 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADDXri &&
6702 ReferencePC - 4 == info->adrp_addr &&
6703 (info->adrp_inst & 0x9f000000) == 0x90000000 &&
6704 (info->adrp_inst & 0x1f) == ((ReferenceValue >> 5) & 0x1f)) {
6705 uint32_t addxri_inst;
6706 uint64_t adrp_imm, addxri_imm;
6708 adrp_imm =
6709 ((info->adrp_inst & 0x00ffffe0) >> 3) | ((info->adrp_inst >> 29) & 0x3);
6710 if (info->adrp_inst & 0x0200000)
6711 adrp_imm |= 0xfffffffffc000000LL;
6713 addxri_inst = ReferenceValue;
6714 addxri_imm = (addxri_inst >> 10) & 0xfff;
6715 if (((addxri_inst >> 22) & 0x3) == 1)
6716 addxri_imm <<= 12;
6718 ReferenceValue = (info->adrp_addr & 0xfffffffffffff000LL) +
6719 (adrp_imm << 12) + addxri_imm;
6721 *ReferenceName =
6722 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
6723 if (*ReferenceName == nullptr)
6724 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
6725 // If this is arm64 and the reference is a load register instruction and we
6726 // have seen an adrp instruction just before it and the adrp's Xd register
6727 // matches this add's Xn register reconstruct the value being referenced and
6728 // look to see if it is a literal pointer. Note the load register
6729 // instruction is passed in ReferenceValue.
6730 } else if (info->O->getArch() == Triple::aarch64 &&
6731 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_LDRXui &&
6732 ReferencePC - 4 == info->adrp_addr &&
6733 (info->adrp_inst & 0x9f000000) == 0x90000000 &&
6734 (info->adrp_inst & 0x1f) == ((ReferenceValue >> 5) & 0x1f)) {
6735 uint32_t ldrxui_inst;
6736 uint64_t adrp_imm, ldrxui_imm;
6738 adrp_imm =
6739 ((info->adrp_inst & 0x00ffffe0) >> 3) | ((info->adrp_inst >> 29) & 0x3);
6740 if (info->adrp_inst & 0x0200000)
6741 adrp_imm |= 0xfffffffffc000000LL;
6743 ldrxui_inst = ReferenceValue;
6744 ldrxui_imm = (ldrxui_inst >> 10) & 0xfff;
6746 ReferenceValue = (info->adrp_addr & 0xfffffffffffff000LL) +
6747 (adrp_imm << 12) + (ldrxui_imm << 3);
6749 *ReferenceName =
6750 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
6751 if (*ReferenceName == nullptr)
6752 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
6754 // If this arm64 and is an load register (PC-relative) instruction the
6755 // ReferenceValue is the PC plus the immediate value.
6756 else if (info->O->getArch() == Triple::aarch64 &&
6757 (*ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_LDRXl ||
6758 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADR)) {
6759 *ReferenceName =
6760 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
6761 if (*ReferenceName == nullptr)
6762 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
6763 } else if (SymbolName != nullptr && strncmp(SymbolName, "__Z", 3) == 0) {
6764 if (info->demangled_name != nullptr)
6765 free(info->demangled_name);
6766 int status;
6767 info->demangled_name =
6768 itaniumDemangle(SymbolName + 1, nullptr, nullptr, &status);
6769 if (info->demangled_name != nullptr) {
6770 *ReferenceName = info->demangled_name;
6771 *ReferenceType = LLVMDisassembler_ReferenceType_DeMangled_Name;
6774 else {
6775 *ReferenceName = nullptr;
6776 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
6779 return SymbolName;
6782 /// Emits the comments that are stored in the CommentStream.
6783 /// Each comment in the CommentStream must end with a newline.
6784 static void emitComments(raw_svector_ostream &CommentStream,
6785 SmallString<128> &CommentsToEmit,
6786 formatted_raw_ostream &FormattedOS,
6787 const MCAsmInfo &MAI) {
6788 // Flush the stream before taking its content.
6789 StringRef Comments = CommentsToEmit.str();
6790 // Get the default information for printing a comment.
6791 StringRef CommentBegin = MAI.getCommentString();
6792 unsigned CommentColumn = MAI.getCommentColumn();
6793 bool IsFirst = true;
6794 while (!Comments.empty()) {
6795 if (!IsFirst)
6796 FormattedOS << '\n';
6797 // Emit a line of comments.
6798 FormattedOS.PadToColumn(CommentColumn);
6799 size_t Position = Comments.find('\n');
6800 FormattedOS << CommentBegin << ' ' << Comments.substr(0, Position);
6801 // Move after the newline character.
6802 Comments = Comments.substr(Position + 1);
6803 IsFirst = false;
6805 FormattedOS.flush();
6807 // Tell the comment stream that the vector changed underneath it.
6808 CommentsToEmit.clear();
6811 static void DisassembleMachO(StringRef Filename, MachOObjectFile *MachOOF,
6812 StringRef DisSegName, StringRef DisSectName) {
6813 const char *McpuDefault = nullptr;
6814 const Target *ThumbTarget = nullptr;
6815 const Target *TheTarget = GetTarget(MachOOF, &McpuDefault, &ThumbTarget);
6816 if (!TheTarget) {
6817 // GetTarget prints out stuff.
6818 return;
6820 std::string MachOMCPU;
6821 if (MCPU.empty() && McpuDefault)
6822 MachOMCPU = McpuDefault;
6823 else
6824 MachOMCPU = MCPU;
6826 std::unique_ptr<const MCInstrInfo> InstrInfo(TheTarget->createMCInstrInfo());
6827 std::unique_ptr<const MCInstrInfo> ThumbInstrInfo;
6828 if (ThumbTarget)
6829 ThumbInstrInfo.reset(ThumbTarget->createMCInstrInfo());
6831 // Package up features to be passed to target/subtarget
6832 std::string FeaturesStr;
6833 if (!MAttrs.empty()) {
6834 SubtargetFeatures Features;
6835 for (unsigned i = 0; i != MAttrs.size(); ++i)
6836 Features.AddFeature(MAttrs[i]);
6837 FeaturesStr = Features.getString();
6840 // Set up disassembler.
6841 std::unique_ptr<const MCRegisterInfo> MRI(
6842 TheTarget->createMCRegInfo(TripleName));
6843 std::unique_ptr<const MCAsmInfo> AsmInfo(
6844 TheTarget->createMCAsmInfo(*MRI, TripleName));
6845 std::unique_ptr<const MCSubtargetInfo> STI(
6846 TheTarget->createMCSubtargetInfo(TripleName, MachOMCPU, FeaturesStr));
6847 MCContext Ctx(AsmInfo.get(), MRI.get(), nullptr);
6848 std::unique_ptr<MCDisassembler> DisAsm(
6849 TheTarget->createMCDisassembler(*STI, Ctx));
6850 std::unique_ptr<MCSymbolizer> Symbolizer;
6851 struct DisassembleInfo SymbolizerInfo(nullptr, nullptr, nullptr, false);
6852 std::unique_ptr<MCRelocationInfo> RelInfo(
6853 TheTarget->createMCRelocationInfo(TripleName, Ctx));
6854 if (RelInfo) {
6855 Symbolizer.reset(TheTarget->createMCSymbolizer(
6856 TripleName, SymbolizerGetOpInfo, SymbolizerSymbolLookUp,
6857 &SymbolizerInfo, &Ctx, std::move(RelInfo)));
6858 DisAsm->setSymbolizer(std::move(Symbolizer));
6860 int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
6861 std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
6862 Triple(TripleName), AsmPrinterVariant, *AsmInfo, *InstrInfo, *MRI));
6863 // Set the display preference for hex vs. decimal immediates.
6864 IP->setPrintImmHex(PrintImmHex);
6865 // Comment stream and backing vector.
6866 SmallString<128> CommentsToEmit;
6867 raw_svector_ostream CommentStream(CommentsToEmit);
6868 // FIXME: Setting the CommentStream in the InstPrinter is problematic in that
6869 // if it is done then arm64 comments for string literals don't get printed
6870 // and some constant get printed instead and not setting it causes intel
6871 // (32-bit and 64-bit) comments printed with different spacing before the
6872 // comment causing different diffs with the 'C' disassembler library API.
6873 // IP->setCommentStream(CommentStream);
6875 if (!AsmInfo || !STI || !DisAsm || !IP) {
6876 WithColor::error(errs(), "llvm-objdump")
6877 << "couldn't initialize disassembler for target " << TripleName << '\n';
6878 return;
6881 // Set up separate thumb disassembler if needed.
6882 std::unique_ptr<const MCRegisterInfo> ThumbMRI;
6883 std::unique_ptr<const MCAsmInfo> ThumbAsmInfo;
6884 std::unique_ptr<const MCSubtargetInfo> ThumbSTI;
6885 std::unique_ptr<MCDisassembler> ThumbDisAsm;
6886 std::unique_ptr<MCInstPrinter> ThumbIP;
6887 std::unique_ptr<MCContext> ThumbCtx;
6888 std::unique_ptr<MCSymbolizer> ThumbSymbolizer;
6889 struct DisassembleInfo ThumbSymbolizerInfo(nullptr, nullptr, nullptr, false);
6890 std::unique_ptr<MCRelocationInfo> ThumbRelInfo;
6891 if (ThumbTarget) {
6892 ThumbMRI.reset(ThumbTarget->createMCRegInfo(ThumbTripleName));
6893 ThumbAsmInfo.reset(
6894 ThumbTarget->createMCAsmInfo(*ThumbMRI, ThumbTripleName));
6895 ThumbSTI.reset(
6896 ThumbTarget->createMCSubtargetInfo(ThumbTripleName, MachOMCPU,
6897 FeaturesStr));
6898 ThumbCtx.reset(new MCContext(ThumbAsmInfo.get(), ThumbMRI.get(), nullptr));
6899 ThumbDisAsm.reset(ThumbTarget->createMCDisassembler(*ThumbSTI, *ThumbCtx));
6900 MCContext *PtrThumbCtx = ThumbCtx.get();
6901 ThumbRelInfo.reset(
6902 ThumbTarget->createMCRelocationInfo(ThumbTripleName, *PtrThumbCtx));
6903 if (ThumbRelInfo) {
6904 ThumbSymbolizer.reset(ThumbTarget->createMCSymbolizer(
6905 ThumbTripleName, SymbolizerGetOpInfo, SymbolizerSymbolLookUp,
6906 &ThumbSymbolizerInfo, PtrThumbCtx, std::move(ThumbRelInfo)));
6907 ThumbDisAsm->setSymbolizer(std::move(ThumbSymbolizer));
6909 int ThumbAsmPrinterVariant = ThumbAsmInfo->getAssemblerDialect();
6910 ThumbIP.reset(ThumbTarget->createMCInstPrinter(
6911 Triple(ThumbTripleName), ThumbAsmPrinterVariant, *ThumbAsmInfo,
6912 *ThumbInstrInfo, *ThumbMRI));
6913 // Set the display preference for hex vs. decimal immediates.
6914 ThumbIP->setPrintImmHex(PrintImmHex);
6917 if (ThumbTarget && (!ThumbAsmInfo || !ThumbSTI || !ThumbDisAsm || !ThumbIP)) {
6918 WithColor::error(errs(), "llvm-objdump")
6919 << "couldn't initialize disassembler for target " << ThumbTripleName
6920 << '\n';
6921 return;
6924 MachO::mach_header Header = MachOOF->getHeader();
6926 // FIXME: Using the -cfg command line option, this code used to be able to
6927 // annotate relocations with the referenced symbol's name, and if this was
6928 // inside a __[cf]string section, the data it points to. This is now replaced
6929 // by the upcoming MCSymbolizer, which needs the appropriate setup done above.
6930 std::vector<SectionRef> Sections;
6931 std::vector<SymbolRef> Symbols;
6932 SmallVector<uint64_t, 8> FoundFns;
6933 uint64_t BaseSegmentAddress;
6935 getSectionsAndSymbols(MachOOF, Sections, Symbols, FoundFns,
6936 BaseSegmentAddress);
6938 // Sort the symbols by address, just in case they didn't come in that way.
6939 llvm::sort(Symbols, SymbolSorter());
6941 // Build a data in code table that is sorted on by the address of each entry.
6942 uint64_t BaseAddress = 0;
6943 if (Header.filetype == MachO::MH_OBJECT)
6944 BaseAddress = Sections[0].getAddress();
6945 else
6946 BaseAddress = BaseSegmentAddress;
6947 DiceTable Dices;
6948 for (dice_iterator DI = MachOOF->begin_dices(), DE = MachOOF->end_dices();
6949 DI != DE; ++DI) {
6950 uint32_t Offset;
6951 DI->getOffset(Offset);
6952 Dices.push_back(std::make_pair(BaseAddress + Offset, *DI));
6954 array_pod_sort(Dices.begin(), Dices.end());
6956 #ifndef NDEBUG
6957 raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls();
6958 #else
6959 raw_ostream &DebugOut = nulls();
6960 #endif
6962 std::unique_ptr<DIContext> diContext;
6963 ObjectFile *DbgObj = MachOOF;
6964 std::unique_ptr<MemoryBuffer> DSYMBuf;
6965 // Try to find debug info and set up the DIContext for it.
6966 if (UseDbg) {
6967 // A separate DSym file path was specified, parse it as a macho file,
6968 // get the sections and supply it to the section name parsing machinery.
6969 if (!DSYMFile.empty()) {
6970 ErrorOr<std::unique_ptr<MemoryBuffer>> BufOrErr =
6971 MemoryBuffer::getFileOrSTDIN(DSYMFile);
6972 if (std::error_code EC = BufOrErr.getError()) {
6973 report_error(DSYMFile, errorCodeToError(EC));
6974 return;
6977 Expected<std::unique_ptr<MachOObjectFile>> DbgObjCheck =
6978 ObjectFile::createMachOObjectFile(BufOrErr.get()->getMemBufferRef());
6980 if (Error E = DbgObjCheck.takeError()) {
6981 report_error(DSYMFile, std::move(E));
6982 return;
6985 DbgObj = DbgObjCheck.get().release();
6986 // We need to keep the file alive, because we're replacing DbgObj with it.
6987 DSYMBuf = std::move(BufOrErr.get());
6990 // Setup the DIContext
6991 diContext = DWARFContext::create(*DbgObj);
6994 if (FilterSections.empty())
6995 outs() << "(" << DisSegName << "," << DisSectName << ") section\n";
6997 for (unsigned SectIdx = 0; SectIdx != Sections.size(); SectIdx++) {
6998 StringRef SectName;
6999 if (Sections[SectIdx].getName(SectName) || SectName != DisSectName)
7000 continue;
7002 DataRefImpl DR = Sections[SectIdx].getRawDataRefImpl();
7004 StringRef SegmentName = MachOOF->getSectionFinalSegmentName(DR);
7005 if (SegmentName != DisSegName)
7006 continue;
7008 StringRef BytesStr;
7009 Sections[SectIdx].getContents(BytesStr);
7010 ArrayRef<uint8_t> Bytes(reinterpret_cast<const uint8_t *>(BytesStr.data()),
7011 BytesStr.size());
7012 uint64_t SectAddress = Sections[SectIdx].getAddress();
7014 bool symbolTableWorked = false;
7016 // Create a map of symbol addresses to symbol names for use by
7017 // the SymbolizerSymbolLookUp() routine.
7018 SymbolAddressMap AddrMap;
7019 bool DisSymNameFound = false;
7020 for (const SymbolRef &Symbol : MachOOF->symbols()) {
7021 Expected<SymbolRef::Type> STOrErr = Symbol.getType();
7022 if (!STOrErr)
7023 report_error(MachOOF->getFileName(), STOrErr.takeError());
7024 SymbolRef::Type ST = *STOrErr;
7025 if (ST == SymbolRef::ST_Function || ST == SymbolRef::ST_Data ||
7026 ST == SymbolRef::ST_Other) {
7027 uint64_t Address = Symbol.getValue();
7028 Expected<StringRef> SymNameOrErr = Symbol.getName();
7029 if (!SymNameOrErr)
7030 report_error(MachOOF->getFileName(), SymNameOrErr.takeError());
7031 StringRef SymName = *SymNameOrErr;
7032 AddrMap[Address] = SymName;
7033 if (!DisSymName.empty() && DisSymName == SymName)
7034 DisSymNameFound = true;
7037 if (!DisSymName.empty() && !DisSymNameFound) {
7038 outs() << "Can't find -dis-symname: " << DisSymName << "\n";
7039 return;
7041 // Set up the block of info used by the Symbolizer call backs.
7042 SymbolizerInfo.verbose = !NoSymbolicOperands;
7043 SymbolizerInfo.O = MachOOF;
7044 SymbolizerInfo.S = Sections[SectIdx];
7045 SymbolizerInfo.AddrMap = &AddrMap;
7046 SymbolizerInfo.Sections = &Sections;
7047 // Same for the ThumbSymbolizer
7048 ThumbSymbolizerInfo.verbose = !NoSymbolicOperands;
7049 ThumbSymbolizerInfo.O = MachOOF;
7050 ThumbSymbolizerInfo.S = Sections[SectIdx];
7051 ThumbSymbolizerInfo.AddrMap = &AddrMap;
7052 ThumbSymbolizerInfo.Sections = &Sections;
7054 unsigned int Arch = MachOOF->getArch();
7056 // Skip all symbols if this is a stubs file.
7057 if (Bytes.empty())
7058 return;
7060 // If the section has symbols but no symbol at the start of the section
7061 // these are used to make sure the bytes before the first symbol are
7062 // disassembled.
7063 bool FirstSymbol = true;
7064 bool FirstSymbolAtSectionStart = true;
7066 // Disassemble symbol by symbol.
7067 for (unsigned SymIdx = 0; SymIdx != Symbols.size(); SymIdx++) {
7068 Expected<StringRef> SymNameOrErr = Symbols[SymIdx].getName();
7069 if (!SymNameOrErr)
7070 report_error(MachOOF->getFileName(), SymNameOrErr.takeError());
7071 StringRef SymName = *SymNameOrErr;
7073 Expected<SymbolRef::Type> STOrErr = Symbols[SymIdx].getType();
7074 if (!STOrErr)
7075 report_error(MachOOF->getFileName(), STOrErr.takeError());
7076 SymbolRef::Type ST = *STOrErr;
7077 if (ST != SymbolRef::ST_Function && ST != SymbolRef::ST_Data)
7078 continue;
7080 // Make sure the symbol is defined in this section.
7081 bool containsSym = Sections[SectIdx].containsSymbol(Symbols[SymIdx]);
7082 if (!containsSym) {
7083 if (!DisSymName.empty() && DisSymName == SymName) {
7084 outs() << "-dis-symname: " << DisSymName << " not in the section\n";
7085 return;
7087 continue;
7089 // The __mh_execute_header is special and we need to deal with that fact
7090 // this symbol is before the start of the (__TEXT,__text) section and at the
7091 // address of the start of the __TEXT segment. This is because this symbol
7092 // is an N_SECT symbol in the (__TEXT,__text) but its address is before the
7093 // start of the section in a standard MH_EXECUTE filetype.
7094 if (!DisSymName.empty() && DisSymName == "__mh_execute_header") {
7095 outs() << "-dis-symname: __mh_execute_header not in any section\n";
7096 return;
7098 // When this code is trying to disassemble a symbol at a time and in the
7099 // case there is only the __mh_execute_header symbol left as in a stripped
7100 // executable, we need to deal with this by ignoring this symbol so the
7101 // whole section is disassembled and this symbol is then not displayed.
7102 if (SymName == "__mh_execute_header" || SymName == "__mh_dylib_header" ||
7103 SymName == "__mh_bundle_header" || SymName == "__mh_object_header" ||
7104 SymName == "__mh_preload_header" || SymName == "__mh_dylinker_header")
7105 continue;
7107 // If we are only disassembling one symbol see if this is that symbol.
7108 if (!DisSymName.empty() && DisSymName != SymName)
7109 continue;
7111 // Start at the address of the symbol relative to the section's address.
7112 uint64_t SectSize = Sections[SectIdx].getSize();
7113 uint64_t Start = Symbols[SymIdx].getValue();
7114 uint64_t SectionAddress = Sections[SectIdx].getAddress();
7115 Start -= SectionAddress;
7117 if (Start > SectSize) {
7118 outs() << "section data ends, " << SymName
7119 << " lies outside valid range\n";
7120 return;
7123 // Stop disassembling either at the beginning of the next symbol or at
7124 // the end of the section.
7125 bool containsNextSym = false;
7126 uint64_t NextSym = 0;
7127 uint64_t NextSymIdx = SymIdx + 1;
7128 while (Symbols.size() > NextSymIdx) {
7129 Expected<SymbolRef::Type> STOrErr = Symbols[NextSymIdx].getType();
7130 if (!STOrErr)
7131 report_error(MachOOF->getFileName(), STOrErr.takeError());
7132 SymbolRef::Type NextSymType = *STOrErr;
7133 if (NextSymType == SymbolRef::ST_Function) {
7134 containsNextSym =
7135 Sections[SectIdx].containsSymbol(Symbols[NextSymIdx]);
7136 NextSym = Symbols[NextSymIdx].getValue();
7137 NextSym -= SectionAddress;
7138 break;
7140 ++NextSymIdx;
7143 uint64_t End = containsNextSym ? std::min(NextSym, SectSize) : SectSize;
7144 uint64_t Size;
7146 symbolTableWorked = true;
7148 DataRefImpl Symb = Symbols[SymIdx].getRawDataRefImpl();
7149 bool IsThumb = MachOOF->getSymbolFlags(Symb) & SymbolRef::SF_Thumb;
7151 // We only need the dedicated Thumb target if there's a real choice
7152 // (i.e. we're not targeting M-class) and the function is Thumb.
7153 bool UseThumbTarget = IsThumb && ThumbTarget;
7155 // If we are not specifying a symbol to start disassembly with and this
7156 // is the first symbol in the section but not at the start of the section
7157 // then move the disassembly index to the start of the section and
7158 // don't print the symbol name just yet. This is so the bytes before the
7159 // first symbol are disassembled.
7160 uint64_t SymbolStart = Start;
7161 if (DisSymName.empty() && FirstSymbol && Start != 0) {
7162 FirstSymbolAtSectionStart = false;
7163 Start = 0;
7165 else
7166 outs() << SymName << ":\n";
7168 DILineInfo lastLine;
7169 for (uint64_t Index = Start; Index < End; Index += Size) {
7170 MCInst Inst;
7172 // If this is the first symbol in the section and it was not at the
7173 // start of the section, see if we are at its Index now and if so print
7174 // the symbol name.
7175 if (FirstSymbol && !FirstSymbolAtSectionStart && Index == SymbolStart)
7176 outs() << SymName << ":\n";
7178 uint64_t PC = SectAddress + Index;
7179 if (!NoLeadingAddr) {
7180 if (FullLeadingAddr) {
7181 if (MachOOF->is64Bit())
7182 outs() << format("%016" PRIx64, PC);
7183 else
7184 outs() << format("%08" PRIx64, PC);
7185 } else {
7186 outs() << format("%8" PRIx64 ":", PC);
7189 if (!NoShowRawInsn || Arch == Triple::arm)
7190 outs() << "\t";
7192 // Check the data in code table here to see if this is data not an
7193 // instruction to be disassembled.
7194 DiceTable Dice;
7195 Dice.push_back(std::make_pair(PC, DiceRef()));
7196 dice_table_iterator DTI =
7197 std::search(Dices.begin(), Dices.end(), Dice.begin(), Dice.end(),
7198 compareDiceTableEntries);
7199 if (DTI != Dices.end()) {
7200 uint16_t Length;
7201 DTI->second.getLength(Length);
7202 uint16_t Kind;
7203 DTI->second.getKind(Kind);
7204 Size = DumpDataInCode(Bytes.data() + Index, Length, Kind);
7205 if ((Kind == MachO::DICE_KIND_JUMP_TABLE8) &&
7206 (PC == (DTI->first + Length - 1)) && (Length & 1))
7207 Size++;
7208 continue;
7211 SmallVector<char, 64> AnnotationsBytes;
7212 raw_svector_ostream Annotations(AnnotationsBytes);
7214 bool gotInst;
7215 if (UseThumbTarget)
7216 gotInst = ThumbDisAsm->getInstruction(Inst, Size, Bytes.slice(Index),
7217 PC, DebugOut, Annotations);
7218 else
7219 gotInst = DisAsm->getInstruction(Inst, Size, Bytes.slice(Index), PC,
7220 DebugOut, Annotations);
7221 if (gotInst) {
7222 if (!NoShowRawInsn || Arch == Triple::arm) {
7223 dumpBytes(makeArrayRef(Bytes.data() + Index, Size), outs());
7225 formatted_raw_ostream FormattedOS(outs());
7226 StringRef AnnotationsStr = Annotations.str();
7227 if (UseThumbTarget)
7228 ThumbIP->printInst(&Inst, FormattedOS, AnnotationsStr, *ThumbSTI);
7229 else
7230 IP->printInst(&Inst, FormattedOS, AnnotationsStr, *STI);
7231 emitComments(CommentStream, CommentsToEmit, FormattedOS, *AsmInfo);
7233 // Print debug info.
7234 if (diContext) {
7235 DILineInfo dli = diContext->getLineInfoForAddress(PC);
7236 // Print valid line info if it changed.
7237 if (dli != lastLine && dli.Line != 0)
7238 outs() << "\t## " << dli.FileName << ':' << dli.Line << ':'
7239 << dli.Column;
7240 lastLine = dli;
7242 outs() << "\n";
7243 } else {
7244 unsigned int Arch = MachOOF->getArch();
7245 if (Arch == Triple::x86_64 || Arch == Triple::x86) {
7246 outs() << format("\t.byte 0x%02x #bad opcode\n",
7247 *(Bytes.data() + Index) & 0xff);
7248 Size = 1; // skip exactly one illegible byte and move on.
7249 } else if (Arch == Triple::aarch64 ||
7250 (Arch == Triple::arm && !IsThumb)) {
7251 uint32_t opcode = (*(Bytes.data() + Index) & 0xff) |
7252 (*(Bytes.data() + Index + 1) & 0xff) << 8 |
7253 (*(Bytes.data() + Index + 2) & 0xff) << 16 |
7254 (*(Bytes.data() + Index + 3) & 0xff) << 24;
7255 outs() << format("\t.long\t0x%08x\n", opcode);
7256 Size = 4;
7257 } else if (Arch == Triple::arm) {
7258 assert(IsThumb && "ARM mode should have been dealt with above");
7259 uint32_t opcode = (*(Bytes.data() + Index) & 0xff) |
7260 (*(Bytes.data() + Index + 1) & 0xff) << 8;
7261 outs() << format("\t.short\t0x%04x\n", opcode);
7262 Size = 2;
7263 } else{
7264 WithColor::warning(errs(), "llvm-objdump")
7265 << "invalid instruction encoding\n";
7266 if (Size == 0)
7267 Size = 1; // skip illegible bytes
7271 // Now that we are done disassembled the first symbol set the bool that
7272 // were doing this to false.
7273 FirstSymbol = false;
7275 if (!symbolTableWorked) {
7276 // Reading the symbol table didn't work, disassemble the whole section.
7277 uint64_t SectAddress = Sections[SectIdx].getAddress();
7278 uint64_t SectSize = Sections[SectIdx].getSize();
7279 uint64_t InstSize;
7280 for (uint64_t Index = 0; Index < SectSize; Index += InstSize) {
7281 MCInst Inst;
7283 uint64_t PC = SectAddress + Index;
7284 SmallVector<char, 64> AnnotationsBytes;
7285 raw_svector_ostream Annotations(AnnotationsBytes);
7286 if (DisAsm->getInstruction(Inst, InstSize, Bytes.slice(Index), PC,
7287 DebugOut, Annotations)) {
7288 if (!NoLeadingAddr) {
7289 if (FullLeadingAddr) {
7290 if (MachOOF->is64Bit())
7291 outs() << format("%016" PRIx64, PC);
7292 else
7293 outs() << format("%08" PRIx64, PC);
7294 } else {
7295 outs() << format("%8" PRIx64 ":", PC);
7298 if (!NoShowRawInsn || Arch == Triple::arm) {
7299 outs() << "\t";
7300 dumpBytes(makeArrayRef(Bytes.data() + Index, InstSize), outs());
7302 StringRef AnnotationsStr = Annotations.str();
7303 IP->printInst(&Inst, outs(), AnnotationsStr, *STI);
7304 outs() << "\n";
7305 } else {
7306 unsigned int Arch = MachOOF->getArch();
7307 if (Arch == Triple::x86_64 || Arch == Triple::x86) {
7308 outs() << format("\t.byte 0x%02x #bad opcode\n",
7309 *(Bytes.data() + Index) & 0xff);
7310 InstSize = 1; // skip exactly one illegible byte and move on.
7311 } else {
7312 WithColor::warning(errs(), "llvm-objdump")
7313 << "invalid instruction encoding\n";
7314 if (InstSize == 0)
7315 InstSize = 1; // skip illegible bytes
7320 // The TripleName's need to be reset if we are called again for a different
7321 // archtecture.
7322 TripleName = "";
7323 ThumbTripleName = "";
7325 if (SymbolizerInfo.demangled_name != nullptr)
7326 free(SymbolizerInfo.demangled_name);
7327 if (ThumbSymbolizerInfo.demangled_name != nullptr)
7328 free(ThumbSymbolizerInfo.demangled_name);
7332 //===----------------------------------------------------------------------===//
7333 // __compact_unwind section dumping
7334 //===----------------------------------------------------------------------===//
7336 namespace {
7338 template <typename T>
7339 static uint64_t read(StringRef Contents, ptrdiff_t Offset) {
7340 using llvm::support::little;
7341 using llvm::support::unaligned;
7343 if (Offset + sizeof(T) > Contents.size()) {
7344 outs() << "warning: attempt to read past end of buffer\n";
7345 return T();
7348 uint64_t Val =
7349 support::endian::read<T, little, unaligned>(Contents.data() + Offset);
7350 return Val;
7353 template <typename T>
7354 static uint64_t readNext(StringRef Contents, ptrdiff_t &Offset) {
7355 T Val = read<T>(Contents, Offset);
7356 Offset += sizeof(T);
7357 return Val;
7360 struct CompactUnwindEntry {
7361 uint32_t OffsetInSection;
7363 uint64_t FunctionAddr;
7364 uint32_t Length;
7365 uint32_t CompactEncoding;
7366 uint64_t PersonalityAddr;
7367 uint64_t LSDAAddr;
7369 RelocationRef FunctionReloc;
7370 RelocationRef PersonalityReloc;
7371 RelocationRef LSDAReloc;
7373 CompactUnwindEntry(StringRef Contents, unsigned Offset, bool Is64)
7374 : OffsetInSection(Offset) {
7375 if (Is64)
7376 read<uint64_t>(Contents, Offset);
7377 else
7378 read<uint32_t>(Contents, Offset);
7381 private:
7382 template <typename UIntPtr> void read(StringRef Contents, ptrdiff_t Offset) {
7383 FunctionAddr = readNext<UIntPtr>(Contents, Offset);
7384 Length = readNext<uint32_t>(Contents, Offset);
7385 CompactEncoding = readNext<uint32_t>(Contents, Offset);
7386 PersonalityAddr = readNext<UIntPtr>(Contents, Offset);
7387 LSDAAddr = readNext<UIntPtr>(Contents, Offset);
7392 /// Given a relocation from __compact_unwind, consisting of the RelocationRef
7393 /// and data being relocated, determine the best base Name and Addend to use for
7394 /// display purposes.
7396 /// 1. An Extern relocation will directly reference a symbol (and the data is
7397 /// then already an addend), so use that.
7398 /// 2. Otherwise the data is an offset in the object file's layout; try to find
7399 // a symbol before it in the same section, and use the offset from there.
7400 /// 3. Finally, if all that fails, fall back to an offset from the start of the
7401 /// referenced section.
7402 static void findUnwindRelocNameAddend(const MachOObjectFile *Obj,
7403 std::map<uint64_t, SymbolRef> &Symbols,
7404 const RelocationRef &Reloc, uint64_t Addr,
7405 StringRef &Name, uint64_t &Addend) {
7406 if (Reloc.getSymbol() != Obj->symbol_end()) {
7407 Expected<StringRef> NameOrErr = Reloc.getSymbol()->getName();
7408 if (!NameOrErr)
7409 report_error(Obj->getFileName(), NameOrErr.takeError());
7410 Name = *NameOrErr;
7411 Addend = Addr;
7412 return;
7415 auto RE = Obj->getRelocation(Reloc.getRawDataRefImpl());
7416 SectionRef RelocSection = Obj->getAnyRelocationSection(RE);
7418 uint64_t SectionAddr = RelocSection.getAddress();
7420 auto Sym = Symbols.upper_bound(Addr);
7421 if (Sym == Symbols.begin()) {
7422 // The first symbol in the object is after this reference, the best we can
7423 // do is section-relative notation.
7424 RelocSection.getName(Name);
7425 Addend = Addr - SectionAddr;
7426 return;
7429 // Go back one so that SymbolAddress <= Addr.
7430 --Sym;
7432 auto SectOrErr = Sym->second.getSection();
7433 if (!SectOrErr)
7434 report_error(Obj->getFileName(), SectOrErr.takeError());
7435 section_iterator SymSection = *SectOrErr;
7436 if (RelocSection == *SymSection) {
7437 // There's a valid symbol in the same section before this reference.
7438 Expected<StringRef> NameOrErr = Sym->second.getName();
7439 if (!NameOrErr)
7440 report_error(Obj->getFileName(), NameOrErr.takeError());
7441 Name = *NameOrErr;
7442 Addend = Addr - Sym->first;
7443 return;
7446 // There is a symbol before this reference, but it's in a different
7447 // section. Probably not helpful to mention it, so use the section name.
7448 RelocSection.getName(Name);
7449 Addend = Addr - SectionAddr;
7452 static void printUnwindRelocDest(const MachOObjectFile *Obj,
7453 std::map<uint64_t, SymbolRef> &Symbols,
7454 const RelocationRef &Reloc, uint64_t Addr) {
7455 StringRef Name;
7456 uint64_t Addend;
7458 if (!Reloc.getObject())
7459 return;
7461 findUnwindRelocNameAddend(Obj, Symbols, Reloc, Addr, Name, Addend);
7463 outs() << Name;
7464 if (Addend)
7465 outs() << " + " << format("0x%" PRIx64, Addend);
7468 static void
7469 printMachOCompactUnwindSection(const MachOObjectFile *Obj,
7470 std::map<uint64_t, SymbolRef> &Symbols,
7471 const SectionRef &CompactUnwind) {
7473 if (!Obj->isLittleEndian()) {
7474 outs() << "Skipping big-endian __compact_unwind section\n";
7475 return;
7478 bool Is64 = Obj->is64Bit();
7479 uint32_t PointerSize = Is64 ? sizeof(uint64_t) : sizeof(uint32_t);
7480 uint32_t EntrySize = 3 * PointerSize + 2 * sizeof(uint32_t);
7482 StringRef Contents;
7483 CompactUnwind.getContents(Contents);
7485 SmallVector<CompactUnwindEntry, 4> CompactUnwinds;
7487 // First populate the initial raw offsets, encodings and so on from the entry.
7488 for (unsigned Offset = 0; Offset < Contents.size(); Offset += EntrySize) {
7489 CompactUnwindEntry Entry(Contents, Offset, Is64);
7490 CompactUnwinds.push_back(Entry);
7493 // Next we need to look at the relocations to find out what objects are
7494 // actually being referred to.
7495 for (const RelocationRef &Reloc : CompactUnwind.relocations()) {
7496 uint64_t RelocAddress = Reloc.getOffset();
7498 uint32_t EntryIdx = RelocAddress / EntrySize;
7499 uint32_t OffsetInEntry = RelocAddress - EntryIdx * EntrySize;
7500 CompactUnwindEntry &Entry = CompactUnwinds[EntryIdx];
7502 if (OffsetInEntry == 0)
7503 Entry.FunctionReloc = Reloc;
7504 else if (OffsetInEntry == PointerSize + 2 * sizeof(uint32_t))
7505 Entry.PersonalityReloc = Reloc;
7506 else if (OffsetInEntry == 2 * PointerSize + 2 * sizeof(uint32_t))
7507 Entry.LSDAReloc = Reloc;
7508 else {
7509 outs() << "Invalid relocation in __compact_unwind section\n";
7510 return;
7514 // Finally, we're ready to print the data we've gathered.
7515 outs() << "Contents of __compact_unwind section:\n";
7516 for (auto &Entry : CompactUnwinds) {
7517 outs() << " Entry at offset "
7518 << format("0x%" PRIx32, Entry.OffsetInSection) << ":\n";
7520 // 1. Start of the region this entry applies to.
7521 outs() << " start: " << format("0x%" PRIx64,
7522 Entry.FunctionAddr) << ' ';
7523 printUnwindRelocDest(Obj, Symbols, Entry.FunctionReloc, Entry.FunctionAddr);
7524 outs() << '\n';
7526 // 2. Length of the region this entry applies to.
7527 outs() << " length: " << format("0x%" PRIx32, Entry.Length)
7528 << '\n';
7529 // 3. The 32-bit compact encoding.
7530 outs() << " compact encoding: "
7531 << format("0x%08" PRIx32, Entry.CompactEncoding) << '\n';
7533 // 4. The personality function, if present.
7534 if (Entry.PersonalityReloc.getObject()) {
7535 outs() << " personality function: "
7536 << format("0x%" PRIx64, Entry.PersonalityAddr) << ' ';
7537 printUnwindRelocDest(Obj, Symbols, Entry.PersonalityReloc,
7538 Entry.PersonalityAddr);
7539 outs() << '\n';
7542 // 5. This entry's language-specific data area.
7543 if (Entry.LSDAReloc.getObject()) {
7544 outs() << " LSDA: " << format("0x%" PRIx64,
7545 Entry.LSDAAddr) << ' ';
7546 printUnwindRelocDest(Obj, Symbols, Entry.LSDAReloc, Entry.LSDAAddr);
7547 outs() << '\n';
7552 //===----------------------------------------------------------------------===//
7553 // __unwind_info section dumping
7554 //===----------------------------------------------------------------------===//
7556 static void printRegularSecondLevelUnwindPage(StringRef PageData) {
7557 ptrdiff_t Pos = 0;
7558 uint32_t Kind = readNext<uint32_t>(PageData, Pos);
7559 (void)Kind;
7560 assert(Kind == 2 && "kind for a regular 2nd level index should be 2");
7562 uint16_t EntriesStart = readNext<uint16_t>(PageData, Pos);
7563 uint16_t NumEntries = readNext<uint16_t>(PageData, Pos);
7565 Pos = EntriesStart;
7566 for (unsigned i = 0; i < NumEntries; ++i) {
7567 uint32_t FunctionOffset = readNext<uint32_t>(PageData, Pos);
7568 uint32_t Encoding = readNext<uint32_t>(PageData, Pos);
7570 outs() << " [" << i << "]: "
7571 << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
7572 << ", "
7573 << "encoding=" << format("0x%08" PRIx32, Encoding) << '\n';
7577 static void printCompressedSecondLevelUnwindPage(
7578 StringRef PageData, uint32_t FunctionBase,
7579 const SmallVectorImpl<uint32_t> &CommonEncodings) {
7580 ptrdiff_t Pos = 0;
7581 uint32_t Kind = readNext<uint32_t>(PageData, Pos);
7582 (void)Kind;
7583 assert(Kind == 3 && "kind for a compressed 2nd level index should be 3");
7585 uint16_t EntriesStart = readNext<uint16_t>(PageData, Pos);
7586 uint16_t NumEntries = readNext<uint16_t>(PageData, Pos);
7588 uint16_t EncodingsStart = readNext<uint16_t>(PageData, Pos);
7589 readNext<uint16_t>(PageData, Pos);
7590 StringRef PageEncodings = PageData.substr(EncodingsStart, StringRef::npos);
7592 Pos = EntriesStart;
7593 for (unsigned i = 0; i < NumEntries; ++i) {
7594 uint32_t Entry = readNext<uint32_t>(PageData, Pos);
7595 uint32_t FunctionOffset = FunctionBase + (Entry & 0xffffff);
7596 uint32_t EncodingIdx = Entry >> 24;
7598 uint32_t Encoding;
7599 if (EncodingIdx < CommonEncodings.size())
7600 Encoding = CommonEncodings[EncodingIdx];
7601 else
7602 Encoding = read<uint32_t>(PageEncodings,
7603 sizeof(uint32_t) *
7604 (EncodingIdx - CommonEncodings.size()));
7606 outs() << " [" << i << "]: "
7607 << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
7608 << ", "
7609 << "encoding[" << EncodingIdx
7610 << "]=" << format("0x%08" PRIx32, Encoding) << '\n';
7614 static void printMachOUnwindInfoSection(const MachOObjectFile *Obj,
7615 std::map<uint64_t, SymbolRef> &Symbols,
7616 const SectionRef &UnwindInfo) {
7618 if (!Obj->isLittleEndian()) {
7619 outs() << "Skipping big-endian __unwind_info section\n";
7620 return;
7623 outs() << "Contents of __unwind_info section:\n";
7625 StringRef Contents;
7626 UnwindInfo.getContents(Contents);
7627 ptrdiff_t Pos = 0;
7629 //===----------------------------------
7630 // Section header
7631 //===----------------------------------
7633 uint32_t Version = readNext<uint32_t>(Contents, Pos);
7634 outs() << " Version: "
7635 << format("0x%" PRIx32, Version) << '\n';
7636 if (Version != 1) {
7637 outs() << " Skipping section with unknown version\n";
7638 return;
7641 uint32_t CommonEncodingsStart = readNext<uint32_t>(Contents, Pos);
7642 outs() << " Common encodings array section offset: "
7643 << format("0x%" PRIx32, CommonEncodingsStart) << '\n';
7644 uint32_t NumCommonEncodings = readNext<uint32_t>(Contents, Pos);
7645 outs() << " Number of common encodings in array: "
7646 << format("0x%" PRIx32, NumCommonEncodings) << '\n';
7648 uint32_t PersonalitiesStart = readNext<uint32_t>(Contents, Pos);
7649 outs() << " Personality function array section offset: "
7650 << format("0x%" PRIx32, PersonalitiesStart) << '\n';
7651 uint32_t NumPersonalities = readNext<uint32_t>(Contents, Pos);
7652 outs() << " Number of personality functions in array: "
7653 << format("0x%" PRIx32, NumPersonalities) << '\n';
7655 uint32_t IndicesStart = readNext<uint32_t>(Contents, Pos);
7656 outs() << " Index array section offset: "
7657 << format("0x%" PRIx32, IndicesStart) << '\n';
7658 uint32_t NumIndices = readNext<uint32_t>(Contents, Pos);
7659 outs() << " Number of indices in array: "
7660 << format("0x%" PRIx32, NumIndices) << '\n';
7662 //===----------------------------------
7663 // A shared list of common encodings
7664 //===----------------------------------
7666 // These occupy indices in the range [0, N] whenever an encoding is referenced
7667 // from a compressed 2nd level index table. In practice the linker only
7668 // creates ~128 of these, so that indices are available to embed encodings in
7669 // the 2nd level index.
7671 SmallVector<uint32_t, 64> CommonEncodings;
7672 outs() << " Common encodings: (count = " << NumCommonEncodings << ")\n";
7673 Pos = CommonEncodingsStart;
7674 for (unsigned i = 0; i < NumCommonEncodings; ++i) {
7675 uint32_t Encoding = readNext<uint32_t>(Contents, Pos);
7676 CommonEncodings.push_back(Encoding);
7678 outs() << " encoding[" << i << "]: " << format("0x%08" PRIx32, Encoding)
7679 << '\n';
7682 //===----------------------------------
7683 // Personality functions used in this executable
7684 //===----------------------------------
7686 // There should be only a handful of these (one per source language,
7687 // roughly). Particularly since they only get 2 bits in the compact encoding.
7689 outs() << " Personality functions: (count = " << NumPersonalities << ")\n";
7690 Pos = PersonalitiesStart;
7691 for (unsigned i = 0; i < NumPersonalities; ++i) {
7692 uint32_t PersonalityFn = readNext<uint32_t>(Contents, Pos);
7693 outs() << " personality[" << i + 1
7694 << "]: " << format("0x%08" PRIx32, PersonalityFn) << '\n';
7697 //===----------------------------------
7698 // The level 1 index entries
7699 //===----------------------------------
7701 // These specify an approximate place to start searching for the more detailed
7702 // information, sorted by PC.
7704 struct IndexEntry {
7705 uint32_t FunctionOffset;
7706 uint32_t SecondLevelPageStart;
7707 uint32_t LSDAStart;
7710 SmallVector<IndexEntry, 4> IndexEntries;
7712 outs() << " Top level indices: (count = " << NumIndices << ")\n";
7713 Pos = IndicesStart;
7714 for (unsigned i = 0; i < NumIndices; ++i) {
7715 IndexEntry Entry;
7717 Entry.FunctionOffset = readNext<uint32_t>(Contents, Pos);
7718 Entry.SecondLevelPageStart = readNext<uint32_t>(Contents, Pos);
7719 Entry.LSDAStart = readNext<uint32_t>(Contents, Pos);
7720 IndexEntries.push_back(Entry);
7722 outs() << " [" << i << "]: "
7723 << "function offset=" << format("0x%08" PRIx32, Entry.FunctionOffset)
7724 << ", "
7725 << "2nd level page offset="
7726 << format("0x%08" PRIx32, Entry.SecondLevelPageStart) << ", "
7727 << "LSDA offset=" << format("0x%08" PRIx32, Entry.LSDAStart) << '\n';
7730 //===----------------------------------
7731 // Next come the LSDA tables
7732 //===----------------------------------
7734 // The LSDA layout is rather implicit: it's a contiguous array of entries from
7735 // the first top-level index's LSDAOffset to the last (sentinel).
7737 outs() << " LSDA descriptors:\n";
7738 Pos = IndexEntries[0].LSDAStart;
7739 const uint32_t LSDASize = 2 * sizeof(uint32_t);
7740 int NumLSDAs =
7741 (IndexEntries.back().LSDAStart - IndexEntries[0].LSDAStart) / LSDASize;
7743 for (int i = 0; i < NumLSDAs; ++i) {
7744 uint32_t FunctionOffset = readNext<uint32_t>(Contents, Pos);
7745 uint32_t LSDAOffset = readNext<uint32_t>(Contents, Pos);
7746 outs() << " [" << i << "]: "
7747 << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
7748 << ", "
7749 << "LSDA offset=" << format("0x%08" PRIx32, LSDAOffset) << '\n';
7752 //===----------------------------------
7753 // Finally, the 2nd level indices
7754 //===----------------------------------
7756 // Generally these are 4K in size, and have 2 possible forms:
7757 // + Regular stores up to 511 entries with disparate encodings
7758 // + Compressed stores up to 1021 entries if few enough compact encoding
7759 // values are used.
7760 outs() << " Second level indices:\n";
7761 for (unsigned i = 0; i < IndexEntries.size() - 1; ++i) {
7762 // The final sentinel top-level index has no associated 2nd level page
7763 if (IndexEntries[i].SecondLevelPageStart == 0)
7764 break;
7766 outs() << " Second level index[" << i << "]: "
7767 << "offset in section="
7768 << format("0x%08" PRIx32, IndexEntries[i].SecondLevelPageStart)
7769 << ", "
7770 << "base function offset="
7771 << format("0x%08" PRIx32, IndexEntries[i].FunctionOffset) << '\n';
7773 Pos = IndexEntries[i].SecondLevelPageStart;
7774 if (Pos + sizeof(uint32_t) > Contents.size()) {
7775 outs() << "warning: invalid offset for second level page: " << Pos << '\n';
7776 continue;
7779 uint32_t Kind =
7780 *reinterpret_cast<const support::ulittle32_t *>(Contents.data() + Pos);
7781 if (Kind == 2)
7782 printRegularSecondLevelUnwindPage(Contents.substr(Pos, 4096));
7783 else if (Kind == 3)
7784 printCompressedSecondLevelUnwindPage(Contents.substr(Pos, 4096),
7785 IndexEntries[i].FunctionOffset,
7786 CommonEncodings);
7787 else
7788 outs() << " Skipping 2nd level page with unknown kind " << Kind
7789 << '\n';
7793 void llvm::printMachOUnwindInfo(const MachOObjectFile *Obj) {
7794 std::map<uint64_t, SymbolRef> Symbols;
7795 for (const SymbolRef &SymRef : Obj->symbols()) {
7796 // Discard any undefined or absolute symbols. They're not going to take part
7797 // in the convenience lookup for unwind info and just take up resources.
7798 auto SectOrErr = SymRef.getSection();
7799 if (!SectOrErr) {
7800 // TODO: Actually report errors helpfully.
7801 consumeError(SectOrErr.takeError());
7802 continue;
7804 section_iterator Section = *SectOrErr;
7805 if (Section == Obj->section_end())
7806 continue;
7808 uint64_t Addr = SymRef.getValue();
7809 Symbols.insert(std::make_pair(Addr, SymRef));
7812 for (const SectionRef &Section : Obj->sections()) {
7813 StringRef SectName;
7814 Section.getName(SectName);
7815 if (SectName == "__compact_unwind")
7816 printMachOCompactUnwindSection(Obj, Symbols, Section);
7817 else if (SectName == "__unwind_info")
7818 printMachOUnwindInfoSection(Obj, Symbols, Section);
7822 static void PrintMachHeader(uint32_t magic, uint32_t cputype,
7823 uint32_t cpusubtype, uint32_t filetype,
7824 uint32_t ncmds, uint32_t sizeofcmds, uint32_t flags,
7825 bool verbose) {
7826 outs() << "Mach header\n";
7827 outs() << " magic cputype cpusubtype caps filetype ncmds "
7828 "sizeofcmds flags\n";
7829 if (verbose) {
7830 if (magic == MachO::MH_MAGIC)
7831 outs() << " MH_MAGIC";
7832 else if (magic == MachO::MH_MAGIC_64)
7833 outs() << "MH_MAGIC_64";
7834 else
7835 outs() << format(" 0x%08" PRIx32, magic);
7836 switch (cputype) {
7837 case MachO::CPU_TYPE_I386:
7838 outs() << " I386";
7839 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
7840 case MachO::CPU_SUBTYPE_I386_ALL:
7841 outs() << " ALL";
7842 break;
7843 default:
7844 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
7845 break;
7847 break;
7848 case MachO::CPU_TYPE_X86_64:
7849 outs() << " X86_64";
7850 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
7851 case MachO::CPU_SUBTYPE_X86_64_ALL:
7852 outs() << " ALL";
7853 break;
7854 case MachO::CPU_SUBTYPE_X86_64_H:
7855 outs() << " Haswell";
7856 break;
7857 default:
7858 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
7859 break;
7861 break;
7862 case MachO::CPU_TYPE_ARM:
7863 outs() << " ARM";
7864 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
7865 case MachO::CPU_SUBTYPE_ARM_ALL:
7866 outs() << " ALL";
7867 break;
7868 case MachO::CPU_SUBTYPE_ARM_V4T:
7869 outs() << " V4T";
7870 break;
7871 case MachO::CPU_SUBTYPE_ARM_V5TEJ:
7872 outs() << " V5TEJ";
7873 break;
7874 case MachO::CPU_SUBTYPE_ARM_XSCALE:
7875 outs() << " XSCALE";
7876 break;
7877 case MachO::CPU_SUBTYPE_ARM_V6:
7878 outs() << " V6";
7879 break;
7880 case MachO::CPU_SUBTYPE_ARM_V6M:
7881 outs() << " V6M";
7882 break;
7883 case MachO::CPU_SUBTYPE_ARM_V7:
7884 outs() << " V7";
7885 break;
7886 case MachO::CPU_SUBTYPE_ARM_V7EM:
7887 outs() << " V7EM";
7888 break;
7889 case MachO::CPU_SUBTYPE_ARM_V7K:
7890 outs() << " V7K";
7891 break;
7892 case MachO::CPU_SUBTYPE_ARM_V7M:
7893 outs() << " V7M";
7894 break;
7895 case MachO::CPU_SUBTYPE_ARM_V7S:
7896 outs() << " V7S";
7897 break;
7898 default:
7899 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
7900 break;
7902 break;
7903 case MachO::CPU_TYPE_ARM64:
7904 outs() << " ARM64";
7905 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
7906 case MachO::CPU_SUBTYPE_ARM64_ALL:
7907 outs() << " ALL";
7908 break;
7909 default:
7910 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
7911 break;
7913 break;
7914 case MachO::CPU_TYPE_POWERPC:
7915 outs() << " PPC";
7916 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
7917 case MachO::CPU_SUBTYPE_POWERPC_ALL:
7918 outs() << " ALL";
7919 break;
7920 default:
7921 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
7922 break;
7924 break;
7925 case MachO::CPU_TYPE_POWERPC64:
7926 outs() << " PPC64";
7927 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
7928 case MachO::CPU_SUBTYPE_POWERPC_ALL:
7929 outs() << " ALL";
7930 break;
7931 default:
7932 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
7933 break;
7935 break;
7936 default:
7937 outs() << format(" %7d", cputype);
7938 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
7939 break;
7941 if ((cpusubtype & MachO::CPU_SUBTYPE_MASK) == MachO::CPU_SUBTYPE_LIB64) {
7942 outs() << " LIB64";
7943 } else {
7944 outs() << format(" 0x%02" PRIx32,
7945 (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24);
7947 switch (filetype) {
7948 case MachO::MH_OBJECT:
7949 outs() << " OBJECT";
7950 break;
7951 case MachO::MH_EXECUTE:
7952 outs() << " EXECUTE";
7953 break;
7954 case MachO::MH_FVMLIB:
7955 outs() << " FVMLIB";
7956 break;
7957 case MachO::MH_CORE:
7958 outs() << " CORE";
7959 break;
7960 case MachO::MH_PRELOAD:
7961 outs() << " PRELOAD";
7962 break;
7963 case MachO::MH_DYLIB:
7964 outs() << " DYLIB";
7965 break;
7966 case MachO::MH_DYLIB_STUB:
7967 outs() << " DYLIB_STUB";
7968 break;
7969 case MachO::MH_DYLINKER:
7970 outs() << " DYLINKER";
7971 break;
7972 case MachO::MH_BUNDLE:
7973 outs() << " BUNDLE";
7974 break;
7975 case MachO::MH_DSYM:
7976 outs() << " DSYM";
7977 break;
7978 case MachO::MH_KEXT_BUNDLE:
7979 outs() << " KEXTBUNDLE";
7980 break;
7981 default:
7982 outs() << format(" %10u", filetype);
7983 break;
7985 outs() << format(" %5u", ncmds);
7986 outs() << format(" %10u", sizeofcmds);
7987 uint32_t f = flags;
7988 if (f & MachO::MH_NOUNDEFS) {
7989 outs() << " NOUNDEFS";
7990 f &= ~MachO::MH_NOUNDEFS;
7992 if (f & MachO::MH_INCRLINK) {
7993 outs() << " INCRLINK";
7994 f &= ~MachO::MH_INCRLINK;
7996 if (f & MachO::MH_DYLDLINK) {
7997 outs() << " DYLDLINK";
7998 f &= ~MachO::MH_DYLDLINK;
8000 if (f & MachO::MH_BINDATLOAD) {
8001 outs() << " BINDATLOAD";
8002 f &= ~MachO::MH_BINDATLOAD;
8004 if (f & MachO::MH_PREBOUND) {
8005 outs() << " PREBOUND";
8006 f &= ~MachO::MH_PREBOUND;
8008 if (f & MachO::MH_SPLIT_SEGS) {
8009 outs() << " SPLIT_SEGS";
8010 f &= ~MachO::MH_SPLIT_SEGS;
8012 if (f & MachO::MH_LAZY_INIT) {
8013 outs() << " LAZY_INIT";
8014 f &= ~MachO::MH_LAZY_INIT;
8016 if (f & MachO::MH_TWOLEVEL) {
8017 outs() << " TWOLEVEL";
8018 f &= ~MachO::MH_TWOLEVEL;
8020 if (f & MachO::MH_FORCE_FLAT) {
8021 outs() << " FORCE_FLAT";
8022 f &= ~MachO::MH_FORCE_FLAT;
8024 if (f & MachO::MH_NOMULTIDEFS) {
8025 outs() << " NOMULTIDEFS";
8026 f &= ~MachO::MH_NOMULTIDEFS;
8028 if (f & MachO::MH_NOFIXPREBINDING) {
8029 outs() << " NOFIXPREBINDING";
8030 f &= ~MachO::MH_NOFIXPREBINDING;
8032 if (f & MachO::MH_PREBINDABLE) {
8033 outs() << " PREBINDABLE";
8034 f &= ~MachO::MH_PREBINDABLE;
8036 if (f & MachO::MH_ALLMODSBOUND) {
8037 outs() << " ALLMODSBOUND";
8038 f &= ~MachO::MH_ALLMODSBOUND;
8040 if (f & MachO::MH_SUBSECTIONS_VIA_SYMBOLS) {
8041 outs() << " SUBSECTIONS_VIA_SYMBOLS";
8042 f &= ~MachO::MH_SUBSECTIONS_VIA_SYMBOLS;
8044 if (f & MachO::MH_CANONICAL) {
8045 outs() << " CANONICAL";
8046 f &= ~MachO::MH_CANONICAL;
8048 if (f & MachO::MH_WEAK_DEFINES) {
8049 outs() << " WEAK_DEFINES";
8050 f &= ~MachO::MH_WEAK_DEFINES;
8052 if (f & MachO::MH_BINDS_TO_WEAK) {
8053 outs() << " BINDS_TO_WEAK";
8054 f &= ~MachO::MH_BINDS_TO_WEAK;
8056 if (f & MachO::MH_ALLOW_STACK_EXECUTION) {
8057 outs() << " ALLOW_STACK_EXECUTION";
8058 f &= ~MachO::MH_ALLOW_STACK_EXECUTION;
8060 if (f & MachO::MH_DEAD_STRIPPABLE_DYLIB) {
8061 outs() << " DEAD_STRIPPABLE_DYLIB";
8062 f &= ~MachO::MH_DEAD_STRIPPABLE_DYLIB;
8064 if (f & MachO::MH_PIE) {
8065 outs() << " PIE";
8066 f &= ~MachO::MH_PIE;
8068 if (f & MachO::MH_NO_REEXPORTED_DYLIBS) {
8069 outs() << " NO_REEXPORTED_DYLIBS";
8070 f &= ~MachO::MH_NO_REEXPORTED_DYLIBS;
8072 if (f & MachO::MH_HAS_TLV_DESCRIPTORS) {
8073 outs() << " MH_HAS_TLV_DESCRIPTORS";
8074 f &= ~MachO::MH_HAS_TLV_DESCRIPTORS;
8076 if (f & MachO::MH_NO_HEAP_EXECUTION) {
8077 outs() << " MH_NO_HEAP_EXECUTION";
8078 f &= ~MachO::MH_NO_HEAP_EXECUTION;
8080 if (f & MachO::MH_APP_EXTENSION_SAFE) {
8081 outs() << " APP_EXTENSION_SAFE";
8082 f &= ~MachO::MH_APP_EXTENSION_SAFE;
8084 if (f & MachO::MH_NLIST_OUTOFSYNC_WITH_DYLDINFO) {
8085 outs() << " NLIST_OUTOFSYNC_WITH_DYLDINFO";
8086 f &= ~MachO::MH_NLIST_OUTOFSYNC_WITH_DYLDINFO;
8088 if (f != 0 || flags == 0)
8089 outs() << format(" 0x%08" PRIx32, f);
8090 } else {
8091 outs() << format(" 0x%08" PRIx32, magic);
8092 outs() << format(" %7d", cputype);
8093 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
8094 outs() << format(" 0x%02" PRIx32,
8095 (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24);
8096 outs() << format(" %10u", filetype);
8097 outs() << format(" %5u", ncmds);
8098 outs() << format(" %10u", sizeofcmds);
8099 outs() << format(" 0x%08" PRIx32, flags);
8101 outs() << "\n";
8104 static void PrintSegmentCommand(uint32_t cmd, uint32_t cmdsize,
8105 StringRef SegName, uint64_t vmaddr,
8106 uint64_t vmsize, uint64_t fileoff,
8107 uint64_t filesize, uint32_t maxprot,
8108 uint32_t initprot, uint32_t nsects,
8109 uint32_t flags, uint32_t object_size,
8110 bool verbose) {
8111 uint64_t expected_cmdsize;
8112 if (cmd == MachO::LC_SEGMENT) {
8113 outs() << " cmd LC_SEGMENT\n";
8114 expected_cmdsize = nsects;
8115 expected_cmdsize *= sizeof(struct MachO::section);
8116 expected_cmdsize += sizeof(struct MachO::segment_command);
8117 } else {
8118 outs() << " cmd LC_SEGMENT_64\n";
8119 expected_cmdsize = nsects;
8120 expected_cmdsize *= sizeof(struct MachO::section_64);
8121 expected_cmdsize += sizeof(struct MachO::segment_command_64);
8123 outs() << " cmdsize " << cmdsize;
8124 if (cmdsize != expected_cmdsize)
8125 outs() << " Inconsistent size\n";
8126 else
8127 outs() << "\n";
8128 outs() << " segname " << SegName << "\n";
8129 if (cmd == MachO::LC_SEGMENT_64) {
8130 outs() << " vmaddr " << format("0x%016" PRIx64, vmaddr) << "\n";
8131 outs() << " vmsize " << format("0x%016" PRIx64, vmsize) << "\n";
8132 } else {
8133 outs() << " vmaddr " << format("0x%08" PRIx64, vmaddr) << "\n";
8134 outs() << " vmsize " << format("0x%08" PRIx64, vmsize) << "\n";
8136 outs() << " fileoff " << fileoff;
8137 if (fileoff > object_size)
8138 outs() << " (past end of file)\n";
8139 else
8140 outs() << "\n";
8141 outs() << " filesize " << filesize;
8142 if (fileoff + filesize > object_size)
8143 outs() << " (past end of file)\n";
8144 else
8145 outs() << "\n";
8146 if (verbose) {
8147 if ((maxprot &
8148 ~(MachO::VM_PROT_READ | MachO::VM_PROT_WRITE |
8149 MachO::VM_PROT_EXECUTE)) != 0)
8150 outs() << " maxprot ?" << format("0x%08" PRIx32, maxprot) << "\n";
8151 else {
8152 outs() << " maxprot ";
8153 outs() << ((maxprot & MachO::VM_PROT_READ) ? "r" : "-");
8154 outs() << ((maxprot & MachO::VM_PROT_WRITE) ? "w" : "-");
8155 outs() << ((maxprot & MachO::VM_PROT_EXECUTE) ? "x\n" : "-\n");
8157 if ((initprot &
8158 ~(MachO::VM_PROT_READ | MachO::VM_PROT_WRITE |
8159 MachO::VM_PROT_EXECUTE)) != 0)
8160 outs() << " initprot ?" << format("0x%08" PRIx32, initprot) << "\n";
8161 else {
8162 outs() << " initprot ";
8163 outs() << ((initprot & MachO::VM_PROT_READ) ? "r" : "-");
8164 outs() << ((initprot & MachO::VM_PROT_WRITE) ? "w" : "-");
8165 outs() << ((initprot & MachO::VM_PROT_EXECUTE) ? "x\n" : "-\n");
8167 } else {
8168 outs() << " maxprot " << format("0x%08" PRIx32, maxprot) << "\n";
8169 outs() << " initprot " << format("0x%08" PRIx32, initprot) << "\n";
8171 outs() << " nsects " << nsects << "\n";
8172 if (verbose) {
8173 outs() << " flags";
8174 if (flags == 0)
8175 outs() << " (none)\n";
8176 else {
8177 if (flags & MachO::SG_HIGHVM) {
8178 outs() << " HIGHVM";
8179 flags &= ~MachO::SG_HIGHVM;
8181 if (flags & MachO::SG_FVMLIB) {
8182 outs() << " FVMLIB";
8183 flags &= ~MachO::SG_FVMLIB;
8185 if (flags & MachO::SG_NORELOC) {
8186 outs() << " NORELOC";
8187 flags &= ~MachO::SG_NORELOC;
8189 if (flags & MachO::SG_PROTECTED_VERSION_1) {
8190 outs() << " PROTECTED_VERSION_1";
8191 flags &= ~MachO::SG_PROTECTED_VERSION_1;
8193 if (flags)
8194 outs() << format(" 0x%08" PRIx32, flags) << " (unknown flags)\n";
8195 else
8196 outs() << "\n";
8198 } else {
8199 outs() << " flags " << format("0x%" PRIx32, flags) << "\n";
8203 static void PrintSection(const char *sectname, const char *segname,
8204 uint64_t addr, uint64_t size, uint32_t offset,
8205 uint32_t align, uint32_t reloff, uint32_t nreloc,
8206 uint32_t flags, uint32_t reserved1, uint32_t reserved2,
8207 uint32_t cmd, const char *sg_segname,
8208 uint32_t filetype, uint32_t object_size,
8209 bool verbose) {
8210 outs() << "Section\n";
8211 outs() << " sectname " << format("%.16s\n", sectname);
8212 outs() << " segname " << format("%.16s", segname);
8213 if (filetype != MachO::MH_OBJECT && strncmp(sg_segname, segname, 16) != 0)
8214 outs() << " (does not match segment)\n";
8215 else
8216 outs() << "\n";
8217 if (cmd == MachO::LC_SEGMENT_64) {
8218 outs() << " addr " << format("0x%016" PRIx64, addr) << "\n";
8219 outs() << " size " << format("0x%016" PRIx64, size);
8220 } else {
8221 outs() << " addr " << format("0x%08" PRIx64, addr) << "\n";
8222 outs() << " size " << format("0x%08" PRIx64, size);
8224 if ((flags & MachO::S_ZEROFILL) != 0 && offset + size > object_size)
8225 outs() << " (past end of file)\n";
8226 else
8227 outs() << "\n";
8228 outs() << " offset " << offset;
8229 if (offset > object_size)
8230 outs() << " (past end of file)\n";
8231 else
8232 outs() << "\n";
8233 uint32_t align_shifted = 1 << align;
8234 outs() << " align 2^" << align << " (" << align_shifted << ")\n";
8235 outs() << " reloff " << reloff;
8236 if (reloff > object_size)
8237 outs() << " (past end of file)\n";
8238 else
8239 outs() << "\n";
8240 outs() << " nreloc " << nreloc;
8241 if (reloff + nreloc * sizeof(struct MachO::relocation_info) > object_size)
8242 outs() << " (past end of file)\n";
8243 else
8244 outs() << "\n";
8245 uint32_t section_type = flags & MachO::SECTION_TYPE;
8246 if (verbose) {
8247 outs() << " type";
8248 if (section_type == MachO::S_REGULAR)
8249 outs() << " S_REGULAR\n";
8250 else if (section_type == MachO::S_ZEROFILL)
8251 outs() << " S_ZEROFILL\n";
8252 else if (section_type == MachO::S_CSTRING_LITERALS)
8253 outs() << " S_CSTRING_LITERALS\n";
8254 else if (section_type == MachO::S_4BYTE_LITERALS)
8255 outs() << " S_4BYTE_LITERALS\n";
8256 else if (section_type == MachO::S_8BYTE_LITERALS)
8257 outs() << " S_8BYTE_LITERALS\n";
8258 else if (section_type == MachO::S_16BYTE_LITERALS)
8259 outs() << " S_16BYTE_LITERALS\n";
8260 else if (section_type == MachO::S_LITERAL_POINTERS)
8261 outs() << " S_LITERAL_POINTERS\n";
8262 else if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS)
8263 outs() << " S_NON_LAZY_SYMBOL_POINTERS\n";
8264 else if (section_type == MachO::S_LAZY_SYMBOL_POINTERS)
8265 outs() << " S_LAZY_SYMBOL_POINTERS\n";
8266 else if (section_type == MachO::S_SYMBOL_STUBS)
8267 outs() << " S_SYMBOL_STUBS\n";
8268 else if (section_type == MachO::S_MOD_INIT_FUNC_POINTERS)
8269 outs() << " S_MOD_INIT_FUNC_POINTERS\n";
8270 else if (section_type == MachO::S_MOD_TERM_FUNC_POINTERS)
8271 outs() << " S_MOD_TERM_FUNC_POINTERS\n";
8272 else if (section_type == MachO::S_COALESCED)
8273 outs() << " S_COALESCED\n";
8274 else if (section_type == MachO::S_INTERPOSING)
8275 outs() << " S_INTERPOSING\n";
8276 else if (section_type == MachO::S_DTRACE_DOF)
8277 outs() << " S_DTRACE_DOF\n";
8278 else if (section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS)
8279 outs() << " S_LAZY_DYLIB_SYMBOL_POINTERS\n";
8280 else if (section_type == MachO::S_THREAD_LOCAL_REGULAR)
8281 outs() << " S_THREAD_LOCAL_REGULAR\n";
8282 else if (section_type == MachO::S_THREAD_LOCAL_ZEROFILL)
8283 outs() << " S_THREAD_LOCAL_ZEROFILL\n";
8284 else if (section_type == MachO::S_THREAD_LOCAL_VARIABLES)
8285 outs() << " S_THREAD_LOCAL_VARIABLES\n";
8286 else if (section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS)
8287 outs() << " S_THREAD_LOCAL_VARIABLE_POINTERS\n";
8288 else if (section_type == MachO::S_THREAD_LOCAL_INIT_FUNCTION_POINTERS)
8289 outs() << " S_THREAD_LOCAL_INIT_FUNCTION_POINTERS\n";
8290 else
8291 outs() << format("0x%08" PRIx32, section_type) << "\n";
8292 outs() << "attributes";
8293 uint32_t section_attributes = flags & MachO::SECTION_ATTRIBUTES;
8294 if (section_attributes & MachO::S_ATTR_PURE_INSTRUCTIONS)
8295 outs() << " PURE_INSTRUCTIONS";
8296 if (section_attributes & MachO::S_ATTR_NO_TOC)
8297 outs() << " NO_TOC";
8298 if (section_attributes & MachO::S_ATTR_STRIP_STATIC_SYMS)
8299 outs() << " STRIP_STATIC_SYMS";
8300 if (section_attributes & MachO::S_ATTR_NO_DEAD_STRIP)
8301 outs() << " NO_DEAD_STRIP";
8302 if (section_attributes & MachO::S_ATTR_LIVE_SUPPORT)
8303 outs() << " LIVE_SUPPORT";
8304 if (section_attributes & MachO::S_ATTR_SELF_MODIFYING_CODE)
8305 outs() << " SELF_MODIFYING_CODE";
8306 if (section_attributes & MachO::S_ATTR_DEBUG)
8307 outs() << " DEBUG";
8308 if (section_attributes & MachO::S_ATTR_SOME_INSTRUCTIONS)
8309 outs() << " SOME_INSTRUCTIONS";
8310 if (section_attributes & MachO::S_ATTR_EXT_RELOC)
8311 outs() << " EXT_RELOC";
8312 if (section_attributes & MachO::S_ATTR_LOC_RELOC)
8313 outs() << " LOC_RELOC";
8314 if (section_attributes == 0)
8315 outs() << " (none)";
8316 outs() << "\n";
8317 } else
8318 outs() << " flags " << format("0x%08" PRIx32, flags) << "\n";
8319 outs() << " reserved1 " << reserved1;
8320 if (section_type == MachO::S_SYMBOL_STUBS ||
8321 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
8322 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
8323 section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
8324 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS)
8325 outs() << " (index into indirect symbol table)\n";
8326 else
8327 outs() << "\n";
8328 outs() << " reserved2 " << reserved2;
8329 if (section_type == MachO::S_SYMBOL_STUBS)
8330 outs() << " (size of stubs)\n";
8331 else
8332 outs() << "\n";
8335 static void PrintSymtabLoadCommand(MachO::symtab_command st, bool Is64Bit,
8336 uint32_t object_size) {
8337 outs() << " cmd LC_SYMTAB\n";
8338 outs() << " cmdsize " << st.cmdsize;
8339 if (st.cmdsize != sizeof(struct MachO::symtab_command))
8340 outs() << " Incorrect size\n";
8341 else
8342 outs() << "\n";
8343 outs() << " symoff " << st.symoff;
8344 if (st.symoff > object_size)
8345 outs() << " (past end of file)\n";
8346 else
8347 outs() << "\n";
8348 outs() << " nsyms " << st.nsyms;
8349 uint64_t big_size;
8350 if (Is64Bit) {
8351 big_size = st.nsyms;
8352 big_size *= sizeof(struct MachO::nlist_64);
8353 big_size += st.symoff;
8354 if (big_size > object_size)
8355 outs() << " (past end of file)\n";
8356 else
8357 outs() << "\n";
8358 } else {
8359 big_size = st.nsyms;
8360 big_size *= sizeof(struct MachO::nlist);
8361 big_size += st.symoff;
8362 if (big_size > object_size)
8363 outs() << " (past end of file)\n";
8364 else
8365 outs() << "\n";
8367 outs() << " stroff " << st.stroff;
8368 if (st.stroff > object_size)
8369 outs() << " (past end of file)\n";
8370 else
8371 outs() << "\n";
8372 outs() << " strsize " << st.strsize;
8373 big_size = st.stroff;
8374 big_size += st.strsize;
8375 if (big_size > object_size)
8376 outs() << " (past end of file)\n";
8377 else
8378 outs() << "\n";
8381 static void PrintDysymtabLoadCommand(MachO::dysymtab_command dyst,
8382 uint32_t nsyms, uint32_t object_size,
8383 bool Is64Bit) {
8384 outs() << " cmd LC_DYSYMTAB\n";
8385 outs() << " cmdsize " << dyst.cmdsize;
8386 if (dyst.cmdsize != sizeof(struct MachO::dysymtab_command))
8387 outs() << " Incorrect size\n";
8388 else
8389 outs() << "\n";
8390 outs() << " ilocalsym " << dyst.ilocalsym;
8391 if (dyst.ilocalsym > nsyms)
8392 outs() << " (greater than the number of symbols)\n";
8393 else
8394 outs() << "\n";
8395 outs() << " nlocalsym " << dyst.nlocalsym;
8396 uint64_t big_size;
8397 big_size = dyst.ilocalsym;
8398 big_size += dyst.nlocalsym;
8399 if (big_size > nsyms)
8400 outs() << " (past the end of the symbol table)\n";
8401 else
8402 outs() << "\n";
8403 outs() << " iextdefsym " << dyst.iextdefsym;
8404 if (dyst.iextdefsym > nsyms)
8405 outs() << " (greater than the number of symbols)\n";
8406 else
8407 outs() << "\n";
8408 outs() << " nextdefsym " << dyst.nextdefsym;
8409 big_size = dyst.iextdefsym;
8410 big_size += dyst.nextdefsym;
8411 if (big_size > nsyms)
8412 outs() << " (past the end of the symbol table)\n";
8413 else
8414 outs() << "\n";
8415 outs() << " iundefsym " << dyst.iundefsym;
8416 if (dyst.iundefsym > nsyms)
8417 outs() << " (greater than the number of symbols)\n";
8418 else
8419 outs() << "\n";
8420 outs() << " nundefsym " << dyst.nundefsym;
8421 big_size = dyst.iundefsym;
8422 big_size += dyst.nundefsym;
8423 if (big_size > nsyms)
8424 outs() << " (past the end of the symbol table)\n";
8425 else
8426 outs() << "\n";
8427 outs() << " tocoff " << dyst.tocoff;
8428 if (dyst.tocoff > object_size)
8429 outs() << " (past end of file)\n";
8430 else
8431 outs() << "\n";
8432 outs() << " ntoc " << dyst.ntoc;
8433 big_size = dyst.ntoc;
8434 big_size *= sizeof(struct MachO::dylib_table_of_contents);
8435 big_size += dyst.tocoff;
8436 if (big_size > object_size)
8437 outs() << " (past end of file)\n";
8438 else
8439 outs() << "\n";
8440 outs() << " modtaboff " << dyst.modtaboff;
8441 if (dyst.modtaboff > object_size)
8442 outs() << " (past end of file)\n";
8443 else
8444 outs() << "\n";
8445 outs() << " nmodtab " << dyst.nmodtab;
8446 uint64_t modtabend;
8447 if (Is64Bit) {
8448 modtabend = dyst.nmodtab;
8449 modtabend *= sizeof(struct MachO::dylib_module_64);
8450 modtabend += dyst.modtaboff;
8451 } else {
8452 modtabend = dyst.nmodtab;
8453 modtabend *= sizeof(struct MachO::dylib_module);
8454 modtabend += dyst.modtaboff;
8456 if (modtabend > object_size)
8457 outs() << " (past end of file)\n";
8458 else
8459 outs() << "\n";
8460 outs() << " extrefsymoff " << dyst.extrefsymoff;
8461 if (dyst.extrefsymoff > object_size)
8462 outs() << " (past end of file)\n";
8463 else
8464 outs() << "\n";
8465 outs() << " nextrefsyms " << dyst.nextrefsyms;
8466 big_size = dyst.nextrefsyms;
8467 big_size *= sizeof(struct MachO::dylib_reference);
8468 big_size += dyst.extrefsymoff;
8469 if (big_size > object_size)
8470 outs() << " (past end of file)\n";
8471 else
8472 outs() << "\n";
8473 outs() << " indirectsymoff " << dyst.indirectsymoff;
8474 if (dyst.indirectsymoff > object_size)
8475 outs() << " (past end of file)\n";
8476 else
8477 outs() << "\n";
8478 outs() << " nindirectsyms " << dyst.nindirectsyms;
8479 big_size = dyst.nindirectsyms;
8480 big_size *= sizeof(uint32_t);
8481 big_size += dyst.indirectsymoff;
8482 if (big_size > object_size)
8483 outs() << " (past end of file)\n";
8484 else
8485 outs() << "\n";
8486 outs() << " extreloff " << dyst.extreloff;
8487 if (dyst.extreloff > object_size)
8488 outs() << " (past end of file)\n";
8489 else
8490 outs() << "\n";
8491 outs() << " nextrel " << dyst.nextrel;
8492 big_size = dyst.nextrel;
8493 big_size *= sizeof(struct MachO::relocation_info);
8494 big_size += dyst.extreloff;
8495 if (big_size > object_size)
8496 outs() << " (past end of file)\n";
8497 else
8498 outs() << "\n";
8499 outs() << " locreloff " << dyst.locreloff;
8500 if (dyst.locreloff > object_size)
8501 outs() << " (past end of file)\n";
8502 else
8503 outs() << "\n";
8504 outs() << " nlocrel " << dyst.nlocrel;
8505 big_size = dyst.nlocrel;
8506 big_size *= sizeof(struct MachO::relocation_info);
8507 big_size += dyst.locreloff;
8508 if (big_size > object_size)
8509 outs() << " (past end of file)\n";
8510 else
8511 outs() << "\n";
8514 static void PrintDyldInfoLoadCommand(MachO::dyld_info_command dc,
8515 uint32_t object_size) {
8516 if (dc.cmd == MachO::LC_DYLD_INFO)
8517 outs() << " cmd LC_DYLD_INFO\n";
8518 else
8519 outs() << " cmd LC_DYLD_INFO_ONLY\n";
8520 outs() << " cmdsize " << dc.cmdsize;
8521 if (dc.cmdsize != sizeof(struct MachO::dyld_info_command))
8522 outs() << " Incorrect size\n";
8523 else
8524 outs() << "\n";
8525 outs() << " rebase_off " << dc.rebase_off;
8526 if (dc.rebase_off > object_size)
8527 outs() << " (past end of file)\n";
8528 else
8529 outs() << "\n";
8530 outs() << " rebase_size " << dc.rebase_size;
8531 uint64_t big_size;
8532 big_size = dc.rebase_off;
8533 big_size += dc.rebase_size;
8534 if (big_size > object_size)
8535 outs() << " (past end of file)\n";
8536 else
8537 outs() << "\n";
8538 outs() << " bind_off " << dc.bind_off;
8539 if (dc.bind_off > object_size)
8540 outs() << " (past end of file)\n";
8541 else
8542 outs() << "\n";
8543 outs() << " bind_size " << dc.bind_size;
8544 big_size = dc.bind_off;
8545 big_size += dc.bind_size;
8546 if (big_size > object_size)
8547 outs() << " (past end of file)\n";
8548 else
8549 outs() << "\n";
8550 outs() << " weak_bind_off " << dc.weak_bind_off;
8551 if (dc.weak_bind_off > object_size)
8552 outs() << " (past end of file)\n";
8553 else
8554 outs() << "\n";
8555 outs() << " weak_bind_size " << dc.weak_bind_size;
8556 big_size = dc.weak_bind_off;
8557 big_size += dc.weak_bind_size;
8558 if (big_size > object_size)
8559 outs() << " (past end of file)\n";
8560 else
8561 outs() << "\n";
8562 outs() << " lazy_bind_off " << dc.lazy_bind_off;
8563 if (dc.lazy_bind_off > object_size)
8564 outs() << " (past end of file)\n";
8565 else
8566 outs() << "\n";
8567 outs() << " lazy_bind_size " << dc.lazy_bind_size;
8568 big_size = dc.lazy_bind_off;
8569 big_size += dc.lazy_bind_size;
8570 if (big_size > object_size)
8571 outs() << " (past end of file)\n";
8572 else
8573 outs() << "\n";
8574 outs() << " export_off " << dc.export_off;
8575 if (dc.export_off > object_size)
8576 outs() << " (past end of file)\n";
8577 else
8578 outs() << "\n";
8579 outs() << " export_size " << dc.export_size;
8580 big_size = dc.export_off;
8581 big_size += dc.export_size;
8582 if (big_size > object_size)
8583 outs() << " (past end of file)\n";
8584 else
8585 outs() << "\n";
8588 static void PrintDyldLoadCommand(MachO::dylinker_command dyld,
8589 const char *Ptr) {
8590 if (dyld.cmd == MachO::LC_ID_DYLINKER)
8591 outs() << " cmd LC_ID_DYLINKER\n";
8592 else if (dyld.cmd == MachO::LC_LOAD_DYLINKER)
8593 outs() << " cmd LC_LOAD_DYLINKER\n";
8594 else if (dyld.cmd == MachO::LC_DYLD_ENVIRONMENT)
8595 outs() << " cmd LC_DYLD_ENVIRONMENT\n";
8596 else
8597 outs() << " cmd ?(" << dyld.cmd << ")\n";
8598 outs() << " cmdsize " << dyld.cmdsize;
8599 if (dyld.cmdsize < sizeof(struct MachO::dylinker_command))
8600 outs() << " Incorrect size\n";
8601 else
8602 outs() << "\n";
8603 if (dyld.name >= dyld.cmdsize)
8604 outs() << " name ?(bad offset " << dyld.name << ")\n";
8605 else {
8606 const char *P = (const char *)(Ptr) + dyld.name;
8607 outs() << " name " << P << " (offset " << dyld.name << ")\n";
8611 static void PrintUuidLoadCommand(MachO::uuid_command uuid) {
8612 outs() << " cmd LC_UUID\n";
8613 outs() << " cmdsize " << uuid.cmdsize;
8614 if (uuid.cmdsize != sizeof(struct MachO::uuid_command))
8615 outs() << " Incorrect size\n";
8616 else
8617 outs() << "\n";
8618 outs() << " uuid ";
8619 for (int i = 0; i < 16; ++i) {
8620 outs() << format("%02" PRIX32, uuid.uuid[i]);
8621 if (i == 3 || i == 5 || i == 7 || i == 9)
8622 outs() << "-";
8624 outs() << "\n";
8627 static void PrintRpathLoadCommand(MachO::rpath_command rpath, const char *Ptr) {
8628 outs() << " cmd LC_RPATH\n";
8629 outs() << " cmdsize " << rpath.cmdsize;
8630 if (rpath.cmdsize < sizeof(struct MachO::rpath_command))
8631 outs() << " Incorrect size\n";
8632 else
8633 outs() << "\n";
8634 if (rpath.path >= rpath.cmdsize)
8635 outs() << " path ?(bad offset " << rpath.path << ")\n";
8636 else {
8637 const char *P = (const char *)(Ptr) + rpath.path;
8638 outs() << " path " << P << " (offset " << rpath.path << ")\n";
8642 static void PrintVersionMinLoadCommand(MachO::version_min_command vd) {
8643 StringRef LoadCmdName;
8644 switch (vd.cmd) {
8645 case MachO::LC_VERSION_MIN_MACOSX:
8646 LoadCmdName = "LC_VERSION_MIN_MACOSX";
8647 break;
8648 case MachO::LC_VERSION_MIN_IPHONEOS:
8649 LoadCmdName = "LC_VERSION_MIN_IPHONEOS";
8650 break;
8651 case MachO::LC_VERSION_MIN_TVOS:
8652 LoadCmdName = "LC_VERSION_MIN_TVOS";
8653 break;
8654 case MachO::LC_VERSION_MIN_WATCHOS:
8655 LoadCmdName = "LC_VERSION_MIN_WATCHOS";
8656 break;
8657 default:
8658 llvm_unreachable("Unknown version min load command");
8661 outs() << " cmd " << LoadCmdName << '\n';
8662 outs() << " cmdsize " << vd.cmdsize;
8663 if (vd.cmdsize != sizeof(struct MachO::version_min_command))
8664 outs() << " Incorrect size\n";
8665 else
8666 outs() << "\n";
8667 outs() << " version "
8668 << MachOObjectFile::getVersionMinMajor(vd, false) << "."
8669 << MachOObjectFile::getVersionMinMinor(vd, false);
8670 uint32_t Update = MachOObjectFile::getVersionMinUpdate(vd, false);
8671 if (Update != 0)
8672 outs() << "." << Update;
8673 outs() << "\n";
8674 if (vd.sdk == 0)
8675 outs() << " sdk n/a";
8676 else {
8677 outs() << " sdk "
8678 << MachOObjectFile::getVersionMinMajor(vd, true) << "."
8679 << MachOObjectFile::getVersionMinMinor(vd, true);
8681 Update = MachOObjectFile::getVersionMinUpdate(vd, true);
8682 if (Update != 0)
8683 outs() << "." << Update;
8684 outs() << "\n";
8687 static void PrintNoteLoadCommand(MachO::note_command Nt) {
8688 outs() << " cmd LC_NOTE\n";
8689 outs() << " cmdsize " << Nt.cmdsize;
8690 if (Nt.cmdsize != sizeof(struct MachO::note_command))
8691 outs() << " Incorrect size\n";
8692 else
8693 outs() << "\n";
8694 const char *d = Nt.data_owner;
8695 outs() << "data_owner " << format("%.16s\n", d);
8696 outs() << " offset " << Nt.offset << "\n";
8697 outs() << " size " << Nt.size << "\n";
8700 static void PrintBuildToolVersion(MachO::build_tool_version bv) {
8701 outs() << " tool " << MachOObjectFile::getBuildTool(bv.tool) << "\n";
8702 outs() << " version " << MachOObjectFile::getVersionString(bv.version)
8703 << "\n";
8706 static void PrintBuildVersionLoadCommand(const MachOObjectFile *obj,
8707 MachO::build_version_command bd) {
8708 outs() << " cmd LC_BUILD_VERSION\n";
8709 outs() << " cmdsize " << bd.cmdsize;
8710 if (bd.cmdsize !=
8711 sizeof(struct MachO::build_version_command) +
8712 bd.ntools * sizeof(struct MachO::build_tool_version))
8713 outs() << " Incorrect size\n";
8714 else
8715 outs() << "\n";
8716 outs() << " platform " << MachOObjectFile::getBuildPlatform(bd.platform)
8717 << "\n";
8718 if (bd.sdk)
8719 outs() << " sdk " << MachOObjectFile::getVersionString(bd.sdk)
8720 << "\n";
8721 else
8722 outs() << " sdk n/a\n";
8723 outs() << " minos " << MachOObjectFile::getVersionString(bd.minos)
8724 << "\n";
8725 outs() << " ntools " << bd.ntools << "\n";
8726 for (unsigned i = 0; i < bd.ntools; ++i) {
8727 MachO::build_tool_version bv = obj->getBuildToolVersion(i);
8728 PrintBuildToolVersion(bv);
8732 static void PrintSourceVersionCommand(MachO::source_version_command sd) {
8733 outs() << " cmd LC_SOURCE_VERSION\n";
8734 outs() << " cmdsize " << sd.cmdsize;
8735 if (sd.cmdsize != sizeof(struct MachO::source_version_command))
8736 outs() << " Incorrect size\n";
8737 else
8738 outs() << "\n";
8739 uint64_t a = (sd.version >> 40) & 0xffffff;
8740 uint64_t b = (sd.version >> 30) & 0x3ff;
8741 uint64_t c = (sd.version >> 20) & 0x3ff;
8742 uint64_t d = (sd.version >> 10) & 0x3ff;
8743 uint64_t e = sd.version & 0x3ff;
8744 outs() << " version " << a << "." << b;
8745 if (e != 0)
8746 outs() << "." << c << "." << d << "." << e;
8747 else if (d != 0)
8748 outs() << "." << c << "." << d;
8749 else if (c != 0)
8750 outs() << "." << c;
8751 outs() << "\n";
8754 static void PrintEntryPointCommand(MachO::entry_point_command ep) {
8755 outs() << " cmd LC_MAIN\n";
8756 outs() << " cmdsize " << ep.cmdsize;
8757 if (ep.cmdsize != sizeof(struct MachO::entry_point_command))
8758 outs() << " Incorrect size\n";
8759 else
8760 outs() << "\n";
8761 outs() << " entryoff " << ep.entryoff << "\n";
8762 outs() << " stacksize " << ep.stacksize << "\n";
8765 static void PrintEncryptionInfoCommand(MachO::encryption_info_command ec,
8766 uint32_t object_size) {
8767 outs() << " cmd LC_ENCRYPTION_INFO\n";
8768 outs() << " cmdsize " << ec.cmdsize;
8769 if (ec.cmdsize != sizeof(struct MachO::encryption_info_command))
8770 outs() << " Incorrect size\n";
8771 else
8772 outs() << "\n";
8773 outs() << " cryptoff " << ec.cryptoff;
8774 if (ec.cryptoff > object_size)
8775 outs() << " (past end of file)\n";
8776 else
8777 outs() << "\n";
8778 outs() << " cryptsize " << ec.cryptsize;
8779 if (ec.cryptsize > object_size)
8780 outs() << " (past end of file)\n";
8781 else
8782 outs() << "\n";
8783 outs() << " cryptid " << ec.cryptid << "\n";
8786 static void PrintEncryptionInfoCommand64(MachO::encryption_info_command_64 ec,
8787 uint32_t object_size) {
8788 outs() << " cmd LC_ENCRYPTION_INFO_64\n";
8789 outs() << " cmdsize " << ec.cmdsize;
8790 if (ec.cmdsize != sizeof(struct MachO::encryption_info_command_64))
8791 outs() << " Incorrect size\n";
8792 else
8793 outs() << "\n";
8794 outs() << " cryptoff " << ec.cryptoff;
8795 if (ec.cryptoff > object_size)
8796 outs() << " (past end of file)\n";
8797 else
8798 outs() << "\n";
8799 outs() << " cryptsize " << ec.cryptsize;
8800 if (ec.cryptsize > object_size)
8801 outs() << " (past end of file)\n";
8802 else
8803 outs() << "\n";
8804 outs() << " cryptid " << ec.cryptid << "\n";
8805 outs() << " pad " << ec.pad << "\n";
8808 static void PrintLinkerOptionCommand(MachO::linker_option_command lo,
8809 const char *Ptr) {
8810 outs() << " cmd LC_LINKER_OPTION\n";
8811 outs() << " cmdsize " << lo.cmdsize;
8812 if (lo.cmdsize < sizeof(struct MachO::linker_option_command))
8813 outs() << " Incorrect size\n";
8814 else
8815 outs() << "\n";
8816 outs() << " count " << lo.count << "\n";
8817 const char *string = Ptr + sizeof(struct MachO::linker_option_command);
8818 uint32_t left = lo.cmdsize - sizeof(struct MachO::linker_option_command);
8819 uint32_t i = 0;
8820 while (left > 0) {
8821 while (*string == '\0' && left > 0) {
8822 string++;
8823 left--;
8825 if (left > 0) {
8826 i++;
8827 outs() << " string #" << i << " " << format("%.*s\n", left, string);
8828 uint32_t NullPos = StringRef(string, left).find('\0');
8829 uint32_t len = std::min(NullPos, left) + 1;
8830 string += len;
8831 left -= len;
8834 if (lo.count != i)
8835 outs() << " count " << lo.count << " does not match number of strings "
8836 << i << "\n";
8839 static void PrintSubFrameworkCommand(MachO::sub_framework_command sub,
8840 const char *Ptr) {
8841 outs() << " cmd LC_SUB_FRAMEWORK\n";
8842 outs() << " cmdsize " << sub.cmdsize;
8843 if (sub.cmdsize < sizeof(struct MachO::sub_framework_command))
8844 outs() << " Incorrect size\n";
8845 else
8846 outs() << "\n";
8847 if (sub.umbrella < sub.cmdsize) {
8848 const char *P = Ptr + sub.umbrella;
8849 outs() << " umbrella " << P << " (offset " << sub.umbrella << ")\n";
8850 } else {
8851 outs() << " umbrella ?(bad offset " << sub.umbrella << ")\n";
8855 static void PrintSubUmbrellaCommand(MachO::sub_umbrella_command sub,
8856 const char *Ptr) {
8857 outs() << " cmd LC_SUB_UMBRELLA\n";
8858 outs() << " cmdsize " << sub.cmdsize;
8859 if (sub.cmdsize < sizeof(struct MachO::sub_umbrella_command))
8860 outs() << " Incorrect size\n";
8861 else
8862 outs() << "\n";
8863 if (sub.sub_umbrella < sub.cmdsize) {
8864 const char *P = Ptr + sub.sub_umbrella;
8865 outs() << " sub_umbrella " << P << " (offset " << sub.sub_umbrella << ")\n";
8866 } else {
8867 outs() << " sub_umbrella ?(bad offset " << sub.sub_umbrella << ")\n";
8871 static void PrintSubLibraryCommand(MachO::sub_library_command sub,
8872 const char *Ptr) {
8873 outs() << " cmd LC_SUB_LIBRARY\n";
8874 outs() << " cmdsize " << sub.cmdsize;
8875 if (sub.cmdsize < sizeof(struct MachO::sub_library_command))
8876 outs() << " Incorrect size\n";
8877 else
8878 outs() << "\n";
8879 if (sub.sub_library < sub.cmdsize) {
8880 const char *P = Ptr + sub.sub_library;
8881 outs() << " sub_library " << P << " (offset " << sub.sub_library << ")\n";
8882 } else {
8883 outs() << " sub_library ?(bad offset " << sub.sub_library << ")\n";
8887 static void PrintSubClientCommand(MachO::sub_client_command sub,
8888 const char *Ptr) {
8889 outs() << " cmd LC_SUB_CLIENT\n";
8890 outs() << " cmdsize " << sub.cmdsize;
8891 if (sub.cmdsize < sizeof(struct MachO::sub_client_command))
8892 outs() << " Incorrect size\n";
8893 else
8894 outs() << "\n";
8895 if (sub.client < sub.cmdsize) {
8896 const char *P = Ptr + sub.client;
8897 outs() << " client " << P << " (offset " << sub.client << ")\n";
8898 } else {
8899 outs() << " client ?(bad offset " << sub.client << ")\n";
8903 static void PrintRoutinesCommand(MachO::routines_command r) {
8904 outs() << " cmd LC_ROUTINES\n";
8905 outs() << " cmdsize " << r.cmdsize;
8906 if (r.cmdsize != sizeof(struct MachO::routines_command))
8907 outs() << " Incorrect size\n";
8908 else
8909 outs() << "\n";
8910 outs() << " init_address " << format("0x%08" PRIx32, r.init_address) << "\n";
8911 outs() << " init_module " << r.init_module << "\n";
8912 outs() << " reserved1 " << r.reserved1 << "\n";
8913 outs() << " reserved2 " << r.reserved2 << "\n";
8914 outs() << " reserved3 " << r.reserved3 << "\n";
8915 outs() << " reserved4 " << r.reserved4 << "\n";
8916 outs() << " reserved5 " << r.reserved5 << "\n";
8917 outs() << " reserved6 " << r.reserved6 << "\n";
8920 static void PrintRoutinesCommand64(MachO::routines_command_64 r) {
8921 outs() << " cmd LC_ROUTINES_64\n";
8922 outs() << " cmdsize " << r.cmdsize;
8923 if (r.cmdsize != sizeof(struct MachO::routines_command_64))
8924 outs() << " Incorrect size\n";
8925 else
8926 outs() << "\n";
8927 outs() << " init_address " << format("0x%016" PRIx64, r.init_address) << "\n";
8928 outs() << " init_module " << r.init_module << "\n";
8929 outs() << " reserved1 " << r.reserved1 << "\n";
8930 outs() << " reserved2 " << r.reserved2 << "\n";
8931 outs() << " reserved3 " << r.reserved3 << "\n";
8932 outs() << " reserved4 " << r.reserved4 << "\n";
8933 outs() << " reserved5 " << r.reserved5 << "\n";
8934 outs() << " reserved6 " << r.reserved6 << "\n";
8937 static void Print_x86_thread_state32_t(MachO::x86_thread_state32_t &cpu32) {
8938 outs() << "\t eax " << format("0x%08" PRIx32, cpu32.eax);
8939 outs() << " ebx " << format("0x%08" PRIx32, cpu32.ebx);
8940 outs() << " ecx " << format("0x%08" PRIx32, cpu32.ecx);
8941 outs() << " edx " << format("0x%08" PRIx32, cpu32.edx) << "\n";
8942 outs() << "\t edi " << format("0x%08" PRIx32, cpu32.edi);
8943 outs() << " esi " << format("0x%08" PRIx32, cpu32.esi);
8944 outs() << " ebp " << format("0x%08" PRIx32, cpu32.ebp);
8945 outs() << " esp " << format("0x%08" PRIx32, cpu32.esp) << "\n";
8946 outs() << "\t ss " << format("0x%08" PRIx32, cpu32.ss);
8947 outs() << " eflags " << format("0x%08" PRIx32, cpu32.eflags);
8948 outs() << " eip " << format("0x%08" PRIx32, cpu32.eip);
8949 outs() << " cs " << format("0x%08" PRIx32, cpu32.cs) << "\n";
8950 outs() << "\t ds " << format("0x%08" PRIx32, cpu32.ds);
8951 outs() << " es " << format("0x%08" PRIx32, cpu32.es);
8952 outs() << " fs " << format("0x%08" PRIx32, cpu32.fs);
8953 outs() << " gs " << format("0x%08" PRIx32, cpu32.gs) << "\n";
8956 static void Print_x86_thread_state64_t(MachO::x86_thread_state64_t &cpu64) {
8957 outs() << " rax " << format("0x%016" PRIx64, cpu64.rax);
8958 outs() << " rbx " << format("0x%016" PRIx64, cpu64.rbx);
8959 outs() << " rcx " << format("0x%016" PRIx64, cpu64.rcx) << "\n";
8960 outs() << " rdx " << format("0x%016" PRIx64, cpu64.rdx);
8961 outs() << " rdi " << format("0x%016" PRIx64, cpu64.rdi);
8962 outs() << " rsi " << format("0x%016" PRIx64, cpu64.rsi) << "\n";
8963 outs() << " rbp " << format("0x%016" PRIx64, cpu64.rbp);
8964 outs() << " rsp " << format("0x%016" PRIx64, cpu64.rsp);
8965 outs() << " r8 " << format("0x%016" PRIx64, cpu64.r8) << "\n";
8966 outs() << " r9 " << format("0x%016" PRIx64, cpu64.r9);
8967 outs() << " r10 " << format("0x%016" PRIx64, cpu64.r10);
8968 outs() << " r11 " << format("0x%016" PRIx64, cpu64.r11) << "\n";
8969 outs() << " r12 " << format("0x%016" PRIx64, cpu64.r12);
8970 outs() << " r13 " << format("0x%016" PRIx64, cpu64.r13);
8971 outs() << " r14 " << format("0x%016" PRIx64, cpu64.r14) << "\n";
8972 outs() << " r15 " << format("0x%016" PRIx64, cpu64.r15);
8973 outs() << " rip " << format("0x%016" PRIx64, cpu64.rip) << "\n";
8974 outs() << "rflags " << format("0x%016" PRIx64, cpu64.rflags);
8975 outs() << " cs " << format("0x%016" PRIx64, cpu64.cs);
8976 outs() << " fs " << format("0x%016" PRIx64, cpu64.fs) << "\n";
8977 outs() << " gs " << format("0x%016" PRIx64, cpu64.gs) << "\n";
8980 static void Print_mmst_reg(MachO::mmst_reg_t &r) {
8981 uint32_t f;
8982 outs() << "\t mmst_reg ";
8983 for (f = 0; f < 10; f++)
8984 outs() << format("%02" PRIx32, (r.mmst_reg[f] & 0xff)) << " ";
8985 outs() << "\n";
8986 outs() << "\t mmst_rsrv ";
8987 for (f = 0; f < 6; f++)
8988 outs() << format("%02" PRIx32, (r.mmst_rsrv[f] & 0xff)) << " ";
8989 outs() << "\n";
8992 static void Print_xmm_reg(MachO::xmm_reg_t &r) {
8993 uint32_t f;
8994 outs() << "\t xmm_reg ";
8995 for (f = 0; f < 16; f++)
8996 outs() << format("%02" PRIx32, (r.xmm_reg[f] & 0xff)) << " ";
8997 outs() << "\n";
9000 static void Print_x86_float_state_t(MachO::x86_float_state64_t &fpu) {
9001 outs() << "\t fpu_reserved[0] " << fpu.fpu_reserved[0];
9002 outs() << " fpu_reserved[1] " << fpu.fpu_reserved[1] << "\n";
9003 outs() << "\t control: invalid " << fpu.fpu_fcw.invalid;
9004 outs() << " denorm " << fpu.fpu_fcw.denorm;
9005 outs() << " zdiv " << fpu.fpu_fcw.zdiv;
9006 outs() << " ovrfl " << fpu.fpu_fcw.ovrfl;
9007 outs() << " undfl " << fpu.fpu_fcw.undfl;
9008 outs() << " precis " << fpu.fpu_fcw.precis << "\n";
9009 outs() << "\t\t pc ";
9010 if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_24B)
9011 outs() << "FP_PREC_24B ";
9012 else if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_53B)
9013 outs() << "FP_PREC_53B ";
9014 else if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_64B)
9015 outs() << "FP_PREC_64B ";
9016 else
9017 outs() << fpu.fpu_fcw.pc << " ";
9018 outs() << "rc ";
9019 if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_NEAR)
9020 outs() << "FP_RND_NEAR ";
9021 else if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_DOWN)
9022 outs() << "FP_RND_DOWN ";
9023 else if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_UP)
9024 outs() << "FP_RND_UP ";
9025 else if (fpu.fpu_fcw.rc == MachO::x86_FP_CHOP)
9026 outs() << "FP_CHOP ";
9027 outs() << "\n";
9028 outs() << "\t status: invalid " << fpu.fpu_fsw.invalid;
9029 outs() << " denorm " << fpu.fpu_fsw.denorm;
9030 outs() << " zdiv " << fpu.fpu_fsw.zdiv;
9031 outs() << " ovrfl " << fpu.fpu_fsw.ovrfl;
9032 outs() << " undfl " << fpu.fpu_fsw.undfl;
9033 outs() << " precis " << fpu.fpu_fsw.precis;
9034 outs() << " stkflt " << fpu.fpu_fsw.stkflt << "\n";
9035 outs() << "\t errsumm " << fpu.fpu_fsw.errsumm;
9036 outs() << " c0 " << fpu.fpu_fsw.c0;
9037 outs() << " c1 " << fpu.fpu_fsw.c1;
9038 outs() << " c2 " << fpu.fpu_fsw.c2;
9039 outs() << " tos " << fpu.fpu_fsw.tos;
9040 outs() << " c3 " << fpu.fpu_fsw.c3;
9041 outs() << " busy " << fpu.fpu_fsw.busy << "\n";
9042 outs() << "\t fpu_ftw " << format("0x%02" PRIx32, fpu.fpu_ftw);
9043 outs() << " fpu_rsrv1 " << format("0x%02" PRIx32, fpu.fpu_rsrv1);
9044 outs() << " fpu_fop " << format("0x%04" PRIx32, fpu.fpu_fop);
9045 outs() << " fpu_ip " << format("0x%08" PRIx32, fpu.fpu_ip) << "\n";
9046 outs() << "\t fpu_cs " << format("0x%04" PRIx32, fpu.fpu_cs);
9047 outs() << " fpu_rsrv2 " << format("0x%04" PRIx32, fpu.fpu_rsrv2);
9048 outs() << " fpu_dp " << format("0x%08" PRIx32, fpu.fpu_dp);
9049 outs() << " fpu_ds " << format("0x%04" PRIx32, fpu.fpu_ds) << "\n";
9050 outs() << "\t fpu_rsrv3 " << format("0x%04" PRIx32, fpu.fpu_rsrv3);
9051 outs() << " fpu_mxcsr " << format("0x%08" PRIx32, fpu.fpu_mxcsr);
9052 outs() << " fpu_mxcsrmask " << format("0x%08" PRIx32, fpu.fpu_mxcsrmask);
9053 outs() << "\n";
9054 outs() << "\t fpu_stmm0:\n";
9055 Print_mmst_reg(fpu.fpu_stmm0);
9056 outs() << "\t fpu_stmm1:\n";
9057 Print_mmst_reg(fpu.fpu_stmm1);
9058 outs() << "\t fpu_stmm2:\n";
9059 Print_mmst_reg(fpu.fpu_stmm2);
9060 outs() << "\t fpu_stmm3:\n";
9061 Print_mmst_reg(fpu.fpu_stmm3);
9062 outs() << "\t fpu_stmm4:\n";
9063 Print_mmst_reg(fpu.fpu_stmm4);
9064 outs() << "\t fpu_stmm5:\n";
9065 Print_mmst_reg(fpu.fpu_stmm5);
9066 outs() << "\t fpu_stmm6:\n";
9067 Print_mmst_reg(fpu.fpu_stmm6);
9068 outs() << "\t fpu_stmm7:\n";
9069 Print_mmst_reg(fpu.fpu_stmm7);
9070 outs() << "\t fpu_xmm0:\n";
9071 Print_xmm_reg(fpu.fpu_xmm0);
9072 outs() << "\t fpu_xmm1:\n";
9073 Print_xmm_reg(fpu.fpu_xmm1);
9074 outs() << "\t fpu_xmm2:\n";
9075 Print_xmm_reg(fpu.fpu_xmm2);
9076 outs() << "\t fpu_xmm3:\n";
9077 Print_xmm_reg(fpu.fpu_xmm3);
9078 outs() << "\t fpu_xmm4:\n";
9079 Print_xmm_reg(fpu.fpu_xmm4);
9080 outs() << "\t fpu_xmm5:\n";
9081 Print_xmm_reg(fpu.fpu_xmm5);
9082 outs() << "\t fpu_xmm6:\n";
9083 Print_xmm_reg(fpu.fpu_xmm6);
9084 outs() << "\t fpu_xmm7:\n";
9085 Print_xmm_reg(fpu.fpu_xmm7);
9086 outs() << "\t fpu_xmm8:\n";
9087 Print_xmm_reg(fpu.fpu_xmm8);
9088 outs() << "\t fpu_xmm9:\n";
9089 Print_xmm_reg(fpu.fpu_xmm9);
9090 outs() << "\t fpu_xmm10:\n";
9091 Print_xmm_reg(fpu.fpu_xmm10);
9092 outs() << "\t fpu_xmm11:\n";
9093 Print_xmm_reg(fpu.fpu_xmm11);
9094 outs() << "\t fpu_xmm12:\n";
9095 Print_xmm_reg(fpu.fpu_xmm12);
9096 outs() << "\t fpu_xmm13:\n";
9097 Print_xmm_reg(fpu.fpu_xmm13);
9098 outs() << "\t fpu_xmm14:\n";
9099 Print_xmm_reg(fpu.fpu_xmm14);
9100 outs() << "\t fpu_xmm15:\n";
9101 Print_xmm_reg(fpu.fpu_xmm15);
9102 outs() << "\t fpu_rsrv4:\n";
9103 for (uint32_t f = 0; f < 6; f++) {
9104 outs() << "\t ";
9105 for (uint32_t g = 0; g < 16; g++)
9106 outs() << format("%02" PRIx32, fpu.fpu_rsrv4[f * g]) << " ";
9107 outs() << "\n";
9109 outs() << "\t fpu_reserved1 " << format("0x%08" PRIx32, fpu.fpu_reserved1);
9110 outs() << "\n";
9113 static void Print_x86_exception_state_t(MachO::x86_exception_state64_t &exc64) {
9114 outs() << "\t trapno " << format("0x%08" PRIx32, exc64.trapno);
9115 outs() << " err " << format("0x%08" PRIx32, exc64.err);
9116 outs() << " faultvaddr " << format("0x%016" PRIx64, exc64.faultvaddr) << "\n";
9119 static void Print_arm_thread_state32_t(MachO::arm_thread_state32_t &cpu32) {
9120 outs() << "\t r0 " << format("0x%08" PRIx32, cpu32.r[0]);
9121 outs() << " r1 " << format("0x%08" PRIx32, cpu32.r[1]);
9122 outs() << " r2 " << format("0x%08" PRIx32, cpu32.r[2]);
9123 outs() << " r3 " << format("0x%08" PRIx32, cpu32.r[3]) << "\n";
9124 outs() << "\t r4 " << format("0x%08" PRIx32, cpu32.r[4]);
9125 outs() << " r5 " << format("0x%08" PRIx32, cpu32.r[5]);
9126 outs() << " r6 " << format("0x%08" PRIx32, cpu32.r[6]);
9127 outs() << " r7 " << format("0x%08" PRIx32, cpu32.r[7]) << "\n";
9128 outs() << "\t r8 " << format("0x%08" PRIx32, cpu32.r[8]);
9129 outs() << " r9 " << format("0x%08" PRIx32, cpu32.r[9]);
9130 outs() << " r10 " << format("0x%08" PRIx32, cpu32.r[10]);
9131 outs() << " r11 " << format("0x%08" PRIx32, cpu32.r[11]) << "\n";
9132 outs() << "\t r12 " << format("0x%08" PRIx32, cpu32.r[12]);
9133 outs() << " sp " << format("0x%08" PRIx32, cpu32.sp);
9134 outs() << " lr " << format("0x%08" PRIx32, cpu32.lr);
9135 outs() << " pc " << format("0x%08" PRIx32, cpu32.pc) << "\n";
9136 outs() << "\t cpsr " << format("0x%08" PRIx32, cpu32.cpsr) << "\n";
9139 static void Print_arm_thread_state64_t(MachO::arm_thread_state64_t &cpu64) {
9140 outs() << "\t x0 " << format("0x%016" PRIx64, cpu64.x[0]);
9141 outs() << " x1 " << format("0x%016" PRIx64, cpu64.x[1]);
9142 outs() << " x2 " << format("0x%016" PRIx64, cpu64.x[2]) << "\n";
9143 outs() << "\t x3 " << format("0x%016" PRIx64, cpu64.x[3]);
9144 outs() << " x4 " << format("0x%016" PRIx64, cpu64.x[4]);
9145 outs() << " x5 " << format("0x%016" PRIx64, cpu64.x[5]) << "\n";
9146 outs() << "\t x6 " << format("0x%016" PRIx64, cpu64.x[6]);
9147 outs() << " x7 " << format("0x%016" PRIx64, cpu64.x[7]);
9148 outs() << " x8 " << format("0x%016" PRIx64, cpu64.x[8]) << "\n";
9149 outs() << "\t x9 " << format("0x%016" PRIx64, cpu64.x[9]);
9150 outs() << " x10 " << format("0x%016" PRIx64, cpu64.x[10]);
9151 outs() << " x11 " << format("0x%016" PRIx64, cpu64.x[11]) << "\n";
9152 outs() << "\t x12 " << format("0x%016" PRIx64, cpu64.x[12]);
9153 outs() << " x13 " << format("0x%016" PRIx64, cpu64.x[13]);
9154 outs() << " x14 " << format("0x%016" PRIx64, cpu64.x[14]) << "\n";
9155 outs() << "\t x15 " << format("0x%016" PRIx64, cpu64.x[15]);
9156 outs() << " x16 " << format("0x%016" PRIx64, cpu64.x[16]);
9157 outs() << " x17 " << format("0x%016" PRIx64, cpu64.x[17]) << "\n";
9158 outs() << "\t x18 " << format("0x%016" PRIx64, cpu64.x[18]);
9159 outs() << " x19 " << format("0x%016" PRIx64, cpu64.x[19]);
9160 outs() << " x20 " << format("0x%016" PRIx64, cpu64.x[20]) << "\n";
9161 outs() << "\t x21 " << format("0x%016" PRIx64, cpu64.x[21]);
9162 outs() << " x22 " << format("0x%016" PRIx64, cpu64.x[22]);
9163 outs() << " x23 " << format("0x%016" PRIx64, cpu64.x[23]) << "\n";
9164 outs() << "\t x24 " << format("0x%016" PRIx64, cpu64.x[24]);
9165 outs() << " x25 " << format("0x%016" PRIx64, cpu64.x[25]);
9166 outs() << " x26 " << format("0x%016" PRIx64, cpu64.x[26]) << "\n";
9167 outs() << "\t x27 " << format("0x%016" PRIx64, cpu64.x[27]);
9168 outs() << " x28 " << format("0x%016" PRIx64, cpu64.x[28]);
9169 outs() << " fp " << format("0x%016" PRIx64, cpu64.fp) << "\n";
9170 outs() << "\t lr " << format("0x%016" PRIx64, cpu64.lr);
9171 outs() << " sp " << format("0x%016" PRIx64, cpu64.sp);
9172 outs() << " pc " << format("0x%016" PRIx64, cpu64.pc) << "\n";
9173 outs() << "\t cpsr " << format("0x%08" PRIx32, cpu64.cpsr) << "\n";
9176 static void PrintThreadCommand(MachO::thread_command t, const char *Ptr,
9177 bool isLittleEndian, uint32_t cputype) {
9178 if (t.cmd == MachO::LC_THREAD)
9179 outs() << " cmd LC_THREAD\n";
9180 else if (t.cmd == MachO::LC_UNIXTHREAD)
9181 outs() << " cmd LC_UNIXTHREAD\n";
9182 else
9183 outs() << " cmd " << t.cmd << " (unknown)\n";
9184 outs() << " cmdsize " << t.cmdsize;
9185 if (t.cmdsize < sizeof(struct MachO::thread_command) + 2 * sizeof(uint32_t))
9186 outs() << " Incorrect size\n";
9187 else
9188 outs() << "\n";
9190 const char *begin = Ptr + sizeof(struct MachO::thread_command);
9191 const char *end = Ptr + t.cmdsize;
9192 uint32_t flavor, count, left;
9193 if (cputype == MachO::CPU_TYPE_I386) {
9194 while (begin < end) {
9195 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9196 memcpy((char *)&flavor, begin, sizeof(uint32_t));
9197 begin += sizeof(uint32_t);
9198 } else {
9199 flavor = 0;
9200 begin = end;
9202 if (isLittleEndian != sys::IsLittleEndianHost)
9203 sys::swapByteOrder(flavor);
9204 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9205 memcpy((char *)&count, begin, sizeof(uint32_t));
9206 begin += sizeof(uint32_t);
9207 } else {
9208 count = 0;
9209 begin = end;
9211 if (isLittleEndian != sys::IsLittleEndianHost)
9212 sys::swapByteOrder(count);
9213 if (flavor == MachO::x86_THREAD_STATE32) {
9214 outs() << " flavor i386_THREAD_STATE\n";
9215 if (count == MachO::x86_THREAD_STATE32_COUNT)
9216 outs() << " count i386_THREAD_STATE_COUNT\n";
9217 else
9218 outs() << " count " << count
9219 << " (not x86_THREAD_STATE32_COUNT)\n";
9220 MachO::x86_thread_state32_t cpu32;
9221 left = end - begin;
9222 if (left >= sizeof(MachO::x86_thread_state32_t)) {
9223 memcpy(&cpu32, begin, sizeof(MachO::x86_thread_state32_t));
9224 begin += sizeof(MachO::x86_thread_state32_t);
9225 } else {
9226 memset(&cpu32, '\0', sizeof(MachO::x86_thread_state32_t));
9227 memcpy(&cpu32, begin, left);
9228 begin += left;
9230 if (isLittleEndian != sys::IsLittleEndianHost)
9231 swapStruct(cpu32);
9232 Print_x86_thread_state32_t(cpu32);
9233 } else if (flavor == MachO::x86_THREAD_STATE) {
9234 outs() << " flavor x86_THREAD_STATE\n";
9235 if (count == MachO::x86_THREAD_STATE_COUNT)
9236 outs() << " count x86_THREAD_STATE_COUNT\n";
9237 else
9238 outs() << " count " << count
9239 << " (not x86_THREAD_STATE_COUNT)\n";
9240 struct MachO::x86_thread_state_t ts;
9241 left = end - begin;
9242 if (left >= sizeof(MachO::x86_thread_state_t)) {
9243 memcpy(&ts, begin, sizeof(MachO::x86_thread_state_t));
9244 begin += sizeof(MachO::x86_thread_state_t);
9245 } else {
9246 memset(&ts, '\0', sizeof(MachO::x86_thread_state_t));
9247 memcpy(&ts, begin, left);
9248 begin += left;
9250 if (isLittleEndian != sys::IsLittleEndianHost)
9251 swapStruct(ts);
9252 if (ts.tsh.flavor == MachO::x86_THREAD_STATE32) {
9253 outs() << "\t tsh.flavor x86_THREAD_STATE32 ";
9254 if (ts.tsh.count == MachO::x86_THREAD_STATE32_COUNT)
9255 outs() << "tsh.count x86_THREAD_STATE32_COUNT\n";
9256 else
9257 outs() << "tsh.count " << ts.tsh.count
9258 << " (not x86_THREAD_STATE32_COUNT\n";
9259 Print_x86_thread_state32_t(ts.uts.ts32);
9260 } else {
9261 outs() << "\t tsh.flavor " << ts.tsh.flavor << " tsh.count "
9262 << ts.tsh.count << "\n";
9264 } else {
9265 outs() << " flavor " << flavor << " (unknown)\n";
9266 outs() << " count " << count << "\n";
9267 outs() << " state (unknown)\n";
9268 begin += count * sizeof(uint32_t);
9271 } else if (cputype == MachO::CPU_TYPE_X86_64) {
9272 while (begin < end) {
9273 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9274 memcpy((char *)&flavor, begin, sizeof(uint32_t));
9275 begin += sizeof(uint32_t);
9276 } else {
9277 flavor = 0;
9278 begin = end;
9280 if (isLittleEndian != sys::IsLittleEndianHost)
9281 sys::swapByteOrder(flavor);
9282 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9283 memcpy((char *)&count, begin, sizeof(uint32_t));
9284 begin += sizeof(uint32_t);
9285 } else {
9286 count = 0;
9287 begin = end;
9289 if (isLittleEndian != sys::IsLittleEndianHost)
9290 sys::swapByteOrder(count);
9291 if (flavor == MachO::x86_THREAD_STATE64) {
9292 outs() << " flavor x86_THREAD_STATE64\n";
9293 if (count == MachO::x86_THREAD_STATE64_COUNT)
9294 outs() << " count x86_THREAD_STATE64_COUNT\n";
9295 else
9296 outs() << " count " << count
9297 << " (not x86_THREAD_STATE64_COUNT)\n";
9298 MachO::x86_thread_state64_t cpu64;
9299 left = end - begin;
9300 if (left >= sizeof(MachO::x86_thread_state64_t)) {
9301 memcpy(&cpu64, begin, sizeof(MachO::x86_thread_state64_t));
9302 begin += sizeof(MachO::x86_thread_state64_t);
9303 } else {
9304 memset(&cpu64, '\0', sizeof(MachO::x86_thread_state64_t));
9305 memcpy(&cpu64, begin, left);
9306 begin += left;
9308 if (isLittleEndian != sys::IsLittleEndianHost)
9309 swapStruct(cpu64);
9310 Print_x86_thread_state64_t(cpu64);
9311 } else if (flavor == MachO::x86_THREAD_STATE) {
9312 outs() << " flavor x86_THREAD_STATE\n";
9313 if (count == MachO::x86_THREAD_STATE_COUNT)
9314 outs() << " count x86_THREAD_STATE_COUNT\n";
9315 else
9316 outs() << " count " << count
9317 << " (not x86_THREAD_STATE_COUNT)\n";
9318 struct MachO::x86_thread_state_t ts;
9319 left = end - begin;
9320 if (left >= sizeof(MachO::x86_thread_state_t)) {
9321 memcpy(&ts, begin, sizeof(MachO::x86_thread_state_t));
9322 begin += sizeof(MachO::x86_thread_state_t);
9323 } else {
9324 memset(&ts, '\0', sizeof(MachO::x86_thread_state_t));
9325 memcpy(&ts, begin, left);
9326 begin += left;
9328 if (isLittleEndian != sys::IsLittleEndianHost)
9329 swapStruct(ts);
9330 if (ts.tsh.flavor == MachO::x86_THREAD_STATE64) {
9331 outs() << "\t tsh.flavor x86_THREAD_STATE64 ";
9332 if (ts.tsh.count == MachO::x86_THREAD_STATE64_COUNT)
9333 outs() << "tsh.count x86_THREAD_STATE64_COUNT\n";
9334 else
9335 outs() << "tsh.count " << ts.tsh.count
9336 << " (not x86_THREAD_STATE64_COUNT\n";
9337 Print_x86_thread_state64_t(ts.uts.ts64);
9338 } else {
9339 outs() << "\t tsh.flavor " << ts.tsh.flavor << " tsh.count "
9340 << ts.tsh.count << "\n";
9342 } else if (flavor == MachO::x86_FLOAT_STATE) {
9343 outs() << " flavor x86_FLOAT_STATE\n";
9344 if (count == MachO::x86_FLOAT_STATE_COUNT)
9345 outs() << " count x86_FLOAT_STATE_COUNT\n";
9346 else
9347 outs() << " count " << count << " (not x86_FLOAT_STATE_COUNT)\n";
9348 struct MachO::x86_float_state_t fs;
9349 left = end - begin;
9350 if (left >= sizeof(MachO::x86_float_state_t)) {
9351 memcpy(&fs, begin, sizeof(MachO::x86_float_state_t));
9352 begin += sizeof(MachO::x86_float_state_t);
9353 } else {
9354 memset(&fs, '\0', sizeof(MachO::x86_float_state_t));
9355 memcpy(&fs, begin, left);
9356 begin += left;
9358 if (isLittleEndian != sys::IsLittleEndianHost)
9359 swapStruct(fs);
9360 if (fs.fsh.flavor == MachO::x86_FLOAT_STATE64) {
9361 outs() << "\t fsh.flavor x86_FLOAT_STATE64 ";
9362 if (fs.fsh.count == MachO::x86_FLOAT_STATE64_COUNT)
9363 outs() << "fsh.count x86_FLOAT_STATE64_COUNT\n";
9364 else
9365 outs() << "fsh.count " << fs.fsh.count
9366 << " (not x86_FLOAT_STATE64_COUNT\n";
9367 Print_x86_float_state_t(fs.ufs.fs64);
9368 } else {
9369 outs() << "\t fsh.flavor " << fs.fsh.flavor << " fsh.count "
9370 << fs.fsh.count << "\n";
9372 } else if (flavor == MachO::x86_EXCEPTION_STATE) {
9373 outs() << " flavor x86_EXCEPTION_STATE\n";
9374 if (count == MachO::x86_EXCEPTION_STATE_COUNT)
9375 outs() << " count x86_EXCEPTION_STATE_COUNT\n";
9376 else
9377 outs() << " count " << count
9378 << " (not x86_EXCEPTION_STATE_COUNT)\n";
9379 struct MachO::x86_exception_state_t es;
9380 left = end - begin;
9381 if (left >= sizeof(MachO::x86_exception_state_t)) {
9382 memcpy(&es, begin, sizeof(MachO::x86_exception_state_t));
9383 begin += sizeof(MachO::x86_exception_state_t);
9384 } else {
9385 memset(&es, '\0', sizeof(MachO::x86_exception_state_t));
9386 memcpy(&es, begin, left);
9387 begin += left;
9389 if (isLittleEndian != sys::IsLittleEndianHost)
9390 swapStruct(es);
9391 if (es.esh.flavor == MachO::x86_EXCEPTION_STATE64) {
9392 outs() << "\t esh.flavor x86_EXCEPTION_STATE64\n";
9393 if (es.esh.count == MachO::x86_EXCEPTION_STATE64_COUNT)
9394 outs() << "\t esh.count x86_EXCEPTION_STATE64_COUNT\n";
9395 else
9396 outs() << "\t esh.count " << es.esh.count
9397 << " (not x86_EXCEPTION_STATE64_COUNT\n";
9398 Print_x86_exception_state_t(es.ues.es64);
9399 } else {
9400 outs() << "\t esh.flavor " << es.esh.flavor << " esh.count "
9401 << es.esh.count << "\n";
9403 } else if (flavor == MachO::x86_EXCEPTION_STATE64) {
9404 outs() << " flavor x86_EXCEPTION_STATE64\n";
9405 if (count == MachO::x86_EXCEPTION_STATE64_COUNT)
9406 outs() << " count x86_EXCEPTION_STATE64_COUNT\n";
9407 else
9408 outs() << " count " << count
9409 << " (not x86_EXCEPTION_STATE64_COUNT)\n";
9410 struct MachO::x86_exception_state64_t es64;
9411 left = end - begin;
9412 if (left >= sizeof(MachO::x86_exception_state64_t)) {
9413 memcpy(&es64, begin, sizeof(MachO::x86_exception_state64_t));
9414 begin += sizeof(MachO::x86_exception_state64_t);
9415 } else {
9416 memset(&es64, '\0', sizeof(MachO::x86_exception_state64_t));
9417 memcpy(&es64, begin, left);
9418 begin += left;
9420 if (isLittleEndian != sys::IsLittleEndianHost)
9421 swapStruct(es64);
9422 Print_x86_exception_state_t(es64);
9423 } else {
9424 outs() << " flavor " << flavor << " (unknown)\n";
9425 outs() << " count " << count << "\n";
9426 outs() << " state (unknown)\n";
9427 begin += count * sizeof(uint32_t);
9430 } else if (cputype == MachO::CPU_TYPE_ARM) {
9431 while (begin < end) {
9432 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9433 memcpy((char *)&flavor, begin, sizeof(uint32_t));
9434 begin += sizeof(uint32_t);
9435 } else {
9436 flavor = 0;
9437 begin = end;
9439 if (isLittleEndian != sys::IsLittleEndianHost)
9440 sys::swapByteOrder(flavor);
9441 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9442 memcpy((char *)&count, begin, sizeof(uint32_t));
9443 begin += sizeof(uint32_t);
9444 } else {
9445 count = 0;
9446 begin = end;
9448 if (isLittleEndian != sys::IsLittleEndianHost)
9449 sys::swapByteOrder(count);
9450 if (flavor == MachO::ARM_THREAD_STATE) {
9451 outs() << " flavor ARM_THREAD_STATE\n";
9452 if (count == MachO::ARM_THREAD_STATE_COUNT)
9453 outs() << " count ARM_THREAD_STATE_COUNT\n";
9454 else
9455 outs() << " count " << count
9456 << " (not ARM_THREAD_STATE_COUNT)\n";
9457 MachO::arm_thread_state32_t cpu32;
9458 left = end - begin;
9459 if (left >= sizeof(MachO::arm_thread_state32_t)) {
9460 memcpy(&cpu32, begin, sizeof(MachO::arm_thread_state32_t));
9461 begin += sizeof(MachO::arm_thread_state32_t);
9462 } else {
9463 memset(&cpu32, '\0', sizeof(MachO::arm_thread_state32_t));
9464 memcpy(&cpu32, begin, left);
9465 begin += left;
9467 if (isLittleEndian != sys::IsLittleEndianHost)
9468 swapStruct(cpu32);
9469 Print_arm_thread_state32_t(cpu32);
9470 } else {
9471 outs() << " flavor " << flavor << " (unknown)\n";
9472 outs() << " count " << count << "\n";
9473 outs() << " state (unknown)\n";
9474 begin += count * sizeof(uint32_t);
9477 } else if (cputype == MachO::CPU_TYPE_ARM64) {
9478 while (begin < end) {
9479 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9480 memcpy((char *)&flavor, begin, sizeof(uint32_t));
9481 begin += sizeof(uint32_t);
9482 } else {
9483 flavor = 0;
9484 begin = end;
9486 if (isLittleEndian != sys::IsLittleEndianHost)
9487 sys::swapByteOrder(flavor);
9488 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9489 memcpy((char *)&count, begin, sizeof(uint32_t));
9490 begin += sizeof(uint32_t);
9491 } else {
9492 count = 0;
9493 begin = end;
9495 if (isLittleEndian != sys::IsLittleEndianHost)
9496 sys::swapByteOrder(count);
9497 if (flavor == MachO::ARM_THREAD_STATE64) {
9498 outs() << " flavor ARM_THREAD_STATE64\n";
9499 if (count == MachO::ARM_THREAD_STATE64_COUNT)
9500 outs() << " count ARM_THREAD_STATE64_COUNT\n";
9501 else
9502 outs() << " count " << count
9503 << " (not ARM_THREAD_STATE64_COUNT)\n";
9504 MachO::arm_thread_state64_t cpu64;
9505 left = end - begin;
9506 if (left >= sizeof(MachO::arm_thread_state64_t)) {
9507 memcpy(&cpu64, begin, sizeof(MachO::arm_thread_state64_t));
9508 begin += sizeof(MachO::arm_thread_state64_t);
9509 } else {
9510 memset(&cpu64, '\0', sizeof(MachO::arm_thread_state64_t));
9511 memcpy(&cpu64, begin, left);
9512 begin += left;
9514 if (isLittleEndian != sys::IsLittleEndianHost)
9515 swapStruct(cpu64);
9516 Print_arm_thread_state64_t(cpu64);
9517 } else {
9518 outs() << " flavor " << flavor << " (unknown)\n";
9519 outs() << " count " << count << "\n";
9520 outs() << " state (unknown)\n";
9521 begin += count * sizeof(uint32_t);
9524 } else {
9525 while (begin < end) {
9526 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9527 memcpy((char *)&flavor, begin, sizeof(uint32_t));
9528 begin += sizeof(uint32_t);
9529 } else {
9530 flavor = 0;
9531 begin = end;
9533 if (isLittleEndian != sys::IsLittleEndianHost)
9534 sys::swapByteOrder(flavor);
9535 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9536 memcpy((char *)&count, begin, sizeof(uint32_t));
9537 begin += sizeof(uint32_t);
9538 } else {
9539 count = 0;
9540 begin = end;
9542 if (isLittleEndian != sys::IsLittleEndianHost)
9543 sys::swapByteOrder(count);
9544 outs() << " flavor " << flavor << "\n";
9545 outs() << " count " << count << "\n";
9546 outs() << " state (Unknown cputype/cpusubtype)\n";
9547 begin += count * sizeof(uint32_t);
9552 static void PrintDylibCommand(MachO::dylib_command dl, const char *Ptr) {
9553 if (dl.cmd == MachO::LC_ID_DYLIB)
9554 outs() << " cmd LC_ID_DYLIB\n";
9555 else if (dl.cmd == MachO::LC_LOAD_DYLIB)
9556 outs() << " cmd LC_LOAD_DYLIB\n";
9557 else if (dl.cmd == MachO::LC_LOAD_WEAK_DYLIB)
9558 outs() << " cmd LC_LOAD_WEAK_DYLIB\n";
9559 else if (dl.cmd == MachO::LC_REEXPORT_DYLIB)
9560 outs() << " cmd LC_REEXPORT_DYLIB\n";
9561 else if (dl.cmd == MachO::LC_LAZY_LOAD_DYLIB)
9562 outs() << " cmd LC_LAZY_LOAD_DYLIB\n";
9563 else if (dl.cmd == MachO::LC_LOAD_UPWARD_DYLIB)
9564 outs() << " cmd LC_LOAD_UPWARD_DYLIB\n";
9565 else
9566 outs() << " cmd " << dl.cmd << " (unknown)\n";
9567 outs() << " cmdsize " << dl.cmdsize;
9568 if (dl.cmdsize < sizeof(struct MachO::dylib_command))
9569 outs() << " Incorrect size\n";
9570 else
9571 outs() << "\n";
9572 if (dl.dylib.name < dl.cmdsize) {
9573 const char *P = (const char *)(Ptr) + dl.dylib.name;
9574 outs() << " name " << P << " (offset " << dl.dylib.name << ")\n";
9575 } else {
9576 outs() << " name ?(bad offset " << dl.dylib.name << ")\n";
9578 outs() << " time stamp " << dl.dylib.timestamp << " ";
9579 time_t t = dl.dylib.timestamp;
9580 outs() << ctime(&t);
9581 outs() << " current version ";
9582 if (dl.dylib.current_version == 0xffffffff)
9583 outs() << "n/a\n";
9584 else
9585 outs() << ((dl.dylib.current_version >> 16) & 0xffff) << "."
9586 << ((dl.dylib.current_version >> 8) & 0xff) << "."
9587 << (dl.dylib.current_version & 0xff) << "\n";
9588 outs() << "compatibility version ";
9589 if (dl.dylib.compatibility_version == 0xffffffff)
9590 outs() << "n/a\n";
9591 else
9592 outs() << ((dl.dylib.compatibility_version >> 16) & 0xffff) << "."
9593 << ((dl.dylib.compatibility_version >> 8) & 0xff) << "."
9594 << (dl.dylib.compatibility_version & 0xff) << "\n";
9597 static void PrintLinkEditDataCommand(MachO::linkedit_data_command ld,
9598 uint32_t object_size) {
9599 if (ld.cmd == MachO::LC_CODE_SIGNATURE)
9600 outs() << " cmd LC_CODE_SIGNATURE\n";
9601 else if (ld.cmd == MachO::LC_SEGMENT_SPLIT_INFO)
9602 outs() << " cmd LC_SEGMENT_SPLIT_INFO\n";
9603 else if (ld.cmd == MachO::LC_FUNCTION_STARTS)
9604 outs() << " cmd LC_FUNCTION_STARTS\n";
9605 else if (ld.cmd == MachO::LC_DATA_IN_CODE)
9606 outs() << " cmd LC_DATA_IN_CODE\n";
9607 else if (ld.cmd == MachO::LC_DYLIB_CODE_SIGN_DRS)
9608 outs() << " cmd LC_DYLIB_CODE_SIGN_DRS\n";
9609 else if (ld.cmd == MachO::LC_LINKER_OPTIMIZATION_HINT)
9610 outs() << " cmd LC_LINKER_OPTIMIZATION_HINT\n";
9611 else
9612 outs() << " cmd " << ld.cmd << " (?)\n";
9613 outs() << " cmdsize " << ld.cmdsize;
9614 if (ld.cmdsize != sizeof(struct MachO::linkedit_data_command))
9615 outs() << " Incorrect size\n";
9616 else
9617 outs() << "\n";
9618 outs() << " dataoff " << ld.dataoff;
9619 if (ld.dataoff > object_size)
9620 outs() << " (past end of file)\n";
9621 else
9622 outs() << "\n";
9623 outs() << " datasize " << ld.datasize;
9624 uint64_t big_size = ld.dataoff;
9625 big_size += ld.datasize;
9626 if (big_size > object_size)
9627 outs() << " (past end of file)\n";
9628 else
9629 outs() << "\n";
9632 static void PrintLoadCommands(const MachOObjectFile *Obj, uint32_t filetype,
9633 uint32_t cputype, bool verbose) {
9634 StringRef Buf = Obj->getData();
9635 unsigned Index = 0;
9636 for (const auto &Command : Obj->load_commands()) {
9637 outs() << "Load command " << Index++ << "\n";
9638 if (Command.C.cmd == MachO::LC_SEGMENT) {
9639 MachO::segment_command SLC = Obj->getSegmentLoadCommand(Command);
9640 const char *sg_segname = SLC.segname;
9641 PrintSegmentCommand(SLC.cmd, SLC.cmdsize, SLC.segname, SLC.vmaddr,
9642 SLC.vmsize, SLC.fileoff, SLC.filesize, SLC.maxprot,
9643 SLC.initprot, SLC.nsects, SLC.flags, Buf.size(),
9644 verbose);
9645 for (unsigned j = 0; j < SLC.nsects; j++) {
9646 MachO::section S = Obj->getSection(Command, j);
9647 PrintSection(S.sectname, S.segname, S.addr, S.size, S.offset, S.align,
9648 S.reloff, S.nreloc, S.flags, S.reserved1, S.reserved2,
9649 SLC.cmd, sg_segname, filetype, Buf.size(), verbose);
9651 } else if (Command.C.cmd == MachO::LC_SEGMENT_64) {
9652 MachO::segment_command_64 SLC_64 = Obj->getSegment64LoadCommand(Command);
9653 const char *sg_segname = SLC_64.segname;
9654 PrintSegmentCommand(SLC_64.cmd, SLC_64.cmdsize, SLC_64.segname,
9655 SLC_64.vmaddr, SLC_64.vmsize, SLC_64.fileoff,
9656 SLC_64.filesize, SLC_64.maxprot, SLC_64.initprot,
9657 SLC_64.nsects, SLC_64.flags, Buf.size(), verbose);
9658 for (unsigned j = 0; j < SLC_64.nsects; j++) {
9659 MachO::section_64 S_64 = Obj->getSection64(Command, j);
9660 PrintSection(S_64.sectname, S_64.segname, S_64.addr, S_64.size,
9661 S_64.offset, S_64.align, S_64.reloff, S_64.nreloc,
9662 S_64.flags, S_64.reserved1, S_64.reserved2, SLC_64.cmd,
9663 sg_segname, filetype, Buf.size(), verbose);
9665 } else if (Command.C.cmd == MachO::LC_SYMTAB) {
9666 MachO::symtab_command Symtab = Obj->getSymtabLoadCommand();
9667 PrintSymtabLoadCommand(Symtab, Obj->is64Bit(), Buf.size());
9668 } else if (Command.C.cmd == MachO::LC_DYSYMTAB) {
9669 MachO::dysymtab_command Dysymtab = Obj->getDysymtabLoadCommand();
9670 MachO::symtab_command Symtab = Obj->getSymtabLoadCommand();
9671 PrintDysymtabLoadCommand(Dysymtab, Symtab.nsyms, Buf.size(),
9672 Obj->is64Bit());
9673 } else if (Command.C.cmd == MachO::LC_DYLD_INFO ||
9674 Command.C.cmd == MachO::LC_DYLD_INFO_ONLY) {
9675 MachO::dyld_info_command DyldInfo = Obj->getDyldInfoLoadCommand(Command);
9676 PrintDyldInfoLoadCommand(DyldInfo, Buf.size());
9677 } else if (Command.C.cmd == MachO::LC_LOAD_DYLINKER ||
9678 Command.C.cmd == MachO::LC_ID_DYLINKER ||
9679 Command.C.cmd == MachO::LC_DYLD_ENVIRONMENT) {
9680 MachO::dylinker_command Dyld = Obj->getDylinkerCommand(Command);
9681 PrintDyldLoadCommand(Dyld, Command.Ptr);
9682 } else if (Command.C.cmd == MachO::LC_UUID) {
9683 MachO::uuid_command Uuid = Obj->getUuidCommand(Command);
9684 PrintUuidLoadCommand(Uuid);
9685 } else if (Command.C.cmd == MachO::LC_RPATH) {
9686 MachO::rpath_command Rpath = Obj->getRpathCommand(Command);
9687 PrintRpathLoadCommand(Rpath, Command.Ptr);
9688 } else if (Command.C.cmd == MachO::LC_VERSION_MIN_MACOSX ||
9689 Command.C.cmd == MachO::LC_VERSION_MIN_IPHONEOS ||
9690 Command.C.cmd == MachO::LC_VERSION_MIN_TVOS ||
9691 Command.C.cmd == MachO::LC_VERSION_MIN_WATCHOS) {
9692 MachO::version_min_command Vd = Obj->getVersionMinLoadCommand(Command);
9693 PrintVersionMinLoadCommand(Vd);
9694 } else if (Command.C.cmd == MachO::LC_NOTE) {
9695 MachO::note_command Nt = Obj->getNoteLoadCommand(Command);
9696 PrintNoteLoadCommand(Nt);
9697 } else if (Command.C.cmd == MachO::LC_BUILD_VERSION) {
9698 MachO::build_version_command Bv =
9699 Obj->getBuildVersionLoadCommand(Command);
9700 PrintBuildVersionLoadCommand(Obj, Bv);
9701 } else if (Command.C.cmd == MachO::LC_SOURCE_VERSION) {
9702 MachO::source_version_command Sd = Obj->getSourceVersionCommand(Command);
9703 PrintSourceVersionCommand(Sd);
9704 } else if (Command.C.cmd == MachO::LC_MAIN) {
9705 MachO::entry_point_command Ep = Obj->getEntryPointCommand(Command);
9706 PrintEntryPointCommand(Ep);
9707 } else if (Command.C.cmd == MachO::LC_ENCRYPTION_INFO) {
9708 MachO::encryption_info_command Ei =
9709 Obj->getEncryptionInfoCommand(Command);
9710 PrintEncryptionInfoCommand(Ei, Buf.size());
9711 } else if (Command.C.cmd == MachO::LC_ENCRYPTION_INFO_64) {
9712 MachO::encryption_info_command_64 Ei =
9713 Obj->getEncryptionInfoCommand64(Command);
9714 PrintEncryptionInfoCommand64(Ei, Buf.size());
9715 } else if (Command.C.cmd == MachO::LC_LINKER_OPTION) {
9716 MachO::linker_option_command Lo =
9717 Obj->getLinkerOptionLoadCommand(Command);
9718 PrintLinkerOptionCommand(Lo, Command.Ptr);
9719 } else if (Command.C.cmd == MachO::LC_SUB_FRAMEWORK) {
9720 MachO::sub_framework_command Sf = Obj->getSubFrameworkCommand(Command);
9721 PrintSubFrameworkCommand(Sf, Command.Ptr);
9722 } else if (Command.C.cmd == MachO::LC_SUB_UMBRELLA) {
9723 MachO::sub_umbrella_command Sf = Obj->getSubUmbrellaCommand(Command);
9724 PrintSubUmbrellaCommand(Sf, Command.Ptr);
9725 } else if (Command.C.cmd == MachO::LC_SUB_LIBRARY) {
9726 MachO::sub_library_command Sl = Obj->getSubLibraryCommand(Command);
9727 PrintSubLibraryCommand(Sl, Command.Ptr);
9728 } else if (Command.C.cmd == MachO::LC_SUB_CLIENT) {
9729 MachO::sub_client_command Sc = Obj->getSubClientCommand(Command);
9730 PrintSubClientCommand(Sc, Command.Ptr);
9731 } else if (Command.C.cmd == MachO::LC_ROUTINES) {
9732 MachO::routines_command Rc = Obj->getRoutinesCommand(Command);
9733 PrintRoutinesCommand(Rc);
9734 } else if (Command.C.cmd == MachO::LC_ROUTINES_64) {
9735 MachO::routines_command_64 Rc = Obj->getRoutinesCommand64(Command);
9736 PrintRoutinesCommand64(Rc);
9737 } else if (Command.C.cmd == MachO::LC_THREAD ||
9738 Command.C.cmd == MachO::LC_UNIXTHREAD) {
9739 MachO::thread_command Tc = Obj->getThreadCommand(Command);
9740 PrintThreadCommand(Tc, Command.Ptr, Obj->isLittleEndian(), cputype);
9741 } else if (Command.C.cmd == MachO::LC_LOAD_DYLIB ||
9742 Command.C.cmd == MachO::LC_ID_DYLIB ||
9743 Command.C.cmd == MachO::LC_LOAD_WEAK_DYLIB ||
9744 Command.C.cmd == MachO::LC_REEXPORT_DYLIB ||
9745 Command.C.cmd == MachO::LC_LAZY_LOAD_DYLIB ||
9746 Command.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB) {
9747 MachO::dylib_command Dl = Obj->getDylibIDLoadCommand(Command);
9748 PrintDylibCommand(Dl, Command.Ptr);
9749 } else if (Command.C.cmd == MachO::LC_CODE_SIGNATURE ||
9750 Command.C.cmd == MachO::LC_SEGMENT_SPLIT_INFO ||
9751 Command.C.cmd == MachO::LC_FUNCTION_STARTS ||
9752 Command.C.cmd == MachO::LC_DATA_IN_CODE ||
9753 Command.C.cmd == MachO::LC_DYLIB_CODE_SIGN_DRS ||
9754 Command.C.cmd == MachO::LC_LINKER_OPTIMIZATION_HINT) {
9755 MachO::linkedit_data_command Ld =
9756 Obj->getLinkeditDataLoadCommand(Command);
9757 PrintLinkEditDataCommand(Ld, Buf.size());
9758 } else {
9759 outs() << " cmd ?(" << format("0x%08" PRIx32, Command.C.cmd)
9760 << ")\n";
9761 outs() << " cmdsize " << Command.C.cmdsize << "\n";
9762 // TODO: get and print the raw bytes of the load command.
9764 // TODO: print all the other kinds of load commands.
9768 static void PrintMachHeader(const MachOObjectFile *Obj, bool verbose) {
9769 if (Obj->is64Bit()) {
9770 MachO::mach_header_64 H_64;
9771 H_64 = Obj->getHeader64();
9772 PrintMachHeader(H_64.magic, H_64.cputype, H_64.cpusubtype, H_64.filetype,
9773 H_64.ncmds, H_64.sizeofcmds, H_64.flags, verbose);
9774 } else {
9775 MachO::mach_header H;
9776 H = Obj->getHeader();
9777 PrintMachHeader(H.magic, H.cputype, H.cpusubtype, H.filetype, H.ncmds,
9778 H.sizeofcmds, H.flags, verbose);
9782 void llvm::printMachOFileHeader(const object::ObjectFile *Obj) {
9783 const MachOObjectFile *file = dyn_cast<const MachOObjectFile>(Obj);
9784 PrintMachHeader(file, !NonVerbose);
9787 void llvm::printMachOLoadCommands(const object::ObjectFile *Obj) {
9788 const MachOObjectFile *file = dyn_cast<const MachOObjectFile>(Obj);
9789 uint32_t filetype = 0;
9790 uint32_t cputype = 0;
9791 if (file->is64Bit()) {
9792 MachO::mach_header_64 H_64;
9793 H_64 = file->getHeader64();
9794 filetype = H_64.filetype;
9795 cputype = H_64.cputype;
9796 } else {
9797 MachO::mach_header H;
9798 H = file->getHeader();
9799 filetype = H.filetype;
9800 cputype = H.cputype;
9802 PrintLoadCommands(file, filetype, cputype, !NonVerbose);
9805 //===----------------------------------------------------------------------===//
9806 // export trie dumping
9807 //===----------------------------------------------------------------------===//
9809 void llvm::printMachOExportsTrie(const object::MachOObjectFile *Obj) {
9810 uint64_t BaseSegmentAddress = 0;
9811 for (const auto &Command : Obj->load_commands()) {
9812 if (Command.C.cmd == MachO::LC_SEGMENT) {
9813 MachO::segment_command Seg = Obj->getSegmentLoadCommand(Command);
9814 if (Seg.fileoff == 0 && Seg.filesize != 0) {
9815 BaseSegmentAddress = Seg.vmaddr;
9816 break;
9818 } else if (Command.C.cmd == MachO::LC_SEGMENT_64) {
9819 MachO::segment_command_64 Seg = Obj->getSegment64LoadCommand(Command);
9820 if (Seg.fileoff == 0 && Seg.filesize != 0) {
9821 BaseSegmentAddress = Seg.vmaddr;
9822 break;
9826 Error Err = Error::success();
9827 for (const llvm::object::ExportEntry &Entry : Obj->exports(Err)) {
9828 uint64_t Flags = Entry.flags();
9829 bool ReExport = (Flags & MachO::EXPORT_SYMBOL_FLAGS_REEXPORT);
9830 bool WeakDef = (Flags & MachO::EXPORT_SYMBOL_FLAGS_WEAK_DEFINITION);
9831 bool ThreadLocal = ((Flags & MachO::EXPORT_SYMBOL_FLAGS_KIND_MASK) ==
9832 MachO::EXPORT_SYMBOL_FLAGS_KIND_THREAD_LOCAL);
9833 bool Abs = ((Flags & MachO::EXPORT_SYMBOL_FLAGS_KIND_MASK) ==
9834 MachO::EXPORT_SYMBOL_FLAGS_KIND_ABSOLUTE);
9835 bool Resolver = (Flags & MachO::EXPORT_SYMBOL_FLAGS_STUB_AND_RESOLVER);
9836 if (ReExport)
9837 outs() << "[re-export] ";
9838 else
9839 outs() << format("0x%08llX ",
9840 Entry.address() + BaseSegmentAddress);
9841 outs() << Entry.name();
9842 if (WeakDef || ThreadLocal || Resolver || Abs) {
9843 bool NeedsComma = false;
9844 outs() << " [";
9845 if (WeakDef) {
9846 outs() << "weak_def";
9847 NeedsComma = true;
9849 if (ThreadLocal) {
9850 if (NeedsComma)
9851 outs() << ", ";
9852 outs() << "per-thread";
9853 NeedsComma = true;
9855 if (Abs) {
9856 if (NeedsComma)
9857 outs() << ", ";
9858 outs() << "absolute";
9859 NeedsComma = true;
9861 if (Resolver) {
9862 if (NeedsComma)
9863 outs() << ", ";
9864 outs() << format("resolver=0x%08llX", Entry.other());
9865 NeedsComma = true;
9867 outs() << "]";
9869 if (ReExport) {
9870 StringRef DylibName = "unknown";
9871 int Ordinal = Entry.other() - 1;
9872 Obj->getLibraryShortNameByIndex(Ordinal, DylibName);
9873 if (Entry.otherName().empty())
9874 outs() << " (from " << DylibName << ")";
9875 else
9876 outs() << " (" << Entry.otherName() << " from " << DylibName << ")";
9878 outs() << "\n";
9880 if (Err)
9881 report_error(Obj->getFileName(), std::move(Err));
9884 //===----------------------------------------------------------------------===//
9885 // rebase table dumping
9886 //===----------------------------------------------------------------------===//
9888 void llvm::printMachORebaseTable(object::MachOObjectFile *Obj) {
9889 outs() << "segment section address type\n";
9890 Error Err = Error::success();
9891 for (const llvm::object::MachORebaseEntry &Entry : Obj->rebaseTable(Err)) {
9892 StringRef SegmentName = Entry.segmentName();
9893 StringRef SectionName = Entry.sectionName();
9894 uint64_t Address = Entry.address();
9896 // Table lines look like: __DATA __nl_symbol_ptr 0x0000F00C pointer
9897 outs() << format("%-8s %-18s 0x%08" PRIX64 " %s\n",
9898 SegmentName.str().c_str(), SectionName.str().c_str(),
9899 Address, Entry.typeName().str().c_str());
9901 if (Err)
9902 report_error(Obj->getFileName(), std::move(Err));
9905 static StringRef ordinalName(const object::MachOObjectFile *Obj, int Ordinal) {
9906 StringRef DylibName;
9907 switch (Ordinal) {
9908 case MachO::BIND_SPECIAL_DYLIB_SELF:
9909 return "this-image";
9910 case MachO::BIND_SPECIAL_DYLIB_MAIN_EXECUTABLE:
9911 return "main-executable";
9912 case MachO::BIND_SPECIAL_DYLIB_FLAT_LOOKUP:
9913 return "flat-namespace";
9914 default:
9915 if (Ordinal > 0) {
9916 std::error_code EC =
9917 Obj->getLibraryShortNameByIndex(Ordinal - 1, DylibName);
9918 if (EC)
9919 return "<<bad library ordinal>>";
9920 return DylibName;
9923 return "<<unknown special ordinal>>";
9926 //===----------------------------------------------------------------------===//
9927 // bind table dumping
9928 //===----------------------------------------------------------------------===//
9930 void llvm::printMachOBindTable(object::MachOObjectFile *Obj) {
9931 // Build table of sections so names can used in final output.
9932 outs() << "segment section address type "
9933 "addend dylib symbol\n";
9934 Error Err = Error::success();
9935 for (const llvm::object::MachOBindEntry &Entry : Obj->bindTable(Err)) {
9936 StringRef SegmentName = Entry.segmentName();
9937 StringRef SectionName = Entry.sectionName();
9938 uint64_t Address = Entry.address();
9940 // Table lines look like:
9941 // __DATA __got 0x00012010 pointer 0 libSystem ___stack_chk_guard
9942 StringRef Attr;
9943 if (Entry.flags() & MachO::BIND_SYMBOL_FLAGS_WEAK_IMPORT)
9944 Attr = " (weak_import)";
9945 outs() << left_justify(SegmentName, 8) << " "
9946 << left_justify(SectionName, 18) << " "
9947 << format_hex(Address, 10, true) << " "
9948 << left_justify(Entry.typeName(), 8) << " "
9949 << format_decimal(Entry.addend(), 8) << " "
9950 << left_justify(ordinalName(Obj, Entry.ordinal()), 16) << " "
9951 << Entry.symbolName() << Attr << "\n";
9953 if (Err)
9954 report_error(Obj->getFileName(), std::move(Err));
9957 //===----------------------------------------------------------------------===//
9958 // lazy bind table dumping
9959 //===----------------------------------------------------------------------===//
9961 void llvm::printMachOLazyBindTable(object::MachOObjectFile *Obj) {
9962 outs() << "segment section address "
9963 "dylib symbol\n";
9964 Error Err = Error::success();
9965 for (const llvm::object::MachOBindEntry &Entry : Obj->lazyBindTable(Err)) {
9966 StringRef SegmentName = Entry.segmentName();
9967 StringRef SectionName = Entry.sectionName();
9968 uint64_t Address = Entry.address();
9970 // Table lines look like:
9971 // __DATA __got 0x00012010 libSystem ___stack_chk_guard
9972 outs() << left_justify(SegmentName, 8) << " "
9973 << left_justify(SectionName, 18) << " "
9974 << format_hex(Address, 10, true) << " "
9975 << left_justify(ordinalName(Obj, Entry.ordinal()), 16) << " "
9976 << Entry.symbolName() << "\n";
9978 if (Err)
9979 report_error(Obj->getFileName(), std::move(Err));
9982 //===----------------------------------------------------------------------===//
9983 // weak bind table dumping
9984 //===----------------------------------------------------------------------===//
9986 void llvm::printMachOWeakBindTable(object::MachOObjectFile *Obj) {
9987 outs() << "segment section address "
9988 "type addend symbol\n";
9989 Error Err = Error::success();
9990 for (const llvm::object::MachOBindEntry &Entry : Obj->weakBindTable(Err)) {
9991 // Strong symbols don't have a location to update.
9992 if (Entry.flags() & MachO::BIND_SYMBOL_FLAGS_NON_WEAK_DEFINITION) {
9993 outs() << " strong "
9994 << Entry.symbolName() << "\n";
9995 continue;
9997 StringRef SegmentName = Entry.segmentName();
9998 StringRef SectionName = Entry.sectionName();
9999 uint64_t Address = Entry.address();
10001 // Table lines look like:
10002 // __DATA __data 0x00001000 pointer 0 _foo
10003 outs() << left_justify(SegmentName, 8) << " "
10004 << left_justify(SectionName, 18) << " "
10005 << format_hex(Address, 10, true) << " "
10006 << left_justify(Entry.typeName(), 8) << " "
10007 << format_decimal(Entry.addend(), 8) << " " << Entry.symbolName()
10008 << "\n";
10010 if (Err)
10011 report_error(Obj->getFileName(), std::move(Err));
10014 // get_dyld_bind_info_symbolname() is used for disassembly and passed an
10015 // address, ReferenceValue, in the Mach-O file and looks in the dyld bind
10016 // information for that address. If the address is found its binding symbol
10017 // name is returned. If not nullptr is returned.
10018 static const char *get_dyld_bind_info_symbolname(uint64_t ReferenceValue,
10019 struct DisassembleInfo *info) {
10020 if (info->bindtable == nullptr) {
10021 info->bindtable = llvm::make_unique<SymbolAddressMap>();
10022 Error Err = Error::success();
10023 for (const llvm::object::MachOBindEntry &Entry : info->O->bindTable(Err)) {
10024 uint64_t Address = Entry.address();
10025 StringRef name = Entry.symbolName();
10026 if (!name.empty())
10027 (*info->bindtable)[Address] = name;
10029 if (Err)
10030 report_error(info->O->getFileName(), std::move(Err));
10032 auto name = info->bindtable->lookup(ReferenceValue);
10033 return !name.empty() ? name.data() : nullptr;