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)"));
99 static cl::list<std::string>
100 ArchFlags("arch", cl::desc("architecture(s) from a Mach-O file to dump"),
102 bool ArchAll = false;
104 static std::string ThumbTripleName;
106 static const Target *GetTarget(const MachOObjectFile *MachOObj,
107 const char **McpuDefault,
108 const Target **ThumbTarget) {
109 // Figure out the target triple.
110 if (TripleName.empty()) {
111 llvm::Triple TT("unknown-unknown-unknown");
112 llvm::Triple ThumbTriple = Triple();
113 TT = MachOObj->getArch(McpuDefault, &ThumbTriple);
114 TripleName = TT.str();
115 ThumbTripleName = ThumbTriple.str();
118 // Get the target specific parser.
120 const Target *TheTarget = TargetRegistry::lookupTarget(TripleName, Error);
121 if (TheTarget && ThumbTripleName.empty())
124 *ThumbTarget = TargetRegistry::lookupTarget(ThumbTripleName, Error);
128 errs() << "llvm-objdump: error: unable to get target for '";
130 errs() << TripleName;
132 errs() << ThumbTripleName;
133 errs() << "', see --version and --triple.\n";
137 struct SymbolSorter {
138 bool operator()(const SymbolRef &A, const SymbolRef &B) {
139 SymbolRef::Type AType, BType;
143 uint64_t AAddr, BAddr;
144 if (AType != SymbolRef::ST_Function)
148 if (BType != SymbolRef::ST_Function)
152 return AAddr < BAddr;
156 // Types for the storted data in code table that is built before disassembly
157 // and the predicate function to sort them.
158 typedef std::pair<uint64_t, DiceRef> DiceTableEntry;
159 typedef std::vector<DiceTableEntry> DiceTable;
160 typedef DiceTable::iterator dice_table_iterator;
162 // This is used to search for a data in code table entry for the PC being
163 // disassembled. The j parameter has the PC in j.first. A single data in code
164 // table entry can cover many bytes for each of its Kind's. So if the offset,
165 // aka the i.first value, of the data in code table entry plus its Length
166 // covers the PC being searched for this will return true. If not it will
168 static bool compareDiceTableEntries(const DiceTableEntry &i,
169 const DiceTableEntry &j) {
171 i.second.getLength(Length);
173 return j.first >= i.first && j.first < i.first + Length;
176 static uint64_t DumpDataInCode(const char *bytes, uint64_t Length,
177 unsigned short Kind) {
178 uint32_t Value, Size = 1;
182 case MachO::DICE_KIND_DATA:
185 DumpBytes(StringRef(bytes, 4));
186 Value = bytes[3] << 24 | bytes[2] << 16 | bytes[1] << 8 | bytes[0];
187 outs() << "\t.long " << Value;
189 } else if (Length >= 2) {
191 DumpBytes(StringRef(bytes, 2));
192 Value = bytes[1] << 8 | bytes[0];
193 outs() << "\t.short " << Value;
197 DumpBytes(StringRef(bytes, 2));
199 outs() << "\t.byte " << Value;
202 if (Kind == MachO::DICE_KIND_DATA)
203 outs() << "\t@ KIND_DATA\n";
205 outs() << "\t@ data in code kind = " << Kind << "\n";
207 case MachO::DICE_KIND_JUMP_TABLE8:
209 DumpBytes(StringRef(bytes, 1));
211 outs() << "\t.byte " << format("%3u", Value) << "\t@ KIND_JUMP_TABLE8\n";
214 case MachO::DICE_KIND_JUMP_TABLE16:
216 DumpBytes(StringRef(bytes, 2));
217 Value = bytes[1] << 8 | bytes[0];
218 outs() << "\t.short " << format("%5u", Value & 0xffff)
219 << "\t@ KIND_JUMP_TABLE16\n";
222 case MachO::DICE_KIND_JUMP_TABLE32:
223 case MachO::DICE_KIND_ABS_JUMP_TABLE32:
225 DumpBytes(StringRef(bytes, 4));
226 Value = bytes[3] << 24 | bytes[2] << 16 | bytes[1] << 8 | bytes[0];
227 outs() << "\t.long " << Value;
228 if (Kind == MachO::DICE_KIND_JUMP_TABLE32)
229 outs() << "\t@ KIND_JUMP_TABLE32\n";
231 outs() << "\t@ KIND_ABS_JUMP_TABLE32\n";
238 static void getSectionsAndSymbols(const MachO::mach_header Header,
239 MachOObjectFile *MachOObj,
240 std::vector<SectionRef> &Sections,
241 std::vector<SymbolRef> &Symbols,
242 SmallVectorImpl<uint64_t> &FoundFns,
243 uint64_t &BaseSegmentAddress) {
244 for (const SymbolRef &Symbol : MachOObj->symbols()) {
246 Symbol.getName(SymName);
247 if (!SymName.startswith("ltmp"))
248 Symbols.push_back(Symbol);
251 for (const SectionRef &Section : MachOObj->sections()) {
253 Section.getName(SectName);
254 Sections.push_back(Section);
257 MachOObjectFile::LoadCommandInfo Command =
258 MachOObj->getFirstLoadCommandInfo();
259 bool BaseSegmentAddressSet = false;
260 for (unsigned i = 0;; ++i) {
261 if (Command.C.cmd == MachO::LC_FUNCTION_STARTS) {
262 // We found a function starts segment, parse the addresses for later
264 MachO::linkedit_data_command LLC =
265 MachOObj->getLinkeditDataLoadCommand(Command);
267 MachOObj->ReadULEB128s(LLC.dataoff, FoundFns);
268 } else if (Command.C.cmd == MachO::LC_SEGMENT) {
269 MachO::segment_command SLC = MachOObj->getSegmentLoadCommand(Command);
270 StringRef SegName = SLC.segname;
271 if (!BaseSegmentAddressSet && SegName != "__PAGEZERO") {
272 BaseSegmentAddressSet = true;
273 BaseSegmentAddress = SLC.vmaddr;
277 if (i == Header.ncmds - 1)
280 Command = MachOObj->getNextLoadCommandInfo(Command);
284 static void PrintIndirectSymbolTable(MachOObjectFile *O, bool verbose,
285 uint32_t n, uint32_t count,
286 uint32_t stride, uint64_t addr) {
287 MachO::dysymtab_command Dysymtab = O->getDysymtabLoadCommand();
288 uint32_t nindirectsyms = Dysymtab.nindirectsyms;
289 if (n > nindirectsyms)
290 outs() << " (entries start past the end of the indirect symbol "
291 "table) (reserved1 field greater than the table size)";
292 else if (n + count > nindirectsyms)
293 outs() << " (entries extends past the end of the indirect symbol "
296 uint32_t cputype = O->getHeader().cputype;
297 if (cputype & MachO::CPU_ARCH_ABI64)
298 outs() << "address index";
300 outs() << "address index";
305 for (uint32_t j = 0; j < count && n + j < nindirectsyms; j++) {
306 if (cputype & MachO::CPU_ARCH_ABI64)
307 outs() << format("0x%016" PRIx64, addr + j * stride) << " ";
309 outs() << format("0x%08" PRIx32, addr + j * stride) << " ";
310 MachO::dysymtab_command Dysymtab = O->getDysymtabLoadCommand();
311 uint32_t indirect_symbol = O->getIndirectSymbolTableEntry(Dysymtab, n + j);
312 if (indirect_symbol == MachO::INDIRECT_SYMBOL_LOCAL) {
316 if (indirect_symbol ==
317 (MachO::INDIRECT_SYMBOL_LOCAL | MachO::INDIRECT_SYMBOL_ABS)) {
318 outs() << "LOCAL ABSOLUTE\n";
321 if (indirect_symbol == MachO::INDIRECT_SYMBOL_ABS) {
322 outs() << "ABSOLUTE\n";
325 outs() << format("%5u ", indirect_symbol);
326 MachO::symtab_command Symtab = O->getSymtabLoadCommand();
327 if (indirect_symbol < Symtab.nsyms) {
328 symbol_iterator Sym = O->getSymbolByIndex(indirect_symbol);
329 SymbolRef Symbol = *Sym;
331 Symbol.getName(SymName);
340 static void PrintIndirectSymbols(MachOObjectFile *O, bool verbose) {
341 uint32_t LoadCommandCount = O->getHeader().ncmds;
342 MachOObjectFile::LoadCommandInfo Load = O->getFirstLoadCommandInfo();
343 for (unsigned I = 0;; ++I) {
344 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
345 MachO::segment_command_64 Seg = O->getSegment64LoadCommand(Load);
346 for (unsigned J = 0; J < Seg.nsects; ++J) {
347 MachO::section_64 Sec = O->getSection64(Load, J);
348 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
349 if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
350 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
351 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
352 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
353 section_type == MachO::S_SYMBOL_STUBS) {
355 if (section_type == MachO::S_SYMBOL_STUBS)
356 stride = Sec.reserved2;
360 outs() << "Can't print indirect symbols for (" << Sec.segname << ","
361 << Sec.sectname << ") "
362 << "(size of stubs in reserved2 field is zero)\n";
365 uint32_t count = Sec.size / stride;
366 outs() << "Indirect symbols for (" << Sec.segname << ","
367 << Sec.sectname << ") " << count << " entries";
368 uint32_t n = Sec.reserved1;
369 PrintIndirectSymbolTable(O, verbose, n, count, stride, Sec.addr);
372 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
373 MachO::segment_command Seg = O->getSegmentLoadCommand(Load);
374 for (unsigned J = 0; J < Seg.nsects; ++J) {
375 MachO::section Sec = O->getSection(Load, J);
376 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
377 if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
378 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
379 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
380 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
381 section_type == MachO::S_SYMBOL_STUBS) {
383 if (section_type == MachO::S_SYMBOL_STUBS)
384 stride = Sec.reserved2;
388 outs() << "Can't print indirect symbols for (" << Sec.segname << ","
389 << Sec.sectname << ") "
390 << "(size of stubs in reserved2 field is zero)\n";
393 uint32_t count = Sec.size / stride;
394 outs() << "Indirect symbols for (" << Sec.segname << ","
395 << Sec.sectname << ") " << count << " entries";
396 uint32_t n = Sec.reserved1;
397 PrintIndirectSymbolTable(O, verbose, n, count, stride, Sec.addr);
401 if (I == LoadCommandCount - 1)
404 Load = O->getNextLoadCommandInfo(Load);
408 static void PrintDataInCodeTable(MachOObjectFile *O, bool verbose) {
409 MachO::linkedit_data_command DIC = O->getDataInCodeLoadCommand();
410 uint32_t nentries = DIC.datasize / sizeof(struct MachO::data_in_code_entry);
411 outs() << "Data in code table (" << nentries << " entries)\n";
412 outs() << "offset length kind\n";
413 for (dice_iterator DI = O->begin_dices(), DE = O->end_dices(); DI != DE;
416 DI->getOffset(Offset);
417 outs() << format("0x%08" PRIx32, Offset) << " ";
419 DI->getLength(Length);
420 outs() << format("%6u", Length) << " ";
425 case MachO::DICE_KIND_DATA:
428 case MachO::DICE_KIND_JUMP_TABLE8:
429 outs() << "JUMP_TABLE8";
431 case MachO::DICE_KIND_JUMP_TABLE16:
432 outs() << "JUMP_TABLE16";
434 case MachO::DICE_KIND_JUMP_TABLE32:
435 outs() << "JUMP_TABLE32";
437 case MachO::DICE_KIND_ABS_JUMP_TABLE32:
438 outs() << "ABS_JUMP_TABLE32";
441 outs() << format("0x%04" PRIx32, Kind);
445 outs() << format("0x%04" PRIx32, Kind);
450 static void PrintLinkOptHints(MachOObjectFile *O) {
451 MachO::linkedit_data_command LohLC = O->getLinkOptHintsLoadCommand();
452 const char *loh = O->getData().substr(LohLC.dataoff, 1).data();
453 uint32_t nloh = LohLC.datasize;
454 outs() << "Linker optimiztion hints (" << nloh << " total bytes)\n";
455 for (uint32_t i = 0; i < nloh;) {
457 uint64_t identifier = decodeULEB128((const uint8_t *)(loh + i), &n);
459 outs() << " identifier " << identifier << " ";
462 switch (identifier) {
464 outs() << "AdrpAdrp\n";
467 outs() << "AdrpLdr\n";
470 outs() << "AdrpAddLdr\n";
473 outs() << "AdrpLdrGotLdr\n";
476 outs() << "AdrpAddStr\n";
479 outs() << "AdrpLdrGotStr\n";
482 outs() << "AdrpAdd\n";
485 outs() << "AdrpLdrGot\n";
488 outs() << "Unknown identifier value\n";
491 uint64_t narguments = decodeULEB128((const uint8_t *)(loh + i), &n);
493 outs() << " narguments " << narguments << "\n";
497 for (uint32_t j = 0; j < narguments; j++) {
498 uint64_t value = decodeULEB128((const uint8_t *)(loh + i), &n);
500 outs() << "\tvalue " << format("0x%" PRIx64, value) << "\n";
507 typedef DenseMap<uint64_t, StringRef> SymbolAddressMap;
509 static void CreateSymbolAddressMap(MachOObjectFile *O,
510 SymbolAddressMap *AddrMap) {
511 // Create a map of symbol addresses to symbol names.
512 for (const SymbolRef &Symbol : O->symbols()) {
515 if (ST == SymbolRef::ST_Function || ST == SymbolRef::ST_Data ||
516 ST == SymbolRef::ST_Other) {
518 Symbol.getAddress(Address);
520 Symbol.getName(SymName);
521 (*AddrMap)[Address] = SymName;
526 // GuessSymbolName is passed the address of what might be a symbol and a
527 // pointer to the SymbolAddressMap. It returns the name of a symbol
528 // with that address or nullptr if no symbol is found with that address.
529 static const char *GuessSymbolName(uint64_t value, SymbolAddressMap *AddrMap) {
530 const char *SymbolName = nullptr;
531 // A DenseMap can't lookup up some values.
532 if (value != 0xffffffffffffffffULL && value != 0xfffffffffffffffeULL) {
533 StringRef name = AddrMap->lookup(value);
535 SymbolName = name.data();
540 static void DumpCstringChar(const char c) {
544 outs().write_escaped(p);
547 static void DumpCstringSection(MachOObjectFile *O, const char *sect,
548 uint32_t sect_size, uint64_t sect_addr,
549 bool print_addresses) {
550 for (uint32_t i = 0; i < sect_size; i++) {
551 if (print_addresses) {
553 outs() << format("%016" PRIx64, sect_addr + i) << " ";
555 outs() << format("%08" PRIx64, sect_addr + i) << " ";
557 for (; i < sect_size && sect[i] != '\0'; i++)
558 DumpCstringChar(sect[i]);
559 if (i < sect_size && sect[i] == '\0')
564 static void DumpLiteral4(uint32_t l, float f) {
565 outs() << format("0x%08" PRIx32, l);
566 if ((l & 0x7f800000) != 0x7f800000)
567 outs() << format(" (%.16e)\n", f);
570 outs() << " (+Infinity)\n";
571 else if (l == 0xff800000)
572 outs() << " (-Infinity)\n";
573 else if ((l & 0x00400000) == 0x00400000)
574 outs() << " (non-signaling Not-a-Number)\n";
576 outs() << " (signaling Not-a-Number)\n";
580 static void DumpLiteral4Section(MachOObjectFile *O, const char *sect,
581 uint32_t sect_size, uint64_t sect_addr,
582 bool print_addresses) {
583 for (uint32_t i = 0; i < sect_size; i += sizeof(float)) {
584 if (print_addresses) {
586 outs() << format("%016" PRIx64, sect_addr + i) << " ";
588 outs() << format("%08" PRIx64, sect_addr + i) << " ";
591 memcpy(&f, sect + i, sizeof(float));
592 if (O->isLittleEndian() != sys::IsLittleEndianHost)
593 sys::swapByteOrder(f);
595 memcpy(&l, sect + i, sizeof(uint32_t));
596 if (O->isLittleEndian() != sys::IsLittleEndianHost)
597 sys::swapByteOrder(l);
602 static void DumpLiteral8(MachOObjectFile *O, uint32_t l0, uint32_t l1,
604 outs() << format("0x%08" PRIx32, l0) << " " << format("0x%08" PRIx32, l1);
606 if (O->isLittleEndian()) {
613 // Hi is the high word, so this is equivalent to if(isfinite(d))
614 if ((Hi & 0x7ff00000) != 0x7ff00000)
615 outs() << format(" (%.16e)\n", d);
617 if (Hi == 0x7ff00000 && Lo == 0)
618 outs() << " (+Infinity)\n";
619 else if (Hi == 0xfff00000 && Lo == 0)
620 outs() << " (-Infinity)\n";
621 else if ((Hi & 0x00080000) == 0x00080000)
622 outs() << " (non-signaling Not-a-Number)\n";
624 outs() << " (signaling Not-a-Number)\n";
628 static void DumpLiteral8Section(MachOObjectFile *O, const char *sect,
629 uint32_t sect_size, uint64_t sect_addr,
630 bool print_addresses) {
631 for (uint32_t i = 0; i < sect_size; i += sizeof(double)) {
632 if (print_addresses) {
634 outs() << format("%016" PRIx64, sect_addr + i) << " ";
636 outs() << format("%08" PRIx64, sect_addr + i) << " ";
639 memcpy(&d, sect + i, sizeof(double));
640 if (O->isLittleEndian() != sys::IsLittleEndianHost)
641 sys::swapByteOrder(d);
643 memcpy(&l0, sect + i, sizeof(uint32_t));
644 memcpy(&l1, sect + i + sizeof(uint32_t), sizeof(uint32_t));
645 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
646 sys::swapByteOrder(l0);
647 sys::swapByteOrder(l1);
649 DumpLiteral8(O, l0, l1, d);
653 static void DumpLiteral16(uint32_t l0, uint32_t l1, uint32_t l2, uint32_t l3) {
654 outs() << format("0x%08" PRIx32, l0) << " ";
655 outs() << format("0x%08" PRIx32, l1) << " ";
656 outs() << format("0x%08" PRIx32, l2) << " ";
657 outs() << format("0x%08" PRIx32, l3) << "\n";
660 static void DumpLiteral16Section(MachOObjectFile *O, const char *sect,
661 uint32_t sect_size, uint64_t sect_addr,
662 bool print_addresses) {
663 for (uint32_t i = 0; i < sect_size; i += 16) {
664 if (print_addresses) {
666 outs() << format("%016" PRIx64, sect_addr + i) << " ";
668 outs() << format("%08" PRIx64, sect_addr + i) << " ";
670 uint32_t l0, l1, l2, l3;
671 memcpy(&l0, sect + i, sizeof(uint32_t));
672 memcpy(&l1, sect + i + sizeof(uint32_t), sizeof(uint32_t));
673 memcpy(&l2, sect + i + 2 * sizeof(uint32_t), sizeof(uint32_t));
674 memcpy(&l3, sect + i + 3 * sizeof(uint32_t), sizeof(uint32_t));
675 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
676 sys::swapByteOrder(l0);
677 sys::swapByteOrder(l1);
678 sys::swapByteOrder(l2);
679 sys::swapByteOrder(l3);
681 DumpLiteral16(l0, l1, l2, l3);
685 static void DumpLiteralPointerSection(MachOObjectFile *O,
686 const SectionRef &Section,
687 const char *sect, uint32_t sect_size,
689 bool print_addresses) {
690 // Collect the literal sections in this Mach-O file.
691 std::vector<SectionRef> LiteralSections;
692 for (const SectionRef &Section : O->sections()) {
693 DataRefImpl Ref = Section.getRawDataRefImpl();
694 uint32_t section_type;
696 const MachO::section_64 Sec = O->getSection64(Ref);
697 section_type = Sec.flags & MachO::SECTION_TYPE;
699 const MachO::section Sec = O->getSection(Ref);
700 section_type = Sec.flags & MachO::SECTION_TYPE;
702 if (section_type == MachO::S_CSTRING_LITERALS ||
703 section_type == MachO::S_4BYTE_LITERALS ||
704 section_type == MachO::S_8BYTE_LITERALS ||
705 section_type == MachO::S_16BYTE_LITERALS)
706 LiteralSections.push_back(Section);
709 // Set the size of the literal pointer.
710 uint32_t lp_size = O->is64Bit() ? 8 : 4;
712 // Collect the external relocation symbols for the the literal pointers.
713 std::vector<std::pair<uint64_t, SymbolRef>> Relocs;
714 for (const RelocationRef &Reloc : Section.relocations()) {
716 MachO::any_relocation_info RE;
717 bool isExtern = false;
718 Rel = Reloc.getRawDataRefImpl();
719 RE = O->getRelocation(Rel);
720 isExtern = O->getPlainRelocationExternal(RE);
722 uint64_t RelocOffset;
723 Reloc.getOffset(RelocOffset);
724 symbol_iterator RelocSym = Reloc.getSymbol();
725 Relocs.push_back(std::make_pair(RelocOffset, *RelocSym));
728 array_pod_sort(Relocs.begin(), Relocs.end());
730 // Dump each literal pointer.
731 for (uint32_t i = 0; i < sect_size; i += lp_size) {
732 if (print_addresses) {
734 outs() << format("%016" PRIx64, sect_addr + i) << " ";
736 outs() << format("%08" PRIx64, sect_addr + i) << " ";
740 memcpy(&lp, sect + i, sizeof(uint64_t));
741 if (O->isLittleEndian() != sys::IsLittleEndianHost)
742 sys::swapByteOrder(lp);
745 memcpy(&li, sect + i, sizeof(uint32_t));
746 if (O->isLittleEndian() != sys::IsLittleEndianHost)
747 sys::swapByteOrder(li);
751 // First look for an external relocation entry for this literal pointer.
752 bool reloc_found = false;
753 for (unsigned j = 0, e = Relocs.size(); j != e; ++j) {
754 if (Relocs[i].first == i) {
755 symbol_iterator RelocSym = Relocs[j].second;
757 RelocSym->getName(SymName);
758 outs() << "external relocation entry for symbol:" << SymName << "\n";
762 if (reloc_found == true)
765 // For local references see what the section the literal pointer points to.
767 for (unsigned SectIdx = 0; SectIdx != LiteralSections.size(); SectIdx++) {
768 uint64_t SectAddress = LiteralSections[SectIdx].getAddress();
769 uint64_t SectSize = LiteralSections[SectIdx].getSize();
770 if (lp >= SectAddress && lp < SectAddress + SectSize) {
774 LiteralSections[SectIdx].getName(SectName);
775 DataRefImpl Ref = LiteralSections[SectIdx].getRawDataRefImpl();
776 StringRef SegmentName = O->getSectionFinalSegmentName(Ref);
777 outs() << SegmentName << ":" << SectName << ":";
779 uint32_t section_type;
781 const MachO::section_64 Sec = O->getSection64(Ref);
782 section_type = Sec.flags & MachO::SECTION_TYPE;
784 const MachO::section Sec = O->getSection(Ref);
785 section_type = Sec.flags & MachO::SECTION_TYPE;
789 LiteralSections[SectIdx].getContents(BytesStr);
790 const char *Contents = reinterpret_cast<const char *>(BytesStr.data());
792 switch (section_type) {
793 case MachO::S_CSTRING_LITERALS:
794 for (uint64_t i = lp - SectAddress;
795 i < SectSize && Contents[i] != '\0'; i++) {
796 DumpCstringChar(Contents[i]);
800 case MachO::S_4BYTE_LITERALS:
802 memcpy(&f, Contents + (lp - SectAddress), sizeof(float));
804 memcpy(&l, Contents + (lp - SectAddress), sizeof(uint32_t));
805 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
806 sys::swapByteOrder(f);
807 sys::swapByteOrder(l);
811 case MachO::S_8BYTE_LITERALS: {
813 memcpy(&d, Contents + (lp - SectAddress), sizeof(double));
815 memcpy(&l0, Contents + (lp - SectAddress), sizeof(uint32_t));
816 memcpy(&l1, Contents + (lp - SectAddress) + sizeof(uint32_t),
818 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
819 sys::swapByteOrder(f);
820 sys::swapByteOrder(l0);
821 sys::swapByteOrder(l1);
823 DumpLiteral8(O, l0, l1, d);
826 case MachO::S_16BYTE_LITERALS: {
827 uint32_t l0, l1, l2, l3;
828 memcpy(&l0, Contents + (lp - SectAddress), sizeof(uint32_t));
829 memcpy(&l1, Contents + (lp - SectAddress) + sizeof(uint32_t),
831 memcpy(&l2, Contents + (lp - SectAddress) + 2 * sizeof(uint32_t),
833 memcpy(&l3, Contents + (lp - SectAddress) + 3 * sizeof(uint32_t),
835 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
836 sys::swapByteOrder(l0);
837 sys::swapByteOrder(l1);
838 sys::swapByteOrder(l2);
839 sys::swapByteOrder(l3);
841 DumpLiteral16(l0, l1, l2, l3);
848 outs() << format("0x%" PRIx64, lp) << " (not in a literal section)\n";
852 static void DumpInitTermPointerSection(MachOObjectFile *O, const char *sect,
853 uint32_t sect_size, uint64_t sect_addr,
854 SymbolAddressMap *AddrMap,
858 stride = sizeof(uint64_t);
860 stride = sizeof(uint32_t);
861 for (uint32_t i = 0; i < sect_size; i += stride) {
862 const char *SymbolName = nullptr;
864 outs() << format("0x%016" PRIx64, sect_addr + i * stride) << " ";
865 uint64_t pointer_value;
866 memcpy(&pointer_value, sect + i, stride);
867 if (O->isLittleEndian() != sys::IsLittleEndianHost)
868 sys::swapByteOrder(pointer_value);
869 outs() << format("0x%016" PRIx64, pointer_value);
871 SymbolName = GuessSymbolName(pointer_value, AddrMap);
873 outs() << format("0x%08" PRIx64, sect_addr + i * stride) << " ";
874 uint32_t pointer_value;
875 memcpy(&pointer_value, sect + i, stride);
876 if (O->isLittleEndian() != sys::IsLittleEndianHost)
877 sys::swapByteOrder(pointer_value);
878 outs() << format("0x%08" PRIx32, pointer_value);
880 SymbolName = GuessSymbolName(pointer_value, AddrMap);
883 outs() << " " << SymbolName;
888 static void DumpRawSectionContents(MachOObjectFile *O, const char *sect,
889 uint32_t size, uint64_t addr) {
890 uint32_t cputype = O->getHeader().cputype;
891 if (cputype == MachO::CPU_TYPE_I386 || cputype == MachO::CPU_TYPE_X86_64) {
893 for (uint32_t i = 0; i < size; i += j, addr += j) {
895 outs() << format("%016" PRIx64, addr) << "\t";
897 outs() << format("%08" PRIx64, sect) << "\t";
898 for (j = 0; j < 16 && i + j < size; j++) {
899 uint8_t byte_word = *(sect + i + j);
900 outs() << format("%02" PRIx32, (uint32_t)byte_word) << " ";
906 for (uint32_t i = 0; i < size; i += j, addr += j) {
908 outs() << format("%016" PRIx64, addr) << "\t";
910 outs() << format("%08" PRIx64, sect) << "\t";
911 for (j = 0; j < 4 * sizeof(int32_t) && i + j < size;
912 j += sizeof(int32_t)) {
913 if (i + j + sizeof(int32_t) < size) {
915 memcpy(&long_word, sect + i + j, sizeof(int32_t));
916 if (O->isLittleEndian() != sys::IsLittleEndianHost)
917 sys::swapByteOrder(long_word);
918 outs() << format("%08" PRIx32, long_word) << " ";
920 for (uint32_t k = 0; i + j + k < size; k++) {
921 uint8_t byte_word = *(sect + i + j);
922 outs() << format("%02" PRIx32, (uint32_t)byte_word) << " ";
931 static void DisassembleMachO(StringRef Filename, MachOObjectFile *MachOOF,
932 StringRef DisSegName, StringRef DisSectName);
934 static void DumpSectionContents(StringRef Filename, MachOObjectFile *O,
936 SymbolAddressMap AddrMap;
938 CreateSymbolAddressMap(O, &AddrMap);
940 for (unsigned i = 0; i < DumpSections.size(); ++i) {
941 StringRef DumpSection = DumpSections[i];
942 std::pair<StringRef, StringRef> DumpSegSectName;
943 DumpSegSectName = DumpSection.split(',');
944 StringRef DumpSegName, DumpSectName;
945 if (DumpSegSectName.second.size()) {
946 DumpSegName = DumpSegSectName.first;
947 DumpSectName = DumpSegSectName.second;
950 DumpSectName = DumpSegSectName.first;
952 for (const SectionRef &Section : O->sections()) {
954 Section.getName(SectName);
955 DataRefImpl Ref = Section.getRawDataRefImpl();
956 StringRef SegName = O->getSectionFinalSegmentName(Ref);
957 if ((DumpSegName.empty() || SegName == DumpSegName) &&
958 (SectName == DumpSectName)) {
959 outs() << "Contents of (" << SegName << "," << SectName
961 uint32_t section_flags;
963 const MachO::section_64 Sec = O->getSection64(Ref);
964 section_flags = Sec.flags;
967 const MachO::section Sec = O->getSection(Ref);
968 section_flags = Sec.flags;
970 uint32_t section_type = section_flags & MachO::SECTION_TYPE;
973 Section.getContents(BytesStr);
974 const char *sect = reinterpret_cast<const char *>(BytesStr.data());
975 uint32_t sect_size = BytesStr.size();
976 uint64_t sect_addr = Section.getAddress();
979 if ((section_flags & MachO::S_ATTR_PURE_INSTRUCTIONS) ||
980 (section_flags & MachO::S_ATTR_SOME_INSTRUCTIONS)) {
981 DisassembleMachO(Filename, O, SegName, SectName);
984 switch (section_type) {
985 case MachO::S_REGULAR:
986 DumpRawSectionContents(O, sect, sect_size, sect_addr);
988 case MachO::S_ZEROFILL:
989 outs() << "zerofill section and has no contents in the file\n";
991 case MachO::S_CSTRING_LITERALS:
992 DumpCstringSection(O, sect, sect_size, sect_addr, verbose);
994 case MachO::S_4BYTE_LITERALS:
995 DumpLiteral4Section(O, sect, sect_size, sect_addr, verbose);
997 case MachO::S_8BYTE_LITERALS:
998 DumpLiteral8Section(O, sect, sect_size, sect_addr, verbose);
1000 case MachO::S_16BYTE_LITERALS:
1001 DumpLiteral16Section(O, sect, sect_size, sect_addr, verbose);
1003 case MachO::S_LITERAL_POINTERS:
1004 DumpLiteralPointerSection(O, Section, sect, sect_size, sect_addr,
1007 case MachO::S_MOD_INIT_FUNC_POINTERS:
1008 case MachO::S_MOD_TERM_FUNC_POINTERS:
1009 DumpInitTermPointerSection(O, sect, sect_size, sect_addr, &AddrMap,
1013 outs() << "Unknown section type ("
1014 << format("0x%08" PRIx32, section_type) << ")\n";
1015 DumpRawSectionContents(O, sect, sect_size, sect_addr);
1019 if (section_type == MachO::S_ZEROFILL)
1020 outs() << "zerofill section and has no contents in the file\n";
1022 DumpRawSectionContents(O, sect, sect_size, sect_addr);
1029 // checkMachOAndArchFlags() checks to see if the ObjectFile is a Mach-O file
1030 // and if it is and there is a list of architecture flags is specified then
1031 // check to make sure this Mach-O file is one of those architectures or all
1032 // architectures were specified. If not then an error is generated and this
1033 // routine returns false. Else it returns true.
1034 static bool checkMachOAndArchFlags(ObjectFile *O, StringRef Filename) {
1035 if (isa<MachOObjectFile>(O) && !ArchAll && ArchFlags.size() != 0) {
1036 MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(O);
1037 bool ArchFound = false;
1038 MachO::mach_header H;
1039 MachO::mach_header_64 H_64;
1041 if (MachO->is64Bit()) {
1042 H_64 = MachO->MachOObjectFile::getHeader64();
1043 T = MachOObjectFile::getArch(H_64.cputype, H_64.cpusubtype);
1045 H = MachO->MachOObjectFile::getHeader();
1046 T = MachOObjectFile::getArch(H.cputype, H.cpusubtype);
1049 for (i = 0; i < ArchFlags.size(); ++i) {
1050 if (ArchFlags[i] == T.getArchName())
1055 errs() << "llvm-objdump: file: " + Filename + " does not contain "
1056 << "architecture: " + ArchFlags[i] + "\n";
1063 // ProcessMachO() is passed a single opened Mach-O file, which may be an
1064 // archive member and or in a slice of a universal file. It prints the
1065 // the file name and header info and then processes it according to the
1066 // command line options.
1067 static void ProcessMachO(StringRef Filename, MachOObjectFile *MachOOF,
1068 StringRef ArchiveMemberName = StringRef(),
1069 StringRef ArchitectureName = StringRef()) {
1070 // If we are doing some processing here on the Mach-O file print the header
1071 // info. And don't print it otherwise like in the case of printing the
1072 // UniversalHeaders or ArchiveHeaders.
1073 if (Disassemble || PrivateHeaders || ExportsTrie || Rebase || Bind ||
1074 LazyBind || WeakBind || IndirectSymbols || DataInCode || LinkOptHints ||
1075 DumpSections.size() != 0) {
1077 if (!ArchiveMemberName.empty())
1078 outs() << '(' << ArchiveMemberName << ')';
1079 if (!ArchitectureName.empty())
1080 outs() << " (architecture " << ArchitectureName << ")";
1085 DisassembleMachO(Filename, MachOOF, "__TEXT", "__text");
1086 if (IndirectSymbols)
1087 PrintIndirectSymbols(MachOOF, true);
1089 PrintDataInCodeTable(MachOOF, true);
1091 PrintLinkOptHints(MachOOF);
1093 PrintRelocations(MachOOF);
1095 PrintSectionHeaders(MachOOF);
1096 if (SectionContents)
1097 PrintSectionContents(MachOOF);
1098 if (DumpSections.size() != 0)
1099 DumpSectionContents(Filename, MachOOF, true);
1101 PrintSymbolTable(MachOOF);
1103 printMachOUnwindInfo(MachOOF);
1105 printMachOFileHeader(MachOOF);
1107 printExportsTrie(MachOOF);
1109 printRebaseTable(MachOOF);
1111 printBindTable(MachOOF);
1113 printLazyBindTable(MachOOF);
1115 printWeakBindTable(MachOOF);
1118 // printUnknownCPUType() helps print_fat_headers for unknown CPU's.
1119 static void printUnknownCPUType(uint32_t cputype, uint32_t cpusubtype) {
1120 outs() << " cputype (" << cputype << ")\n";
1121 outs() << " cpusubtype (" << cpusubtype << ")\n";
1124 // printCPUType() helps print_fat_headers by printing the cputype and
1125 // pusubtype (symbolically for the one's it knows about).
1126 static void printCPUType(uint32_t cputype, uint32_t cpusubtype) {
1128 case MachO::CPU_TYPE_I386:
1129 switch (cpusubtype) {
1130 case MachO::CPU_SUBTYPE_I386_ALL:
1131 outs() << " cputype CPU_TYPE_I386\n";
1132 outs() << " cpusubtype CPU_SUBTYPE_I386_ALL\n";
1135 printUnknownCPUType(cputype, cpusubtype);
1139 case MachO::CPU_TYPE_X86_64:
1140 switch (cpusubtype) {
1141 case MachO::CPU_SUBTYPE_X86_64_ALL:
1142 outs() << " cputype CPU_TYPE_X86_64\n";
1143 outs() << " cpusubtype CPU_SUBTYPE_X86_64_ALL\n";
1145 case MachO::CPU_SUBTYPE_X86_64_H:
1146 outs() << " cputype CPU_TYPE_X86_64\n";
1147 outs() << " cpusubtype CPU_SUBTYPE_X86_64_H\n";
1150 printUnknownCPUType(cputype, cpusubtype);
1154 case MachO::CPU_TYPE_ARM:
1155 switch (cpusubtype) {
1156 case MachO::CPU_SUBTYPE_ARM_ALL:
1157 outs() << " cputype CPU_TYPE_ARM\n";
1158 outs() << " cpusubtype CPU_SUBTYPE_ARM_ALL\n";
1160 case MachO::CPU_SUBTYPE_ARM_V4T:
1161 outs() << " cputype CPU_TYPE_ARM\n";
1162 outs() << " cpusubtype CPU_SUBTYPE_ARM_V4T\n";
1164 case MachO::CPU_SUBTYPE_ARM_V5TEJ:
1165 outs() << " cputype CPU_TYPE_ARM\n";
1166 outs() << " cpusubtype CPU_SUBTYPE_ARM_V5TEJ\n";
1168 case MachO::CPU_SUBTYPE_ARM_XSCALE:
1169 outs() << " cputype CPU_TYPE_ARM\n";
1170 outs() << " cpusubtype CPU_SUBTYPE_ARM_XSCALE\n";
1172 case MachO::CPU_SUBTYPE_ARM_V6:
1173 outs() << " cputype CPU_TYPE_ARM\n";
1174 outs() << " cpusubtype CPU_SUBTYPE_ARM_V6\n";
1176 case MachO::CPU_SUBTYPE_ARM_V6M:
1177 outs() << " cputype CPU_TYPE_ARM\n";
1178 outs() << " cpusubtype CPU_SUBTYPE_ARM_V6M\n";
1180 case MachO::CPU_SUBTYPE_ARM_V7:
1181 outs() << " cputype CPU_TYPE_ARM\n";
1182 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7\n";
1184 case MachO::CPU_SUBTYPE_ARM_V7EM:
1185 outs() << " cputype CPU_TYPE_ARM\n";
1186 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7EM\n";
1188 case MachO::CPU_SUBTYPE_ARM_V7K:
1189 outs() << " cputype CPU_TYPE_ARM\n";
1190 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7K\n";
1192 case MachO::CPU_SUBTYPE_ARM_V7M:
1193 outs() << " cputype CPU_TYPE_ARM\n";
1194 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7M\n";
1196 case MachO::CPU_SUBTYPE_ARM_V7S:
1197 outs() << " cputype CPU_TYPE_ARM\n";
1198 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7S\n";
1201 printUnknownCPUType(cputype, cpusubtype);
1205 case MachO::CPU_TYPE_ARM64:
1206 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
1207 case MachO::CPU_SUBTYPE_ARM64_ALL:
1208 outs() << " cputype CPU_TYPE_ARM64\n";
1209 outs() << " cpusubtype CPU_SUBTYPE_ARM64_ALL\n";
1212 printUnknownCPUType(cputype, cpusubtype);
1217 printUnknownCPUType(cputype, cpusubtype);
1222 static void printMachOUniversalHeaders(const object::MachOUniversalBinary *UB,
1224 outs() << "Fat headers\n";
1226 outs() << "fat_magic FAT_MAGIC\n";
1228 outs() << "fat_magic " << format("0x%" PRIx32, MachO::FAT_MAGIC) << "\n";
1230 uint32_t nfat_arch = UB->getNumberOfObjects();
1231 StringRef Buf = UB->getData();
1232 uint64_t size = Buf.size();
1233 uint64_t big_size = sizeof(struct MachO::fat_header) +
1234 nfat_arch * sizeof(struct MachO::fat_arch);
1235 outs() << "nfat_arch " << UB->getNumberOfObjects();
1237 outs() << " (malformed, contains zero architecture types)\n";
1238 else if (big_size > size)
1239 outs() << " (malformed, architectures past end of file)\n";
1243 for (uint32_t i = 0; i < nfat_arch; ++i) {
1244 MachOUniversalBinary::ObjectForArch OFA(UB, i);
1245 uint32_t cputype = OFA.getCPUType();
1246 uint32_t cpusubtype = OFA.getCPUSubType();
1247 outs() << "architecture ";
1248 for (uint32_t j = 0; i != 0 && j <= i - 1; j++) {
1249 MachOUniversalBinary::ObjectForArch other_OFA(UB, j);
1250 uint32_t other_cputype = other_OFA.getCPUType();
1251 uint32_t other_cpusubtype = other_OFA.getCPUSubType();
1252 if (cputype != 0 && cpusubtype != 0 && cputype == other_cputype &&
1253 (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) ==
1254 (other_cpusubtype & ~MachO::CPU_SUBTYPE_MASK)) {
1255 outs() << "(illegal duplicate architecture) ";
1260 outs() << OFA.getArchTypeName() << "\n";
1261 printCPUType(cputype, cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
1263 outs() << i << "\n";
1264 outs() << " cputype " << cputype << "\n";
1265 outs() << " cpusubtype " << (cpusubtype & ~MachO::CPU_SUBTYPE_MASK)
1269 (cpusubtype & MachO::CPU_SUBTYPE_MASK) == MachO::CPU_SUBTYPE_LIB64)
1270 outs() << " capabilities CPU_SUBTYPE_LIB64\n";
1272 outs() << " capabilities "
1273 << format("0x%" PRIx32,
1274 (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24) << "\n";
1275 outs() << " offset " << OFA.getOffset();
1276 if (OFA.getOffset() > size)
1277 outs() << " (past end of file)";
1278 if (OFA.getOffset() % (1 << OFA.getAlign()) != 0)
1279 outs() << " (not aligned on it's alignment (2^" << OFA.getAlign() << ")";
1281 outs() << " size " << OFA.getSize();
1282 big_size = OFA.getOffset() + OFA.getSize();
1283 if (big_size > size)
1284 outs() << " (past end of file)";
1286 outs() << " align 2^" << OFA.getAlign() << " (" << (1 << OFA.getAlign())
1291 static void printArchiveChild(Archive::Child &C, bool verbose,
1292 bool print_offset) {
1294 outs() << C.getChildOffset() << "\t";
1295 sys::fs::perms Mode = C.getAccessMode();
1297 // FIXME: this first dash, "-", is for (Mode & S_IFMT) == S_IFREG.
1298 // But there is nothing in sys::fs::perms for S_IFMT or S_IFREG.
1300 if (Mode & sys::fs::owner_read)
1304 if (Mode & sys::fs::owner_write)
1308 if (Mode & sys::fs::owner_exe)
1312 if (Mode & sys::fs::group_read)
1316 if (Mode & sys::fs::group_write)
1320 if (Mode & sys::fs::group_exe)
1324 if (Mode & sys::fs::others_read)
1328 if (Mode & sys::fs::others_write)
1332 if (Mode & sys::fs::others_exe)
1337 outs() << format("0%o ", Mode);
1340 unsigned UID = C.getUID();
1341 outs() << format("%3d/", UID);
1342 unsigned GID = C.getGID();
1343 outs() << format("%-3d ", GID);
1344 uint64_t Size = C.getRawSize();
1345 outs() << format("%5" PRId64, Size) << " ";
1347 StringRef RawLastModified = C.getRawLastModified();
1350 if (RawLastModified.getAsInteger(10, Seconds))
1351 outs() << "(date: \"%s\" contains non-decimal chars) " << RawLastModified;
1353 // Since cime(3) returns a 26 character string of the form:
1354 // "Sun Sep 16 01:03:52 1973\n\0"
1355 // just print 24 characters.
1357 outs() << format("%.24s ", ctime(&t));
1360 outs() << RawLastModified << " ";
1364 ErrorOr<StringRef> NameOrErr = C.getName();
1365 if (NameOrErr.getError()) {
1366 StringRef RawName = C.getRawName();
1367 outs() << RawName << "\n";
1369 StringRef Name = NameOrErr.get();
1370 outs() << Name << "\n";
1373 StringRef RawName = C.getRawName();
1374 outs() << RawName << "\n";
1378 static void printArchiveHeaders(Archive *A, bool verbose, bool print_offset) {
1379 if (A->hasSymbolTable()) {
1380 Archive::child_iterator S = A->getSymbolTableChild();
1381 Archive::Child C = *S;
1382 printArchiveChild(C, verbose, print_offset);
1384 for (Archive::child_iterator I = A->child_begin(), E = A->child_end(); I != E;
1386 Archive::Child C = *I;
1387 printArchiveChild(C, verbose, print_offset);
1391 // ParseInputMachO() parses the named Mach-O file in Filename and handles the
1392 // -arch flags selecting just those slices as specified by them and also parses
1393 // archive files. Then for each individual Mach-O file ProcessMachO() is
1394 // called to process the file based on the command line options.
1395 void llvm::ParseInputMachO(StringRef Filename) {
1396 // Check for -arch all and verifiy the -arch flags are valid.
1397 for (unsigned i = 0; i < ArchFlags.size(); ++i) {
1398 if (ArchFlags[i] == "all") {
1401 if (!MachOObjectFile::isValidArch(ArchFlags[i])) {
1402 errs() << "llvm-objdump: Unknown architecture named '" + ArchFlags[i] +
1403 "'for the -arch option\n";
1409 // Attempt to open the binary.
1410 ErrorOr<OwningBinary<Binary>> BinaryOrErr = createBinary(Filename);
1411 if (std::error_code EC = BinaryOrErr.getError()) {
1412 errs() << "llvm-objdump: '" << Filename << "': " << EC.message() << ".\n";
1415 Binary &Bin = *BinaryOrErr.get().getBinary();
1417 if (Archive *A = dyn_cast<Archive>(&Bin)) {
1418 outs() << "Archive : " << Filename << "\n";
1420 printArchiveHeaders(A, true, false);
1421 for (Archive::child_iterator I = A->child_begin(), E = A->child_end();
1423 ErrorOr<std::unique_ptr<Binary>> ChildOrErr = I->getAsBinary();
1424 if (ChildOrErr.getError())
1426 if (MachOObjectFile *O = dyn_cast<MachOObjectFile>(&*ChildOrErr.get())) {
1427 if (!checkMachOAndArchFlags(O, Filename))
1429 ProcessMachO(Filename, O, O->getFileName());
1434 if (UniversalHeaders) {
1435 if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(&Bin))
1436 printMachOUniversalHeaders(UB, true);
1438 if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(&Bin)) {
1439 // If we have a list of architecture flags specified dump only those.
1440 if (!ArchAll && ArchFlags.size() != 0) {
1441 // Look for a slice in the universal binary that matches each ArchFlag.
1443 for (unsigned i = 0; i < ArchFlags.size(); ++i) {
1445 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
1446 E = UB->end_objects();
1448 if (ArchFlags[i] == I->getArchTypeName()) {
1450 ErrorOr<std::unique_ptr<ObjectFile>> ObjOrErr =
1451 I->getAsObjectFile();
1452 std::string ArchitectureName = "";
1453 if (ArchFlags.size() > 1)
1454 ArchitectureName = I->getArchTypeName();
1456 ObjectFile &O = *ObjOrErr.get();
1457 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&O))
1458 ProcessMachO(Filename, MachOOF, "", ArchitectureName);
1459 } else if (ErrorOr<std::unique_ptr<Archive>> AOrErr =
1460 I->getAsArchive()) {
1461 std::unique_ptr<Archive> &A = *AOrErr;
1462 outs() << "Archive : " << Filename;
1463 if (!ArchitectureName.empty())
1464 outs() << " (architecture " << ArchitectureName << ")";
1467 printArchiveHeaders(A.get(), true, false);
1468 for (Archive::child_iterator AI = A->child_begin(),
1469 AE = A->child_end();
1471 ErrorOr<std::unique_ptr<Binary>> ChildOrErr = AI->getAsBinary();
1472 if (ChildOrErr.getError())
1474 if (MachOObjectFile *O =
1475 dyn_cast<MachOObjectFile>(&*ChildOrErr.get()))
1476 ProcessMachO(Filename, O, O->getFileName(), ArchitectureName);
1482 errs() << "llvm-objdump: file: " + Filename + " does not contain "
1483 << "architecture: " + ArchFlags[i] + "\n";
1489 // No architecture flags were specified so if this contains a slice that
1490 // matches the host architecture dump only that.
1492 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
1493 E = UB->end_objects();
1495 if (MachOObjectFile::getHostArch().getArchName() ==
1496 I->getArchTypeName()) {
1497 ErrorOr<std::unique_ptr<ObjectFile>> ObjOrErr = I->getAsObjectFile();
1498 std::string ArchiveName;
1499 ArchiveName.clear();
1501 ObjectFile &O = *ObjOrErr.get();
1502 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&O))
1503 ProcessMachO(Filename, MachOOF);
1504 } else if (ErrorOr<std::unique_ptr<Archive>> AOrErr =
1505 I->getAsArchive()) {
1506 std::unique_ptr<Archive> &A = *AOrErr;
1507 outs() << "Archive : " << Filename << "\n";
1509 printArchiveHeaders(A.get(), true, false);
1510 for (Archive::child_iterator AI = A->child_begin(),
1511 AE = A->child_end();
1513 ErrorOr<std::unique_ptr<Binary>> ChildOrErr = AI->getAsBinary();
1514 if (ChildOrErr.getError())
1516 if (MachOObjectFile *O =
1517 dyn_cast<MachOObjectFile>(&*ChildOrErr.get()))
1518 ProcessMachO(Filename, O, O->getFileName());
1525 // Either all architectures have been specified or none have been specified
1526 // and this does not contain the host architecture so dump all the slices.
1527 bool moreThanOneArch = UB->getNumberOfObjects() > 1;
1528 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
1529 E = UB->end_objects();
1531 ErrorOr<std::unique_ptr<ObjectFile>> ObjOrErr = I->getAsObjectFile();
1532 std::string ArchitectureName = "";
1533 if (moreThanOneArch)
1534 ArchitectureName = I->getArchTypeName();
1536 ObjectFile &Obj = *ObjOrErr.get();
1537 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&Obj))
1538 ProcessMachO(Filename, MachOOF, "", ArchitectureName);
1539 } else if (ErrorOr<std::unique_ptr<Archive>> AOrErr = I->getAsArchive()) {
1540 std::unique_ptr<Archive> &A = *AOrErr;
1541 outs() << "Archive : " << Filename;
1542 if (!ArchitectureName.empty())
1543 outs() << " (architecture " << ArchitectureName << ")";
1546 printArchiveHeaders(A.get(), true, false);
1547 for (Archive::child_iterator AI = A->child_begin(), AE = A->child_end();
1549 ErrorOr<std::unique_ptr<Binary>> ChildOrErr = AI->getAsBinary();
1550 if (ChildOrErr.getError())
1552 if (MachOObjectFile *O =
1553 dyn_cast<MachOObjectFile>(&*ChildOrErr.get())) {
1554 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(O))
1555 ProcessMachO(Filename, MachOOF, MachOOF->getFileName(),
1563 if (ObjectFile *O = dyn_cast<ObjectFile>(&Bin)) {
1564 if (!checkMachOAndArchFlags(O, Filename))
1566 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&*O)) {
1567 ProcessMachO(Filename, MachOOF);
1569 errs() << "llvm-objdump: '" << Filename << "': "
1570 << "Object is not a Mach-O file type.\n";
1572 errs() << "llvm-objdump: '" << Filename << "': "
1573 << "Unrecognized file type.\n";
1576 typedef std::pair<uint64_t, const char *> BindInfoEntry;
1577 typedef std::vector<BindInfoEntry> BindTable;
1578 typedef BindTable::iterator bind_table_iterator;
1580 // The block of info used by the Symbolizer call backs.
1581 struct DisassembleInfo {
1585 SymbolAddressMap *AddrMap;
1586 std::vector<SectionRef> *Sections;
1587 const char *class_name;
1588 const char *selector_name;
1590 char *demangled_name;
1593 BindTable *bindtable;
1596 // SymbolizerGetOpInfo() is the operand information call back function.
1597 // This is called to get the symbolic information for operand(s) of an
1598 // instruction when it is being done. This routine does this from
1599 // the relocation information, symbol table, etc. That block of information
1600 // is a pointer to the struct DisassembleInfo that was passed when the
1601 // disassembler context was created and passed to back to here when
1602 // called back by the disassembler for instruction operands that could have
1603 // relocation information. The address of the instruction containing operand is
1604 // at the Pc parameter. The immediate value the operand has is passed in
1605 // op_info->Value and is at Offset past the start of the instruction and has a
1606 // byte Size of 1, 2 or 4. The symbolc information is returned in TagBuf is the
1607 // LLVMOpInfo1 struct defined in the header "llvm-c/Disassembler.h" as symbol
1608 // names and addends of the symbolic expression to add for the operand. The
1609 // value of TagType is currently 1 (for the LLVMOpInfo1 struct). If symbolic
1610 // information is returned then this function returns 1 else it returns 0.
1611 static int SymbolizerGetOpInfo(void *DisInfo, uint64_t Pc, uint64_t Offset,
1612 uint64_t Size, int TagType, void *TagBuf) {
1613 struct DisassembleInfo *info = (struct DisassembleInfo *)DisInfo;
1614 struct LLVMOpInfo1 *op_info = (struct LLVMOpInfo1 *)TagBuf;
1615 uint64_t value = op_info->Value;
1617 // Make sure all fields returned are zero if we don't set them.
1618 memset((void *)op_info, '\0', sizeof(struct LLVMOpInfo1));
1619 op_info->Value = value;
1621 // If the TagType is not the value 1 which it code knows about or if no
1622 // verbose symbolic information is wanted then just return 0, indicating no
1623 // information is being returned.
1624 if (TagType != 1 || info->verbose == false)
1627 unsigned int Arch = info->O->getArch();
1628 if (Arch == Triple::x86) {
1629 if (Size != 1 && Size != 2 && Size != 4 && Size != 0)
1631 // First search the section's relocation entries (if any) for an entry
1632 // for this section offset.
1633 uint32_t sect_addr = info->S.getAddress();
1634 uint32_t sect_offset = (Pc + Offset) - sect_addr;
1635 bool reloc_found = false;
1637 MachO::any_relocation_info RE;
1638 bool isExtern = false;
1640 bool r_scattered = false;
1641 uint32_t r_value, pair_r_value, r_type;
1642 for (const RelocationRef &Reloc : info->S.relocations()) {
1643 uint64_t RelocOffset;
1644 Reloc.getOffset(RelocOffset);
1645 if (RelocOffset == sect_offset) {
1646 Rel = Reloc.getRawDataRefImpl();
1647 RE = info->O->getRelocation(Rel);
1648 r_type = info->O->getAnyRelocationType(RE);
1649 r_scattered = info->O->isRelocationScattered(RE);
1651 r_value = info->O->getScatteredRelocationValue(RE);
1652 if (r_type == MachO::GENERIC_RELOC_SECTDIFF ||
1653 r_type == MachO::GENERIC_RELOC_LOCAL_SECTDIFF) {
1654 DataRefImpl RelNext = Rel;
1655 info->O->moveRelocationNext(RelNext);
1656 MachO::any_relocation_info RENext;
1657 RENext = info->O->getRelocation(RelNext);
1658 if (info->O->isRelocationScattered(RENext))
1659 pair_r_value = info->O->getScatteredRelocationValue(RENext);
1664 isExtern = info->O->getPlainRelocationExternal(RE);
1666 symbol_iterator RelocSym = Reloc.getSymbol();
1674 if (reloc_found && isExtern) {
1676 Symbol.getName(SymName);
1677 const char *name = SymName.data();
1678 op_info->AddSymbol.Present = 1;
1679 op_info->AddSymbol.Name = name;
1680 // For i386 extern relocation entries the value in the instruction is
1681 // the offset from the symbol, and value is already set in op_info->Value.
1684 if (reloc_found && (r_type == MachO::GENERIC_RELOC_SECTDIFF ||
1685 r_type == MachO::GENERIC_RELOC_LOCAL_SECTDIFF)) {
1686 const char *add = GuessSymbolName(r_value, info->AddrMap);
1687 const char *sub = GuessSymbolName(pair_r_value, info->AddrMap);
1688 uint32_t offset = value - (r_value - pair_r_value);
1689 op_info->AddSymbol.Present = 1;
1691 op_info->AddSymbol.Name = add;
1693 op_info->AddSymbol.Value = r_value;
1694 op_info->SubtractSymbol.Present = 1;
1696 op_info->SubtractSymbol.Name = sub;
1698 op_info->SubtractSymbol.Value = pair_r_value;
1699 op_info->Value = offset;
1703 // Second search the external relocation entries of a fully linked image
1704 // (if any) for an entry that matches this segment offset.
1705 // uint32_t seg_offset = (Pc + Offset);
1707 } else if (Arch == Triple::x86_64) {
1708 if (Size != 1 && Size != 2 && Size != 4 && Size != 0)
1710 // First search the section's relocation entries (if any) for an entry
1711 // for this section offset.
1712 uint64_t sect_addr = info->S.getAddress();
1713 uint64_t sect_offset = (Pc + Offset) - sect_addr;
1714 bool reloc_found = false;
1716 MachO::any_relocation_info RE;
1717 bool isExtern = false;
1719 for (const RelocationRef &Reloc : info->S.relocations()) {
1720 uint64_t RelocOffset;
1721 Reloc.getOffset(RelocOffset);
1722 if (RelocOffset == sect_offset) {
1723 Rel = Reloc.getRawDataRefImpl();
1724 RE = info->O->getRelocation(Rel);
1725 // NOTE: Scattered relocations don't exist on x86_64.
1726 isExtern = info->O->getPlainRelocationExternal(RE);
1728 symbol_iterator RelocSym = Reloc.getSymbol();
1735 if (reloc_found && isExtern) {
1736 // The Value passed in will be adjusted by the Pc if the instruction
1737 // adds the Pc. But for x86_64 external relocation entries the Value
1738 // is the offset from the external symbol.
1739 if (info->O->getAnyRelocationPCRel(RE))
1740 op_info->Value -= Pc + Offset + Size;
1742 Symbol.getName(SymName);
1743 const char *name = SymName.data();
1744 unsigned Type = info->O->getAnyRelocationType(RE);
1745 if (Type == MachO::X86_64_RELOC_SUBTRACTOR) {
1746 DataRefImpl RelNext = Rel;
1747 info->O->moveRelocationNext(RelNext);
1748 MachO::any_relocation_info RENext = info->O->getRelocation(RelNext);
1749 unsigned TypeNext = info->O->getAnyRelocationType(RENext);
1750 bool isExternNext = info->O->getPlainRelocationExternal(RENext);
1751 unsigned SymbolNum = info->O->getPlainRelocationSymbolNum(RENext);
1752 if (TypeNext == MachO::X86_64_RELOC_UNSIGNED && isExternNext) {
1753 op_info->SubtractSymbol.Present = 1;
1754 op_info->SubtractSymbol.Name = name;
1755 symbol_iterator RelocSymNext = info->O->getSymbolByIndex(SymbolNum);
1756 Symbol = *RelocSymNext;
1757 StringRef SymNameNext;
1758 Symbol.getName(SymNameNext);
1759 name = SymNameNext.data();
1762 // TODO: add the VariantKinds to op_info->VariantKind for relocation types
1763 // like: X86_64_RELOC_TLV, X86_64_RELOC_GOT_LOAD and X86_64_RELOC_GOT.
1764 op_info->AddSymbol.Present = 1;
1765 op_info->AddSymbol.Name = name;
1769 // Second search the external relocation entries of a fully linked image
1770 // (if any) for an entry that matches this segment offset.
1771 // uint64_t seg_offset = (Pc + Offset);
1773 } else if (Arch == Triple::arm) {
1774 if (Offset != 0 || (Size != 4 && Size != 2))
1776 // First search the section's relocation entries (if any) for an entry
1777 // for this section offset.
1778 uint32_t sect_addr = info->S.getAddress();
1779 uint32_t sect_offset = (Pc + Offset) - sect_addr;
1780 bool reloc_found = false;
1782 MachO::any_relocation_info RE;
1783 bool isExtern = false;
1785 bool r_scattered = false;
1786 uint32_t r_value, pair_r_value, r_type, r_length, other_half;
1787 for (const RelocationRef &Reloc : info->S.relocations()) {
1788 uint64_t RelocOffset;
1789 Reloc.getOffset(RelocOffset);
1790 if (RelocOffset == sect_offset) {
1791 Rel = Reloc.getRawDataRefImpl();
1792 RE = info->O->getRelocation(Rel);
1793 r_length = info->O->getAnyRelocationLength(RE);
1794 r_scattered = info->O->isRelocationScattered(RE);
1796 r_value = info->O->getScatteredRelocationValue(RE);
1797 r_type = info->O->getScatteredRelocationType(RE);
1799 r_type = info->O->getAnyRelocationType(RE);
1800 isExtern = info->O->getPlainRelocationExternal(RE);
1802 symbol_iterator RelocSym = Reloc.getSymbol();
1806 if (r_type == MachO::ARM_RELOC_HALF ||
1807 r_type == MachO::ARM_RELOC_SECTDIFF ||
1808 r_type == MachO::ARM_RELOC_LOCAL_SECTDIFF ||
1809 r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
1810 DataRefImpl RelNext = Rel;
1811 info->O->moveRelocationNext(RelNext);
1812 MachO::any_relocation_info RENext;
1813 RENext = info->O->getRelocation(RelNext);
1814 other_half = info->O->getAnyRelocationAddress(RENext) & 0xffff;
1815 if (info->O->isRelocationScattered(RENext))
1816 pair_r_value = info->O->getScatteredRelocationValue(RENext);
1822 if (reloc_found && isExtern) {
1824 Symbol.getName(SymName);
1825 const char *name = SymName.data();
1826 op_info->AddSymbol.Present = 1;
1827 op_info->AddSymbol.Name = name;
1829 case MachO::ARM_RELOC_HALF:
1830 if ((r_length & 0x1) == 1) {
1831 op_info->Value = value << 16 | other_half;
1832 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
1834 op_info->Value = other_half << 16 | value;
1835 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
1843 // If we have a branch that is not an external relocation entry then
1844 // return 0 so the code in tryAddingSymbolicOperand() can use the
1845 // SymbolLookUp call back with the branch target address to look up the
1846 // symbol and possiblity add an annotation for a symbol stub.
1847 if (reloc_found && isExtern == 0 && (r_type == MachO::ARM_RELOC_BR24 ||
1848 r_type == MachO::ARM_THUMB_RELOC_BR22))
1851 uint32_t offset = 0;
1853 if (r_type == MachO::ARM_RELOC_HALF ||
1854 r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
1855 if ((r_length & 0x1) == 1)
1856 value = value << 16 | other_half;
1858 value = other_half << 16 | value;
1860 if (r_scattered && (r_type != MachO::ARM_RELOC_HALF &&
1861 r_type != MachO::ARM_RELOC_HALF_SECTDIFF)) {
1862 offset = value - r_value;
1867 if (reloc_found && r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
1868 if ((r_length & 0x1) == 1)
1869 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
1871 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
1872 const char *add = GuessSymbolName(r_value, info->AddrMap);
1873 const char *sub = GuessSymbolName(pair_r_value, info->AddrMap);
1874 int32_t offset = value - (r_value - pair_r_value);
1875 op_info->AddSymbol.Present = 1;
1877 op_info->AddSymbol.Name = add;
1879 op_info->AddSymbol.Value = r_value;
1880 op_info->SubtractSymbol.Present = 1;
1882 op_info->SubtractSymbol.Name = sub;
1884 op_info->SubtractSymbol.Value = pair_r_value;
1885 op_info->Value = offset;
1889 if (reloc_found == false)
1892 op_info->AddSymbol.Present = 1;
1893 op_info->Value = offset;
1895 if (r_type == MachO::ARM_RELOC_HALF) {
1896 if ((r_length & 0x1) == 1)
1897 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
1899 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
1902 const char *add = GuessSymbolName(value, info->AddrMap);
1903 if (add != nullptr) {
1904 op_info->AddSymbol.Name = add;
1907 op_info->AddSymbol.Value = value;
1909 } else if (Arch == Triple::aarch64) {
1910 if (Offset != 0 || Size != 4)
1912 // First search the section's relocation entries (if any) for an entry
1913 // for this section offset.
1914 uint64_t sect_addr = info->S.getAddress();
1915 uint64_t sect_offset = (Pc + Offset) - sect_addr;
1916 bool reloc_found = false;
1918 MachO::any_relocation_info RE;
1919 bool isExtern = false;
1921 uint32_t r_type = 0;
1922 for (const RelocationRef &Reloc : info->S.relocations()) {
1923 uint64_t RelocOffset;
1924 Reloc.getOffset(RelocOffset);
1925 if (RelocOffset == sect_offset) {
1926 Rel = Reloc.getRawDataRefImpl();
1927 RE = info->O->getRelocation(Rel);
1928 r_type = info->O->getAnyRelocationType(RE);
1929 if (r_type == MachO::ARM64_RELOC_ADDEND) {
1930 DataRefImpl RelNext = Rel;
1931 info->O->moveRelocationNext(RelNext);
1932 MachO::any_relocation_info RENext = info->O->getRelocation(RelNext);
1934 value = info->O->getPlainRelocationSymbolNum(RENext);
1935 op_info->Value = value;
1938 // NOTE: Scattered relocations don't exist on arm64.
1939 isExtern = info->O->getPlainRelocationExternal(RE);
1941 symbol_iterator RelocSym = Reloc.getSymbol();
1948 if (reloc_found && isExtern) {
1950 Symbol.getName(SymName);
1951 const char *name = SymName.data();
1952 op_info->AddSymbol.Present = 1;
1953 op_info->AddSymbol.Name = name;
1956 case MachO::ARM64_RELOC_PAGE21:
1958 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_PAGE;
1960 case MachO::ARM64_RELOC_PAGEOFF12:
1962 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_PAGEOFF;
1964 case MachO::ARM64_RELOC_GOT_LOAD_PAGE21:
1966 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_GOTPAGE;
1968 case MachO::ARM64_RELOC_GOT_LOAD_PAGEOFF12:
1970 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_GOTPAGEOFF;
1972 case MachO::ARM64_RELOC_TLVP_LOAD_PAGE21:
1973 /* @tvlppage is not implemented in llvm-mc */
1974 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_TLVP;
1976 case MachO::ARM64_RELOC_TLVP_LOAD_PAGEOFF12:
1977 /* @tvlppageoff is not implemented in llvm-mc */
1978 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_TLVOFF;
1981 case MachO::ARM64_RELOC_BRANCH26:
1982 op_info->VariantKind = LLVMDisassembler_VariantKind_None;
1993 // GuessCstringPointer is passed the address of what might be a pointer to a
1994 // literal string in a cstring section. If that address is in a cstring section
1995 // it returns a pointer to that string. Else it returns nullptr.
1996 static const char *GuessCstringPointer(uint64_t ReferenceValue,
1997 struct DisassembleInfo *info) {
1998 uint32_t LoadCommandCount = info->O->getHeader().ncmds;
1999 MachOObjectFile::LoadCommandInfo Load = info->O->getFirstLoadCommandInfo();
2000 for (unsigned I = 0;; ++I) {
2001 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
2002 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
2003 for (unsigned J = 0; J < Seg.nsects; ++J) {
2004 MachO::section_64 Sec = info->O->getSection64(Load, J);
2005 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
2006 if (section_type == MachO::S_CSTRING_LITERALS &&
2007 ReferenceValue >= Sec.addr &&
2008 ReferenceValue < Sec.addr + Sec.size) {
2009 uint64_t sect_offset = ReferenceValue - Sec.addr;
2010 uint64_t object_offset = Sec.offset + sect_offset;
2011 StringRef MachOContents = info->O->getData();
2012 uint64_t object_size = MachOContents.size();
2013 const char *object_addr = (const char *)MachOContents.data();
2014 if (object_offset < object_size) {
2015 const char *name = object_addr + object_offset;
2022 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
2023 MachO::segment_command Seg = info->O->getSegmentLoadCommand(Load);
2024 for (unsigned J = 0; J < Seg.nsects; ++J) {
2025 MachO::section Sec = info->O->getSection(Load, J);
2026 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
2027 if (section_type == MachO::S_CSTRING_LITERALS &&
2028 ReferenceValue >= Sec.addr &&
2029 ReferenceValue < Sec.addr + Sec.size) {
2030 uint64_t sect_offset = ReferenceValue - Sec.addr;
2031 uint64_t object_offset = Sec.offset + sect_offset;
2032 StringRef MachOContents = info->O->getData();
2033 uint64_t object_size = MachOContents.size();
2034 const char *object_addr = (const char *)MachOContents.data();
2035 if (object_offset < object_size) {
2036 const char *name = object_addr + object_offset;
2044 if (I == LoadCommandCount - 1)
2047 Load = info->O->getNextLoadCommandInfo(Load);
2052 // GuessIndirectSymbol returns the name of the indirect symbol for the
2053 // ReferenceValue passed in or nullptr. This is used when ReferenceValue maybe
2054 // an address of a symbol stub or a lazy or non-lazy pointer to associate the
2055 // symbol name being referenced by the stub or pointer.
2056 static const char *GuessIndirectSymbol(uint64_t ReferenceValue,
2057 struct DisassembleInfo *info) {
2058 uint32_t LoadCommandCount = info->O->getHeader().ncmds;
2059 MachOObjectFile::LoadCommandInfo Load = info->O->getFirstLoadCommandInfo();
2060 MachO::dysymtab_command Dysymtab = info->O->getDysymtabLoadCommand();
2061 MachO::symtab_command Symtab = info->O->getSymtabLoadCommand();
2062 for (unsigned I = 0;; ++I) {
2063 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
2064 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
2065 for (unsigned J = 0; J < Seg.nsects; ++J) {
2066 MachO::section_64 Sec = info->O->getSection64(Load, J);
2067 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
2068 if ((section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
2069 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
2070 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
2071 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
2072 section_type == MachO::S_SYMBOL_STUBS) &&
2073 ReferenceValue >= Sec.addr &&
2074 ReferenceValue < Sec.addr + Sec.size) {
2076 if (section_type == MachO::S_SYMBOL_STUBS)
2077 stride = Sec.reserved2;
2082 uint32_t index = Sec.reserved1 + (ReferenceValue - Sec.addr) / stride;
2083 if (index < Dysymtab.nindirectsyms) {
2084 uint32_t indirect_symbol =
2085 info->O->getIndirectSymbolTableEntry(Dysymtab, index);
2086 if (indirect_symbol < Symtab.nsyms) {
2087 symbol_iterator Sym = info->O->getSymbolByIndex(indirect_symbol);
2088 SymbolRef Symbol = *Sym;
2090 Symbol.getName(SymName);
2091 const char *name = SymName.data();
2097 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
2098 MachO::segment_command Seg = info->O->getSegmentLoadCommand(Load);
2099 for (unsigned J = 0; J < Seg.nsects; ++J) {
2100 MachO::section Sec = info->O->getSection(Load, J);
2101 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
2102 if ((section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
2103 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
2104 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
2105 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
2106 section_type == MachO::S_SYMBOL_STUBS) &&
2107 ReferenceValue >= Sec.addr &&
2108 ReferenceValue < Sec.addr + Sec.size) {
2110 if (section_type == MachO::S_SYMBOL_STUBS)
2111 stride = Sec.reserved2;
2116 uint32_t index = Sec.reserved1 + (ReferenceValue - Sec.addr) / stride;
2117 if (index < Dysymtab.nindirectsyms) {
2118 uint32_t indirect_symbol =
2119 info->O->getIndirectSymbolTableEntry(Dysymtab, index);
2120 if (indirect_symbol < Symtab.nsyms) {
2121 symbol_iterator Sym = info->O->getSymbolByIndex(indirect_symbol);
2122 SymbolRef Symbol = *Sym;
2124 Symbol.getName(SymName);
2125 const char *name = SymName.data();
2132 if (I == LoadCommandCount - 1)
2135 Load = info->O->getNextLoadCommandInfo(Load);
2140 // method_reference() is called passing it the ReferenceName that might be
2141 // a reference it to an Objective-C method call. If so then it allocates and
2142 // assembles a method call string with the values last seen and saved in
2143 // the DisassembleInfo's class_name and selector_name fields. This is saved
2144 // into the method field of the info and any previous string is free'ed.
2145 // Then the class_name field in the info is set to nullptr. The method call
2146 // string is set into ReferenceName and ReferenceType is set to
2147 // LLVMDisassembler_ReferenceType_Out_Objc_Message. If this not a method call
2148 // then both ReferenceType and ReferenceName are left unchanged.
2149 static void method_reference(struct DisassembleInfo *info,
2150 uint64_t *ReferenceType,
2151 const char **ReferenceName) {
2152 unsigned int Arch = info->O->getArch();
2153 if (*ReferenceName != nullptr) {
2154 if (strcmp(*ReferenceName, "_objc_msgSend") == 0) {
2155 if (info->selector_name != nullptr) {
2156 if (info->method != nullptr)
2158 if (info->class_name != nullptr) {
2159 info->method = (char *)malloc(5 + strlen(info->class_name) +
2160 strlen(info->selector_name));
2161 if (info->method != nullptr) {
2162 strcpy(info->method, "+[");
2163 strcat(info->method, info->class_name);
2164 strcat(info->method, " ");
2165 strcat(info->method, info->selector_name);
2166 strcat(info->method, "]");
2167 *ReferenceName = info->method;
2168 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
2171 info->method = (char *)malloc(9 + strlen(info->selector_name));
2172 if (info->method != nullptr) {
2173 if (Arch == Triple::x86_64)
2174 strcpy(info->method, "-[%rdi ");
2175 else if (Arch == Triple::aarch64)
2176 strcpy(info->method, "-[x0 ");
2178 strcpy(info->method, "-[r? ");
2179 strcat(info->method, info->selector_name);
2180 strcat(info->method, "]");
2181 *ReferenceName = info->method;
2182 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
2185 info->class_name = nullptr;
2187 } else if (strcmp(*ReferenceName, "_objc_msgSendSuper2") == 0) {
2188 if (info->selector_name != nullptr) {
2189 if (info->method != nullptr)
2191 info->method = (char *)malloc(17 + strlen(info->selector_name));
2192 if (info->method != nullptr) {
2193 if (Arch == Triple::x86_64)
2194 strcpy(info->method, "-[[%rdi super] ");
2195 else if (Arch == Triple::aarch64)
2196 strcpy(info->method, "-[[x0 super] ");
2198 strcpy(info->method, "-[[r? super] ");
2199 strcat(info->method, info->selector_name);
2200 strcat(info->method, "]");
2201 *ReferenceName = info->method;
2202 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
2204 info->class_name = nullptr;
2210 // GuessPointerPointer() is passed the address of what might be a pointer to
2211 // a reference to an Objective-C class, selector, message ref or cfstring.
2212 // If so the value of the pointer is returned and one of the booleans are set
2213 // to true. If not zero is returned and all the booleans are set to false.
2214 static uint64_t GuessPointerPointer(uint64_t ReferenceValue,
2215 struct DisassembleInfo *info,
2216 bool &classref, bool &selref, bool &msgref,
2222 uint32_t LoadCommandCount = info->O->getHeader().ncmds;
2223 MachOObjectFile::LoadCommandInfo Load = info->O->getFirstLoadCommandInfo();
2224 for (unsigned I = 0;; ++I) {
2225 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
2226 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
2227 for (unsigned J = 0; J < Seg.nsects; ++J) {
2228 MachO::section_64 Sec = info->O->getSection64(Load, J);
2229 if ((strncmp(Sec.sectname, "__objc_selrefs", 16) == 0 ||
2230 strncmp(Sec.sectname, "__objc_classrefs", 16) == 0 ||
2231 strncmp(Sec.sectname, "__objc_superrefs", 16) == 0 ||
2232 strncmp(Sec.sectname, "__objc_msgrefs", 16) == 0 ||
2233 strncmp(Sec.sectname, "__cfstring", 16) == 0) &&
2234 ReferenceValue >= Sec.addr &&
2235 ReferenceValue < Sec.addr + Sec.size) {
2236 uint64_t sect_offset = ReferenceValue - Sec.addr;
2237 uint64_t object_offset = Sec.offset + sect_offset;
2238 StringRef MachOContents = info->O->getData();
2239 uint64_t object_size = MachOContents.size();
2240 const char *object_addr = (const char *)MachOContents.data();
2241 if (object_offset < object_size) {
2242 uint64_t pointer_value;
2243 memcpy(&pointer_value, object_addr + object_offset,
2245 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
2246 sys::swapByteOrder(pointer_value);
2247 if (strncmp(Sec.sectname, "__objc_selrefs", 16) == 0)
2249 else if (strncmp(Sec.sectname, "__objc_classrefs", 16) == 0 ||
2250 strncmp(Sec.sectname, "__objc_superrefs", 16) == 0)
2252 else if (strncmp(Sec.sectname, "__objc_msgrefs", 16) == 0 &&
2253 ReferenceValue + 8 < Sec.addr + Sec.size) {
2255 memcpy(&pointer_value, object_addr + object_offset + 8,
2257 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
2258 sys::swapByteOrder(pointer_value);
2259 } else if (strncmp(Sec.sectname, "__cfstring", 16) == 0)
2261 return pointer_value;
2268 // TODO: Look for LC_SEGMENT for 32-bit Mach-O files.
2269 if (I == LoadCommandCount - 1)
2272 Load = info->O->getNextLoadCommandInfo(Load);
2277 // get_pointer_64 returns a pointer to the bytes in the object file at the
2278 // Address from a section in the Mach-O file. And indirectly returns the
2279 // offset into the section, number of bytes left in the section past the offset
2280 // and which section is was being referenced. If the Address is not in a
2281 // section nullptr is returned.
2282 static const char *get_pointer_64(uint64_t Address, uint32_t &offset,
2283 uint32_t &left, SectionRef &S,
2284 DisassembleInfo *info) {
2288 for (unsigned SectIdx = 0; SectIdx != info->Sections->size(); SectIdx++) {
2289 uint64_t SectAddress = ((*(info->Sections))[SectIdx]).getAddress();
2290 uint64_t SectSize = ((*(info->Sections))[SectIdx]).getSize();
2291 if (Address >= SectAddress && Address < SectAddress + SectSize) {
2292 S = (*(info->Sections))[SectIdx];
2293 offset = Address - SectAddress;
2294 left = SectSize - offset;
2295 StringRef SectContents;
2296 ((*(info->Sections))[SectIdx]).getContents(SectContents);
2297 return SectContents.data() + offset;
2303 // get_symbol_64() returns the name of a symbol (or nullptr) and the address of
2304 // the symbol indirectly through n_value. Based on the relocation information
2305 // for the specified section offset in the specified section reference.
2306 static const char *get_symbol_64(uint32_t sect_offset, SectionRef S,
2307 DisassembleInfo *info, uint64_t &n_value) {
2309 if (info->verbose == false)
2312 // See if there is an external relocation entry at the sect_offset.
2313 bool reloc_found = false;
2315 MachO::any_relocation_info RE;
2316 bool isExtern = false;
2318 for (const RelocationRef &Reloc : S.relocations()) {
2319 uint64_t RelocOffset;
2320 Reloc.getOffset(RelocOffset);
2321 if (RelocOffset == sect_offset) {
2322 Rel = Reloc.getRawDataRefImpl();
2323 RE = info->O->getRelocation(Rel);
2324 if (info->O->isRelocationScattered(RE))
2326 isExtern = info->O->getPlainRelocationExternal(RE);
2328 symbol_iterator RelocSym = Reloc.getSymbol();
2335 // If there is an external relocation entry for a symbol in this section
2336 // at this section_offset then use that symbol's value for the n_value
2337 // and return its name.
2338 const char *SymbolName = nullptr;
2339 if (reloc_found && isExtern) {
2340 Symbol.getAddress(n_value);
2342 Symbol.getName(name);
2343 if (!name.empty()) {
2344 SymbolName = name.data();
2349 // TODO: For fully linked images, look through the external relocation
2350 // entries off the dynamic symtab command. For these the r_offset is from the
2351 // start of the first writeable segment in the Mach-O file. So the offset
2352 // to this section from that segment is passed to this routine by the caller,
2353 // as the database_offset. Which is the difference of the section's starting
2354 // address and the first writable segment.
2356 // NOTE: need add passing the database_offset to this routine.
2358 // TODO: We did not find an external relocation entry so look up the
2359 // ReferenceValue as an address of a symbol and if found return that symbol's
2362 // NOTE: need add passing the ReferenceValue to this routine. Then that code
2363 // would simply be this:
2364 // SymbolName = GuessSymbolName(ReferenceValue, info->AddrMap);
2369 // These are structs in the Objective-C meta data and read to produce the
2370 // comments for disassembly. While these are part of the ABI they are no
2371 // public defintions. So the are here not in include/llvm/Support/MachO.h .
2373 // The cfstring object in a 64-bit Mach-O file.
2374 struct cfstring64_t {
2375 uint64_t isa; // class64_t * (64-bit pointer)
2376 uint64_t flags; // flag bits
2377 uint64_t characters; // char * (64-bit pointer)
2378 uint64_t length; // number of non-NULL characters in above
2381 // The class object in a 64-bit Mach-O file.
2383 uint64_t isa; // class64_t * (64-bit pointer)
2384 uint64_t superclass; // class64_t * (64-bit pointer)
2385 uint64_t cache; // Cache (64-bit pointer)
2386 uint64_t vtable; // IMP * (64-bit pointer)
2387 uint64_t data; // class_ro64_t * (64-bit pointer)
2390 struct class_ro64_t {
2392 uint32_t instanceStart;
2393 uint32_t instanceSize;
2395 uint64_t ivarLayout; // const uint8_t * (64-bit pointer)
2396 uint64_t name; // const char * (64-bit pointer)
2397 uint64_t baseMethods; // const method_list_t * (64-bit pointer)
2398 uint64_t baseProtocols; // const protocol_list_t * (64-bit pointer)
2399 uint64_t ivars; // const ivar_list_t * (64-bit pointer)
2400 uint64_t weakIvarLayout; // const uint8_t * (64-bit pointer)
2401 uint64_t baseProperties; // const struct objc_property_list (64-bit pointer)
2404 inline void swapStruct(struct cfstring64_t &cfs) {
2405 sys::swapByteOrder(cfs.isa);
2406 sys::swapByteOrder(cfs.flags);
2407 sys::swapByteOrder(cfs.characters);
2408 sys::swapByteOrder(cfs.length);
2411 inline void swapStruct(struct class64_t &c) {
2412 sys::swapByteOrder(c.isa);
2413 sys::swapByteOrder(c.superclass);
2414 sys::swapByteOrder(c.cache);
2415 sys::swapByteOrder(c.vtable);
2416 sys::swapByteOrder(c.data);
2419 inline void swapStruct(struct class_ro64_t &cro) {
2420 sys::swapByteOrder(cro.flags);
2421 sys::swapByteOrder(cro.instanceStart);
2422 sys::swapByteOrder(cro.instanceSize);
2423 sys::swapByteOrder(cro.reserved);
2424 sys::swapByteOrder(cro.ivarLayout);
2425 sys::swapByteOrder(cro.name);
2426 sys::swapByteOrder(cro.baseMethods);
2427 sys::swapByteOrder(cro.baseProtocols);
2428 sys::swapByteOrder(cro.ivars);
2429 sys::swapByteOrder(cro.weakIvarLayout);
2430 sys::swapByteOrder(cro.baseProperties);
2433 static const char *get_dyld_bind_info_symbolname(uint64_t ReferenceValue,
2434 struct DisassembleInfo *info);
2436 // get_objc2_64bit_class_name() is used for disassembly and is passed a pointer
2437 // to an Objective-C class and returns the class name. It is also passed the
2438 // address of the pointer, so when the pointer is zero as it can be in an .o
2439 // file, that is used to look for an external relocation entry with a symbol
2441 static const char *get_objc2_64bit_class_name(uint64_t pointer_value,
2442 uint64_t ReferenceValue,
2443 struct DisassembleInfo *info) {
2445 uint32_t offset, left;
2448 // The pointer_value can be 0 in an object file and have a relocation
2449 // entry for the class symbol at the ReferenceValue (the address of the
2451 if (pointer_value == 0) {
2452 r = get_pointer_64(ReferenceValue, offset, left, S, info);
2453 if (r == nullptr || left < sizeof(uint64_t))
2456 const char *symbol_name = get_symbol_64(offset, S, info, n_value);
2457 if (symbol_name == nullptr)
2459 const char *class_name = strrchr(symbol_name, '$');
2460 if (class_name != nullptr && class_name[1] == '_' && class_name[2] != '\0')
2461 return class_name + 2;
2466 // The case were the pointer_value is non-zero and points to a class defined
2467 // in this Mach-O file.
2468 r = get_pointer_64(pointer_value, offset, left, S, info);
2469 if (r == nullptr || left < sizeof(struct class64_t))
2472 memcpy(&c, r, sizeof(struct class64_t));
2473 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
2477 r = get_pointer_64(c.data, offset, left, S, info);
2478 if (r == nullptr || left < sizeof(struct class_ro64_t))
2480 struct class_ro64_t cro;
2481 memcpy(&cro, r, sizeof(struct class_ro64_t));
2482 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
2486 const char *name = get_pointer_64(cro.name, offset, left, S, info);
2490 // get_objc2_64bit_cfstring_name is used for disassembly and is passed a
2491 // pointer to a cfstring and returns its name or nullptr.
2492 static const char *get_objc2_64bit_cfstring_name(uint64_t ReferenceValue,
2493 struct DisassembleInfo *info) {
2494 const char *r, *name;
2495 uint32_t offset, left;
2497 struct cfstring64_t cfs;
2498 uint64_t cfs_characters;
2500 r = get_pointer_64(ReferenceValue, offset, left, S, info);
2501 if (r == nullptr || left < sizeof(struct cfstring64_t))
2503 memcpy(&cfs, r, sizeof(struct cfstring64_t));
2504 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
2506 if (cfs.characters == 0) {
2508 const char *symbol_name = get_symbol_64(
2509 offset + offsetof(struct cfstring64_t, characters), S, info, n_value);
2510 if (symbol_name == nullptr)
2512 cfs_characters = n_value;
2514 cfs_characters = cfs.characters;
2515 name = get_pointer_64(cfs_characters, offset, left, S, info);
2520 // get_objc2_64bit_selref() is used for disassembly and is passed a the address
2521 // of a pointer to an Objective-C selector reference when the pointer value is
2522 // zero as in a .o file and is likely to have a external relocation entry with
2523 // who's symbol's n_value is the real pointer to the selector name. If that is
2524 // the case the real pointer to the selector name is returned else 0 is
2526 static uint64_t get_objc2_64bit_selref(uint64_t ReferenceValue,
2527 struct DisassembleInfo *info) {
2528 uint32_t offset, left;
2531 const char *r = get_pointer_64(ReferenceValue, offset, left, S, info);
2532 if (r == nullptr || left < sizeof(uint64_t))
2535 const char *symbol_name = get_symbol_64(offset, S, info, n_value);
2536 if (symbol_name == nullptr)
2541 // GuessLiteralPointer returns a string which for the item in the Mach-O file
2542 // for the address passed in as ReferenceValue for printing as a comment with
2543 // the instruction and also returns the corresponding type of that item
2544 // indirectly through ReferenceType.
2546 // If ReferenceValue is an address of literal cstring then a pointer to the
2547 // cstring is returned and ReferenceType is set to
2548 // LLVMDisassembler_ReferenceType_Out_LitPool_CstrAddr .
2550 // If ReferenceValue is an address of an Objective-C CFString, Selector ref or
2551 // Class ref that name is returned and the ReferenceType is set accordingly.
2553 // Lastly, literals which are Symbol address in a literal pool are looked for
2554 // and if found the symbol name is returned and ReferenceType is set to
2555 // LLVMDisassembler_ReferenceType_Out_LitPool_SymAddr .
2557 // If there is no item in the Mach-O file for the address passed in as
2558 // ReferenceValue nullptr is returned and ReferenceType is unchanged.
2559 static const char *GuessLiteralPointer(uint64_t ReferenceValue,
2560 uint64_t ReferencePC,
2561 uint64_t *ReferenceType,
2562 struct DisassembleInfo *info) {
2563 // First see if there is an external relocation entry at the ReferencePC.
2564 uint64_t sect_addr = info->S.getAddress();
2565 uint64_t sect_offset = ReferencePC - sect_addr;
2566 bool reloc_found = false;
2568 MachO::any_relocation_info RE;
2569 bool isExtern = false;
2571 for (const RelocationRef &Reloc : info->S.relocations()) {
2572 uint64_t RelocOffset;
2573 Reloc.getOffset(RelocOffset);
2574 if (RelocOffset == sect_offset) {
2575 Rel = Reloc.getRawDataRefImpl();
2576 RE = info->O->getRelocation(Rel);
2577 if (info->O->isRelocationScattered(RE))
2579 isExtern = info->O->getPlainRelocationExternal(RE);
2581 symbol_iterator RelocSym = Reloc.getSymbol();
2588 // If there is an external relocation entry for a symbol in a section
2589 // then used that symbol's value for the value of the reference.
2590 if (reloc_found && isExtern) {
2591 if (info->O->getAnyRelocationPCRel(RE)) {
2592 unsigned Type = info->O->getAnyRelocationType(RE);
2593 if (Type == MachO::X86_64_RELOC_SIGNED) {
2594 Symbol.getAddress(ReferenceValue);
2599 // Look for literals such as Objective-C CFStrings refs, Selector refs,
2600 // Message refs and Class refs.
2601 bool classref, selref, msgref, cfstring;
2602 uint64_t pointer_value = GuessPointerPointer(ReferenceValue, info, classref,
2603 selref, msgref, cfstring);
2604 if (classref == true && pointer_value == 0) {
2605 // Note the ReferenceValue is a pointer into the __objc_classrefs section.
2606 // And the pointer_value in that section is typically zero as it will be
2607 // set by dyld as part of the "bind information".
2608 const char *name = get_dyld_bind_info_symbolname(ReferenceValue, info);
2609 if (name != nullptr) {
2610 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Class_Ref;
2611 const char *class_name = strrchr(name, '$');
2612 if (class_name != nullptr && class_name[1] == '_' &&
2613 class_name[2] != '\0') {
2614 info->class_name = class_name + 2;
2620 if (classref == true) {
2621 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Class_Ref;
2623 get_objc2_64bit_class_name(pointer_value, ReferenceValue, info);
2624 if (name != nullptr)
2625 info->class_name = name;
2627 name = "bad class ref";
2631 if (cfstring == true) {
2632 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_CFString_Ref;
2633 const char *name = get_objc2_64bit_cfstring_name(ReferenceValue, info);
2637 if (selref == true && pointer_value == 0)
2638 pointer_value = get_objc2_64bit_selref(ReferenceValue, info);
2640 if (pointer_value != 0)
2641 ReferenceValue = pointer_value;
2643 const char *name = GuessCstringPointer(ReferenceValue, info);
2645 if (pointer_value != 0 && selref == true) {
2646 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Selector_Ref;
2647 info->selector_name = name;
2648 } else if (pointer_value != 0 && msgref == true) {
2649 info->class_name = nullptr;
2650 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message_Ref;
2651 info->selector_name = name;
2653 *ReferenceType = LLVMDisassembler_ReferenceType_Out_LitPool_CstrAddr;
2657 // Lastly look for an indirect symbol with this ReferenceValue which is in
2658 // a literal pool. If found return that symbol name.
2659 name = GuessIndirectSymbol(ReferenceValue, info);
2661 *ReferenceType = LLVMDisassembler_ReferenceType_Out_LitPool_SymAddr;
2668 // SymbolizerSymbolLookUp is the symbol lookup function passed when creating
2669 // the Symbolizer. It looks up the ReferenceValue using the info passed via the
2670 // pointer to the struct DisassembleInfo that was passed when MCSymbolizer
2671 // is created and returns the symbol name that matches the ReferenceValue or
2672 // nullptr if none. The ReferenceType is passed in for the IN type of
2673 // reference the instruction is making from the values in defined in the header
2674 // "llvm-c/Disassembler.h". On return the ReferenceType can set to a specific
2675 // Out type and the ReferenceName will also be set which is added as a comment
2676 // to the disassembled instruction.
2679 // If the symbol name is a C++ mangled name then the demangled name is
2680 // returned through ReferenceName and ReferenceType is set to
2681 // LLVMDisassembler_ReferenceType_DeMangled_Name .
2684 // When this is called to get a symbol name for a branch target then the
2685 // ReferenceType will be LLVMDisassembler_ReferenceType_In_Branch and then
2686 // SymbolValue will be looked for in the indirect symbol table to determine if
2687 // it is an address for a symbol stub. If so then the symbol name for that
2688 // stub is returned indirectly through ReferenceName and then ReferenceType is
2689 // set to LLVMDisassembler_ReferenceType_Out_SymbolStub.
2691 // When this is called with an value loaded via a PC relative load then
2692 // ReferenceType will be LLVMDisassembler_ReferenceType_In_PCrel_Load then the
2693 // SymbolValue is checked to be an address of literal pointer, symbol pointer,
2694 // or an Objective-C meta data reference. If so the output ReferenceType is
2695 // set to correspond to that as well as setting the ReferenceName.
2696 static const char *SymbolizerSymbolLookUp(void *DisInfo,
2697 uint64_t ReferenceValue,
2698 uint64_t *ReferenceType,
2699 uint64_t ReferencePC,
2700 const char **ReferenceName) {
2701 struct DisassembleInfo *info = (struct DisassembleInfo *)DisInfo;
2702 // If no verbose symbolic information is wanted then just return nullptr.
2703 if (info->verbose == false) {
2704 *ReferenceName = nullptr;
2705 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
2709 const char *SymbolName = GuessSymbolName(ReferenceValue, info->AddrMap);
2711 if (*ReferenceType == LLVMDisassembler_ReferenceType_In_Branch) {
2712 *ReferenceName = GuessIndirectSymbol(ReferenceValue, info);
2713 if (*ReferenceName != nullptr) {
2714 method_reference(info, ReferenceType, ReferenceName);
2715 if (*ReferenceType != LLVMDisassembler_ReferenceType_Out_Objc_Message)
2716 *ReferenceType = LLVMDisassembler_ReferenceType_Out_SymbolStub;
2719 if (SymbolName != nullptr && strncmp(SymbolName, "__Z", 3) == 0) {
2720 if (info->demangled_name != nullptr)
2721 free(info->demangled_name);
2723 info->demangled_name =
2724 abi::__cxa_demangle(SymbolName + 1, nullptr, nullptr, &status);
2725 if (info->demangled_name != nullptr) {
2726 *ReferenceName = info->demangled_name;
2727 *ReferenceType = LLVMDisassembler_ReferenceType_DeMangled_Name;
2729 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
2732 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
2733 } else if (*ReferenceType == LLVMDisassembler_ReferenceType_In_PCrel_Load) {
2735 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
2737 method_reference(info, ReferenceType, ReferenceName);
2739 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
2740 // If this is arm64 and the reference is an adrp instruction save the
2741 // instruction, passed in ReferenceValue and the address of the instruction
2742 // for use later if we see and add immediate instruction.
2743 } else if (info->O->getArch() == Triple::aarch64 &&
2744 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADRP) {
2745 info->adrp_inst = ReferenceValue;
2746 info->adrp_addr = ReferencePC;
2747 SymbolName = nullptr;
2748 *ReferenceName = nullptr;
2749 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
2750 // If this is arm64 and reference is an add immediate instruction and we
2752 // seen an adrp instruction just before it and the adrp's Xd register
2754 // this add's Xn register reconstruct the value being referenced and look to
2755 // see if it is a literal pointer. Note the add immediate instruction is
2756 // passed in ReferenceValue.
2757 } else if (info->O->getArch() == Triple::aarch64 &&
2758 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADDXri &&
2759 ReferencePC - 4 == info->adrp_addr &&
2760 (info->adrp_inst & 0x9f000000) == 0x90000000 &&
2761 (info->adrp_inst & 0x1f) == ((ReferenceValue >> 5) & 0x1f)) {
2762 uint32_t addxri_inst;
2763 uint64_t adrp_imm, addxri_imm;
2766 ((info->adrp_inst & 0x00ffffe0) >> 3) | ((info->adrp_inst >> 29) & 0x3);
2767 if (info->adrp_inst & 0x0200000)
2768 adrp_imm |= 0xfffffffffc000000LL;
2770 addxri_inst = ReferenceValue;
2771 addxri_imm = (addxri_inst >> 10) & 0xfff;
2772 if (((addxri_inst >> 22) & 0x3) == 1)
2775 ReferenceValue = (info->adrp_addr & 0xfffffffffffff000LL) +
2776 (adrp_imm << 12) + addxri_imm;
2779 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
2780 if (*ReferenceName == nullptr)
2781 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
2782 // If this is arm64 and the reference is a load register instruction and we
2783 // have seen an adrp instruction just before it and the adrp's Xd register
2784 // matches this add's Xn register reconstruct the value being referenced and
2785 // look to see if it is a literal pointer. Note the load register
2786 // instruction is passed in ReferenceValue.
2787 } else if (info->O->getArch() == Triple::aarch64 &&
2788 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_LDRXui &&
2789 ReferencePC - 4 == info->adrp_addr &&
2790 (info->adrp_inst & 0x9f000000) == 0x90000000 &&
2791 (info->adrp_inst & 0x1f) == ((ReferenceValue >> 5) & 0x1f)) {
2792 uint32_t ldrxui_inst;
2793 uint64_t adrp_imm, ldrxui_imm;
2796 ((info->adrp_inst & 0x00ffffe0) >> 3) | ((info->adrp_inst >> 29) & 0x3);
2797 if (info->adrp_inst & 0x0200000)
2798 adrp_imm |= 0xfffffffffc000000LL;
2800 ldrxui_inst = ReferenceValue;
2801 ldrxui_imm = (ldrxui_inst >> 10) & 0xfff;
2803 ReferenceValue = (info->adrp_addr & 0xfffffffffffff000LL) +
2804 (adrp_imm << 12) + (ldrxui_imm << 3);
2807 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
2808 if (*ReferenceName == nullptr)
2809 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
2811 // If this arm64 and is an load register (PC-relative) instruction the
2812 // ReferenceValue is the PC plus the immediate value.
2813 else if (info->O->getArch() == Triple::aarch64 &&
2814 (*ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_LDRXl ||
2815 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADR)) {
2817 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
2818 if (*ReferenceName == nullptr)
2819 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
2822 else if (SymbolName != nullptr && strncmp(SymbolName, "__Z", 3) == 0) {
2823 if (info->demangled_name != nullptr)
2824 free(info->demangled_name);
2826 info->demangled_name =
2827 abi::__cxa_demangle(SymbolName + 1, nullptr, nullptr, &status);
2828 if (info->demangled_name != nullptr) {
2829 *ReferenceName = info->demangled_name;
2830 *ReferenceType = LLVMDisassembler_ReferenceType_DeMangled_Name;
2835 *ReferenceName = nullptr;
2836 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
2842 /// \brief Emits the comments that are stored in the CommentStream.
2843 /// Each comment in the CommentStream must end with a newline.
2844 static void emitComments(raw_svector_ostream &CommentStream,
2845 SmallString<128> &CommentsToEmit,
2846 formatted_raw_ostream &FormattedOS,
2847 const MCAsmInfo &MAI) {
2848 // Flush the stream before taking its content.
2849 CommentStream.flush();
2850 StringRef Comments = CommentsToEmit.str();
2851 // Get the default information for printing a comment.
2852 const char *CommentBegin = MAI.getCommentString();
2853 unsigned CommentColumn = MAI.getCommentColumn();
2854 bool IsFirst = true;
2855 while (!Comments.empty()) {
2857 FormattedOS << '\n';
2858 // Emit a line of comments.
2859 FormattedOS.PadToColumn(CommentColumn);
2860 size_t Position = Comments.find('\n');
2861 FormattedOS << CommentBegin << ' ' << Comments.substr(0, Position);
2862 // Move after the newline character.
2863 Comments = Comments.substr(Position + 1);
2866 FormattedOS.flush();
2868 // Tell the comment stream that the vector changed underneath it.
2869 CommentsToEmit.clear();
2870 CommentStream.resync();
2873 static void DisassembleMachO(StringRef Filename, MachOObjectFile *MachOOF,
2874 StringRef DisSegName, StringRef DisSectName) {
2875 const char *McpuDefault = nullptr;
2876 const Target *ThumbTarget = nullptr;
2877 const Target *TheTarget = GetTarget(MachOOF, &McpuDefault, &ThumbTarget);
2879 // GetTarget prints out stuff.
2882 if (MCPU.empty() && McpuDefault)
2885 std::unique_ptr<const MCInstrInfo> InstrInfo(TheTarget->createMCInstrInfo());
2886 std::unique_ptr<const MCInstrInfo> ThumbInstrInfo;
2888 ThumbInstrInfo.reset(ThumbTarget->createMCInstrInfo());
2890 // Package up features to be passed to target/subtarget
2891 std::string FeaturesStr;
2892 if (MAttrs.size()) {
2893 SubtargetFeatures Features;
2894 for (unsigned i = 0; i != MAttrs.size(); ++i)
2895 Features.AddFeature(MAttrs[i]);
2896 FeaturesStr = Features.getString();
2899 // Set up disassembler.
2900 std::unique_ptr<const MCRegisterInfo> MRI(
2901 TheTarget->createMCRegInfo(TripleName));
2902 std::unique_ptr<const MCAsmInfo> AsmInfo(
2903 TheTarget->createMCAsmInfo(*MRI, TripleName));
2904 std::unique_ptr<const MCSubtargetInfo> STI(
2905 TheTarget->createMCSubtargetInfo(TripleName, MCPU, FeaturesStr));
2906 MCContext Ctx(AsmInfo.get(), MRI.get(), nullptr);
2907 std::unique_ptr<MCDisassembler> DisAsm(
2908 TheTarget->createMCDisassembler(*STI, Ctx));
2909 std::unique_ptr<MCSymbolizer> Symbolizer;
2910 struct DisassembleInfo SymbolizerInfo;
2911 std::unique_ptr<MCRelocationInfo> RelInfo(
2912 TheTarget->createMCRelocationInfo(TripleName, Ctx));
2914 Symbolizer.reset(TheTarget->createMCSymbolizer(
2915 TripleName, SymbolizerGetOpInfo, SymbolizerSymbolLookUp,
2916 &SymbolizerInfo, &Ctx, std::move(RelInfo)));
2917 DisAsm->setSymbolizer(std::move(Symbolizer));
2919 int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
2920 std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
2921 AsmPrinterVariant, *AsmInfo, *InstrInfo, *MRI, *STI));
2922 // Set the display preference for hex vs. decimal immediates.
2923 IP->setPrintImmHex(PrintImmHex);
2924 // Comment stream and backing vector.
2925 SmallString<128> CommentsToEmit;
2926 raw_svector_ostream CommentStream(CommentsToEmit);
2927 // FIXME: Setting the CommentStream in the InstPrinter is problematic in that
2928 // if it is done then arm64 comments for string literals don't get printed
2929 // and some constant get printed instead and not setting it causes intel
2930 // (32-bit and 64-bit) comments printed with different spacing before the
2931 // comment causing different diffs with the 'C' disassembler library API.
2932 // IP->setCommentStream(CommentStream);
2934 if (!AsmInfo || !STI || !DisAsm || !IP) {
2935 errs() << "error: couldn't initialize disassembler for target "
2936 << TripleName << '\n';
2940 // Set up thumb disassembler.
2941 std::unique_ptr<const MCRegisterInfo> ThumbMRI;
2942 std::unique_ptr<const MCAsmInfo> ThumbAsmInfo;
2943 std::unique_ptr<const MCSubtargetInfo> ThumbSTI;
2944 std::unique_ptr<MCDisassembler> ThumbDisAsm;
2945 std::unique_ptr<MCInstPrinter> ThumbIP;
2946 std::unique_ptr<MCContext> ThumbCtx;
2947 std::unique_ptr<MCSymbolizer> ThumbSymbolizer;
2948 struct DisassembleInfo ThumbSymbolizerInfo;
2949 std::unique_ptr<MCRelocationInfo> ThumbRelInfo;
2951 ThumbMRI.reset(ThumbTarget->createMCRegInfo(ThumbTripleName));
2953 ThumbTarget->createMCAsmInfo(*ThumbMRI, ThumbTripleName));
2955 ThumbTarget->createMCSubtargetInfo(ThumbTripleName, MCPU, FeaturesStr));
2956 ThumbCtx.reset(new MCContext(ThumbAsmInfo.get(), ThumbMRI.get(), nullptr));
2957 ThumbDisAsm.reset(ThumbTarget->createMCDisassembler(*ThumbSTI, *ThumbCtx));
2958 MCContext *PtrThumbCtx = ThumbCtx.get();
2960 ThumbTarget->createMCRelocationInfo(ThumbTripleName, *PtrThumbCtx));
2962 ThumbSymbolizer.reset(ThumbTarget->createMCSymbolizer(
2963 ThumbTripleName, SymbolizerGetOpInfo, SymbolizerSymbolLookUp,
2964 &ThumbSymbolizerInfo, PtrThumbCtx, std::move(ThumbRelInfo)));
2965 ThumbDisAsm->setSymbolizer(std::move(ThumbSymbolizer));
2967 int ThumbAsmPrinterVariant = ThumbAsmInfo->getAssemblerDialect();
2968 ThumbIP.reset(ThumbTarget->createMCInstPrinter(
2969 ThumbAsmPrinterVariant, *ThumbAsmInfo, *ThumbInstrInfo, *ThumbMRI,
2971 // Set the display preference for hex vs. decimal immediates.
2972 ThumbIP->setPrintImmHex(PrintImmHex);
2975 if (ThumbTarget && (!ThumbAsmInfo || !ThumbSTI || !ThumbDisAsm || !ThumbIP)) {
2976 errs() << "error: couldn't initialize disassembler for target "
2977 << ThumbTripleName << '\n';
2981 MachO::mach_header Header = MachOOF->getHeader();
2983 // FIXME: Using the -cfg command line option, this code used to be able to
2984 // annotate relocations with the referenced symbol's name, and if this was
2985 // inside a __[cf]string section, the data it points to. This is now replaced
2986 // by the upcoming MCSymbolizer, which needs the appropriate setup done above.
2987 std::vector<SectionRef> Sections;
2988 std::vector<SymbolRef> Symbols;
2989 SmallVector<uint64_t, 8> FoundFns;
2990 uint64_t BaseSegmentAddress;
2992 getSectionsAndSymbols(Header, MachOOF, Sections, Symbols, FoundFns,
2993 BaseSegmentAddress);
2995 // Sort the symbols by address, just in case they didn't come in that way.
2996 std::sort(Symbols.begin(), Symbols.end(), SymbolSorter());
2998 // Build a data in code table that is sorted on by the address of each entry.
2999 uint64_t BaseAddress = 0;
3000 if (Header.filetype == MachO::MH_OBJECT)
3001 BaseAddress = Sections[0].getAddress();
3003 BaseAddress = BaseSegmentAddress;
3005 for (dice_iterator DI = MachOOF->begin_dices(), DE = MachOOF->end_dices();
3008 DI->getOffset(Offset);
3009 Dices.push_back(std::make_pair(BaseAddress + Offset, *DI));
3011 array_pod_sort(Dices.begin(), Dices.end());
3014 raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls();
3016 raw_ostream &DebugOut = nulls();
3019 std::unique_ptr<DIContext> diContext;
3020 ObjectFile *DbgObj = MachOOF;
3021 // Try to find debug info and set up the DIContext for it.
3023 // A separate DSym file path was specified, parse it as a macho file,
3024 // get the sections and supply it to the section name parsing machinery.
3025 if (!DSYMFile.empty()) {
3026 ErrorOr<std::unique_ptr<MemoryBuffer>> BufOrErr =
3027 MemoryBuffer::getFileOrSTDIN(DSYMFile);
3028 if (std::error_code EC = BufOrErr.getError()) {
3029 errs() << "llvm-objdump: " << Filename << ": " << EC.message() << '\n';
3033 ObjectFile::createMachOObjectFile(BufOrErr.get()->getMemBufferRef())
3038 // Setup the DIContext
3039 diContext.reset(DIContext::getDWARFContext(*DbgObj));
3042 if (DumpSections.size() == 0)
3043 outs() << "(" << DisSegName << "," << DisSectName << ") section\n";
3045 for (unsigned SectIdx = 0; SectIdx != Sections.size(); SectIdx++) {
3047 if (Sections[SectIdx].getName(SectName) || SectName != DisSectName)
3050 DataRefImpl DR = Sections[SectIdx].getRawDataRefImpl();
3052 StringRef SegmentName = MachOOF->getSectionFinalSegmentName(DR);
3053 if (SegmentName != DisSegName)
3057 Sections[SectIdx].getContents(BytesStr);
3058 ArrayRef<uint8_t> Bytes(reinterpret_cast<const uint8_t *>(BytesStr.data()),
3060 uint64_t SectAddress = Sections[SectIdx].getAddress();
3062 bool symbolTableWorked = false;
3064 // Parse relocations.
3065 std::vector<std::pair<uint64_t, SymbolRef>> Relocs;
3066 for (const RelocationRef &Reloc : Sections[SectIdx].relocations()) {
3067 uint64_t RelocOffset;
3068 Reloc.getOffset(RelocOffset);
3069 uint64_t SectionAddress = Sections[SectIdx].getAddress();
3070 RelocOffset -= SectionAddress;
3072 symbol_iterator RelocSym = Reloc.getSymbol();
3074 Relocs.push_back(std::make_pair(RelocOffset, *RelocSym));
3076 array_pod_sort(Relocs.begin(), Relocs.end());
3078 // Create a map of symbol addresses to symbol names for use by
3079 // the SymbolizerSymbolLookUp() routine.
3080 SymbolAddressMap AddrMap;
3081 for (const SymbolRef &Symbol : MachOOF->symbols()) {
3084 if (ST == SymbolRef::ST_Function || ST == SymbolRef::ST_Data ||
3085 ST == SymbolRef::ST_Other) {
3087 Symbol.getAddress(Address);
3089 Symbol.getName(SymName);
3090 AddrMap[Address] = SymName;
3093 // Set up the block of info used by the Symbolizer call backs.
3094 SymbolizerInfo.verbose = true;
3095 SymbolizerInfo.O = MachOOF;
3096 SymbolizerInfo.S = Sections[SectIdx];
3097 SymbolizerInfo.AddrMap = &AddrMap;
3098 SymbolizerInfo.Sections = &Sections;
3099 SymbolizerInfo.class_name = nullptr;
3100 SymbolizerInfo.selector_name = nullptr;
3101 SymbolizerInfo.method = nullptr;
3102 SymbolizerInfo.demangled_name = nullptr;
3103 SymbolizerInfo.bindtable = nullptr;
3104 SymbolizerInfo.adrp_addr = 0;
3105 SymbolizerInfo.adrp_inst = 0;
3106 // Same for the ThumbSymbolizer
3107 ThumbSymbolizerInfo.verbose = true;
3108 ThumbSymbolizerInfo.O = MachOOF;
3109 ThumbSymbolizerInfo.S = Sections[SectIdx];
3110 ThumbSymbolizerInfo.AddrMap = &AddrMap;
3111 ThumbSymbolizerInfo.Sections = &Sections;
3112 ThumbSymbolizerInfo.class_name = nullptr;
3113 ThumbSymbolizerInfo.selector_name = nullptr;
3114 ThumbSymbolizerInfo.method = nullptr;
3115 ThumbSymbolizerInfo.demangled_name = nullptr;
3116 ThumbSymbolizerInfo.bindtable = nullptr;
3117 ThumbSymbolizerInfo.adrp_addr = 0;
3118 ThumbSymbolizerInfo.adrp_inst = 0;
3120 // Disassemble symbol by symbol.
3121 for (unsigned SymIdx = 0; SymIdx != Symbols.size(); SymIdx++) {
3123 Symbols[SymIdx].getName(SymName);
3126 Symbols[SymIdx].getType(ST);
3127 if (ST != SymbolRef::ST_Function)
3130 // Make sure the symbol is defined in this section.
3131 bool containsSym = Sections[SectIdx].containsSymbol(Symbols[SymIdx]);
3135 // Start at the address of the symbol relative to the section's address.
3137 uint64_t SectionAddress = Sections[SectIdx].getAddress();
3138 Symbols[SymIdx].getAddress(Start);
3139 Start -= SectionAddress;
3141 // Stop disassembling either at the beginning of the next symbol or at
3142 // the end of the section.
3143 bool containsNextSym = false;
3144 uint64_t NextSym = 0;
3145 uint64_t NextSymIdx = SymIdx + 1;
3146 while (Symbols.size() > NextSymIdx) {
3147 SymbolRef::Type NextSymType;
3148 Symbols[NextSymIdx].getType(NextSymType);
3149 if (NextSymType == SymbolRef::ST_Function) {
3151 Sections[SectIdx].containsSymbol(Symbols[NextSymIdx]);
3152 Symbols[NextSymIdx].getAddress(NextSym);
3153 NextSym -= SectionAddress;
3159 uint64_t SectSize = Sections[SectIdx].getSize();
3160 uint64_t End = containsNextSym ? NextSym : SectSize;
3163 symbolTableWorked = true;
3165 DataRefImpl Symb = Symbols[SymIdx].getRawDataRefImpl();
3167 (MachOOF->getSymbolFlags(Symb) & SymbolRef::SF_Thumb) && ThumbTarget;
3169 outs() << SymName << ":\n";
3170 DILineInfo lastLine;
3171 for (uint64_t Index = Start; Index < End; Index += Size) {
3174 uint64_t PC = SectAddress + Index;
3175 if (FullLeadingAddr) {
3176 if (MachOOF->is64Bit())
3177 outs() << format("%016" PRIx64, PC);
3179 outs() << format("%08" PRIx64, PC);
3181 outs() << format("%8" PRIx64 ":", PC);
3186 // Check the data in code table here to see if this is data not an
3187 // instruction to be disassembled.
3189 Dice.push_back(std::make_pair(PC, DiceRef()));
3190 dice_table_iterator DTI =
3191 std::search(Dices.begin(), Dices.end(), Dice.begin(), Dice.end(),
3192 compareDiceTableEntries);
3193 if (DTI != Dices.end()) {
3195 DTI->second.getLength(Length);
3197 DTI->second.getKind(Kind);
3198 Size = DumpDataInCode(reinterpret_cast<const char *>(Bytes.data()) +
3201 if ((Kind == MachO::DICE_KIND_JUMP_TABLE8) &&
3202 (PC == (DTI->first + Length - 1)) && (Length & 1))
3207 SmallVector<char, 64> AnnotationsBytes;
3208 raw_svector_ostream Annotations(AnnotationsBytes);
3212 gotInst = ThumbDisAsm->getInstruction(Inst, Size, Bytes.slice(Index),
3213 PC, DebugOut, Annotations);
3215 gotInst = DisAsm->getInstruction(Inst, Size, Bytes.slice(Index), PC,
3216 DebugOut, Annotations);
3218 if (!NoShowRawInsn) {
3219 DumpBytes(StringRef(
3220 reinterpret_cast<const char *>(Bytes.data()) + Index, Size));
3222 formatted_raw_ostream FormattedOS(outs());
3223 Annotations.flush();
3224 StringRef AnnotationsStr = Annotations.str();
3226 ThumbIP->printInst(&Inst, FormattedOS, AnnotationsStr);
3228 IP->printInst(&Inst, FormattedOS, AnnotationsStr);
3229 emitComments(CommentStream, CommentsToEmit, FormattedOS, *AsmInfo);
3231 // Print debug info.
3233 DILineInfo dli = diContext->getLineInfoForAddress(PC);
3234 // Print valid line info if it changed.
3235 if (dli != lastLine && dli.Line != 0)
3236 outs() << "\t## " << dli.FileName << ':' << dli.Line << ':'
3242 unsigned int Arch = MachOOF->getArch();
3243 if (Arch == Triple::x86_64 || Arch == Triple::x86) {
3244 outs() << format("\t.byte 0x%02x #bad opcode\n",
3245 *(Bytes.data() + Index) & 0xff);
3246 Size = 1; // skip exactly one illegible byte and move on.
3247 } else if (Arch == Triple::aarch64) {
3248 uint32_t opcode = (*(Bytes.data() + Index) & 0xff) |
3249 (*(Bytes.data() + Index + 1) & 0xff) << 8 |
3250 (*(Bytes.data() + Index + 2) & 0xff) << 16 |
3251 (*(Bytes.data() + Index + 3) & 0xff) << 24;
3252 outs() << format("\t.long\t0x%08x\n", opcode);
3255 errs() << "llvm-objdump: warning: invalid instruction encoding\n";
3257 Size = 1; // skip illegible bytes
3262 if (!symbolTableWorked) {
3263 // Reading the symbol table didn't work, disassemble the whole section.
3264 uint64_t SectAddress = Sections[SectIdx].getAddress();
3265 uint64_t SectSize = Sections[SectIdx].getSize();
3267 for (uint64_t Index = 0; Index < SectSize; Index += InstSize) {
3270 uint64_t PC = SectAddress + Index;
3271 if (DisAsm->getInstruction(Inst, InstSize, Bytes.slice(Index), PC,
3272 DebugOut, nulls())) {
3273 if (FullLeadingAddr) {
3274 if (MachOOF->is64Bit())
3275 outs() << format("%016" PRIx64, PC);
3277 outs() << format("%08" PRIx64, PC);
3279 outs() << format("%8" PRIx64 ":", PC);
3281 if (!NoShowRawInsn) {
3284 StringRef(reinterpret_cast<const char *>(Bytes.data()) + Index,
3287 IP->printInst(&Inst, outs(), "");
3290 unsigned int Arch = MachOOF->getArch();
3291 if (Arch == Triple::x86_64 || Arch == Triple::x86) {
3292 outs() << format("\t.byte 0x%02x #bad opcode\n",
3293 *(Bytes.data() + Index) & 0xff);
3294 InstSize = 1; // skip exactly one illegible byte and move on.
3296 errs() << "llvm-objdump: warning: invalid instruction encoding\n";
3298 InstSize = 1; // skip illegible bytes
3303 // The TripleName's need to be reset if we are called again for a different
3306 ThumbTripleName = "";
3308 if (SymbolizerInfo.method != nullptr)
3309 free(SymbolizerInfo.method);
3310 if (SymbolizerInfo.demangled_name != nullptr)
3311 free(SymbolizerInfo.demangled_name);
3312 if (SymbolizerInfo.bindtable != nullptr)
3313 delete SymbolizerInfo.bindtable;
3314 if (ThumbSymbolizerInfo.method != nullptr)
3315 free(ThumbSymbolizerInfo.method);
3316 if (ThumbSymbolizerInfo.demangled_name != nullptr)
3317 free(ThumbSymbolizerInfo.demangled_name);
3318 if (ThumbSymbolizerInfo.bindtable != nullptr)
3319 delete ThumbSymbolizerInfo.bindtable;
3323 //===----------------------------------------------------------------------===//
3324 // __compact_unwind section dumping
3325 //===----------------------------------------------------------------------===//
3329 template <typename T> static uint64_t readNext(const char *&Buf) {
3330 using llvm::support::little;
3331 using llvm::support::unaligned;
3333 uint64_t Val = support::endian::read<T, little, unaligned>(Buf);
3338 struct CompactUnwindEntry {
3339 uint32_t OffsetInSection;
3341 uint64_t FunctionAddr;
3343 uint32_t CompactEncoding;
3344 uint64_t PersonalityAddr;
3347 RelocationRef FunctionReloc;
3348 RelocationRef PersonalityReloc;
3349 RelocationRef LSDAReloc;
3351 CompactUnwindEntry(StringRef Contents, unsigned Offset, bool Is64)
3352 : OffsetInSection(Offset) {
3354 read<uint64_t>(Contents.data() + Offset);
3356 read<uint32_t>(Contents.data() + Offset);
3360 template <typename UIntPtr> void read(const char *Buf) {
3361 FunctionAddr = readNext<UIntPtr>(Buf);
3362 Length = readNext<uint32_t>(Buf);
3363 CompactEncoding = readNext<uint32_t>(Buf);
3364 PersonalityAddr = readNext<UIntPtr>(Buf);
3365 LSDAAddr = readNext<UIntPtr>(Buf);
3370 /// Given a relocation from __compact_unwind, consisting of the RelocationRef
3371 /// and data being relocated, determine the best base Name and Addend to use for
3372 /// display purposes.
3374 /// 1. An Extern relocation will directly reference a symbol (and the data is
3375 /// then already an addend), so use that.
3376 /// 2. Otherwise the data is an offset in the object file's layout; try to find
3377 // a symbol before it in the same section, and use the offset from there.
3378 /// 3. Finally, if all that fails, fall back to an offset from the start of the
3379 /// referenced section.
3380 static void findUnwindRelocNameAddend(const MachOObjectFile *Obj,
3381 std::map<uint64_t, SymbolRef> &Symbols,
3382 const RelocationRef &Reloc, uint64_t Addr,
3383 StringRef &Name, uint64_t &Addend) {
3384 if (Reloc.getSymbol() != Obj->symbol_end()) {
3385 Reloc.getSymbol()->getName(Name);
3390 auto RE = Obj->getRelocation(Reloc.getRawDataRefImpl());
3391 SectionRef RelocSection = Obj->getRelocationSection(RE);
3393 uint64_t SectionAddr = RelocSection.getAddress();
3395 auto Sym = Symbols.upper_bound(Addr);
3396 if (Sym == Symbols.begin()) {
3397 // The first symbol in the object is after this reference, the best we can
3398 // do is section-relative notation.
3399 RelocSection.getName(Name);
3400 Addend = Addr - SectionAddr;
3404 // Go back one so that SymbolAddress <= Addr.
3407 section_iterator SymSection = Obj->section_end();
3408 Sym->second.getSection(SymSection);
3409 if (RelocSection == *SymSection) {
3410 // There's a valid symbol in the same section before this reference.
3411 Sym->second.getName(Name);
3412 Addend = Addr - Sym->first;
3416 // There is a symbol before this reference, but it's in a different
3417 // section. Probably not helpful to mention it, so use the section name.
3418 RelocSection.getName(Name);
3419 Addend = Addr - SectionAddr;
3422 static void printUnwindRelocDest(const MachOObjectFile *Obj,
3423 std::map<uint64_t, SymbolRef> &Symbols,
3424 const RelocationRef &Reloc, uint64_t Addr) {
3428 if (!Reloc.getObjectFile())
3431 findUnwindRelocNameAddend(Obj, Symbols, Reloc, Addr, Name, Addend);
3435 outs() << " + " << format("0x%" PRIx64, Addend);
3439 printMachOCompactUnwindSection(const MachOObjectFile *Obj,
3440 std::map<uint64_t, SymbolRef> &Symbols,
3441 const SectionRef &CompactUnwind) {
3443 assert(Obj->isLittleEndian() &&
3444 "There should not be a big-endian .o with __compact_unwind");
3446 bool Is64 = Obj->is64Bit();
3447 uint32_t PointerSize = Is64 ? sizeof(uint64_t) : sizeof(uint32_t);
3448 uint32_t EntrySize = 3 * PointerSize + 2 * sizeof(uint32_t);
3451 CompactUnwind.getContents(Contents);
3453 SmallVector<CompactUnwindEntry, 4> CompactUnwinds;
3455 // First populate the initial raw offsets, encodings and so on from the entry.
3456 for (unsigned Offset = 0; Offset < Contents.size(); Offset += EntrySize) {
3457 CompactUnwindEntry Entry(Contents.data(), Offset, Is64);
3458 CompactUnwinds.push_back(Entry);
3461 // Next we need to look at the relocations to find out what objects are
3462 // actually being referred to.
3463 for (const RelocationRef &Reloc : CompactUnwind.relocations()) {
3464 uint64_t RelocAddress;
3465 Reloc.getOffset(RelocAddress);
3467 uint32_t EntryIdx = RelocAddress / EntrySize;
3468 uint32_t OffsetInEntry = RelocAddress - EntryIdx * EntrySize;
3469 CompactUnwindEntry &Entry = CompactUnwinds[EntryIdx];
3471 if (OffsetInEntry == 0)
3472 Entry.FunctionReloc = Reloc;
3473 else if (OffsetInEntry == PointerSize + 2 * sizeof(uint32_t))
3474 Entry.PersonalityReloc = Reloc;
3475 else if (OffsetInEntry == 2 * PointerSize + 2 * sizeof(uint32_t))
3476 Entry.LSDAReloc = Reloc;
3478 llvm_unreachable("Unexpected relocation in __compact_unwind section");
3481 // Finally, we're ready to print the data we've gathered.
3482 outs() << "Contents of __compact_unwind section:\n";
3483 for (auto &Entry : CompactUnwinds) {
3484 outs() << " Entry at offset "
3485 << format("0x%" PRIx32, Entry.OffsetInSection) << ":\n";
3487 // 1. Start of the region this entry applies to.
3488 outs() << " start: " << format("0x%" PRIx64,
3489 Entry.FunctionAddr) << ' ';
3490 printUnwindRelocDest(Obj, Symbols, Entry.FunctionReloc, Entry.FunctionAddr);
3493 // 2. Length of the region this entry applies to.
3494 outs() << " length: " << format("0x%" PRIx32, Entry.Length)
3496 // 3. The 32-bit compact encoding.
3497 outs() << " compact encoding: "
3498 << format("0x%08" PRIx32, Entry.CompactEncoding) << '\n';
3500 // 4. The personality function, if present.
3501 if (Entry.PersonalityReloc.getObjectFile()) {
3502 outs() << " personality function: "
3503 << format("0x%" PRIx64, Entry.PersonalityAddr) << ' ';
3504 printUnwindRelocDest(Obj, Symbols, Entry.PersonalityReloc,
3505 Entry.PersonalityAddr);
3509 // 5. This entry's language-specific data area.
3510 if (Entry.LSDAReloc.getObjectFile()) {
3511 outs() << " LSDA: " << format("0x%" PRIx64,
3512 Entry.LSDAAddr) << ' ';
3513 printUnwindRelocDest(Obj, Symbols, Entry.LSDAReloc, Entry.LSDAAddr);
3519 //===----------------------------------------------------------------------===//
3520 // __unwind_info section dumping
3521 //===----------------------------------------------------------------------===//
3523 static void printRegularSecondLevelUnwindPage(const char *PageStart) {
3524 const char *Pos = PageStart;
3525 uint32_t Kind = readNext<uint32_t>(Pos);
3527 assert(Kind == 2 && "kind for a regular 2nd level index should be 2");
3529 uint16_t EntriesStart = readNext<uint16_t>(Pos);
3530 uint16_t NumEntries = readNext<uint16_t>(Pos);
3532 Pos = PageStart + EntriesStart;
3533 for (unsigned i = 0; i < NumEntries; ++i) {
3534 uint32_t FunctionOffset = readNext<uint32_t>(Pos);
3535 uint32_t Encoding = readNext<uint32_t>(Pos);
3537 outs() << " [" << i << "]: "
3538 << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
3540 << "encoding=" << format("0x%08" PRIx32, Encoding) << '\n';
3544 static void printCompressedSecondLevelUnwindPage(
3545 const char *PageStart, uint32_t FunctionBase,
3546 const SmallVectorImpl<uint32_t> &CommonEncodings) {
3547 const char *Pos = PageStart;
3548 uint32_t Kind = readNext<uint32_t>(Pos);
3550 assert(Kind == 3 && "kind for a compressed 2nd level index should be 3");
3552 uint16_t EntriesStart = readNext<uint16_t>(Pos);
3553 uint16_t NumEntries = readNext<uint16_t>(Pos);
3555 uint16_t EncodingsStart = readNext<uint16_t>(Pos);
3556 readNext<uint16_t>(Pos);
3557 const auto *PageEncodings = reinterpret_cast<const support::ulittle32_t *>(
3558 PageStart + EncodingsStart);
3560 Pos = PageStart + EntriesStart;
3561 for (unsigned i = 0; i < NumEntries; ++i) {
3562 uint32_t Entry = readNext<uint32_t>(Pos);
3563 uint32_t FunctionOffset = FunctionBase + (Entry & 0xffffff);
3564 uint32_t EncodingIdx = Entry >> 24;
3567 if (EncodingIdx < CommonEncodings.size())
3568 Encoding = CommonEncodings[EncodingIdx];
3570 Encoding = PageEncodings[EncodingIdx - CommonEncodings.size()];
3572 outs() << " [" << i << "]: "
3573 << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
3575 << "encoding[" << EncodingIdx
3576 << "]=" << format("0x%08" PRIx32, Encoding) << '\n';
3580 static void printMachOUnwindInfoSection(const MachOObjectFile *Obj,
3581 std::map<uint64_t, SymbolRef> &Symbols,
3582 const SectionRef &UnwindInfo) {
3584 assert(Obj->isLittleEndian() &&
3585 "There should not be a big-endian .o with __unwind_info");
3587 outs() << "Contents of __unwind_info section:\n";
3590 UnwindInfo.getContents(Contents);
3591 const char *Pos = Contents.data();
3593 //===----------------------------------
3595 //===----------------------------------
3597 uint32_t Version = readNext<uint32_t>(Pos);
3598 outs() << " Version: "
3599 << format("0x%" PRIx32, Version) << '\n';
3600 assert(Version == 1 && "only understand version 1");
3602 uint32_t CommonEncodingsStart = readNext<uint32_t>(Pos);
3603 outs() << " Common encodings array section offset: "
3604 << format("0x%" PRIx32, CommonEncodingsStart) << '\n';
3605 uint32_t NumCommonEncodings = readNext<uint32_t>(Pos);
3606 outs() << " Number of common encodings in array: "
3607 << format("0x%" PRIx32, NumCommonEncodings) << '\n';
3609 uint32_t PersonalitiesStart = readNext<uint32_t>(Pos);
3610 outs() << " Personality function array section offset: "
3611 << format("0x%" PRIx32, PersonalitiesStart) << '\n';
3612 uint32_t NumPersonalities = readNext<uint32_t>(Pos);
3613 outs() << " Number of personality functions in array: "
3614 << format("0x%" PRIx32, NumPersonalities) << '\n';
3616 uint32_t IndicesStart = readNext<uint32_t>(Pos);
3617 outs() << " Index array section offset: "
3618 << format("0x%" PRIx32, IndicesStart) << '\n';
3619 uint32_t NumIndices = readNext<uint32_t>(Pos);
3620 outs() << " Number of indices in array: "
3621 << format("0x%" PRIx32, NumIndices) << '\n';
3623 //===----------------------------------
3624 // A shared list of common encodings
3625 //===----------------------------------
3627 // These occupy indices in the range [0, N] whenever an encoding is referenced
3628 // from a compressed 2nd level index table. In practice the linker only
3629 // creates ~128 of these, so that indices are available to embed encodings in
3630 // the 2nd level index.
3632 SmallVector<uint32_t, 64> CommonEncodings;
3633 outs() << " Common encodings: (count = " << NumCommonEncodings << ")\n";
3634 Pos = Contents.data() + CommonEncodingsStart;
3635 for (unsigned i = 0; i < NumCommonEncodings; ++i) {
3636 uint32_t Encoding = readNext<uint32_t>(Pos);
3637 CommonEncodings.push_back(Encoding);
3639 outs() << " encoding[" << i << "]: " << format("0x%08" PRIx32, Encoding)
3643 //===----------------------------------
3644 // Personality functions used in this executable
3645 //===----------------------------------
3647 // There should be only a handful of these (one per source language,
3648 // roughly). Particularly since they only get 2 bits in the compact encoding.
3650 outs() << " Personality functions: (count = " << NumPersonalities << ")\n";
3651 Pos = Contents.data() + PersonalitiesStart;
3652 for (unsigned i = 0; i < NumPersonalities; ++i) {
3653 uint32_t PersonalityFn = readNext<uint32_t>(Pos);
3654 outs() << " personality[" << i + 1
3655 << "]: " << format("0x%08" PRIx32, PersonalityFn) << '\n';
3658 //===----------------------------------
3659 // The level 1 index entries
3660 //===----------------------------------
3662 // These specify an approximate place to start searching for the more detailed
3663 // information, sorted by PC.
3666 uint32_t FunctionOffset;
3667 uint32_t SecondLevelPageStart;
3671 SmallVector<IndexEntry, 4> IndexEntries;
3673 outs() << " Top level indices: (count = " << NumIndices << ")\n";
3674 Pos = Contents.data() + IndicesStart;
3675 for (unsigned i = 0; i < NumIndices; ++i) {
3678 Entry.FunctionOffset = readNext<uint32_t>(Pos);
3679 Entry.SecondLevelPageStart = readNext<uint32_t>(Pos);
3680 Entry.LSDAStart = readNext<uint32_t>(Pos);
3681 IndexEntries.push_back(Entry);
3683 outs() << " [" << i << "]: "
3684 << "function offset=" << format("0x%08" PRIx32, Entry.FunctionOffset)
3686 << "2nd level page offset="
3687 << format("0x%08" PRIx32, Entry.SecondLevelPageStart) << ", "
3688 << "LSDA offset=" << format("0x%08" PRIx32, Entry.LSDAStart) << '\n';
3691 //===----------------------------------
3692 // Next come the LSDA tables
3693 //===----------------------------------
3695 // The LSDA layout is rather implicit: it's a contiguous array of entries from
3696 // the first top-level index's LSDAOffset to the last (sentinel).
3698 outs() << " LSDA descriptors:\n";
3699 Pos = Contents.data() + IndexEntries[0].LSDAStart;
3700 int NumLSDAs = (IndexEntries.back().LSDAStart - IndexEntries[0].LSDAStart) /
3701 (2 * sizeof(uint32_t));
3702 for (int i = 0; i < NumLSDAs; ++i) {
3703 uint32_t FunctionOffset = readNext<uint32_t>(Pos);
3704 uint32_t LSDAOffset = readNext<uint32_t>(Pos);
3705 outs() << " [" << i << "]: "
3706 << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
3708 << "LSDA offset=" << format("0x%08" PRIx32, LSDAOffset) << '\n';
3711 //===----------------------------------
3712 // Finally, the 2nd level indices
3713 //===----------------------------------
3715 // Generally these are 4K in size, and have 2 possible forms:
3716 // + Regular stores up to 511 entries with disparate encodings
3717 // + Compressed stores up to 1021 entries if few enough compact encoding
3719 outs() << " Second level indices:\n";
3720 for (unsigned i = 0; i < IndexEntries.size() - 1; ++i) {
3721 // The final sentinel top-level index has no associated 2nd level page
3722 if (IndexEntries[i].SecondLevelPageStart == 0)
3725 outs() << " Second level index[" << i << "]: "
3726 << "offset in section="
3727 << format("0x%08" PRIx32, IndexEntries[i].SecondLevelPageStart)
3729 << "base function offset="
3730 << format("0x%08" PRIx32, IndexEntries[i].FunctionOffset) << '\n';
3732 Pos = Contents.data() + IndexEntries[i].SecondLevelPageStart;
3733 uint32_t Kind = *reinterpret_cast<const support::ulittle32_t *>(Pos);
3735 printRegularSecondLevelUnwindPage(Pos);
3737 printCompressedSecondLevelUnwindPage(Pos, IndexEntries[i].FunctionOffset,
3740 llvm_unreachable("Do not know how to print this kind of 2nd level page");
3744 void llvm::printMachOUnwindInfo(const MachOObjectFile *Obj) {
3745 std::map<uint64_t, SymbolRef> Symbols;
3746 for (const SymbolRef &SymRef : Obj->symbols()) {
3747 // Discard any undefined or absolute symbols. They're not going to take part
3748 // in the convenience lookup for unwind info and just take up resources.
3749 section_iterator Section = Obj->section_end();
3750 SymRef.getSection(Section);
3751 if (Section == Obj->section_end())
3755 SymRef.getAddress(Addr);
3756 Symbols.insert(std::make_pair(Addr, SymRef));
3759 for (const SectionRef &Section : Obj->sections()) {
3761 Section.getName(SectName);
3762 if (SectName == "__compact_unwind")
3763 printMachOCompactUnwindSection(Obj, Symbols, Section);
3764 else if (SectName == "__unwind_info")
3765 printMachOUnwindInfoSection(Obj, Symbols, Section);
3766 else if (SectName == "__eh_frame")
3767 outs() << "llvm-objdump: warning: unhandled __eh_frame section\n";
3771 static void PrintMachHeader(uint32_t magic, uint32_t cputype,
3772 uint32_t cpusubtype, uint32_t filetype,
3773 uint32_t ncmds, uint32_t sizeofcmds, uint32_t flags,
3775 outs() << "Mach header\n";
3776 outs() << " magic cputype cpusubtype caps filetype ncmds "
3777 "sizeofcmds flags\n";
3779 if (magic == MachO::MH_MAGIC)
3780 outs() << " MH_MAGIC";
3781 else if (magic == MachO::MH_MAGIC_64)
3782 outs() << "MH_MAGIC_64";
3784 outs() << format(" 0x%08" PRIx32, magic);
3786 case MachO::CPU_TYPE_I386:
3788 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
3789 case MachO::CPU_SUBTYPE_I386_ALL:
3793 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
3797 case MachO::CPU_TYPE_X86_64:
3798 outs() << " X86_64";
3799 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
3800 case MachO::CPU_SUBTYPE_X86_64_ALL:
3803 case MachO::CPU_SUBTYPE_X86_64_H:
3804 outs() << " Haswell";
3807 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
3811 case MachO::CPU_TYPE_ARM:
3813 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
3814 case MachO::CPU_SUBTYPE_ARM_ALL:
3817 case MachO::CPU_SUBTYPE_ARM_V4T:
3820 case MachO::CPU_SUBTYPE_ARM_V5TEJ:
3823 case MachO::CPU_SUBTYPE_ARM_XSCALE:
3824 outs() << " XSCALE";
3826 case MachO::CPU_SUBTYPE_ARM_V6:
3829 case MachO::CPU_SUBTYPE_ARM_V6M:
3832 case MachO::CPU_SUBTYPE_ARM_V7:
3835 case MachO::CPU_SUBTYPE_ARM_V7EM:
3838 case MachO::CPU_SUBTYPE_ARM_V7K:
3841 case MachO::CPU_SUBTYPE_ARM_V7M:
3844 case MachO::CPU_SUBTYPE_ARM_V7S:
3848 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
3852 case MachO::CPU_TYPE_ARM64:
3854 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
3855 case MachO::CPU_SUBTYPE_ARM64_ALL:
3859 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
3863 case MachO::CPU_TYPE_POWERPC:
3865 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
3866 case MachO::CPU_SUBTYPE_POWERPC_ALL:
3870 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
3874 case MachO::CPU_TYPE_POWERPC64:
3876 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
3877 case MachO::CPU_SUBTYPE_POWERPC_ALL:
3881 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
3886 if ((cpusubtype & MachO::CPU_SUBTYPE_MASK) == MachO::CPU_SUBTYPE_LIB64) {
3889 outs() << format(" 0x%02" PRIx32,
3890 (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24);
3893 case MachO::MH_OBJECT:
3894 outs() << " OBJECT";
3896 case MachO::MH_EXECUTE:
3897 outs() << " EXECUTE";
3899 case MachO::MH_FVMLIB:
3900 outs() << " FVMLIB";
3902 case MachO::MH_CORE:
3905 case MachO::MH_PRELOAD:
3906 outs() << " PRELOAD";
3908 case MachO::MH_DYLIB:
3911 case MachO::MH_DYLIB_STUB:
3912 outs() << " DYLIB_STUB";
3914 case MachO::MH_DYLINKER:
3915 outs() << " DYLINKER";
3917 case MachO::MH_BUNDLE:
3918 outs() << " BUNDLE";
3920 case MachO::MH_DSYM:
3923 case MachO::MH_KEXT_BUNDLE:
3924 outs() << " KEXTBUNDLE";
3927 outs() << format(" %10u", filetype);
3930 outs() << format(" %5u", ncmds);
3931 outs() << format(" %10u", sizeofcmds);
3933 if (f & MachO::MH_NOUNDEFS) {
3934 outs() << " NOUNDEFS";
3935 f &= ~MachO::MH_NOUNDEFS;
3937 if (f & MachO::MH_INCRLINK) {
3938 outs() << " INCRLINK";
3939 f &= ~MachO::MH_INCRLINK;
3941 if (f & MachO::MH_DYLDLINK) {
3942 outs() << " DYLDLINK";
3943 f &= ~MachO::MH_DYLDLINK;
3945 if (f & MachO::MH_BINDATLOAD) {
3946 outs() << " BINDATLOAD";
3947 f &= ~MachO::MH_BINDATLOAD;
3949 if (f & MachO::MH_PREBOUND) {
3950 outs() << " PREBOUND";
3951 f &= ~MachO::MH_PREBOUND;
3953 if (f & MachO::MH_SPLIT_SEGS) {
3954 outs() << " SPLIT_SEGS";
3955 f &= ~MachO::MH_SPLIT_SEGS;
3957 if (f & MachO::MH_LAZY_INIT) {
3958 outs() << " LAZY_INIT";
3959 f &= ~MachO::MH_LAZY_INIT;
3961 if (f & MachO::MH_TWOLEVEL) {
3962 outs() << " TWOLEVEL";
3963 f &= ~MachO::MH_TWOLEVEL;
3965 if (f & MachO::MH_FORCE_FLAT) {
3966 outs() << " FORCE_FLAT";
3967 f &= ~MachO::MH_FORCE_FLAT;
3969 if (f & MachO::MH_NOMULTIDEFS) {
3970 outs() << " NOMULTIDEFS";
3971 f &= ~MachO::MH_NOMULTIDEFS;
3973 if (f & MachO::MH_NOFIXPREBINDING) {
3974 outs() << " NOFIXPREBINDING";
3975 f &= ~MachO::MH_NOFIXPREBINDING;
3977 if (f & MachO::MH_PREBINDABLE) {
3978 outs() << " PREBINDABLE";
3979 f &= ~MachO::MH_PREBINDABLE;
3981 if (f & MachO::MH_ALLMODSBOUND) {
3982 outs() << " ALLMODSBOUND";
3983 f &= ~MachO::MH_ALLMODSBOUND;
3985 if (f & MachO::MH_SUBSECTIONS_VIA_SYMBOLS) {
3986 outs() << " SUBSECTIONS_VIA_SYMBOLS";
3987 f &= ~MachO::MH_SUBSECTIONS_VIA_SYMBOLS;
3989 if (f & MachO::MH_CANONICAL) {
3990 outs() << " CANONICAL";
3991 f &= ~MachO::MH_CANONICAL;
3993 if (f & MachO::MH_WEAK_DEFINES) {
3994 outs() << " WEAK_DEFINES";
3995 f &= ~MachO::MH_WEAK_DEFINES;
3997 if (f & MachO::MH_BINDS_TO_WEAK) {
3998 outs() << " BINDS_TO_WEAK";
3999 f &= ~MachO::MH_BINDS_TO_WEAK;
4001 if (f & MachO::MH_ALLOW_STACK_EXECUTION) {
4002 outs() << " ALLOW_STACK_EXECUTION";
4003 f &= ~MachO::MH_ALLOW_STACK_EXECUTION;
4005 if (f & MachO::MH_DEAD_STRIPPABLE_DYLIB) {
4006 outs() << " DEAD_STRIPPABLE_DYLIB";
4007 f &= ~MachO::MH_DEAD_STRIPPABLE_DYLIB;
4009 if (f & MachO::MH_PIE) {
4011 f &= ~MachO::MH_PIE;
4013 if (f & MachO::MH_NO_REEXPORTED_DYLIBS) {
4014 outs() << " NO_REEXPORTED_DYLIBS";
4015 f &= ~MachO::MH_NO_REEXPORTED_DYLIBS;
4017 if (f & MachO::MH_HAS_TLV_DESCRIPTORS) {
4018 outs() << " MH_HAS_TLV_DESCRIPTORS";
4019 f &= ~MachO::MH_HAS_TLV_DESCRIPTORS;
4021 if (f & MachO::MH_NO_HEAP_EXECUTION) {
4022 outs() << " MH_NO_HEAP_EXECUTION";
4023 f &= ~MachO::MH_NO_HEAP_EXECUTION;
4025 if (f & MachO::MH_APP_EXTENSION_SAFE) {
4026 outs() << " APP_EXTENSION_SAFE";
4027 f &= ~MachO::MH_APP_EXTENSION_SAFE;
4029 if (f != 0 || flags == 0)
4030 outs() << format(" 0x%08" PRIx32, f);
4032 outs() << format(" 0x%08" PRIx32, magic);
4033 outs() << format(" %7d", cputype);
4034 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
4035 outs() << format(" 0x%02" PRIx32,
4036 (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24);
4037 outs() << format(" %10u", filetype);
4038 outs() << format(" %5u", ncmds);
4039 outs() << format(" %10u", sizeofcmds);
4040 outs() << format(" 0x%08" PRIx32, flags);
4045 static void PrintSegmentCommand(uint32_t cmd, uint32_t cmdsize,
4046 StringRef SegName, uint64_t vmaddr,
4047 uint64_t vmsize, uint64_t fileoff,
4048 uint64_t filesize, uint32_t maxprot,
4049 uint32_t initprot, uint32_t nsects,
4050 uint32_t flags, uint32_t object_size,
4052 uint64_t expected_cmdsize;
4053 if (cmd == MachO::LC_SEGMENT) {
4054 outs() << " cmd LC_SEGMENT\n";
4055 expected_cmdsize = nsects;
4056 expected_cmdsize *= sizeof(struct MachO::section);
4057 expected_cmdsize += sizeof(struct MachO::segment_command);
4059 outs() << " cmd LC_SEGMENT_64\n";
4060 expected_cmdsize = nsects;
4061 expected_cmdsize *= sizeof(struct MachO::section_64);
4062 expected_cmdsize += sizeof(struct MachO::segment_command_64);
4064 outs() << " cmdsize " << cmdsize;
4065 if (cmdsize != expected_cmdsize)
4066 outs() << " Inconsistent size\n";
4069 outs() << " segname " << SegName << "\n";
4070 if (cmd == MachO::LC_SEGMENT_64) {
4071 outs() << " vmaddr " << format("0x%016" PRIx64, vmaddr) << "\n";
4072 outs() << " vmsize " << format("0x%016" PRIx64, vmsize) << "\n";
4074 outs() << " vmaddr " << format("0x%08" PRIx64, vmaddr) << "\n";
4075 outs() << " vmsize " << format("0x%08" PRIx64, vmsize) << "\n";
4077 outs() << " fileoff " << fileoff;
4078 if (fileoff > object_size)
4079 outs() << " (past end of file)\n";
4082 outs() << " filesize " << filesize;
4083 if (fileoff + filesize > object_size)
4084 outs() << " (past end of file)\n";
4089 ~(MachO::VM_PROT_READ | MachO::VM_PROT_WRITE |
4090 MachO::VM_PROT_EXECUTE)) != 0)
4091 outs() << " maxprot ?" << format("0x%08" PRIx32, maxprot) << "\n";
4093 if (maxprot & MachO::VM_PROT_READ)
4094 outs() << " maxprot r";
4096 outs() << " maxprot -";
4097 if (maxprot & MachO::VM_PROT_WRITE)
4101 if (maxprot & MachO::VM_PROT_EXECUTE)
4107 ~(MachO::VM_PROT_READ | MachO::VM_PROT_WRITE |
4108 MachO::VM_PROT_EXECUTE)) != 0)
4109 outs() << " initprot ?" << format("0x%08" PRIx32, initprot) << "\n";
4111 if (initprot & MachO::VM_PROT_READ)
4112 outs() << " initprot r";
4114 outs() << " initprot -";
4115 if (initprot & MachO::VM_PROT_WRITE)
4119 if (initprot & MachO::VM_PROT_EXECUTE)
4125 outs() << " maxprot " << format("0x%08" PRIx32, maxprot) << "\n";
4126 outs() << " initprot " << format("0x%08" PRIx32, initprot) << "\n";
4128 outs() << " nsects " << nsects << "\n";
4132 outs() << " (none)\n";
4134 if (flags & MachO::SG_HIGHVM) {
4135 outs() << " HIGHVM";
4136 flags &= ~MachO::SG_HIGHVM;
4138 if (flags & MachO::SG_FVMLIB) {
4139 outs() << " FVMLIB";
4140 flags &= ~MachO::SG_FVMLIB;
4142 if (flags & MachO::SG_NORELOC) {
4143 outs() << " NORELOC";
4144 flags &= ~MachO::SG_NORELOC;
4146 if (flags & MachO::SG_PROTECTED_VERSION_1) {
4147 outs() << " PROTECTED_VERSION_1";
4148 flags &= ~MachO::SG_PROTECTED_VERSION_1;
4151 outs() << format(" 0x%08" PRIx32, flags) << " (unknown flags)\n";
4156 outs() << " flags " << format("0x%" PRIx32, flags) << "\n";
4160 static void PrintSection(const char *sectname, const char *segname,
4161 uint64_t addr, uint64_t size, uint32_t offset,
4162 uint32_t align, uint32_t reloff, uint32_t nreloc,
4163 uint32_t flags, uint32_t reserved1, uint32_t reserved2,
4164 uint32_t cmd, const char *sg_segname,
4165 uint32_t filetype, uint32_t object_size,
4167 outs() << "Section\n";
4168 outs() << " sectname " << format("%.16s\n", sectname);
4169 outs() << " segname " << format("%.16s", segname);
4170 if (filetype != MachO::MH_OBJECT && strncmp(sg_segname, segname, 16) != 0)
4171 outs() << " (does not match segment)\n";
4174 if (cmd == MachO::LC_SEGMENT_64) {
4175 outs() << " addr " << format("0x%016" PRIx64, addr) << "\n";
4176 outs() << " size " << format("0x%016" PRIx64, size);
4178 outs() << " addr " << format("0x%08" PRIx64, addr) << "\n";
4179 outs() << " size " << format("0x%08" PRIx64, size);
4181 if ((flags & MachO::S_ZEROFILL) != 0 && offset + size > object_size)
4182 outs() << " (past end of file)\n";
4185 outs() << " offset " << offset;
4186 if (offset > object_size)
4187 outs() << " (past end of file)\n";
4190 uint32_t align_shifted = 1 << align;
4191 outs() << " align 2^" << align << " (" << align_shifted << ")\n";
4192 outs() << " reloff " << reloff;
4193 if (reloff > object_size)
4194 outs() << " (past end of file)\n";
4197 outs() << " nreloc " << nreloc;
4198 if (reloff + nreloc * sizeof(struct MachO::relocation_info) > object_size)
4199 outs() << " (past end of file)\n";
4202 uint32_t section_type = flags & MachO::SECTION_TYPE;
4205 if (section_type == MachO::S_REGULAR)
4206 outs() << " S_REGULAR\n";
4207 else if (section_type == MachO::S_ZEROFILL)
4208 outs() << " S_ZEROFILL\n";
4209 else if (section_type == MachO::S_CSTRING_LITERALS)
4210 outs() << " S_CSTRING_LITERALS\n";
4211 else if (section_type == MachO::S_4BYTE_LITERALS)
4212 outs() << " S_4BYTE_LITERALS\n";
4213 else if (section_type == MachO::S_8BYTE_LITERALS)
4214 outs() << " S_8BYTE_LITERALS\n";
4215 else if (section_type == MachO::S_16BYTE_LITERALS)
4216 outs() << " S_16BYTE_LITERALS\n";
4217 else if (section_type == MachO::S_LITERAL_POINTERS)
4218 outs() << " S_LITERAL_POINTERS\n";
4219 else if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS)
4220 outs() << " S_NON_LAZY_SYMBOL_POINTERS\n";
4221 else if (section_type == MachO::S_LAZY_SYMBOL_POINTERS)
4222 outs() << " S_LAZY_SYMBOL_POINTERS\n";
4223 else if (section_type == MachO::S_SYMBOL_STUBS)
4224 outs() << " S_SYMBOL_STUBS\n";
4225 else if (section_type == MachO::S_MOD_INIT_FUNC_POINTERS)
4226 outs() << " S_MOD_INIT_FUNC_POINTERS\n";
4227 else if (section_type == MachO::S_MOD_TERM_FUNC_POINTERS)
4228 outs() << " S_MOD_TERM_FUNC_POINTERS\n";
4229 else if (section_type == MachO::S_COALESCED)
4230 outs() << " S_COALESCED\n";
4231 else if (section_type == MachO::S_INTERPOSING)
4232 outs() << " S_INTERPOSING\n";
4233 else if (section_type == MachO::S_DTRACE_DOF)
4234 outs() << " S_DTRACE_DOF\n";
4235 else if (section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS)
4236 outs() << " S_LAZY_DYLIB_SYMBOL_POINTERS\n";
4237 else if (section_type == MachO::S_THREAD_LOCAL_REGULAR)
4238 outs() << " S_THREAD_LOCAL_REGULAR\n";
4239 else if (section_type == MachO::S_THREAD_LOCAL_ZEROFILL)
4240 outs() << " S_THREAD_LOCAL_ZEROFILL\n";
4241 else if (section_type == MachO::S_THREAD_LOCAL_VARIABLES)
4242 outs() << " S_THREAD_LOCAL_VARIABLES\n";
4243 else if (section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS)
4244 outs() << " S_THREAD_LOCAL_VARIABLE_POINTERS\n";
4245 else if (section_type == MachO::S_THREAD_LOCAL_INIT_FUNCTION_POINTERS)
4246 outs() << " S_THREAD_LOCAL_INIT_FUNCTION_POINTERS\n";
4248 outs() << format("0x%08" PRIx32, section_type) << "\n";
4249 outs() << "attributes";
4250 uint32_t section_attributes = flags & MachO::SECTION_ATTRIBUTES;
4251 if (section_attributes & MachO::S_ATTR_PURE_INSTRUCTIONS)
4252 outs() << " PURE_INSTRUCTIONS";
4253 if (section_attributes & MachO::S_ATTR_NO_TOC)
4254 outs() << " NO_TOC";
4255 if (section_attributes & MachO::S_ATTR_STRIP_STATIC_SYMS)
4256 outs() << " STRIP_STATIC_SYMS";
4257 if (section_attributes & MachO::S_ATTR_NO_DEAD_STRIP)
4258 outs() << " NO_DEAD_STRIP";
4259 if (section_attributes & MachO::S_ATTR_LIVE_SUPPORT)
4260 outs() << " LIVE_SUPPORT";
4261 if (section_attributes & MachO::S_ATTR_SELF_MODIFYING_CODE)
4262 outs() << " SELF_MODIFYING_CODE";
4263 if (section_attributes & MachO::S_ATTR_DEBUG)
4265 if (section_attributes & MachO::S_ATTR_SOME_INSTRUCTIONS)
4266 outs() << " SOME_INSTRUCTIONS";
4267 if (section_attributes & MachO::S_ATTR_EXT_RELOC)
4268 outs() << " EXT_RELOC";
4269 if (section_attributes & MachO::S_ATTR_LOC_RELOC)
4270 outs() << " LOC_RELOC";
4271 if (section_attributes == 0)
4272 outs() << " (none)";
4275 outs() << " flags " << format("0x%08" PRIx32, flags) << "\n";
4276 outs() << " reserved1 " << reserved1;
4277 if (section_type == MachO::S_SYMBOL_STUBS ||
4278 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
4279 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
4280 section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
4281 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS)
4282 outs() << " (index into indirect symbol table)\n";
4285 outs() << " reserved2 " << reserved2;
4286 if (section_type == MachO::S_SYMBOL_STUBS)
4287 outs() << " (size of stubs)\n";
4292 static void PrintSymtabLoadCommand(MachO::symtab_command st, bool Is64Bit,
4293 uint32_t object_size) {
4294 outs() << " cmd LC_SYMTAB\n";
4295 outs() << " cmdsize " << st.cmdsize;
4296 if (st.cmdsize != sizeof(struct MachO::symtab_command))
4297 outs() << " Incorrect size\n";
4300 outs() << " symoff " << st.symoff;
4301 if (st.symoff > object_size)
4302 outs() << " (past end of file)\n";
4305 outs() << " nsyms " << st.nsyms;
4308 big_size = st.nsyms;
4309 big_size *= sizeof(struct MachO::nlist_64);
4310 big_size += st.symoff;
4311 if (big_size > object_size)
4312 outs() << " (past end of file)\n";
4316 big_size = st.nsyms;
4317 big_size *= sizeof(struct MachO::nlist);
4318 big_size += st.symoff;
4319 if (big_size > object_size)
4320 outs() << " (past end of file)\n";
4324 outs() << " stroff " << st.stroff;
4325 if (st.stroff > object_size)
4326 outs() << " (past end of file)\n";
4329 outs() << " strsize " << st.strsize;
4330 big_size = st.stroff;
4331 big_size += st.strsize;
4332 if (big_size > object_size)
4333 outs() << " (past end of file)\n";
4338 static void PrintDysymtabLoadCommand(MachO::dysymtab_command dyst,
4339 uint32_t nsyms, uint32_t object_size,
4341 outs() << " cmd LC_DYSYMTAB\n";
4342 outs() << " cmdsize " << dyst.cmdsize;
4343 if (dyst.cmdsize != sizeof(struct MachO::dysymtab_command))
4344 outs() << " Incorrect size\n";
4347 outs() << " ilocalsym " << dyst.ilocalsym;
4348 if (dyst.ilocalsym > nsyms)
4349 outs() << " (greater than the number of symbols)\n";
4352 outs() << " nlocalsym " << dyst.nlocalsym;
4354 big_size = dyst.ilocalsym;
4355 big_size += dyst.nlocalsym;
4356 if (big_size > nsyms)
4357 outs() << " (past the end of the symbol table)\n";
4360 outs() << " iextdefsym " << dyst.iextdefsym;
4361 if (dyst.iextdefsym > nsyms)
4362 outs() << " (greater than the number of symbols)\n";
4365 outs() << " nextdefsym " << dyst.nextdefsym;
4366 big_size = dyst.iextdefsym;
4367 big_size += dyst.nextdefsym;
4368 if (big_size > nsyms)
4369 outs() << " (past the end of the symbol table)\n";
4372 outs() << " iundefsym " << dyst.iundefsym;
4373 if (dyst.iundefsym > nsyms)
4374 outs() << " (greater than the number of symbols)\n";
4377 outs() << " nundefsym " << dyst.nundefsym;
4378 big_size = dyst.iundefsym;
4379 big_size += dyst.nundefsym;
4380 if (big_size > nsyms)
4381 outs() << " (past the end of the symbol table)\n";
4384 outs() << " tocoff " << dyst.tocoff;
4385 if (dyst.tocoff > object_size)
4386 outs() << " (past end of file)\n";
4389 outs() << " ntoc " << dyst.ntoc;
4390 big_size = dyst.ntoc;
4391 big_size *= sizeof(struct MachO::dylib_table_of_contents);
4392 big_size += dyst.tocoff;
4393 if (big_size > object_size)
4394 outs() << " (past end of file)\n";
4397 outs() << " modtaboff " << dyst.modtaboff;
4398 if (dyst.modtaboff > object_size)
4399 outs() << " (past end of file)\n";
4402 outs() << " nmodtab " << dyst.nmodtab;
4405 modtabend = dyst.nmodtab;
4406 modtabend *= sizeof(struct MachO::dylib_module_64);
4407 modtabend += dyst.modtaboff;
4409 modtabend = dyst.nmodtab;
4410 modtabend *= sizeof(struct MachO::dylib_module);
4411 modtabend += dyst.modtaboff;
4413 if (modtabend > object_size)
4414 outs() << " (past end of file)\n";
4417 outs() << " extrefsymoff " << dyst.extrefsymoff;
4418 if (dyst.extrefsymoff > object_size)
4419 outs() << " (past end of file)\n";
4422 outs() << " nextrefsyms " << dyst.nextrefsyms;
4423 big_size = dyst.nextrefsyms;
4424 big_size *= sizeof(struct MachO::dylib_reference);
4425 big_size += dyst.extrefsymoff;
4426 if (big_size > object_size)
4427 outs() << " (past end of file)\n";
4430 outs() << " indirectsymoff " << dyst.indirectsymoff;
4431 if (dyst.indirectsymoff > object_size)
4432 outs() << " (past end of file)\n";
4435 outs() << " nindirectsyms " << dyst.nindirectsyms;
4436 big_size = dyst.nindirectsyms;
4437 big_size *= sizeof(uint32_t);
4438 big_size += dyst.indirectsymoff;
4439 if (big_size > object_size)
4440 outs() << " (past end of file)\n";
4443 outs() << " extreloff " << dyst.extreloff;
4444 if (dyst.extreloff > object_size)
4445 outs() << " (past end of file)\n";
4448 outs() << " nextrel " << dyst.nextrel;
4449 big_size = dyst.nextrel;
4450 big_size *= sizeof(struct MachO::relocation_info);
4451 big_size += dyst.extreloff;
4452 if (big_size > object_size)
4453 outs() << " (past end of file)\n";
4456 outs() << " locreloff " << dyst.locreloff;
4457 if (dyst.locreloff > object_size)
4458 outs() << " (past end of file)\n";
4461 outs() << " nlocrel " << dyst.nlocrel;
4462 big_size = dyst.nlocrel;
4463 big_size *= sizeof(struct MachO::relocation_info);
4464 big_size += dyst.locreloff;
4465 if (big_size > object_size)
4466 outs() << " (past end of file)\n";
4471 static void PrintDyldInfoLoadCommand(MachO::dyld_info_command dc,
4472 uint32_t object_size) {
4473 if (dc.cmd == MachO::LC_DYLD_INFO)
4474 outs() << " cmd LC_DYLD_INFO\n";
4476 outs() << " cmd LC_DYLD_INFO_ONLY\n";
4477 outs() << " cmdsize " << dc.cmdsize;
4478 if (dc.cmdsize != sizeof(struct MachO::dyld_info_command))
4479 outs() << " Incorrect size\n";
4482 outs() << " rebase_off " << dc.rebase_off;
4483 if (dc.rebase_off > object_size)
4484 outs() << " (past end of file)\n";
4487 outs() << " rebase_size " << dc.rebase_size;
4489 big_size = dc.rebase_off;
4490 big_size += dc.rebase_size;
4491 if (big_size > object_size)
4492 outs() << " (past end of file)\n";
4495 outs() << " bind_off " << dc.bind_off;
4496 if (dc.bind_off > object_size)
4497 outs() << " (past end of file)\n";
4500 outs() << " bind_size " << dc.bind_size;
4501 big_size = dc.bind_off;
4502 big_size += dc.bind_size;
4503 if (big_size > object_size)
4504 outs() << " (past end of file)\n";
4507 outs() << " weak_bind_off " << dc.weak_bind_off;
4508 if (dc.weak_bind_off > object_size)
4509 outs() << " (past end of file)\n";
4512 outs() << " weak_bind_size " << dc.weak_bind_size;
4513 big_size = dc.weak_bind_off;
4514 big_size += dc.weak_bind_size;
4515 if (big_size > object_size)
4516 outs() << " (past end of file)\n";
4519 outs() << " lazy_bind_off " << dc.lazy_bind_off;
4520 if (dc.lazy_bind_off > object_size)
4521 outs() << " (past end of file)\n";
4524 outs() << " lazy_bind_size " << dc.lazy_bind_size;
4525 big_size = dc.lazy_bind_off;
4526 big_size += dc.lazy_bind_size;
4527 if (big_size > object_size)
4528 outs() << " (past end of file)\n";
4531 outs() << " export_off " << dc.export_off;
4532 if (dc.export_off > object_size)
4533 outs() << " (past end of file)\n";
4536 outs() << " export_size " << dc.export_size;
4537 big_size = dc.export_off;
4538 big_size += dc.export_size;
4539 if (big_size > object_size)
4540 outs() << " (past end of file)\n";
4545 static void PrintDyldLoadCommand(MachO::dylinker_command dyld,
4547 if (dyld.cmd == MachO::LC_ID_DYLINKER)
4548 outs() << " cmd LC_ID_DYLINKER\n";
4549 else if (dyld.cmd == MachO::LC_LOAD_DYLINKER)
4550 outs() << " cmd LC_LOAD_DYLINKER\n";
4551 else if (dyld.cmd == MachO::LC_DYLD_ENVIRONMENT)
4552 outs() << " cmd LC_DYLD_ENVIRONMENT\n";
4554 outs() << " cmd ?(" << dyld.cmd << ")\n";
4555 outs() << " cmdsize " << dyld.cmdsize;
4556 if (dyld.cmdsize < sizeof(struct MachO::dylinker_command))
4557 outs() << " Incorrect size\n";
4560 if (dyld.name >= dyld.cmdsize)
4561 outs() << " name ?(bad offset " << dyld.name << ")\n";
4563 const char *P = (const char *)(Ptr) + dyld.name;
4564 outs() << " name " << P << " (offset " << dyld.name << ")\n";
4568 static void PrintUuidLoadCommand(MachO::uuid_command uuid) {
4569 outs() << " cmd LC_UUID\n";
4570 outs() << " cmdsize " << uuid.cmdsize;
4571 if (uuid.cmdsize != sizeof(struct MachO::uuid_command))
4572 outs() << " Incorrect size\n";
4576 outs() << format("%02" PRIX32, uuid.uuid[0]);
4577 outs() << format("%02" PRIX32, uuid.uuid[1]);
4578 outs() << format("%02" PRIX32, uuid.uuid[2]);
4579 outs() << format("%02" PRIX32, uuid.uuid[3]);
4581 outs() << format("%02" PRIX32, uuid.uuid[4]);
4582 outs() << format("%02" PRIX32, uuid.uuid[5]);
4584 outs() << format("%02" PRIX32, uuid.uuid[6]);
4585 outs() << format("%02" PRIX32, uuid.uuid[7]);
4587 outs() << format("%02" PRIX32, uuid.uuid[8]);
4588 outs() << format("%02" PRIX32, uuid.uuid[9]);
4590 outs() << format("%02" PRIX32, uuid.uuid[10]);
4591 outs() << format("%02" PRIX32, uuid.uuid[11]);
4592 outs() << format("%02" PRIX32, uuid.uuid[12]);
4593 outs() << format("%02" PRIX32, uuid.uuid[13]);
4594 outs() << format("%02" PRIX32, uuid.uuid[14]);
4595 outs() << format("%02" PRIX32, uuid.uuid[15]);
4599 static void PrintRpathLoadCommand(MachO::rpath_command rpath, const char *Ptr) {
4600 outs() << " cmd LC_RPATH\n";
4601 outs() << " cmdsize " << rpath.cmdsize;
4602 if (rpath.cmdsize < sizeof(struct MachO::rpath_command))
4603 outs() << " Incorrect size\n";
4606 if (rpath.path >= rpath.cmdsize)
4607 outs() << " path ?(bad offset " << rpath.path << ")\n";
4609 const char *P = (const char *)(Ptr) + rpath.path;
4610 outs() << " path " << P << " (offset " << rpath.path << ")\n";
4614 static void PrintVersionMinLoadCommand(MachO::version_min_command vd) {
4615 if (vd.cmd == MachO::LC_VERSION_MIN_MACOSX)
4616 outs() << " cmd LC_VERSION_MIN_MACOSX\n";
4617 else if (vd.cmd == MachO::LC_VERSION_MIN_IPHONEOS)
4618 outs() << " cmd LC_VERSION_MIN_IPHONEOS\n";
4620 outs() << " cmd " << vd.cmd << " (?)\n";
4621 outs() << " cmdsize " << vd.cmdsize;
4622 if (vd.cmdsize != sizeof(struct MachO::version_min_command))
4623 outs() << " Incorrect size\n";
4626 outs() << " version " << ((vd.version >> 16) & 0xffff) << "."
4627 << ((vd.version >> 8) & 0xff);
4628 if ((vd.version & 0xff) != 0)
4629 outs() << "." << (vd.version & 0xff);
4632 outs() << " sdk n/a";
4634 outs() << " sdk " << ((vd.sdk >> 16) & 0xffff) << "."
4635 << ((vd.sdk >> 8) & 0xff);
4637 if ((vd.sdk & 0xff) != 0)
4638 outs() << "." << (vd.sdk & 0xff);
4642 static void PrintSourceVersionCommand(MachO::source_version_command sd) {
4643 outs() << " cmd LC_SOURCE_VERSION\n";
4644 outs() << " cmdsize " << sd.cmdsize;
4645 if (sd.cmdsize != sizeof(struct MachO::source_version_command))
4646 outs() << " Incorrect size\n";
4649 uint64_t a = (sd.version >> 40) & 0xffffff;
4650 uint64_t b = (sd.version >> 30) & 0x3ff;
4651 uint64_t c = (sd.version >> 20) & 0x3ff;
4652 uint64_t d = (sd.version >> 10) & 0x3ff;
4653 uint64_t e = sd.version & 0x3ff;
4654 outs() << " version " << a << "." << b;
4656 outs() << "." << c << "." << d << "." << e;
4658 outs() << "." << c << "." << d;
4664 static void PrintEntryPointCommand(MachO::entry_point_command ep) {
4665 outs() << " cmd LC_MAIN\n";
4666 outs() << " cmdsize " << ep.cmdsize;
4667 if (ep.cmdsize != sizeof(struct MachO::entry_point_command))
4668 outs() << " Incorrect size\n";
4671 outs() << " entryoff " << ep.entryoff << "\n";
4672 outs() << " stacksize " << ep.stacksize << "\n";
4675 static void PrintEncryptionInfoCommand(MachO::encryption_info_command ec,
4676 uint32_t object_size) {
4677 outs() << " cmd LC_ENCRYPTION_INFO\n";
4678 outs() << " cmdsize " << ec.cmdsize;
4679 if (ec.cmdsize != sizeof(struct MachO::encryption_info_command))
4680 outs() << " Incorrect size\n";
4683 outs() << " cryptoff " << ec.cryptoff;
4684 if (ec.cryptoff > object_size)
4685 outs() << " (past end of file)\n";
4688 outs() << " cryptsize " << ec.cryptsize;
4689 if (ec.cryptsize > object_size)
4690 outs() << " (past end of file)\n";
4693 outs() << " cryptid " << ec.cryptid << "\n";
4696 static void PrintEncryptionInfoCommand64(MachO::encryption_info_command_64 ec,
4697 uint32_t object_size) {
4698 outs() << " cmd LC_ENCRYPTION_INFO_64\n";
4699 outs() << " cmdsize " << ec.cmdsize;
4700 if (ec.cmdsize != sizeof(struct MachO::encryption_info_command_64))
4701 outs() << " Incorrect size\n";
4704 outs() << " cryptoff " << ec.cryptoff;
4705 if (ec.cryptoff > object_size)
4706 outs() << " (past end of file)\n";
4709 outs() << " cryptsize " << ec.cryptsize;
4710 if (ec.cryptsize > object_size)
4711 outs() << " (past end of file)\n";
4714 outs() << " cryptid " << ec.cryptid << "\n";
4715 outs() << " pad " << ec.pad << "\n";
4718 static void PrintLinkerOptionCommand(MachO::linker_option_command lo,
4720 outs() << " cmd LC_LINKER_OPTION\n";
4721 outs() << " cmdsize " << lo.cmdsize;
4722 if (lo.cmdsize < sizeof(struct MachO::linker_option_command))
4723 outs() << " Incorrect size\n";
4726 outs() << " count " << lo.count << "\n";
4727 const char *string = Ptr + sizeof(struct MachO::linker_option_command);
4728 uint32_t left = lo.cmdsize - sizeof(struct MachO::linker_option_command);
4731 while (*string == '\0' && left > 0) {
4737 outs() << " string #" << i << " " << format("%.*s\n", left, string);
4738 uint32_t NullPos = StringRef(string, left).find('\0');
4739 uint32_t len = std::min(NullPos, left) + 1;
4745 outs() << " count " << lo.count << " does not match number of strings "
4749 static void PrintSubFrameworkCommand(MachO::sub_framework_command sub,
4751 outs() << " cmd LC_SUB_FRAMEWORK\n";
4752 outs() << " cmdsize " << sub.cmdsize;
4753 if (sub.cmdsize < sizeof(struct MachO::sub_framework_command))
4754 outs() << " Incorrect size\n";
4757 if (sub.umbrella < sub.cmdsize) {
4758 const char *P = Ptr + sub.umbrella;
4759 outs() << " umbrella " << P << " (offset " << sub.umbrella << ")\n";
4761 outs() << " umbrella ?(bad offset " << sub.umbrella << ")\n";
4765 static void PrintSubUmbrellaCommand(MachO::sub_umbrella_command sub,
4767 outs() << " cmd LC_SUB_UMBRELLA\n";
4768 outs() << " cmdsize " << sub.cmdsize;
4769 if (sub.cmdsize < sizeof(struct MachO::sub_umbrella_command))
4770 outs() << " Incorrect size\n";
4773 if (sub.sub_umbrella < sub.cmdsize) {
4774 const char *P = Ptr + sub.sub_umbrella;
4775 outs() << " sub_umbrella " << P << " (offset " << sub.sub_umbrella << ")\n";
4777 outs() << " sub_umbrella ?(bad offset " << sub.sub_umbrella << ")\n";
4781 static void PrintSubLibraryCommand(MachO::sub_library_command sub,
4783 outs() << " cmd LC_SUB_LIBRARY\n";
4784 outs() << " cmdsize " << sub.cmdsize;
4785 if (sub.cmdsize < sizeof(struct MachO::sub_library_command))
4786 outs() << " Incorrect size\n";
4789 if (sub.sub_library < sub.cmdsize) {
4790 const char *P = Ptr + sub.sub_library;
4791 outs() << " sub_library " << P << " (offset " << sub.sub_library << ")\n";
4793 outs() << " sub_library ?(bad offset " << sub.sub_library << ")\n";
4797 static void PrintSubClientCommand(MachO::sub_client_command sub,
4799 outs() << " cmd LC_SUB_CLIENT\n";
4800 outs() << " cmdsize " << sub.cmdsize;
4801 if (sub.cmdsize < sizeof(struct MachO::sub_client_command))
4802 outs() << " Incorrect size\n";
4805 if (sub.client < sub.cmdsize) {
4806 const char *P = Ptr + sub.client;
4807 outs() << " client " << P << " (offset " << sub.client << ")\n";
4809 outs() << " client ?(bad offset " << sub.client << ")\n";
4813 static void PrintRoutinesCommand(MachO::routines_command r) {
4814 outs() << " cmd LC_ROUTINES\n";
4815 outs() << " cmdsize " << r.cmdsize;
4816 if (r.cmdsize != sizeof(struct MachO::routines_command))
4817 outs() << " Incorrect size\n";
4820 outs() << " init_address " << format("0x%08" PRIx32, r.init_address) << "\n";
4821 outs() << " init_module " << r.init_module << "\n";
4822 outs() << " reserved1 " << r.reserved1 << "\n";
4823 outs() << " reserved2 " << r.reserved2 << "\n";
4824 outs() << " reserved3 " << r.reserved3 << "\n";
4825 outs() << " reserved4 " << r.reserved4 << "\n";
4826 outs() << " reserved5 " << r.reserved5 << "\n";
4827 outs() << " reserved6 " << r.reserved6 << "\n";
4830 static void PrintRoutinesCommand64(MachO::routines_command_64 r) {
4831 outs() << " cmd LC_ROUTINES_64\n";
4832 outs() << " cmdsize " << r.cmdsize;
4833 if (r.cmdsize != sizeof(struct MachO::routines_command_64))
4834 outs() << " Incorrect size\n";
4837 outs() << " init_address " << format("0x%016" PRIx64, r.init_address) << "\n";
4838 outs() << " init_module " << r.init_module << "\n";
4839 outs() << " reserved1 " << r.reserved1 << "\n";
4840 outs() << " reserved2 " << r.reserved2 << "\n";
4841 outs() << " reserved3 " << r.reserved3 << "\n";
4842 outs() << " reserved4 " << r.reserved4 << "\n";
4843 outs() << " reserved5 " << r.reserved5 << "\n";
4844 outs() << " reserved6 " << r.reserved6 << "\n";
4847 static void Print_x86_thread_state64_t(MachO::x86_thread_state64_t &cpu64) {
4848 outs() << " rax " << format("0x%016" PRIx64, cpu64.rax);
4849 outs() << " rbx " << format("0x%016" PRIx64, cpu64.rbx);
4850 outs() << " rcx " << format("0x%016" PRIx64, cpu64.rcx) << "\n";
4851 outs() << " rdx " << format("0x%016" PRIx64, cpu64.rdx);
4852 outs() << " rdi " << format("0x%016" PRIx64, cpu64.rdi);
4853 outs() << " rsi " << format("0x%016" PRIx64, cpu64.rsi) << "\n";
4854 outs() << " rbp " << format("0x%016" PRIx64, cpu64.rbp);
4855 outs() << " rsp " << format("0x%016" PRIx64, cpu64.rsp);
4856 outs() << " r8 " << format("0x%016" PRIx64, cpu64.r8) << "\n";
4857 outs() << " r9 " << format("0x%016" PRIx64, cpu64.r9);
4858 outs() << " r10 " << format("0x%016" PRIx64, cpu64.r10);
4859 outs() << " r11 " << format("0x%016" PRIx64, cpu64.r11) << "\n";
4860 outs() << " r12 " << format("0x%016" PRIx64, cpu64.r12);
4861 outs() << " r13 " << format("0x%016" PRIx64, cpu64.r13);
4862 outs() << " r14 " << format("0x%016" PRIx64, cpu64.r14) << "\n";
4863 outs() << " r15 " << format("0x%016" PRIx64, cpu64.r15);
4864 outs() << " rip " << format("0x%016" PRIx64, cpu64.rip) << "\n";
4865 outs() << "rflags " << format("0x%016" PRIx64, cpu64.rflags);
4866 outs() << " cs " << format("0x%016" PRIx64, cpu64.cs);
4867 outs() << " fs " << format("0x%016" PRIx64, cpu64.fs) << "\n";
4868 outs() << " gs " << format("0x%016" PRIx64, cpu64.gs) << "\n";
4871 static void Print_mmst_reg(MachO::mmst_reg_t &r) {
4873 outs() << "\t mmst_reg ";
4874 for (f = 0; f < 10; f++)
4875 outs() << format("%02" PRIx32, (r.mmst_reg[f] & 0xff)) << " ";
4877 outs() << "\t mmst_rsrv ";
4878 for (f = 0; f < 6; f++)
4879 outs() << format("%02" PRIx32, (r.mmst_rsrv[f] & 0xff)) << " ";
4883 static void Print_xmm_reg(MachO::xmm_reg_t &r) {
4885 outs() << "\t xmm_reg ";
4886 for (f = 0; f < 16; f++)
4887 outs() << format("%02" PRIx32, (r.xmm_reg[f] & 0xff)) << " ";
4891 static void Print_x86_float_state_t(MachO::x86_float_state64_t &fpu) {
4892 outs() << "\t fpu_reserved[0] " << fpu.fpu_reserved[0];
4893 outs() << " fpu_reserved[1] " << fpu.fpu_reserved[1] << "\n";
4894 outs() << "\t control: invalid " << fpu.fpu_fcw.invalid;
4895 outs() << " denorm " << fpu.fpu_fcw.denorm;
4896 outs() << " zdiv " << fpu.fpu_fcw.zdiv;
4897 outs() << " ovrfl " << fpu.fpu_fcw.ovrfl;
4898 outs() << " undfl " << fpu.fpu_fcw.undfl;
4899 outs() << " precis " << fpu.fpu_fcw.precis << "\n";
4900 outs() << "\t\t pc ";
4901 if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_24B)
4902 outs() << "FP_PREC_24B ";
4903 else if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_53B)
4904 outs() << "FP_PREC_53B ";
4905 else if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_64B)
4906 outs() << "FP_PREC_64B ";
4908 outs() << fpu.fpu_fcw.pc << " ";
4910 if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_NEAR)
4911 outs() << "FP_RND_NEAR ";
4912 else if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_DOWN)
4913 outs() << "FP_RND_DOWN ";
4914 else if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_UP)
4915 outs() << "FP_RND_UP ";
4916 else if (fpu.fpu_fcw.rc == MachO::x86_FP_CHOP)
4917 outs() << "FP_CHOP ";
4919 outs() << "\t status: invalid " << fpu.fpu_fsw.invalid;
4920 outs() << " denorm " << fpu.fpu_fsw.denorm;
4921 outs() << " zdiv " << fpu.fpu_fsw.zdiv;
4922 outs() << " ovrfl " << fpu.fpu_fsw.ovrfl;
4923 outs() << " undfl " << fpu.fpu_fsw.undfl;
4924 outs() << " precis " << fpu.fpu_fsw.precis;
4925 outs() << " stkflt " << fpu.fpu_fsw.stkflt << "\n";
4926 outs() << "\t errsumm " << fpu.fpu_fsw.errsumm;
4927 outs() << " c0 " << fpu.fpu_fsw.c0;
4928 outs() << " c1 " << fpu.fpu_fsw.c1;
4929 outs() << " c2 " << fpu.fpu_fsw.c2;
4930 outs() << " tos " << fpu.fpu_fsw.tos;
4931 outs() << " c3 " << fpu.fpu_fsw.c3;
4932 outs() << " busy " << fpu.fpu_fsw.busy << "\n";
4933 outs() << "\t fpu_ftw " << format("0x%02" PRIx32, fpu.fpu_ftw);
4934 outs() << " fpu_rsrv1 " << format("0x%02" PRIx32, fpu.fpu_rsrv1);
4935 outs() << " fpu_fop " << format("0x%04" PRIx32, fpu.fpu_fop);
4936 outs() << " fpu_ip " << format("0x%08" PRIx32, fpu.fpu_ip) << "\n";
4937 outs() << "\t fpu_cs " << format("0x%04" PRIx32, fpu.fpu_cs);
4938 outs() << " fpu_rsrv2 " << format("0x%04" PRIx32, fpu.fpu_rsrv2);
4939 outs() << " fpu_dp " << format("0x%08" PRIx32, fpu.fpu_dp);
4940 outs() << " fpu_ds " << format("0x%04" PRIx32, fpu.fpu_ds) << "\n";
4941 outs() << "\t fpu_rsrv3 " << format("0x%04" PRIx32, fpu.fpu_rsrv3);
4942 outs() << " fpu_mxcsr " << format("0x%08" PRIx32, fpu.fpu_mxcsr);
4943 outs() << " fpu_mxcsrmask " << format("0x%08" PRIx32, fpu.fpu_mxcsrmask);
4945 outs() << "\t fpu_stmm0:\n";
4946 Print_mmst_reg(fpu.fpu_stmm0);
4947 outs() << "\t fpu_stmm1:\n";
4948 Print_mmst_reg(fpu.fpu_stmm1);
4949 outs() << "\t fpu_stmm2:\n";
4950 Print_mmst_reg(fpu.fpu_stmm2);
4951 outs() << "\t fpu_stmm3:\n";
4952 Print_mmst_reg(fpu.fpu_stmm3);
4953 outs() << "\t fpu_stmm4:\n";
4954 Print_mmst_reg(fpu.fpu_stmm4);
4955 outs() << "\t fpu_stmm5:\n";
4956 Print_mmst_reg(fpu.fpu_stmm5);
4957 outs() << "\t fpu_stmm6:\n";
4958 Print_mmst_reg(fpu.fpu_stmm6);
4959 outs() << "\t fpu_stmm7:\n";
4960 Print_mmst_reg(fpu.fpu_stmm7);
4961 outs() << "\t fpu_xmm0:\n";
4962 Print_xmm_reg(fpu.fpu_xmm0);
4963 outs() << "\t fpu_xmm1:\n";
4964 Print_xmm_reg(fpu.fpu_xmm1);
4965 outs() << "\t fpu_xmm2:\n";
4966 Print_xmm_reg(fpu.fpu_xmm2);
4967 outs() << "\t fpu_xmm3:\n";
4968 Print_xmm_reg(fpu.fpu_xmm3);
4969 outs() << "\t fpu_xmm4:\n";
4970 Print_xmm_reg(fpu.fpu_xmm4);
4971 outs() << "\t fpu_xmm5:\n";
4972 Print_xmm_reg(fpu.fpu_xmm5);
4973 outs() << "\t fpu_xmm6:\n";
4974 Print_xmm_reg(fpu.fpu_xmm6);
4975 outs() << "\t fpu_xmm7:\n";
4976 Print_xmm_reg(fpu.fpu_xmm7);
4977 outs() << "\t fpu_xmm8:\n";
4978 Print_xmm_reg(fpu.fpu_xmm8);
4979 outs() << "\t fpu_xmm9:\n";
4980 Print_xmm_reg(fpu.fpu_xmm9);
4981 outs() << "\t fpu_xmm10:\n";
4982 Print_xmm_reg(fpu.fpu_xmm10);
4983 outs() << "\t fpu_xmm11:\n";
4984 Print_xmm_reg(fpu.fpu_xmm11);
4985 outs() << "\t fpu_xmm12:\n";
4986 Print_xmm_reg(fpu.fpu_xmm12);
4987 outs() << "\t fpu_xmm13:\n";
4988 Print_xmm_reg(fpu.fpu_xmm13);
4989 outs() << "\t fpu_xmm14:\n";
4990 Print_xmm_reg(fpu.fpu_xmm14);
4991 outs() << "\t fpu_xmm15:\n";
4992 Print_xmm_reg(fpu.fpu_xmm15);
4993 outs() << "\t fpu_rsrv4:\n";
4994 for (uint32_t f = 0; f < 6; f++) {
4996 for (uint32_t g = 0; g < 16; g++)
4997 outs() << format("%02" PRIx32, fpu.fpu_rsrv4[f * g]) << " ";
5000 outs() << "\t fpu_reserved1 " << format("0x%08" PRIx32, fpu.fpu_reserved1);
5004 static void Print_x86_exception_state_t(MachO::x86_exception_state64_t &exc64) {
5005 outs() << "\t trapno " << format("0x%08" PRIx32, exc64.trapno);
5006 outs() << " err " << format("0x%08" PRIx32, exc64.err);
5007 outs() << " faultvaddr " << format("0x%016" PRIx64, exc64.faultvaddr) << "\n";
5010 static void PrintThreadCommand(MachO::thread_command t, const char *Ptr,
5011 bool isLittleEndian, uint32_t cputype) {
5012 if (t.cmd == MachO::LC_THREAD)
5013 outs() << " cmd LC_THREAD\n";
5014 else if (t.cmd == MachO::LC_UNIXTHREAD)
5015 outs() << " cmd LC_UNIXTHREAD\n";
5017 outs() << " cmd " << t.cmd << " (unknown)\n";
5018 outs() << " cmdsize " << t.cmdsize;
5019 if (t.cmdsize < sizeof(struct MachO::thread_command) + 2 * sizeof(uint32_t))
5020 outs() << " Incorrect size\n";
5024 const char *begin = Ptr + sizeof(struct MachO::thread_command);
5025 const char *end = Ptr + t.cmdsize;
5026 uint32_t flavor, count, left;
5027 if (cputype == MachO::CPU_TYPE_X86_64) {
5028 while (begin < end) {
5029 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
5030 memcpy((char *)&flavor, begin, sizeof(uint32_t));
5031 begin += sizeof(uint32_t);
5036 if (isLittleEndian != sys::IsLittleEndianHost)
5037 sys::swapByteOrder(flavor);
5038 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
5039 memcpy((char *)&count, begin, sizeof(uint32_t));
5040 begin += sizeof(uint32_t);
5045 if (isLittleEndian != sys::IsLittleEndianHost)
5046 sys::swapByteOrder(count);
5047 if (flavor == MachO::x86_THREAD_STATE64) {
5048 outs() << " flavor x86_THREAD_STATE64\n";
5049 if (count == MachO::x86_THREAD_STATE64_COUNT)
5050 outs() << " count x86_THREAD_STATE64_COUNT\n";
5052 outs() << " count " << count
5053 << " (not x86_THREAD_STATE64_COUNT)\n";
5054 MachO::x86_thread_state64_t cpu64;
5056 if (left >= sizeof(MachO::x86_thread_state64_t)) {
5057 memcpy(&cpu64, begin, sizeof(MachO::x86_thread_state64_t));
5058 begin += sizeof(MachO::x86_thread_state64_t);
5060 memset(&cpu64, '\0', sizeof(MachO::x86_thread_state64_t));
5061 memcpy(&cpu64, begin, left);
5064 if (isLittleEndian != sys::IsLittleEndianHost)
5066 Print_x86_thread_state64_t(cpu64);
5067 } else if (flavor == MachO::x86_THREAD_STATE) {
5068 outs() << " flavor x86_THREAD_STATE\n";
5069 if (count == MachO::x86_THREAD_STATE_COUNT)
5070 outs() << " count x86_THREAD_STATE_COUNT\n";
5072 outs() << " count " << count
5073 << " (not x86_THREAD_STATE_COUNT)\n";
5074 struct MachO::x86_thread_state_t ts;
5076 if (left >= sizeof(MachO::x86_thread_state_t)) {
5077 memcpy(&ts, begin, sizeof(MachO::x86_thread_state_t));
5078 begin += sizeof(MachO::x86_thread_state_t);
5080 memset(&ts, '\0', sizeof(MachO::x86_thread_state_t));
5081 memcpy(&ts, begin, left);
5084 if (isLittleEndian != sys::IsLittleEndianHost)
5086 if (ts.tsh.flavor == MachO::x86_THREAD_STATE64) {
5087 outs() << "\t tsh.flavor x86_THREAD_STATE64 ";
5088 if (ts.tsh.count == MachO::x86_THREAD_STATE64_COUNT)
5089 outs() << "tsh.count x86_THREAD_STATE64_COUNT\n";
5091 outs() << "tsh.count " << ts.tsh.count
5092 << " (not x86_THREAD_STATE64_COUNT\n";
5093 Print_x86_thread_state64_t(ts.uts.ts64);
5095 outs() << "\t tsh.flavor " << ts.tsh.flavor << " tsh.count "
5096 << ts.tsh.count << "\n";
5098 } else if (flavor == MachO::x86_FLOAT_STATE) {
5099 outs() << " flavor x86_FLOAT_STATE\n";
5100 if (count == MachO::x86_FLOAT_STATE_COUNT)
5101 outs() << " count x86_FLOAT_STATE_COUNT\n";
5103 outs() << " count " << count << " (not x86_FLOAT_STATE_COUNT)\n";
5104 struct MachO::x86_float_state_t fs;
5106 if (left >= sizeof(MachO::x86_float_state_t)) {
5107 memcpy(&fs, begin, sizeof(MachO::x86_float_state_t));
5108 begin += sizeof(MachO::x86_float_state_t);
5110 memset(&fs, '\0', sizeof(MachO::x86_float_state_t));
5111 memcpy(&fs, begin, left);
5114 if (isLittleEndian != sys::IsLittleEndianHost)
5116 if (fs.fsh.flavor == MachO::x86_FLOAT_STATE64) {
5117 outs() << "\t fsh.flavor x86_FLOAT_STATE64 ";
5118 if (fs.fsh.count == MachO::x86_FLOAT_STATE64_COUNT)
5119 outs() << "fsh.count x86_FLOAT_STATE64_COUNT\n";
5121 outs() << "fsh.count " << fs.fsh.count
5122 << " (not x86_FLOAT_STATE64_COUNT\n";
5123 Print_x86_float_state_t(fs.ufs.fs64);
5125 outs() << "\t fsh.flavor " << fs.fsh.flavor << " fsh.count "
5126 << fs.fsh.count << "\n";
5128 } else if (flavor == MachO::x86_EXCEPTION_STATE) {
5129 outs() << " flavor x86_EXCEPTION_STATE\n";
5130 if (count == MachO::x86_EXCEPTION_STATE_COUNT)
5131 outs() << " count x86_EXCEPTION_STATE_COUNT\n";
5133 outs() << " count " << count
5134 << " (not x86_EXCEPTION_STATE_COUNT)\n";
5135 struct MachO::x86_exception_state_t es;
5137 if (left >= sizeof(MachO::x86_exception_state_t)) {
5138 memcpy(&es, begin, sizeof(MachO::x86_exception_state_t));
5139 begin += sizeof(MachO::x86_exception_state_t);
5141 memset(&es, '\0', sizeof(MachO::x86_exception_state_t));
5142 memcpy(&es, begin, left);
5145 if (isLittleEndian != sys::IsLittleEndianHost)
5147 if (es.esh.flavor == MachO::x86_EXCEPTION_STATE64) {
5148 outs() << "\t esh.flavor x86_EXCEPTION_STATE64\n";
5149 if (es.esh.count == MachO::x86_EXCEPTION_STATE64_COUNT)
5150 outs() << "\t esh.count x86_EXCEPTION_STATE64_COUNT\n";
5152 outs() << "\t esh.count " << es.esh.count
5153 << " (not x86_EXCEPTION_STATE64_COUNT\n";
5154 Print_x86_exception_state_t(es.ues.es64);
5156 outs() << "\t esh.flavor " << es.esh.flavor << " esh.count "
5157 << es.esh.count << "\n";
5160 outs() << " flavor " << flavor << " (unknown)\n";
5161 outs() << " count " << count << "\n";
5162 outs() << " state (unknown)\n";
5163 begin += count * sizeof(uint32_t);
5167 while (begin < end) {
5168 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
5169 memcpy((char *)&flavor, begin, sizeof(uint32_t));
5170 begin += sizeof(uint32_t);
5175 if (isLittleEndian != sys::IsLittleEndianHost)
5176 sys::swapByteOrder(flavor);
5177 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
5178 memcpy((char *)&count, begin, sizeof(uint32_t));
5179 begin += sizeof(uint32_t);
5184 if (isLittleEndian != sys::IsLittleEndianHost)
5185 sys::swapByteOrder(count);
5186 outs() << " flavor " << flavor << "\n";
5187 outs() << " count " << count << "\n";
5188 outs() << " state (Unknown cputype/cpusubtype)\n";
5189 begin += count * sizeof(uint32_t);
5194 static void PrintDylibCommand(MachO::dylib_command dl, const char *Ptr) {
5195 if (dl.cmd == MachO::LC_ID_DYLIB)
5196 outs() << " cmd LC_ID_DYLIB\n";
5197 else if (dl.cmd == MachO::LC_LOAD_DYLIB)
5198 outs() << " cmd LC_LOAD_DYLIB\n";
5199 else if (dl.cmd == MachO::LC_LOAD_WEAK_DYLIB)
5200 outs() << " cmd LC_LOAD_WEAK_DYLIB\n";
5201 else if (dl.cmd == MachO::LC_REEXPORT_DYLIB)
5202 outs() << " cmd LC_REEXPORT_DYLIB\n";
5203 else if (dl.cmd == MachO::LC_LAZY_LOAD_DYLIB)
5204 outs() << " cmd LC_LAZY_LOAD_DYLIB\n";
5205 else if (dl.cmd == MachO::LC_LOAD_UPWARD_DYLIB)
5206 outs() << " cmd LC_LOAD_UPWARD_DYLIB\n";
5208 outs() << " cmd " << dl.cmd << " (unknown)\n";
5209 outs() << " cmdsize " << dl.cmdsize;
5210 if (dl.cmdsize < sizeof(struct MachO::dylib_command))
5211 outs() << " Incorrect size\n";
5214 if (dl.dylib.name < dl.cmdsize) {
5215 const char *P = (const char *)(Ptr) + dl.dylib.name;
5216 outs() << " name " << P << " (offset " << dl.dylib.name << ")\n";
5218 outs() << " name ?(bad offset " << dl.dylib.name << ")\n";
5220 outs() << " time stamp " << dl.dylib.timestamp << " ";
5221 time_t t = dl.dylib.timestamp;
5222 outs() << ctime(&t);
5223 outs() << " current version ";
5224 if (dl.dylib.current_version == 0xffffffff)
5227 outs() << ((dl.dylib.current_version >> 16) & 0xffff) << "."
5228 << ((dl.dylib.current_version >> 8) & 0xff) << "."
5229 << (dl.dylib.current_version & 0xff) << "\n";
5230 outs() << "compatibility version ";
5231 if (dl.dylib.compatibility_version == 0xffffffff)
5234 outs() << ((dl.dylib.compatibility_version >> 16) & 0xffff) << "."
5235 << ((dl.dylib.compatibility_version >> 8) & 0xff) << "."
5236 << (dl.dylib.compatibility_version & 0xff) << "\n";
5239 static void PrintLinkEditDataCommand(MachO::linkedit_data_command ld,
5240 uint32_t object_size) {
5241 if (ld.cmd == MachO::LC_CODE_SIGNATURE)
5242 outs() << " cmd LC_FUNCTION_STARTS\n";
5243 else if (ld.cmd == MachO::LC_SEGMENT_SPLIT_INFO)
5244 outs() << " cmd LC_SEGMENT_SPLIT_INFO\n";
5245 else if (ld.cmd == MachO::LC_FUNCTION_STARTS)
5246 outs() << " cmd LC_FUNCTION_STARTS\n";
5247 else if (ld.cmd == MachO::LC_DATA_IN_CODE)
5248 outs() << " cmd LC_DATA_IN_CODE\n";
5249 else if (ld.cmd == MachO::LC_DYLIB_CODE_SIGN_DRS)
5250 outs() << " cmd LC_DYLIB_CODE_SIGN_DRS\n";
5251 else if (ld.cmd == MachO::LC_LINKER_OPTIMIZATION_HINT)
5252 outs() << " cmd LC_LINKER_OPTIMIZATION_HINT\n";
5254 outs() << " cmd " << ld.cmd << " (?)\n";
5255 outs() << " cmdsize " << ld.cmdsize;
5256 if (ld.cmdsize != sizeof(struct MachO::linkedit_data_command))
5257 outs() << " Incorrect size\n";
5260 outs() << " dataoff " << ld.dataoff;
5261 if (ld.dataoff > object_size)
5262 outs() << " (past end of file)\n";
5265 outs() << " datasize " << ld.datasize;
5266 uint64_t big_size = ld.dataoff;
5267 big_size += ld.datasize;
5268 if (big_size > object_size)
5269 outs() << " (past end of file)\n";
5274 static void PrintLoadCommands(const MachOObjectFile *Obj, uint32_t ncmds,
5275 uint32_t filetype, uint32_t cputype,
5279 StringRef Buf = Obj->getData();
5280 MachOObjectFile::LoadCommandInfo Command = Obj->getFirstLoadCommandInfo();
5281 for (unsigned i = 0;; ++i) {
5282 outs() << "Load command " << i << "\n";
5283 if (Command.C.cmd == MachO::LC_SEGMENT) {
5284 MachO::segment_command SLC = Obj->getSegmentLoadCommand(Command);
5285 const char *sg_segname = SLC.segname;
5286 PrintSegmentCommand(SLC.cmd, SLC.cmdsize, SLC.segname, SLC.vmaddr,
5287 SLC.vmsize, SLC.fileoff, SLC.filesize, SLC.maxprot,
5288 SLC.initprot, SLC.nsects, SLC.flags, Buf.size(),
5290 for (unsigned j = 0; j < SLC.nsects; j++) {
5291 MachO::section S = Obj->getSection(Command, j);
5292 PrintSection(S.sectname, S.segname, S.addr, S.size, S.offset, S.align,
5293 S.reloff, S.nreloc, S.flags, S.reserved1, S.reserved2,
5294 SLC.cmd, sg_segname, filetype, Buf.size(), verbose);
5296 } else if (Command.C.cmd == MachO::LC_SEGMENT_64) {
5297 MachO::segment_command_64 SLC_64 = Obj->getSegment64LoadCommand(Command);
5298 const char *sg_segname = SLC_64.segname;
5299 PrintSegmentCommand(SLC_64.cmd, SLC_64.cmdsize, SLC_64.segname,
5300 SLC_64.vmaddr, SLC_64.vmsize, SLC_64.fileoff,
5301 SLC_64.filesize, SLC_64.maxprot, SLC_64.initprot,
5302 SLC_64.nsects, SLC_64.flags, Buf.size(), verbose);
5303 for (unsigned j = 0; j < SLC_64.nsects; j++) {
5304 MachO::section_64 S_64 = Obj->getSection64(Command, j);
5305 PrintSection(S_64.sectname, S_64.segname, S_64.addr, S_64.size,
5306 S_64.offset, S_64.align, S_64.reloff, S_64.nreloc,
5307 S_64.flags, S_64.reserved1, S_64.reserved2, SLC_64.cmd,
5308 sg_segname, filetype, Buf.size(), verbose);
5310 } else if (Command.C.cmd == MachO::LC_SYMTAB) {
5311 MachO::symtab_command Symtab = Obj->getSymtabLoadCommand();
5312 PrintSymtabLoadCommand(Symtab, Obj->is64Bit(), Buf.size());
5313 } else if (Command.C.cmd == MachO::LC_DYSYMTAB) {
5314 MachO::dysymtab_command Dysymtab = Obj->getDysymtabLoadCommand();
5315 MachO::symtab_command Symtab = Obj->getSymtabLoadCommand();
5316 PrintDysymtabLoadCommand(Dysymtab, Symtab.nsyms, Buf.size(),
5318 } else if (Command.C.cmd == MachO::LC_DYLD_INFO ||
5319 Command.C.cmd == MachO::LC_DYLD_INFO_ONLY) {
5320 MachO::dyld_info_command DyldInfo = Obj->getDyldInfoLoadCommand(Command);
5321 PrintDyldInfoLoadCommand(DyldInfo, Buf.size());
5322 } else if (Command.C.cmd == MachO::LC_LOAD_DYLINKER ||
5323 Command.C.cmd == MachO::LC_ID_DYLINKER ||
5324 Command.C.cmd == MachO::LC_DYLD_ENVIRONMENT) {
5325 MachO::dylinker_command Dyld = Obj->getDylinkerCommand(Command);
5326 PrintDyldLoadCommand(Dyld, Command.Ptr);
5327 } else if (Command.C.cmd == MachO::LC_UUID) {
5328 MachO::uuid_command Uuid = Obj->getUuidCommand(Command);
5329 PrintUuidLoadCommand(Uuid);
5330 } else if (Command.C.cmd == MachO::LC_RPATH) {
5331 MachO::rpath_command Rpath = Obj->getRpathCommand(Command);
5332 PrintRpathLoadCommand(Rpath, Command.Ptr);
5333 } else if (Command.C.cmd == MachO::LC_VERSION_MIN_MACOSX ||
5334 Command.C.cmd == MachO::LC_VERSION_MIN_IPHONEOS) {
5335 MachO::version_min_command Vd = Obj->getVersionMinLoadCommand(Command);
5336 PrintVersionMinLoadCommand(Vd);
5337 } else if (Command.C.cmd == MachO::LC_SOURCE_VERSION) {
5338 MachO::source_version_command Sd = Obj->getSourceVersionCommand(Command);
5339 PrintSourceVersionCommand(Sd);
5340 } else if (Command.C.cmd == MachO::LC_MAIN) {
5341 MachO::entry_point_command Ep = Obj->getEntryPointCommand(Command);
5342 PrintEntryPointCommand(Ep);
5343 } else if (Command.C.cmd == MachO::LC_ENCRYPTION_INFO) {
5344 MachO::encryption_info_command Ei =
5345 Obj->getEncryptionInfoCommand(Command);
5346 PrintEncryptionInfoCommand(Ei, Buf.size());
5347 } else if (Command.C.cmd == MachO::LC_ENCRYPTION_INFO_64) {
5348 MachO::encryption_info_command_64 Ei =
5349 Obj->getEncryptionInfoCommand64(Command);
5350 PrintEncryptionInfoCommand64(Ei, Buf.size());
5351 } else if (Command.C.cmd == MachO::LC_LINKER_OPTION) {
5352 MachO::linker_option_command Lo =
5353 Obj->getLinkerOptionLoadCommand(Command);
5354 PrintLinkerOptionCommand(Lo, Command.Ptr);
5355 } else if (Command.C.cmd == MachO::LC_SUB_FRAMEWORK) {
5356 MachO::sub_framework_command Sf = Obj->getSubFrameworkCommand(Command);
5357 PrintSubFrameworkCommand(Sf, Command.Ptr);
5358 } else if (Command.C.cmd == MachO::LC_SUB_UMBRELLA) {
5359 MachO::sub_umbrella_command Sf = Obj->getSubUmbrellaCommand(Command);
5360 PrintSubUmbrellaCommand(Sf, Command.Ptr);
5361 } else if (Command.C.cmd == MachO::LC_SUB_LIBRARY) {
5362 MachO::sub_library_command Sl = Obj->getSubLibraryCommand(Command);
5363 PrintSubLibraryCommand(Sl, Command.Ptr);
5364 } else if (Command.C.cmd == MachO::LC_SUB_CLIENT) {
5365 MachO::sub_client_command Sc = Obj->getSubClientCommand(Command);
5366 PrintSubClientCommand(Sc, Command.Ptr);
5367 } else if (Command.C.cmd == MachO::LC_ROUTINES) {
5368 MachO::routines_command Rc = Obj->getRoutinesCommand(Command);
5369 PrintRoutinesCommand(Rc);
5370 } else if (Command.C.cmd == MachO::LC_ROUTINES_64) {
5371 MachO::routines_command_64 Rc = Obj->getRoutinesCommand64(Command);
5372 PrintRoutinesCommand64(Rc);
5373 } else if (Command.C.cmd == MachO::LC_THREAD ||
5374 Command.C.cmd == MachO::LC_UNIXTHREAD) {
5375 MachO::thread_command Tc = Obj->getThreadCommand(Command);
5376 PrintThreadCommand(Tc, Command.Ptr, Obj->isLittleEndian(), cputype);
5377 } else if (Command.C.cmd == MachO::LC_LOAD_DYLIB ||
5378 Command.C.cmd == MachO::LC_ID_DYLIB ||
5379 Command.C.cmd == MachO::LC_LOAD_WEAK_DYLIB ||
5380 Command.C.cmd == MachO::LC_REEXPORT_DYLIB ||
5381 Command.C.cmd == MachO::LC_LAZY_LOAD_DYLIB ||
5382 Command.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB) {
5383 MachO::dylib_command Dl = Obj->getDylibIDLoadCommand(Command);
5384 PrintDylibCommand(Dl, Command.Ptr);
5385 } else if (Command.C.cmd == MachO::LC_CODE_SIGNATURE ||
5386 Command.C.cmd == MachO::LC_SEGMENT_SPLIT_INFO ||
5387 Command.C.cmd == MachO::LC_FUNCTION_STARTS ||
5388 Command.C.cmd == MachO::LC_DATA_IN_CODE ||
5389 Command.C.cmd == MachO::LC_DYLIB_CODE_SIGN_DRS ||
5390 Command.C.cmd == MachO::LC_LINKER_OPTIMIZATION_HINT) {
5391 MachO::linkedit_data_command Ld =
5392 Obj->getLinkeditDataLoadCommand(Command);
5393 PrintLinkEditDataCommand(Ld, Buf.size());
5395 outs() << " cmd ?(" << format("0x%08" PRIx32, Command.C.cmd)
5397 outs() << " cmdsize " << Command.C.cmdsize << "\n";
5398 // TODO: get and print the raw bytes of the load command.
5400 // TODO: print all the other kinds of load commands.
5404 Command = Obj->getNextLoadCommandInfo(Command);
5408 static void getAndPrintMachHeader(const MachOObjectFile *Obj, uint32_t &ncmds,
5409 uint32_t &filetype, uint32_t &cputype,
5411 if (Obj->is64Bit()) {
5412 MachO::mach_header_64 H_64;
5413 H_64 = Obj->getHeader64();
5414 PrintMachHeader(H_64.magic, H_64.cputype, H_64.cpusubtype, H_64.filetype,
5415 H_64.ncmds, H_64.sizeofcmds, H_64.flags, verbose);
5417 filetype = H_64.filetype;
5418 cputype = H_64.cputype;
5420 MachO::mach_header H;
5421 H = Obj->getHeader();
5422 PrintMachHeader(H.magic, H.cputype, H.cpusubtype, H.filetype, H.ncmds,
5423 H.sizeofcmds, H.flags, verbose);
5425 filetype = H.filetype;
5426 cputype = H.cputype;
5430 void llvm::printMachOFileHeader(const object::ObjectFile *Obj) {
5431 const MachOObjectFile *file = dyn_cast<const MachOObjectFile>(Obj);
5433 uint32_t filetype = 0;
5434 uint32_t cputype = 0;
5435 getAndPrintMachHeader(file, ncmds, filetype, cputype, true);
5436 PrintLoadCommands(file, ncmds, filetype, cputype, true);
5439 //===----------------------------------------------------------------------===//
5440 // export trie dumping
5441 //===----------------------------------------------------------------------===//
5443 void llvm::printMachOExportsTrie(const object::MachOObjectFile *Obj) {
5444 for (const llvm::object::ExportEntry &Entry : Obj->exports()) {
5445 uint64_t Flags = Entry.flags();
5446 bool ReExport = (Flags & MachO::EXPORT_SYMBOL_FLAGS_REEXPORT);
5447 bool WeakDef = (Flags & MachO::EXPORT_SYMBOL_FLAGS_WEAK_DEFINITION);
5448 bool ThreadLocal = ((Flags & MachO::EXPORT_SYMBOL_FLAGS_KIND_MASK) ==
5449 MachO::EXPORT_SYMBOL_FLAGS_KIND_THREAD_LOCAL);
5450 bool Abs = ((Flags & MachO::EXPORT_SYMBOL_FLAGS_KIND_MASK) ==
5451 MachO::EXPORT_SYMBOL_FLAGS_KIND_ABSOLUTE);
5452 bool Resolver = (Flags & MachO::EXPORT_SYMBOL_FLAGS_STUB_AND_RESOLVER);
5454 outs() << "[re-export] ";
5456 outs() << format("0x%08llX ",
5457 Entry.address()); // FIXME:add in base address
5458 outs() << Entry.name();
5459 if (WeakDef || ThreadLocal || Resolver || Abs) {
5460 bool NeedsComma = false;
5463 outs() << "weak_def";
5469 outs() << "per-thread";
5475 outs() << "absolute";
5481 outs() << format("resolver=0x%08llX", Entry.other());
5487 StringRef DylibName = "unknown";
5488 int Ordinal = Entry.other() - 1;
5489 Obj->getLibraryShortNameByIndex(Ordinal, DylibName);
5490 if (Entry.otherName().empty())
5491 outs() << " (from " << DylibName << ")";
5493 outs() << " (" << Entry.otherName() << " from " << DylibName << ")";
5499 //===----------------------------------------------------------------------===//
5500 // rebase table dumping
5501 //===----------------------------------------------------------------------===//
5506 SegInfo(const object::MachOObjectFile *Obj);
5508 StringRef segmentName(uint32_t SegIndex);
5509 StringRef sectionName(uint32_t SegIndex, uint64_t SegOffset);
5510 uint64_t address(uint32_t SegIndex, uint64_t SegOffset);
5513 struct SectionInfo {
5516 StringRef SectionName;
5517 StringRef SegmentName;
5518 uint64_t OffsetInSegment;
5519 uint64_t SegmentStartAddress;
5520 uint32_t SegmentIndex;
5522 const SectionInfo &findSection(uint32_t SegIndex, uint64_t SegOffset);
5523 SmallVector<SectionInfo, 32> Sections;
5527 SegInfo::SegInfo(const object::MachOObjectFile *Obj) {
5528 // Build table of sections so segIndex/offset pairs can be translated.
5529 uint32_t CurSegIndex = Obj->hasPageZeroSegment() ? 1 : 0;
5530 StringRef CurSegName;
5531 uint64_t CurSegAddress;
5532 for (const SectionRef &Section : Obj->sections()) {
5534 if (error(Section.getName(Info.SectionName)))
5536 Info.Address = Section.getAddress();
5537 Info.Size = Section.getSize();
5539 Obj->getSectionFinalSegmentName(Section.getRawDataRefImpl());
5540 if (!Info.SegmentName.equals(CurSegName)) {
5542 CurSegName = Info.SegmentName;
5543 CurSegAddress = Info.Address;
5545 Info.SegmentIndex = CurSegIndex - 1;
5546 Info.OffsetInSegment = Info.Address - CurSegAddress;
5547 Info.SegmentStartAddress = CurSegAddress;
5548 Sections.push_back(Info);
5552 StringRef SegInfo::segmentName(uint32_t SegIndex) {
5553 for (const SectionInfo &SI : Sections) {
5554 if (SI.SegmentIndex == SegIndex)
5555 return SI.SegmentName;
5557 llvm_unreachable("invalid segIndex");
5560 const SegInfo::SectionInfo &SegInfo::findSection(uint32_t SegIndex,
5561 uint64_t OffsetInSeg) {
5562 for (const SectionInfo &SI : Sections) {
5563 if (SI.SegmentIndex != SegIndex)
5565 if (SI.OffsetInSegment > OffsetInSeg)
5567 if (OffsetInSeg >= (SI.OffsetInSegment + SI.Size))
5571 llvm_unreachable("segIndex and offset not in any section");
5574 StringRef SegInfo::sectionName(uint32_t SegIndex, uint64_t OffsetInSeg) {
5575 return findSection(SegIndex, OffsetInSeg).SectionName;
5578 uint64_t SegInfo::address(uint32_t SegIndex, uint64_t OffsetInSeg) {
5579 const SectionInfo &SI = findSection(SegIndex, OffsetInSeg);
5580 return SI.SegmentStartAddress + OffsetInSeg;
5583 void llvm::printMachORebaseTable(const object::MachOObjectFile *Obj) {
5584 // Build table of sections so names can used in final output.
5585 SegInfo sectionTable(Obj);
5587 outs() << "segment section address type\n";
5588 for (const llvm::object::MachORebaseEntry &Entry : Obj->rebaseTable()) {
5589 uint32_t SegIndex = Entry.segmentIndex();
5590 uint64_t OffsetInSeg = Entry.segmentOffset();
5591 StringRef SegmentName = sectionTable.segmentName(SegIndex);
5592 StringRef SectionName = sectionTable.sectionName(SegIndex, OffsetInSeg);
5593 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
5595 // Table lines look like: __DATA __nl_symbol_ptr 0x0000F00C pointer
5596 outs() << format("%-8s %-18s 0x%08" PRIX64 " %s\n",
5597 SegmentName.str().c_str(), SectionName.str().c_str(),
5598 Address, Entry.typeName().str().c_str());
5602 static StringRef ordinalName(const object::MachOObjectFile *Obj, int Ordinal) {
5603 StringRef DylibName;
5605 case MachO::BIND_SPECIAL_DYLIB_SELF:
5606 return "this-image";
5607 case MachO::BIND_SPECIAL_DYLIB_MAIN_EXECUTABLE:
5608 return "main-executable";
5609 case MachO::BIND_SPECIAL_DYLIB_FLAT_LOOKUP:
5610 return "flat-namespace";
5613 std::error_code EC =
5614 Obj->getLibraryShortNameByIndex(Ordinal - 1, DylibName);
5616 return "<<bad library ordinal>>";
5620 return "<<unknown special ordinal>>";
5623 //===----------------------------------------------------------------------===//
5624 // bind table dumping
5625 //===----------------------------------------------------------------------===//
5627 void llvm::printMachOBindTable(const object::MachOObjectFile *Obj) {
5628 // Build table of sections so names can used in final output.
5629 SegInfo sectionTable(Obj);
5631 outs() << "segment section address type "
5632 "addend dylib symbol\n";
5633 for (const llvm::object::MachOBindEntry &Entry : Obj->bindTable()) {
5634 uint32_t SegIndex = Entry.segmentIndex();
5635 uint64_t OffsetInSeg = Entry.segmentOffset();
5636 StringRef SegmentName = sectionTable.segmentName(SegIndex);
5637 StringRef SectionName = sectionTable.sectionName(SegIndex, OffsetInSeg);
5638 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
5640 // Table lines look like:
5641 // __DATA __got 0x00012010 pointer 0 libSystem ___stack_chk_guard
5643 if (Entry.flags() & MachO::BIND_SYMBOL_FLAGS_WEAK_IMPORT)
5644 Attr = " (weak_import)";
5645 outs() << left_justify(SegmentName, 8) << " "
5646 << left_justify(SectionName, 18) << " "
5647 << format_hex(Address, 10, true) << " "
5648 << left_justify(Entry.typeName(), 8) << " "
5649 << format_decimal(Entry.addend(), 8) << " "
5650 << left_justify(ordinalName(Obj, Entry.ordinal()), 16) << " "
5651 << Entry.symbolName() << Attr << "\n";
5655 //===----------------------------------------------------------------------===//
5656 // lazy bind table dumping
5657 //===----------------------------------------------------------------------===//
5659 void llvm::printMachOLazyBindTable(const object::MachOObjectFile *Obj) {
5660 // Build table of sections so names can used in final output.
5661 SegInfo sectionTable(Obj);
5663 outs() << "segment section address "
5665 for (const llvm::object::MachOBindEntry &Entry : Obj->lazyBindTable()) {
5666 uint32_t SegIndex = Entry.segmentIndex();
5667 uint64_t OffsetInSeg = Entry.segmentOffset();
5668 StringRef SegmentName = sectionTable.segmentName(SegIndex);
5669 StringRef SectionName = sectionTable.sectionName(SegIndex, OffsetInSeg);
5670 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
5672 // Table lines look like:
5673 // __DATA __got 0x00012010 libSystem ___stack_chk_guard
5674 outs() << left_justify(SegmentName, 8) << " "
5675 << left_justify(SectionName, 18) << " "
5676 << format_hex(Address, 10, true) << " "
5677 << left_justify(ordinalName(Obj, Entry.ordinal()), 16) << " "
5678 << Entry.symbolName() << "\n";
5682 //===----------------------------------------------------------------------===//
5683 // weak bind table dumping
5684 //===----------------------------------------------------------------------===//
5686 void llvm::printMachOWeakBindTable(const object::MachOObjectFile *Obj) {
5687 // Build table of sections so names can used in final output.
5688 SegInfo sectionTable(Obj);
5690 outs() << "segment section address "
5691 "type addend symbol\n";
5692 for (const llvm::object::MachOBindEntry &Entry : Obj->weakBindTable()) {
5693 // Strong symbols don't have a location to update.
5694 if (Entry.flags() & MachO::BIND_SYMBOL_FLAGS_NON_WEAK_DEFINITION) {
5695 outs() << " strong "
5696 << Entry.symbolName() << "\n";
5699 uint32_t SegIndex = Entry.segmentIndex();
5700 uint64_t OffsetInSeg = Entry.segmentOffset();
5701 StringRef SegmentName = sectionTable.segmentName(SegIndex);
5702 StringRef SectionName = sectionTable.sectionName(SegIndex, OffsetInSeg);
5703 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
5705 // Table lines look like:
5706 // __DATA __data 0x00001000 pointer 0 _foo
5707 outs() << left_justify(SegmentName, 8) << " "
5708 << left_justify(SectionName, 18) << " "
5709 << format_hex(Address, 10, true) << " "
5710 << left_justify(Entry.typeName(), 8) << " "
5711 << format_decimal(Entry.addend(), 8) << " " << Entry.symbolName()
5716 // get_dyld_bind_info_symbolname() is used for disassembly and passed an
5717 // address, ReferenceValue, in the Mach-O file and looks in the dyld bind
5718 // information for that address. If the address is found its binding symbol
5719 // name is returned. If not nullptr is returned.
5720 static const char *get_dyld_bind_info_symbolname(uint64_t ReferenceValue,
5721 struct DisassembleInfo *info) {
5722 if (info->bindtable == nullptr) {
5723 info->bindtable = new (BindTable);
5724 SegInfo sectionTable(info->O);
5725 for (const llvm::object::MachOBindEntry &Entry : info->O->bindTable()) {
5726 uint32_t SegIndex = Entry.segmentIndex();
5727 uint64_t OffsetInSeg = Entry.segmentOffset();
5728 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
5729 const char *SymbolName = nullptr;
5730 StringRef name = Entry.symbolName();
5732 SymbolName = name.data();
5733 info->bindtable->push_back(std::make_pair(Address, SymbolName));
5736 for (bind_table_iterator BI = info->bindtable->begin(),
5737 BE = info->bindtable->end();
5739 uint64_t Address = BI->first;
5740 if (ReferenceValue == Address) {
5741 const char *SymbolName = BI->second;