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"));
67 PrintImmHex("print-imm-hex",
68 cl::desc("Use hex format for immediate values"));
70 cl::opt<bool> llvm::UniversalHeaders("universal-headers",
71 cl::desc("Print Mach-O universal headers "
72 "(requires -macho)"));
75 llvm::ArchiveHeaders("archive-headers",
76 cl::desc("Print archive headers for Mach-O archives "
77 "(requires -macho)"));
80 llvm::IndirectSymbols("indirect-symbols",
81 cl::desc("Print indirect symbol table for Mach-O "
82 "objects (requires -macho)"));
85 llvm::DataInCode("data-in-code",
86 cl::desc("Print the data in code table for Mach-O objects "
87 "(requires -macho)"));
90 llvm::LinkOptHints("link-opt-hints",
91 cl::desc("Print the linker optimization hints for "
92 "Mach-O objects (requires -macho)"));
95 llvm::DumpSections("section",
96 cl::desc("Prints the specified segment,section for "
97 "Mach-O objects (requires -macho)"));
100 llvm::InfoPlist("info-plist",
101 cl::desc("Print the info plist section as strings for "
102 "Mach-O objects (requires -macho)"));
105 llvm::NonVerbose("non-verbose",
106 cl::desc("Print the info for Mach-O objects in "
107 "non-verbose or numeric form (requires -macho)"));
109 static cl::list<std::string>
110 ArchFlags("arch", cl::desc("architecture(s) from a Mach-O file to dump"),
112 bool ArchAll = false;
114 static std::string ThumbTripleName;
116 static const Target *GetTarget(const MachOObjectFile *MachOObj,
117 const char **McpuDefault,
118 const Target **ThumbTarget) {
119 // Figure out the target triple.
120 if (TripleName.empty()) {
121 llvm::Triple TT("unknown-unknown-unknown");
122 llvm::Triple ThumbTriple = Triple();
123 TT = MachOObj->getArch(McpuDefault, &ThumbTriple);
124 TripleName = TT.str();
125 ThumbTripleName = ThumbTriple.str();
128 // Get the target specific parser.
130 const Target *TheTarget = TargetRegistry::lookupTarget(TripleName, Error);
131 if (TheTarget && ThumbTripleName.empty())
134 *ThumbTarget = TargetRegistry::lookupTarget(ThumbTripleName, Error);
138 errs() << "llvm-objdump: error: unable to get target for '";
140 errs() << TripleName;
142 errs() << ThumbTripleName;
143 errs() << "', see --version and --triple.\n";
147 struct SymbolSorter {
148 bool operator()(const SymbolRef &A, const SymbolRef &B) {
149 SymbolRef::Type AType, BType;
153 uint64_t AAddr, BAddr;
154 if (AType != SymbolRef::ST_Function)
158 if (BType != SymbolRef::ST_Function)
162 return AAddr < BAddr;
166 // Types for the storted data in code table that is built before disassembly
167 // and the predicate function to sort them.
168 typedef std::pair<uint64_t, DiceRef> DiceTableEntry;
169 typedef std::vector<DiceTableEntry> DiceTable;
170 typedef DiceTable::iterator dice_table_iterator;
172 // This is used to search for a data in code table entry for the PC being
173 // disassembled. The j parameter has the PC in j.first. A single data in code
174 // table entry can cover many bytes for each of its Kind's. So if the offset,
175 // aka the i.first value, of the data in code table entry plus its Length
176 // covers the PC being searched for this will return true. If not it will
178 static bool compareDiceTableEntries(const DiceTableEntry &i,
179 const DiceTableEntry &j) {
181 i.second.getLength(Length);
183 return j.first >= i.first && j.first < i.first + Length;
186 static uint64_t DumpDataInCode(const char *bytes, uint64_t Length,
187 unsigned short Kind) {
188 uint32_t Value, Size = 1;
192 case MachO::DICE_KIND_DATA:
195 DumpBytes(StringRef(bytes, 4));
196 Value = bytes[3] << 24 | bytes[2] << 16 | bytes[1] << 8 | bytes[0];
197 outs() << "\t.long " << Value;
199 } else if (Length >= 2) {
201 DumpBytes(StringRef(bytes, 2));
202 Value = bytes[1] << 8 | bytes[0];
203 outs() << "\t.short " << Value;
207 DumpBytes(StringRef(bytes, 2));
209 outs() << "\t.byte " << Value;
212 if (Kind == MachO::DICE_KIND_DATA)
213 outs() << "\t@ KIND_DATA\n";
215 outs() << "\t@ data in code kind = " << Kind << "\n";
217 case MachO::DICE_KIND_JUMP_TABLE8:
219 DumpBytes(StringRef(bytes, 1));
221 outs() << "\t.byte " << format("%3u", Value) << "\t@ KIND_JUMP_TABLE8\n";
224 case MachO::DICE_KIND_JUMP_TABLE16:
226 DumpBytes(StringRef(bytes, 2));
227 Value = bytes[1] << 8 | bytes[0];
228 outs() << "\t.short " << format("%5u", Value & 0xffff)
229 << "\t@ KIND_JUMP_TABLE16\n";
232 case MachO::DICE_KIND_JUMP_TABLE32:
233 case MachO::DICE_KIND_ABS_JUMP_TABLE32:
235 DumpBytes(StringRef(bytes, 4));
236 Value = bytes[3] << 24 | bytes[2] << 16 | bytes[1] << 8 | bytes[0];
237 outs() << "\t.long " << Value;
238 if (Kind == MachO::DICE_KIND_JUMP_TABLE32)
239 outs() << "\t@ KIND_JUMP_TABLE32\n";
241 outs() << "\t@ KIND_ABS_JUMP_TABLE32\n";
248 static void getSectionsAndSymbols(const MachO::mach_header Header,
249 MachOObjectFile *MachOObj,
250 std::vector<SectionRef> &Sections,
251 std::vector<SymbolRef> &Symbols,
252 SmallVectorImpl<uint64_t> &FoundFns,
253 uint64_t &BaseSegmentAddress) {
254 for (const SymbolRef &Symbol : MachOObj->symbols()) {
256 Symbol.getName(SymName);
257 if (!SymName.startswith("ltmp"))
258 Symbols.push_back(Symbol);
261 for (const SectionRef &Section : MachOObj->sections()) {
263 Section.getName(SectName);
264 Sections.push_back(Section);
267 MachOObjectFile::LoadCommandInfo Command =
268 MachOObj->getFirstLoadCommandInfo();
269 bool BaseSegmentAddressSet = false;
270 for (unsigned i = 0;; ++i) {
271 if (Command.C.cmd == MachO::LC_FUNCTION_STARTS) {
272 // We found a function starts segment, parse the addresses for later
274 MachO::linkedit_data_command LLC =
275 MachOObj->getLinkeditDataLoadCommand(Command);
277 MachOObj->ReadULEB128s(LLC.dataoff, FoundFns);
278 } else if (Command.C.cmd == MachO::LC_SEGMENT) {
279 MachO::segment_command SLC = MachOObj->getSegmentLoadCommand(Command);
280 StringRef SegName = SLC.segname;
281 if (!BaseSegmentAddressSet && SegName != "__PAGEZERO") {
282 BaseSegmentAddressSet = true;
283 BaseSegmentAddress = SLC.vmaddr;
287 if (i == Header.ncmds - 1)
290 Command = MachOObj->getNextLoadCommandInfo(Command);
294 static void PrintIndirectSymbolTable(MachOObjectFile *O, bool verbose,
295 uint32_t n, uint32_t count,
296 uint32_t stride, uint64_t addr) {
297 MachO::dysymtab_command Dysymtab = O->getDysymtabLoadCommand();
298 uint32_t nindirectsyms = Dysymtab.nindirectsyms;
299 if (n > nindirectsyms)
300 outs() << " (entries start past the end of the indirect symbol "
301 "table) (reserved1 field greater than the table size)";
302 else if (n + count > nindirectsyms)
303 outs() << " (entries extends past the end of the indirect symbol "
306 uint32_t cputype = O->getHeader().cputype;
307 if (cputype & MachO::CPU_ARCH_ABI64)
308 outs() << "address index";
310 outs() << "address index";
315 for (uint32_t j = 0; j < count && n + j < nindirectsyms; j++) {
316 if (cputype & MachO::CPU_ARCH_ABI64)
317 outs() << format("0x%016" PRIx64, addr + j * stride) << " ";
319 outs() << format("0x%08" PRIx32, addr + j * stride) << " ";
320 MachO::dysymtab_command Dysymtab = O->getDysymtabLoadCommand();
321 uint32_t indirect_symbol = O->getIndirectSymbolTableEntry(Dysymtab, n + j);
322 if (indirect_symbol == MachO::INDIRECT_SYMBOL_LOCAL) {
326 if (indirect_symbol ==
327 (MachO::INDIRECT_SYMBOL_LOCAL | MachO::INDIRECT_SYMBOL_ABS)) {
328 outs() << "LOCAL ABSOLUTE\n";
331 if (indirect_symbol == MachO::INDIRECT_SYMBOL_ABS) {
332 outs() << "ABSOLUTE\n";
335 outs() << format("%5u ", indirect_symbol);
337 MachO::symtab_command Symtab = O->getSymtabLoadCommand();
338 if (indirect_symbol < Symtab.nsyms) {
339 symbol_iterator Sym = O->getSymbolByIndex(indirect_symbol);
340 SymbolRef Symbol = *Sym;
342 Symbol.getName(SymName);
352 static void PrintIndirectSymbols(MachOObjectFile *O, bool verbose) {
353 uint32_t LoadCommandCount = O->getHeader().ncmds;
354 MachOObjectFile::LoadCommandInfo Load = O->getFirstLoadCommandInfo();
355 for (unsigned I = 0;; ++I) {
356 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
357 MachO::segment_command_64 Seg = O->getSegment64LoadCommand(Load);
358 for (unsigned J = 0; J < Seg.nsects; ++J) {
359 MachO::section_64 Sec = O->getSection64(Load, J);
360 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
361 if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
362 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
363 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
364 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
365 section_type == MachO::S_SYMBOL_STUBS) {
367 if (section_type == MachO::S_SYMBOL_STUBS)
368 stride = Sec.reserved2;
372 outs() << "Can't print indirect symbols for (" << Sec.segname << ","
373 << Sec.sectname << ") "
374 << "(size of stubs in reserved2 field is zero)\n";
377 uint32_t count = Sec.size / stride;
378 outs() << "Indirect symbols for (" << Sec.segname << ","
379 << Sec.sectname << ") " << count << " entries";
380 uint32_t n = Sec.reserved1;
381 PrintIndirectSymbolTable(O, verbose, n, count, stride, Sec.addr);
384 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
385 MachO::segment_command Seg = O->getSegmentLoadCommand(Load);
386 for (unsigned J = 0; J < Seg.nsects; ++J) {
387 MachO::section Sec = O->getSection(Load, J);
388 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
389 if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
390 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
391 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
392 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
393 section_type == MachO::S_SYMBOL_STUBS) {
395 if (section_type == MachO::S_SYMBOL_STUBS)
396 stride = Sec.reserved2;
400 outs() << "Can't print indirect symbols for (" << Sec.segname << ","
401 << Sec.sectname << ") "
402 << "(size of stubs in reserved2 field is zero)\n";
405 uint32_t count = Sec.size / stride;
406 outs() << "Indirect symbols for (" << Sec.segname << ","
407 << Sec.sectname << ") " << count << " entries";
408 uint32_t n = Sec.reserved1;
409 PrintIndirectSymbolTable(O, verbose, n, count, stride, Sec.addr);
413 if (I == LoadCommandCount - 1)
416 Load = O->getNextLoadCommandInfo(Load);
420 static void PrintDataInCodeTable(MachOObjectFile *O, bool verbose) {
421 MachO::linkedit_data_command DIC = O->getDataInCodeLoadCommand();
422 uint32_t nentries = DIC.datasize / sizeof(struct MachO::data_in_code_entry);
423 outs() << "Data in code table (" << nentries << " entries)\n";
424 outs() << "offset length kind\n";
425 for (dice_iterator DI = O->begin_dices(), DE = O->end_dices(); DI != DE;
428 DI->getOffset(Offset);
429 outs() << format("0x%08" PRIx32, Offset) << " ";
431 DI->getLength(Length);
432 outs() << format("%6u", Length) << " ";
437 case MachO::DICE_KIND_DATA:
440 case MachO::DICE_KIND_JUMP_TABLE8:
441 outs() << "JUMP_TABLE8";
443 case MachO::DICE_KIND_JUMP_TABLE16:
444 outs() << "JUMP_TABLE16";
446 case MachO::DICE_KIND_JUMP_TABLE32:
447 outs() << "JUMP_TABLE32";
449 case MachO::DICE_KIND_ABS_JUMP_TABLE32:
450 outs() << "ABS_JUMP_TABLE32";
453 outs() << format("0x%04" PRIx32, Kind);
457 outs() << format("0x%04" PRIx32, Kind);
462 static void PrintLinkOptHints(MachOObjectFile *O) {
463 MachO::linkedit_data_command LohLC = O->getLinkOptHintsLoadCommand();
464 const char *loh = O->getData().substr(LohLC.dataoff, 1).data();
465 uint32_t nloh = LohLC.datasize;
466 outs() << "Linker optimiztion hints (" << nloh << " total bytes)\n";
467 for (uint32_t i = 0; i < nloh;) {
469 uint64_t identifier = decodeULEB128((const uint8_t *)(loh + i), &n);
471 outs() << " identifier " << identifier << " ";
474 switch (identifier) {
476 outs() << "AdrpAdrp\n";
479 outs() << "AdrpLdr\n";
482 outs() << "AdrpAddLdr\n";
485 outs() << "AdrpLdrGotLdr\n";
488 outs() << "AdrpAddStr\n";
491 outs() << "AdrpLdrGotStr\n";
494 outs() << "AdrpAdd\n";
497 outs() << "AdrpLdrGot\n";
500 outs() << "Unknown identifier value\n";
503 uint64_t narguments = decodeULEB128((const uint8_t *)(loh + i), &n);
505 outs() << " narguments " << narguments << "\n";
509 for (uint32_t j = 0; j < narguments; j++) {
510 uint64_t value = decodeULEB128((const uint8_t *)(loh + i), &n);
512 outs() << "\tvalue " << format("0x%" PRIx64, value) << "\n";
519 typedef DenseMap<uint64_t, StringRef> SymbolAddressMap;
521 static void CreateSymbolAddressMap(MachOObjectFile *O,
522 SymbolAddressMap *AddrMap) {
523 // Create a map of symbol addresses to symbol names.
524 for (const SymbolRef &Symbol : O->symbols()) {
527 if (ST == SymbolRef::ST_Function || ST == SymbolRef::ST_Data ||
528 ST == SymbolRef::ST_Other) {
530 Symbol.getAddress(Address);
532 Symbol.getName(SymName);
533 (*AddrMap)[Address] = SymName;
538 // GuessSymbolName is passed the address of what might be a symbol and a
539 // pointer to the SymbolAddressMap. It returns the name of a symbol
540 // with that address or nullptr if no symbol is found with that address.
541 static const char *GuessSymbolName(uint64_t value, SymbolAddressMap *AddrMap) {
542 const char *SymbolName = nullptr;
543 // A DenseMap can't lookup up some values.
544 if (value != 0xffffffffffffffffULL && value != 0xfffffffffffffffeULL) {
545 StringRef name = AddrMap->lookup(value);
547 SymbolName = name.data();
552 static void DumpCstringChar(const char c) {
556 outs().write_escaped(p);
559 static void DumpCstringSection(MachOObjectFile *O, const char *sect,
560 uint32_t sect_size, uint64_t sect_addr,
561 bool print_addresses) {
562 for (uint32_t i = 0; i < sect_size; i++) {
563 if (print_addresses) {
565 outs() << format("%016" PRIx64, sect_addr + i) << " ";
567 outs() << format("%08" PRIx64, sect_addr + i) << " ";
569 for (; i < sect_size && sect[i] != '\0'; i++)
570 DumpCstringChar(sect[i]);
571 if (i < sect_size && sect[i] == '\0')
576 static void DumpLiteral4(uint32_t l, float f) {
577 outs() << format("0x%08" PRIx32, l);
578 if ((l & 0x7f800000) != 0x7f800000)
579 outs() << format(" (%.16e)\n", f);
582 outs() << " (+Infinity)\n";
583 else if (l == 0xff800000)
584 outs() << " (-Infinity)\n";
585 else if ((l & 0x00400000) == 0x00400000)
586 outs() << " (non-signaling Not-a-Number)\n";
588 outs() << " (signaling Not-a-Number)\n";
592 static void DumpLiteral4Section(MachOObjectFile *O, const char *sect,
593 uint32_t sect_size, uint64_t sect_addr,
594 bool print_addresses) {
595 for (uint32_t i = 0; i < sect_size; i += sizeof(float)) {
596 if (print_addresses) {
598 outs() << format("%016" PRIx64, sect_addr + i) << " ";
600 outs() << format("%08" PRIx64, sect_addr + i) << " ";
603 memcpy(&f, sect + i, sizeof(float));
604 if (O->isLittleEndian() != sys::IsLittleEndianHost)
605 sys::swapByteOrder(f);
607 memcpy(&l, sect + i, sizeof(uint32_t));
608 if (O->isLittleEndian() != sys::IsLittleEndianHost)
609 sys::swapByteOrder(l);
614 static void DumpLiteral8(MachOObjectFile *O, uint32_t l0, uint32_t l1,
616 outs() << format("0x%08" PRIx32, l0) << " " << format("0x%08" PRIx32, l1);
618 if (O->isLittleEndian()) {
625 // Hi is the high word, so this is equivalent to if(isfinite(d))
626 if ((Hi & 0x7ff00000) != 0x7ff00000)
627 outs() << format(" (%.16e)\n", d);
629 if (Hi == 0x7ff00000 && Lo == 0)
630 outs() << " (+Infinity)\n";
631 else if (Hi == 0xfff00000 && Lo == 0)
632 outs() << " (-Infinity)\n";
633 else if ((Hi & 0x00080000) == 0x00080000)
634 outs() << " (non-signaling Not-a-Number)\n";
636 outs() << " (signaling Not-a-Number)\n";
640 static void DumpLiteral8Section(MachOObjectFile *O, const char *sect,
641 uint32_t sect_size, uint64_t sect_addr,
642 bool print_addresses) {
643 for (uint32_t i = 0; i < sect_size; i += sizeof(double)) {
644 if (print_addresses) {
646 outs() << format("%016" PRIx64, sect_addr + i) << " ";
648 outs() << format("%08" PRIx64, sect_addr + i) << " ";
651 memcpy(&d, sect + i, sizeof(double));
652 if (O->isLittleEndian() != sys::IsLittleEndianHost)
653 sys::swapByteOrder(d);
655 memcpy(&l0, sect + i, sizeof(uint32_t));
656 memcpy(&l1, sect + i + sizeof(uint32_t), sizeof(uint32_t));
657 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
658 sys::swapByteOrder(l0);
659 sys::swapByteOrder(l1);
661 DumpLiteral8(O, l0, l1, d);
665 static void DumpLiteral16(uint32_t l0, uint32_t l1, uint32_t l2, uint32_t l3) {
666 outs() << format("0x%08" PRIx32, l0) << " ";
667 outs() << format("0x%08" PRIx32, l1) << " ";
668 outs() << format("0x%08" PRIx32, l2) << " ";
669 outs() << format("0x%08" PRIx32, l3) << "\n";
672 static void DumpLiteral16Section(MachOObjectFile *O, const char *sect,
673 uint32_t sect_size, uint64_t sect_addr,
674 bool print_addresses) {
675 for (uint32_t i = 0; i < sect_size; i += 16) {
676 if (print_addresses) {
678 outs() << format("%016" PRIx64, sect_addr + i) << " ";
680 outs() << format("%08" PRIx64, sect_addr + i) << " ";
682 uint32_t l0, l1, l2, l3;
683 memcpy(&l0, sect + i, sizeof(uint32_t));
684 memcpy(&l1, sect + i + sizeof(uint32_t), sizeof(uint32_t));
685 memcpy(&l2, sect + i + 2 * sizeof(uint32_t), sizeof(uint32_t));
686 memcpy(&l3, sect + i + 3 * sizeof(uint32_t), sizeof(uint32_t));
687 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
688 sys::swapByteOrder(l0);
689 sys::swapByteOrder(l1);
690 sys::swapByteOrder(l2);
691 sys::swapByteOrder(l3);
693 DumpLiteral16(l0, l1, l2, l3);
697 static void DumpLiteralPointerSection(MachOObjectFile *O,
698 const SectionRef &Section,
699 const char *sect, uint32_t sect_size,
701 bool print_addresses) {
702 // Collect the literal sections in this Mach-O file.
703 std::vector<SectionRef> LiteralSections;
704 for (const SectionRef &Section : O->sections()) {
705 DataRefImpl Ref = Section.getRawDataRefImpl();
706 uint32_t section_type;
708 const MachO::section_64 Sec = O->getSection64(Ref);
709 section_type = Sec.flags & MachO::SECTION_TYPE;
711 const MachO::section Sec = O->getSection(Ref);
712 section_type = Sec.flags & MachO::SECTION_TYPE;
714 if (section_type == MachO::S_CSTRING_LITERALS ||
715 section_type == MachO::S_4BYTE_LITERALS ||
716 section_type == MachO::S_8BYTE_LITERALS ||
717 section_type == MachO::S_16BYTE_LITERALS)
718 LiteralSections.push_back(Section);
721 // Set the size of the literal pointer.
722 uint32_t lp_size = O->is64Bit() ? 8 : 4;
724 // Collect the external relocation symbols for the the literal pointers.
725 std::vector<std::pair<uint64_t, SymbolRef>> Relocs;
726 for (const RelocationRef &Reloc : Section.relocations()) {
728 MachO::any_relocation_info RE;
729 bool isExtern = false;
730 Rel = Reloc.getRawDataRefImpl();
731 RE = O->getRelocation(Rel);
732 isExtern = O->getPlainRelocationExternal(RE);
734 uint64_t RelocOffset;
735 Reloc.getOffset(RelocOffset);
736 symbol_iterator RelocSym = Reloc.getSymbol();
737 Relocs.push_back(std::make_pair(RelocOffset, *RelocSym));
740 array_pod_sort(Relocs.begin(), Relocs.end());
742 // Dump each literal pointer.
743 for (uint32_t i = 0; i < sect_size; i += lp_size) {
744 if (print_addresses) {
746 outs() << format("%016" PRIx64, sect_addr + i) << " ";
748 outs() << format("%08" PRIx64, sect_addr + i) << " ";
752 memcpy(&lp, sect + i, sizeof(uint64_t));
753 if (O->isLittleEndian() != sys::IsLittleEndianHost)
754 sys::swapByteOrder(lp);
757 memcpy(&li, sect + i, sizeof(uint32_t));
758 if (O->isLittleEndian() != sys::IsLittleEndianHost)
759 sys::swapByteOrder(li);
763 // First look for an external relocation entry for this literal pointer.
764 bool reloc_found = false;
765 for (unsigned j = 0, e = Relocs.size(); j != e; ++j) {
766 if (Relocs[i].first == i) {
767 symbol_iterator RelocSym = Relocs[j].second;
769 RelocSym->getName(SymName);
770 outs() << "external relocation entry for symbol:" << SymName << "\n";
774 if (reloc_found == true)
777 // For local references see what the section the literal pointer points to.
779 for (unsigned SectIdx = 0; SectIdx != LiteralSections.size(); SectIdx++) {
780 uint64_t SectAddress = LiteralSections[SectIdx].getAddress();
781 uint64_t SectSize = LiteralSections[SectIdx].getSize();
782 if (lp >= SectAddress && lp < SectAddress + SectSize) {
786 LiteralSections[SectIdx].getName(SectName);
787 DataRefImpl Ref = LiteralSections[SectIdx].getRawDataRefImpl();
788 StringRef SegmentName = O->getSectionFinalSegmentName(Ref);
789 outs() << SegmentName << ":" << SectName << ":";
791 uint32_t section_type;
793 const MachO::section_64 Sec = O->getSection64(Ref);
794 section_type = Sec.flags & MachO::SECTION_TYPE;
796 const MachO::section Sec = O->getSection(Ref);
797 section_type = Sec.flags & MachO::SECTION_TYPE;
801 LiteralSections[SectIdx].getContents(BytesStr);
802 const char *Contents = reinterpret_cast<const char *>(BytesStr.data());
804 switch (section_type) {
805 case MachO::S_CSTRING_LITERALS:
806 for (uint64_t i = lp - SectAddress;
807 i < SectSize && Contents[i] != '\0'; i++) {
808 DumpCstringChar(Contents[i]);
812 case MachO::S_4BYTE_LITERALS:
814 memcpy(&f, Contents + (lp - SectAddress), sizeof(float));
816 memcpy(&l, Contents + (lp - SectAddress), sizeof(uint32_t));
817 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
818 sys::swapByteOrder(f);
819 sys::swapByteOrder(l);
823 case MachO::S_8BYTE_LITERALS: {
825 memcpy(&d, Contents + (lp - SectAddress), sizeof(double));
827 memcpy(&l0, Contents + (lp - SectAddress), sizeof(uint32_t));
828 memcpy(&l1, Contents + (lp - SectAddress) + sizeof(uint32_t),
830 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
831 sys::swapByteOrder(f);
832 sys::swapByteOrder(l0);
833 sys::swapByteOrder(l1);
835 DumpLiteral8(O, l0, l1, d);
838 case MachO::S_16BYTE_LITERALS: {
839 uint32_t l0, l1, l2, l3;
840 memcpy(&l0, Contents + (lp - SectAddress), sizeof(uint32_t));
841 memcpy(&l1, Contents + (lp - SectAddress) + sizeof(uint32_t),
843 memcpy(&l2, Contents + (lp - SectAddress) + 2 * sizeof(uint32_t),
845 memcpy(&l3, Contents + (lp - SectAddress) + 3 * sizeof(uint32_t),
847 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
848 sys::swapByteOrder(l0);
849 sys::swapByteOrder(l1);
850 sys::swapByteOrder(l2);
851 sys::swapByteOrder(l3);
853 DumpLiteral16(l0, l1, l2, l3);
860 outs() << format("0x%" PRIx64, lp) << " (not in a literal section)\n";
864 static void DumpInitTermPointerSection(MachOObjectFile *O, const char *sect,
865 uint32_t sect_size, uint64_t sect_addr,
866 SymbolAddressMap *AddrMap,
870 stride = sizeof(uint64_t);
872 stride = sizeof(uint32_t);
873 for (uint32_t i = 0; i < sect_size; i += stride) {
874 const char *SymbolName = nullptr;
876 outs() << format("0x%016" PRIx64, sect_addr + i * stride) << " ";
877 uint64_t pointer_value;
878 memcpy(&pointer_value, sect + i, stride);
879 if (O->isLittleEndian() != sys::IsLittleEndianHost)
880 sys::swapByteOrder(pointer_value);
881 outs() << format("0x%016" PRIx64, pointer_value);
883 SymbolName = GuessSymbolName(pointer_value, AddrMap);
885 outs() << format("0x%08" PRIx64, sect_addr + i * stride) << " ";
886 uint32_t pointer_value;
887 memcpy(&pointer_value, sect + i, stride);
888 if (O->isLittleEndian() != sys::IsLittleEndianHost)
889 sys::swapByteOrder(pointer_value);
890 outs() << format("0x%08" PRIx32, pointer_value);
892 SymbolName = GuessSymbolName(pointer_value, AddrMap);
895 outs() << " " << SymbolName;
900 static void DumpRawSectionContents(MachOObjectFile *O, const char *sect,
901 uint32_t size, uint64_t addr) {
902 uint32_t cputype = O->getHeader().cputype;
903 if (cputype == MachO::CPU_TYPE_I386 || cputype == MachO::CPU_TYPE_X86_64) {
905 for (uint32_t i = 0; i < size; i += j, addr += j) {
907 outs() << format("%016" PRIx64, addr) << "\t";
909 outs() << format("%08" PRIx64, addr) << "\t";
910 for (j = 0; j < 16 && i + j < size; j++) {
911 uint8_t byte_word = *(sect + i + j);
912 outs() << format("%02" PRIx32, (uint32_t)byte_word) << " ";
918 for (uint32_t i = 0; i < size; i += j, addr += j) {
920 outs() << format("%016" PRIx64, addr) << "\t";
922 outs() << format("%08" PRIx64, sect) << "\t";
923 for (j = 0; j < 4 * sizeof(int32_t) && i + j < size;
924 j += sizeof(int32_t)) {
925 if (i + j + sizeof(int32_t) < size) {
927 memcpy(&long_word, sect + i + j, sizeof(int32_t));
928 if (O->isLittleEndian() != sys::IsLittleEndianHost)
929 sys::swapByteOrder(long_word);
930 outs() << format("%08" PRIx32, long_word) << " ";
932 for (uint32_t k = 0; i + j + k < size; k++) {
933 uint8_t byte_word = *(sect + i + j);
934 outs() << format("%02" PRIx32, (uint32_t)byte_word) << " ";
943 static void DisassembleMachO(StringRef Filename, MachOObjectFile *MachOOF,
944 StringRef DisSegName, StringRef DisSectName);
946 static void DumpSectionContents(StringRef Filename, MachOObjectFile *O,
948 SymbolAddressMap AddrMap;
950 CreateSymbolAddressMap(O, &AddrMap);
952 for (unsigned i = 0; i < DumpSections.size(); ++i) {
953 StringRef DumpSection = DumpSections[i];
954 std::pair<StringRef, StringRef> DumpSegSectName;
955 DumpSegSectName = DumpSection.split(',');
956 StringRef DumpSegName, DumpSectName;
957 if (DumpSegSectName.second.size()) {
958 DumpSegName = DumpSegSectName.first;
959 DumpSectName = DumpSegSectName.second;
962 DumpSectName = DumpSegSectName.first;
964 for (const SectionRef &Section : O->sections()) {
966 Section.getName(SectName);
967 DataRefImpl Ref = Section.getRawDataRefImpl();
968 StringRef SegName = O->getSectionFinalSegmentName(Ref);
969 if ((DumpSegName.empty() || SegName == DumpSegName) &&
970 (SectName == DumpSectName)) {
971 outs() << "Contents of (" << SegName << "," << SectName
973 uint32_t section_flags;
975 const MachO::section_64 Sec = O->getSection64(Ref);
976 section_flags = Sec.flags;
979 const MachO::section Sec = O->getSection(Ref);
980 section_flags = Sec.flags;
982 uint32_t section_type = section_flags & MachO::SECTION_TYPE;
985 Section.getContents(BytesStr);
986 const char *sect = reinterpret_cast<const char *>(BytesStr.data());
987 uint32_t sect_size = BytesStr.size();
988 uint64_t sect_addr = Section.getAddress();
991 if ((section_flags & MachO::S_ATTR_PURE_INSTRUCTIONS) ||
992 (section_flags & MachO::S_ATTR_SOME_INSTRUCTIONS)) {
993 DisassembleMachO(Filename, O, SegName, SectName);
996 if (SegName == "__TEXT" && SectName == "__info_plist") {
1000 switch (section_type) {
1001 case MachO::S_REGULAR:
1002 DumpRawSectionContents(O, sect, sect_size, sect_addr);
1004 case MachO::S_ZEROFILL:
1005 outs() << "zerofill section and has no contents in the file\n";
1007 case MachO::S_CSTRING_LITERALS:
1008 DumpCstringSection(O, sect, sect_size, sect_addr, verbose);
1010 case MachO::S_4BYTE_LITERALS:
1011 DumpLiteral4Section(O, sect, sect_size, sect_addr, verbose);
1013 case MachO::S_8BYTE_LITERALS:
1014 DumpLiteral8Section(O, sect, sect_size, sect_addr, verbose);
1016 case MachO::S_16BYTE_LITERALS:
1017 DumpLiteral16Section(O, sect, sect_size, sect_addr, verbose);
1019 case MachO::S_LITERAL_POINTERS:
1020 DumpLiteralPointerSection(O, Section, sect, sect_size, sect_addr,
1023 case MachO::S_MOD_INIT_FUNC_POINTERS:
1024 case MachO::S_MOD_TERM_FUNC_POINTERS:
1025 DumpInitTermPointerSection(O, sect, sect_size, sect_addr, &AddrMap,
1029 outs() << "Unknown section type ("
1030 << format("0x%08" PRIx32, section_type) << ")\n";
1031 DumpRawSectionContents(O, sect, sect_size, sect_addr);
1035 if (section_type == MachO::S_ZEROFILL)
1036 outs() << "zerofill section and has no contents in the file\n";
1038 DumpRawSectionContents(O, sect, sect_size, sect_addr);
1045 static void DumpInfoPlistSectionContents(StringRef Filename,
1046 MachOObjectFile *O) {
1047 for (const SectionRef &Section : O->sections()) {
1049 Section.getName(SectName);
1050 DataRefImpl Ref = Section.getRawDataRefImpl();
1051 StringRef SegName = O->getSectionFinalSegmentName(Ref);
1052 if (SegName == "__TEXT" && SectName == "__info_plist") {
1053 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
1055 Section.getContents(BytesStr);
1056 const char *sect = reinterpret_cast<const char *>(BytesStr.data());
1063 // checkMachOAndArchFlags() checks to see if the ObjectFile is a Mach-O file
1064 // and if it is and there is a list of architecture flags is specified then
1065 // check to make sure this Mach-O file is one of those architectures or all
1066 // architectures were specified. If not then an error is generated and this
1067 // routine returns false. Else it returns true.
1068 static bool checkMachOAndArchFlags(ObjectFile *O, StringRef Filename) {
1069 if (isa<MachOObjectFile>(O) && !ArchAll && ArchFlags.size() != 0) {
1070 MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(O);
1071 bool ArchFound = false;
1072 MachO::mach_header H;
1073 MachO::mach_header_64 H_64;
1075 if (MachO->is64Bit()) {
1076 H_64 = MachO->MachOObjectFile::getHeader64();
1077 T = MachOObjectFile::getArch(H_64.cputype, H_64.cpusubtype);
1079 H = MachO->MachOObjectFile::getHeader();
1080 T = MachOObjectFile::getArch(H.cputype, H.cpusubtype);
1083 for (i = 0; i < ArchFlags.size(); ++i) {
1084 if (ArchFlags[i] == T.getArchName())
1089 errs() << "llvm-objdump: file: " + Filename + " does not contain "
1090 << "architecture: " + ArchFlags[i] + "\n";
1097 // ProcessMachO() is passed a single opened Mach-O file, which may be an
1098 // archive member and or in a slice of a universal file. It prints the
1099 // the file name and header info and then processes it according to the
1100 // command line options.
1101 static void ProcessMachO(StringRef Filename, MachOObjectFile *MachOOF,
1102 StringRef ArchiveMemberName = StringRef(),
1103 StringRef ArchitectureName = StringRef()) {
1104 // If we are doing some processing here on the Mach-O file print the header
1105 // info. And don't print it otherwise like in the case of printing the
1106 // UniversalHeaders or ArchiveHeaders.
1107 if (Disassemble || PrivateHeaders || ExportsTrie || Rebase || Bind ||
1108 LazyBind || WeakBind || IndirectSymbols || DataInCode || LinkOptHints ||
1109 DumpSections.size() != 0) {
1111 if (!ArchiveMemberName.empty())
1112 outs() << '(' << ArchiveMemberName << ')';
1113 if (!ArchitectureName.empty())
1114 outs() << " (architecture " << ArchitectureName << ")";
1119 DisassembleMachO(Filename, MachOOF, "__TEXT", "__text");
1120 if (IndirectSymbols)
1121 PrintIndirectSymbols(MachOOF, !NonVerbose);
1123 PrintDataInCodeTable(MachOOF, !NonVerbose);
1125 PrintLinkOptHints(MachOOF);
1127 PrintRelocations(MachOOF);
1129 PrintSectionHeaders(MachOOF);
1130 if (SectionContents)
1131 PrintSectionContents(MachOOF);
1132 if (DumpSections.size() != 0)
1133 DumpSectionContents(Filename, MachOOF, !NonVerbose);
1135 DumpInfoPlistSectionContents(Filename, MachOOF);
1137 PrintSymbolTable(MachOOF);
1139 printMachOUnwindInfo(MachOOF);
1141 printMachOFileHeader(MachOOF);
1143 printExportsTrie(MachOOF);
1145 printRebaseTable(MachOOF);
1147 printBindTable(MachOOF);
1149 printLazyBindTable(MachOOF);
1151 printWeakBindTable(MachOOF);
1154 // printUnknownCPUType() helps print_fat_headers for unknown CPU's.
1155 static void printUnknownCPUType(uint32_t cputype, uint32_t cpusubtype) {
1156 outs() << " cputype (" << cputype << ")\n";
1157 outs() << " cpusubtype (" << cpusubtype << ")\n";
1160 // printCPUType() helps print_fat_headers by printing the cputype and
1161 // pusubtype (symbolically for the one's it knows about).
1162 static void printCPUType(uint32_t cputype, uint32_t cpusubtype) {
1164 case MachO::CPU_TYPE_I386:
1165 switch (cpusubtype) {
1166 case MachO::CPU_SUBTYPE_I386_ALL:
1167 outs() << " cputype CPU_TYPE_I386\n";
1168 outs() << " cpusubtype CPU_SUBTYPE_I386_ALL\n";
1171 printUnknownCPUType(cputype, cpusubtype);
1175 case MachO::CPU_TYPE_X86_64:
1176 switch (cpusubtype) {
1177 case MachO::CPU_SUBTYPE_X86_64_ALL:
1178 outs() << " cputype CPU_TYPE_X86_64\n";
1179 outs() << " cpusubtype CPU_SUBTYPE_X86_64_ALL\n";
1181 case MachO::CPU_SUBTYPE_X86_64_H:
1182 outs() << " cputype CPU_TYPE_X86_64\n";
1183 outs() << " cpusubtype CPU_SUBTYPE_X86_64_H\n";
1186 printUnknownCPUType(cputype, cpusubtype);
1190 case MachO::CPU_TYPE_ARM:
1191 switch (cpusubtype) {
1192 case MachO::CPU_SUBTYPE_ARM_ALL:
1193 outs() << " cputype CPU_TYPE_ARM\n";
1194 outs() << " cpusubtype CPU_SUBTYPE_ARM_ALL\n";
1196 case MachO::CPU_SUBTYPE_ARM_V4T:
1197 outs() << " cputype CPU_TYPE_ARM\n";
1198 outs() << " cpusubtype CPU_SUBTYPE_ARM_V4T\n";
1200 case MachO::CPU_SUBTYPE_ARM_V5TEJ:
1201 outs() << " cputype CPU_TYPE_ARM\n";
1202 outs() << " cpusubtype CPU_SUBTYPE_ARM_V5TEJ\n";
1204 case MachO::CPU_SUBTYPE_ARM_XSCALE:
1205 outs() << " cputype CPU_TYPE_ARM\n";
1206 outs() << " cpusubtype CPU_SUBTYPE_ARM_XSCALE\n";
1208 case MachO::CPU_SUBTYPE_ARM_V6:
1209 outs() << " cputype CPU_TYPE_ARM\n";
1210 outs() << " cpusubtype CPU_SUBTYPE_ARM_V6\n";
1212 case MachO::CPU_SUBTYPE_ARM_V6M:
1213 outs() << " cputype CPU_TYPE_ARM\n";
1214 outs() << " cpusubtype CPU_SUBTYPE_ARM_V6M\n";
1216 case MachO::CPU_SUBTYPE_ARM_V7:
1217 outs() << " cputype CPU_TYPE_ARM\n";
1218 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7\n";
1220 case MachO::CPU_SUBTYPE_ARM_V7EM:
1221 outs() << " cputype CPU_TYPE_ARM\n";
1222 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7EM\n";
1224 case MachO::CPU_SUBTYPE_ARM_V7K:
1225 outs() << " cputype CPU_TYPE_ARM\n";
1226 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7K\n";
1228 case MachO::CPU_SUBTYPE_ARM_V7M:
1229 outs() << " cputype CPU_TYPE_ARM\n";
1230 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7M\n";
1232 case MachO::CPU_SUBTYPE_ARM_V7S:
1233 outs() << " cputype CPU_TYPE_ARM\n";
1234 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7S\n";
1237 printUnknownCPUType(cputype, cpusubtype);
1241 case MachO::CPU_TYPE_ARM64:
1242 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
1243 case MachO::CPU_SUBTYPE_ARM64_ALL:
1244 outs() << " cputype CPU_TYPE_ARM64\n";
1245 outs() << " cpusubtype CPU_SUBTYPE_ARM64_ALL\n";
1248 printUnknownCPUType(cputype, cpusubtype);
1253 printUnknownCPUType(cputype, cpusubtype);
1258 static void printMachOUniversalHeaders(const object::MachOUniversalBinary *UB,
1260 outs() << "Fat headers\n";
1262 outs() << "fat_magic FAT_MAGIC\n";
1264 outs() << "fat_magic " << format("0x%" PRIx32, MachO::FAT_MAGIC) << "\n";
1266 uint32_t nfat_arch = UB->getNumberOfObjects();
1267 StringRef Buf = UB->getData();
1268 uint64_t size = Buf.size();
1269 uint64_t big_size = sizeof(struct MachO::fat_header) +
1270 nfat_arch * sizeof(struct MachO::fat_arch);
1271 outs() << "nfat_arch " << UB->getNumberOfObjects();
1273 outs() << " (malformed, contains zero architecture types)\n";
1274 else if (big_size > size)
1275 outs() << " (malformed, architectures past end of file)\n";
1279 for (uint32_t i = 0; i < nfat_arch; ++i) {
1280 MachOUniversalBinary::ObjectForArch OFA(UB, i);
1281 uint32_t cputype = OFA.getCPUType();
1282 uint32_t cpusubtype = OFA.getCPUSubType();
1283 outs() << "architecture ";
1284 for (uint32_t j = 0; i != 0 && j <= i - 1; j++) {
1285 MachOUniversalBinary::ObjectForArch other_OFA(UB, j);
1286 uint32_t other_cputype = other_OFA.getCPUType();
1287 uint32_t other_cpusubtype = other_OFA.getCPUSubType();
1288 if (cputype != 0 && cpusubtype != 0 && cputype == other_cputype &&
1289 (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) ==
1290 (other_cpusubtype & ~MachO::CPU_SUBTYPE_MASK)) {
1291 outs() << "(illegal duplicate architecture) ";
1296 outs() << OFA.getArchTypeName() << "\n";
1297 printCPUType(cputype, cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
1299 outs() << i << "\n";
1300 outs() << " cputype " << cputype << "\n";
1301 outs() << " cpusubtype " << (cpusubtype & ~MachO::CPU_SUBTYPE_MASK)
1305 (cpusubtype & MachO::CPU_SUBTYPE_MASK) == MachO::CPU_SUBTYPE_LIB64)
1306 outs() << " capabilities CPU_SUBTYPE_LIB64\n";
1308 outs() << " capabilities "
1309 << format("0x%" PRIx32,
1310 (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24) << "\n";
1311 outs() << " offset " << OFA.getOffset();
1312 if (OFA.getOffset() > size)
1313 outs() << " (past end of file)";
1314 if (OFA.getOffset() % (1 << OFA.getAlign()) != 0)
1315 outs() << " (not aligned on it's alignment (2^" << OFA.getAlign() << ")";
1317 outs() << " size " << OFA.getSize();
1318 big_size = OFA.getOffset() + OFA.getSize();
1319 if (big_size > size)
1320 outs() << " (past end of file)";
1322 outs() << " align 2^" << OFA.getAlign() << " (" << (1 << OFA.getAlign())
1327 static void printArchiveChild(Archive::Child &C, bool verbose,
1328 bool print_offset) {
1330 outs() << C.getChildOffset() << "\t";
1331 sys::fs::perms Mode = C.getAccessMode();
1333 // FIXME: this first dash, "-", is for (Mode & S_IFMT) == S_IFREG.
1334 // But there is nothing in sys::fs::perms for S_IFMT or S_IFREG.
1336 if (Mode & sys::fs::owner_read)
1340 if (Mode & sys::fs::owner_write)
1344 if (Mode & sys::fs::owner_exe)
1348 if (Mode & sys::fs::group_read)
1352 if (Mode & sys::fs::group_write)
1356 if (Mode & sys::fs::group_exe)
1360 if (Mode & sys::fs::others_read)
1364 if (Mode & sys::fs::others_write)
1368 if (Mode & sys::fs::others_exe)
1373 outs() << format("0%o ", Mode);
1376 unsigned UID = C.getUID();
1377 outs() << format("%3d/", UID);
1378 unsigned GID = C.getGID();
1379 outs() << format("%-3d ", GID);
1380 uint64_t Size = C.getRawSize();
1381 outs() << format("%5" PRId64, Size) << " ";
1383 StringRef RawLastModified = C.getRawLastModified();
1386 if (RawLastModified.getAsInteger(10, Seconds))
1387 outs() << "(date: \"%s\" contains non-decimal chars) " << RawLastModified;
1389 // Since cime(3) returns a 26 character string of the form:
1390 // "Sun Sep 16 01:03:52 1973\n\0"
1391 // just print 24 characters.
1393 outs() << format("%.24s ", ctime(&t));
1396 outs() << RawLastModified << " ";
1400 ErrorOr<StringRef> NameOrErr = C.getName();
1401 if (NameOrErr.getError()) {
1402 StringRef RawName = C.getRawName();
1403 outs() << RawName << "\n";
1405 StringRef Name = NameOrErr.get();
1406 outs() << Name << "\n";
1409 StringRef RawName = C.getRawName();
1410 outs() << RawName << "\n";
1414 static void printArchiveHeaders(Archive *A, bool verbose, bool print_offset) {
1415 if (A->hasSymbolTable()) {
1416 Archive::child_iterator S = A->getSymbolTableChild();
1417 Archive::Child C = *S;
1418 printArchiveChild(C, verbose, print_offset);
1420 for (Archive::child_iterator I = A->child_begin(), E = A->child_end(); I != E;
1422 Archive::Child C = *I;
1423 printArchiveChild(C, verbose, print_offset);
1427 // ParseInputMachO() parses the named Mach-O file in Filename and handles the
1428 // -arch flags selecting just those slices as specified by them and also parses
1429 // archive files. Then for each individual Mach-O file ProcessMachO() is
1430 // called to process the file based on the command line options.
1431 void llvm::ParseInputMachO(StringRef Filename) {
1432 // Check for -arch all and verifiy the -arch flags are valid.
1433 for (unsigned i = 0; i < ArchFlags.size(); ++i) {
1434 if (ArchFlags[i] == "all") {
1437 if (!MachOObjectFile::isValidArch(ArchFlags[i])) {
1438 errs() << "llvm-objdump: Unknown architecture named '" + ArchFlags[i] +
1439 "'for the -arch option\n";
1445 // Attempt to open the binary.
1446 ErrorOr<OwningBinary<Binary>> BinaryOrErr = createBinary(Filename);
1447 if (std::error_code EC = BinaryOrErr.getError()) {
1448 errs() << "llvm-objdump: '" << Filename << "': " << EC.message() << ".\n";
1451 Binary &Bin = *BinaryOrErr.get().getBinary();
1453 if (Archive *A = dyn_cast<Archive>(&Bin)) {
1454 outs() << "Archive : " << Filename << "\n";
1456 printArchiveHeaders(A, true, false);
1457 for (Archive::child_iterator I = A->child_begin(), E = A->child_end();
1459 ErrorOr<std::unique_ptr<Binary>> ChildOrErr = I->getAsBinary();
1460 if (ChildOrErr.getError())
1462 if (MachOObjectFile *O = dyn_cast<MachOObjectFile>(&*ChildOrErr.get())) {
1463 if (!checkMachOAndArchFlags(O, Filename))
1465 ProcessMachO(Filename, O, O->getFileName());
1470 if (UniversalHeaders) {
1471 if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(&Bin))
1472 printMachOUniversalHeaders(UB, !NonVerbose);
1474 if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(&Bin)) {
1475 // If we have a list of architecture flags specified dump only those.
1476 if (!ArchAll && ArchFlags.size() != 0) {
1477 // Look for a slice in the universal binary that matches each ArchFlag.
1479 for (unsigned i = 0; i < ArchFlags.size(); ++i) {
1481 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
1482 E = UB->end_objects();
1484 if (ArchFlags[i] == I->getArchTypeName()) {
1486 ErrorOr<std::unique_ptr<ObjectFile>> ObjOrErr =
1487 I->getAsObjectFile();
1488 std::string ArchitectureName = "";
1489 if (ArchFlags.size() > 1)
1490 ArchitectureName = I->getArchTypeName();
1492 ObjectFile &O = *ObjOrErr.get();
1493 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&O))
1494 ProcessMachO(Filename, MachOOF, "", ArchitectureName);
1495 } else if (ErrorOr<std::unique_ptr<Archive>> AOrErr =
1496 I->getAsArchive()) {
1497 std::unique_ptr<Archive> &A = *AOrErr;
1498 outs() << "Archive : " << Filename;
1499 if (!ArchitectureName.empty())
1500 outs() << " (architecture " << ArchitectureName << ")";
1503 printArchiveHeaders(A.get(), true, false);
1504 for (Archive::child_iterator AI = A->child_begin(),
1505 AE = A->child_end();
1507 ErrorOr<std::unique_ptr<Binary>> ChildOrErr = AI->getAsBinary();
1508 if (ChildOrErr.getError())
1510 if (MachOObjectFile *O =
1511 dyn_cast<MachOObjectFile>(&*ChildOrErr.get()))
1512 ProcessMachO(Filename, O, O->getFileName(), ArchitectureName);
1518 errs() << "llvm-objdump: file: " + Filename + " does not contain "
1519 << "architecture: " + ArchFlags[i] + "\n";
1525 // No architecture flags were specified so if this contains a slice that
1526 // matches the host architecture dump only that.
1528 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
1529 E = UB->end_objects();
1531 if (MachOObjectFile::getHostArch().getArchName() ==
1532 I->getArchTypeName()) {
1533 ErrorOr<std::unique_ptr<ObjectFile>> ObjOrErr = I->getAsObjectFile();
1534 std::string ArchiveName;
1535 ArchiveName.clear();
1537 ObjectFile &O = *ObjOrErr.get();
1538 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&O))
1539 ProcessMachO(Filename, MachOOF);
1540 } else if (ErrorOr<std::unique_ptr<Archive>> AOrErr =
1541 I->getAsArchive()) {
1542 std::unique_ptr<Archive> &A = *AOrErr;
1543 outs() << "Archive : " << Filename << "\n";
1545 printArchiveHeaders(A.get(), true, false);
1546 for (Archive::child_iterator AI = A->child_begin(),
1547 AE = A->child_end();
1549 ErrorOr<std::unique_ptr<Binary>> ChildOrErr = AI->getAsBinary();
1550 if (ChildOrErr.getError())
1552 if (MachOObjectFile *O =
1553 dyn_cast<MachOObjectFile>(&*ChildOrErr.get()))
1554 ProcessMachO(Filename, O, O->getFileName());
1561 // Either all architectures have been specified or none have been specified
1562 // and this does not contain the host architecture so dump all the slices.
1563 bool moreThanOneArch = UB->getNumberOfObjects() > 1;
1564 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
1565 E = UB->end_objects();
1567 ErrorOr<std::unique_ptr<ObjectFile>> ObjOrErr = I->getAsObjectFile();
1568 std::string ArchitectureName = "";
1569 if (moreThanOneArch)
1570 ArchitectureName = I->getArchTypeName();
1572 ObjectFile &Obj = *ObjOrErr.get();
1573 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&Obj))
1574 ProcessMachO(Filename, MachOOF, "", ArchitectureName);
1575 } else if (ErrorOr<std::unique_ptr<Archive>> AOrErr = 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(), AE = A->child_end();
1585 ErrorOr<std::unique_ptr<Binary>> ChildOrErr = AI->getAsBinary();
1586 if (ChildOrErr.getError())
1588 if (MachOObjectFile *O =
1589 dyn_cast<MachOObjectFile>(&*ChildOrErr.get())) {
1590 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(O))
1591 ProcessMachO(Filename, MachOOF, MachOOF->getFileName(),
1599 if (ObjectFile *O = dyn_cast<ObjectFile>(&Bin)) {
1600 if (!checkMachOAndArchFlags(O, Filename))
1602 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&*O)) {
1603 ProcessMachO(Filename, MachOOF);
1605 errs() << "llvm-objdump: '" << Filename << "': "
1606 << "Object is not a Mach-O file type.\n";
1608 errs() << "llvm-objdump: '" << Filename << "': "
1609 << "Unrecognized file type.\n";
1612 typedef std::pair<uint64_t, const char *> BindInfoEntry;
1613 typedef std::vector<BindInfoEntry> BindTable;
1614 typedef BindTable::iterator bind_table_iterator;
1616 // The block of info used by the Symbolizer call backs.
1617 struct DisassembleInfo {
1621 SymbolAddressMap *AddrMap;
1622 std::vector<SectionRef> *Sections;
1623 const char *class_name;
1624 const char *selector_name;
1626 char *demangled_name;
1629 BindTable *bindtable;
1632 // SymbolizerGetOpInfo() is the operand information call back function.
1633 // This is called to get the symbolic information for operand(s) of an
1634 // instruction when it is being done. This routine does this from
1635 // the relocation information, symbol table, etc. That block of information
1636 // is a pointer to the struct DisassembleInfo that was passed when the
1637 // disassembler context was created and passed to back to here when
1638 // called back by the disassembler for instruction operands that could have
1639 // relocation information. The address of the instruction containing operand is
1640 // at the Pc parameter. The immediate value the operand has is passed in
1641 // op_info->Value and is at Offset past the start of the instruction and has a
1642 // byte Size of 1, 2 or 4. The symbolc information is returned in TagBuf is the
1643 // LLVMOpInfo1 struct defined in the header "llvm-c/Disassembler.h" as symbol
1644 // names and addends of the symbolic expression to add for the operand. The
1645 // value of TagType is currently 1 (for the LLVMOpInfo1 struct). If symbolic
1646 // information is returned then this function returns 1 else it returns 0.
1647 static int SymbolizerGetOpInfo(void *DisInfo, uint64_t Pc, uint64_t Offset,
1648 uint64_t Size, int TagType, void *TagBuf) {
1649 struct DisassembleInfo *info = (struct DisassembleInfo *)DisInfo;
1650 struct LLVMOpInfo1 *op_info = (struct LLVMOpInfo1 *)TagBuf;
1651 uint64_t value = op_info->Value;
1653 // Make sure all fields returned are zero if we don't set them.
1654 memset((void *)op_info, '\0', sizeof(struct LLVMOpInfo1));
1655 op_info->Value = value;
1657 // If the TagType is not the value 1 which it code knows about or if no
1658 // verbose symbolic information is wanted then just return 0, indicating no
1659 // information is being returned.
1660 if (TagType != 1 || info->verbose == false)
1663 unsigned int Arch = info->O->getArch();
1664 if (Arch == Triple::x86) {
1665 if (Size != 1 && Size != 2 && Size != 4 && Size != 0)
1667 // First search the section's relocation entries (if any) for an entry
1668 // for this section offset.
1669 uint32_t sect_addr = info->S.getAddress();
1670 uint32_t sect_offset = (Pc + Offset) - sect_addr;
1671 bool reloc_found = false;
1673 MachO::any_relocation_info RE;
1674 bool isExtern = false;
1676 bool r_scattered = false;
1677 uint32_t r_value, pair_r_value, r_type;
1678 for (const RelocationRef &Reloc : info->S.relocations()) {
1679 uint64_t RelocOffset;
1680 Reloc.getOffset(RelocOffset);
1681 if (RelocOffset == sect_offset) {
1682 Rel = Reloc.getRawDataRefImpl();
1683 RE = info->O->getRelocation(Rel);
1684 r_type = info->O->getAnyRelocationType(RE);
1685 r_scattered = info->O->isRelocationScattered(RE);
1687 r_value = info->O->getScatteredRelocationValue(RE);
1688 if (r_type == MachO::GENERIC_RELOC_SECTDIFF ||
1689 r_type == MachO::GENERIC_RELOC_LOCAL_SECTDIFF) {
1690 DataRefImpl RelNext = Rel;
1691 info->O->moveRelocationNext(RelNext);
1692 MachO::any_relocation_info RENext;
1693 RENext = info->O->getRelocation(RelNext);
1694 if (info->O->isRelocationScattered(RENext))
1695 pair_r_value = info->O->getScatteredRelocationValue(RENext);
1700 isExtern = info->O->getPlainRelocationExternal(RE);
1702 symbol_iterator RelocSym = Reloc.getSymbol();
1710 if (reloc_found && isExtern) {
1712 Symbol.getName(SymName);
1713 const char *name = SymName.data();
1714 op_info->AddSymbol.Present = 1;
1715 op_info->AddSymbol.Name = name;
1716 // For i386 extern relocation entries the value in the instruction is
1717 // the offset from the symbol, and value is already set in op_info->Value.
1720 if (reloc_found && (r_type == MachO::GENERIC_RELOC_SECTDIFF ||
1721 r_type == MachO::GENERIC_RELOC_LOCAL_SECTDIFF)) {
1722 const char *add = GuessSymbolName(r_value, info->AddrMap);
1723 const char *sub = GuessSymbolName(pair_r_value, info->AddrMap);
1724 uint32_t offset = value - (r_value - pair_r_value);
1725 op_info->AddSymbol.Present = 1;
1727 op_info->AddSymbol.Name = add;
1729 op_info->AddSymbol.Value = r_value;
1730 op_info->SubtractSymbol.Present = 1;
1732 op_info->SubtractSymbol.Name = sub;
1734 op_info->SubtractSymbol.Value = pair_r_value;
1735 op_info->Value = offset;
1739 // Second search the external relocation entries of a fully linked image
1740 // (if any) for an entry that matches this segment offset.
1741 // uint32_t seg_offset = (Pc + Offset);
1743 } else if (Arch == Triple::x86_64) {
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 uint64_t sect_addr = info->S.getAddress();
1749 uint64_t sect_offset = (Pc + Offset) - sect_addr;
1750 bool reloc_found = false;
1752 MachO::any_relocation_info RE;
1753 bool isExtern = false;
1755 for (const RelocationRef &Reloc : info->S.relocations()) {
1756 uint64_t RelocOffset;
1757 Reloc.getOffset(RelocOffset);
1758 if (RelocOffset == sect_offset) {
1759 Rel = Reloc.getRawDataRefImpl();
1760 RE = info->O->getRelocation(Rel);
1761 // NOTE: Scattered relocations don't exist on x86_64.
1762 isExtern = info->O->getPlainRelocationExternal(RE);
1764 symbol_iterator RelocSym = Reloc.getSymbol();
1771 if (reloc_found && isExtern) {
1772 // The Value passed in will be adjusted by the Pc if the instruction
1773 // adds the Pc. But for x86_64 external relocation entries the Value
1774 // is the offset from the external symbol.
1775 if (info->O->getAnyRelocationPCRel(RE))
1776 op_info->Value -= Pc + Offset + Size;
1778 Symbol.getName(SymName);
1779 const char *name = SymName.data();
1780 unsigned Type = info->O->getAnyRelocationType(RE);
1781 if (Type == MachO::X86_64_RELOC_SUBTRACTOR) {
1782 DataRefImpl RelNext = Rel;
1783 info->O->moveRelocationNext(RelNext);
1784 MachO::any_relocation_info RENext = info->O->getRelocation(RelNext);
1785 unsigned TypeNext = info->O->getAnyRelocationType(RENext);
1786 bool isExternNext = info->O->getPlainRelocationExternal(RENext);
1787 unsigned SymbolNum = info->O->getPlainRelocationSymbolNum(RENext);
1788 if (TypeNext == MachO::X86_64_RELOC_UNSIGNED && isExternNext) {
1789 op_info->SubtractSymbol.Present = 1;
1790 op_info->SubtractSymbol.Name = name;
1791 symbol_iterator RelocSymNext = info->O->getSymbolByIndex(SymbolNum);
1792 Symbol = *RelocSymNext;
1793 StringRef SymNameNext;
1794 Symbol.getName(SymNameNext);
1795 name = SymNameNext.data();
1798 // TODO: add the VariantKinds to op_info->VariantKind for relocation types
1799 // like: X86_64_RELOC_TLV, X86_64_RELOC_GOT_LOAD and X86_64_RELOC_GOT.
1800 op_info->AddSymbol.Present = 1;
1801 op_info->AddSymbol.Name = name;
1805 // Second search the external relocation entries of a fully linked image
1806 // (if any) for an entry that matches this segment offset.
1807 // uint64_t seg_offset = (Pc + Offset);
1809 } else if (Arch == Triple::arm) {
1810 if (Offset != 0 || (Size != 4 && Size != 2))
1812 // First search the section's relocation entries (if any) for an entry
1813 // for this section offset.
1814 uint32_t sect_addr = info->S.getAddress();
1815 uint32_t sect_offset = (Pc + Offset) - sect_addr;
1816 bool reloc_found = false;
1818 MachO::any_relocation_info RE;
1819 bool isExtern = false;
1821 bool r_scattered = false;
1822 uint32_t r_value, pair_r_value, r_type, r_length, other_half;
1823 for (const RelocationRef &Reloc : info->S.relocations()) {
1824 uint64_t RelocOffset;
1825 Reloc.getOffset(RelocOffset);
1826 if (RelocOffset == sect_offset) {
1827 Rel = Reloc.getRawDataRefImpl();
1828 RE = info->O->getRelocation(Rel);
1829 r_length = info->O->getAnyRelocationLength(RE);
1830 r_scattered = info->O->isRelocationScattered(RE);
1832 r_value = info->O->getScatteredRelocationValue(RE);
1833 r_type = info->O->getScatteredRelocationType(RE);
1835 r_type = info->O->getAnyRelocationType(RE);
1836 isExtern = info->O->getPlainRelocationExternal(RE);
1838 symbol_iterator RelocSym = Reloc.getSymbol();
1842 if (r_type == MachO::ARM_RELOC_HALF ||
1843 r_type == MachO::ARM_RELOC_SECTDIFF ||
1844 r_type == MachO::ARM_RELOC_LOCAL_SECTDIFF ||
1845 r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
1846 DataRefImpl RelNext = Rel;
1847 info->O->moveRelocationNext(RelNext);
1848 MachO::any_relocation_info RENext;
1849 RENext = info->O->getRelocation(RelNext);
1850 other_half = info->O->getAnyRelocationAddress(RENext) & 0xffff;
1851 if (info->O->isRelocationScattered(RENext))
1852 pair_r_value = info->O->getScatteredRelocationValue(RENext);
1858 if (reloc_found && isExtern) {
1860 Symbol.getName(SymName);
1861 const char *name = SymName.data();
1862 op_info->AddSymbol.Present = 1;
1863 op_info->AddSymbol.Name = name;
1865 case MachO::ARM_RELOC_HALF:
1866 if ((r_length & 0x1) == 1) {
1867 op_info->Value = value << 16 | other_half;
1868 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
1870 op_info->Value = other_half << 16 | value;
1871 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
1879 // If we have a branch that is not an external relocation entry then
1880 // return 0 so the code in tryAddingSymbolicOperand() can use the
1881 // SymbolLookUp call back with the branch target address to look up the
1882 // symbol and possiblity add an annotation for a symbol stub.
1883 if (reloc_found && isExtern == 0 && (r_type == MachO::ARM_RELOC_BR24 ||
1884 r_type == MachO::ARM_THUMB_RELOC_BR22))
1887 uint32_t offset = 0;
1889 if (r_type == MachO::ARM_RELOC_HALF ||
1890 r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
1891 if ((r_length & 0x1) == 1)
1892 value = value << 16 | other_half;
1894 value = other_half << 16 | value;
1896 if (r_scattered && (r_type != MachO::ARM_RELOC_HALF &&
1897 r_type != MachO::ARM_RELOC_HALF_SECTDIFF)) {
1898 offset = value - r_value;
1903 if (reloc_found && r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
1904 if ((r_length & 0x1) == 1)
1905 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
1907 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
1908 const char *add = GuessSymbolName(r_value, info->AddrMap);
1909 const char *sub = GuessSymbolName(pair_r_value, info->AddrMap);
1910 int32_t offset = value - (r_value - pair_r_value);
1911 op_info->AddSymbol.Present = 1;
1913 op_info->AddSymbol.Name = add;
1915 op_info->AddSymbol.Value = r_value;
1916 op_info->SubtractSymbol.Present = 1;
1918 op_info->SubtractSymbol.Name = sub;
1920 op_info->SubtractSymbol.Value = pair_r_value;
1921 op_info->Value = offset;
1925 if (reloc_found == false)
1928 op_info->AddSymbol.Present = 1;
1929 op_info->Value = offset;
1931 if (r_type == MachO::ARM_RELOC_HALF) {
1932 if ((r_length & 0x1) == 1)
1933 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
1935 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
1938 const char *add = GuessSymbolName(value, info->AddrMap);
1939 if (add != nullptr) {
1940 op_info->AddSymbol.Name = add;
1943 op_info->AddSymbol.Value = value;
1945 } else if (Arch == Triple::aarch64) {
1946 if (Offset != 0 || Size != 4)
1948 // First search the section's relocation entries (if any) for an entry
1949 // for this section offset.
1950 uint64_t sect_addr = info->S.getAddress();
1951 uint64_t sect_offset = (Pc + Offset) - sect_addr;
1952 bool reloc_found = false;
1954 MachO::any_relocation_info RE;
1955 bool isExtern = false;
1957 uint32_t r_type = 0;
1958 for (const RelocationRef &Reloc : info->S.relocations()) {
1959 uint64_t RelocOffset;
1960 Reloc.getOffset(RelocOffset);
1961 if (RelocOffset == sect_offset) {
1962 Rel = Reloc.getRawDataRefImpl();
1963 RE = info->O->getRelocation(Rel);
1964 r_type = info->O->getAnyRelocationType(RE);
1965 if (r_type == MachO::ARM64_RELOC_ADDEND) {
1966 DataRefImpl RelNext = Rel;
1967 info->O->moveRelocationNext(RelNext);
1968 MachO::any_relocation_info RENext = info->O->getRelocation(RelNext);
1970 value = info->O->getPlainRelocationSymbolNum(RENext);
1971 op_info->Value = value;
1974 // NOTE: Scattered relocations don't exist on arm64.
1975 isExtern = info->O->getPlainRelocationExternal(RE);
1977 symbol_iterator RelocSym = Reloc.getSymbol();
1984 if (reloc_found && isExtern) {
1986 Symbol.getName(SymName);
1987 const char *name = SymName.data();
1988 op_info->AddSymbol.Present = 1;
1989 op_info->AddSymbol.Name = name;
1992 case MachO::ARM64_RELOC_PAGE21:
1994 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_PAGE;
1996 case MachO::ARM64_RELOC_PAGEOFF12:
1998 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_PAGEOFF;
2000 case MachO::ARM64_RELOC_GOT_LOAD_PAGE21:
2002 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_GOTPAGE;
2004 case MachO::ARM64_RELOC_GOT_LOAD_PAGEOFF12:
2006 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_GOTPAGEOFF;
2008 case MachO::ARM64_RELOC_TLVP_LOAD_PAGE21:
2009 /* @tvlppage is not implemented in llvm-mc */
2010 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_TLVP;
2012 case MachO::ARM64_RELOC_TLVP_LOAD_PAGEOFF12:
2013 /* @tvlppageoff is not implemented in llvm-mc */
2014 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_TLVOFF;
2017 case MachO::ARM64_RELOC_BRANCH26:
2018 op_info->VariantKind = LLVMDisassembler_VariantKind_None;
2029 // GuessCstringPointer is passed the address of what might be a pointer to a
2030 // literal string in a cstring section. If that address is in a cstring section
2031 // it returns a pointer to that string. Else it returns nullptr.
2032 static const char *GuessCstringPointer(uint64_t ReferenceValue,
2033 struct DisassembleInfo *info) {
2034 uint32_t LoadCommandCount = info->O->getHeader().ncmds;
2035 MachOObjectFile::LoadCommandInfo Load = info->O->getFirstLoadCommandInfo();
2036 for (unsigned I = 0;; ++I) {
2037 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
2038 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
2039 for (unsigned J = 0; J < Seg.nsects; ++J) {
2040 MachO::section_64 Sec = info->O->getSection64(Load, J);
2041 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
2042 if (section_type == MachO::S_CSTRING_LITERALS &&
2043 ReferenceValue >= Sec.addr &&
2044 ReferenceValue < Sec.addr + Sec.size) {
2045 uint64_t sect_offset = ReferenceValue - Sec.addr;
2046 uint64_t object_offset = Sec.offset + sect_offset;
2047 StringRef MachOContents = info->O->getData();
2048 uint64_t object_size = MachOContents.size();
2049 const char *object_addr = (const char *)MachOContents.data();
2050 if (object_offset < object_size) {
2051 const char *name = object_addr + object_offset;
2058 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
2059 MachO::segment_command Seg = info->O->getSegmentLoadCommand(Load);
2060 for (unsigned J = 0; J < Seg.nsects; ++J) {
2061 MachO::section Sec = info->O->getSection(Load, J);
2062 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
2063 if (section_type == MachO::S_CSTRING_LITERALS &&
2064 ReferenceValue >= Sec.addr &&
2065 ReferenceValue < Sec.addr + Sec.size) {
2066 uint64_t sect_offset = ReferenceValue - Sec.addr;
2067 uint64_t object_offset = Sec.offset + sect_offset;
2068 StringRef MachOContents = info->O->getData();
2069 uint64_t object_size = MachOContents.size();
2070 const char *object_addr = (const char *)MachOContents.data();
2071 if (object_offset < object_size) {
2072 const char *name = object_addr + object_offset;
2080 if (I == LoadCommandCount - 1)
2083 Load = info->O->getNextLoadCommandInfo(Load);
2088 // GuessIndirectSymbol returns the name of the indirect symbol for the
2089 // ReferenceValue passed in or nullptr. This is used when ReferenceValue maybe
2090 // an address of a symbol stub or a lazy or non-lazy pointer to associate the
2091 // symbol name being referenced by the stub or pointer.
2092 static const char *GuessIndirectSymbol(uint64_t ReferenceValue,
2093 struct DisassembleInfo *info) {
2094 uint32_t LoadCommandCount = info->O->getHeader().ncmds;
2095 MachOObjectFile::LoadCommandInfo Load = info->O->getFirstLoadCommandInfo();
2096 MachO::dysymtab_command Dysymtab = info->O->getDysymtabLoadCommand();
2097 MachO::symtab_command Symtab = info->O->getSymtabLoadCommand();
2098 for (unsigned I = 0;; ++I) {
2099 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
2100 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
2101 for (unsigned J = 0; J < Seg.nsects; ++J) {
2102 MachO::section_64 Sec = info->O->getSection64(Load, J);
2103 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
2104 if ((section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
2105 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
2106 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
2107 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
2108 section_type == MachO::S_SYMBOL_STUBS) &&
2109 ReferenceValue >= Sec.addr &&
2110 ReferenceValue < Sec.addr + Sec.size) {
2112 if (section_type == MachO::S_SYMBOL_STUBS)
2113 stride = Sec.reserved2;
2118 uint32_t index = Sec.reserved1 + (ReferenceValue - Sec.addr) / stride;
2119 if (index < Dysymtab.nindirectsyms) {
2120 uint32_t indirect_symbol =
2121 info->O->getIndirectSymbolTableEntry(Dysymtab, index);
2122 if (indirect_symbol < Symtab.nsyms) {
2123 symbol_iterator Sym = info->O->getSymbolByIndex(indirect_symbol);
2124 SymbolRef Symbol = *Sym;
2126 Symbol.getName(SymName);
2127 const char *name = SymName.data();
2133 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
2134 MachO::segment_command Seg = info->O->getSegmentLoadCommand(Load);
2135 for (unsigned J = 0; J < Seg.nsects; ++J) {
2136 MachO::section Sec = info->O->getSection(Load, J);
2137 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
2138 if ((section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
2139 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
2140 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
2141 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
2142 section_type == MachO::S_SYMBOL_STUBS) &&
2143 ReferenceValue >= Sec.addr &&
2144 ReferenceValue < Sec.addr + Sec.size) {
2146 if (section_type == MachO::S_SYMBOL_STUBS)
2147 stride = Sec.reserved2;
2152 uint32_t index = Sec.reserved1 + (ReferenceValue - Sec.addr) / stride;
2153 if (index < Dysymtab.nindirectsyms) {
2154 uint32_t indirect_symbol =
2155 info->O->getIndirectSymbolTableEntry(Dysymtab, index);
2156 if (indirect_symbol < Symtab.nsyms) {
2157 symbol_iterator Sym = info->O->getSymbolByIndex(indirect_symbol);
2158 SymbolRef Symbol = *Sym;
2160 Symbol.getName(SymName);
2161 const char *name = SymName.data();
2168 if (I == LoadCommandCount - 1)
2171 Load = info->O->getNextLoadCommandInfo(Load);
2176 // method_reference() is called passing it the ReferenceName that might be
2177 // a reference it to an Objective-C method call. If so then it allocates and
2178 // assembles a method call string with the values last seen and saved in
2179 // the DisassembleInfo's class_name and selector_name fields. This is saved
2180 // into the method field of the info and any previous string is free'ed.
2181 // Then the class_name field in the info is set to nullptr. The method call
2182 // string is set into ReferenceName and ReferenceType is set to
2183 // LLVMDisassembler_ReferenceType_Out_Objc_Message. If this not a method call
2184 // then both ReferenceType and ReferenceName are left unchanged.
2185 static void method_reference(struct DisassembleInfo *info,
2186 uint64_t *ReferenceType,
2187 const char **ReferenceName) {
2188 unsigned int Arch = info->O->getArch();
2189 if (*ReferenceName != nullptr) {
2190 if (strcmp(*ReferenceName, "_objc_msgSend") == 0) {
2191 if (info->selector_name != nullptr) {
2192 if (info->method != nullptr)
2194 if (info->class_name != nullptr) {
2195 info->method = (char *)malloc(5 + strlen(info->class_name) +
2196 strlen(info->selector_name));
2197 if (info->method != nullptr) {
2198 strcpy(info->method, "+[");
2199 strcat(info->method, info->class_name);
2200 strcat(info->method, " ");
2201 strcat(info->method, info->selector_name);
2202 strcat(info->method, "]");
2203 *ReferenceName = info->method;
2204 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
2207 info->method = (char *)malloc(9 + strlen(info->selector_name));
2208 if (info->method != nullptr) {
2209 if (Arch == Triple::x86_64)
2210 strcpy(info->method, "-[%rdi ");
2211 else if (Arch == Triple::aarch64)
2212 strcpy(info->method, "-[x0 ");
2214 strcpy(info->method, "-[r? ");
2215 strcat(info->method, info->selector_name);
2216 strcat(info->method, "]");
2217 *ReferenceName = info->method;
2218 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
2221 info->class_name = nullptr;
2223 } else if (strcmp(*ReferenceName, "_objc_msgSendSuper2") == 0) {
2224 if (info->selector_name != nullptr) {
2225 if (info->method != nullptr)
2227 info->method = (char *)malloc(17 + strlen(info->selector_name));
2228 if (info->method != nullptr) {
2229 if (Arch == Triple::x86_64)
2230 strcpy(info->method, "-[[%rdi super] ");
2231 else if (Arch == Triple::aarch64)
2232 strcpy(info->method, "-[[x0 super] ");
2234 strcpy(info->method, "-[[r? super] ");
2235 strcat(info->method, info->selector_name);
2236 strcat(info->method, "]");
2237 *ReferenceName = info->method;
2238 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
2240 info->class_name = nullptr;
2246 // GuessPointerPointer() is passed the address of what might be a pointer to
2247 // a reference to an Objective-C class, selector, message ref or cfstring.
2248 // If so the value of the pointer is returned and one of the booleans are set
2249 // to true. If not zero is returned and all the booleans are set to false.
2250 static uint64_t GuessPointerPointer(uint64_t ReferenceValue,
2251 struct DisassembleInfo *info,
2252 bool &classref, bool &selref, bool &msgref,
2258 uint32_t LoadCommandCount = info->O->getHeader().ncmds;
2259 MachOObjectFile::LoadCommandInfo Load = info->O->getFirstLoadCommandInfo();
2260 for (unsigned I = 0;; ++I) {
2261 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
2262 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
2263 for (unsigned J = 0; J < Seg.nsects; ++J) {
2264 MachO::section_64 Sec = info->O->getSection64(Load, J);
2265 if ((strncmp(Sec.sectname, "__objc_selrefs", 16) == 0 ||
2266 strncmp(Sec.sectname, "__objc_classrefs", 16) == 0 ||
2267 strncmp(Sec.sectname, "__objc_superrefs", 16) == 0 ||
2268 strncmp(Sec.sectname, "__objc_msgrefs", 16) == 0 ||
2269 strncmp(Sec.sectname, "__cfstring", 16) == 0) &&
2270 ReferenceValue >= Sec.addr &&
2271 ReferenceValue < Sec.addr + Sec.size) {
2272 uint64_t sect_offset = ReferenceValue - Sec.addr;
2273 uint64_t object_offset = Sec.offset + sect_offset;
2274 StringRef MachOContents = info->O->getData();
2275 uint64_t object_size = MachOContents.size();
2276 const char *object_addr = (const char *)MachOContents.data();
2277 if (object_offset < object_size) {
2278 uint64_t pointer_value;
2279 memcpy(&pointer_value, object_addr + object_offset,
2281 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
2282 sys::swapByteOrder(pointer_value);
2283 if (strncmp(Sec.sectname, "__objc_selrefs", 16) == 0)
2285 else if (strncmp(Sec.sectname, "__objc_classrefs", 16) == 0 ||
2286 strncmp(Sec.sectname, "__objc_superrefs", 16) == 0)
2288 else if (strncmp(Sec.sectname, "__objc_msgrefs", 16) == 0 &&
2289 ReferenceValue + 8 < Sec.addr + Sec.size) {
2291 memcpy(&pointer_value, object_addr + object_offset + 8,
2293 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
2294 sys::swapByteOrder(pointer_value);
2295 } else if (strncmp(Sec.sectname, "__cfstring", 16) == 0)
2297 return pointer_value;
2304 // TODO: Look for LC_SEGMENT for 32-bit Mach-O files.
2305 if (I == LoadCommandCount - 1)
2308 Load = info->O->getNextLoadCommandInfo(Load);
2313 // get_pointer_64 returns a pointer to the bytes in the object file at the
2314 // Address from a section in the Mach-O file. And indirectly returns the
2315 // offset into the section, number of bytes left in the section past the offset
2316 // and which section is was being referenced. If the Address is not in a
2317 // section nullptr is returned.
2318 static const char *get_pointer_64(uint64_t Address, uint32_t &offset,
2319 uint32_t &left, SectionRef &S,
2320 DisassembleInfo *info) {
2324 for (unsigned SectIdx = 0; SectIdx != info->Sections->size(); SectIdx++) {
2325 uint64_t SectAddress = ((*(info->Sections))[SectIdx]).getAddress();
2326 uint64_t SectSize = ((*(info->Sections))[SectIdx]).getSize();
2327 if (Address >= SectAddress && Address < SectAddress + SectSize) {
2328 S = (*(info->Sections))[SectIdx];
2329 offset = Address - SectAddress;
2330 left = SectSize - offset;
2331 StringRef SectContents;
2332 ((*(info->Sections))[SectIdx]).getContents(SectContents);
2333 return SectContents.data() + offset;
2339 // get_symbol_64() returns the name of a symbol (or nullptr) and the address of
2340 // the symbol indirectly through n_value. Based on the relocation information
2341 // for the specified section offset in the specified section reference.
2342 static const char *get_symbol_64(uint32_t sect_offset, SectionRef S,
2343 DisassembleInfo *info, uint64_t &n_value) {
2345 if (info->verbose == false)
2348 // See if there is an external relocation entry at the sect_offset.
2349 bool reloc_found = false;
2351 MachO::any_relocation_info RE;
2352 bool isExtern = false;
2354 for (const RelocationRef &Reloc : S.relocations()) {
2355 uint64_t RelocOffset;
2356 Reloc.getOffset(RelocOffset);
2357 if (RelocOffset == sect_offset) {
2358 Rel = Reloc.getRawDataRefImpl();
2359 RE = info->O->getRelocation(Rel);
2360 if (info->O->isRelocationScattered(RE))
2362 isExtern = info->O->getPlainRelocationExternal(RE);
2364 symbol_iterator RelocSym = Reloc.getSymbol();
2371 // If there is an external relocation entry for a symbol in this section
2372 // at this section_offset then use that symbol's value for the n_value
2373 // and return its name.
2374 const char *SymbolName = nullptr;
2375 if (reloc_found && isExtern) {
2376 Symbol.getAddress(n_value);
2378 Symbol.getName(name);
2379 if (!name.empty()) {
2380 SymbolName = name.data();
2385 // TODO: For fully linked images, look through the external relocation
2386 // entries off the dynamic symtab command. For these the r_offset is from the
2387 // start of the first writeable segment in the Mach-O file. So the offset
2388 // to this section from that segment is passed to this routine by the caller,
2389 // as the database_offset. Which is the difference of the section's starting
2390 // address and the first writable segment.
2392 // NOTE: need add passing the database_offset to this routine.
2394 // TODO: We did not find an external relocation entry so look up the
2395 // ReferenceValue as an address of a symbol and if found return that symbol's
2398 // NOTE: need add passing the ReferenceValue to this routine. Then that code
2399 // would simply be this:
2400 // SymbolName = GuessSymbolName(ReferenceValue, info->AddrMap);
2405 // These are structs in the Objective-C meta data and read to produce the
2406 // comments for disassembly. While these are part of the ABI they are no
2407 // public defintions. So the are here not in include/llvm/Support/MachO.h .
2409 // The cfstring object in a 64-bit Mach-O file.
2410 struct cfstring64_t {
2411 uint64_t isa; // class64_t * (64-bit pointer)
2412 uint64_t flags; // flag bits
2413 uint64_t characters; // char * (64-bit pointer)
2414 uint64_t length; // number of non-NULL characters in above
2417 // The class object in a 64-bit Mach-O file.
2419 uint64_t isa; // class64_t * (64-bit pointer)
2420 uint64_t superclass; // class64_t * (64-bit pointer)
2421 uint64_t cache; // Cache (64-bit pointer)
2422 uint64_t vtable; // IMP * (64-bit pointer)
2423 uint64_t data; // class_ro64_t * (64-bit pointer)
2426 struct class_ro64_t {
2428 uint32_t instanceStart;
2429 uint32_t instanceSize;
2431 uint64_t ivarLayout; // const uint8_t * (64-bit pointer)
2432 uint64_t name; // const char * (64-bit pointer)
2433 uint64_t baseMethods; // const method_list_t * (64-bit pointer)
2434 uint64_t baseProtocols; // const protocol_list_t * (64-bit pointer)
2435 uint64_t ivars; // const ivar_list_t * (64-bit pointer)
2436 uint64_t weakIvarLayout; // const uint8_t * (64-bit pointer)
2437 uint64_t baseProperties; // const struct objc_property_list (64-bit pointer)
2440 inline void swapStruct(struct cfstring64_t &cfs) {
2441 sys::swapByteOrder(cfs.isa);
2442 sys::swapByteOrder(cfs.flags);
2443 sys::swapByteOrder(cfs.characters);
2444 sys::swapByteOrder(cfs.length);
2447 inline void swapStruct(struct class64_t &c) {
2448 sys::swapByteOrder(c.isa);
2449 sys::swapByteOrder(c.superclass);
2450 sys::swapByteOrder(c.cache);
2451 sys::swapByteOrder(c.vtable);
2452 sys::swapByteOrder(c.data);
2455 inline void swapStruct(struct class_ro64_t &cro) {
2456 sys::swapByteOrder(cro.flags);
2457 sys::swapByteOrder(cro.instanceStart);
2458 sys::swapByteOrder(cro.instanceSize);
2459 sys::swapByteOrder(cro.reserved);
2460 sys::swapByteOrder(cro.ivarLayout);
2461 sys::swapByteOrder(cro.name);
2462 sys::swapByteOrder(cro.baseMethods);
2463 sys::swapByteOrder(cro.baseProtocols);
2464 sys::swapByteOrder(cro.ivars);
2465 sys::swapByteOrder(cro.weakIvarLayout);
2466 sys::swapByteOrder(cro.baseProperties);
2469 static const char *get_dyld_bind_info_symbolname(uint64_t ReferenceValue,
2470 struct DisassembleInfo *info);
2472 // get_objc2_64bit_class_name() is used for disassembly and is passed a pointer
2473 // to an Objective-C class and returns the class name. It is also passed the
2474 // address of the pointer, so when the pointer is zero as it can be in an .o
2475 // file, that is used to look for an external relocation entry with a symbol
2477 static const char *get_objc2_64bit_class_name(uint64_t pointer_value,
2478 uint64_t ReferenceValue,
2479 struct DisassembleInfo *info) {
2481 uint32_t offset, left;
2484 // The pointer_value can be 0 in an object file and have a relocation
2485 // entry for the class symbol at the ReferenceValue (the address of the
2487 if (pointer_value == 0) {
2488 r = get_pointer_64(ReferenceValue, offset, left, S, info);
2489 if (r == nullptr || left < sizeof(uint64_t))
2492 const char *symbol_name = get_symbol_64(offset, S, info, n_value);
2493 if (symbol_name == nullptr)
2495 const char *class_name = strrchr(symbol_name, '$');
2496 if (class_name != nullptr && class_name[1] == '_' && class_name[2] != '\0')
2497 return class_name + 2;
2502 // The case were the pointer_value is non-zero and points to a class defined
2503 // in this Mach-O file.
2504 r = get_pointer_64(pointer_value, offset, left, S, info);
2505 if (r == nullptr || left < sizeof(struct class64_t))
2508 memcpy(&c, r, sizeof(struct class64_t));
2509 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
2513 r = get_pointer_64(c.data, offset, left, S, info);
2514 if (r == nullptr || left < sizeof(struct class_ro64_t))
2516 struct class_ro64_t cro;
2517 memcpy(&cro, r, sizeof(struct class_ro64_t));
2518 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
2522 const char *name = get_pointer_64(cro.name, offset, left, S, info);
2526 // get_objc2_64bit_cfstring_name is used for disassembly and is passed a
2527 // pointer to a cfstring and returns its name or nullptr.
2528 static const char *get_objc2_64bit_cfstring_name(uint64_t ReferenceValue,
2529 struct DisassembleInfo *info) {
2530 const char *r, *name;
2531 uint32_t offset, left;
2533 struct cfstring64_t cfs;
2534 uint64_t cfs_characters;
2536 r = get_pointer_64(ReferenceValue, offset, left, S, info);
2537 if (r == nullptr || left < sizeof(struct cfstring64_t))
2539 memcpy(&cfs, r, sizeof(struct cfstring64_t));
2540 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
2542 if (cfs.characters == 0) {
2544 const char *symbol_name = get_symbol_64(
2545 offset + offsetof(struct cfstring64_t, characters), S, info, n_value);
2546 if (symbol_name == nullptr)
2548 cfs_characters = n_value;
2550 cfs_characters = cfs.characters;
2551 name = get_pointer_64(cfs_characters, offset, left, S, info);
2556 // get_objc2_64bit_selref() is used for disassembly and is passed a the address
2557 // of a pointer to an Objective-C selector reference when the pointer value is
2558 // zero as in a .o file and is likely to have a external relocation entry with
2559 // who's symbol's n_value is the real pointer to the selector name. If that is
2560 // the case the real pointer to the selector name is returned else 0 is
2562 static uint64_t get_objc2_64bit_selref(uint64_t ReferenceValue,
2563 struct DisassembleInfo *info) {
2564 uint32_t offset, left;
2567 const char *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)
2577 // GuessLiteralPointer returns a string which for the item in the Mach-O file
2578 // for the address passed in as ReferenceValue for printing as a comment with
2579 // the instruction and also returns the corresponding type of that item
2580 // indirectly through ReferenceType.
2582 // If ReferenceValue is an address of literal cstring then a pointer to the
2583 // cstring is returned and ReferenceType is set to
2584 // LLVMDisassembler_ReferenceType_Out_LitPool_CstrAddr .
2586 // If ReferenceValue is an address of an Objective-C CFString, Selector ref or
2587 // Class ref that name is returned and the ReferenceType is set accordingly.
2589 // Lastly, literals which are Symbol address in a literal pool are looked for
2590 // and if found the symbol name is returned and ReferenceType is set to
2591 // LLVMDisassembler_ReferenceType_Out_LitPool_SymAddr .
2593 // If there is no item in the Mach-O file for the address passed in as
2594 // ReferenceValue nullptr is returned and ReferenceType is unchanged.
2595 static const char *GuessLiteralPointer(uint64_t ReferenceValue,
2596 uint64_t ReferencePC,
2597 uint64_t *ReferenceType,
2598 struct DisassembleInfo *info) {
2599 // First see if there is an external relocation entry at the ReferencePC.
2600 uint64_t sect_addr = info->S.getAddress();
2601 uint64_t sect_offset = ReferencePC - sect_addr;
2602 bool reloc_found = false;
2604 MachO::any_relocation_info RE;
2605 bool isExtern = false;
2607 for (const RelocationRef &Reloc : info->S.relocations()) {
2608 uint64_t RelocOffset;
2609 Reloc.getOffset(RelocOffset);
2610 if (RelocOffset == sect_offset) {
2611 Rel = Reloc.getRawDataRefImpl();
2612 RE = info->O->getRelocation(Rel);
2613 if (info->O->isRelocationScattered(RE))
2615 isExtern = info->O->getPlainRelocationExternal(RE);
2617 symbol_iterator RelocSym = Reloc.getSymbol();
2624 // If there is an external relocation entry for a symbol in a section
2625 // then used that symbol's value for the value of the reference.
2626 if (reloc_found && isExtern) {
2627 if (info->O->getAnyRelocationPCRel(RE)) {
2628 unsigned Type = info->O->getAnyRelocationType(RE);
2629 if (Type == MachO::X86_64_RELOC_SIGNED) {
2630 Symbol.getAddress(ReferenceValue);
2635 // Look for literals such as Objective-C CFStrings refs, Selector refs,
2636 // Message refs and Class refs.
2637 bool classref, selref, msgref, cfstring;
2638 uint64_t pointer_value = GuessPointerPointer(ReferenceValue, info, classref,
2639 selref, msgref, cfstring);
2640 if (classref == true && pointer_value == 0) {
2641 // Note the ReferenceValue is a pointer into the __objc_classrefs section.
2642 // And the pointer_value in that section is typically zero as it will be
2643 // set by dyld as part of the "bind information".
2644 const char *name = get_dyld_bind_info_symbolname(ReferenceValue, info);
2645 if (name != nullptr) {
2646 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Class_Ref;
2647 const char *class_name = strrchr(name, '$');
2648 if (class_name != nullptr && class_name[1] == '_' &&
2649 class_name[2] != '\0') {
2650 info->class_name = class_name + 2;
2656 if (classref == true) {
2657 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Class_Ref;
2659 get_objc2_64bit_class_name(pointer_value, ReferenceValue, info);
2660 if (name != nullptr)
2661 info->class_name = name;
2663 name = "bad class ref";
2667 if (cfstring == true) {
2668 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_CFString_Ref;
2669 const char *name = get_objc2_64bit_cfstring_name(ReferenceValue, info);
2673 if (selref == true && pointer_value == 0)
2674 pointer_value = get_objc2_64bit_selref(ReferenceValue, info);
2676 if (pointer_value != 0)
2677 ReferenceValue = pointer_value;
2679 const char *name = GuessCstringPointer(ReferenceValue, info);
2681 if (pointer_value != 0 && selref == true) {
2682 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Selector_Ref;
2683 info->selector_name = name;
2684 } else if (pointer_value != 0 && msgref == true) {
2685 info->class_name = nullptr;
2686 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message_Ref;
2687 info->selector_name = name;
2689 *ReferenceType = LLVMDisassembler_ReferenceType_Out_LitPool_CstrAddr;
2693 // Lastly look for an indirect symbol with this ReferenceValue which is in
2694 // a literal pool. If found return that symbol name.
2695 name = GuessIndirectSymbol(ReferenceValue, info);
2697 *ReferenceType = LLVMDisassembler_ReferenceType_Out_LitPool_SymAddr;
2704 // SymbolizerSymbolLookUp is the symbol lookup function passed when creating
2705 // the Symbolizer. It looks up the ReferenceValue using the info passed via the
2706 // pointer to the struct DisassembleInfo that was passed when MCSymbolizer
2707 // is created and returns the symbol name that matches the ReferenceValue or
2708 // nullptr if none. The ReferenceType is passed in for the IN type of
2709 // reference the instruction is making from the values in defined in the header
2710 // "llvm-c/Disassembler.h". On return the ReferenceType can set to a specific
2711 // Out type and the ReferenceName will also be set which is added as a comment
2712 // to the disassembled instruction.
2715 // If the symbol name is a C++ mangled name then the demangled name is
2716 // returned through ReferenceName and ReferenceType is set to
2717 // LLVMDisassembler_ReferenceType_DeMangled_Name .
2720 // When this is called to get a symbol name for a branch target then the
2721 // ReferenceType will be LLVMDisassembler_ReferenceType_In_Branch and then
2722 // SymbolValue will be looked for in the indirect symbol table to determine if
2723 // it is an address for a symbol stub. If so then the symbol name for that
2724 // stub is returned indirectly through ReferenceName and then ReferenceType is
2725 // set to LLVMDisassembler_ReferenceType_Out_SymbolStub.
2727 // When this is called with an value loaded via a PC relative load then
2728 // ReferenceType will be LLVMDisassembler_ReferenceType_In_PCrel_Load then the
2729 // SymbolValue is checked to be an address of literal pointer, symbol pointer,
2730 // or an Objective-C meta data reference. If so the output ReferenceType is
2731 // set to correspond to that as well as setting the ReferenceName.
2732 static const char *SymbolizerSymbolLookUp(void *DisInfo,
2733 uint64_t ReferenceValue,
2734 uint64_t *ReferenceType,
2735 uint64_t ReferencePC,
2736 const char **ReferenceName) {
2737 struct DisassembleInfo *info = (struct DisassembleInfo *)DisInfo;
2738 // If no verbose symbolic information is wanted then just return nullptr.
2739 if (info->verbose == false) {
2740 *ReferenceName = nullptr;
2741 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
2745 const char *SymbolName = GuessSymbolName(ReferenceValue, info->AddrMap);
2747 if (*ReferenceType == LLVMDisassembler_ReferenceType_In_Branch) {
2748 *ReferenceName = GuessIndirectSymbol(ReferenceValue, info);
2749 if (*ReferenceName != nullptr) {
2750 method_reference(info, ReferenceType, ReferenceName);
2751 if (*ReferenceType != LLVMDisassembler_ReferenceType_Out_Objc_Message)
2752 *ReferenceType = LLVMDisassembler_ReferenceType_Out_SymbolStub;
2755 if (SymbolName != nullptr && strncmp(SymbolName, "__Z", 3) == 0) {
2756 if (info->demangled_name != nullptr)
2757 free(info->demangled_name);
2759 info->demangled_name =
2760 abi::__cxa_demangle(SymbolName + 1, nullptr, nullptr, &status);
2761 if (info->demangled_name != nullptr) {
2762 *ReferenceName = info->demangled_name;
2763 *ReferenceType = LLVMDisassembler_ReferenceType_DeMangled_Name;
2765 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
2768 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
2769 } else if (*ReferenceType == LLVMDisassembler_ReferenceType_In_PCrel_Load) {
2771 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
2773 method_reference(info, ReferenceType, ReferenceName);
2775 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
2776 // If this is arm64 and the reference is an adrp instruction save the
2777 // instruction, passed in ReferenceValue and the address of the instruction
2778 // for use later if we see and add immediate instruction.
2779 } else if (info->O->getArch() == Triple::aarch64 &&
2780 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADRP) {
2781 info->adrp_inst = ReferenceValue;
2782 info->adrp_addr = ReferencePC;
2783 SymbolName = nullptr;
2784 *ReferenceName = nullptr;
2785 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
2786 // If this is arm64 and reference is an add immediate instruction and we
2788 // seen an adrp instruction just before it and the adrp's Xd register
2790 // this add's Xn register reconstruct the value being referenced and look to
2791 // see if it is a literal pointer. Note the add immediate instruction is
2792 // passed in ReferenceValue.
2793 } else if (info->O->getArch() == Triple::aarch64 &&
2794 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADDXri &&
2795 ReferencePC - 4 == info->adrp_addr &&
2796 (info->adrp_inst & 0x9f000000) == 0x90000000 &&
2797 (info->adrp_inst & 0x1f) == ((ReferenceValue >> 5) & 0x1f)) {
2798 uint32_t addxri_inst;
2799 uint64_t adrp_imm, addxri_imm;
2802 ((info->adrp_inst & 0x00ffffe0) >> 3) | ((info->adrp_inst >> 29) & 0x3);
2803 if (info->adrp_inst & 0x0200000)
2804 adrp_imm |= 0xfffffffffc000000LL;
2806 addxri_inst = ReferenceValue;
2807 addxri_imm = (addxri_inst >> 10) & 0xfff;
2808 if (((addxri_inst >> 22) & 0x3) == 1)
2811 ReferenceValue = (info->adrp_addr & 0xfffffffffffff000LL) +
2812 (adrp_imm << 12) + addxri_imm;
2815 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
2816 if (*ReferenceName == nullptr)
2817 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
2818 // If this is arm64 and the reference is a load register instruction and we
2819 // have seen an adrp instruction just before it and the adrp's Xd register
2820 // matches this add's Xn register reconstruct the value being referenced and
2821 // look to see if it is a literal pointer. Note the load register
2822 // instruction is passed in ReferenceValue.
2823 } else if (info->O->getArch() == Triple::aarch64 &&
2824 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_LDRXui &&
2825 ReferencePC - 4 == info->adrp_addr &&
2826 (info->adrp_inst & 0x9f000000) == 0x90000000 &&
2827 (info->adrp_inst & 0x1f) == ((ReferenceValue >> 5) & 0x1f)) {
2828 uint32_t ldrxui_inst;
2829 uint64_t adrp_imm, ldrxui_imm;
2832 ((info->adrp_inst & 0x00ffffe0) >> 3) | ((info->adrp_inst >> 29) & 0x3);
2833 if (info->adrp_inst & 0x0200000)
2834 adrp_imm |= 0xfffffffffc000000LL;
2836 ldrxui_inst = ReferenceValue;
2837 ldrxui_imm = (ldrxui_inst >> 10) & 0xfff;
2839 ReferenceValue = (info->adrp_addr & 0xfffffffffffff000LL) +
2840 (adrp_imm << 12) + (ldrxui_imm << 3);
2843 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
2844 if (*ReferenceName == nullptr)
2845 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
2847 // If this arm64 and is an load register (PC-relative) instruction the
2848 // ReferenceValue is the PC plus the immediate value.
2849 else if (info->O->getArch() == Triple::aarch64 &&
2850 (*ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_LDRXl ||
2851 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADR)) {
2853 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
2854 if (*ReferenceName == nullptr)
2855 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
2858 else if (SymbolName != nullptr && strncmp(SymbolName, "__Z", 3) == 0) {
2859 if (info->demangled_name != nullptr)
2860 free(info->demangled_name);
2862 info->demangled_name =
2863 abi::__cxa_demangle(SymbolName + 1, nullptr, nullptr, &status);
2864 if (info->demangled_name != nullptr) {
2865 *ReferenceName = info->demangled_name;
2866 *ReferenceType = LLVMDisassembler_ReferenceType_DeMangled_Name;
2871 *ReferenceName = nullptr;
2872 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
2878 /// \brief Emits the comments that are stored in the CommentStream.
2879 /// Each comment in the CommentStream must end with a newline.
2880 static void emitComments(raw_svector_ostream &CommentStream,
2881 SmallString<128> &CommentsToEmit,
2882 formatted_raw_ostream &FormattedOS,
2883 const MCAsmInfo &MAI) {
2884 // Flush the stream before taking its content.
2885 CommentStream.flush();
2886 StringRef Comments = CommentsToEmit.str();
2887 // Get the default information for printing a comment.
2888 const char *CommentBegin = MAI.getCommentString();
2889 unsigned CommentColumn = MAI.getCommentColumn();
2890 bool IsFirst = true;
2891 while (!Comments.empty()) {
2893 FormattedOS << '\n';
2894 // Emit a line of comments.
2895 FormattedOS.PadToColumn(CommentColumn);
2896 size_t Position = Comments.find('\n');
2897 FormattedOS << CommentBegin << ' ' << Comments.substr(0, Position);
2898 // Move after the newline character.
2899 Comments = Comments.substr(Position + 1);
2902 FormattedOS.flush();
2904 // Tell the comment stream that the vector changed underneath it.
2905 CommentsToEmit.clear();
2906 CommentStream.resync();
2909 static void DisassembleMachO(StringRef Filename, MachOObjectFile *MachOOF,
2910 StringRef DisSegName, StringRef DisSectName) {
2911 const char *McpuDefault = nullptr;
2912 const Target *ThumbTarget = nullptr;
2913 const Target *TheTarget = GetTarget(MachOOF, &McpuDefault, &ThumbTarget);
2915 // GetTarget prints out stuff.
2918 if (MCPU.empty() && McpuDefault)
2921 std::unique_ptr<const MCInstrInfo> InstrInfo(TheTarget->createMCInstrInfo());
2922 std::unique_ptr<const MCInstrInfo> ThumbInstrInfo;
2924 ThumbInstrInfo.reset(ThumbTarget->createMCInstrInfo());
2926 // Package up features to be passed to target/subtarget
2927 std::string FeaturesStr;
2928 if (MAttrs.size()) {
2929 SubtargetFeatures Features;
2930 for (unsigned i = 0; i != MAttrs.size(); ++i)
2931 Features.AddFeature(MAttrs[i]);
2932 FeaturesStr = Features.getString();
2935 // Set up disassembler.
2936 std::unique_ptr<const MCRegisterInfo> MRI(
2937 TheTarget->createMCRegInfo(TripleName));
2938 std::unique_ptr<const MCAsmInfo> AsmInfo(
2939 TheTarget->createMCAsmInfo(*MRI, TripleName));
2940 std::unique_ptr<const MCSubtargetInfo> STI(
2941 TheTarget->createMCSubtargetInfo(TripleName, MCPU, FeaturesStr));
2942 MCContext Ctx(AsmInfo.get(), MRI.get(), nullptr);
2943 std::unique_ptr<MCDisassembler> DisAsm(
2944 TheTarget->createMCDisassembler(*STI, Ctx));
2945 std::unique_ptr<MCSymbolizer> Symbolizer;
2946 struct DisassembleInfo SymbolizerInfo;
2947 std::unique_ptr<MCRelocationInfo> RelInfo(
2948 TheTarget->createMCRelocationInfo(TripleName, Ctx));
2950 Symbolizer.reset(TheTarget->createMCSymbolizer(
2951 TripleName, SymbolizerGetOpInfo, SymbolizerSymbolLookUp,
2952 &SymbolizerInfo, &Ctx, std::move(RelInfo)));
2953 DisAsm->setSymbolizer(std::move(Symbolizer));
2955 int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
2956 std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
2957 AsmPrinterVariant, *AsmInfo, *InstrInfo, *MRI, *STI));
2958 // Set the display preference for hex vs. decimal immediates.
2959 IP->setPrintImmHex(PrintImmHex);
2960 // Comment stream and backing vector.
2961 SmallString<128> CommentsToEmit;
2962 raw_svector_ostream CommentStream(CommentsToEmit);
2963 // FIXME: Setting the CommentStream in the InstPrinter is problematic in that
2964 // if it is done then arm64 comments for string literals don't get printed
2965 // and some constant get printed instead and not setting it causes intel
2966 // (32-bit and 64-bit) comments printed with different spacing before the
2967 // comment causing different diffs with the 'C' disassembler library API.
2968 // IP->setCommentStream(CommentStream);
2970 if (!AsmInfo || !STI || !DisAsm || !IP) {
2971 errs() << "error: couldn't initialize disassembler for target "
2972 << TripleName << '\n';
2976 // Set up thumb disassembler.
2977 std::unique_ptr<const MCRegisterInfo> ThumbMRI;
2978 std::unique_ptr<const MCAsmInfo> ThumbAsmInfo;
2979 std::unique_ptr<const MCSubtargetInfo> ThumbSTI;
2980 std::unique_ptr<MCDisassembler> ThumbDisAsm;
2981 std::unique_ptr<MCInstPrinter> ThumbIP;
2982 std::unique_ptr<MCContext> ThumbCtx;
2983 std::unique_ptr<MCSymbolizer> ThumbSymbolizer;
2984 struct DisassembleInfo ThumbSymbolizerInfo;
2985 std::unique_ptr<MCRelocationInfo> ThumbRelInfo;
2987 ThumbMRI.reset(ThumbTarget->createMCRegInfo(ThumbTripleName));
2989 ThumbTarget->createMCAsmInfo(*ThumbMRI, ThumbTripleName));
2991 ThumbTarget->createMCSubtargetInfo(ThumbTripleName, MCPU, FeaturesStr));
2992 ThumbCtx.reset(new MCContext(ThumbAsmInfo.get(), ThumbMRI.get(), nullptr));
2993 ThumbDisAsm.reset(ThumbTarget->createMCDisassembler(*ThumbSTI, *ThumbCtx));
2994 MCContext *PtrThumbCtx = ThumbCtx.get();
2996 ThumbTarget->createMCRelocationInfo(ThumbTripleName, *PtrThumbCtx));
2998 ThumbSymbolizer.reset(ThumbTarget->createMCSymbolizer(
2999 ThumbTripleName, SymbolizerGetOpInfo, SymbolizerSymbolLookUp,
3000 &ThumbSymbolizerInfo, PtrThumbCtx, std::move(ThumbRelInfo)));
3001 ThumbDisAsm->setSymbolizer(std::move(ThumbSymbolizer));
3003 int ThumbAsmPrinterVariant = ThumbAsmInfo->getAssemblerDialect();
3004 ThumbIP.reset(ThumbTarget->createMCInstPrinter(
3005 ThumbAsmPrinterVariant, *ThumbAsmInfo, *ThumbInstrInfo, *ThumbMRI,
3007 // Set the display preference for hex vs. decimal immediates.
3008 ThumbIP->setPrintImmHex(PrintImmHex);
3011 if (ThumbTarget && (!ThumbAsmInfo || !ThumbSTI || !ThumbDisAsm || !ThumbIP)) {
3012 errs() << "error: couldn't initialize disassembler for target "
3013 << ThumbTripleName << '\n';
3017 MachO::mach_header Header = MachOOF->getHeader();
3019 // FIXME: Using the -cfg command line option, this code used to be able to
3020 // annotate relocations with the referenced symbol's name, and if this was
3021 // inside a __[cf]string section, the data it points to. This is now replaced
3022 // by the upcoming MCSymbolizer, which needs the appropriate setup done above.
3023 std::vector<SectionRef> Sections;
3024 std::vector<SymbolRef> Symbols;
3025 SmallVector<uint64_t, 8> FoundFns;
3026 uint64_t BaseSegmentAddress;
3028 getSectionsAndSymbols(Header, MachOOF, Sections, Symbols, FoundFns,
3029 BaseSegmentAddress);
3031 // Sort the symbols by address, just in case they didn't come in that way.
3032 std::sort(Symbols.begin(), Symbols.end(), SymbolSorter());
3034 // Build a data in code table that is sorted on by the address of each entry.
3035 uint64_t BaseAddress = 0;
3036 if (Header.filetype == MachO::MH_OBJECT)
3037 BaseAddress = Sections[0].getAddress();
3039 BaseAddress = BaseSegmentAddress;
3041 for (dice_iterator DI = MachOOF->begin_dices(), DE = MachOOF->end_dices();
3044 DI->getOffset(Offset);
3045 Dices.push_back(std::make_pair(BaseAddress + Offset, *DI));
3047 array_pod_sort(Dices.begin(), Dices.end());
3050 raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls();
3052 raw_ostream &DebugOut = nulls();
3055 std::unique_ptr<DIContext> diContext;
3056 ObjectFile *DbgObj = MachOOF;
3057 // Try to find debug info and set up the DIContext for it.
3059 // A separate DSym file path was specified, parse it as a macho file,
3060 // get the sections and supply it to the section name parsing machinery.
3061 if (!DSYMFile.empty()) {
3062 ErrorOr<std::unique_ptr<MemoryBuffer>> BufOrErr =
3063 MemoryBuffer::getFileOrSTDIN(DSYMFile);
3064 if (std::error_code EC = BufOrErr.getError()) {
3065 errs() << "llvm-objdump: " << Filename << ": " << EC.message() << '\n';
3069 ObjectFile::createMachOObjectFile(BufOrErr.get()->getMemBufferRef())
3074 // Setup the DIContext
3075 diContext.reset(DIContext::getDWARFContext(*DbgObj));
3078 if (DumpSections.size() == 0)
3079 outs() << "(" << DisSegName << "," << DisSectName << ") section\n";
3081 for (unsigned SectIdx = 0; SectIdx != Sections.size(); SectIdx++) {
3083 if (Sections[SectIdx].getName(SectName) || SectName != DisSectName)
3086 DataRefImpl DR = Sections[SectIdx].getRawDataRefImpl();
3088 StringRef SegmentName = MachOOF->getSectionFinalSegmentName(DR);
3089 if (SegmentName != DisSegName)
3093 Sections[SectIdx].getContents(BytesStr);
3094 ArrayRef<uint8_t> Bytes(reinterpret_cast<const uint8_t *>(BytesStr.data()),
3096 uint64_t SectAddress = Sections[SectIdx].getAddress();
3098 bool symbolTableWorked = false;
3100 // Parse relocations.
3101 std::vector<std::pair<uint64_t, SymbolRef>> Relocs;
3102 for (const RelocationRef &Reloc : Sections[SectIdx].relocations()) {
3103 uint64_t RelocOffset;
3104 Reloc.getOffset(RelocOffset);
3105 uint64_t SectionAddress = Sections[SectIdx].getAddress();
3106 RelocOffset -= SectionAddress;
3108 symbol_iterator RelocSym = Reloc.getSymbol();
3110 Relocs.push_back(std::make_pair(RelocOffset, *RelocSym));
3112 array_pod_sort(Relocs.begin(), Relocs.end());
3114 // Create a map of symbol addresses to symbol names for use by
3115 // the SymbolizerSymbolLookUp() routine.
3116 SymbolAddressMap AddrMap;
3117 for (const SymbolRef &Symbol : MachOOF->symbols()) {
3120 if (ST == SymbolRef::ST_Function || ST == SymbolRef::ST_Data ||
3121 ST == SymbolRef::ST_Other) {
3123 Symbol.getAddress(Address);
3125 Symbol.getName(SymName);
3126 AddrMap[Address] = SymName;
3129 // Set up the block of info used by the Symbolizer call backs.
3130 SymbolizerInfo.verbose = true;
3131 SymbolizerInfo.O = MachOOF;
3132 SymbolizerInfo.S = Sections[SectIdx];
3133 SymbolizerInfo.AddrMap = &AddrMap;
3134 SymbolizerInfo.Sections = &Sections;
3135 SymbolizerInfo.class_name = nullptr;
3136 SymbolizerInfo.selector_name = nullptr;
3137 SymbolizerInfo.method = nullptr;
3138 SymbolizerInfo.demangled_name = nullptr;
3139 SymbolizerInfo.bindtable = nullptr;
3140 SymbolizerInfo.adrp_addr = 0;
3141 SymbolizerInfo.adrp_inst = 0;
3142 // Same for the ThumbSymbolizer
3143 ThumbSymbolizerInfo.verbose = true;
3144 ThumbSymbolizerInfo.O = MachOOF;
3145 ThumbSymbolizerInfo.S = Sections[SectIdx];
3146 ThumbSymbolizerInfo.AddrMap = &AddrMap;
3147 ThumbSymbolizerInfo.Sections = &Sections;
3148 ThumbSymbolizerInfo.class_name = nullptr;
3149 ThumbSymbolizerInfo.selector_name = nullptr;
3150 ThumbSymbolizerInfo.method = nullptr;
3151 ThumbSymbolizerInfo.demangled_name = nullptr;
3152 ThumbSymbolizerInfo.bindtable = nullptr;
3153 ThumbSymbolizerInfo.adrp_addr = 0;
3154 ThumbSymbolizerInfo.adrp_inst = 0;
3156 // Disassemble symbol by symbol.
3157 for (unsigned SymIdx = 0; SymIdx != Symbols.size(); SymIdx++) {
3159 Symbols[SymIdx].getName(SymName);
3162 Symbols[SymIdx].getType(ST);
3163 if (ST != SymbolRef::ST_Function)
3166 // Make sure the symbol is defined in this section.
3167 bool containsSym = Sections[SectIdx].containsSymbol(Symbols[SymIdx]);
3171 // Start at the address of the symbol relative to the section's address.
3173 uint64_t SectionAddress = Sections[SectIdx].getAddress();
3174 Symbols[SymIdx].getAddress(Start);
3175 Start -= SectionAddress;
3177 // Stop disassembling either at the beginning of the next symbol or at
3178 // the end of the section.
3179 bool containsNextSym = false;
3180 uint64_t NextSym = 0;
3181 uint64_t NextSymIdx = SymIdx + 1;
3182 while (Symbols.size() > NextSymIdx) {
3183 SymbolRef::Type NextSymType;
3184 Symbols[NextSymIdx].getType(NextSymType);
3185 if (NextSymType == SymbolRef::ST_Function) {
3187 Sections[SectIdx].containsSymbol(Symbols[NextSymIdx]);
3188 Symbols[NextSymIdx].getAddress(NextSym);
3189 NextSym -= SectionAddress;
3195 uint64_t SectSize = Sections[SectIdx].getSize();
3196 uint64_t End = containsNextSym ? NextSym : SectSize;
3199 symbolTableWorked = true;
3201 DataRefImpl Symb = Symbols[SymIdx].getRawDataRefImpl();
3203 (MachOOF->getSymbolFlags(Symb) & SymbolRef::SF_Thumb) && ThumbTarget;
3205 outs() << SymName << ":\n";
3206 DILineInfo lastLine;
3207 for (uint64_t Index = Start; Index < End; Index += Size) {
3210 uint64_t PC = SectAddress + Index;
3211 if (FullLeadingAddr) {
3212 if (MachOOF->is64Bit())
3213 outs() << format("%016" PRIx64, PC);
3215 outs() << format("%08" PRIx64, PC);
3217 outs() << format("%8" PRIx64 ":", PC);
3222 // Check the data in code table here to see if this is data not an
3223 // instruction to be disassembled.
3225 Dice.push_back(std::make_pair(PC, DiceRef()));
3226 dice_table_iterator DTI =
3227 std::search(Dices.begin(), Dices.end(), Dice.begin(), Dice.end(),
3228 compareDiceTableEntries);
3229 if (DTI != Dices.end()) {
3231 DTI->second.getLength(Length);
3233 DTI->second.getKind(Kind);
3234 Size = DumpDataInCode(reinterpret_cast<const char *>(Bytes.data()) +
3237 if ((Kind == MachO::DICE_KIND_JUMP_TABLE8) &&
3238 (PC == (DTI->first + Length - 1)) && (Length & 1))
3243 SmallVector<char, 64> AnnotationsBytes;
3244 raw_svector_ostream Annotations(AnnotationsBytes);
3248 gotInst = ThumbDisAsm->getInstruction(Inst, Size, Bytes.slice(Index),
3249 PC, DebugOut, Annotations);
3251 gotInst = DisAsm->getInstruction(Inst, Size, Bytes.slice(Index), PC,
3252 DebugOut, Annotations);
3254 if (!NoShowRawInsn) {
3255 DumpBytes(StringRef(
3256 reinterpret_cast<const char *>(Bytes.data()) + Index, Size));
3258 formatted_raw_ostream FormattedOS(outs());
3259 Annotations.flush();
3260 StringRef AnnotationsStr = Annotations.str();
3262 ThumbIP->printInst(&Inst, FormattedOS, AnnotationsStr);
3264 IP->printInst(&Inst, FormattedOS, AnnotationsStr);
3265 emitComments(CommentStream, CommentsToEmit, FormattedOS, *AsmInfo);
3267 // Print debug info.
3269 DILineInfo dli = diContext->getLineInfoForAddress(PC);
3270 // Print valid line info if it changed.
3271 if (dli != lastLine && dli.Line != 0)
3272 outs() << "\t## " << dli.FileName << ':' << dli.Line << ':'
3278 unsigned int Arch = MachOOF->getArch();
3279 if (Arch == Triple::x86_64 || Arch == Triple::x86) {
3280 outs() << format("\t.byte 0x%02x #bad opcode\n",
3281 *(Bytes.data() + Index) & 0xff);
3282 Size = 1; // skip exactly one illegible byte and move on.
3283 } else if (Arch == Triple::aarch64) {
3284 uint32_t opcode = (*(Bytes.data() + Index) & 0xff) |
3285 (*(Bytes.data() + Index + 1) & 0xff) << 8 |
3286 (*(Bytes.data() + Index + 2) & 0xff) << 16 |
3287 (*(Bytes.data() + Index + 3) & 0xff) << 24;
3288 outs() << format("\t.long\t0x%08x\n", opcode);
3291 errs() << "llvm-objdump: warning: invalid instruction encoding\n";
3293 Size = 1; // skip illegible bytes
3298 if (!symbolTableWorked) {
3299 // Reading the symbol table didn't work, disassemble the whole section.
3300 uint64_t SectAddress = Sections[SectIdx].getAddress();
3301 uint64_t SectSize = Sections[SectIdx].getSize();
3303 for (uint64_t Index = 0; Index < SectSize; Index += InstSize) {
3306 uint64_t PC = SectAddress + Index;
3307 if (DisAsm->getInstruction(Inst, InstSize, Bytes.slice(Index), PC,
3308 DebugOut, nulls())) {
3309 if (FullLeadingAddr) {
3310 if (MachOOF->is64Bit())
3311 outs() << format("%016" PRIx64, PC);
3313 outs() << format("%08" PRIx64, PC);
3315 outs() << format("%8" PRIx64 ":", PC);
3317 if (!NoShowRawInsn) {
3320 StringRef(reinterpret_cast<const char *>(Bytes.data()) + Index,
3323 IP->printInst(&Inst, outs(), "");
3326 unsigned int Arch = MachOOF->getArch();
3327 if (Arch == Triple::x86_64 || Arch == Triple::x86) {
3328 outs() << format("\t.byte 0x%02x #bad opcode\n",
3329 *(Bytes.data() + Index) & 0xff);
3330 InstSize = 1; // skip exactly one illegible byte and move on.
3332 errs() << "llvm-objdump: warning: invalid instruction encoding\n";
3334 InstSize = 1; // skip illegible bytes
3339 // The TripleName's need to be reset if we are called again for a different
3342 ThumbTripleName = "";
3344 if (SymbolizerInfo.method != nullptr)
3345 free(SymbolizerInfo.method);
3346 if (SymbolizerInfo.demangled_name != nullptr)
3347 free(SymbolizerInfo.demangled_name);
3348 if (SymbolizerInfo.bindtable != nullptr)
3349 delete SymbolizerInfo.bindtable;
3350 if (ThumbSymbolizerInfo.method != nullptr)
3351 free(ThumbSymbolizerInfo.method);
3352 if (ThumbSymbolizerInfo.demangled_name != nullptr)
3353 free(ThumbSymbolizerInfo.demangled_name);
3354 if (ThumbSymbolizerInfo.bindtable != nullptr)
3355 delete ThumbSymbolizerInfo.bindtable;
3359 //===----------------------------------------------------------------------===//
3360 // __compact_unwind section dumping
3361 //===----------------------------------------------------------------------===//
3365 template <typename T> static uint64_t readNext(const char *&Buf) {
3366 using llvm::support::little;
3367 using llvm::support::unaligned;
3369 uint64_t Val = support::endian::read<T, little, unaligned>(Buf);
3374 struct CompactUnwindEntry {
3375 uint32_t OffsetInSection;
3377 uint64_t FunctionAddr;
3379 uint32_t CompactEncoding;
3380 uint64_t PersonalityAddr;
3383 RelocationRef FunctionReloc;
3384 RelocationRef PersonalityReloc;
3385 RelocationRef LSDAReloc;
3387 CompactUnwindEntry(StringRef Contents, unsigned Offset, bool Is64)
3388 : OffsetInSection(Offset) {
3390 read<uint64_t>(Contents.data() + Offset);
3392 read<uint32_t>(Contents.data() + Offset);
3396 template <typename UIntPtr> void read(const char *Buf) {
3397 FunctionAddr = readNext<UIntPtr>(Buf);
3398 Length = readNext<uint32_t>(Buf);
3399 CompactEncoding = readNext<uint32_t>(Buf);
3400 PersonalityAddr = readNext<UIntPtr>(Buf);
3401 LSDAAddr = readNext<UIntPtr>(Buf);
3406 /// Given a relocation from __compact_unwind, consisting of the RelocationRef
3407 /// and data being relocated, determine the best base Name and Addend to use for
3408 /// display purposes.
3410 /// 1. An Extern relocation will directly reference a symbol (and the data is
3411 /// then already an addend), so use that.
3412 /// 2. Otherwise the data is an offset in the object file's layout; try to find
3413 // a symbol before it in the same section, and use the offset from there.
3414 /// 3. Finally, if all that fails, fall back to an offset from the start of the
3415 /// referenced section.
3416 static void findUnwindRelocNameAddend(const MachOObjectFile *Obj,
3417 std::map<uint64_t, SymbolRef> &Symbols,
3418 const RelocationRef &Reloc, uint64_t Addr,
3419 StringRef &Name, uint64_t &Addend) {
3420 if (Reloc.getSymbol() != Obj->symbol_end()) {
3421 Reloc.getSymbol()->getName(Name);
3426 auto RE = Obj->getRelocation(Reloc.getRawDataRefImpl());
3427 SectionRef RelocSection = Obj->getRelocationSection(RE);
3429 uint64_t SectionAddr = RelocSection.getAddress();
3431 auto Sym = Symbols.upper_bound(Addr);
3432 if (Sym == Symbols.begin()) {
3433 // The first symbol in the object is after this reference, the best we can
3434 // do is section-relative notation.
3435 RelocSection.getName(Name);
3436 Addend = Addr - SectionAddr;
3440 // Go back one so that SymbolAddress <= Addr.
3443 section_iterator SymSection = Obj->section_end();
3444 Sym->second.getSection(SymSection);
3445 if (RelocSection == *SymSection) {
3446 // There's a valid symbol in the same section before this reference.
3447 Sym->second.getName(Name);
3448 Addend = Addr - Sym->first;
3452 // There is a symbol before this reference, but it's in a different
3453 // section. Probably not helpful to mention it, so use the section name.
3454 RelocSection.getName(Name);
3455 Addend = Addr - SectionAddr;
3458 static void printUnwindRelocDest(const MachOObjectFile *Obj,
3459 std::map<uint64_t, SymbolRef> &Symbols,
3460 const RelocationRef &Reloc, uint64_t Addr) {
3464 if (!Reloc.getObjectFile())
3467 findUnwindRelocNameAddend(Obj, Symbols, Reloc, Addr, Name, Addend);
3471 outs() << " + " << format("0x%" PRIx64, Addend);
3475 printMachOCompactUnwindSection(const MachOObjectFile *Obj,
3476 std::map<uint64_t, SymbolRef> &Symbols,
3477 const SectionRef &CompactUnwind) {
3479 assert(Obj->isLittleEndian() &&
3480 "There should not be a big-endian .o with __compact_unwind");
3482 bool Is64 = Obj->is64Bit();
3483 uint32_t PointerSize = Is64 ? sizeof(uint64_t) : sizeof(uint32_t);
3484 uint32_t EntrySize = 3 * PointerSize + 2 * sizeof(uint32_t);
3487 CompactUnwind.getContents(Contents);
3489 SmallVector<CompactUnwindEntry, 4> CompactUnwinds;
3491 // First populate the initial raw offsets, encodings and so on from the entry.
3492 for (unsigned Offset = 0; Offset < Contents.size(); Offset += EntrySize) {
3493 CompactUnwindEntry Entry(Contents.data(), Offset, Is64);
3494 CompactUnwinds.push_back(Entry);
3497 // Next we need to look at the relocations to find out what objects are
3498 // actually being referred to.
3499 for (const RelocationRef &Reloc : CompactUnwind.relocations()) {
3500 uint64_t RelocAddress;
3501 Reloc.getOffset(RelocAddress);
3503 uint32_t EntryIdx = RelocAddress / EntrySize;
3504 uint32_t OffsetInEntry = RelocAddress - EntryIdx * EntrySize;
3505 CompactUnwindEntry &Entry = CompactUnwinds[EntryIdx];
3507 if (OffsetInEntry == 0)
3508 Entry.FunctionReloc = Reloc;
3509 else if (OffsetInEntry == PointerSize + 2 * sizeof(uint32_t))
3510 Entry.PersonalityReloc = Reloc;
3511 else if (OffsetInEntry == 2 * PointerSize + 2 * sizeof(uint32_t))
3512 Entry.LSDAReloc = Reloc;
3514 llvm_unreachable("Unexpected relocation in __compact_unwind section");
3517 // Finally, we're ready to print the data we've gathered.
3518 outs() << "Contents of __compact_unwind section:\n";
3519 for (auto &Entry : CompactUnwinds) {
3520 outs() << " Entry at offset "
3521 << format("0x%" PRIx32, Entry.OffsetInSection) << ":\n";
3523 // 1. Start of the region this entry applies to.
3524 outs() << " start: " << format("0x%" PRIx64,
3525 Entry.FunctionAddr) << ' ';
3526 printUnwindRelocDest(Obj, Symbols, Entry.FunctionReloc, Entry.FunctionAddr);
3529 // 2. Length of the region this entry applies to.
3530 outs() << " length: " << format("0x%" PRIx32, Entry.Length)
3532 // 3. The 32-bit compact encoding.
3533 outs() << " compact encoding: "
3534 << format("0x%08" PRIx32, Entry.CompactEncoding) << '\n';
3536 // 4. The personality function, if present.
3537 if (Entry.PersonalityReloc.getObjectFile()) {
3538 outs() << " personality function: "
3539 << format("0x%" PRIx64, Entry.PersonalityAddr) << ' ';
3540 printUnwindRelocDest(Obj, Symbols, Entry.PersonalityReloc,
3541 Entry.PersonalityAddr);
3545 // 5. This entry's language-specific data area.
3546 if (Entry.LSDAReloc.getObjectFile()) {
3547 outs() << " LSDA: " << format("0x%" PRIx64,
3548 Entry.LSDAAddr) << ' ';
3549 printUnwindRelocDest(Obj, Symbols, Entry.LSDAReloc, Entry.LSDAAddr);
3555 //===----------------------------------------------------------------------===//
3556 // __unwind_info section dumping
3557 //===----------------------------------------------------------------------===//
3559 static void printRegularSecondLevelUnwindPage(const char *PageStart) {
3560 const char *Pos = PageStart;
3561 uint32_t Kind = readNext<uint32_t>(Pos);
3563 assert(Kind == 2 && "kind for a regular 2nd level index should be 2");
3565 uint16_t EntriesStart = readNext<uint16_t>(Pos);
3566 uint16_t NumEntries = readNext<uint16_t>(Pos);
3568 Pos = PageStart + EntriesStart;
3569 for (unsigned i = 0; i < NumEntries; ++i) {
3570 uint32_t FunctionOffset = readNext<uint32_t>(Pos);
3571 uint32_t Encoding = readNext<uint32_t>(Pos);
3573 outs() << " [" << i << "]: "
3574 << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
3576 << "encoding=" << format("0x%08" PRIx32, Encoding) << '\n';
3580 static void printCompressedSecondLevelUnwindPage(
3581 const char *PageStart, uint32_t FunctionBase,
3582 const SmallVectorImpl<uint32_t> &CommonEncodings) {
3583 const char *Pos = PageStart;
3584 uint32_t Kind = readNext<uint32_t>(Pos);
3586 assert(Kind == 3 && "kind for a compressed 2nd level index should be 3");
3588 uint16_t EntriesStart = readNext<uint16_t>(Pos);
3589 uint16_t NumEntries = readNext<uint16_t>(Pos);
3591 uint16_t EncodingsStart = readNext<uint16_t>(Pos);
3592 readNext<uint16_t>(Pos);
3593 const auto *PageEncodings = reinterpret_cast<const support::ulittle32_t *>(
3594 PageStart + EncodingsStart);
3596 Pos = PageStart + EntriesStart;
3597 for (unsigned i = 0; i < NumEntries; ++i) {
3598 uint32_t Entry = readNext<uint32_t>(Pos);
3599 uint32_t FunctionOffset = FunctionBase + (Entry & 0xffffff);
3600 uint32_t EncodingIdx = Entry >> 24;
3603 if (EncodingIdx < CommonEncodings.size())
3604 Encoding = CommonEncodings[EncodingIdx];
3606 Encoding = PageEncodings[EncodingIdx - CommonEncodings.size()];
3608 outs() << " [" << i << "]: "
3609 << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
3611 << "encoding[" << EncodingIdx
3612 << "]=" << format("0x%08" PRIx32, Encoding) << '\n';
3616 static void printMachOUnwindInfoSection(const MachOObjectFile *Obj,
3617 std::map<uint64_t, SymbolRef> &Symbols,
3618 const SectionRef &UnwindInfo) {
3620 assert(Obj->isLittleEndian() &&
3621 "There should not be a big-endian .o with __unwind_info");
3623 outs() << "Contents of __unwind_info section:\n";
3626 UnwindInfo.getContents(Contents);
3627 const char *Pos = Contents.data();
3629 //===----------------------------------
3631 //===----------------------------------
3633 uint32_t Version = readNext<uint32_t>(Pos);
3634 outs() << " Version: "
3635 << format("0x%" PRIx32, Version) << '\n';
3636 assert(Version == 1 && "only understand version 1");
3638 uint32_t CommonEncodingsStart = readNext<uint32_t>(Pos);
3639 outs() << " Common encodings array section offset: "
3640 << format("0x%" PRIx32, CommonEncodingsStart) << '\n';
3641 uint32_t NumCommonEncodings = readNext<uint32_t>(Pos);
3642 outs() << " Number of common encodings in array: "
3643 << format("0x%" PRIx32, NumCommonEncodings) << '\n';
3645 uint32_t PersonalitiesStart = readNext<uint32_t>(Pos);
3646 outs() << " Personality function array section offset: "
3647 << format("0x%" PRIx32, PersonalitiesStart) << '\n';
3648 uint32_t NumPersonalities = readNext<uint32_t>(Pos);
3649 outs() << " Number of personality functions in array: "
3650 << format("0x%" PRIx32, NumPersonalities) << '\n';
3652 uint32_t IndicesStart = readNext<uint32_t>(Pos);
3653 outs() << " Index array section offset: "
3654 << format("0x%" PRIx32, IndicesStart) << '\n';
3655 uint32_t NumIndices = readNext<uint32_t>(Pos);
3656 outs() << " Number of indices in array: "
3657 << format("0x%" PRIx32, NumIndices) << '\n';
3659 //===----------------------------------
3660 // A shared list of common encodings
3661 //===----------------------------------
3663 // These occupy indices in the range [0, N] whenever an encoding is referenced
3664 // from a compressed 2nd level index table. In practice the linker only
3665 // creates ~128 of these, so that indices are available to embed encodings in
3666 // the 2nd level index.
3668 SmallVector<uint32_t, 64> CommonEncodings;
3669 outs() << " Common encodings: (count = " << NumCommonEncodings << ")\n";
3670 Pos = Contents.data() + CommonEncodingsStart;
3671 for (unsigned i = 0; i < NumCommonEncodings; ++i) {
3672 uint32_t Encoding = readNext<uint32_t>(Pos);
3673 CommonEncodings.push_back(Encoding);
3675 outs() << " encoding[" << i << "]: " << format("0x%08" PRIx32, Encoding)
3679 //===----------------------------------
3680 // Personality functions used in this executable
3681 //===----------------------------------
3683 // There should be only a handful of these (one per source language,
3684 // roughly). Particularly since they only get 2 bits in the compact encoding.
3686 outs() << " Personality functions: (count = " << NumPersonalities << ")\n";
3687 Pos = Contents.data() + PersonalitiesStart;
3688 for (unsigned i = 0; i < NumPersonalities; ++i) {
3689 uint32_t PersonalityFn = readNext<uint32_t>(Pos);
3690 outs() << " personality[" << i + 1
3691 << "]: " << format("0x%08" PRIx32, PersonalityFn) << '\n';
3694 //===----------------------------------
3695 // The level 1 index entries
3696 //===----------------------------------
3698 // These specify an approximate place to start searching for the more detailed
3699 // information, sorted by PC.
3702 uint32_t FunctionOffset;
3703 uint32_t SecondLevelPageStart;
3707 SmallVector<IndexEntry, 4> IndexEntries;
3709 outs() << " Top level indices: (count = " << NumIndices << ")\n";
3710 Pos = Contents.data() + IndicesStart;
3711 for (unsigned i = 0; i < NumIndices; ++i) {
3714 Entry.FunctionOffset = readNext<uint32_t>(Pos);
3715 Entry.SecondLevelPageStart = readNext<uint32_t>(Pos);
3716 Entry.LSDAStart = readNext<uint32_t>(Pos);
3717 IndexEntries.push_back(Entry);
3719 outs() << " [" << i << "]: "
3720 << "function offset=" << format("0x%08" PRIx32, Entry.FunctionOffset)
3722 << "2nd level page offset="
3723 << format("0x%08" PRIx32, Entry.SecondLevelPageStart) << ", "
3724 << "LSDA offset=" << format("0x%08" PRIx32, Entry.LSDAStart) << '\n';
3727 //===----------------------------------
3728 // Next come the LSDA tables
3729 //===----------------------------------
3731 // The LSDA layout is rather implicit: it's a contiguous array of entries from
3732 // the first top-level index's LSDAOffset to the last (sentinel).
3734 outs() << " LSDA descriptors:\n";
3735 Pos = Contents.data() + IndexEntries[0].LSDAStart;
3736 int NumLSDAs = (IndexEntries.back().LSDAStart - IndexEntries[0].LSDAStart) /
3737 (2 * sizeof(uint32_t));
3738 for (int i = 0; i < NumLSDAs; ++i) {
3739 uint32_t FunctionOffset = readNext<uint32_t>(Pos);
3740 uint32_t LSDAOffset = readNext<uint32_t>(Pos);
3741 outs() << " [" << i << "]: "
3742 << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
3744 << "LSDA offset=" << format("0x%08" PRIx32, LSDAOffset) << '\n';
3747 //===----------------------------------
3748 // Finally, the 2nd level indices
3749 //===----------------------------------
3751 // Generally these are 4K in size, and have 2 possible forms:
3752 // + Regular stores up to 511 entries with disparate encodings
3753 // + Compressed stores up to 1021 entries if few enough compact encoding
3755 outs() << " Second level indices:\n";
3756 for (unsigned i = 0; i < IndexEntries.size() - 1; ++i) {
3757 // The final sentinel top-level index has no associated 2nd level page
3758 if (IndexEntries[i].SecondLevelPageStart == 0)
3761 outs() << " Second level index[" << i << "]: "
3762 << "offset in section="
3763 << format("0x%08" PRIx32, IndexEntries[i].SecondLevelPageStart)
3765 << "base function offset="
3766 << format("0x%08" PRIx32, IndexEntries[i].FunctionOffset) << '\n';
3768 Pos = Contents.data() + IndexEntries[i].SecondLevelPageStart;
3769 uint32_t Kind = *reinterpret_cast<const support::ulittle32_t *>(Pos);
3771 printRegularSecondLevelUnwindPage(Pos);
3773 printCompressedSecondLevelUnwindPage(Pos, IndexEntries[i].FunctionOffset,
3776 llvm_unreachable("Do not know how to print this kind of 2nd level page");
3780 void llvm::printMachOUnwindInfo(const MachOObjectFile *Obj) {
3781 std::map<uint64_t, SymbolRef> Symbols;
3782 for (const SymbolRef &SymRef : Obj->symbols()) {
3783 // Discard any undefined or absolute symbols. They're not going to take part
3784 // in the convenience lookup for unwind info and just take up resources.
3785 section_iterator Section = Obj->section_end();
3786 SymRef.getSection(Section);
3787 if (Section == Obj->section_end())
3791 SymRef.getAddress(Addr);
3792 Symbols.insert(std::make_pair(Addr, SymRef));
3795 for (const SectionRef &Section : Obj->sections()) {
3797 Section.getName(SectName);
3798 if (SectName == "__compact_unwind")
3799 printMachOCompactUnwindSection(Obj, Symbols, Section);
3800 else if (SectName == "__unwind_info")
3801 printMachOUnwindInfoSection(Obj, Symbols, Section);
3802 else if (SectName == "__eh_frame")
3803 outs() << "llvm-objdump: warning: unhandled __eh_frame section\n";
3807 static void PrintMachHeader(uint32_t magic, uint32_t cputype,
3808 uint32_t cpusubtype, uint32_t filetype,
3809 uint32_t ncmds, uint32_t sizeofcmds, uint32_t flags,
3811 outs() << "Mach header\n";
3812 outs() << " magic cputype cpusubtype caps filetype ncmds "
3813 "sizeofcmds flags\n";
3815 if (magic == MachO::MH_MAGIC)
3816 outs() << " MH_MAGIC";
3817 else if (magic == MachO::MH_MAGIC_64)
3818 outs() << "MH_MAGIC_64";
3820 outs() << format(" 0x%08" PRIx32, magic);
3822 case MachO::CPU_TYPE_I386:
3824 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
3825 case MachO::CPU_SUBTYPE_I386_ALL:
3829 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
3833 case MachO::CPU_TYPE_X86_64:
3834 outs() << " X86_64";
3835 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
3836 case MachO::CPU_SUBTYPE_X86_64_ALL:
3839 case MachO::CPU_SUBTYPE_X86_64_H:
3840 outs() << " Haswell";
3843 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
3847 case MachO::CPU_TYPE_ARM:
3849 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
3850 case MachO::CPU_SUBTYPE_ARM_ALL:
3853 case MachO::CPU_SUBTYPE_ARM_V4T:
3856 case MachO::CPU_SUBTYPE_ARM_V5TEJ:
3859 case MachO::CPU_SUBTYPE_ARM_XSCALE:
3860 outs() << " XSCALE";
3862 case MachO::CPU_SUBTYPE_ARM_V6:
3865 case MachO::CPU_SUBTYPE_ARM_V6M:
3868 case MachO::CPU_SUBTYPE_ARM_V7:
3871 case MachO::CPU_SUBTYPE_ARM_V7EM:
3874 case MachO::CPU_SUBTYPE_ARM_V7K:
3877 case MachO::CPU_SUBTYPE_ARM_V7M:
3880 case MachO::CPU_SUBTYPE_ARM_V7S:
3884 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
3888 case MachO::CPU_TYPE_ARM64:
3890 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
3891 case MachO::CPU_SUBTYPE_ARM64_ALL:
3895 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
3899 case MachO::CPU_TYPE_POWERPC:
3901 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
3902 case MachO::CPU_SUBTYPE_POWERPC_ALL:
3906 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
3910 case MachO::CPU_TYPE_POWERPC64:
3912 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
3913 case MachO::CPU_SUBTYPE_POWERPC_ALL:
3917 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
3922 if ((cpusubtype & MachO::CPU_SUBTYPE_MASK) == MachO::CPU_SUBTYPE_LIB64) {
3925 outs() << format(" 0x%02" PRIx32,
3926 (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24);
3929 case MachO::MH_OBJECT:
3930 outs() << " OBJECT";
3932 case MachO::MH_EXECUTE:
3933 outs() << " EXECUTE";
3935 case MachO::MH_FVMLIB:
3936 outs() << " FVMLIB";
3938 case MachO::MH_CORE:
3941 case MachO::MH_PRELOAD:
3942 outs() << " PRELOAD";
3944 case MachO::MH_DYLIB:
3947 case MachO::MH_DYLIB_STUB:
3948 outs() << " DYLIB_STUB";
3950 case MachO::MH_DYLINKER:
3951 outs() << " DYLINKER";
3953 case MachO::MH_BUNDLE:
3954 outs() << " BUNDLE";
3956 case MachO::MH_DSYM:
3959 case MachO::MH_KEXT_BUNDLE:
3960 outs() << " KEXTBUNDLE";
3963 outs() << format(" %10u", filetype);
3966 outs() << format(" %5u", ncmds);
3967 outs() << format(" %10u", sizeofcmds);
3969 if (f & MachO::MH_NOUNDEFS) {
3970 outs() << " NOUNDEFS";
3971 f &= ~MachO::MH_NOUNDEFS;
3973 if (f & MachO::MH_INCRLINK) {
3974 outs() << " INCRLINK";
3975 f &= ~MachO::MH_INCRLINK;
3977 if (f & MachO::MH_DYLDLINK) {
3978 outs() << " DYLDLINK";
3979 f &= ~MachO::MH_DYLDLINK;
3981 if (f & MachO::MH_BINDATLOAD) {
3982 outs() << " BINDATLOAD";
3983 f &= ~MachO::MH_BINDATLOAD;
3985 if (f & MachO::MH_PREBOUND) {
3986 outs() << " PREBOUND";
3987 f &= ~MachO::MH_PREBOUND;
3989 if (f & MachO::MH_SPLIT_SEGS) {
3990 outs() << " SPLIT_SEGS";
3991 f &= ~MachO::MH_SPLIT_SEGS;
3993 if (f & MachO::MH_LAZY_INIT) {
3994 outs() << " LAZY_INIT";
3995 f &= ~MachO::MH_LAZY_INIT;
3997 if (f & MachO::MH_TWOLEVEL) {
3998 outs() << " TWOLEVEL";
3999 f &= ~MachO::MH_TWOLEVEL;
4001 if (f & MachO::MH_FORCE_FLAT) {
4002 outs() << " FORCE_FLAT";
4003 f &= ~MachO::MH_FORCE_FLAT;
4005 if (f & MachO::MH_NOMULTIDEFS) {
4006 outs() << " NOMULTIDEFS";
4007 f &= ~MachO::MH_NOMULTIDEFS;
4009 if (f & MachO::MH_NOFIXPREBINDING) {
4010 outs() << " NOFIXPREBINDING";
4011 f &= ~MachO::MH_NOFIXPREBINDING;
4013 if (f & MachO::MH_PREBINDABLE) {
4014 outs() << " PREBINDABLE";
4015 f &= ~MachO::MH_PREBINDABLE;
4017 if (f & MachO::MH_ALLMODSBOUND) {
4018 outs() << " ALLMODSBOUND";
4019 f &= ~MachO::MH_ALLMODSBOUND;
4021 if (f & MachO::MH_SUBSECTIONS_VIA_SYMBOLS) {
4022 outs() << " SUBSECTIONS_VIA_SYMBOLS";
4023 f &= ~MachO::MH_SUBSECTIONS_VIA_SYMBOLS;
4025 if (f & MachO::MH_CANONICAL) {
4026 outs() << " CANONICAL";
4027 f &= ~MachO::MH_CANONICAL;
4029 if (f & MachO::MH_WEAK_DEFINES) {
4030 outs() << " WEAK_DEFINES";
4031 f &= ~MachO::MH_WEAK_DEFINES;
4033 if (f & MachO::MH_BINDS_TO_WEAK) {
4034 outs() << " BINDS_TO_WEAK";
4035 f &= ~MachO::MH_BINDS_TO_WEAK;
4037 if (f & MachO::MH_ALLOW_STACK_EXECUTION) {
4038 outs() << " ALLOW_STACK_EXECUTION";
4039 f &= ~MachO::MH_ALLOW_STACK_EXECUTION;
4041 if (f & MachO::MH_DEAD_STRIPPABLE_DYLIB) {
4042 outs() << " DEAD_STRIPPABLE_DYLIB";
4043 f &= ~MachO::MH_DEAD_STRIPPABLE_DYLIB;
4045 if (f & MachO::MH_PIE) {
4047 f &= ~MachO::MH_PIE;
4049 if (f & MachO::MH_NO_REEXPORTED_DYLIBS) {
4050 outs() << " NO_REEXPORTED_DYLIBS";
4051 f &= ~MachO::MH_NO_REEXPORTED_DYLIBS;
4053 if (f & MachO::MH_HAS_TLV_DESCRIPTORS) {
4054 outs() << " MH_HAS_TLV_DESCRIPTORS";
4055 f &= ~MachO::MH_HAS_TLV_DESCRIPTORS;
4057 if (f & MachO::MH_NO_HEAP_EXECUTION) {
4058 outs() << " MH_NO_HEAP_EXECUTION";
4059 f &= ~MachO::MH_NO_HEAP_EXECUTION;
4061 if (f & MachO::MH_APP_EXTENSION_SAFE) {
4062 outs() << " APP_EXTENSION_SAFE";
4063 f &= ~MachO::MH_APP_EXTENSION_SAFE;
4065 if (f != 0 || flags == 0)
4066 outs() << format(" 0x%08" PRIx32, f);
4068 outs() << format(" 0x%08" PRIx32, magic);
4069 outs() << format(" %7d", cputype);
4070 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
4071 outs() << format(" 0x%02" PRIx32,
4072 (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24);
4073 outs() << format(" %10u", filetype);
4074 outs() << format(" %5u", ncmds);
4075 outs() << format(" %10u", sizeofcmds);
4076 outs() << format(" 0x%08" PRIx32, flags);
4081 static void PrintSegmentCommand(uint32_t cmd, uint32_t cmdsize,
4082 StringRef SegName, uint64_t vmaddr,
4083 uint64_t vmsize, uint64_t fileoff,
4084 uint64_t filesize, uint32_t maxprot,
4085 uint32_t initprot, uint32_t nsects,
4086 uint32_t flags, uint32_t object_size,
4088 uint64_t expected_cmdsize;
4089 if (cmd == MachO::LC_SEGMENT) {
4090 outs() << " cmd LC_SEGMENT\n";
4091 expected_cmdsize = nsects;
4092 expected_cmdsize *= sizeof(struct MachO::section);
4093 expected_cmdsize += sizeof(struct MachO::segment_command);
4095 outs() << " cmd LC_SEGMENT_64\n";
4096 expected_cmdsize = nsects;
4097 expected_cmdsize *= sizeof(struct MachO::section_64);
4098 expected_cmdsize += sizeof(struct MachO::segment_command_64);
4100 outs() << " cmdsize " << cmdsize;
4101 if (cmdsize != expected_cmdsize)
4102 outs() << " Inconsistent size\n";
4105 outs() << " segname " << SegName << "\n";
4106 if (cmd == MachO::LC_SEGMENT_64) {
4107 outs() << " vmaddr " << format("0x%016" PRIx64, vmaddr) << "\n";
4108 outs() << " vmsize " << format("0x%016" PRIx64, vmsize) << "\n";
4110 outs() << " vmaddr " << format("0x%08" PRIx64, vmaddr) << "\n";
4111 outs() << " vmsize " << format("0x%08" PRIx64, vmsize) << "\n";
4113 outs() << " fileoff " << fileoff;
4114 if (fileoff > object_size)
4115 outs() << " (past end of file)\n";
4118 outs() << " filesize " << filesize;
4119 if (fileoff + filesize > object_size)
4120 outs() << " (past end of file)\n";
4125 ~(MachO::VM_PROT_READ | MachO::VM_PROT_WRITE |
4126 MachO::VM_PROT_EXECUTE)) != 0)
4127 outs() << " maxprot ?" << format("0x%08" PRIx32, maxprot) << "\n";
4129 if (maxprot & MachO::VM_PROT_READ)
4130 outs() << " maxprot r";
4132 outs() << " maxprot -";
4133 if (maxprot & MachO::VM_PROT_WRITE)
4137 if (maxprot & MachO::VM_PROT_EXECUTE)
4143 ~(MachO::VM_PROT_READ | MachO::VM_PROT_WRITE |
4144 MachO::VM_PROT_EXECUTE)) != 0)
4145 outs() << " initprot ?" << format("0x%08" PRIx32, initprot) << "\n";
4147 if (initprot & MachO::VM_PROT_READ)
4148 outs() << " initprot r";
4150 outs() << " initprot -";
4151 if (initprot & MachO::VM_PROT_WRITE)
4155 if (initprot & MachO::VM_PROT_EXECUTE)
4161 outs() << " maxprot " << format("0x%08" PRIx32, maxprot) << "\n";
4162 outs() << " initprot " << format("0x%08" PRIx32, initprot) << "\n";
4164 outs() << " nsects " << nsects << "\n";
4168 outs() << " (none)\n";
4170 if (flags & MachO::SG_HIGHVM) {
4171 outs() << " HIGHVM";
4172 flags &= ~MachO::SG_HIGHVM;
4174 if (flags & MachO::SG_FVMLIB) {
4175 outs() << " FVMLIB";
4176 flags &= ~MachO::SG_FVMLIB;
4178 if (flags & MachO::SG_NORELOC) {
4179 outs() << " NORELOC";
4180 flags &= ~MachO::SG_NORELOC;
4182 if (flags & MachO::SG_PROTECTED_VERSION_1) {
4183 outs() << " PROTECTED_VERSION_1";
4184 flags &= ~MachO::SG_PROTECTED_VERSION_1;
4187 outs() << format(" 0x%08" PRIx32, flags) << " (unknown flags)\n";
4192 outs() << " flags " << format("0x%" PRIx32, flags) << "\n";
4196 static void PrintSection(const char *sectname, const char *segname,
4197 uint64_t addr, uint64_t size, uint32_t offset,
4198 uint32_t align, uint32_t reloff, uint32_t nreloc,
4199 uint32_t flags, uint32_t reserved1, uint32_t reserved2,
4200 uint32_t cmd, const char *sg_segname,
4201 uint32_t filetype, uint32_t object_size,
4203 outs() << "Section\n";
4204 outs() << " sectname " << format("%.16s\n", sectname);
4205 outs() << " segname " << format("%.16s", segname);
4206 if (filetype != MachO::MH_OBJECT && strncmp(sg_segname, segname, 16) != 0)
4207 outs() << " (does not match segment)\n";
4210 if (cmd == MachO::LC_SEGMENT_64) {
4211 outs() << " addr " << format("0x%016" PRIx64, addr) << "\n";
4212 outs() << " size " << format("0x%016" PRIx64, size);
4214 outs() << " addr " << format("0x%08" PRIx64, addr) << "\n";
4215 outs() << " size " << format("0x%08" PRIx64, size);
4217 if ((flags & MachO::S_ZEROFILL) != 0 && offset + size > object_size)
4218 outs() << " (past end of file)\n";
4221 outs() << " offset " << offset;
4222 if (offset > object_size)
4223 outs() << " (past end of file)\n";
4226 uint32_t align_shifted = 1 << align;
4227 outs() << " align 2^" << align << " (" << align_shifted << ")\n";
4228 outs() << " reloff " << reloff;
4229 if (reloff > object_size)
4230 outs() << " (past end of file)\n";
4233 outs() << " nreloc " << nreloc;
4234 if (reloff + nreloc * sizeof(struct MachO::relocation_info) > object_size)
4235 outs() << " (past end of file)\n";
4238 uint32_t section_type = flags & MachO::SECTION_TYPE;
4241 if (section_type == MachO::S_REGULAR)
4242 outs() << " S_REGULAR\n";
4243 else if (section_type == MachO::S_ZEROFILL)
4244 outs() << " S_ZEROFILL\n";
4245 else if (section_type == MachO::S_CSTRING_LITERALS)
4246 outs() << " S_CSTRING_LITERALS\n";
4247 else if (section_type == MachO::S_4BYTE_LITERALS)
4248 outs() << " S_4BYTE_LITERALS\n";
4249 else if (section_type == MachO::S_8BYTE_LITERALS)
4250 outs() << " S_8BYTE_LITERALS\n";
4251 else if (section_type == MachO::S_16BYTE_LITERALS)
4252 outs() << " S_16BYTE_LITERALS\n";
4253 else if (section_type == MachO::S_LITERAL_POINTERS)
4254 outs() << " S_LITERAL_POINTERS\n";
4255 else if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS)
4256 outs() << " S_NON_LAZY_SYMBOL_POINTERS\n";
4257 else if (section_type == MachO::S_LAZY_SYMBOL_POINTERS)
4258 outs() << " S_LAZY_SYMBOL_POINTERS\n";
4259 else if (section_type == MachO::S_SYMBOL_STUBS)
4260 outs() << " S_SYMBOL_STUBS\n";
4261 else if (section_type == MachO::S_MOD_INIT_FUNC_POINTERS)
4262 outs() << " S_MOD_INIT_FUNC_POINTERS\n";
4263 else if (section_type == MachO::S_MOD_TERM_FUNC_POINTERS)
4264 outs() << " S_MOD_TERM_FUNC_POINTERS\n";
4265 else if (section_type == MachO::S_COALESCED)
4266 outs() << " S_COALESCED\n";
4267 else if (section_type == MachO::S_INTERPOSING)
4268 outs() << " S_INTERPOSING\n";
4269 else if (section_type == MachO::S_DTRACE_DOF)
4270 outs() << " S_DTRACE_DOF\n";
4271 else if (section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS)
4272 outs() << " S_LAZY_DYLIB_SYMBOL_POINTERS\n";
4273 else if (section_type == MachO::S_THREAD_LOCAL_REGULAR)
4274 outs() << " S_THREAD_LOCAL_REGULAR\n";
4275 else if (section_type == MachO::S_THREAD_LOCAL_ZEROFILL)
4276 outs() << " S_THREAD_LOCAL_ZEROFILL\n";
4277 else if (section_type == MachO::S_THREAD_LOCAL_VARIABLES)
4278 outs() << " S_THREAD_LOCAL_VARIABLES\n";
4279 else if (section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS)
4280 outs() << " S_THREAD_LOCAL_VARIABLE_POINTERS\n";
4281 else if (section_type == MachO::S_THREAD_LOCAL_INIT_FUNCTION_POINTERS)
4282 outs() << " S_THREAD_LOCAL_INIT_FUNCTION_POINTERS\n";
4284 outs() << format("0x%08" PRIx32, section_type) << "\n";
4285 outs() << "attributes";
4286 uint32_t section_attributes = flags & MachO::SECTION_ATTRIBUTES;
4287 if (section_attributes & MachO::S_ATTR_PURE_INSTRUCTIONS)
4288 outs() << " PURE_INSTRUCTIONS";
4289 if (section_attributes & MachO::S_ATTR_NO_TOC)
4290 outs() << " NO_TOC";
4291 if (section_attributes & MachO::S_ATTR_STRIP_STATIC_SYMS)
4292 outs() << " STRIP_STATIC_SYMS";
4293 if (section_attributes & MachO::S_ATTR_NO_DEAD_STRIP)
4294 outs() << " NO_DEAD_STRIP";
4295 if (section_attributes & MachO::S_ATTR_LIVE_SUPPORT)
4296 outs() << " LIVE_SUPPORT";
4297 if (section_attributes & MachO::S_ATTR_SELF_MODIFYING_CODE)
4298 outs() << " SELF_MODIFYING_CODE";
4299 if (section_attributes & MachO::S_ATTR_DEBUG)
4301 if (section_attributes & MachO::S_ATTR_SOME_INSTRUCTIONS)
4302 outs() << " SOME_INSTRUCTIONS";
4303 if (section_attributes & MachO::S_ATTR_EXT_RELOC)
4304 outs() << " EXT_RELOC";
4305 if (section_attributes & MachO::S_ATTR_LOC_RELOC)
4306 outs() << " LOC_RELOC";
4307 if (section_attributes == 0)
4308 outs() << " (none)";
4311 outs() << " flags " << format("0x%08" PRIx32, flags) << "\n";
4312 outs() << " reserved1 " << reserved1;
4313 if (section_type == MachO::S_SYMBOL_STUBS ||
4314 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
4315 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
4316 section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
4317 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS)
4318 outs() << " (index into indirect symbol table)\n";
4321 outs() << " reserved2 " << reserved2;
4322 if (section_type == MachO::S_SYMBOL_STUBS)
4323 outs() << " (size of stubs)\n";
4328 static void PrintSymtabLoadCommand(MachO::symtab_command st, bool Is64Bit,
4329 uint32_t object_size) {
4330 outs() << " cmd LC_SYMTAB\n";
4331 outs() << " cmdsize " << st.cmdsize;
4332 if (st.cmdsize != sizeof(struct MachO::symtab_command))
4333 outs() << " Incorrect size\n";
4336 outs() << " symoff " << st.symoff;
4337 if (st.symoff > object_size)
4338 outs() << " (past end of file)\n";
4341 outs() << " nsyms " << st.nsyms;
4344 big_size = st.nsyms;
4345 big_size *= sizeof(struct MachO::nlist_64);
4346 big_size += st.symoff;
4347 if (big_size > object_size)
4348 outs() << " (past end of file)\n";
4352 big_size = st.nsyms;
4353 big_size *= sizeof(struct MachO::nlist);
4354 big_size += st.symoff;
4355 if (big_size > object_size)
4356 outs() << " (past end of file)\n";
4360 outs() << " stroff " << st.stroff;
4361 if (st.stroff > object_size)
4362 outs() << " (past end of file)\n";
4365 outs() << " strsize " << st.strsize;
4366 big_size = st.stroff;
4367 big_size += st.strsize;
4368 if (big_size > object_size)
4369 outs() << " (past end of file)\n";
4374 static void PrintDysymtabLoadCommand(MachO::dysymtab_command dyst,
4375 uint32_t nsyms, uint32_t object_size,
4377 outs() << " cmd LC_DYSYMTAB\n";
4378 outs() << " cmdsize " << dyst.cmdsize;
4379 if (dyst.cmdsize != sizeof(struct MachO::dysymtab_command))
4380 outs() << " Incorrect size\n";
4383 outs() << " ilocalsym " << dyst.ilocalsym;
4384 if (dyst.ilocalsym > nsyms)
4385 outs() << " (greater than the number of symbols)\n";
4388 outs() << " nlocalsym " << dyst.nlocalsym;
4390 big_size = dyst.ilocalsym;
4391 big_size += dyst.nlocalsym;
4392 if (big_size > nsyms)
4393 outs() << " (past the end of the symbol table)\n";
4396 outs() << " iextdefsym " << dyst.iextdefsym;
4397 if (dyst.iextdefsym > nsyms)
4398 outs() << " (greater than the number of symbols)\n";
4401 outs() << " nextdefsym " << dyst.nextdefsym;
4402 big_size = dyst.iextdefsym;
4403 big_size += dyst.nextdefsym;
4404 if (big_size > nsyms)
4405 outs() << " (past the end of the symbol table)\n";
4408 outs() << " iundefsym " << dyst.iundefsym;
4409 if (dyst.iundefsym > nsyms)
4410 outs() << " (greater than the number of symbols)\n";
4413 outs() << " nundefsym " << dyst.nundefsym;
4414 big_size = dyst.iundefsym;
4415 big_size += dyst.nundefsym;
4416 if (big_size > nsyms)
4417 outs() << " (past the end of the symbol table)\n";
4420 outs() << " tocoff " << dyst.tocoff;
4421 if (dyst.tocoff > object_size)
4422 outs() << " (past end of file)\n";
4425 outs() << " ntoc " << dyst.ntoc;
4426 big_size = dyst.ntoc;
4427 big_size *= sizeof(struct MachO::dylib_table_of_contents);
4428 big_size += dyst.tocoff;
4429 if (big_size > object_size)
4430 outs() << " (past end of file)\n";
4433 outs() << " modtaboff " << dyst.modtaboff;
4434 if (dyst.modtaboff > object_size)
4435 outs() << " (past end of file)\n";
4438 outs() << " nmodtab " << dyst.nmodtab;
4441 modtabend = dyst.nmodtab;
4442 modtabend *= sizeof(struct MachO::dylib_module_64);
4443 modtabend += dyst.modtaboff;
4445 modtabend = dyst.nmodtab;
4446 modtabend *= sizeof(struct MachO::dylib_module);
4447 modtabend += dyst.modtaboff;
4449 if (modtabend > object_size)
4450 outs() << " (past end of file)\n";
4453 outs() << " extrefsymoff " << dyst.extrefsymoff;
4454 if (dyst.extrefsymoff > object_size)
4455 outs() << " (past end of file)\n";
4458 outs() << " nextrefsyms " << dyst.nextrefsyms;
4459 big_size = dyst.nextrefsyms;
4460 big_size *= sizeof(struct MachO::dylib_reference);
4461 big_size += dyst.extrefsymoff;
4462 if (big_size > object_size)
4463 outs() << " (past end of file)\n";
4466 outs() << " indirectsymoff " << dyst.indirectsymoff;
4467 if (dyst.indirectsymoff > object_size)
4468 outs() << " (past end of file)\n";
4471 outs() << " nindirectsyms " << dyst.nindirectsyms;
4472 big_size = dyst.nindirectsyms;
4473 big_size *= sizeof(uint32_t);
4474 big_size += dyst.indirectsymoff;
4475 if (big_size > object_size)
4476 outs() << " (past end of file)\n";
4479 outs() << " extreloff " << dyst.extreloff;
4480 if (dyst.extreloff > object_size)
4481 outs() << " (past end of file)\n";
4484 outs() << " nextrel " << dyst.nextrel;
4485 big_size = dyst.nextrel;
4486 big_size *= sizeof(struct MachO::relocation_info);
4487 big_size += dyst.extreloff;
4488 if (big_size > object_size)
4489 outs() << " (past end of file)\n";
4492 outs() << " locreloff " << dyst.locreloff;
4493 if (dyst.locreloff > object_size)
4494 outs() << " (past end of file)\n";
4497 outs() << " nlocrel " << dyst.nlocrel;
4498 big_size = dyst.nlocrel;
4499 big_size *= sizeof(struct MachO::relocation_info);
4500 big_size += dyst.locreloff;
4501 if (big_size > object_size)
4502 outs() << " (past end of file)\n";
4507 static void PrintDyldInfoLoadCommand(MachO::dyld_info_command dc,
4508 uint32_t object_size) {
4509 if (dc.cmd == MachO::LC_DYLD_INFO)
4510 outs() << " cmd LC_DYLD_INFO\n";
4512 outs() << " cmd LC_DYLD_INFO_ONLY\n";
4513 outs() << " cmdsize " << dc.cmdsize;
4514 if (dc.cmdsize != sizeof(struct MachO::dyld_info_command))
4515 outs() << " Incorrect size\n";
4518 outs() << " rebase_off " << dc.rebase_off;
4519 if (dc.rebase_off > object_size)
4520 outs() << " (past end of file)\n";
4523 outs() << " rebase_size " << dc.rebase_size;
4525 big_size = dc.rebase_off;
4526 big_size += dc.rebase_size;
4527 if (big_size > object_size)
4528 outs() << " (past end of file)\n";
4531 outs() << " bind_off " << dc.bind_off;
4532 if (dc.bind_off > object_size)
4533 outs() << " (past end of file)\n";
4536 outs() << " bind_size " << dc.bind_size;
4537 big_size = dc.bind_off;
4538 big_size += dc.bind_size;
4539 if (big_size > object_size)
4540 outs() << " (past end of file)\n";
4543 outs() << " weak_bind_off " << dc.weak_bind_off;
4544 if (dc.weak_bind_off > object_size)
4545 outs() << " (past end of file)\n";
4548 outs() << " weak_bind_size " << dc.weak_bind_size;
4549 big_size = dc.weak_bind_off;
4550 big_size += dc.weak_bind_size;
4551 if (big_size > object_size)
4552 outs() << " (past end of file)\n";
4555 outs() << " lazy_bind_off " << dc.lazy_bind_off;
4556 if (dc.lazy_bind_off > object_size)
4557 outs() << " (past end of file)\n";
4560 outs() << " lazy_bind_size " << dc.lazy_bind_size;
4561 big_size = dc.lazy_bind_off;
4562 big_size += dc.lazy_bind_size;
4563 if (big_size > object_size)
4564 outs() << " (past end of file)\n";
4567 outs() << " export_off " << dc.export_off;
4568 if (dc.export_off > object_size)
4569 outs() << " (past end of file)\n";
4572 outs() << " export_size " << dc.export_size;
4573 big_size = dc.export_off;
4574 big_size += dc.export_size;
4575 if (big_size > object_size)
4576 outs() << " (past end of file)\n";
4581 static void PrintDyldLoadCommand(MachO::dylinker_command dyld,
4583 if (dyld.cmd == MachO::LC_ID_DYLINKER)
4584 outs() << " cmd LC_ID_DYLINKER\n";
4585 else if (dyld.cmd == MachO::LC_LOAD_DYLINKER)
4586 outs() << " cmd LC_LOAD_DYLINKER\n";
4587 else if (dyld.cmd == MachO::LC_DYLD_ENVIRONMENT)
4588 outs() << " cmd LC_DYLD_ENVIRONMENT\n";
4590 outs() << " cmd ?(" << dyld.cmd << ")\n";
4591 outs() << " cmdsize " << dyld.cmdsize;
4592 if (dyld.cmdsize < sizeof(struct MachO::dylinker_command))
4593 outs() << " Incorrect size\n";
4596 if (dyld.name >= dyld.cmdsize)
4597 outs() << " name ?(bad offset " << dyld.name << ")\n";
4599 const char *P = (const char *)(Ptr) + dyld.name;
4600 outs() << " name " << P << " (offset " << dyld.name << ")\n";
4604 static void PrintUuidLoadCommand(MachO::uuid_command uuid) {
4605 outs() << " cmd LC_UUID\n";
4606 outs() << " cmdsize " << uuid.cmdsize;
4607 if (uuid.cmdsize != sizeof(struct MachO::uuid_command))
4608 outs() << " Incorrect size\n";
4612 outs() << format("%02" PRIX32, uuid.uuid[0]);
4613 outs() << format("%02" PRIX32, uuid.uuid[1]);
4614 outs() << format("%02" PRIX32, uuid.uuid[2]);
4615 outs() << format("%02" PRIX32, uuid.uuid[3]);
4617 outs() << format("%02" PRIX32, uuid.uuid[4]);
4618 outs() << format("%02" PRIX32, uuid.uuid[5]);
4620 outs() << format("%02" PRIX32, uuid.uuid[6]);
4621 outs() << format("%02" PRIX32, uuid.uuid[7]);
4623 outs() << format("%02" PRIX32, uuid.uuid[8]);
4624 outs() << format("%02" PRIX32, uuid.uuid[9]);
4626 outs() << format("%02" PRIX32, uuid.uuid[10]);
4627 outs() << format("%02" PRIX32, uuid.uuid[11]);
4628 outs() << format("%02" PRIX32, uuid.uuid[12]);
4629 outs() << format("%02" PRIX32, uuid.uuid[13]);
4630 outs() << format("%02" PRIX32, uuid.uuid[14]);
4631 outs() << format("%02" PRIX32, uuid.uuid[15]);
4635 static void PrintRpathLoadCommand(MachO::rpath_command rpath, const char *Ptr) {
4636 outs() << " cmd LC_RPATH\n";
4637 outs() << " cmdsize " << rpath.cmdsize;
4638 if (rpath.cmdsize < sizeof(struct MachO::rpath_command))
4639 outs() << " Incorrect size\n";
4642 if (rpath.path >= rpath.cmdsize)
4643 outs() << " path ?(bad offset " << rpath.path << ")\n";
4645 const char *P = (const char *)(Ptr) + rpath.path;
4646 outs() << " path " << P << " (offset " << rpath.path << ")\n";
4650 static void PrintVersionMinLoadCommand(MachO::version_min_command vd) {
4651 if (vd.cmd == MachO::LC_VERSION_MIN_MACOSX)
4652 outs() << " cmd LC_VERSION_MIN_MACOSX\n";
4653 else if (vd.cmd == MachO::LC_VERSION_MIN_IPHONEOS)
4654 outs() << " cmd LC_VERSION_MIN_IPHONEOS\n";
4656 outs() << " cmd " << vd.cmd << " (?)\n";
4657 outs() << " cmdsize " << vd.cmdsize;
4658 if (vd.cmdsize != sizeof(struct MachO::version_min_command))
4659 outs() << " Incorrect size\n";
4662 outs() << " version " << ((vd.version >> 16) & 0xffff) << "."
4663 << ((vd.version >> 8) & 0xff);
4664 if ((vd.version & 0xff) != 0)
4665 outs() << "." << (vd.version & 0xff);
4668 outs() << " sdk n/a";
4670 outs() << " sdk " << ((vd.sdk >> 16) & 0xffff) << "."
4671 << ((vd.sdk >> 8) & 0xff);
4673 if ((vd.sdk & 0xff) != 0)
4674 outs() << "." << (vd.sdk & 0xff);
4678 static void PrintSourceVersionCommand(MachO::source_version_command sd) {
4679 outs() << " cmd LC_SOURCE_VERSION\n";
4680 outs() << " cmdsize " << sd.cmdsize;
4681 if (sd.cmdsize != sizeof(struct MachO::source_version_command))
4682 outs() << " Incorrect size\n";
4685 uint64_t a = (sd.version >> 40) & 0xffffff;
4686 uint64_t b = (sd.version >> 30) & 0x3ff;
4687 uint64_t c = (sd.version >> 20) & 0x3ff;
4688 uint64_t d = (sd.version >> 10) & 0x3ff;
4689 uint64_t e = sd.version & 0x3ff;
4690 outs() << " version " << a << "." << b;
4692 outs() << "." << c << "." << d << "." << e;
4694 outs() << "." << c << "." << d;
4700 static void PrintEntryPointCommand(MachO::entry_point_command ep) {
4701 outs() << " cmd LC_MAIN\n";
4702 outs() << " cmdsize " << ep.cmdsize;
4703 if (ep.cmdsize != sizeof(struct MachO::entry_point_command))
4704 outs() << " Incorrect size\n";
4707 outs() << " entryoff " << ep.entryoff << "\n";
4708 outs() << " stacksize " << ep.stacksize << "\n";
4711 static void PrintEncryptionInfoCommand(MachO::encryption_info_command ec,
4712 uint32_t object_size) {
4713 outs() << " cmd LC_ENCRYPTION_INFO\n";
4714 outs() << " cmdsize " << ec.cmdsize;
4715 if (ec.cmdsize != sizeof(struct MachO::encryption_info_command))
4716 outs() << " Incorrect size\n";
4719 outs() << " cryptoff " << ec.cryptoff;
4720 if (ec.cryptoff > object_size)
4721 outs() << " (past end of file)\n";
4724 outs() << " cryptsize " << ec.cryptsize;
4725 if (ec.cryptsize > object_size)
4726 outs() << " (past end of file)\n";
4729 outs() << " cryptid " << ec.cryptid << "\n";
4732 static void PrintEncryptionInfoCommand64(MachO::encryption_info_command_64 ec,
4733 uint32_t object_size) {
4734 outs() << " cmd LC_ENCRYPTION_INFO_64\n";
4735 outs() << " cmdsize " << ec.cmdsize;
4736 if (ec.cmdsize != sizeof(struct MachO::encryption_info_command_64))
4737 outs() << " Incorrect size\n";
4740 outs() << " cryptoff " << ec.cryptoff;
4741 if (ec.cryptoff > object_size)
4742 outs() << " (past end of file)\n";
4745 outs() << " cryptsize " << ec.cryptsize;
4746 if (ec.cryptsize > object_size)
4747 outs() << " (past end of file)\n";
4750 outs() << " cryptid " << ec.cryptid << "\n";
4751 outs() << " pad " << ec.pad << "\n";
4754 static void PrintLinkerOptionCommand(MachO::linker_option_command lo,
4756 outs() << " cmd LC_LINKER_OPTION\n";
4757 outs() << " cmdsize " << lo.cmdsize;
4758 if (lo.cmdsize < sizeof(struct MachO::linker_option_command))
4759 outs() << " Incorrect size\n";
4762 outs() << " count " << lo.count << "\n";
4763 const char *string = Ptr + sizeof(struct MachO::linker_option_command);
4764 uint32_t left = lo.cmdsize - sizeof(struct MachO::linker_option_command);
4767 while (*string == '\0' && left > 0) {
4773 outs() << " string #" << i << " " << format("%.*s\n", left, string);
4774 uint32_t NullPos = StringRef(string, left).find('\0');
4775 uint32_t len = std::min(NullPos, left) + 1;
4781 outs() << " count " << lo.count << " does not match number of strings "
4785 static void PrintSubFrameworkCommand(MachO::sub_framework_command sub,
4787 outs() << " cmd LC_SUB_FRAMEWORK\n";
4788 outs() << " cmdsize " << sub.cmdsize;
4789 if (sub.cmdsize < sizeof(struct MachO::sub_framework_command))
4790 outs() << " Incorrect size\n";
4793 if (sub.umbrella < sub.cmdsize) {
4794 const char *P = Ptr + sub.umbrella;
4795 outs() << " umbrella " << P << " (offset " << sub.umbrella << ")\n";
4797 outs() << " umbrella ?(bad offset " << sub.umbrella << ")\n";
4801 static void PrintSubUmbrellaCommand(MachO::sub_umbrella_command sub,
4803 outs() << " cmd LC_SUB_UMBRELLA\n";
4804 outs() << " cmdsize " << sub.cmdsize;
4805 if (sub.cmdsize < sizeof(struct MachO::sub_umbrella_command))
4806 outs() << " Incorrect size\n";
4809 if (sub.sub_umbrella < sub.cmdsize) {
4810 const char *P = Ptr + sub.sub_umbrella;
4811 outs() << " sub_umbrella " << P << " (offset " << sub.sub_umbrella << ")\n";
4813 outs() << " sub_umbrella ?(bad offset " << sub.sub_umbrella << ")\n";
4817 static void PrintSubLibraryCommand(MachO::sub_library_command sub,
4819 outs() << " cmd LC_SUB_LIBRARY\n";
4820 outs() << " cmdsize " << sub.cmdsize;
4821 if (sub.cmdsize < sizeof(struct MachO::sub_library_command))
4822 outs() << " Incorrect size\n";
4825 if (sub.sub_library < sub.cmdsize) {
4826 const char *P = Ptr + sub.sub_library;
4827 outs() << " sub_library " << P << " (offset " << sub.sub_library << ")\n";
4829 outs() << " sub_library ?(bad offset " << sub.sub_library << ")\n";
4833 static void PrintSubClientCommand(MachO::sub_client_command sub,
4835 outs() << " cmd LC_SUB_CLIENT\n";
4836 outs() << " cmdsize " << sub.cmdsize;
4837 if (sub.cmdsize < sizeof(struct MachO::sub_client_command))
4838 outs() << " Incorrect size\n";
4841 if (sub.client < sub.cmdsize) {
4842 const char *P = Ptr + sub.client;
4843 outs() << " client " << P << " (offset " << sub.client << ")\n";
4845 outs() << " client ?(bad offset " << sub.client << ")\n";
4849 static void PrintRoutinesCommand(MachO::routines_command r) {
4850 outs() << " cmd LC_ROUTINES\n";
4851 outs() << " cmdsize " << r.cmdsize;
4852 if (r.cmdsize != sizeof(struct MachO::routines_command))
4853 outs() << " Incorrect size\n";
4856 outs() << " init_address " << format("0x%08" PRIx32, r.init_address) << "\n";
4857 outs() << " init_module " << r.init_module << "\n";
4858 outs() << " reserved1 " << r.reserved1 << "\n";
4859 outs() << " reserved2 " << r.reserved2 << "\n";
4860 outs() << " reserved3 " << r.reserved3 << "\n";
4861 outs() << " reserved4 " << r.reserved4 << "\n";
4862 outs() << " reserved5 " << r.reserved5 << "\n";
4863 outs() << " reserved6 " << r.reserved6 << "\n";
4866 static void PrintRoutinesCommand64(MachO::routines_command_64 r) {
4867 outs() << " cmd LC_ROUTINES_64\n";
4868 outs() << " cmdsize " << r.cmdsize;
4869 if (r.cmdsize != sizeof(struct MachO::routines_command_64))
4870 outs() << " Incorrect size\n";
4873 outs() << " init_address " << format("0x%016" PRIx64, r.init_address) << "\n";
4874 outs() << " init_module " << r.init_module << "\n";
4875 outs() << " reserved1 " << r.reserved1 << "\n";
4876 outs() << " reserved2 " << r.reserved2 << "\n";
4877 outs() << " reserved3 " << r.reserved3 << "\n";
4878 outs() << " reserved4 " << r.reserved4 << "\n";
4879 outs() << " reserved5 " << r.reserved5 << "\n";
4880 outs() << " reserved6 " << r.reserved6 << "\n";
4883 static void Print_x86_thread_state64_t(MachO::x86_thread_state64_t &cpu64) {
4884 outs() << " rax " << format("0x%016" PRIx64, cpu64.rax);
4885 outs() << " rbx " << format("0x%016" PRIx64, cpu64.rbx);
4886 outs() << " rcx " << format("0x%016" PRIx64, cpu64.rcx) << "\n";
4887 outs() << " rdx " << format("0x%016" PRIx64, cpu64.rdx);
4888 outs() << " rdi " << format("0x%016" PRIx64, cpu64.rdi);
4889 outs() << " rsi " << format("0x%016" PRIx64, cpu64.rsi) << "\n";
4890 outs() << " rbp " << format("0x%016" PRIx64, cpu64.rbp);
4891 outs() << " rsp " << format("0x%016" PRIx64, cpu64.rsp);
4892 outs() << " r8 " << format("0x%016" PRIx64, cpu64.r8) << "\n";
4893 outs() << " r9 " << format("0x%016" PRIx64, cpu64.r9);
4894 outs() << " r10 " << format("0x%016" PRIx64, cpu64.r10);
4895 outs() << " r11 " << format("0x%016" PRIx64, cpu64.r11) << "\n";
4896 outs() << " r12 " << format("0x%016" PRIx64, cpu64.r12);
4897 outs() << " r13 " << format("0x%016" PRIx64, cpu64.r13);
4898 outs() << " r14 " << format("0x%016" PRIx64, cpu64.r14) << "\n";
4899 outs() << " r15 " << format("0x%016" PRIx64, cpu64.r15);
4900 outs() << " rip " << format("0x%016" PRIx64, cpu64.rip) << "\n";
4901 outs() << "rflags " << format("0x%016" PRIx64, cpu64.rflags);
4902 outs() << " cs " << format("0x%016" PRIx64, cpu64.cs);
4903 outs() << " fs " << format("0x%016" PRIx64, cpu64.fs) << "\n";
4904 outs() << " gs " << format("0x%016" PRIx64, cpu64.gs) << "\n";
4907 static void Print_mmst_reg(MachO::mmst_reg_t &r) {
4909 outs() << "\t mmst_reg ";
4910 for (f = 0; f < 10; f++)
4911 outs() << format("%02" PRIx32, (r.mmst_reg[f] & 0xff)) << " ";
4913 outs() << "\t mmst_rsrv ";
4914 for (f = 0; f < 6; f++)
4915 outs() << format("%02" PRIx32, (r.mmst_rsrv[f] & 0xff)) << " ";
4919 static void Print_xmm_reg(MachO::xmm_reg_t &r) {
4921 outs() << "\t xmm_reg ";
4922 for (f = 0; f < 16; f++)
4923 outs() << format("%02" PRIx32, (r.xmm_reg[f] & 0xff)) << " ";
4927 static void Print_x86_float_state_t(MachO::x86_float_state64_t &fpu) {
4928 outs() << "\t fpu_reserved[0] " << fpu.fpu_reserved[0];
4929 outs() << " fpu_reserved[1] " << fpu.fpu_reserved[1] << "\n";
4930 outs() << "\t control: invalid " << fpu.fpu_fcw.invalid;
4931 outs() << " denorm " << fpu.fpu_fcw.denorm;
4932 outs() << " zdiv " << fpu.fpu_fcw.zdiv;
4933 outs() << " ovrfl " << fpu.fpu_fcw.ovrfl;
4934 outs() << " undfl " << fpu.fpu_fcw.undfl;
4935 outs() << " precis " << fpu.fpu_fcw.precis << "\n";
4936 outs() << "\t\t pc ";
4937 if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_24B)
4938 outs() << "FP_PREC_24B ";
4939 else if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_53B)
4940 outs() << "FP_PREC_53B ";
4941 else if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_64B)
4942 outs() << "FP_PREC_64B ";
4944 outs() << fpu.fpu_fcw.pc << " ";
4946 if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_NEAR)
4947 outs() << "FP_RND_NEAR ";
4948 else if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_DOWN)
4949 outs() << "FP_RND_DOWN ";
4950 else if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_UP)
4951 outs() << "FP_RND_UP ";
4952 else if (fpu.fpu_fcw.rc == MachO::x86_FP_CHOP)
4953 outs() << "FP_CHOP ";
4955 outs() << "\t status: invalid " << fpu.fpu_fsw.invalid;
4956 outs() << " denorm " << fpu.fpu_fsw.denorm;
4957 outs() << " zdiv " << fpu.fpu_fsw.zdiv;
4958 outs() << " ovrfl " << fpu.fpu_fsw.ovrfl;
4959 outs() << " undfl " << fpu.fpu_fsw.undfl;
4960 outs() << " precis " << fpu.fpu_fsw.precis;
4961 outs() << " stkflt " << fpu.fpu_fsw.stkflt << "\n";
4962 outs() << "\t errsumm " << fpu.fpu_fsw.errsumm;
4963 outs() << " c0 " << fpu.fpu_fsw.c0;
4964 outs() << " c1 " << fpu.fpu_fsw.c1;
4965 outs() << " c2 " << fpu.fpu_fsw.c2;
4966 outs() << " tos " << fpu.fpu_fsw.tos;
4967 outs() << " c3 " << fpu.fpu_fsw.c3;
4968 outs() << " busy " << fpu.fpu_fsw.busy << "\n";
4969 outs() << "\t fpu_ftw " << format("0x%02" PRIx32, fpu.fpu_ftw);
4970 outs() << " fpu_rsrv1 " << format("0x%02" PRIx32, fpu.fpu_rsrv1);
4971 outs() << " fpu_fop " << format("0x%04" PRIx32, fpu.fpu_fop);
4972 outs() << " fpu_ip " << format("0x%08" PRIx32, fpu.fpu_ip) << "\n";
4973 outs() << "\t fpu_cs " << format("0x%04" PRIx32, fpu.fpu_cs);
4974 outs() << " fpu_rsrv2 " << format("0x%04" PRIx32, fpu.fpu_rsrv2);
4975 outs() << " fpu_dp " << format("0x%08" PRIx32, fpu.fpu_dp);
4976 outs() << " fpu_ds " << format("0x%04" PRIx32, fpu.fpu_ds) << "\n";
4977 outs() << "\t fpu_rsrv3 " << format("0x%04" PRIx32, fpu.fpu_rsrv3);
4978 outs() << " fpu_mxcsr " << format("0x%08" PRIx32, fpu.fpu_mxcsr);
4979 outs() << " fpu_mxcsrmask " << format("0x%08" PRIx32, fpu.fpu_mxcsrmask);
4981 outs() << "\t fpu_stmm0:\n";
4982 Print_mmst_reg(fpu.fpu_stmm0);
4983 outs() << "\t fpu_stmm1:\n";
4984 Print_mmst_reg(fpu.fpu_stmm1);
4985 outs() << "\t fpu_stmm2:\n";
4986 Print_mmst_reg(fpu.fpu_stmm2);
4987 outs() << "\t fpu_stmm3:\n";
4988 Print_mmst_reg(fpu.fpu_stmm3);
4989 outs() << "\t fpu_stmm4:\n";
4990 Print_mmst_reg(fpu.fpu_stmm4);
4991 outs() << "\t fpu_stmm5:\n";
4992 Print_mmst_reg(fpu.fpu_stmm5);
4993 outs() << "\t fpu_stmm6:\n";
4994 Print_mmst_reg(fpu.fpu_stmm6);
4995 outs() << "\t fpu_stmm7:\n";
4996 Print_mmst_reg(fpu.fpu_stmm7);
4997 outs() << "\t fpu_xmm0:\n";
4998 Print_xmm_reg(fpu.fpu_xmm0);
4999 outs() << "\t fpu_xmm1:\n";
5000 Print_xmm_reg(fpu.fpu_xmm1);
5001 outs() << "\t fpu_xmm2:\n";
5002 Print_xmm_reg(fpu.fpu_xmm2);
5003 outs() << "\t fpu_xmm3:\n";
5004 Print_xmm_reg(fpu.fpu_xmm3);
5005 outs() << "\t fpu_xmm4:\n";
5006 Print_xmm_reg(fpu.fpu_xmm4);
5007 outs() << "\t fpu_xmm5:\n";
5008 Print_xmm_reg(fpu.fpu_xmm5);
5009 outs() << "\t fpu_xmm6:\n";
5010 Print_xmm_reg(fpu.fpu_xmm6);
5011 outs() << "\t fpu_xmm7:\n";
5012 Print_xmm_reg(fpu.fpu_xmm7);
5013 outs() << "\t fpu_xmm8:\n";
5014 Print_xmm_reg(fpu.fpu_xmm8);
5015 outs() << "\t fpu_xmm9:\n";
5016 Print_xmm_reg(fpu.fpu_xmm9);
5017 outs() << "\t fpu_xmm10:\n";
5018 Print_xmm_reg(fpu.fpu_xmm10);
5019 outs() << "\t fpu_xmm11:\n";
5020 Print_xmm_reg(fpu.fpu_xmm11);
5021 outs() << "\t fpu_xmm12:\n";
5022 Print_xmm_reg(fpu.fpu_xmm12);
5023 outs() << "\t fpu_xmm13:\n";
5024 Print_xmm_reg(fpu.fpu_xmm13);
5025 outs() << "\t fpu_xmm14:\n";
5026 Print_xmm_reg(fpu.fpu_xmm14);
5027 outs() << "\t fpu_xmm15:\n";
5028 Print_xmm_reg(fpu.fpu_xmm15);
5029 outs() << "\t fpu_rsrv4:\n";
5030 for (uint32_t f = 0; f < 6; f++) {
5032 for (uint32_t g = 0; g < 16; g++)
5033 outs() << format("%02" PRIx32, fpu.fpu_rsrv4[f * g]) << " ";
5036 outs() << "\t fpu_reserved1 " << format("0x%08" PRIx32, fpu.fpu_reserved1);
5040 static void Print_x86_exception_state_t(MachO::x86_exception_state64_t &exc64) {
5041 outs() << "\t trapno " << format("0x%08" PRIx32, exc64.trapno);
5042 outs() << " err " << format("0x%08" PRIx32, exc64.err);
5043 outs() << " faultvaddr " << format("0x%016" PRIx64, exc64.faultvaddr) << "\n";
5046 static void PrintThreadCommand(MachO::thread_command t, const char *Ptr,
5047 bool isLittleEndian, uint32_t cputype) {
5048 if (t.cmd == MachO::LC_THREAD)
5049 outs() << " cmd LC_THREAD\n";
5050 else if (t.cmd == MachO::LC_UNIXTHREAD)
5051 outs() << " cmd LC_UNIXTHREAD\n";
5053 outs() << " cmd " << t.cmd << " (unknown)\n";
5054 outs() << " cmdsize " << t.cmdsize;
5055 if (t.cmdsize < sizeof(struct MachO::thread_command) + 2 * sizeof(uint32_t))
5056 outs() << " Incorrect size\n";
5060 const char *begin = Ptr + sizeof(struct MachO::thread_command);
5061 const char *end = Ptr + t.cmdsize;
5062 uint32_t flavor, count, left;
5063 if (cputype == MachO::CPU_TYPE_X86_64) {
5064 while (begin < end) {
5065 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
5066 memcpy((char *)&flavor, begin, sizeof(uint32_t));
5067 begin += sizeof(uint32_t);
5072 if (isLittleEndian != sys::IsLittleEndianHost)
5073 sys::swapByteOrder(flavor);
5074 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
5075 memcpy((char *)&count, begin, sizeof(uint32_t));
5076 begin += sizeof(uint32_t);
5081 if (isLittleEndian != sys::IsLittleEndianHost)
5082 sys::swapByteOrder(count);
5083 if (flavor == MachO::x86_THREAD_STATE64) {
5084 outs() << " flavor x86_THREAD_STATE64\n";
5085 if (count == MachO::x86_THREAD_STATE64_COUNT)
5086 outs() << " count x86_THREAD_STATE64_COUNT\n";
5088 outs() << " count " << count
5089 << " (not x86_THREAD_STATE64_COUNT)\n";
5090 MachO::x86_thread_state64_t cpu64;
5092 if (left >= sizeof(MachO::x86_thread_state64_t)) {
5093 memcpy(&cpu64, begin, sizeof(MachO::x86_thread_state64_t));
5094 begin += sizeof(MachO::x86_thread_state64_t);
5096 memset(&cpu64, '\0', sizeof(MachO::x86_thread_state64_t));
5097 memcpy(&cpu64, begin, left);
5100 if (isLittleEndian != sys::IsLittleEndianHost)
5102 Print_x86_thread_state64_t(cpu64);
5103 } else if (flavor == MachO::x86_THREAD_STATE) {
5104 outs() << " flavor x86_THREAD_STATE\n";
5105 if (count == MachO::x86_THREAD_STATE_COUNT)
5106 outs() << " count x86_THREAD_STATE_COUNT\n";
5108 outs() << " count " << count
5109 << " (not x86_THREAD_STATE_COUNT)\n";
5110 struct MachO::x86_thread_state_t ts;
5112 if (left >= sizeof(MachO::x86_thread_state_t)) {
5113 memcpy(&ts, begin, sizeof(MachO::x86_thread_state_t));
5114 begin += sizeof(MachO::x86_thread_state_t);
5116 memset(&ts, '\0', sizeof(MachO::x86_thread_state_t));
5117 memcpy(&ts, begin, left);
5120 if (isLittleEndian != sys::IsLittleEndianHost)
5122 if (ts.tsh.flavor == MachO::x86_THREAD_STATE64) {
5123 outs() << "\t tsh.flavor x86_THREAD_STATE64 ";
5124 if (ts.tsh.count == MachO::x86_THREAD_STATE64_COUNT)
5125 outs() << "tsh.count x86_THREAD_STATE64_COUNT\n";
5127 outs() << "tsh.count " << ts.tsh.count
5128 << " (not x86_THREAD_STATE64_COUNT\n";
5129 Print_x86_thread_state64_t(ts.uts.ts64);
5131 outs() << "\t tsh.flavor " << ts.tsh.flavor << " tsh.count "
5132 << ts.tsh.count << "\n";
5134 } else if (flavor == MachO::x86_FLOAT_STATE) {
5135 outs() << " flavor x86_FLOAT_STATE\n";
5136 if (count == MachO::x86_FLOAT_STATE_COUNT)
5137 outs() << " count x86_FLOAT_STATE_COUNT\n";
5139 outs() << " count " << count << " (not x86_FLOAT_STATE_COUNT)\n";
5140 struct MachO::x86_float_state_t fs;
5142 if (left >= sizeof(MachO::x86_float_state_t)) {
5143 memcpy(&fs, begin, sizeof(MachO::x86_float_state_t));
5144 begin += sizeof(MachO::x86_float_state_t);
5146 memset(&fs, '\0', sizeof(MachO::x86_float_state_t));
5147 memcpy(&fs, begin, left);
5150 if (isLittleEndian != sys::IsLittleEndianHost)
5152 if (fs.fsh.flavor == MachO::x86_FLOAT_STATE64) {
5153 outs() << "\t fsh.flavor x86_FLOAT_STATE64 ";
5154 if (fs.fsh.count == MachO::x86_FLOAT_STATE64_COUNT)
5155 outs() << "fsh.count x86_FLOAT_STATE64_COUNT\n";
5157 outs() << "fsh.count " << fs.fsh.count
5158 << " (not x86_FLOAT_STATE64_COUNT\n";
5159 Print_x86_float_state_t(fs.ufs.fs64);
5161 outs() << "\t fsh.flavor " << fs.fsh.flavor << " fsh.count "
5162 << fs.fsh.count << "\n";
5164 } else if (flavor == MachO::x86_EXCEPTION_STATE) {
5165 outs() << " flavor x86_EXCEPTION_STATE\n";
5166 if (count == MachO::x86_EXCEPTION_STATE_COUNT)
5167 outs() << " count x86_EXCEPTION_STATE_COUNT\n";
5169 outs() << " count " << count
5170 << " (not x86_EXCEPTION_STATE_COUNT)\n";
5171 struct MachO::x86_exception_state_t es;
5173 if (left >= sizeof(MachO::x86_exception_state_t)) {
5174 memcpy(&es, begin, sizeof(MachO::x86_exception_state_t));
5175 begin += sizeof(MachO::x86_exception_state_t);
5177 memset(&es, '\0', sizeof(MachO::x86_exception_state_t));
5178 memcpy(&es, begin, left);
5181 if (isLittleEndian != sys::IsLittleEndianHost)
5183 if (es.esh.flavor == MachO::x86_EXCEPTION_STATE64) {
5184 outs() << "\t esh.flavor x86_EXCEPTION_STATE64\n";
5185 if (es.esh.count == MachO::x86_EXCEPTION_STATE64_COUNT)
5186 outs() << "\t esh.count x86_EXCEPTION_STATE64_COUNT\n";
5188 outs() << "\t esh.count " << es.esh.count
5189 << " (not x86_EXCEPTION_STATE64_COUNT\n";
5190 Print_x86_exception_state_t(es.ues.es64);
5192 outs() << "\t esh.flavor " << es.esh.flavor << " esh.count "
5193 << es.esh.count << "\n";
5196 outs() << " flavor " << flavor << " (unknown)\n";
5197 outs() << " count " << count << "\n";
5198 outs() << " state (unknown)\n";
5199 begin += count * sizeof(uint32_t);
5203 while (begin < end) {
5204 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
5205 memcpy((char *)&flavor, begin, sizeof(uint32_t));
5206 begin += sizeof(uint32_t);
5211 if (isLittleEndian != sys::IsLittleEndianHost)
5212 sys::swapByteOrder(flavor);
5213 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
5214 memcpy((char *)&count, begin, sizeof(uint32_t));
5215 begin += sizeof(uint32_t);
5220 if (isLittleEndian != sys::IsLittleEndianHost)
5221 sys::swapByteOrder(count);
5222 outs() << " flavor " << flavor << "\n";
5223 outs() << " count " << count << "\n";
5224 outs() << " state (Unknown cputype/cpusubtype)\n";
5225 begin += count * sizeof(uint32_t);
5230 static void PrintDylibCommand(MachO::dylib_command dl, const char *Ptr) {
5231 if (dl.cmd == MachO::LC_ID_DYLIB)
5232 outs() << " cmd LC_ID_DYLIB\n";
5233 else if (dl.cmd == MachO::LC_LOAD_DYLIB)
5234 outs() << " cmd LC_LOAD_DYLIB\n";
5235 else if (dl.cmd == MachO::LC_LOAD_WEAK_DYLIB)
5236 outs() << " cmd LC_LOAD_WEAK_DYLIB\n";
5237 else if (dl.cmd == MachO::LC_REEXPORT_DYLIB)
5238 outs() << " cmd LC_REEXPORT_DYLIB\n";
5239 else if (dl.cmd == MachO::LC_LAZY_LOAD_DYLIB)
5240 outs() << " cmd LC_LAZY_LOAD_DYLIB\n";
5241 else if (dl.cmd == MachO::LC_LOAD_UPWARD_DYLIB)
5242 outs() << " cmd LC_LOAD_UPWARD_DYLIB\n";
5244 outs() << " cmd " << dl.cmd << " (unknown)\n";
5245 outs() << " cmdsize " << dl.cmdsize;
5246 if (dl.cmdsize < sizeof(struct MachO::dylib_command))
5247 outs() << " Incorrect size\n";
5250 if (dl.dylib.name < dl.cmdsize) {
5251 const char *P = (const char *)(Ptr) + dl.dylib.name;
5252 outs() << " name " << P << " (offset " << dl.dylib.name << ")\n";
5254 outs() << " name ?(bad offset " << dl.dylib.name << ")\n";
5256 outs() << " time stamp " << dl.dylib.timestamp << " ";
5257 time_t t = dl.dylib.timestamp;
5258 outs() << ctime(&t);
5259 outs() << " current version ";
5260 if (dl.dylib.current_version == 0xffffffff)
5263 outs() << ((dl.dylib.current_version >> 16) & 0xffff) << "."
5264 << ((dl.dylib.current_version >> 8) & 0xff) << "."
5265 << (dl.dylib.current_version & 0xff) << "\n";
5266 outs() << "compatibility version ";
5267 if (dl.dylib.compatibility_version == 0xffffffff)
5270 outs() << ((dl.dylib.compatibility_version >> 16) & 0xffff) << "."
5271 << ((dl.dylib.compatibility_version >> 8) & 0xff) << "."
5272 << (dl.dylib.compatibility_version & 0xff) << "\n";
5275 static void PrintLinkEditDataCommand(MachO::linkedit_data_command ld,
5276 uint32_t object_size) {
5277 if (ld.cmd == MachO::LC_CODE_SIGNATURE)
5278 outs() << " cmd LC_FUNCTION_STARTS\n";
5279 else if (ld.cmd == MachO::LC_SEGMENT_SPLIT_INFO)
5280 outs() << " cmd LC_SEGMENT_SPLIT_INFO\n";
5281 else if (ld.cmd == MachO::LC_FUNCTION_STARTS)
5282 outs() << " cmd LC_FUNCTION_STARTS\n";
5283 else if (ld.cmd == MachO::LC_DATA_IN_CODE)
5284 outs() << " cmd LC_DATA_IN_CODE\n";
5285 else if (ld.cmd == MachO::LC_DYLIB_CODE_SIGN_DRS)
5286 outs() << " cmd LC_DYLIB_CODE_SIGN_DRS\n";
5287 else if (ld.cmd == MachO::LC_LINKER_OPTIMIZATION_HINT)
5288 outs() << " cmd LC_LINKER_OPTIMIZATION_HINT\n";
5290 outs() << " cmd " << ld.cmd << " (?)\n";
5291 outs() << " cmdsize " << ld.cmdsize;
5292 if (ld.cmdsize != sizeof(struct MachO::linkedit_data_command))
5293 outs() << " Incorrect size\n";
5296 outs() << " dataoff " << ld.dataoff;
5297 if (ld.dataoff > object_size)
5298 outs() << " (past end of file)\n";
5301 outs() << " datasize " << ld.datasize;
5302 uint64_t big_size = ld.dataoff;
5303 big_size += ld.datasize;
5304 if (big_size > object_size)
5305 outs() << " (past end of file)\n";
5310 static void PrintLoadCommands(const MachOObjectFile *Obj, uint32_t ncmds,
5311 uint32_t filetype, uint32_t cputype,
5315 StringRef Buf = Obj->getData();
5316 MachOObjectFile::LoadCommandInfo Command = Obj->getFirstLoadCommandInfo();
5317 for (unsigned i = 0;; ++i) {
5318 outs() << "Load command " << i << "\n";
5319 if (Command.C.cmd == MachO::LC_SEGMENT) {
5320 MachO::segment_command SLC = Obj->getSegmentLoadCommand(Command);
5321 const char *sg_segname = SLC.segname;
5322 PrintSegmentCommand(SLC.cmd, SLC.cmdsize, SLC.segname, SLC.vmaddr,
5323 SLC.vmsize, SLC.fileoff, SLC.filesize, SLC.maxprot,
5324 SLC.initprot, SLC.nsects, SLC.flags, Buf.size(),
5326 for (unsigned j = 0; j < SLC.nsects; j++) {
5327 MachO::section S = Obj->getSection(Command, j);
5328 PrintSection(S.sectname, S.segname, S.addr, S.size, S.offset, S.align,
5329 S.reloff, S.nreloc, S.flags, S.reserved1, S.reserved2,
5330 SLC.cmd, sg_segname, filetype, Buf.size(), verbose);
5332 } else if (Command.C.cmd == MachO::LC_SEGMENT_64) {
5333 MachO::segment_command_64 SLC_64 = Obj->getSegment64LoadCommand(Command);
5334 const char *sg_segname = SLC_64.segname;
5335 PrintSegmentCommand(SLC_64.cmd, SLC_64.cmdsize, SLC_64.segname,
5336 SLC_64.vmaddr, SLC_64.vmsize, SLC_64.fileoff,
5337 SLC_64.filesize, SLC_64.maxprot, SLC_64.initprot,
5338 SLC_64.nsects, SLC_64.flags, Buf.size(), verbose);
5339 for (unsigned j = 0; j < SLC_64.nsects; j++) {
5340 MachO::section_64 S_64 = Obj->getSection64(Command, j);
5341 PrintSection(S_64.sectname, S_64.segname, S_64.addr, S_64.size,
5342 S_64.offset, S_64.align, S_64.reloff, S_64.nreloc,
5343 S_64.flags, S_64.reserved1, S_64.reserved2, SLC_64.cmd,
5344 sg_segname, filetype, Buf.size(), verbose);
5346 } else if (Command.C.cmd == MachO::LC_SYMTAB) {
5347 MachO::symtab_command Symtab = Obj->getSymtabLoadCommand();
5348 PrintSymtabLoadCommand(Symtab, Obj->is64Bit(), Buf.size());
5349 } else if (Command.C.cmd == MachO::LC_DYSYMTAB) {
5350 MachO::dysymtab_command Dysymtab = Obj->getDysymtabLoadCommand();
5351 MachO::symtab_command Symtab = Obj->getSymtabLoadCommand();
5352 PrintDysymtabLoadCommand(Dysymtab, Symtab.nsyms, Buf.size(),
5354 } else if (Command.C.cmd == MachO::LC_DYLD_INFO ||
5355 Command.C.cmd == MachO::LC_DYLD_INFO_ONLY) {
5356 MachO::dyld_info_command DyldInfo = Obj->getDyldInfoLoadCommand(Command);
5357 PrintDyldInfoLoadCommand(DyldInfo, Buf.size());
5358 } else if (Command.C.cmd == MachO::LC_LOAD_DYLINKER ||
5359 Command.C.cmd == MachO::LC_ID_DYLINKER ||
5360 Command.C.cmd == MachO::LC_DYLD_ENVIRONMENT) {
5361 MachO::dylinker_command Dyld = Obj->getDylinkerCommand(Command);
5362 PrintDyldLoadCommand(Dyld, Command.Ptr);
5363 } else if (Command.C.cmd == MachO::LC_UUID) {
5364 MachO::uuid_command Uuid = Obj->getUuidCommand(Command);
5365 PrintUuidLoadCommand(Uuid);
5366 } else if (Command.C.cmd == MachO::LC_RPATH) {
5367 MachO::rpath_command Rpath = Obj->getRpathCommand(Command);
5368 PrintRpathLoadCommand(Rpath, Command.Ptr);
5369 } else if (Command.C.cmd == MachO::LC_VERSION_MIN_MACOSX ||
5370 Command.C.cmd == MachO::LC_VERSION_MIN_IPHONEOS) {
5371 MachO::version_min_command Vd = Obj->getVersionMinLoadCommand(Command);
5372 PrintVersionMinLoadCommand(Vd);
5373 } else if (Command.C.cmd == MachO::LC_SOURCE_VERSION) {
5374 MachO::source_version_command Sd = Obj->getSourceVersionCommand(Command);
5375 PrintSourceVersionCommand(Sd);
5376 } else if (Command.C.cmd == MachO::LC_MAIN) {
5377 MachO::entry_point_command Ep = Obj->getEntryPointCommand(Command);
5378 PrintEntryPointCommand(Ep);
5379 } else if (Command.C.cmd == MachO::LC_ENCRYPTION_INFO) {
5380 MachO::encryption_info_command Ei =
5381 Obj->getEncryptionInfoCommand(Command);
5382 PrintEncryptionInfoCommand(Ei, Buf.size());
5383 } else if (Command.C.cmd == MachO::LC_ENCRYPTION_INFO_64) {
5384 MachO::encryption_info_command_64 Ei =
5385 Obj->getEncryptionInfoCommand64(Command);
5386 PrintEncryptionInfoCommand64(Ei, Buf.size());
5387 } else if (Command.C.cmd == MachO::LC_LINKER_OPTION) {
5388 MachO::linker_option_command Lo =
5389 Obj->getLinkerOptionLoadCommand(Command);
5390 PrintLinkerOptionCommand(Lo, Command.Ptr);
5391 } else if (Command.C.cmd == MachO::LC_SUB_FRAMEWORK) {
5392 MachO::sub_framework_command Sf = Obj->getSubFrameworkCommand(Command);
5393 PrintSubFrameworkCommand(Sf, Command.Ptr);
5394 } else if (Command.C.cmd == MachO::LC_SUB_UMBRELLA) {
5395 MachO::sub_umbrella_command Sf = Obj->getSubUmbrellaCommand(Command);
5396 PrintSubUmbrellaCommand(Sf, Command.Ptr);
5397 } else if (Command.C.cmd == MachO::LC_SUB_LIBRARY) {
5398 MachO::sub_library_command Sl = Obj->getSubLibraryCommand(Command);
5399 PrintSubLibraryCommand(Sl, Command.Ptr);
5400 } else if (Command.C.cmd == MachO::LC_SUB_CLIENT) {
5401 MachO::sub_client_command Sc = Obj->getSubClientCommand(Command);
5402 PrintSubClientCommand(Sc, Command.Ptr);
5403 } else if (Command.C.cmd == MachO::LC_ROUTINES) {
5404 MachO::routines_command Rc = Obj->getRoutinesCommand(Command);
5405 PrintRoutinesCommand(Rc);
5406 } else if (Command.C.cmd == MachO::LC_ROUTINES_64) {
5407 MachO::routines_command_64 Rc = Obj->getRoutinesCommand64(Command);
5408 PrintRoutinesCommand64(Rc);
5409 } else if (Command.C.cmd == MachO::LC_THREAD ||
5410 Command.C.cmd == MachO::LC_UNIXTHREAD) {
5411 MachO::thread_command Tc = Obj->getThreadCommand(Command);
5412 PrintThreadCommand(Tc, Command.Ptr, Obj->isLittleEndian(), cputype);
5413 } else if (Command.C.cmd == MachO::LC_LOAD_DYLIB ||
5414 Command.C.cmd == MachO::LC_ID_DYLIB ||
5415 Command.C.cmd == MachO::LC_LOAD_WEAK_DYLIB ||
5416 Command.C.cmd == MachO::LC_REEXPORT_DYLIB ||
5417 Command.C.cmd == MachO::LC_LAZY_LOAD_DYLIB ||
5418 Command.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB) {
5419 MachO::dylib_command Dl = Obj->getDylibIDLoadCommand(Command);
5420 PrintDylibCommand(Dl, Command.Ptr);
5421 } else if (Command.C.cmd == MachO::LC_CODE_SIGNATURE ||
5422 Command.C.cmd == MachO::LC_SEGMENT_SPLIT_INFO ||
5423 Command.C.cmd == MachO::LC_FUNCTION_STARTS ||
5424 Command.C.cmd == MachO::LC_DATA_IN_CODE ||
5425 Command.C.cmd == MachO::LC_DYLIB_CODE_SIGN_DRS ||
5426 Command.C.cmd == MachO::LC_LINKER_OPTIMIZATION_HINT) {
5427 MachO::linkedit_data_command Ld =
5428 Obj->getLinkeditDataLoadCommand(Command);
5429 PrintLinkEditDataCommand(Ld, Buf.size());
5431 outs() << " cmd ?(" << format("0x%08" PRIx32, Command.C.cmd)
5433 outs() << " cmdsize " << Command.C.cmdsize << "\n";
5434 // TODO: get and print the raw bytes of the load command.
5436 // TODO: print all the other kinds of load commands.
5440 Command = Obj->getNextLoadCommandInfo(Command);
5444 static void getAndPrintMachHeader(const MachOObjectFile *Obj, uint32_t &ncmds,
5445 uint32_t &filetype, uint32_t &cputype,
5447 if (Obj->is64Bit()) {
5448 MachO::mach_header_64 H_64;
5449 H_64 = Obj->getHeader64();
5450 PrintMachHeader(H_64.magic, H_64.cputype, H_64.cpusubtype, H_64.filetype,
5451 H_64.ncmds, H_64.sizeofcmds, H_64.flags, verbose);
5453 filetype = H_64.filetype;
5454 cputype = H_64.cputype;
5456 MachO::mach_header H;
5457 H = Obj->getHeader();
5458 PrintMachHeader(H.magic, H.cputype, H.cpusubtype, H.filetype, H.ncmds,
5459 H.sizeofcmds, H.flags, verbose);
5461 filetype = H.filetype;
5462 cputype = H.cputype;
5466 void llvm::printMachOFileHeader(const object::ObjectFile *Obj) {
5467 const MachOObjectFile *file = dyn_cast<const MachOObjectFile>(Obj);
5469 uint32_t filetype = 0;
5470 uint32_t cputype = 0;
5471 getAndPrintMachHeader(file, ncmds, filetype, cputype, !NonVerbose);
5472 PrintLoadCommands(file, ncmds, filetype, cputype, !NonVerbose);
5475 //===----------------------------------------------------------------------===//
5476 // export trie dumping
5477 //===----------------------------------------------------------------------===//
5479 void llvm::printMachOExportsTrie(const object::MachOObjectFile *Obj) {
5480 for (const llvm::object::ExportEntry &Entry : Obj->exports()) {
5481 uint64_t Flags = Entry.flags();
5482 bool ReExport = (Flags & MachO::EXPORT_SYMBOL_FLAGS_REEXPORT);
5483 bool WeakDef = (Flags & MachO::EXPORT_SYMBOL_FLAGS_WEAK_DEFINITION);
5484 bool ThreadLocal = ((Flags & MachO::EXPORT_SYMBOL_FLAGS_KIND_MASK) ==
5485 MachO::EXPORT_SYMBOL_FLAGS_KIND_THREAD_LOCAL);
5486 bool Abs = ((Flags & MachO::EXPORT_SYMBOL_FLAGS_KIND_MASK) ==
5487 MachO::EXPORT_SYMBOL_FLAGS_KIND_ABSOLUTE);
5488 bool Resolver = (Flags & MachO::EXPORT_SYMBOL_FLAGS_STUB_AND_RESOLVER);
5490 outs() << "[re-export] ";
5492 outs() << format("0x%08llX ",
5493 Entry.address()); // FIXME:add in base address
5494 outs() << Entry.name();
5495 if (WeakDef || ThreadLocal || Resolver || Abs) {
5496 bool NeedsComma = false;
5499 outs() << "weak_def";
5505 outs() << "per-thread";
5511 outs() << "absolute";
5517 outs() << format("resolver=0x%08llX", Entry.other());
5523 StringRef DylibName = "unknown";
5524 int Ordinal = Entry.other() - 1;
5525 Obj->getLibraryShortNameByIndex(Ordinal, DylibName);
5526 if (Entry.otherName().empty())
5527 outs() << " (from " << DylibName << ")";
5529 outs() << " (" << Entry.otherName() << " from " << DylibName << ")";
5535 //===----------------------------------------------------------------------===//
5536 // rebase table dumping
5537 //===----------------------------------------------------------------------===//
5542 SegInfo(const object::MachOObjectFile *Obj);
5544 StringRef segmentName(uint32_t SegIndex);
5545 StringRef sectionName(uint32_t SegIndex, uint64_t SegOffset);
5546 uint64_t address(uint32_t SegIndex, uint64_t SegOffset);
5549 struct SectionInfo {
5552 StringRef SectionName;
5553 StringRef SegmentName;
5554 uint64_t OffsetInSegment;
5555 uint64_t SegmentStartAddress;
5556 uint32_t SegmentIndex;
5558 const SectionInfo &findSection(uint32_t SegIndex, uint64_t SegOffset);
5559 SmallVector<SectionInfo, 32> Sections;
5563 SegInfo::SegInfo(const object::MachOObjectFile *Obj) {
5564 // Build table of sections so segIndex/offset pairs can be translated.
5565 uint32_t CurSegIndex = Obj->hasPageZeroSegment() ? 1 : 0;
5566 StringRef CurSegName;
5567 uint64_t CurSegAddress;
5568 for (const SectionRef &Section : Obj->sections()) {
5570 if (error(Section.getName(Info.SectionName)))
5572 Info.Address = Section.getAddress();
5573 Info.Size = Section.getSize();
5575 Obj->getSectionFinalSegmentName(Section.getRawDataRefImpl());
5576 if (!Info.SegmentName.equals(CurSegName)) {
5578 CurSegName = Info.SegmentName;
5579 CurSegAddress = Info.Address;
5581 Info.SegmentIndex = CurSegIndex - 1;
5582 Info.OffsetInSegment = Info.Address - CurSegAddress;
5583 Info.SegmentStartAddress = CurSegAddress;
5584 Sections.push_back(Info);
5588 StringRef SegInfo::segmentName(uint32_t SegIndex) {
5589 for (const SectionInfo &SI : Sections) {
5590 if (SI.SegmentIndex == SegIndex)
5591 return SI.SegmentName;
5593 llvm_unreachable("invalid segIndex");
5596 const SegInfo::SectionInfo &SegInfo::findSection(uint32_t SegIndex,
5597 uint64_t OffsetInSeg) {
5598 for (const SectionInfo &SI : Sections) {
5599 if (SI.SegmentIndex != SegIndex)
5601 if (SI.OffsetInSegment > OffsetInSeg)
5603 if (OffsetInSeg >= (SI.OffsetInSegment + SI.Size))
5607 llvm_unreachable("segIndex and offset not in any section");
5610 StringRef SegInfo::sectionName(uint32_t SegIndex, uint64_t OffsetInSeg) {
5611 return findSection(SegIndex, OffsetInSeg).SectionName;
5614 uint64_t SegInfo::address(uint32_t SegIndex, uint64_t OffsetInSeg) {
5615 const SectionInfo &SI = findSection(SegIndex, OffsetInSeg);
5616 return SI.SegmentStartAddress + OffsetInSeg;
5619 void llvm::printMachORebaseTable(const object::MachOObjectFile *Obj) {
5620 // Build table of sections so names can used in final output.
5621 SegInfo sectionTable(Obj);
5623 outs() << "segment section address type\n";
5624 for (const llvm::object::MachORebaseEntry &Entry : Obj->rebaseTable()) {
5625 uint32_t SegIndex = Entry.segmentIndex();
5626 uint64_t OffsetInSeg = Entry.segmentOffset();
5627 StringRef SegmentName = sectionTable.segmentName(SegIndex);
5628 StringRef SectionName = sectionTable.sectionName(SegIndex, OffsetInSeg);
5629 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
5631 // Table lines look like: __DATA __nl_symbol_ptr 0x0000F00C pointer
5632 outs() << format("%-8s %-18s 0x%08" PRIX64 " %s\n",
5633 SegmentName.str().c_str(), SectionName.str().c_str(),
5634 Address, Entry.typeName().str().c_str());
5638 static StringRef ordinalName(const object::MachOObjectFile *Obj, int Ordinal) {
5639 StringRef DylibName;
5641 case MachO::BIND_SPECIAL_DYLIB_SELF:
5642 return "this-image";
5643 case MachO::BIND_SPECIAL_DYLIB_MAIN_EXECUTABLE:
5644 return "main-executable";
5645 case MachO::BIND_SPECIAL_DYLIB_FLAT_LOOKUP:
5646 return "flat-namespace";
5649 std::error_code EC =
5650 Obj->getLibraryShortNameByIndex(Ordinal - 1, DylibName);
5652 return "<<bad library ordinal>>";
5656 return "<<unknown special ordinal>>";
5659 //===----------------------------------------------------------------------===//
5660 // bind table dumping
5661 //===----------------------------------------------------------------------===//
5663 void llvm::printMachOBindTable(const object::MachOObjectFile *Obj) {
5664 // Build table of sections so names can used in final output.
5665 SegInfo sectionTable(Obj);
5667 outs() << "segment section address type "
5668 "addend dylib symbol\n";
5669 for (const llvm::object::MachOBindEntry &Entry : Obj->bindTable()) {
5670 uint32_t SegIndex = Entry.segmentIndex();
5671 uint64_t OffsetInSeg = Entry.segmentOffset();
5672 StringRef SegmentName = sectionTable.segmentName(SegIndex);
5673 StringRef SectionName = sectionTable.sectionName(SegIndex, OffsetInSeg);
5674 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
5676 // Table lines look like:
5677 // __DATA __got 0x00012010 pointer 0 libSystem ___stack_chk_guard
5679 if (Entry.flags() & MachO::BIND_SYMBOL_FLAGS_WEAK_IMPORT)
5680 Attr = " (weak_import)";
5681 outs() << left_justify(SegmentName, 8) << " "
5682 << left_justify(SectionName, 18) << " "
5683 << format_hex(Address, 10, true) << " "
5684 << left_justify(Entry.typeName(), 8) << " "
5685 << format_decimal(Entry.addend(), 8) << " "
5686 << left_justify(ordinalName(Obj, Entry.ordinal()), 16) << " "
5687 << Entry.symbolName() << Attr << "\n";
5691 //===----------------------------------------------------------------------===//
5692 // lazy bind table dumping
5693 //===----------------------------------------------------------------------===//
5695 void llvm::printMachOLazyBindTable(const object::MachOObjectFile *Obj) {
5696 // Build table of sections so names can used in final output.
5697 SegInfo sectionTable(Obj);
5699 outs() << "segment section address "
5701 for (const llvm::object::MachOBindEntry &Entry : Obj->lazyBindTable()) {
5702 uint32_t SegIndex = Entry.segmentIndex();
5703 uint64_t OffsetInSeg = Entry.segmentOffset();
5704 StringRef SegmentName = sectionTable.segmentName(SegIndex);
5705 StringRef SectionName = sectionTable.sectionName(SegIndex, OffsetInSeg);
5706 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
5708 // Table lines look like:
5709 // __DATA __got 0x00012010 libSystem ___stack_chk_guard
5710 outs() << left_justify(SegmentName, 8) << " "
5711 << left_justify(SectionName, 18) << " "
5712 << format_hex(Address, 10, true) << " "
5713 << left_justify(ordinalName(Obj, Entry.ordinal()), 16) << " "
5714 << Entry.symbolName() << "\n";
5718 //===----------------------------------------------------------------------===//
5719 // weak bind table dumping
5720 //===----------------------------------------------------------------------===//
5722 void llvm::printMachOWeakBindTable(const object::MachOObjectFile *Obj) {
5723 // Build table of sections so names can used in final output.
5724 SegInfo sectionTable(Obj);
5726 outs() << "segment section address "
5727 "type addend symbol\n";
5728 for (const llvm::object::MachOBindEntry &Entry : Obj->weakBindTable()) {
5729 // Strong symbols don't have a location to update.
5730 if (Entry.flags() & MachO::BIND_SYMBOL_FLAGS_NON_WEAK_DEFINITION) {
5731 outs() << " strong "
5732 << Entry.symbolName() << "\n";
5735 uint32_t SegIndex = Entry.segmentIndex();
5736 uint64_t OffsetInSeg = Entry.segmentOffset();
5737 StringRef SegmentName = sectionTable.segmentName(SegIndex);
5738 StringRef SectionName = sectionTable.sectionName(SegIndex, OffsetInSeg);
5739 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
5741 // Table lines look like:
5742 // __DATA __data 0x00001000 pointer 0 _foo
5743 outs() << left_justify(SegmentName, 8) << " "
5744 << left_justify(SectionName, 18) << " "
5745 << format_hex(Address, 10, true) << " "
5746 << left_justify(Entry.typeName(), 8) << " "
5747 << format_decimal(Entry.addend(), 8) << " " << Entry.symbolName()
5752 // get_dyld_bind_info_symbolname() is used for disassembly and passed an
5753 // address, ReferenceValue, in the Mach-O file and looks in the dyld bind
5754 // information for that address. If the address is found its binding symbol
5755 // name is returned. If not nullptr is returned.
5756 static const char *get_dyld_bind_info_symbolname(uint64_t ReferenceValue,
5757 struct DisassembleInfo *info) {
5758 if (info->bindtable == nullptr) {
5759 info->bindtable = new (BindTable);
5760 SegInfo sectionTable(info->O);
5761 for (const llvm::object::MachOBindEntry &Entry : info->O->bindTable()) {
5762 uint32_t SegIndex = Entry.segmentIndex();
5763 uint64_t OffsetInSeg = Entry.segmentOffset();
5764 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
5765 const char *SymbolName = nullptr;
5766 StringRef name = Entry.symbolName();
5768 SymbolName = name.data();
5769 info->bindtable->push_back(std::make_pair(Address, SymbolName));
5772 for (bind_table_iterator BI = info->bindtable->begin(),
5773 BE = info->bindtable->end();
5775 uint64_t Address = BI->first;
5776 if (ReferenceValue == Address) {
5777 const char *SymbolName = BI->second;