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 DumpCstringSection(MachOObjectFile *O, const char *sect,
541 uint32_t sect_size, uint64_t sect_addr,
542 bool print_addresses) {
543 for (uint32_t i = 0; i < sect_size; i++) {
544 if (print_addresses) {
546 outs() << format("0x%016" PRIx64, sect_addr + i) << " ";
548 outs() << format("0x%08" PRIx64, sect_addr + i) << " ";
550 for (; i < sect_size && sect[i] != '\0'; i++) {
554 outs().write_escaped(p);
556 if (i < sect_size && sect[i] == '\0')
561 static void DumpLiteral4(uint32_t l, float f) {
562 outs() << format("0x%08" PRIx32, l);
563 if ((l & 0x7f800000) != 0x7f800000)
564 outs() << format(" (%.16e)\n", f);
567 outs() << " (+Infinity)\n";
568 else if (l == 0xff800000)
569 outs() << " (-Infinity)\n";
570 else if ((l & 0x00400000) == 0x00400000)
571 outs() << " (non-signaling Not-a-Number)\n";
573 outs() << " (signaling Not-a-Number)\n";
577 static void DumpLiteral4Section(MachOObjectFile *O, const char *sect,
578 uint32_t sect_size, uint64_t sect_addr,
579 bool print_addresses) {
580 for (uint32_t i = 0; i < sect_size; i += sizeof(float)) {
581 if (print_addresses) {
583 outs() << format("0x%016" PRIx64, sect_addr + i) << " ";
585 outs() << format("0x%08" PRIx64, sect_addr + i) << " ";
588 memcpy(&f, sect + i, sizeof(float));
589 if (O->isLittleEndian() != sys::IsLittleEndianHost)
590 sys::swapByteOrder(f);
592 memcpy(&l, sect + i, sizeof(uint32_t));
593 if (O->isLittleEndian() != sys::IsLittleEndianHost)
594 sys::swapByteOrder(l);
599 static void DumpLiteral8(MachOObjectFile *O, uint32_t l0, uint32_t l1,
601 outs() << format("0x%08" PRIx32, l0) << " " << format("0x%08" PRIx32, l1);
603 if (O->isLittleEndian()) {
610 // Hi is the high word, so this is equivalent to if(isfinite(d))
611 if ((Hi & 0x7ff00000) != 0x7ff00000)
612 outs() << format(" (%.16e)\n", d);
614 if (Hi == 0x7ff00000 && Lo == 0)
615 outs() << " (+Infinity)\n";
616 else if (Hi == 0xfff00000 && Lo == 0)
617 outs() << " (-Infinity)\n";
618 else if ((Hi & 0x00080000) == 0x00080000)
619 outs() << " (non-signaling Not-a-Number)\n";
621 outs() << " (signaling Not-a-Number)\n";
625 static void DumpLiteral8Section(MachOObjectFile *O, const char *sect,
626 uint32_t sect_size, uint64_t sect_addr,
627 bool print_addresses) {
628 for (uint32_t i = 0; i < sect_size; i += sizeof(double)) {
629 if (print_addresses) {
631 outs() << format("0x%016" PRIx64, sect_addr + i) << " ";
633 outs() << format("0x%08" PRIx64, sect_addr + i) << " ";
636 memcpy(&d, sect + i, sizeof(double));
637 if (O->isLittleEndian() != sys::IsLittleEndianHost)
638 sys::swapByteOrder(d);
640 memcpy(&l0, sect + i, sizeof(uint32_t));
641 memcpy(&l1, sect + i + sizeof(uint32_t), sizeof(uint32_t));
642 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
643 sys::swapByteOrder(l0);
644 sys::swapByteOrder(l1);
646 DumpLiteral8(O, l0, l1, d);
650 static void DumpLiteral16Section(MachOObjectFile *O, const char *sect,
651 uint32_t sect_size, uint64_t sect_addr,
652 bool print_addresses) {
653 for (uint32_t i = 0; i < sect_size; i += 16) {
654 if (print_addresses) {
656 outs() << format("0x%016" PRIx64, sect_addr + i) << " ";
658 outs() << format("0x%08" PRIx64, sect_addr + i) << " ";
660 uint32_t l0, l1, l2, l3;
661 memcpy(&l0, sect + i, sizeof(uint32_t));
662 memcpy(&l1, sect + i + sizeof(uint32_t), sizeof(uint32_t));
663 memcpy(&l2, sect + i + 2 * sizeof(uint32_t), sizeof(uint32_t));
664 memcpy(&l3, sect + i + 3 * sizeof(uint32_t), sizeof(uint32_t));
665 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
666 sys::swapByteOrder(l0);
667 sys::swapByteOrder(l1);
668 sys::swapByteOrder(l2);
669 sys::swapByteOrder(l3);
671 outs() << format("0x%08" PRIx32, l0) << " ";
672 outs() << format("0x%08" PRIx32, l1) << " ";
673 outs() << format("0x%08" PRIx32, l2) << " ";
674 outs() << format("0x%08" PRIx32, l3) << "\n";
678 static void DumpInitTermPointerSection(MachOObjectFile *O, const char *sect,
679 uint32_t sect_size, uint64_t sect_addr,
680 SymbolAddressMap *AddrMap,
684 stride = sizeof(uint64_t);
686 stride = sizeof(uint32_t);
687 for (uint32_t i = 0; i < sect_size; i += stride) {
688 const char *SymbolName = nullptr;
690 outs() << format("0x%016" PRIx64, sect_addr + i * stride) << " ";
691 uint64_t pointer_value;
692 memcpy(&pointer_value, sect + i, stride);
693 if (O->isLittleEndian() != sys::IsLittleEndianHost)
694 sys::swapByteOrder(pointer_value);
695 outs() << format("0x%016" PRIx64, pointer_value);
697 SymbolName = GuessSymbolName(pointer_value, AddrMap);
699 outs() << format("0x%08" PRIx64, sect_addr + i * stride) << " ";
700 uint32_t pointer_value;
701 memcpy(&pointer_value, sect + i, stride);
702 if (O->isLittleEndian() != sys::IsLittleEndianHost)
703 sys::swapByteOrder(pointer_value);
704 outs() << format("0x%08" PRIx32, pointer_value);
706 SymbolName = GuessSymbolName(pointer_value, AddrMap);
709 outs() << " " << SymbolName;
714 static void DumpRawSectionContents(MachOObjectFile *O, const char *sect,
715 uint32_t size, uint64_t addr) {
716 uint32_t cputype = O->getHeader().cputype;
717 if (cputype == MachO::CPU_TYPE_I386 || cputype == MachO::CPU_TYPE_X86_64) {
719 for (uint32_t i = 0; i < size; i += j, addr += j) {
721 outs() << format("%016" PRIx64, addr) << "\t";
723 outs() << format("%08" PRIx64, sect) << "\t";
724 for (j = 0; j < 16 && i + j < size; j++) {
725 uint8_t byte_word = *(sect + i + j);
726 outs() << format("%02" PRIx32, (uint32_t)byte_word) << " ";
732 for (uint32_t i = 0; i < size; i += j, addr += j) {
734 outs() << format("%016" PRIx64, addr) << "\t";
736 outs() << format("%08" PRIx64, sect) << "\t";
737 for (j = 0; j < 4 * sizeof(int32_t) && i + j < size;
738 j += sizeof(int32_t)) {
739 if (i + j + sizeof(int32_t) < size) {
741 memcpy(&long_word, sect + i + j, sizeof(int32_t));
742 if (O->isLittleEndian() != sys::IsLittleEndianHost)
743 sys::swapByteOrder(long_word);
744 outs() << format("%08" PRIx32, long_word) << " ";
746 for (uint32_t k = 0; i + j + k < size; k++) {
747 uint8_t byte_word = *(sect + i + j);
748 outs() << format("%02" PRIx32, (uint32_t)byte_word) << " ";
757 static void DisassembleMachO(StringRef Filename, MachOObjectFile *MachOOF,
758 StringRef DisSegName, StringRef DisSectName);
760 static void DumpSectionContents(StringRef Filename, MachOObjectFile *O,
762 SymbolAddressMap AddrMap;
764 CreateSymbolAddressMap(O, &AddrMap);
766 for (unsigned i = 0; i < DumpSections.size(); ++i) {
767 StringRef DumpSection = DumpSections[i];
768 std::pair<StringRef, StringRef> DumpSegSectName;
769 DumpSegSectName = DumpSection.split(',');
770 StringRef DumpSegName, DumpSectName;
771 if (DumpSegSectName.second.size()) {
772 DumpSegName = DumpSegSectName.first;
773 DumpSectName = DumpSegSectName.second;
776 DumpSectName = DumpSegSectName.first;
778 for (const SectionRef &Section : O->sections()) {
780 Section.getName(SectName);
781 DataRefImpl Ref = Section.getRawDataRefImpl();
782 StringRef SegName = O->getSectionFinalSegmentName(Ref);
783 if ((DumpSegName.empty() || SegName == DumpSegName) &&
784 (SectName == DumpSectName)) {
785 outs() << "Contents of (" << SegName << "," << SectName
787 uint32_t section_flags;
789 const MachO::section_64 Sec = O->getSection64(Ref);
790 section_flags = Sec.flags;
793 const MachO::section Sec = O->getSection(Ref);
794 section_flags = Sec.flags;
796 uint32_t section_type = section_flags & MachO::SECTION_TYPE;
799 Section.getContents(BytesStr);
800 const char *sect = reinterpret_cast<const char *>(BytesStr.data());
801 uint32_t sect_size = BytesStr.size();
802 uint64_t sect_addr = Section.getAddress();
805 if ((section_flags & MachO::S_ATTR_PURE_INSTRUCTIONS) ||
806 (section_flags & MachO::S_ATTR_SOME_INSTRUCTIONS)) {
807 DisassembleMachO(Filename, O, SegName, SectName);
810 switch (section_type) {
811 case MachO::S_REGULAR:
812 DumpRawSectionContents(O, sect, sect_size, sect_addr);
814 case MachO::S_ZEROFILL:
815 outs() << "zerofill section and has no contents in the file\n";
817 case MachO::S_CSTRING_LITERALS:
818 DumpCstringSection(O, sect, sect_size, sect_addr, verbose);
820 case MachO::S_4BYTE_LITERALS:
821 DumpLiteral4Section(O, sect, sect_size, sect_addr, verbose);
823 case MachO::S_8BYTE_LITERALS:
824 DumpLiteral8Section(O, sect, sect_size, sect_addr, verbose);
826 case MachO::S_16BYTE_LITERALS:
827 DumpLiteral16Section(O, sect, sect_size, sect_addr, verbose);
829 case MachO::S_MOD_INIT_FUNC_POINTERS:
830 case MachO::S_MOD_TERM_FUNC_POINTERS:
831 DumpInitTermPointerSection(O, sect, sect_size, sect_addr, &AddrMap,
835 outs() << "Unknown section type ("
836 << format("0x%08" PRIx32, section_type) << ")\n";
837 DumpRawSectionContents(O, sect, sect_size, sect_addr);
841 if (section_type == MachO::S_ZEROFILL)
842 outs() << "zerofill section and has no contents in the file\n";
844 DumpRawSectionContents(O, sect, sect_size, sect_addr);
851 // checkMachOAndArchFlags() checks to see if the ObjectFile is a Mach-O file
852 // and if it is and there is a list of architecture flags is specified then
853 // check to make sure this Mach-O file is one of those architectures or all
854 // architectures were specified. If not then an error is generated and this
855 // routine returns false. Else it returns true.
856 static bool checkMachOAndArchFlags(ObjectFile *O, StringRef Filename) {
857 if (isa<MachOObjectFile>(O) && !ArchAll && ArchFlags.size() != 0) {
858 MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(O);
859 bool ArchFound = false;
860 MachO::mach_header H;
861 MachO::mach_header_64 H_64;
863 if (MachO->is64Bit()) {
864 H_64 = MachO->MachOObjectFile::getHeader64();
865 T = MachOObjectFile::getArch(H_64.cputype, H_64.cpusubtype);
867 H = MachO->MachOObjectFile::getHeader();
868 T = MachOObjectFile::getArch(H.cputype, H.cpusubtype);
871 for (i = 0; i < ArchFlags.size(); ++i) {
872 if (ArchFlags[i] == T.getArchName())
877 errs() << "llvm-objdump: file: " + Filename + " does not contain "
878 << "architecture: " + ArchFlags[i] + "\n";
885 // ProcessMachO() is passed a single opened Mach-O file, which may be an
886 // archive member and or in a slice of a universal file. It prints the
887 // the file name and header info and then processes it according to the
888 // command line options.
889 static void ProcessMachO(StringRef Filename, MachOObjectFile *MachOOF,
890 StringRef ArchiveMemberName = StringRef(),
891 StringRef ArchitectureName = StringRef()) {
892 // If we are doing some processing here on the Mach-O file print the header
893 // info. And don't print it otherwise like in the case of printing the
894 // UniversalHeaders or ArchiveHeaders.
895 if (Disassemble || PrivateHeaders || ExportsTrie || Rebase || Bind ||
896 LazyBind || WeakBind || IndirectSymbols || DataInCode || LinkOptHints ||
897 DumpSections.size() != 0) {
899 if (!ArchiveMemberName.empty())
900 outs() << '(' << ArchiveMemberName << ')';
901 if (!ArchitectureName.empty())
902 outs() << " (architecture " << ArchitectureName << ")";
907 DisassembleMachO(Filename, MachOOF, "__TEXT", "__text");
909 PrintIndirectSymbols(MachOOF, true);
911 PrintDataInCodeTable(MachOOF, true);
913 PrintLinkOptHints(MachOOF);
915 PrintRelocations(MachOOF);
917 PrintSectionHeaders(MachOOF);
919 PrintSectionContents(MachOOF);
920 if (DumpSections.size() != 0)
921 DumpSectionContents(Filename, MachOOF, true);
923 PrintSymbolTable(MachOOF);
925 printMachOUnwindInfo(MachOOF);
927 printMachOFileHeader(MachOOF);
929 printExportsTrie(MachOOF);
931 printRebaseTable(MachOOF);
933 printBindTable(MachOOF);
935 printLazyBindTable(MachOOF);
937 printWeakBindTable(MachOOF);
940 // printUnknownCPUType() helps print_fat_headers for unknown CPU's.
941 static void printUnknownCPUType(uint32_t cputype, uint32_t cpusubtype) {
942 outs() << " cputype (" << cputype << ")\n";
943 outs() << " cpusubtype (" << cpusubtype << ")\n";
946 // printCPUType() helps print_fat_headers by printing the cputype and
947 // pusubtype (symbolically for the one's it knows about).
948 static void printCPUType(uint32_t cputype, uint32_t cpusubtype) {
950 case MachO::CPU_TYPE_I386:
951 switch (cpusubtype) {
952 case MachO::CPU_SUBTYPE_I386_ALL:
953 outs() << " cputype CPU_TYPE_I386\n";
954 outs() << " cpusubtype CPU_SUBTYPE_I386_ALL\n";
957 printUnknownCPUType(cputype, cpusubtype);
961 case MachO::CPU_TYPE_X86_64:
962 switch (cpusubtype) {
963 case MachO::CPU_SUBTYPE_X86_64_ALL:
964 outs() << " cputype CPU_TYPE_X86_64\n";
965 outs() << " cpusubtype CPU_SUBTYPE_X86_64_ALL\n";
967 case MachO::CPU_SUBTYPE_X86_64_H:
968 outs() << " cputype CPU_TYPE_X86_64\n";
969 outs() << " cpusubtype CPU_SUBTYPE_X86_64_H\n";
972 printUnknownCPUType(cputype, cpusubtype);
976 case MachO::CPU_TYPE_ARM:
977 switch (cpusubtype) {
978 case MachO::CPU_SUBTYPE_ARM_ALL:
979 outs() << " cputype CPU_TYPE_ARM\n";
980 outs() << " cpusubtype CPU_SUBTYPE_ARM_ALL\n";
982 case MachO::CPU_SUBTYPE_ARM_V4T:
983 outs() << " cputype CPU_TYPE_ARM\n";
984 outs() << " cpusubtype CPU_SUBTYPE_ARM_V4T\n";
986 case MachO::CPU_SUBTYPE_ARM_V5TEJ:
987 outs() << " cputype CPU_TYPE_ARM\n";
988 outs() << " cpusubtype CPU_SUBTYPE_ARM_V5TEJ\n";
990 case MachO::CPU_SUBTYPE_ARM_XSCALE:
991 outs() << " cputype CPU_TYPE_ARM\n";
992 outs() << " cpusubtype CPU_SUBTYPE_ARM_XSCALE\n";
994 case MachO::CPU_SUBTYPE_ARM_V6:
995 outs() << " cputype CPU_TYPE_ARM\n";
996 outs() << " cpusubtype CPU_SUBTYPE_ARM_V6\n";
998 case MachO::CPU_SUBTYPE_ARM_V6M:
999 outs() << " cputype CPU_TYPE_ARM\n";
1000 outs() << " cpusubtype CPU_SUBTYPE_ARM_V6M\n";
1002 case MachO::CPU_SUBTYPE_ARM_V7:
1003 outs() << " cputype CPU_TYPE_ARM\n";
1004 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7\n";
1006 case MachO::CPU_SUBTYPE_ARM_V7EM:
1007 outs() << " cputype CPU_TYPE_ARM\n";
1008 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7EM\n";
1010 case MachO::CPU_SUBTYPE_ARM_V7K:
1011 outs() << " cputype CPU_TYPE_ARM\n";
1012 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7K\n";
1014 case MachO::CPU_SUBTYPE_ARM_V7M:
1015 outs() << " cputype CPU_TYPE_ARM\n";
1016 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7M\n";
1018 case MachO::CPU_SUBTYPE_ARM_V7S:
1019 outs() << " cputype CPU_TYPE_ARM\n";
1020 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7S\n";
1023 printUnknownCPUType(cputype, cpusubtype);
1027 case MachO::CPU_TYPE_ARM64:
1028 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
1029 case MachO::CPU_SUBTYPE_ARM64_ALL:
1030 outs() << " cputype CPU_TYPE_ARM64\n";
1031 outs() << " cpusubtype CPU_SUBTYPE_ARM64_ALL\n";
1034 printUnknownCPUType(cputype, cpusubtype);
1039 printUnknownCPUType(cputype, cpusubtype);
1044 static void printMachOUniversalHeaders(const object::MachOUniversalBinary *UB,
1046 outs() << "Fat headers\n";
1048 outs() << "fat_magic FAT_MAGIC\n";
1050 outs() << "fat_magic " << format("0x%" PRIx32, MachO::FAT_MAGIC) << "\n";
1052 uint32_t nfat_arch = UB->getNumberOfObjects();
1053 StringRef Buf = UB->getData();
1054 uint64_t size = Buf.size();
1055 uint64_t big_size = sizeof(struct MachO::fat_header) +
1056 nfat_arch * sizeof(struct MachO::fat_arch);
1057 outs() << "nfat_arch " << UB->getNumberOfObjects();
1059 outs() << " (malformed, contains zero architecture types)\n";
1060 else if (big_size > size)
1061 outs() << " (malformed, architectures past end of file)\n";
1065 for (uint32_t i = 0; i < nfat_arch; ++i) {
1066 MachOUniversalBinary::ObjectForArch OFA(UB, i);
1067 uint32_t cputype = OFA.getCPUType();
1068 uint32_t cpusubtype = OFA.getCPUSubType();
1069 outs() << "architecture ";
1070 for (uint32_t j = 0; i != 0 && j <= i - 1; j++) {
1071 MachOUniversalBinary::ObjectForArch other_OFA(UB, j);
1072 uint32_t other_cputype = other_OFA.getCPUType();
1073 uint32_t other_cpusubtype = other_OFA.getCPUSubType();
1074 if (cputype != 0 && cpusubtype != 0 && cputype == other_cputype &&
1075 (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) ==
1076 (other_cpusubtype & ~MachO::CPU_SUBTYPE_MASK)) {
1077 outs() << "(illegal duplicate architecture) ";
1082 outs() << OFA.getArchTypeName() << "\n";
1083 printCPUType(cputype, cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
1085 outs() << i << "\n";
1086 outs() << " cputype " << cputype << "\n";
1087 outs() << " cpusubtype " << (cpusubtype & ~MachO::CPU_SUBTYPE_MASK)
1091 (cpusubtype & MachO::CPU_SUBTYPE_MASK) == MachO::CPU_SUBTYPE_LIB64)
1092 outs() << " capabilities CPU_SUBTYPE_LIB64\n";
1094 outs() << " capabilities "
1095 << format("0x%" PRIx32,
1096 (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24) << "\n";
1097 outs() << " offset " << OFA.getOffset();
1098 if (OFA.getOffset() > size)
1099 outs() << " (past end of file)";
1100 if (OFA.getOffset() % (1 << OFA.getAlign()) != 0)
1101 outs() << " (not aligned on it's alignment (2^" << OFA.getAlign() << ")";
1103 outs() << " size " << OFA.getSize();
1104 big_size = OFA.getOffset() + OFA.getSize();
1105 if (big_size > size)
1106 outs() << " (past end of file)";
1108 outs() << " align 2^" << OFA.getAlign() << " (" << (1 << OFA.getAlign())
1113 static void printArchiveChild(Archive::Child &C, bool verbose,
1114 bool print_offset) {
1116 outs() << C.getChildOffset() << "\t";
1117 sys::fs::perms Mode = C.getAccessMode();
1119 // FIXME: this first dash, "-", is for (Mode & S_IFMT) == S_IFREG.
1120 // But there is nothing in sys::fs::perms for S_IFMT or S_IFREG.
1122 if (Mode & sys::fs::owner_read)
1126 if (Mode & sys::fs::owner_write)
1130 if (Mode & sys::fs::owner_exe)
1134 if (Mode & sys::fs::group_read)
1138 if (Mode & sys::fs::group_write)
1142 if (Mode & sys::fs::group_exe)
1146 if (Mode & sys::fs::others_read)
1150 if (Mode & sys::fs::others_write)
1154 if (Mode & sys::fs::others_exe)
1159 outs() << format("0%o ", Mode);
1162 unsigned UID = C.getUID();
1163 outs() << format("%3d/", UID);
1164 unsigned GID = C.getGID();
1165 outs() << format("%-3d ", GID);
1166 uint64_t Size = C.getRawSize();
1167 outs() << format("%5" PRId64, Size) << " ";
1169 StringRef RawLastModified = C.getRawLastModified();
1172 if (RawLastModified.getAsInteger(10, Seconds))
1173 outs() << "(date: \"%s\" contains non-decimal chars) " << RawLastModified;
1175 // Since cime(3) returns a 26 character string of the form:
1176 // "Sun Sep 16 01:03:52 1973\n\0"
1177 // just print 24 characters.
1179 outs() << format("%.24s ", ctime(&t));
1182 outs() << RawLastModified << " ";
1186 ErrorOr<StringRef> NameOrErr = C.getName();
1187 if (NameOrErr.getError()) {
1188 StringRef RawName = C.getRawName();
1189 outs() << RawName << "\n";
1191 StringRef Name = NameOrErr.get();
1192 outs() << Name << "\n";
1195 StringRef RawName = C.getRawName();
1196 outs() << RawName << "\n";
1200 static void printArchiveHeaders(Archive *A, bool verbose, bool print_offset) {
1201 if (A->hasSymbolTable()) {
1202 Archive::child_iterator S = A->getSymbolTableChild();
1203 Archive::Child C = *S;
1204 printArchiveChild(C, verbose, print_offset);
1206 for (Archive::child_iterator I = A->child_begin(), E = A->child_end(); I != E;
1208 Archive::Child C = *I;
1209 printArchiveChild(C, verbose, print_offset);
1213 // ParseInputMachO() parses the named Mach-O file in Filename and handles the
1214 // -arch flags selecting just those slices as specified by them and also parses
1215 // archive files. Then for each individual Mach-O file ProcessMachO() is
1216 // called to process the file based on the command line options.
1217 void llvm::ParseInputMachO(StringRef Filename) {
1218 // Check for -arch all and verifiy the -arch flags are valid.
1219 for (unsigned i = 0; i < ArchFlags.size(); ++i) {
1220 if (ArchFlags[i] == "all") {
1223 if (!MachOObjectFile::isValidArch(ArchFlags[i])) {
1224 errs() << "llvm-objdump: Unknown architecture named '" + ArchFlags[i] +
1225 "'for the -arch option\n";
1231 // Attempt to open the binary.
1232 ErrorOr<OwningBinary<Binary>> BinaryOrErr = createBinary(Filename);
1233 if (std::error_code EC = BinaryOrErr.getError()) {
1234 errs() << "llvm-objdump: '" << Filename << "': " << EC.message() << ".\n";
1237 Binary &Bin = *BinaryOrErr.get().getBinary();
1239 if (Archive *A = dyn_cast<Archive>(&Bin)) {
1240 outs() << "Archive : " << Filename << "\n";
1242 printArchiveHeaders(A, true, false);
1243 for (Archive::child_iterator I = A->child_begin(), E = A->child_end();
1245 ErrorOr<std::unique_ptr<Binary>> ChildOrErr = I->getAsBinary();
1246 if (ChildOrErr.getError())
1248 if (MachOObjectFile *O = dyn_cast<MachOObjectFile>(&*ChildOrErr.get())) {
1249 if (!checkMachOAndArchFlags(O, Filename))
1251 ProcessMachO(Filename, O, O->getFileName());
1256 if (UniversalHeaders) {
1257 if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(&Bin))
1258 printMachOUniversalHeaders(UB, true);
1260 if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(&Bin)) {
1261 // If we have a list of architecture flags specified dump only those.
1262 if (!ArchAll && ArchFlags.size() != 0) {
1263 // Look for a slice in the universal binary that matches each ArchFlag.
1265 for (unsigned i = 0; i < ArchFlags.size(); ++i) {
1267 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
1268 E = UB->end_objects();
1270 if (ArchFlags[i] == I->getArchTypeName()) {
1272 ErrorOr<std::unique_ptr<ObjectFile>> ObjOrErr =
1273 I->getAsObjectFile();
1274 std::string ArchitectureName = "";
1275 if (ArchFlags.size() > 1)
1276 ArchitectureName = I->getArchTypeName();
1278 ObjectFile &O = *ObjOrErr.get();
1279 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&O))
1280 ProcessMachO(Filename, MachOOF, "", ArchitectureName);
1281 } else if (ErrorOr<std::unique_ptr<Archive>> AOrErr =
1282 I->getAsArchive()) {
1283 std::unique_ptr<Archive> &A = *AOrErr;
1284 outs() << "Archive : " << Filename;
1285 if (!ArchitectureName.empty())
1286 outs() << " (architecture " << ArchitectureName << ")";
1289 printArchiveHeaders(A.get(), true, false);
1290 for (Archive::child_iterator AI = A->child_begin(),
1291 AE = A->child_end();
1293 ErrorOr<std::unique_ptr<Binary>> ChildOrErr = AI->getAsBinary();
1294 if (ChildOrErr.getError())
1296 if (MachOObjectFile *O =
1297 dyn_cast<MachOObjectFile>(&*ChildOrErr.get()))
1298 ProcessMachO(Filename, O, O->getFileName(), ArchitectureName);
1304 errs() << "llvm-objdump: file: " + Filename + " does not contain "
1305 << "architecture: " + ArchFlags[i] + "\n";
1311 // No architecture flags were specified so if this contains a slice that
1312 // matches the host architecture dump only that.
1314 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
1315 E = UB->end_objects();
1317 if (MachOObjectFile::getHostArch().getArchName() ==
1318 I->getArchTypeName()) {
1319 ErrorOr<std::unique_ptr<ObjectFile>> ObjOrErr = I->getAsObjectFile();
1320 std::string ArchiveName;
1321 ArchiveName.clear();
1323 ObjectFile &O = *ObjOrErr.get();
1324 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&O))
1325 ProcessMachO(Filename, MachOOF);
1326 } else if (ErrorOr<std::unique_ptr<Archive>> AOrErr =
1327 I->getAsArchive()) {
1328 std::unique_ptr<Archive> &A = *AOrErr;
1329 outs() << "Archive : " << Filename << "\n";
1331 printArchiveHeaders(A.get(), true, false);
1332 for (Archive::child_iterator AI = A->child_begin(),
1333 AE = A->child_end();
1335 ErrorOr<std::unique_ptr<Binary>> ChildOrErr = AI->getAsBinary();
1336 if (ChildOrErr.getError())
1338 if (MachOObjectFile *O =
1339 dyn_cast<MachOObjectFile>(&*ChildOrErr.get()))
1340 ProcessMachO(Filename, O, O->getFileName());
1347 // Either all architectures have been specified or none have been specified
1348 // and this does not contain the host architecture so dump all the slices.
1349 bool moreThanOneArch = UB->getNumberOfObjects() > 1;
1350 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
1351 E = UB->end_objects();
1353 ErrorOr<std::unique_ptr<ObjectFile>> ObjOrErr = I->getAsObjectFile();
1354 std::string ArchitectureName = "";
1355 if (moreThanOneArch)
1356 ArchitectureName = I->getArchTypeName();
1358 ObjectFile &Obj = *ObjOrErr.get();
1359 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&Obj))
1360 ProcessMachO(Filename, MachOOF, "", ArchitectureName);
1361 } else if (ErrorOr<std::unique_ptr<Archive>> AOrErr = I->getAsArchive()) {
1362 std::unique_ptr<Archive> &A = *AOrErr;
1363 outs() << "Archive : " << Filename;
1364 if (!ArchitectureName.empty())
1365 outs() << " (architecture " << ArchitectureName << ")";
1368 printArchiveHeaders(A.get(), true, false);
1369 for (Archive::child_iterator AI = A->child_begin(), AE = A->child_end();
1371 ErrorOr<std::unique_ptr<Binary>> ChildOrErr = AI->getAsBinary();
1372 if (ChildOrErr.getError())
1374 if (MachOObjectFile *O =
1375 dyn_cast<MachOObjectFile>(&*ChildOrErr.get())) {
1376 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(O))
1377 ProcessMachO(Filename, MachOOF, MachOOF->getFileName(),
1385 if (ObjectFile *O = dyn_cast<ObjectFile>(&Bin)) {
1386 if (!checkMachOAndArchFlags(O, Filename))
1388 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&*O)) {
1389 ProcessMachO(Filename, MachOOF);
1391 errs() << "llvm-objdump: '" << Filename << "': "
1392 << "Object is not a Mach-O file type.\n";
1394 errs() << "llvm-objdump: '" << Filename << "': "
1395 << "Unrecognized file type.\n";
1398 typedef std::pair<uint64_t, const char *> BindInfoEntry;
1399 typedef std::vector<BindInfoEntry> BindTable;
1400 typedef BindTable::iterator bind_table_iterator;
1402 // The block of info used by the Symbolizer call backs.
1403 struct DisassembleInfo {
1407 SymbolAddressMap *AddrMap;
1408 std::vector<SectionRef> *Sections;
1409 const char *class_name;
1410 const char *selector_name;
1412 char *demangled_name;
1415 BindTable *bindtable;
1418 // SymbolizerGetOpInfo() is the operand information call back function.
1419 // This is called to get the symbolic information for operand(s) of an
1420 // instruction when it is being done. This routine does this from
1421 // the relocation information, symbol table, etc. That block of information
1422 // is a pointer to the struct DisassembleInfo that was passed when the
1423 // disassembler context was created and passed to back to here when
1424 // called back by the disassembler for instruction operands that could have
1425 // relocation information. The address of the instruction containing operand is
1426 // at the Pc parameter. The immediate value the operand has is passed in
1427 // op_info->Value and is at Offset past the start of the instruction and has a
1428 // byte Size of 1, 2 or 4. The symbolc information is returned in TagBuf is the
1429 // LLVMOpInfo1 struct defined in the header "llvm-c/Disassembler.h" as symbol
1430 // names and addends of the symbolic expression to add for the operand. The
1431 // value of TagType is currently 1 (for the LLVMOpInfo1 struct). If symbolic
1432 // information is returned then this function returns 1 else it returns 0.
1433 int SymbolizerGetOpInfo(void *DisInfo, uint64_t Pc, uint64_t Offset,
1434 uint64_t Size, int TagType, void *TagBuf) {
1435 struct DisassembleInfo *info = (struct DisassembleInfo *)DisInfo;
1436 struct LLVMOpInfo1 *op_info = (struct LLVMOpInfo1 *)TagBuf;
1437 uint64_t value = op_info->Value;
1439 // Make sure all fields returned are zero if we don't set them.
1440 memset((void *)op_info, '\0', sizeof(struct LLVMOpInfo1));
1441 op_info->Value = value;
1443 // If the TagType is not the value 1 which it code knows about or if no
1444 // verbose symbolic information is wanted then just return 0, indicating no
1445 // information is being returned.
1446 if (TagType != 1 || info->verbose == false)
1449 unsigned int Arch = info->O->getArch();
1450 if (Arch == Triple::x86) {
1451 if (Size != 1 && Size != 2 && Size != 4 && Size != 0)
1453 // First search the section's relocation entries (if any) for an entry
1454 // for this section offset.
1455 uint32_t sect_addr = info->S.getAddress();
1456 uint32_t sect_offset = (Pc + Offset) - sect_addr;
1457 bool reloc_found = false;
1459 MachO::any_relocation_info RE;
1460 bool isExtern = false;
1462 bool r_scattered = false;
1463 uint32_t r_value, pair_r_value, r_type;
1464 for (const RelocationRef &Reloc : info->S.relocations()) {
1465 uint64_t RelocOffset;
1466 Reloc.getOffset(RelocOffset);
1467 if (RelocOffset == sect_offset) {
1468 Rel = Reloc.getRawDataRefImpl();
1469 RE = info->O->getRelocation(Rel);
1470 r_type = info->O->getAnyRelocationType(RE);
1471 r_scattered = info->O->isRelocationScattered(RE);
1473 r_value = info->O->getScatteredRelocationValue(RE);
1474 if (r_type == MachO::GENERIC_RELOC_SECTDIFF ||
1475 r_type == MachO::GENERIC_RELOC_LOCAL_SECTDIFF) {
1476 DataRefImpl RelNext = Rel;
1477 info->O->moveRelocationNext(RelNext);
1478 MachO::any_relocation_info RENext;
1479 RENext = info->O->getRelocation(RelNext);
1480 if (info->O->isRelocationScattered(RENext))
1481 pair_r_value = info->O->getScatteredRelocationValue(RENext);
1486 isExtern = info->O->getPlainRelocationExternal(RE);
1488 symbol_iterator RelocSym = Reloc.getSymbol();
1496 if (reloc_found && isExtern) {
1498 Symbol.getName(SymName);
1499 const char *name = SymName.data();
1500 op_info->AddSymbol.Present = 1;
1501 op_info->AddSymbol.Name = name;
1502 // For i386 extern relocation entries the value in the instruction is
1503 // the offset from the symbol, and value is already set in op_info->Value.
1506 if (reloc_found && (r_type == MachO::GENERIC_RELOC_SECTDIFF ||
1507 r_type == MachO::GENERIC_RELOC_LOCAL_SECTDIFF)) {
1508 const char *add = GuessSymbolName(r_value, info->AddrMap);
1509 const char *sub = GuessSymbolName(pair_r_value, info->AddrMap);
1510 uint32_t offset = value - (r_value - pair_r_value);
1511 op_info->AddSymbol.Present = 1;
1513 op_info->AddSymbol.Name = add;
1515 op_info->AddSymbol.Value = r_value;
1516 op_info->SubtractSymbol.Present = 1;
1518 op_info->SubtractSymbol.Name = sub;
1520 op_info->SubtractSymbol.Value = pair_r_value;
1521 op_info->Value = offset;
1525 // Second search the external relocation entries of a fully linked image
1526 // (if any) for an entry that matches this segment offset.
1527 // uint32_t seg_offset = (Pc + Offset);
1529 } else if (Arch == Triple::x86_64) {
1530 if (Size != 1 && Size != 2 && Size != 4 && Size != 0)
1532 // First search the section's relocation entries (if any) for an entry
1533 // for this section offset.
1534 uint64_t sect_addr = info->S.getAddress();
1535 uint64_t sect_offset = (Pc + Offset) - sect_addr;
1536 bool reloc_found = false;
1538 MachO::any_relocation_info RE;
1539 bool isExtern = false;
1541 for (const RelocationRef &Reloc : info->S.relocations()) {
1542 uint64_t RelocOffset;
1543 Reloc.getOffset(RelocOffset);
1544 if (RelocOffset == sect_offset) {
1545 Rel = Reloc.getRawDataRefImpl();
1546 RE = info->O->getRelocation(Rel);
1547 // NOTE: Scattered relocations don't exist on x86_64.
1548 isExtern = info->O->getPlainRelocationExternal(RE);
1550 symbol_iterator RelocSym = Reloc.getSymbol();
1557 if (reloc_found && isExtern) {
1558 // The Value passed in will be adjusted by the Pc if the instruction
1559 // adds the Pc. But for x86_64 external relocation entries the Value
1560 // is the offset from the external symbol.
1561 if (info->O->getAnyRelocationPCRel(RE))
1562 op_info->Value -= Pc + Offset + Size;
1564 Symbol.getName(SymName);
1565 const char *name = SymName.data();
1566 unsigned Type = info->O->getAnyRelocationType(RE);
1567 if (Type == MachO::X86_64_RELOC_SUBTRACTOR) {
1568 DataRefImpl RelNext = Rel;
1569 info->O->moveRelocationNext(RelNext);
1570 MachO::any_relocation_info RENext = info->O->getRelocation(RelNext);
1571 unsigned TypeNext = info->O->getAnyRelocationType(RENext);
1572 bool isExternNext = info->O->getPlainRelocationExternal(RENext);
1573 unsigned SymbolNum = info->O->getPlainRelocationSymbolNum(RENext);
1574 if (TypeNext == MachO::X86_64_RELOC_UNSIGNED && isExternNext) {
1575 op_info->SubtractSymbol.Present = 1;
1576 op_info->SubtractSymbol.Name = name;
1577 symbol_iterator RelocSymNext = info->O->getSymbolByIndex(SymbolNum);
1578 Symbol = *RelocSymNext;
1579 StringRef SymNameNext;
1580 Symbol.getName(SymNameNext);
1581 name = SymNameNext.data();
1584 // TODO: add the VariantKinds to op_info->VariantKind for relocation types
1585 // like: X86_64_RELOC_TLV, X86_64_RELOC_GOT_LOAD and X86_64_RELOC_GOT.
1586 op_info->AddSymbol.Present = 1;
1587 op_info->AddSymbol.Name = name;
1591 // Second search the external relocation entries of a fully linked image
1592 // (if any) for an entry that matches this segment offset.
1593 // uint64_t seg_offset = (Pc + Offset);
1595 } else if (Arch == Triple::arm) {
1596 if (Offset != 0 || (Size != 4 && Size != 2))
1598 // First search the section's relocation entries (if any) for an entry
1599 // for this section offset.
1600 uint32_t sect_addr = info->S.getAddress();
1601 uint32_t sect_offset = (Pc + Offset) - sect_addr;
1602 bool reloc_found = false;
1604 MachO::any_relocation_info RE;
1605 bool isExtern = false;
1607 bool r_scattered = false;
1608 uint32_t r_value, pair_r_value, r_type, r_length, other_half;
1609 for (const RelocationRef &Reloc : info->S.relocations()) {
1610 uint64_t RelocOffset;
1611 Reloc.getOffset(RelocOffset);
1612 if (RelocOffset == sect_offset) {
1613 Rel = Reloc.getRawDataRefImpl();
1614 RE = info->O->getRelocation(Rel);
1615 r_length = info->O->getAnyRelocationLength(RE);
1616 r_scattered = info->O->isRelocationScattered(RE);
1618 r_value = info->O->getScatteredRelocationValue(RE);
1619 r_type = info->O->getScatteredRelocationType(RE);
1621 r_type = info->O->getAnyRelocationType(RE);
1622 isExtern = info->O->getPlainRelocationExternal(RE);
1624 symbol_iterator RelocSym = Reloc.getSymbol();
1628 if (r_type == MachO::ARM_RELOC_HALF ||
1629 r_type == MachO::ARM_RELOC_SECTDIFF ||
1630 r_type == MachO::ARM_RELOC_LOCAL_SECTDIFF ||
1631 r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
1632 DataRefImpl RelNext = Rel;
1633 info->O->moveRelocationNext(RelNext);
1634 MachO::any_relocation_info RENext;
1635 RENext = info->O->getRelocation(RelNext);
1636 other_half = info->O->getAnyRelocationAddress(RENext) & 0xffff;
1637 if (info->O->isRelocationScattered(RENext))
1638 pair_r_value = info->O->getScatteredRelocationValue(RENext);
1644 if (reloc_found && isExtern) {
1646 Symbol.getName(SymName);
1647 const char *name = SymName.data();
1648 op_info->AddSymbol.Present = 1;
1649 op_info->AddSymbol.Name = name;
1651 case MachO::ARM_RELOC_HALF:
1652 if ((r_length & 0x1) == 1) {
1653 op_info->Value = value << 16 | other_half;
1654 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
1656 op_info->Value = other_half << 16 | value;
1657 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
1665 // If we have a branch that is not an external relocation entry then
1666 // return 0 so the code in tryAddingSymbolicOperand() can use the
1667 // SymbolLookUp call back with the branch target address to look up the
1668 // symbol and possiblity add an annotation for a symbol stub.
1669 if (reloc_found && isExtern == 0 && (r_type == MachO::ARM_RELOC_BR24 ||
1670 r_type == MachO::ARM_THUMB_RELOC_BR22))
1673 uint32_t offset = 0;
1675 if (r_type == MachO::ARM_RELOC_HALF ||
1676 r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
1677 if ((r_length & 0x1) == 1)
1678 value = value << 16 | other_half;
1680 value = other_half << 16 | value;
1682 if (r_scattered && (r_type != MachO::ARM_RELOC_HALF &&
1683 r_type != MachO::ARM_RELOC_HALF_SECTDIFF)) {
1684 offset = value - r_value;
1689 if (reloc_found && r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
1690 if ((r_length & 0x1) == 1)
1691 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
1693 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
1694 const char *add = GuessSymbolName(r_value, info->AddrMap);
1695 const char *sub = GuessSymbolName(pair_r_value, info->AddrMap);
1696 int32_t offset = value - (r_value - pair_r_value);
1697 op_info->AddSymbol.Present = 1;
1699 op_info->AddSymbol.Name = add;
1701 op_info->AddSymbol.Value = r_value;
1702 op_info->SubtractSymbol.Present = 1;
1704 op_info->SubtractSymbol.Name = sub;
1706 op_info->SubtractSymbol.Value = pair_r_value;
1707 op_info->Value = offset;
1711 if (reloc_found == false)
1714 op_info->AddSymbol.Present = 1;
1715 op_info->Value = offset;
1717 if (r_type == MachO::ARM_RELOC_HALF) {
1718 if ((r_length & 0x1) == 1)
1719 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
1721 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
1724 const char *add = GuessSymbolName(value, info->AddrMap);
1725 if (add != nullptr) {
1726 op_info->AddSymbol.Name = add;
1729 op_info->AddSymbol.Value = value;
1731 } else if (Arch == Triple::aarch64) {
1732 if (Offset != 0 || Size != 4)
1734 // First search the section's relocation entries (if any) for an entry
1735 // for this section offset.
1736 uint64_t sect_addr = info->S.getAddress();
1737 uint64_t sect_offset = (Pc + Offset) - sect_addr;
1738 bool reloc_found = false;
1740 MachO::any_relocation_info RE;
1741 bool isExtern = false;
1743 uint32_t r_type = 0;
1744 for (const RelocationRef &Reloc : info->S.relocations()) {
1745 uint64_t RelocOffset;
1746 Reloc.getOffset(RelocOffset);
1747 if (RelocOffset == sect_offset) {
1748 Rel = Reloc.getRawDataRefImpl();
1749 RE = info->O->getRelocation(Rel);
1750 r_type = info->O->getAnyRelocationType(RE);
1751 if (r_type == MachO::ARM64_RELOC_ADDEND) {
1752 DataRefImpl RelNext = Rel;
1753 info->O->moveRelocationNext(RelNext);
1754 MachO::any_relocation_info RENext = info->O->getRelocation(RelNext);
1756 value = info->O->getPlainRelocationSymbolNum(RENext);
1757 op_info->Value = value;
1760 // NOTE: Scattered relocations don't exist on arm64.
1761 isExtern = info->O->getPlainRelocationExternal(RE);
1763 symbol_iterator RelocSym = Reloc.getSymbol();
1770 if (reloc_found && isExtern) {
1772 Symbol.getName(SymName);
1773 const char *name = SymName.data();
1774 op_info->AddSymbol.Present = 1;
1775 op_info->AddSymbol.Name = name;
1778 case MachO::ARM64_RELOC_PAGE21:
1780 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_PAGE;
1782 case MachO::ARM64_RELOC_PAGEOFF12:
1784 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_PAGEOFF;
1786 case MachO::ARM64_RELOC_GOT_LOAD_PAGE21:
1788 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_GOTPAGE;
1790 case MachO::ARM64_RELOC_GOT_LOAD_PAGEOFF12:
1792 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_GOTPAGEOFF;
1794 case MachO::ARM64_RELOC_TLVP_LOAD_PAGE21:
1795 /* @tvlppage is not implemented in llvm-mc */
1796 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_TLVP;
1798 case MachO::ARM64_RELOC_TLVP_LOAD_PAGEOFF12:
1799 /* @tvlppageoff is not implemented in llvm-mc */
1800 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_TLVOFF;
1803 case MachO::ARM64_RELOC_BRANCH26:
1804 op_info->VariantKind = LLVMDisassembler_VariantKind_None;
1815 // GuessCstringPointer is passed the address of what might be a pointer to a
1816 // literal string in a cstring section. If that address is in a cstring section
1817 // it returns a pointer to that string. Else it returns nullptr.
1818 const char *GuessCstringPointer(uint64_t ReferenceValue,
1819 struct DisassembleInfo *info) {
1820 uint32_t LoadCommandCount = info->O->getHeader().ncmds;
1821 MachOObjectFile::LoadCommandInfo Load = info->O->getFirstLoadCommandInfo();
1822 for (unsigned I = 0;; ++I) {
1823 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
1824 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
1825 for (unsigned J = 0; J < Seg.nsects; ++J) {
1826 MachO::section_64 Sec = info->O->getSection64(Load, J);
1827 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
1828 if (section_type == MachO::S_CSTRING_LITERALS &&
1829 ReferenceValue >= Sec.addr &&
1830 ReferenceValue < Sec.addr + Sec.size) {
1831 uint64_t sect_offset = ReferenceValue - Sec.addr;
1832 uint64_t object_offset = Sec.offset + sect_offset;
1833 StringRef MachOContents = info->O->getData();
1834 uint64_t object_size = MachOContents.size();
1835 const char *object_addr = (const char *)MachOContents.data();
1836 if (object_offset < object_size) {
1837 const char *name = object_addr + object_offset;
1844 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
1845 MachO::segment_command Seg = info->O->getSegmentLoadCommand(Load);
1846 for (unsigned J = 0; J < Seg.nsects; ++J) {
1847 MachO::section Sec = info->O->getSection(Load, J);
1848 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
1849 if (section_type == MachO::S_CSTRING_LITERALS &&
1850 ReferenceValue >= Sec.addr &&
1851 ReferenceValue < Sec.addr + Sec.size) {
1852 uint64_t sect_offset = ReferenceValue - Sec.addr;
1853 uint64_t object_offset = Sec.offset + sect_offset;
1854 StringRef MachOContents = info->O->getData();
1855 uint64_t object_size = MachOContents.size();
1856 const char *object_addr = (const char *)MachOContents.data();
1857 if (object_offset < object_size) {
1858 const char *name = object_addr + object_offset;
1866 if (I == LoadCommandCount - 1)
1869 Load = info->O->getNextLoadCommandInfo(Load);
1874 // GuessIndirectSymbol returns the name of the indirect symbol for the
1875 // ReferenceValue passed in or nullptr. This is used when ReferenceValue maybe
1876 // an address of a symbol stub or a lazy or non-lazy pointer to associate the
1877 // symbol name being referenced by the stub or pointer.
1878 static const char *GuessIndirectSymbol(uint64_t ReferenceValue,
1879 struct DisassembleInfo *info) {
1880 uint32_t LoadCommandCount = info->O->getHeader().ncmds;
1881 MachOObjectFile::LoadCommandInfo Load = info->O->getFirstLoadCommandInfo();
1882 MachO::dysymtab_command Dysymtab = info->O->getDysymtabLoadCommand();
1883 MachO::symtab_command Symtab = info->O->getSymtabLoadCommand();
1884 for (unsigned I = 0;; ++I) {
1885 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
1886 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
1887 for (unsigned J = 0; J < Seg.nsects; ++J) {
1888 MachO::section_64 Sec = info->O->getSection64(Load, J);
1889 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
1890 if ((section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
1891 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
1892 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
1893 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
1894 section_type == MachO::S_SYMBOL_STUBS) &&
1895 ReferenceValue >= Sec.addr &&
1896 ReferenceValue < Sec.addr + Sec.size) {
1898 if (section_type == MachO::S_SYMBOL_STUBS)
1899 stride = Sec.reserved2;
1904 uint32_t index = Sec.reserved1 + (ReferenceValue - Sec.addr) / stride;
1905 if (index < Dysymtab.nindirectsyms) {
1906 uint32_t indirect_symbol =
1907 info->O->getIndirectSymbolTableEntry(Dysymtab, index);
1908 if (indirect_symbol < Symtab.nsyms) {
1909 symbol_iterator Sym = info->O->getSymbolByIndex(indirect_symbol);
1910 SymbolRef Symbol = *Sym;
1912 Symbol.getName(SymName);
1913 const char *name = SymName.data();
1919 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
1920 MachO::segment_command Seg = info->O->getSegmentLoadCommand(Load);
1921 for (unsigned J = 0; J < Seg.nsects; ++J) {
1922 MachO::section Sec = info->O->getSection(Load, J);
1923 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
1924 if ((section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
1925 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
1926 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
1927 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
1928 section_type == MachO::S_SYMBOL_STUBS) &&
1929 ReferenceValue >= Sec.addr &&
1930 ReferenceValue < Sec.addr + Sec.size) {
1932 if (section_type == MachO::S_SYMBOL_STUBS)
1933 stride = Sec.reserved2;
1938 uint32_t index = Sec.reserved1 + (ReferenceValue - Sec.addr) / stride;
1939 if (index < Dysymtab.nindirectsyms) {
1940 uint32_t indirect_symbol =
1941 info->O->getIndirectSymbolTableEntry(Dysymtab, index);
1942 if (indirect_symbol < Symtab.nsyms) {
1943 symbol_iterator Sym = info->O->getSymbolByIndex(indirect_symbol);
1944 SymbolRef Symbol = *Sym;
1946 Symbol.getName(SymName);
1947 const char *name = SymName.data();
1954 if (I == LoadCommandCount - 1)
1957 Load = info->O->getNextLoadCommandInfo(Load);
1962 // method_reference() is called passing it the ReferenceName that might be
1963 // a reference it to an Objective-C method call. If so then it allocates and
1964 // assembles a method call string with the values last seen and saved in
1965 // the DisassembleInfo's class_name and selector_name fields. This is saved
1966 // into the method field of the info and any previous string is free'ed.
1967 // Then the class_name field in the info is set to nullptr. The method call
1968 // string is set into ReferenceName and ReferenceType is set to
1969 // LLVMDisassembler_ReferenceType_Out_Objc_Message. If this not a method call
1970 // then both ReferenceType and ReferenceName are left unchanged.
1971 static void method_reference(struct DisassembleInfo *info,
1972 uint64_t *ReferenceType,
1973 const char **ReferenceName) {
1974 unsigned int Arch = info->O->getArch();
1975 if (*ReferenceName != nullptr) {
1976 if (strcmp(*ReferenceName, "_objc_msgSend") == 0) {
1977 if (info->selector_name != nullptr) {
1978 if (info->method != nullptr)
1980 if (info->class_name != nullptr) {
1981 info->method = (char *)malloc(5 + strlen(info->class_name) +
1982 strlen(info->selector_name));
1983 if (info->method != nullptr) {
1984 strcpy(info->method, "+[");
1985 strcat(info->method, info->class_name);
1986 strcat(info->method, " ");
1987 strcat(info->method, info->selector_name);
1988 strcat(info->method, "]");
1989 *ReferenceName = info->method;
1990 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
1993 info->method = (char *)malloc(9 + strlen(info->selector_name));
1994 if (info->method != nullptr) {
1995 if (Arch == Triple::x86_64)
1996 strcpy(info->method, "-[%rdi ");
1997 else if (Arch == Triple::aarch64)
1998 strcpy(info->method, "-[x0 ");
2000 strcpy(info->method, "-[r? ");
2001 strcat(info->method, info->selector_name);
2002 strcat(info->method, "]");
2003 *ReferenceName = info->method;
2004 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
2007 info->class_name = nullptr;
2009 } else if (strcmp(*ReferenceName, "_objc_msgSendSuper2") == 0) {
2010 if (info->selector_name != nullptr) {
2011 if (info->method != nullptr)
2013 info->method = (char *)malloc(17 + strlen(info->selector_name));
2014 if (info->method != nullptr) {
2015 if (Arch == Triple::x86_64)
2016 strcpy(info->method, "-[[%rdi super] ");
2017 else if (Arch == Triple::aarch64)
2018 strcpy(info->method, "-[[x0 super] ");
2020 strcpy(info->method, "-[[r? super] ");
2021 strcat(info->method, info->selector_name);
2022 strcat(info->method, "]");
2023 *ReferenceName = info->method;
2024 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
2026 info->class_name = nullptr;
2032 // GuessPointerPointer() is passed the address of what might be a pointer to
2033 // a reference to an Objective-C class, selector, message ref or cfstring.
2034 // If so the value of the pointer is returned and one of the booleans are set
2035 // to true. If not zero is returned and all the booleans are set to false.
2036 static uint64_t GuessPointerPointer(uint64_t ReferenceValue,
2037 struct DisassembleInfo *info,
2038 bool &classref, bool &selref, bool &msgref,
2044 uint32_t LoadCommandCount = info->O->getHeader().ncmds;
2045 MachOObjectFile::LoadCommandInfo Load = info->O->getFirstLoadCommandInfo();
2046 for (unsigned I = 0;; ++I) {
2047 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
2048 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
2049 for (unsigned J = 0; J < Seg.nsects; ++J) {
2050 MachO::section_64 Sec = info->O->getSection64(Load, J);
2051 if ((strncmp(Sec.sectname, "__objc_selrefs", 16) == 0 ||
2052 strncmp(Sec.sectname, "__objc_classrefs", 16) == 0 ||
2053 strncmp(Sec.sectname, "__objc_superrefs", 16) == 0 ||
2054 strncmp(Sec.sectname, "__objc_msgrefs", 16) == 0 ||
2055 strncmp(Sec.sectname, "__cfstring", 16) == 0) &&
2056 ReferenceValue >= Sec.addr &&
2057 ReferenceValue < Sec.addr + Sec.size) {
2058 uint64_t sect_offset = ReferenceValue - Sec.addr;
2059 uint64_t object_offset = Sec.offset + sect_offset;
2060 StringRef MachOContents = info->O->getData();
2061 uint64_t object_size = MachOContents.size();
2062 const char *object_addr = (const char *)MachOContents.data();
2063 if (object_offset < object_size) {
2064 uint64_t pointer_value;
2065 memcpy(&pointer_value, object_addr + object_offset,
2067 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
2068 sys::swapByteOrder(pointer_value);
2069 if (strncmp(Sec.sectname, "__objc_selrefs", 16) == 0)
2071 else if (strncmp(Sec.sectname, "__objc_classrefs", 16) == 0 ||
2072 strncmp(Sec.sectname, "__objc_superrefs", 16) == 0)
2074 else if (strncmp(Sec.sectname, "__objc_msgrefs", 16) == 0 &&
2075 ReferenceValue + 8 < Sec.addr + Sec.size) {
2077 memcpy(&pointer_value, object_addr + object_offset + 8,
2079 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
2080 sys::swapByteOrder(pointer_value);
2081 } else if (strncmp(Sec.sectname, "__cfstring", 16) == 0)
2083 return pointer_value;
2090 // TODO: Look for LC_SEGMENT for 32-bit Mach-O files.
2091 if (I == LoadCommandCount - 1)
2094 Load = info->O->getNextLoadCommandInfo(Load);
2099 // get_pointer_64 returns a pointer to the bytes in the object file at the
2100 // Address from a section in the Mach-O file. And indirectly returns the
2101 // offset into the section, number of bytes left in the section past the offset
2102 // and which section is was being referenced. If the Address is not in a
2103 // section nullptr is returned.
2104 const char *get_pointer_64(uint64_t Address, uint32_t &offset, uint32_t &left,
2105 SectionRef &S, DisassembleInfo *info) {
2109 for (unsigned SectIdx = 0; SectIdx != info->Sections->size(); SectIdx++) {
2110 uint64_t SectAddress = ((*(info->Sections))[SectIdx]).getAddress();
2111 uint64_t SectSize = ((*(info->Sections))[SectIdx]).getSize();
2112 if (Address >= SectAddress && Address < SectAddress + SectSize) {
2113 S = (*(info->Sections))[SectIdx];
2114 offset = Address - SectAddress;
2115 left = SectSize - offset;
2116 StringRef SectContents;
2117 ((*(info->Sections))[SectIdx]).getContents(SectContents);
2118 return SectContents.data() + offset;
2124 // get_symbol_64() returns the name of a symbol (or nullptr) and the address of
2125 // the symbol indirectly through n_value. Based on the relocation information
2126 // for the specified section offset in the specified section reference.
2127 const char *get_symbol_64(uint32_t sect_offset, SectionRef S,
2128 DisassembleInfo *info, uint64_t &n_value) {
2130 if (info->verbose == false)
2133 // See if there is an external relocation entry at the sect_offset.
2134 bool reloc_found = false;
2136 MachO::any_relocation_info RE;
2137 bool isExtern = false;
2139 for (const RelocationRef &Reloc : S.relocations()) {
2140 uint64_t RelocOffset;
2141 Reloc.getOffset(RelocOffset);
2142 if (RelocOffset == sect_offset) {
2143 Rel = Reloc.getRawDataRefImpl();
2144 RE = info->O->getRelocation(Rel);
2145 if (info->O->isRelocationScattered(RE))
2147 isExtern = info->O->getPlainRelocationExternal(RE);
2149 symbol_iterator RelocSym = Reloc.getSymbol();
2156 // If there is an external relocation entry for a symbol in this section
2157 // at this section_offset then use that symbol's value for the n_value
2158 // and return its name.
2159 const char *SymbolName = nullptr;
2160 if (reloc_found && isExtern) {
2161 Symbol.getAddress(n_value);
2163 Symbol.getName(name);
2164 if (!name.empty()) {
2165 SymbolName = name.data();
2170 // TODO: For fully linked images, look through the external relocation
2171 // entries off the dynamic symtab command. For these the r_offset is from the
2172 // start of the first writeable segment in the Mach-O file. So the offset
2173 // to this section from that segment is passed to this routine by the caller,
2174 // as the database_offset. Which is the difference of the section's starting
2175 // address and the first writable segment.
2177 // NOTE: need add passing the database_offset to this routine.
2179 // TODO: We did not find an external relocation entry so look up the
2180 // ReferenceValue as an address of a symbol and if found return that symbol's
2183 // NOTE: need add passing the ReferenceValue to this routine. Then that code
2184 // would simply be this:
2185 // SymbolName = GuessSymbolName(ReferenceValue, info->AddrMap);
2190 // These are structs in the Objective-C meta data and read to produce the
2191 // comments for disassembly. While these are part of the ABI they are no
2192 // public defintions. So the are here not in include/llvm/Support/MachO.h .
2194 // The cfstring object in a 64-bit Mach-O file.
2195 struct cfstring64_t {
2196 uint64_t isa; // class64_t * (64-bit pointer)
2197 uint64_t flags; // flag bits
2198 uint64_t characters; // char * (64-bit pointer)
2199 uint64_t length; // number of non-NULL characters in above
2202 // The class object in a 64-bit Mach-O file.
2204 uint64_t isa; // class64_t * (64-bit pointer)
2205 uint64_t superclass; // class64_t * (64-bit pointer)
2206 uint64_t cache; // Cache (64-bit pointer)
2207 uint64_t vtable; // IMP * (64-bit pointer)
2208 uint64_t data; // class_ro64_t * (64-bit pointer)
2211 struct class_ro64_t {
2213 uint32_t instanceStart;
2214 uint32_t instanceSize;
2216 uint64_t ivarLayout; // const uint8_t * (64-bit pointer)
2217 uint64_t name; // const char * (64-bit pointer)
2218 uint64_t baseMethods; // const method_list_t * (64-bit pointer)
2219 uint64_t baseProtocols; // const protocol_list_t * (64-bit pointer)
2220 uint64_t ivars; // const ivar_list_t * (64-bit pointer)
2221 uint64_t weakIvarLayout; // const uint8_t * (64-bit pointer)
2222 uint64_t baseProperties; // const struct objc_property_list (64-bit pointer)
2225 inline void swapStruct(struct cfstring64_t &cfs) {
2226 sys::swapByteOrder(cfs.isa);
2227 sys::swapByteOrder(cfs.flags);
2228 sys::swapByteOrder(cfs.characters);
2229 sys::swapByteOrder(cfs.length);
2232 inline void swapStruct(struct class64_t &c) {
2233 sys::swapByteOrder(c.isa);
2234 sys::swapByteOrder(c.superclass);
2235 sys::swapByteOrder(c.cache);
2236 sys::swapByteOrder(c.vtable);
2237 sys::swapByteOrder(c.data);
2240 inline void swapStruct(struct class_ro64_t &cro) {
2241 sys::swapByteOrder(cro.flags);
2242 sys::swapByteOrder(cro.instanceStart);
2243 sys::swapByteOrder(cro.instanceSize);
2244 sys::swapByteOrder(cro.reserved);
2245 sys::swapByteOrder(cro.ivarLayout);
2246 sys::swapByteOrder(cro.name);
2247 sys::swapByteOrder(cro.baseMethods);
2248 sys::swapByteOrder(cro.baseProtocols);
2249 sys::swapByteOrder(cro.ivars);
2250 sys::swapByteOrder(cro.weakIvarLayout);
2251 sys::swapByteOrder(cro.baseProperties);
2254 static const char *get_dyld_bind_info_symbolname(uint64_t ReferenceValue,
2255 struct DisassembleInfo *info);
2257 // get_objc2_64bit_class_name() is used for disassembly and is passed a pointer
2258 // to an Objective-C class and returns the class name. It is also passed the
2259 // address of the pointer, so when the pointer is zero as it can be in an .o
2260 // file, that is used to look for an external relocation entry with a symbol
2262 const char *get_objc2_64bit_class_name(uint64_t pointer_value,
2263 uint64_t ReferenceValue,
2264 struct DisassembleInfo *info) {
2266 uint32_t offset, left;
2269 // The pointer_value can be 0 in an object file and have a relocation
2270 // entry for the class symbol at the ReferenceValue (the address of the
2272 if (pointer_value == 0) {
2273 r = get_pointer_64(ReferenceValue, offset, left, S, info);
2274 if (r == nullptr || left < sizeof(uint64_t))
2277 const char *symbol_name = get_symbol_64(offset, S, info, n_value);
2278 if (symbol_name == nullptr)
2280 const char *class_name = strrchr(symbol_name, '$');
2281 if (class_name != nullptr && class_name[1] == '_' && class_name[2] != '\0')
2282 return class_name + 2;
2287 // The case were the pointer_value is non-zero and points to a class defined
2288 // in this Mach-O file.
2289 r = get_pointer_64(pointer_value, offset, left, S, info);
2290 if (r == nullptr || left < sizeof(struct class64_t))
2293 memcpy(&c, r, sizeof(struct class64_t));
2294 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
2298 r = get_pointer_64(c.data, offset, left, S, info);
2299 if (r == nullptr || left < sizeof(struct class_ro64_t))
2301 struct class_ro64_t cro;
2302 memcpy(&cro, r, sizeof(struct class_ro64_t));
2303 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
2307 const char *name = get_pointer_64(cro.name, offset, left, S, info);
2311 // get_objc2_64bit_cfstring_name is used for disassembly and is passed a
2312 // pointer to a cfstring and returns its name or nullptr.
2313 const char *get_objc2_64bit_cfstring_name(uint64_t ReferenceValue,
2314 struct DisassembleInfo *info) {
2315 const char *r, *name;
2316 uint32_t offset, left;
2318 struct cfstring64_t cfs;
2319 uint64_t cfs_characters;
2321 r = get_pointer_64(ReferenceValue, offset, left, S, info);
2322 if (r == nullptr || left < sizeof(struct cfstring64_t))
2324 memcpy(&cfs, r, sizeof(struct cfstring64_t));
2325 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
2327 if (cfs.characters == 0) {
2329 const char *symbol_name = get_symbol_64(
2330 offset + offsetof(struct cfstring64_t, characters), S, info, n_value);
2331 if (symbol_name == nullptr)
2333 cfs_characters = n_value;
2335 cfs_characters = cfs.characters;
2336 name = get_pointer_64(cfs_characters, offset, left, S, info);
2341 // get_objc2_64bit_selref() is used for disassembly and is passed a the address
2342 // of a pointer to an Objective-C selector reference when the pointer value is
2343 // zero as in a .o file and is likely to have a external relocation entry with
2344 // who's symbol's n_value is the real pointer to the selector name. If that is
2345 // the case the real pointer to the selector name is returned else 0 is
2347 uint64_t get_objc2_64bit_selref(uint64_t ReferenceValue,
2348 struct DisassembleInfo *info) {
2349 uint32_t offset, left;
2352 const char *r = get_pointer_64(ReferenceValue, offset, left, S, info);
2353 if (r == nullptr || left < sizeof(uint64_t))
2356 const char *symbol_name = get_symbol_64(offset, S, info, n_value);
2357 if (symbol_name == nullptr)
2362 // GuessLiteralPointer returns a string which for the item in the Mach-O file
2363 // for the address passed in as ReferenceValue for printing as a comment with
2364 // the instruction and also returns the corresponding type of that item
2365 // indirectly through ReferenceType.
2367 // If ReferenceValue is an address of literal cstring then a pointer to the
2368 // cstring is returned and ReferenceType is set to
2369 // LLVMDisassembler_ReferenceType_Out_LitPool_CstrAddr .
2371 // If ReferenceValue is an address of an Objective-C CFString, Selector ref or
2372 // Class ref that name is returned and the ReferenceType is set accordingly.
2374 // Lastly, literals which are Symbol address in a literal pool are looked for
2375 // and if found the symbol name is returned and ReferenceType is set to
2376 // LLVMDisassembler_ReferenceType_Out_LitPool_SymAddr .
2378 // If there is no item in the Mach-O file for the address passed in as
2379 // ReferenceValue nullptr is returned and ReferenceType is unchanged.
2380 const char *GuessLiteralPointer(uint64_t ReferenceValue, uint64_t ReferencePC,
2381 uint64_t *ReferenceType,
2382 struct DisassembleInfo *info) {
2383 // First see if there is an external relocation entry at the ReferencePC.
2384 uint64_t sect_addr = info->S.getAddress();
2385 uint64_t sect_offset = ReferencePC - sect_addr;
2386 bool reloc_found = false;
2388 MachO::any_relocation_info RE;
2389 bool isExtern = false;
2391 for (const RelocationRef &Reloc : info->S.relocations()) {
2392 uint64_t RelocOffset;
2393 Reloc.getOffset(RelocOffset);
2394 if (RelocOffset == sect_offset) {
2395 Rel = Reloc.getRawDataRefImpl();
2396 RE = info->O->getRelocation(Rel);
2397 if (info->O->isRelocationScattered(RE))
2399 isExtern = info->O->getPlainRelocationExternal(RE);
2401 symbol_iterator RelocSym = Reloc.getSymbol();
2408 // If there is an external relocation entry for a symbol in a section
2409 // then used that symbol's value for the value of the reference.
2410 if (reloc_found && isExtern) {
2411 if (info->O->getAnyRelocationPCRel(RE)) {
2412 unsigned Type = info->O->getAnyRelocationType(RE);
2413 if (Type == MachO::X86_64_RELOC_SIGNED) {
2414 Symbol.getAddress(ReferenceValue);
2419 // Look for literals such as Objective-C CFStrings refs, Selector refs,
2420 // Message refs and Class refs.
2421 bool classref, selref, msgref, cfstring;
2422 uint64_t pointer_value = GuessPointerPointer(ReferenceValue, info, classref,
2423 selref, msgref, cfstring);
2424 if (classref == true && pointer_value == 0) {
2425 // Note the ReferenceValue is a pointer into the __objc_classrefs section.
2426 // And the pointer_value in that section is typically zero as it will be
2427 // set by dyld as part of the "bind information".
2428 const char *name = get_dyld_bind_info_symbolname(ReferenceValue, info);
2429 if (name != nullptr) {
2430 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Class_Ref;
2431 const char *class_name = strrchr(name, '$');
2432 if (class_name != nullptr && class_name[1] == '_' &&
2433 class_name[2] != '\0') {
2434 info->class_name = class_name + 2;
2440 if (classref == true) {
2441 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Class_Ref;
2443 get_objc2_64bit_class_name(pointer_value, ReferenceValue, info);
2444 if (name != nullptr)
2445 info->class_name = name;
2447 name = "bad class ref";
2451 if (cfstring == true) {
2452 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_CFString_Ref;
2453 const char *name = get_objc2_64bit_cfstring_name(ReferenceValue, info);
2457 if (selref == true && pointer_value == 0)
2458 pointer_value = get_objc2_64bit_selref(ReferenceValue, info);
2460 if (pointer_value != 0)
2461 ReferenceValue = pointer_value;
2463 const char *name = GuessCstringPointer(ReferenceValue, info);
2465 if (pointer_value != 0 && selref == true) {
2466 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Selector_Ref;
2467 info->selector_name = name;
2468 } else if (pointer_value != 0 && msgref == true) {
2469 info->class_name = nullptr;
2470 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message_Ref;
2471 info->selector_name = name;
2473 *ReferenceType = LLVMDisassembler_ReferenceType_Out_LitPool_CstrAddr;
2477 // Lastly look for an indirect symbol with this ReferenceValue which is in
2478 // a literal pool. If found return that symbol name.
2479 name = GuessIndirectSymbol(ReferenceValue, info);
2481 *ReferenceType = LLVMDisassembler_ReferenceType_Out_LitPool_SymAddr;
2488 // SymbolizerSymbolLookUp is the symbol lookup function passed when creating
2489 // the Symbolizer. It looks up the ReferenceValue using the info passed via the
2490 // pointer to the struct DisassembleInfo that was passed when MCSymbolizer
2491 // is created and returns the symbol name that matches the ReferenceValue or
2492 // nullptr if none. The ReferenceType is passed in for the IN type of
2493 // reference the instruction is making from the values in defined in the header
2494 // "llvm-c/Disassembler.h". On return the ReferenceType can set to a specific
2495 // Out type and the ReferenceName will also be set which is added as a comment
2496 // to the disassembled instruction.
2499 // If the symbol name is a C++ mangled name then the demangled name is
2500 // returned through ReferenceName and ReferenceType is set to
2501 // LLVMDisassembler_ReferenceType_DeMangled_Name .
2504 // When this is called to get a symbol name for a branch target then the
2505 // ReferenceType will be LLVMDisassembler_ReferenceType_In_Branch and then
2506 // SymbolValue will be looked for in the indirect symbol table to determine if
2507 // it is an address for a symbol stub. If so then the symbol name for that
2508 // stub is returned indirectly through ReferenceName and then ReferenceType is
2509 // set to LLVMDisassembler_ReferenceType_Out_SymbolStub.
2511 // When this is called with an value loaded via a PC relative load then
2512 // ReferenceType will be LLVMDisassembler_ReferenceType_In_PCrel_Load then the
2513 // SymbolValue is checked to be an address of literal pointer, symbol pointer,
2514 // or an Objective-C meta data reference. If so the output ReferenceType is
2515 // set to correspond to that as well as setting the ReferenceName.
2516 const char *SymbolizerSymbolLookUp(void *DisInfo, uint64_t ReferenceValue,
2517 uint64_t *ReferenceType,
2518 uint64_t ReferencePC,
2519 const char **ReferenceName) {
2520 struct DisassembleInfo *info = (struct DisassembleInfo *)DisInfo;
2521 // If no verbose symbolic information is wanted then just return nullptr.
2522 if (info->verbose == false) {
2523 *ReferenceName = nullptr;
2524 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
2528 const char *SymbolName = GuessSymbolName(ReferenceValue, info->AddrMap);
2530 if (*ReferenceType == LLVMDisassembler_ReferenceType_In_Branch) {
2531 *ReferenceName = GuessIndirectSymbol(ReferenceValue, info);
2532 if (*ReferenceName != nullptr) {
2533 method_reference(info, ReferenceType, ReferenceName);
2534 if (*ReferenceType != LLVMDisassembler_ReferenceType_Out_Objc_Message)
2535 *ReferenceType = LLVMDisassembler_ReferenceType_Out_SymbolStub;
2538 if (SymbolName != nullptr && strncmp(SymbolName, "__Z", 3) == 0) {
2539 if (info->demangled_name != nullptr)
2540 free(info->demangled_name);
2542 info->demangled_name =
2543 abi::__cxa_demangle(SymbolName + 1, nullptr, nullptr, &status);
2544 if (info->demangled_name != nullptr) {
2545 *ReferenceName = info->demangled_name;
2546 *ReferenceType = LLVMDisassembler_ReferenceType_DeMangled_Name;
2548 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
2551 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
2552 } else if (*ReferenceType == LLVMDisassembler_ReferenceType_In_PCrel_Load) {
2554 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
2556 method_reference(info, ReferenceType, ReferenceName);
2558 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
2559 // If this is arm64 and the reference is an adrp instruction save the
2560 // instruction, passed in ReferenceValue and the address of the instruction
2561 // for use later if we see and add immediate instruction.
2562 } else if (info->O->getArch() == Triple::aarch64 &&
2563 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADRP) {
2564 info->adrp_inst = ReferenceValue;
2565 info->adrp_addr = ReferencePC;
2566 SymbolName = nullptr;
2567 *ReferenceName = nullptr;
2568 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
2569 // If this is arm64 and reference is an add immediate instruction and we
2571 // seen an adrp instruction just before it and the adrp's Xd register
2573 // this add's Xn register reconstruct the value being referenced and look to
2574 // see if it is a literal pointer. Note the add immediate instruction is
2575 // passed in ReferenceValue.
2576 } else if (info->O->getArch() == Triple::aarch64 &&
2577 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADDXri &&
2578 ReferencePC - 4 == info->adrp_addr &&
2579 (info->adrp_inst & 0x9f000000) == 0x90000000 &&
2580 (info->adrp_inst & 0x1f) == ((ReferenceValue >> 5) & 0x1f)) {
2581 uint32_t addxri_inst;
2582 uint64_t adrp_imm, addxri_imm;
2585 ((info->adrp_inst & 0x00ffffe0) >> 3) | ((info->adrp_inst >> 29) & 0x3);
2586 if (info->adrp_inst & 0x0200000)
2587 adrp_imm |= 0xfffffffffc000000LL;
2589 addxri_inst = ReferenceValue;
2590 addxri_imm = (addxri_inst >> 10) & 0xfff;
2591 if (((addxri_inst >> 22) & 0x3) == 1)
2594 ReferenceValue = (info->adrp_addr & 0xfffffffffffff000LL) +
2595 (adrp_imm << 12) + addxri_imm;
2598 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
2599 if (*ReferenceName == nullptr)
2600 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
2601 // If this is arm64 and the reference is a load register instruction and we
2602 // have seen an adrp instruction just before it and the adrp's Xd register
2603 // matches this add's Xn register reconstruct the value being referenced and
2604 // look to see if it is a literal pointer. Note the load register
2605 // instruction is passed in ReferenceValue.
2606 } else if (info->O->getArch() == Triple::aarch64 &&
2607 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_LDRXui &&
2608 ReferencePC - 4 == info->adrp_addr &&
2609 (info->adrp_inst & 0x9f000000) == 0x90000000 &&
2610 (info->adrp_inst & 0x1f) == ((ReferenceValue >> 5) & 0x1f)) {
2611 uint32_t ldrxui_inst;
2612 uint64_t adrp_imm, ldrxui_imm;
2615 ((info->adrp_inst & 0x00ffffe0) >> 3) | ((info->adrp_inst >> 29) & 0x3);
2616 if (info->adrp_inst & 0x0200000)
2617 adrp_imm |= 0xfffffffffc000000LL;
2619 ldrxui_inst = ReferenceValue;
2620 ldrxui_imm = (ldrxui_inst >> 10) & 0xfff;
2622 ReferenceValue = (info->adrp_addr & 0xfffffffffffff000LL) +
2623 (adrp_imm << 12) + (ldrxui_imm << 3);
2626 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
2627 if (*ReferenceName == nullptr)
2628 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
2630 // If this arm64 and is an load register (PC-relative) instruction the
2631 // ReferenceValue is the PC plus the immediate value.
2632 else if (info->O->getArch() == Triple::aarch64 &&
2633 (*ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_LDRXl ||
2634 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADR)) {
2636 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
2637 if (*ReferenceName == nullptr)
2638 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
2641 else if (SymbolName != nullptr && strncmp(SymbolName, "__Z", 3) == 0) {
2642 if (info->demangled_name != nullptr)
2643 free(info->demangled_name);
2645 info->demangled_name =
2646 abi::__cxa_demangle(SymbolName + 1, nullptr, nullptr, &status);
2647 if (info->demangled_name != nullptr) {
2648 *ReferenceName = info->demangled_name;
2649 *ReferenceType = LLVMDisassembler_ReferenceType_DeMangled_Name;
2654 *ReferenceName = nullptr;
2655 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
2661 /// \brief Emits the comments that are stored in the CommentStream.
2662 /// Each comment in the CommentStream must end with a newline.
2663 static void emitComments(raw_svector_ostream &CommentStream,
2664 SmallString<128> &CommentsToEmit,
2665 formatted_raw_ostream &FormattedOS,
2666 const MCAsmInfo &MAI) {
2667 // Flush the stream before taking its content.
2668 CommentStream.flush();
2669 StringRef Comments = CommentsToEmit.str();
2670 // Get the default information for printing a comment.
2671 const char *CommentBegin = MAI.getCommentString();
2672 unsigned CommentColumn = MAI.getCommentColumn();
2673 bool IsFirst = true;
2674 while (!Comments.empty()) {
2676 FormattedOS << '\n';
2677 // Emit a line of comments.
2678 FormattedOS.PadToColumn(CommentColumn);
2679 size_t Position = Comments.find('\n');
2680 FormattedOS << CommentBegin << ' ' << Comments.substr(0, Position);
2681 // Move after the newline character.
2682 Comments = Comments.substr(Position + 1);
2685 FormattedOS.flush();
2687 // Tell the comment stream that the vector changed underneath it.
2688 CommentsToEmit.clear();
2689 CommentStream.resync();
2692 static void DisassembleMachO(StringRef Filename, MachOObjectFile *MachOOF,
2693 StringRef DisSegName, StringRef DisSectName) {
2694 const char *McpuDefault = nullptr;
2695 const Target *ThumbTarget = nullptr;
2696 const Target *TheTarget = GetTarget(MachOOF, &McpuDefault, &ThumbTarget);
2698 // GetTarget prints out stuff.
2701 if (MCPU.empty() && McpuDefault)
2704 std::unique_ptr<const MCInstrInfo> InstrInfo(TheTarget->createMCInstrInfo());
2705 std::unique_ptr<const MCInstrInfo> ThumbInstrInfo;
2707 ThumbInstrInfo.reset(ThumbTarget->createMCInstrInfo());
2709 // Package up features to be passed to target/subtarget
2710 std::string FeaturesStr;
2711 if (MAttrs.size()) {
2712 SubtargetFeatures Features;
2713 for (unsigned i = 0; i != MAttrs.size(); ++i)
2714 Features.AddFeature(MAttrs[i]);
2715 FeaturesStr = Features.getString();
2718 // Set up disassembler.
2719 std::unique_ptr<const MCRegisterInfo> MRI(
2720 TheTarget->createMCRegInfo(TripleName));
2721 std::unique_ptr<const MCAsmInfo> AsmInfo(
2722 TheTarget->createMCAsmInfo(*MRI, TripleName));
2723 std::unique_ptr<const MCSubtargetInfo> STI(
2724 TheTarget->createMCSubtargetInfo(TripleName, MCPU, FeaturesStr));
2725 MCContext Ctx(AsmInfo.get(), MRI.get(), nullptr);
2726 std::unique_ptr<MCDisassembler> DisAsm(
2727 TheTarget->createMCDisassembler(*STI, Ctx));
2728 std::unique_ptr<MCSymbolizer> Symbolizer;
2729 struct DisassembleInfo SymbolizerInfo;
2730 std::unique_ptr<MCRelocationInfo> RelInfo(
2731 TheTarget->createMCRelocationInfo(TripleName, Ctx));
2733 Symbolizer.reset(TheTarget->createMCSymbolizer(
2734 TripleName, SymbolizerGetOpInfo, SymbolizerSymbolLookUp,
2735 &SymbolizerInfo, &Ctx, std::move(RelInfo)));
2736 DisAsm->setSymbolizer(std::move(Symbolizer));
2738 int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
2739 std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
2740 AsmPrinterVariant, *AsmInfo, *InstrInfo, *MRI, *STI));
2741 // Set the display preference for hex vs. decimal immediates.
2742 IP->setPrintImmHex(PrintImmHex);
2743 // Comment stream and backing vector.
2744 SmallString<128> CommentsToEmit;
2745 raw_svector_ostream CommentStream(CommentsToEmit);
2746 // FIXME: Setting the CommentStream in the InstPrinter is problematic in that
2747 // if it is done then arm64 comments for string literals don't get printed
2748 // and some constant get printed instead and not setting it causes intel
2749 // (32-bit and 64-bit) comments printed with different spacing before the
2750 // comment causing different diffs with the 'C' disassembler library API.
2751 // IP->setCommentStream(CommentStream);
2753 if (!AsmInfo || !STI || !DisAsm || !IP) {
2754 errs() << "error: couldn't initialize disassembler for target "
2755 << TripleName << '\n';
2759 // Set up thumb disassembler.
2760 std::unique_ptr<const MCRegisterInfo> ThumbMRI;
2761 std::unique_ptr<const MCAsmInfo> ThumbAsmInfo;
2762 std::unique_ptr<const MCSubtargetInfo> ThumbSTI;
2763 std::unique_ptr<MCDisassembler> ThumbDisAsm;
2764 std::unique_ptr<MCInstPrinter> ThumbIP;
2765 std::unique_ptr<MCContext> ThumbCtx;
2766 std::unique_ptr<MCSymbolizer> ThumbSymbolizer;
2767 struct DisassembleInfo ThumbSymbolizerInfo;
2768 std::unique_ptr<MCRelocationInfo> ThumbRelInfo;
2770 ThumbMRI.reset(ThumbTarget->createMCRegInfo(ThumbTripleName));
2772 ThumbTarget->createMCAsmInfo(*ThumbMRI, ThumbTripleName));
2774 ThumbTarget->createMCSubtargetInfo(ThumbTripleName, MCPU, FeaturesStr));
2775 ThumbCtx.reset(new MCContext(ThumbAsmInfo.get(), ThumbMRI.get(), nullptr));
2776 ThumbDisAsm.reset(ThumbTarget->createMCDisassembler(*ThumbSTI, *ThumbCtx));
2777 MCContext *PtrThumbCtx = ThumbCtx.get();
2779 ThumbTarget->createMCRelocationInfo(ThumbTripleName, *PtrThumbCtx));
2781 ThumbSymbolizer.reset(ThumbTarget->createMCSymbolizer(
2782 ThumbTripleName, SymbolizerGetOpInfo, SymbolizerSymbolLookUp,
2783 &ThumbSymbolizerInfo, PtrThumbCtx, std::move(ThumbRelInfo)));
2784 ThumbDisAsm->setSymbolizer(std::move(ThumbSymbolizer));
2786 int ThumbAsmPrinterVariant = ThumbAsmInfo->getAssemblerDialect();
2787 ThumbIP.reset(ThumbTarget->createMCInstPrinter(
2788 ThumbAsmPrinterVariant, *ThumbAsmInfo, *ThumbInstrInfo, *ThumbMRI,
2790 // Set the display preference for hex vs. decimal immediates.
2791 ThumbIP->setPrintImmHex(PrintImmHex);
2794 if (ThumbTarget && (!ThumbAsmInfo || !ThumbSTI || !ThumbDisAsm || !ThumbIP)) {
2795 errs() << "error: couldn't initialize disassembler for target "
2796 << ThumbTripleName << '\n';
2800 MachO::mach_header Header = MachOOF->getHeader();
2802 // FIXME: Using the -cfg command line option, this code used to be able to
2803 // annotate relocations with the referenced symbol's name, and if this was
2804 // inside a __[cf]string section, the data it points to. This is now replaced
2805 // by the upcoming MCSymbolizer, which needs the appropriate setup done above.
2806 std::vector<SectionRef> Sections;
2807 std::vector<SymbolRef> Symbols;
2808 SmallVector<uint64_t, 8> FoundFns;
2809 uint64_t BaseSegmentAddress;
2811 getSectionsAndSymbols(Header, MachOOF, Sections, Symbols, FoundFns,
2812 BaseSegmentAddress);
2814 // Sort the symbols by address, just in case they didn't come in that way.
2815 std::sort(Symbols.begin(), Symbols.end(), SymbolSorter());
2817 // Build a data in code table that is sorted on by the address of each entry.
2818 uint64_t BaseAddress = 0;
2819 if (Header.filetype == MachO::MH_OBJECT)
2820 BaseAddress = Sections[0].getAddress();
2822 BaseAddress = BaseSegmentAddress;
2824 for (dice_iterator DI = MachOOF->begin_dices(), DE = MachOOF->end_dices();
2827 DI->getOffset(Offset);
2828 Dices.push_back(std::make_pair(BaseAddress + Offset, *DI));
2830 array_pod_sort(Dices.begin(), Dices.end());
2833 raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls();
2835 raw_ostream &DebugOut = nulls();
2838 std::unique_ptr<DIContext> diContext;
2839 ObjectFile *DbgObj = MachOOF;
2840 // Try to find debug info and set up the DIContext for it.
2842 // A separate DSym file path was specified, parse it as a macho file,
2843 // get the sections and supply it to the section name parsing machinery.
2844 if (!DSYMFile.empty()) {
2845 ErrorOr<std::unique_ptr<MemoryBuffer>> BufOrErr =
2846 MemoryBuffer::getFileOrSTDIN(DSYMFile);
2847 if (std::error_code EC = BufOrErr.getError()) {
2848 errs() << "llvm-objdump: " << Filename << ": " << EC.message() << '\n';
2852 ObjectFile::createMachOObjectFile(BufOrErr.get()->getMemBufferRef())
2857 // Setup the DIContext
2858 diContext.reset(DIContext::getDWARFContext(*DbgObj));
2861 if (DumpSections.size() == 0)
2862 outs() << "(" << DisSegName << "," << DisSectName << ") section\n";
2864 for (unsigned SectIdx = 0; SectIdx != Sections.size(); SectIdx++) {
2866 if (Sections[SectIdx].getName(SectName) || SectName != DisSectName)
2869 DataRefImpl DR = Sections[SectIdx].getRawDataRefImpl();
2871 StringRef SegmentName = MachOOF->getSectionFinalSegmentName(DR);
2872 if (SegmentName != DisSegName)
2876 Sections[SectIdx].getContents(BytesStr);
2877 ArrayRef<uint8_t> Bytes(reinterpret_cast<const uint8_t *>(BytesStr.data()),
2879 uint64_t SectAddress = Sections[SectIdx].getAddress();
2881 bool symbolTableWorked = false;
2883 // Parse relocations.
2884 std::vector<std::pair<uint64_t, SymbolRef>> Relocs;
2885 for (const RelocationRef &Reloc : Sections[SectIdx].relocations()) {
2886 uint64_t RelocOffset;
2887 Reloc.getOffset(RelocOffset);
2888 uint64_t SectionAddress = Sections[SectIdx].getAddress();
2889 RelocOffset -= SectionAddress;
2891 symbol_iterator RelocSym = Reloc.getSymbol();
2893 Relocs.push_back(std::make_pair(RelocOffset, *RelocSym));
2895 array_pod_sort(Relocs.begin(), Relocs.end());
2897 // Create a map of symbol addresses to symbol names for use by
2898 // the SymbolizerSymbolLookUp() routine.
2899 SymbolAddressMap AddrMap;
2900 for (const SymbolRef &Symbol : MachOOF->symbols()) {
2903 if (ST == SymbolRef::ST_Function || ST == SymbolRef::ST_Data ||
2904 ST == SymbolRef::ST_Other) {
2906 Symbol.getAddress(Address);
2908 Symbol.getName(SymName);
2909 AddrMap[Address] = SymName;
2912 // Set up the block of info used by the Symbolizer call backs.
2913 SymbolizerInfo.verbose = true;
2914 SymbolizerInfo.O = MachOOF;
2915 SymbolizerInfo.S = Sections[SectIdx];
2916 SymbolizerInfo.AddrMap = &AddrMap;
2917 SymbolizerInfo.Sections = &Sections;
2918 SymbolizerInfo.class_name = nullptr;
2919 SymbolizerInfo.selector_name = nullptr;
2920 SymbolizerInfo.method = nullptr;
2921 SymbolizerInfo.demangled_name = nullptr;
2922 SymbolizerInfo.bindtable = nullptr;
2923 SymbolizerInfo.adrp_addr = 0;
2924 SymbolizerInfo.adrp_inst = 0;
2925 // Same for the ThumbSymbolizer
2926 ThumbSymbolizerInfo.verbose = true;
2927 ThumbSymbolizerInfo.O = MachOOF;
2928 ThumbSymbolizerInfo.S = Sections[SectIdx];
2929 ThumbSymbolizerInfo.AddrMap = &AddrMap;
2930 ThumbSymbolizerInfo.Sections = &Sections;
2931 ThumbSymbolizerInfo.class_name = nullptr;
2932 ThumbSymbolizerInfo.selector_name = nullptr;
2933 ThumbSymbolizerInfo.method = nullptr;
2934 ThumbSymbolizerInfo.demangled_name = nullptr;
2935 ThumbSymbolizerInfo.bindtable = nullptr;
2936 ThumbSymbolizerInfo.adrp_addr = 0;
2937 ThumbSymbolizerInfo.adrp_inst = 0;
2939 // Disassemble symbol by symbol.
2940 for (unsigned SymIdx = 0; SymIdx != Symbols.size(); SymIdx++) {
2942 Symbols[SymIdx].getName(SymName);
2945 Symbols[SymIdx].getType(ST);
2946 if (ST != SymbolRef::ST_Function)
2949 // Make sure the symbol is defined in this section.
2950 bool containsSym = Sections[SectIdx].containsSymbol(Symbols[SymIdx]);
2954 // Start at the address of the symbol relative to the section's address.
2956 uint64_t SectionAddress = Sections[SectIdx].getAddress();
2957 Symbols[SymIdx].getAddress(Start);
2958 Start -= SectionAddress;
2960 // Stop disassembling either at the beginning of the next symbol or at
2961 // the end of the section.
2962 bool containsNextSym = false;
2963 uint64_t NextSym = 0;
2964 uint64_t NextSymIdx = SymIdx + 1;
2965 while (Symbols.size() > NextSymIdx) {
2966 SymbolRef::Type NextSymType;
2967 Symbols[NextSymIdx].getType(NextSymType);
2968 if (NextSymType == SymbolRef::ST_Function) {
2970 Sections[SectIdx].containsSymbol(Symbols[NextSymIdx]);
2971 Symbols[NextSymIdx].getAddress(NextSym);
2972 NextSym -= SectionAddress;
2978 uint64_t SectSize = Sections[SectIdx].getSize();
2979 uint64_t End = containsNextSym ? NextSym : SectSize;
2982 symbolTableWorked = true;
2984 DataRefImpl Symb = Symbols[SymIdx].getRawDataRefImpl();
2986 (MachOOF->getSymbolFlags(Symb) & SymbolRef::SF_Thumb) && ThumbTarget;
2988 outs() << SymName << ":\n";
2989 DILineInfo lastLine;
2990 for (uint64_t Index = Start; Index < End; Index += Size) {
2993 uint64_t PC = SectAddress + Index;
2994 if (FullLeadingAddr) {
2995 if (MachOOF->is64Bit())
2996 outs() << format("%016" PRIx64, PC);
2998 outs() << format("%08" PRIx64, PC);
3000 outs() << format("%8" PRIx64 ":", PC);
3005 // Check the data in code table here to see if this is data not an
3006 // instruction to be disassembled.
3008 Dice.push_back(std::make_pair(PC, DiceRef()));
3009 dice_table_iterator DTI =
3010 std::search(Dices.begin(), Dices.end(), Dice.begin(), Dice.end(),
3011 compareDiceTableEntries);
3012 if (DTI != Dices.end()) {
3014 DTI->second.getLength(Length);
3016 DTI->second.getKind(Kind);
3017 Size = DumpDataInCode(reinterpret_cast<const char *>(Bytes.data()) +
3020 if ((Kind == MachO::DICE_KIND_JUMP_TABLE8) &&
3021 (PC == (DTI->first + Length - 1)) && (Length & 1))
3026 SmallVector<char, 64> AnnotationsBytes;
3027 raw_svector_ostream Annotations(AnnotationsBytes);
3031 gotInst = ThumbDisAsm->getInstruction(Inst, Size, Bytes.slice(Index),
3032 PC, DebugOut, Annotations);
3034 gotInst = DisAsm->getInstruction(Inst, Size, Bytes.slice(Index), PC,
3035 DebugOut, Annotations);
3037 if (!NoShowRawInsn) {
3038 DumpBytes(StringRef(
3039 reinterpret_cast<const char *>(Bytes.data()) + Index, Size));
3041 formatted_raw_ostream FormattedOS(outs());
3042 Annotations.flush();
3043 StringRef AnnotationsStr = Annotations.str();
3045 ThumbIP->printInst(&Inst, FormattedOS, AnnotationsStr);
3047 IP->printInst(&Inst, FormattedOS, AnnotationsStr);
3048 emitComments(CommentStream, CommentsToEmit, FormattedOS, *AsmInfo);
3050 // Print debug info.
3052 DILineInfo dli = diContext->getLineInfoForAddress(PC);
3053 // Print valid line info if it changed.
3054 if (dli != lastLine && dli.Line != 0)
3055 outs() << "\t## " << dli.FileName << ':' << dli.Line << ':'
3061 unsigned int Arch = MachOOF->getArch();
3062 if (Arch == Triple::x86_64 || Arch == Triple::x86) {
3063 outs() << format("\t.byte 0x%02x #bad opcode\n",
3064 *(Bytes.data() + Index) & 0xff);
3065 Size = 1; // skip exactly one illegible byte and move on.
3066 } else if (Arch == Triple::aarch64) {
3067 uint32_t opcode = (*(Bytes.data() + Index) & 0xff) |
3068 (*(Bytes.data() + Index + 1) & 0xff) << 8 |
3069 (*(Bytes.data() + Index + 2) & 0xff) << 16 |
3070 (*(Bytes.data() + Index + 3) & 0xff) << 24;
3071 outs() << format("\t.long\t0x%08x\n", opcode);
3074 errs() << "llvm-objdump: warning: invalid instruction encoding\n";
3076 Size = 1; // skip illegible bytes
3081 if (!symbolTableWorked) {
3082 // Reading the symbol table didn't work, disassemble the whole section.
3083 uint64_t SectAddress = Sections[SectIdx].getAddress();
3084 uint64_t SectSize = Sections[SectIdx].getSize();
3086 for (uint64_t Index = 0; Index < SectSize; Index += InstSize) {
3089 uint64_t PC = SectAddress + Index;
3090 if (DisAsm->getInstruction(Inst, InstSize, Bytes.slice(Index), PC,
3091 DebugOut, nulls())) {
3092 if (FullLeadingAddr) {
3093 if (MachOOF->is64Bit())
3094 outs() << format("%016" PRIx64, PC);
3096 outs() << format("%08" PRIx64, PC);
3098 outs() << format("%8" PRIx64 ":", PC);
3100 if (!NoShowRawInsn) {
3103 StringRef(reinterpret_cast<const char *>(Bytes.data()) + Index,
3106 IP->printInst(&Inst, outs(), "");
3109 unsigned int Arch = MachOOF->getArch();
3110 if (Arch == Triple::x86_64 || Arch == Triple::x86) {
3111 outs() << format("\t.byte 0x%02x #bad opcode\n",
3112 *(Bytes.data() + Index) & 0xff);
3113 InstSize = 1; // skip exactly one illegible byte and move on.
3115 errs() << "llvm-objdump: warning: invalid instruction encoding\n";
3117 InstSize = 1; // skip illegible bytes
3122 // The TripleName's need to be reset if we are called again for a different
3125 ThumbTripleName = "";
3127 if (SymbolizerInfo.method != nullptr)
3128 free(SymbolizerInfo.method);
3129 if (SymbolizerInfo.demangled_name != nullptr)
3130 free(SymbolizerInfo.demangled_name);
3131 if (SymbolizerInfo.bindtable != nullptr)
3132 delete SymbolizerInfo.bindtable;
3133 if (ThumbSymbolizerInfo.method != nullptr)
3134 free(ThumbSymbolizerInfo.method);
3135 if (ThumbSymbolizerInfo.demangled_name != nullptr)
3136 free(ThumbSymbolizerInfo.demangled_name);
3137 if (ThumbSymbolizerInfo.bindtable != nullptr)
3138 delete ThumbSymbolizerInfo.bindtable;
3142 //===----------------------------------------------------------------------===//
3143 // __compact_unwind section dumping
3144 //===----------------------------------------------------------------------===//
3148 template <typename T> static uint64_t readNext(const char *&Buf) {
3149 using llvm::support::little;
3150 using llvm::support::unaligned;
3152 uint64_t Val = support::endian::read<T, little, unaligned>(Buf);
3157 struct CompactUnwindEntry {
3158 uint32_t OffsetInSection;
3160 uint64_t FunctionAddr;
3162 uint32_t CompactEncoding;
3163 uint64_t PersonalityAddr;
3166 RelocationRef FunctionReloc;
3167 RelocationRef PersonalityReloc;
3168 RelocationRef LSDAReloc;
3170 CompactUnwindEntry(StringRef Contents, unsigned Offset, bool Is64)
3171 : OffsetInSection(Offset) {
3173 read<uint64_t>(Contents.data() + Offset);
3175 read<uint32_t>(Contents.data() + Offset);
3179 template <typename UIntPtr> void read(const char *Buf) {
3180 FunctionAddr = readNext<UIntPtr>(Buf);
3181 Length = readNext<uint32_t>(Buf);
3182 CompactEncoding = readNext<uint32_t>(Buf);
3183 PersonalityAddr = readNext<UIntPtr>(Buf);
3184 LSDAAddr = readNext<UIntPtr>(Buf);
3189 /// Given a relocation from __compact_unwind, consisting of the RelocationRef
3190 /// and data being relocated, determine the best base Name and Addend to use for
3191 /// display purposes.
3193 /// 1. An Extern relocation will directly reference a symbol (and the data is
3194 /// then already an addend), so use that.
3195 /// 2. Otherwise the data is an offset in the object file's layout; try to find
3196 // a symbol before it in the same section, and use the offset from there.
3197 /// 3. Finally, if all that fails, fall back to an offset from the start of the
3198 /// referenced section.
3199 static void findUnwindRelocNameAddend(const MachOObjectFile *Obj,
3200 std::map<uint64_t, SymbolRef> &Symbols,
3201 const RelocationRef &Reloc, uint64_t Addr,
3202 StringRef &Name, uint64_t &Addend) {
3203 if (Reloc.getSymbol() != Obj->symbol_end()) {
3204 Reloc.getSymbol()->getName(Name);
3209 auto RE = Obj->getRelocation(Reloc.getRawDataRefImpl());
3210 SectionRef RelocSection = Obj->getRelocationSection(RE);
3212 uint64_t SectionAddr = RelocSection.getAddress();
3214 auto Sym = Symbols.upper_bound(Addr);
3215 if (Sym == Symbols.begin()) {
3216 // The first symbol in the object is after this reference, the best we can
3217 // do is section-relative notation.
3218 RelocSection.getName(Name);
3219 Addend = Addr - SectionAddr;
3223 // Go back one so that SymbolAddress <= Addr.
3226 section_iterator SymSection = Obj->section_end();
3227 Sym->second.getSection(SymSection);
3228 if (RelocSection == *SymSection) {
3229 // There's a valid symbol in the same section before this reference.
3230 Sym->second.getName(Name);
3231 Addend = Addr - Sym->first;
3235 // There is a symbol before this reference, but it's in a different
3236 // section. Probably not helpful to mention it, so use the section name.
3237 RelocSection.getName(Name);
3238 Addend = Addr - SectionAddr;
3241 static void printUnwindRelocDest(const MachOObjectFile *Obj,
3242 std::map<uint64_t, SymbolRef> &Symbols,
3243 const RelocationRef &Reloc, uint64_t Addr) {
3247 if (!Reloc.getObjectFile())
3250 findUnwindRelocNameAddend(Obj, Symbols, Reloc, Addr, Name, Addend);
3254 outs() << " + " << format("0x%" PRIx64, Addend);
3258 printMachOCompactUnwindSection(const MachOObjectFile *Obj,
3259 std::map<uint64_t, SymbolRef> &Symbols,
3260 const SectionRef &CompactUnwind) {
3262 assert(Obj->isLittleEndian() &&
3263 "There should not be a big-endian .o with __compact_unwind");
3265 bool Is64 = Obj->is64Bit();
3266 uint32_t PointerSize = Is64 ? sizeof(uint64_t) : sizeof(uint32_t);
3267 uint32_t EntrySize = 3 * PointerSize + 2 * sizeof(uint32_t);
3270 CompactUnwind.getContents(Contents);
3272 SmallVector<CompactUnwindEntry, 4> CompactUnwinds;
3274 // First populate the initial raw offsets, encodings and so on from the entry.
3275 for (unsigned Offset = 0; Offset < Contents.size(); Offset += EntrySize) {
3276 CompactUnwindEntry Entry(Contents.data(), Offset, Is64);
3277 CompactUnwinds.push_back(Entry);
3280 // Next we need to look at the relocations to find out what objects are
3281 // actually being referred to.
3282 for (const RelocationRef &Reloc : CompactUnwind.relocations()) {
3283 uint64_t RelocAddress;
3284 Reloc.getOffset(RelocAddress);
3286 uint32_t EntryIdx = RelocAddress / EntrySize;
3287 uint32_t OffsetInEntry = RelocAddress - EntryIdx * EntrySize;
3288 CompactUnwindEntry &Entry = CompactUnwinds[EntryIdx];
3290 if (OffsetInEntry == 0)
3291 Entry.FunctionReloc = Reloc;
3292 else if (OffsetInEntry == PointerSize + 2 * sizeof(uint32_t))
3293 Entry.PersonalityReloc = Reloc;
3294 else if (OffsetInEntry == 2 * PointerSize + 2 * sizeof(uint32_t))
3295 Entry.LSDAReloc = Reloc;
3297 llvm_unreachable("Unexpected relocation in __compact_unwind section");
3300 // Finally, we're ready to print the data we've gathered.
3301 outs() << "Contents of __compact_unwind section:\n";
3302 for (auto &Entry : CompactUnwinds) {
3303 outs() << " Entry at offset "
3304 << format("0x%" PRIx32, Entry.OffsetInSection) << ":\n";
3306 // 1. Start of the region this entry applies to.
3307 outs() << " start: " << format("0x%" PRIx64,
3308 Entry.FunctionAddr) << ' ';
3309 printUnwindRelocDest(Obj, Symbols, Entry.FunctionReloc, Entry.FunctionAddr);
3312 // 2. Length of the region this entry applies to.
3313 outs() << " length: " << format("0x%" PRIx32, Entry.Length)
3315 // 3. The 32-bit compact encoding.
3316 outs() << " compact encoding: "
3317 << format("0x%08" PRIx32, Entry.CompactEncoding) << '\n';
3319 // 4. The personality function, if present.
3320 if (Entry.PersonalityReloc.getObjectFile()) {
3321 outs() << " personality function: "
3322 << format("0x%" PRIx64, Entry.PersonalityAddr) << ' ';
3323 printUnwindRelocDest(Obj, Symbols, Entry.PersonalityReloc,
3324 Entry.PersonalityAddr);
3328 // 5. This entry's language-specific data area.
3329 if (Entry.LSDAReloc.getObjectFile()) {
3330 outs() << " LSDA: " << format("0x%" PRIx64,
3331 Entry.LSDAAddr) << ' ';
3332 printUnwindRelocDest(Obj, Symbols, Entry.LSDAReloc, Entry.LSDAAddr);
3338 //===----------------------------------------------------------------------===//
3339 // __unwind_info section dumping
3340 //===----------------------------------------------------------------------===//
3342 static void printRegularSecondLevelUnwindPage(const char *PageStart) {
3343 const char *Pos = PageStart;
3344 uint32_t Kind = readNext<uint32_t>(Pos);
3346 assert(Kind == 2 && "kind for a regular 2nd level index should be 2");
3348 uint16_t EntriesStart = readNext<uint16_t>(Pos);
3349 uint16_t NumEntries = readNext<uint16_t>(Pos);
3351 Pos = PageStart + EntriesStart;
3352 for (unsigned i = 0; i < NumEntries; ++i) {
3353 uint32_t FunctionOffset = readNext<uint32_t>(Pos);
3354 uint32_t Encoding = readNext<uint32_t>(Pos);
3356 outs() << " [" << i << "]: "
3357 << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
3359 << "encoding=" << format("0x%08" PRIx32, Encoding) << '\n';
3363 static void printCompressedSecondLevelUnwindPage(
3364 const char *PageStart, uint32_t FunctionBase,
3365 const SmallVectorImpl<uint32_t> &CommonEncodings) {
3366 const char *Pos = PageStart;
3367 uint32_t Kind = readNext<uint32_t>(Pos);
3369 assert(Kind == 3 && "kind for a compressed 2nd level index should be 3");
3371 uint16_t EntriesStart = readNext<uint16_t>(Pos);
3372 uint16_t NumEntries = readNext<uint16_t>(Pos);
3374 uint16_t EncodingsStart = readNext<uint16_t>(Pos);
3375 readNext<uint16_t>(Pos);
3376 const auto *PageEncodings = reinterpret_cast<const support::ulittle32_t *>(
3377 PageStart + EncodingsStart);
3379 Pos = PageStart + EntriesStart;
3380 for (unsigned i = 0; i < NumEntries; ++i) {
3381 uint32_t Entry = readNext<uint32_t>(Pos);
3382 uint32_t FunctionOffset = FunctionBase + (Entry & 0xffffff);
3383 uint32_t EncodingIdx = Entry >> 24;
3386 if (EncodingIdx < CommonEncodings.size())
3387 Encoding = CommonEncodings[EncodingIdx];
3389 Encoding = PageEncodings[EncodingIdx - CommonEncodings.size()];
3391 outs() << " [" << i << "]: "
3392 << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
3394 << "encoding[" << EncodingIdx
3395 << "]=" << format("0x%08" PRIx32, Encoding) << '\n';
3399 static void printMachOUnwindInfoSection(const MachOObjectFile *Obj,
3400 std::map<uint64_t, SymbolRef> &Symbols,
3401 const SectionRef &UnwindInfo) {
3403 assert(Obj->isLittleEndian() &&
3404 "There should not be a big-endian .o with __unwind_info");
3406 outs() << "Contents of __unwind_info section:\n";
3409 UnwindInfo.getContents(Contents);
3410 const char *Pos = Contents.data();
3412 //===----------------------------------
3414 //===----------------------------------
3416 uint32_t Version = readNext<uint32_t>(Pos);
3417 outs() << " Version: "
3418 << format("0x%" PRIx32, Version) << '\n';
3419 assert(Version == 1 && "only understand version 1");
3421 uint32_t CommonEncodingsStart = readNext<uint32_t>(Pos);
3422 outs() << " Common encodings array section offset: "
3423 << format("0x%" PRIx32, CommonEncodingsStart) << '\n';
3424 uint32_t NumCommonEncodings = readNext<uint32_t>(Pos);
3425 outs() << " Number of common encodings in array: "
3426 << format("0x%" PRIx32, NumCommonEncodings) << '\n';
3428 uint32_t PersonalitiesStart = readNext<uint32_t>(Pos);
3429 outs() << " Personality function array section offset: "
3430 << format("0x%" PRIx32, PersonalitiesStart) << '\n';
3431 uint32_t NumPersonalities = readNext<uint32_t>(Pos);
3432 outs() << " Number of personality functions in array: "
3433 << format("0x%" PRIx32, NumPersonalities) << '\n';
3435 uint32_t IndicesStart = readNext<uint32_t>(Pos);
3436 outs() << " Index array section offset: "
3437 << format("0x%" PRIx32, IndicesStart) << '\n';
3438 uint32_t NumIndices = readNext<uint32_t>(Pos);
3439 outs() << " Number of indices in array: "
3440 << format("0x%" PRIx32, NumIndices) << '\n';
3442 //===----------------------------------
3443 // A shared list of common encodings
3444 //===----------------------------------
3446 // These occupy indices in the range [0, N] whenever an encoding is referenced
3447 // from a compressed 2nd level index table. In practice the linker only
3448 // creates ~128 of these, so that indices are available to embed encodings in
3449 // the 2nd level index.
3451 SmallVector<uint32_t, 64> CommonEncodings;
3452 outs() << " Common encodings: (count = " << NumCommonEncodings << ")\n";
3453 Pos = Contents.data() + CommonEncodingsStart;
3454 for (unsigned i = 0; i < NumCommonEncodings; ++i) {
3455 uint32_t Encoding = readNext<uint32_t>(Pos);
3456 CommonEncodings.push_back(Encoding);
3458 outs() << " encoding[" << i << "]: " << format("0x%08" PRIx32, Encoding)
3462 //===----------------------------------
3463 // Personality functions used in this executable
3464 //===----------------------------------
3466 // There should be only a handful of these (one per source language,
3467 // roughly). Particularly since they only get 2 bits in the compact encoding.
3469 outs() << " Personality functions: (count = " << NumPersonalities << ")\n";
3470 Pos = Contents.data() + PersonalitiesStart;
3471 for (unsigned i = 0; i < NumPersonalities; ++i) {
3472 uint32_t PersonalityFn = readNext<uint32_t>(Pos);
3473 outs() << " personality[" << i + 1
3474 << "]: " << format("0x%08" PRIx32, PersonalityFn) << '\n';
3477 //===----------------------------------
3478 // The level 1 index entries
3479 //===----------------------------------
3481 // These specify an approximate place to start searching for the more detailed
3482 // information, sorted by PC.
3485 uint32_t FunctionOffset;
3486 uint32_t SecondLevelPageStart;
3490 SmallVector<IndexEntry, 4> IndexEntries;
3492 outs() << " Top level indices: (count = " << NumIndices << ")\n";
3493 Pos = Contents.data() + IndicesStart;
3494 for (unsigned i = 0; i < NumIndices; ++i) {
3497 Entry.FunctionOffset = readNext<uint32_t>(Pos);
3498 Entry.SecondLevelPageStart = readNext<uint32_t>(Pos);
3499 Entry.LSDAStart = readNext<uint32_t>(Pos);
3500 IndexEntries.push_back(Entry);
3502 outs() << " [" << i << "]: "
3503 << "function offset=" << format("0x%08" PRIx32, Entry.FunctionOffset)
3505 << "2nd level page offset="
3506 << format("0x%08" PRIx32, Entry.SecondLevelPageStart) << ", "
3507 << "LSDA offset=" << format("0x%08" PRIx32, Entry.LSDAStart) << '\n';
3510 //===----------------------------------
3511 // Next come the LSDA tables
3512 //===----------------------------------
3514 // The LSDA layout is rather implicit: it's a contiguous array of entries from
3515 // the first top-level index's LSDAOffset to the last (sentinel).
3517 outs() << " LSDA descriptors:\n";
3518 Pos = Contents.data() + IndexEntries[0].LSDAStart;
3519 int NumLSDAs = (IndexEntries.back().LSDAStart - IndexEntries[0].LSDAStart) /
3520 (2 * sizeof(uint32_t));
3521 for (int i = 0; i < NumLSDAs; ++i) {
3522 uint32_t FunctionOffset = readNext<uint32_t>(Pos);
3523 uint32_t LSDAOffset = readNext<uint32_t>(Pos);
3524 outs() << " [" << i << "]: "
3525 << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
3527 << "LSDA offset=" << format("0x%08" PRIx32, LSDAOffset) << '\n';
3530 //===----------------------------------
3531 // Finally, the 2nd level indices
3532 //===----------------------------------
3534 // Generally these are 4K in size, and have 2 possible forms:
3535 // + Regular stores up to 511 entries with disparate encodings
3536 // + Compressed stores up to 1021 entries if few enough compact encoding
3538 outs() << " Second level indices:\n";
3539 for (unsigned i = 0; i < IndexEntries.size() - 1; ++i) {
3540 // The final sentinel top-level index has no associated 2nd level page
3541 if (IndexEntries[i].SecondLevelPageStart == 0)
3544 outs() << " Second level index[" << i << "]: "
3545 << "offset in section="
3546 << format("0x%08" PRIx32, IndexEntries[i].SecondLevelPageStart)
3548 << "base function offset="
3549 << format("0x%08" PRIx32, IndexEntries[i].FunctionOffset) << '\n';
3551 Pos = Contents.data() + IndexEntries[i].SecondLevelPageStart;
3552 uint32_t Kind = *reinterpret_cast<const support::ulittle32_t *>(Pos);
3554 printRegularSecondLevelUnwindPage(Pos);
3556 printCompressedSecondLevelUnwindPage(Pos, IndexEntries[i].FunctionOffset,
3559 llvm_unreachable("Do not know how to print this kind of 2nd level page");
3563 void llvm::printMachOUnwindInfo(const MachOObjectFile *Obj) {
3564 std::map<uint64_t, SymbolRef> Symbols;
3565 for (const SymbolRef &SymRef : Obj->symbols()) {
3566 // Discard any undefined or absolute symbols. They're not going to take part
3567 // in the convenience lookup for unwind info and just take up resources.
3568 section_iterator Section = Obj->section_end();
3569 SymRef.getSection(Section);
3570 if (Section == Obj->section_end())
3574 SymRef.getAddress(Addr);
3575 Symbols.insert(std::make_pair(Addr, SymRef));
3578 for (const SectionRef &Section : Obj->sections()) {
3580 Section.getName(SectName);
3581 if (SectName == "__compact_unwind")
3582 printMachOCompactUnwindSection(Obj, Symbols, Section);
3583 else if (SectName == "__unwind_info")
3584 printMachOUnwindInfoSection(Obj, Symbols, Section);
3585 else if (SectName == "__eh_frame")
3586 outs() << "llvm-objdump: warning: unhandled __eh_frame section\n";
3590 static void PrintMachHeader(uint32_t magic, uint32_t cputype,
3591 uint32_t cpusubtype, uint32_t filetype,
3592 uint32_t ncmds, uint32_t sizeofcmds, uint32_t flags,
3594 outs() << "Mach header\n";
3595 outs() << " magic cputype cpusubtype caps filetype ncmds "
3596 "sizeofcmds flags\n";
3598 if (magic == MachO::MH_MAGIC)
3599 outs() << " MH_MAGIC";
3600 else if (magic == MachO::MH_MAGIC_64)
3601 outs() << "MH_MAGIC_64";
3603 outs() << format(" 0x%08" PRIx32, magic);
3605 case MachO::CPU_TYPE_I386:
3607 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
3608 case MachO::CPU_SUBTYPE_I386_ALL:
3612 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
3616 case MachO::CPU_TYPE_X86_64:
3617 outs() << " X86_64";
3618 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
3619 case MachO::CPU_SUBTYPE_X86_64_ALL:
3622 case MachO::CPU_SUBTYPE_X86_64_H:
3623 outs() << " Haswell";
3626 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
3630 case MachO::CPU_TYPE_ARM:
3632 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
3633 case MachO::CPU_SUBTYPE_ARM_ALL:
3636 case MachO::CPU_SUBTYPE_ARM_V4T:
3639 case MachO::CPU_SUBTYPE_ARM_V5TEJ:
3642 case MachO::CPU_SUBTYPE_ARM_XSCALE:
3643 outs() << " XSCALE";
3645 case MachO::CPU_SUBTYPE_ARM_V6:
3648 case MachO::CPU_SUBTYPE_ARM_V6M:
3651 case MachO::CPU_SUBTYPE_ARM_V7:
3654 case MachO::CPU_SUBTYPE_ARM_V7EM:
3657 case MachO::CPU_SUBTYPE_ARM_V7K:
3660 case MachO::CPU_SUBTYPE_ARM_V7M:
3663 case MachO::CPU_SUBTYPE_ARM_V7S:
3667 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
3671 case MachO::CPU_TYPE_ARM64:
3673 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
3674 case MachO::CPU_SUBTYPE_ARM64_ALL:
3678 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
3682 case MachO::CPU_TYPE_POWERPC:
3684 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
3685 case MachO::CPU_SUBTYPE_POWERPC_ALL:
3689 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
3693 case MachO::CPU_TYPE_POWERPC64:
3695 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
3696 case MachO::CPU_SUBTYPE_POWERPC_ALL:
3700 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
3705 if ((cpusubtype & MachO::CPU_SUBTYPE_MASK) == MachO::CPU_SUBTYPE_LIB64) {
3708 outs() << format(" 0x%02" PRIx32,
3709 (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24);
3712 case MachO::MH_OBJECT:
3713 outs() << " OBJECT";
3715 case MachO::MH_EXECUTE:
3716 outs() << " EXECUTE";
3718 case MachO::MH_FVMLIB:
3719 outs() << " FVMLIB";
3721 case MachO::MH_CORE:
3724 case MachO::MH_PRELOAD:
3725 outs() << " PRELOAD";
3727 case MachO::MH_DYLIB:
3730 case MachO::MH_DYLIB_STUB:
3731 outs() << " DYLIB_STUB";
3733 case MachO::MH_DYLINKER:
3734 outs() << " DYLINKER";
3736 case MachO::MH_BUNDLE:
3737 outs() << " BUNDLE";
3739 case MachO::MH_DSYM:
3742 case MachO::MH_KEXT_BUNDLE:
3743 outs() << " KEXTBUNDLE";
3746 outs() << format(" %10u", filetype);
3749 outs() << format(" %5u", ncmds);
3750 outs() << format(" %10u", sizeofcmds);
3752 if (f & MachO::MH_NOUNDEFS) {
3753 outs() << " NOUNDEFS";
3754 f &= ~MachO::MH_NOUNDEFS;
3756 if (f & MachO::MH_INCRLINK) {
3757 outs() << " INCRLINK";
3758 f &= ~MachO::MH_INCRLINK;
3760 if (f & MachO::MH_DYLDLINK) {
3761 outs() << " DYLDLINK";
3762 f &= ~MachO::MH_DYLDLINK;
3764 if (f & MachO::MH_BINDATLOAD) {
3765 outs() << " BINDATLOAD";
3766 f &= ~MachO::MH_BINDATLOAD;
3768 if (f & MachO::MH_PREBOUND) {
3769 outs() << " PREBOUND";
3770 f &= ~MachO::MH_PREBOUND;
3772 if (f & MachO::MH_SPLIT_SEGS) {
3773 outs() << " SPLIT_SEGS";
3774 f &= ~MachO::MH_SPLIT_SEGS;
3776 if (f & MachO::MH_LAZY_INIT) {
3777 outs() << " LAZY_INIT";
3778 f &= ~MachO::MH_LAZY_INIT;
3780 if (f & MachO::MH_TWOLEVEL) {
3781 outs() << " TWOLEVEL";
3782 f &= ~MachO::MH_TWOLEVEL;
3784 if (f & MachO::MH_FORCE_FLAT) {
3785 outs() << " FORCE_FLAT";
3786 f &= ~MachO::MH_FORCE_FLAT;
3788 if (f & MachO::MH_NOMULTIDEFS) {
3789 outs() << " NOMULTIDEFS";
3790 f &= ~MachO::MH_NOMULTIDEFS;
3792 if (f & MachO::MH_NOFIXPREBINDING) {
3793 outs() << " NOFIXPREBINDING";
3794 f &= ~MachO::MH_NOFIXPREBINDING;
3796 if (f & MachO::MH_PREBINDABLE) {
3797 outs() << " PREBINDABLE";
3798 f &= ~MachO::MH_PREBINDABLE;
3800 if (f & MachO::MH_ALLMODSBOUND) {
3801 outs() << " ALLMODSBOUND";
3802 f &= ~MachO::MH_ALLMODSBOUND;
3804 if (f & MachO::MH_SUBSECTIONS_VIA_SYMBOLS) {
3805 outs() << " SUBSECTIONS_VIA_SYMBOLS";
3806 f &= ~MachO::MH_SUBSECTIONS_VIA_SYMBOLS;
3808 if (f & MachO::MH_CANONICAL) {
3809 outs() << " CANONICAL";
3810 f &= ~MachO::MH_CANONICAL;
3812 if (f & MachO::MH_WEAK_DEFINES) {
3813 outs() << " WEAK_DEFINES";
3814 f &= ~MachO::MH_WEAK_DEFINES;
3816 if (f & MachO::MH_BINDS_TO_WEAK) {
3817 outs() << " BINDS_TO_WEAK";
3818 f &= ~MachO::MH_BINDS_TO_WEAK;
3820 if (f & MachO::MH_ALLOW_STACK_EXECUTION) {
3821 outs() << " ALLOW_STACK_EXECUTION";
3822 f &= ~MachO::MH_ALLOW_STACK_EXECUTION;
3824 if (f & MachO::MH_DEAD_STRIPPABLE_DYLIB) {
3825 outs() << " DEAD_STRIPPABLE_DYLIB";
3826 f &= ~MachO::MH_DEAD_STRIPPABLE_DYLIB;
3828 if (f & MachO::MH_PIE) {
3830 f &= ~MachO::MH_PIE;
3832 if (f & MachO::MH_NO_REEXPORTED_DYLIBS) {
3833 outs() << " NO_REEXPORTED_DYLIBS";
3834 f &= ~MachO::MH_NO_REEXPORTED_DYLIBS;
3836 if (f & MachO::MH_HAS_TLV_DESCRIPTORS) {
3837 outs() << " MH_HAS_TLV_DESCRIPTORS";
3838 f &= ~MachO::MH_HAS_TLV_DESCRIPTORS;
3840 if (f & MachO::MH_NO_HEAP_EXECUTION) {
3841 outs() << " MH_NO_HEAP_EXECUTION";
3842 f &= ~MachO::MH_NO_HEAP_EXECUTION;
3844 if (f & MachO::MH_APP_EXTENSION_SAFE) {
3845 outs() << " APP_EXTENSION_SAFE";
3846 f &= ~MachO::MH_APP_EXTENSION_SAFE;
3848 if (f != 0 || flags == 0)
3849 outs() << format(" 0x%08" PRIx32, f);
3851 outs() << format(" 0x%08" PRIx32, magic);
3852 outs() << format(" %7d", cputype);
3853 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
3854 outs() << format(" 0x%02" PRIx32,
3855 (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24);
3856 outs() << format(" %10u", filetype);
3857 outs() << format(" %5u", ncmds);
3858 outs() << format(" %10u", sizeofcmds);
3859 outs() << format(" 0x%08" PRIx32, flags);
3864 static void PrintSegmentCommand(uint32_t cmd, uint32_t cmdsize,
3865 StringRef SegName, uint64_t vmaddr,
3866 uint64_t vmsize, uint64_t fileoff,
3867 uint64_t filesize, uint32_t maxprot,
3868 uint32_t initprot, uint32_t nsects,
3869 uint32_t flags, uint32_t object_size,
3871 uint64_t expected_cmdsize;
3872 if (cmd == MachO::LC_SEGMENT) {
3873 outs() << " cmd LC_SEGMENT\n";
3874 expected_cmdsize = nsects;
3875 expected_cmdsize *= sizeof(struct MachO::section);
3876 expected_cmdsize += sizeof(struct MachO::segment_command);
3878 outs() << " cmd LC_SEGMENT_64\n";
3879 expected_cmdsize = nsects;
3880 expected_cmdsize *= sizeof(struct MachO::section_64);
3881 expected_cmdsize += sizeof(struct MachO::segment_command_64);
3883 outs() << " cmdsize " << cmdsize;
3884 if (cmdsize != expected_cmdsize)
3885 outs() << " Inconsistent size\n";
3888 outs() << " segname " << SegName << "\n";
3889 if (cmd == MachO::LC_SEGMENT_64) {
3890 outs() << " vmaddr " << format("0x%016" PRIx64, vmaddr) << "\n";
3891 outs() << " vmsize " << format("0x%016" PRIx64, vmsize) << "\n";
3893 outs() << " vmaddr " << format("0x%08" PRIx64, vmaddr) << "\n";
3894 outs() << " vmsize " << format("0x%08" PRIx64, vmsize) << "\n";
3896 outs() << " fileoff " << fileoff;
3897 if (fileoff > object_size)
3898 outs() << " (past end of file)\n";
3901 outs() << " filesize " << filesize;
3902 if (fileoff + filesize > object_size)
3903 outs() << " (past end of file)\n";
3908 ~(MachO::VM_PROT_READ | MachO::VM_PROT_WRITE |
3909 MachO::VM_PROT_EXECUTE)) != 0)
3910 outs() << " maxprot ?" << format("0x%08" PRIx32, maxprot) << "\n";
3912 if (maxprot & MachO::VM_PROT_READ)
3913 outs() << " maxprot r";
3915 outs() << " maxprot -";
3916 if (maxprot & MachO::VM_PROT_WRITE)
3920 if (maxprot & MachO::VM_PROT_EXECUTE)
3926 ~(MachO::VM_PROT_READ | MachO::VM_PROT_WRITE |
3927 MachO::VM_PROT_EXECUTE)) != 0)
3928 outs() << " initprot ?" << format("0x%08" PRIx32, initprot) << "\n";
3930 if (initprot & MachO::VM_PROT_READ)
3931 outs() << " initprot r";
3933 outs() << " initprot -";
3934 if (initprot & MachO::VM_PROT_WRITE)
3938 if (initprot & MachO::VM_PROT_EXECUTE)
3944 outs() << " maxprot " << format("0x%08" PRIx32, maxprot) << "\n";
3945 outs() << " initprot " << format("0x%08" PRIx32, initprot) << "\n";
3947 outs() << " nsects " << nsects << "\n";
3951 outs() << " (none)\n";
3953 if (flags & MachO::SG_HIGHVM) {
3954 outs() << " HIGHVM";
3955 flags &= ~MachO::SG_HIGHVM;
3957 if (flags & MachO::SG_FVMLIB) {
3958 outs() << " FVMLIB";
3959 flags &= ~MachO::SG_FVMLIB;
3961 if (flags & MachO::SG_NORELOC) {
3962 outs() << " NORELOC";
3963 flags &= ~MachO::SG_NORELOC;
3965 if (flags & MachO::SG_PROTECTED_VERSION_1) {
3966 outs() << " PROTECTED_VERSION_1";
3967 flags &= ~MachO::SG_PROTECTED_VERSION_1;
3970 outs() << format(" 0x%08" PRIx32, flags) << " (unknown flags)\n";
3975 outs() << " flags " << format("0x%" PRIx32, flags) << "\n";
3979 static void PrintSection(const char *sectname, const char *segname,
3980 uint64_t addr, uint64_t size, uint32_t offset,
3981 uint32_t align, uint32_t reloff, uint32_t nreloc,
3982 uint32_t flags, uint32_t reserved1, uint32_t reserved2,
3983 uint32_t cmd, const char *sg_segname,
3984 uint32_t filetype, uint32_t object_size,
3986 outs() << "Section\n";
3987 outs() << " sectname " << format("%.16s\n", sectname);
3988 outs() << " segname " << format("%.16s", segname);
3989 if (filetype != MachO::MH_OBJECT && strncmp(sg_segname, segname, 16) != 0)
3990 outs() << " (does not match segment)\n";
3993 if (cmd == MachO::LC_SEGMENT_64) {
3994 outs() << " addr " << format("0x%016" PRIx64, addr) << "\n";
3995 outs() << " size " << format("0x%016" PRIx64, size);
3997 outs() << " addr " << format("0x%08" PRIx64, addr) << "\n";
3998 outs() << " size " << format("0x%08" PRIx64, size);
4000 if ((flags & MachO::S_ZEROFILL) != 0 && offset + size > object_size)
4001 outs() << " (past end of file)\n";
4004 outs() << " offset " << offset;
4005 if (offset > object_size)
4006 outs() << " (past end of file)\n";
4009 uint32_t align_shifted = 1 << align;
4010 outs() << " align 2^" << align << " (" << align_shifted << ")\n";
4011 outs() << " reloff " << reloff;
4012 if (reloff > object_size)
4013 outs() << " (past end of file)\n";
4016 outs() << " nreloc " << nreloc;
4017 if (reloff + nreloc * sizeof(struct MachO::relocation_info) > object_size)
4018 outs() << " (past end of file)\n";
4021 uint32_t section_type = flags & MachO::SECTION_TYPE;
4024 if (section_type == MachO::S_REGULAR)
4025 outs() << " S_REGULAR\n";
4026 else if (section_type == MachO::S_ZEROFILL)
4027 outs() << " S_ZEROFILL\n";
4028 else if (section_type == MachO::S_CSTRING_LITERALS)
4029 outs() << " S_CSTRING_LITERALS\n";
4030 else if (section_type == MachO::S_4BYTE_LITERALS)
4031 outs() << " S_4BYTE_LITERALS\n";
4032 else if (section_type == MachO::S_8BYTE_LITERALS)
4033 outs() << " S_8BYTE_LITERALS\n";
4034 else if (section_type == MachO::S_16BYTE_LITERALS)
4035 outs() << " S_16BYTE_LITERALS\n";
4036 else if (section_type == MachO::S_LITERAL_POINTERS)
4037 outs() << " S_LITERAL_POINTERS\n";
4038 else if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS)
4039 outs() << " S_NON_LAZY_SYMBOL_POINTERS\n";
4040 else if (section_type == MachO::S_LAZY_SYMBOL_POINTERS)
4041 outs() << " S_LAZY_SYMBOL_POINTERS\n";
4042 else if (section_type == MachO::S_SYMBOL_STUBS)
4043 outs() << " S_SYMBOL_STUBS\n";
4044 else if (section_type == MachO::S_MOD_INIT_FUNC_POINTERS)
4045 outs() << " S_MOD_INIT_FUNC_POINTERS\n";
4046 else if (section_type == MachO::S_MOD_TERM_FUNC_POINTERS)
4047 outs() << " S_MOD_TERM_FUNC_POINTERS\n";
4048 else if (section_type == MachO::S_COALESCED)
4049 outs() << " S_COALESCED\n";
4050 else if (section_type == MachO::S_INTERPOSING)
4051 outs() << " S_INTERPOSING\n";
4052 else if (section_type == MachO::S_DTRACE_DOF)
4053 outs() << " S_DTRACE_DOF\n";
4054 else if (section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS)
4055 outs() << " S_LAZY_DYLIB_SYMBOL_POINTERS\n";
4056 else if (section_type == MachO::S_THREAD_LOCAL_REGULAR)
4057 outs() << " S_THREAD_LOCAL_REGULAR\n";
4058 else if (section_type == MachO::S_THREAD_LOCAL_ZEROFILL)
4059 outs() << " S_THREAD_LOCAL_ZEROFILL\n";
4060 else if (section_type == MachO::S_THREAD_LOCAL_VARIABLES)
4061 outs() << " S_THREAD_LOCAL_VARIABLES\n";
4062 else if (section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS)
4063 outs() << " S_THREAD_LOCAL_VARIABLE_POINTERS\n";
4064 else if (section_type == MachO::S_THREAD_LOCAL_INIT_FUNCTION_POINTERS)
4065 outs() << " S_THREAD_LOCAL_INIT_FUNCTION_POINTERS\n";
4067 outs() << format("0x%08" PRIx32, section_type) << "\n";
4068 outs() << "attributes";
4069 uint32_t section_attributes = flags & MachO::SECTION_ATTRIBUTES;
4070 if (section_attributes & MachO::S_ATTR_PURE_INSTRUCTIONS)
4071 outs() << " PURE_INSTRUCTIONS";
4072 if (section_attributes & MachO::S_ATTR_NO_TOC)
4073 outs() << " NO_TOC";
4074 if (section_attributes & MachO::S_ATTR_STRIP_STATIC_SYMS)
4075 outs() << " STRIP_STATIC_SYMS";
4076 if (section_attributes & MachO::S_ATTR_NO_DEAD_STRIP)
4077 outs() << " NO_DEAD_STRIP";
4078 if (section_attributes & MachO::S_ATTR_LIVE_SUPPORT)
4079 outs() << " LIVE_SUPPORT";
4080 if (section_attributes & MachO::S_ATTR_SELF_MODIFYING_CODE)
4081 outs() << " SELF_MODIFYING_CODE";
4082 if (section_attributes & MachO::S_ATTR_DEBUG)
4084 if (section_attributes & MachO::S_ATTR_SOME_INSTRUCTIONS)
4085 outs() << " SOME_INSTRUCTIONS";
4086 if (section_attributes & MachO::S_ATTR_EXT_RELOC)
4087 outs() << " EXT_RELOC";
4088 if (section_attributes & MachO::S_ATTR_LOC_RELOC)
4089 outs() << " LOC_RELOC";
4090 if (section_attributes == 0)
4091 outs() << " (none)";
4094 outs() << " flags " << format("0x%08" PRIx32, flags) << "\n";
4095 outs() << " reserved1 " << reserved1;
4096 if (section_type == MachO::S_SYMBOL_STUBS ||
4097 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
4098 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
4099 section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
4100 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS)
4101 outs() << " (index into indirect symbol table)\n";
4104 outs() << " reserved2 " << reserved2;
4105 if (section_type == MachO::S_SYMBOL_STUBS)
4106 outs() << " (size of stubs)\n";
4111 static void PrintSymtabLoadCommand(MachO::symtab_command st, bool Is64Bit,
4112 uint32_t object_size) {
4113 outs() << " cmd LC_SYMTAB\n";
4114 outs() << " cmdsize " << st.cmdsize;
4115 if (st.cmdsize != sizeof(struct MachO::symtab_command))
4116 outs() << " Incorrect size\n";
4119 outs() << " symoff " << st.symoff;
4120 if (st.symoff > object_size)
4121 outs() << " (past end of file)\n";
4124 outs() << " nsyms " << st.nsyms;
4127 big_size = st.nsyms;
4128 big_size *= sizeof(struct MachO::nlist_64);
4129 big_size += st.symoff;
4130 if (big_size > object_size)
4131 outs() << " (past end of file)\n";
4135 big_size = st.nsyms;
4136 big_size *= sizeof(struct MachO::nlist);
4137 big_size += st.symoff;
4138 if (big_size > object_size)
4139 outs() << " (past end of file)\n";
4143 outs() << " stroff " << st.stroff;
4144 if (st.stroff > object_size)
4145 outs() << " (past end of file)\n";
4148 outs() << " strsize " << st.strsize;
4149 big_size = st.stroff;
4150 big_size += st.strsize;
4151 if (big_size > object_size)
4152 outs() << " (past end of file)\n";
4157 static void PrintDysymtabLoadCommand(MachO::dysymtab_command dyst,
4158 uint32_t nsyms, uint32_t object_size,
4160 outs() << " cmd LC_DYSYMTAB\n";
4161 outs() << " cmdsize " << dyst.cmdsize;
4162 if (dyst.cmdsize != sizeof(struct MachO::dysymtab_command))
4163 outs() << " Incorrect size\n";
4166 outs() << " ilocalsym " << dyst.ilocalsym;
4167 if (dyst.ilocalsym > nsyms)
4168 outs() << " (greater than the number of symbols)\n";
4171 outs() << " nlocalsym " << dyst.nlocalsym;
4173 big_size = dyst.ilocalsym;
4174 big_size += dyst.nlocalsym;
4175 if (big_size > nsyms)
4176 outs() << " (past the end of the symbol table)\n";
4179 outs() << " iextdefsym " << dyst.iextdefsym;
4180 if (dyst.iextdefsym > nsyms)
4181 outs() << " (greater than the number of symbols)\n";
4184 outs() << " nextdefsym " << dyst.nextdefsym;
4185 big_size = dyst.iextdefsym;
4186 big_size += dyst.nextdefsym;
4187 if (big_size > nsyms)
4188 outs() << " (past the end of the symbol table)\n";
4191 outs() << " iundefsym " << dyst.iundefsym;
4192 if (dyst.iundefsym > nsyms)
4193 outs() << " (greater than the number of symbols)\n";
4196 outs() << " nundefsym " << dyst.nundefsym;
4197 big_size = dyst.iundefsym;
4198 big_size += dyst.nundefsym;
4199 if (big_size > nsyms)
4200 outs() << " (past the end of the symbol table)\n";
4203 outs() << " tocoff " << dyst.tocoff;
4204 if (dyst.tocoff > object_size)
4205 outs() << " (past end of file)\n";
4208 outs() << " ntoc " << dyst.ntoc;
4209 big_size = dyst.ntoc;
4210 big_size *= sizeof(struct MachO::dylib_table_of_contents);
4211 big_size += dyst.tocoff;
4212 if (big_size > object_size)
4213 outs() << " (past end of file)\n";
4216 outs() << " modtaboff " << dyst.modtaboff;
4217 if (dyst.modtaboff > object_size)
4218 outs() << " (past end of file)\n";
4221 outs() << " nmodtab " << dyst.nmodtab;
4224 modtabend = dyst.nmodtab;
4225 modtabend *= sizeof(struct MachO::dylib_module_64);
4226 modtabend += dyst.modtaboff;
4228 modtabend = dyst.nmodtab;
4229 modtabend *= sizeof(struct MachO::dylib_module);
4230 modtabend += dyst.modtaboff;
4232 if (modtabend > object_size)
4233 outs() << " (past end of file)\n";
4236 outs() << " extrefsymoff " << dyst.extrefsymoff;
4237 if (dyst.extrefsymoff > object_size)
4238 outs() << " (past end of file)\n";
4241 outs() << " nextrefsyms " << dyst.nextrefsyms;
4242 big_size = dyst.nextrefsyms;
4243 big_size *= sizeof(struct MachO::dylib_reference);
4244 big_size += dyst.extrefsymoff;
4245 if (big_size > object_size)
4246 outs() << " (past end of file)\n";
4249 outs() << " indirectsymoff " << dyst.indirectsymoff;
4250 if (dyst.indirectsymoff > object_size)
4251 outs() << " (past end of file)\n";
4254 outs() << " nindirectsyms " << dyst.nindirectsyms;
4255 big_size = dyst.nindirectsyms;
4256 big_size *= sizeof(uint32_t);
4257 big_size += dyst.indirectsymoff;
4258 if (big_size > object_size)
4259 outs() << " (past end of file)\n";
4262 outs() << " extreloff " << dyst.extreloff;
4263 if (dyst.extreloff > object_size)
4264 outs() << " (past end of file)\n";
4267 outs() << " nextrel " << dyst.nextrel;
4268 big_size = dyst.nextrel;
4269 big_size *= sizeof(struct MachO::relocation_info);
4270 big_size += dyst.extreloff;
4271 if (big_size > object_size)
4272 outs() << " (past end of file)\n";
4275 outs() << " locreloff " << dyst.locreloff;
4276 if (dyst.locreloff > object_size)
4277 outs() << " (past end of file)\n";
4280 outs() << " nlocrel " << dyst.nlocrel;
4281 big_size = dyst.nlocrel;
4282 big_size *= sizeof(struct MachO::relocation_info);
4283 big_size += dyst.locreloff;
4284 if (big_size > object_size)
4285 outs() << " (past end of file)\n";
4290 static void PrintDyldInfoLoadCommand(MachO::dyld_info_command dc,
4291 uint32_t object_size) {
4292 if (dc.cmd == MachO::LC_DYLD_INFO)
4293 outs() << " cmd LC_DYLD_INFO\n";
4295 outs() << " cmd LC_DYLD_INFO_ONLY\n";
4296 outs() << " cmdsize " << dc.cmdsize;
4297 if (dc.cmdsize != sizeof(struct MachO::dyld_info_command))
4298 outs() << " Incorrect size\n";
4301 outs() << " rebase_off " << dc.rebase_off;
4302 if (dc.rebase_off > object_size)
4303 outs() << " (past end of file)\n";
4306 outs() << " rebase_size " << dc.rebase_size;
4308 big_size = dc.rebase_off;
4309 big_size += dc.rebase_size;
4310 if (big_size > object_size)
4311 outs() << " (past end of file)\n";
4314 outs() << " bind_off " << dc.bind_off;
4315 if (dc.bind_off > object_size)
4316 outs() << " (past end of file)\n";
4319 outs() << " bind_size " << dc.bind_size;
4320 big_size = dc.bind_off;
4321 big_size += dc.bind_size;
4322 if (big_size > object_size)
4323 outs() << " (past end of file)\n";
4326 outs() << " weak_bind_off " << dc.weak_bind_off;
4327 if (dc.weak_bind_off > object_size)
4328 outs() << " (past end of file)\n";
4331 outs() << " weak_bind_size " << dc.weak_bind_size;
4332 big_size = dc.weak_bind_off;
4333 big_size += dc.weak_bind_size;
4334 if (big_size > object_size)
4335 outs() << " (past end of file)\n";
4338 outs() << " lazy_bind_off " << dc.lazy_bind_off;
4339 if (dc.lazy_bind_off > object_size)
4340 outs() << " (past end of file)\n";
4343 outs() << " lazy_bind_size " << dc.lazy_bind_size;
4344 big_size = dc.lazy_bind_off;
4345 big_size += dc.lazy_bind_size;
4346 if (big_size > object_size)
4347 outs() << " (past end of file)\n";
4350 outs() << " export_off " << dc.export_off;
4351 if (dc.export_off > object_size)
4352 outs() << " (past end of file)\n";
4355 outs() << " export_size " << dc.export_size;
4356 big_size = dc.export_off;
4357 big_size += dc.export_size;
4358 if (big_size > object_size)
4359 outs() << " (past end of file)\n";
4364 static void PrintDyldLoadCommand(MachO::dylinker_command dyld,
4366 if (dyld.cmd == MachO::LC_ID_DYLINKER)
4367 outs() << " cmd LC_ID_DYLINKER\n";
4368 else if (dyld.cmd == MachO::LC_LOAD_DYLINKER)
4369 outs() << " cmd LC_LOAD_DYLINKER\n";
4370 else if (dyld.cmd == MachO::LC_DYLD_ENVIRONMENT)
4371 outs() << " cmd LC_DYLD_ENVIRONMENT\n";
4373 outs() << " cmd ?(" << dyld.cmd << ")\n";
4374 outs() << " cmdsize " << dyld.cmdsize;
4375 if (dyld.cmdsize < sizeof(struct MachO::dylinker_command))
4376 outs() << " Incorrect size\n";
4379 if (dyld.name >= dyld.cmdsize)
4380 outs() << " name ?(bad offset " << dyld.name << ")\n";
4382 const char *P = (const char *)(Ptr) + dyld.name;
4383 outs() << " name " << P << " (offset " << dyld.name << ")\n";
4387 static void PrintUuidLoadCommand(MachO::uuid_command uuid) {
4388 outs() << " cmd LC_UUID\n";
4389 outs() << " cmdsize " << uuid.cmdsize;
4390 if (uuid.cmdsize != sizeof(struct MachO::uuid_command))
4391 outs() << " Incorrect size\n";
4395 outs() << format("%02" PRIX32, uuid.uuid[0]);
4396 outs() << format("%02" PRIX32, uuid.uuid[1]);
4397 outs() << format("%02" PRIX32, uuid.uuid[2]);
4398 outs() << format("%02" PRIX32, uuid.uuid[3]);
4400 outs() << format("%02" PRIX32, uuid.uuid[4]);
4401 outs() << format("%02" PRIX32, uuid.uuid[5]);
4403 outs() << format("%02" PRIX32, uuid.uuid[6]);
4404 outs() << format("%02" PRIX32, uuid.uuid[7]);
4406 outs() << format("%02" PRIX32, uuid.uuid[8]);
4407 outs() << format("%02" PRIX32, uuid.uuid[9]);
4409 outs() << format("%02" PRIX32, uuid.uuid[10]);
4410 outs() << format("%02" PRIX32, uuid.uuid[11]);
4411 outs() << format("%02" PRIX32, uuid.uuid[12]);
4412 outs() << format("%02" PRIX32, uuid.uuid[13]);
4413 outs() << format("%02" PRIX32, uuid.uuid[14]);
4414 outs() << format("%02" PRIX32, uuid.uuid[15]);
4418 static void PrintRpathLoadCommand(MachO::rpath_command rpath, const char *Ptr) {
4419 outs() << " cmd LC_RPATH\n";
4420 outs() << " cmdsize " << rpath.cmdsize;
4421 if (rpath.cmdsize < sizeof(struct MachO::rpath_command))
4422 outs() << " Incorrect size\n";
4425 if (rpath.path >= rpath.cmdsize)
4426 outs() << " path ?(bad offset " << rpath.path << ")\n";
4428 const char *P = (const char *)(Ptr) + rpath.path;
4429 outs() << " path " << P << " (offset " << rpath.path << ")\n";
4433 static void PrintVersionMinLoadCommand(MachO::version_min_command vd) {
4434 if (vd.cmd == MachO::LC_VERSION_MIN_MACOSX)
4435 outs() << " cmd LC_VERSION_MIN_MACOSX\n";
4436 else if (vd.cmd == MachO::LC_VERSION_MIN_IPHONEOS)
4437 outs() << " cmd LC_VERSION_MIN_IPHONEOS\n";
4439 outs() << " cmd " << vd.cmd << " (?)\n";
4440 outs() << " cmdsize " << vd.cmdsize;
4441 if (vd.cmdsize != sizeof(struct MachO::version_min_command))
4442 outs() << " Incorrect size\n";
4445 outs() << " version " << ((vd.version >> 16) & 0xffff) << "."
4446 << ((vd.version >> 8) & 0xff);
4447 if ((vd.version & 0xff) != 0)
4448 outs() << "." << (vd.version & 0xff);
4451 outs() << " sdk n/a";
4453 outs() << " sdk " << ((vd.sdk >> 16) & 0xffff) << "."
4454 << ((vd.sdk >> 8) & 0xff);
4456 if ((vd.sdk & 0xff) != 0)
4457 outs() << "." << (vd.sdk & 0xff);
4461 static void PrintSourceVersionCommand(MachO::source_version_command sd) {
4462 outs() << " cmd LC_SOURCE_VERSION\n";
4463 outs() << " cmdsize " << sd.cmdsize;
4464 if (sd.cmdsize != sizeof(struct MachO::source_version_command))
4465 outs() << " Incorrect size\n";
4468 uint64_t a = (sd.version >> 40) & 0xffffff;
4469 uint64_t b = (sd.version >> 30) & 0x3ff;
4470 uint64_t c = (sd.version >> 20) & 0x3ff;
4471 uint64_t d = (sd.version >> 10) & 0x3ff;
4472 uint64_t e = sd.version & 0x3ff;
4473 outs() << " version " << a << "." << b;
4475 outs() << "." << c << "." << d << "." << e;
4477 outs() << "." << c << "." << d;
4483 static void PrintEntryPointCommand(MachO::entry_point_command ep) {
4484 outs() << " cmd LC_MAIN\n";
4485 outs() << " cmdsize " << ep.cmdsize;
4486 if (ep.cmdsize != sizeof(struct MachO::entry_point_command))
4487 outs() << " Incorrect size\n";
4490 outs() << " entryoff " << ep.entryoff << "\n";
4491 outs() << " stacksize " << ep.stacksize << "\n";
4494 static void PrintEncryptionInfoCommand(MachO::encryption_info_command ec,
4495 uint32_t object_size) {
4496 outs() << " cmd LC_ENCRYPTION_INFO\n";
4497 outs() << " cmdsize " << ec.cmdsize;
4498 if (ec.cmdsize != sizeof(struct MachO::encryption_info_command))
4499 outs() << " Incorrect size\n";
4502 outs() << " cryptoff " << ec.cryptoff;
4503 if (ec.cryptoff > object_size)
4504 outs() << " (past end of file)\n";
4507 outs() << " cryptsize " << ec.cryptsize;
4508 if (ec.cryptsize > object_size)
4509 outs() << " (past end of file)\n";
4512 outs() << " cryptid " << ec.cryptid << "\n";
4515 static void PrintEncryptionInfoCommand64(MachO::encryption_info_command_64 ec,
4516 uint32_t object_size) {
4517 outs() << " cmd LC_ENCRYPTION_INFO_64\n";
4518 outs() << " cmdsize " << ec.cmdsize;
4519 if (ec.cmdsize != sizeof(struct MachO::encryption_info_command_64))
4520 outs() << " Incorrect size\n";
4523 outs() << " cryptoff " << ec.cryptoff;
4524 if (ec.cryptoff > object_size)
4525 outs() << " (past end of file)\n";
4528 outs() << " cryptsize " << ec.cryptsize;
4529 if (ec.cryptsize > object_size)
4530 outs() << " (past end of file)\n";
4533 outs() << " cryptid " << ec.cryptid << "\n";
4534 outs() << " pad " << ec.pad << "\n";
4537 static void PrintLinkerOptionCommand(MachO::linker_option_command lo,
4539 outs() << " cmd LC_LINKER_OPTION\n";
4540 outs() << " cmdsize " << lo.cmdsize;
4541 if (lo.cmdsize < sizeof(struct MachO::linker_option_command))
4542 outs() << " Incorrect size\n";
4545 outs() << " count " << lo.count << "\n";
4546 const char *string = Ptr + sizeof(struct MachO::linker_option_command);
4547 uint32_t left = lo.cmdsize - sizeof(struct MachO::linker_option_command);
4550 while (*string == '\0' && left > 0) {
4556 outs() << " string #" << i << " " << format("%.*s\n", left, string);
4557 uint32_t NullPos = StringRef(string, left).find('\0');
4558 uint32_t len = std::min(NullPos, left) + 1;
4564 outs() << " count " << lo.count << " does not match number of strings "
4568 static void PrintSubFrameworkCommand(MachO::sub_framework_command sub,
4570 outs() << " cmd LC_SUB_FRAMEWORK\n";
4571 outs() << " cmdsize " << sub.cmdsize;
4572 if (sub.cmdsize < sizeof(struct MachO::sub_framework_command))
4573 outs() << " Incorrect size\n";
4576 if (sub.umbrella < sub.cmdsize) {
4577 const char *P = Ptr + sub.umbrella;
4578 outs() << " umbrella " << P << " (offset " << sub.umbrella << ")\n";
4580 outs() << " umbrella ?(bad offset " << sub.umbrella << ")\n";
4584 static void PrintSubUmbrellaCommand(MachO::sub_umbrella_command sub,
4586 outs() << " cmd LC_SUB_UMBRELLA\n";
4587 outs() << " cmdsize " << sub.cmdsize;
4588 if (sub.cmdsize < sizeof(struct MachO::sub_umbrella_command))
4589 outs() << " Incorrect size\n";
4592 if (sub.sub_umbrella < sub.cmdsize) {
4593 const char *P = Ptr + sub.sub_umbrella;
4594 outs() << " sub_umbrella " << P << " (offset " << sub.sub_umbrella << ")\n";
4596 outs() << " sub_umbrella ?(bad offset " << sub.sub_umbrella << ")\n";
4600 static void PrintSubLibraryCommand(MachO::sub_library_command sub,
4602 outs() << " cmd LC_SUB_LIBRARY\n";
4603 outs() << " cmdsize " << sub.cmdsize;
4604 if (sub.cmdsize < sizeof(struct MachO::sub_library_command))
4605 outs() << " Incorrect size\n";
4608 if (sub.sub_library < sub.cmdsize) {
4609 const char *P = Ptr + sub.sub_library;
4610 outs() << " sub_library " << P << " (offset " << sub.sub_library << ")\n";
4612 outs() << " sub_library ?(bad offset " << sub.sub_library << ")\n";
4616 static void PrintSubClientCommand(MachO::sub_client_command sub,
4618 outs() << " cmd LC_SUB_CLIENT\n";
4619 outs() << " cmdsize " << sub.cmdsize;
4620 if (sub.cmdsize < sizeof(struct MachO::sub_client_command))
4621 outs() << " Incorrect size\n";
4624 if (sub.client < sub.cmdsize) {
4625 const char *P = Ptr + sub.client;
4626 outs() << " client " << P << " (offset " << sub.client << ")\n";
4628 outs() << " client ?(bad offset " << sub.client << ")\n";
4632 static void PrintRoutinesCommand(MachO::routines_command r) {
4633 outs() << " cmd LC_ROUTINES\n";
4634 outs() << " cmdsize " << r.cmdsize;
4635 if (r.cmdsize != sizeof(struct MachO::routines_command))
4636 outs() << " Incorrect size\n";
4639 outs() << " init_address " << format("0x%08" PRIx32, r.init_address) << "\n";
4640 outs() << " init_module " << r.init_module << "\n";
4641 outs() << " reserved1 " << r.reserved1 << "\n";
4642 outs() << " reserved2 " << r.reserved2 << "\n";
4643 outs() << " reserved3 " << r.reserved3 << "\n";
4644 outs() << " reserved4 " << r.reserved4 << "\n";
4645 outs() << " reserved5 " << r.reserved5 << "\n";
4646 outs() << " reserved6 " << r.reserved6 << "\n";
4649 static void PrintRoutinesCommand64(MachO::routines_command_64 r) {
4650 outs() << " cmd LC_ROUTINES_64\n";
4651 outs() << " cmdsize " << r.cmdsize;
4652 if (r.cmdsize != sizeof(struct MachO::routines_command_64))
4653 outs() << " Incorrect size\n";
4656 outs() << " init_address " << format("0x%016" PRIx64, r.init_address) << "\n";
4657 outs() << " init_module " << r.init_module << "\n";
4658 outs() << " reserved1 " << r.reserved1 << "\n";
4659 outs() << " reserved2 " << r.reserved2 << "\n";
4660 outs() << " reserved3 " << r.reserved3 << "\n";
4661 outs() << " reserved4 " << r.reserved4 << "\n";
4662 outs() << " reserved5 " << r.reserved5 << "\n";
4663 outs() << " reserved6 " << r.reserved6 << "\n";
4666 static void Print_x86_thread_state64_t(MachO::x86_thread_state64_t &cpu64) {
4667 outs() << " rax " << format("0x%016" PRIx64, cpu64.rax);
4668 outs() << " rbx " << format("0x%016" PRIx64, cpu64.rbx);
4669 outs() << " rcx " << format("0x%016" PRIx64, cpu64.rcx) << "\n";
4670 outs() << " rdx " << format("0x%016" PRIx64, cpu64.rdx);
4671 outs() << " rdi " << format("0x%016" PRIx64, cpu64.rdi);
4672 outs() << " rsi " << format("0x%016" PRIx64, cpu64.rsi) << "\n";
4673 outs() << " rbp " << format("0x%016" PRIx64, cpu64.rbp);
4674 outs() << " rsp " << format("0x%016" PRIx64, cpu64.rsp);
4675 outs() << " r8 " << format("0x%016" PRIx64, cpu64.r8) << "\n";
4676 outs() << " r9 " << format("0x%016" PRIx64, cpu64.r9);
4677 outs() << " r10 " << format("0x%016" PRIx64, cpu64.r10);
4678 outs() << " r11 " << format("0x%016" PRIx64, cpu64.r11) << "\n";
4679 outs() << " r12 " << format("0x%016" PRIx64, cpu64.r12);
4680 outs() << " r13 " << format("0x%016" PRIx64, cpu64.r13);
4681 outs() << " r14 " << format("0x%016" PRIx64, cpu64.r14) << "\n";
4682 outs() << " r15 " << format("0x%016" PRIx64, cpu64.r15);
4683 outs() << " rip " << format("0x%016" PRIx64, cpu64.rip) << "\n";
4684 outs() << "rflags " << format("0x%016" PRIx64, cpu64.rflags);
4685 outs() << " cs " << format("0x%016" PRIx64, cpu64.cs);
4686 outs() << " fs " << format("0x%016" PRIx64, cpu64.fs) << "\n";
4687 outs() << " gs " << format("0x%016" PRIx64, cpu64.gs) << "\n";
4690 static void Print_mmst_reg(MachO::mmst_reg_t &r) {
4692 outs() << "\t mmst_reg ";
4693 for (f = 0; f < 10; f++)
4694 outs() << format("%02" PRIx32, (r.mmst_reg[f] & 0xff)) << " ";
4696 outs() << "\t mmst_rsrv ";
4697 for (f = 0; f < 6; f++)
4698 outs() << format("%02" PRIx32, (r.mmst_rsrv[f] & 0xff)) << " ";
4702 static void Print_xmm_reg(MachO::xmm_reg_t &r) {
4704 outs() << "\t xmm_reg ";
4705 for (f = 0; f < 16; f++)
4706 outs() << format("%02" PRIx32, (r.xmm_reg[f] & 0xff)) << " ";
4710 static void Print_x86_float_state_t(MachO::x86_float_state64_t &fpu) {
4711 outs() << "\t fpu_reserved[0] " << fpu.fpu_reserved[0];
4712 outs() << " fpu_reserved[1] " << fpu.fpu_reserved[1] << "\n";
4713 outs() << "\t control: invalid " << fpu.fpu_fcw.invalid;
4714 outs() << " denorm " << fpu.fpu_fcw.denorm;
4715 outs() << " zdiv " << fpu.fpu_fcw.zdiv;
4716 outs() << " ovrfl " << fpu.fpu_fcw.ovrfl;
4717 outs() << " undfl " << fpu.fpu_fcw.undfl;
4718 outs() << " precis " << fpu.fpu_fcw.precis << "\n";
4719 outs() << "\t\t pc ";
4720 if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_24B)
4721 outs() << "FP_PREC_24B ";
4722 else if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_53B)
4723 outs() << "FP_PREC_53B ";
4724 else if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_64B)
4725 outs() << "FP_PREC_64B ";
4727 outs() << fpu.fpu_fcw.pc << " ";
4729 if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_NEAR)
4730 outs() << "FP_RND_NEAR ";
4731 else if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_DOWN)
4732 outs() << "FP_RND_DOWN ";
4733 else if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_UP)
4734 outs() << "FP_RND_UP ";
4735 else if (fpu.fpu_fcw.rc == MachO::x86_FP_CHOP)
4736 outs() << "FP_CHOP ";
4738 outs() << "\t status: invalid " << fpu.fpu_fsw.invalid;
4739 outs() << " denorm " << fpu.fpu_fsw.denorm;
4740 outs() << " zdiv " << fpu.fpu_fsw.zdiv;
4741 outs() << " ovrfl " << fpu.fpu_fsw.ovrfl;
4742 outs() << " undfl " << fpu.fpu_fsw.undfl;
4743 outs() << " precis " << fpu.fpu_fsw.precis;
4744 outs() << " stkflt " << fpu.fpu_fsw.stkflt << "\n";
4745 outs() << "\t errsumm " << fpu.fpu_fsw.errsumm;
4746 outs() << " c0 " << fpu.fpu_fsw.c0;
4747 outs() << " c1 " << fpu.fpu_fsw.c1;
4748 outs() << " c2 " << fpu.fpu_fsw.c2;
4749 outs() << " tos " << fpu.fpu_fsw.tos;
4750 outs() << " c3 " << fpu.fpu_fsw.c3;
4751 outs() << " busy " << fpu.fpu_fsw.busy << "\n";
4752 outs() << "\t fpu_ftw " << format("0x%02" PRIx32, fpu.fpu_ftw);
4753 outs() << " fpu_rsrv1 " << format("0x%02" PRIx32, fpu.fpu_rsrv1);
4754 outs() << " fpu_fop " << format("0x%04" PRIx32, fpu.fpu_fop);
4755 outs() << " fpu_ip " << format("0x%08" PRIx32, fpu.fpu_ip) << "\n";
4756 outs() << "\t fpu_cs " << format("0x%04" PRIx32, fpu.fpu_cs);
4757 outs() << " fpu_rsrv2 " << format("0x%04" PRIx32, fpu.fpu_rsrv2);
4758 outs() << " fpu_dp " << format("0x%08" PRIx32, fpu.fpu_dp);
4759 outs() << " fpu_ds " << format("0x%04" PRIx32, fpu.fpu_ds) << "\n";
4760 outs() << "\t fpu_rsrv3 " << format("0x%04" PRIx32, fpu.fpu_rsrv3);
4761 outs() << " fpu_mxcsr " << format("0x%08" PRIx32, fpu.fpu_mxcsr);
4762 outs() << " fpu_mxcsrmask " << format("0x%08" PRIx32, fpu.fpu_mxcsrmask);
4764 outs() << "\t fpu_stmm0:\n";
4765 Print_mmst_reg(fpu.fpu_stmm0);
4766 outs() << "\t fpu_stmm1:\n";
4767 Print_mmst_reg(fpu.fpu_stmm1);
4768 outs() << "\t fpu_stmm2:\n";
4769 Print_mmst_reg(fpu.fpu_stmm2);
4770 outs() << "\t fpu_stmm3:\n";
4771 Print_mmst_reg(fpu.fpu_stmm3);
4772 outs() << "\t fpu_stmm4:\n";
4773 Print_mmst_reg(fpu.fpu_stmm4);
4774 outs() << "\t fpu_stmm5:\n";
4775 Print_mmst_reg(fpu.fpu_stmm5);
4776 outs() << "\t fpu_stmm6:\n";
4777 Print_mmst_reg(fpu.fpu_stmm6);
4778 outs() << "\t fpu_stmm7:\n";
4779 Print_mmst_reg(fpu.fpu_stmm7);
4780 outs() << "\t fpu_xmm0:\n";
4781 Print_xmm_reg(fpu.fpu_xmm0);
4782 outs() << "\t fpu_xmm1:\n";
4783 Print_xmm_reg(fpu.fpu_xmm1);
4784 outs() << "\t fpu_xmm2:\n";
4785 Print_xmm_reg(fpu.fpu_xmm2);
4786 outs() << "\t fpu_xmm3:\n";
4787 Print_xmm_reg(fpu.fpu_xmm3);
4788 outs() << "\t fpu_xmm4:\n";
4789 Print_xmm_reg(fpu.fpu_xmm4);
4790 outs() << "\t fpu_xmm5:\n";
4791 Print_xmm_reg(fpu.fpu_xmm5);
4792 outs() << "\t fpu_xmm6:\n";
4793 Print_xmm_reg(fpu.fpu_xmm6);
4794 outs() << "\t fpu_xmm7:\n";
4795 Print_xmm_reg(fpu.fpu_xmm7);
4796 outs() << "\t fpu_xmm8:\n";
4797 Print_xmm_reg(fpu.fpu_xmm8);
4798 outs() << "\t fpu_xmm9:\n";
4799 Print_xmm_reg(fpu.fpu_xmm9);
4800 outs() << "\t fpu_xmm10:\n";
4801 Print_xmm_reg(fpu.fpu_xmm10);
4802 outs() << "\t fpu_xmm11:\n";
4803 Print_xmm_reg(fpu.fpu_xmm11);
4804 outs() << "\t fpu_xmm12:\n";
4805 Print_xmm_reg(fpu.fpu_xmm12);
4806 outs() << "\t fpu_xmm13:\n";
4807 Print_xmm_reg(fpu.fpu_xmm13);
4808 outs() << "\t fpu_xmm14:\n";
4809 Print_xmm_reg(fpu.fpu_xmm14);
4810 outs() << "\t fpu_xmm15:\n";
4811 Print_xmm_reg(fpu.fpu_xmm15);
4812 outs() << "\t fpu_rsrv4:\n";
4813 for (uint32_t f = 0; f < 6; f++) {
4815 for (uint32_t g = 0; g < 16; g++)
4816 outs() << format("%02" PRIx32, fpu.fpu_rsrv4[f * g]) << " ";
4819 outs() << "\t fpu_reserved1 " << format("0x%08" PRIx32, fpu.fpu_reserved1);
4823 static void Print_x86_exception_state_t(MachO::x86_exception_state64_t &exc64) {
4824 outs() << "\t trapno " << format("0x%08" PRIx32, exc64.trapno);
4825 outs() << " err " << format("0x%08" PRIx32, exc64.err);
4826 outs() << " faultvaddr " << format("0x%016" PRIx64, exc64.faultvaddr) << "\n";
4829 static void PrintThreadCommand(MachO::thread_command t, const char *Ptr,
4830 bool isLittleEndian, uint32_t cputype) {
4831 if (t.cmd == MachO::LC_THREAD)
4832 outs() << " cmd LC_THREAD\n";
4833 else if (t.cmd == MachO::LC_UNIXTHREAD)
4834 outs() << " cmd LC_UNIXTHREAD\n";
4836 outs() << " cmd " << t.cmd << " (unknown)\n";
4837 outs() << " cmdsize " << t.cmdsize;
4838 if (t.cmdsize < sizeof(struct MachO::thread_command) + 2 * sizeof(uint32_t))
4839 outs() << " Incorrect size\n";
4843 const char *begin = Ptr + sizeof(struct MachO::thread_command);
4844 const char *end = Ptr + t.cmdsize;
4845 uint32_t flavor, count, left;
4846 if (cputype == MachO::CPU_TYPE_X86_64) {
4847 while (begin < end) {
4848 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
4849 memcpy((char *)&flavor, begin, sizeof(uint32_t));
4850 begin += sizeof(uint32_t);
4855 if (isLittleEndian != sys::IsLittleEndianHost)
4856 sys::swapByteOrder(flavor);
4857 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
4858 memcpy((char *)&count, begin, sizeof(uint32_t));
4859 begin += sizeof(uint32_t);
4864 if (isLittleEndian != sys::IsLittleEndianHost)
4865 sys::swapByteOrder(count);
4866 if (flavor == MachO::x86_THREAD_STATE64) {
4867 outs() << " flavor x86_THREAD_STATE64\n";
4868 if (count == MachO::x86_THREAD_STATE64_COUNT)
4869 outs() << " count x86_THREAD_STATE64_COUNT\n";
4871 outs() << " count " << count
4872 << " (not x86_THREAD_STATE64_COUNT)\n";
4873 MachO::x86_thread_state64_t cpu64;
4875 if (left >= sizeof(MachO::x86_thread_state64_t)) {
4876 memcpy(&cpu64, begin, sizeof(MachO::x86_thread_state64_t));
4877 begin += sizeof(MachO::x86_thread_state64_t);
4879 memset(&cpu64, '\0', sizeof(MachO::x86_thread_state64_t));
4880 memcpy(&cpu64, begin, left);
4883 if (isLittleEndian != sys::IsLittleEndianHost)
4885 Print_x86_thread_state64_t(cpu64);
4886 } else if (flavor == MachO::x86_THREAD_STATE) {
4887 outs() << " flavor x86_THREAD_STATE\n";
4888 if (count == MachO::x86_THREAD_STATE_COUNT)
4889 outs() << " count x86_THREAD_STATE_COUNT\n";
4891 outs() << " count " << count
4892 << " (not x86_THREAD_STATE_COUNT)\n";
4893 struct MachO::x86_thread_state_t ts;
4895 if (left >= sizeof(MachO::x86_thread_state_t)) {
4896 memcpy(&ts, begin, sizeof(MachO::x86_thread_state_t));
4897 begin += sizeof(MachO::x86_thread_state_t);
4899 memset(&ts, '\0', sizeof(MachO::x86_thread_state_t));
4900 memcpy(&ts, begin, left);
4903 if (isLittleEndian != sys::IsLittleEndianHost)
4905 if (ts.tsh.flavor == MachO::x86_THREAD_STATE64) {
4906 outs() << "\t tsh.flavor x86_THREAD_STATE64 ";
4907 if (ts.tsh.count == MachO::x86_THREAD_STATE64_COUNT)
4908 outs() << "tsh.count x86_THREAD_STATE64_COUNT\n";
4910 outs() << "tsh.count " << ts.tsh.count
4911 << " (not x86_THREAD_STATE64_COUNT\n";
4912 Print_x86_thread_state64_t(ts.uts.ts64);
4914 outs() << "\t tsh.flavor " << ts.tsh.flavor << " tsh.count "
4915 << ts.tsh.count << "\n";
4917 } else if (flavor == MachO::x86_FLOAT_STATE) {
4918 outs() << " flavor x86_FLOAT_STATE\n";
4919 if (count == MachO::x86_FLOAT_STATE_COUNT)
4920 outs() << " count x86_FLOAT_STATE_COUNT\n";
4922 outs() << " count " << count << " (not x86_FLOAT_STATE_COUNT)\n";
4923 struct MachO::x86_float_state_t fs;
4925 if (left >= sizeof(MachO::x86_float_state_t)) {
4926 memcpy(&fs, begin, sizeof(MachO::x86_float_state_t));
4927 begin += sizeof(MachO::x86_float_state_t);
4929 memset(&fs, '\0', sizeof(MachO::x86_float_state_t));
4930 memcpy(&fs, begin, left);
4933 if (isLittleEndian != sys::IsLittleEndianHost)
4935 if (fs.fsh.flavor == MachO::x86_FLOAT_STATE64) {
4936 outs() << "\t fsh.flavor x86_FLOAT_STATE64 ";
4937 if (fs.fsh.count == MachO::x86_FLOAT_STATE64_COUNT)
4938 outs() << "fsh.count x86_FLOAT_STATE64_COUNT\n";
4940 outs() << "fsh.count " << fs.fsh.count
4941 << " (not x86_FLOAT_STATE64_COUNT\n";
4942 Print_x86_float_state_t(fs.ufs.fs64);
4944 outs() << "\t fsh.flavor " << fs.fsh.flavor << " fsh.count "
4945 << fs.fsh.count << "\n";
4947 } else if (flavor == MachO::x86_EXCEPTION_STATE) {
4948 outs() << " flavor x86_EXCEPTION_STATE\n";
4949 if (count == MachO::x86_EXCEPTION_STATE_COUNT)
4950 outs() << " count x86_EXCEPTION_STATE_COUNT\n";
4952 outs() << " count " << count
4953 << " (not x86_EXCEPTION_STATE_COUNT)\n";
4954 struct MachO::x86_exception_state_t es;
4956 if (left >= sizeof(MachO::x86_exception_state_t)) {
4957 memcpy(&es, begin, sizeof(MachO::x86_exception_state_t));
4958 begin += sizeof(MachO::x86_exception_state_t);
4960 memset(&es, '\0', sizeof(MachO::x86_exception_state_t));
4961 memcpy(&es, begin, left);
4964 if (isLittleEndian != sys::IsLittleEndianHost)
4966 if (es.esh.flavor == MachO::x86_EXCEPTION_STATE64) {
4967 outs() << "\t esh.flavor x86_EXCEPTION_STATE64\n";
4968 if (es.esh.count == MachO::x86_EXCEPTION_STATE64_COUNT)
4969 outs() << "\t esh.count x86_EXCEPTION_STATE64_COUNT\n";
4971 outs() << "\t esh.count " << es.esh.count
4972 << " (not x86_EXCEPTION_STATE64_COUNT\n";
4973 Print_x86_exception_state_t(es.ues.es64);
4975 outs() << "\t esh.flavor " << es.esh.flavor << " esh.count "
4976 << es.esh.count << "\n";
4979 outs() << " flavor " << flavor << " (unknown)\n";
4980 outs() << " count " << count << "\n";
4981 outs() << " state (unknown)\n";
4982 begin += count * sizeof(uint32_t);
4986 while (begin < end) {
4987 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
4988 memcpy((char *)&flavor, begin, sizeof(uint32_t));
4989 begin += sizeof(uint32_t);
4994 if (isLittleEndian != sys::IsLittleEndianHost)
4995 sys::swapByteOrder(flavor);
4996 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
4997 memcpy((char *)&count, begin, sizeof(uint32_t));
4998 begin += sizeof(uint32_t);
5003 if (isLittleEndian != sys::IsLittleEndianHost)
5004 sys::swapByteOrder(count);
5005 outs() << " flavor " << flavor << "\n";
5006 outs() << " count " << count << "\n";
5007 outs() << " state (Unknown cputype/cpusubtype)\n";
5008 begin += count * sizeof(uint32_t);
5013 static void PrintDylibCommand(MachO::dylib_command dl, const char *Ptr) {
5014 if (dl.cmd == MachO::LC_ID_DYLIB)
5015 outs() << " cmd LC_ID_DYLIB\n";
5016 else if (dl.cmd == MachO::LC_LOAD_DYLIB)
5017 outs() << " cmd LC_LOAD_DYLIB\n";
5018 else if (dl.cmd == MachO::LC_LOAD_WEAK_DYLIB)
5019 outs() << " cmd LC_LOAD_WEAK_DYLIB\n";
5020 else if (dl.cmd == MachO::LC_REEXPORT_DYLIB)
5021 outs() << " cmd LC_REEXPORT_DYLIB\n";
5022 else if (dl.cmd == MachO::LC_LAZY_LOAD_DYLIB)
5023 outs() << " cmd LC_LAZY_LOAD_DYLIB\n";
5024 else if (dl.cmd == MachO::LC_LOAD_UPWARD_DYLIB)
5025 outs() << " cmd LC_LOAD_UPWARD_DYLIB\n";
5027 outs() << " cmd " << dl.cmd << " (unknown)\n";
5028 outs() << " cmdsize " << dl.cmdsize;
5029 if (dl.cmdsize < sizeof(struct MachO::dylib_command))
5030 outs() << " Incorrect size\n";
5033 if (dl.dylib.name < dl.cmdsize) {
5034 const char *P = (const char *)(Ptr) + dl.dylib.name;
5035 outs() << " name " << P << " (offset " << dl.dylib.name << ")\n";
5037 outs() << " name ?(bad offset " << dl.dylib.name << ")\n";
5039 outs() << " time stamp " << dl.dylib.timestamp << " ";
5040 time_t t = dl.dylib.timestamp;
5041 outs() << ctime(&t);
5042 outs() << " current version ";
5043 if (dl.dylib.current_version == 0xffffffff)
5046 outs() << ((dl.dylib.current_version >> 16) & 0xffff) << "."
5047 << ((dl.dylib.current_version >> 8) & 0xff) << "."
5048 << (dl.dylib.current_version & 0xff) << "\n";
5049 outs() << "compatibility version ";
5050 if (dl.dylib.compatibility_version == 0xffffffff)
5053 outs() << ((dl.dylib.compatibility_version >> 16) & 0xffff) << "."
5054 << ((dl.dylib.compatibility_version >> 8) & 0xff) << "."
5055 << (dl.dylib.compatibility_version & 0xff) << "\n";
5058 static void PrintLinkEditDataCommand(MachO::linkedit_data_command ld,
5059 uint32_t object_size) {
5060 if (ld.cmd == MachO::LC_CODE_SIGNATURE)
5061 outs() << " cmd LC_FUNCTION_STARTS\n";
5062 else if (ld.cmd == MachO::LC_SEGMENT_SPLIT_INFO)
5063 outs() << " cmd LC_SEGMENT_SPLIT_INFO\n";
5064 else if (ld.cmd == MachO::LC_FUNCTION_STARTS)
5065 outs() << " cmd LC_FUNCTION_STARTS\n";
5066 else if (ld.cmd == MachO::LC_DATA_IN_CODE)
5067 outs() << " cmd LC_DATA_IN_CODE\n";
5068 else if (ld.cmd == MachO::LC_DYLIB_CODE_SIGN_DRS)
5069 outs() << " cmd LC_DYLIB_CODE_SIGN_DRS\n";
5070 else if (ld.cmd == MachO::LC_LINKER_OPTIMIZATION_HINT)
5071 outs() << " cmd LC_LINKER_OPTIMIZATION_HINT\n";
5073 outs() << " cmd " << ld.cmd << " (?)\n";
5074 outs() << " cmdsize " << ld.cmdsize;
5075 if (ld.cmdsize != sizeof(struct MachO::linkedit_data_command))
5076 outs() << " Incorrect size\n";
5079 outs() << " dataoff " << ld.dataoff;
5080 if (ld.dataoff > object_size)
5081 outs() << " (past end of file)\n";
5084 outs() << " datasize " << ld.datasize;
5085 uint64_t big_size = ld.dataoff;
5086 big_size += ld.datasize;
5087 if (big_size > object_size)
5088 outs() << " (past end of file)\n";
5093 static void PrintLoadCommands(const MachOObjectFile *Obj, uint32_t ncmds,
5094 uint32_t filetype, uint32_t cputype,
5098 StringRef Buf = Obj->getData();
5099 MachOObjectFile::LoadCommandInfo Command = Obj->getFirstLoadCommandInfo();
5100 for (unsigned i = 0;; ++i) {
5101 outs() << "Load command " << i << "\n";
5102 if (Command.C.cmd == MachO::LC_SEGMENT) {
5103 MachO::segment_command SLC = Obj->getSegmentLoadCommand(Command);
5104 const char *sg_segname = SLC.segname;
5105 PrintSegmentCommand(SLC.cmd, SLC.cmdsize, SLC.segname, SLC.vmaddr,
5106 SLC.vmsize, SLC.fileoff, SLC.filesize, SLC.maxprot,
5107 SLC.initprot, SLC.nsects, SLC.flags, Buf.size(),
5109 for (unsigned j = 0; j < SLC.nsects; j++) {
5110 MachO::section S = Obj->getSection(Command, j);
5111 PrintSection(S.sectname, S.segname, S.addr, S.size, S.offset, S.align,
5112 S.reloff, S.nreloc, S.flags, S.reserved1, S.reserved2,
5113 SLC.cmd, sg_segname, filetype, Buf.size(), verbose);
5115 } else if (Command.C.cmd == MachO::LC_SEGMENT_64) {
5116 MachO::segment_command_64 SLC_64 = Obj->getSegment64LoadCommand(Command);
5117 const char *sg_segname = SLC_64.segname;
5118 PrintSegmentCommand(SLC_64.cmd, SLC_64.cmdsize, SLC_64.segname,
5119 SLC_64.vmaddr, SLC_64.vmsize, SLC_64.fileoff,
5120 SLC_64.filesize, SLC_64.maxprot, SLC_64.initprot,
5121 SLC_64.nsects, SLC_64.flags, Buf.size(), verbose);
5122 for (unsigned j = 0; j < SLC_64.nsects; j++) {
5123 MachO::section_64 S_64 = Obj->getSection64(Command, j);
5124 PrintSection(S_64.sectname, S_64.segname, S_64.addr, S_64.size,
5125 S_64.offset, S_64.align, S_64.reloff, S_64.nreloc,
5126 S_64.flags, S_64.reserved1, S_64.reserved2, SLC_64.cmd,
5127 sg_segname, filetype, Buf.size(), verbose);
5129 } else if (Command.C.cmd == MachO::LC_SYMTAB) {
5130 MachO::symtab_command Symtab = Obj->getSymtabLoadCommand();
5131 PrintSymtabLoadCommand(Symtab, Obj->is64Bit(), Buf.size());
5132 } else if (Command.C.cmd == MachO::LC_DYSYMTAB) {
5133 MachO::dysymtab_command Dysymtab = Obj->getDysymtabLoadCommand();
5134 MachO::symtab_command Symtab = Obj->getSymtabLoadCommand();
5135 PrintDysymtabLoadCommand(Dysymtab, Symtab.nsyms, Buf.size(),
5137 } else if (Command.C.cmd == MachO::LC_DYLD_INFO ||
5138 Command.C.cmd == MachO::LC_DYLD_INFO_ONLY) {
5139 MachO::dyld_info_command DyldInfo = Obj->getDyldInfoLoadCommand(Command);
5140 PrintDyldInfoLoadCommand(DyldInfo, Buf.size());
5141 } else if (Command.C.cmd == MachO::LC_LOAD_DYLINKER ||
5142 Command.C.cmd == MachO::LC_ID_DYLINKER ||
5143 Command.C.cmd == MachO::LC_DYLD_ENVIRONMENT) {
5144 MachO::dylinker_command Dyld = Obj->getDylinkerCommand(Command);
5145 PrintDyldLoadCommand(Dyld, Command.Ptr);
5146 } else if (Command.C.cmd == MachO::LC_UUID) {
5147 MachO::uuid_command Uuid = Obj->getUuidCommand(Command);
5148 PrintUuidLoadCommand(Uuid);
5149 } else if (Command.C.cmd == MachO::LC_RPATH) {
5150 MachO::rpath_command Rpath = Obj->getRpathCommand(Command);
5151 PrintRpathLoadCommand(Rpath, Command.Ptr);
5152 } else if (Command.C.cmd == MachO::LC_VERSION_MIN_MACOSX ||
5153 Command.C.cmd == MachO::LC_VERSION_MIN_IPHONEOS) {
5154 MachO::version_min_command Vd = Obj->getVersionMinLoadCommand(Command);
5155 PrintVersionMinLoadCommand(Vd);
5156 } else if (Command.C.cmd == MachO::LC_SOURCE_VERSION) {
5157 MachO::source_version_command Sd = Obj->getSourceVersionCommand(Command);
5158 PrintSourceVersionCommand(Sd);
5159 } else if (Command.C.cmd == MachO::LC_MAIN) {
5160 MachO::entry_point_command Ep = Obj->getEntryPointCommand(Command);
5161 PrintEntryPointCommand(Ep);
5162 } else if (Command.C.cmd == MachO::LC_ENCRYPTION_INFO) {
5163 MachO::encryption_info_command Ei =
5164 Obj->getEncryptionInfoCommand(Command);
5165 PrintEncryptionInfoCommand(Ei, Buf.size());
5166 } else if (Command.C.cmd == MachO::LC_ENCRYPTION_INFO_64) {
5167 MachO::encryption_info_command_64 Ei =
5168 Obj->getEncryptionInfoCommand64(Command);
5169 PrintEncryptionInfoCommand64(Ei, Buf.size());
5170 } else if (Command.C.cmd == MachO::LC_LINKER_OPTION) {
5171 MachO::linker_option_command Lo =
5172 Obj->getLinkerOptionLoadCommand(Command);
5173 PrintLinkerOptionCommand(Lo, Command.Ptr);
5174 } else if (Command.C.cmd == MachO::LC_SUB_FRAMEWORK) {
5175 MachO::sub_framework_command Sf = Obj->getSubFrameworkCommand(Command);
5176 PrintSubFrameworkCommand(Sf, Command.Ptr);
5177 } else if (Command.C.cmd == MachO::LC_SUB_UMBRELLA) {
5178 MachO::sub_umbrella_command Sf = Obj->getSubUmbrellaCommand(Command);
5179 PrintSubUmbrellaCommand(Sf, Command.Ptr);
5180 } else if (Command.C.cmd == MachO::LC_SUB_LIBRARY) {
5181 MachO::sub_library_command Sl = Obj->getSubLibraryCommand(Command);
5182 PrintSubLibraryCommand(Sl, Command.Ptr);
5183 } else if (Command.C.cmd == MachO::LC_SUB_CLIENT) {
5184 MachO::sub_client_command Sc = Obj->getSubClientCommand(Command);
5185 PrintSubClientCommand(Sc, Command.Ptr);
5186 } else if (Command.C.cmd == MachO::LC_ROUTINES) {
5187 MachO::routines_command Rc = Obj->getRoutinesCommand(Command);
5188 PrintRoutinesCommand(Rc);
5189 } else if (Command.C.cmd == MachO::LC_ROUTINES_64) {
5190 MachO::routines_command_64 Rc = Obj->getRoutinesCommand64(Command);
5191 PrintRoutinesCommand64(Rc);
5192 } else if (Command.C.cmd == MachO::LC_THREAD ||
5193 Command.C.cmd == MachO::LC_UNIXTHREAD) {
5194 MachO::thread_command Tc = Obj->getThreadCommand(Command);
5195 PrintThreadCommand(Tc, Command.Ptr, Obj->isLittleEndian(), cputype);
5196 } else if (Command.C.cmd == MachO::LC_LOAD_DYLIB ||
5197 Command.C.cmd == MachO::LC_ID_DYLIB ||
5198 Command.C.cmd == MachO::LC_LOAD_WEAK_DYLIB ||
5199 Command.C.cmd == MachO::LC_REEXPORT_DYLIB ||
5200 Command.C.cmd == MachO::LC_LAZY_LOAD_DYLIB ||
5201 Command.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB) {
5202 MachO::dylib_command Dl = Obj->getDylibIDLoadCommand(Command);
5203 PrintDylibCommand(Dl, Command.Ptr);
5204 } else if (Command.C.cmd == MachO::LC_CODE_SIGNATURE ||
5205 Command.C.cmd == MachO::LC_SEGMENT_SPLIT_INFO ||
5206 Command.C.cmd == MachO::LC_FUNCTION_STARTS ||
5207 Command.C.cmd == MachO::LC_DATA_IN_CODE ||
5208 Command.C.cmd == MachO::LC_DYLIB_CODE_SIGN_DRS ||
5209 Command.C.cmd == MachO::LC_LINKER_OPTIMIZATION_HINT) {
5210 MachO::linkedit_data_command Ld =
5211 Obj->getLinkeditDataLoadCommand(Command);
5212 PrintLinkEditDataCommand(Ld, Buf.size());
5214 outs() << " cmd ?(" << format("0x%08" PRIx32, Command.C.cmd)
5216 outs() << " cmdsize " << Command.C.cmdsize << "\n";
5217 // TODO: get and print the raw bytes of the load command.
5219 // TODO: print all the other kinds of load commands.
5223 Command = Obj->getNextLoadCommandInfo(Command);
5227 static void getAndPrintMachHeader(const MachOObjectFile *Obj, uint32_t &ncmds,
5228 uint32_t &filetype, uint32_t &cputype,
5230 if (Obj->is64Bit()) {
5231 MachO::mach_header_64 H_64;
5232 H_64 = Obj->getHeader64();
5233 PrintMachHeader(H_64.magic, H_64.cputype, H_64.cpusubtype, H_64.filetype,
5234 H_64.ncmds, H_64.sizeofcmds, H_64.flags, verbose);
5236 filetype = H_64.filetype;
5237 cputype = H_64.cputype;
5239 MachO::mach_header H;
5240 H = Obj->getHeader();
5241 PrintMachHeader(H.magic, H.cputype, H.cpusubtype, H.filetype, H.ncmds,
5242 H.sizeofcmds, H.flags, verbose);
5244 filetype = H.filetype;
5245 cputype = H.cputype;
5249 void llvm::printMachOFileHeader(const object::ObjectFile *Obj) {
5250 const MachOObjectFile *file = dyn_cast<const MachOObjectFile>(Obj);
5252 uint32_t filetype = 0;
5253 uint32_t cputype = 0;
5254 getAndPrintMachHeader(file, ncmds, filetype, cputype, true);
5255 PrintLoadCommands(file, ncmds, filetype, cputype, true);
5258 //===----------------------------------------------------------------------===//
5259 // export trie dumping
5260 //===----------------------------------------------------------------------===//
5262 void llvm::printMachOExportsTrie(const object::MachOObjectFile *Obj) {
5263 for (const llvm::object::ExportEntry &Entry : Obj->exports()) {
5264 uint64_t Flags = Entry.flags();
5265 bool ReExport = (Flags & MachO::EXPORT_SYMBOL_FLAGS_REEXPORT);
5266 bool WeakDef = (Flags & MachO::EXPORT_SYMBOL_FLAGS_WEAK_DEFINITION);
5267 bool ThreadLocal = ((Flags & MachO::EXPORT_SYMBOL_FLAGS_KIND_MASK) ==
5268 MachO::EXPORT_SYMBOL_FLAGS_KIND_THREAD_LOCAL);
5269 bool Abs = ((Flags & MachO::EXPORT_SYMBOL_FLAGS_KIND_MASK) ==
5270 MachO::EXPORT_SYMBOL_FLAGS_KIND_ABSOLUTE);
5271 bool Resolver = (Flags & MachO::EXPORT_SYMBOL_FLAGS_STUB_AND_RESOLVER);
5273 outs() << "[re-export] ";
5275 outs() << format("0x%08llX ",
5276 Entry.address()); // FIXME:add in base address
5277 outs() << Entry.name();
5278 if (WeakDef || ThreadLocal || Resolver || Abs) {
5279 bool NeedsComma = false;
5282 outs() << "weak_def";
5288 outs() << "per-thread";
5294 outs() << "absolute";
5300 outs() << format("resolver=0x%08llX", Entry.other());
5306 StringRef DylibName = "unknown";
5307 int Ordinal = Entry.other() - 1;
5308 Obj->getLibraryShortNameByIndex(Ordinal, DylibName);
5309 if (Entry.otherName().empty())
5310 outs() << " (from " << DylibName << ")";
5312 outs() << " (" << Entry.otherName() << " from " << DylibName << ")";
5318 //===----------------------------------------------------------------------===//
5319 // rebase table dumping
5320 //===----------------------------------------------------------------------===//
5325 SegInfo(const object::MachOObjectFile *Obj);
5327 StringRef segmentName(uint32_t SegIndex);
5328 StringRef sectionName(uint32_t SegIndex, uint64_t SegOffset);
5329 uint64_t address(uint32_t SegIndex, uint64_t SegOffset);
5332 struct SectionInfo {
5335 StringRef SectionName;
5336 StringRef SegmentName;
5337 uint64_t OffsetInSegment;
5338 uint64_t SegmentStartAddress;
5339 uint32_t SegmentIndex;
5341 const SectionInfo &findSection(uint32_t SegIndex, uint64_t SegOffset);
5342 SmallVector<SectionInfo, 32> Sections;
5346 SegInfo::SegInfo(const object::MachOObjectFile *Obj) {
5347 // Build table of sections so segIndex/offset pairs can be translated.
5348 uint32_t CurSegIndex = Obj->hasPageZeroSegment() ? 1 : 0;
5349 StringRef CurSegName;
5350 uint64_t CurSegAddress;
5351 for (const SectionRef &Section : Obj->sections()) {
5353 if (error(Section.getName(Info.SectionName)))
5355 Info.Address = Section.getAddress();
5356 Info.Size = Section.getSize();
5358 Obj->getSectionFinalSegmentName(Section.getRawDataRefImpl());
5359 if (!Info.SegmentName.equals(CurSegName)) {
5361 CurSegName = Info.SegmentName;
5362 CurSegAddress = Info.Address;
5364 Info.SegmentIndex = CurSegIndex - 1;
5365 Info.OffsetInSegment = Info.Address - CurSegAddress;
5366 Info.SegmentStartAddress = CurSegAddress;
5367 Sections.push_back(Info);
5371 StringRef SegInfo::segmentName(uint32_t SegIndex) {
5372 for (const SectionInfo &SI : Sections) {
5373 if (SI.SegmentIndex == SegIndex)
5374 return SI.SegmentName;
5376 llvm_unreachable("invalid segIndex");
5379 const SegInfo::SectionInfo &SegInfo::findSection(uint32_t SegIndex,
5380 uint64_t OffsetInSeg) {
5381 for (const SectionInfo &SI : Sections) {
5382 if (SI.SegmentIndex != SegIndex)
5384 if (SI.OffsetInSegment > OffsetInSeg)
5386 if (OffsetInSeg >= (SI.OffsetInSegment + SI.Size))
5390 llvm_unreachable("segIndex and offset not in any section");
5393 StringRef SegInfo::sectionName(uint32_t SegIndex, uint64_t OffsetInSeg) {
5394 return findSection(SegIndex, OffsetInSeg).SectionName;
5397 uint64_t SegInfo::address(uint32_t SegIndex, uint64_t OffsetInSeg) {
5398 const SectionInfo &SI = findSection(SegIndex, OffsetInSeg);
5399 return SI.SegmentStartAddress + OffsetInSeg;
5402 void llvm::printMachORebaseTable(const object::MachOObjectFile *Obj) {
5403 // Build table of sections so names can used in final output.
5404 SegInfo sectionTable(Obj);
5406 outs() << "segment section address type\n";
5407 for (const llvm::object::MachORebaseEntry &Entry : Obj->rebaseTable()) {
5408 uint32_t SegIndex = Entry.segmentIndex();
5409 uint64_t OffsetInSeg = Entry.segmentOffset();
5410 StringRef SegmentName = sectionTable.segmentName(SegIndex);
5411 StringRef SectionName = sectionTable.sectionName(SegIndex, OffsetInSeg);
5412 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
5414 // Table lines look like: __DATA __nl_symbol_ptr 0x0000F00C pointer
5415 outs() << format("%-8s %-18s 0x%08" PRIX64 " %s\n",
5416 SegmentName.str().c_str(), SectionName.str().c_str(),
5417 Address, Entry.typeName().str().c_str());
5421 static StringRef ordinalName(const object::MachOObjectFile *Obj, int Ordinal) {
5422 StringRef DylibName;
5424 case MachO::BIND_SPECIAL_DYLIB_SELF:
5425 return "this-image";
5426 case MachO::BIND_SPECIAL_DYLIB_MAIN_EXECUTABLE:
5427 return "main-executable";
5428 case MachO::BIND_SPECIAL_DYLIB_FLAT_LOOKUP:
5429 return "flat-namespace";
5432 std::error_code EC =
5433 Obj->getLibraryShortNameByIndex(Ordinal - 1, DylibName);
5435 return "<<bad library ordinal>>";
5439 return "<<unknown special ordinal>>";
5442 //===----------------------------------------------------------------------===//
5443 // bind table dumping
5444 //===----------------------------------------------------------------------===//
5446 void llvm::printMachOBindTable(const object::MachOObjectFile *Obj) {
5447 // Build table of sections so names can used in final output.
5448 SegInfo sectionTable(Obj);
5450 outs() << "segment section address type "
5451 "addend dylib symbol\n";
5452 for (const llvm::object::MachOBindEntry &Entry : Obj->bindTable()) {
5453 uint32_t SegIndex = Entry.segmentIndex();
5454 uint64_t OffsetInSeg = Entry.segmentOffset();
5455 StringRef SegmentName = sectionTable.segmentName(SegIndex);
5456 StringRef SectionName = sectionTable.sectionName(SegIndex, OffsetInSeg);
5457 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
5459 // Table lines look like:
5460 // __DATA __got 0x00012010 pointer 0 libSystem ___stack_chk_guard
5462 if (Entry.flags() & MachO::BIND_SYMBOL_FLAGS_WEAK_IMPORT)
5463 Attr = " (weak_import)";
5464 outs() << left_justify(SegmentName, 8) << " "
5465 << left_justify(SectionName, 18) << " "
5466 << format_hex(Address, 10, true) << " "
5467 << left_justify(Entry.typeName(), 8) << " "
5468 << format_decimal(Entry.addend(), 8) << " "
5469 << left_justify(ordinalName(Obj, Entry.ordinal()), 16) << " "
5470 << Entry.symbolName() << Attr << "\n";
5474 //===----------------------------------------------------------------------===//
5475 // lazy bind table dumping
5476 //===----------------------------------------------------------------------===//
5478 void llvm::printMachOLazyBindTable(const object::MachOObjectFile *Obj) {
5479 // Build table of sections so names can used in final output.
5480 SegInfo sectionTable(Obj);
5482 outs() << "segment section address "
5484 for (const llvm::object::MachOBindEntry &Entry : Obj->lazyBindTable()) {
5485 uint32_t SegIndex = Entry.segmentIndex();
5486 uint64_t OffsetInSeg = Entry.segmentOffset();
5487 StringRef SegmentName = sectionTable.segmentName(SegIndex);
5488 StringRef SectionName = sectionTable.sectionName(SegIndex, OffsetInSeg);
5489 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
5491 // Table lines look like:
5492 // __DATA __got 0x00012010 libSystem ___stack_chk_guard
5493 outs() << left_justify(SegmentName, 8) << " "
5494 << left_justify(SectionName, 18) << " "
5495 << format_hex(Address, 10, true) << " "
5496 << left_justify(ordinalName(Obj, Entry.ordinal()), 16) << " "
5497 << Entry.symbolName() << "\n";
5501 //===----------------------------------------------------------------------===//
5502 // weak bind table dumping
5503 //===----------------------------------------------------------------------===//
5505 void llvm::printMachOWeakBindTable(const object::MachOObjectFile *Obj) {
5506 // Build table of sections so names can used in final output.
5507 SegInfo sectionTable(Obj);
5509 outs() << "segment section address "
5510 "type addend symbol\n";
5511 for (const llvm::object::MachOBindEntry &Entry : Obj->weakBindTable()) {
5512 // Strong symbols don't have a location to update.
5513 if (Entry.flags() & MachO::BIND_SYMBOL_FLAGS_NON_WEAK_DEFINITION) {
5514 outs() << " strong "
5515 << Entry.symbolName() << "\n";
5518 uint32_t SegIndex = Entry.segmentIndex();
5519 uint64_t OffsetInSeg = Entry.segmentOffset();
5520 StringRef SegmentName = sectionTable.segmentName(SegIndex);
5521 StringRef SectionName = sectionTable.sectionName(SegIndex, OffsetInSeg);
5522 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
5524 // Table lines look like:
5525 // __DATA __data 0x00001000 pointer 0 _foo
5526 outs() << left_justify(SegmentName, 8) << " "
5527 << left_justify(SectionName, 18) << " "
5528 << format_hex(Address, 10, true) << " "
5529 << left_justify(Entry.typeName(), 8) << " "
5530 << format_decimal(Entry.addend(), 8) << " " << Entry.symbolName()
5535 // get_dyld_bind_info_symbolname() is used for disassembly and passed an
5536 // address, ReferenceValue, in the Mach-O file and looks in the dyld bind
5537 // information for that address. If the address is found its binding symbol
5538 // name is returned. If not nullptr is returned.
5539 static const char *get_dyld_bind_info_symbolname(uint64_t ReferenceValue,
5540 struct DisassembleInfo *info) {
5541 if (info->bindtable == nullptr) {
5542 info->bindtable = new (BindTable);
5543 SegInfo sectionTable(info->O);
5544 for (const llvm::object::MachOBindEntry &Entry : info->O->bindTable()) {
5545 uint32_t SegIndex = Entry.segmentIndex();
5546 uint64_t OffsetInSeg = Entry.segmentOffset();
5547 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
5548 const char *SymbolName = nullptr;
5549 StringRef name = Entry.symbolName();
5551 SymbolName = name.data();
5552 info->bindtable->push_back(std::make_pair(Address, SymbolName));
5555 for (bind_table_iterator BI = info->bindtable->begin(),
5556 BE = info->bindtable->end();
5558 uint64_t Address = BI->first;
5559 if (ReferenceValue == Address) {
5560 const char *SymbolName = BI->second;