1 //===-- MachODump.cpp - Object file dumping utility for llvm --------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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/Config/config.h"
20 #include "llvm/DebugInfo/DWARF/DIContext.h"
21 #include "llvm/MC/MCAsmInfo.h"
22 #include "llvm/MC/MCContext.h"
23 #include "llvm/MC/MCDisassembler.h"
24 #include "llvm/MC/MCInst.h"
25 #include "llvm/MC/MCInstPrinter.h"
26 #include "llvm/MC/MCInstrDesc.h"
27 #include "llvm/MC/MCInstrInfo.h"
28 #include "llvm/MC/MCRegisterInfo.h"
29 #include "llvm/MC/MCSubtargetInfo.h"
30 #include "llvm/Object/MachO.h"
31 #include "llvm/Object/MachOUniversal.h"
32 #include "llvm/Support/Casting.h"
33 #include "llvm/Support/CommandLine.h"
34 #include "llvm/Support/Debug.h"
35 #include "llvm/Support/Endian.h"
36 #include "llvm/Support/Format.h"
37 #include "llvm/Support/FormattedStream.h"
38 #include "llvm/Support/GraphWriter.h"
39 #include "llvm/Support/LEB128.h"
40 #include "llvm/Support/MachO.h"
41 #include "llvm/Support/MemoryBuffer.h"
42 #include "llvm/Support/TargetRegistry.h"
43 #include "llvm/Support/TargetSelect.h"
44 #include "llvm/Support/raw_ostream.h"
47 #include <system_error>
54 using namespace object;
58 cl::desc("Print line information from debug info if available"));
60 static cl::opt<std::string> DSYMFile("dsym",
61 cl::desc("Use .dSYM file for debug info"));
63 static cl::opt<bool> FullLeadingAddr("full-leading-addr",
64 cl::desc("Print full leading address"));
66 static cl::opt<bool> NoLeadingAddr("no-leading-addr",
67 cl::desc("Print no leading address"));
70 PrintImmHex("print-imm-hex",
71 cl::desc("Use hex format for immediate values"));
73 cl::opt<bool> llvm::UniversalHeaders("universal-headers",
74 cl::desc("Print Mach-O universal headers "
75 "(requires -macho)"));
78 llvm::ArchiveHeaders("archive-headers",
79 cl::desc("Print archive headers for Mach-O archives "
80 "(requires -macho)"));
83 llvm::IndirectSymbols("indirect-symbols",
84 cl::desc("Print indirect symbol table for Mach-O "
85 "objects (requires -macho)"));
88 llvm::DataInCode("data-in-code",
89 cl::desc("Print the data in code table for Mach-O objects "
90 "(requires -macho)"));
93 llvm::LinkOptHints("link-opt-hints",
94 cl::desc("Print the linker optimization hints for "
95 "Mach-O objects (requires -macho)"));
98 llvm::DumpSections("section",
99 cl::desc("Prints the specified segment,section for "
100 "Mach-O objects (requires -macho)"));
103 llvm::InfoPlist("info-plist",
104 cl::desc("Print the info plist section as strings for "
105 "Mach-O objects (requires -macho)"));
108 llvm::DylibsUsed("dylibs-used",
109 cl::desc("Print the shared libraries used for linked "
110 "Mach-O files (requires -macho)"));
113 llvm::DylibId("dylib-id",
114 cl::desc("Print the shared library's id for the dylib Mach-O "
115 "file (requires -macho)"));
118 llvm::NonVerbose("non-verbose",
119 cl::desc("Print the info for Mach-O objects in "
120 "non-verbose or numeric form (requires -macho)"));
122 cl::opt<std::string> llvm::DisSymName(
124 cl::desc("disassemble just this symbol's instructions (requires -macho"));
126 static cl::opt<bool> NoSymbolicOperands(
127 "no-symbolic-operands",
128 cl::desc("do not symbolic operands when disassembling (requires -macho)"));
131 static cl::list<std::string>
132 ArchFlags("arch", cl::desc("architecture(s) from a Mach-O file to dump"),
134 bool ArchAll = false;
136 static std::string ThumbTripleName;
138 static const Target *GetTarget(const MachOObjectFile *MachOObj,
139 const char **McpuDefault,
140 const Target **ThumbTarget) {
141 // Figure out the target triple.
142 if (TripleName.empty()) {
143 llvm::Triple TT("unknown-unknown-unknown");
144 llvm::Triple ThumbTriple = Triple();
145 TT = MachOObj->getArch(McpuDefault, &ThumbTriple);
146 TripleName = TT.str();
147 ThumbTripleName = ThumbTriple.str();
150 // Get the target specific parser.
152 const Target *TheTarget = TargetRegistry::lookupTarget(TripleName, Error);
153 if (TheTarget && ThumbTripleName.empty())
156 *ThumbTarget = TargetRegistry::lookupTarget(ThumbTripleName, Error);
160 errs() << "llvm-objdump: error: unable to get target for '";
162 errs() << TripleName;
164 errs() << ThumbTripleName;
165 errs() << "', see --version and --triple.\n";
169 struct SymbolSorter {
170 bool operator()(const SymbolRef &A, const SymbolRef &B) {
171 SymbolRef::Type AType, BType;
175 uint64_t AAddr, BAddr;
176 if (AType != SymbolRef::ST_Function)
180 if (BType != SymbolRef::ST_Function)
184 return AAddr < BAddr;
188 // Types for the storted data in code table that is built before disassembly
189 // and the predicate function to sort them.
190 typedef std::pair<uint64_t, DiceRef> DiceTableEntry;
191 typedef std::vector<DiceTableEntry> DiceTable;
192 typedef DiceTable::iterator dice_table_iterator;
194 // This is used to search for a data in code table entry for the PC being
195 // disassembled. The j parameter has the PC in j.first. A single data in code
196 // table entry can cover many bytes for each of its Kind's. So if the offset,
197 // aka the i.first value, of the data in code table entry plus its Length
198 // covers the PC being searched for this will return true. If not it will
200 static bool compareDiceTableEntries(const DiceTableEntry &i,
201 const DiceTableEntry &j) {
203 i.second.getLength(Length);
205 return j.first >= i.first && j.first < i.first + Length;
208 static uint64_t DumpDataInCode(const char *bytes, uint64_t Length,
209 unsigned short Kind) {
210 uint32_t Value, Size = 1;
214 case MachO::DICE_KIND_DATA:
217 DumpBytes(StringRef(bytes, 4));
218 Value = bytes[3] << 24 | bytes[2] << 16 | bytes[1] << 8 | bytes[0];
219 outs() << "\t.long " << Value;
221 } else if (Length >= 2) {
223 DumpBytes(StringRef(bytes, 2));
224 Value = bytes[1] << 8 | bytes[0];
225 outs() << "\t.short " << Value;
229 DumpBytes(StringRef(bytes, 2));
231 outs() << "\t.byte " << Value;
234 if (Kind == MachO::DICE_KIND_DATA)
235 outs() << "\t@ KIND_DATA\n";
237 outs() << "\t@ data in code kind = " << Kind << "\n";
239 case MachO::DICE_KIND_JUMP_TABLE8:
241 DumpBytes(StringRef(bytes, 1));
243 outs() << "\t.byte " << format("%3u", Value) << "\t@ KIND_JUMP_TABLE8\n";
246 case MachO::DICE_KIND_JUMP_TABLE16:
248 DumpBytes(StringRef(bytes, 2));
249 Value = bytes[1] << 8 | bytes[0];
250 outs() << "\t.short " << format("%5u", Value & 0xffff)
251 << "\t@ KIND_JUMP_TABLE16\n";
254 case MachO::DICE_KIND_JUMP_TABLE32:
255 case MachO::DICE_KIND_ABS_JUMP_TABLE32:
257 DumpBytes(StringRef(bytes, 4));
258 Value = bytes[3] << 24 | bytes[2] << 16 | bytes[1] << 8 | bytes[0];
259 outs() << "\t.long " << Value;
260 if (Kind == MachO::DICE_KIND_JUMP_TABLE32)
261 outs() << "\t@ KIND_JUMP_TABLE32\n";
263 outs() << "\t@ KIND_ABS_JUMP_TABLE32\n";
270 static void getSectionsAndSymbols(const MachO::mach_header Header,
271 MachOObjectFile *MachOObj,
272 std::vector<SectionRef> &Sections,
273 std::vector<SymbolRef> &Symbols,
274 SmallVectorImpl<uint64_t> &FoundFns,
275 uint64_t &BaseSegmentAddress) {
276 for (const SymbolRef &Symbol : MachOObj->symbols()) {
278 Symbol.getName(SymName);
279 if (!SymName.startswith("ltmp"))
280 Symbols.push_back(Symbol);
283 for (const SectionRef &Section : MachOObj->sections()) {
285 Section.getName(SectName);
286 Sections.push_back(Section);
289 MachOObjectFile::LoadCommandInfo Command =
290 MachOObj->getFirstLoadCommandInfo();
291 bool BaseSegmentAddressSet = false;
292 for (unsigned i = 0;; ++i) {
293 if (Command.C.cmd == MachO::LC_FUNCTION_STARTS) {
294 // We found a function starts segment, parse the addresses for later
296 MachO::linkedit_data_command LLC =
297 MachOObj->getLinkeditDataLoadCommand(Command);
299 MachOObj->ReadULEB128s(LLC.dataoff, FoundFns);
300 } else if (Command.C.cmd == MachO::LC_SEGMENT) {
301 MachO::segment_command SLC = MachOObj->getSegmentLoadCommand(Command);
302 StringRef SegName = SLC.segname;
303 if (!BaseSegmentAddressSet && SegName != "__PAGEZERO") {
304 BaseSegmentAddressSet = true;
305 BaseSegmentAddress = SLC.vmaddr;
309 if (i == Header.ncmds - 1)
312 Command = MachOObj->getNextLoadCommandInfo(Command);
316 static void PrintIndirectSymbolTable(MachOObjectFile *O, bool verbose,
317 uint32_t n, uint32_t count,
318 uint32_t stride, uint64_t addr) {
319 MachO::dysymtab_command Dysymtab = O->getDysymtabLoadCommand();
320 uint32_t nindirectsyms = Dysymtab.nindirectsyms;
321 if (n > nindirectsyms)
322 outs() << " (entries start past the end of the indirect symbol "
323 "table) (reserved1 field greater than the table size)";
324 else if (n + count > nindirectsyms)
325 outs() << " (entries extends past the end of the indirect symbol "
328 uint32_t cputype = O->getHeader().cputype;
329 if (cputype & MachO::CPU_ARCH_ABI64)
330 outs() << "address index";
332 outs() << "address index";
337 for (uint32_t j = 0; j < count && n + j < nindirectsyms; j++) {
338 if (cputype & MachO::CPU_ARCH_ABI64)
339 outs() << format("0x%016" PRIx64, addr + j * stride) << " ";
341 outs() << format("0x%08" PRIx32, addr + j * stride) << " ";
342 MachO::dysymtab_command Dysymtab = O->getDysymtabLoadCommand();
343 uint32_t indirect_symbol = O->getIndirectSymbolTableEntry(Dysymtab, n + j);
344 if (indirect_symbol == MachO::INDIRECT_SYMBOL_LOCAL) {
348 if (indirect_symbol ==
349 (MachO::INDIRECT_SYMBOL_LOCAL | MachO::INDIRECT_SYMBOL_ABS)) {
350 outs() << "LOCAL ABSOLUTE\n";
353 if (indirect_symbol == MachO::INDIRECT_SYMBOL_ABS) {
354 outs() << "ABSOLUTE\n";
357 outs() << format("%5u ", indirect_symbol);
359 MachO::symtab_command Symtab = O->getSymtabLoadCommand();
360 if (indirect_symbol < Symtab.nsyms) {
361 symbol_iterator Sym = O->getSymbolByIndex(indirect_symbol);
362 SymbolRef Symbol = *Sym;
364 Symbol.getName(SymName);
374 static void PrintIndirectSymbols(MachOObjectFile *O, bool verbose) {
375 uint32_t LoadCommandCount = O->getHeader().ncmds;
376 MachOObjectFile::LoadCommandInfo Load = O->getFirstLoadCommandInfo();
377 for (unsigned I = 0;; ++I) {
378 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
379 MachO::segment_command_64 Seg = O->getSegment64LoadCommand(Load);
380 for (unsigned J = 0; J < Seg.nsects; ++J) {
381 MachO::section_64 Sec = O->getSection64(Load, J);
382 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
383 if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
384 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
385 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
386 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
387 section_type == MachO::S_SYMBOL_STUBS) {
389 if (section_type == MachO::S_SYMBOL_STUBS)
390 stride = Sec.reserved2;
394 outs() << "Can't print indirect symbols for (" << Sec.segname << ","
395 << Sec.sectname << ") "
396 << "(size of stubs in reserved2 field is zero)\n";
399 uint32_t count = Sec.size / stride;
400 outs() << "Indirect symbols for (" << Sec.segname << ","
401 << Sec.sectname << ") " << count << " entries";
402 uint32_t n = Sec.reserved1;
403 PrintIndirectSymbolTable(O, verbose, n, count, stride, Sec.addr);
406 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
407 MachO::segment_command Seg = O->getSegmentLoadCommand(Load);
408 for (unsigned J = 0; J < Seg.nsects; ++J) {
409 MachO::section Sec = O->getSection(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) {
417 if (section_type == MachO::S_SYMBOL_STUBS)
418 stride = Sec.reserved2;
422 outs() << "Can't print indirect symbols for (" << Sec.segname << ","
423 << Sec.sectname << ") "
424 << "(size of stubs in reserved2 field is zero)\n";
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);
435 if (I == LoadCommandCount - 1)
438 Load = O->getNextLoadCommandInfo(Load);
442 static void PrintDataInCodeTable(MachOObjectFile *O, bool verbose) {
443 MachO::linkedit_data_command DIC = O->getDataInCodeLoadCommand();
444 uint32_t nentries = DIC.datasize / sizeof(struct MachO::data_in_code_entry);
445 outs() << "Data in code table (" << nentries << " entries)\n";
446 outs() << "offset length kind\n";
447 for (dice_iterator DI = O->begin_dices(), DE = O->end_dices(); DI != DE;
450 DI->getOffset(Offset);
451 outs() << format("0x%08" PRIx32, Offset) << " ";
453 DI->getLength(Length);
454 outs() << format("%6u", Length) << " ";
459 case MachO::DICE_KIND_DATA:
462 case MachO::DICE_KIND_JUMP_TABLE8:
463 outs() << "JUMP_TABLE8";
465 case MachO::DICE_KIND_JUMP_TABLE16:
466 outs() << "JUMP_TABLE16";
468 case MachO::DICE_KIND_JUMP_TABLE32:
469 outs() << "JUMP_TABLE32";
471 case MachO::DICE_KIND_ABS_JUMP_TABLE32:
472 outs() << "ABS_JUMP_TABLE32";
475 outs() << format("0x%04" PRIx32, Kind);
479 outs() << format("0x%04" PRIx32, Kind);
484 static void PrintLinkOptHints(MachOObjectFile *O) {
485 MachO::linkedit_data_command LohLC = O->getLinkOptHintsLoadCommand();
486 const char *loh = O->getData().substr(LohLC.dataoff, 1).data();
487 uint32_t nloh = LohLC.datasize;
488 outs() << "Linker optimiztion hints (" << nloh << " total bytes)\n";
489 for (uint32_t i = 0; i < nloh;) {
491 uint64_t identifier = decodeULEB128((const uint8_t *)(loh + i), &n);
493 outs() << " identifier " << identifier << " ";
496 switch (identifier) {
498 outs() << "AdrpAdrp\n";
501 outs() << "AdrpLdr\n";
504 outs() << "AdrpAddLdr\n";
507 outs() << "AdrpLdrGotLdr\n";
510 outs() << "AdrpAddStr\n";
513 outs() << "AdrpLdrGotStr\n";
516 outs() << "AdrpAdd\n";
519 outs() << "AdrpLdrGot\n";
522 outs() << "Unknown identifier value\n";
525 uint64_t narguments = decodeULEB128((const uint8_t *)(loh + i), &n);
527 outs() << " narguments " << narguments << "\n";
531 for (uint32_t j = 0; j < narguments; j++) {
532 uint64_t value = decodeULEB128((const uint8_t *)(loh + i), &n);
534 outs() << "\tvalue " << format("0x%" PRIx64, value) << "\n";
541 static void PrintDylibs(MachOObjectFile *O, bool JustId) {
542 uint32_t LoadCommandCount = O->getHeader().ncmds;
543 MachOObjectFile::LoadCommandInfo Load = O->getFirstLoadCommandInfo();
544 for (unsigned I = 0;; ++I) {
545 if ((JustId && Load.C.cmd == MachO::LC_ID_DYLIB) ||
546 (!JustId && (Load.C.cmd == MachO::LC_ID_DYLIB ||
547 Load.C.cmd == MachO::LC_LOAD_DYLIB ||
548 Load.C.cmd == MachO::LC_LOAD_WEAK_DYLIB ||
549 Load.C.cmd == MachO::LC_REEXPORT_DYLIB ||
550 Load.C.cmd == MachO::LC_LAZY_LOAD_DYLIB ||
551 Load.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB))) {
552 MachO::dylib_command dl = O->getDylibIDLoadCommand(Load);
553 if (dl.dylib.name < dl.cmdsize) {
554 const char *p = (const char *)(Load.Ptr) + dl.dylib.name;
559 outs() << " (compatibility version "
560 << ((dl.dylib.compatibility_version >> 16) & 0xffff) << "."
561 << ((dl.dylib.compatibility_version >> 8) & 0xff) << "."
562 << (dl.dylib.compatibility_version & 0xff) << ",";
563 outs() << " current version "
564 << ((dl.dylib.current_version >> 16) & 0xffff) << "."
565 << ((dl.dylib.current_version >> 8) & 0xff) << "."
566 << (dl.dylib.current_version & 0xff) << ")\n";
569 outs() << "\tBad offset (" << dl.dylib.name << ") for name of ";
570 if (Load.C.cmd == MachO::LC_ID_DYLIB)
571 outs() << "LC_ID_DYLIB ";
572 else if (Load.C.cmd == MachO::LC_LOAD_DYLIB)
573 outs() << "LC_LOAD_DYLIB ";
574 else if (Load.C.cmd == MachO::LC_LOAD_WEAK_DYLIB)
575 outs() << "LC_LOAD_WEAK_DYLIB ";
576 else if (Load.C.cmd == MachO::LC_LAZY_LOAD_DYLIB)
577 outs() << "LC_LAZY_LOAD_DYLIB ";
578 else if (Load.C.cmd == MachO::LC_REEXPORT_DYLIB)
579 outs() << "LC_REEXPORT_DYLIB ";
580 else if (Load.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB)
581 outs() << "LC_LOAD_UPWARD_DYLIB ";
584 outs() << "command " << I << "\n";
587 if (I == LoadCommandCount - 1)
590 Load = O->getNextLoadCommandInfo(Load);
594 typedef DenseMap<uint64_t, StringRef> SymbolAddressMap;
596 static void CreateSymbolAddressMap(MachOObjectFile *O,
597 SymbolAddressMap *AddrMap) {
598 // Create a map of symbol addresses to symbol names.
599 for (const SymbolRef &Symbol : O->symbols()) {
602 if (ST == SymbolRef::ST_Function || ST == SymbolRef::ST_Data ||
603 ST == SymbolRef::ST_Other) {
605 Symbol.getAddress(Address);
607 Symbol.getName(SymName);
608 (*AddrMap)[Address] = SymName;
613 // GuessSymbolName is passed the address of what might be a symbol and a
614 // pointer to the SymbolAddressMap. It returns the name of a symbol
615 // with that address or nullptr if no symbol is found with that address.
616 static const char *GuessSymbolName(uint64_t value, SymbolAddressMap *AddrMap) {
617 const char *SymbolName = nullptr;
618 // A DenseMap can't lookup up some values.
619 if (value != 0xffffffffffffffffULL && value != 0xfffffffffffffffeULL) {
620 StringRef name = AddrMap->lookup(value);
622 SymbolName = name.data();
627 static void DumpCstringChar(const char c) {
631 outs().write_escaped(p);
634 static void DumpCstringSection(MachOObjectFile *O, const char *sect,
635 uint32_t sect_size, uint64_t sect_addr,
636 bool print_addresses) {
637 for (uint32_t i = 0; i < sect_size; i++) {
638 if (print_addresses) {
640 outs() << format("%016" PRIx64, sect_addr + i) << " ";
642 outs() << format("%08" PRIx64, sect_addr + i) << " ";
644 for (; i < sect_size && sect[i] != '\0'; i++)
645 DumpCstringChar(sect[i]);
646 if (i < sect_size && sect[i] == '\0')
651 static void DumpLiteral4(uint32_t l, float f) {
652 outs() << format("0x%08" PRIx32, l);
653 if ((l & 0x7f800000) != 0x7f800000)
654 outs() << format(" (%.16e)\n", f);
657 outs() << " (+Infinity)\n";
658 else if (l == 0xff800000)
659 outs() << " (-Infinity)\n";
660 else if ((l & 0x00400000) == 0x00400000)
661 outs() << " (non-signaling Not-a-Number)\n";
663 outs() << " (signaling Not-a-Number)\n";
667 static void DumpLiteral4Section(MachOObjectFile *O, const char *sect,
668 uint32_t sect_size, uint64_t sect_addr,
669 bool print_addresses) {
670 for (uint32_t i = 0; i < sect_size; i += sizeof(float)) {
671 if (print_addresses) {
673 outs() << format("%016" PRIx64, sect_addr + i) << " ";
675 outs() << format("%08" PRIx64, sect_addr + i) << " ";
678 memcpy(&f, sect + i, sizeof(float));
679 if (O->isLittleEndian() != sys::IsLittleEndianHost)
680 sys::swapByteOrder(f);
682 memcpy(&l, sect + i, sizeof(uint32_t));
683 if (O->isLittleEndian() != sys::IsLittleEndianHost)
684 sys::swapByteOrder(l);
689 static void DumpLiteral8(MachOObjectFile *O, uint32_t l0, uint32_t l1,
691 outs() << format("0x%08" PRIx32, l0) << " " << format("0x%08" PRIx32, l1);
693 if (O->isLittleEndian()) {
700 // Hi is the high word, so this is equivalent to if(isfinite(d))
701 if ((Hi & 0x7ff00000) != 0x7ff00000)
702 outs() << format(" (%.16e)\n", d);
704 if (Hi == 0x7ff00000 && Lo == 0)
705 outs() << " (+Infinity)\n";
706 else if (Hi == 0xfff00000 && Lo == 0)
707 outs() << " (-Infinity)\n";
708 else if ((Hi & 0x00080000) == 0x00080000)
709 outs() << " (non-signaling Not-a-Number)\n";
711 outs() << " (signaling Not-a-Number)\n";
715 static void DumpLiteral8Section(MachOObjectFile *O, const char *sect,
716 uint32_t sect_size, uint64_t sect_addr,
717 bool print_addresses) {
718 for (uint32_t i = 0; i < sect_size; i += sizeof(double)) {
719 if (print_addresses) {
721 outs() << format("%016" PRIx64, sect_addr + i) << " ";
723 outs() << format("%08" PRIx64, sect_addr + i) << " ";
726 memcpy(&d, sect + i, sizeof(double));
727 if (O->isLittleEndian() != sys::IsLittleEndianHost)
728 sys::swapByteOrder(d);
730 memcpy(&l0, sect + i, sizeof(uint32_t));
731 memcpy(&l1, sect + i + sizeof(uint32_t), sizeof(uint32_t));
732 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
733 sys::swapByteOrder(l0);
734 sys::swapByteOrder(l1);
736 DumpLiteral8(O, l0, l1, d);
740 static void DumpLiteral16(uint32_t l0, uint32_t l1, uint32_t l2, uint32_t l3) {
741 outs() << format("0x%08" PRIx32, l0) << " ";
742 outs() << format("0x%08" PRIx32, l1) << " ";
743 outs() << format("0x%08" PRIx32, l2) << " ";
744 outs() << format("0x%08" PRIx32, l3) << "\n";
747 static void DumpLiteral16Section(MachOObjectFile *O, const char *sect,
748 uint32_t sect_size, uint64_t sect_addr,
749 bool print_addresses) {
750 for (uint32_t i = 0; i < sect_size; i += 16) {
751 if (print_addresses) {
753 outs() << format("%016" PRIx64, sect_addr + i) << " ";
755 outs() << format("%08" PRIx64, sect_addr + i) << " ";
757 uint32_t l0, l1, l2, l3;
758 memcpy(&l0, sect + i, sizeof(uint32_t));
759 memcpy(&l1, sect + i + sizeof(uint32_t), sizeof(uint32_t));
760 memcpy(&l2, sect + i + 2 * sizeof(uint32_t), sizeof(uint32_t));
761 memcpy(&l3, sect + i + 3 * sizeof(uint32_t), sizeof(uint32_t));
762 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
763 sys::swapByteOrder(l0);
764 sys::swapByteOrder(l1);
765 sys::swapByteOrder(l2);
766 sys::swapByteOrder(l3);
768 DumpLiteral16(l0, l1, l2, l3);
772 static void DumpLiteralPointerSection(MachOObjectFile *O,
773 const SectionRef &Section,
774 const char *sect, uint32_t sect_size,
776 bool print_addresses) {
777 // Collect the literal sections in this Mach-O file.
778 std::vector<SectionRef> LiteralSections;
779 for (const SectionRef &Section : O->sections()) {
780 DataRefImpl Ref = Section.getRawDataRefImpl();
781 uint32_t section_type;
783 const MachO::section_64 Sec = O->getSection64(Ref);
784 section_type = Sec.flags & MachO::SECTION_TYPE;
786 const MachO::section Sec = O->getSection(Ref);
787 section_type = Sec.flags & MachO::SECTION_TYPE;
789 if (section_type == MachO::S_CSTRING_LITERALS ||
790 section_type == MachO::S_4BYTE_LITERALS ||
791 section_type == MachO::S_8BYTE_LITERALS ||
792 section_type == MachO::S_16BYTE_LITERALS)
793 LiteralSections.push_back(Section);
796 // Set the size of the literal pointer.
797 uint32_t lp_size = O->is64Bit() ? 8 : 4;
799 // Collect the external relocation symbols for the the literal pointers.
800 std::vector<std::pair<uint64_t, SymbolRef>> Relocs;
801 for (const RelocationRef &Reloc : Section.relocations()) {
803 MachO::any_relocation_info RE;
804 bool isExtern = false;
805 Rel = Reloc.getRawDataRefImpl();
806 RE = O->getRelocation(Rel);
807 isExtern = O->getPlainRelocationExternal(RE);
809 uint64_t RelocOffset;
810 Reloc.getOffset(RelocOffset);
811 symbol_iterator RelocSym = Reloc.getSymbol();
812 Relocs.push_back(std::make_pair(RelocOffset, *RelocSym));
815 array_pod_sort(Relocs.begin(), Relocs.end());
817 // Dump each literal pointer.
818 for (uint32_t i = 0; i < sect_size; i += lp_size) {
819 if (print_addresses) {
821 outs() << format("%016" PRIx64, sect_addr + i) << " ";
823 outs() << format("%08" PRIx64, sect_addr + i) << " ";
827 memcpy(&lp, sect + i, sizeof(uint64_t));
828 if (O->isLittleEndian() != sys::IsLittleEndianHost)
829 sys::swapByteOrder(lp);
832 memcpy(&li, sect + i, sizeof(uint32_t));
833 if (O->isLittleEndian() != sys::IsLittleEndianHost)
834 sys::swapByteOrder(li);
838 // First look for an external relocation entry for this literal pointer.
839 bool reloc_found = false;
840 for (unsigned j = 0, e = Relocs.size(); j != e; ++j) {
841 if (Relocs[i].first == i) {
842 symbol_iterator RelocSym = Relocs[j].second;
844 RelocSym->getName(SymName);
845 outs() << "external relocation entry for symbol:" << SymName << "\n";
849 if (reloc_found == true)
852 // For local references see what the section the literal pointer points to.
854 for (unsigned SectIdx = 0; SectIdx != LiteralSections.size(); SectIdx++) {
855 uint64_t SectAddress = LiteralSections[SectIdx].getAddress();
856 uint64_t SectSize = LiteralSections[SectIdx].getSize();
857 if (lp >= SectAddress && lp < SectAddress + SectSize) {
861 LiteralSections[SectIdx].getName(SectName);
862 DataRefImpl Ref = LiteralSections[SectIdx].getRawDataRefImpl();
863 StringRef SegmentName = O->getSectionFinalSegmentName(Ref);
864 outs() << SegmentName << ":" << SectName << ":";
866 uint32_t section_type;
868 const MachO::section_64 Sec = O->getSection64(Ref);
869 section_type = Sec.flags & MachO::SECTION_TYPE;
871 const MachO::section Sec = O->getSection(Ref);
872 section_type = Sec.flags & MachO::SECTION_TYPE;
876 LiteralSections[SectIdx].getContents(BytesStr);
877 const char *Contents = reinterpret_cast<const char *>(BytesStr.data());
879 switch (section_type) {
880 case MachO::S_CSTRING_LITERALS:
881 for (uint64_t i = lp - SectAddress;
882 i < SectSize && Contents[i] != '\0'; i++) {
883 DumpCstringChar(Contents[i]);
887 case MachO::S_4BYTE_LITERALS:
889 memcpy(&f, Contents + (lp - SectAddress), sizeof(float));
891 memcpy(&l, Contents + (lp - SectAddress), sizeof(uint32_t));
892 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
893 sys::swapByteOrder(f);
894 sys::swapByteOrder(l);
898 case MachO::S_8BYTE_LITERALS: {
900 memcpy(&d, Contents + (lp - SectAddress), sizeof(double));
902 memcpy(&l0, Contents + (lp - SectAddress), sizeof(uint32_t));
903 memcpy(&l1, Contents + (lp - SectAddress) + sizeof(uint32_t),
905 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
906 sys::swapByteOrder(f);
907 sys::swapByteOrder(l0);
908 sys::swapByteOrder(l1);
910 DumpLiteral8(O, l0, l1, d);
913 case MachO::S_16BYTE_LITERALS: {
914 uint32_t l0, l1, l2, l3;
915 memcpy(&l0, Contents + (lp - SectAddress), sizeof(uint32_t));
916 memcpy(&l1, Contents + (lp - SectAddress) + sizeof(uint32_t),
918 memcpy(&l2, Contents + (lp - SectAddress) + 2 * sizeof(uint32_t),
920 memcpy(&l3, Contents + (lp - SectAddress) + 3 * sizeof(uint32_t),
922 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
923 sys::swapByteOrder(l0);
924 sys::swapByteOrder(l1);
925 sys::swapByteOrder(l2);
926 sys::swapByteOrder(l3);
928 DumpLiteral16(l0, l1, l2, l3);
935 outs() << format("0x%" PRIx64, lp) << " (not in a literal section)\n";
939 static void DumpInitTermPointerSection(MachOObjectFile *O, const char *sect,
940 uint32_t sect_size, uint64_t sect_addr,
941 SymbolAddressMap *AddrMap,
945 stride = sizeof(uint64_t);
947 stride = sizeof(uint32_t);
948 for (uint32_t i = 0; i < sect_size; i += stride) {
949 const char *SymbolName = nullptr;
951 outs() << format("0x%016" PRIx64, sect_addr + i * stride) << " ";
952 uint64_t pointer_value;
953 memcpy(&pointer_value, sect + i, stride);
954 if (O->isLittleEndian() != sys::IsLittleEndianHost)
955 sys::swapByteOrder(pointer_value);
956 outs() << format("0x%016" PRIx64, pointer_value);
958 SymbolName = GuessSymbolName(pointer_value, AddrMap);
960 outs() << format("0x%08" PRIx64, sect_addr + i * stride) << " ";
961 uint32_t pointer_value;
962 memcpy(&pointer_value, sect + i, stride);
963 if (O->isLittleEndian() != sys::IsLittleEndianHost)
964 sys::swapByteOrder(pointer_value);
965 outs() << format("0x%08" PRIx32, pointer_value);
967 SymbolName = GuessSymbolName(pointer_value, AddrMap);
970 outs() << " " << SymbolName;
975 static void DumpRawSectionContents(MachOObjectFile *O, const char *sect,
976 uint32_t size, uint64_t addr) {
977 uint32_t cputype = O->getHeader().cputype;
978 if (cputype == MachO::CPU_TYPE_I386 || cputype == MachO::CPU_TYPE_X86_64) {
980 for (uint32_t i = 0; i < size; i += j, addr += j) {
982 outs() << format("%016" PRIx64, addr) << "\t";
984 outs() << format("%08" PRIx64, addr) << "\t";
985 for (j = 0; j < 16 && i + j < size; j++) {
986 uint8_t byte_word = *(sect + i + j);
987 outs() << format("%02" PRIx32, (uint32_t)byte_word) << " ";
993 for (uint32_t i = 0; i < size; i += j, addr += j) {
995 outs() << format("%016" PRIx64, addr) << "\t";
997 outs() << format("%08" PRIx64, sect) << "\t";
998 for (j = 0; j < 4 * sizeof(int32_t) && i + j < size;
999 j += sizeof(int32_t)) {
1000 if (i + j + sizeof(int32_t) < size) {
1002 memcpy(&long_word, sect + i + j, sizeof(int32_t));
1003 if (O->isLittleEndian() != sys::IsLittleEndianHost)
1004 sys::swapByteOrder(long_word);
1005 outs() << format("%08" PRIx32, long_word) << " ";
1007 for (uint32_t k = 0; i + j + k < size; k++) {
1008 uint8_t byte_word = *(sect + i + j);
1009 outs() << format("%02" PRIx32, (uint32_t)byte_word) << " ";
1018 static void DisassembleMachO(StringRef Filename, MachOObjectFile *MachOOF,
1019 StringRef DisSegName, StringRef DisSectName);
1021 static void DumpSectionContents(StringRef Filename, MachOObjectFile *O,
1023 SymbolAddressMap AddrMap;
1025 CreateSymbolAddressMap(O, &AddrMap);
1027 for (unsigned i = 0; i < DumpSections.size(); ++i) {
1028 StringRef DumpSection = DumpSections[i];
1029 std::pair<StringRef, StringRef> DumpSegSectName;
1030 DumpSegSectName = DumpSection.split(',');
1031 StringRef DumpSegName, DumpSectName;
1032 if (DumpSegSectName.second.size()) {
1033 DumpSegName = DumpSegSectName.first;
1034 DumpSectName = DumpSegSectName.second;
1037 DumpSectName = DumpSegSectName.first;
1039 for (const SectionRef &Section : O->sections()) {
1041 Section.getName(SectName);
1042 DataRefImpl Ref = Section.getRawDataRefImpl();
1043 StringRef SegName = O->getSectionFinalSegmentName(Ref);
1044 if ((DumpSegName.empty() || SegName == DumpSegName) &&
1045 (SectName == DumpSectName)) {
1046 outs() << "Contents of (" << SegName << "," << SectName
1048 uint32_t section_flags;
1050 const MachO::section_64 Sec = O->getSection64(Ref);
1051 section_flags = Sec.flags;
1054 const MachO::section Sec = O->getSection(Ref);
1055 section_flags = Sec.flags;
1057 uint32_t section_type = section_flags & MachO::SECTION_TYPE;
1060 Section.getContents(BytesStr);
1061 const char *sect = reinterpret_cast<const char *>(BytesStr.data());
1062 uint32_t sect_size = BytesStr.size();
1063 uint64_t sect_addr = Section.getAddress();
1066 if ((section_flags & MachO::S_ATTR_PURE_INSTRUCTIONS) ||
1067 (section_flags & MachO::S_ATTR_SOME_INSTRUCTIONS)) {
1068 DisassembleMachO(Filename, O, SegName, SectName);
1071 if (SegName == "__TEXT" && SectName == "__info_plist") {
1075 switch (section_type) {
1076 case MachO::S_REGULAR:
1077 DumpRawSectionContents(O, sect, sect_size, sect_addr);
1079 case MachO::S_ZEROFILL:
1080 outs() << "zerofill section and has no contents in the file\n";
1082 case MachO::S_CSTRING_LITERALS:
1083 DumpCstringSection(O, sect, sect_size, sect_addr, !NoLeadingAddr);
1085 case MachO::S_4BYTE_LITERALS:
1086 DumpLiteral4Section(O, sect, sect_size, sect_addr, !NoLeadingAddr);
1088 case MachO::S_8BYTE_LITERALS:
1089 DumpLiteral8Section(O, sect, sect_size, sect_addr, !NoLeadingAddr);
1091 case MachO::S_16BYTE_LITERALS:
1092 DumpLiteral16Section(O, sect, sect_size, sect_addr, !NoLeadingAddr);
1094 case MachO::S_LITERAL_POINTERS:
1095 DumpLiteralPointerSection(O, Section, sect, sect_size, sect_addr,
1098 case MachO::S_MOD_INIT_FUNC_POINTERS:
1099 case MachO::S_MOD_TERM_FUNC_POINTERS:
1100 DumpInitTermPointerSection(O, sect, sect_size, sect_addr, &AddrMap,
1104 outs() << "Unknown section type ("
1105 << format("0x%08" PRIx32, section_type) << ")\n";
1106 DumpRawSectionContents(O, sect, sect_size, sect_addr);
1110 if (section_type == MachO::S_ZEROFILL)
1111 outs() << "zerofill section and has no contents in the file\n";
1113 DumpRawSectionContents(O, sect, sect_size, sect_addr);
1120 static void DumpInfoPlistSectionContents(StringRef Filename,
1121 MachOObjectFile *O) {
1122 for (const SectionRef &Section : O->sections()) {
1124 Section.getName(SectName);
1125 DataRefImpl Ref = Section.getRawDataRefImpl();
1126 StringRef SegName = O->getSectionFinalSegmentName(Ref);
1127 if (SegName == "__TEXT" && SectName == "__info_plist") {
1128 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
1130 Section.getContents(BytesStr);
1131 const char *sect = reinterpret_cast<const char *>(BytesStr.data());
1138 // checkMachOAndArchFlags() checks to see if the ObjectFile is a Mach-O file
1139 // and if it is and there is a list of architecture flags is specified then
1140 // check to make sure this Mach-O file is one of those architectures or all
1141 // architectures were specified. If not then an error is generated and this
1142 // routine returns false. Else it returns true.
1143 static bool checkMachOAndArchFlags(ObjectFile *O, StringRef Filename) {
1144 if (isa<MachOObjectFile>(O) && !ArchAll && ArchFlags.size() != 0) {
1145 MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(O);
1146 bool ArchFound = false;
1147 MachO::mach_header H;
1148 MachO::mach_header_64 H_64;
1150 if (MachO->is64Bit()) {
1151 H_64 = MachO->MachOObjectFile::getHeader64();
1152 T = MachOObjectFile::getArch(H_64.cputype, H_64.cpusubtype);
1154 H = MachO->MachOObjectFile::getHeader();
1155 T = MachOObjectFile::getArch(H.cputype, H.cpusubtype);
1158 for (i = 0; i < ArchFlags.size(); ++i) {
1159 if (ArchFlags[i] == T.getArchName())
1164 errs() << "llvm-objdump: file: " + Filename + " does not contain "
1165 << "architecture: " + ArchFlags[i] + "\n";
1172 // ProcessMachO() is passed a single opened Mach-O file, which may be an
1173 // archive member and or in a slice of a universal file. It prints the
1174 // the file name and header info and then processes it according to the
1175 // command line options.
1176 static void ProcessMachO(StringRef Filename, MachOObjectFile *MachOOF,
1177 StringRef ArchiveMemberName = StringRef(),
1178 StringRef ArchitectureName = StringRef()) {
1179 // If we are doing some processing here on the Mach-O file print the header
1180 // info. And don't print it otherwise like in the case of printing the
1181 // UniversalHeaders or ArchiveHeaders.
1182 if (Disassemble || PrivateHeaders || ExportsTrie || Rebase || Bind ||
1183 LazyBind || WeakBind || IndirectSymbols || DataInCode || LinkOptHints ||
1184 DylibsUsed || DylibId || DumpSections.size() != 0) {
1186 if (!ArchiveMemberName.empty())
1187 outs() << '(' << ArchiveMemberName << ')';
1188 if (!ArchitectureName.empty())
1189 outs() << " (architecture " << ArchitectureName << ")";
1194 DisassembleMachO(Filename, MachOOF, "__TEXT", "__text");
1195 if (IndirectSymbols)
1196 PrintIndirectSymbols(MachOOF, !NonVerbose);
1198 PrintDataInCodeTable(MachOOF, !NonVerbose);
1200 PrintLinkOptHints(MachOOF);
1202 PrintRelocations(MachOOF);
1204 PrintSectionHeaders(MachOOF);
1205 if (SectionContents)
1206 PrintSectionContents(MachOOF);
1207 if (DumpSections.size() != 0)
1208 DumpSectionContents(Filename, MachOOF, !NonVerbose);
1210 DumpInfoPlistSectionContents(Filename, MachOOF);
1212 PrintDylibs(MachOOF, false);
1214 PrintDylibs(MachOOF, true);
1216 PrintSymbolTable(MachOOF);
1218 printMachOUnwindInfo(MachOOF);
1220 printMachOFileHeader(MachOOF);
1222 printExportsTrie(MachOOF);
1224 printRebaseTable(MachOOF);
1226 printBindTable(MachOOF);
1228 printLazyBindTable(MachOOF);
1230 printWeakBindTable(MachOOF);
1233 // printUnknownCPUType() helps print_fat_headers for unknown CPU's.
1234 static void printUnknownCPUType(uint32_t cputype, uint32_t cpusubtype) {
1235 outs() << " cputype (" << cputype << ")\n";
1236 outs() << " cpusubtype (" << cpusubtype << ")\n";
1239 // printCPUType() helps print_fat_headers by printing the cputype and
1240 // pusubtype (symbolically for the one's it knows about).
1241 static void printCPUType(uint32_t cputype, uint32_t cpusubtype) {
1243 case MachO::CPU_TYPE_I386:
1244 switch (cpusubtype) {
1245 case MachO::CPU_SUBTYPE_I386_ALL:
1246 outs() << " cputype CPU_TYPE_I386\n";
1247 outs() << " cpusubtype CPU_SUBTYPE_I386_ALL\n";
1250 printUnknownCPUType(cputype, cpusubtype);
1254 case MachO::CPU_TYPE_X86_64:
1255 switch (cpusubtype) {
1256 case MachO::CPU_SUBTYPE_X86_64_ALL:
1257 outs() << " cputype CPU_TYPE_X86_64\n";
1258 outs() << " cpusubtype CPU_SUBTYPE_X86_64_ALL\n";
1260 case MachO::CPU_SUBTYPE_X86_64_H:
1261 outs() << " cputype CPU_TYPE_X86_64\n";
1262 outs() << " cpusubtype CPU_SUBTYPE_X86_64_H\n";
1265 printUnknownCPUType(cputype, cpusubtype);
1269 case MachO::CPU_TYPE_ARM:
1270 switch (cpusubtype) {
1271 case MachO::CPU_SUBTYPE_ARM_ALL:
1272 outs() << " cputype CPU_TYPE_ARM\n";
1273 outs() << " cpusubtype CPU_SUBTYPE_ARM_ALL\n";
1275 case MachO::CPU_SUBTYPE_ARM_V4T:
1276 outs() << " cputype CPU_TYPE_ARM\n";
1277 outs() << " cpusubtype CPU_SUBTYPE_ARM_V4T\n";
1279 case MachO::CPU_SUBTYPE_ARM_V5TEJ:
1280 outs() << " cputype CPU_TYPE_ARM\n";
1281 outs() << " cpusubtype CPU_SUBTYPE_ARM_V5TEJ\n";
1283 case MachO::CPU_SUBTYPE_ARM_XSCALE:
1284 outs() << " cputype CPU_TYPE_ARM\n";
1285 outs() << " cpusubtype CPU_SUBTYPE_ARM_XSCALE\n";
1287 case MachO::CPU_SUBTYPE_ARM_V6:
1288 outs() << " cputype CPU_TYPE_ARM\n";
1289 outs() << " cpusubtype CPU_SUBTYPE_ARM_V6\n";
1291 case MachO::CPU_SUBTYPE_ARM_V6M:
1292 outs() << " cputype CPU_TYPE_ARM\n";
1293 outs() << " cpusubtype CPU_SUBTYPE_ARM_V6M\n";
1295 case MachO::CPU_SUBTYPE_ARM_V7:
1296 outs() << " cputype CPU_TYPE_ARM\n";
1297 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7\n";
1299 case MachO::CPU_SUBTYPE_ARM_V7EM:
1300 outs() << " cputype CPU_TYPE_ARM\n";
1301 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7EM\n";
1303 case MachO::CPU_SUBTYPE_ARM_V7K:
1304 outs() << " cputype CPU_TYPE_ARM\n";
1305 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7K\n";
1307 case MachO::CPU_SUBTYPE_ARM_V7M:
1308 outs() << " cputype CPU_TYPE_ARM\n";
1309 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7M\n";
1311 case MachO::CPU_SUBTYPE_ARM_V7S:
1312 outs() << " cputype CPU_TYPE_ARM\n";
1313 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7S\n";
1316 printUnknownCPUType(cputype, cpusubtype);
1320 case MachO::CPU_TYPE_ARM64:
1321 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
1322 case MachO::CPU_SUBTYPE_ARM64_ALL:
1323 outs() << " cputype CPU_TYPE_ARM64\n";
1324 outs() << " cpusubtype CPU_SUBTYPE_ARM64_ALL\n";
1327 printUnknownCPUType(cputype, cpusubtype);
1332 printUnknownCPUType(cputype, cpusubtype);
1337 static void printMachOUniversalHeaders(const object::MachOUniversalBinary *UB,
1339 outs() << "Fat headers\n";
1341 outs() << "fat_magic FAT_MAGIC\n";
1343 outs() << "fat_magic " << format("0x%" PRIx32, MachO::FAT_MAGIC) << "\n";
1345 uint32_t nfat_arch = UB->getNumberOfObjects();
1346 StringRef Buf = UB->getData();
1347 uint64_t size = Buf.size();
1348 uint64_t big_size = sizeof(struct MachO::fat_header) +
1349 nfat_arch * sizeof(struct MachO::fat_arch);
1350 outs() << "nfat_arch " << UB->getNumberOfObjects();
1352 outs() << " (malformed, contains zero architecture types)\n";
1353 else if (big_size > size)
1354 outs() << " (malformed, architectures past end of file)\n";
1358 for (uint32_t i = 0; i < nfat_arch; ++i) {
1359 MachOUniversalBinary::ObjectForArch OFA(UB, i);
1360 uint32_t cputype = OFA.getCPUType();
1361 uint32_t cpusubtype = OFA.getCPUSubType();
1362 outs() << "architecture ";
1363 for (uint32_t j = 0; i != 0 && j <= i - 1; j++) {
1364 MachOUniversalBinary::ObjectForArch other_OFA(UB, j);
1365 uint32_t other_cputype = other_OFA.getCPUType();
1366 uint32_t other_cpusubtype = other_OFA.getCPUSubType();
1367 if (cputype != 0 && cpusubtype != 0 && cputype == other_cputype &&
1368 (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) ==
1369 (other_cpusubtype & ~MachO::CPU_SUBTYPE_MASK)) {
1370 outs() << "(illegal duplicate architecture) ";
1375 outs() << OFA.getArchTypeName() << "\n";
1376 printCPUType(cputype, cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
1378 outs() << i << "\n";
1379 outs() << " cputype " << cputype << "\n";
1380 outs() << " cpusubtype " << (cpusubtype & ~MachO::CPU_SUBTYPE_MASK)
1384 (cpusubtype & MachO::CPU_SUBTYPE_MASK) == MachO::CPU_SUBTYPE_LIB64)
1385 outs() << " capabilities CPU_SUBTYPE_LIB64\n";
1387 outs() << " capabilities "
1388 << format("0x%" PRIx32,
1389 (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24) << "\n";
1390 outs() << " offset " << OFA.getOffset();
1391 if (OFA.getOffset() > size)
1392 outs() << " (past end of file)";
1393 if (OFA.getOffset() % (1 << OFA.getAlign()) != 0)
1394 outs() << " (not aligned on it's alignment (2^" << OFA.getAlign() << ")";
1396 outs() << " size " << OFA.getSize();
1397 big_size = OFA.getOffset() + OFA.getSize();
1398 if (big_size > size)
1399 outs() << " (past end of file)";
1401 outs() << " align 2^" << OFA.getAlign() << " (" << (1 << OFA.getAlign())
1406 static void printArchiveChild(Archive::Child &C, bool verbose,
1407 bool print_offset) {
1409 outs() << C.getChildOffset() << "\t";
1410 sys::fs::perms Mode = C.getAccessMode();
1412 // FIXME: this first dash, "-", is for (Mode & S_IFMT) == S_IFREG.
1413 // But there is nothing in sys::fs::perms for S_IFMT or S_IFREG.
1415 if (Mode & sys::fs::owner_read)
1419 if (Mode & sys::fs::owner_write)
1423 if (Mode & sys::fs::owner_exe)
1427 if (Mode & sys::fs::group_read)
1431 if (Mode & sys::fs::group_write)
1435 if (Mode & sys::fs::group_exe)
1439 if (Mode & sys::fs::others_read)
1443 if (Mode & sys::fs::others_write)
1447 if (Mode & sys::fs::others_exe)
1452 outs() << format("0%o ", Mode);
1455 unsigned UID = C.getUID();
1456 outs() << format("%3d/", UID);
1457 unsigned GID = C.getGID();
1458 outs() << format("%-3d ", GID);
1459 uint64_t Size = C.getRawSize();
1460 outs() << format("%5" PRId64, Size) << " ";
1462 StringRef RawLastModified = C.getRawLastModified();
1465 if (RawLastModified.getAsInteger(10, Seconds))
1466 outs() << "(date: \"%s\" contains non-decimal chars) " << RawLastModified;
1468 // Since cime(3) returns a 26 character string of the form:
1469 // "Sun Sep 16 01:03:52 1973\n\0"
1470 // just print 24 characters.
1472 outs() << format("%.24s ", ctime(&t));
1475 outs() << RawLastModified << " ";
1479 ErrorOr<StringRef> NameOrErr = C.getName();
1480 if (NameOrErr.getError()) {
1481 StringRef RawName = C.getRawName();
1482 outs() << RawName << "\n";
1484 StringRef Name = NameOrErr.get();
1485 outs() << Name << "\n";
1488 StringRef RawName = C.getRawName();
1489 outs() << RawName << "\n";
1493 static void printArchiveHeaders(Archive *A, bool verbose, bool print_offset) {
1494 if (A->hasSymbolTable()) {
1495 Archive::child_iterator S = A->getSymbolTableChild();
1496 Archive::Child C = *S;
1497 printArchiveChild(C, verbose, print_offset);
1499 for (Archive::child_iterator I = A->child_begin(), E = A->child_end(); I != E;
1501 Archive::Child C = *I;
1502 printArchiveChild(C, verbose, print_offset);
1506 // ParseInputMachO() parses the named Mach-O file in Filename and handles the
1507 // -arch flags selecting just those slices as specified by them and also parses
1508 // archive files. Then for each individual Mach-O file ProcessMachO() is
1509 // called to process the file based on the command line options.
1510 void llvm::ParseInputMachO(StringRef Filename) {
1511 // Check for -arch all and verifiy the -arch flags are valid.
1512 for (unsigned i = 0; i < ArchFlags.size(); ++i) {
1513 if (ArchFlags[i] == "all") {
1516 if (!MachOObjectFile::isValidArch(ArchFlags[i])) {
1517 errs() << "llvm-objdump: Unknown architecture named '" + ArchFlags[i] +
1518 "'for the -arch option\n";
1524 // Attempt to open the binary.
1525 ErrorOr<OwningBinary<Binary>> BinaryOrErr = createBinary(Filename);
1526 if (std::error_code EC = BinaryOrErr.getError()) {
1527 errs() << "llvm-objdump: '" << Filename << "': " << EC.message() << ".\n";
1530 Binary &Bin = *BinaryOrErr.get().getBinary();
1532 if (Archive *A = dyn_cast<Archive>(&Bin)) {
1533 outs() << "Archive : " << Filename << "\n";
1535 printArchiveHeaders(A, true, false);
1536 for (Archive::child_iterator I = A->child_begin(), E = A->child_end();
1538 ErrorOr<std::unique_ptr<Binary>> ChildOrErr = I->getAsBinary();
1539 if (ChildOrErr.getError())
1541 if (MachOObjectFile *O = dyn_cast<MachOObjectFile>(&*ChildOrErr.get())) {
1542 if (!checkMachOAndArchFlags(O, Filename))
1544 ProcessMachO(Filename, O, O->getFileName());
1549 if (UniversalHeaders) {
1550 if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(&Bin))
1551 printMachOUniversalHeaders(UB, !NonVerbose);
1553 if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(&Bin)) {
1554 // If we have a list of architecture flags specified dump only those.
1555 if (!ArchAll && ArchFlags.size() != 0) {
1556 // Look for a slice in the universal binary that matches each ArchFlag.
1558 for (unsigned i = 0; i < ArchFlags.size(); ++i) {
1560 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
1561 E = UB->end_objects();
1563 if (ArchFlags[i] == I->getArchTypeName()) {
1565 ErrorOr<std::unique_ptr<ObjectFile>> ObjOrErr =
1566 I->getAsObjectFile();
1567 std::string ArchitectureName = "";
1568 if (ArchFlags.size() > 1)
1569 ArchitectureName = I->getArchTypeName();
1571 ObjectFile &O = *ObjOrErr.get();
1572 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&O))
1573 ProcessMachO(Filename, MachOOF, "", ArchitectureName);
1574 } else if (ErrorOr<std::unique_ptr<Archive>> AOrErr =
1575 I->getAsArchive()) {
1576 std::unique_ptr<Archive> &A = *AOrErr;
1577 outs() << "Archive : " << Filename;
1578 if (!ArchitectureName.empty())
1579 outs() << " (architecture " << ArchitectureName << ")";
1582 printArchiveHeaders(A.get(), true, false);
1583 for (Archive::child_iterator AI = A->child_begin(),
1584 AE = A->child_end();
1586 ErrorOr<std::unique_ptr<Binary>> ChildOrErr = AI->getAsBinary();
1587 if (ChildOrErr.getError())
1589 if (MachOObjectFile *O =
1590 dyn_cast<MachOObjectFile>(&*ChildOrErr.get()))
1591 ProcessMachO(Filename, O, O->getFileName(), ArchitectureName);
1597 errs() << "llvm-objdump: file: " + Filename + " does not contain "
1598 << "architecture: " + ArchFlags[i] + "\n";
1604 // No architecture flags were specified so if this contains a slice that
1605 // matches the host architecture dump only that.
1607 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
1608 E = UB->end_objects();
1610 if (MachOObjectFile::getHostArch().getArchName() ==
1611 I->getArchTypeName()) {
1612 ErrorOr<std::unique_ptr<ObjectFile>> ObjOrErr = I->getAsObjectFile();
1613 std::string ArchiveName;
1614 ArchiveName.clear();
1616 ObjectFile &O = *ObjOrErr.get();
1617 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&O))
1618 ProcessMachO(Filename, MachOOF);
1619 } else if (ErrorOr<std::unique_ptr<Archive>> AOrErr =
1620 I->getAsArchive()) {
1621 std::unique_ptr<Archive> &A = *AOrErr;
1622 outs() << "Archive : " << Filename << "\n";
1624 printArchiveHeaders(A.get(), true, false);
1625 for (Archive::child_iterator AI = A->child_begin(),
1626 AE = A->child_end();
1628 ErrorOr<std::unique_ptr<Binary>> ChildOrErr = AI->getAsBinary();
1629 if (ChildOrErr.getError())
1631 if (MachOObjectFile *O =
1632 dyn_cast<MachOObjectFile>(&*ChildOrErr.get()))
1633 ProcessMachO(Filename, O, O->getFileName());
1640 // Either all architectures have been specified or none have been specified
1641 // and this does not contain the host architecture so dump all the slices.
1642 bool moreThanOneArch = UB->getNumberOfObjects() > 1;
1643 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
1644 E = UB->end_objects();
1646 ErrorOr<std::unique_ptr<ObjectFile>> ObjOrErr = I->getAsObjectFile();
1647 std::string ArchitectureName = "";
1648 if (moreThanOneArch)
1649 ArchitectureName = I->getArchTypeName();
1651 ObjectFile &Obj = *ObjOrErr.get();
1652 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&Obj))
1653 ProcessMachO(Filename, MachOOF, "", ArchitectureName);
1654 } else if (ErrorOr<std::unique_ptr<Archive>> AOrErr = I->getAsArchive()) {
1655 std::unique_ptr<Archive> &A = *AOrErr;
1656 outs() << "Archive : " << Filename;
1657 if (!ArchitectureName.empty())
1658 outs() << " (architecture " << ArchitectureName << ")";
1661 printArchiveHeaders(A.get(), true, false);
1662 for (Archive::child_iterator AI = A->child_begin(), AE = A->child_end();
1664 ErrorOr<std::unique_ptr<Binary>> ChildOrErr = AI->getAsBinary();
1665 if (ChildOrErr.getError())
1667 if (MachOObjectFile *O =
1668 dyn_cast<MachOObjectFile>(&*ChildOrErr.get())) {
1669 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(O))
1670 ProcessMachO(Filename, MachOOF, MachOOF->getFileName(),
1678 if (ObjectFile *O = dyn_cast<ObjectFile>(&Bin)) {
1679 if (!checkMachOAndArchFlags(O, Filename))
1681 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&*O)) {
1682 ProcessMachO(Filename, MachOOF);
1684 errs() << "llvm-objdump: '" << Filename << "': "
1685 << "Object is not a Mach-O file type.\n";
1687 errs() << "llvm-objdump: '" << Filename << "': "
1688 << "Unrecognized file type.\n";
1691 typedef std::pair<uint64_t, const char *> BindInfoEntry;
1692 typedef std::vector<BindInfoEntry> BindTable;
1693 typedef BindTable::iterator bind_table_iterator;
1695 // The block of info used by the Symbolizer call backs.
1696 struct DisassembleInfo {
1700 SymbolAddressMap *AddrMap;
1701 std::vector<SectionRef> *Sections;
1702 const char *class_name;
1703 const char *selector_name;
1705 char *demangled_name;
1708 BindTable *bindtable;
1711 // SymbolizerGetOpInfo() is the operand information call back function.
1712 // This is called to get the symbolic information for operand(s) of an
1713 // instruction when it is being done. This routine does this from
1714 // the relocation information, symbol table, etc. That block of information
1715 // is a pointer to the struct DisassembleInfo that was passed when the
1716 // disassembler context was created and passed to back to here when
1717 // called back by the disassembler for instruction operands that could have
1718 // relocation information. The address of the instruction containing operand is
1719 // at the Pc parameter. The immediate value the operand has is passed in
1720 // op_info->Value and is at Offset past the start of the instruction and has a
1721 // byte Size of 1, 2 or 4. The symbolc information is returned in TagBuf is the
1722 // LLVMOpInfo1 struct defined in the header "llvm-c/Disassembler.h" as symbol
1723 // names and addends of the symbolic expression to add for the operand. The
1724 // value of TagType is currently 1 (for the LLVMOpInfo1 struct). If symbolic
1725 // information is returned then this function returns 1 else it returns 0.
1726 static int SymbolizerGetOpInfo(void *DisInfo, uint64_t Pc, uint64_t Offset,
1727 uint64_t Size, int TagType, void *TagBuf) {
1728 struct DisassembleInfo *info = (struct DisassembleInfo *)DisInfo;
1729 struct LLVMOpInfo1 *op_info = (struct LLVMOpInfo1 *)TagBuf;
1730 uint64_t value = op_info->Value;
1732 // Make sure all fields returned are zero if we don't set them.
1733 memset((void *)op_info, '\0', sizeof(struct LLVMOpInfo1));
1734 op_info->Value = value;
1736 // If the TagType is not the value 1 which it code knows about or if no
1737 // verbose symbolic information is wanted then just return 0, indicating no
1738 // information is being returned.
1739 if (TagType != 1 || info->verbose == false)
1742 unsigned int Arch = info->O->getArch();
1743 if (Arch == Triple::x86) {
1744 if (Size != 1 && Size != 2 && Size != 4 && Size != 0)
1746 // First search the section's relocation entries (if any) for an entry
1747 // for this section offset.
1748 uint32_t sect_addr = info->S.getAddress();
1749 uint32_t sect_offset = (Pc + Offset) - sect_addr;
1750 bool reloc_found = false;
1752 MachO::any_relocation_info RE;
1753 bool isExtern = false;
1755 bool r_scattered = false;
1756 uint32_t r_value, pair_r_value, r_type;
1757 for (const RelocationRef &Reloc : info->S.relocations()) {
1758 uint64_t RelocOffset;
1759 Reloc.getOffset(RelocOffset);
1760 if (RelocOffset == sect_offset) {
1761 Rel = Reloc.getRawDataRefImpl();
1762 RE = info->O->getRelocation(Rel);
1763 r_type = info->O->getAnyRelocationType(RE);
1764 r_scattered = info->O->isRelocationScattered(RE);
1766 r_value = info->O->getScatteredRelocationValue(RE);
1767 if (r_type == MachO::GENERIC_RELOC_SECTDIFF ||
1768 r_type == MachO::GENERIC_RELOC_LOCAL_SECTDIFF) {
1769 DataRefImpl RelNext = Rel;
1770 info->O->moveRelocationNext(RelNext);
1771 MachO::any_relocation_info RENext;
1772 RENext = info->O->getRelocation(RelNext);
1773 if (info->O->isRelocationScattered(RENext))
1774 pair_r_value = info->O->getScatteredRelocationValue(RENext);
1779 isExtern = info->O->getPlainRelocationExternal(RE);
1781 symbol_iterator RelocSym = Reloc.getSymbol();
1789 if (reloc_found && isExtern) {
1791 Symbol.getName(SymName);
1792 const char *name = SymName.data();
1793 op_info->AddSymbol.Present = 1;
1794 op_info->AddSymbol.Name = name;
1795 // For i386 extern relocation entries the value in the instruction is
1796 // the offset from the symbol, and value is already set in op_info->Value.
1799 if (reloc_found && (r_type == MachO::GENERIC_RELOC_SECTDIFF ||
1800 r_type == MachO::GENERIC_RELOC_LOCAL_SECTDIFF)) {
1801 const char *add = GuessSymbolName(r_value, info->AddrMap);
1802 const char *sub = GuessSymbolName(pair_r_value, info->AddrMap);
1803 uint32_t offset = value - (r_value - pair_r_value);
1804 op_info->AddSymbol.Present = 1;
1806 op_info->AddSymbol.Name = add;
1808 op_info->AddSymbol.Value = r_value;
1809 op_info->SubtractSymbol.Present = 1;
1811 op_info->SubtractSymbol.Name = sub;
1813 op_info->SubtractSymbol.Value = pair_r_value;
1814 op_info->Value = offset;
1818 // Second search the external relocation entries of a fully linked image
1819 // (if any) for an entry that matches this segment offset.
1820 // uint32_t seg_offset = (Pc + Offset);
1822 } else if (Arch == Triple::x86_64) {
1823 if (Size != 1 && Size != 2 && Size != 4 && Size != 0)
1825 // First search the section's relocation entries (if any) for an entry
1826 // for this section offset.
1827 uint64_t sect_addr = info->S.getAddress();
1828 uint64_t sect_offset = (Pc + Offset) - sect_addr;
1829 bool reloc_found = false;
1831 MachO::any_relocation_info RE;
1832 bool isExtern = false;
1834 for (const RelocationRef &Reloc : info->S.relocations()) {
1835 uint64_t RelocOffset;
1836 Reloc.getOffset(RelocOffset);
1837 if (RelocOffset == sect_offset) {
1838 Rel = Reloc.getRawDataRefImpl();
1839 RE = info->O->getRelocation(Rel);
1840 // NOTE: Scattered relocations don't exist on x86_64.
1841 isExtern = info->O->getPlainRelocationExternal(RE);
1843 symbol_iterator RelocSym = Reloc.getSymbol();
1850 if (reloc_found && isExtern) {
1851 // The Value passed in will be adjusted by the Pc if the instruction
1852 // adds the Pc. But for x86_64 external relocation entries the Value
1853 // is the offset from the external symbol.
1854 if (info->O->getAnyRelocationPCRel(RE))
1855 op_info->Value -= Pc + Offset + Size;
1857 Symbol.getName(SymName);
1858 const char *name = SymName.data();
1859 unsigned Type = info->O->getAnyRelocationType(RE);
1860 if (Type == MachO::X86_64_RELOC_SUBTRACTOR) {
1861 DataRefImpl RelNext = Rel;
1862 info->O->moveRelocationNext(RelNext);
1863 MachO::any_relocation_info RENext = info->O->getRelocation(RelNext);
1864 unsigned TypeNext = info->O->getAnyRelocationType(RENext);
1865 bool isExternNext = info->O->getPlainRelocationExternal(RENext);
1866 unsigned SymbolNum = info->O->getPlainRelocationSymbolNum(RENext);
1867 if (TypeNext == MachO::X86_64_RELOC_UNSIGNED && isExternNext) {
1868 op_info->SubtractSymbol.Present = 1;
1869 op_info->SubtractSymbol.Name = name;
1870 symbol_iterator RelocSymNext = info->O->getSymbolByIndex(SymbolNum);
1871 Symbol = *RelocSymNext;
1872 StringRef SymNameNext;
1873 Symbol.getName(SymNameNext);
1874 name = SymNameNext.data();
1877 // TODO: add the VariantKinds to op_info->VariantKind for relocation types
1878 // like: X86_64_RELOC_TLV, X86_64_RELOC_GOT_LOAD and X86_64_RELOC_GOT.
1879 op_info->AddSymbol.Present = 1;
1880 op_info->AddSymbol.Name = name;
1884 // Second search the external relocation entries of a fully linked image
1885 // (if any) for an entry that matches this segment offset.
1886 // uint64_t seg_offset = (Pc + Offset);
1888 } else if (Arch == Triple::arm) {
1889 if (Offset != 0 || (Size != 4 && Size != 2))
1891 // First search the section's relocation entries (if any) for an entry
1892 // for this section offset.
1893 uint32_t sect_addr = info->S.getAddress();
1894 uint32_t sect_offset = (Pc + Offset) - sect_addr;
1895 bool reloc_found = false;
1897 MachO::any_relocation_info RE;
1898 bool isExtern = false;
1900 bool r_scattered = false;
1901 uint32_t r_value, pair_r_value, r_type, r_length, other_half;
1902 for (const RelocationRef &Reloc : info->S.relocations()) {
1903 uint64_t RelocOffset;
1904 Reloc.getOffset(RelocOffset);
1905 if (RelocOffset == sect_offset) {
1906 Rel = Reloc.getRawDataRefImpl();
1907 RE = info->O->getRelocation(Rel);
1908 r_length = info->O->getAnyRelocationLength(RE);
1909 r_scattered = info->O->isRelocationScattered(RE);
1911 r_value = info->O->getScatteredRelocationValue(RE);
1912 r_type = info->O->getScatteredRelocationType(RE);
1914 r_type = info->O->getAnyRelocationType(RE);
1915 isExtern = info->O->getPlainRelocationExternal(RE);
1917 symbol_iterator RelocSym = Reloc.getSymbol();
1921 if (r_type == MachO::ARM_RELOC_HALF ||
1922 r_type == MachO::ARM_RELOC_SECTDIFF ||
1923 r_type == MachO::ARM_RELOC_LOCAL_SECTDIFF ||
1924 r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
1925 DataRefImpl RelNext = Rel;
1926 info->O->moveRelocationNext(RelNext);
1927 MachO::any_relocation_info RENext;
1928 RENext = info->O->getRelocation(RelNext);
1929 other_half = info->O->getAnyRelocationAddress(RENext) & 0xffff;
1930 if (info->O->isRelocationScattered(RENext))
1931 pair_r_value = info->O->getScatteredRelocationValue(RENext);
1937 if (reloc_found && isExtern) {
1939 Symbol.getName(SymName);
1940 const char *name = SymName.data();
1941 op_info->AddSymbol.Present = 1;
1942 op_info->AddSymbol.Name = name;
1944 case MachO::ARM_RELOC_HALF:
1945 if ((r_length & 0x1) == 1) {
1946 op_info->Value = value << 16 | other_half;
1947 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
1949 op_info->Value = other_half << 16 | value;
1950 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
1958 // If we have a branch that is not an external relocation entry then
1959 // return 0 so the code in tryAddingSymbolicOperand() can use the
1960 // SymbolLookUp call back with the branch target address to look up the
1961 // symbol and possiblity add an annotation for a symbol stub.
1962 if (reloc_found && isExtern == 0 && (r_type == MachO::ARM_RELOC_BR24 ||
1963 r_type == MachO::ARM_THUMB_RELOC_BR22))
1966 uint32_t offset = 0;
1968 if (r_type == MachO::ARM_RELOC_HALF ||
1969 r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
1970 if ((r_length & 0x1) == 1)
1971 value = value << 16 | other_half;
1973 value = other_half << 16 | value;
1975 if (r_scattered && (r_type != MachO::ARM_RELOC_HALF &&
1976 r_type != MachO::ARM_RELOC_HALF_SECTDIFF)) {
1977 offset = value - r_value;
1982 if (reloc_found && r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
1983 if ((r_length & 0x1) == 1)
1984 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
1986 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
1987 const char *add = GuessSymbolName(r_value, info->AddrMap);
1988 const char *sub = GuessSymbolName(pair_r_value, info->AddrMap);
1989 int32_t offset = value - (r_value - pair_r_value);
1990 op_info->AddSymbol.Present = 1;
1992 op_info->AddSymbol.Name = add;
1994 op_info->AddSymbol.Value = r_value;
1995 op_info->SubtractSymbol.Present = 1;
1997 op_info->SubtractSymbol.Name = sub;
1999 op_info->SubtractSymbol.Value = pair_r_value;
2000 op_info->Value = offset;
2004 if (reloc_found == false)
2007 op_info->AddSymbol.Present = 1;
2008 op_info->Value = offset;
2010 if (r_type == MachO::ARM_RELOC_HALF) {
2011 if ((r_length & 0x1) == 1)
2012 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
2014 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
2017 const char *add = GuessSymbolName(value, info->AddrMap);
2018 if (add != nullptr) {
2019 op_info->AddSymbol.Name = add;
2022 op_info->AddSymbol.Value = value;
2024 } else if (Arch == Triple::aarch64) {
2025 if (Offset != 0 || Size != 4)
2027 // First search the section's relocation entries (if any) for an entry
2028 // for this section offset.
2029 uint64_t sect_addr = info->S.getAddress();
2030 uint64_t sect_offset = (Pc + Offset) - sect_addr;
2031 bool reloc_found = false;
2033 MachO::any_relocation_info RE;
2034 bool isExtern = false;
2036 uint32_t r_type = 0;
2037 for (const RelocationRef &Reloc : info->S.relocations()) {
2038 uint64_t RelocOffset;
2039 Reloc.getOffset(RelocOffset);
2040 if (RelocOffset == sect_offset) {
2041 Rel = Reloc.getRawDataRefImpl();
2042 RE = info->O->getRelocation(Rel);
2043 r_type = info->O->getAnyRelocationType(RE);
2044 if (r_type == MachO::ARM64_RELOC_ADDEND) {
2045 DataRefImpl RelNext = Rel;
2046 info->O->moveRelocationNext(RelNext);
2047 MachO::any_relocation_info RENext = info->O->getRelocation(RelNext);
2049 value = info->O->getPlainRelocationSymbolNum(RENext);
2050 op_info->Value = value;
2053 // NOTE: Scattered relocations don't exist on arm64.
2054 isExtern = info->O->getPlainRelocationExternal(RE);
2056 symbol_iterator RelocSym = Reloc.getSymbol();
2063 if (reloc_found && isExtern) {
2065 Symbol.getName(SymName);
2066 const char *name = SymName.data();
2067 op_info->AddSymbol.Present = 1;
2068 op_info->AddSymbol.Name = name;
2071 case MachO::ARM64_RELOC_PAGE21:
2073 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_PAGE;
2075 case MachO::ARM64_RELOC_PAGEOFF12:
2077 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_PAGEOFF;
2079 case MachO::ARM64_RELOC_GOT_LOAD_PAGE21:
2081 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_GOTPAGE;
2083 case MachO::ARM64_RELOC_GOT_LOAD_PAGEOFF12:
2085 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_GOTPAGEOFF;
2087 case MachO::ARM64_RELOC_TLVP_LOAD_PAGE21:
2088 /* @tvlppage is not implemented in llvm-mc */
2089 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_TLVP;
2091 case MachO::ARM64_RELOC_TLVP_LOAD_PAGEOFF12:
2092 /* @tvlppageoff is not implemented in llvm-mc */
2093 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_TLVOFF;
2096 case MachO::ARM64_RELOC_BRANCH26:
2097 op_info->VariantKind = LLVMDisassembler_VariantKind_None;
2108 // GuessCstringPointer is passed the address of what might be a pointer to a
2109 // literal string in a cstring section. If that address is in a cstring section
2110 // it returns a pointer to that string. Else it returns nullptr.
2111 static const char *GuessCstringPointer(uint64_t ReferenceValue,
2112 struct DisassembleInfo *info) {
2113 uint32_t LoadCommandCount = info->O->getHeader().ncmds;
2114 MachOObjectFile::LoadCommandInfo Load = info->O->getFirstLoadCommandInfo();
2115 for (unsigned I = 0;; ++I) {
2116 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
2117 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
2118 for (unsigned J = 0; J < Seg.nsects; ++J) {
2119 MachO::section_64 Sec = info->O->getSection64(Load, J);
2120 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
2121 if (section_type == MachO::S_CSTRING_LITERALS &&
2122 ReferenceValue >= Sec.addr &&
2123 ReferenceValue < Sec.addr + Sec.size) {
2124 uint64_t sect_offset = ReferenceValue - Sec.addr;
2125 uint64_t object_offset = Sec.offset + sect_offset;
2126 StringRef MachOContents = info->O->getData();
2127 uint64_t object_size = MachOContents.size();
2128 const char *object_addr = (const char *)MachOContents.data();
2129 if (object_offset < object_size) {
2130 const char *name = object_addr + object_offset;
2137 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
2138 MachO::segment_command Seg = info->O->getSegmentLoadCommand(Load);
2139 for (unsigned J = 0; J < Seg.nsects; ++J) {
2140 MachO::section Sec = info->O->getSection(Load, J);
2141 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
2142 if (section_type == MachO::S_CSTRING_LITERALS &&
2143 ReferenceValue >= Sec.addr &&
2144 ReferenceValue < Sec.addr + Sec.size) {
2145 uint64_t sect_offset = ReferenceValue - Sec.addr;
2146 uint64_t object_offset = Sec.offset + sect_offset;
2147 StringRef MachOContents = info->O->getData();
2148 uint64_t object_size = MachOContents.size();
2149 const char *object_addr = (const char *)MachOContents.data();
2150 if (object_offset < object_size) {
2151 const char *name = object_addr + object_offset;
2159 if (I == LoadCommandCount - 1)
2162 Load = info->O->getNextLoadCommandInfo(Load);
2167 // GuessIndirectSymbol returns the name of the indirect symbol for the
2168 // ReferenceValue passed in or nullptr. This is used when ReferenceValue maybe
2169 // an address of a symbol stub or a lazy or non-lazy pointer to associate the
2170 // symbol name being referenced by the stub or pointer.
2171 static const char *GuessIndirectSymbol(uint64_t ReferenceValue,
2172 struct DisassembleInfo *info) {
2173 uint32_t LoadCommandCount = info->O->getHeader().ncmds;
2174 MachOObjectFile::LoadCommandInfo Load = info->O->getFirstLoadCommandInfo();
2175 MachO::dysymtab_command Dysymtab = info->O->getDysymtabLoadCommand();
2176 MachO::symtab_command Symtab = info->O->getSymtabLoadCommand();
2177 for (unsigned I = 0;; ++I) {
2178 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
2179 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
2180 for (unsigned J = 0; J < Seg.nsects; ++J) {
2181 MachO::section_64 Sec = info->O->getSection64(Load, J);
2182 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
2183 if ((section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
2184 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
2185 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
2186 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
2187 section_type == MachO::S_SYMBOL_STUBS) &&
2188 ReferenceValue >= Sec.addr &&
2189 ReferenceValue < Sec.addr + Sec.size) {
2191 if (section_type == MachO::S_SYMBOL_STUBS)
2192 stride = Sec.reserved2;
2197 uint32_t index = Sec.reserved1 + (ReferenceValue - Sec.addr) / stride;
2198 if (index < Dysymtab.nindirectsyms) {
2199 uint32_t indirect_symbol =
2200 info->O->getIndirectSymbolTableEntry(Dysymtab, index);
2201 if (indirect_symbol < Symtab.nsyms) {
2202 symbol_iterator Sym = info->O->getSymbolByIndex(indirect_symbol);
2203 SymbolRef Symbol = *Sym;
2205 Symbol.getName(SymName);
2206 const char *name = SymName.data();
2212 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
2213 MachO::segment_command Seg = info->O->getSegmentLoadCommand(Load);
2214 for (unsigned J = 0; J < Seg.nsects; ++J) {
2215 MachO::section Sec = info->O->getSection(Load, J);
2216 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
2217 if ((section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
2218 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
2219 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
2220 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
2221 section_type == MachO::S_SYMBOL_STUBS) &&
2222 ReferenceValue >= Sec.addr &&
2223 ReferenceValue < Sec.addr + Sec.size) {
2225 if (section_type == MachO::S_SYMBOL_STUBS)
2226 stride = Sec.reserved2;
2231 uint32_t index = Sec.reserved1 + (ReferenceValue - Sec.addr) / stride;
2232 if (index < Dysymtab.nindirectsyms) {
2233 uint32_t indirect_symbol =
2234 info->O->getIndirectSymbolTableEntry(Dysymtab, index);
2235 if (indirect_symbol < Symtab.nsyms) {
2236 symbol_iterator Sym = info->O->getSymbolByIndex(indirect_symbol);
2237 SymbolRef Symbol = *Sym;
2239 Symbol.getName(SymName);
2240 const char *name = SymName.data();
2247 if (I == LoadCommandCount - 1)
2250 Load = info->O->getNextLoadCommandInfo(Load);
2255 // method_reference() is called passing it the ReferenceName that might be
2256 // a reference it to an Objective-C method call. If so then it allocates and
2257 // assembles a method call string with the values last seen and saved in
2258 // the DisassembleInfo's class_name and selector_name fields. This is saved
2259 // into the method field of the info and any previous string is free'ed.
2260 // Then the class_name field in the info is set to nullptr. The method call
2261 // string is set into ReferenceName and ReferenceType is set to
2262 // LLVMDisassembler_ReferenceType_Out_Objc_Message. If this not a method call
2263 // then both ReferenceType and ReferenceName are left unchanged.
2264 static void method_reference(struct DisassembleInfo *info,
2265 uint64_t *ReferenceType,
2266 const char **ReferenceName) {
2267 unsigned int Arch = info->O->getArch();
2268 if (*ReferenceName != nullptr) {
2269 if (strcmp(*ReferenceName, "_objc_msgSend") == 0) {
2270 if (info->selector_name != nullptr) {
2271 if (info->method != nullptr)
2273 if (info->class_name != nullptr) {
2274 info->method = (char *)malloc(5 + strlen(info->class_name) +
2275 strlen(info->selector_name));
2276 if (info->method != nullptr) {
2277 strcpy(info->method, "+[");
2278 strcat(info->method, info->class_name);
2279 strcat(info->method, " ");
2280 strcat(info->method, info->selector_name);
2281 strcat(info->method, "]");
2282 *ReferenceName = info->method;
2283 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
2286 info->method = (char *)malloc(9 + strlen(info->selector_name));
2287 if (info->method != nullptr) {
2288 if (Arch == Triple::x86_64)
2289 strcpy(info->method, "-[%rdi ");
2290 else if (Arch == Triple::aarch64)
2291 strcpy(info->method, "-[x0 ");
2293 strcpy(info->method, "-[r? ");
2294 strcat(info->method, info->selector_name);
2295 strcat(info->method, "]");
2296 *ReferenceName = info->method;
2297 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
2300 info->class_name = nullptr;
2302 } else if (strcmp(*ReferenceName, "_objc_msgSendSuper2") == 0) {
2303 if (info->selector_name != nullptr) {
2304 if (info->method != nullptr)
2306 info->method = (char *)malloc(17 + strlen(info->selector_name));
2307 if (info->method != nullptr) {
2308 if (Arch == Triple::x86_64)
2309 strcpy(info->method, "-[[%rdi super] ");
2310 else if (Arch == Triple::aarch64)
2311 strcpy(info->method, "-[[x0 super] ");
2313 strcpy(info->method, "-[[r? super] ");
2314 strcat(info->method, info->selector_name);
2315 strcat(info->method, "]");
2316 *ReferenceName = info->method;
2317 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
2319 info->class_name = nullptr;
2325 // GuessPointerPointer() is passed the address of what might be a pointer to
2326 // a reference to an Objective-C class, selector, message ref or cfstring.
2327 // If so the value of the pointer is returned and one of the booleans are set
2328 // to true. If not zero is returned and all the booleans are set to false.
2329 static uint64_t GuessPointerPointer(uint64_t ReferenceValue,
2330 struct DisassembleInfo *info,
2331 bool &classref, bool &selref, bool &msgref,
2337 uint32_t LoadCommandCount = info->O->getHeader().ncmds;
2338 MachOObjectFile::LoadCommandInfo Load = info->O->getFirstLoadCommandInfo();
2339 for (unsigned I = 0;; ++I) {
2340 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
2341 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
2342 for (unsigned J = 0; J < Seg.nsects; ++J) {
2343 MachO::section_64 Sec = info->O->getSection64(Load, J);
2344 if ((strncmp(Sec.sectname, "__objc_selrefs", 16) == 0 ||
2345 strncmp(Sec.sectname, "__objc_classrefs", 16) == 0 ||
2346 strncmp(Sec.sectname, "__objc_superrefs", 16) == 0 ||
2347 strncmp(Sec.sectname, "__objc_msgrefs", 16) == 0 ||
2348 strncmp(Sec.sectname, "__cfstring", 16) == 0) &&
2349 ReferenceValue >= Sec.addr &&
2350 ReferenceValue < Sec.addr + Sec.size) {
2351 uint64_t sect_offset = ReferenceValue - Sec.addr;
2352 uint64_t object_offset = Sec.offset + sect_offset;
2353 StringRef MachOContents = info->O->getData();
2354 uint64_t object_size = MachOContents.size();
2355 const char *object_addr = (const char *)MachOContents.data();
2356 if (object_offset < object_size) {
2357 uint64_t pointer_value;
2358 memcpy(&pointer_value, object_addr + object_offset,
2360 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
2361 sys::swapByteOrder(pointer_value);
2362 if (strncmp(Sec.sectname, "__objc_selrefs", 16) == 0)
2364 else if (strncmp(Sec.sectname, "__objc_classrefs", 16) == 0 ||
2365 strncmp(Sec.sectname, "__objc_superrefs", 16) == 0)
2367 else if (strncmp(Sec.sectname, "__objc_msgrefs", 16) == 0 &&
2368 ReferenceValue + 8 < Sec.addr + Sec.size) {
2370 memcpy(&pointer_value, object_addr + object_offset + 8,
2372 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
2373 sys::swapByteOrder(pointer_value);
2374 } else if (strncmp(Sec.sectname, "__cfstring", 16) == 0)
2376 return pointer_value;
2383 // TODO: Look for LC_SEGMENT for 32-bit Mach-O files.
2384 if (I == LoadCommandCount - 1)
2387 Load = info->O->getNextLoadCommandInfo(Load);
2392 // get_pointer_64 returns a pointer to the bytes in the object file at the
2393 // Address from a section in the Mach-O file. And indirectly returns the
2394 // offset into the section, number of bytes left in the section past the offset
2395 // and which section is was being referenced. If the Address is not in a
2396 // section nullptr is returned.
2397 static const char *get_pointer_64(uint64_t Address, uint32_t &offset,
2398 uint32_t &left, SectionRef &S,
2399 DisassembleInfo *info) {
2403 for (unsigned SectIdx = 0; SectIdx != info->Sections->size(); SectIdx++) {
2404 uint64_t SectAddress = ((*(info->Sections))[SectIdx]).getAddress();
2405 uint64_t SectSize = ((*(info->Sections))[SectIdx]).getSize();
2406 if (Address >= SectAddress && Address < SectAddress + SectSize) {
2407 S = (*(info->Sections))[SectIdx];
2408 offset = Address - SectAddress;
2409 left = SectSize - offset;
2410 StringRef SectContents;
2411 ((*(info->Sections))[SectIdx]).getContents(SectContents);
2412 return SectContents.data() + offset;
2418 // get_symbol_64() returns the name of a symbol (or nullptr) and the address of
2419 // the symbol indirectly through n_value. Based on the relocation information
2420 // for the specified section offset in the specified section reference.
2421 static const char *get_symbol_64(uint32_t sect_offset, SectionRef S,
2422 DisassembleInfo *info, uint64_t &n_value) {
2424 if (info->verbose == false)
2427 // See if there is an external relocation entry at the sect_offset.
2428 bool reloc_found = false;
2430 MachO::any_relocation_info RE;
2431 bool isExtern = false;
2433 for (const RelocationRef &Reloc : S.relocations()) {
2434 uint64_t RelocOffset;
2435 Reloc.getOffset(RelocOffset);
2436 if (RelocOffset == sect_offset) {
2437 Rel = Reloc.getRawDataRefImpl();
2438 RE = info->O->getRelocation(Rel);
2439 if (info->O->isRelocationScattered(RE))
2441 isExtern = info->O->getPlainRelocationExternal(RE);
2443 symbol_iterator RelocSym = Reloc.getSymbol();
2450 // If there is an external relocation entry for a symbol in this section
2451 // at this section_offset then use that symbol's value for the n_value
2452 // and return its name.
2453 const char *SymbolName = nullptr;
2454 if (reloc_found && isExtern) {
2455 Symbol.getAddress(n_value);
2457 Symbol.getName(name);
2458 if (!name.empty()) {
2459 SymbolName = name.data();
2464 // TODO: For fully linked images, look through the external relocation
2465 // entries off the dynamic symtab command. For these the r_offset is from the
2466 // start of the first writeable segment in the Mach-O file. So the offset
2467 // to this section from that segment is passed to this routine by the caller,
2468 // as the database_offset. Which is the difference of the section's starting
2469 // address and the first writable segment.
2471 // NOTE: need add passing the database_offset to this routine.
2473 // TODO: We did not find an external relocation entry so look up the
2474 // ReferenceValue as an address of a symbol and if found return that symbol's
2477 // NOTE: need add passing the ReferenceValue to this routine. Then that code
2478 // would simply be this:
2479 // SymbolName = GuessSymbolName(ReferenceValue, info->AddrMap);
2484 // These are structs in the Objective-C meta data and read to produce the
2485 // comments for disassembly. While these are part of the ABI they are no
2486 // public defintions. So the are here not in include/llvm/Support/MachO.h .
2488 // The cfstring object in a 64-bit Mach-O file.
2489 struct cfstring64_t {
2490 uint64_t isa; // class64_t * (64-bit pointer)
2491 uint64_t flags; // flag bits
2492 uint64_t characters; // char * (64-bit pointer)
2493 uint64_t length; // number of non-NULL characters in above
2496 // The class object in a 64-bit Mach-O file.
2498 uint64_t isa; // class64_t * (64-bit pointer)
2499 uint64_t superclass; // class64_t * (64-bit pointer)
2500 uint64_t cache; // Cache (64-bit pointer)
2501 uint64_t vtable; // IMP * (64-bit pointer)
2502 uint64_t data; // class_ro64_t * (64-bit pointer)
2505 struct class_ro64_t {
2507 uint32_t instanceStart;
2508 uint32_t instanceSize;
2510 uint64_t ivarLayout; // const uint8_t * (64-bit pointer)
2511 uint64_t name; // const char * (64-bit pointer)
2512 uint64_t baseMethods; // const method_list_t * (64-bit pointer)
2513 uint64_t baseProtocols; // const protocol_list_t * (64-bit pointer)
2514 uint64_t ivars; // const ivar_list_t * (64-bit pointer)
2515 uint64_t weakIvarLayout; // const uint8_t * (64-bit pointer)
2516 uint64_t baseProperties; // const struct objc_property_list (64-bit pointer)
2519 inline void swapStruct(struct cfstring64_t &cfs) {
2520 sys::swapByteOrder(cfs.isa);
2521 sys::swapByteOrder(cfs.flags);
2522 sys::swapByteOrder(cfs.characters);
2523 sys::swapByteOrder(cfs.length);
2526 inline void swapStruct(struct class64_t &c) {
2527 sys::swapByteOrder(c.isa);
2528 sys::swapByteOrder(c.superclass);
2529 sys::swapByteOrder(c.cache);
2530 sys::swapByteOrder(c.vtable);
2531 sys::swapByteOrder(c.data);
2534 inline void swapStruct(struct class_ro64_t &cro) {
2535 sys::swapByteOrder(cro.flags);
2536 sys::swapByteOrder(cro.instanceStart);
2537 sys::swapByteOrder(cro.instanceSize);
2538 sys::swapByteOrder(cro.reserved);
2539 sys::swapByteOrder(cro.ivarLayout);
2540 sys::swapByteOrder(cro.name);
2541 sys::swapByteOrder(cro.baseMethods);
2542 sys::swapByteOrder(cro.baseProtocols);
2543 sys::swapByteOrder(cro.ivars);
2544 sys::swapByteOrder(cro.weakIvarLayout);
2545 sys::swapByteOrder(cro.baseProperties);
2548 static const char *get_dyld_bind_info_symbolname(uint64_t ReferenceValue,
2549 struct DisassembleInfo *info);
2551 // get_objc2_64bit_class_name() is used for disassembly and is passed a pointer
2552 // to an Objective-C class and returns the class name. It is also passed the
2553 // address of the pointer, so when the pointer is zero as it can be in an .o
2554 // file, that is used to look for an external relocation entry with a symbol
2556 static const char *get_objc2_64bit_class_name(uint64_t pointer_value,
2557 uint64_t ReferenceValue,
2558 struct DisassembleInfo *info) {
2560 uint32_t offset, left;
2563 // The pointer_value can be 0 in an object file and have a relocation
2564 // entry for the class symbol at the ReferenceValue (the address of the
2566 if (pointer_value == 0) {
2567 r = get_pointer_64(ReferenceValue, offset, left, S, info);
2568 if (r == nullptr || left < sizeof(uint64_t))
2571 const char *symbol_name = get_symbol_64(offset, S, info, n_value);
2572 if (symbol_name == nullptr)
2574 const char *class_name = strrchr(symbol_name, '$');
2575 if (class_name != nullptr && class_name[1] == '_' && class_name[2] != '\0')
2576 return class_name + 2;
2581 // The case were the pointer_value is non-zero and points to a class defined
2582 // in this Mach-O file.
2583 r = get_pointer_64(pointer_value, offset, left, S, info);
2584 if (r == nullptr || left < sizeof(struct class64_t))
2587 memcpy(&c, r, sizeof(struct class64_t));
2588 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
2592 r = get_pointer_64(c.data, offset, left, S, info);
2593 if (r == nullptr || left < sizeof(struct class_ro64_t))
2595 struct class_ro64_t cro;
2596 memcpy(&cro, r, sizeof(struct class_ro64_t));
2597 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
2601 const char *name = get_pointer_64(cro.name, offset, left, S, info);
2605 // get_objc2_64bit_cfstring_name is used for disassembly and is passed a
2606 // pointer to a cfstring and returns its name or nullptr.
2607 static const char *get_objc2_64bit_cfstring_name(uint64_t ReferenceValue,
2608 struct DisassembleInfo *info) {
2609 const char *r, *name;
2610 uint32_t offset, left;
2612 struct cfstring64_t cfs;
2613 uint64_t cfs_characters;
2615 r = get_pointer_64(ReferenceValue, offset, left, S, info);
2616 if (r == nullptr || left < sizeof(struct cfstring64_t))
2618 memcpy(&cfs, r, sizeof(struct cfstring64_t));
2619 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
2621 if (cfs.characters == 0) {
2623 const char *symbol_name = get_symbol_64(
2624 offset + offsetof(struct cfstring64_t, characters), S, info, n_value);
2625 if (symbol_name == nullptr)
2627 cfs_characters = n_value;
2629 cfs_characters = cfs.characters;
2630 name = get_pointer_64(cfs_characters, offset, left, S, info);
2635 // get_objc2_64bit_selref() is used for disassembly and is passed a the address
2636 // of a pointer to an Objective-C selector reference when the pointer value is
2637 // zero as in a .o file and is likely to have a external relocation entry with
2638 // who's symbol's n_value is the real pointer to the selector name. If that is
2639 // the case the real pointer to the selector name is returned else 0 is
2641 static uint64_t get_objc2_64bit_selref(uint64_t ReferenceValue,
2642 struct DisassembleInfo *info) {
2643 uint32_t offset, left;
2646 const char *r = get_pointer_64(ReferenceValue, offset, left, S, info);
2647 if (r == nullptr || left < sizeof(uint64_t))
2650 const char *symbol_name = get_symbol_64(offset, S, info, n_value);
2651 if (symbol_name == nullptr)
2656 // GuessLiteralPointer returns a string which for the item in the Mach-O file
2657 // for the address passed in as ReferenceValue for printing as a comment with
2658 // the instruction and also returns the corresponding type of that item
2659 // indirectly through ReferenceType.
2661 // If ReferenceValue is an address of literal cstring then a pointer to the
2662 // cstring is returned and ReferenceType is set to
2663 // LLVMDisassembler_ReferenceType_Out_LitPool_CstrAddr .
2665 // If ReferenceValue is an address of an Objective-C CFString, Selector ref or
2666 // Class ref that name is returned and the ReferenceType is set accordingly.
2668 // Lastly, literals which are Symbol address in a literal pool are looked for
2669 // and if found the symbol name is returned and ReferenceType is set to
2670 // LLVMDisassembler_ReferenceType_Out_LitPool_SymAddr .
2672 // If there is no item in the Mach-O file for the address passed in as
2673 // ReferenceValue nullptr is returned and ReferenceType is unchanged.
2674 static const char *GuessLiteralPointer(uint64_t ReferenceValue,
2675 uint64_t ReferencePC,
2676 uint64_t *ReferenceType,
2677 struct DisassembleInfo *info) {
2678 // First see if there is an external relocation entry at the ReferencePC.
2679 uint64_t sect_addr = info->S.getAddress();
2680 uint64_t sect_offset = ReferencePC - sect_addr;
2681 bool reloc_found = false;
2683 MachO::any_relocation_info RE;
2684 bool isExtern = false;
2686 for (const RelocationRef &Reloc : info->S.relocations()) {
2687 uint64_t RelocOffset;
2688 Reloc.getOffset(RelocOffset);
2689 if (RelocOffset == sect_offset) {
2690 Rel = Reloc.getRawDataRefImpl();
2691 RE = info->O->getRelocation(Rel);
2692 if (info->O->isRelocationScattered(RE))
2694 isExtern = info->O->getPlainRelocationExternal(RE);
2696 symbol_iterator RelocSym = Reloc.getSymbol();
2703 // If there is an external relocation entry for a symbol in a section
2704 // then used that symbol's value for the value of the reference.
2705 if (reloc_found && isExtern) {
2706 if (info->O->getAnyRelocationPCRel(RE)) {
2707 unsigned Type = info->O->getAnyRelocationType(RE);
2708 if (Type == MachO::X86_64_RELOC_SIGNED) {
2709 Symbol.getAddress(ReferenceValue);
2714 // Look for literals such as Objective-C CFStrings refs, Selector refs,
2715 // Message refs and Class refs.
2716 bool classref, selref, msgref, cfstring;
2717 uint64_t pointer_value = GuessPointerPointer(ReferenceValue, info, classref,
2718 selref, msgref, cfstring);
2719 if (classref == true && pointer_value == 0) {
2720 // Note the ReferenceValue is a pointer into the __objc_classrefs section.
2721 // And the pointer_value in that section is typically zero as it will be
2722 // set by dyld as part of the "bind information".
2723 const char *name = get_dyld_bind_info_symbolname(ReferenceValue, info);
2724 if (name != nullptr) {
2725 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Class_Ref;
2726 const char *class_name = strrchr(name, '$');
2727 if (class_name != nullptr && class_name[1] == '_' &&
2728 class_name[2] != '\0') {
2729 info->class_name = class_name + 2;
2735 if (classref == true) {
2736 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Class_Ref;
2738 get_objc2_64bit_class_name(pointer_value, ReferenceValue, info);
2739 if (name != nullptr)
2740 info->class_name = name;
2742 name = "bad class ref";
2746 if (cfstring == true) {
2747 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_CFString_Ref;
2748 const char *name = get_objc2_64bit_cfstring_name(ReferenceValue, info);
2752 if (selref == true && pointer_value == 0)
2753 pointer_value = get_objc2_64bit_selref(ReferenceValue, info);
2755 if (pointer_value != 0)
2756 ReferenceValue = pointer_value;
2758 const char *name = GuessCstringPointer(ReferenceValue, info);
2760 if (pointer_value != 0 && selref == true) {
2761 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Selector_Ref;
2762 info->selector_name = name;
2763 } else if (pointer_value != 0 && msgref == true) {
2764 info->class_name = nullptr;
2765 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message_Ref;
2766 info->selector_name = name;
2768 *ReferenceType = LLVMDisassembler_ReferenceType_Out_LitPool_CstrAddr;
2772 // Lastly look for an indirect symbol with this ReferenceValue which is in
2773 // a literal pool. If found return that symbol name.
2774 name = GuessIndirectSymbol(ReferenceValue, info);
2776 *ReferenceType = LLVMDisassembler_ReferenceType_Out_LitPool_SymAddr;
2783 // SymbolizerSymbolLookUp is the symbol lookup function passed when creating
2784 // the Symbolizer. It looks up the ReferenceValue using the info passed via the
2785 // pointer to the struct DisassembleInfo that was passed when MCSymbolizer
2786 // is created and returns the symbol name that matches the ReferenceValue or
2787 // nullptr if none. The ReferenceType is passed in for the IN type of
2788 // reference the instruction is making from the values in defined in the header
2789 // "llvm-c/Disassembler.h". On return the ReferenceType can set to a specific
2790 // Out type and the ReferenceName will also be set which is added as a comment
2791 // to the disassembled instruction.
2794 // If the symbol name is a C++ mangled name then the demangled name is
2795 // returned through ReferenceName and ReferenceType is set to
2796 // LLVMDisassembler_ReferenceType_DeMangled_Name .
2799 // When this is called to get a symbol name for a branch target then the
2800 // ReferenceType will be LLVMDisassembler_ReferenceType_In_Branch and then
2801 // SymbolValue will be looked for in the indirect symbol table to determine if
2802 // it is an address for a symbol stub. If so then the symbol name for that
2803 // stub is returned indirectly through ReferenceName and then ReferenceType is
2804 // set to LLVMDisassembler_ReferenceType_Out_SymbolStub.
2806 // When this is called with an value loaded via a PC relative load then
2807 // ReferenceType will be LLVMDisassembler_ReferenceType_In_PCrel_Load then the
2808 // SymbolValue is checked to be an address of literal pointer, symbol pointer,
2809 // or an Objective-C meta data reference. If so the output ReferenceType is
2810 // set to correspond to that as well as setting the ReferenceName.
2811 static const char *SymbolizerSymbolLookUp(void *DisInfo,
2812 uint64_t ReferenceValue,
2813 uint64_t *ReferenceType,
2814 uint64_t ReferencePC,
2815 const char **ReferenceName) {
2816 struct DisassembleInfo *info = (struct DisassembleInfo *)DisInfo;
2817 // If no verbose symbolic information is wanted then just return nullptr.
2818 if (info->verbose == false) {
2819 *ReferenceName = nullptr;
2820 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
2824 const char *SymbolName = GuessSymbolName(ReferenceValue, info->AddrMap);
2826 if (*ReferenceType == LLVMDisassembler_ReferenceType_In_Branch) {
2827 *ReferenceName = GuessIndirectSymbol(ReferenceValue, info);
2828 if (*ReferenceName != nullptr) {
2829 method_reference(info, ReferenceType, ReferenceName);
2830 if (*ReferenceType != LLVMDisassembler_ReferenceType_Out_Objc_Message)
2831 *ReferenceType = LLVMDisassembler_ReferenceType_Out_SymbolStub;
2834 if (SymbolName != nullptr && strncmp(SymbolName, "__Z", 3) == 0) {
2835 if (info->demangled_name != nullptr)
2836 free(info->demangled_name);
2838 info->demangled_name =
2839 abi::__cxa_demangle(SymbolName + 1, nullptr, nullptr, &status);
2840 if (info->demangled_name != nullptr) {
2841 *ReferenceName = info->demangled_name;
2842 *ReferenceType = LLVMDisassembler_ReferenceType_DeMangled_Name;
2844 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
2847 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
2848 } else if (*ReferenceType == LLVMDisassembler_ReferenceType_In_PCrel_Load) {
2850 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
2852 method_reference(info, ReferenceType, ReferenceName);
2854 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
2855 // If this is arm64 and the reference is an adrp instruction save the
2856 // instruction, passed in ReferenceValue and the address of the instruction
2857 // for use later if we see and add immediate instruction.
2858 } else if (info->O->getArch() == Triple::aarch64 &&
2859 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADRP) {
2860 info->adrp_inst = ReferenceValue;
2861 info->adrp_addr = ReferencePC;
2862 SymbolName = nullptr;
2863 *ReferenceName = nullptr;
2864 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
2865 // If this is arm64 and reference is an add immediate instruction and we
2867 // seen an adrp instruction just before it and the adrp's Xd register
2869 // this add's Xn register reconstruct the value being referenced and look to
2870 // see if it is a literal pointer. Note the add immediate instruction is
2871 // passed in ReferenceValue.
2872 } else if (info->O->getArch() == Triple::aarch64 &&
2873 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADDXri &&
2874 ReferencePC - 4 == info->adrp_addr &&
2875 (info->adrp_inst & 0x9f000000) == 0x90000000 &&
2876 (info->adrp_inst & 0x1f) == ((ReferenceValue >> 5) & 0x1f)) {
2877 uint32_t addxri_inst;
2878 uint64_t adrp_imm, addxri_imm;
2881 ((info->adrp_inst & 0x00ffffe0) >> 3) | ((info->adrp_inst >> 29) & 0x3);
2882 if (info->adrp_inst & 0x0200000)
2883 adrp_imm |= 0xfffffffffc000000LL;
2885 addxri_inst = ReferenceValue;
2886 addxri_imm = (addxri_inst >> 10) & 0xfff;
2887 if (((addxri_inst >> 22) & 0x3) == 1)
2890 ReferenceValue = (info->adrp_addr & 0xfffffffffffff000LL) +
2891 (adrp_imm << 12) + addxri_imm;
2894 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
2895 if (*ReferenceName == nullptr)
2896 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
2897 // If this is arm64 and the reference is a load register instruction and we
2898 // have seen an adrp instruction just before it and the adrp's Xd register
2899 // matches this add's Xn register reconstruct the value being referenced and
2900 // look to see if it is a literal pointer. Note the load register
2901 // instruction is passed in ReferenceValue.
2902 } else if (info->O->getArch() == Triple::aarch64 &&
2903 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_LDRXui &&
2904 ReferencePC - 4 == info->adrp_addr &&
2905 (info->adrp_inst & 0x9f000000) == 0x90000000 &&
2906 (info->adrp_inst & 0x1f) == ((ReferenceValue >> 5) & 0x1f)) {
2907 uint32_t ldrxui_inst;
2908 uint64_t adrp_imm, ldrxui_imm;
2911 ((info->adrp_inst & 0x00ffffe0) >> 3) | ((info->adrp_inst >> 29) & 0x3);
2912 if (info->adrp_inst & 0x0200000)
2913 adrp_imm |= 0xfffffffffc000000LL;
2915 ldrxui_inst = ReferenceValue;
2916 ldrxui_imm = (ldrxui_inst >> 10) & 0xfff;
2918 ReferenceValue = (info->adrp_addr & 0xfffffffffffff000LL) +
2919 (adrp_imm << 12) + (ldrxui_imm << 3);
2922 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
2923 if (*ReferenceName == nullptr)
2924 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
2926 // If this arm64 and is an load register (PC-relative) instruction the
2927 // ReferenceValue is the PC plus the immediate value.
2928 else if (info->O->getArch() == Triple::aarch64 &&
2929 (*ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_LDRXl ||
2930 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADR)) {
2932 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
2933 if (*ReferenceName == nullptr)
2934 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
2937 else if (SymbolName != nullptr && strncmp(SymbolName, "__Z", 3) == 0) {
2938 if (info->demangled_name != nullptr)
2939 free(info->demangled_name);
2941 info->demangled_name =
2942 abi::__cxa_demangle(SymbolName + 1, nullptr, nullptr, &status);
2943 if (info->demangled_name != nullptr) {
2944 *ReferenceName = info->demangled_name;
2945 *ReferenceType = LLVMDisassembler_ReferenceType_DeMangled_Name;
2950 *ReferenceName = nullptr;
2951 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
2957 /// \brief Emits the comments that are stored in the CommentStream.
2958 /// Each comment in the CommentStream must end with a newline.
2959 static void emitComments(raw_svector_ostream &CommentStream,
2960 SmallString<128> &CommentsToEmit,
2961 formatted_raw_ostream &FormattedOS,
2962 const MCAsmInfo &MAI) {
2963 // Flush the stream before taking its content.
2964 CommentStream.flush();
2965 StringRef Comments = CommentsToEmit.str();
2966 // Get the default information for printing a comment.
2967 const char *CommentBegin = MAI.getCommentString();
2968 unsigned CommentColumn = MAI.getCommentColumn();
2969 bool IsFirst = true;
2970 while (!Comments.empty()) {
2972 FormattedOS << '\n';
2973 // Emit a line of comments.
2974 FormattedOS.PadToColumn(CommentColumn);
2975 size_t Position = Comments.find('\n');
2976 FormattedOS << CommentBegin << ' ' << Comments.substr(0, Position);
2977 // Move after the newline character.
2978 Comments = Comments.substr(Position + 1);
2981 FormattedOS.flush();
2983 // Tell the comment stream that the vector changed underneath it.
2984 CommentsToEmit.clear();
2985 CommentStream.resync();
2988 static void DisassembleMachO(StringRef Filename, MachOObjectFile *MachOOF,
2989 StringRef DisSegName, StringRef DisSectName) {
2990 const char *McpuDefault = nullptr;
2991 const Target *ThumbTarget = nullptr;
2992 const Target *TheTarget = GetTarget(MachOOF, &McpuDefault, &ThumbTarget);
2994 // GetTarget prints out stuff.
2997 if (MCPU.empty() && McpuDefault)
3000 std::unique_ptr<const MCInstrInfo> InstrInfo(TheTarget->createMCInstrInfo());
3001 std::unique_ptr<const MCInstrInfo> ThumbInstrInfo;
3003 ThumbInstrInfo.reset(ThumbTarget->createMCInstrInfo());
3005 // Package up features to be passed to target/subtarget
3006 std::string FeaturesStr;
3007 if (MAttrs.size()) {
3008 SubtargetFeatures Features;
3009 for (unsigned i = 0; i != MAttrs.size(); ++i)
3010 Features.AddFeature(MAttrs[i]);
3011 FeaturesStr = Features.getString();
3014 // Set up disassembler.
3015 std::unique_ptr<const MCRegisterInfo> MRI(
3016 TheTarget->createMCRegInfo(TripleName));
3017 std::unique_ptr<const MCAsmInfo> AsmInfo(
3018 TheTarget->createMCAsmInfo(*MRI, TripleName));
3019 std::unique_ptr<const MCSubtargetInfo> STI(
3020 TheTarget->createMCSubtargetInfo(TripleName, MCPU, FeaturesStr));
3021 MCContext Ctx(AsmInfo.get(), MRI.get(), nullptr);
3022 std::unique_ptr<MCDisassembler> DisAsm(
3023 TheTarget->createMCDisassembler(*STI, Ctx));
3024 std::unique_ptr<MCSymbolizer> Symbolizer;
3025 struct DisassembleInfo SymbolizerInfo;
3026 std::unique_ptr<MCRelocationInfo> RelInfo(
3027 TheTarget->createMCRelocationInfo(TripleName, Ctx));
3029 Symbolizer.reset(TheTarget->createMCSymbolizer(
3030 TripleName, SymbolizerGetOpInfo, SymbolizerSymbolLookUp,
3031 &SymbolizerInfo, &Ctx, std::move(RelInfo)));
3032 DisAsm->setSymbolizer(std::move(Symbolizer));
3034 int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
3035 std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
3036 AsmPrinterVariant, *AsmInfo, *InstrInfo, *MRI, *STI));
3037 // Set the display preference for hex vs. decimal immediates.
3038 IP->setPrintImmHex(PrintImmHex);
3039 // Comment stream and backing vector.
3040 SmallString<128> CommentsToEmit;
3041 raw_svector_ostream CommentStream(CommentsToEmit);
3042 // FIXME: Setting the CommentStream in the InstPrinter is problematic in that
3043 // if it is done then arm64 comments for string literals don't get printed
3044 // and some constant get printed instead and not setting it causes intel
3045 // (32-bit and 64-bit) comments printed with different spacing before the
3046 // comment causing different diffs with the 'C' disassembler library API.
3047 // IP->setCommentStream(CommentStream);
3049 if (!AsmInfo || !STI || !DisAsm || !IP) {
3050 errs() << "error: couldn't initialize disassembler for target "
3051 << TripleName << '\n';
3055 // Set up thumb disassembler.
3056 std::unique_ptr<const MCRegisterInfo> ThumbMRI;
3057 std::unique_ptr<const MCAsmInfo> ThumbAsmInfo;
3058 std::unique_ptr<const MCSubtargetInfo> ThumbSTI;
3059 std::unique_ptr<MCDisassembler> ThumbDisAsm;
3060 std::unique_ptr<MCInstPrinter> ThumbIP;
3061 std::unique_ptr<MCContext> ThumbCtx;
3062 std::unique_ptr<MCSymbolizer> ThumbSymbolizer;
3063 struct DisassembleInfo ThumbSymbolizerInfo;
3064 std::unique_ptr<MCRelocationInfo> ThumbRelInfo;
3066 ThumbMRI.reset(ThumbTarget->createMCRegInfo(ThumbTripleName));
3068 ThumbTarget->createMCAsmInfo(*ThumbMRI, ThumbTripleName));
3070 ThumbTarget->createMCSubtargetInfo(ThumbTripleName, MCPU, FeaturesStr));
3071 ThumbCtx.reset(new MCContext(ThumbAsmInfo.get(), ThumbMRI.get(), nullptr));
3072 ThumbDisAsm.reset(ThumbTarget->createMCDisassembler(*ThumbSTI, *ThumbCtx));
3073 MCContext *PtrThumbCtx = ThumbCtx.get();
3075 ThumbTarget->createMCRelocationInfo(ThumbTripleName, *PtrThumbCtx));
3077 ThumbSymbolizer.reset(ThumbTarget->createMCSymbolizer(
3078 ThumbTripleName, SymbolizerGetOpInfo, SymbolizerSymbolLookUp,
3079 &ThumbSymbolizerInfo, PtrThumbCtx, std::move(ThumbRelInfo)));
3080 ThumbDisAsm->setSymbolizer(std::move(ThumbSymbolizer));
3082 int ThumbAsmPrinterVariant = ThumbAsmInfo->getAssemblerDialect();
3083 ThumbIP.reset(ThumbTarget->createMCInstPrinter(
3084 ThumbAsmPrinterVariant, *ThumbAsmInfo, *ThumbInstrInfo, *ThumbMRI,
3086 // Set the display preference for hex vs. decimal immediates.
3087 ThumbIP->setPrintImmHex(PrintImmHex);
3090 if (ThumbTarget && (!ThumbAsmInfo || !ThumbSTI || !ThumbDisAsm || !ThumbIP)) {
3091 errs() << "error: couldn't initialize disassembler for target "
3092 << ThumbTripleName << '\n';
3096 MachO::mach_header Header = MachOOF->getHeader();
3098 // FIXME: Using the -cfg command line option, this code used to be able to
3099 // annotate relocations with the referenced symbol's name, and if this was
3100 // inside a __[cf]string section, the data it points to. This is now replaced
3101 // by the upcoming MCSymbolizer, which needs the appropriate setup done above.
3102 std::vector<SectionRef> Sections;
3103 std::vector<SymbolRef> Symbols;
3104 SmallVector<uint64_t, 8> FoundFns;
3105 uint64_t BaseSegmentAddress;
3107 getSectionsAndSymbols(Header, MachOOF, Sections, Symbols, FoundFns,
3108 BaseSegmentAddress);
3110 // Sort the symbols by address, just in case they didn't come in that way.
3111 std::sort(Symbols.begin(), Symbols.end(), SymbolSorter());
3113 // Build a data in code table that is sorted on by the address of each entry.
3114 uint64_t BaseAddress = 0;
3115 if (Header.filetype == MachO::MH_OBJECT)
3116 BaseAddress = Sections[0].getAddress();
3118 BaseAddress = BaseSegmentAddress;
3120 for (dice_iterator DI = MachOOF->begin_dices(), DE = MachOOF->end_dices();
3123 DI->getOffset(Offset);
3124 Dices.push_back(std::make_pair(BaseAddress + Offset, *DI));
3126 array_pod_sort(Dices.begin(), Dices.end());
3129 raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls();
3131 raw_ostream &DebugOut = nulls();
3134 std::unique_ptr<DIContext> diContext;
3135 ObjectFile *DbgObj = MachOOF;
3136 // Try to find debug info and set up the DIContext for it.
3138 // A separate DSym file path was specified, parse it as a macho file,
3139 // get the sections and supply it to the section name parsing machinery.
3140 if (!DSYMFile.empty()) {
3141 ErrorOr<std::unique_ptr<MemoryBuffer>> BufOrErr =
3142 MemoryBuffer::getFileOrSTDIN(DSYMFile);
3143 if (std::error_code EC = BufOrErr.getError()) {
3144 errs() << "llvm-objdump: " << Filename << ": " << EC.message() << '\n';
3148 ObjectFile::createMachOObjectFile(BufOrErr.get()->getMemBufferRef())
3153 // Setup the DIContext
3154 diContext.reset(DIContext::getDWARFContext(*DbgObj));
3157 if (DumpSections.size() == 0)
3158 outs() << "(" << DisSegName << "," << DisSectName << ") section\n";
3160 for (unsigned SectIdx = 0; SectIdx != Sections.size(); SectIdx++) {
3162 if (Sections[SectIdx].getName(SectName) || SectName != DisSectName)
3165 DataRefImpl DR = Sections[SectIdx].getRawDataRefImpl();
3167 StringRef SegmentName = MachOOF->getSectionFinalSegmentName(DR);
3168 if (SegmentName != DisSegName)
3172 Sections[SectIdx].getContents(BytesStr);
3173 ArrayRef<uint8_t> Bytes(reinterpret_cast<const uint8_t *>(BytesStr.data()),
3175 uint64_t SectAddress = Sections[SectIdx].getAddress();
3177 bool symbolTableWorked = false;
3179 // Parse relocations.
3180 std::vector<std::pair<uint64_t, SymbolRef>> Relocs;
3181 for (const RelocationRef &Reloc : Sections[SectIdx].relocations()) {
3182 uint64_t RelocOffset;
3183 Reloc.getOffset(RelocOffset);
3184 uint64_t SectionAddress = Sections[SectIdx].getAddress();
3185 RelocOffset -= SectionAddress;
3187 symbol_iterator RelocSym = Reloc.getSymbol();
3189 Relocs.push_back(std::make_pair(RelocOffset, *RelocSym));
3191 array_pod_sort(Relocs.begin(), Relocs.end());
3193 // Create a map of symbol addresses to symbol names for use by
3194 // the SymbolizerSymbolLookUp() routine.
3195 SymbolAddressMap AddrMap;
3196 bool DisSymNameFound = false;
3197 for (const SymbolRef &Symbol : MachOOF->symbols()) {
3200 if (ST == SymbolRef::ST_Function || ST == SymbolRef::ST_Data ||
3201 ST == SymbolRef::ST_Other) {
3203 Symbol.getAddress(Address);
3205 Symbol.getName(SymName);
3206 AddrMap[Address] = SymName;
3207 if (!DisSymName.empty() && DisSymName == SymName)
3208 DisSymNameFound = true;
3211 if (!DisSymName.empty() && DisSymNameFound == false) {
3212 outs() << "Can't find -dis-symname: " << DisSymName << "\n";
3215 // Set up the block of info used by the Symbolizer call backs.
3216 SymbolizerInfo.verbose = !NoSymbolicOperands;
3217 SymbolizerInfo.O = MachOOF;
3218 SymbolizerInfo.S = Sections[SectIdx];
3219 SymbolizerInfo.AddrMap = &AddrMap;
3220 SymbolizerInfo.Sections = &Sections;
3221 SymbolizerInfo.class_name = nullptr;
3222 SymbolizerInfo.selector_name = nullptr;
3223 SymbolizerInfo.method = nullptr;
3224 SymbolizerInfo.demangled_name = nullptr;
3225 SymbolizerInfo.bindtable = nullptr;
3226 SymbolizerInfo.adrp_addr = 0;
3227 SymbolizerInfo.adrp_inst = 0;
3228 // Same for the ThumbSymbolizer
3229 ThumbSymbolizerInfo.verbose = !NoSymbolicOperands;
3230 ThumbSymbolizerInfo.O = MachOOF;
3231 ThumbSymbolizerInfo.S = Sections[SectIdx];
3232 ThumbSymbolizerInfo.AddrMap = &AddrMap;
3233 ThumbSymbolizerInfo.Sections = &Sections;
3234 ThumbSymbolizerInfo.class_name = nullptr;
3235 ThumbSymbolizerInfo.selector_name = nullptr;
3236 ThumbSymbolizerInfo.method = nullptr;
3237 ThumbSymbolizerInfo.demangled_name = nullptr;
3238 ThumbSymbolizerInfo.bindtable = nullptr;
3239 ThumbSymbolizerInfo.adrp_addr = 0;
3240 ThumbSymbolizerInfo.adrp_inst = 0;
3242 // Disassemble symbol by symbol.
3243 for (unsigned SymIdx = 0; SymIdx != Symbols.size(); SymIdx++) {
3245 Symbols[SymIdx].getName(SymName);
3248 Symbols[SymIdx].getType(ST);
3249 if (ST != SymbolRef::ST_Function)
3252 // Make sure the symbol is defined in this section.
3253 bool containsSym = Sections[SectIdx].containsSymbol(Symbols[SymIdx]);
3257 // If we are only disassembling one symbol see if this is that symbol.
3258 if (!DisSymName.empty() && DisSymName != SymName)
3261 // Start at the address of the symbol relative to the section's address.
3263 uint64_t SectionAddress = Sections[SectIdx].getAddress();
3264 Symbols[SymIdx].getAddress(Start);
3265 Start -= SectionAddress;
3267 // Stop disassembling either at the beginning of the next symbol or at
3268 // the end of the section.
3269 bool containsNextSym = false;
3270 uint64_t NextSym = 0;
3271 uint64_t NextSymIdx = SymIdx + 1;
3272 while (Symbols.size() > NextSymIdx) {
3273 SymbolRef::Type NextSymType;
3274 Symbols[NextSymIdx].getType(NextSymType);
3275 if (NextSymType == SymbolRef::ST_Function) {
3277 Sections[SectIdx].containsSymbol(Symbols[NextSymIdx]);
3278 Symbols[NextSymIdx].getAddress(NextSym);
3279 NextSym -= SectionAddress;
3285 uint64_t SectSize = Sections[SectIdx].getSize();
3286 uint64_t End = containsNextSym ? NextSym : SectSize;
3289 symbolTableWorked = true;
3291 DataRefImpl Symb = Symbols[SymIdx].getRawDataRefImpl();
3293 (MachOOF->getSymbolFlags(Symb) & SymbolRef::SF_Thumb) && ThumbTarget;
3295 outs() << SymName << ":\n";
3296 DILineInfo lastLine;
3297 for (uint64_t Index = Start; Index < End; Index += Size) {
3300 uint64_t PC = SectAddress + Index;
3301 if (!NoLeadingAddr) {
3302 if (FullLeadingAddr) {
3303 if (MachOOF->is64Bit())
3304 outs() << format("%016" PRIx64, PC);
3306 outs() << format("%08" PRIx64, PC);
3308 outs() << format("%8" PRIx64 ":", PC);
3314 // Check the data in code table here to see if this is data not an
3315 // instruction to be disassembled.
3317 Dice.push_back(std::make_pair(PC, DiceRef()));
3318 dice_table_iterator DTI =
3319 std::search(Dices.begin(), Dices.end(), Dice.begin(), Dice.end(),
3320 compareDiceTableEntries);
3321 if (DTI != Dices.end()) {
3323 DTI->second.getLength(Length);
3325 DTI->second.getKind(Kind);
3326 Size = DumpDataInCode(reinterpret_cast<const char *>(Bytes.data()) +
3329 if ((Kind == MachO::DICE_KIND_JUMP_TABLE8) &&
3330 (PC == (DTI->first + Length - 1)) && (Length & 1))
3335 SmallVector<char, 64> AnnotationsBytes;
3336 raw_svector_ostream Annotations(AnnotationsBytes);
3340 gotInst = ThumbDisAsm->getInstruction(Inst, Size, Bytes.slice(Index),
3341 PC, DebugOut, Annotations);
3343 gotInst = DisAsm->getInstruction(Inst, Size, Bytes.slice(Index), PC,
3344 DebugOut, Annotations);
3346 if (!NoShowRawInsn) {
3347 DumpBytes(StringRef(
3348 reinterpret_cast<const char *>(Bytes.data()) + Index, Size));
3350 formatted_raw_ostream FormattedOS(outs());
3351 Annotations.flush();
3352 StringRef AnnotationsStr = Annotations.str();
3354 ThumbIP->printInst(&Inst, FormattedOS, AnnotationsStr);
3356 IP->printInst(&Inst, FormattedOS, AnnotationsStr);
3357 emitComments(CommentStream, CommentsToEmit, FormattedOS, *AsmInfo);
3359 // Print debug info.
3361 DILineInfo dli = diContext->getLineInfoForAddress(PC);
3362 // Print valid line info if it changed.
3363 if (dli != lastLine && dli.Line != 0)
3364 outs() << "\t## " << dli.FileName << ':' << dli.Line << ':'
3370 unsigned int Arch = MachOOF->getArch();
3371 if (Arch == Triple::x86_64 || Arch == Triple::x86) {
3372 outs() << format("\t.byte 0x%02x #bad opcode\n",
3373 *(Bytes.data() + Index) & 0xff);
3374 Size = 1; // skip exactly one illegible byte and move on.
3375 } else if (Arch == Triple::aarch64) {
3376 uint32_t opcode = (*(Bytes.data() + Index) & 0xff) |
3377 (*(Bytes.data() + Index + 1) & 0xff) << 8 |
3378 (*(Bytes.data() + Index + 2) & 0xff) << 16 |
3379 (*(Bytes.data() + Index + 3) & 0xff) << 24;
3380 outs() << format("\t.long\t0x%08x\n", opcode);
3383 errs() << "llvm-objdump: warning: invalid instruction encoding\n";
3385 Size = 1; // skip illegible bytes
3390 if (!symbolTableWorked) {
3391 // Reading the symbol table didn't work, disassemble the whole section.
3392 uint64_t SectAddress = Sections[SectIdx].getAddress();
3393 uint64_t SectSize = Sections[SectIdx].getSize();
3395 for (uint64_t Index = 0; Index < SectSize; Index += InstSize) {
3398 uint64_t PC = SectAddress + Index;
3399 if (DisAsm->getInstruction(Inst, InstSize, Bytes.slice(Index), PC,
3400 DebugOut, nulls())) {
3401 if (!NoLeadingAddr) {
3402 if (FullLeadingAddr) {
3403 if (MachOOF->is64Bit())
3404 outs() << format("%016" PRIx64, PC);
3406 outs() << format("%08" PRIx64, PC);
3408 outs() << format("%8" PRIx64 ":", PC);
3411 if (!NoShowRawInsn) {
3414 StringRef(reinterpret_cast<const char *>(Bytes.data()) + Index,
3417 IP->printInst(&Inst, outs(), "");
3420 unsigned int Arch = MachOOF->getArch();
3421 if (Arch == Triple::x86_64 || Arch == Triple::x86) {
3422 outs() << format("\t.byte 0x%02x #bad opcode\n",
3423 *(Bytes.data() + Index) & 0xff);
3424 InstSize = 1; // skip exactly one illegible byte and move on.
3426 errs() << "llvm-objdump: warning: invalid instruction encoding\n";
3428 InstSize = 1; // skip illegible bytes
3433 // The TripleName's need to be reset if we are called again for a different
3436 ThumbTripleName = "";
3438 if (SymbolizerInfo.method != nullptr)
3439 free(SymbolizerInfo.method);
3440 if (SymbolizerInfo.demangled_name != nullptr)
3441 free(SymbolizerInfo.demangled_name);
3442 if (SymbolizerInfo.bindtable != nullptr)
3443 delete SymbolizerInfo.bindtable;
3444 if (ThumbSymbolizerInfo.method != nullptr)
3445 free(ThumbSymbolizerInfo.method);
3446 if (ThumbSymbolizerInfo.demangled_name != nullptr)
3447 free(ThumbSymbolizerInfo.demangled_name);
3448 if (ThumbSymbolizerInfo.bindtable != nullptr)
3449 delete ThumbSymbolizerInfo.bindtable;
3453 //===----------------------------------------------------------------------===//
3454 // __compact_unwind section dumping
3455 //===----------------------------------------------------------------------===//
3459 template <typename T> static uint64_t readNext(const char *&Buf) {
3460 using llvm::support::little;
3461 using llvm::support::unaligned;
3463 uint64_t Val = support::endian::read<T, little, unaligned>(Buf);
3468 struct CompactUnwindEntry {
3469 uint32_t OffsetInSection;
3471 uint64_t FunctionAddr;
3473 uint32_t CompactEncoding;
3474 uint64_t PersonalityAddr;
3477 RelocationRef FunctionReloc;
3478 RelocationRef PersonalityReloc;
3479 RelocationRef LSDAReloc;
3481 CompactUnwindEntry(StringRef Contents, unsigned Offset, bool Is64)
3482 : OffsetInSection(Offset) {
3484 read<uint64_t>(Contents.data() + Offset);
3486 read<uint32_t>(Contents.data() + Offset);
3490 template <typename UIntPtr> void read(const char *Buf) {
3491 FunctionAddr = readNext<UIntPtr>(Buf);
3492 Length = readNext<uint32_t>(Buf);
3493 CompactEncoding = readNext<uint32_t>(Buf);
3494 PersonalityAddr = readNext<UIntPtr>(Buf);
3495 LSDAAddr = readNext<UIntPtr>(Buf);
3500 /// Given a relocation from __compact_unwind, consisting of the RelocationRef
3501 /// and data being relocated, determine the best base Name and Addend to use for
3502 /// display purposes.
3504 /// 1. An Extern relocation will directly reference a symbol (and the data is
3505 /// then already an addend), so use that.
3506 /// 2. Otherwise the data is an offset in the object file's layout; try to find
3507 // a symbol before it in the same section, and use the offset from there.
3508 /// 3. Finally, if all that fails, fall back to an offset from the start of the
3509 /// referenced section.
3510 static void findUnwindRelocNameAddend(const MachOObjectFile *Obj,
3511 std::map<uint64_t, SymbolRef> &Symbols,
3512 const RelocationRef &Reloc, uint64_t Addr,
3513 StringRef &Name, uint64_t &Addend) {
3514 if (Reloc.getSymbol() != Obj->symbol_end()) {
3515 Reloc.getSymbol()->getName(Name);
3520 auto RE = Obj->getRelocation(Reloc.getRawDataRefImpl());
3521 SectionRef RelocSection = Obj->getRelocationSection(RE);
3523 uint64_t SectionAddr = RelocSection.getAddress();
3525 auto Sym = Symbols.upper_bound(Addr);
3526 if (Sym == Symbols.begin()) {
3527 // The first symbol in the object is after this reference, the best we can
3528 // do is section-relative notation.
3529 RelocSection.getName(Name);
3530 Addend = Addr - SectionAddr;
3534 // Go back one so that SymbolAddress <= Addr.
3537 section_iterator SymSection = Obj->section_end();
3538 Sym->second.getSection(SymSection);
3539 if (RelocSection == *SymSection) {
3540 // There's a valid symbol in the same section before this reference.
3541 Sym->second.getName(Name);
3542 Addend = Addr - Sym->first;
3546 // There is a symbol before this reference, but it's in a different
3547 // section. Probably not helpful to mention it, so use the section name.
3548 RelocSection.getName(Name);
3549 Addend = Addr - SectionAddr;
3552 static void printUnwindRelocDest(const MachOObjectFile *Obj,
3553 std::map<uint64_t, SymbolRef> &Symbols,
3554 const RelocationRef &Reloc, uint64_t Addr) {
3558 if (!Reloc.getObjectFile())
3561 findUnwindRelocNameAddend(Obj, Symbols, Reloc, Addr, Name, Addend);
3565 outs() << " + " << format("0x%" PRIx64, Addend);
3569 printMachOCompactUnwindSection(const MachOObjectFile *Obj,
3570 std::map<uint64_t, SymbolRef> &Symbols,
3571 const SectionRef &CompactUnwind) {
3573 assert(Obj->isLittleEndian() &&
3574 "There should not be a big-endian .o with __compact_unwind");
3576 bool Is64 = Obj->is64Bit();
3577 uint32_t PointerSize = Is64 ? sizeof(uint64_t) : sizeof(uint32_t);
3578 uint32_t EntrySize = 3 * PointerSize + 2 * sizeof(uint32_t);
3581 CompactUnwind.getContents(Contents);
3583 SmallVector<CompactUnwindEntry, 4> CompactUnwinds;
3585 // First populate the initial raw offsets, encodings and so on from the entry.
3586 for (unsigned Offset = 0; Offset < Contents.size(); Offset += EntrySize) {
3587 CompactUnwindEntry Entry(Contents.data(), Offset, Is64);
3588 CompactUnwinds.push_back(Entry);
3591 // Next we need to look at the relocations to find out what objects are
3592 // actually being referred to.
3593 for (const RelocationRef &Reloc : CompactUnwind.relocations()) {
3594 uint64_t RelocAddress;
3595 Reloc.getOffset(RelocAddress);
3597 uint32_t EntryIdx = RelocAddress / EntrySize;
3598 uint32_t OffsetInEntry = RelocAddress - EntryIdx * EntrySize;
3599 CompactUnwindEntry &Entry = CompactUnwinds[EntryIdx];
3601 if (OffsetInEntry == 0)
3602 Entry.FunctionReloc = Reloc;
3603 else if (OffsetInEntry == PointerSize + 2 * sizeof(uint32_t))
3604 Entry.PersonalityReloc = Reloc;
3605 else if (OffsetInEntry == 2 * PointerSize + 2 * sizeof(uint32_t))
3606 Entry.LSDAReloc = Reloc;
3608 llvm_unreachable("Unexpected relocation in __compact_unwind section");
3611 // Finally, we're ready to print the data we've gathered.
3612 outs() << "Contents of __compact_unwind section:\n";
3613 for (auto &Entry : CompactUnwinds) {
3614 outs() << " Entry at offset "
3615 << format("0x%" PRIx32, Entry.OffsetInSection) << ":\n";
3617 // 1. Start of the region this entry applies to.
3618 outs() << " start: " << format("0x%" PRIx64,
3619 Entry.FunctionAddr) << ' ';
3620 printUnwindRelocDest(Obj, Symbols, Entry.FunctionReloc, Entry.FunctionAddr);
3623 // 2. Length of the region this entry applies to.
3624 outs() << " length: " << format("0x%" PRIx32, Entry.Length)
3626 // 3. The 32-bit compact encoding.
3627 outs() << " compact encoding: "
3628 << format("0x%08" PRIx32, Entry.CompactEncoding) << '\n';
3630 // 4. The personality function, if present.
3631 if (Entry.PersonalityReloc.getObjectFile()) {
3632 outs() << " personality function: "
3633 << format("0x%" PRIx64, Entry.PersonalityAddr) << ' ';
3634 printUnwindRelocDest(Obj, Symbols, Entry.PersonalityReloc,
3635 Entry.PersonalityAddr);
3639 // 5. This entry's language-specific data area.
3640 if (Entry.LSDAReloc.getObjectFile()) {
3641 outs() << " LSDA: " << format("0x%" PRIx64,
3642 Entry.LSDAAddr) << ' ';
3643 printUnwindRelocDest(Obj, Symbols, Entry.LSDAReloc, Entry.LSDAAddr);
3649 //===----------------------------------------------------------------------===//
3650 // __unwind_info section dumping
3651 //===----------------------------------------------------------------------===//
3653 static void printRegularSecondLevelUnwindPage(const char *PageStart) {
3654 const char *Pos = PageStart;
3655 uint32_t Kind = readNext<uint32_t>(Pos);
3657 assert(Kind == 2 && "kind for a regular 2nd level index should be 2");
3659 uint16_t EntriesStart = readNext<uint16_t>(Pos);
3660 uint16_t NumEntries = readNext<uint16_t>(Pos);
3662 Pos = PageStart + EntriesStart;
3663 for (unsigned i = 0; i < NumEntries; ++i) {
3664 uint32_t FunctionOffset = readNext<uint32_t>(Pos);
3665 uint32_t Encoding = readNext<uint32_t>(Pos);
3667 outs() << " [" << i << "]: "
3668 << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
3670 << "encoding=" << format("0x%08" PRIx32, Encoding) << '\n';
3674 static void printCompressedSecondLevelUnwindPage(
3675 const char *PageStart, uint32_t FunctionBase,
3676 const SmallVectorImpl<uint32_t> &CommonEncodings) {
3677 const char *Pos = PageStart;
3678 uint32_t Kind = readNext<uint32_t>(Pos);
3680 assert(Kind == 3 && "kind for a compressed 2nd level index should be 3");
3682 uint16_t EntriesStart = readNext<uint16_t>(Pos);
3683 uint16_t NumEntries = readNext<uint16_t>(Pos);
3685 uint16_t EncodingsStart = readNext<uint16_t>(Pos);
3686 readNext<uint16_t>(Pos);
3687 const auto *PageEncodings = reinterpret_cast<const support::ulittle32_t *>(
3688 PageStart + EncodingsStart);
3690 Pos = PageStart + EntriesStart;
3691 for (unsigned i = 0; i < NumEntries; ++i) {
3692 uint32_t Entry = readNext<uint32_t>(Pos);
3693 uint32_t FunctionOffset = FunctionBase + (Entry & 0xffffff);
3694 uint32_t EncodingIdx = Entry >> 24;
3697 if (EncodingIdx < CommonEncodings.size())
3698 Encoding = CommonEncodings[EncodingIdx];
3700 Encoding = PageEncodings[EncodingIdx - CommonEncodings.size()];
3702 outs() << " [" << i << "]: "
3703 << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
3705 << "encoding[" << EncodingIdx
3706 << "]=" << format("0x%08" PRIx32, Encoding) << '\n';
3710 static void printMachOUnwindInfoSection(const MachOObjectFile *Obj,
3711 std::map<uint64_t, SymbolRef> &Symbols,
3712 const SectionRef &UnwindInfo) {
3714 assert(Obj->isLittleEndian() &&
3715 "There should not be a big-endian .o with __unwind_info");
3717 outs() << "Contents of __unwind_info section:\n";
3720 UnwindInfo.getContents(Contents);
3721 const char *Pos = Contents.data();
3723 //===----------------------------------
3725 //===----------------------------------
3727 uint32_t Version = readNext<uint32_t>(Pos);
3728 outs() << " Version: "
3729 << format("0x%" PRIx32, Version) << '\n';
3730 assert(Version == 1 && "only understand version 1");
3732 uint32_t CommonEncodingsStart = readNext<uint32_t>(Pos);
3733 outs() << " Common encodings array section offset: "
3734 << format("0x%" PRIx32, CommonEncodingsStart) << '\n';
3735 uint32_t NumCommonEncodings = readNext<uint32_t>(Pos);
3736 outs() << " Number of common encodings in array: "
3737 << format("0x%" PRIx32, NumCommonEncodings) << '\n';
3739 uint32_t PersonalitiesStart = readNext<uint32_t>(Pos);
3740 outs() << " Personality function array section offset: "
3741 << format("0x%" PRIx32, PersonalitiesStart) << '\n';
3742 uint32_t NumPersonalities = readNext<uint32_t>(Pos);
3743 outs() << " Number of personality functions in array: "
3744 << format("0x%" PRIx32, NumPersonalities) << '\n';
3746 uint32_t IndicesStart = readNext<uint32_t>(Pos);
3747 outs() << " Index array section offset: "
3748 << format("0x%" PRIx32, IndicesStart) << '\n';
3749 uint32_t NumIndices = readNext<uint32_t>(Pos);
3750 outs() << " Number of indices in array: "
3751 << format("0x%" PRIx32, NumIndices) << '\n';
3753 //===----------------------------------
3754 // A shared list of common encodings
3755 //===----------------------------------
3757 // These occupy indices in the range [0, N] whenever an encoding is referenced
3758 // from a compressed 2nd level index table. In practice the linker only
3759 // creates ~128 of these, so that indices are available to embed encodings in
3760 // the 2nd level index.
3762 SmallVector<uint32_t, 64> CommonEncodings;
3763 outs() << " Common encodings: (count = " << NumCommonEncodings << ")\n";
3764 Pos = Contents.data() + CommonEncodingsStart;
3765 for (unsigned i = 0; i < NumCommonEncodings; ++i) {
3766 uint32_t Encoding = readNext<uint32_t>(Pos);
3767 CommonEncodings.push_back(Encoding);
3769 outs() << " encoding[" << i << "]: " << format("0x%08" PRIx32, Encoding)
3773 //===----------------------------------
3774 // Personality functions used in this executable
3775 //===----------------------------------
3777 // There should be only a handful of these (one per source language,
3778 // roughly). Particularly since they only get 2 bits in the compact encoding.
3780 outs() << " Personality functions: (count = " << NumPersonalities << ")\n";
3781 Pos = Contents.data() + PersonalitiesStart;
3782 for (unsigned i = 0; i < NumPersonalities; ++i) {
3783 uint32_t PersonalityFn = readNext<uint32_t>(Pos);
3784 outs() << " personality[" << i + 1
3785 << "]: " << format("0x%08" PRIx32, PersonalityFn) << '\n';
3788 //===----------------------------------
3789 // The level 1 index entries
3790 //===----------------------------------
3792 // These specify an approximate place to start searching for the more detailed
3793 // information, sorted by PC.
3796 uint32_t FunctionOffset;
3797 uint32_t SecondLevelPageStart;
3801 SmallVector<IndexEntry, 4> IndexEntries;
3803 outs() << " Top level indices: (count = " << NumIndices << ")\n";
3804 Pos = Contents.data() + IndicesStart;
3805 for (unsigned i = 0; i < NumIndices; ++i) {
3808 Entry.FunctionOffset = readNext<uint32_t>(Pos);
3809 Entry.SecondLevelPageStart = readNext<uint32_t>(Pos);
3810 Entry.LSDAStart = readNext<uint32_t>(Pos);
3811 IndexEntries.push_back(Entry);
3813 outs() << " [" << i << "]: "
3814 << "function offset=" << format("0x%08" PRIx32, Entry.FunctionOffset)
3816 << "2nd level page offset="
3817 << format("0x%08" PRIx32, Entry.SecondLevelPageStart) << ", "
3818 << "LSDA offset=" << format("0x%08" PRIx32, Entry.LSDAStart) << '\n';
3821 //===----------------------------------
3822 // Next come the LSDA tables
3823 //===----------------------------------
3825 // The LSDA layout is rather implicit: it's a contiguous array of entries from
3826 // the first top-level index's LSDAOffset to the last (sentinel).
3828 outs() << " LSDA descriptors:\n";
3829 Pos = Contents.data() + IndexEntries[0].LSDAStart;
3830 int NumLSDAs = (IndexEntries.back().LSDAStart - IndexEntries[0].LSDAStart) /
3831 (2 * sizeof(uint32_t));
3832 for (int i = 0; i < NumLSDAs; ++i) {
3833 uint32_t FunctionOffset = readNext<uint32_t>(Pos);
3834 uint32_t LSDAOffset = readNext<uint32_t>(Pos);
3835 outs() << " [" << i << "]: "
3836 << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
3838 << "LSDA offset=" << format("0x%08" PRIx32, LSDAOffset) << '\n';
3841 //===----------------------------------
3842 // Finally, the 2nd level indices
3843 //===----------------------------------
3845 // Generally these are 4K in size, and have 2 possible forms:
3846 // + Regular stores up to 511 entries with disparate encodings
3847 // + Compressed stores up to 1021 entries if few enough compact encoding
3849 outs() << " Second level indices:\n";
3850 for (unsigned i = 0; i < IndexEntries.size() - 1; ++i) {
3851 // The final sentinel top-level index has no associated 2nd level page
3852 if (IndexEntries[i].SecondLevelPageStart == 0)
3855 outs() << " Second level index[" << i << "]: "
3856 << "offset in section="
3857 << format("0x%08" PRIx32, IndexEntries[i].SecondLevelPageStart)
3859 << "base function offset="
3860 << format("0x%08" PRIx32, IndexEntries[i].FunctionOffset) << '\n';
3862 Pos = Contents.data() + IndexEntries[i].SecondLevelPageStart;
3863 uint32_t Kind = *reinterpret_cast<const support::ulittle32_t *>(Pos);
3865 printRegularSecondLevelUnwindPage(Pos);
3867 printCompressedSecondLevelUnwindPage(Pos, IndexEntries[i].FunctionOffset,
3870 llvm_unreachable("Do not know how to print this kind of 2nd level page");
3874 void llvm::printMachOUnwindInfo(const MachOObjectFile *Obj) {
3875 std::map<uint64_t, SymbolRef> Symbols;
3876 for (const SymbolRef &SymRef : Obj->symbols()) {
3877 // Discard any undefined or absolute symbols. They're not going to take part
3878 // in the convenience lookup for unwind info and just take up resources.
3879 section_iterator Section = Obj->section_end();
3880 SymRef.getSection(Section);
3881 if (Section == Obj->section_end())
3885 SymRef.getAddress(Addr);
3886 Symbols.insert(std::make_pair(Addr, SymRef));
3889 for (const SectionRef &Section : Obj->sections()) {
3891 Section.getName(SectName);
3892 if (SectName == "__compact_unwind")
3893 printMachOCompactUnwindSection(Obj, Symbols, Section);
3894 else if (SectName == "__unwind_info")
3895 printMachOUnwindInfoSection(Obj, Symbols, Section);
3896 else if (SectName == "__eh_frame")
3897 outs() << "llvm-objdump: warning: unhandled __eh_frame section\n";
3901 static void PrintMachHeader(uint32_t magic, uint32_t cputype,
3902 uint32_t cpusubtype, uint32_t filetype,
3903 uint32_t ncmds, uint32_t sizeofcmds, uint32_t flags,
3905 outs() << "Mach header\n";
3906 outs() << " magic cputype cpusubtype caps filetype ncmds "
3907 "sizeofcmds flags\n";
3909 if (magic == MachO::MH_MAGIC)
3910 outs() << " MH_MAGIC";
3911 else if (magic == MachO::MH_MAGIC_64)
3912 outs() << "MH_MAGIC_64";
3914 outs() << format(" 0x%08" PRIx32, magic);
3916 case MachO::CPU_TYPE_I386:
3918 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
3919 case MachO::CPU_SUBTYPE_I386_ALL:
3923 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
3927 case MachO::CPU_TYPE_X86_64:
3928 outs() << " X86_64";
3929 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
3930 case MachO::CPU_SUBTYPE_X86_64_ALL:
3933 case MachO::CPU_SUBTYPE_X86_64_H:
3934 outs() << " Haswell";
3937 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
3941 case MachO::CPU_TYPE_ARM:
3943 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
3944 case MachO::CPU_SUBTYPE_ARM_ALL:
3947 case MachO::CPU_SUBTYPE_ARM_V4T:
3950 case MachO::CPU_SUBTYPE_ARM_V5TEJ:
3953 case MachO::CPU_SUBTYPE_ARM_XSCALE:
3954 outs() << " XSCALE";
3956 case MachO::CPU_SUBTYPE_ARM_V6:
3959 case MachO::CPU_SUBTYPE_ARM_V6M:
3962 case MachO::CPU_SUBTYPE_ARM_V7:
3965 case MachO::CPU_SUBTYPE_ARM_V7EM:
3968 case MachO::CPU_SUBTYPE_ARM_V7K:
3971 case MachO::CPU_SUBTYPE_ARM_V7M:
3974 case MachO::CPU_SUBTYPE_ARM_V7S:
3978 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
3982 case MachO::CPU_TYPE_ARM64:
3984 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
3985 case MachO::CPU_SUBTYPE_ARM64_ALL:
3989 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
3993 case MachO::CPU_TYPE_POWERPC:
3995 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
3996 case MachO::CPU_SUBTYPE_POWERPC_ALL:
4000 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
4004 case MachO::CPU_TYPE_POWERPC64:
4006 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
4007 case MachO::CPU_SUBTYPE_POWERPC_ALL:
4011 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
4016 if ((cpusubtype & MachO::CPU_SUBTYPE_MASK) == MachO::CPU_SUBTYPE_LIB64) {
4019 outs() << format(" 0x%02" PRIx32,
4020 (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24);
4023 case MachO::MH_OBJECT:
4024 outs() << " OBJECT";
4026 case MachO::MH_EXECUTE:
4027 outs() << " EXECUTE";
4029 case MachO::MH_FVMLIB:
4030 outs() << " FVMLIB";
4032 case MachO::MH_CORE:
4035 case MachO::MH_PRELOAD:
4036 outs() << " PRELOAD";
4038 case MachO::MH_DYLIB:
4041 case MachO::MH_DYLIB_STUB:
4042 outs() << " DYLIB_STUB";
4044 case MachO::MH_DYLINKER:
4045 outs() << " DYLINKER";
4047 case MachO::MH_BUNDLE:
4048 outs() << " BUNDLE";
4050 case MachO::MH_DSYM:
4053 case MachO::MH_KEXT_BUNDLE:
4054 outs() << " KEXTBUNDLE";
4057 outs() << format(" %10u", filetype);
4060 outs() << format(" %5u", ncmds);
4061 outs() << format(" %10u", sizeofcmds);
4063 if (f & MachO::MH_NOUNDEFS) {
4064 outs() << " NOUNDEFS";
4065 f &= ~MachO::MH_NOUNDEFS;
4067 if (f & MachO::MH_INCRLINK) {
4068 outs() << " INCRLINK";
4069 f &= ~MachO::MH_INCRLINK;
4071 if (f & MachO::MH_DYLDLINK) {
4072 outs() << " DYLDLINK";
4073 f &= ~MachO::MH_DYLDLINK;
4075 if (f & MachO::MH_BINDATLOAD) {
4076 outs() << " BINDATLOAD";
4077 f &= ~MachO::MH_BINDATLOAD;
4079 if (f & MachO::MH_PREBOUND) {
4080 outs() << " PREBOUND";
4081 f &= ~MachO::MH_PREBOUND;
4083 if (f & MachO::MH_SPLIT_SEGS) {
4084 outs() << " SPLIT_SEGS";
4085 f &= ~MachO::MH_SPLIT_SEGS;
4087 if (f & MachO::MH_LAZY_INIT) {
4088 outs() << " LAZY_INIT";
4089 f &= ~MachO::MH_LAZY_INIT;
4091 if (f & MachO::MH_TWOLEVEL) {
4092 outs() << " TWOLEVEL";
4093 f &= ~MachO::MH_TWOLEVEL;
4095 if (f & MachO::MH_FORCE_FLAT) {
4096 outs() << " FORCE_FLAT";
4097 f &= ~MachO::MH_FORCE_FLAT;
4099 if (f & MachO::MH_NOMULTIDEFS) {
4100 outs() << " NOMULTIDEFS";
4101 f &= ~MachO::MH_NOMULTIDEFS;
4103 if (f & MachO::MH_NOFIXPREBINDING) {
4104 outs() << " NOFIXPREBINDING";
4105 f &= ~MachO::MH_NOFIXPREBINDING;
4107 if (f & MachO::MH_PREBINDABLE) {
4108 outs() << " PREBINDABLE";
4109 f &= ~MachO::MH_PREBINDABLE;
4111 if (f & MachO::MH_ALLMODSBOUND) {
4112 outs() << " ALLMODSBOUND";
4113 f &= ~MachO::MH_ALLMODSBOUND;
4115 if (f & MachO::MH_SUBSECTIONS_VIA_SYMBOLS) {
4116 outs() << " SUBSECTIONS_VIA_SYMBOLS";
4117 f &= ~MachO::MH_SUBSECTIONS_VIA_SYMBOLS;
4119 if (f & MachO::MH_CANONICAL) {
4120 outs() << " CANONICAL";
4121 f &= ~MachO::MH_CANONICAL;
4123 if (f & MachO::MH_WEAK_DEFINES) {
4124 outs() << " WEAK_DEFINES";
4125 f &= ~MachO::MH_WEAK_DEFINES;
4127 if (f & MachO::MH_BINDS_TO_WEAK) {
4128 outs() << " BINDS_TO_WEAK";
4129 f &= ~MachO::MH_BINDS_TO_WEAK;
4131 if (f & MachO::MH_ALLOW_STACK_EXECUTION) {
4132 outs() << " ALLOW_STACK_EXECUTION";
4133 f &= ~MachO::MH_ALLOW_STACK_EXECUTION;
4135 if (f & MachO::MH_DEAD_STRIPPABLE_DYLIB) {
4136 outs() << " DEAD_STRIPPABLE_DYLIB";
4137 f &= ~MachO::MH_DEAD_STRIPPABLE_DYLIB;
4139 if (f & MachO::MH_PIE) {
4141 f &= ~MachO::MH_PIE;
4143 if (f & MachO::MH_NO_REEXPORTED_DYLIBS) {
4144 outs() << " NO_REEXPORTED_DYLIBS";
4145 f &= ~MachO::MH_NO_REEXPORTED_DYLIBS;
4147 if (f & MachO::MH_HAS_TLV_DESCRIPTORS) {
4148 outs() << " MH_HAS_TLV_DESCRIPTORS";
4149 f &= ~MachO::MH_HAS_TLV_DESCRIPTORS;
4151 if (f & MachO::MH_NO_HEAP_EXECUTION) {
4152 outs() << " MH_NO_HEAP_EXECUTION";
4153 f &= ~MachO::MH_NO_HEAP_EXECUTION;
4155 if (f & MachO::MH_APP_EXTENSION_SAFE) {
4156 outs() << " APP_EXTENSION_SAFE";
4157 f &= ~MachO::MH_APP_EXTENSION_SAFE;
4159 if (f != 0 || flags == 0)
4160 outs() << format(" 0x%08" PRIx32, f);
4162 outs() << format(" 0x%08" PRIx32, magic);
4163 outs() << format(" %7d", cputype);
4164 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
4165 outs() << format(" 0x%02" PRIx32,
4166 (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24);
4167 outs() << format(" %10u", filetype);
4168 outs() << format(" %5u", ncmds);
4169 outs() << format(" %10u", sizeofcmds);
4170 outs() << format(" 0x%08" PRIx32, flags);
4175 static void PrintSegmentCommand(uint32_t cmd, uint32_t cmdsize,
4176 StringRef SegName, uint64_t vmaddr,
4177 uint64_t vmsize, uint64_t fileoff,
4178 uint64_t filesize, uint32_t maxprot,
4179 uint32_t initprot, uint32_t nsects,
4180 uint32_t flags, uint32_t object_size,
4182 uint64_t expected_cmdsize;
4183 if (cmd == MachO::LC_SEGMENT) {
4184 outs() << " cmd LC_SEGMENT\n";
4185 expected_cmdsize = nsects;
4186 expected_cmdsize *= sizeof(struct MachO::section);
4187 expected_cmdsize += sizeof(struct MachO::segment_command);
4189 outs() << " cmd LC_SEGMENT_64\n";
4190 expected_cmdsize = nsects;
4191 expected_cmdsize *= sizeof(struct MachO::section_64);
4192 expected_cmdsize += sizeof(struct MachO::segment_command_64);
4194 outs() << " cmdsize " << cmdsize;
4195 if (cmdsize != expected_cmdsize)
4196 outs() << " Inconsistent size\n";
4199 outs() << " segname " << SegName << "\n";
4200 if (cmd == MachO::LC_SEGMENT_64) {
4201 outs() << " vmaddr " << format("0x%016" PRIx64, vmaddr) << "\n";
4202 outs() << " vmsize " << format("0x%016" PRIx64, vmsize) << "\n";
4204 outs() << " vmaddr " << format("0x%08" PRIx64, vmaddr) << "\n";
4205 outs() << " vmsize " << format("0x%08" PRIx64, vmsize) << "\n";
4207 outs() << " fileoff " << fileoff;
4208 if (fileoff > object_size)
4209 outs() << " (past end of file)\n";
4212 outs() << " filesize " << filesize;
4213 if (fileoff + filesize > object_size)
4214 outs() << " (past end of file)\n";
4219 ~(MachO::VM_PROT_READ | MachO::VM_PROT_WRITE |
4220 MachO::VM_PROT_EXECUTE)) != 0)
4221 outs() << " maxprot ?" << format("0x%08" PRIx32, maxprot) << "\n";
4223 if (maxprot & MachO::VM_PROT_READ)
4224 outs() << " maxprot r";
4226 outs() << " maxprot -";
4227 if (maxprot & MachO::VM_PROT_WRITE)
4231 if (maxprot & MachO::VM_PROT_EXECUTE)
4237 ~(MachO::VM_PROT_READ | MachO::VM_PROT_WRITE |
4238 MachO::VM_PROT_EXECUTE)) != 0)
4239 outs() << " initprot ?" << format("0x%08" PRIx32, initprot) << "\n";
4241 if (initprot & MachO::VM_PROT_READ)
4242 outs() << " initprot r";
4244 outs() << " initprot -";
4245 if (initprot & MachO::VM_PROT_WRITE)
4249 if (initprot & MachO::VM_PROT_EXECUTE)
4255 outs() << " maxprot " << format("0x%08" PRIx32, maxprot) << "\n";
4256 outs() << " initprot " << format("0x%08" PRIx32, initprot) << "\n";
4258 outs() << " nsects " << nsects << "\n";
4262 outs() << " (none)\n";
4264 if (flags & MachO::SG_HIGHVM) {
4265 outs() << " HIGHVM";
4266 flags &= ~MachO::SG_HIGHVM;
4268 if (flags & MachO::SG_FVMLIB) {
4269 outs() << " FVMLIB";
4270 flags &= ~MachO::SG_FVMLIB;
4272 if (flags & MachO::SG_NORELOC) {
4273 outs() << " NORELOC";
4274 flags &= ~MachO::SG_NORELOC;
4276 if (flags & MachO::SG_PROTECTED_VERSION_1) {
4277 outs() << " PROTECTED_VERSION_1";
4278 flags &= ~MachO::SG_PROTECTED_VERSION_1;
4281 outs() << format(" 0x%08" PRIx32, flags) << " (unknown flags)\n";
4286 outs() << " flags " << format("0x%" PRIx32, flags) << "\n";
4290 static void PrintSection(const char *sectname, const char *segname,
4291 uint64_t addr, uint64_t size, uint32_t offset,
4292 uint32_t align, uint32_t reloff, uint32_t nreloc,
4293 uint32_t flags, uint32_t reserved1, uint32_t reserved2,
4294 uint32_t cmd, const char *sg_segname,
4295 uint32_t filetype, uint32_t object_size,
4297 outs() << "Section\n";
4298 outs() << " sectname " << format("%.16s\n", sectname);
4299 outs() << " segname " << format("%.16s", segname);
4300 if (filetype != MachO::MH_OBJECT && strncmp(sg_segname, segname, 16) != 0)
4301 outs() << " (does not match segment)\n";
4304 if (cmd == MachO::LC_SEGMENT_64) {
4305 outs() << " addr " << format("0x%016" PRIx64, addr) << "\n";
4306 outs() << " size " << format("0x%016" PRIx64, size);
4308 outs() << " addr " << format("0x%08" PRIx64, addr) << "\n";
4309 outs() << " size " << format("0x%08" PRIx64, size);
4311 if ((flags & MachO::S_ZEROFILL) != 0 && offset + size > object_size)
4312 outs() << " (past end of file)\n";
4315 outs() << " offset " << offset;
4316 if (offset > object_size)
4317 outs() << " (past end of file)\n";
4320 uint32_t align_shifted = 1 << align;
4321 outs() << " align 2^" << align << " (" << align_shifted << ")\n";
4322 outs() << " reloff " << reloff;
4323 if (reloff > object_size)
4324 outs() << " (past end of file)\n";
4327 outs() << " nreloc " << nreloc;
4328 if (reloff + nreloc * sizeof(struct MachO::relocation_info) > object_size)
4329 outs() << " (past end of file)\n";
4332 uint32_t section_type = flags & MachO::SECTION_TYPE;
4335 if (section_type == MachO::S_REGULAR)
4336 outs() << " S_REGULAR\n";
4337 else if (section_type == MachO::S_ZEROFILL)
4338 outs() << " S_ZEROFILL\n";
4339 else if (section_type == MachO::S_CSTRING_LITERALS)
4340 outs() << " S_CSTRING_LITERALS\n";
4341 else if (section_type == MachO::S_4BYTE_LITERALS)
4342 outs() << " S_4BYTE_LITERALS\n";
4343 else if (section_type == MachO::S_8BYTE_LITERALS)
4344 outs() << " S_8BYTE_LITERALS\n";
4345 else if (section_type == MachO::S_16BYTE_LITERALS)
4346 outs() << " S_16BYTE_LITERALS\n";
4347 else if (section_type == MachO::S_LITERAL_POINTERS)
4348 outs() << " S_LITERAL_POINTERS\n";
4349 else if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS)
4350 outs() << " S_NON_LAZY_SYMBOL_POINTERS\n";
4351 else if (section_type == MachO::S_LAZY_SYMBOL_POINTERS)
4352 outs() << " S_LAZY_SYMBOL_POINTERS\n";
4353 else if (section_type == MachO::S_SYMBOL_STUBS)
4354 outs() << " S_SYMBOL_STUBS\n";
4355 else if (section_type == MachO::S_MOD_INIT_FUNC_POINTERS)
4356 outs() << " S_MOD_INIT_FUNC_POINTERS\n";
4357 else if (section_type == MachO::S_MOD_TERM_FUNC_POINTERS)
4358 outs() << " S_MOD_TERM_FUNC_POINTERS\n";
4359 else if (section_type == MachO::S_COALESCED)
4360 outs() << " S_COALESCED\n";
4361 else if (section_type == MachO::S_INTERPOSING)
4362 outs() << " S_INTERPOSING\n";
4363 else if (section_type == MachO::S_DTRACE_DOF)
4364 outs() << " S_DTRACE_DOF\n";
4365 else if (section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS)
4366 outs() << " S_LAZY_DYLIB_SYMBOL_POINTERS\n";
4367 else if (section_type == MachO::S_THREAD_LOCAL_REGULAR)
4368 outs() << " S_THREAD_LOCAL_REGULAR\n";
4369 else if (section_type == MachO::S_THREAD_LOCAL_ZEROFILL)
4370 outs() << " S_THREAD_LOCAL_ZEROFILL\n";
4371 else if (section_type == MachO::S_THREAD_LOCAL_VARIABLES)
4372 outs() << " S_THREAD_LOCAL_VARIABLES\n";
4373 else if (section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS)
4374 outs() << " S_THREAD_LOCAL_VARIABLE_POINTERS\n";
4375 else if (section_type == MachO::S_THREAD_LOCAL_INIT_FUNCTION_POINTERS)
4376 outs() << " S_THREAD_LOCAL_INIT_FUNCTION_POINTERS\n";
4378 outs() << format("0x%08" PRIx32, section_type) << "\n";
4379 outs() << "attributes";
4380 uint32_t section_attributes = flags & MachO::SECTION_ATTRIBUTES;
4381 if (section_attributes & MachO::S_ATTR_PURE_INSTRUCTIONS)
4382 outs() << " PURE_INSTRUCTIONS";
4383 if (section_attributes & MachO::S_ATTR_NO_TOC)
4384 outs() << " NO_TOC";
4385 if (section_attributes & MachO::S_ATTR_STRIP_STATIC_SYMS)
4386 outs() << " STRIP_STATIC_SYMS";
4387 if (section_attributes & MachO::S_ATTR_NO_DEAD_STRIP)
4388 outs() << " NO_DEAD_STRIP";
4389 if (section_attributes & MachO::S_ATTR_LIVE_SUPPORT)
4390 outs() << " LIVE_SUPPORT";
4391 if (section_attributes & MachO::S_ATTR_SELF_MODIFYING_CODE)
4392 outs() << " SELF_MODIFYING_CODE";
4393 if (section_attributes & MachO::S_ATTR_DEBUG)
4395 if (section_attributes & MachO::S_ATTR_SOME_INSTRUCTIONS)
4396 outs() << " SOME_INSTRUCTIONS";
4397 if (section_attributes & MachO::S_ATTR_EXT_RELOC)
4398 outs() << " EXT_RELOC";
4399 if (section_attributes & MachO::S_ATTR_LOC_RELOC)
4400 outs() << " LOC_RELOC";
4401 if (section_attributes == 0)
4402 outs() << " (none)";
4405 outs() << " flags " << format("0x%08" PRIx32, flags) << "\n";
4406 outs() << " reserved1 " << reserved1;
4407 if (section_type == MachO::S_SYMBOL_STUBS ||
4408 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
4409 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
4410 section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
4411 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS)
4412 outs() << " (index into indirect symbol table)\n";
4415 outs() << " reserved2 " << reserved2;
4416 if (section_type == MachO::S_SYMBOL_STUBS)
4417 outs() << " (size of stubs)\n";
4422 static void PrintSymtabLoadCommand(MachO::symtab_command st, bool Is64Bit,
4423 uint32_t object_size) {
4424 outs() << " cmd LC_SYMTAB\n";
4425 outs() << " cmdsize " << st.cmdsize;
4426 if (st.cmdsize != sizeof(struct MachO::symtab_command))
4427 outs() << " Incorrect size\n";
4430 outs() << " symoff " << st.symoff;
4431 if (st.symoff > object_size)
4432 outs() << " (past end of file)\n";
4435 outs() << " nsyms " << st.nsyms;
4438 big_size = st.nsyms;
4439 big_size *= sizeof(struct MachO::nlist_64);
4440 big_size += st.symoff;
4441 if (big_size > object_size)
4442 outs() << " (past end of file)\n";
4446 big_size = st.nsyms;
4447 big_size *= sizeof(struct MachO::nlist);
4448 big_size += st.symoff;
4449 if (big_size > object_size)
4450 outs() << " (past end of file)\n";
4454 outs() << " stroff " << st.stroff;
4455 if (st.stroff > object_size)
4456 outs() << " (past end of file)\n";
4459 outs() << " strsize " << st.strsize;
4460 big_size = st.stroff;
4461 big_size += st.strsize;
4462 if (big_size > object_size)
4463 outs() << " (past end of file)\n";
4468 static void PrintDysymtabLoadCommand(MachO::dysymtab_command dyst,
4469 uint32_t nsyms, uint32_t object_size,
4471 outs() << " cmd LC_DYSYMTAB\n";
4472 outs() << " cmdsize " << dyst.cmdsize;
4473 if (dyst.cmdsize != sizeof(struct MachO::dysymtab_command))
4474 outs() << " Incorrect size\n";
4477 outs() << " ilocalsym " << dyst.ilocalsym;
4478 if (dyst.ilocalsym > nsyms)
4479 outs() << " (greater than the number of symbols)\n";
4482 outs() << " nlocalsym " << dyst.nlocalsym;
4484 big_size = dyst.ilocalsym;
4485 big_size += dyst.nlocalsym;
4486 if (big_size > nsyms)
4487 outs() << " (past the end of the symbol table)\n";
4490 outs() << " iextdefsym " << dyst.iextdefsym;
4491 if (dyst.iextdefsym > nsyms)
4492 outs() << " (greater than the number of symbols)\n";
4495 outs() << " nextdefsym " << dyst.nextdefsym;
4496 big_size = dyst.iextdefsym;
4497 big_size += dyst.nextdefsym;
4498 if (big_size > nsyms)
4499 outs() << " (past the end of the symbol table)\n";
4502 outs() << " iundefsym " << dyst.iundefsym;
4503 if (dyst.iundefsym > nsyms)
4504 outs() << " (greater than the number of symbols)\n";
4507 outs() << " nundefsym " << dyst.nundefsym;
4508 big_size = dyst.iundefsym;
4509 big_size += dyst.nundefsym;
4510 if (big_size > nsyms)
4511 outs() << " (past the end of the symbol table)\n";
4514 outs() << " tocoff " << dyst.tocoff;
4515 if (dyst.tocoff > object_size)
4516 outs() << " (past end of file)\n";
4519 outs() << " ntoc " << dyst.ntoc;
4520 big_size = dyst.ntoc;
4521 big_size *= sizeof(struct MachO::dylib_table_of_contents);
4522 big_size += dyst.tocoff;
4523 if (big_size > object_size)
4524 outs() << " (past end of file)\n";
4527 outs() << " modtaboff " << dyst.modtaboff;
4528 if (dyst.modtaboff > object_size)
4529 outs() << " (past end of file)\n";
4532 outs() << " nmodtab " << dyst.nmodtab;
4535 modtabend = dyst.nmodtab;
4536 modtabend *= sizeof(struct MachO::dylib_module_64);
4537 modtabend += dyst.modtaboff;
4539 modtabend = dyst.nmodtab;
4540 modtabend *= sizeof(struct MachO::dylib_module);
4541 modtabend += dyst.modtaboff;
4543 if (modtabend > object_size)
4544 outs() << " (past end of file)\n";
4547 outs() << " extrefsymoff " << dyst.extrefsymoff;
4548 if (dyst.extrefsymoff > object_size)
4549 outs() << " (past end of file)\n";
4552 outs() << " nextrefsyms " << dyst.nextrefsyms;
4553 big_size = dyst.nextrefsyms;
4554 big_size *= sizeof(struct MachO::dylib_reference);
4555 big_size += dyst.extrefsymoff;
4556 if (big_size > object_size)
4557 outs() << " (past end of file)\n";
4560 outs() << " indirectsymoff " << dyst.indirectsymoff;
4561 if (dyst.indirectsymoff > object_size)
4562 outs() << " (past end of file)\n";
4565 outs() << " nindirectsyms " << dyst.nindirectsyms;
4566 big_size = dyst.nindirectsyms;
4567 big_size *= sizeof(uint32_t);
4568 big_size += dyst.indirectsymoff;
4569 if (big_size > object_size)
4570 outs() << " (past end of file)\n";
4573 outs() << " extreloff " << dyst.extreloff;
4574 if (dyst.extreloff > object_size)
4575 outs() << " (past end of file)\n";
4578 outs() << " nextrel " << dyst.nextrel;
4579 big_size = dyst.nextrel;
4580 big_size *= sizeof(struct MachO::relocation_info);
4581 big_size += dyst.extreloff;
4582 if (big_size > object_size)
4583 outs() << " (past end of file)\n";
4586 outs() << " locreloff " << dyst.locreloff;
4587 if (dyst.locreloff > object_size)
4588 outs() << " (past end of file)\n";
4591 outs() << " nlocrel " << dyst.nlocrel;
4592 big_size = dyst.nlocrel;
4593 big_size *= sizeof(struct MachO::relocation_info);
4594 big_size += dyst.locreloff;
4595 if (big_size > object_size)
4596 outs() << " (past end of file)\n";
4601 static void PrintDyldInfoLoadCommand(MachO::dyld_info_command dc,
4602 uint32_t object_size) {
4603 if (dc.cmd == MachO::LC_DYLD_INFO)
4604 outs() << " cmd LC_DYLD_INFO\n";
4606 outs() << " cmd LC_DYLD_INFO_ONLY\n";
4607 outs() << " cmdsize " << dc.cmdsize;
4608 if (dc.cmdsize != sizeof(struct MachO::dyld_info_command))
4609 outs() << " Incorrect size\n";
4612 outs() << " rebase_off " << dc.rebase_off;
4613 if (dc.rebase_off > object_size)
4614 outs() << " (past end of file)\n";
4617 outs() << " rebase_size " << dc.rebase_size;
4619 big_size = dc.rebase_off;
4620 big_size += dc.rebase_size;
4621 if (big_size > object_size)
4622 outs() << " (past end of file)\n";
4625 outs() << " bind_off " << dc.bind_off;
4626 if (dc.bind_off > object_size)
4627 outs() << " (past end of file)\n";
4630 outs() << " bind_size " << dc.bind_size;
4631 big_size = dc.bind_off;
4632 big_size += dc.bind_size;
4633 if (big_size > object_size)
4634 outs() << " (past end of file)\n";
4637 outs() << " weak_bind_off " << dc.weak_bind_off;
4638 if (dc.weak_bind_off > object_size)
4639 outs() << " (past end of file)\n";
4642 outs() << " weak_bind_size " << dc.weak_bind_size;
4643 big_size = dc.weak_bind_off;
4644 big_size += dc.weak_bind_size;
4645 if (big_size > object_size)
4646 outs() << " (past end of file)\n";
4649 outs() << " lazy_bind_off " << dc.lazy_bind_off;
4650 if (dc.lazy_bind_off > object_size)
4651 outs() << " (past end of file)\n";
4654 outs() << " lazy_bind_size " << dc.lazy_bind_size;
4655 big_size = dc.lazy_bind_off;
4656 big_size += dc.lazy_bind_size;
4657 if (big_size > object_size)
4658 outs() << " (past end of file)\n";
4661 outs() << " export_off " << dc.export_off;
4662 if (dc.export_off > object_size)
4663 outs() << " (past end of file)\n";
4666 outs() << " export_size " << dc.export_size;
4667 big_size = dc.export_off;
4668 big_size += dc.export_size;
4669 if (big_size > object_size)
4670 outs() << " (past end of file)\n";
4675 static void PrintDyldLoadCommand(MachO::dylinker_command dyld,
4677 if (dyld.cmd == MachO::LC_ID_DYLINKER)
4678 outs() << " cmd LC_ID_DYLINKER\n";
4679 else if (dyld.cmd == MachO::LC_LOAD_DYLINKER)
4680 outs() << " cmd LC_LOAD_DYLINKER\n";
4681 else if (dyld.cmd == MachO::LC_DYLD_ENVIRONMENT)
4682 outs() << " cmd LC_DYLD_ENVIRONMENT\n";
4684 outs() << " cmd ?(" << dyld.cmd << ")\n";
4685 outs() << " cmdsize " << dyld.cmdsize;
4686 if (dyld.cmdsize < sizeof(struct MachO::dylinker_command))
4687 outs() << " Incorrect size\n";
4690 if (dyld.name >= dyld.cmdsize)
4691 outs() << " name ?(bad offset " << dyld.name << ")\n";
4693 const char *P = (const char *)(Ptr) + dyld.name;
4694 outs() << " name " << P << " (offset " << dyld.name << ")\n";
4698 static void PrintUuidLoadCommand(MachO::uuid_command uuid) {
4699 outs() << " cmd LC_UUID\n";
4700 outs() << " cmdsize " << uuid.cmdsize;
4701 if (uuid.cmdsize != sizeof(struct MachO::uuid_command))
4702 outs() << " Incorrect size\n";
4706 outs() << format("%02" PRIX32, uuid.uuid[0]);
4707 outs() << format("%02" PRIX32, uuid.uuid[1]);
4708 outs() << format("%02" PRIX32, uuid.uuid[2]);
4709 outs() << format("%02" PRIX32, uuid.uuid[3]);
4711 outs() << format("%02" PRIX32, uuid.uuid[4]);
4712 outs() << format("%02" PRIX32, uuid.uuid[5]);
4714 outs() << format("%02" PRIX32, uuid.uuid[6]);
4715 outs() << format("%02" PRIX32, uuid.uuid[7]);
4717 outs() << format("%02" PRIX32, uuid.uuid[8]);
4718 outs() << format("%02" PRIX32, uuid.uuid[9]);
4720 outs() << format("%02" PRIX32, uuid.uuid[10]);
4721 outs() << format("%02" PRIX32, uuid.uuid[11]);
4722 outs() << format("%02" PRIX32, uuid.uuid[12]);
4723 outs() << format("%02" PRIX32, uuid.uuid[13]);
4724 outs() << format("%02" PRIX32, uuid.uuid[14]);
4725 outs() << format("%02" PRIX32, uuid.uuid[15]);
4729 static void PrintRpathLoadCommand(MachO::rpath_command rpath, const char *Ptr) {
4730 outs() << " cmd LC_RPATH\n";
4731 outs() << " cmdsize " << rpath.cmdsize;
4732 if (rpath.cmdsize < sizeof(struct MachO::rpath_command))
4733 outs() << " Incorrect size\n";
4736 if (rpath.path >= rpath.cmdsize)
4737 outs() << " path ?(bad offset " << rpath.path << ")\n";
4739 const char *P = (const char *)(Ptr) + rpath.path;
4740 outs() << " path " << P << " (offset " << rpath.path << ")\n";
4744 static void PrintVersionMinLoadCommand(MachO::version_min_command vd) {
4745 if (vd.cmd == MachO::LC_VERSION_MIN_MACOSX)
4746 outs() << " cmd LC_VERSION_MIN_MACOSX\n";
4747 else if (vd.cmd == MachO::LC_VERSION_MIN_IPHONEOS)
4748 outs() << " cmd LC_VERSION_MIN_IPHONEOS\n";
4750 outs() << " cmd " << vd.cmd << " (?)\n";
4751 outs() << " cmdsize " << vd.cmdsize;
4752 if (vd.cmdsize != sizeof(struct MachO::version_min_command))
4753 outs() << " Incorrect size\n";
4756 outs() << " version " << ((vd.version >> 16) & 0xffff) << "."
4757 << ((vd.version >> 8) & 0xff);
4758 if ((vd.version & 0xff) != 0)
4759 outs() << "." << (vd.version & 0xff);
4762 outs() << " sdk n/a";
4764 outs() << " sdk " << ((vd.sdk >> 16) & 0xffff) << "."
4765 << ((vd.sdk >> 8) & 0xff);
4767 if ((vd.sdk & 0xff) != 0)
4768 outs() << "." << (vd.sdk & 0xff);
4772 static void PrintSourceVersionCommand(MachO::source_version_command sd) {
4773 outs() << " cmd LC_SOURCE_VERSION\n";
4774 outs() << " cmdsize " << sd.cmdsize;
4775 if (sd.cmdsize != sizeof(struct MachO::source_version_command))
4776 outs() << " Incorrect size\n";
4779 uint64_t a = (sd.version >> 40) & 0xffffff;
4780 uint64_t b = (sd.version >> 30) & 0x3ff;
4781 uint64_t c = (sd.version >> 20) & 0x3ff;
4782 uint64_t d = (sd.version >> 10) & 0x3ff;
4783 uint64_t e = sd.version & 0x3ff;
4784 outs() << " version " << a << "." << b;
4786 outs() << "." << c << "." << d << "." << e;
4788 outs() << "." << c << "." << d;
4794 static void PrintEntryPointCommand(MachO::entry_point_command ep) {
4795 outs() << " cmd LC_MAIN\n";
4796 outs() << " cmdsize " << ep.cmdsize;
4797 if (ep.cmdsize != sizeof(struct MachO::entry_point_command))
4798 outs() << " Incorrect size\n";
4801 outs() << " entryoff " << ep.entryoff << "\n";
4802 outs() << " stacksize " << ep.stacksize << "\n";
4805 static void PrintEncryptionInfoCommand(MachO::encryption_info_command ec,
4806 uint32_t object_size) {
4807 outs() << " cmd LC_ENCRYPTION_INFO\n";
4808 outs() << " cmdsize " << ec.cmdsize;
4809 if (ec.cmdsize != sizeof(struct MachO::encryption_info_command))
4810 outs() << " Incorrect size\n";
4813 outs() << " cryptoff " << ec.cryptoff;
4814 if (ec.cryptoff > object_size)
4815 outs() << " (past end of file)\n";
4818 outs() << " cryptsize " << ec.cryptsize;
4819 if (ec.cryptsize > object_size)
4820 outs() << " (past end of file)\n";
4823 outs() << " cryptid " << ec.cryptid << "\n";
4826 static void PrintEncryptionInfoCommand64(MachO::encryption_info_command_64 ec,
4827 uint32_t object_size) {
4828 outs() << " cmd LC_ENCRYPTION_INFO_64\n";
4829 outs() << " cmdsize " << ec.cmdsize;
4830 if (ec.cmdsize != sizeof(struct MachO::encryption_info_command_64))
4831 outs() << " Incorrect size\n";
4834 outs() << " cryptoff " << ec.cryptoff;
4835 if (ec.cryptoff > object_size)
4836 outs() << " (past end of file)\n";
4839 outs() << " cryptsize " << ec.cryptsize;
4840 if (ec.cryptsize > object_size)
4841 outs() << " (past end of file)\n";
4844 outs() << " cryptid " << ec.cryptid << "\n";
4845 outs() << " pad " << ec.pad << "\n";
4848 static void PrintLinkerOptionCommand(MachO::linker_option_command lo,
4850 outs() << " cmd LC_LINKER_OPTION\n";
4851 outs() << " cmdsize " << lo.cmdsize;
4852 if (lo.cmdsize < sizeof(struct MachO::linker_option_command))
4853 outs() << " Incorrect size\n";
4856 outs() << " count " << lo.count << "\n";
4857 const char *string = Ptr + sizeof(struct MachO::linker_option_command);
4858 uint32_t left = lo.cmdsize - sizeof(struct MachO::linker_option_command);
4861 while (*string == '\0' && left > 0) {
4867 outs() << " string #" << i << " " << format("%.*s\n", left, string);
4868 uint32_t NullPos = StringRef(string, left).find('\0');
4869 uint32_t len = std::min(NullPos, left) + 1;
4875 outs() << " count " << lo.count << " does not match number of strings "
4879 static void PrintSubFrameworkCommand(MachO::sub_framework_command sub,
4881 outs() << " cmd LC_SUB_FRAMEWORK\n";
4882 outs() << " cmdsize " << sub.cmdsize;
4883 if (sub.cmdsize < sizeof(struct MachO::sub_framework_command))
4884 outs() << " Incorrect size\n";
4887 if (sub.umbrella < sub.cmdsize) {
4888 const char *P = Ptr + sub.umbrella;
4889 outs() << " umbrella " << P << " (offset " << sub.umbrella << ")\n";
4891 outs() << " umbrella ?(bad offset " << sub.umbrella << ")\n";
4895 static void PrintSubUmbrellaCommand(MachO::sub_umbrella_command sub,
4897 outs() << " cmd LC_SUB_UMBRELLA\n";
4898 outs() << " cmdsize " << sub.cmdsize;
4899 if (sub.cmdsize < sizeof(struct MachO::sub_umbrella_command))
4900 outs() << " Incorrect size\n";
4903 if (sub.sub_umbrella < sub.cmdsize) {
4904 const char *P = Ptr + sub.sub_umbrella;
4905 outs() << " sub_umbrella " << P << " (offset " << sub.sub_umbrella << ")\n";
4907 outs() << " sub_umbrella ?(bad offset " << sub.sub_umbrella << ")\n";
4911 static void PrintSubLibraryCommand(MachO::sub_library_command sub,
4913 outs() << " cmd LC_SUB_LIBRARY\n";
4914 outs() << " cmdsize " << sub.cmdsize;
4915 if (sub.cmdsize < sizeof(struct MachO::sub_library_command))
4916 outs() << " Incorrect size\n";
4919 if (sub.sub_library < sub.cmdsize) {
4920 const char *P = Ptr + sub.sub_library;
4921 outs() << " sub_library " << P << " (offset " << sub.sub_library << ")\n";
4923 outs() << " sub_library ?(bad offset " << sub.sub_library << ")\n";
4927 static void PrintSubClientCommand(MachO::sub_client_command sub,
4929 outs() << " cmd LC_SUB_CLIENT\n";
4930 outs() << " cmdsize " << sub.cmdsize;
4931 if (sub.cmdsize < sizeof(struct MachO::sub_client_command))
4932 outs() << " Incorrect size\n";
4935 if (sub.client < sub.cmdsize) {
4936 const char *P = Ptr + sub.client;
4937 outs() << " client " << P << " (offset " << sub.client << ")\n";
4939 outs() << " client ?(bad offset " << sub.client << ")\n";
4943 static void PrintRoutinesCommand(MachO::routines_command r) {
4944 outs() << " cmd LC_ROUTINES\n";
4945 outs() << " cmdsize " << r.cmdsize;
4946 if (r.cmdsize != sizeof(struct MachO::routines_command))
4947 outs() << " Incorrect size\n";
4950 outs() << " init_address " << format("0x%08" PRIx32, r.init_address) << "\n";
4951 outs() << " init_module " << r.init_module << "\n";
4952 outs() << " reserved1 " << r.reserved1 << "\n";
4953 outs() << " reserved2 " << r.reserved2 << "\n";
4954 outs() << " reserved3 " << r.reserved3 << "\n";
4955 outs() << " reserved4 " << r.reserved4 << "\n";
4956 outs() << " reserved5 " << r.reserved5 << "\n";
4957 outs() << " reserved6 " << r.reserved6 << "\n";
4960 static void PrintRoutinesCommand64(MachO::routines_command_64 r) {
4961 outs() << " cmd LC_ROUTINES_64\n";
4962 outs() << " cmdsize " << r.cmdsize;
4963 if (r.cmdsize != sizeof(struct MachO::routines_command_64))
4964 outs() << " Incorrect size\n";
4967 outs() << " init_address " << format("0x%016" PRIx64, r.init_address) << "\n";
4968 outs() << " init_module " << r.init_module << "\n";
4969 outs() << " reserved1 " << r.reserved1 << "\n";
4970 outs() << " reserved2 " << r.reserved2 << "\n";
4971 outs() << " reserved3 " << r.reserved3 << "\n";
4972 outs() << " reserved4 " << r.reserved4 << "\n";
4973 outs() << " reserved5 " << r.reserved5 << "\n";
4974 outs() << " reserved6 " << r.reserved6 << "\n";
4977 static void Print_x86_thread_state64_t(MachO::x86_thread_state64_t &cpu64) {
4978 outs() << " rax " << format("0x%016" PRIx64, cpu64.rax);
4979 outs() << " rbx " << format("0x%016" PRIx64, cpu64.rbx);
4980 outs() << " rcx " << format("0x%016" PRIx64, cpu64.rcx) << "\n";
4981 outs() << " rdx " << format("0x%016" PRIx64, cpu64.rdx);
4982 outs() << " rdi " << format("0x%016" PRIx64, cpu64.rdi);
4983 outs() << " rsi " << format("0x%016" PRIx64, cpu64.rsi) << "\n";
4984 outs() << " rbp " << format("0x%016" PRIx64, cpu64.rbp);
4985 outs() << " rsp " << format("0x%016" PRIx64, cpu64.rsp);
4986 outs() << " r8 " << format("0x%016" PRIx64, cpu64.r8) << "\n";
4987 outs() << " r9 " << format("0x%016" PRIx64, cpu64.r9);
4988 outs() << " r10 " << format("0x%016" PRIx64, cpu64.r10);
4989 outs() << " r11 " << format("0x%016" PRIx64, cpu64.r11) << "\n";
4990 outs() << " r12 " << format("0x%016" PRIx64, cpu64.r12);
4991 outs() << " r13 " << format("0x%016" PRIx64, cpu64.r13);
4992 outs() << " r14 " << format("0x%016" PRIx64, cpu64.r14) << "\n";
4993 outs() << " r15 " << format("0x%016" PRIx64, cpu64.r15);
4994 outs() << " rip " << format("0x%016" PRIx64, cpu64.rip) << "\n";
4995 outs() << "rflags " << format("0x%016" PRIx64, cpu64.rflags);
4996 outs() << " cs " << format("0x%016" PRIx64, cpu64.cs);
4997 outs() << " fs " << format("0x%016" PRIx64, cpu64.fs) << "\n";
4998 outs() << " gs " << format("0x%016" PRIx64, cpu64.gs) << "\n";
5001 static void Print_mmst_reg(MachO::mmst_reg_t &r) {
5003 outs() << "\t mmst_reg ";
5004 for (f = 0; f < 10; f++)
5005 outs() << format("%02" PRIx32, (r.mmst_reg[f] & 0xff)) << " ";
5007 outs() << "\t mmst_rsrv ";
5008 for (f = 0; f < 6; f++)
5009 outs() << format("%02" PRIx32, (r.mmst_rsrv[f] & 0xff)) << " ";
5013 static void Print_xmm_reg(MachO::xmm_reg_t &r) {
5015 outs() << "\t xmm_reg ";
5016 for (f = 0; f < 16; f++)
5017 outs() << format("%02" PRIx32, (r.xmm_reg[f] & 0xff)) << " ";
5021 static void Print_x86_float_state_t(MachO::x86_float_state64_t &fpu) {
5022 outs() << "\t fpu_reserved[0] " << fpu.fpu_reserved[0];
5023 outs() << " fpu_reserved[1] " << fpu.fpu_reserved[1] << "\n";
5024 outs() << "\t control: invalid " << fpu.fpu_fcw.invalid;
5025 outs() << " denorm " << fpu.fpu_fcw.denorm;
5026 outs() << " zdiv " << fpu.fpu_fcw.zdiv;
5027 outs() << " ovrfl " << fpu.fpu_fcw.ovrfl;
5028 outs() << " undfl " << fpu.fpu_fcw.undfl;
5029 outs() << " precis " << fpu.fpu_fcw.precis << "\n";
5030 outs() << "\t\t pc ";
5031 if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_24B)
5032 outs() << "FP_PREC_24B ";
5033 else if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_53B)
5034 outs() << "FP_PREC_53B ";
5035 else if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_64B)
5036 outs() << "FP_PREC_64B ";
5038 outs() << fpu.fpu_fcw.pc << " ";
5040 if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_NEAR)
5041 outs() << "FP_RND_NEAR ";
5042 else if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_DOWN)
5043 outs() << "FP_RND_DOWN ";
5044 else if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_UP)
5045 outs() << "FP_RND_UP ";
5046 else if (fpu.fpu_fcw.rc == MachO::x86_FP_CHOP)
5047 outs() << "FP_CHOP ";
5049 outs() << "\t status: invalid " << fpu.fpu_fsw.invalid;
5050 outs() << " denorm " << fpu.fpu_fsw.denorm;
5051 outs() << " zdiv " << fpu.fpu_fsw.zdiv;
5052 outs() << " ovrfl " << fpu.fpu_fsw.ovrfl;
5053 outs() << " undfl " << fpu.fpu_fsw.undfl;
5054 outs() << " precis " << fpu.fpu_fsw.precis;
5055 outs() << " stkflt " << fpu.fpu_fsw.stkflt << "\n";
5056 outs() << "\t errsumm " << fpu.fpu_fsw.errsumm;
5057 outs() << " c0 " << fpu.fpu_fsw.c0;
5058 outs() << " c1 " << fpu.fpu_fsw.c1;
5059 outs() << " c2 " << fpu.fpu_fsw.c2;
5060 outs() << " tos " << fpu.fpu_fsw.tos;
5061 outs() << " c3 " << fpu.fpu_fsw.c3;
5062 outs() << " busy " << fpu.fpu_fsw.busy << "\n";
5063 outs() << "\t fpu_ftw " << format("0x%02" PRIx32, fpu.fpu_ftw);
5064 outs() << " fpu_rsrv1 " << format("0x%02" PRIx32, fpu.fpu_rsrv1);
5065 outs() << " fpu_fop " << format("0x%04" PRIx32, fpu.fpu_fop);
5066 outs() << " fpu_ip " << format("0x%08" PRIx32, fpu.fpu_ip) << "\n";
5067 outs() << "\t fpu_cs " << format("0x%04" PRIx32, fpu.fpu_cs);
5068 outs() << " fpu_rsrv2 " << format("0x%04" PRIx32, fpu.fpu_rsrv2);
5069 outs() << " fpu_dp " << format("0x%08" PRIx32, fpu.fpu_dp);
5070 outs() << " fpu_ds " << format("0x%04" PRIx32, fpu.fpu_ds) << "\n";
5071 outs() << "\t fpu_rsrv3 " << format("0x%04" PRIx32, fpu.fpu_rsrv3);
5072 outs() << " fpu_mxcsr " << format("0x%08" PRIx32, fpu.fpu_mxcsr);
5073 outs() << " fpu_mxcsrmask " << format("0x%08" PRIx32, fpu.fpu_mxcsrmask);
5075 outs() << "\t fpu_stmm0:\n";
5076 Print_mmst_reg(fpu.fpu_stmm0);
5077 outs() << "\t fpu_stmm1:\n";
5078 Print_mmst_reg(fpu.fpu_stmm1);
5079 outs() << "\t fpu_stmm2:\n";
5080 Print_mmst_reg(fpu.fpu_stmm2);
5081 outs() << "\t fpu_stmm3:\n";
5082 Print_mmst_reg(fpu.fpu_stmm3);
5083 outs() << "\t fpu_stmm4:\n";
5084 Print_mmst_reg(fpu.fpu_stmm4);
5085 outs() << "\t fpu_stmm5:\n";
5086 Print_mmst_reg(fpu.fpu_stmm5);
5087 outs() << "\t fpu_stmm6:\n";
5088 Print_mmst_reg(fpu.fpu_stmm6);
5089 outs() << "\t fpu_stmm7:\n";
5090 Print_mmst_reg(fpu.fpu_stmm7);
5091 outs() << "\t fpu_xmm0:\n";
5092 Print_xmm_reg(fpu.fpu_xmm0);
5093 outs() << "\t fpu_xmm1:\n";
5094 Print_xmm_reg(fpu.fpu_xmm1);
5095 outs() << "\t fpu_xmm2:\n";
5096 Print_xmm_reg(fpu.fpu_xmm2);
5097 outs() << "\t fpu_xmm3:\n";
5098 Print_xmm_reg(fpu.fpu_xmm3);
5099 outs() << "\t fpu_xmm4:\n";
5100 Print_xmm_reg(fpu.fpu_xmm4);
5101 outs() << "\t fpu_xmm5:\n";
5102 Print_xmm_reg(fpu.fpu_xmm5);
5103 outs() << "\t fpu_xmm6:\n";
5104 Print_xmm_reg(fpu.fpu_xmm6);
5105 outs() << "\t fpu_xmm7:\n";
5106 Print_xmm_reg(fpu.fpu_xmm7);
5107 outs() << "\t fpu_xmm8:\n";
5108 Print_xmm_reg(fpu.fpu_xmm8);
5109 outs() << "\t fpu_xmm9:\n";
5110 Print_xmm_reg(fpu.fpu_xmm9);
5111 outs() << "\t fpu_xmm10:\n";
5112 Print_xmm_reg(fpu.fpu_xmm10);
5113 outs() << "\t fpu_xmm11:\n";
5114 Print_xmm_reg(fpu.fpu_xmm11);
5115 outs() << "\t fpu_xmm12:\n";
5116 Print_xmm_reg(fpu.fpu_xmm12);
5117 outs() << "\t fpu_xmm13:\n";
5118 Print_xmm_reg(fpu.fpu_xmm13);
5119 outs() << "\t fpu_xmm14:\n";
5120 Print_xmm_reg(fpu.fpu_xmm14);
5121 outs() << "\t fpu_xmm15:\n";
5122 Print_xmm_reg(fpu.fpu_xmm15);
5123 outs() << "\t fpu_rsrv4:\n";
5124 for (uint32_t f = 0; f < 6; f++) {
5126 for (uint32_t g = 0; g < 16; g++)
5127 outs() << format("%02" PRIx32, fpu.fpu_rsrv4[f * g]) << " ";
5130 outs() << "\t fpu_reserved1 " << format("0x%08" PRIx32, fpu.fpu_reserved1);
5134 static void Print_x86_exception_state_t(MachO::x86_exception_state64_t &exc64) {
5135 outs() << "\t trapno " << format("0x%08" PRIx32, exc64.trapno);
5136 outs() << " err " << format("0x%08" PRIx32, exc64.err);
5137 outs() << " faultvaddr " << format("0x%016" PRIx64, exc64.faultvaddr) << "\n";
5140 static void PrintThreadCommand(MachO::thread_command t, const char *Ptr,
5141 bool isLittleEndian, uint32_t cputype) {
5142 if (t.cmd == MachO::LC_THREAD)
5143 outs() << " cmd LC_THREAD\n";
5144 else if (t.cmd == MachO::LC_UNIXTHREAD)
5145 outs() << " cmd LC_UNIXTHREAD\n";
5147 outs() << " cmd " << t.cmd << " (unknown)\n";
5148 outs() << " cmdsize " << t.cmdsize;
5149 if (t.cmdsize < sizeof(struct MachO::thread_command) + 2 * sizeof(uint32_t))
5150 outs() << " Incorrect size\n";
5154 const char *begin = Ptr + sizeof(struct MachO::thread_command);
5155 const char *end = Ptr + t.cmdsize;
5156 uint32_t flavor, count, left;
5157 if (cputype == MachO::CPU_TYPE_X86_64) {
5158 while (begin < end) {
5159 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
5160 memcpy((char *)&flavor, begin, sizeof(uint32_t));
5161 begin += sizeof(uint32_t);
5166 if (isLittleEndian != sys::IsLittleEndianHost)
5167 sys::swapByteOrder(flavor);
5168 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
5169 memcpy((char *)&count, begin, sizeof(uint32_t));
5170 begin += sizeof(uint32_t);
5175 if (isLittleEndian != sys::IsLittleEndianHost)
5176 sys::swapByteOrder(count);
5177 if (flavor == MachO::x86_THREAD_STATE64) {
5178 outs() << " flavor x86_THREAD_STATE64\n";
5179 if (count == MachO::x86_THREAD_STATE64_COUNT)
5180 outs() << " count x86_THREAD_STATE64_COUNT\n";
5182 outs() << " count " << count
5183 << " (not x86_THREAD_STATE64_COUNT)\n";
5184 MachO::x86_thread_state64_t cpu64;
5186 if (left >= sizeof(MachO::x86_thread_state64_t)) {
5187 memcpy(&cpu64, begin, sizeof(MachO::x86_thread_state64_t));
5188 begin += sizeof(MachO::x86_thread_state64_t);
5190 memset(&cpu64, '\0', sizeof(MachO::x86_thread_state64_t));
5191 memcpy(&cpu64, begin, left);
5194 if (isLittleEndian != sys::IsLittleEndianHost)
5196 Print_x86_thread_state64_t(cpu64);
5197 } else if (flavor == MachO::x86_THREAD_STATE) {
5198 outs() << " flavor x86_THREAD_STATE\n";
5199 if (count == MachO::x86_THREAD_STATE_COUNT)
5200 outs() << " count x86_THREAD_STATE_COUNT\n";
5202 outs() << " count " << count
5203 << " (not x86_THREAD_STATE_COUNT)\n";
5204 struct MachO::x86_thread_state_t ts;
5206 if (left >= sizeof(MachO::x86_thread_state_t)) {
5207 memcpy(&ts, begin, sizeof(MachO::x86_thread_state_t));
5208 begin += sizeof(MachO::x86_thread_state_t);
5210 memset(&ts, '\0', sizeof(MachO::x86_thread_state_t));
5211 memcpy(&ts, begin, left);
5214 if (isLittleEndian != sys::IsLittleEndianHost)
5216 if (ts.tsh.flavor == MachO::x86_THREAD_STATE64) {
5217 outs() << "\t tsh.flavor x86_THREAD_STATE64 ";
5218 if (ts.tsh.count == MachO::x86_THREAD_STATE64_COUNT)
5219 outs() << "tsh.count x86_THREAD_STATE64_COUNT\n";
5221 outs() << "tsh.count " << ts.tsh.count
5222 << " (not x86_THREAD_STATE64_COUNT\n";
5223 Print_x86_thread_state64_t(ts.uts.ts64);
5225 outs() << "\t tsh.flavor " << ts.tsh.flavor << " tsh.count "
5226 << ts.tsh.count << "\n";
5228 } else if (flavor == MachO::x86_FLOAT_STATE) {
5229 outs() << " flavor x86_FLOAT_STATE\n";
5230 if (count == MachO::x86_FLOAT_STATE_COUNT)
5231 outs() << " count x86_FLOAT_STATE_COUNT\n";
5233 outs() << " count " << count << " (not x86_FLOAT_STATE_COUNT)\n";
5234 struct MachO::x86_float_state_t fs;
5236 if (left >= sizeof(MachO::x86_float_state_t)) {
5237 memcpy(&fs, begin, sizeof(MachO::x86_float_state_t));
5238 begin += sizeof(MachO::x86_float_state_t);
5240 memset(&fs, '\0', sizeof(MachO::x86_float_state_t));
5241 memcpy(&fs, begin, left);
5244 if (isLittleEndian != sys::IsLittleEndianHost)
5246 if (fs.fsh.flavor == MachO::x86_FLOAT_STATE64) {
5247 outs() << "\t fsh.flavor x86_FLOAT_STATE64 ";
5248 if (fs.fsh.count == MachO::x86_FLOAT_STATE64_COUNT)
5249 outs() << "fsh.count x86_FLOAT_STATE64_COUNT\n";
5251 outs() << "fsh.count " << fs.fsh.count
5252 << " (not x86_FLOAT_STATE64_COUNT\n";
5253 Print_x86_float_state_t(fs.ufs.fs64);
5255 outs() << "\t fsh.flavor " << fs.fsh.flavor << " fsh.count "
5256 << fs.fsh.count << "\n";
5258 } else if (flavor == MachO::x86_EXCEPTION_STATE) {
5259 outs() << " flavor x86_EXCEPTION_STATE\n";
5260 if (count == MachO::x86_EXCEPTION_STATE_COUNT)
5261 outs() << " count x86_EXCEPTION_STATE_COUNT\n";
5263 outs() << " count " << count
5264 << " (not x86_EXCEPTION_STATE_COUNT)\n";
5265 struct MachO::x86_exception_state_t es;
5267 if (left >= sizeof(MachO::x86_exception_state_t)) {
5268 memcpy(&es, begin, sizeof(MachO::x86_exception_state_t));
5269 begin += sizeof(MachO::x86_exception_state_t);
5271 memset(&es, '\0', sizeof(MachO::x86_exception_state_t));
5272 memcpy(&es, begin, left);
5275 if (isLittleEndian != sys::IsLittleEndianHost)
5277 if (es.esh.flavor == MachO::x86_EXCEPTION_STATE64) {
5278 outs() << "\t esh.flavor x86_EXCEPTION_STATE64\n";
5279 if (es.esh.count == MachO::x86_EXCEPTION_STATE64_COUNT)
5280 outs() << "\t esh.count x86_EXCEPTION_STATE64_COUNT\n";
5282 outs() << "\t esh.count " << es.esh.count
5283 << " (not x86_EXCEPTION_STATE64_COUNT\n";
5284 Print_x86_exception_state_t(es.ues.es64);
5286 outs() << "\t esh.flavor " << es.esh.flavor << " esh.count "
5287 << es.esh.count << "\n";
5290 outs() << " flavor " << flavor << " (unknown)\n";
5291 outs() << " count " << count << "\n";
5292 outs() << " state (unknown)\n";
5293 begin += count * sizeof(uint32_t);
5297 while (begin < end) {
5298 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
5299 memcpy((char *)&flavor, begin, sizeof(uint32_t));
5300 begin += sizeof(uint32_t);
5305 if (isLittleEndian != sys::IsLittleEndianHost)
5306 sys::swapByteOrder(flavor);
5307 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
5308 memcpy((char *)&count, begin, sizeof(uint32_t));
5309 begin += sizeof(uint32_t);
5314 if (isLittleEndian != sys::IsLittleEndianHost)
5315 sys::swapByteOrder(count);
5316 outs() << " flavor " << flavor << "\n";
5317 outs() << " count " << count << "\n";
5318 outs() << " state (Unknown cputype/cpusubtype)\n";
5319 begin += count * sizeof(uint32_t);
5324 static void PrintDylibCommand(MachO::dylib_command dl, const char *Ptr) {
5325 if (dl.cmd == MachO::LC_ID_DYLIB)
5326 outs() << " cmd LC_ID_DYLIB\n";
5327 else if (dl.cmd == MachO::LC_LOAD_DYLIB)
5328 outs() << " cmd LC_LOAD_DYLIB\n";
5329 else if (dl.cmd == MachO::LC_LOAD_WEAK_DYLIB)
5330 outs() << " cmd LC_LOAD_WEAK_DYLIB\n";
5331 else if (dl.cmd == MachO::LC_REEXPORT_DYLIB)
5332 outs() << " cmd LC_REEXPORT_DYLIB\n";
5333 else if (dl.cmd == MachO::LC_LAZY_LOAD_DYLIB)
5334 outs() << " cmd LC_LAZY_LOAD_DYLIB\n";
5335 else if (dl.cmd == MachO::LC_LOAD_UPWARD_DYLIB)
5336 outs() << " cmd LC_LOAD_UPWARD_DYLIB\n";
5338 outs() << " cmd " << dl.cmd << " (unknown)\n";
5339 outs() << " cmdsize " << dl.cmdsize;
5340 if (dl.cmdsize < sizeof(struct MachO::dylib_command))
5341 outs() << " Incorrect size\n";
5344 if (dl.dylib.name < dl.cmdsize) {
5345 const char *P = (const char *)(Ptr) + dl.dylib.name;
5346 outs() << " name " << P << " (offset " << dl.dylib.name << ")\n";
5348 outs() << " name ?(bad offset " << dl.dylib.name << ")\n";
5350 outs() << " time stamp " << dl.dylib.timestamp << " ";
5351 time_t t = dl.dylib.timestamp;
5352 outs() << ctime(&t);
5353 outs() << " current version ";
5354 if (dl.dylib.current_version == 0xffffffff)
5357 outs() << ((dl.dylib.current_version >> 16) & 0xffff) << "."
5358 << ((dl.dylib.current_version >> 8) & 0xff) << "."
5359 << (dl.dylib.current_version & 0xff) << "\n";
5360 outs() << "compatibility version ";
5361 if (dl.dylib.compatibility_version == 0xffffffff)
5364 outs() << ((dl.dylib.compatibility_version >> 16) & 0xffff) << "."
5365 << ((dl.dylib.compatibility_version >> 8) & 0xff) << "."
5366 << (dl.dylib.compatibility_version & 0xff) << "\n";
5369 static void PrintLinkEditDataCommand(MachO::linkedit_data_command ld,
5370 uint32_t object_size) {
5371 if (ld.cmd == MachO::LC_CODE_SIGNATURE)
5372 outs() << " cmd LC_FUNCTION_STARTS\n";
5373 else if (ld.cmd == MachO::LC_SEGMENT_SPLIT_INFO)
5374 outs() << " cmd LC_SEGMENT_SPLIT_INFO\n";
5375 else if (ld.cmd == MachO::LC_FUNCTION_STARTS)
5376 outs() << " cmd LC_FUNCTION_STARTS\n";
5377 else if (ld.cmd == MachO::LC_DATA_IN_CODE)
5378 outs() << " cmd LC_DATA_IN_CODE\n";
5379 else if (ld.cmd == MachO::LC_DYLIB_CODE_SIGN_DRS)
5380 outs() << " cmd LC_DYLIB_CODE_SIGN_DRS\n";
5381 else if (ld.cmd == MachO::LC_LINKER_OPTIMIZATION_HINT)
5382 outs() << " cmd LC_LINKER_OPTIMIZATION_HINT\n";
5384 outs() << " cmd " << ld.cmd << " (?)\n";
5385 outs() << " cmdsize " << ld.cmdsize;
5386 if (ld.cmdsize != sizeof(struct MachO::linkedit_data_command))
5387 outs() << " Incorrect size\n";
5390 outs() << " dataoff " << ld.dataoff;
5391 if (ld.dataoff > object_size)
5392 outs() << " (past end of file)\n";
5395 outs() << " datasize " << ld.datasize;
5396 uint64_t big_size = ld.dataoff;
5397 big_size += ld.datasize;
5398 if (big_size > object_size)
5399 outs() << " (past end of file)\n";
5404 static void PrintLoadCommands(const MachOObjectFile *Obj, uint32_t ncmds,
5405 uint32_t filetype, uint32_t cputype,
5409 StringRef Buf = Obj->getData();
5410 MachOObjectFile::LoadCommandInfo Command = Obj->getFirstLoadCommandInfo();
5411 for (unsigned i = 0;; ++i) {
5412 outs() << "Load command " << i << "\n";
5413 if (Command.C.cmd == MachO::LC_SEGMENT) {
5414 MachO::segment_command SLC = Obj->getSegmentLoadCommand(Command);
5415 const char *sg_segname = SLC.segname;
5416 PrintSegmentCommand(SLC.cmd, SLC.cmdsize, SLC.segname, SLC.vmaddr,
5417 SLC.vmsize, SLC.fileoff, SLC.filesize, SLC.maxprot,
5418 SLC.initprot, SLC.nsects, SLC.flags, Buf.size(),
5420 for (unsigned j = 0; j < SLC.nsects; j++) {
5421 MachO::section S = Obj->getSection(Command, j);
5422 PrintSection(S.sectname, S.segname, S.addr, S.size, S.offset, S.align,
5423 S.reloff, S.nreloc, S.flags, S.reserved1, S.reserved2,
5424 SLC.cmd, sg_segname, filetype, Buf.size(), verbose);
5426 } else if (Command.C.cmd == MachO::LC_SEGMENT_64) {
5427 MachO::segment_command_64 SLC_64 = Obj->getSegment64LoadCommand(Command);
5428 const char *sg_segname = SLC_64.segname;
5429 PrintSegmentCommand(SLC_64.cmd, SLC_64.cmdsize, SLC_64.segname,
5430 SLC_64.vmaddr, SLC_64.vmsize, SLC_64.fileoff,
5431 SLC_64.filesize, SLC_64.maxprot, SLC_64.initprot,
5432 SLC_64.nsects, SLC_64.flags, Buf.size(), verbose);
5433 for (unsigned j = 0; j < SLC_64.nsects; j++) {
5434 MachO::section_64 S_64 = Obj->getSection64(Command, j);
5435 PrintSection(S_64.sectname, S_64.segname, S_64.addr, S_64.size,
5436 S_64.offset, S_64.align, S_64.reloff, S_64.nreloc,
5437 S_64.flags, S_64.reserved1, S_64.reserved2, SLC_64.cmd,
5438 sg_segname, filetype, Buf.size(), verbose);
5440 } else if (Command.C.cmd == MachO::LC_SYMTAB) {
5441 MachO::symtab_command Symtab = Obj->getSymtabLoadCommand();
5442 PrintSymtabLoadCommand(Symtab, Obj->is64Bit(), Buf.size());
5443 } else if (Command.C.cmd == MachO::LC_DYSYMTAB) {
5444 MachO::dysymtab_command Dysymtab = Obj->getDysymtabLoadCommand();
5445 MachO::symtab_command Symtab = Obj->getSymtabLoadCommand();
5446 PrintDysymtabLoadCommand(Dysymtab, Symtab.nsyms, Buf.size(),
5448 } else if (Command.C.cmd == MachO::LC_DYLD_INFO ||
5449 Command.C.cmd == MachO::LC_DYLD_INFO_ONLY) {
5450 MachO::dyld_info_command DyldInfo = Obj->getDyldInfoLoadCommand(Command);
5451 PrintDyldInfoLoadCommand(DyldInfo, Buf.size());
5452 } else if (Command.C.cmd == MachO::LC_LOAD_DYLINKER ||
5453 Command.C.cmd == MachO::LC_ID_DYLINKER ||
5454 Command.C.cmd == MachO::LC_DYLD_ENVIRONMENT) {
5455 MachO::dylinker_command Dyld = Obj->getDylinkerCommand(Command);
5456 PrintDyldLoadCommand(Dyld, Command.Ptr);
5457 } else if (Command.C.cmd == MachO::LC_UUID) {
5458 MachO::uuid_command Uuid = Obj->getUuidCommand(Command);
5459 PrintUuidLoadCommand(Uuid);
5460 } else if (Command.C.cmd == MachO::LC_RPATH) {
5461 MachO::rpath_command Rpath = Obj->getRpathCommand(Command);
5462 PrintRpathLoadCommand(Rpath, Command.Ptr);
5463 } else if (Command.C.cmd == MachO::LC_VERSION_MIN_MACOSX ||
5464 Command.C.cmd == MachO::LC_VERSION_MIN_IPHONEOS) {
5465 MachO::version_min_command Vd = Obj->getVersionMinLoadCommand(Command);
5466 PrintVersionMinLoadCommand(Vd);
5467 } else if (Command.C.cmd == MachO::LC_SOURCE_VERSION) {
5468 MachO::source_version_command Sd = Obj->getSourceVersionCommand(Command);
5469 PrintSourceVersionCommand(Sd);
5470 } else if (Command.C.cmd == MachO::LC_MAIN) {
5471 MachO::entry_point_command Ep = Obj->getEntryPointCommand(Command);
5472 PrintEntryPointCommand(Ep);
5473 } else if (Command.C.cmd == MachO::LC_ENCRYPTION_INFO) {
5474 MachO::encryption_info_command Ei =
5475 Obj->getEncryptionInfoCommand(Command);
5476 PrintEncryptionInfoCommand(Ei, Buf.size());
5477 } else if (Command.C.cmd == MachO::LC_ENCRYPTION_INFO_64) {
5478 MachO::encryption_info_command_64 Ei =
5479 Obj->getEncryptionInfoCommand64(Command);
5480 PrintEncryptionInfoCommand64(Ei, Buf.size());
5481 } else if (Command.C.cmd == MachO::LC_LINKER_OPTION) {
5482 MachO::linker_option_command Lo =
5483 Obj->getLinkerOptionLoadCommand(Command);
5484 PrintLinkerOptionCommand(Lo, Command.Ptr);
5485 } else if (Command.C.cmd == MachO::LC_SUB_FRAMEWORK) {
5486 MachO::sub_framework_command Sf = Obj->getSubFrameworkCommand(Command);
5487 PrintSubFrameworkCommand(Sf, Command.Ptr);
5488 } else if (Command.C.cmd == MachO::LC_SUB_UMBRELLA) {
5489 MachO::sub_umbrella_command Sf = Obj->getSubUmbrellaCommand(Command);
5490 PrintSubUmbrellaCommand(Sf, Command.Ptr);
5491 } else if (Command.C.cmd == MachO::LC_SUB_LIBRARY) {
5492 MachO::sub_library_command Sl = Obj->getSubLibraryCommand(Command);
5493 PrintSubLibraryCommand(Sl, Command.Ptr);
5494 } else if (Command.C.cmd == MachO::LC_SUB_CLIENT) {
5495 MachO::sub_client_command Sc = Obj->getSubClientCommand(Command);
5496 PrintSubClientCommand(Sc, Command.Ptr);
5497 } else if (Command.C.cmd == MachO::LC_ROUTINES) {
5498 MachO::routines_command Rc = Obj->getRoutinesCommand(Command);
5499 PrintRoutinesCommand(Rc);
5500 } else if (Command.C.cmd == MachO::LC_ROUTINES_64) {
5501 MachO::routines_command_64 Rc = Obj->getRoutinesCommand64(Command);
5502 PrintRoutinesCommand64(Rc);
5503 } else if (Command.C.cmd == MachO::LC_THREAD ||
5504 Command.C.cmd == MachO::LC_UNIXTHREAD) {
5505 MachO::thread_command Tc = Obj->getThreadCommand(Command);
5506 PrintThreadCommand(Tc, Command.Ptr, Obj->isLittleEndian(), cputype);
5507 } else if (Command.C.cmd == MachO::LC_LOAD_DYLIB ||
5508 Command.C.cmd == MachO::LC_ID_DYLIB ||
5509 Command.C.cmd == MachO::LC_LOAD_WEAK_DYLIB ||
5510 Command.C.cmd == MachO::LC_REEXPORT_DYLIB ||
5511 Command.C.cmd == MachO::LC_LAZY_LOAD_DYLIB ||
5512 Command.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB) {
5513 MachO::dylib_command Dl = Obj->getDylibIDLoadCommand(Command);
5514 PrintDylibCommand(Dl, Command.Ptr);
5515 } else if (Command.C.cmd == MachO::LC_CODE_SIGNATURE ||
5516 Command.C.cmd == MachO::LC_SEGMENT_SPLIT_INFO ||
5517 Command.C.cmd == MachO::LC_FUNCTION_STARTS ||
5518 Command.C.cmd == MachO::LC_DATA_IN_CODE ||
5519 Command.C.cmd == MachO::LC_DYLIB_CODE_SIGN_DRS ||
5520 Command.C.cmd == MachO::LC_LINKER_OPTIMIZATION_HINT) {
5521 MachO::linkedit_data_command Ld =
5522 Obj->getLinkeditDataLoadCommand(Command);
5523 PrintLinkEditDataCommand(Ld, Buf.size());
5525 outs() << " cmd ?(" << format("0x%08" PRIx32, Command.C.cmd)
5527 outs() << " cmdsize " << Command.C.cmdsize << "\n";
5528 // TODO: get and print the raw bytes of the load command.
5530 // TODO: print all the other kinds of load commands.
5534 Command = Obj->getNextLoadCommandInfo(Command);
5538 static void getAndPrintMachHeader(const MachOObjectFile *Obj, uint32_t &ncmds,
5539 uint32_t &filetype, uint32_t &cputype,
5541 if (Obj->is64Bit()) {
5542 MachO::mach_header_64 H_64;
5543 H_64 = Obj->getHeader64();
5544 PrintMachHeader(H_64.magic, H_64.cputype, H_64.cpusubtype, H_64.filetype,
5545 H_64.ncmds, H_64.sizeofcmds, H_64.flags, verbose);
5547 filetype = H_64.filetype;
5548 cputype = H_64.cputype;
5550 MachO::mach_header H;
5551 H = Obj->getHeader();
5552 PrintMachHeader(H.magic, H.cputype, H.cpusubtype, H.filetype, H.ncmds,
5553 H.sizeofcmds, H.flags, verbose);
5555 filetype = H.filetype;
5556 cputype = H.cputype;
5560 void llvm::printMachOFileHeader(const object::ObjectFile *Obj) {
5561 const MachOObjectFile *file = dyn_cast<const MachOObjectFile>(Obj);
5563 uint32_t filetype = 0;
5564 uint32_t cputype = 0;
5565 getAndPrintMachHeader(file, ncmds, filetype, cputype, !NonVerbose);
5566 PrintLoadCommands(file, ncmds, filetype, cputype, !NonVerbose);
5569 //===----------------------------------------------------------------------===//
5570 // export trie dumping
5571 //===----------------------------------------------------------------------===//
5573 void llvm::printMachOExportsTrie(const object::MachOObjectFile *Obj) {
5574 for (const llvm::object::ExportEntry &Entry : Obj->exports()) {
5575 uint64_t Flags = Entry.flags();
5576 bool ReExport = (Flags & MachO::EXPORT_SYMBOL_FLAGS_REEXPORT);
5577 bool WeakDef = (Flags & MachO::EXPORT_SYMBOL_FLAGS_WEAK_DEFINITION);
5578 bool ThreadLocal = ((Flags & MachO::EXPORT_SYMBOL_FLAGS_KIND_MASK) ==
5579 MachO::EXPORT_SYMBOL_FLAGS_KIND_THREAD_LOCAL);
5580 bool Abs = ((Flags & MachO::EXPORT_SYMBOL_FLAGS_KIND_MASK) ==
5581 MachO::EXPORT_SYMBOL_FLAGS_KIND_ABSOLUTE);
5582 bool Resolver = (Flags & MachO::EXPORT_SYMBOL_FLAGS_STUB_AND_RESOLVER);
5584 outs() << "[re-export] ";
5586 outs() << format("0x%08llX ",
5587 Entry.address()); // FIXME:add in base address
5588 outs() << Entry.name();
5589 if (WeakDef || ThreadLocal || Resolver || Abs) {
5590 bool NeedsComma = false;
5593 outs() << "weak_def";
5599 outs() << "per-thread";
5605 outs() << "absolute";
5611 outs() << format("resolver=0x%08llX", Entry.other());
5617 StringRef DylibName = "unknown";
5618 int Ordinal = Entry.other() - 1;
5619 Obj->getLibraryShortNameByIndex(Ordinal, DylibName);
5620 if (Entry.otherName().empty())
5621 outs() << " (from " << DylibName << ")";
5623 outs() << " (" << Entry.otherName() << " from " << DylibName << ")";
5629 //===----------------------------------------------------------------------===//
5630 // rebase table dumping
5631 //===----------------------------------------------------------------------===//
5636 SegInfo(const object::MachOObjectFile *Obj);
5638 StringRef segmentName(uint32_t SegIndex);
5639 StringRef sectionName(uint32_t SegIndex, uint64_t SegOffset);
5640 uint64_t address(uint32_t SegIndex, uint64_t SegOffset);
5643 struct SectionInfo {
5646 StringRef SectionName;
5647 StringRef SegmentName;
5648 uint64_t OffsetInSegment;
5649 uint64_t SegmentStartAddress;
5650 uint32_t SegmentIndex;
5652 const SectionInfo &findSection(uint32_t SegIndex, uint64_t SegOffset);
5653 SmallVector<SectionInfo, 32> Sections;
5657 SegInfo::SegInfo(const object::MachOObjectFile *Obj) {
5658 // Build table of sections so segIndex/offset pairs can be translated.
5659 uint32_t CurSegIndex = Obj->hasPageZeroSegment() ? 1 : 0;
5660 StringRef CurSegName;
5661 uint64_t CurSegAddress;
5662 for (const SectionRef &Section : Obj->sections()) {
5664 if (error(Section.getName(Info.SectionName)))
5666 Info.Address = Section.getAddress();
5667 Info.Size = Section.getSize();
5669 Obj->getSectionFinalSegmentName(Section.getRawDataRefImpl());
5670 if (!Info.SegmentName.equals(CurSegName)) {
5672 CurSegName = Info.SegmentName;
5673 CurSegAddress = Info.Address;
5675 Info.SegmentIndex = CurSegIndex - 1;
5676 Info.OffsetInSegment = Info.Address - CurSegAddress;
5677 Info.SegmentStartAddress = CurSegAddress;
5678 Sections.push_back(Info);
5682 StringRef SegInfo::segmentName(uint32_t SegIndex) {
5683 for (const SectionInfo &SI : Sections) {
5684 if (SI.SegmentIndex == SegIndex)
5685 return SI.SegmentName;
5687 llvm_unreachable("invalid segIndex");
5690 const SegInfo::SectionInfo &SegInfo::findSection(uint32_t SegIndex,
5691 uint64_t OffsetInSeg) {
5692 for (const SectionInfo &SI : Sections) {
5693 if (SI.SegmentIndex != SegIndex)
5695 if (SI.OffsetInSegment > OffsetInSeg)
5697 if (OffsetInSeg >= (SI.OffsetInSegment + SI.Size))
5701 llvm_unreachable("segIndex and offset not in any section");
5704 StringRef SegInfo::sectionName(uint32_t SegIndex, uint64_t OffsetInSeg) {
5705 return findSection(SegIndex, OffsetInSeg).SectionName;
5708 uint64_t SegInfo::address(uint32_t SegIndex, uint64_t OffsetInSeg) {
5709 const SectionInfo &SI = findSection(SegIndex, OffsetInSeg);
5710 return SI.SegmentStartAddress + OffsetInSeg;
5713 void llvm::printMachORebaseTable(const object::MachOObjectFile *Obj) {
5714 // Build table of sections so names can used in final output.
5715 SegInfo sectionTable(Obj);
5717 outs() << "segment section address type\n";
5718 for (const llvm::object::MachORebaseEntry &Entry : Obj->rebaseTable()) {
5719 uint32_t SegIndex = Entry.segmentIndex();
5720 uint64_t OffsetInSeg = Entry.segmentOffset();
5721 StringRef SegmentName = sectionTable.segmentName(SegIndex);
5722 StringRef SectionName = sectionTable.sectionName(SegIndex, OffsetInSeg);
5723 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
5725 // Table lines look like: __DATA __nl_symbol_ptr 0x0000F00C pointer
5726 outs() << format("%-8s %-18s 0x%08" PRIX64 " %s\n",
5727 SegmentName.str().c_str(), SectionName.str().c_str(),
5728 Address, Entry.typeName().str().c_str());
5732 static StringRef ordinalName(const object::MachOObjectFile *Obj, int Ordinal) {
5733 StringRef DylibName;
5735 case MachO::BIND_SPECIAL_DYLIB_SELF:
5736 return "this-image";
5737 case MachO::BIND_SPECIAL_DYLIB_MAIN_EXECUTABLE:
5738 return "main-executable";
5739 case MachO::BIND_SPECIAL_DYLIB_FLAT_LOOKUP:
5740 return "flat-namespace";
5743 std::error_code EC =
5744 Obj->getLibraryShortNameByIndex(Ordinal - 1, DylibName);
5746 return "<<bad library ordinal>>";
5750 return "<<unknown special ordinal>>";
5753 //===----------------------------------------------------------------------===//
5754 // bind table dumping
5755 //===----------------------------------------------------------------------===//
5757 void llvm::printMachOBindTable(const object::MachOObjectFile *Obj) {
5758 // Build table of sections so names can used in final output.
5759 SegInfo sectionTable(Obj);
5761 outs() << "segment section address type "
5762 "addend dylib symbol\n";
5763 for (const llvm::object::MachOBindEntry &Entry : Obj->bindTable()) {
5764 uint32_t SegIndex = Entry.segmentIndex();
5765 uint64_t OffsetInSeg = Entry.segmentOffset();
5766 StringRef SegmentName = sectionTable.segmentName(SegIndex);
5767 StringRef SectionName = sectionTable.sectionName(SegIndex, OffsetInSeg);
5768 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
5770 // Table lines look like:
5771 // __DATA __got 0x00012010 pointer 0 libSystem ___stack_chk_guard
5773 if (Entry.flags() & MachO::BIND_SYMBOL_FLAGS_WEAK_IMPORT)
5774 Attr = " (weak_import)";
5775 outs() << left_justify(SegmentName, 8) << " "
5776 << left_justify(SectionName, 18) << " "
5777 << format_hex(Address, 10, true) << " "
5778 << left_justify(Entry.typeName(), 8) << " "
5779 << format_decimal(Entry.addend(), 8) << " "
5780 << left_justify(ordinalName(Obj, Entry.ordinal()), 16) << " "
5781 << Entry.symbolName() << Attr << "\n";
5785 //===----------------------------------------------------------------------===//
5786 // lazy bind table dumping
5787 //===----------------------------------------------------------------------===//
5789 void llvm::printMachOLazyBindTable(const object::MachOObjectFile *Obj) {
5790 // Build table of sections so names can used in final output.
5791 SegInfo sectionTable(Obj);
5793 outs() << "segment section address "
5795 for (const llvm::object::MachOBindEntry &Entry : Obj->lazyBindTable()) {
5796 uint32_t SegIndex = Entry.segmentIndex();
5797 uint64_t OffsetInSeg = Entry.segmentOffset();
5798 StringRef SegmentName = sectionTable.segmentName(SegIndex);
5799 StringRef SectionName = sectionTable.sectionName(SegIndex, OffsetInSeg);
5800 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
5802 // Table lines look like:
5803 // __DATA __got 0x00012010 libSystem ___stack_chk_guard
5804 outs() << left_justify(SegmentName, 8) << " "
5805 << left_justify(SectionName, 18) << " "
5806 << format_hex(Address, 10, true) << " "
5807 << left_justify(ordinalName(Obj, Entry.ordinal()), 16) << " "
5808 << Entry.symbolName() << "\n";
5812 //===----------------------------------------------------------------------===//
5813 // weak bind table dumping
5814 //===----------------------------------------------------------------------===//
5816 void llvm::printMachOWeakBindTable(const object::MachOObjectFile *Obj) {
5817 // Build table of sections so names can used in final output.
5818 SegInfo sectionTable(Obj);
5820 outs() << "segment section address "
5821 "type addend symbol\n";
5822 for (const llvm::object::MachOBindEntry &Entry : Obj->weakBindTable()) {
5823 // Strong symbols don't have a location to update.
5824 if (Entry.flags() & MachO::BIND_SYMBOL_FLAGS_NON_WEAK_DEFINITION) {
5825 outs() << " strong "
5826 << Entry.symbolName() << "\n";
5829 uint32_t SegIndex = Entry.segmentIndex();
5830 uint64_t OffsetInSeg = Entry.segmentOffset();
5831 StringRef SegmentName = sectionTable.segmentName(SegIndex);
5832 StringRef SectionName = sectionTable.sectionName(SegIndex, OffsetInSeg);
5833 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
5835 // Table lines look like:
5836 // __DATA __data 0x00001000 pointer 0 _foo
5837 outs() << left_justify(SegmentName, 8) << " "
5838 << left_justify(SectionName, 18) << " "
5839 << format_hex(Address, 10, true) << " "
5840 << left_justify(Entry.typeName(), 8) << " "
5841 << format_decimal(Entry.addend(), 8) << " " << Entry.symbolName()
5846 // get_dyld_bind_info_symbolname() is used for disassembly and passed an
5847 // address, ReferenceValue, in the Mach-O file and looks in the dyld bind
5848 // information for that address. If the address is found its binding symbol
5849 // name is returned. If not nullptr is returned.
5850 static const char *get_dyld_bind_info_symbolname(uint64_t ReferenceValue,
5851 struct DisassembleInfo *info) {
5852 if (info->bindtable == nullptr) {
5853 info->bindtable = new (BindTable);
5854 SegInfo sectionTable(info->O);
5855 for (const llvm::object::MachOBindEntry &Entry : info->O->bindTable()) {
5856 uint32_t SegIndex = Entry.segmentIndex();
5857 uint64_t OffsetInSeg = Entry.segmentOffset();
5858 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
5859 const char *SymbolName = nullptr;
5860 StringRef name = Entry.symbolName();
5862 SymbolName = name.data();
5863 info->bindtable->push_back(std::make_pair(Address, SymbolName));
5866 for (bind_table_iterator BI = info->bindtable->begin(),
5867 BE = info->bindtable->end();
5869 uint64_t Address = BI->first;
5870 if (ReferenceValue == Address) {
5871 const char *SymbolName = BI->second;