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)"));
104 static cl::list<std::string>
105 ArchFlags("arch", cl::desc("architecture(s) from a Mach-O file to dump"),
107 bool ArchAll = false;
109 static std::string ThumbTripleName;
111 static const Target *GetTarget(const MachOObjectFile *MachOObj,
112 const char **McpuDefault,
113 const Target **ThumbTarget) {
114 // Figure out the target triple.
115 if (TripleName.empty()) {
116 llvm::Triple TT("unknown-unknown-unknown");
117 llvm::Triple ThumbTriple = Triple();
118 TT = MachOObj->getArch(McpuDefault, &ThumbTriple);
119 TripleName = TT.str();
120 ThumbTripleName = ThumbTriple.str();
123 // Get the target specific parser.
125 const Target *TheTarget = TargetRegistry::lookupTarget(TripleName, Error);
126 if (TheTarget && ThumbTripleName.empty())
129 *ThumbTarget = TargetRegistry::lookupTarget(ThumbTripleName, Error);
133 errs() << "llvm-objdump: error: unable to get target for '";
135 errs() << TripleName;
137 errs() << ThumbTripleName;
138 errs() << "', see --version and --triple.\n";
142 struct SymbolSorter {
143 bool operator()(const SymbolRef &A, const SymbolRef &B) {
144 SymbolRef::Type AType, BType;
148 uint64_t AAddr, BAddr;
149 if (AType != SymbolRef::ST_Function)
153 if (BType != SymbolRef::ST_Function)
157 return AAddr < BAddr;
161 // Types for the storted data in code table that is built before disassembly
162 // and the predicate function to sort them.
163 typedef std::pair<uint64_t, DiceRef> DiceTableEntry;
164 typedef std::vector<DiceTableEntry> DiceTable;
165 typedef DiceTable::iterator dice_table_iterator;
167 // This is used to search for a data in code table entry for the PC being
168 // disassembled. The j parameter has the PC in j.first. A single data in code
169 // table entry can cover many bytes for each of its Kind's. So if the offset,
170 // aka the i.first value, of the data in code table entry plus its Length
171 // covers the PC being searched for this will return true. If not it will
173 static bool compareDiceTableEntries(const DiceTableEntry &i,
174 const DiceTableEntry &j) {
176 i.second.getLength(Length);
178 return j.first >= i.first && j.first < i.first + Length;
181 static uint64_t DumpDataInCode(const char *bytes, uint64_t Length,
182 unsigned short Kind) {
183 uint32_t Value, Size = 1;
187 case MachO::DICE_KIND_DATA:
190 DumpBytes(StringRef(bytes, 4));
191 Value = bytes[3] << 24 | bytes[2] << 16 | bytes[1] << 8 | bytes[0];
192 outs() << "\t.long " << Value;
194 } else if (Length >= 2) {
196 DumpBytes(StringRef(bytes, 2));
197 Value = bytes[1] << 8 | bytes[0];
198 outs() << "\t.short " << Value;
202 DumpBytes(StringRef(bytes, 2));
204 outs() << "\t.byte " << Value;
207 if (Kind == MachO::DICE_KIND_DATA)
208 outs() << "\t@ KIND_DATA\n";
210 outs() << "\t@ data in code kind = " << Kind << "\n";
212 case MachO::DICE_KIND_JUMP_TABLE8:
214 DumpBytes(StringRef(bytes, 1));
216 outs() << "\t.byte " << format("%3u", Value) << "\t@ KIND_JUMP_TABLE8\n";
219 case MachO::DICE_KIND_JUMP_TABLE16:
221 DumpBytes(StringRef(bytes, 2));
222 Value = bytes[1] << 8 | bytes[0];
223 outs() << "\t.short " << format("%5u", Value & 0xffff)
224 << "\t@ KIND_JUMP_TABLE16\n";
227 case MachO::DICE_KIND_JUMP_TABLE32:
228 case MachO::DICE_KIND_ABS_JUMP_TABLE32:
230 DumpBytes(StringRef(bytes, 4));
231 Value = bytes[3] << 24 | bytes[2] << 16 | bytes[1] << 8 | bytes[0];
232 outs() << "\t.long " << Value;
233 if (Kind == MachO::DICE_KIND_JUMP_TABLE32)
234 outs() << "\t@ KIND_JUMP_TABLE32\n";
236 outs() << "\t@ KIND_ABS_JUMP_TABLE32\n";
243 static void getSectionsAndSymbols(const MachO::mach_header Header,
244 MachOObjectFile *MachOObj,
245 std::vector<SectionRef> &Sections,
246 std::vector<SymbolRef> &Symbols,
247 SmallVectorImpl<uint64_t> &FoundFns,
248 uint64_t &BaseSegmentAddress) {
249 for (const SymbolRef &Symbol : MachOObj->symbols()) {
251 Symbol.getName(SymName);
252 if (!SymName.startswith("ltmp"))
253 Symbols.push_back(Symbol);
256 for (const SectionRef &Section : MachOObj->sections()) {
258 Section.getName(SectName);
259 Sections.push_back(Section);
262 MachOObjectFile::LoadCommandInfo Command =
263 MachOObj->getFirstLoadCommandInfo();
264 bool BaseSegmentAddressSet = false;
265 for (unsigned i = 0;; ++i) {
266 if (Command.C.cmd == MachO::LC_FUNCTION_STARTS) {
267 // We found a function starts segment, parse the addresses for later
269 MachO::linkedit_data_command LLC =
270 MachOObj->getLinkeditDataLoadCommand(Command);
272 MachOObj->ReadULEB128s(LLC.dataoff, FoundFns);
273 } else if (Command.C.cmd == MachO::LC_SEGMENT) {
274 MachO::segment_command SLC = MachOObj->getSegmentLoadCommand(Command);
275 StringRef SegName = SLC.segname;
276 if (!BaseSegmentAddressSet && SegName != "__PAGEZERO") {
277 BaseSegmentAddressSet = true;
278 BaseSegmentAddress = SLC.vmaddr;
282 if (i == Header.ncmds - 1)
285 Command = MachOObj->getNextLoadCommandInfo(Command);
289 static void PrintIndirectSymbolTable(MachOObjectFile *O, bool verbose,
290 uint32_t n, uint32_t count,
291 uint32_t stride, uint64_t addr) {
292 MachO::dysymtab_command Dysymtab = O->getDysymtabLoadCommand();
293 uint32_t nindirectsyms = Dysymtab.nindirectsyms;
294 if (n > nindirectsyms)
295 outs() << " (entries start past the end of the indirect symbol "
296 "table) (reserved1 field greater than the table size)";
297 else if (n + count > nindirectsyms)
298 outs() << " (entries extends past the end of the indirect symbol "
301 uint32_t cputype = O->getHeader().cputype;
302 if (cputype & MachO::CPU_ARCH_ABI64)
303 outs() << "address index";
305 outs() << "address index";
310 for (uint32_t j = 0; j < count && n + j < nindirectsyms; j++) {
311 if (cputype & MachO::CPU_ARCH_ABI64)
312 outs() << format("0x%016" PRIx64, addr + j * stride) << " ";
314 outs() << format("0x%08" PRIx32, addr + j * stride) << " ";
315 MachO::dysymtab_command Dysymtab = O->getDysymtabLoadCommand();
316 uint32_t indirect_symbol = O->getIndirectSymbolTableEntry(Dysymtab, n + j);
317 if (indirect_symbol == MachO::INDIRECT_SYMBOL_LOCAL) {
321 if (indirect_symbol ==
322 (MachO::INDIRECT_SYMBOL_LOCAL | MachO::INDIRECT_SYMBOL_ABS)) {
323 outs() << "LOCAL ABSOLUTE\n";
326 if (indirect_symbol == MachO::INDIRECT_SYMBOL_ABS) {
327 outs() << "ABSOLUTE\n";
330 outs() << format("%5u ", indirect_symbol);
331 MachO::symtab_command Symtab = O->getSymtabLoadCommand();
332 if (indirect_symbol < Symtab.nsyms) {
333 symbol_iterator Sym = O->getSymbolByIndex(indirect_symbol);
334 SymbolRef Symbol = *Sym;
336 Symbol.getName(SymName);
345 static void PrintIndirectSymbols(MachOObjectFile *O, bool verbose) {
346 uint32_t LoadCommandCount = O->getHeader().ncmds;
347 MachOObjectFile::LoadCommandInfo Load = O->getFirstLoadCommandInfo();
348 for (unsigned I = 0;; ++I) {
349 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
350 MachO::segment_command_64 Seg = O->getSegment64LoadCommand(Load);
351 for (unsigned J = 0; J < Seg.nsects; ++J) {
352 MachO::section_64 Sec = O->getSection64(Load, J);
353 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
354 if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
355 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
356 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
357 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
358 section_type == MachO::S_SYMBOL_STUBS) {
360 if (section_type == MachO::S_SYMBOL_STUBS)
361 stride = Sec.reserved2;
365 outs() << "Can't print indirect symbols for (" << Sec.segname << ","
366 << Sec.sectname << ") "
367 << "(size of stubs in reserved2 field is zero)\n";
370 uint32_t count = Sec.size / stride;
371 outs() << "Indirect symbols for (" << Sec.segname << ","
372 << Sec.sectname << ") " << count << " entries";
373 uint32_t n = Sec.reserved1;
374 PrintIndirectSymbolTable(O, verbose, n, count, stride, Sec.addr);
377 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
378 MachO::segment_command Seg = O->getSegmentLoadCommand(Load);
379 for (unsigned J = 0; J < Seg.nsects; ++J) {
380 MachO::section Sec = O->getSection(Load, J);
381 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
382 if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
383 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
384 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
385 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
386 section_type == MachO::S_SYMBOL_STUBS) {
388 if (section_type == MachO::S_SYMBOL_STUBS)
389 stride = Sec.reserved2;
393 outs() << "Can't print indirect symbols for (" << Sec.segname << ","
394 << Sec.sectname << ") "
395 << "(size of stubs in reserved2 field is zero)\n";
398 uint32_t count = Sec.size / stride;
399 outs() << "Indirect symbols for (" << Sec.segname << ","
400 << Sec.sectname << ") " << count << " entries";
401 uint32_t n = Sec.reserved1;
402 PrintIndirectSymbolTable(O, verbose, n, count, stride, Sec.addr);
406 if (I == LoadCommandCount - 1)
409 Load = O->getNextLoadCommandInfo(Load);
413 static void PrintDataInCodeTable(MachOObjectFile *O, bool verbose) {
414 MachO::linkedit_data_command DIC = O->getDataInCodeLoadCommand();
415 uint32_t nentries = DIC.datasize / sizeof(struct MachO::data_in_code_entry);
416 outs() << "Data in code table (" << nentries << " entries)\n";
417 outs() << "offset length kind\n";
418 for (dice_iterator DI = O->begin_dices(), DE = O->end_dices(); DI != DE;
421 DI->getOffset(Offset);
422 outs() << format("0x%08" PRIx32, Offset) << " ";
424 DI->getLength(Length);
425 outs() << format("%6u", Length) << " ";
430 case MachO::DICE_KIND_DATA:
433 case MachO::DICE_KIND_JUMP_TABLE8:
434 outs() << "JUMP_TABLE8";
436 case MachO::DICE_KIND_JUMP_TABLE16:
437 outs() << "JUMP_TABLE16";
439 case MachO::DICE_KIND_JUMP_TABLE32:
440 outs() << "JUMP_TABLE32";
442 case MachO::DICE_KIND_ABS_JUMP_TABLE32:
443 outs() << "ABS_JUMP_TABLE32";
446 outs() << format("0x%04" PRIx32, Kind);
450 outs() << format("0x%04" PRIx32, Kind);
455 static void PrintLinkOptHints(MachOObjectFile *O) {
456 MachO::linkedit_data_command LohLC = O->getLinkOptHintsLoadCommand();
457 const char *loh = O->getData().substr(LohLC.dataoff, 1).data();
458 uint32_t nloh = LohLC.datasize;
459 outs() << "Linker optimiztion hints (" << nloh << " total bytes)\n";
460 for (uint32_t i = 0; i < nloh;) {
462 uint64_t identifier = decodeULEB128((const uint8_t *)(loh + i), &n);
464 outs() << " identifier " << identifier << " ";
467 switch (identifier) {
469 outs() << "AdrpAdrp\n";
472 outs() << "AdrpLdr\n";
475 outs() << "AdrpAddLdr\n";
478 outs() << "AdrpLdrGotLdr\n";
481 outs() << "AdrpAddStr\n";
484 outs() << "AdrpLdrGotStr\n";
487 outs() << "AdrpAdd\n";
490 outs() << "AdrpLdrGot\n";
493 outs() << "Unknown identifier value\n";
496 uint64_t narguments = decodeULEB128((const uint8_t *)(loh + i), &n);
498 outs() << " narguments " << narguments << "\n";
502 for (uint32_t j = 0; j < narguments; j++) {
503 uint64_t value = decodeULEB128((const uint8_t *)(loh + i), &n);
505 outs() << "\tvalue " << format("0x%" PRIx64, value) << "\n";
512 typedef DenseMap<uint64_t, StringRef> SymbolAddressMap;
514 static void CreateSymbolAddressMap(MachOObjectFile *O,
515 SymbolAddressMap *AddrMap) {
516 // Create a map of symbol addresses to symbol names.
517 for (const SymbolRef &Symbol : O->symbols()) {
520 if (ST == SymbolRef::ST_Function || ST == SymbolRef::ST_Data ||
521 ST == SymbolRef::ST_Other) {
523 Symbol.getAddress(Address);
525 Symbol.getName(SymName);
526 (*AddrMap)[Address] = SymName;
531 // GuessSymbolName is passed the address of what might be a symbol and a
532 // pointer to the SymbolAddressMap. It returns the name of a symbol
533 // with that address or nullptr if no symbol is found with that address.
534 static const char *GuessSymbolName(uint64_t value, SymbolAddressMap *AddrMap) {
535 const char *SymbolName = nullptr;
536 // A DenseMap can't lookup up some values.
537 if (value != 0xffffffffffffffffULL && value != 0xfffffffffffffffeULL) {
538 StringRef name = AddrMap->lookup(value);
540 SymbolName = name.data();
545 static void DumpCstringChar(const char c) {
549 outs().write_escaped(p);
552 static void DumpCstringSection(MachOObjectFile *O, const char *sect,
553 uint32_t sect_size, uint64_t sect_addr,
554 bool print_addresses) {
555 for (uint32_t i = 0; i < sect_size; i++) {
556 if (print_addresses) {
558 outs() << format("%016" PRIx64, sect_addr + i) << " ";
560 outs() << format("%08" PRIx64, sect_addr + i) << " ";
562 for (; i < sect_size && sect[i] != '\0'; i++)
563 DumpCstringChar(sect[i]);
564 if (i < sect_size && sect[i] == '\0')
569 static void DumpLiteral4(uint32_t l, float f) {
570 outs() << format("0x%08" PRIx32, l);
571 if ((l & 0x7f800000) != 0x7f800000)
572 outs() << format(" (%.16e)\n", f);
575 outs() << " (+Infinity)\n";
576 else if (l == 0xff800000)
577 outs() << " (-Infinity)\n";
578 else if ((l & 0x00400000) == 0x00400000)
579 outs() << " (non-signaling Not-a-Number)\n";
581 outs() << " (signaling Not-a-Number)\n";
585 static void DumpLiteral4Section(MachOObjectFile *O, const char *sect,
586 uint32_t sect_size, uint64_t sect_addr,
587 bool print_addresses) {
588 for (uint32_t i = 0; i < sect_size; i += sizeof(float)) {
589 if (print_addresses) {
591 outs() << format("%016" PRIx64, sect_addr + i) << " ";
593 outs() << format("%08" PRIx64, sect_addr + i) << " ";
596 memcpy(&f, sect + i, sizeof(float));
597 if (O->isLittleEndian() != sys::IsLittleEndianHost)
598 sys::swapByteOrder(f);
600 memcpy(&l, sect + i, sizeof(uint32_t));
601 if (O->isLittleEndian() != sys::IsLittleEndianHost)
602 sys::swapByteOrder(l);
607 static void DumpLiteral8(MachOObjectFile *O, uint32_t l0, uint32_t l1,
609 outs() << format("0x%08" PRIx32, l0) << " " << format("0x%08" PRIx32, l1);
611 if (O->isLittleEndian()) {
618 // Hi is the high word, so this is equivalent to if(isfinite(d))
619 if ((Hi & 0x7ff00000) != 0x7ff00000)
620 outs() << format(" (%.16e)\n", d);
622 if (Hi == 0x7ff00000 && Lo == 0)
623 outs() << " (+Infinity)\n";
624 else if (Hi == 0xfff00000 && Lo == 0)
625 outs() << " (-Infinity)\n";
626 else if ((Hi & 0x00080000) == 0x00080000)
627 outs() << " (non-signaling Not-a-Number)\n";
629 outs() << " (signaling Not-a-Number)\n";
633 static void DumpLiteral8Section(MachOObjectFile *O, const char *sect,
634 uint32_t sect_size, uint64_t sect_addr,
635 bool print_addresses) {
636 for (uint32_t i = 0; i < sect_size; i += sizeof(double)) {
637 if (print_addresses) {
639 outs() << format("%016" PRIx64, sect_addr + i) << " ";
641 outs() << format("%08" PRIx64, sect_addr + i) << " ";
644 memcpy(&d, sect + i, sizeof(double));
645 if (O->isLittleEndian() != sys::IsLittleEndianHost)
646 sys::swapByteOrder(d);
648 memcpy(&l0, sect + i, sizeof(uint32_t));
649 memcpy(&l1, sect + i + sizeof(uint32_t), sizeof(uint32_t));
650 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
651 sys::swapByteOrder(l0);
652 sys::swapByteOrder(l1);
654 DumpLiteral8(O, l0, l1, d);
658 static void DumpLiteral16(uint32_t l0, uint32_t l1, uint32_t l2, uint32_t l3) {
659 outs() << format("0x%08" PRIx32, l0) << " ";
660 outs() << format("0x%08" PRIx32, l1) << " ";
661 outs() << format("0x%08" PRIx32, l2) << " ";
662 outs() << format("0x%08" PRIx32, l3) << "\n";
665 static void DumpLiteral16Section(MachOObjectFile *O, const char *sect,
666 uint32_t sect_size, uint64_t sect_addr,
667 bool print_addresses) {
668 for (uint32_t i = 0; i < sect_size; i += 16) {
669 if (print_addresses) {
671 outs() << format("%016" PRIx64, sect_addr + i) << " ";
673 outs() << format("%08" PRIx64, sect_addr + i) << " ";
675 uint32_t l0, l1, l2, l3;
676 memcpy(&l0, sect + i, sizeof(uint32_t));
677 memcpy(&l1, sect + i + sizeof(uint32_t), sizeof(uint32_t));
678 memcpy(&l2, sect + i + 2 * sizeof(uint32_t), sizeof(uint32_t));
679 memcpy(&l3, sect + i + 3 * sizeof(uint32_t), sizeof(uint32_t));
680 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
681 sys::swapByteOrder(l0);
682 sys::swapByteOrder(l1);
683 sys::swapByteOrder(l2);
684 sys::swapByteOrder(l3);
686 DumpLiteral16(l0, l1, l2, l3);
690 static void DumpLiteralPointerSection(MachOObjectFile *O,
691 const SectionRef &Section,
692 const char *sect, uint32_t sect_size,
694 bool print_addresses) {
695 // Collect the literal sections in this Mach-O file.
696 std::vector<SectionRef> LiteralSections;
697 for (const SectionRef &Section : O->sections()) {
698 DataRefImpl Ref = Section.getRawDataRefImpl();
699 uint32_t section_type;
701 const MachO::section_64 Sec = O->getSection64(Ref);
702 section_type = Sec.flags & MachO::SECTION_TYPE;
704 const MachO::section Sec = O->getSection(Ref);
705 section_type = Sec.flags & MachO::SECTION_TYPE;
707 if (section_type == MachO::S_CSTRING_LITERALS ||
708 section_type == MachO::S_4BYTE_LITERALS ||
709 section_type == MachO::S_8BYTE_LITERALS ||
710 section_type == MachO::S_16BYTE_LITERALS)
711 LiteralSections.push_back(Section);
714 // Set the size of the literal pointer.
715 uint32_t lp_size = O->is64Bit() ? 8 : 4;
717 // Collect the external relocation symbols for the the literal pointers.
718 std::vector<std::pair<uint64_t, SymbolRef>> Relocs;
719 for (const RelocationRef &Reloc : Section.relocations()) {
721 MachO::any_relocation_info RE;
722 bool isExtern = false;
723 Rel = Reloc.getRawDataRefImpl();
724 RE = O->getRelocation(Rel);
725 isExtern = O->getPlainRelocationExternal(RE);
727 uint64_t RelocOffset;
728 Reloc.getOffset(RelocOffset);
729 symbol_iterator RelocSym = Reloc.getSymbol();
730 Relocs.push_back(std::make_pair(RelocOffset, *RelocSym));
733 array_pod_sort(Relocs.begin(), Relocs.end());
735 // Dump each literal pointer.
736 for (uint32_t i = 0; i < sect_size; i += lp_size) {
737 if (print_addresses) {
739 outs() << format("%016" PRIx64, sect_addr + i) << " ";
741 outs() << format("%08" PRIx64, sect_addr + i) << " ";
745 memcpy(&lp, sect + i, sizeof(uint64_t));
746 if (O->isLittleEndian() != sys::IsLittleEndianHost)
747 sys::swapByteOrder(lp);
750 memcpy(&li, sect + i, sizeof(uint32_t));
751 if (O->isLittleEndian() != sys::IsLittleEndianHost)
752 sys::swapByteOrder(li);
756 // First look for an external relocation entry for this literal pointer.
757 bool reloc_found = false;
758 for (unsigned j = 0, e = Relocs.size(); j != e; ++j) {
759 if (Relocs[i].first == i) {
760 symbol_iterator RelocSym = Relocs[j].second;
762 RelocSym->getName(SymName);
763 outs() << "external relocation entry for symbol:" << SymName << "\n";
767 if (reloc_found == true)
770 // For local references see what the section the literal pointer points to.
772 for (unsigned SectIdx = 0; SectIdx != LiteralSections.size(); SectIdx++) {
773 uint64_t SectAddress = LiteralSections[SectIdx].getAddress();
774 uint64_t SectSize = LiteralSections[SectIdx].getSize();
775 if (lp >= SectAddress && lp < SectAddress + SectSize) {
779 LiteralSections[SectIdx].getName(SectName);
780 DataRefImpl Ref = LiteralSections[SectIdx].getRawDataRefImpl();
781 StringRef SegmentName = O->getSectionFinalSegmentName(Ref);
782 outs() << SegmentName << ":" << SectName << ":";
784 uint32_t section_type;
786 const MachO::section_64 Sec = O->getSection64(Ref);
787 section_type = Sec.flags & MachO::SECTION_TYPE;
789 const MachO::section Sec = O->getSection(Ref);
790 section_type = Sec.flags & MachO::SECTION_TYPE;
794 LiteralSections[SectIdx].getContents(BytesStr);
795 const char *Contents = reinterpret_cast<const char *>(BytesStr.data());
797 switch (section_type) {
798 case MachO::S_CSTRING_LITERALS:
799 for (uint64_t i = lp - SectAddress;
800 i < SectSize && Contents[i] != '\0'; i++) {
801 DumpCstringChar(Contents[i]);
805 case MachO::S_4BYTE_LITERALS:
807 memcpy(&f, Contents + (lp - SectAddress), sizeof(float));
809 memcpy(&l, Contents + (lp - SectAddress), sizeof(uint32_t));
810 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
811 sys::swapByteOrder(f);
812 sys::swapByteOrder(l);
816 case MachO::S_8BYTE_LITERALS: {
818 memcpy(&d, Contents + (lp - SectAddress), sizeof(double));
820 memcpy(&l0, Contents + (lp - SectAddress), sizeof(uint32_t));
821 memcpy(&l1, Contents + (lp - SectAddress) + sizeof(uint32_t),
823 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
824 sys::swapByteOrder(f);
825 sys::swapByteOrder(l0);
826 sys::swapByteOrder(l1);
828 DumpLiteral8(O, l0, l1, d);
831 case MachO::S_16BYTE_LITERALS: {
832 uint32_t l0, l1, l2, l3;
833 memcpy(&l0, Contents + (lp - SectAddress), sizeof(uint32_t));
834 memcpy(&l1, Contents + (lp - SectAddress) + sizeof(uint32_t),
836 memcpy(&l2, Contents + (lp - SectAddress) + 2 * sizeof(uint32_t),
838 memcpy(&l3, Contents + (lp - SectAddress) + 3 * sizeof(uint32_t),
840 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
841 sys::swapByteOrder(l0);
842 sys::swapByteOrder(l1);
843 sys::swapByteOrder(l2);
844 sys::swapByteOrder(l3);
846 DumpLiteral16(l0, l1, l2, l3);
853 outs() << format("0x%" PRIx64, lp) << " (not in a literal section)\n";
857 static void DumpInitTermPointerSection(MachOObjectFile *O, const char *sect,
858 uint32_t sect_size, uint64_t sect_addr,
859 SymbolAddressMap *AddrMap,
863 stride = sizeof(uint64_t);
865 stride = sizeof(uint32_t);
866 for (uint32_t i = 0; i < sect_size; i += stride) {
867 const char *SymbolName = nullptr;
869 outs() << format("0x%016" PRIx64, sect_addr + i * stride) << " ";
870 uint64_t pointer_value;
871 memcpy(&pointer_value, sect + i, stride);
872 if (O->isLittleEndian() != sys::IsLittleEndianHost)
873 sys::swapByteOrder(pointer_value);
874 outs() << format("0x%016" PRIx64, pointer_value);
876 SymbolName = GuessSymbolName(pointer_value, AddrMap);
878 outs() << format("0x%08" PRIx64, sect_addr + i * stride) << " ";
879 uint32_t pointer_value;
880 memcpy(&pointer_value, sect + i, stride);
881 if (O->isLittleEndian() != sys::IsLittleEndianHost)
882 sys::swapByteOrder(pointer_value);
883 outs() << format("0x%08" PRIx32, pointer_value);
885 SymbolName = GuessSymbolName(pointer_value, AddrMap);
888 outs() << " " << SymbolName;
893 static void DumpRawSectionContents(MachOObjectFile *O, const char *sect,
894 uint32_t size, uint64_t addr) {
895 uint32_t cputype = O->getHeader().cputype;
896 if (cputype == MachO::CPU_TYPE_I386 || cputype == MachO::CPU_TYPE_X86_64) {
898 for (uint32_t i = 0; i < size; i += j, addr += j) {
900 outs() << format("%016" PRIx64, addr) << "\t";
902 outs() << format("%08" PRIx64, sect) << "\t";
903 for (j = 0; j < 16 && i + j < size; j++) {
904 uint8_t byte_word = *(sect + i + j);
905 outs() << format("%02" PRIx32, (uint32_t)byte_word) << " ";
911 for (uint32_t i = 0; i < size; i += j, addr += j) {
913 outs() << format("%016" PRIx64, addr) << "\t";
915 outs() << format("%08" PRIx64, sect) << "\t";
916 for (j = 0; j < 4 * sizeof(int32_t) && i + j < size;
917 j += sizeof(int32_t)) {
918 if (i + j + sizeof(int32_t) < size) {
920 memcpy(&long_word, sect + i + j, sizeof(int32_t));
921 if (O->isLittleEndian() != sys::IsLittleEndianHost)
922 sys::swapByteOrder(long_word);
923 outs() << format("%08" PRIx32, long_word) << " ";
925 for (uint32_t k = 0; i + j + k < size; k++) {
926 uint8_t byte_word = *(sect + i + j);
927 outs() << format("%02" PRIx32, (uint32_t)byte_word) << " ";
936 static void DisassembleMachO(StringRef Filename, MachOObjectFile *MachOOF,
937 StringRef DisSegName, StringRef DisSectName);
939 static void DumpSectionContents(StringRef Filename, MachOObjectFile *O,
941 SymbolAddressMap AddrMap;
943 CreateSymbolAddressMap(O, &AddrMap);
945 for (unsigned i = 0; i < DumpSections.size(); ++i) {
946 StringRef DumpSection = DumpSections[i];
947 std::pair<StringRef, StringRef> DumpSegSectName;
948 DumpSegSectName = DumpSection.split(',');
949 StringRef DumpSegName, DumpSectName;
950 if (DumpSegSectName.second.size()) {
951 DumpSegName = DumpSegSectName.first;
952 DumpSectName = DumpSegSectName.second;
955 DumpSectName = DumpSegSectName.first;
957 for (const SectionRef &Section : O->sections()) {
959 Section.getName(SectName);
960 DataRefImpl Ref = Section.getRawDataRefImpl();
961 StringRef SegName = O->getSectionFinalSegmentName(Ref);
962 if ((DumpSegName.empty() || SegName == DumpSegName) &&
963 (SectName == DumpSectName)) {
964 outs() << "Contents of (" << SegName << "," << SectName
966 uint32_t section_flags;
968 const MachO::section_64 Sec = O->getSection64(Ref);
969 section_flags = Sec.flags;
972 const MachO::section Sec = O->getSection(Ref);
973 section_flags = Sec.flags;
975 uint32_t section_type = section_flags & MachO::SECTION_TYPE;
978 Section.getContents(BytesStr);
979 const char *sect = reinterpret_cast<const char *>(BytesStr.data());
980 uint32_t sect_size = BytesStr.size();
981 uint64_t sect_addr = Section.getAddress();
984 if ((section_flags & MachO::S_ATTR_PURE_INSTRUCTIONS) ||
985 (section_flags & MachO::S_ATTR_SOME_INSTRUCTIONS)) {
986 DisassembleMachO(Filename, O, SegName, SectName);
989 if (SegName == "__TEXT" && SectName == "__info_plist") {
993 switch (section_type) {
994 case MachO::S_REGULAR:
995 DumpRawSectionContents(O, sect, sect_size, sect_addr);
997 case MachO::S_ZEROFILL:
998 outs() << "zerofill section and has no contents in the file\n";
1000 case MachO::S_CSTRING_LITERALS:
1001 DumpCstringSection(O, sect, sect_size, sect_addr, verbose);
1003 case MachO::S_4BYTE_LITERALS:
1004 DumpLiteral4Section(O, sect, sect_size, sect_addr, verbose);
1006 case MachO::S_8BYTE_LITERALS:
1007 DumpLiteral8Section(O, sect, sect_size, sect_addr, verbose);
1009 case MachO::S_16BYTE_LITERALS:
1010 DumpLiteral16Section(O, sect, sect_size, sect_addr, verbose);
1012 case MachO::S_LITERAL_POINTERS:
1013 DumpLiteralPointerSection(O, Section, sect, sect_size, sect_addr,
1016 case MachO::S_MOD_INIT_FUNC_POINTERS:
1017 case MachO::S_MOD_TERM_FUNC_POINTERS:
1018 DumpInitTermPointerSection(O, sect, sect_size, sect_addr, &AddrMap,
1022 outs() << "Unknown section type ("
1023 << format("0x%08" PRIx32, section_type) << ")\n";
1024 DumpRawSectionContents(O, sect, sect_size, sect_addr);
1028 if (section_type == MachO::S_ZEROFILL)
1029 outs() << "zerofill section and has no contents in the file\n";
1031 DumpRawSectionContents(O, sect, sect_size, sect_addr);
1038 static void DumpInfoPlistSectionContents(StringRef Filename,
1039 MachOObjectFile *O) {
1040 for (const SectionRef &Section : O->sections()) {
1042 Section.getName(SectName);
1043 DataRefImpl Ref = Section.getRawDataRefImpl();
1044 StringRef SegName = O->getSectionFinalSegmentName(Ref);
1045 if (SegName == "__TEXT" && SectName == "__info_plist") {
1046 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
1048 Section.getContents(BytesStr);
1049 const char *sect = reinterpret_cast<const char *>(BytesStr.data());
1056 // checkMachOAndArchFlags() checks to see if the ObjectFile is a Mach-O file
1057 // and if it is and there is a list of architecture flags is specified then
1058 // check to make sure this Mach-O file is one of those architectures or all
1059 // architectures were specified. If not then an error is generated and this
1060 // routine returns false. Else it returns true.
1061 static bool checkMachOAndArchFlags(ObjectFile *O, StringRef Filename) {
1062 if (isa<MachOObjectFile>(O) && !ArchAll && ArchFlags.size() != 0) {
1063 MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(O);
1064 bool ArchFound = false;
1065 MachO::mach_header H;
1066 MachO::mach_header_64 H_64;
1068 if (MachO->is64Bit()) {
1069 H_64 = MachO->MachOObjectFile::getHeader64();
1070 T = MachOObjectFile::getArch(H_64.cputype, H_64.cpusubtype);
1072 H = MachO->MachOObjectFile::getHeader();
1073 T = MachOObjectFile::getArch(H.cputype, H.cpusubtype);
1076 for (i = 0; i < ArchFlags.size(); ++i) {
1077 if (ArchFlags[i] == T.getArchName())
1082 errs() << "llvm-objdump: file: " + Filename + " does not contain "
1083 << "architecture: " + ArchFlags[i] + "\n";
1090 // ProcessMachO() is passed a single opened Mach-O file, which may be an
1091 // archive member and or in a slice of a universal file. It prints the
1092 // the file name and header info and then processes it according to the
1093 // command line options.
1094 static void ProcessMachO(StringRef Filename, MachOObjectFile *MachOOF,
1095 StringRef ArchiveMemberName = StringRef(),
1096 StringRef ArchitectureName = StringRef()) {
1097 // If we are doing some processing here on the Mach-O file print the header
1098 // info. And don't print it otherwise like in the case of printing the
1099 // UniversalHeaders or ArchiveHeaders.
1100 if (Disassemble || PrivateHeaders || ExportsTrie || Rebase || Bind ||
1101 LazyBind || WeakBind || IndirectSymbols || DataInCode || LinkOptHints ||
1102 DumpSections.size() != 0) {
1104 if (!ArchiveMemberName.empty())
1105 outs() << '(' << ArchiveMemberName << ')';
1106 if (!ArchitectureName.empty())
1107 outs() << " (architecture " << ArchitectureName << ")";
1112 DisassembleMachO(Filename, MachOOF, "__TEXT", "__text");
1113 if (IndirectSymbols)
1114 PrintIndirectSymbols(MachOOF, true);
1116 PrintDataInCodeTable(MachOOF, true);
1118 PrintLinkOptHints(MachOOF);
1120 PrintRelocations(MachOOF);
1122 PrintSectionHeaders(MachOOF);
1123 if (SectionContents)
1124 PrintSectionContents(MachOOF);
1125 if (DumpSections.size() != 0)
1126 DumpSectionContents(Filename, MachOOF, true);
1128 DumpInfoPlistSectionContents(Filename, MachOOF);
1130 PrintSymbolTable(MachOOF);
1132 printMachOUnwindInfo(MachOOF);
1134 printMachOFileHeader(MachOOF);
1136 printExportsTrie(MachOOF);
1138 printRebaseTable(MachOOF);
1140 printBindTable(MachOOF);
1142 printLazyBindTable(MachOOF);
1144 printWeakBindTable(MachOOF);
1147 // printUnknownCPUType() helps print_fat_headers for unknown CPU's.
1148 static void printUnknownCPUType(uint32_t cputype, uint32_t cpusubtype) {
1149 outs() << " cputype (" << cputype << ")\n";
1150 outs() << " cpusubtype (" << cpusubtype << ")\n";
1153 // printCPUType() helps print_fat_headers by printing the cputype and
1154 // pusubtype (symbolically for the one's it knows about).
1155 static void printCPUType(uint32_t cputype, uint32_t cpusubtype) {
1157 case MachO::CPU_TYPE_I386:
1158 switch (cpusubtype) {
1159 case MachO::CPU_SUBTYPE_I386_ALL:
1160 outs() << " cputype CPU_TYPE_I386\n";
1161 outs() << " cpusubtype CPU_SUBTYPE_I386_ALL\n";
1164 printUnknownCPUType(cputype, cpusubtype);
1168 case MachO::CPU_TYPE_X86_64:
1169 switch (cpusubtype) {
1170 case MachO::CPU_SUBTYPE_X86_64_ALL:
1171 outs() << " cputype CPU_TYPE_X86_64\n";
1172 outs() << " cpusubtype CPU_SUBTYPE_X86_64_ALL\n";
1174 case MachO::CPU_SUBTYPE_X86_64_H:
1175 outs() << " cputype CPU_TYPE_X86_64\n";
1176 outs() << " cpusubtype CPU_SUBTYPE_X86_64_H\n";
1179 printUnknownCPUType(cputype, cpusubtype);
1183 case MachO::CPU_TYPE_ARM:
1184 switch (cpusubtype) {
1185 case MachO::CPU_SUBTYPE_ARM_ALL:
1186 outs() << " cputype CPU_TYPE_ARM\n";
1187 outs() << " cpusubtype CPU_SUBTYPE_ARM_ALL\n";
1189 case MachO::CPU_SUBTYPE_ARM_V4T:
1190 outs() << " cputype CPU_TYPE_ARM\n";
1191 outs() << " cpusubtype CPU_SUBTYPE_ARM_V4T\n";
1193 case MachO::CPU_SUBTYPE_ARM_V5TEJ:
1194 outs() << " cputype CPU_TYPE_ARM\n";
1195 outs() << " cpusubtype CPU_SUBTYPE_ARM_V5TEJ\n";
1197 case MachO::CPU_SUBTYPE_ARM_XSCALE:
1198 outs() << " cputype CPU_TYPE_ARM\n";
1199 outs() << " cpusubtype CPU_SUBTYPE_ARM_XSCALE\n";
1201 case MachO::CPU_SUBTYPE_ARM_V6:
1202 outs() << " cputype CPU_TYPE_ARM\n";
1203 outs() << " cpusubtype CPU_SUBTYPE_ARM_V6\n";
1205 case MachO::CPU_SUBTYPE_ARM_V6M:
1206 outs() << " cputype CPU_TYPE_ARM\n";
1207 outs() << " cpusubtype CPU_SUBTYPE_ARM_V6M\n";
1209 case MachO::CPU_SUBTYPE_ARM_V7:
1210 outs() << " cputype CPU_TYPE_ARM\n";
1211 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7\n";
1213 case MachO::CPU_SUBTYPE_ARM_V7EM:
1214 outs() << " cputype CPU_TYPE_ARM\n";
1215 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7EM\n";
1217 case MachO::CPU_SUBTYPE_ARM_V7K:
1218 outs() << " cputype CPU_TYPE_ARM\n";
1219 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7K\n";
1221 case MachO::CPU_SUBTYPE_ARM_V7M:
1222 outs() << " cputype CPU_TYPE_ARM\n";
1223 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7M\n";
1225 case MachO::CPU_SUBTYPE_ARM_V7S:
1226 outs() << " cputype CPU_TYPE_ARM\n";
1227 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7S\n";
1230 printUnknownCPUType(cputype, cpusubtype);
1234 case MachO::CPU_TYPE_ARM64:
1235 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
1236 case MachO::CPU_SUBTYPE_ARM64_ALL:
1237 outs() << " cputype CPU_TYPE_ARM64\n";
1238 outs() << " cpusubtype CPU_SUBTYPE_ARM64_ALL\n";
1241 printUnknownCPUType(cputype, cpusubtype);
1246 printUnknownCPUType(cputype, cpusubtype);
1251 static void printMachOUniversalHeaders(const object::MachOUniversalBinary *UB,
1253 outs() << "Fat headers\n";
1255 outs() << "fat_magic FAT_MAGIC\n";
1257 outs() << "fat_magic " << format("0x%" PRIx32, MachO::FAT_MAGIC) << "\n";
1259 uint32_t nfat_arch = UB->getNumberOfObjects();
1260 StringRef Buf = UB->getData();
1261 uint64_t size = Buf.size();
1262 uint64_t big_size = sizeof(struct MachO::fat_header) +
1263 nfat_arch * sizeof(struct MachO::fat_arch);
1264 outs() << "nfat_arch " << UB->getNumberOfObjects();
1266 outs() << " (malformed, contains zero architecture types)\n";
1267 else if (big_size > size)
1268 outs() << " (malformed, architectures past end of file)\n";
1272 for (uint32_t i = 0; i < nfat_arch; ++i) {
1273 MachOUniversalBinary::ObjectForArch OFA(UB, i);
1274 uint32_t cputype = OFA.getCPUType();
1275 uint32_t cpusubtype = OFA.getCPUSubType();
1276 outs() << "architecture ";
1277 for (uint32_t j = 0; i != 0 && j <= i - 1; j++) {
1278 MachOUniversalBinary::ObjectForArch other_OFA(UB, j);
1279 uint32_t other_cputype = other_OFA.getCPUType();
1280 uint32_t other_cpusubtype = other_OFA.getCPUSubType();
1281 if (cputype != 0 && cpusubtype != 0 && cputype == other_cputype &&
1282 (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) ==
1283 (other_cpusubtype & ~MachO::CPU_SUBTYPE_MASK)) {
1284 outs() << "(illegal duplicate architecture) ";
1289 outs() << OFA.getArchTypeName() << "\n";
1290 printCPUType(cputype, cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
1292 outs() << i << "\n";
1293 outs() << " cputype " << cputype << "\n";
1294 outs() << " cpusubtype " << (cpusubtype & ~MachO::CPU_SUBTYPE_MASK)
1298 (cpusubtype & MachO::CPU_SUBTYPE_MASK) == MachO::CPU_SUBTYPE_LIB64)
1299 outs() << " capabilities CPU_SUBTYPE_LIB64\n";
1301 outs() << " capabilities "
1302 << format("0x%" PRIx32,
1303 (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24) << "\n";
1304 outs() << " offset " << OFA.getOffset();
1305 if (OFA.getOffset() > size)
1306 outs() << " (past end of file)";
1307 if (OFA.getOffset() % (1 << OFA.getAlign()) != 0)
1308 outs() << " (not aligned on it's alignment (2^" << OFA.getAlign() << ")";
1310 outs() << " size " << OFA.getSize();
1311 big_size = OFA.getOffset() + OFA.getSize();
1312 if (big_size > size)
1313 outs() << " (past end of file)";
1315 outs() << " align 2^" << OFA.getAlign() << " (" << (1 << OFA.getAlign())
1320 static void printArchiveChild(Archive::Child &C, bool verbose,
1321 bool print_offset) {
1323 outs() << C.getChildOffset() << "\t";
1324 sys::fs::perms Mode = C.getAccessMode();
1326 // FIXME: this first dash, "-", is for (Mode & S_IFMT) == S_IFREG.
1327 // But there is nothing in sys::fs::perms for S_IFMT or S_IFREG.
1329 if (Mode & sys::fs::owner_read)
1333 if (Mode & sys::fs::owner_write)
1337 if (Mode & sys::fs::owner_exe)
1341 if (Mode & sys::fs::group_read)
1345 if (Mode & sys::fs::group_write)
1349 if (Mode & sys::fs::group_exe)
1353 if (Mode & sys::fs::others_read)
1357 if (Mode & sys::fs::others_write)
1361 if (Mode & sys::fs::others_exe)
1366 outs() << format("0%o ", Mode);
1369 unsigned UID = C.getUID();
1370 outs() << format("%3d/", UID);
1371 unsigned GID = C.getGID();
1372 outs() << format("%-3d ", GID);
1373 uint64_t Size = C.getRawSize();
1374 outs() << format("%5" PRId64, Size) << " ";
1376 StringRef RawLastModified = C.getRawLastModified();
1379 if (RawLastModified.getAsInteger(10, Seconds))
1380 outs() << "(date: \"%s\" contains non-decimal chars) " << RawLastModified;
1382 // Since cime(3) returns a 26 character string of the form:
1383 // "Sun Sep 16 01:03:52 1973\n\0"
1384 // just print 24 characters.
1386 outs() << format("%.24s ", ctime(&t));
1389 outs() << RawLastModified << " ";
1393 ErrorOr<StringRef> NameOrErr = C.getName();
1394 if (NameOrErr.getError()) {
1395 StringRef RawName = C.getRawName();
1396 outs() << RawName << "\n";
1398 StringRef Name = NameOrErr.get();
1399 outs() << Name << "\n";
1402 StringRef RawName = C.getRawName();
1403 outs() << RawName << "\n";
1407 static void printArchiveHeaders(Archive *A, bool verbose, bool print_offset) {
1408 if (A->hasSymbolTable()) {
1409 Archive::child_iterator S = A->getSymbolTableChild();
1410 Archive::Child C = *S;
1411 printArchiveChild(C, verbose, print_offset);
1413 for (Archive::child_iterator I = A->child_begin(), E = A->child_end(); I != E;
1415 Archive::Child C = *I;
1416 printArchiveChild(C, verbose, print_offset);
1420 // ParseInputMachO() parses the named Mach-O file in Filename and handles the
1421 // -arch flags selecting just those slices as specified by them and also parses
1422 // archive files. Then for each individual Mach-O file ProcessMachO() is
1423 // called to process the file based on the command line options.
1424 void llvm::ParseInputMachO(StringRef Filename) {
1425 // Check for -arch all and verifiy the -arch flags are valid.
1426 for (unsigned i = 0; i < ArchFlags.size(); ++i) {
1427 if (ArchFlags[i] == "all") {
1430 if (!MachOObjectFile::isValidArch(ArchFlags[i])) {
1431 errs() << "llvm-objdump: Unknown architecture named '" + ArchFlags[i] +
1432 "'for the -arch option\n";
1438 // Attempt to open the binary.
1439 ErrorOr<OwningBinary<Binary>> BinaryOrErr = createBinary(Filename);
1440 if (std::error_code EC = BinaryOrErr.getError()) {
1441 errs() << "llvm-objdump: '" << Filename << "': " << EC.message() << ".\n";
1444 Binary &Bin = *BinaryOrErr.get().getBinary();
1446 if (Archive *A = dyn_cast<Archive>(&Bin)) {
1447 outs() << "Archive : " << Filename << "\n";
1449 printArchiveHeaders(A, true, false);
1450 for (Archive::child_iterator I = A->child_begin(), E = A->child_end();
1452 ErrorOr<std::unique_ptr<Binary>> ChildOrErr = I->getAsBinary();
1453 if (ChildOrErr.getError())
1455 if (MachOObjectFile *O = dyn_cast<MachOObjectFile>(&*ChildOrErr.get())) {
1456 if (!checkMachOAndArchFlags(O, Filename))
1458 ProcessMachO(Filename, O, O->getFileName());
1463 if (UniversalHeaders) {
1464 if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(&Bin))
1465 printMachOUniversalHeaders(UB, true);
1467 if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(&Bin)) {
1468 // If we have a list of architecture flags specified dump only those.
1469 if (!ArchAll && ArchFlags.size() != 0) {
1470 // Look for a slice in the universal binary that matches each ArchFlag.
1472 for (unsigned i = 0; i < ArchFlags.size(); ++i) {
1474 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
1475 E = UB->end_objects();
1477 if (ArchFlags[i] == I->getArchTypeName()) {
1479 ErrorOr<std::unique_ptr<ObjectFile>> ObjOrErr =
1480 I->getAsObjectFile();
1481 std::string ArchitectureName = "";
1482 if (ArchFlags.size() > 1)
1483 ArchitectureName = I->getArchTypeName();
1485 ObjectFile &O = *ObjOrErr.get();
1486 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&O))
1487 ProcessMachO(Filename, MachOOF, "", ArchitectureName);
1488 } else if (ErrorOr<std::unique_ptr<Archive>> AOrErr =
1489 I->getAsArchive()) {
1490 std::unique_ptr<Archive> &A = *AOrErr;
1491 outs() << "Archive : " << Filename;
1492 if (!ArchitectureName.empty())
1493 outs() << " (architecture " << ArchitectureName << ")";
1496 printArchiveHeaders(A.get(), true, false);
1497 for (Archive::child_iterator AI = A->child_begin(),
1498 AE = A->child_end();
1500 ErrorOr<std::unique_ptr<Binary>> ChildOrErr = AI->getAsBinary();
1501 if (ChildOrErr.getError())
1503 if (MachOObjectFile *O =
1504 dyn_cast<MachOObjectFile>(&*ChildOrErr.get()))
1505 ProcessMachO(Filename, O, O->getFileName(), ArchitectureName);
1511 errs() << "llvm-objdump: file: " + Filename + " does not contain "
1512 << "architecture: " + ArchFlags[i] + "\n";
1518 // No architecture flags were specified so if this contains a slice that
1519 // matches the host architecture dump only that.
1521 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
1522 E = UB->end_objects();
1524 if (MachOObjectFile::getHostArch().getArchName() ==
1525 I->getArchTypeName()) {
1526 ErrorOr<std::unique_ptr<ObjectFile>> ObjOrErr = I->getAsObjectFile();
1527 std::string ArchiveName;
1528 ArchiveName.clear();
1530 ObjectFile &O = *ObjOrErr.get();
1531 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&O))
1532 ProcessMachO(Filename, MachOOF);
1533 } else if (ErrorOr<std::unique_ptr<Archive>> AOrErr =
1534 I->getAsArchive()) {
1535 std::unique_ptr<Archive> &A = *AOrErr;
1536 outs() << "Archive : " << Filename << "\n";
1538 printArchiveHeaders(A.get(), true, false);
1539 for (Archive::child_iterator AI = A->child_begin(),
1540 AE = A->child_end();
1542 ErrorOr<std::unique_ptr<Binary>> ChildOrErr = AI->getAsBinary();
1543 if (ChildOrErr.getError())
1545 if (MachOObjectFile *O =
1546 dyn_cast<MachOObjectFile>(&*ChildOrErr.get()))
1547 ProcessMachO(Filename, O, O->getFileName());
1554 // Either all architectures have been specified or none have been specified
1555 // and this does not contain the host architecture so dump all the slices.
1556 bool moreThanOneArch = UB->getNumberOfObjects() > 1;
1557 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
1558 E = UB->end_objects();
1560 ErrorOr<std::unique_ptr<ObjectFile>> ObjOrErr = I->getAsObjectFile();
1561 std::string ArchitectureName = "";
1562 if (moreThanOneArch)
1563 ArchitectureName = I->getArchTypeName();
1565 ObjectFile &Obj = *ObjOrErr.get();
1566 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&Obj))
1567 ProcessMachO(Filename, MachOOF, "", ArchitectureName);
1568 } else if (ErrorOr<std::unique_ptr<Archive>> AOrErr = I->getAsArchive()) {
1569 std::unique_ptr<Archive> &A = *AOrErr;
1570 outs() << "Archive : " << Filename;
1571 if (!ArchitectureName.empty())
1572 outs() << " (architecture " << ArchitectureName << ")";
1575 printArchiveHeaders(A.get(), true, false);
1576 for (Archive::child_iterator AI = A->child_begin(), AE = A->child_end();
1578 ErrorOr<std::unique_ptr<Binary>> ChildOrErr = AI->getAsBinary();
1579 if (ChildOrErr.getError())
1581 if (MachOObjectFile *O =
1582 dyn_cast<MachOObjectFile>(&*ChildOrErr.get())) {
1583 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(O))
1584 ProcessMachO(Filename, MachOOF, MachOOF->getFileName(),
1592 if (ObjectFile *O = dyn_cast<ObjectFile>(&Bin)) {
1593 if (!checkMachOAndArchFlags(O, Filename))
1595 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&*O)) {
1596 ProcessMachO(Filename, MachOOF);
1598 errs() << "llvm-objdump: '" << Filename << "': "
1599 << "Object is not a Mach-O file type.\n";
1601 errs() << "llvm-objdump: '" << Filename << "': "
1602 << "Unrecognized file type.\n";
1605 typedef std::pair<uint64_t, const char *> BindInfoEntry;
1606 typedef std::vector<BindInfoEntry> BindTable;
1607 typedef BindTable::iterator bind_table_iterator;
1609 // The block of info used by the Symbolizer call backs.
1610 struct DisassembleInfo {
1614 SymbolAddressMap *AddrMap;
1615 std::vector<SectionRef> *Sections;
1616 const char *class_name;
1617 const char *selector_name;
1619 char *demangled_name;
1622 BindTable *bindtable;
1625 // SymbolizerGetOpInfo() is the operand information call back function.
1626 // This is called to get the symbolic information for operand(s) of an
1627 // instruction when it is being done. This routine does this from
1628 // the relocation information, symbol table, etc. That block of information
1629 // is a pointer to the struct DisassembleInfo that was passed when the
1630 // disassembler context was created and passed to back to here when
1631 // called back by the disassembler for instruction operands that could have
1632 // relocation information. The address of the instruction containing operand is
1633 // at the Pc parameter. The immediate value the operand has is passed in
1634 // op_info->Value and is at Offset past the start of the instruction and has a
1635 // byte Size of 1, 2 or 4. The symbolc information is returned in TagBuf is the
1636 // LLVMOpInfo1 struct defined in the header "llvm-c/Disassembler.h" as symbol
1637 // names and addends of the symbolic expression to add for the operand. The
1638 // value of TagType is currently 1 (for the LLVMOpInfo1 struct). If symbolic
1639 // information is returned then this function returns 1 else it returns 0.
1640 static int SymbolizerGetOpInfo(void *DisInfo, uint64_t Pc, uint64_t Offset,
1641 uint64_t Size, int TagType, void *TagBuf) {
1642 struct DisassembleInfo *info = (struct DisassembleInfo *)DisInfo;
1643 struct LLVMOpInfo1 *op_info = (struct LLVMOpInfo1 *)TagBuf;
1644 uint64_t value = op_info->Value;
1646 // Make sure all fields returned are zero if we don't set them.
1647 memset((void *)op_info, '\0', sizeof(struct LLVMOpInfo1));
1648 op_info->Value = value;
1650 // If the TagType is not the value 1 which it code knows about or if no
1651 // verbose symbolic information is wanted then just return 0, indicating no
1652 // information is being returned.
1653 if (TagType != 1 || info->verbose == false)
1656 unsigned int Arch = info->O->getArch();
1657 if (Arch == Triple::x86) {
1658 if (Size != 1 && Size != 2 && Size != 4 && Size != 0)
1660 // First search the section's relocation entries (if any) for an entry
1661 // for this section offset.
1662 uint32_t sect_addr = info->S.getAddress();
1663 uint32_t sect_offset = (Pc + Offset) - sect_addr;
1664 bool reloc_found = false;
1666 MachO::any_relocation_info RE;
1667 bool isExtern = false;
1669 bool r_scattered = false;
1670 uint32_t r_value, pair_r_value, r_type;
1671 for (const RelocationRef &Reloc : info->S.relocations()) {
1672 uint64_t RelocOffset;
1673 Reloc.getOffset(RelocOffset);
1674 if (RelocOffset == sect_offset) {
1675 Rel = Reloc.getRawDataRefImpl();
1676 RE = info->O->getRelocation(Rel);
1677 r_type = info->O->getAnyRelocationType(RE);
1678 r_scattered = info->O->isRelocationScattered(RE);
1680 r_value = info->O->getScatteredRelocationValue(RE);
1681 if (r_type == MachO::GENERIC_RELOC_SECTDIFF ||
1682 r_type == MachO::GENERIC_RELOC_LOCAL_SECTDIFF) {
1683 DataRefImpl RelNext = Rel;
1684 info->O->moveRelocationNext(RelNext);
1685 MachO::any_relocation_info RENext;
1686 RENext = info->O->getRelocation(RelNext);
1687 if (info->O->isRelocationScattered(RENext))
1688 pair_r_value = info->O->getScatteredRelocationValue(RENext);
1693 isExtern = info->O->getPlainRelocationExternal(RE);
1695 symbol_iterator RelocSym = Reloc.getSymbol();
1703 if (reloc_found && isExtern) {
1705 Symbol.getName(SymName);
1706 const char *name = SymName.data();
1707 op_info->AddSymbol.Present = 1;
1708 op_info->AddSymbol.Name = name;
1709 // For i386 extern relocation entries the value in the instruction is
1710 // the offset from the symbol, and value is already set in op_info->Value.
1713 if (reloc_found && (r_type == MachO::GENERIC_RELOC_SECTDIFF ||
1714 r_type == MachO::GENERIC_RELOC_LOCAL_SECTDIFF)) {
1715 const char *add = GuessSymbolName(r_value, info->AddrMap);
1716 const char *sub = GuessSymbolName(pair_r_value, info->AddrMap);
1717 uint32_t offset = value - (r_value - pair_r_value);
1718 op_info->AddSymbol.Present = 1;
1720 op_info->AddSymbol.Name = add;
1722 op_info->AddSymbol.Value = r_value;
1723 op_info->SubtractSymbol.Present = 1;
1725 op_info->SubtractSymbol.Name = sub;
1727 op_info->SubtractSymbol.Value = pair_r_value;
1728 op_info->Value = offset;
1732 // Second search the external relocation entries of a fully linked image
1733 // (if any) for an entry that matches this segment offset.
1734 // uint32_t seg_offset = (Pc + Offset);
1736 } else if (Arch == Triple::x86_64) {
1737 if (Size != 1 && Size != 2 && Size != 4 && Size != 0)
1739 // First search the section's relocation entries (if any) for an entry
1740 // for this section offset.
1741 uint64_t sect_addr = info->S.getAddress();
1742 uint64_t sect_offset = (Pc + Offset) - sect_addr;
1743 bool reloc_found = false;
1745 MachO::any_relocation_info RE;
1746 bool isExtern = false;
1748 for (const RelocationRef &Reloc : info->S.relocations()) {
1749 uint64_t RelocOffset;
1750 Reloc.getOffset(RelocOffset);
1751 if (RelocOffset == sect_offset) {
1752 Rel = Reloc.getRawDataRefImpl();
1753 RE = info->O->getRelocation(Rel);
1754 // NOTE: Scattered relocations don't exist on x86_64.
1755 isExtern = info->O->getPlainRelocationExternal(RE);
1757 symbol_iterator RelocSym = Reloc.getSymbol();
1764 if (reloc_found && isExtern) {
1765 // The Value passed in will be adjusted by the Pc if the instruction
1766 // adds the Pc. But for x86_64 external relocation entries the Value
1767 // is the offset from the external symbol.
1768 if (info->O->getAnyRelocationPCRel(RE))
1769 op_info->Value -= Pc + Offset + Size;
1771 Symbol.getName(SymName);
1772 const char *name = SymName.data();
1773 unsigned Type = info->O->getAnyRelocationType(RE);
1774 if (Type == MachO::X86_64_RELOC_SUBTRACTOR) {
1775 DataRefImpl RelNext = Rel;
1776 info->O->moveRelocationNext(RelNext);
1777 MachO::any_relocation_info RENext = info->O->getRelocation(RelNext);
1778 unsigned TypeNext = info->O->getAnyRelocationType(RENext);
1779 bool isExternNext = info->O->getPlainRelocationExternal(RENext);
1780 unsigned SymbolNum = info->O->getPlainRelocationSymbolNum(RENext);
1781 if (TypeNext == MachO::X86_64_RELOC_UNSIGNED && isExternNext) {
1782 op_info->SubtractSymbol.Present = 1;
1783 op_info->SubtractSymbol.Name = name;
1784 symbol_iterator RelocSymNext = info->O->getSymbolByIndex(SymbolNum);
1785 Symbol = *RelocSymNext;
1786 StringRef SymNameNext;
1787 Symbol.getName(SymNameNext);
1788 name = SymNameNext.data();
1791 // TODO: add the VariantKinds to op_info->VariantKind for relocation types
1792 // like: X86_64_RELOC_TLV, X86_64_RELOC_GOT_LOAD and X86_64_RELOC_GOT.
1793 op_info->AddSymbol.Present = 1;
1794 op_info->AddSymbol.Name = name;
1798 // Second search the external relocation entries of a fully linked image
1799 // (if any) for an entry that matches this segment offset.
1800 // uint64_t seg_offset = (Pc + Offset);
1802 } else if (Arch == Triple::arm) {
1803 if (Offset != 0 || (Size != 4 && Size != 2))
1805 // First search the section's relocation entries (if any) for an entry
1806 // for this section offset.
1807 uint32_t sect_addr = info->S.getAddress();
1808 uint32_t sect_offset = (Pc + Offset) - sect_addr;
1809 bool reloc_found = false;
1811 MachO::any_relocation_info RE;
1812 bool isExtern = false;
1814 bool r_scattered = false;
1815 uint32_t r_value, pair_r_value, r_type, r_length, other_half;
1816 for (const RelocationRef &Reloc : info->S.relocations()) {
1817 uint64_t RelocOffset;
1818 Reloc.getOffset(RelocOffset);
1819 if (RelocOffset == sect_offset) {
1820 Rel = Reloc.getRawDataRefImpl();
1821 RE = info->O->getRelocation(Rel);
1822 r_length = info->O->getAnyRelocationLength(RE);
1823 r_scattered = info->O->isRelocationScattered(RE);
1825 r_value = info->O->getScatteredRelocationValue(RE);
1826 r_type = info->O->getScatteredRelocationType(RE);
1828 r_type = info->O->getAnyRelocationType(RE);
1829 isExtern = info->O->getPlainRelocationExternal(RE);
1831 symbol_iterator RelocSym = Reloc.getSymbol();
1835 if (r_type == MachO::ARM_RELOC_HALF ||
1836 r_type == MachO::ARM_RELOC_SECTDIFF ||
1837 r_type == MachO::ARM_RELOC_LOCAL_SECTDIFF ||
1838 r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
1839 DataRefImpl RelNext = Rel;
1840 info->O->moveRelocationNext(RelNext);
1841 MachO::any_relocation_info RENext;
1842 RENext = info->O->getRelocation(RelNext);
1843 other_half = info->O->getAnyRelocationAddress(RENext) & 0xffff;
1844 if (info->O->isRelocationScattered(RENext))
1845 pair_r_value = info->O->getScatteredRelocationValue(RENext);
1851 if (reloc_found && isExtern) {
1853 Symbol.getName(SymName);
1854 const char *name = SymName.data();
1855 op_info->AddSymbol.Present = 1;
1856 op_info->AddSymbol.Name = name;
1858 case MachO::ARM_RELOC_HALF:
1859 if ((r_length & 0x1) == 1) {
1860 op_info->Value = value << 16 | other_half;
1861 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
1863 op_info->Value = other_half << 16 | value;
1864 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
1872 // If we have a branch that is not an external relocation entry then
1873 // return 0 so the code in tryAddingSymbolicOperand() can use the
1874 // SymbolLookUp call back with the branch target address to look up the
1875 // symbol and possiblity add an annotation for a symbol stub.
1876 if (reloc_found && isExtern == 0 && (r_type == MachO::ARM_RELOC_BR24 ||
1877 r_type == MachO::ARM_THUMB_RELOC_BR22))
1880 uint32_t offset = 0;
1882 if (r_type == MachO::ARM_RELOC_HALF ||
1883 r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
1884 if ((r_length & 0x1) == 1)
1885 value = value << 16 | other_half;
1887 value = other_half << 16 | value;
1889 if (r_scattered && (r_type != MachO::ARM_RELOC_HALF &&
1890 r_type != MachO::ARM_RELOC_HALF_SECTDIFF)) {
1891 offset = value - r_value;
1896 if (reloc_found && r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
1897 if ((r_length & 0x1) == 1)
1898 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
1900 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
1901 const char *add = GuessSymbolName(r_value, info->AddrMap);
1902 const char *sub = GuessSymbolName(pair_r_value, info->AddrMap);
1903 int32_t offset = value - (r_value - pair_r_value);
1904 op_info->AddSymbol.Present = 1;
1906 op_info->AddSymbol.Name = add;
1908 op_info->AddSymbol.Value = r_value;
1909 op_info->SubtractSymbol.Present = 1;
1911 op_info->SubtractSymbol.Name = sub;
1913 op_info->SubtractSymbol.Value = pair_r_value;
1914 op_info->Value = offset;
1918 if (reloc_found == false)
1921 op_info->AddSymbol.Present = 1;
1922 op_info->Value = offset;
1924 if (r_type == MachO::ARM_RELOC_HALF) {
1925 if ((r_length & 0x1) == 1)
1926 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
1928 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
1931 const char *add = GuessSymbolName(value, info->AddrMap);
1932 if (add != nullptr) {
1933 op_info->AddSymbol.Name = add;
1936 op_info->AddSymbol.Value = value;
1938 } else if (Arch == Triple::aarch64) {
1939 if (Offset != 0 || Size != 4)
1941 // First search the section's relocation entries (if any) for an entry
1942 // for this section offset.
1943 uint64_t sect_addr = info->S.getAddress();
1944 uint64_t sect_offset = (Pc + Offset) - sect_addr;
1945 bool reloc_found = false;
1947 MachO::any_relocation_info RE;
1948 bool isExtern = false;
1950 uint32_t r_type = 0;
1951 for (const RelocationRef &Reloc : info->S.relocations()) {
1952 uint64_t RelocOffset;
1953 Reloc.getOffset(RelocOffset);
1954 if (RelocOffset == sect_offset) {
1955 Rel = Reloc.getRawDataRefImpl();
1956 RE = info->O->getRelocation(Rel);
1957 r_type = info->O->getAnyRelocationType(RE);
1958 if (r_type == MachO::ARM64_RELOC_ADDEND) {
1959 DataRefImpl RelNext = Rel;
1960 info->O->moveRelocationNext(RelNext);
1961 MachO::any_relocation_info RENext = info->O->getRelocation(RelNext);
1963 value = info->O->getPlainRelocationSymbolNum(RENext);
1964 op_info->Value = value;
1967 // NOTE: Scattered relocations don't exist on arm64.
1968 isExtern = info->O->getPlainRelocationExternal(RE);
1970 symbol_iterator RelocSym = Reloc.getSymbol();
1977 if (reloc_found && isExtern) {
1979 Symbol.getName(SymName);
1980 const char *name = SymName.data();
1981 op_info->AddSymbol.Present = 1;
1982 op_info->AddSymbol.Name = name;
1985 case MachO::ARM64_RELOC_PAGE21:
1987 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_PAGE;
1989 case MachO::ARM64_RELOC_PAGEOFF12:
1991 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_PAGEOFF;
1993 case MachO::ARM64_RELOC_GOT_LOAD_PAGE21:
1995 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_GOTPAGE;
1997 case MachO::ARM64_RELOC_GOT_LOAD_PAGEOFF12:
1999 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_GOTPAGEOFF;
2001 case MachO::ARM64_RELOC_TLVP_LOAD_PAGE21:
2002 /* @tvlppage is not implemented in llvm-mc */
2003 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_TLVP;
2005 case MachO::ARM64_RELOC_TLVP_LOAD_PAGEOFF12:
2006 /* @tvlppageoff is not implemented in llvm-mc */
2007 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_TLVOFF;
2010 case MachO::ARM64_RELOC_BRANCH26:
2011 op_info->VariantKind = LLVMDisassembler_VariantKind_None;
2022 // GuessCstringPointer is passed the address of what might be a pointer to a
2023 // literal string in a cstring section. If that address is in a cstring section
2024 // it returns a pointer to that string. Else it returns nullptr.
2025 static const char *GuessCstringPointer(uint64_t ReferenceValue,
2026 struct DisassembleInfo *info) {
2027 uint32_t LoadCommandCount = info->O->getHeader().ncmds;
2028 MachOObjectFile::LoadCommandInfo Load = info->O->getFirstLoadCommandInfo();
2029 for (unsigned I = 0;; ++I) {
2030 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
2031 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
2032 for (unsigned J = 0; J < Seg.nsects; ++J) {
2033 MachO::section_64 Sec = info->O->getSection64(Load, J);
2034 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
2035 if (section_type == MachO::S_CSTRING_LITERALS &&
2036 ReferenceValue >= Sec.addr &&
2037 ReferenceValue < Sec.addr + Sec.size) {
2038 uint64_t sect_offset = ReferenceValue - Sec.addr;
2039 uint64_t object_offset = Sec.offset + sect_offset;
2040 StringRef MachOContents = info->O->getData();
2041 uint64_t object_size = MachOContents.size();
2042 const char *object_addr = (const char *)MachOContents.data();
2043 if (object_offset < object_size) {
2044 const char *name = object_addr + object_offset;
2051 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
2052 MachO::segment_command Seg = info->O->getSegmentLoadCommand(Load);
2053 for (unsigned J = 0; J < Seg.nsects; ++J) {
2054 MachO::section Sec = info->O->getSection(Load, J);
2055 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
2056 if (section_type == MachO::S_CSTRING_LITERALS &&
2057 ReferenceValue >= Sec.addr &&
2058 ReferenceValue < Sec.addr + Sec.size) {
2059 uint64_t sect_offset = ReferenceValue - Sec.addr;
2060 uint64_t object_offset = Sec.offset + sect_offset;
2061 StringRef MachOContents = info->O->getData();
2062 uint64_t object_size = MachOContents.size();
2063 const char *object_addr = (const char *)MachOContents.data();
2064 if (object_offset < object_size) {
2065 const char *name = object_addr + object_offset;
2073 if (I == LoadCommandCount - 1)
2076 Load = info->O->getNextLoadCommandInfo(Load);
2081 // GuessIndirectSymbol returns the name of the indirect symbol for the
2082 // ReferenceValue passed in or nullptr. This is used when ReferenceValue maybe
2083 // an address of a symbol stub or a lazy or non-lazy pointer to associate the
2084 // symbol name being referenced by the stub or pointer.
2085 static const char *GuessIndirectSymbol(uint64_t ReferenceValue,
2086 struct DisassembleInfo *info) {
2087 uint32_t LoadCommandCount = info->O->getHeader().ncmds;
2088 MachOObjectFile::LoadCommandInfo Load = info->O->getFirstLoadCommandInfo();
2089 MachO::dysymtab_command Dysymtab = info->O->getDysymtabLoadCommand();
2090 MachO::symtab_command Symtab = info->O->getSymtabLoadCommand();
2091 for (unsigned I = 0;; ++I) {
2092 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
2093 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
2094 for (unsigned J = 0; J < Seg.nsects; ++J) {
2095 MachO::section_64 Sec = info->O->getSection64(Load, J);
2096 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
2097 if ((section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
2098 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
2099 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
2100 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
2101 section_type == MachO::S_SYMBOL_STUBS) &&
2102 ReferenceValue >= Sec.addr &&
2103 ReferenceValue < Sec.addr + Sec.size) {
2105 if (section_type == MachO::S_SYMBOL_STUBS)
2106 stride = Sec.reserved2;
2111 uint32_t index = Sec.reserved1 + (ReferenceValue - Sec.addr) / stride;
2112 if (index < Dysymtab.nindirectsyms) {
2113 uint32_t indirect_symbol =
2114 info->O->getIndirectSymbolTableEntry(Dysymtab, index);
2115 if (indirect_symbol < Symtab.nsyms) {
2116 symbol_iterator Sym = info->O->getSymbolByIndex(indirect_symbol);
2117 SymbolRef Symbol = *Sym;
2119 Symbol.getName(SymName);
2120 const char *name = SymName.data();
2126 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
2127 MachO::segment_command Seg = info->O->getSegmentLoadCommand(Load);
2128 for (unsigned J = 0; J < Seg.nsects; ++J) {
2129 MachO::section Sec = info->O->getSection(Load, J);
2130 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
2131 if ((section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
2132 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
2133 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
2134 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
2135 section_type == MachO::S_SYMBOL_STUBS) &&
2136 ReferenceValue >= Sec.addr &&
2137 ReferenceValue < Sec.addr + Sec.size) {
2139 if (section_type == MachO::S_SYMBOL_STUBS)
2140 stride = Sec.reserved2;
2145 uint32_t index = Sec.reserved1 + (ReferenceValue - Sec.addr) / stride;
2146 if (index < Dysymtab.nindirectsyms) {
2147 uint32_t indirect_symbol =
2148 info->O->getIndirectSymbolTableEntry(Dysymtab, index);
2149 if (indirect_symbol < Symtab.nsyms) {
2150 symbol_iterator Sym = info->O->getSymbolByIndex(indirect_symbol);
2151 SymbolRef Symbol = *Sym;
2153 Symbol.getName(SymName);
2154 const char *name = SymName.data();
2161 if (I == LoadCommandCount - 1)
2164 Load = info->O->getNextLoadCommandInfo(Load);
2169 // method_reference() is called passing it the ReferenceName that might be
2170 // a reference it to an Objective-C method call. If so then it allocates and
2171 // assembles a method call string with the values last seen and saved in
2172 // the DisassembleInfo's class_name and selector_name fields. This is saved
2173 // into the method field of the info and any previous string is free'ed.
2174 // Then the class_name field in the info is set to nullptr. The method call
2175 // string is set into ReferenceName and ReferenceType is set to
2176 // LLVMDisassembler_ReferenceType_Out_Objc_Message. If this not a method call
2177 // then both ReferenceType and ReferenceName are left unchanged.
2178 static void method_reference(struct DisassembleInfo *info,
2179 uint64_t *ReferenceType,
2180 const char **ReferenceName) {
2181 unsigned int Arch = info->O->getArch();
2182 if (*ReferenceName != nullptr) {
2183 if (strcmp(*ReferenceName, "_objc_msgSend") == 0) {
2184 if (info->selector_name != nullptr) {
2185 if (info->method != nullptr)
2187 if (info->class_name != nullptr) {
2188 info->method = (char *)malloc(5 + strlen(info->class_name) +
2189 strlen(info->selector_name));
2190 if (info->method != nullptr) {
2191 strcpy(info->method, "+[");
2192 strcat(info->method, info->class_name);
2193 strcat(info->method, " ");
2194 strcat(info->method, info->selector_name);
2195 strcat(info->method, "]");
2196 *ReferenceName = info->method;
2197 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
2200 info->method = (char *)malloc(9 + strlen(info->selector_name));
2201 if (info->method != nullptr) {
2202 if (Arch == Triple::x86_64)
2203 strcpy(info->method, "-[%rdi ");
2204 else if (Arch == Triple::aarch64)
2205 strcpy(info->method, "-[x0 ");
2207 strcpy(info->method, "-[r? ");
2208 strcat(info->method, info->selector_name);
2209 strcat(info->method, "]");
2210 *ReferenceName = info->method;
2211 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
2214 info->class_name = nullptr;
2216 } else if (strcmp(*ReferenceName, "_objc_msgSendSuper2") == 0) {
2217 if (info->selector_name != nullptr) {
2218 if (info->method != nullptr)
2220 info->method = (char *)malloc(17 + strlen(info->selector_name));
2221 if (info->method != nullptr) {
2222 if (Arch == Triple::x86_64)
2223 strcpy(info->method, "-[[%rdi super] ");
2224 else if (Arch == Triple::aarch64)
2225 strcpy(info->method, "-[[x0 super] ");
2227 strcpy(info->method, "-[[r? super] ");
2228 strcat(info->method, info->selector_name);
2229 strcat(info->method, "]");
2230 *ReferenceName = info->method;
2231 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
2233 info->class_name = nullptr;
2239 // GuessPointerPointer() is passed the address of what might be a pointer to
2240 // a reference to an Objective-C class, selector, message ref or cfstring.
2241 // If so the value of the pointer is returned and one of the booleans are set
2242 // to true. If not zero is returned and all the booleans are set to false.
2243 static uint64_t GuessPointerPointer(uint64_t ReferenceValue,
2244 struct DisassembleInfo *info,
2245 bool &classref, bool &selref, bool &msgref,
2251 uint32_t LoadCommandCount = info->O->getHeader().ncmds;
2252 MachOObjectFile::LoadCommandInfo Load = info->O->getFirstLoadCommandInfo();
2253 for (unsigned I = 0;; ++I) {
2254 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
2255 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
2256 for (unsigned J = 0; J < Seg.nsects; ++J) {
2257 MachO::section_64 Sec = info->O->getSection64(Load, J);
2258 if ((strncmp(Sec.sectname, "__objc_selrefs", 16) == 0 ||
2259 strncmp(Sec.sectname, "__objc_classrefs", 16) == 0 ||
2260 strncmp(Sec.sectname, "__objc_superrefs", 16) == 0 ||
2261 strncmp(Sec.sectname, "__objc_msgrefs", 16) == 0 ||
2262 strncmp(Sec.sectname, "__cfstring", 16) == 0) &&
2263 ReferenceValue >= Sec.addr &&
2264 ReferenceValue < Sec.addr + Sec.size) {
2265 uint64_t sect_offset = ReferenceValue - Sec.addr;
2266 uint64_t object_offset = Sec.offset + sect_offset;
2267 StringRef MachOContents = info->O->getData();
2268 uint64_t object_size = MachOContents.size();
2269 const char *object_addr = (const char *)MachOContents.data();
2270 if (object_offset < object_size) {
2271 uint64_t pointer_value;
2272 memcpy(&pointer_value, object_addr + object_offset,
2274 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
2275 sys::swapByteOrder(pointer_value);
2276 if (strncmp(Sec.sectname, "__objc_selrefs", 16) == 0)
2278 else if (strncmp(Sec.sectname, "__objc_classrefs", 16) == 0 ||
2279 strncmp(Sec.sectname, "__objc_superrefs", 16) == 0)
2281 else if (strncmp(Sec.sectname, "__objc_msgrefs", 16) == 0 &&
2282 ReferenceValue + 8 < Sec.addr + Sec.size) {
2284 memcpy(&pointer_value, object_addr + object_offset + 8,
2286 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
2287 sys::swapByteOrder(pointer_value);
2288 } else if (strncmp(Sec.sectname, "__cfstring", 16) == 0)
2290 return pointer_value;
2297 // TODO: Look for LC_SEGMENT for 32-bit Mach-O files.
2298 if (I == LoadCommandCount - 1)
2301 Load = info->O->getNextLoadCommandInfo(Load);
2306 // get_pointer_64 returns a pointer to the bytes in the object file at the
2307 // Address from a section in the Mach-O file. And indirectly returns the
2308 // offset into the section, number of bytes left in the section past the offset
2309 // and which section is was being referenced. If the Address is not in a
2310 // section nullptr is returned.
2311 static const char *get_pointer_64(uint64_t Address, uint32_t &offset,
2312 uint32_t &left, SectionRef &S,
2313 DisassembleInfo *info) {
2317 for (unsigned SectIdx = 0; SectIdx != info->Sections->size(); SectIdx++) {
2318 uint64_t SectAddress = ((*(info->Sections))[SectIdx]).getAddress();
2319 uint64_t SectSize = ((*(info->Sections))[SectIdx]).getSize();
2320 if (Address >= SectAddress && Address < SectAddress + SectSize) {
2321 S = (*(info->Sections))[SectIdx];
2322 offset = Address - SectAddress;
2323 left = SectSize - offset;
2324 StringRef SectContents;
2325 ((*(info->Sections))[SectIdx]).getContents(SectContents);
2326 return SectContents.data() + offset;
2332 // get_symbol_64() returns the name of a symbol (or nullptr) and the address of
2333 // the symbol indirectly through n_value. Based on the relocation information
2334 // for the specified section offset in the specified section reference.
2335 static const char *get_symbol_64(uint32_t sect_offset, SectionRef S,
2336 DisassembleInfo *info, uint64_t &n_value) {
2338 if (info->verbose == false)
2341 // See if there is an external relocation entry at the sect_offset.
2342 bool reloc_found = false;
2344 MachO::any_relocation_info RE;
2345 bool isExtern = false;
2347 for (const RelocationRef &Reloc : S.relocations()) {
2348 uint64_t RelocOffset;
2349 Reloc.getOffset(RelocOffset);
2350 if (RelocOffset == sect_offset) {
2351 Rel = Reloc.getRawDataRefImpl();
2352 RE = info->O->getRelocation(Rel);
2353 if (info->O->isRelocationScattered(RE))
2355 isExtern = info->O->getPlainRelocationExternal(RE);
2357 symbol_iterator RelocSym = Reloc.getSymbol();
2364 // If there is an external relocation entry for a symbol in this section
2365 // at this section_offset then use that symbol's value for the n_value
2366 // and return its name.
2367 const char *SymbolName = nullptr;
2368 if (reloc_found && isExtern) {
2369 Symbol.getAddress(n_value);
2371 Symbol.getName(name);
2372 if (!name.empty()) {
2373 SymbolName = name.data();
2378 // TODO: For fully linked images, look through the external relocation
2379 // entries off the dynamic symtab command. For these the r_offset is from the
2380 // start of the first writeable segment in the Mach-O file. So the offset
2381 // to this section from that segment is passed to this routine by the caller,
2382 // as the database_offset. Which is the difference of the section's starting
2383 // address and the first writable segment.
2385 // NOTE: need add passing the database_offset to this routine.
2387 // TODO: We did not find an external relocation entry so look up the
2388 // ReferenceValue as an address of a symbol and if found return that symbol's
2391 // NOTE: need add passing the ReferenceValue to this routine. Then that code
2392 // would simply be this:
2393 // SymbolName = GuessSymbolName(ReferenceValue, info->AddrMap);
2398 // These are structs in the Objective-C meta data and read to produce the
2399 // comments for disassembly. While these are part of the ABI they are no
2400 // public defintions. So the are here not in include/llvm/Support/MachO.h .
2402 // The cfstring object in a 64-bit Mach-O file.
2403 struct cfstring64_t {
2404 uint64_t isa; // class64_t * (64-bit pointer)
2405 uint64_t flags; // flag bits
2406 uint64_t characters; // char * (64-bit pointer)
2407 uint64_t length; // number of non-NULL characters in above
2410 // The class object in a 64-bit Mach-O file.
2412 uint64_t isa; // class64_t * (64-bit pointer)
2413 uint64_t superclass; // class64_t * (64-bit pointer)
2414 uint64_t cache; // Cache (64-bit pointer)
2415 uint64_t vtable; // IMP * (64-bit pointer)
2416 uint64_t data; // class_ro64_t * (64-bit pointer)
2419 struct class_ro64_t {
2421 uint32_t instanceStart;
2422 uint32_t instanceSize;
2424 uint64_t ivarLayout; // const uint8_t * (64-bit pointer)
2425 uint64_t name; // const char * (64-bit pointer)
2426 uint64_t baseMethods; // const method_list_t * (64-bit pointer)
2427 uint64_t baseProtocols; // const protocol_list_t * (64-bit pointer)
2428 uint64_t ivars; // const ivar_list_t * (64-bit pointer)
2429 uint64_t weakIvarLayout; // const uint8_t * (64-bit pointer)
2430 uint64_t baseProperties; // const struct objc_property_list (64-bit pointer)
2433 inline void swapStruct(struct cfstring64_t &cfs) {
2434 sys::swapByteOrder(cfs.isa);
2435 sys::swapByteOrder(cfs.flags);
2436 sys::swapByteOrder(cfs.characters);
2437 sys::swapByteOrder(cfs.length);
2440 inline void swapStruct(struct class64_t &c) {
2441 sys::swapByteOrder(c.isa);
2442 sys::swapByteOrder(c.superclass);
2443 sys::swapByteOrder(c.cache);
2444 sys::swapByteOrder(c.vtable);
2445 sys::swapByteOrder(c.data);
2448 inline void swapStruct(struct class_ro64_t &cro) {
2449 sys::swapByteOrder(cro.flags);
2450 sys::swapByteOrder(cro.instanceStart);
2451 sys::swapByteOrder(cro.instanceSize);
2452 sys::swapByteOrder(cro.reserved);
2453 sys::swapByteOrder(cro.ivarLayout);
2454 sys::swapByteOrder(cro.name);
2455 sys::swapByteOrder(cro.baseMethods);
2456 sys::swapByteOrder(cro.baseProtocols);
2457 sys::swapByteOrder(cro.ivars);
2458 sys::swapByteOrder(cro.weakIvarLayout);
2459 sys::swapByteOrder(cro.baseProperties);
2462 static const char *get_dyld_bind_info_symbolname(uint64_t ReferenceValue,
2463 struct DisassembleInfo *info);
2465 // get_objc2_64bit_class_name() is used for disassembly and is passed a pointer
2466 // to an Objective-C class and returns the class name. It is also passed the
2467 // address of the pointer, so when the pointer is zero as it can be in an .o
2468 // file, that is used to look for an external relocation entry with a symbol
2470 static const char *get_objc2_64bit_class_name(uint64_t pointer_value,
2471 uint64_t ReferenceValue,
2472 struct DisassembleInfo *info) {
2474 uint32_t offset, left;
2477 // The pointer_value can be 0 in an object file and have a relocation
2478 // entry for the class symbol at the ReferenceValue (the address of the
2480 if (pointer_value == 0) {
2481 r = get_pointer_64(ReferenceValue, offset, left, S, info);
2482 if (r == nullptr || left < sizeof(uint64_t))
2485 const char *symbol_name = get_symbol_64(offset, S, info, n_value);
2486 if (symbol_name == nullptr)
2488 const char *class_name = strrchr(symbol_name, '$');
2489 if (class_name != nullptr && class_name[1] == '_' && class_name[2] != '\0')
2490 return class_name + 2;
2495 // The case were the pointer_value is non-zero and points to a class defined
2496 // in this Mach-O file.
2497 r = get_pointer_64(pointer_value, offset, left, S, info);
2498 if (r == nullptr || left < sizeof(struct class64_t))
2501 memcpy(&c, r, sizeof(struct class64_t));
2502 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
2506 r = get_pointer_64(c.data, offset, left, S, info);
2507 if (r == nullptr || left < sizeof(struct class_ro64_t))
2509 struct class_ro64_t cro;
2510 memcpy(&cro, r, sizeof(struct class_ro64_t));
2511 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
2515 const char *name = get_pointer_64(cro.name, offset, left, S, info);
2519 // get_objc2_64bit_cfstring_name is used for disassembly and is passed a
2520 // pointer to a cfstring and returns its name or nullptr.
2521 static const char *get_objc2_64bit_cfstring_name(uint64_t ReferenceValue,
2522 struct DisassembleInfo *info) {
2523 const char *r, *name;
2524 uint32_t offset, left;
2526 struct cfstring64_t cfs;
2527 uint64_t cfs_characters;
2529 r = get_pointer_64(ReferenceValue, offset, left, S, info);
2530 if (r == nullptr || left < sizeof(struct cfstring64_t))
2532 memcpy(&cfs, r, sizeof(struct cfstring64_t));
2533 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
2535 if (cfs.characters == 0) {
2537 const char *symbol_name = get_symbol_64(
2538 offset + offsetof(struct cfstring64_t, characters), S, info, n_value);
2539 if (symbol_name == nullptr)
2541 cfs_characters = n_value;
2543 cfs_characters = cfs.characters;
2544 name = get_pointer_64(cfs_characters, offset, left, S, info);
2549 // get_objc2_64bit_selref() is used for disassembly and is passed a the address
2550 // of a pointer to an Objective-C selector reference when the pointer value is
2551 // zero as in a .o file and is likely to have a external relocation entry with
2552 // who's symbol's n_value is the real pointer to the selector name. If that is
2553 // the case the real pointer to the selector name is returned else 0 is
2555 static uint64_t get_objc2_64bit_selref(uint64_t ReferenceValue,
2556 struct DisassembleInfo *info) {
2557 uint32_t offset, left;
2560 const char *r = get_pointer_64(ReferenceValue, offset, left, S, info);
2561 if (r == nullptr || left < sizeof(uint64_t))
2564 const char *symbol_name = get_symbol_64(offset, S, info, n_value);
2565 if (symbol_name == nullptr)
2570 // GuessLiteralPointer returns a string which for the item in the Mach-O file
2571 // for the address passed in as ReferenceValue for printing as a comment with
2572 // the instruction and also returns the corresponding type of that item
2573 // indirectly through ReferenceType.
2575 // If ReferenceValue is an address of literal cstring then a pointer to the
2576 // cstring is returned and ReferenceType is set to
2577 // LLVMDisassembler_ReferenceType_Out_LitPool_CstrAddr .
2579 // If ReferenceValue is an address of an Objective-C CFString, Selector ref or
2580 // Class ref that name is returned and the ReferenceType is set accordingly.
2582 // Lastly, literals which are Symbol address in a literal pool are looked for
2583 // and if found the symbol name is returned and ReferenceType is set to
2584 // LLVMDisassembler_ReferenceType_Out_LitPool_SymAddr .
2586 // If there is no item in the Mach-O file for the address passed in as
2587 // ReferenceValue nullptr is returned and ReferenceType is unchanged.
2588 static const char *GuessLiteralPointer(uint64_t ReferenceValue,
2589 uint64_t ReferencePC,
2590 uint64_t *ReferenceType,
2591 struct DisassembleInfo *info) {
2592 // First see if there is an external relocation entry at the ReferencePC.
2593 uint64_t sect_addr = info->S.getAddress();
2594 uint64_t sect_offset = ReferencePC - sect_addr;
2595 bool reloc_found = false;
2597 MachO::any_relocation_info RE;
2598 bool isExtern = false;
2600 for (const RelocationRef &Reloc : info->S.relocations()) {
2601 uint64_t RelocOffset;
2602 Reloc.getOffset(RelocOffset);
2603 if (RelocOffset == sect_offset) {
2604 Rel = Reloc.getRawDataRefImpl();
2605 RE = info->O->getRelocation(Rel);
2606 if (info->O->isRelocationScattered(RE))
2608 isExtern = info->O->getPlainRelocationExternal(RE);
2610 symbol_iterator RelocSym = Reloc.getSymbol();
2617 // If there is an external relocation entry for a symbol in a section
2618 // then used that symbol's value for the value of the reference.
2619 if (reloc_found && isExtern) {
2620 if (info->O->getAnyRelocationPCRel(RE)) {
2621 unsigned Type = info->O->getAnyRelocationType(RE);
2622 if (Type == MachO::X86_64_RELOC_SIGNED) {
2623 Symbol.getAddress(ReferenceValue);
2628 // Look for literals such as Objective-C CFStrings refs, Selector refs,
2629 // Message refs and Class refs.
2630 bool classref, selref, msgref, cfstring;
2631 uint64_t pointer_value = GuessPointerPointer(ReferenceValue, info, classref,
2632 selref, msgref, cfstring);
2633 if (classref == true && pointer_value == 0) {
2634 // Note the ReferenceValue is a pointer into the __objc_classrefs section.
2635 // And the pointer_value in that section is typically zero as it will be
2636 // set by dyld as part of the "bind information".
2637 const char *name = get_dyld_bind_info_symbolname(ReferenceValue, info);
2638 if (name != nullptr) {
2639 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Class_Ref;
2640 const char *class_name = strrchr(name, '$');
2641 if (class_name != nullptr && class_name[1] == '_' &&
2642 class_name[2] != '\0') {
2643 info->class_name = class_name + 2;
2649 if (classref == true) {
2650 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Class_Ref;
2652 get_objc2_64bit_class_name(pointer_value, ReferenceValue, info);
2653 if (name != nullptr)
2654 info->class_name = name;
2656 name = "bad class ref";
2660 if (cfstring == true) {
2661 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_CFString_Ref;
2662 const char *name = get_objc2_64bit_cfstring_name(ReferenceValue, info);
2666 if (selref == true && pointer_value == 0)
2667 pointer_value = get_objc2_64bit_selref(ReferenceValue, info);
2669 if (pointer_value != 0)
2670 ReferenceValue = pointer_value;
2672 const char *name = GuessCstringPointer(ReferenceValue, info);
2674 if (pointer_value != 0 && selref == true) {
2675 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Selector_Ref;
2676 info->selector_name = name;
2677 } else if (pointer_value != 0 && msgref == true) {
2678 info->class_name = nullptr;
2679 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message_Ref;
2680 info->selector_name = name;
2682 *ReferenceType = LLVMDisassembler_ReferenceType_Out_LitPool_CstrAddr;
2686 // Lastly look for an indirect symbol with this ReferenceValue which is in
2687 // a literal pool. If found return that symbol name.
2688 name = GuessIndirectSymbol(ReferenceValue, info);
2690 *ReferenceType = LLVMDisassembler_ReferenceType_Out_LitPool_SymAddr;
2697 // SymbolizerSymbolLookUp is the symbol lookup function passed when creating
2698 // the Symbolizer. It looks up the ReferenceValue using the info passed via the
2699 // pointer to the struct DisassembleInfo that was passed when MCSymbolizer
2700 // is created and returns the symbol name that matches the ReferenceValue or
2701 // nullptr if none. The ReferenceType is passed in for the IN type of
2702 // reference the instruction is making from the values in defined in the header
2703 // "llvm-c/Disassembler.h". On return the ReferenceType can set to a specific
2704 // Out type and the ReferenceName will also be set which is added as a comment
2705 // to the disassembled instruction.
2708 // If the symbol name is a C++ mangled name then the demangled name is
2709 // returned through ReferenceName and ReferenceType is set to
2710 // LLVMDisassembler_ReferenceType_DeMangled_Name .
2713 // When this is called to get a symbol name for a branch target then the
2714 // ReferenceType will be LLVMDisassembler_ReferenceType_In_Branch and then
2715 // SymbolValue will be looked for in the indirect symbol table to determine if
2716 // it is an address for a symbol stub. If so then the symbol name for that
2717 // stub is returned indirectly through ReferenceName and then ReferenceType is
2718 // set to LLVMDisassembler_ReferenceType_Out_SymbolStub.
2720 // When this is called with an value loaded via a PC relative load then
2721 // ReferenceType will be LLVMDisassembler_ReferenceType_In_PCrel_Load then the
2722 // SymbolValue is checked to be an address of literal pointer, symbol pointer,
2723 // or an Objective-C meta data reference. If so the output ReferenceType is
2724 // set to correspond to that as well as setting the ReferenceName.
2725 static const char *SymbolizerSymbolLookUp(void *DisInfo,
2726 uint64_t ReferenceValue,
2727 uint64_t *ReferenceType,
2728 uint64_t ReferencePC,
2729 const char **ReferenceName) {
2730 struct DisassembleInfo *info = (struct DisassembleInfo *)DisInfo;
2731 // If no verbose symbolic information is wanted then just return nullptr.
2732 if (info->verbose == false) {
2733 *ReferenceName = nullptr;
2734 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
2738 const char *SymbolName = GuessSymbolName(ReferenceValue, info->AddrMap);
2740 if (*ReferenceType == LLVMDisassembler_ReferenceType_In_Branch) {
2741 *ReferenceName = GuessIndirectSymbol(ReferenceValue, info);
2742 if (*ReferenceName != nullptr) {
2743 method_reference(info, ReferenceType, ReferenceName);
2744 if (*ReferenceType != LLVMDisassembler_ReferenceType_Out_Objc_Message)
2745 *ReferenceType = LLVMDisassembler_ReferenceType_Out_SymbolStub;
2748 if (SymbolName != nullptr && strncmp(SymbolName, "__Z", 3) == 0) {
2749 if (info->demangled_name != nullptr)
2750 free(info->demangled_name);
2752 info->demangled_name =
2753 abi::__cxa_demangle(SymbolName + 1, nullptr, nullptr, &status);
2754 if (info->demangled_name != nullptr) {
2755 *ReferenceName = info->demangled_name;
2756 *ReferenceType = LLVMDisassembler_ReferenceType_DeMangled_Name;
2758 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
2761 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
2762 } else if (*ReferenceType == LLVMDisassembler_ReferenceType_In_PCrel_Load) {
2764 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
2766 method_reference(info, ReferenceType, ReferenceName);
2768 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
2769 // If this is arm64 and the reference is an adrp instruction save the
2770 // instruction, passed in ReferenceValue and the address of the instruction
2771 // for use later if we see and add immediate instruction.
2772 } else if (info->O->getArch() == Triple::aarch64 &&
2773 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADRP) {
2774 info->adrp_inst = ReferenceValue;
2775 info->adrp_addr = ReferencePC;
2776 SymbolName = nullptr;
2777 *ReferenceName = nullptr;
2778 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
2779 // If this is arm64 and reference is an add immediate instruction and we
2781 // seen an adrp instruction just before it and the adrp's Xd register
2783 // this add's Xn register reconstruct the value being referenced and look to
2784 // see if it is a literal pointer. Note the add immediate instruction is
2785 // passed in ReferenceValue.
2786 } else if (info->O->getArch() == Triple::aarch64 &&
2787 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADDXri &&
2788 ReferencePC - 4 == info->adrp_addr &&
2789 (info->adrp_inst & 0x9f000000) == 0x90000000 &&
2790 (info->adrp_inst & 0x1f) == ((ReferenceValue >> 5) & 0x1f)) {
2791 uint32_t addxri_inst;
2792 uint64_t adrp_imm, addxri_imm;
2795 ((info->adrp_inst & 0x00ffffe0) >> 3) | ((info->adrp_inst >> 29) & 0x3);
2796 if (info->adrp_inst & 0x0200000)
2797 adrp_imm |= 0xfffffffffc000000LL;
2799 addxri_inst = ReferenceValue;
2800 addxri_imm = (addxri_inst >> 10) & 0xfff;
2801 if (((addxri_inst >> 22) & 0x3) == 1)
2804 ReferenceValue = (info->adrp_addr & 0xfffffffffffff000LL) +
2805 (adrp_imm << 12) + addxri_imm;
2808 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
2809 if (*ReferenceName == nullptr)
2810 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
2811 // If this is arm64 and the reference is a load register instruction and we
2812 // have seen an adrp instruction just before it and the adrp's Xd register
2813 // matches this add's Xn register reconstruct the value being referenced and
2814 // look to see if it is a literal pointer. Note the load register
2815 // instruction is passed in ReferenceValue.
2816 } else if (info->O->getArch() == Triple::aarch64 &&
2817 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_LDRXui &&
2818 ReferencePC - 4 == info->adrp_addr &&
2819 (info->adrp_inst & 0x9f000000) == 0x90000000 &&
2820 (info->adrp_inst & 0x1f) == ((ReferenceValue >> 5) & 0x1f)) {
2821 uint32_t ldrxui_inst;
2822 uint64_t adrp_imm, ldrxui_imm;
2825 ((info->adrp_inst & 0x00ffffe0) >> 3) | ((info->adrp_inst >> 29) & 0x3);
2826 if (info->adrp_inst & 0x0200000)
2827 adrp_imm |= 0xfffffffffc000000LL;
2829 ldrxui_inst = ReferenceValue;
2830 ldrxui_imm = (ldrxui_inst >> 10) & 0xfff;
2832 ReferenceValue = (info->adrp_addr & 0xfffffffffffff000LL) +
2833 (adrp_imm << 12) + (ldrxui_imm << 3);
2836 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
2837 if (*ReferenceName == nullptr)
2838 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
2840 // If this arm64 and is an load register (PC-relative) instruction the
2841 // ReferenceValue is the PC plus the immediate value.
2842 else if (info->O->getArch() == Triple::aarch64 &&
2843 (*ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_LDRXl ||
2844 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADR)) {
2846 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
2847 if (*ReferenceName == nullptr)
2848 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
2851 else if (SymbolName != nullptr && strncmp(SymbolName, "__Z", 3) == 0) {
2852 if (info->demangled_name != nullptr)
2853 free(info->demangled_name);
2855 info->demangled_name =
2856 abi::__cxa_demangle(SymbolName + 1, nullptr, nullptr, &status);
2857 if (info->demangled_name != nullptr) {
2858 *ReferenceName = info->demangled_name;
2859 *ReferenceType = LLVMDisassembler_ReferenceType_DeMangled_Name;
2864 *ReferenceName = nullptr;
2865 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
2871 /// \brief Emits the comments that are stored in the CommentStream.
2872 /// Each comment in the CommentStream must end with a newline.
2873 static void emitComments(raw_svector_ostream &CommentStream,
2874 SmallString<128> &CommentsToEmit,
2875 formatted_raw_ostream &FormattedOS,
2876 const MCAsmInfo &MAI) {
2877 // Flush the stream before taking its content.
2878 CommentStream.flush();
2879 StringRef Comments = CommentsToEmit.str();
2880 // Get the default information for printing a comment.
2881 const char *CommentBegin = MAI.getCommentString();
2882 unsigned CommentColumn = MAI.getCommentColumn();
2883 bool IsFirst = true;
2884 while (!Comments.empty()) {
2886 FormattedOS << '\n';
2887 // Emit a line of comments.
2888 FormattedOS.PadToColumn(CommentColumn);
2889 size_t Position = Comments.find('\n');
2890 FormattedOS << CommentBegin << ' ' << Comments.substr(0, Position);
2891 // Move after the newline character.
2892 Comments = Comments.substr(Position + 1);
2895 FormattedOS.flush();
2897 // Tell the comment stream that the vector changed underneath it.
2898 CommentsToEmit.clear();
2899 CommentStream.resync();
2902 static void DisassembleMachO(StringRef Filename, MachOObjectFile *MachOOF,
2903 StringRef DisSegName, StringRef DisSectName) {
2904 const char *McpuDefault = nullptr;
2905 const Target *ThumbTarget = nullptr;
2906 const Target *TheTarget = GetTarget(MachOOF, &McpuDefault, &ThumbTarget);
2908 // GetTarget prints out stuff.
2911 if (MCPU.empty() && McpuDefault)
2914 std::unique_ptr<const MCInstrInfo> InstrInfo(TheTarget->createMCInstrInfo());
2915 std::unique_ptr<const MCInstrInfo> ThumbInstrInfo;
2917 ThumbInstrInfo.reset(ThumbTarget->createMCInstrInfo());
2919 // Package up features to be passed to target/subtarget
2920 std::string FeaturesStr;
2921 if (MAttrs.size()) {
2922 SubtargetFeatures Features;
2923 for (unsigned i = 0; i != MAttrs.size(); ++i)
2924 Features.AddFeature(MAttrs[i]);
2925 FeaturesStr = Features.getString();
2928 // Set up disassembler.
2929 std::unique_ptr<const MCRegisterInfo> MRI(
2930 TheTarget->createMCRegInfo(TripleName));
2931 std::unique_ptr<const MCAsmInfo> AsmInfo(
2932 TheTarget->createMCAsmInfo(*MRI, TripleName));
2933 std::unique_ptr<const MCSubtargetInfo> STI(
2934 TheTarget->createMCSubtargetInfo(TripleName, MCPU, FeaturesStr));
2935 MCContext Ctx(AsmInfo.get(), MRI.get(), nullptr);
2936 std::unique_ptr<MCDisassembler> DisAsm(
2937 TheTarget->createMCDisassembler(*STI, Ctx));
2938 std::unique_ptr<MCSymbolizer> Symbolizer;
2939 struct DisassembleInfo SymbolizerInfo;
2940 std::unique_ptr<MCRelocationInfo> RelInfo(
2941 TheTarget->createMCRelocationInfo(TripleName, Ctx));
2943 Symbolizer.reset(TheTarget->createMCSymbolizer(
2944 TripleName, SymbolizerGetOpInfo, SymbolizerSymbolLookUp,
2945 &SymbolizerInfo, &Ctx, std::move(RelInfo)));
2946 DisAsm->setSymbolizer(std::move(Symbolizer));
2948 int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
2949 std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
2950 AsmPrinterVariant, *AsmInfo, *InstrInfo, *MRI, *STI));
2951 // Set the display preference for hex vs. decimal immediates.
2952 IP->setPrintImmHex(PrintImmHex);
2953 // Comment stream and backing vector.
2954 SmallString<128> CommentsToEmit;
2955 raw_svector_ostream CommentStream(CommentsToEmit);
2956 // FIXME: Setting the CommentStream in the InstPrinter is problematic in that
2957 // if it is done then arm64 comments for string literals don't get printed
2958 // and some constant get printed instead and not setting it causes intel
2959 // (32-bit and 64-bit) comments printed with different spacing before the
2960 // comment causing different diffs with the 'C' disassembler library API.
2961 // IP->setCommentStream(CommentStream);
2963 if (!AsmInfo || !STI || !DisAsm || !IP) {
2964 errs() << "error: couldn't initialize disassembler for target "
2965 << TripleName << '\n';
2969 // Set up thumb disassembler.
2970 std::unique_ptr<const MCRegisterInfo> ThumbMRI;
2971 std::unique_ptr<const MCAsmInfo> ThumbAsmInfo;
2972 std::unique_ptr<const MCSubtargetInfo> ThumbSTI;
2973 std::unique_ptr<MCDisassembler> ThumbDisAsm;
2974 std::unique_ptr<MCInstPrinter> ThumbIP;
2975 std::unique_ptr<MCContext> ThumbCtx;
2976 std::unique_ptr<MCSymbolizer> ThumbSymbolizer;
2977 struct DisassembleInfo ThumbSymbolizerInfo;
2978 std::unique_ptr<MCRelocationInfo> ThumbRelInfo;
2980 ThumbMRI.reset(ThumbTarget->createMCRegInfo(ThumbTripleName));
2982 ThumbTarget->createMCAsmInfo(*ThumbMRI, ThumbTripleName));
2984 ThumbTarget->createMCSubtargetInfo(ThumbTripleName, MCPU, FeaturesStr));
2985 ThumbCtx.reset(new MCContext(ThumbAsmInfo.get(), ThumbMRI.get(), nullptr));
2986 ThumbDisAsm.reset(ThumbTarget->createMCDisassembler(*ThumbSTI, *ThumbCtx));
2987 MCContext *PtrThumbCtx = ThumbCtx.get();
2989 ThumbTarget->createMCRelocationInfo(ThumbTripleName, *PtrThumbCtx));
2991 ThumbSymbolizer.reset(ThumbTarget->createMCSymbolizer(
2992 ThumbTripleName, SymbolizerGetOpInfo, SymbolizerSymbolLookUp,
2993 &ThumbSymbolizerInfo, PtrThumbCtx, std::move(ThumbRelInfo)));
2994 ThumbDisAsm->setSymbolizer(std::move(ThumbSymbolizer));
2996 int ThumbAsmPrinterVariant = ThumbAsmInfo->getAssemblerDialect();
2997 ThumbIP.reset(ThumbTarget->createMCInstPrinter(
2998 ThumbAsmPrinterVariant, *ThumbAsmInfo, *ThumbInstrInfo, *ThumbMRI,
3000 // Set the display preference for hex vs. decimal immediates.
3001 ThumbIP->setPrintImmHex(PrintImmHex);
3004 if (ThumbTarget && (!ThumbAsmInfo || !ThumbSTI || !ThumbDisAsm || !ThumbIP)) {
3005 errs() << "error: couldn't initialize disassembler for target "
3006 << ThumbTripleName << '\n';
3010 MachO::mach_header Header = MachOOF->getHeader();
3012 // FIXME: Using the -cfg command line option, this code used to be able to
3013 // annotate relocations with the referenced symbol's name, and if this was
3014 // inside a __[cf]string section, the data it points to. This is now replaced
3015 // by the upcoming MCSymbolizer, which needs the appropriate setup done above.
3016 std::vector<SectionRef> Sections;
3017 std::vector<SymbolRef> Symbols;
3018 SmallVector<uint64_t, 8> FoundFns;
3019 uint64_t BaseSegmentAddress;
3021 getSectionsAndSymbols(Header, MachOOF, Sections, Symbols, FoundFns,
3022 BaseSegmentAddress);
3024 // Sort the symbols by address, just in case they didn't come in that way.
3025 std::sort(Symbols.begin(), Symbols.end(), SymbolSorter());
3027 // Build a data in code table that is sorted on by the address of each entry.
3028 uint64_t BaseAddress = 0;
3029 if (Header.filetype == MachO::MH_OBJECT)
3030 BaseAddress = Sections[0].getAddress();
3032 BaseAddress = BaseSegmentAddress;
3034 for (dice_iterator DI = MachOOF->begin_dices(), DE = MachOOF->end_dices();
3037 DI->getOffset(Offset);
3038 Dices.push_back(std::make_pair(BaseAddress + Offset, *DI));
3040 array_pod_sort(Dices.begin(), Dices.end());
3043 raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls();
3045 raw_ostream &DebugOut = nulls();
3048 std::unique_ptr<DIContext> diContext;
3049 ObjectFile *DbgObj = MachOOF;
3050 // Try to find debug info and set up the DIContext for it.
3052 // A separate DSym file path was specified, parse it as a macho file,
3053 // get the sections and supply it to the section name parsing machinery.
3054 if (!DSYMFile.empty()) {
3055 ErrorOr<std::unique_ptr<MemoryBuffer>> BufOrErr =
3056 MemoryBuffer::getFileOrSTDIN(DSYMFile);
3057 if (std::error_code EC = BufOrErr.getError()) {
3058 errs() << "llvm-objdump: " << Filename << ": " << EC.message() << '\n';
3062 ObjectFile::createMachOObjectFile(BufOrErr.get()->getMemBufferRef())
3067 // Setup the DIContext
3068 diContext.reset(DIContext::getDWARFContext(*DbgObj));
3071 if (DumpSections.size() == 0)
3072 outs() << "(" << DisSegName << "," << DisSectName << ") section\n";
3074 for (unsigned SectIdx = 0; SectIdx != Sections.size(); SectIdx++) {
3076 if (Sections[SectIdx].getName(SectName) || SectName != DisSectName)
3079 DataRefImpl DR = Sections[SectIdx].getRawDataRefImpl();
3081 StringRef SegmentName = MachOOF->getSectionFinalSegmentName(DR);
3082 if (SegmentName != DisSegName)
3086 Sections[SectIdx].getContents(BytesStr);
3087 ArrayRef<uint8_t> Bytes(reinterpret_cast<const uint8_t *>(BytesStr.data()),
3089 uint64_t SectAddress = Sections[SectIdx].getAddress();
3091 bool symbolTableWorked = false;
3093 // Parse relocations.
3094 std::vector<std::pair<uint64_t, SymbolRef>> Relocs;
3095 for (const RelocationRef &Reloc : Sections[SectIdx].relocations()) {
3096 uint64_t RelocOffset;
3097 Reloc.getOffset(RelocOffset);
3098 uint64_t SectionAddress = Sections[SectIdx].getAddress();
3099 RelocOffset -= SectionAddress;
3101 symbol_iterator RelocSym = Reloc.getSymbol();
3103 Relocs.push_back(std::make_pair(RelocOffset, *RelocSym));
3105 array_pod_sort(Relocs.begin(), Relocs.end());
3107 // Create a map of symbol addresses to symbol names for use by
3108 // the SymbolizerSymbolLookUp() routine.
3109 SymbolAddressMap AddrMap;
3110 for (const SymbolRef &Symbol : MachOOF->symbols()) {
3113 if (ST == SymbolRef::ST_Function || ST == SymbolRef::ST_Data ||
3114 ST == SymbolRef::ST_Other) {
3116 Symbol.getAddress(Address);
3118 Symbol.getName(SymName);
3119 AddrMap[Address] = SymName;
3122 // Set up the block of info used by the Symbolizer call backs.
3123 SymbolizerInfo.verbose = true;
3124 SymbolizerInfo.O = MachOOF;
3125 SymbolizerInfo.S = Sections[SectIdx];
3126 SymbolizerInfo.AddrMap = &AddrMap;
3127 SymbolizerInfo.Sections = &Sections;
3128 SymbolizerInfo.class_name = nullptr;
3129 SymbolizerInfo.selector_name = nullptr;
3130 SymbolizerInfo.method = nullptr;
3131 SymbolizerInfo.demangled_name = nullptr;
3132 SymbolizerInfo.bindtable = nullptr;
3133 SymbolizerInfo.adrp_addr = 0;
3134 SymbolizerInfo.adrp_inst = 0;
3135 // Same for the ThumbSymbolizer
3136 ThumbSymbolizerInfo.verbose = true;
3137 ThumbSymbolizerInfo.O = MachOOF;
3138 ThumbSymbolizerInfo.S = Sections[SectIdx];
3139 ThumbSymbolizerInfo.AddrMap = &AddrMap;
3140 ThumbSymbolizerInfo.Sections = &Sections;
3141 ThumbSymbolizerInfo.class_name = nullptr;
3142 ThumbSymbolizerInfo.selector_name = nullptr;
3143 ThumbSymbolizerInfo.method = nullptr;
3144 ThumbSymbolizerInfo.demangled_name = nullptr;
3145 ThumbSymbolizerInfo.bindtable = nullptr;
3146 ThumbSymbolizerInfo.adrp_addr = 0;
3147 ThumbSymbolizerInfo.adrp_inst = 0;
3149 // Disassemble symbol by symbol.
3150 for (unsigned SymIdx = 0; SymIdx != Symbols.size(); SymIdx++) {
3152 Symbols[SymIdx].getName(SymName);
3155 Symbols[SymIdx].getType(ST);
3156 if (ST != SymbolRef::ST_Function)
3159 // Make sure the symbol is defined in this section.
3160 bool containsSym = Sections[SectIdx].containsSymbol(Symbols[SymIdx]);
3164 // Start at the address of the symbol relative to the section's address.
3166 uint64_t SectionAddress = Sections[SectIdx].getAddress();
3167 Symbols[SymIdx].getAddress(Start);
3168 Start -= SectionAddress;
3170 // Stop disassembling either at the beginning of the next symbol or at
3171 // the end of the section.
3172 bool containsNextSym = false;
3173 uint64_t NextSym = 0;
3174 uint64_t NextSymIdx = SymIdx + 1;
3175 while (Symbols.size() > NextSymIdx) {
3176 SymbolRef::Type NextSymType;
3177 Symbols[NextSymIdx].getType(NextSymType);
3178 if (NextSymType == SymbolRef::ST_Function) {
3180 Sections[SectIdx].containsSymbol(Symbols[NextSymIdx]);
3181 Symbols[NextSymIdx].getAddress(NextSym);
3182 NextSym -= SectionAddress;
3188 uint64_t SectSize = Sections[SectIdx].getSize();
3189 uint64_t End = containsNextSym ? NextSym : SectSize;
3192 symbolTableWorked = true;
3194 DataRefImpl Symb = Symbols[SymIdx].getRawDataRefImpl();
3196 (MachOOF->getSymbolFlags(Symb) & SymbolRef::SF_Thumb) && ThumbTarget;
3198 outs() << SymName << ":\n";
3199 DILineInfo lastLine;
3200 for (uint64_t Index = Start; Index < End; Index += Size) {
3203 uint64_t PC = SectAddress + Index;
3204 if (FullLeadingAddr) {
3205 if (MachOOF->is64Bit())
3206 outs() << format("%016" PRIx64, PC);
3208 outs() << format("%08" PRIx64, PC);
3210 outs() << format("%8" PRIx64 ":", PC);
3215 // Check the data in code table here to see if this is data not an
3216 // instruction to be disassembled.
3218 Dice.push_back(std::make_pair(PC, DiceRef()));
3219 dice_table_iterator DTI =
3220 std::search(Dices.begin(), Dices.end(), Dice.begin(), Dice.end(),
3221 compareDiceTableEntries);
3222 if (DTI != Dices.end()) {
3224 DTI->second.getLength(Length);
3226 DTI->second.getKind(Kind);
3227 Size = DumpDataInCode(reinterpret_cast<const char *>(Bytes.data()) +
3230 if ((Kind == MachO::DICE_KIND_JUMP_TABLE8) &&
3231 (PC == (DTI->first + Length - 1)) && (Length & 1))
3236 SmallVector<char, 64> AnnotationsBytes;
3237 raw_svector_ostream Annotations(AnnotationsBytes);
3241 gotInst = ThumbDisAsm->getInstruction(Inst, Size, Bytes.slice(Index),
3242 PC, DebugOut, Annotations);
3244 gotInst = DisAsm->getInstruction(Inst, Size, Bytes.slice(Index), PC,
3245 DebugOut, Annotations);
3247 if (!NoShowRawInsn) {
3248 DumpBytes(StringRef(
3249 reinterpret_cast<const char *>(Bytes.data()) + Index, Size));
3251 formatted_raw_ostream FormattedOS(outs());
3252 Annotations.flush();
3253 StringRef AnnotationsStr = Annotations.str();
3255 ThumbIP->printInst(&Inst, FormattedOS, AnnotationsStr);
3257 IP->printInst(&Inst, FormattedOS, AnnotationsStr);
3258 emitComments(CommentStream, CommentsToEmit, FormattedOS, *AsmInfo);
3260 // Print debug info.
3262 DILineInfo dli = diContext->getLineInfoForAddress(PC);
3263 // Print valid line info if it changed.
3264 if (dli != lastLine && dli.Line != 0)
3265 outs() << "\t## " << dli.FileName << ':' << dli.Line << ':'
3271 unsigned int Arch = MachOOF->getArch();
3272 if (Arch == Triple::x86_64 || Arch == Triple::x86) {
3273 outs() << format("\t.byte 0x%02x #bad opcode\n",
3274 *(Bytes.data() + Index) & 0xff);
3275 Size = 1; // skip exactly one illegible byte and move on.
3276 } else if (Arch == Triple::aarch64) {
3277 uint32_t opcode = (*(Bytes.data() + Index) & 0xff) |
3278 (*(Bytes.data() + Index + 1) & 0xff) << 8 |
3279 (*(Bytes.data() + Index + 2) & 0xff) << 16 |
3280 (*(Bytes.data() + Index + 3) & 0xff) << 24;
3281 outs() << format("\t.long\t0x%08x\n", opcode);
3284 errs() << "llvm-objdump: warning: invalid instruction encoding\n";
3286 Size = 1; // skip illegible bytes
3291 if (!symbolTableWorked) {
3292 // Reading the symbol table didn't work, disassemble the whole section.
3293 uint64_t SectAddress = Sections[SectIdx].getAddress();
3294 uint64_t SectSize = Sections[SectIdx].getSize();
3296 for (uint64_t Index = 0; Index < SectSize; Index += InstSize) {
3299 uint64_t PC = SectAddress + Index;
3300 if (DisAsm->getInstruction(Inst, InstSize, Bytes.slice(Index), PC,
3301 DebugOut, nulls())) {
3302 if (FullLeadingAddr) {
3303 if (MachOOF->is64Bit())
3304 outs() << format("%016" PRIx64, PC);
3306 outs() << format("%08" PRIx64, PC);
3308 outs() << format("%8" PRIx64 ":", PC);
3310 if (!NoShowRawInsn) {
3313 StringRef(reinterpret_cast<const char *>(Bytes.data()) + Index,
3316 IP->printInst(&Inst, outs(), "");
3319 unsigned int Arch = MachOOF->getArch();
3320 if (Arch == Triple::x86_64 || Arch == Triple::x86) {
3321 outs() << format("\t.byte 0x%02x #bad opcode\n",
3322 *(Bytes.data() + Index) & 0xff);
3323 InstSize = 1; // skip exactly one illegible byte and move on.
3325 errs() << "llvm-objdump: warning: invalid instruction encoding\n";
3327 InstSize = 1; // skip illegible bytes
3332 // The TripleName's need to be reset if we are called again for a different
3335 ThumbTripleName = "";
3337 if (SymbolizerInfo.method != nullptr)
3338 free(SymbolizerInfo.method);
3339 if (SymbolizerInfo.demangled_name != nullptr)
3340 free(SymbolizerInfo.demangled_name);
3341 if (SymbolizerInfo.bindtable != nullptr)
3342 delete SymbolizerInfo.bindtable;
3343 if (ThumbSymbolizerInfo.method != nullptr)
3344 free(ThumbSymbolizerInfo.method);
3345 if (ThumbSymbolizerInfo.demangled_name != nullptr)
3346 free(ThumbSymbolizerInfo.demangled_name);
3347 if (ThumbSymbolizerInfo.bindtable != nullptr)
3348 delete ThumbSymbolizerInfo.bindtable;
3352 //===----------------------------------------------------------------------===//
3353 // __compact_unwind section dumping
3354 //===----------------------------------------------------------------------===//
3358 template <typename T> static uint64_t readNext(const char *&Buf) {
3359 using llvm::support::little;
3360 using llvm::support::unaligned;
3362 uint64_t Val = support::endian::read<T, little, unaligned>(Buf);
3367 struct CompactUnwindEntry {
3368 uint32_t OffsetInSection;
3370 uint64_t FunctionAddr;
3372 uint32_t CompactEncoding;
3373 uint64_t PersonalityAddr;
3376 RelocationRef FunctionReloc;
3377 RelocationRef PersonalityReloc;
3378 RelocationRef LSDAReloc;
3380 CompactUnwindEntry(StringRef Contents, unsigned Offset, bool Is64)
3381 : OffsetInSection(Offset) {
3383 read<uint64_t>(Contents.data() + Offset);
3385 read<uint32_t>(Contents.data() + Offset);
3389 template <typename UIntPtr> void read(const char *Buf) {
3390 FunctionAddr = readNext<UIntPtr>(Buf);
3391 Length = readNext<uint32_t>(Buf);
3392 CompactEncoding = readNext<uint32_t>(Buf);
3393 PersonalityAddr = readNext<UIntPtr>(Buf);
3394 LSDAAddr = readNext<UIntPtr>(Buf);
3399 /// Given a relocation from __compact_unwind, consisting of the RelocationRef
3400 /// and data being relocated, determine the best base Name and Addend to use for
3401 /// display purposes.
3403 /// 1. An Extern relocation will directly reference a symbol (and the data is
3404 /// then already an addend), so use that.
3405 /// 2. Otherwise the data is an offset in the object file's layout; try to find
3406 // a symbol before it in the same section, and use the offset from there.
3407 /// 3. Finally, if all that fails, fall back to an offset from the start of the
3408 /// referenced section.
3409 static void findUnwindRelocNameAddend(const MachOObjectFile *Obj,
3410 std::map<uint64_t, SymbolRef> &Symbols,
3411 const RelocationRef &Reloc, uint64_t Addr,
3412 StringRef &Name, uint64_t &Addend) {
3413 if (Reloc.getSymbol() != Obj->symbol_end()) {
3414 Reloc.getSymbol()->getName(Name);
3419 auto RE = Obj->getRelocation(Reloc.getRawDataRefImpl());
3420 SectionRef RelocSection = Obj->getRelocationSection(RE);
3422 uint64_t SectionAddr = RelocSection.getAddress();
3424 auto Sym = Symbols.upper_bound(Addr);
3425 if (Sym == Symbols.begin()) {
3426 // The first symbol in the object is after this reference, the best we can
3427 // do is section-relative notation.
3428 RelocSection.getName(Name);
3429 Addend = Addr - SectionAddr;
3433 // Go back one so that SymbolAddress <= Addr.
3436 section_iterator SymSection = Obj->section_end();
3437 Sym->second.getSection(SymSection);
3438 if (RelocSection == *SymSection) {
3439 // There's a valid symbol in the same section before this reference.
3440 Sym->second.getName(Name);
3441 Addend = Addr - Sym->first;
3445 // There is a symbol before this reference, but it's in a different
3446 // section. Probably not helpful to mention it, so use the section name.
3447 RelocSection.getName(Name);
3448 Addend = Addr - SectionAddr;
3451 static void printUnwindRelocDest(const MachOObjectFile *Obj,
3452 std::map<uint64_t, SymbolRef> &Symbols,
3453 const RelocationRef &Reloc, uint64_t Addr) {
3457 if (!Reloc.getObjectFile())
3460 findUnwindRelocNameAddend(Obj, Symbols, Reloc, Addr, Name, Addend);
3464 outs() << " + " << format("0x%" PRIx64, Addend);
3468 printMachOCompactUnwindSection(const MachOObjectFile *Obj,
3469 std::map<uint64_t, SymbolRef> &Symbols,
3470 const SectionRef &CompactUnwind) {
3472 assert(Obj->isLittleEndian() &&
3473 "There should not be a big-endian .o with __compact_unwind");
3475 bool Is64 = Obj->is64Bit();
3476 uint32_t PointerSize = Is64 ? sizeof(uint64_t) : sizeof(uint32_t);
3477 uint32_t EntrySize = 3 * PointerSize + 2 * sizeof(uint32_t);
3480 CompactUnwind.getContents(Contents);
3482 SmallVector<CompactUnwindEntry, 4> CompactUnwinds;
3484 // First populate the initial raw offsets, encodings and so on from the entry.
3485 for (unsigned Offset = 0; Offset < Contents.size(); Offset += EntrySize) {
3486 CompactUnwindEntry Entry(Contents.data(), Offset, Is64);
3487 CompactUnwinds.push_back(Entry);
3490 // Next we need to look at the relocations to find out what objects are
3491 // actually being referred to.
3492 for (const RelocationRef &Reloc : CompactUnwind.relocations()) {
3493 uint64_t RelocAddress;
3494 Reloc.getOffset(RelocAddress);
3496 uint32_t EntryIdx = RelocAddress / EntrySize;
3497 uint32_t OffsetInEntry = RelocAddress - EntryIdx * EntrySize;
3498 CompactUnwindEntry &Entry = CompactUnwinds[EntryIdx];
3500 if (OffsetInEntry == 0)
3501 Entry.FunctionReloc = Reloc;
3502 else if (OffsetInEntry == PointerSize + 2 * sizeof(uint32_t))
3503 Entry.PersonalityReloc = Reloc;
3504 else if (OffsetInEntry == 2 * PointerSize + 2 * sizeof(uint32_t))
3505 Entry.LSDAReloc = Reloc;
3507 llvm_unreachable("Unexpected relocation in __compact_unwind section");
3510 // Finally, we're ready to print the data we've gathered.
3511 outs() << "Contents of __compact_unwind section:\n";
3512 for (auto &Entry : CompactUnwinds) {
3513 outs() << " Entry at offset "
3514 << format("0x%" PRIx32, Entry.OffsetInSection) << ":\n";
3516 // 1. Start of the region this entry applies to.
3517 outs() << " start: " << format("0x%" PRIx64,
3518 Entry.FunctionAddr) << ' ';
3519 printUnwindRelocDest(Obj, Symbols, Entry.FunctionReloc, Entry.FunctionAddr);
3522 // 2. Length of the region this entry applies to.
3523 outs() << " length: " << format("0x%" PRIx32, Entry.Length)
3525 // 3. The 32-bit compact encoding.
3526 outs() << " compact encoding: "
3527 << format("0x%08" PRIx32, Entry.CompactEncoding) << '\n';
3529 // 4. The personality function, if present.
3530 if (Entry.PersonalityReloc.getObjectFile()) {
3531 outs() << " personality function: "
3532 << format("0x%" PRIx64, Entry.PersonalityAddr) << ' ';
3533 printUnwindRelocDest(Obj, Symbols, Entry.PersonalityReloc,
3534 Entry.PersonalityAddr);
3538 // 5. This entry's language-specific data area.
3539 if (Entry.LSDAReloc.getObjectFile()) {
3540 outs() << " LSDA: " << format("0x%" PRIx64,
3541 Entry.LSDAAddr) << ' ';
3542 printUnwindRelocDest(Obj, Symbols, Entry.LSDAReloc, Entry.LSDAAddr);
3548 //===----------------------------------------------------------------------===//
3549 // __unwind_info section dumping
3550 //===----------------------------------------------------------------------===//
3552 static void printRegularSecondLevelUnwindPage(const char *PageStart) {
3553 const char *Pos = PageStart;
3554 uint32_t Kind = readNext<uint32_t>(Pos);
3556 assert(Kind == 2 && "kind for a regular 2nd level index should be 2");
3558 uint16_t EntriesStart = readNext<uint16_t>(Pos);
3559 uint16_t NumEntries = readNext<uint16_t>(Pos);
3561 Pos = PageStart + EntriesStart;
3562 for (unsigned i = 0; i < NumEntries; ++i) {
3563 uint32_t FunctionOffset = readNext<uint32_t>(Pos);
3564 uint32_t Encoding = readNext<uint32_t>(Pos);
3566 outs() << " [" << i << "]: "
3567 << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
3569 << "encoding=" << format("0x%08" PRIx32, Encoding) << '\n';
3573 static void printCompressedSecondLevelUnwindPage(
3574 const char *PageStart, uint32_t FunctionBase,
3575 const SmallVectorImpl<uint32_t> &CommonEncodings) {
3576 const char *Pos = PageStart;
3577 uint32_t Kind = readNext<uint32_t>(Pos);
3579 assert(Kind == 3 && "kind for a compressed 2nd level index should be 3");
3581 uint16_t EntriesStart = readNext<uint16_t>(Pos);
3582 uint16_t NumEntries = readNext<uint16_t>(Pos);
3584 uint16_t EncodingsStart = readNext<uint16_t>(Pos);
3585 readNext<uint16_t>(Pos);
3586 const auto *PageEncodings = reinterpret_cast<const support::ulittle32_t *>(
3587 PageStart + EncodingsStart);
3589 Pos = PageStart + EntriesStart;
3590 for (unsigned i = 0; i < NumEntries; ++i) {
3591 uint32_t Entry = readNext<uint32_t>(Pos);
3592 uint32_t FunctionOffset = FunctionBase + (Entry & 0xffffff);
3593 uint32_t EncodingIdx = Entry >> 24;
3596 if (EncodingIdx < CommonEncodings.size())
3597 Encoding = CommonEncodings[EncodingIdx];
3599 Encoding = PageEncodings[EncodingIdx - CommonEncodings.size()];
3601 outs() << " [" << i << "]: "
3602 << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
3604 << "encoding[" << EncodingIdx
3605 << "]=" << format("0x%08" PRIx32, Encoding) << '\n';
3609 static void printMachOUnwindInfoSection(const MachOObjectFile *Obj,
3610 std::map<uint64_t, SymbolRef> &Symbols,
3611 const SectionRef &UnwindInfo) {
3613 assert(Obj->isLittleEndian() &&
3614 "There should not be a big-endian .o with __unwind_info");
3616 outs() << "Contents of __unwind_info section:\n";
3619 UnwindInfo.getContents(Contents);
3620 const char *Pos = Contents.data();
3622 //===----------------------------------
3624 //===----------------------------------
3626 uint32_t Version = readNext<uint32_t>(Pos);
3627 outs() << " Version: "
3628 << format("0x%" PRIx32, Version) << '\n';
3629 assert(Version == 1 && "only understand version 1");
3631 uint32_t CommonEncodingsStart = readNext<uint32_t>(Pos);
3632 outs() << " Common encodings array section offset: "
3633 << format("0x%" PRIx32, CommonEncodingsStart) << '\n';
3634 uint32_t NumCommonEncodings = readNext<uint32_t>(Pos);
3635 outs() << " Number of common encodings in array: "
3636 << format("0x%" PRIx32, NumCommonEncodings) << '\n';
3638 uint32_t PersonalitiesStart = readNext<uint32_t>(Pos);
3639 outs() << " Personality function array section offset: "
3640 << format("0x%" PRIx32, PersonalitiesStart) << '\n';
3641 uint32_t NumPersonalities = readNext<uint32_t>(Pos);
3642 outs() << " Number of personality functions in array: "
3643 << format("0x%" PRIx32, NumPersonalities) << '\n';
3645 uint32_t IndicesStart = readNext<uint32_t>(Pos);
3646 outs() << " Index array section offset: "
3647 << format("0x%" PRIx32, IndicesStart) << '\n';
3648 uint32_t NumIndices = readNext<uint32_t>(Pos);
3649 outs() << " Number of indices in array: "
3650 << format("0x%" PRIx32, NumIndices) << '\n';
3652 //===----------------------------------
3653 // A shared list of common encodings
3654 //===----------------------------------
3656 // These occupy indices in the range [0, N] whenever an encoding is referenced
3657 // from a compressed 2nd level index table. In practice the linker only
3658 // creates ~128 of these, so that indices are available to embed encodings in
3659 // the 2nd level index.
3661 SmallVector<uint32_t, 64> CommonEncodings;
3662 outs() << " Common encodings: (count = " << NumCommonEncodings << ")\n";
3663 Pos = Contents.data() + CommonEncodingsStart;
3664 for (unsigned i = 0; i < NumCommonEncodings; ++i) {
3665 uint32_t Encoding = readNext<uint32_t>(Pos);
3666 CommonEncodings.push_back(Encoding);
3668 outs() << " encoding[" << i << "]: " << format("0x%08" PRIx32, Encoding)
3672 //===----------------------------------
3673 // Personality functions used in this executable
3674 //===----------------------------------
3676 // There should be only a handful of these (one per source language,
3677 // roughly). Particularly since they only get 2 bits in the compact encoding.
3679 outs() << " Personality functions: (count = " << NumPersonalities << ")\n";
3680 Pos = Contents.data() + PersonalitiesStart;
3681 for (unsigned i = 0; i < NumPersonalities; ++i) {
3682 uint32_t PersonalityFn = readNext<uint32_t>(Pos);
3683 outs() << " personality[" << i + 1
3684 << "]: " << format("0x%08" PRIx32, PersonalityFn) << '\n';
3687 //===----------------------------------
3688 // The level 1 index entries
3689 //===----------------------------------
3691 // These specify an approximate place to start searching for the more detailed
3692 // information, sorted by PC.
3695 uint32_t FunctionOffset;
3696 uint32_t SecondLevelPageStart;
3700 SmallVector<IndexEntry, 4> IndexEntries;
3702 outs() << " Top level indices: (count = " << NumIndices << ")\n";
3703 Pos = Contents.data() + IndicesStart;
3704 for (unsigned i = 0; i < NumIndices; ++i) {
3707 Entry.FunctionOffset = readNext<uint32_t>(Pos);
3708 Entry.SecondLevelPageStart = readNext<uint32_t>(Pos);
3709 Entry.LSDAStart = readNext<uint32_t>(Pos);
3710 IndexEntries.push_back(Entry);
3712 outs() << " [" << i << "]: "
3713 << "function offset=" << format("0x%08" PRIx32, Entry.FunctionOffset)
3715 << "2nd level page offset="
3716 << format("0x%08" PRIx32, Entry.SecondLevelPageStart) << ", "
3717 << "LSDA offset=" << format("0x%08" PRIx32, Entry.LSDAStart) << '\n';
3720 //===----------------------------------
3721 // Next come the LSDA tables
3722 //===----------------------------------
3724 // The LSDA layout is rather implicit: it's a contiguous array of entries from
3725 // the first top-level index's LSDAOffset to the last (sentinel).
3727 outs() << " LSDA descriptors:\n";
3728 Pos = Contents.data() + IndexEntries[0].LSDAStart;
3729 int NumLSDAs = (IndexEntries.back().LSDAStart - IndexEntries[0].LSDAStart) /
3730 (2 * sizeof(uint32_t));
3731 for (int i = 0; i < NumLSDAs; ++i) {
3732 uint32_t FunctionOffset = readNext<uint32_t>(Pos);
3733 uint32_t LSDAOffset = readNext<uint32_t>(Pos);
3734 outs() << " [" << i << "]: "
3735 << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
3737 << "LSDA offset=" << format("0x%08" PRIx32, LSDAOffset) << '\n';
3740 //===----------------------------------
3741 // Finally, the 2nd level indices
3742 //===----------------------------------
3744 // Generally these are 4K in size, and have 2 possible forms:
3745 // + Regular stores up to 511 entries with disparate encodings
3746 // + Compressed stores up to 1021 entries if few enough compact encoding
3748 outs() << " Second level indices:\n";
3749 for (unsigned i = 0; i < IndexEntries.size() - 1; ++i) {
3750 // The final sentinel top-level index has no associated 2nd level page
3751 if (IndexEntries[i].SecondLevelPageStart == 0)
3754 outs() << " Second level index[" << i << "]: "
3755 << "offset in section="
3756 << format("0x%08" PRIx32, IndexEntries[i].SecondLevelPageStart)
3758 << "base function offset="
3759 << format("0x%08" PRIx32, IndexEntries[i].FunctionOffset) << '\n';
3761 Pos = Contents.data() + IndexEntries[i].SecondLevelPageStart;
3762 uint32_t Kind = *reinterpret_cast<const support::ulittle32_t *>(Pos);
3764 printRegularSecondLevelUnwindPage(Pos);
3766 printCompressedSecondLevelUnwindPage(Pos, IndexEntries[i].FunctionOffset,
3769 llvm_unreachable("Do not know how to print this kind of 2nd level page");
3773 void llvm::printMachOUnwindInfo(const MachOObjectFile *Obj) {
3774 std::map<uint64_t, SymbolRef> Symbols;
3775 for (const SymbolRef &SymRef : Obj->symbols()) {
3776 // Discard any undefined or absolute symbols. They're not going to take part
3777 // in the convenience lookup for unwind info and just take up resources.
3778 section_iterator Section = Obj->section_end();
3779 SymRef.getSection(Section);
3780 if (Section == Obj->section_end())
3784 SymRef.getAddress(Addr);
3785 Symbols.insert(std::make_pair(Addr, SymRef));
3788 for (const SectionRef &Section : Obj->sections()) {
3790 Section.getName(SectName);
3791 if (SectName == "__compact_unwind")
3792 printMachOCompactUnwindSection(Obj, Symbols, Section);
3793 else if (SectName == "__unwind_info")
3794 printMachOUnwindInfoSection(Obj, Symbols, Section);
3795 else if (SectName == "__eh_frame")
3796 outs() << "llvm-objdump: warning: unhandled __eh_frame section\n";
3800 static void PrintMachHeader(uint32_t magic, uint32_t cputype,
3801 uint32_t cpusubtype, uint32_t filetype,
3802 uint32_t ncmds, uint32_t sizeofcmds, uint32_t flags,
3804 outs() << "Mach header\n";
3805 outs() << " magic cputype cpusubtype caps filetype ncmds "
3806 "sizeofcmds flags\n";
3808 if (magic == MachO::MH_MAGIC)
3809 outs() << " MH_MAGIC";
3810 else if (magic == MachO::MH_MAGIC_64)
3811 outs() << "MH_MAGIC_64";
3813 outs() << format(" 0x%08" PRIx32, magic);
3815 case MachO::CPU_TYPE_I386:
3817 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
3818 case MachO::CPU_SUBTYPE_I386_ALL:
3822 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
3826 case MachO::CPU_TYPE_X86_64:
3827 outs() << " X86_64";
3828 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
3829 case MachO::CPU_SUBTYPE_X86_64_ALL:
3832 case MachO::CPU_SUBTYPE_X86_64_H:
3833 outs() << " Haswell";
3836 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
3840 case MachO::CPU_TYPE_ARM:
3842 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
3843 case MachO::CPU_SUBTYPE_ARM_ALL:
3846 case MachO::CPU_SUBTYPE_ARM_V4T:
3849 case MachO::CPU_SUBTYPE_ARM_V5TEJ:
3852 case MachO::CPU_SUBTYPE_ARM_XSCALE:
3853 outs() << " XSCALE";
3855 case MachO::CPU_SUBTYPE_ARM_V6:
3858 case MachO::CPU_SUBTYPE_ARM_V6M:
3861 case MachO::CPU_SUBTYPE_ARM_V7:
3864 case MachO::CPU_SUBTYPE_ARM_V7EM:
3867 case MachO::CPU_SUBTYPE_ARM_V7K:
3870 case MachO::CPU_SUBTYPE_ARM_V7M:
3873 case MachO::CPU_SUBTYPE_ARM_V7S:
3877 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
3881 case MachO::CPU_TYPE_ARM64:
3883 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
3884 case MachO::CPU_SUBTYPE_ARM64_ALL:
3888 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
3892 case MachO::CPU_TYPE_POWERPC:
3894 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
3895 case MachO::CPU_SUBTYPE_POWERPC_ALL:
3899 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
3903 case MachO::CPU_TYPE_POWERPC64:
3905 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
3906 case MachO::CPU_SUBTYPE_POWERPC_ALL:
3910 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
3915 if ((cpusubtype & MachO::CPU_SUBTYPE_MASK) == MachO::CPU_SUBTYPE_LIB64) {
3918 outs() << format(" 0x%02" PRIx32,
3919 (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24);
3922 case MachO::MH_OBJECT:
3923 outs() << " OBJECT";
3925 case MachO::MH_EXECUTE:
3926 outs() << " EXECUTE";
3928 case MachO::MH_FVMLIB:
3929 outs() << " FVMLIB";
3931 case MachO::MH_CORE:
3934 case MachO::MH_PRELOAD:
3935 outs() << " PRELOAD";
3937 case MachO::MH_DYLIB:
3940 case MachO::MH_DYLIB_STUB:
3941 outs() << " DYLIB_STUB";
3943 case MachO::MH_DYLINKER:
3944 outs() << " DYLINKER";
3946 case MachO::MH_BUNDLE:
3947 outs() << " BUNDLE";
3949 case MachO::MH_DSYM:
3952 case MachO::MH_KEXT_BUNDLE:
3953 outs() << " KEXTBUNDLE";
3956 outs() << format(" %10u", filetype);
3959 outs() << format(" %5u", ncmds);
3960 outs() << format(" %10u", sizeofcmds);
3962 if (f & MachO::MH_NOUNDEFS) {
3963 outs() << " NOUNDEFS";
3964 f &= ~MachO::MH_NOUNDEFS;
3966 if (f & MachO::MH_INCRLINK) {
3967 outs() << " INCRLINK";
3968 f &= ~MachO::MH_INCRLINK;
3970 if (f & MachO::MH_DYLDLINK) {
3971 outs() << " DYLDLINK";
3972 f &= ~MachO::MH_DYLDLINK;
3974 if (f & MachO::MH_BINDATLOAD) {
3975 outs() << " BINDATLOAD";
3976 f &= ~MachO::MH_BINDATLOAD;
3978 if (f & MachO::MH_PREBOUND) {
3979 outs() << " PREBOUND";
3980 f &= ~MachO::MH_PREBOUND;
3982 if (f & MachO::MH_SPLIT_SEGS) {
3983 outs() << " SPLIT_SEGS";
3984 f &= ~MachO::MH_SPLIT_SEGS;
3986 if (f & MachO::MH_LAZY_INIT) {
3987 outs() << " LAZY_INIT";
3988 f &= ~MachO::MH_LAZY_INIT;
3990 if (f & MachO::MH_TWOLEVEL) {
3991 outs() << " TWOLEVEL";
3992 f &= ~MachO::MH_TWOLEVEL;
3994 if (f & MachO::MH_FORCE_FLAT) {
3995 outs() << " FORCE_FLAT";
3996 f &= ~MachO::MH_FORCE_FLAT;
3998 if (f & MachO::MH_NOMULTIDEFS) {
3999 outs() << " NOMULTIDEFS";
4000 f &= ~MachO::MH_NOMULTIDEFS;
4002 if (f & MachO::MH_NOFIXPREBINDING) {
4003 outs() << " NOFIXPREBINDING";
4004 f &= ~MachO::MH_NOFIXPREBINDING;
4006 if (f & MachO::MH_PREBINDABLE) {
4007 outs() << " PREBINDABLE";
4008 f &= ~MachO::MH_PREBINDABLE;
4010 if (f & MachO::MH_ALLMODSBOUND) {
4011 outs() << " ALLMODSBOUND";
4012 f &= ~MachO::MH_ALLMODSBOUND;
4014 if (f & MachO::MH_SUBSECTIONS_VIA_SYMBOLS) {
4015 outs() << " SUBSECTIONS_VIA_SYMBOLS";
4016 f &= ~MachO::MH_SUBSECTIONS_VIA_SYMBOLS;
4018 if (f & MachO::MH_CANONICAL) {
4019 outs() << " CANONICAL";
4020 f &= ~MachO::MH_CANONICAL;
4022 if (f & MachO::MH_WEAK_DEFINES) {
4023 outs() << " WEAK_DEFINES";
4024 f &= ~MachO::MH_WEAK_DEFINES;
4026 if (f & MachO::MH_BINDS_TO_WEAK) {
4027 outs() << " BINDS_TO_WEAK";
4028 f &= ~MachO::MH_BINDS_TO_WEAK;
4030 if (f & MachO::MH_ALLOW_STACK_EXECUTION) {
4031 outs() << " ALLOW_STACK_EXECUTION";
4032 f &= ~MachO::MH_ALLOW_STACK_EXECUTION;
4034 if (f & MachO::MH_DEAD_STRIPPABLE_DYLIB) {
4035 outs() << " DEAD_STRIPPABLE_DYLIB";
4036 f &= ~MachO::MH_DEAD_STRIPPABLE_DYLIB;
4038 if (f & MachO::MH_PIE) {
4040 f &= ~MachO::MH_PIE;
4042 if (f & MachO::MH_NO_REEXPORTED_DYLIBS) {
4043 outs() << " NO_REEXPORTED_DYLIBS";
4044 f &= ~MachO::MH_NO_REEXPORTED_DYLIBS;
4046 if (f & MachO::MH_HAS_TLV_DESCRIPTORS) {
4047 outs() << " MH_HAS_TLV_DESCRIPTORS";
4048 f &= ~MachO::MH_HAS_TLV_DESCRIPTORS;
4050 if (f & MachO::MH_NO_HEAP_EXECUTION) {
4051 outs() << " MH_NO_HEAP_EXECUTION";
4052 f &= ~MachO::MH_NO_HEAP_EXECUTION;
4054 if (f & MachO::MH_APP_EXTENSION_SAFE) {
4055 outs() << " APP_EXTENSION_SAFE";
4056 f &= ~MachO::MH_APP_EXTENSION_SAFE;
4058 if (f != 0 || flags == 0)
4059 outs() << format(" 0x%08" PRIx32, f);
4061 outs() << format(" 0x%08" PRIx32, magic);
4062 outs() << format(" %7d", cputype);
4063 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
4064 outs() << format(" 0x%02" PRIx32,
4065 (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24);
4066 outs() << format(" %10u", filetype);
4067 outs() << format(" %5u", ncmds);
4068 outs() << format(" %10u", sizeofcmds);
4069 outs() << format(" 0x%08" PRIx32, flags);
4074 static void PrintSegmentCommand(uint32_t cmd, uint32_t cmdsize,
4075 StringRef SegName, uint64_t vmaddr,
4076 uint64_t vmsize, uint64_t fileoff,
4077 uint64_t filesize, uint32_t maxprot,
4078 uint32_t initprot, uint32_t nsects,
4079 uint32_t flags, uint32_t object_size,
4081 uint64_t expected_cmdsize;
4082 if (cmd == MachO::LC_SEGMENT) {
4083 outs() << " cmd LC_SEGMENT\n";
4084 expected_cmdsize = nsects;
4085 expected_cmdsize *= sizeof(struct MachO::section);
4086 expected_cmdsize += sizeof(struct MachO::segment_command);
4088 outs() << " cmd LC_SEGMENT_64\n";
4089 expected_cmdsize = nsects;
4090 expected_cmdsize *= sizeof(struct MachO::section_64);
4091 expected_cmdsize += sizeof(struct MachO::segment_command_64);
4093 outs() << " cmdsize " << cmdsize;
4094 if (cmdsize != expected_cmdsize)
4095 outs() << " Inconsistent size\n";
4098 outs() << " segname " << SegName << "\n";
4099 if (cmd == MachO::LC_SEGMENT_64) {
4100 outs() << " vmaddr " << format("0x%016" PRIx64, vmaddr) << "\n";
4101 outs() << " vmsize " << format("0x%016" PRIx64, vmsize) << "\n";
4103 outs() << " vmaddr " << format("0x%08" PRIx64, vmaddr) << "\n";
4104 outs() << " vmsize " << format("0x%08" PRIx64, vmsize) << "\n";
4106 outs() << " fileoff " << fileoff;
4107 if (fileoff > object_size)
4108 outs() << " (past end of file)\n";
4111 outs() << " filesize " << filesize;
4112 if (fileoff + filesize > object_size)
4113 outs() << " (past end of file)\n";
4118 ~(MachO::VM_PROT_READ | MachO::VM_PROT_WRITE |
4119 MachO::VM_PROT_EXECUTE)) != 0)
4120 outs() << " maxprot ?" << format("0x%08" PRIx32, maxprot) << "\n";
4122 if (maxprot & MachO::VM_PROT_READ)
4123 outs() << " maxprot r";
4125 outs() << " maxprot -";
4126 if (maxprot & MachO::VM_PROT_WRITE)
4130 if (maxprot & MachO::VM_PROT_EXECUTE)
4136 ~(MachO::VM_PROT_READ | MachO::VM_PROT_WRITE |
4137 MachO::VM_PROT_EXECUTE)) != 0)
4138 outs() << " initprot ?" << format("0x%08" PRIx32, initprot) << "\n";
4140 if (initprot & MachO::VM_PROT_READ)
4141 outs() << " initprot r";
4143 outs() << " initprot -";
4144 if (initprot & MachO::VM_PROT_WRITE)
4148 if (initprot & MachO::VM_PROT_EXECUTE)
4154 outs() << " maxprot " << format("0x%08" PRIx32, maxprot) << "\n";
4155 outs() << " initprot " << format("0x%08" PRIx32, initprot) << "\n";
4157 outs() << " nsects " << nsects << "\n";
4161 outs() << " (none)\n";
4163 if (flags & MachO::SG_HIGHVM) {
4164 outs() << " HIGHVM";
4165 flags &= ~MachO::SG_HIGHVM;
4167 if (flags & MachO::SG_FVMLIB) {
4168 outs() << " FVMLIB";
4169 flags &= ~MachO::SG_FVMLIB;
4171 if (flags & MachO::SG_NORELOC) {
4172 outs() << " NORELOC";
4173 flags &= ~MachO::SG_NORELOC;
4175 if (flags & MachO::SG_PROTECTED_VERSION_1) {
4176 outs() << " PROTECTED_VERSION_1";
4177 flags &= ~MachO::SG_PROTECTED_VERSION_1;
4180 outs() << format(" 0x%08" PRIx32, flags) << " (unknown flags)\n";
4185 outs() << " flags " << format("0x%" PRIx32, flags) << "\n";
4189 static void PrintSection(const char *sectname, const char *segname,
4190 uint64_t addr, uint64_t size, uint32_t offset,
4191 uint32_t align, uint32_t reloff, uint32_t nreloc,
4192 uint32_t flags, uint32_t reserved1, uint32_t reserved2,
4193 uint32_t cmd, const char *sg_segname,
4194 uint32_t filetype, uint32_t object_size,
4196 outs() << "Section\n";
4197 outs() << " sectname " << format("%.16s\n", sectname);
4198 outs() << " segname " << format("%.16s", segname);
4199 if (filetype != MachO::MH_OBJECT && strncmp(sg_segname, segname, 16) != 0)
4200 outs() << " (does not match segment)\n";
4203 if (cmd == MachO::LC_SEGMENT_64) {
4204 outs() << " addr " << format("0x%016" PRIx64, addr) << "\n";
4205 outs() << " size " << format("0x%016" PRIx64, size);
4207 outs() << " addr " << format("0x%08" PRIx64, addr) << "\n";
4208 outs() << " size " << format("0x%08" PRIx64, size);
4210 if ((flags & MachO::S_ZEROFILL) != 0 && offset + size > object_size)
4211 outs() << " (past end of file)\n";
4214 outs() << " offset " << offset;
4215 if (offset > object_size)
4216 outs() << " (past end of file)\n";
4219 uint32_t align_shifted = 1 << align;
4220 outs() << " align 2^" << align << " (" << align_shifted << ")\n";
4221 outs() << " reloff " << reloff;
4222 if (reloff > object_size)
4223 outs() << " (past end of file)\n";
4226 outs() << " nreloc " << nreloc;
4227 if (reloff + nreloc * sizeof(struct MachO::relocation_info) > object_size)
4228 outs() << " (past end of file)\n";
4231 uint32_t section_type = flags & MachO::SECTION_TYPE;
4234 if (section_type == MachO::S_REGULAR)
4235 outs() << " S_REGULAR\n";
4236 else if (section_type == MachO::S_ZEROFILL)
4237 outs() << " S_ZEROFILL\n";
4238 else if (section_type == MachO::S_CSTRING_LITERALS)
4239 outs() << " S_CSTRING_LITERALS\n";
4240 else if (section_type == MachO::S_4BYTE_LITERALS)
4241 outs() << " S_4BYTE_LITERALS\n";
4242 else if (section_type == MachO::S_8BYTE_LITERALS)
4243 outs() << " S_8BYTE_LITERALS\n";
4244 else if (section_type == MachO::S_16BYTE_LITERALS)
4245 outs() << " S_16BYTE_LITERALS\n";
4246 else if (section_type == MachO::S_LITERAL_POINTERS)
4247 outs() << " S_LITERAL_POINTERS\n";
4248 else if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS)
4249 outs() << " S_NON_LAZY_SYMBOL_POINTERS\n";
4250 else if (section_type == MachO::S_LAZY_SYMBOL_POINTERS)
4251 outs() << " S_LAZY_SYMBOL_POINTERS\n";
4252 else if (section_type == MachO::S_SYMBOL_STUBS)
4253 outs() << " S_SYMBOL_STUBS\n";
4254 else if (section_type == MachO::S_MOD_INIT_FUNC_POINTERS)
4255 outs() << " S_MOD_INIT_FUNC_POINTERS\n";
4256 else if (section_type == MachO::S_MOD_TERM_FUNC_POINTERS)
4257 outs() << " S_MOD_TERM_FUNC_POINTERS\n";
4258 else if (section_type == MachO::S_COALESCED)
4259 outs() << " S_COALESCED\n";
4260 else if (section_type == MachO::S_INTERPOSING)
4261 outs() << " S_INTERPOSING\n";
4262 else if (section_type == MachO::S_DTRACE_DOF)
4263 outs() << " S_DTRACE_DOF\n";
4264 else if (section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS)
4265 outs() << " S_LAZY_DYLIB_SYMBOL_POINTERS\n";
4266 else if (section_type == MachO::S_THREAD_LOCAL_REGULAR)
4267 outs() << " S_THREAD_LOCAL_REGULAR\n";
4268 else if (section_type == MachO::S_THREAD_LOCAL_ZEROFILL)
4269 outs() << " S_THREAD_LOCAL_ZEROFILL\n";
4270 else if (section_type == MachO::S_THREAD_LOCAL_VARIABLES)
4271 outs() << " S_THREAD_LOCAL_VARIABLES\n";
4272 else if (section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS)
4273 outs() << " S_THREAD_LOCAL_VARIABLE_POINTERS\n";
4274 else if (section_type == MachO::S_THREAD_LOCAL_INIT_FUNCTION_POINTERS)
4275 outs() << " S_THREAD_LOCAL_INIT_FUNCTION_POINTERS\n";
4277 outs() << format("0x%08" PRIx32, section_type) << "\n";
4278 outs() << "attributes";
4279 uint32_t section_attributes = flags & MachO::SECTION_ATTRIBUTES;
4280 if (section_attributes & MachO::S_ATTR_PURE_INSTRUCTIONS)
4281 outs() << " PURE_INSTRUCTIONS";
4282 if (section_attributes & MachO::S_ATTR_NO_TOC)
4283 outs() << " NO_TOC";
4284 if (section_attributes & MachO::S_ATTR_STRIP_STATIC_SYMS)
4285 outs() << " STRIP_STATIC_SYMS";
4286 if (section_attributes & MachO::S_ATTR_NO_DEAD_STRIP)
4287 outs() << " NO_DEAD_STRIP";
4288 if (section_attributes & MachO::S_ATTR_LIVE_SUPPORT)
4289 outs() << " LIVE_SUPPORT";
4290 if (section_attributes & MachO::S_ATTR_SELF_MODIFYING_CODE)
4291 outs() << " SELF_MODIFYING_CODE";
4292 if (section_attributes & MachO::S_ATTR_DEBUG)
4294 if (section_attributes & MachO::S_ATTR_SOME_INSTRUCTIONS)
4295 outs() << " SOME_INSTRUCTIONS";
4296 if (section_attributes & MachO::S_ATTR_EXT_RELOC)
4297 outs() << " EXT_RELOC";
4298 if (section_attributes & MachO::S_ATTR_LOC_RELOC)
4299 outs() << " LOC_RELOC";
4300 if (section_attributes == 0)
4301 outs() << " (none)";
4304 outs() << " flags " << format("0x%08" PRIx32, flags) << "\n";
4305 outs() << " reserved1 " << reserved1;
4306 if (section_type == MachO::S_SYMBOL_STUBS ||
4307 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
4308 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
4309 section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
4310 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS)
4311 outs() << " (index into indirect symbol table)\n";
4314 outs() << " reserved2 " << reserved2;
4315 if (section_type == MachO::S_SYMBOL_STUBS)
4316 outs() << " (size of stubs)\n";
4321 static void PrintSymtabLoadCommand(MachO::symtab_command st, bool Is64Bit,
4322 uint32_t object_size) {
4323 outs() << " cmd LC_SYMTAB\n";
4324 outs() << " cmdsize " << st.cmdsize;
4325 if (st.cmdsize != sizeof(struct MachO::symtab_command))
4326 outs() << " Incorrect size\n";
4329 outs() << " symoff " << st.symoff;
4330 if (st.symoff > object_size)
4331 outs() << " (past end of file)\n";
4334 outs() << " nsyms " << st.nsyms;
4337 big_size = st.nsyms;
4338 big_size *= sizeof(struct MachO::nlist_64);
4339 big_size += st.symoff;
4340 if (big_size > object_size)
4341 outs() << " (past end of file)\n";
4345 big_size = st.nsyms;
4346 big_size *= sizeof(struct MachO::nlist);
4347 big_size += st.symoff;
4348 if (big_size > object_size)
4349 outs() << " (past end of file)\n";
4353 outs() << " stroff " << st.stroff;
4354 if (st.stroff > object_size)
4355 outs() << " (past end of file)\n";
4358 outs() << " strsize " << st.strsize;
4359 big_size = st.stroff;
4360 big_size += st.strsize;
4361 if (big_size > object_size)
4362 outs() << " (past end of file)\n";
4367 static void PrintDysymtabLoadCommand(MachO::dysymtab_command dyst,
4368 uint32_t nsyms, uint32_t object_size,
4370 outs() << " cmd LC_DYSYMTAB\n";
4371 outs() << " cmdsize " << dyst.cmdsize;
4372 if (dyst.cmdsize != sizeof(struct MachO::dysymtab_command))
4373 outs() << " Incorrect size\n";
4376 outs() << " ilocalsym " << dyst.ilocalsym;
4377 if (dyst.ilocalsym > nsyms)
4378 outs() << " (greater than the number of symbols)\n";
4381 outs() << " nlocalsym " << dyst.nlocalsym;
4383 big_size = dyst.ilocalsym;
4384 big_size += dyst.nlocalsym;
4385 if (big_size > nsyms)
4386 outs() << " (past the end of the symbol table)\n";
4389 outs() << " iextdefsym " << dyst.iextdefsym;
4390 if (dyst.iextdefsym > nsyms)
4391 outs() << " (greater than the number of symbols)\n";
4394 outs() << " nextdefsym " << dyst.nextdefsym;
4395 big_size = dyst.iextdefsym;
4396 big_size += dyst.nextdefsym;
4397 if (big_size > nsyms)
4398 outs() << " (past the end of the symbol table)\n";
4401 outs() << " iundefsym " << dyst.iundefsym;
4402 if (dyst.iundefsym > nsyms)
4403 outs() << " (greater than the number of symbols)\n";
4406 outs() << " nundefsym " << dyst.nundefsym;
4407 big_size = dyst.iundefsym;
4408 big_size += dyst.nundefsym;
4409 if (big_size > nsyms)
4410 outs() << " (past the end of the symbol table)\n";
4413 outs() << " tocoff " << dyst.tocoff;
4414 if (dyst.tocoff > object_size)
4415 outs() << " (past end of file)\n";
4418 outs() << " ntoc " << dyst.ntoc;
4419 big_size = dyst.ntoc;
4420 big_size *= sizeof(struct MachO::dylib_table_of_contents);
4421 big_size += dyst.tocoff;
4422 if (big_size > object_size)
4423 outs() << " (past end of file)\n";
4426 outs() << " modtaboff " << dyst.modtaboff;
4427 if (dyst.modtaboff > object_size)
4428 outs() << " (past end of file)\n";
4431 outs() << " nmodtab " << dyst.nmodtab;
4434 modtabend = dyst.nmodtab;
4435 modtabend *= sizeof(struct MachO::dylib_module_64);
4436 modtabend += dyst.modtaboff;
4438 modtabend = dyst.nmodtab;
4439 modtabend *= sizeof(struct MachO::dylib_module);
4440 modtabend += dyst.modtaboff;
4442 if (modtabend > object_size)
4443 outs() << " (past end of file)\n";
4446 outs() << " extrefsymoff " << dyst.extrefsymoff;
4447 if (dyst.extrefsymoff > object_size)
4448 outs() << " (past end of file)\n";
4451 outs() << " nextrefsyms " << dyst.nextrefsyms;
4452 big_size = dyst.nextrefsyms;
4453 big_size *= sizeof(struct MachO::dylib_reference);
4454 big_size += dyst.extrefsymoff;
4455 if (big_size > object_size)
4456 outs() << " (past end of file)\n";
4459 outs() << " indirectsymoff " << dyst.indirectsymoff;
4460 if (dyst.indirectsymoff > object_size)
4461 outs() << " (past end of file)\n";
4464 outs() << " nindirectsyms " << dyst.nindirectsyms;
4465 big_size = dyst.nindirectsyms;
4466 big_size *= sizeof(uint32_t);
4467 big_size += dyst.indirectsymoff;
4468 if (big_size > object_size)
4469 outs() << " (past end of file)\n";
4472 outs() << " extreloff " << dyst.extreloff;
4473 if (dyst.extreloff > object_size)
4474 outs() << " (past end of file)\n";
4477 outs() << " nextrel " << dyst.nextrel;
4478 big_size = dyst.nextrel;
4479 big_size *= sizeof(struct MachO::relocation_info);
4480 big_size += dyst.extreloff;
4481 if (big_size > object_size)
4482 outs() << " (past end of file)\n";
4485 outs() << " locreloff " << dyst.locreloff;
4486 if (dyst.locreloff > object_size)
4487 outs() << " (past end of file)\n";
4490 outs() << " nlocrel " << dyst.nlocrel;
4491 big_size = dyst.nlocrel;
4492 big_size *= sizeof(struct MachO::relocation_info);
4493 big_size += dyst.locreloff;
4494 if (big_size > object_size)
4495 outs() << " (past end of file)\n";
4500 static void PrintDyldInfoLoadCommand(MachO::dyld_info_command dc,
4501 uint32_t object_size) {
4502 if (dc.cmd == MachO::LC_DYLD_INFO)
4503 outs() << " cmd LC_DYLD_INFO\n";
4505 outs() << " cmd LC_DYLD_INFO_ONLY\n";
4506 outs() << " cmdsize " << dc.cmdsize;
4507 if (dc.cmdsize != sizeof(struct MachO::dyld_info_command))
4508 outs() << " Incorrect size\n";
4511 outs() << " rebase_off " << dc.rebase_off;
4512 if (dc.rebase_off > object_size)
4513 outs() << " (past end of file)\n";
4516 outs() << " rebase_size " << dc.rebase_size;
4518 big_size = dc.rebase_off;
4519 big_size += dc.rebase_size;
4520 if (big_size > object_size)
4521 outs() << " (past end of file)\n";
4524 outs() << " bind_off " << dc.bind_off;
4525 if (dc.bind_off > object_size)
4526 outs() << " (past end of file)\n";
4529 outs() << " bind_size " << dc.bind_size;
4530 big_size = dc.bind_off;
4531 big_size += dc.bind_size;
4532 if (big_size > object_size)
4533 outs() << " (past end of file)\n";
4536 outs() << " weak_bind_off " << dc.weak_bind_off;
4537 if (dc.weak_bind_off > object_size)
4538 outs() << " (past end of file)\n";
4541 outs() << " weak_bind_size " << dc.weak_bind_size;
4542 big_size = dc.weak_bind_off;
4543 big_size += dc.weak_bind_size;
4544 if (big_size > object_size)
4545 outs() << " (past end of file)\n";
4548 outs() << " lazy_bind_off " << dc.lazy_bind_off;
4549 if (dc.lazy_bind_off > object_size)
4550 outs() << " (past end of file)\n";
4553 outs() << " lazy_bind_size " << dc.lazy_bind_size;
4554 big_size = dc.lazy_bind_off;
4555 big_size += dc.lazy_bind_size;
4556 if (big_size > object_size)
4557 outs() << " (past end of file)\n";
4560 outs() << " export_off " << dc.export_off;
4561 if (dc.export_off > object_size)
4562 outs() << " (past end of file)\n";
4565 outs() << " export_size " << dc.export_size;
4566 big_size = dc.export_off;
4567 big_size += dc.export_size;
4568 if (big_size > object_size)
4569 outs() << " (past end of file)\n";
4574 static void PrintDyldLoadCommand(MachO::dylinker_command dyld,
4576 if (dyld.cmd == MachO::LC_ID_DYLINKER)
4577 outs() << " cmd LC_ID_DYLINKER\n";
4578 else if (dyld.cmd == MachO::LC_LOAD_DYLINKER)
4579 outs() << " cmd LC_LOAD_DYLINKER\n";
4580 else if (dyld.cmd == MachO::LC_DYLD_ENVIRONMENT)
4581 outs() << " cmd LC_DYLD_ENVIRONMENT\n";
4583 outs() << " cmd ?(" << dyld.cmd << ")\n";
4584 outs() << " cmdsize " << dyld.cmdsize;
4585 if (dyld.cmdsize < sizeof(struct MachO::dylinker_command))
4586 outs() << " Incorrect size\n";
4589 if (dyld.name >= dyld.cmdsize)
4590 outs() << " name ?(bad offset " << dyld.name << ")\n";
4592 const char *P = (const char *)(Ptr) + dyld.name;
4593 outs() << " name " << P << " (offset " << dyld.name << ")\n";
4597 static void PrintUuidLoadCommand(MachO::uuid_command uuid) {
4598 outs() << " cmd LC_UUID\n";
4599 outs() << " cmdsize " << uuid.cmdsize;
4600 if (uuid.cmdsize != sizeof(struct MachO::uuid_command))
4601 outs() << " Incorrect size\n";
4605 outs() << format("%02" PRIX32, uuid.uuid[0]);
4606 outs() << format("%02" PRIX32, uuid.uuid[1]);
4607 outs() << format("%02" PRIX32, uuid.uuid[2]);
4608 outs() << format("%02" PRIX32, uuid.uuid[3]);
4610 outs() << format("%02" PRIX32, uuid.uuid[4]);
4611 outs() << format("%02" PRIX32, uuid.uuid[5]);
4613 outs() << format("%02" PRIX32, uuid.uuid[6]);
4614 outs() << format("%02" PRIX32, uuid.uuid[7]);
4616 outs() << format("%02" PRIX32, uuid.uuid[8]);
4617 outs() << format("%02" PRIX32, uuid.uuid[9]);
4619 outs() << format("%02" PRIX32, uuid.uuid[10]);
4620 outs() << format("%02" PRIX32, uuid.uuid[11]);
4621 outs() << format("%02" PRIX32, uuid.uuid[12]);
4622 outs() << format("%02" PRIX32, uuid.uuid[13]);
4623 outs() << format("%02" PRIX32, uuid.uuid[14]);
4624 outs() << format("%02" PRIX32, uuid.uuid[15]);
4628 static void PrintRpathLoadCommand(MachO::rpath_command rpath, const char *Ptr) {
4629 outs() << " cmd LC_RPATH\n";
4630 outs() << " cmdsize " << rpath.cmdsize;
4631 if (rpath.cmdsize < sizeof(struct MachO::rpath_command))
4632 outs() << " Incorrect size\n";
4635 if (rpath.path >= rpath.cmdsize)
4636 outs() << " path ?(bad offset " << rpath.path << ")\n";
4638 const char *P = (const char *)(Ptr) + rpath.path;
4639 outs() << " path " << P << " (offset " << rpath.path << ")\n";
4643 static void PrintVersionMinLoadCommand(MachO::version_min_command vd) {
4644 if (vd.cmd == MachO::LC_VERSION_MIN_MACOSX)
4645 outs() << " cmd LC_VERSION_MIN_MACOSX\n";
4646 else if (vd.cmd == MachO::LC_VERSION_MIN_IPHONEOS)
4647 outs() << " cmd LC_VERSION_MIN_IPHONEOS\n";
4649 outs() << " cmd " << vd.cmd << " (?)\n";
4650 outs() << " cmdsize " << vd.cmdsize;
4651 if (vd.cmdsize != sizeof(struct MachO::version_min_command))
4652 outs() << " Incorrect size\n";
4655 outs() << " version " << ((vd.version >> 16) & 0xffff) << "."
4656 << ((vd.version >> 8) & 0xff);
4657 if ((vd.version & 0xff) != 0)
4658 outs() << "." << (vd.version & 0xff);
4661 outs() << " sdk n/a";
4663 outs() << " sdk " << ((vd.sdk >> 16) & 0xffff) << "."
4664 << ((vd.sdk >> 8) & 0xff);
4666 if ((vd.sdk & 0xff) != 0)
4667 outs() << "." << (vd.sdk & 0xff);
4671 static void PrintSourceVersionCommand(MachO::source_version_command sd) {
4672 outs() << " cmd LC_SOURCE_VERSION\n";
4673 outs() << " cmdsize " << sd.cmdsize;
4674 if (sd.cmdsize != sizeof(struct MachO::source_version_command))
4675 outs() << " Incorrect size\n";
4678 uint64_t a = (sd.version >> 40) & 0xffffff;
4679 uint64_t b = (sd.version >> 30) & 0x3ff;
4680 uint64_t c = (sd.version >> 20) & 0x3ff;
4681 uint64_t d = (sd.version >> 10) & 0x3ff;
4682 uint64_t e = sd.version & 0x3ff;
4683 outs() << " version " << a << "." << b;
4685 outs() << "." << c << "." << d << "." << e;
4687 outs() << "." << c << "." << d;
4693 static void PrintEntryPointCommand(MachO::entry_point_command ep) {
4694 outs() << " cmd LC_MAIN\n";
4695 outs() << " cmdsize " << ep.cmdsize;
4696 if (ep.cmdsize != sizeof(struct MachO::entry_point_command))
4697 outs() << " Incorrect size\n";
4700 outs() << " entryoff " << ep.entryoff << "\n";
4701 outs() << " stacksize " << ep.stacksize << "\n";
4704 static void PrintEncryptionInfoCommand(MachO::encryption_info_command ec,
4705 uint32_t object_size) {
4706 outs() << " cmd LC_ENCRYPTION_INFO\n";
4707 outs() << " cmdsize " << ec.cmdsize;
4708 if (ec.cmdsize != sizeof(struct MachO::encryption_info_command))
4709 outs() << " Incorrect size\n";
4712 outs() << " cryptoff " << ec.cryptoff;
4713 if (ec.cryptoff > object_size)
4714 outs() << " (past end of file)\n";
4717 outs() << " cryptsize " << ec.cryptsize;
4718 if (ec.cryptsize > object_size)
4719 outs() << " (past end of file)\n";
4722 outs() << " cryptid " << ec.cryptid << "\n";
4725 static void PrintEncryptionInfoCommand64(MachO::encryption_info_command_64 ec,
4726 uint32_t object_size) {
4727 outs() << " cmd LC_ENCRYPTION_INFO_64\n";
4728 outs() << " cmdsize " << ec.cmdsize;
4729 if (ec.cmdsize != sizeof(struct MachO::encryption_info_command_64))
4730 outs() << " Incorrect size\n";
4733 outs() << " cryptoff " << ec.cryptoff;
4734 if (ec.cryptoff > object_size)
4735 outs() << " (past end of file)\n";
4738 outs() << " cryptsize " << ec.cryptsize;
4739 if (ec.cryptsize > object_size)
4740 outs() << " (past end of file)\n";
4743 outs() << " cryptid " << ec.cryptid << "\n";
4744 outs() << " pad " << ec.pad << "\n";
4747 static void PrintLinkerOptionCommand(MachO::linker_option_command lo,
4749 outs() << " cmd LC_LINKER_OPTION\n";
4750 outs() << " cmdsize " << lo.cmdsize;
4751 if (lo.cmdsize < sizeof(struct MachO::linker_option_command))
4752 outs() << " Incorrect size\n";
4755 outs() << " count " << lo.count << "\n";
4756 const char *string = Ptr + sizeof(struct MachO::linker_option_command);
4757 uint32_t left = lo.cmdsize - sizeof(struct MachO::linker_option_command);
4760 while (*string == '\0' && left > 0) {
4766 outs() << " string #" << i << " " << format("%.*s\n", left, string);
4767 uint32_t NullPos = StringRef(string, left).find('\0');
4768 uint32_t len = std::min(NullPos, left) + 1;
4774 outs() << " count " << lo.count << " does not match number of strings "
4778 static void PrintSubFrameworkCommand(MachO::sub_framework_command sub,
4780 outs() << " cmd LC_SUB_FRAMEWORK\n";
4781 outs() << " cmdsize " << sub.cmdsize;
4782 if (sub.cmdsize < sizeof(struct MachO::sub_framework_command))
4783 outs() << " Incorrect size\n";
4786 if (sub.umbrella < sub.cmdsize) {
4787 const char *P = Ptr + sub.umbrella;
4788 outs() << " umbrella " << P << " (offset " << sub.umbrella << ")\n";
4790 outs() << " umbrella ?(bad offset " << sub.umbrella << ")\n";
4794 static void PrintSubUmbrellaCommand(MachO::sub_umbrella_command sub,
4796 outs() << " cmd LC_SUB_UMBRELLA\n";
4797 outs() << " cmdsize " << sub.cmdsize;
4798 if (sub.cmdsize < sizeof(struct MachO::sub_umbrella_command))
4799 outs() << " Incorrect size\n";
4802 if (sub.sub_umbrella < sub.cmdsize) {
4803 const char *P = Ptr + sub.sub_umbrella;
4804 outs() << " sub_umbrella " << P << " (offset " << sub.sub_umbrella << ")\n";
4806 outs() << " sub_umbrella ?(bad offset " << sub.sub_umbrella << ")\n";
4810 static void PrintSubLibraryCommand(MachO::sub_library_command sub,
4812 outs() << " cmd LC_SUB_LIBRARY\n";
4813 outs() << " cmdsize " << sub.cmdsize;
4814 if (sub.cmdsize < sizeof(struct MachO::sub_library_command))
4815 outs() << " Incorrect size\n";
4818 if (sub.sub_library < sub.cmdsize) {
4819 const char *P = Ptr + sub.sub_library;
4820 outs() << " sub_library " << P << " (offset " << sub.sub_library << ")\n";
4822 outs() << " sub_library ?(bad offset " << sub.sub_library << ")\n";
4826 static void PrintSubClientCommand(MachO::sub_client_command sub,
4828 outs() << " cmd LC_SUB_CLIENT\n";
4829 outs() << " cmdsize " << sub.cmdsize;
4830 if (sub.cmdsize < sizeof(struct MachO::sub_client_command))
4831 outs() << " Incorrect size\n";
4834 if (sub.client < sub.cmdsize) {
4835 const char *P = Ptr + sub.client;
4836 outs() << " client " << P << " (offset " << sub.client << ")\n";
4838 outs() << " client ?(bad offset " << sub.client << ")\n";
4842 static void PrintRoutinesCommand(MachO::routines_command r) {
4843 outs() << " cmd LC_ROUTINES\n";
4844 outs() << " cmdsize " << r.cmdsize;
4845 if (r.cmdsize != sizeof(struct MachO::routines_command))
4846 outs() << " Incorrect size\n";
4849 outs() << " init_address " << format("0x%08" PRIx32, r.init_address) << "\n";
4850 outs() << " init_module " << r.init_module << "\n";
4851 outs() << " reserved1 " << r.reserved1 << "\n";
4852 outs() << " reserved2 " << r.reserved2 << "\n";
4853 outs() << " reserved3 " << r.reserved3 << "\n";
4854 outs() << " reserved4 " << r.reserved4 << "\n";
4855 outs() << " reserved5 " << r.reserved5 << "\n";
4856 outs() << " reserved6 " << r.reserved6 << "\n";
4859 static void PrintRoutinesCommand64(MachO::routines_command_64 r) {
4860 outs() << " cmd LC_ROUTINES_64\n";
4861 outs() << " cmdsize " << r.cmdsize;
4862 if (r.cmdsize != sizeof(struct MachO::routines_command_64))
4863 outs() << " Incorrect size\n";
4866 outs() << " init_address " << format("0x%016" PRIx64, r.init_address) << "\n";
4867 outs() << " init_module " << r.init_module << "\n";
4868 outs() << " reserved1 " << r.reserved1 << "\n";
4869 outs() << " reserved2 " << r.reserved2 << "\n";
4870 outs() << " reserved3 " << r.reserved3 << "\n";
4871 outs() << " reserved4 " << r.reserved4 << "\n";
4872 outs() << " reserved5 " << r.reserved5 << "\n";
4873 outs() << " reserved6 " << r.reserved6 << "\n";
4876 static void Print_x86_thread_state64_t(MachO::x86_thread_state64_t &cpu64) {
4877 outs() << " rax " << format("0x%016" PRIx64, cpu64.rax);
4878 outs() << " rbx " << format("0x%016" PRIx64, cpu64.rbx);
4879 outs() << " rcx " << format("0x%016" PRIx64, cpu64.rcx) << "\n";
4880 outs() << " rdx " << format("0x%016" PRIx64, cpu64.rdx);
4881 outs() << " rdi " << format("0x%016" PRIx64, cpu64.rdi);
4882 outs() << " rsi " << format("0x%016" PRIx64, cpu64.rsi) << "\n";
4883 outs() << " rbp " << format("0x%016" PRIx64, cpu64.rbp);
4884 outs() << " rsp " << format("0x%016" PRIx64, cpu64.rsp);
4885 outs() << " r8 " << format("0x%016" PRIx64, cpu64.r8) << "\n";
4886 outs() << " r9 " << format("0x%016" PRIx64, cpu64.r9);
4887 outs() << " r10 " << format("0x%016" PRIx64, cpu64.r10);
4888 outs() << " r11 " << format("0x%016" PRIx64, cpu64.r11) << "\n";
4889 outs() << " r12 " << format("0x%016" PRIx64, cpu64.r12);
4890 outs() << " r13 " << format("0x%016" PRIx64, cpu64.r13);
4891 outs() << " r14 " << format("0x%016" PRIx64, cpu64.r14) << "\n";
4892 outs() << " r15 " << format("0x%016" PRIx64, cpu64.r15);
4893 outs() << " rip " << format("0x%016" PRIx64, cpu64.rip) << "\n";
4894 outs() << "rflags " << format("0x%016" PRIx64, cpu64.rflags);
4895 outs() << " cs " << format("0x%016" PRIx64, cpu64.cs);
4896 outs() << " fs " << format("0x%016" PRIx64, cpu64.fs) << "\n";
4897 outs() << " gs " << format("0x%016" PRIx64, cpu64.gs) << "\n";
4900 static void Print_mmst_reg(MachO::mmst_reg_t &r) {
4902 outs() << "\t mmst_reg ";
4903 for (f = 0; f < 10; f++)
4904 outs() << format("%02" PRIx32, (r.mmst_reg[f] & 0xff)) << " ";
4906 outs() << "\t mmst_rsrv ";
4907 for (f = 0; f < 6; f++)
4908 outs() << format("%02" PRIx32, (r.mmst_rsrv[f] & 0xff)) << " ";
4912 static void Print_xmm_reg(MachO::xmm_reg_t &r) {
4914 outs() << "\t xmm_reg ";
4915 for (f = 0; f < 16; f++)
4916 outs() << format("%02" PRIx32, (r.xmm_reg[f] & 0xff)) << " ";
4920 static void Print_x86_float_state_t(MachO::x86_float_state64_t &fpu) {
4921 outs() << "\t fpu_reserved[0] " << fpu.fpu_reserved[0];
4922 outs() << " fpu_reserved[1] " << fpu.fpu_reserved[1] << "\n";
4923 outs() << "\t control: invalid " << fpu.fpu_fcw.invalid;
4924 outs() << " denorm " << fpu.fpu_fcw.denorm;
4925 outs() << " zdiv " << fpu.fpu_fcw.zdiv;
4926 outs() << " ovrfl " << fpu.fpu_fcw.ovrfl;
4927 outs() << " undfl " << fpu.fpu_fcw.undfl;
4928 outs() << " precis " << fpu.fpu_fcw.precis << "\n";
4929 outs() << "\t\t pc ";
4930 if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_24B)
4931 outs() << "FP_PREC_24B ";
4932 else if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_53B)
4933 outs() << "FP_PREC_53B ";
4934 else if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_64B)
4935 outs() << "FP_PREC_64B ";
4937 outs() << fpu.fpu_fcw.pc << " ";
4939 if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_NEAR)
4940 outs() << "FP_RND_NEAR ";
4941 else if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_DOWN)
4942 outs() << "FP_RND_DOWN ";
4943 else if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_UP)
4944 outs() << "FP_RND_UP ";
4945 else if (fpu.fpu_fcw.rc == MachO::x86_FP_CHOP)
4946 outs() << "FP_CHOP ";
4948 outs() << "\t status: invalid " << fpu.fpu_fsw.invalid;
4949 outs() << " denorm " << fpu.fpu_fsw.denorm;
4950 outs() << " zdiv " << fpu.fpu_fsw.zdiv;
4951 outs() << " ovrfl " << fpu.fpu_fsw.ovrfl;
4952 outs() << " undfl " << fpu.fpu_fsw.undfl;
4953 outs() << " precis " << fpu.fpu_fsw.precis;
4954 outs() << " stkflt " << fpu.fpu_fsw.stkflt << "\n";
4955 outs() << "\t errsumm " << fpu.fpu_fsw.errsumm;
4956 outs() << " c0 " << fpu.fpu_fsw.c0;
4957 outs() << " c1 " << fpu.fpu_fsw.c1;
4958 outs() << " c2 " << fpu.fpu_fsw.c2;
4959 outs() << " tos " << fpu.fpu_fsw.tos;
4960 outs() << " c3 " << fpu.fpu_fsw.c3;
4961 outs() << " busy " << fpu.fpu_fsw.busy << "\n";
4962 outs() << "\t fpu_ftw " << format("0x%02" PRIx32, fpu.fpu_ftw);
4963 outs() << " fpu_rsrv1 " << format("0x%02" PRIx32, fpu.fpu_rsrv1);
4964 outs() << " fpu_fop " << format("0x%04" PRIx32, fpu.fpu_fop);
4965 outs() << " fpu_ip " << format("0x%08" PRIx32, fpu.fpu_ip) << "\n";
4966 outs() << "\t fpu_cs " << format("0x%04" PRIx32, fpu.fpu_cs);
4967 outs() << " fpu_rsrv2 " << format("0x%04" PRIx32, fpu.fpu_rsrv2);
4968 outs() << " fpu_dp " << format("0x%08" PRIx32, fpu.fpu_dp);
4969 outs() << " fpu_ds " << format("0x%04" PRIx32, fpu.fpu_ds) << "\n";
4970 outs() << "\t fpu_rsrv3 " << format("0x%04" PRIx32, fpu.fpu_rsrv3);
4971 outs() << " fpu_mxcsr " << format("0x%08" PRIx32, fpu.fpu_mxcsr);
4972 outs() << " fpu_mxcsrmask " << format("0x%08" PRIx32, fpu.fpu_mxcsrmask);
4974 outs() << "\t fpu_stmm0:\n";
4975 Print_mmst_reg(fpu.fpu_stmm0);
4976 outs() << "\t fpu_stmm1:\n";
4977 Print_mmst_reg(fpu.fpu_stmm1);
4978 outs() << "\t fpu_stmm2:\n";
4979 Print_mmst_reg(fpu.fpu_stmm2);
4980 outs() << "\t fpu_stmm3:\n";
4981 Print_mmst_reg(fpu.fpu_stmm3);
4982 outs() << "\t fpu_stmm4:\n";
4983 Print_mmst_reg(fpu.fpu_stmm4);
4984 outs() << "\t fpu_stmm5:\n";
4985 Print_mmst_reg(fpu.fpu_stmm5);
4986 outs() << "\t fpu_stmm6:\n";
4987 Print_mmst_reg(fpu.fpu_stmm6);
4988 outs() << "\t fpu_stmm7:\n";
4989 Print_mmst_reg(fpu.fpu_stmm7);
4990 outs() << "\t fpu_xmm0:\n";
4991 Print_xmm_reg(fpu.fpu_xmm0);
4992 outs() << "\t fpu_xmm1:\n";
4993 Print_xmm_reg(fpu.fpu_xmm1);
4994 outs() << "\t fpu_xmm2:\n";
4995 Print_xmm_reg(fpu.fpu_xmm2);
4996 outs() << "\t fpu_xmm3:\n";
4997 Print_xmm_reg(fpu.fpu_xmm3);
4998 outs() << "\t fpu_xmm4:\n";
4999 Print_xmm_reg(fpu.fpu_xmm4);
5000 outs() << "\t fpu_xmm5:\n";
5001 Print_xmm_reg(fpu.fpu_xmm5);
5002 outs() << "\t fpu_xmm6:\n";
5003 Print_xmm_reg(fpu.fpu_xmm6);
5004 outs() << "\t fpu_xmm7:\n";
5005 Print_xmm_reg(fpu.fpu_xmm7);
5006 outs() << "\t fpu_xmm8:\n";
5007 Print_xmm_reg(fpu.fpu_xmm8);
5008 outs() << "\t fpu_xmm9:\n";
5009 Print_xmm_reg(fpu.fpu_xmm9);
5010 outs() << "\t fpu_xmm10:\n";
5011 Print_xmm_reg(fpu.fpu_xmm10);
5012 outs() << "\t fpu_xmm11:\n";
5013 Print_xmm_reg(fpu.fpu_xmm11);
5014 outs() << "\t fpu_xmm12:\n";
5015 Print_xmm_reg(fpu.fpu_xmm12);
5016 outs() << "\t fpu_xmm13:\n";
5017 Print_xmm_reg(fpu.fpu_xmm13);
5018 outs() << "\t fpu_xmm14:\n";
5019 Print_xmm_reg(fpu.fpu_xmm14);
5020 outs() << "\t fpu_xmm15:\n";
5021 Print_xmm_reg(fpu.fpu_xmm15);
5022 outs() << "\t fpu_rsrv4:\n";
5023 for (uint32_t f = 0; f < 6; f++) {
5025 for (uint32_t g = 0; g < 16; g++)
5026 outs() << format("%02" PRIx32, fpu.fpu_rsrv4[f * g]) << " ";
5029 outs() << "\t fpu_reserved1 " << format("0x%08" PRIx32, fpu.fpu_reserved1);
5033 static void Print_x86_exception_state_t(MachO::x86_exception_state64_t &exc64) {
5034 outs() << "\t trapno " << format("0x%08" PRIx32, exc64.trapno);
5035 outs() << " err " << format("0x%08" PRIx32, exc64.err);
5036 outs() << " faultvaddr " << format("0x%016" PRIx64, exc64.faultvaddr) << "\n";
5039 static void PrintThreadCommand(MachO::thread_command t, const char *Ptr,
5040 bool isLittleEndian, uint32_t cputype) {
5041 if (t.cmd == MachO::LC_THREAD)
5042 outs() << " cmd LC_THREAD\n";
5043 else if (t.cmd == MachO::LC_UNIXTHREAD)
5044 outs() << " cmd LC_UNIXTHREAD\n";
5046 outs() << " cmd " << t.cmd << " (unknown)\n";
5047 outs() << " cmdsize " << t.cmdsize;
5048 if (t.cmdsize < sizeof(struct MachO::thread_command) + 2 * sizeof(uint32_t))
5049 outs() << " Incorrect size\n";
5053 const char *begin = Ptr + sizeof(struct MachO::thread_command);
5054 const char *end = Ptr + t.cmdsize;
5055 uint32_t flavor, count, left;
5056 if (cputype == MachO::CPU_TYPE_X86_64) {
5057 while (begin < end) {
5058 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
5059 memcpy((char *)&flavor, begin, sizeof(uint32_t));
5060 begin += sizeof(uint32_t);
5065 if (isLittleEndian != sys::IsLittleEndianHost)
5066 sys::swapByteOrder(flavor);
5067 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
5068 memcpy((char *)&count, begin, sizeof(uint32_t));
5069 begin += sizeof(uint32_t);
5074 if (isLittleEndian != sys::IsLittleEndianHost)
5075 sys::swapByteOrder(count);
5076 if (flavor == MachO::x86_THREAD_STATE64) {
5077 outs() << " flavor x86_THREAD_STATE64\n";
5078 if (count == MachO::x86_THREAD_STATE64_COUNT)
5079 outs() << " count x86_THREAD_STATE64_COUNT\n";
5081 outs() << " count " << count
5082 << " (not x86_THREAD_STATE64_COUNT)\n";
5083 MachO::x86_thread_state64_t cpu64;
5085 if (left >= sizeof(MachO::x86_thread_state64_t)) {
5086 memcpy(&cpu64, begin, sizeof(MachO::x86_thread_state64_t));
5087 begin += sizeof(MachO::x86_thread_state64_t);
5089 memset(&cpu64, '\0', sizeof(MachO::x86_thread_state64_t));
5090 memcpy(&cpu64, begin, left);
5093 if (isLittleEndian != sys::IsLittleEndianHost)
5095 Print_x86_thread_state64_t(cpu64);
5096 } else if (flavor == MachO::x86_THREAD_STATE) {
5097 outs() << " flavor x86_THREAD_STATE\n";
5098 if (count == MachO::x86_THREAD_STATE_COUNT)
5099 outs() << " count x86_THREAD_STATE_COUNT\n";
5101 outs() << " count " << count
5102 << " (not x86_THREAD_STATE_COUNT)\n";
5103 struct MachO::x86_thread_state_t ts;
5105 if (left >= sizeof(MachO::x86_thread_state_t)) {
5106 memcpy(&ts, begin, sizeof(MachO::x86_thread_state_t));
5107 begin += sizeof(MachO::x86_thread_state_t);
5109 memset(&ts, '\0', sizeof(MachO::x86_thread_state_t));
5110 memcpy(&ts, begin, left);
5113 if (isLittleEndian != sys::IsLittleEndianHost)
5115 if (ts.tsh.flavor == MachO::x86_THREAD_STATE64) {
5116 outs() << "\t tsh.flavor x86_THREAD_STATE64 ";
5117 if (ts.tsh.count == MachO::x86_THREAD_STATE64_COUNT)
5118 outs() << "tsh.count x86_THREAD_STATE64_COUNT\n";
5120 outs() << "tsh.count " << ts.tsh.count
5121 << " (not x86_THREAD_STATE64_COUNT\n";
5122 Print_x86_thread_state64_t(ts.uts.ts64);
5124 outs() << "\t tsh.flavor " << ts.tsh.flavor << " tsh.count "
5125 << ts.tsh.count << "\n";
5127 } else if (flavor == MachO::x86_FLOAT_STATE) {
5128 outs() << " flavor x86_FLOAT_STATE\n";
5129 if (count == MachO::x86_FLOAT_STATE_COUNT)
5130 outs() << " count x86_FLOAT_STATE_COUNT\n";
5132 outs() << " count " << count << " (not x86_FLOAT_STATE_COUNT)\n";
5133 struct MachO::x86_float_state_t fs;
5135 if (left >= sizeof(MachO::x86_float_state_t)) {
5136 memcpy(&fs, begin, sizeof(MachO::x86_float_state_t));
5137 begin += sizeof(MachO::x86_float_state_t);
5139 memset(&fs, '\0', sizeof(MachO::x86_float_state_t));
5140 memcpy(&fs, begin, left);
5143 if (isLittleEndian != sys::IsLittleEndianHost)
5145 if (fs.fsh.flavor == MachO::x86_FLOAT_STATE64) {
5146 outs() << "\t fsh.flavor x86_FLOAT_STATE64 ";
5147 if (fs.fsh.count == MachO::x86_FLOAT_STATE64_COUNT)
5148 outs() << "fsh.count x86_FLOAT_STATE64_COUNT\n";
5150 outs() << "fsh.count " << fs.fsh.count
5151 << " (not x86_FLOAT_STATE64_COUNT\n";
5152 Print_x86_float_state_t(fs.ufs.fs64);
5154 outs() << "\t fsh.flavor " << fs.fsh.flavor << " fsh.count "
5155 << fs.fsh.count << "\n";
5157 } else if (flavor == MachO::x86_EXCEPTION_STATE) {
5158 outs() << " flavor x86_EXCEPTION_STATE\n";
5159 if (count == MachO::x86_EXCEPTION_STATE_COUNT)
5160 outs() << " count x86_EXCEPTION_STATE_COUNT\n";
5162 outs() << " count " << count
5163 << " (not x86_EXCEPTION_STATE_COUNT)\n";
5164 struct MachO::x86_exception_state_t es;
5166 if (left >= sizeof(MachO::x86_exception_state_t)) {
5167 memcpy(&es, begin, sizeof(MachO::x86_exception_state_t));
5168 begin += sizeof(MachO::x86_exception_state_t);
5170 memset(&es, '\0', sizeof(MachO::x86_exception_state_t));
5171 memcpy(&es, begin, left);
5174 if (isLittleEndian != sys::IsLittleEndianHost)
5176 if (es.esh.flavor == MachO::x86_EXCEPTION_STATE64) {
5177 outs() << "\t esh.flavor x86_EXCEPTION_STATE64\n";
5178 if (es.esh.count == MachO::x86_EXCEPTION_STATE64_COUNT)
5179 outs() << "\t esh.count x86_EXCEPTION_STATE64_COUNT\n";
5181 outs() << "\t esh.count " << es.esh.count
5182 << " (not x86_EXCEPTION_STATE64_COUNT\n";
5183 Print_x86_exception_state_t(es.ues.es64);
5185 outs() << "\t esh.flavor " << es.esh.flavor << " esh.count "
5186 << es.esh.count << "\n";
5189 outs() << " flavor " << flavor << " (unknown)\n";
5190 outs() << " count " << count << "\n";
5191 outs() << " state (unknown)\n";
5192 begin += count * sizeof(uint32_t);
5196 while (begin < end) {
5197 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
5198 memcpy((char *)&flavor, begin, sizeof(uint32_t));
5199 begin += sizeof(uint32_t);
5204 if (isLittleEndian != sys::IsLittleEndianHost)
5205 sys::swapByteOrder(flavor);
5206 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
5207 memcpy((char *)&count, begin, sizeof(uint32_t));
5208 begin += sizeof(uint32_t);
5213 if (isLittleEndian != sys::IsLittleEndianHost)
5214 sys::swapByteOrder(count);
5215 outs() << " flavor " << flavor << "\n";
5216 outs() << " count " << count << "\n";
5217 outs() << " state (Unknown cputype/cpusubtype)\n";
5218 begin += count * sizeof(uint32_t);
5223 static void PrintDylibCommand(MachO::dylib_command dl, const char *Ptr) {
5224 if (dl.cmd == MachO::LC_ID_DYLIB)
5225 outs() << " cmd LC_ID_DYLIB\n";
5226 else if (dl.cmd == MachO::LC_LOAD_DYLIB)
5227 outs() << " cmd LC_LOAD_DYLIB\n";
5228 else if (dl.cmd == MachO::LC_LOAD_WEAK_DYLIB)
5229 outs() << " cmd LC_LOAD_WEAK_DYLIB\n";
5230 else if (dl.cmd == MachO::LC_REEXPORT_DYLIB)
5231 outs() << " cmd LC_REEXPORT_DYLIB\n";
5232 else if (dl.cmd == MachO::LC_LAZY_LOAD_DYLIB)
5233 outs() << " cmd LC_LAZY_LOAD_DYLIB\n";
5234 else if (dl.cmd == MachO::LC_LOAD_UPWARD_DYLIB)
5235 outs() << " cmd LC_LOAD_UPWARD_DYLIB\n";
5237 outs() << " cmd " << dl.cmd << " (unknown)\n";
5238 outs() << " cmdsize " << dl.cmdsize;
5239 if (dl.cmdsize < sizeof(struct MachO::dylib_command))
5240 outs() << " Incorrect size\n";
5243 if (dl.dylib.name < dl.cmdsize) {
5244 const char *P = (const char *)(Ptr) + dl.dylib.name;
5245 outs() << " name " << P << " (offset " << dl.dylib.name << ")\n";
5247 outs() << " name ?(bad offset " << dl.dylib.name << ")\n";
5249 outs() << " time stamp " << dl.dylib.timestamp << " ";
5250 time_t t = dl.dylib.timestamp;
5251 outs() << ctime(&t);
5252 outs() << " current version ";
5253 if (dl.dylib.current_version == 0xffffffff)
5256 outs() << ((dl.dylib.current_version >> 16) & 0xffff) << "."
5257 << ((dl.dylib.current_version >> 8) & 0xff) << "."
5258 << (dl.dylib.current_version & 0xff) << "\n";
5259 outs() << "compatibility version ";
5260 if (dl.dylib.compatibility_version == 0xffffffff)
5263 outs() << ((dl.dylib.compatibility_version >> 16) & 0xffff) << "."
5264 << ((dl.dylib.compatibility_version >> 8) & 0xff) << "."
5265 << (dl.dylib.compatibility_version & 0xff) << "\n";
5268 static void PrintLinkEditDataCommand(MachO::linkedit_data_command ld,
5269 uint32_t object_size) {
5270 if (ld.cmd == MachO::LC_CODE_SIGNATURE)
5271 outs() << " cmd LC_FUNCTION_STARTS\n";
5272 else if (ld.cmd == MachO::LC_SEGMENT_SPLIT_INFO)
5273 outs() << " cmd LC_SEGMENT_SPLIT_INFO\n";
5274 else if (ld.cmd == MachO::LC_FUNCTION_STARTS)
5275 outs() << " cmd LC_FUNCTION_STARTS\n";
5276 else if (ld.cmd == MachO::LC_DATA_IN_CODE)
5277 outs() << " cmd LC_DATA_IN_CODE\n";
5278 else if (ld.cmd == MachO::LC_DYLIB_CODE_SIGN_DRS)
5279 outs() << " cmd LC_DYLIB_CODE_SIGN_DRS\n";
5280 else if (ld.cmd == MachO::LC_LINKER_OPTIMIZATION_HINT)
5281 outs() << " cmd LC_LINKER_OPTIMIZATION_HINT\n";
5283 outs() << " cmd " << ld.cmd << " (?)\n";
5284 outs() << " cmdsize " << ld.cmdsize;
5285 if (ld.cmdsize != sizeof(struct MachO::linkedit_data_command))
5286 outs() << " Incorrect size\n";
5289 outs() << " dataoff " << ld.dataoff;
5290 if (ld.dataoff > object_size)
5291 outs() << " (past end of file)\n";
5294 outs() << " datasize " << ld.datasize;
5295 uint64_t big_size = ld.dataoff;
5296 big_size += ld.datasize;
5297 if (big_size > object_size)
5298 outs() << " (past end of file)\n";
5303 static void PrintLoadCommands(const MachOObjectFile *Obj, uint32_t ncmds,
5304 uint32_t filetype, uint32_t cputype,
5308 StringRef Buf = Obj->getData();
5309 MachOObjectFile::LoadCommandInfo Command = Obj->getFirstLoadCommandInfo();
5310 for (unsigned i = 0;; ++i) {
5311 outs() << "Load command " << i << "\n";
5312 if (Command.C.cmd == MachO::LC_SEGMENT) {
5313 MachO::segment_command SLC = Obj->getSegmentLoadCommand(Command);
5314 const char *sg_segname = SLC.segname;
5315 PrintSegmentCommand(SLC.cmd, SLC.cmdsize, SLC.segname, SLC.vmaddr,
5316 SLC.vmsize, SLC.fileoff, SLC.filesize, SLC.maxprot,
5317 SLC.initprot, SLC.nsects, SLC.flags, Buf.size(),
5319 for (unsigned j = 0; j < SLC.nsects; j++) {
5320 MachO::section S = Obj->getSection(Command, j);
5321 PrintSection(S.sectname, S.segname, S.addr, S.size, S.offset, S.align,
5322 S.reloff, S.nreloc, S.flags, S.reserved1, S.reserved2,
5323 SLC.cmd, sg_segname, filetype, Buf.size(), verbose);
5325 } else if (Command.C.cmd == MachO::LC_SEGMENT_64) {
5326 MachO::segment_command_64 SLC_64 = Obj->getSegment64LoadCommand(Command);
5327 const char *sg_segname = SLC_64.segname;
5328 PrintSegmentCommand(SLC_64.cmd, SLC_64.cmdsize, SLC_64.segname,
5329 SLC_64.vmaddr, SLC_64.vmsize, SLC_64.fileoff,
5330 SLC_64.filesize, SLC_64.maxprot, SLC_64.initprot,
5331 SLC_64.nsects, SLC_64.flags, Buf.size(), verbose);
5332 for (unsigned j = 0; j < SLC_64.nsects; j++) {
5333 MachO::section_64 S_64 = Obj->getSection64(Command, j);
5334 PrintSection(S_64.sectname, S_64.segname, S_64.addr, S_64.size,
5335 S_64.offset, S_64.align, S_64.reloff, S_64.nreloc,
5336 S_64.flags, S_64.reserved1, S_64.reserved2, SLC_64.cmd,
5337 sg_segname, filetype, Buf.size(), verbose);
5339 } else if (Command.C.cmd == MachO::LC_SYMTAB) {
5340 MachO::symtab_command Symtab = Obj->getSymtabLoadCommand();
5341 PrintSymtabLoadCommand(Symtab, Obj->is64Bit(), Buf.size());
5342 } else if (Command.C.cmd == MachO::LC_DYSYMTAB) {
5343 MachO::dysymtab_command Dysymtab = Obj->getDysymtabLoadCommand();
5344 MachO::symtab_command Symtab = Obj->getSymtabLoadCommand();
5345 PrintDysymtabLoadCommand(Dysymtab, Symtab.nsyms, Buf.size(),
5347 } else if (Command.C.cmd == MachO::LC_DYLD_INFO ||
5348 Command.C.cmd == MachO::LC_DYLD_INFO_ONLY) {
5349 MachO::dyld_info_command DyldInfo = Obj->getDyldInfoLoadCommand(Command);
5350 PrintDyldInfoLoadCommand(DyldInfo, Buf.size());
5351 } else if (Command.C.cmd == MachO::LC_LOAD_DYLINKER ||
5352 Command.C.cmd == MachO::LC_ID_DYLINKER ||
5353 Command.C.cmd == MachO::LC_DYLD_ENVIRONMENT) {
5354 MachO::dylinker_command Dyld = Obj->getDylinkerCommand(Command);
5355 PrintDyldLoadCommand(Dyld, Command.Ptr);
5356 } else if (Command.C.cmd == MachO::LC_UUID) {
5357 MachO::uuid_command Uuid = Obj->getUuidCommand(Command);
5358 PrintUuidLoadCommand(Uuid);
5359 } else if (Command.C.cmd == MachO::LC_RPATH) {
5360 MachO::rpath_command Rpath = Obj->getRpathCommand(Command);
5361 PrintRpathLoadCommand(Rpath, Command.Ptr);
5362 } else if (Command.C.cmd == MachO::LC_VERSION_MIN_MACOSX ||
5363 Command.C.cmd == MachO::LC_VERSION_MIN_IPHONEOS) {
5364 MachO::version_min_command Vd = Obj->getVersionMinLoadCommand(Command);
5365 PrintVersionMinLoadCommand(Vd);
5366 } else if (Command.C.cmd == MachO::LC_SOURCE_VERSION) {
5367 MachO::source_version_command Sd = Obj->getSourceVersionCommand(Command);
5368 PrintSourceVersionCommand(Sd);
5369 } else if (Command.C.cmd == MachO::LC_MAIN) {
5370 MachO::entry_point_command Ep = Obj->getEntryPointCommand(Command);
5371 PrintEntryPointCommand(Ep);
5372 } else if (Command.C.cmd == MachO::LC_ENCRYPTION_INFO) {
5373 MachO::encryption_info_command Ei =
5374 Obj->getEncryptionInfoCommand(Command);
5375 PrintEncryptionInfoCommand(Ei, Buf.size());
5376 } else if (Command.C.cmd == MachO::LC_ENCRYPTION_INFO_64) {
5377 MachO::encryption_info_command_64 Ei =
5378 Obj->getEncryptionInfoCommand64(Command);
5379 PrintEncryptionInfoCommand64(Ei, Buf.size());
5380 } else if (Command.C.cmd == MachO::LC_LINKER_OPTION) {
5381 MachO::linker_option_command Lo =
5382 Obj->getLinkerOptionLoadCommand(Command);
5383 PrintLinkerOptionCommand(Lo, Command.Ptr);
5384 } else if (Command.C.cmd == MachO::LC_SUB_FRAMEWORK) {
5385 MachO::sub_framework_command Sf = Obj->getSubFrameworkCommand(Command);
5386 PrintSubFrameworkCommand(Sf, Command.Ptr);
5387 } else if (Command.C.cmd == MachO::LC_SUB_UMBRELLA) {
5388 MachO::sub_umbrella_command Sf = Obj->getSubUmbrellaCommand(Command);
5389 PrintSubUmbrellaCommand(Sf, Command.Ptr);
5390 } else if (Command.C.cmd == MachO::LC_SUB_LIBRARY) {
5391 MachO::sub_library_command Sl = Obj->getSubLibraryCommand(Command);
5392 PrintSubLibraryCommand(Sl, Command.Ptr);
5393 } else if (Command.C.cmd == MachO::LC_SUB_CLIENT) {
5394 MachO::sub_client_command Sc = Obj->getSubClientCommand(Command);
5395 PrintSubClientCommand(Sc, Command.Ptr);
5396 } else if (Command.C.cmd == MachO::LC_ROUTINES) {
5397 MachO::routines_command Rc = Obj->getRoutinesCommand(Command);
5398 PrintRoutinesCommand(Rc);
5399 } else if (Command.C.cmd == MachO::LC_ROUTINES_64) {
5400 MachO::routines_command_64 Rc = Obj->getRoutinesCommand64(Command);
5401 PrintRoutinesCommand64(Rc);
5402 } else if (Command.C.cmd == MachO::LC_THREAD ||
5403 Command.C.cmd == MachO::LC_UNIXTHREAD) {
5404 MachO::thread_command Tc = Obj->getThreadCommand(Command);
5405 PrintThreadCommand(Tc, Command.Ptr, Obj->isLittleEndian(), cputype);
5406 } else if (Command.C.cmd == MachO::LC_LOAD_DYLIB ||
5407 Command.C.cmd == MachO::LC_ID_DYLIB ||
5408 Command.C.cmd == MachO::LC_LOAD_WEAK_DYLIB ||
5409 Command.C.cmd == MachO::LC_REEXPORT_DYLIB ||
5410 Command.C.cmd == MachO::LC_LAZY_LOAD_DYLIB ||
5411 Command.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB) {
5412 MachO::dylib_command Dl = Obj->getDylibIDLoadCommand(Command);
5413 PrintDylibCommand(Dl, Command.Ptr);
5414 } else if (Command.C.cmd == MachO::LC_CODE_SIGNATURE ||
5415 Command.C.cmd == MachO::LC_SEGMENT_SPLIT_INFO ||
5416 Command.C.cmd == MachO::LC_FUNCTION_STARTS ||
5417 Command.C.cmd == MachO::LC_DATA_IN_CODE ||
5418 Command.C.cmd == MachO::LC_DYLIB_CODE_SIGN_DRS ||
5419 Command.C.cmd == MachO::LC_LINKER_OPTIMIZATION_HINT) {
5420 MachO::linkedit_data_command Ld =
5421 Obj->getLinkeditDataLoadCommand(Command);
5422 PrintLinkEditDataCommand(Ld, Buf.size());
5424 outs() << " cmd ?(" << format("0x%08" PRIx32, Command.C.cmd)
5426 outs() << " cmdsize " << Command.C.cmdsize << "\n";
5427 // TODO: get and print the raw bytes of the load command.
5429 // TODO: print all the other kinds of load commands.
5433 Command = Obj->getNextLoadCommandInfo(Command);
5437 static void getAndPrintMachHeader(const MachOObjectFile *Obj, uint32_t &ncmds,
5438 uint32_t &filetype, uint32_t &cputype,
5440 if (Obj->is64Bit()) {
5441 MachO::mach_header_64 H_64;
5442 H_64 = Obj->getHeader64();
5443 PrintMachHeader(H_64.magic, H_64.cputype, H_64.cpusubtype, H_64.filetype,
5444 H_64.ncmds, H_64.sizeofcmds, H_64.flags, verbose);
5446 filetype = H_64.filetype;
5447 cputype = H_64.cputype;
5449 MachO::mach_header H;
5450 H = Obj->getHeader();
5451 PrintMachHeader(H.magic, H.cputype, H.cpusubtype, H.filetype, H.ncmds,
5452 H.sizeofcmds, H.flags, verbose);
5454 filetype = H.filetype;
5455 cputype = H.cputype;
5459 void llvm::printMachOFileHeader(const object::ObjectFile *Obj) {
5460 const MachOObjectFile *file = dyn_cast<const MachOObjectFile>(Obj);
5462 uint32_t filetype = 0;
5463 uint32_t cputype = 0;
5464 getAndPrintMachHeader(file, ncmds, filetype, cputype, true);
5465 PrintLoadCommands(file, ncmds, filetype, cputype, true);
5468 //===----------------------------------------------------------------------===//
5469 // export trie dumping
5470 //===----------------------------------------------------------------------===//
5472 void llvm::printMachOExportsTrie(const object::MachOObjectFile *Obj) {
5473 for (const llvm::object::ExportEntry &Entry : Obj->exports()) {
5474 uint64_t Flags = Entry.flags();
5475 bool ReExport = (Flags & MachO::EXPORT_SYMBOL_FLAGS_REEXPORT);
5476 bool WeakDef = (Flags & MachO::EXPORT_SYMBOL_FLAGS_WEAK_DEFINITION);
5477 bool ThreadLocal = ((Flags & MachO::EXPORT_SYMBOL_FLAGS_KIND_MASK) ==
5478 MachO::EXPORT_SYMBOL_FLAGS_KIND_THREAD_LOCAL);
5479 bool Abs = ((Flags & MachO::EXPORT_SYMBOL_FLAGS_KIND_MASK) ==
5480 MachO::EXPORT_SYMBOL_FLAGS_KIND_ABSOLUTE);
5481 bool Resolver = (Flags & MachO::EXPORT_SYMBOL_FLAGS_STUB_AND_RESOLVER);
5483 outs() << "[re-export] ";
5485 outs() << format("0x%08llX ",
5486 Entry.address()); // FIXME:add in base address
5487 outs() << Entry.name();
5488 if (WeakDef || ThreadLocal || Resolver || Abs) {
5489 bool NeedsComma = false;
5492 outs() << "weak_def";
5498 outs() << "per-thread";
5504 outs() << "absolute";
5510 outs() << format("resolver=0x%08llX", Entry.other());
5516 StringRef DylibName = "unknown";
5517 int Ordinal = Entry.other() - 1;
5518 Obj->getLibraryShortNameByIndex(Ordinal, DylibName);
5519 if (Entry.otherName().empty())
5520 outs() << " (from " << DylibName << ")";
5522 outs() << " (" << Entry.otherName() << " from " << DylibName << ")";
5528 //===----------------------------------------------------------------------===//
5529 // rebase table dumping
5530 //===----------------------------------------------------------------------===//
5535 SegInfo(const object::MachOObjectFile *Obj);
5537 StringRef segmentName(uint32_t SegIndex);
5538 StringRef sectionName(uint32_t SegIndex, uint64_t SegOffset);
5539 uint64_t address(uint32_t SegIndex, uint64_t SegOffset);
5542 struct SectionInfo {
5545 StringRef SectionName;
5546 StringRef SegmentName;
5547 uint64_t OffsetInSegment;
5548 uint64_t SegmentStartAddress;
5549 uint32_t SegmentIndex;
5551 const SectionInfo &findSection(uint32_t SegIndex, uint64_t SegOffset);
5552 SmallVector<SectionInfo, 32> Sections;
5556 SegInfo::SegInfo(const object::MachOObjectFile *Obj) {
5557 // Build table of sections so segIndex/offset pairs can be translated.
5558 uint32_t CurSegIndex = Obj->hasPageZeroSegment() ? 1 : 0;
5559 StringRef CurSegName;
5560 uint64_t CurSegAddress;
5561 for (const SectionRef &Section : Obj->sections()) {
5563 if (error(Section.getName(Info.SectionName)))
5565 Info.Address = Section.getAddress();
5566 Info.Size = Section.getSize();
5568 Obj->getSectionFinalSegmentName(Section.getRawDataRefImpl());
5569 if (!Info.SegmentName.equals(CurSegName)) {
5571 CurSegName = Info.SegmentName;
5572 CurSegAddress = Info.Address;
5574 Info.SegmentIndex = CurSegIndex - 1;
5575 Info.OffsetInSegment = Info.Address - CurSegAddress;
5576 Info.SegmentStartAddress = CurSegAddress;
5577 Sections.push_back(Info);
5581 StringRef SegInfo::segmentName(uint32_t SegIndex) {
5582 for (const SectionInfo &SI : Sections) {
5583 if (SI.SegmentIndex == SegIndex)
5584 return SI.SegmentName;
5586 llvm_unreachable("invalid segIndex");
5589 const SegInfo::SectionInfo &SegInfo::findSection(uint32_t SegIndex,
5590 uint64_t OffsetInSeg) {
5591 for (const SectionInfo &SI : Sections) {
5592 if (SI.SegmentIndex != SegIndex)
5594 if (SI.OffsetInSegment > OffsetInSeg)
5596 if (OffsetInSeg >= (SI.OffsetInSegment + SI.Size))
5600 llvm_unreachable("segIndex and offset not in any section");
5603 StringRef SegInfo::sectionName(uint32_t SegIndex, uint64_t OffsetInSeg) {
5604 return findSection(SegIndex, OffsetInSeg).SectionName;
5607 uint64_t SegInfo::address(uint32_t SegIndex, uint64_t OffsetInSeg) {
5608 const SectionInfo &SI = findSection(SegIndex, OffsetInSeg);
5609 return SI.SegmentStartAddress + OffsetInSeg;
5612 void llvm::printMachORebaseTable(const object::MachOObjectFile *Obj) {
5613 // Build table of sections so names can used in final output.
5614 SegInfo sectionTable(Obj);
5616 outs() << "segment section address type\n";
5617 for (const llvm::object::MachORebaseEntry &Entry : Obj->rebaseTable()) {
5618 uint32_t SegIndex = Entry.segmentIndex();
5619 uint64_t OffsetInSeg = Entry.segmentOffset();
5620 StringRef SegmentName = sectionTable.segmentName(SegIndex);
5621 StringRef SectionName = sectionTable.sectionName(SegIndex, OffsetInSeg);
5622 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
5624 // Table lines look like: __DATA __nl_symbol_ptr 0x0000F00C pointer
5625 outs() << format("%-8s %-18s 0x%08" PRIX64 " %s\n",
5626 SegmentName.str().c_str(), SectionName.str().c_str(),
5627 Address, Entry.typeName().str().c_str());
5631 static StringRef ordinalName(const object::MachOObjectFile *Obj, int Ordinal) {
5632 StringRef DylibName;
5634 case MachO::BIND_SPECIAL_DYLIB_SELF:
5635 return "this-image";
5636 case MachO::BIND_SPECIAL_DYLIB_MAIN_EXECUTABLE:
5637 return "main-executable";
5638 case MachO::BIND_SPECIAL_DYLIB_FLAT_LOOKUP:
5639 return "flat-namespace";
5642 std::error_code EC =
5643 Obj->getLibraryShortNameByIndex(Ordinal - 1, DylibName);
5645 return "<<bad library ordinal>>";
5649 return "<<unknown special ordinal>>";
5652 //===----------------------------------------------------------------------===//
5653 // bind table dumping
5654 //===----------------------------------------------------------------------===//
5656 void llvm::printMachOBindTable(const object::MachOObjectFile *Obj) {
5657 // Build table of sections so names can used in final output.
5658 SegInfo sectionTable(Obj);
5660 outs() << "segment section address type "
5661 "addend dylib symbol\n";
5662 for (const llvm::object::MachOBindEntry &Entry : Obj->bindTable()) {
5663 uint32_t SegIndex = Entry.segmentIndex();
5664 uint64_t OffsetInSeg = Entry.segmentOffset();
5665 StringRef SegmentName = sectionTable.segmentName(SegIndex);
5666 StringRef SectionName = sectionTable.sectionName(SegIndex, OffsetInSeg);
5667 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
5669 // Table lines look like:
5670 // __DATA __got 0x00012010 pointer 0 libSystem ___stack_chk_guard
5672 if (Entry.flags() & MachO::BIND_SYMBOL_FLAGS_WEAK_IMPORT)
5673 Attr = " (weak_import)";
5674 outs() << left_justify(SegmentName, 8) << " "
5675 << left_justify(SectionName, 18) << " "
5676 << format_hex(Address, 10, true) << " "
5677 << left_justify(Entry.typeName(), 8) << " "
5678 << format_decimal(Entry.addend(), 8) << " "
5679 << left_justify(ordinalName(Obj, Entry.ordinal()), 16) << " "
5680 << Entry.symbolName() << Attr << "\n";
5684 //===----------------------------------------------------------------------===//
5685 // lazy bind table dumping
5686 //===----------------------------------------------------------------------===//
5688 void llvm::printMachOLazyBindTable(const object::MachOObjectFile *Obj) {
5689 // Build table of sections so names can used in final output.
5690 SegInfo sectionTable(Obj);
5692 outs() << "segment section address "
5694 for (const llvm::object::MachOBindEntry &Entry : Obj->lazyBindTable()) {
5695 uint32_t SegIndex = Entry.segmentIndex();
5696 uint64_t OffsetInSeg = Entry.segmentOffset();
5697 StringRef SegmentName = sectionTable.segmentName(SegIndex);
5698 StringRef SectionName = sectionTable.sectionName(SegIndex, OffsetInSeg);
5699 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
5701 // Table lines look like:
5702 // __DATA __got 0x00012010 libSystem ___stack_chk_guard
5703 outs() << left_justify(SegmentName, 8) << " "
5704 << left_justify(SectionName, 18) << " "
5705 << format_hex(Address, 10, true) << " "
5706 << left_justify(ordinalName(Obj, Entry.ordinal()), 16) << " "
5707 << Entry.symbolName() << "\n";
5711 //===----------------------------------------------------------------------===//
5712 // weak bind table dumping
5713 //===----------------------------------------------------------------------===//
5715 void llvm::printMachOWeakBindTable(const object::MachOObjectFile *Obj) {
5716 // Build table of sections so names can used in final output.
5717 SegInfo sectionTable(Obj);
5719 outs() << "segment section address "
5720 "type addend symbol\n";
5721 for (const llvm::object::MachOBindEntry &Entry : Obj->weakBindTable()) {
5722 // Strong symbols don't have a location to update.
5723 if (Entry.flags() & MachO::BIND_SYMBOL_FLAGS_NON_WEAK_DEFINITION) {
5724 outs() << " strong "
5725 << Entry.symbolName() << "\n";
5728 uint32_t SegIndex = Entry.segmentIndex();
5729 uint64_t OffsetInSeg = Entry.segmentOffset();
5730 StringRef SegmentName = sectionTable.segmentName(SegIndex);
5731 StringRef SectionName = sectionTable.sectionName(SegIndex, OffsetInSeg);
5732 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
5734 // Table lines look like:
5735 // __DATA __data 0x00001000 pointer 0 _foo
5736 outs() << left_justify(SegmentName, 8) << " "
5737 << left_justify(SectionName, 18) << " "
5738 << format_hex(Address, 10, true) << " "
5739 << left_justify(Entry.typeName(), 8) << " "
5740 << format_decimal(Entry.addend(), 8) << " " << Entry.symbolName()
5745 // get_dyld_bind_info_symbolname() is used for disassembly and passed an
5746 // address, ReferenceValue, in the Mach-O file and looks in the dyld bind
5747 // information for that address. If the address is found its binding symbol
5748 // name is returned. If not nullptr is returned.
5749 static const char *get_dyld_bind_info_symbolname(uint64_t ReferenceValue,
5750 struct DisassembleInfo *info) {
5751 if (info->bindtable == nullptr) {
5752 info->bindtable = new (BindTable);
5753 SegInfo sectionTable(info->O);
5754 for (const llvm::object::MachOBindEntry &Entry : info->O->bindTable()) {
5755 uint32_t SegIndex = Entry.segmentIndex();
5756 uint64_t OffsetInSeg = Entry.segmentOffset();
5757 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
5758 const char *SymbolName = nullptr;
5759 StringRef name = Entry.symbolName();
5761 SymbolName = name.data();
5762 info->bindtable->push_back(std::make_pair(Address, SymbolName));
5765 for (bind_table_iterator BI = info->bindtable->begin(),
5766 BE = info->bindtable->end();
5768 uint64_t Address = BI->first;
5769 if (ReferenceValue == Address) {
5770 const char *SymbolName = BI->second;