1 //===-- MachODump.cpp - Object file dumping utility for llvm --------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the MachO-specific dumper for llvm-objdump.
12 //===----------------------------------------------------------------------===//
14 #include "llvm-objdump.h"
15 #include "llvm-c/Disassembler.h"
16 #include "llvm/ADT/STLExtras.h"
17 #include "llvm/ADT/StringExtras.h"
18 #include "llvm/ADT/Triple.h"
19 #include "llvm/Config/config.h"
20 #include "llvm/DebugInfo/DWARF/DIContext.h"
21 #include "llvm/MC/MCAsmInfo.h"
22 #include "llvm/MC/MCContext.h"
23 #include "llvm/MC/MCDisassembler.h"
24 #include "llvm/MC/MCInst.h"
25 #include "llvm/MC/MCInstPrinter.h"
26 #include "llvm/MC/MCInstrDesc.h"
27 #include "llvm/MC/MCInstrInfo.h"
28 #include "llvm/MC/MCRegisterInfo.h"
29 #include "llvm/MC/MCSubtargetInfo.h"
30 #include "llvm/Object/MachO.h"
31 #include "llvm/Object/MachOUniversal.h"
32 #include "llvm/Support/Casting.h"
33 #include "llvm/Support/CommandLine.h"
34 #include "llvm/Support/Debug.h"
35 #include "llvm/Support/Endian.h"
36 #include "llvm/Support/Format.h"
37 #include "llvm/Support/FormattedStream.h"
38 #include "llvm/Support/GraphWriter.h"
39 #include "llvm/Support/LEB128.h"
40 #include "llvm/Support/MachO.h"
41 #include "llvm/Support/MemoryBuffer.h"
42 #include "llvm/Support/TargetRegistry.h"
43 #include "llvm/Support/TargetSelect.h"
44 #include "llvm/Support/raw_ostream.h"
47 #include <system_error>
54 using namespace object;
58 cl::desc("Print line information from debug info if available"));
60 static cl::opt<std::string> DSYMFile("dsym",
61 cl::desc("Use .dSYM file for debug info"));
63 static cl::opt<bool> FullLeadingAddr("full-leading-addr",
64 cl::desc("Print full leading address"));
66 static cl::opt<bool> NoLeadingAddr("no-leading-addr",
67 cl::desc("Print no leading address"));
70 PrintImmHex("print-imm-hex",
71 cl::desc("Use hex format for immediate values"));
73 cl::opt<bool> llvm::UniversalHeaders("universal-headers",
74 cl::desc("Print Mach-O universal headers "
75 "(requires -macho)"));
78 llvm::ArchiveHeaders("archive-headers",
79 cl::desc("Print archive headers for Mach-O archives "
80 "(requires -macho)"));
83 llvm::IndirectSymbols("indirect-symbols",
84 cl::desc("Print indirect symbol table for Mach-O "
85 "objects (requires -macho)"));
88 llvm::DataInCode("data-in-code",
89 cl::desc("Print the data in code table for Mach-O objects "
90 "(requires -macho)"));
93 llvm::LinkOptHints("link-opt-hints",
94 cl::desc("Print the linker optimization hints for "
95 "Mach-O objects (requires -macho)"));
98 llvm::DumpSections("section",
99 cl::desc("Prints the specified segment,section for "
100 "Mach-O objects (requires -macho)"));
102 cl::opt<bool> llvm::Raw("raw",
103 cl::desc("Have -section dump the raw binary contents"));
106 llvm::InfoPlist("info-plist",
107 cl::desc("Print the info plist section as strings for "
108 "Mach-O objects (requires -macho)"));
111 llvm::DylibsUsed("dylibs-used",
112 cl::desc("Print the shared libraries used for linked "
113 "Mach-O files (requires -macho)"));
116 llvm::DylibId("dylib-id",
117 cl::desc("Print the shared library's id for the dylib Mach-O "
118 "file (requires -macho)"));
121 llvm::NonVerbose("non-verbose",
122 cl::desc("Print the info for Mach-O objects in "
123 "non-verbose or numeric form (requires -macho)"));
125 cl::opt<std::string> llvm::DisSymName(
127 cl::desc("disassemble just this symbol's instructions (requires -macho"));
129 static cl::opt<bool> NoSymbolicOperands(
130 "no-symbolic-operands",
131 cl::desc("do not symbolic operands when disassembling (requires -macho)"));
134 static cl::list<std::string>
135 ArchFlags("arch", cl::desc("architecture(s) from a Mach-O file to dump"),
137 bool ArchAll = false;
139 static std::string ThumbTripleName;
141 static const Target *GetTarget(const MachOObjectFile *MachOObj,
142 const char **McpuDefault,
143 const Target **ThumbTarget) {
144 // Figure out the target triple.
145 if (TripleName.empty()) {
146 llvm::Triple TT("unknown-unknown-unknown");
147 llvm::Triple ThumbTriple = Triple();
148 TT = MachOObj->getArch(McpuDefault, &ThumbTriple);
149 TripleName = TT.str();
150 ThumbTripleName = ThumbTriple.str();
153 // Get the target specific parser.
155 const Target *TheTarget = TargetRegistry::lookupTarget(TripleName, Error);
156 if (TheTarget && ThumbTripleName.empty())
159 *ThumbTarget = TargetRegistry::lookupTarget(ThumbTripleName, Error);
163 errs() << "llvm-objdump: error: unable to get target for '";
165 errs() << TripleName;
167 errs() << ThumbTripleName;
168 errs() << "', see --version and --triple.\n";
172 struct SymbolSorter {
173 bool operator()(const SymbolRef &A, const SymbolRef &B) {
174 SymbolRef::Type AType, BType;
178 uint64_t AAddr, BAddr;
179 if (AType != SymbolRef::ST_Function)
183 if (BType != SymbolRef::ST_Function)
187 return AAddr < BAddr;
191 // Types for the storted data in code table that is built before disassembly
192 // and the predicate function to sort them.
193 typedef std::pair<uint64_t, DiceRef> DiceTableEntry;
194 typedef std::vector<DiceTableEntry> DiceTable;
195 typedef DiceTable::iterator dice_table_iterator;
197 // This is used to search for a data in code table entry for the PC being
198 // disassembled. The j parameter has the PC in j.first. A single data in code
199 // table entry can cover many bytes for each of its Kind's. So if the offset,
200 // aka the i.first value, of the data in code table entry plus its Length
201 // covers the PC being searched for this will return true. If not it will
203 static bool compareDiceTableEntries(const DiceTableEntry &i,
204 const DiceTableEntry &j) {
206 i.second.getLength(Length);
208 return j.first >= i.first && j.first < i.first + Length;
211 static uint64_t DumpDataInCode(const uint8_t *bytes, uint64_t Length,
212 unsigned short Kind) {
213 uint32_t Value, Size = 1;
217 case MachO::DICE_KIND_DATA:
220 DumpBytes(ArrayRef<uint8_t>(bytes, 4));
221 Value = bytes[3] << 24 | bytes[2] << 16 | bytes[1] << 8 | bytes[0];
222 outs() << "\t.long " << Value;
224 } else if (Length >= 2) {
226 DumpBytes(ArrayRef<uint8_t>(bytes, 2));
227 Value = bytes[1] << 8 | bytes[0];
228 outs() << "\t.short " << Value;
232 DumpBytes(ArrayRef<uint8_t>(bytes, 2));
234 outs() << "\t.byte " << Value;
237 if (Kind == MachO::DICE_KIND_DATA)
238 outs() << "\t@ KIND_DATA\n";
240 outs() << "\t@ data in code kind = " << Kind << "\n";
242 case MachO::DICE_KIND_JUMP_TABLE8:
244 DumpBytes(ArrayRef<uint8_t>(bytes, 1));
246 outs() << "\t.byte " << format("%3u", Value) << "\t@ KIND_JUMP_TABLE8\n";
249 case MachO::DICE_KIND_JUMP_TABLE16:
251 DumpBytes(ArrayRef<uint8_t>(bytes, 2));
252 Value = bytes[1] << 8 | bytes[0];
253 outs() << "\t.short " << format("%5u", Value & 0xffff)
254 << "\t@ KIND_JUMP_TABLE16\n";
257 case MachO::DICE_KIND_JUMP_TABLE32:
258 case MachO::DICE_KIND_ABS_JUMP_TABLE32:
260 DumpBytes(ArrayRef<uint8_t>(bytes, 4));
261 Value = bytes[3] << 24 | bytes[2] << 16 | bytes[1] << 8 | bytes[0];
262 outs() << "\t.long " << Value;
263 if (Kind == MachO::DICE_KIND_JUMP_TABLE32)
264 outs() << "\t@ KIND_JUMP_TABLE32\n";
266 outs() << "\t@ KIND_ABS_JUMP_TABLE32\n";
273 static void getSectionsAndSymbols(const MachO::mach_header Header,
274 MachOObjectFile *MachOObj,
275 std::vector<SectionRef> &Sections,
276 std::vector<SymbolRef> &Symbols,
277 SmallVectorImpl<uint64_t> &FoundFns,
278 uint64_t &BaseSegmentAddress) {
279 for (const SymbolRef &Symbol : MachOObj->symbols()) {
281 Symbol.getName(SymName);
282 if (!SymName.startswith("ltmp"))
283 Symbols.push_back(Symbol);
286 for (const SectionRef &Section : MachOObj->sections()) {
288 Section.getName(SectName);
289 Sections.push_back(Section);
292 MachOObjectFile::LoadCommandInfo Command =
293 MachOObj->getFirstLoadCommandInfo();
294 bool BaseSegmentAddressSet = false;
295 for (unsigned i = 0;; ++i) {
296 if (Command.C.cmd == MachO::LC_FUNCTION_STARTS) {
297 // We found a function starts segment, parse the addresses for later
299 MachO::linkedit_data_command LLC =
300 MachOObj->getLinkeditDataLoadCommand(Command);
302 MachOObj->ReadULEB128s(LLC.dataoff, FoundFns);
303 } else if (Command.C.cmd == MachO::LC_SEGMENT) {
304 MachO::segment_command SLC = MachOObj->getSegmentLoadCommand(Command);
305 StringRef SegName = SLC.segname;
306 if (!BaseSegmentAddressSet && SegName != "__PAGEZERO") {
307 BaseSegmentAddressSet = true;
308 BaseSegmentAddress = SLC.vmaddr;
312 if (i == Header.ncmds - 1)
315 Command = MachOObj->getNextLoadCommandInfo(Command);
319 static void PrintIndirectSymbolTable(MachOObjectFile *O, bool verbose,
320 uint32_t n, uint32_t count,
321 uint32_t stride, uint64_t addr) {
322 MachO::dysymtab_command Dysymtab = O->getDysymtabLoadCommand();
323 uint32_t nindirectsyms = Dysymtab.nindirectsyms;
324 if (n > nindirectsyms)
325 outs() << " (entries start past the end of the indirect symbol "
326 "table) (reserved1 field greater than the table size)";
327 else if (n + count > nindirectsyms)
328 outs() << " (entries extends past the end of the indirect symbol "
331 uint32_t cputype = O->getHeader().cputype;
332 if (cputype & MachO::CPU_ARCH_ABI64)
333 outs() << "address index";
335 outs() << "address index";
340 for (uint32_t j = 0; j < count && n + j < nindirectsyms; j++) {
341 if (cputype & MachO::CPU_ARCH_ABI64)
342 outs() << format("0x%016" PRIx64, addr + j * stride) << " ";
344 outs() << format("0x%08" PRIx32, addr + j * stride) << " ";
345 MachO::dysymtab_command Dysymtab = O->getDysymtabLoadCommand();
346 uint32_t indirect_symbol = O->getIndirectSymbolTableEntry(Dysymtab, n + j);
347 if (indirect_symbol == MachO::INDIRECT_SYMBOL_LOCAL) {
351 if (indirect_symbol ==
352 (MachO::INDIRECT_SYMBOL_LOCAL | MachO::INDIRECT_SYMBOL_ABS)) {
353 outs() << "LOCAL ABSOLUTE\n";
356 if (indirect_symbol == MachO::INDIRECT_SYMBOL_ABS) {
357 outs() << "ABSOLUTE\n";
360 outs() << format("%5u ", indirect_symbol);
362 MachO::symtab_command Symtab = O->getSymtabLoadCommand();
363 if (indirect_symbol < Symtab.nsyms) {
364 symbol_iterator Sym = O->getSymbolByIndex(indirect_symbol);
365 SymbolRef Symbol = *Sym;
367 Symbol.getName(SymName);
377 static void PrintIndirectSymbols(MachOObjectFile *O, bool verbose) {
378 uint32_t LoadCommandCount = O->getHeader().ncmds;
379 MachOObjectFile::LoadCommandInfo Load = O->getFirstLoadCommandInfo();
380 for (unsigned I = 0;; ++I) {
381 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
382 MachO::segment_command_64 Seg = O->getSegment64LoadCommand(Load);
383 for (unsigned J = 0; J < Seg.nsects; ++J) {
384 MachO::section_64 Sec = O->getSection64(Load, J);
385 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
386 if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
387 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
388 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
389 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
390 section_type == MachO::S_SYMBOL_STUBS) {
392 if (section_type == MachO::S_SYMBOL_STUBS)
393 stride = Sec.reserved2;
397 outs() << "Can't print indirect symbols for (" << Sec.segname << ","
398 << Sec.sectname << ") "
399 << "(size of stubs in reserved2 field is zero)\n";
402 uint32_t count = Sec.size / stride;
403 outs() << "Indirect symbols for (" << Sec.segname << ","
404 << Sec.sectname << ") " << count << " entries";
405 uint32_t n = Sec.reserved1;
406 PrintIndirectSymbolTable(O, verbose, n, count, stride, Sec.addr);
409 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
410 MachO::segment_command Seg = O->getSegmentLoadCommand(Load);
411 for (unsigned J = 0; J < Seg.nsects; ++J) {
412 MachO::section Sec = O->getSection(Load, J);
413 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
414 if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
415 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
416 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
417 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
418 section_type == MachO::S_SYMBOL_STUBS) {
420 if (section_type == MachO::S_SYMBOL_STUBS)
421 stride = Sec.reserved2;
425 outs() << "Can't print indirect symbols for (" << Sec.segname << ","
426 << Sec.sectname << ") "
427 << "(size of stubs in reserved2 field is zero)\n";
430 uint32_t count = Sec.size / stride;
431 outs() << "Indirect symbols for (" << Sec.segname << ","
432 << Sec.sectname << ") " << count << " entries";
433 uint32_t n = Sec.reserved1;
434 PrintIndirectSymbolTable(O, verbose, n, count, stride, Sec.addr);
438 if (I == LoadCommandCount - 1)
441 Load = O->getNextLoadCommandInfo(Load);
445 static void PrintDataInCodeTable(MachOObjectFile *O, bool verbose) {
446 MachO::linkedit_data_command DIC = O->getDataInCodeLoadCommand();
447 uint32_t nentries = DIC.datasize / sizeof(struct MachO::data_in_code_entry);
448 outs() << "Data in code table (" << nentries << " entries)\n";
449 outs() << "offset length kind\n";
450 for (dice_iterator DI = O->begin_dices(), DE = O->end_dices(); DI != DE;
453 DI->getOffset(Offset);
454 outs() << format("0x%08" PRIx32, Offset) << " ";
456 DI->getLength(Length);
457 outs() << format("%6u", Length) << " ";
462 case MachO::DICE_KIND_DATA:
465 case MachO::DICE_KIND_JUMP_TABLE8:
466 outs() << "JUMP_TABLE8";
468 case MachO::DICE_KIND_JUMP_TABLE16:
469 outs() << "JUMP_TABLE16";
471 case MachO::DICE_KIND_JUMP_TABLE32:
472 outs() << "JUMP_TABLE32";
474 case MachO::DICE_KIND_ABS_JUMP_TABLE32:
475 outs() << "ABS_JUMP_TABLE32";
478 outs() << format("0x%04" PRIx32, Kind);
482 outs() << format("0x%04" PRIx32, Kind);
487 static void PrintLinkOptHints(MachOObjectFile *O) {
488 MachO::linkedit_data_command LohLC = O->getLinkOptHintsLoadCommand();
489 const char *loh = O->getData().substr(LohLC.dataoff, 1).data();
490 uint32_t nloh = LohLC.datasize;
491 outs() << "Linker optimiztion hints (" << nloh << " total bytes)\n";
492 for (uint32_t i = 0; i < nloh;) {
494 uint64_t identifier = decodeULEB128((const uint8_t *)(loh + i), &n);
496 outs() << " identifier " << identifier << " ";
499 switch (identifier) {
501 outs() << "AdrpAdrp\n";
504 outs() << "AdrpLdr\n";
507 outs() << "AdrpAddLdr\n";
510 outs() << "AdrpLdrGotLdr\n";
513 outs() << "AdrpAddStr\n";
516 outs() << "AdrpLdrGotStr\n";
519 outs() << "AdrpAdd\n";
522 outs() << "AdrpLdrGot\n";
525 outs() << "Unknown identifier value\n";
528 uint64_t narguments = decodeULEB128((const uint8_t *)(loh + i), &n);
530 outs() << " narguments " << narguments << "\n";
534 for (uint32_t j = 0; j < narguments; j++) {
535 uint64_t value = decodeULEB128((const uint8_t *)(loh + i), &n);
537 outs() << "\tvalue " << format("0x%" PRIx64, value) << "\n";
544 static void PrintDylibs(MachOObjectFile *O, bool JustId) {
545 uint32_t LoadCommandCount = O->getHeader().ncmds;
546 MachOObjectFile::LoadCommandInfo Load = O->getFirstLoadCommandInfo();
547 for (unsigned I = 0;; ++I) {
548 if ((JustId && Load.C.cmd == MachO::LC_ID_DYLIB) ||
549 (!JustId && (Load.C.cmd == MachO::LC_ID_DYLIB ||
550 Load.C.cmd == MachO::LC_LOAD_DYLIB ||
551 Load.C.cmd == MachO::LC_LOAD_WEAK_DYLIB ||
552 Load.C.cmd == MachO::LC_REEXPORT_DYLIB ||
553 Load.C.cmd == MachO::LC_LAZY_LOAD_DYLIB ||
554 Load.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB))) {
555 MachO::dylib_command dl = O->getDylibIDLoadCommand(Load);
556 if (dl.dylib.name < dl.cmdsize) {
557 const char *p = (const char *)(Load.Ptr) + dl.dylib.name;
562 outs() << " (compatibility version "
563 << ((dl.dylib.compatibility_version >> 16) & 0xffff) << "."
564 << ((dl.dylib.compatibility_version >> 8) & 0xff) << "."
565 << (dl.dylib.compatibility_version & 0xff) << ",";
566 outs() << " current version "
567 << ((dl.dylib.current_version >> 16) & 0xffff) << "."
568 << ((dl.dylib.current_version >> 8) & 0xff) << "."
569 << (dl.dylib.current_version & 0xff) << ")\n";
572 outs() << "\tBad offset (" << dl.dylib.name << ") for name of ";
573 if (Load.C.cmd == MachO::LC_ID_DYLIB)
574 outs() << "LC_ID_DYLIB ";
575 else if (Load.C.cmd == MachO::LC_LOAD_DYLIB)
576 outs() << "LC_LOAD_DYLIB ";
577 else if (Load.C.cmd == MachO::LC_LOAD_WEAK_DYLIB)
578 outs() << "LC_LOAD_WEAK_DYLIB ";
579 else if (Load.C.cmd == MachO::LC_LAZY_LOAD_DYLIB)
580 outs() << "LC_LAZY_LOAD_DYLIB ";
581 else if (Load.C.cmd == MachO::LC_REEXPORT_DYLIB)
582 outs() << "LC_REEXPORT_DYLIB ";
583 else if (Load.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB)
584 outs() << "LC_LOAD_UPWARD_DYLIB ";
587 outs() << "command " << I << "\n";
590 if (I == LoadCommandCount - 1)
593 Load = O->getNextLoadCommandInfo(Load);
597 typedef DenseMap<uint64_t, StringRef> SymbolAddressMap;
599 static void CreateSymbolAddressMap(MachOObjectFile *O,
600 SymbolAddressMap *AddrMap) {
601 // Create a map of symbol addresses to symbol names.
602 for (const SymbolRef &Symbol : O->symbols()) {
605 if (ST == SymbolRef::ST_Function || ST == SymbolRef::ST_Data ||
606 ST == SymbolRef::ST_Other) {
608 Symbol.getAddress(Address);
610 Symbol.getName(SymName);
611 (*AddrMap)[Address] = SymName;
616 // GuessSymbolName is passed the address of what might be a symbol and a
617 // pointer to the SymbolAddressMap. It returns the name of a symbol
618 // with that address or nullptr if no symbol is found with that address.
619 static const char *GuessSymbolName(uint64_t value, SymbolAddressMap *AddrMap) {
620 const char *SymbolName = nullptr;
621 // A DenseMap can't lookup up some values.
622 if (value != 0xffffffffffffffffULL && value != 0xfffffffffffffffeULL) {
623 StringRef name = AddrMap->lookup(value);
625 SymbolName = name.data();
630 static void DumpCstringChar(const char c) {
634 outs().write_escaped(p);
637 static void DumpCstringSection(MachOObjectFile *O, const char *sect,
638 uint32_t sect_size, uint64_t sect_addr,
639 bool print_addresses) {
640 for (uint32_t i = 0; i < sect_size; i++) {
641 if (print_addresses) {
643 outs() << format("%016" PRIx64, sect_addr + i) << " ";
645 outs() << format("%08" PRIx64, sect_addr + i) << " ";
647 for (; i < sect_size && sect[i] != '\0'; i++)
648 DumpCstringChar(sect[i]);
649 if (i < sect_size && sect[i] == '\0')
654 static void DumpLiteral4(uint32_t l, float f) {
655 outs() << format("0x%08" PRIx32, l);
656 if ((l & 0x7f800000) != 0x7f800000)
657 outs() << format(" (%.16e)\n", f);
660 outs() << " (+Infinity)\n";
661 else if (l == 0xff800000)
662 outs() << " (-Infinity)\n";
663 else if ((l & 0x00400000) == 0x00400000)
664 outs() << " (non-signaling Not-a-Number)\n";
666 outs() << " (signaling Not-a-Number)\n";
670 static void DumpLiteral4Section(MachOObjectFile *O, const char *sect,
671 uint32_t sect_size, uint64_t sect_addr,
672 bool print_addresses) {
673 for (uint32_t i = 0; i < sect_size; i += sizeof(float)) {
674 if (print_addresses) {
676 outs() << format("%016" PRIx64, sect_addr + i) << " ";
678 outs() << format("%08" PRIx64, sect_addr + i) << " ";
681 memcpy(&f, sect + i, sizeof(float));
682 if (O->isLittleEndian() != sys::IsLittleEndianHost)
683 sys::swapByteOrder(f);
685 memcpy(&l, sect + i, sizeof(uint32_t));
686 if (O->isLittleEndian() != sys::IsLittleEndianHost)
687 sys::swapByteOrder(l);
692 static void DumpLiteral8(MachOObjectFile *O, uint32_t l0, uint32_t l1,
694 outs() << format("0x%08" PRIx32, l0) << " " << format("0x%08" PRIx32, l1);
696 if (O->isLittleEndian()) {
703 // Hi is the high word, so this is equivalent to if(isfinite(d))
704 if ((Hi & 0x7ff00000) != 0x7ff00000)
705 outs() << format(" (%.16e)\n", d);
707 if (Hi == 0x7ff00000 && Lo == 0)
708 outs() << " (+Infinity)\n";
709 else if (Hi == 0xfff00000 && Lo == 0)
710 outs() << " (-Infinity)\n";
711 else if ((Hi & 0x00080000) == 0x00080000)
712 outs() << " (non-signaling Not-a-Number)\n";
714 outs() << " (signaling Not-a-Number)\n";
718 static void DumpLiteral8Section(MachOObjectFile *O, const char *sect,
719 uint32_t sect_size, uint64_t sect_addr,
720 bool print_addresses) {
721 for (uint32_t i = 0; i < sect_size; i += sizeof(double)) {
722 if (print_addresses) {
724 outs() << format("%016" PRIx64, sect_addr + i) << " ";
726 outs() << format("%08" PRIx64, sect_addr + i) << " ";
729 memcpy(&d, sect + i, sizeof(double));
730 if (O->isLittleEndian() != sys::IsLittleEndianHost)
731 sys::swapByteOrder(d);
733 memcpy(&l0, sect + i, sizeof(uint32_t));
734 memcpy(&l1, sect + i + sizeof(uint32_t), sizeof(uint32_t));
735 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
736 sys::swapByteOrder(l0);
737 sys::swapByteOrder(l1);
739 DumpLiteral8(O, l0, l1, d);
743 static void DumpLiteral16(uint32_t l0, uint32_t l1, uint32_t l2, uint32_t l3) {
744 outs() << format("0x%08" PRIx32, l0) << " ";
745 outs() << format("0x%08" PRIx32, l1) << " ";
746 outs() << format("0x%08" PRIx32, l2) << " ";
747 outs() << format("0x%08" PRIx32, l3) << "\n";
750 static void DumpLiteral16Section(MachOObjectFile *O, const char *sect,
751 uint32_t sect_size, uint64_t sect_addr,
752 bool print_addresses) {
753 for (uint32_t i = 0; i < sect_size; i += 16) {
754 if (print_addresses) {
756 outs() << format("%016" PRIx64, sect_addr + i) << " ";
758 outs() << format("%08" PRIx64, sect_addr + i) << " ";
760 uint32_t l0, l1, l2, l3;
761 memcpy(&l0, sect + i, sizeof(uint32_t));
762 memcpy(&l1, sect + i + sizeof(uint32_t), sizeof(uint32_t));
763 memcpy(&l2, sect + i + 2 * sizeof(uint32_t), sizeof(uint32_t));
764 memcpy(&l3, sect + i + 3 * sizeof(uint32_t), sizeof(uint32_t));
765 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
766 sys::swapByteOrder(l0);
767 sys::swapByteOrder(l1);
768 sys::swapByteOrder(l2);
769 sys::swapByteOrder(l3);
771 DumpLiteral16(l0, l1, l2, l3);
775 static void DumpLiteralPointerSection(MachOObjectFile *O,
776 const SectionRef &Section,
777 const char *sect, uint32_t sect_size,
779 bool print_addresses) {
780 // Collect the literal sections in this Mach-O file.
781 std::vector<SectionRef> LiteralSections;
782 for (const SectionRef &Section : O->sections()) {
783 DataRefImpl Ref = Section.getRawDataRefImpl();
784 uint32_t section_type;
786 const MachO::section_64 Sec = O->getSection64(Ref);
787 section_type = Sec.flags & MachO::SECTION_TYPE;
789 const MachO::section Sec = O->getSection(Ref);
790 section_type = Sec.flags & MachO::SECTION_TYPE;
792 if (section_type == MachO::S_CSTRING_LITERALS ||
793 section_type == MachO::S_4BYTE_LITERALS ||
794 section_type == MachO::S_8BYTE_LITERALS ||
795 section_type == MachO::S_16BYTE_LITERALS)
796 LiteralSections.push_back(Section);
799 // Set the size of the literal pointer.
800 uint32_t lp_size = O->is64Bit() ? 8 : 4;
802 // Collect the external relocation symbols for the the literal pointers.
803 std::vector<std::pair<uint64_t, SymbolRef>> Relocs;
804 for (const RelocationRef &Reloc : Section.relocations()) {
806 MachO::any_relocation_info RE;
807 bool isExtern = false;
808 Rel = Reloc.getRawDataRefImpl();
809 RE = O->getRelocation(Rel);
810 isExtern = O->getPlainRelocationExternal(RE);
812 uint64_t RelocOffset;
813 Reloc.getOffset(RelocOffset);
814 symbol_iterator RelocSym = Reloc.getSymbol();
815 Relocs.push_back(std::make_pair(RelocOffset, *RelocSym));
818 array_pod_sort(Relocs.begin(), Relocs.end());
820 // Dump each literal pointer.
821 for (uint32_t i = 0; i < sect_size; i += lp_size) {
822 if (print_addresses) {
824 outs() << format("%016" PRIx64, sect_addr + i) << " ";
826 outs() << format("%08" PRIx64, sect_addr + i) << " ";
830 memcpy(&lp, sect + i, sizeof(uint64_t));
831 if (O->isLittleEndian() != sys::IsLittleEndianHost)
832 sys::swapByteOrder(lp);
835 memcpy(&li, sect + i, sizeof(uint32_t));
836 if (O->isLittleEndian() != sys::IsLittleEndianHost)
837 sys::swapByteOrder(li);
841 // First look for an external relocation entry for this literal pointer.
842 auto Reloc = std::find_if(
843 Relocs.begin(), Relocs.end(),
844 [&](const std::pair<uint64_t, SymbolRef> &P) { return P.first == i; });
845 if (Reloc != Relocs.end()) {
846 symbol_iterator RelocSym = Reloc->second;
848 RelocSym->getName(SymName);
849 outs() << "external relocation entry for symbol:" << SymName << "\n";
853 // For local references see what the section the literal pointer points to.
854 auto Sect = std::find_if(LiteralSections.begin(), LiteralSections.end(),
855 [&](const SectionRef &R) {
856 return lp >= R.getAddress() &&
857 lp < R.getAddress() + R.getSize();
859 if (Sect == LiteralSections.end()) {
860 outs() << format("0x%" PRIx64, lp) << " (not in a literal section)\n";
864 uint64_t SectAddress = Sect->getAddress();
865 uint64_t SectSize = Sect->getSize();
868 Sect->getName(SectName);
869 DataRefImpl Ref = Sect->getRawDataRefImpl();
870 StringRef SegmentName = O->getSectionFinalSegmentName(Ref);
871 outs() << SegmentName << ":" << SectName << ":";
873 uint32_t section_type;
875 const MachO::section_64 Sec = O->getSection64(Ref);
876 section_type = Sec.flags & MachO::SECTION_TYPE;
878 const MachO::section Sec = O->getSection(Ref);
879 section_type = Sec.flags & MachO::SECTION_TYPE;
883 Sect->getContents(BytesStr);
884 const char *Contents = reinterpret_cast<const char *>(BytesStr.data());
886 switch (section_type) {
887 case MachO::S_CSTRING_LITERALS:
888 for (uint64_t i = lp - SectAddress; i < SectSize && Contents[i] != '\0';
890 DumpCstringChar(Contents[i]);
894 case MachO::S_4BYTE_LITERALS:
896 memcpy(&f, Contents + (lp - SectAddress), sizeof(float));
898 memcpy(&l, Contents + (lp - SectAddress), sizeof(uint32_t));
899 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
900 sys::swapByteOrder(f);
901 sys::swapByteOrder(l);
905 case MachO::S_8BYTE_LITERALS: {
907 memcpy(&d, Contents + (lp - SectAddress), sizeof(double));
909 memcpy(&l0, Contents + (lp - SectAddress), sizeof(uint32_t));
910 memcpy(&l1, Contents + (lp - SectAddress) + sizeof(uint32_t),
912 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
913 sys::swapByteOrder(f);
914 sys::swapByteOrder(l0);
915 sys::swapByteOrder(l1);
917 DumpLiteral8(O, l0, l1, d);
920 case MachO::S_16BYTE_LITERALS: {
921 uint32_t l0, l1, l2, l3;
922 memcpy(&l0, Contents + (lp - SectAddress), sizeof(uint32_t));
923 memcpy(&l1, Contents + (lp - SectAddress) + sizeof(uint32_t),
925 memcpy(&l2, Contents + (lp - SectAddress) + 2 * sizeof(uint32_t),
927 memcpy(&l3, Contents + (lp - SectAddress) + 3 * sizeof(uint32_t),
929 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
930 sys::swapByteOrder(l0);
931 sys::swapByteOrder(l1);
932 sys::swapByteOrder(l2);
933 sys::swapByteOrder(l3);
935 DumpLiteral16(l0, l1, l2, l3);
942 static void DumpInitTermPointerSection(MachOObjectFile *O, const char *sect,
943 uint32_t sect_size, uint64_t sect_addr,
944 SymbolAddressMap *AddrMap,
948 stride = sizeof(uint64_t);
950 stride = sizeof(uint32_t);
951 for (uint32_t i = 0; i < sect_size; i += stride) {
952 const char *SymbolName = nullptr;
954 outs() << format("0x%016" PRIx64, sect_addr + i * stride) << " ";
955 uint64_t pointer_value;
956 memcpy(&pointer_value, sect + i, stride);
957 if (O->isLittleEndian() != sys::IsLittleEndianHost)
958 sys::swapByteOrder(pointer_value);
959 outs() << format("0x%016" PRIx64, pointer_value);
961 SymbolName = GuessSymbolName(pointer_value, AddrMap);
963 outs() << format("0x%08" PRIx64, sect_addr + i * stride) << " ";
964 uint32_t pointer_value;
965 memcpy(&pointer_value, sect + i, stride);
966 if (O->isLittleEndian() != sys::IsLittleEndianHost)
967 sys::swapByteOrder(pointer_value);
968 outs() << format("0x%08" PRIx32, pointer_value);
970 SymbolName = GuessSymbolName(pointer_value, AddrMap);
973 outs() << " " << SymbolName;
978 static void DumpRawSectionContents(MachOObjectFile *O, const char *sect,
979 uint32_t size, uint64_t addr) {
980 uint32_t cputype = O->getHeader().cputype;
981 if (cputype == MachO::CPU_TYPE_I386 || cputype == MachO::CPU_TYPE_X86_64) {
983 for (uint32_t i = 0; i < size; i += j, addr += j) {
985 outs() << format("%016" PRIx64, addr) << "\t";
987 outs() << format("%08" PRIx64, addr) << "\t";
988 for (j = 0; j < 16 && i + j < size; j++) {
989 uint8_t byte_word = *(sect + i + j);
990 outs() << format("%02" PRIx32, (uint32_t)byte_word) << " ";
996 for (uint32_t i = 0; i < size; i += j, addr += j) {
998 outs() << format("%016" PRIx64, addr) << "\t";
1000 outs() << format("%08" PRIx64, sect) << "\t";
1001 for (j = 0; j < 4 * sizeof(int32_t) && i + j < size;
1002 j += sizeof(int32_t)) {
1003 if (i + j + sizeof(int32_t) < size) {
1005 memcpy(&long_word, sect + i + j, sizeof(int32_t));
1006 if (O->isLittleEndian() != sys::IsLittleEndianHost)
1007 sys::swapByteOrder(long_word);
1008 outs() << format("%08" PRIx32, long_word) << " ";
1010 for (uint32_t k = 0; i + j + k < size; k++) {
1011 uint8_t byte_word = *(sect + i + j);
1012 outs() << format("%02" PRIx32, (uint32_t)byte_word) << " ";
1021 static void DisassembleMachO(StringRef Filename, MachOObjectFile *MachOOF,
1022 StringRef DisSegName, StringRef DisSectName);
1024 static void DumpSectionContents(StringRef Filename, MachOObjectFile *O,
1026 SymbolAddressMap AddrMap;
1028 CreateSymbolAddressMap(O, &AddrMap);
1030 for (unsigned i = 0; i < DumpSections.size(); ++i) {
1031 StringRef DumpSection = DumpSections[i];
1032 std::pair<StringRef, StringRef> DumpSegSectName;
1033 DumpSegSectName = DumpSection.split(',');
1034 StringRef DumpSegName, DumpSectName;
1035 if (DumpSegSectName.second.size()) {
1036 DumpSegName = DumpSegSectName.first;
1037 DumpSectName = DumpSegSectName.second;
1040 DumpSectName = DumpSegSectName.first;
1042 for (const SectionRef &Section : O->sections()) {
1044 Section.getName(SectName);
1045 DataRefImpl Ref = Section.getRawDataRefImpl();
1046 StringRef SegName = O->getSectionFinalSegmentName(Ref);
1047 if ((DumpSegName.empty() || SegName == DumpSegName) &&
1048 (SectName == DumpSectName)) {
1050 uint32_t section_flags;
1052 const MachO::section_64 Sec = O->getSection64(Ref);
1053 section_flags = Sec.flags;
1056 const MachO::section Sec = O->getSection(Ref);
1057 section_flags = Sec.flags;
1059 uint32_t section_type = section_flags & MachO::SECTION_TYPE;
1062 Section.getContents(BytesStr);
1063 const char *sect = reinterpret_cast<const char *>(BytesStr.data());
1064 uint32_t sect_size = BytesStr.size();
1065 uint64_t sect_addr = Section.getAddress();
1068 outs().write(BytesStr.data(), BytesStr.size());
1072 outs() << "Contents of (" << SegName << "," << SectName
1076 if ((section_flags & MachO::S_ATTR_PURE_INSTRUCTIONS) ||
1077 (section_flags & MachO::S_ATTR_SOME_INSTRUCTIONS)) {
1078 DisassembleMachO(Filename, O, SegName, SectName);
1081 if (SegName == "__TEXT" && SectName == "__info_plist") {
1085 switch (section_type) {
1086 case MachO::S_REGULAR:
1087 DumpRawSectionContents(O, sect, sect_size, sect_addr);
1089 case MachO::S_ZEROFILL:
1090 outs() << "zerofill section and has no contents in the file\n";
1092 case MachO::S_CSTRING_LITERALS:
1093 DumpCstringSection(O, sect, sect_size, sect_addr, !NoLeadingAddr);
1095 case MachO::S_4BYTE_LITERALS:
1096 DumpLiteral4Section(O, sect, sect_size, sect_addr, !NoLeadingAddr);
1098 case MachO::S_8BYTE_LITERALS:
1099 DumpLiteral8Section(O, sect, sect_size, sect_addr, !NoLeadingAddr);
1101 case MachO::S_16BYTE_LITERALS:
1102 DumpLiteral16Section(O, sect, sect_size, sect_addr, !NoLeadingAddr);
1104 case MachO::S_LITERAL_POINTERS:
1105 DumpLiteralPointerSection(O, Section, sect, sect_size, sect_addr,
1108 case MachO::S_MOD_INIT_FUNC_POINTERS:
1109 case MachO::S_MOD_TERM_FUNC_POINTERS:
1110 DumpInitTermPointerSection(O, sect, sect_size, sect_addr, &AddrMap,
1114 outs() << "Unknown section type ("
1115 << format("0x%08" PRIx32, section_type) << ")\n";
1116 DumpRawSectionContents(O, sect, sect_size, sect_addr);
1120 if (section_type == MachO::S_ZEROFILL)
1121 outs() << "zerofill section and has no contents in the file\n";
1123 DumpRawSectionContents(O, sect, sect_size, sect_addr);
1130 static void DumpInfoPlistSectionContents(StringRef Filename,
1131 MachOObjectFile *O) {
1132 for (const SectionRef &Section : O->sections()) {
1134 Section.getName(SectName);
1135 DataRefImpl Ref = Section.getRawDataRefImpl();
1136 StringRef SegName = O->getSectionFinalSegmentName(Ref);
1137 if (SegName == "__TEXT" && SectName == "__info_plist") {
1138 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
1140 Section.getContents(BytesStr);
1141 const char *sect = reinterpret_cast<const char *>(BytesStr.data());
1148 // checkMachOAndArchFlags() checks to see if the ObjectFile is a Mach-O file
1149 // and if it is and there is a list of architecture flags is specified then
1150 // check to make sure this Mach-O file is one of those architectures or all
1151 // architectures were specified. If not then an error is generated and this
1152 // routine returns false. Else it returns true.
1153 static bool checkMachOAndArchFlags(ObjectFile *O, StringRef Filename) {
1154 if (isa<MachOObjectFile>(O) && !ArchAll && ArchFlags.size() != 0) {
1155 MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(O);
1156 bool ArchFound = false;
1157 MachO::mach_header H;
1158 MachO::mach_header_64 H_64;
1160 if (MachO->is64Bit()) {
1161 H_64 = MachO->MachOObjectFile::getHeader64();
1162 T = MachOObjectFile::getArch(H_64.cputype, H_64.cpusubtype);
1164 H = MachO->MachOObjectFile::getHeader();
1165 T = MachOObjectFile::getArch(H.cputype, H.cpusubtype);
1168 for (i = 0; i < ArchFlags.size(); ++i) {
1169 if (ArchFlags[i] == T.getArchName())
1174 errs() << "llvm-objdump: file: " + Filename + " does not contain "
1175 << "architecture: " + ArchFlags[i] + "\n";
1182 // ProcessMachO() is passed a single opened Mach-O file, which may be an
1183 // archive member and or in a slice of a universal file. It prints the
1184 // the file name and header info and then processes it according to the
1185 // command line options.
1186 static void ProcessMachO(StringRef Filename, MachOObjectFile *MachOOF,
1187 StringRef ArchiveMemberName = StringRef(),
1188 StringRef ArchitectureName = StringRef()) {
1189 // If we are doing some processing here on the Mach-O file print the header
1190 // info. And don't print it otherwise like in the case of printing the
1191 // UniversalHeaders or ArchiveHeaders.
1192 if (Disassemble || PrivateHeaders || ExportsTrie || Rebase || Bind ||
1193 LazyBind || WeakBind || IndirectSymbols || DataInCode || LinkOptHints ||
1194 DylibsUsed || DylibId || (DumpSections.size() != 0 && !Raw)) {
1196 if (!ArchiveMemberName.empty())
1197 outs() << '(' << ArchiveMemberName << ')';
1198 if (!ArchitectureName.empty())
1199 outs() << " (architecture " << ArchitectureName << ")";
1204 DisassembleMachO(Filename, MachOOF, "__TEXT", "__text");
1205 if (IndirectSymbols)
1206 PrintIndirectSymbols(MachOOF, !NonVerbose);
1208 PrintDataInCodeTable(MachOOF, !NonVerbose);
1210 PrintLinkOptHints(MachOOF);
1212 PrintRelocations(MachOOF);
1214 PrintSectionHeaders(MachOOF);
1215 if (SectionContents)
1216 PrintSectionContents(MachOOF);
1217 if (DumpSections.size() != 0)
1218 DumpSectionContents(Filename, MachOOF, !NonVerbose);
1220 DumpInfoPlistSectionContents(Filename, MachOOF);
1222 PrintDylibs(MachOOF, false);
1224 PrintDylibs(MachOOF, true);
1226 PrintSymbolTable(MachOOF);
1228 printMachOUnwindInfo(MachOOF);
1230 printMachOFileHeader(MachOOF);
1232 printExportsTrie(MachOOF);
1234 printRebaseTable(MachOOF);
1236 printBindTable(MachOOF);
1238 printLazyBindTable(MachOOF);
1240 printWeakBindTable(MachOOF);
1243 // printUnknownCPUType() helps print_fat_headers for unknown CPU's.
1244 static void printUnknownCPUType(uint32_t cputype, uint32_t cpusubtype) {
1245 outs() << " cputype (" << cputype << ")\n";
1246 outs() << " cpusubtype (" << cpusubtype << ")\n";
1249 // printCPUType() helps print_fat_headers by printing the cputype and
1250 // pusubtype (symbolically for the one's it knows about).
1251 static void printCPUType(uint32_t cputype, uint32_t cpusubtype) {
1253 case MachO::CPU_TYPE_I386:
1254 switch (cpusubtype) {
1255 case MachO::CPU_SUBTYPE_I386_ALL:
1256 outs() << " cputype CPU_TYPE_I386\n";
1257 outs() << " cpusubtype CPU_SUBTYPE_I386_ALL\n";
1260 printUnknownCPUType(cputype, cpusubtype);
1264 case MachO::CPU_TYPE_X86_64:
1265 switch (cpusubtype) {
1266 case MachO::CPU_SUBTYPE_X86_64_ALL:
1267 outs() << " cputype CPU_TYPE_X86_64\n";
1268 outs() << " cpusubtype CPU_SUBTYPE_X86_64_ALL\n";
1270 case MachO::CPU_SUBTYPE_X86_64_H:
1271 outs() << " cputype CPU_TYPE_X86_64\n";
1272 outs() << " cpusubtype CPU_SUBTYPE_X86_64_H\n";
1275 printUnknownCPUType(cputype, cpusubtype);
1279 case MachO::CPU_TYPE_ARM:
1280 switch (cpusubtype) {
1281 case MachO::CPU_SUBTYPE_ARM_ALL:
1282 outs() << " cputype CPU_TYPE_ARM\n";
1283 outs() << " cpusubtype CPU_SUBTYPE_ARM_ALL\n";
1285 case MachO::CPU_SUBTYPE_ARM_V4T:
1286 outs() << " cputype CPU_TYPE_ARM\n";
1287 outs() << " cpusubtype CPU_SUBTYPE_ARM_V4T\n";
1289 case MachO::CPU_SUBTYPE_ARM_V5TEJ:
1290 outs() << " cputype CPU_TYPE_ARM\n";
1291 outs() << " cpusubtype CPU_SUBTYPE_ARM_V5TEJ\n";
1293 case MachO::CPU_SUBTYPE_ARM_XSCALE:
1294 outs() << " cputype CPU_TYPE_ARM\n";
1295 outs() << " cpusubtype CPU_SUBTYPE_ARM_XSCALE\n";
1297 case MachO::CPU_SUBTYPE_ARM_V6:
1298 outs() << " cputype CPU_TYPE_ARM\n";
1299 outs() << " cpusubtype CPU_SUBTYPE_ARM_V6\n";
1301 case MachO::CPU_SUBTYPE_ARM_V6M:
1302 outs() << " cputype CPU_TYPE_ARM\n";
1303 outs() << " cpusubtype CPU_SUBTYPE_ARM_V6M\n";
1305 case MachO::CPU_SUBTYPE_ARM_V7:
1306 outs() << " cputype CPU_TYPE_ARM\n";
1307 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7\n";
1309 case MachO::CPU_SUBTYPE_ARM_V7EM:
1310 outs() << " cputype CPU_TYPE_ARM\n";
1311 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7EM\n";
1313 case MachO::CPU_SUBTYPE_ARM_V7K:
1314 outs() << " cputype CPU_TYPE_ARM\n";
1315 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7K\n";
1317 case MachO::CPU_SUBTYPE_ARM_V7M:
1318 outs() << " cputype CPU_TYPE_ARM\n";
1319 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7M\n";
1321 case MachO::CPU_SUBTYPE_ARM_V7S:
1322 outs() << " cputype CPU_TYPE_ARM\n";
1323 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7S\n";
1326 printUnknownCPUType(cputype, cpusubtype);
1330 case MachO::CPU_TYPE_ARM64:
1331 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
1332 case MachO::CPU_SUBTYPE_ARM64_ALL:
1333 outs() << " cputype CPU_TYPE_ARM64\n";
1334 outs() << " cpusubtype CPU_SUBTYPE_ARM64_ALL\n";
1337 printUnknownCPUType(cputype, cpusubtype);
1342 printUnknownCPUType(cputype, cpusubtype);
1347 static void printMachOUniversalHeaders(const object::MachOUniversalBinary *UB,
1349 outs() << "Fat headers\n";
1351 outs() << "fat_magic FAT_MAGIC\n";
1353 outs() << "fat_magic " << format("0x%" PRIx32, MachO::FAT_MAGIC) << "\n";
1355 uint32_t nfat_arch = UB->getNumberOfObjects();
1356 StringRef Buf = UB->getData();
1357 uint64_t size = Buf.size();
1358 uint64_t big_size = sizeof(struct MachO::fat_header) +
1359 nfat_arch * sizeof(struct MachO::fat_arch);
1360 outs() << "nfat_arch " << UB->getNumberOfObjects();
1362 outs() << " (malformed, contains zero architecture types)\n";
1363 else if (big_size > size)
1364 outs() << " (malformed, architectures past end of file)\n";
1368 for (uint32_t i = 0; i < nfat_arch; ++i) {
1369 MachOUniversalBinary::ObjectForArch OFA(UB, i);
1370 uint32_t cputype = OFA.getCPUType();
1371 uint32_t cpusubtype = OFA.getCPUSubType();
1372 outs() << "architecture ";
1373 for (uint32_t j = 0; i != 0 && j <= i - 1; j++) {
1374 MachOUniversalBinary::ObjectForArch other_OFA(UB, j);
1375 uint32_t other_cputype = other_OFA.getCPUType();
1376 uint32_t other_cpusubtype = other_OFA.getCPUSubType();
1377 if (cputype != 0 && cpusubtype != 0 && cputype == other_cputype &&
1378 (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) ==
1379 (other_cpusubtype & ~MachO::CPU_SUBTYPE_MASK)) {
1380 outs() << "(illegal duplicate architecture) ";
1385 outs() << OFA.getArchTypeName() << "\n";
1386 printCPUType(cputype, cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
1388 outs() << i << "\n";
1389 outs() << " cputype " << cputype << "\n";
1390 outs() << " cpusubtype " << (cpusubtype & ~MachO::CPU_SUBTYPE_MASK)
1394 (cpusubtype & MachO::CPU_SUBTYPE_MASK) == MachO::CPU_SUBTYPE_LIB64)
1395 outs() << " capabilities CPU_SUBTYPE_LIB64\n";
1397 outs() << " capabilities "
1398 << format("0x%" PRIx32,
1399 (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24) << "\n";
1400 outs() << " offset " << OFA.getOffset();
1401 if (OFA.getOffset() > size)
1402 outs() << " (past end of file)";
1403 if (OFA.getOffset() % (1 << OFA.getAlign()) != 0)
1404 outs() << " (not aligned on it's alignment (2^" << OFA.getAlign() << ")";
1406 outs() << " size " << OFA.getSize();
1407 big_size = OFA.getOffset() + OFA.getSize();
1408 if (big_size > size)
1409 outs() << " (past end of file)";
1411 outs() << " align 2^" << OFA.getAlign() << " (" << (1 << OFA.getAlign())
1416 static void printArchiveChild(Archive::Child &C, bool verbose,
1417 bool print_offset) {
1419 outs() << C.getChildOffset() << "\t";
1420 sys::fs::perms Mode = C.getAccessMode();
1422 // FIXME: this first dash, "-", is for (Mode & S_IFMT) == S_IFREG.
1423 // But there is nothing in sys::fs::perms for S_IFMT or S_IFREG.
1425 if (Mode & sys::fs::owner_read)
1429 if (Mode & sys::fs::owner_write)
1433 if (Mode & sys::fs::owner_exe)
1437 if (Mode & sys::fs::group_read)
1441 if (Mode & sys::fs::group_write)
1445 if (Mode & sys::fs::group_exe)
1449 if (Mode & sys::fs::others_read)
1453 if (Mode & sys::fs::others_write)
1457 if (Mode & sys::fs::others_exe)
1462 outs() << format("0%o ", Mode);
1465 unsigned UID = C.getUID();
1466 outs() << format("%3d/", UID);
1467 unsigned GID = C.getGID();
1468 outs() << format("%-3d ", GID);
1469 uint64_t Size = C.getRawSize();
1470 outs() << format("%5" PRId64, Size) << " ";
1472 StringRef RawLastModified = C.getRawLastModified();
1475 if (RawLastModified.getAsInteger(10, Seconds))
1476 outs() << "(date: \"%s\" contains non-decimal chars) " << RawLastModified;
1478 // Since cime(3) returns a 26 character string of the form:
1479 // "Sun Sep 16 01:03:52 1973\n\0"
1480 // just print 24 characters.
1482 outs() << format("%.24s ", ctime(&t));
1485 outs() << RawLastModified << " ";
1489 ErrorOr<StringRef> NameOrErr = C.getName();
1490 if (NameOrErr.getError()) {
1491 StringRef RawName = C.getRawName();
1492 outs() << RawName << "\n";
1494 StringRef Name = NameOrErr.get();
1495 outs() << Name << "\n";
1498 StringRef RawName = C.getRawName();
1499 outs() << RawName << "\n";
1503 static void printArchiveHeaders(Archive *A, bool verbose, bool print_offset) {
1504 if (A->hasSymbolTable()) {
1505 Archive::child_iterator S = A->getSymbolTableChild();
1506 Archive::Child C = *S;
1507 printArchiveChild(C, verbose, print_offset);
1509 for (Archive::child_iterator I = A->child_begin(), E = A->child_end(); I != E;
1511 Archive::Child C = *I;
1512 printArchiveChild(C, verbose, print_offset);
1516 // ParseInputMachO() parses the named Mach-O file in Filename and handles the
1517 // -arch flags selecting just those slices as specified by them and also parses
1518 // archive files. Then for each individual Mach-O file ProcessMachO() is
1519 // called to process the file based on the command line options.
1520 void llvm::ParseInputMachO(StringRef Filename) {
1521 // Check for -arch all and verifiy the -arch flags are valid.
1522 for (unsigned i = 0; i < ArchFlags.size(); ++i) {
1523 if (ArchFlags[i] == "all") {
1526 if (!MachOObjectFile::isValidArch(ArchFlags[i])) {
1527 errs() << "llvm-objdump: Unknown architecture named '" + ArchFlags[i] +
1528 "'for the -arch option\n";
1534 // Attempt to open the binary.
1535 ErrorOr<OwningBinary<Binary>> BinaryOrErr = createBinary(Filename);
1536 if (std::error_code EC = BinaryOrErr.getError()) {
1537 errs() << "llvm-objdump: '" << Filename << "': " << EC.message() << ".\n";
1540 Binary &Bin = *BinaryOrErr.get().getBinary();
1542 if (Archive *A = dyn_cast<Archive>(&Bin)) {
1543 outs() << "Archive : " << Filename << "\n";
1545 printArchiveHeaders(A, true, false);
1546 for (Archive::child_iterator I = A->child_begin(), E = A->child_end();
1548 ErrorOr<std::unique_ptr<Binary>> ChildOrErr = I->getAsBinary();
1549 if (ChildOrErr.getError())
1551 if (MachOObjectFile *O = dyn_cast<MachOObjectFile>(&*ChildOrErr.get())) {
1552 if (!checkMachOAndArchFlags(O, Filename))
1554 ProcessMachO(Filename, O, O->getFileName());
1559 if (UniversalHeaders) {
1560 if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(&Bin))
1561 printMachOUniversalHeaders(UB, !NonVerbose);
1563 if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(&Bin)) {
1564 // If we have a list of architecture flags specified dump only those.
1565 if (!ArchAll && ArchFlags.size() != 0) {
1566 // Look for a slice in the universal binary that matches each ArchFlag.
1568 for (unsigned i = 0; i < ArchFlags.size(); ++i) {
1570 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
1571 E = UB->end_objects();
1573 if (ArchFlags[i] == I->getArchTypeName()) {
1575 ErrorOr<std::unique_ptr<ObjectFile>> ObjOrErr =
1576 I->getAsObjectFile();
1577 std::string ArchitectureName = "";
1578 if (ArchFlags.size() > 1)
1579 ArchitectureName = I->getArchTypeName();
1581 ObjectFile &O = *ObjOrErr.get();
1582 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&O))
1583 ProcessMachO(Filename, MachOOF, "", ArchitectureName);
1584 } else if (ErrorOr<std::unique_ptr<Archive>> AOrErr =
1585 I->getAsArchive()) {
1586 std::unique_ptr<Archive> &A = *AOrErr;
1587 outs() << "Archive : " << Filename;
1588 if (!ArchitectureName.empty())
1589 outs() << " (architecture " << ArchitectureName << ")";
1592 printArchiveHeaders(A.get(), true, false);
1593 for (Archive::child_iterator AI = A->child_begin(),
1594 AE = A->child_end();
1596 ErrorOr<std::unique_ptr<Binary>> ChildOrErr = AI->getAsBinary();
1597 if (ChildOrErr.getError())
1599 if (MachOObjectFile *O =
1600 dyn_cast<MachOObjectFile>(&*ChildOrErr.get()))
1601 ProcessMachO(Filename, O, O->getFileName(), ArchitectureName);
1607 errs() << "llvm-objdump: file: " + Filename + " does not contain "
1608 << "architecture: " + ArchFlags[i] + "\n";
1614 // No architecture flags were specified so if this contains a slice that
1615 // matches the host architecture dump only that.
1617 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
1618 E = UB->end_objects();
1620 if (MachOObjectFile::getHostArch().getArchName() ==
1621 I->getArchTypeName()) {
1622 ErrorOr<std::unique_ptr<ObjectFile>> ObjOrErr = I->getAsObjectFile();
1623 std::string ArchiveName;
1624 ArchiveName.clear();
1626 ObjectFile &O = *ObjOrErr.get();
1627 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&O))
1628 ProcessMachO(Filename, MachOOF);
1629 } else if (ErrorOr<std::unique_ptr<Archive>> AOrErr =
1630 I->getAsArchive()) {
1631 std::unique_ptr<Archive> &A = *AOrErr;
1632 outs() << "Archive : " << Filename << "\n";
1634 printArchiveHeaders(A.get(), true, false);
1635 for (Archive::child_iterator AI = A->child_begin(),
1636 AE = A->child_end();
1638 ErrorOr<std::unique_ptr<Binary>> ChildOrErr = AI->getAsBinary();
1639 if (ChildOrErr.getError())
1641 if (MachOObjectFile *O =
1642 dyn_cast<MachOObjectFile>(&*ChildOrErr.get()))
1643 ProcessMachO(Filename, O, O->getFileName());
1650 // Either all architectures have been specified or none have been specified
1651 // and this does not contain the host architecture so dump all the slices.
1652 bool moreThanOneArch = UB->getNumberOfObjects() > 1;
1653 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
1654 E = UB->end_objects();
1656 ErrorOr<std::unique_ptr<ObjectFile>> ObjOrErr = I->getAsObjectFile();
1657 std::string ArchitectureName = "";
1658 if (moreThanOneArch)
1659 ArchitectureName = I->getArchTypeName();
1661 ObjectFile &Obj = *ObjOrErr.get();
1662 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&Obj))
1663 ProcessMachO(Filename, MachOOF, "", ArchitectureName);
1664 } else if (ErrorOr<std::unique_ptr<Archive>> AOrErr = I->getAsArchive()) {
1665 std::unique_ptr<Archive> &A = *AOrErr;
1666 outs() << "Archive : " << Filename;
1667 if (!ArchitectureName.empty())
1668 outs() << " (architecture " << ArchitectureName << ")";
1671 printArchiveHeaders(A.get(), true, false);
1672 for (Archive::child_iterator AI = A->child_begin(), AE = A->child_end();
1674 ErrorOr<std::unique_ptr<Binary>> ChildOrErr = AI->getAsBinary();
1675 if (ChildOrErr.getError())
1677 if (MachOObjectFile *O =
1678 dyn_cast<MachOObjectFile>(&*ChildOrErr.get())) {
1679 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(O))
1680 ProcessMachO(Filename, MachOOF, MachOOF->getFileName(),
1688 if (ObjectFile *O = dyn_cast<ObjectFile>(&Bin)) {
1689 if (!checkMachOAndArchFlags(O, Filename))
1691 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&*O)) {
1692 ProcessMachO(Filename, MachOOF);
1694 errs() << "llvm-objdump: '" << Filename << "': "
1695 << "Object is not a Mach-O file type.\n";
1697 errs() << "llvm-objdump: '" << Filename << "': "
1698 << "Unrecognized file type.\n";
1701 typedef std::pair<uint64_t, const char *> BindInfoEntry;
1702 typedef std::vector<BindInfoEntry> BindTable;
1703 typedef BindTable::iterator bind_table_iterator;
1705 // The block of info used by the Symbolizer call backs.
1706 struct DisassembleInfo {
1710 SymbolAddressMap *AddrMap;
1711 std::vector<SectionRef> *Sections;
1712 const char *class_name;
1713 const char *selector_name;
1715 char *demangled_name;
1718 BindTable *bindtable;
1721 // SymbolizerGetOpInfo() is the operand information call back function.
1722 // This is called to get the symbolic information for operand(s) of an
1723 // instruction when it is being done. This routine does this from
1724 // the relocation information, symbol table, etc. That block of information
1725 // is a pointer to the struct DisassembleInfo that was passed when the
1726 // disassembler context was created and passed to back to here when
1727 // called back by the disassembler for instruction operands that could have
1728 // relocation information. The address of the instruction containing operand is
1729 // at the Pc parameter. The immediate value the operand has is passed in
1730 // op_info->Value and is at Offset past the start of the instruction and has a
1731 // byte Size of 1, 2 or 4. The symbolc information is returned in TagBuf is the
1732 // LLVMOpInfo1 struct defined in the header "llvm-c/Disassembler.h" as symbol
1733 // names and addends of the symbolic expression to add for the operand. The
1734 // value of TagType is currently 1 (for the LLVMOpInfo1 struct). If symbolic
1735 // information is returned then this function returns 1 else it returns 0.
1736 static int SymbolizerGetOpInfo(void *DisInfo, uint64_t Pc, uint64_t Offset,
1737 uint64_t Size, int TagType, void *TagBuf) {
1738 struct DisassembleInfo *info = (struct DisassembleInfo *)DisInfo;
1739 struct LLVMOpInfo1 *op_info = (struct LLVMOpInfo1 *)TagBuf;
1740 uint64_t value = op_info->Value;
1742 // Make sure all fields returned are zero if we don't set them.
1743 memset((void *)op_info, '\0', sizeof(struct LLVMOpInfo1));
1744 op_info->Value = value;
1746 // If the TagType is not the value 1 which it code knows about or if no
1747 // verbose symbolic information is wanted then just return 0, indicating no
1748 // information is being returned.
1749 if (TagType != 1 || !info->verbose)
1752 unsigned int Arch = info->O->getArch();
1753 if (Arch == Triple::x86) {
1754 if (Size != 1 && Size != 2 && Size != 4 && Size != 0)
1756 // First search the section's relocation entries (if any) for an entry
1757 // for this section offset.
1758 uint32_t sect_addr = info->S.getAddress();
1759 uint32_t sect_offset = (Pc + Offset) - sect_addr;
1760 bool reloc_found = false;
1762 MachO::any_relocation_info RE;
1763 bool isExtern = false;
1765 bool r_scattered = false;
1766 uint32_t r_value, pair_r_value, r_type;
1767 for (const RelocationRef &Reloc : info->S.relocations()) {
1768 uint64_t RelocOffset;
1769 Reloc.getOffset(RelocOffset);
1770 if (RelocOffset == sect_offset) {
1771 Rel = Reloc.getRawDataRefImpl();
1772 RE = info->O->getRelocation(Rel);
1773 r_type = info->O->getAnyRelocationType(RE);
1774 r_scattered = info->O->isRelocationScattered(RE);
1776 r_value = info->O->getScatteredRelocationValue(RE);
1777 if (r_type == MachO::GENERIC_RELOC_SECTDIFF ||
1778 r_type == MachO::GENERIC_RELOC_LOCAL_SECTDIFF) {
1779 DataRefImpl RelNext = Rel;
1780 info->O->moveRelocationNext(RelNext);
1781 MachO::any_relocation_info RENext;
1782 RENext = info->O->getRelocation(RelNext);
1783 if (info->O->isRelocationScattered(RENext))
1784 pair_r_value = info->O->getScatteredRelocationValue(RENext);
1789 isExtern = info->O->getPlainRelocationExternal(RE);
1791 symbol_iterator RelocSym = Reloc.getSymbol();
1799 if (reloc_found && isExtern) {
1801 Symbol.getName(SymName);
1802 const char *name = SymName.data();
1803 op_info->AddSymbol.Present = 1;
1804 op_info->AddSymbol.Name = name;
1805 // For i386 extern relocation entries the value in the instruction is
1806 // the offset from the symbol, and value is already set in op_info->Value.
1809 if (reloc_found && (r_type == MachO::GENERIC_RELOC_SECTDIFF ||
1810 r_type == MachO::GENERIC_RELOC_LOCAL_SECTDIFF)) {
1811 const char *add = GuessSymbolName(r_value, info->AddrMap);
1812 const char *sub = GuessSymbolName(pair_r_value, info->AddrMap);
1813 uint32_t offset = value - (r_value - pair_r_value);
1814 op_info->AddSymbol.Present = 1;
1816 op_info->AddSymbol.Name = add;
1818 op_info->AddSymbol.Value = r_value;
1819 op_info->SubtractSymbol.Present = 1;
1821 op_info->SubtractSymbol.Name = sub;
1823 op_info->SubtractSymbol.Value = pair_r_value;
1824 op_info->Value = offset;
1828 // Second search the external relocation entries of a fully linked image
1829 // (if any) for an entry that matches this segment offset.
1830 // uint32_t seg_offset = (Pc + Offset);
1833 if (Arch == Triple::x86_64) {
1834 if (Size != 1 && Size != 2 && Size != 4 && Size != 0)
1836 // First search the section's relocation entries (if any) for an entry
1837 // for this section offset.
1838 uint64_t sect_addr = info->S.getAddress();
1839 uint64_t sect_offset = (Pc + Offset) - sect_addr;
1840 bool reloc_found = false;
1842 MachO::any_relocation_info RE;
1843 bool isExtern = false;
1845 for (const RelocationRef &Reloc : info->S.relocations()) {
1846 uint64_t RelocOffset;
1847 Reloc.getOffset(RelocOffset);
1848 if (RelocOffset == sect_offset) {
1849 Rel = Reloc.getRawDataRefImpl();
1850 RE = info->O->getRelocation(Rel);
1851 // NOTE: Scattered relocations don't exist on x86_64.
1852 isExtern = info->O->getPlainRelocationExternal(RE);
1854 symbol_iterator RelocSym = Reloc.getSymbol();
1861 if (reloc_found && isExtern) {
1862 // The Value passed in will be adjusted by the Pc if the instruction
1863 // adds the Pc. But for x86_64 external relocation entries the Value
1864 // is the offset from the external symbol.
1865 if (info->O->getAnyRelocationPCRel(RE))
1866 op_info->Value -= Pc + Offset + Size;
1868 Symbol.getName(SymName);
1869 const char *name = SymName.data();
1870 unsigned Type = info->O->getAnyRelocationType(RE);
1871 if (Type == MachO::X86_64_RELOC_SUBTRACTOR) {
1872 DataRefImpl RelNext = Rel;
1873 info->O->moveRelocationNext(RelNext);
1874 MachO::any_relocation_info RENext = info->O->getRelocation(RelNext);
1875 unsigned TypeNext = info->O->getAnyRelocationType(RENext);
1876 bool isExternNext = info->O->getPlainRelocationExternal(RENext);
1877 unsigned SymbolNum = info->O->getPlainRelocationSymbolNum(RENext);
1878 if (TypeNext == MachO::X86_64_RELOC_UNSIGNED && isExternNext) {
1879 op_info->SubtractSymbol.Present = 1;
1880 op_info->SubtractSymbol.Name = name;
1881 symbol_iterator RelocSymNext = info->O->getSymbolByIndex(SymbolNum);
1882 Symbol = *RelocSymNext;
1883 StringRef SymNameNext;
1884 Symbol.getName(SymNameNext);
1885 name = SymNameNext.data();
1888 // TODO: add the VariantKinds to op_info->VariantKind for relocation types
1889 // like: X86_64_RELOC_TLV, X86_64_RELOC_GOT_LOAD and X86_64_RELOC_GOT.
1890 op_info->AddSymbol.Present = 1;
1891 op_info->AddSymbol.Name = name;
1895 // Second search the external relocation entries of a fully linked image
1896 // (if any) for an entry that matches this segment offset.
1897 // uint64_t seg_offset = (Pc + Offset);
1900 if (Arch == Triple::arm) {
1901 if (Offset != 0 || (Size != 4 && Size != 2))
1903 // First search the section's relocation entries (if any) for an entry
1904 // for this section offset.
1905 uint32_t sect_addr = info->S.getAddress();
1906 uint32_t sect_offset = (Pc + Offset) - sect_addr;
1908 MachO::any_relocation_info RE;
1909 bool isExtern = false;
1911 bool r_scattered = false;
1912 uint32_t r_value, pair_r_value, r_type, r_length, other_half;
1914 std::find_if(info->S.relocations().begin(), info->S.relocations().end(),
1915 [&](const RelocationRef &Reloc) {
1916 uint64_t RelocOffset;
1917 Reloc.getOffset(RelocOffset);
1918 return RelocOffset == sect_offset;
1921 if (Reloc == info->S.relocations().end())
1924 Rel = Reloc->getRawDataRefImpl();
1925 RE = info->O->getRelocation(Rel);
1926 r_length = info->O->getAnyRelocationLength(RE);
1927 r_scattered = info->O->isRelocationScattered(RE);
1929 r_value = info->O->getScatteredRelocationValue(RE);
1930 r_type = info->O->getScatteredRelocationType(RE);
1932 r_type = info->O->getAnyRelocationType(RE);
1933 isExtern = info->O->getPlainRelocationExternal(RE);
1935 symbol_iterator RelocSym = Reloc->getSymbol();
1939 if (r_type == MachO::ARM_RELOC_HALF ||
1940 r_type == MachO::ARM_RELOC_SECTDIFF ||
1941 r_type == MachO::ARM_RELOC_LOCAL_SECTDIFF ||
1942 r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
1943 DataRefImpl RelNext = Rel;
1944 info->O->moveRelocationNext(RelNext);
1945 MachO::any_relocation_info RENext;
1946 RENext = info->O->getRelocation(RelNext);
1947 other_half = info->O->getAnyRelocationAddress(RENext) & 0xffff;
1948 if (info->O->isRelocationScattered(RENext))
1949 pair_r_value = info->O->getScatteredRelocationValue(RENext);
1954 Symbol.getName(SymName);
1955 const char *name = SymName.data();
1956 op_info->AddSymbol.Present = 1;
1957 op_info->AddSymbol.Name = name;
1959 case MachO::ARM_RELOC_HALF:
1960 if ((r_length & 0x1) == 1) {
1961 op_info->Value = value << 16 | other_half;
1962 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
1964 op_info->Value = other_half << 16 | value;
1965 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
1973 // If we have a branch that is not an external relocation entry then
1974 // return 0 so the code in tryAddingSymbolicOperand() can use the
1975 // SymbolLookUp call back with the branch target address to look up the
1976 // symbol and possiblity add an annotation for a symbol stub.
1977 if (isExtern == 0 && (r_type == MachO::ARM_RELOC_BR24 ||
1978 r_type == MachO::ARM_THUMB_RELOC_BR22))
1981 uint32_t offset = 0;
1982 if (r_type == MachO::ARM_RELOC_HALF ||
1983 r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
1984 if ((r_length & 0x1) == 1)
1985 value = value << 16 | other_half;
1987 value = other_half << 16 | value;
1989 if (r_scattered && (r_type != MachO::ARM_RELOC_HALF &&
1990 r_type != MachO::ARM_RELOC_HALF_SECTDIFF)) {
1991 offset = value - r_value;
1995 if (r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
1996 if ((r_length & 0x1) == 1)
1997 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
1999 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
2000 const char *add = GuessSymbolName(r_value, info->AddrMap);
2001 const char *sub = GuessSymbolName(pair_r_value, info->AddrMap);
2002 int32_t offset = value - (r_value - pair_r_value);
2003 op_info->AddSymbol.Present = 1;
2005 op_info->AddSymbol.Name = add;
2007 op_info->AddSymbol.Value = r_value;
2008 op_info->SubtractSymbol.Present = 1;
2010 op_info->SubtractSymbol.Name = sub;
2012 op_info->SubtractSymbol.Value = pair_r_value;
2013 op_info->Value = offset;
2017 op_info->AddSymbol.Present = 1;
2018 op_info->Value = offset;
2019 if (r_type == MachO::ARM_RELOC_HALF) {
2020 if ((r_length & 0x1) == 1)
2021 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
2023 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
2025 const char *add = GuessSymbolName(value, info->AddrMap);
2026 if (add != nullptr) {
2027 op_info->AddSymbol.Name = add;
2030 op_info->AddSymbol.Value = value;
2033 if (Arch == Triple::aarch64) {
2034 if (Offset != 0 || Size != 4)
2036 // First search the section's relocation entries (if any) for an entry
2037 // for this section offset.
2038 uint64_t sect_addr = info->S.getAddress();
2039 uint64_t sect_offset = (Pc + Offset) - sect_addr;
2041 std::find_if(info->S.relocations().begin(), info->S.relocations().end(),
2042 [&](const RelocationRef &Reloc) {
2043 uint64_t RelocOffset;
2044 Reloc.getOffset(RelocOffset);
2045 return RelocOffset == sect_offset;
2048 if (Reloc == info->S.relocations().end())
2051 DataRefImpl Rel = Reloc->getRawDataRefImpl();
2052 MachO::any_relocation_info RE = info->O->getRelocation(Rel);
2053 uint32_t r_type = info->O->getAnyRelocationType(RE);
2054 if (r_type == MachO::ARM64_RELOC_ADDEND) {
2055 DataRefImpl RelNext = Rel;
2056 info->O->moveRelocationNext(RelNext);
2057 MachO::any_relocation_info RENext = info->O->getRelocation(RelNext);
2059 value = info->O->getPlainRelocationSymbolNum(RENext);
2060 op_info->Value = value;
2063 // NOTE: Scattered relocations don't exist on arm64.
2064 if (!info->O->getPlainRelocationExternal(RE))
2067 Reloc->getSymbol()->getName(SymName);
2068 const char *name = SymName.data();
2069 op_info->AddSymbol.Present = 1;
2070 op_info->AddSymbol.Name = name;
2073 case MachO::ARM64_RELOC_PAGE21:
2075 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_PAGE;
2077 case MachO::ARM64_RELOC_PAGEOFF12:
2079 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_PAGEOFF;
2081 case MachO::ARM64_RELOC_GOT_LOAD_PAGE21:
2083 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_GOTPAGE;
2085 case MachO::ARM64_RELOC_GOT_LOAD_PAGEOFF12:
2087 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_GOTPAGEOFF;
2089 case MachO::ARM64_RELOC_TLVP_LOAD_PAGE21:
2090 /* @tvlppage is not implemented in llvm-mc */
2091 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_TLVP;
2093 case MachO::ARM64_RELOC_TLVP_LOAD_PAGEOFF12:
2094 /* @tvlppageoff is not implemented in llvm-mc */
2095 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_TLVOFF;
2098 case MachO::ARM64_RELOC_BRANCH26:
2099 op_info->VariantKind = LLVMDisassembler_VariantKind_None;
2107 // GuessCstringPointer is passed the address of what might be a pointer to a
2108 // literal string in a cstring section. If that address is in a cstring section
2109 // it returns a pointer to that string. Else it returns nullptr.
2110 static const char *GuessCstringPointer(uint64_t ReferenceValue,
2111 struct DisassembleInfo *info) {
2112 uint32_t LoadCommandCount = info->O->getHeader().ncmds;
2113 MachOObjectFile::LoadCommandInfo Load = info->O->getFirstLoadCommandInfo();
2114 for (unsigned I = 0;; ++I) {
2115 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
2116 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
2117 for (unsigned J = 0; J < Seg.nsects; ++J) {
2118 MachO::section_64 Sec = info->O->getSection64(Load, J);
2119 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
2120 if (section_type == MachO::S_CSTRING_LITERALS &&
2121 ReferenceValue >= Sec.addr &&
2122 ReferenceValue < Sec.addr + Sec.size) {
2123 uint64_t sect_offset = ReferenceValue - Sec.addr;
2124 uint64_t object_offset = Sec.offset + sect_offset;
2125 StringRef MachOContents = info->O->getData();
2126 uint64_t object_size = MachOContents.size();
2127 const char *object_addr = (const char *)MachOContents.data();
2128 if (object_offset < object_size) {
2129 const char *name = object_addr + object_offset;
2136 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
2137 MachO::segment_command Seg = info->O->getSegmentLoadCommand(Load);
2138 for (unsigned J = 0; J < Seg.nsects; ++J) {
2139 MachO::section Sec = info->O->getSection(Load, J);
2140 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
2141 if (section_type == MachO::S_CSTRING_LITERALS &&
2142 ReferenceValue >= Sec.addr &&
2143 ReferenceValue < Sec.addr + Sec.size) {
2144 uint64_t sect_offset = ReferenceValue - Sec.addr;
2145 uint64_t object_offset = Sec.offset + sect_offset;
2146 StringRef MachOContents = info->O->getData();
2147 uint64_t object_size = MachOContents.size();
2148 const char *object_addr = (const char *)MachOContents.data();
2149 if (object_offset < object_size) {
2150 const char *name = object_addr + object_offset;
2158 if (I == LoadCommandCount - 1)
2161 Load = info->O->getNextLoadCommandInfo(Load);
2166 // GuessIndirectSymbol returns the name of the indirect symbol for the
2167 // ReferenceValue passed in or nullptr. This is used when ReferenceValue maybe
2168 // an address of a symbol stub or a lazy or non-lazy pointer to associate the
2169 // symbol name being referenced by the stub or pointer.
2170 static const char *GuessIndirectSymbol(uint64_t ReferenceValue,
2171 struct DisassembleInfo *info) {
2172 uint32_t LoadCommandCount = info->O->getHeader().ncmds;
2173 MachOObjectFile::LoadCommandInfo Load = info->O->getFirstLoadCommandInfo();
2174 MachO::dysymtab_command Dysymtab = info->O->getDysymtabLoadCommand();
2175 MachO::symtab_command Symtab = info->O->getSymtabLoadCommand();
2176 for (unsigned I = 0;; ++I) {
2177 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
2178 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
2179 for (unsigned J = 0; J < Seg.nsects; ++J) {
2180 MachO::section_64 Sec = info->O->getSection64(Load, J);
2181 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
2182 if ((section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
2183 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
2184 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
2185 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
2186 section_type == MachO::S_SYMBOL_STUBS) &&
2187 ReferenceValue >= Sec.addr &&
2188 ReferenceValue < Sec.addr + Sec.size) {
2190 if (section_type == MachO::S_SYMBOL_STUBS)
2191 stride = Sec.reserved2;
2196 uint32_t index = Sec.reserved1 + (ReferenceValue - Sec.addr) / stride;
2197 if (index < Dysymtab.nindirectsyms) {
2198 uint32_t indirect_symbol =
2199 info->O->getIndirectSymbolTableEntry(Dysymtab, index);
2200 if (indirect_symbol < Symtab.nsyms) {
2201 symbol_iterator Sym = info->O->getSymbolByIndex(indirect_symbol);
2202 SymbolRef Symbol = *Sym;
2204 Symbol.getName(SymName);
2205 const char *name = SymName.data();
2211 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
2212 MachO::segment_command Seg = info->O->getSegmentLoadCommand(Load);
2213 for (unsigned J = 0; J < Seg.nsects; ++J) {
2214 MachO::section Sec = info->O->getSection(Load, J);
2215 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
2216 if ((section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
2217 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
2218 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
2219 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
2220 section_type == MachO::S_SYMBOL_STUBS) &&
2221 ReferenceValue >= Sec.addr &&
2222 ReferenceValue < Sec.addr + Sec.size) {
2224 if (section_type == MachO::S_SYMBOL_STUBS)
2225 stride = Sec.reserved2;
2230 uint32_t index = Sec.reserved1 + (ReferenceValue - Sec.addr) / stride;
2231 if (index < Dysymtab.nindirectsyms) {
2232 uint32_t indirect_symbol =
2233 info->O->getIndirectSymbolTableEntry(Dysymtab, index);
2234 if (indirect_symbol < Symtab.nsyms) {
2235 symbol_iterator Sym = info->O->getSymbolByIndex(indirect_symbol);
2236 SymbolRef Symbol = *Sym;
2238 Symbol.getName(SymName);
2239 const char *name = SymName.data();
2246 if (I == LoadCommandCount - 1)
2249 Load = info->O->getNextLoadCommandInfo(Load);
2254 // method_reference() is called passing it the ReferenceName that might be
2255 // a reference it to an Objective-C method call. If so then it allocates and
2256 // assembles a method call string with the values last seen and saved in
2257 // the DisassembleInfo's class_name and selector_name fields. This is saved
2258 // into the method field of the info and any previous string is free'ed.
2259 // Then the class_name field in the info is set to nullptr. The method call
2260 // string is set into ReferenceName and ReferenceType is set to
2261 // LLVMDisassembler_ReferenceType_Out_Objc_Message. If this not a method call
2262 // then both ReferenceType and ReferenceName are left unchanged.
2263 static void method_reference(struct DisassembleInfo *info,
2264 uint64_t *ReferenceType,
2265 const char **ReferenceName) {
2266 unsigned int Arch = info->O->getArch();
2267 if (*ReferenceName != nullptr) {
2268 if (strcmp(*ReferenceName, "_objc_msgSend") == 0) {
2269 if (info->selector_name != nullptr) {
2270 if (info->method != nullptr)
2272 if (info->class_name != nullptr) {
2273 info->method = (char *)malloc(5 + strlen(info->class_name) +
2274 strlen(info->selector_name));
2275 if (info->method != nullptr) {
2276 strcpy(info->method, "+[");
2277 strcat(info->method, info->class_name);
2278 strcat(info->method, " ");
2279 strcat(info->method, info->selector_name);
2280 strcat(info->method, "]");
2281 *ReferenceName = info->method;
2282 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
2285 info->method = (char *)malloc(9 + strlen(info->selector_name));
2286 if (info->method != nullptr) {
2287 if (Arch == Triple::x86_64)
2288 strcpy(info->method, "-[%rdi ");
2289 else if (Arch == Triple::aarch64)
2290 strcpy(info->method, "-[x0 ");
2292 strcpy(info->method, "-[r? ");
2293 strcat(info->method, info->selector_name);
2294 strcat(info->method, "]");
2295 *ReferenceName = info->method;
2296 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
2299 info->class_name = nullptr;
2301 } else if (strcmp(*ReferenceName, "_objc_msgSendSuper2") == 0) {
2302 if (info->selector_name != nullptr) {
2303 if (info->method != nullptr)
2305 info->method = (char *)malloc(17 + strlen(info->selector_name));
2306 if (info->method != nullptr) {
2307 if (Arch == Triple::x86_64)
2308 strcpy(info->method, "-[[%rdi super] ");
2309 else if (Arch == Triple::aarch64)
2310 strcpy(info->method, "-[[x0 super] ");
2312 strcpy(info->method, "-[[r? super] ");
2313 strcat(info->method, info->selector_name);
2314 strcat(info->method, "]");
2315 *ReferenceName = info->method;
2316 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
2318 info->class_name = nullptr;
2324 // GuessPointerPointer() is passed the address of what might be a pointer to
2325 // a reference to an Objective-C class, selector, message ref or cfstring.
2326 // If so the value of the pointer is returned and one of the booleans are set
2327 // to true. If not zero is returned and all the booleans are set to false.
2328 static uint64_t GuessPointerPointer(uint64_t ReferenceValue,
2329 struct DisassembleInfo *info,
2330 bool &classref, bool &selref, bool &msgref,
2336 uint32_t LoadCommandCount = info->O->getHeader().ncmds;
2337 MachOObjectFile::LoadCommandInfo Load = info->O->getFirstLoadCommandInfo();
2338 for (unsigned I = 0;; ++I) {
2339 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
2340 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
2341 for (unsigned J = 0; J < Seg.nsects; ++J) {
2342 MachO::section_64 Sec = info->O->getSection64(Load, J);
2343 if ((strncmp(Sec.sectname, "__objc_selrefs", 16) == 0 ||
2344 strncmp(Sec.sectname, "__objc_classrefs", 16) == 0 ||
2345 strncmp(Sec.sectname, "__objc_superrefs", 16) == 0 ||
2346 strncmp(Sec.sectname, "__objc_msgrefs", 16) == 0 ||
2347 strncmp(Sec.sectname, "__cfstring", 16) == 0) &&
2348 ReferenceValue >= Sec.addr &&
2349 ReferenceValue < Sec.addr + Sec.size) {
2350 uint64_t sect_offset = ReferenceValue - Sec.addr;
2351 uint64_t object_offset = Sec.offset + sect_offset;
2352 StringRef MachOContents = info->O->getData();
2353 uint64_t object_size = MachOContents.size();
2354 const char *object_addr = (const char *)MachOContents.data();
2355 if (object_offset < object_size) {
2356 uint64_t pointer_value;
2357 memcpy(&pointer_value, object_addr + object_offset,
2359 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
2360 sys::swapByteOrder(pointer_value);
2361 if (strncmp(Sec.sectname, "__objc_selrefs", 16) == 0)
2363 else if (strncmp(Sec.sectname, "__objc_classrefs", 16) == 0 ||
2364 strncmp(Sec.sectname, "__objc_superrefs", 16) == 0)
2366 else if (strncmp(Sec.sectname, "__objc_msgrefs", 16) == 0 &&
2367 ReferenceValue + 8 < Sec.addr + Sec.size) {
2369 memcpy(&pointer_value, object_addr + object_offset + 8,
2371 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
2372 sys::swapByteOrder(pointer_value);
2373 } else if (strncmp(Sec.sectname, "__cfstring", 16) == 0)
2375 return pointer_value;
2382 // TODO: Look for LC_SEGMENT for 32-bit Mach-O files.
2383 if (I == LoadCommandCount - 1)
2386 Load = info->O->getNextLoadCommandInfo(Load);
2391 // get_pointer_64 returns a pointer to the bytes in the object file at the
2392 // Address from a section in the Mach-O file. And indirectly returns the
2393 // offset into the section, number of bytes left in the section past the offset
2394 // and which section is was being referenced. If the Address is not in a
2395 // section nullptr is returned.
2396 static const char *get_pointer_64(uint64_t Address, uint32_t &offset,
2397 uint32_t &left, SectionRef &S,
2398 DisassembleInfo *info) {
2402 for (unsigned SectIdx = 0; SectIdx != info->Sections->size(); SectIdx++) {
2403 uint64_t SectAddress = ((*(info->Sections))[SectIdx]).getAddress();
2404 uint64_t SectSize = ((*(info->Sections))[SectIdx]).getSize();
2405 if (Address >= SectAddress && Address < SectAddress + SectSize) {
2406 S = (*(info->Sections))[SectIdx];
2407 offset = Address - SectAddress;
2408 left = SectSize - offset;
2409 StringRef SectContents;
2410 ((*(info->Sections))[SectIdx]).getContents(SectContents);
2411 return SectContents.data() + offset;
2417 // get_symbol_64() returns the name of a symbol (or nullptr) and the address of
2418 // the symbol indirectly through n_value. Based on the relocation information
2419 // for the specified section offset in the specified section reference.
2420 static const char *get_symbol_64(uint32_t sect_offset, SectionRef S,
2421 DisassembleInfo *info, uint64_t &n_value) {
2426 // See if there is an external relocation entry at the sect_offset.
2427 bool reloc_found = false;
2429 MachO::any_relocation_info RE;
2430 bool isExtern = false;
2432 for (const RelocationRef &Reloc : S.relocations()) {
2433 uint64_t RelocOffset;
2434 Reloc.getOffset(RelocOffset);
2435 if (RelocOffset == sect_offset) {
2436 Rel = Reloc.getRawDataRefImpl();
2437 RE = info->O->getRelocation(Rel);
2438 if (info->O->isRelocationScattered(RE))
2440 isExtern = info->O->getPlainRelocationExternal(RE);
2442 symbol_iterator RelocSym = Reloc.getSymbol();
2449 // If there is an external relocation entry for a symbol in this section
2450 // at this section_offset then use that symbol's value for the n_value
2451 // and return its name.
2452 const char *SymbolName = nullptr;
2453 if (reloc_found && isExtern) {
2454 Symbol.getAddress(n_value);
2456 Symbol.getName(name);
2457 if (!name.empty()) {
2458 SymbolName = name.data();
2463 // TODO: For fully linked images, look through the external relocation
2464 // entries off the dynamic symtab command. For these the r_offset is from the
2465 // start of the first writeable segment in the Mach-O file. So the offset
2466 // to this section from that segment is passed to this routine by the caller,
2467 // as the database_offset. Which is the difference of the section's starting
2468 // address and the first writable segment.
2470 // NOTE: need add passing the database_offset to this routine.
2472 // TODO: We did not find an external relocation entry so look up the
2473 // ReferenceValue as an address of a symbol and if found return that symbol's
2476 // NOTE: need add passing the ReferenceValue to this routine. Then that code
2477 // would simply be this:
2478 // SymbolName = GuessSymbolName(ReferenceValue, info->AddrMap);
2483 // These are structs in the Objective-C meta data and read to produce the
2484 // comments for disassembly. While these are part of the ABI they are no
2485 // public defintions. So the are here not in include/llvm/Support/MachO.h .
2487 // The cfstring object in a 64-bit Mach-O file.
2488 struct cfstring64_t {
2489 uint64_t isa; // class64_t * (64-bit pointer)
2490 uint64_t flags; // flag bits
2491 uint64_t characters; // char * (64-bit pointer)
2492 uint64_t length; // number of non-NULL characters in above
2495 // The class object in a 64-bit Mach-O file.
2497 uint64_t isa; // class64_t * (64-bit pointer)
2498 uint64_t superclass; // class64_t * (64-bit pointer)
2499 uint64_t cache; // Cache (64-bit pointer)
2500 uint64_t vtable; // IMP * (64-bit pointer)
2501 uint64_t data; // class_ro64_t * (64-bit pointer)
2504 struct class_ro64_t {
2506 uint32_t instanceStart;
2507 uint32_t instanceSize;
2509 uint64_t ivarLayout; // const uint8_t * (64-bit pointer)
2510 uint64_t name; // const char * (64-bit pointer)
2511 uint64_t baseMethods; // const method_list_t * (64-bit pointer)
2512 uint64_t baseProtocols; // const protocol_list_t * (64-bit pointer)
2513 uint64_t ivars; // const ivar_list_t * (64-bit pointer)
2514 uint64_t weakIvarLayout; // const uint8_t * (64-bit pointer)
2515 uint64_t baseProperties; // const struct objc_property_list (64-bit pointer)
2518 inline void swapStruct(struct cfstring64_t &cfs) {
2519 sys::swapByteOrder(cfs.isa);
2520 sys::swapByteOrder(cfs.flags);
2521 sys::swapByteOrder(cfs.characters);
2522 sys::swapByteOrder(cfs.length);
2525 inline void swapStruct(struct class64_t &c) {
2526 sys::swapByteOrder(c.isa);
2527 sys::swapByteOrder(c.superclass);
2528 sys::swapByteOrder(c.cache);
2529 sys::swapByteOrder(c.vtable);
2530 sys::swapByteOrder(c.data);
2533 inline void swapStruct(struct class_ro64_t &cro) {
2534 sys::swapByteOrder(cro.flags);
2535 sys::swapByteOrder(cro.instanceStart);
2536 sys::swapByteOrder(cro.instanceSize);
2537 sys::swapByteOrder(cro.reserved);
2538 sys::swapByteOrder(cro.ivarLayout);
2539 sys::swapByteOrder(cro.name);
2540 sys::swapByteOrder(cro.baseMethods);
2541 sys::swapByteOrder(cro.baseProtocols);
2542 sys::swapByteOrder(cro.ivars);
2543 sys::swapByteOrder(cro.weakIvarLayout);
2544 sys::swapByteOrder(cro.baseProperties);
2547 static const char *get_dyld_bind_info_symbolname(uint64_t ReferenceValue,
2548 struct DisassembleInfo *info);
2550 // get_objc2_64bit_class_name() is used for disassembly and is passed a pointer
2551 // to an Objective-C class and returns the class name. It is also passed the
2552 // address of the pointer, so when the pointer is zero as it can be in an .o
2553 // file, that is used to look for an external relocation entry with a symbol
2555 static const char *get_objc2_64bit_class_name(uint64_t pointer_value,
2556 uint64_t ReferenceValue,
2557 struct DisassembleInfo *info) {
2559 uint32_t offset, left;
2562 // The pointer_value can be 0 in an object file and have a relocation
2563 // entry for the class symbol at the ReferenceValue (the address of the
2565 if (pointer_value == 0) {
2566 r = get_pointer_64(ReferenceValue, offset, left, S, info);
2567 if (r == nullptr || left < sizeof(uint64_t))
2570 const char *symbol_name = get_symbol_64(offset, S, info, n_value);
2571 if (symbol_name == nullptr)
2573 const char *class_name = strrchr(symbol_name, '$');
2574 if (class_name != nullptr && class_name[1] == '_' && class_name[2] != '\0')
2575 return class_name + 2;
2580 // The case were the pointer_value is non-zero and points to a class defined
2581 // in this Mach-O file.
2582 r = get_pointer_64(pointer_value, offset, left, S, info);
2583 if (r == nullptr || left < sizeof(struct class64_t))
2586 memcpy(&c, r, sizeof(struct class64_t));
2587 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
2591 r = get_pointer_64(c.data, offset, left, S, info);
2592 if (r == nullptr || left < sizeof(struct class_ro64_t))
2594 struct class_ro64_t cro;
2595 memcpy(&cro, r, sizeof(struct class_ro64_t));
2596 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
2600 const char *name = get_pointer_64(cro.name, offset, left, S, info);
2604 // get_objc2_64bit_cfstring_name is used for disassembly and is passed a
2605 // pointer to a cfstring and returns its name or nullptr.
2606 static const char *get_objc2_64bit_cfstring_name(uint64_t ReferenceValue,
2607 struct DisassembleInfo *info) {
2608 const char *r, *name;
2609 uint32_t offset, left;
2611 struct cfstring64_t cfs;
2612 uint64_t cfs_characters;
2614 r = get_pointer_64(ReferenceValue, offset, left, S, info);
2615 if (r == nullptr || left < sizeof(struct cfstring64_t))
2617 memcpy(&cfs, r, sizeof(struct cfstring64_t));
2618 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
2620 if (cfs.characters == 0) {
2622 const char *symbol_name = get_symbol_64(
2623 offset + offsetof(struct cfstring64_t, characters), S, info, n_value);
2624 if (symbol_name == nullptr)
2626 cfs_characters = n_value;
2628 cfs_characters = cfs.characters;
2629 name = get_pointer_64(cfs_characters, offset, left, S, info);
2634 // get_objc2_64bit_selref() is used for disassembly and is passed a the address
2635 // of a pointer to an Objective-C selector reference when the pointer value is
2636 // zero as in a .o file and is likely to have a external relocation entry with
2637 // who's symbol's n_value is the real pointer to the selector name. If that is
2638 // the case the real pointer to the selector name is returned else 0 is
2640 static uint64_t get_objc2_64bit_selref(uint64_t ReferenceValue,
2641 struct DisassembleInfo *info) {
2642 uint32_t offset, left;
2645 const char *r = get_pointer_64(ReferenceValue, offset, left, S, info);
2646 if (r == nullptr || left < sizeof(uint64_t))
2649 const char *symbol_name = get_symbol_64(offset, S, info, n_value);
2650 if (symbol_name == nullptr)
2655 // GuessLiteralPointer returns a string which for the item in the Mach-O file
2656 // for the address passed in as ReferenceValue for printing as a comment with
2657 // the instruction and also returns the corresponding type of that item
2658 // indirectly through ReferenceType.
2660 // If ReferenceValue is an address of literal cstring then a pointer to the
2661 // cstring is returned and ReferenceType is set to
2662 // LLVMDisassembler_ReferenceType_Out_LitPool_CstrAddr .
2664 // If ReferenceValue is an address of an Objective-C CFString, Selector ref or
2665 // Class ref that name is returned and the ReferenceType is set accordingly.
2667 // Lastly, literals which are Symbol address in a literal pool are looked for
2668 // and if found the symbol name is returned and ReferenceType is set to
2669 // LLVMDisassembler_ReferenceType_Out_LitPool_SymAddr .
2671 // If there is no item in the Mach-O file for the address passed in as
2672 // ReferenceValue nullptr is returned and ReferenceType is unchanged.
2673 static const char *GuessLiteralPointer(uint64_t ReferenceValue,
2674 uint64_t ReferencePC,
2675 uint64_t *ReferenceType,
2676 struct DisassembleInfo *info) {
2677 // First see if there is an external relocation entry at the ReferencePC.
2678 uint64_t sect_addr = info->S.getAddress();
2679 uint64_t sect_offset = ReferencePC - sect_addr;
2680 bool reloc_found = false;
2682 MachO::any_relocation_info RE;
2683 bool isExtern = false;
2685 for (const RelocationRef &Reloc : info->S.relocations()) {
2686 uint64_t RelocOffset;
2687 Reloc.getOffset(RelocOffset);
2688 if (RelocOffset == sect_offset) {
2689 Rel = Reloc.getRawDataRefImpl();
2690 RE = info->O->getRelocation(Rel);
2691 if (info->O->isRelocationScattered(RE))
2693 isExtern = info->O->getPlainRelocationExternal(RE);
2695 symbol_iterator RelocSym = Reloc.getSymbol();
2702 // If there is an external relocation entry for a symbol in a section
2703 // then used that symbol's value for the value of the reference.
2704 if (reloc_found && isExtern) {
2705 if (info->O->getAnyRelocationPCRel(RE)) {
2706 unsigned Type = info->O->getAnyRelocationType(RE);
2707 if (Type == MachO::X86_64_RELOC_SIGNED) {
2708 Symbol.getAddress(ReferenceValue);
2713 // Look for literals such as Objective-C CFStrings refs, Selector refs,
2714 // Message refs and Class refs.
2715 bool classref, selref, msgref, cfstring;
2716 uint64_t pointer_value = GuessPointerPointer(ReferenceValue, info, classref,
2717 selref, msgref, cfstring);
2718 if (classref && pointer_value == 0) {
2719 // Note the ReferenceValue is a pointer into the __objc_classrefs section.
2720 // And the pointer_value in that section is typically zero as it will be
2721 // set by dyld as part of the "bind information".
2722 const char *name = get_dyld_bind_info_symbolname(ReferenceValue, info);
2723 if (name != nullptr) {
2724 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Class_Ref;
2725 const char *class_name = strrchr(name, '$');
2726 if (class_name != nullptr && class_name[1] == '_' &&
2727 class_name[2] != '\0') {
2728 info->class_name = class_name + 2;
2735 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Class_Ref;
2737 get_objc2_64bit_class_name(pointer_value, ReferenceValue, info);
2738 if (name != nullptr)
2739 info->class_name = name;
2741 name = "bad class ref";
2746 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_CFString_Ref;
2747 const char *name = get_objc2_64bit_cfstring_name(ReferenceValue, info);
2751 if (selref && pointer_value == 0)
2752 pointer_value = get_objc2_64bit_selref(ReferenceValue, info);
2754 if (pointer_value != 0)
2755 ReferenceValue = pointer_value;
2757 const char *name = GuessCstringPointer(ReferenceValue, info);
2759 if (pointer_value != 0 && selref) {
2760 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Selector_Ref;
2761 info->selector_name = name;
2762 } else if (pointer_value != 0 && msgref) {
2763 info->class_name = nullptr;
2764 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message_Ref;
2765 info->selector_name = name;
2767 *ReferenceType = LLVMDisassembler_ReferenceType_Out_LitPool_CstrAddr;
2771 // Lastly look for an indirect symbol with this ReferenceValue which is in
2772 // a literal pool. If found return that symbol name.
2773 name = GuessIndirectSymbol(ReferenceValue, info);
2775 *ReferenceType = LLVMDisassembler_ReferenceType_Out_LitPool_SymAddr;
2782 // SymbolizerSymbolLookUp is the symbol lookup function passed when creating
2783 // the Symbolizer. It looks up the ReferenceValue using the info passed via the
2784 // pointer to the struct DisassembleInfo that was passed when MCSymbolizer
2785 // is created and returns the symbol name that matches the ReferenceValue or
2786 // nullptr if none. The ReferenceType is passed in for the IN type of
2787 // reference the instruction is making from the values in defined in the header
2788 // "llvm-c/Disassembler.h". On return the ReferenceType can set to a specific
2789 // Out type and the ReferenceName will also be set which is added as a comment
2790 // to the disassembled instruction.
2793 // If the symbol name is a C++ mangled name then the demangled name is
2794 // returned through ReferenceName and ReferenceType is set to
2795 // LLVMDisassembler_ReferenceType_DeMangled_Name .
2798 // When this is called to get a symbol name for a branch target then the
2799 // ReferenceType will be LLVMDisassembler_ReferenceType_In_Branch and then
2800 // SymbolValue will be looked for in the indirect symbol table to determine if
2801 // it is an address for a symbol stub. If so then the symbol name for that
2802 // stub is returned indirectly through ReferenceName and then ReferenceType is
2803 // set to LLVMDisassembler_ReferenceType_Out_SymbolStub.
2805 // When this is called with an value loaded via a PC relative load then
2806 // ReferenceType will be LLVMDisassembler_ReferenceType_In_PCrel_Load then the
2807 // SymbolValue is checked to be an address of literal pointer, symbol pointer,
2808 // or an Objective-C meta data reference. If so the output ReferenceType is
2809 // set to correspond to that as well as setting the ReferenceName.
2810 static const char *SymbolizerSymbolLookUp(void *DisInfo,
2811 uint64_t ReferenceValue,
2812 uint64_t *ReferenceType,
2813 uint64_t ReferencePC,
2814 const char **ReferenceName) {
2815 struct DisassembleInfo *info = (struct DisassembleInfo *)DisInfo;
2816 // If no verbose symbolic information is wanted then just return nullptr.
2817 if (!info->verbose) {
2818 *ReferenceName = nullptr;
2819 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
2823 const char *SymbolName = GuessSymbolName(ReferenceValue, info->AddrMap);
2825 if (*ReferenceType == LLVMDisassembler_ReferenceType_In_Branch) {
2826 *ReferenceName = GuessIndirectSymbol(ReferenceValue, info);
2827 if (*ReferenceName != nullptr) {
2828 method_reference(info, ReferenceType, ReferenceName);
2829 if (*ReferenceType != LLVMDisassembler_ReferenceType_Out_Objc_Message)
2830 *ReferenceType = LLVMDisassembler_ReferenceType_Out_SymbolStub;
2833 if (SymbolName != nullptr && strncmp(SymbolName, "__Z", 3) == 0) {
2834 if (info->demangled_name != nullptr)
2835 free(info->demangled_name);
2837 info->demangled_name =
2838 abi::__cxa_demangle(SymbolName + 1, nullptr, nullptr, &status);
2839 if (info->demangled_name != nullptr) {
2840 *ReferenceName = info->demangled_name;
2841 *ReferenceType = LLVMDisassembler_ReferenceType_DeMangled_Name;
2843 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
2846 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
2847 } else if (*ReferenceType == LLVMDisassembler_ReferenceType_In_PCrel_Load) {
2849 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
2851 method_reference(info, ReferenceType, ReferenceName);
2853 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
2854 // If this is arm64 and the reference is an adrp instruction save the
2855 // instruction, passed in ReferenceValue and the address of the instruction
2856 // for use later if we see and add immediate instruction.
2857 } else if (info->O->getArch() == Triple::aarch64 &&
2858 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADRP) {
2859 info->adrp_inst = ReferenceValue;
2860 info->adrp_addr = ReferencePC;
2861 SymbolName = nullptr;
2862 *ReferenceName = nullptr;
2863 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
2864 // If this is arm64 and reference is an add immediate instruction and we
2866 // seen an adrp instruction just before it and the adrp's Xd register
2868 // this add's Xn register reconstruct the value being referenced and look to
2869 // see if it is a literal pointer. Note the add immediate instruction is
2870 // passed in ReferenceValue.
2871 } else if (info->O->getArch() == Triple::aarch64 &&
2872 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADDXri &&
2873 ReferencePC - 4 == info->adrp_addr &&
2874 (info->adrp_inst & 0x9f000000) == 0x90000000 &&
2875 (info->adrp_inst & 0x1f) == ((ReferenceValue >> 5) & 0x1f)) {
2876 uint32_t addxri_inst;
2877 uint64_t adrp_imm, addxri_imm;
2880 ((info->adrp_inst & 0x00ffffe0) >> 3) | ((info->adrp_inst >> 29) & 0x3);
2881 if (info->adrp_inst & 0x0200000)
2882 adrp_imm |= 0xfffffffffc000000LL;
2884 addxri_inst = ReferenceValue;
2885 addxri_imm = (addxri_inst >> 10) & 0xfff;
2886 if (((addxri_inst >> 22) & 0x3) == 1)
2889 ReferenceValue = (info->adrp_addr & 0xfffffffffffff000LL) +
2890 (adrp_imm << 12) + addxri_imm;
2893 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
2894 if (*ReferenceName == nullptr)
2895 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
2896 // If this is arm64 and the reference is a load register instruction and we
2897 // have seen an adrp instruction just before it and the adrp's Xd register
2898 // matches this add's Xn register reconstruct the value being referenced and
2899 // look to see if it is a literal pointer. Note the load register
2900 // instruction is passed in ReferenceValue.
2901 } else if (info->O->getArch() == Triple::aarch64 &&
2902 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_LDRXui &&
2903 ReferencePC - 4 == info->adrp_addr &&
2904 (info->adrp_inst & 0x9f000000) == 0x90000000 &&
2905 (info->adrp_inst & 0x1f) == ((ReferenceValue >> 5) & 0x1f)) {
2906 uint32_t ldrxui_inst;
2907 uint64_t adrp_imm, ldrxui_imm;
2910 ((info->adrp_inst & 0x00ffffe0) >> 3) | ((info->adrp_inst >> 29) & 0x3);
2911 if (info->adrp_inst & 0x0200000)
2912 adrp_imm |= 0xfffffffffc000000LL;
2914 ldrxui_inst = ReferenceValue;
2915 ldrxui_imm = (ldrxui_inst >> 10) & 0xfff;
2917 ReferenceValue = (info->adrp_addr & 0xfffffffffffff000LL) +
2918 (adrp_imm << 12) + (ldrxui_imm << 3);
2921 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
2922 if (*ReferenceName == nullptr)
2923 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
2925 // If this arm64 and is an load register (PC-relative) instruction the
2926 // ReferenceValue is the PC plus the immediate value.
2927 else if (info->O->getArch() == Triple::aarch64 &&
2928 (*ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_LDRXl ||
2929 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADR)) {
2931 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
2932 if (*ReferenceName == nullptr)
2933 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
2936 else if (SymbolName != nullptr && strncmp(SymbolName, "__Z", 3) == 0) {
2937 if (info->demangled_name != nullptr)
2938 free(info->demangled_name);
2940 info->demangled_name =
2941 abi::__cxa_demangle(SymbolName + 1, nullptr, nullptr, &status);
2942 if (info->demangled_name != nullptr) {
2943 *ReferenceName = info->demangled_name;
2944 *ReferenceType = LLVMDisassembler_ReferenceType_DeMangled_Name;
2949 *ReferenceName = nullptr;
2950 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
2956 /// \brief Emits the comments that are stored in the CommentStream.
2957 /// Each comment in the CommentStream must end with a newline.
2958 static void emitComments(raw_svector_ostream &CommentStream,
2959 SmallString<128> &CommentsToEmit,
2960 formatted_raw_ostream &FormattedOS,
2961 const MCAsmInfo &MAI) {
2962 // Flush the stream before taking its content.
2963 CommentStream.flush();
2964 StringRef Comments = CommentsToEmit.str();
2965 // Get the default information for printing a comment.
2966 const char *CommentBegin = MAI.getCommentString();
2967 unsigned CommentColumn = MAI.getCommentColumn();
2968 bool IsFirst = true;
2969 while (!Comments.empty()) {
2971 FormattedOS << '\n';
2972 // Emit a line of comments.
2973 FormattedOS.PadToColumn(CommentColumn);
2974 size_t Position = Comments.find('\n');
2975 FormattedOS << CommentBegin << ' ' << Comments.substr(0, Position);
2976 // Move after the newline character.
2977 Comments = Comments.substr(Position + 1);
2980 FormattedOS.flush();
2982 // Tell the comment stream that the vector changed underneath it.
2983 CommentsToEmit.clear();
2984 CommentStream.resync();
2987 static void DisassembleMachO(StringRef Filename, MachOObjectFile *MachOOF,
2988 StringRef DisSegName, StringRef DisSectName) {
2989 const char *McpuDefault = nullptr;
2990 const Target *ThumbTarget = nullptr;
2991 const Target *TheTarget = GetTarget(MachOOF, &McpuDefault, &ThumbTarget);
2993 // GetTarget prints out stuff.
2996 if (MCPU.empty() && McpuDefault)
2999 std::unique_ptr<const MCInstrInfo> InstrInfo(TheTarget->createMCInstrInfo());
3000 std::unique_ptr<const MCInstrInfo> ThumbInstrInfo;
3002 ThumbInstrInfo.reset(ThumbTarget->createMCInstrInfo());
3004 // Package up features to be passed to target/subtarget
3005 std::string FeaturesStr;
3006 if (MAttrs.size()) {
3007 SubtargetFeatures Features;
3008 for (unsigned i = 0; i != MAttrs.size(); ++i)
3009 Features.AddFeature(MAttrs[i]);
3010 FeaturesStr = Features.getString();
3013 // Set up disassembler.
3014 std::unique_ptr<const MCRegisterInfo> MRI(
3015 TheTarget->createMCRegInfo(TripleName));
3016 std::unique_ptr<const MCAsmInfo> AsmInfo(
3017 TheTarget->createMCAsmInfo(*MRI, TripleName));
3018 std::unique_ptr<const MCSubtargetInfo> STI(
3019 TheTarget->createMCSubtargetInfo(TripleName, MCPU, FeaturesStr));
3020 MCContext Ctx(AsmInfo.get(), MRI.get(), nullptr);
3021 std::unique_ptr<MCDisassembler> DisAsm(
3022 TheTarget->createMCDisassembler(*STI, Ctx));
3023 std::unique_ptr<MCSymbolizer> Symbolizer;
3024 struct DisassembleInfo SymbolizerInfo;
3025 std::unique_ptr<MCRelocationInfo> RelInfo(
3026 TheTarget->createMCRelocationInfo(TripleName, Ctx));
3028 Symbolizer.reset(TheTarget->createMCSymbolizer(
3029 TripleName, SymbolizerGetOpInfo, SymbolizerSymbolLookUp,
3030 &SymbolizerInfo, &Ctx, std::move(RelInfo)));
3031 DisAsm->setSymbolizer(std::move(Symbolizer));
3033 int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
3034 std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
3035 AsmPrinterVariant, *AsmInfo, *InstrInfo, *MRI, *STI));
3036 // Set the display preference for hex vs. decimal immediates.
3037 IP->setPrintImmHex(PrintImmHex);
3038 // Comment stream and backing vector.
3039 SmallString<128> CommentsToEmit;
3040 raw_svector_ostream CommentStream(CommentsToEmit);
3041 // FIXME: Setting the CommentStream in the InstPrinter is problematic in that
3042 // if it is done then arm64 comments for string literals don't get printed
3043 // and some constant get printed instead and not setting it causes intel
3044 // (32-bit and 64-bit) comments printed with different spacing before the
3045 // comment causing different diffs with the 'C' disassembler library API.
3046 // IP->setCommentStream(CommentStream);
3048 if (!AsmInfo || !STI || !DisAsm || !IP) {
3049 errs() << "error: couldn't initialize disassembler for target "
3050 << TripleName << '\n';
3054 // Set up thumb disassembler.
3055 std::unique_ptr<const MCRegisterInfo> ThumbMRI;
3056 std::unique_ptr<const MCAsmInfo> ThumbAsmInfo;
3057 std::unique_ptr<const MCSubtargetInfo> ThumbSTI;
3058 std::unique_ptr<MCDisassembler> ThumbDisAsm;
3059 std::unique_ptr<MCInstPrinter> ThumbIP;
3060 std::unique_ptr<MCContext> ThumbCtx;
3061 std::unique_ptr<MCSymbolizer> ThumbSymbolizer;
3062 struct DisassembleInfo ThumbSymbolizerInfo;
3063 std::unique_ptr<MCRelocationInfo> ThumbRelInfo;
3065 ThumbMRI.reset(ThumbTarget->createMCRegInfo(ThumbTripleName));
3067 ThumbTarget->createMCAsmInfo(*ThumbMRI, ThumbTripleName));
3069 ThumbTarget->createMCSubtargetInfo(ThumbTripleName, MCPU, FeaturesStr));
3070 ThumbCtx.reset(new MCContext(ThumbAsmInfo.get(), ThumbMRI.get(), nullptr));
3071 ThumbDisAsm.reset(ThumbTarget->createMCDisassembler(*ThumbSTI, *ThumbCtx));
3072 MCContext *PtrThumbCtx = ThumbCtx.get();
3074 ThumbTarget->createMCRelocationInfo(ThumbTripleName, *PtrThumbCtx));
3076 ThumbSymbolizer.reset(ThumbTarget->createMCSymbolizer(
3077 ThumbTripleName, SymbolizerGetOpInfo, SymbolizerSymbolLookUp,
3078 &ThumbSymbolizerInfo, PtrThumbCtx, std::move(ThumbRelInfo)));
3079 ThumbDisAsm->setSymbolizer(std::move(ThumbSymbolizer));
3081 int ThumbAsmPrinterVariant = ThumbAsmInfo->getAssemblerDialect();
3082 ThumbIP.reset(ThumbTarget->createMCInstPrinter(
3083 ThumbAsmPrinterVariant, *ThumbAsmInfo, *ThumbInstrInfo, *ThumbMRI,
3085 // Set the display preference for hex vs. decimal immediates.
3086 ThumbIP->setPrintImmHex(PrintImmHex);
3089 if (ThumbTarget && (!ThumbAsmInfo || !ThumbSTI || !ThumbDisAsm || !ThumbIP)) {
3090 errs() << "error: couldn't initialize disassembler for target "
3091 << ThumbTripleName << '\n';
3095 MachO::mach_header Header = MachOOF->getHeader();
3097 // FIXME: Using the -cfg command line option, this code used to be able to
3098 // annotate relocations with the referenced symbol's name, and if this was
3099 // inside a __[cf]string section, the data it points to. This is now replaced
3100 // by the upcoming MCSymbolizer, which needs the appropriate setup done above.
3101 std::vector<SectionRef> Sections;
3102 std::vector<SymbolRef> Symbols;
3103 SmallVector<uint64_t, 8> FoundFns;
3104 uint64_t BaseSegmentAddress;
3106 getSectionsAndSymbols(Header, MachOOF, Sections, Symbols, FoundFns,
3107 BaseSegmentAddress);
3109 // Sort the symbols by address, just in case they didn't come in that way.
3110 std::sort(Symbols.begin(), Symbols.end(), SymbolSorter());
3112 // Build a data in code table that is sorted on by the address of each entry.
3113 uint64_t BaseAddress = 0;
3114 if (Header.filetype == MachO::MH_OBJECT)
3115 BaseAddress = Sections[0].getAddress();
3117 BaseAddress = BaseSegmentAddress;
3119 for (dice_iterator DI = MachOOF->begin_dices(), DE = MachOOF->end_dices();
3122 DI->getOffset(Offset);
3123 Dices.push_back(std::make_pair(BaseAddress + Offset, *DI));
3125 array_pod_sort(Dices.begin(), Dices.end());
3128 raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls();
3130 raw_ostream &DebugOut = nulls();
3133 std::unique_ptr<DIContext> diContext;
3134 ObjectFile *DbgObj = MachOOF;
3135 // Try to find debug info and set up the DIContext for it.
3137 // A separate DSym file path was specified, parse it as a macho file,
3138 // get the sections and supply it to the section name parsing machinery.
3139 if (!DSYMFile.empty()) {
3140 ErrorOr<std::unique_ptr<MemoryBuffer>> BufOrErr =
3141 MemoryBuffer::getFileOrSTDIN(DSYMFile);
3142 if (std::error_code EC = BufOrErr.getError()) {
3143 errs() << "llvm-objdump: " << Filename << ": " << EC.message() << '\n';
3147 ObjectFile::createMachOObjectFile(BufOrErr.get()->getMemBufferRef())
3152 // Setup the DIContext
3153 diContext.reset(DIContext::getDWARFContext(*DbgObj));
3156 if (DumpSections.size() == 0)
3157 outs() << "(" << DisSegName << "," << DisSectName << ") section\n";
3159 for (unsigned SectIdx = 0; SectIdx != Sections.size(); SectIdx++) {
3161 if (Sections[SectIdx].getName(SectName) || SectName != DisSectName)
3164 DataRefImpl DR = Sections[SectIdx].getRawDataRefImpl();
3166 StringRef SegmentName = MachOOF->getSectionFinalSegmentName(DR);
3167 if (SegmentName != DisSegName)
3171 Sections[SectIdx].getContents(BytesStr);
3172 ArrayRef<uint8_t> Bytes(reinterpret_cast<const uint8_t *>(BytesStr.data()),
3174 uint64_t SectAddress = Sections[SectIdx].getAddress();
3176 bool symbolTableWorked = false;
3178 // Parse relocations.
3179 std::vector<std::pair<uint64_t, SymbolRef>> Relocs;
3180 for (const RelocationRef &Reloc : Sections[SectIdx].relocations()) {
3181 uint64_t RelocOffset;
3182 Reloc.getOffset(RelocOffset);
3183 uint64_t SectionAddress = Sections[SectIdx].getAddress();
3184 RelocOffset -= SectionAddress;
3186 symbol_iterator RelocSym = Reloc.getSymbol();
3188 Relocs.push_back(std::make_pair(RelocOffset, *RelocSym));
3190 array_pod_sort(Relocs.begin(), Relocs.end());
3192 // Create a map of symbol addresses to symbol names for use by
3193 // the SymbolizerSymbolLookUp() routine.
3194 SymbolAddressMap AddrMap;
3195 bool DisSymNameFound = false;
3196 for (const SymbolRef &Symbol : MachOOF->symbols()) {
3199 if (ST == SymbolRef::ST_Function || ST == SymbolRef::ST_Data ||
3200 ST == SymbolRef::ST_Other) {
3202 Symbol.getAddress(Address);
3204 Symbol.getName(SymName);
3205 AddrMap[Address] = SymName;
3206 if (!DisSymName.empty() && DisSymName == SymName)
3207 DisSymNameFound = true;
3210 if (!DisSymName.empty() && !DisSymNameFound) {
3211 outs() << "Can't find -dis-symname: " << DisSymName << "\n";
3214 // Set up the block of info used by the Symbolizer call backs.
3215 SymbolizerInfo.verbose = !NoSymbolicOperands;
3216 SymbolizerInfo.O = MachOOF;
3217 SymbolizerInfo.S = Sections[SectIdx];
3218 SymbolizerInfo.AddrMap = &AddrMap;
3219 SymbolizerInfo.Sections = &Sections;
3220 SymbolizerInfo.class_name = nullptr;
3221 SymbolizerInfo.selector_name = nullptr;
3222 SymbolizerInfo.method = nullptr;
3223 SymbolizerInfo.demangled_name = nullptr;
3224 SymbolizerInfo.bindtable = nullptr;
3225 SymbolizerInfo.adrp_addr = 0;
3226 SymbolizerInfo.adrp_inst = 0;
3227 // Same for the ThumbSymbolizer
3228 ThumbSymbolizerInfo.verbose = !NoSymbolicOperands;
3229 ThumbSymbolizerInfo.O = MachOOF;
3230 ThumbSymbolizerInfo.S = Sections[SectIdx];
3231 ThumbSymbolizerInfo.AddrMap = &AddrMap;
3232 ThumbSymbolizerInfo.Sections = &Sections;
3233 ThumbSymbolizerInfo.class_name = nullptr;
3234 ThumbSymbolizerInfo.selector_name = nullptr;
3235 ThumbSymbolizerInfo.method = nullptr;
3236 ThumbSymbolizerInfo.demangled_name = nullptr;
3237 ThumbSymbolizerInfo.bindtable = nullptr;
3238 ThumbSymbolizerInfo.adrp_addr = 0;
3239 ThumbSymbolizerInfo.adrp_inst = 0;
3241 // Disassemble symbol by symbol.
3242 for (unsigned SymIdx = 0; SymIdx != Symbols.size(); SymIdx++) {
3244 Symbols[SymIdx].getName(SymName);
3247 Symbols[SymIdx].getType(ST);
3248 if (ST != SymbolRef::ST_Function)
3251 // Make sure the symbol is defined in this section.
3252 bool containsSym = Sections[SectIdx].containsSymbol(Symbols[SymIdx]);
3256 // If we are only disassembling one symbol see if this is that symbol.
3257 if (!DisSymName.empty() && DisSymName != SymName)
3260 // Start at the address of the symbol relative to the section's address.
3262 uint64_t SectionAddress = Sections[SectIdx].getAddress();
3263 Symbols[SymIdx].getAddress(Start);
3264 Start -= SectionAddress;
3266 // Stop disassembling either at the beginning of the next symbol or at
3267 // the end of the section.
3268 bool containsNextSym = false;
3269 uint64_t NextSym = 0;
3270 uint64_t NextSymIdx = SymIdx + 1;
3271 while (Symbols.size() > NextSymIdx) {
3272 SymbolRef::Type NextSymType;
3273 Symbols[NextSymIdx].getType(NextSymType);
3274 if (NextSymType == SymbolRef::ST_Function) {
3276 Sections[SectIdx].containsSymbol(Symbols[NextSymIdx]);
3277 Symbols[NextSymIdx].getAddress(NextSym);
3278 NextSym -= SectionAddress;
3284 uint64_t SectSize = Sections[SectIdx].getSize();
3285 uint64_t End = containsNextSym ? NextSym : SectSize;
3288 symbolTableWorked = true;
3290 DataRefImpl Symb = Symbols[SymIdx].getRawDataRefImpl();
3292 (MachOOF->getSymbolFlags(Symb) & SymbolRef::SF_Thumb) && ThumbTarget;
3294 outs() << SymName << ":\n";
3295 DILineInfo lastLine;
3296 for (uint64_t Index = Start; Index < End; Index += Size) {
3299 uint64_t PC = SectAddress + Index;
3300 if (!NoLeadingAddr) {
3301 if (FullLeadingAddr) {
3302 if (MachOOF->is64Bit())
3303 outs() << format("%016" PRIx64, PC);
3305 outs() << format("%08" PRIx64, PC);
3307 outs() << format("%8" PRIx64 ":", PC);
3313 // Check the data in code table here to see if this is data not an
3314 // instruction to be disassembled.
3316 Dice.push_back(std::make_pair(PC, DiceRef()));
3317 dice_table_iterator DTI =
3318 std::search(Dices.begin(), Dices.end(), Dice.begin(), Dice.end(),
3319 compareDiceTableEntries);
3320 if (DTI != Dices.end()) {
3322 DTI->second.getLength(Length);
3324 DTI->second.getKind(Kind);
3325 Size = DumpDataInCode(Bytes.data() + Index, Length, Kind);
3326 if ((Kind == MachO::DICE_KIND_JUMP_TABLE8) &&
3327 (PC == (DTI->first + Length - 1)) && (Length & 1))
3332 SmallVector<char, 64> AnnotationsBytes;
3333 raw_svector_ostream Annotations(AnnotationsBytes);
3337 gotInst = ThumbDisAsm->getInstruction(Inst, Size, Bytes.slice(Index),
3338 PC, DebugOut, Annotations);
3340 gotInst = DisAsm->getInstruction(Inst, Size, Bytes.slice(Index), PC,
3341 DebugOut, Annotations);
3343 if (!NoShowRawInsn) {
3344 DumpBytes(ArrayRef<uint8_t>(Bytes.data() + Index, Size));
3346 formatted_raw_ostream FormattedOS(outs());
3347 Annotations.flush();
3348 StringRef AnnotationsStr = Annotations.str();
3350 ThumbIP->printInst(&Inst, FormattedOS, AnnotationsStr, *ThumbSTI);
3352 IP->printInst(&Inst, FormattedOS, AnnotationsStr, *STI);
3353 emitComments(CommentStream, CommentsToEmit, FormattedOS, *AsmInfo);
3355 // Print debug info.
3357 DILineInfo dli = diContext->getLineInfoForAddress(PC);
3358 // Print valid line info if it changed.
3359 if (dli != lastLine && dli.Line != 0)
3360 outs() << "\t## " << dli.FileName << ':' << dli.Line << ':'
3366 unsigned int Arch = MachOOF->getArch();
3367 if (Arch == Triple::x86_64 || Arch == Triple::x86) {
3368 outs() << format("\t.byte 0x%02x #bad opcode\n",
3369 *(Bytes.data() + Index) & 0xff);
3370 Size = 1; // skip exactly one illegible byte and move on.
3371 } else if (Arch == Triple::aarch64) {
3372 uint32_t opcode = (*(Bytes.data() + Index) & 0xff) |
3373 (*(Bytes.data() + Index + 1) & 0xff) << 8 |
3374 (*(Bytes.data() + Index + 2) & 0xff) << 16 |
3375 (*(Bytes.data() + Index + 3) & 0xff) << 24;
3376 outs() << format("\t.long\t0x%08x\n", opcode);
3379 errs() << "llvm-objdump: warning: invalid instruction encoding\n";
3381 Size = 1; // skip illegible bytes
3386 if (!symbolTableWorked) {
3387 // Reading the symbol table didn't work, disassemble the whole section.
3388 uint64_t SectAddress = Sections[SectIdx].getAddress();
3389 uint64_t SectSize = Sections[SectIdx].getSize();
3391 for (uint64_t Index = 0; Index < SectSize; Index += InstSize) {
3394 uint64_t PC = SectAddress + Index;
3395 if (DisAsm->getInstruction(Inst, InstSize, Bytes.slice(Index), PC,
3396 DebugOut, nulls())) {
3397 if (!NoLeadingAddr) {
3398 if (FullLeadingAddr) {
3399 if (MachOOF->is64Bit())
3400 outs() << format("%016" PRIx64, PC);
3402 outs() << format("%08" PRIx64, PC);
3404 outs() << format("%8" PRIx64 ":", PC);
3407 if (!NoShowRawInsn) {
3409 DumpBytes(ArrayRef<uint8_t>(Bytes.data() + Index, InstSize));
3411 IP->printInst(&Inst, outs(), "", *STI);
3414 unsigned int Arch = MachOOF->getArch();
3415 if (Arch == Triple::x86_64 || Arch == Triple::x86) {
3416 outs() << format("\t.byte 0x%02x #bad opcode\n",
3417 *(Bytes.data() + Index) & 0xff);
3418 InstSize = 1; // skip exactly one illegible byte and move on.
3420 errs() << "llvm-objdump: warning: invalid instruction encoding\n";
3422 InstSize = 1; // skip illegible bytes
3427 // The TripleName's need to be reset if we are called again for a different
3430 ThumbTripleName = "";
3432 if (SymbolizerInfo.method != nullptr)
3433 free(SymbolizerInfo.method);
3434 if (SymbolizerInfo.demangled_name != nullptr)
3435 free(SymbolizerInfo.demangled_name);
3436 if (SymbolizerInfo.bindtable != nullptr)
3437 delete SymbolizerInfo.bindtable;
3438 if (ThumbSymbolizerInfo.method != nullptr)
3439 free(ThumbSymbolizerInfo.method);
3440 if (ThumbSymbolizerInfo.demangled_name != nullptr)
3441 free(ThumbSymbolizerInfo.demangled_name);
3442 if (ThumbSymbolizerInfo.bindtable != nullptr)
3443 delete ThumbSymbolizerInfo.bindtable;
3447 //===----------------------------------------------------------------------===//
3448 // __compact_unwind section dumping
3449 //===----------------------------------------------------------------------===//
3453 template <typename T> static uint64_t readNext(const char *&Buf) {
3454 using llvm::support::little;
3455 using llvm::support::unaligned;
3457 uint64_t Val = support::endian::read<T, little, unaligned>(Buf);
3462 struct CompactUnwindEntry {
3463 uint32_t OffsetInSection;
3465 uint64_t FunctionAddr;
3467 uint32_t CompactEncoding;
3468 uint64_t PersonalityAddr;
3471 RelocationRef FunctionReloc;
3472 RelocationRef PersonalityReloc;
3473 RelocationRef LSDAReloc;
3475 CompactUnwindEntry(StringRef Contents, unsigned Offset, bool Is64)
3476 : OffsetInSection(Offset) {
3478 read<uint64_t>(Contents.data() + Offset);
3480 read<uint32_t>(Contents.data() + Offset);
3484 template <typename UIntPtr> void read(const char *Buf) {
3485 FunctionAddr = readNext<UIntPtr>(Buf);
3486 Length = readNext<uint32_t>(Buf);
3487 CompactEncoding = readNext<uint32_t>(Buf);
3488 PersonalityAddr = readNext<UIntPtr>(Buf);
3489 LSDAAddr = readNext<UIntPtr>(Buf);
3494 /// Given a relocation from __compact_unwind, consisting of the RelocationRef
3495 /// and data being relocated, determine the best base Name and Addend to use for
3496 /// display purposes.
3498 /// 1. An Extern relocation will directly reference a symbol (and the data is
3499 /// then already an addend), so use that.
3500 /// 2. Otherwise the data is an offset in the object file's layout; try to find
3501 // a symbol before it in the same section, and use the offset from there.
3502 /// 3. Finally, if all that fails, fall back to an offset from the start of the
3503 /// referenced section.
3504 static void findUnwindRelocNameAddend(const MachOObjectFile *Obj,
3505 std::map<uint64_t, SymbolRef> &Symbols,
3506 const RelocationRef &Reloc, uint64_t Addr,
3507 StringRef &Name, uint64_t &Addend) {
3508 if (Reloc.getSymbol() != Obj->symbol_end()) {
3509 Reloc.getSymbol()->getName(Name);
3514 auto RE = Obj->getRelocation(Reloc.getRawDataRefImpl());
3515 SectionRef RelocSection = Obj->getRelocationSection(RE);
3517 uint64_t SectionAddr = RelocSection.getAddress();
3519 auto Sym = Symbols.upper_bound(Addr);
3520 if (Sym == Symbols.begin()) {
3521 // The first symbol in the object is after this reference, the best we can
3522 // do is section-relative notation.
3523 RelocSection.getName(Name);
3524 Addend = Addr - SectionAddr;
3528 // Go back one so that SymbolAddress <= Addr.
3531 section_iterator SymSection = Obj->section_end();
3532 Sym->second.getSection(SymSection);
3533 if (RelocSection == *SymSection) {
3534 // There's a valid symbol in the same section before this reference.
3535 Sym->second.getName(Name);
3536 Addend = Addr - Sym->first;
3540 // There is a symbol before this reference, but it's in a different
3541 // section. Probably not helpful to mention it, so use the section name.
3542 RelocSection.getName(Name);
3543 Addend = Addr - SectionAddr;
3546 static void printUnwindRelocDest(const MachOObjectFile *Obj,
3547 std::map<uint64_t, SymbolRef> &Symbols,
3548 const RelocationRef &Reloc, uint64_t Addr) {
3552 if (!Reloc.getObjectFile())
3555 findUnwindRelocNameAddend(Obj, Symbols, Reloc, Addr, Name, Addend);
3559 outs() << " + " << format("0x%" PRIx64, Addend);
3563 printMachOCompactUnwindSection(const MachOObjectFile *Obj,
3564 std::map<uint64_t, SymbolRef> &Symbols,
3565 const SectionRef &CompactUnwind) {
3567 assert(Obj->isLittleEndian() &&
3568 "There should not be a big-endian .o with __compact_unwind");
3570 bool Is64 = Obj->is64Bit();
3571 uint32_t PointerSize = Is64 ? sizeof(uint64_t) : sizeof(uint32_t);
3572 uint32_t EntrySize = 3 * PointerSize + 2 * sizeof(uint32_t);
3575 CompactUnwind.getContents(Contents);
3577 SmallVector<CompactUnwindEntry, 4> CompactUnwinds;
3579 // First populate the initial raw offsets, encodings and so on from the entry.
3580 for (unsigned Offset = 0; Offset < Contents.size(); Offset += EntrySize) {
3581 CompactUnwindEntry Entry(Contents.data(), Offset, Is64);
3582 CompactUnwinds.push_back(Entry);
3585 // Next we need to look at the relocations to find out what objects are
3586 // actually being referred to.
3587 for (const RelocationRef &Reloc : CompactUnwind.relocations()) {
3588 uint64_t RelocAddress;
3589 Reloc.getOffset(RelocAddress);
3591 uint32_t EntryIdx = RelocAddress / EntrySize;
3592 uint32_t OffsetInEntry = RelocAddress - EntryIdx * EntrySize;
3593 CompactUnwindEntry &Entry = CompactUnwinds[EntryIdx];
3595 if (OffsetInEntry == 0)
3596 Entry.FunctionReloc = Reloc;
3597 else if (OffsetInEntry == PointerSize + 2 * sizeof(uint32_t))
3598 Entry.PersonalityReloc = Reloc;
3599 else if (OffsetInEntry == 2 * PointerSize + 2 * sizeof(uint32_t))
3600 Entry.LSDAReloc = Reloc;
3602 llvm_unreachable("Unexpected relocation in __compact_unwind section");
3605 // Finally, we're ready to print the data we've gathered.
3606 outs() << "Contents of __compact_unwind section:\n";
3607 for (auto &Entry : CompactUnwinds) {
3608 outs() << " Entry at offset "
3609 << format("0x%" PRIx32, Entry.OffsetInSection) << ":\n";
3611 // 1. Start of the region this entry applies to.
3612 outs() << " start: " << format("0x%" PRIx64,
3613 Entry.FunctionAddr) << ' ';
3614 printUnwindRelocDest(Obj, Symbols, Entry.FunctionReloc, Entry.FunctionAddr);
3617 // 2. Length of the region this entry applies to.
3618 outs() << " length: " << format("0x%" PRIx32, Entry.Length)
3620 // 3. The 32-bit compact encoding.
3621 outs() << " compact encoding: "
3622 << format("0x%08" PRIx32, Entry.CompactEncoding) << '\n';
3624 // 4. The personality function, if present.
3625 if (Entry.PersonalityReloc.getObjectFile()) {
3626 outs() << " personality function: "
3627 << format("0x%" PRIx64, Entry.PersonalityAddr) << ' ';
3628 printUnwindRelocDest(Obj, Symbols, Entry.PersonalityReloc,
3629 Entry.PersonalityAddr);
3633 // 5. This entry's language-specific data area.
3634 if (Entry.LSDAReloc.getObjectFile()) {
3635 outs() << " LSDA: " << format("0x%" PRIx64,
3636 Entry.LSDAAddr) << ' ';
3637 printUnwindRelocDest(Obj, Symbols, Entry.LSDAReloc, Entry.LSDAAddr);
3643 //===----------------------------------------------------------------------===//
3644 // __unwind_info section dumping
3645 //===----------------------------------------------------------------------===//
3647 static void printRegularSecondLevelUnwindPage(const char *PageStart) {
3648 const char *Pos = PageStart;
3649 uint32_t Kind = readNext<uint32_t>(Pos);
3651 assert(Kind == 2 && "kind for a regular 2nd level index should be 2");
3653 uint16_t EntriesStart = readNext<uint16_t>(Pos);
3654 uint16_t NumEntries = readNext<uint16_t>(Pos);
3656 Pos = PageStart + EntriesStart;
3657 for (unsigned i = 0; i < NumEntries; ++i) {
3658 uint32_t FunctionOffset = readNext<uint32_t>(Pos);
3659 uint32_t Encoding = readNext<uint32_t>(Pos);
3661 outs() << " [" << i << "]: "
3662 << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
3664 << "encoding=" << format("0x%08" PRIx32, Encoding) << '\n';
3668 static void printCompressedSecondLevelUnwindPage(
3669 const char *PageStart, uint32_t FunctionBase,
3670 const SmallVectorImpl<uint32_t> &CommonEncodings) {
3671 const char *Pos = PageStart;
3672 uint32_t Kind = readNext<uint32_t>(Pos);
3674 assert(Kind == 3 && "kind for a compressed 2nd level index should be 3");
3676 uint16_t EntriesStart = readNext<uint16_t>(Pos);
3677 uint16_t NumEntries = readNext<uint16_t>(Pos);
3679 uint16_t EncodingsStart = readNext<uint16_t>(Pos);
3680 readNext<uint16_t>(Pos);
3681 const auto *PageEncodings = reinterpret_cast<const support::ulittle32_t *>(
3682 PageStart + EncodingsStart);
3684 Pos = PageStart + EntriesStart;
3685 for (unsigned i = 0; i < NumEntries; ++i) {
3686 uint32_t Entry = readNext<uint32_t>(Pos);
3687 uint32_t FunctionOffset = FunctionBase + (Entry & 0xffffff);
3688 uint32_t EncodingIdx = Entry >> 24;
3691 if (EncodingIdx < CommonEncodings.size())
3692 Encoding = CommonEncodings[EncodingIdx];
3694 Encoding = PageEncodings[EncodingIdx - CommonEncodings.size()];
3696 outs() << " [" << i << "]: "
3697 << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
3699 << "encoding[" << EncodingIdx
3700 << "]=" << format("0x%08" PRIx32, Encoding) << '\n';
3704 static void printMachOUnwindInfoSection(const MachOObjectFile *Obj,
3705 std::map<uint64_t, SymbolRef> &Symbols,
3706 const SectionRef &UnwindInfo) {
3708 assert(Obj->isLittleEndian() &&
3709 "There should not be a big-endian .o with __unwind_info");
3711 outs() << "Contents of __unwind_info section:\n";
3714 UnwindInfo.getContents(Contents);
3715 const char *Pos = Contents.data();
3717 //===----------------------------------
3719 //===----------------------------------
3721 uint32_t Version = readNext<uint32_t>(Pos);
3722 outs() << " Version: "
3723 << format("0x%" PRIx32, Version) << '\n';
3724 assert(Version == 1 && "only understand version 1");
3726 uint32_t CommonEncodingsStart = readNext<uint32_t>(Pos);
3727 outs() << " Common encodings array section offset: "
3728 << format("0x%" PRIx32, CommonEncodingsStart) << '\n';
3729 uint32_t NumCommonEncodings = readNext<uint32_t>(Pos);
3730 outs() << " Number of common encodings in array: "
3731 << format("0x%" PRIx32, NumCommonEncodings) << '\n';
3733 uint32_t PersonalitiesStart = readNext<uint32_t>(Pos);
3734 outs() << " Personality function array section offset: "
3735 << format("0x%" PRIx32, PersonalitiesStart) << '\n';
3736 uint32_t NumPersonalities = readNext<uint32_t>(Pos);
3737 outs() << " Number of personality functions in array: "
3738 << format("0x%" PRIx32, NumPersonalities) << '\n';
3740 uint32_t IndicesStart = readNext<uint32_t>(Pos);
3741 outs() << " Index array section offset: "
3742 << format("0x%" PRIx32, IndicesStart) << '\n';
3743 uint32_t NumIndices = readNext<uint32_t>(Pos);
3744 outs() << " Number of indices in array: "
3745 << format("0x%" PRIx32, NumIndices) << '\n';
3747 //===----------------------------------
3748 // A shared list of common encodings
3749 //===----------------------------------
3751 // These occupy indices in the range [0, N] whenever an encoding is referenced
3752 // from a compressed 2nd level index table. In practice the linker only
3753 // creates ~128 of these, so that indices are available to embed encodings in
3754 // the 2nd level index.
3756 SmallVector<uint32_t, 64> CommonEncodings;
3757 outs() << " Common encodings: (count = " << NumCommonEncodings << ")\n";
3758 Pos = Contents.data() + CommonEncodingsStart;
3759 for (unsigned i = 0; i < NumCommonEncodings; ++i) {
3760 uint32_t Encoding = readNext<uint32_t>(Pos);
3761 CommonEncodings.push_back(Encoding);
3763 outs() << " encoding[" << i << "]: " << format("0x%08" PRIx32, Encoding)
3767 //===----------------------------------
3768 // Personality functions used in this executable
3769 //===----------------------------------
3771 // There should be only a handful of these (one per source language,
3772 // roughly). Particularly since they only get 2 bits in the compact encoding.
3774 outs() << " Personality functions: (count = " << NumPersonalities << ")\n";
3775 Pos = Contents.data() + PersonalitiesStart;
3776 for (unsigned i = 0; i < NumPersonalities; ++i) {
3777 uint32_t PersonalityFn = readNext<uint32_t>(Pos);
3778 outs() << " personality[" << i + 1
3779 << "]: " << format("0x%08" PRIx32, PersonalityFn) << '\n';
3782 //===----------------------------------
3783 // The level 1 index entries
3784 //===----------------------------------
3786 // These specify an approximate place to start searching for the more detailed
3787 // information, sorted by PC.
3790 uint32_t FunctionOffset;
3791 uint32_t SecondLevelPageStart;
3795 SmallVector<IndexEntry, 4> IndexEntries;
3797 outs() << " Top level indices: (count = " << NumIndices << ")\n";
3798 Pos = Contents.data() + IndicesStart;
3799 for (unsigned i = 0; i < NumIndices; ++i) {
3802 Entry.FunctionOffset = readNext<uint32_t>(Pos);
3803 Entry.SecondLevelPageStart = readNext<uint32_t>(Pos);
3804 Entry.LSDAStart = readNext<uint32_t>(Pos);
3805 IndexEntries.push_back(Entry);
3807 outs() << " [" << i << "]: "
3808 << "function offset=" << format("0x%08" PRIx32, Entry.FunctionOffset)
3810 << "2nd level page offset="
3811 << format("0x%08" PRIx32, Entry.SecondLevelPageStart) << ", "
3812 << "LSDA offset=" << format("0x%08" PRIx32, Entry.LSDAStart) << '\n';
3815 //===----------------------------------
3816 // Next come the LSDA tables
3817 //===----------------------------------
3819 // The LSDA layout is rather implicit: it's a contiguous array of entries from
3820 // the first top-level index's LSDAOffset to the last (sentinel).
3822 outs() << " LSDA descriptors:\n";
3823 Pos = Contents.data() + IndexEntries[0].LSDAStart;
3824 int NumLSDAs = (IndexEntries.back().LSDAStart - IndexEntries[0].LSDAStart) /
3825 (2 * sizeof(uint32_t));
3826 for (int i = 0; i < NumLSDAs; ++i) {
3827 uint32_t FunctionOffset = readNext<uint32_t>(Pos);
3828 uint32_t LSDAOffset = readNext<uint32_t>(Pos);
3829 outs() << " [" << i << "]: "
3830 << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
3832 << "LSDA offset=" << format("0x%08" PRIx32, LSDAOffset) << '\n';
3835 //===----------------------------------
3836 // Finally, the 2nd level indices
3837 //===----------------------------------
3839 // Generally these are 4K in size, and have 2 possible forms:
3840 // + Regular stores up to 511 entries with disparate encodings
3841 // + Compressed stores up to 1021 entries if few enough compact encoding
3843 outs() << " Second level indices:\n";
3844 for (unsigned i = 0; i < IndexEntries.size() - 1; ++i) {
3845 // The final sentinel top-level index has no associated 2nd level page
3846 if (IndexEntries[i].SecondLevelPageStart == 0)
3849 outs() << " Second level index[" << i << "]: "
3850 << "offset in section="
3851 << format("0x%08" PRIx32, IndexEntries[i].SecondLevelPageStart)
3853 << "base function offset="
3854 << format("0x%08" PRIx32, IndexEntries[i].FunctionOffset) << '\n';
3856 Pos = Contents.data() + IndexEntries[i].SecondLevelPageStart;
3857 uint32_t Kind = *reinterpret_cast<const support::ulittle32_t *>(Pos);
3859 printRegularSecondLevelUnwindPage(Pos);
3861 printCompressedSecondLevelUnwindPage(Pos, IndexEntries[i].FunctionOffset,
3864 llvm_unreachable("Do not know how to print this kind of 2nd level page");
3868 void llvm::printMachOUnwindInfo(const MachOObjectFile *Obj) {
3869 std::map<uint64_t, SymbolRef> Symbols;
3870 for (const SymbolRef &SymRef : Obj->symbols()) {
3871 // Discard any undefined or absolute symbols. They're not going to take part
3872 // in the convenience lookup for unwind info and just take up resources.
3873 section_iterator Section = Obj->section_end();
3874 SymRef.getSection(Section);
3875 if (Section == Obj->section_end())
3879 SymRef.getAddress(Addr);
3880 Symbols.insert(std::make_pair(Addr, SymRef));
3883 for (const SectionRef &Section : Obj->sections()) {
3885 Section.getName(SectName);
3886 if (SectName == "__compact_unwind")
3887 printMachOCompactUnwindSection(Obj, Symbols, Section);
3888 else if (SectName == "__unwind_info")
3889 printMachOUnwindInfoSection(Obj, Symbols, Section);
3890 else if (SectName == "__eh_frame")
3891 outs() << "llvm-objdump: warning: unhandled __eh_frame section\n";
3895 static void PrintMachHeader(uint32_t magic, uint32_t cputype,
3896 uint32_t cpusubtype, uint32_t filetype,
3897 uint32_t ncmds, uint32_t sizeofcmds, uint32_t flags,
3899 outs() << "Mach header\n";
3900 outs() << " magic cputype cpusubtype caps filetype ncmds "
3901 "sizeofcmds flags\n";
3903 if (magic == MachO::MH_MAGIC)
3904 outs() << " MH_MAGIC";
3905 else if (magic == MachO::MH_MAGIC_64)
3906 outs() << "MH_MAGIC_64";
3908 outs() << format(" 0x%08" PRIx32, magic);
3910 case MachO::CPU_TYPE_I386:
3912 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
3913 case MachO::CPU_SUBTYPE_I386_ALL:
3917 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
3921 case MachO::CPU_TYPE_X86_64:
3922 outs() << " X86_64";
3923 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
3924 case MachO::CPU_SUBTYPE_X86_64_ALL:
3927 case MachO::CPU_SUBTYPE_X86_64_H:
3928 outs() << " Haswell";
3931 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
3935 case MachO::CPU_TYPE_ARM:
3937 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
3938 case MachO::CPU_SUBTYPE_ARM_ALL:
3941 case MachO::CPU_SUBTYPE_ARM_V4T:
3944 case MachO::CPU_SUBTYPE_ARM_V5TEJ:
3947 case MachO::CPU_SUBTYPE_ARM_XSCALE:
3948 outs() << " XSCALE";
3950 case MachO::CPU_SUBTYPE_ARM_V6:
3953 case MachO::CPU_SUBTYPE_ARM_V6M:
3956 case MachO::CPU_SUBTYPE_ARM_V7:
3959 case MachO::CPU_SUBTYPE_ARM_V7EM:
3962 case MachO::CPU_SUBTYPE_ARM_V7K:
3965 case MachO::CPU_SUBTYPE_ARM_V7M:
3968 case MachO::CPU_SUBTYPE_ARM_V7S:
3972 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
3976 case MachO::CPU_TYPE_ARM64:
3978 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
3979 case MachO::CPU_SUBTYPE_ARM64_ALL:
3983 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
3987 case MachO::CPU_TYPE_POWERPC:
3989 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
3990 case MachO::CPU_SUBTYPE_POWERPC_ALL:
3994 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
3998 case MachO::CPU_TYPE_POWERPC64:
4000 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
4001 case MachO::CPU_SUBTYPE_POWERPC_ALL:
4005 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
4010 if ((cpusubtype & MachO::CPU_SUBTYPE_MASK) == MachO::CPU_SUBTYPE_LIB64) {
4013 outs() << format(" 0x%02" PRIx32,
4014 (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24);
4017 case MachO::MH_OBJECT:
4018 outs() << " OBJECT";
4020 case MachO::MH_EXECUTE:
4021 outs() << " EXECUTE";
4023 case MachO::MH_FVMLIB:
4024 outs() << " FVMLIB";
4026 case MachO::MH_CORE:
4029 case MachO::MH_PRELOAD:
4030 outs() << " PRELOAD";
4032 case MachO::MH_DYLIB:
4035 case MachO::MH_DYLIB_STUB:
4036 outs() << " DYLIB_STUB";
4038 case MachO::MH_DYLINKER:
4039 outs() << " DYLINKER";
4041 case MachO::MH_BUNDLE:
4042 outs() << " BUNDLE";
4044 case MachO::MH_DSYM:
4047 case MachO::MH_KEXT_BUNDLE:
4048 outs() << " KEXTBUNDLE";
4051 outs() << format(" %10u", filetype);
4054 outs() << format(" %5u", ncmds);
4055 outs() << format(" %10u", sizeofcmds);
4057 if (f & MachO::MH_NOUNDEFS) {
4058 outs() << " NOUNDEFS";
4059 f &= ~MachO::MH_NOUNDEFS;
4061 if (f & MachO::MH_INCRLINK) {
4062 outs() << " INCRLINK";
4063 f &= ~MachO::MH_INCRLINK;
4065 if (f & MachO::MH_DYLDLINK) {
4066 outs() << " DYLDLINK";
4067 f &= ~MachO::MH_DYLDLINK;
4069 if (f & MachO::MH_BINDATLOAD) {
4070 outs() << " BINDATLOAD";
4071 f &= ~MachO::MH_BINDATLOAD;
4073 if (f & MachO::MH_PREBOUND) {
4074 outs() << " PREBOUND";
4075 f &= ~MachO::MH_PREBOUND;
4077 if (f & MachO::MH_SPLIT_SEGS) {
4078 outs() << " SPLIT_SEGS";
4079 f &= ~MachO::MH_SPLIT_SEGS;
4081 if (f & MachO::MH_LAZY_INIT) {
4082 outs() << " LAZY_INIT";
4083 f &= ~MachO::MH_LAZY_INIT;
4085 if (f & MachO::MH_TWOLEVEL) {
4086 outs() << " TWOLEVEL";
4087 f &= ~MachO::MH_TWOLEVEL;
4089 if (f & MachO::MH_FORCE_FLAT) {
4090 outs() << " FORCE_FLAT";
4091 f &= ~MachO::MH_FORCE_FLAT;
4093 if (f & MachO::MH_NOMULTIDEFS) {
4094 outs() << " NOMULTIDEFS";
4095 f &= ~MachO::MH_NOMULTIDEFS;
4097 if (f & MachO::MH_NOFIXPREBINDING) {
4098 outs() << " NOFIXPREBINDING";
4099 f &= ~MachO::MH_NOFIXPREBINDING;
4101 if (f & MachO::MH_PREBINDABLE) {
4102 outs() << " PREBINDABLE";
4103 f &= ~MachO::MH_PREBINDABLE;
4105 if (f & MachO::MH_ALLMODSBOUND) {
4106 outs() << " ALLMODSBOUND";
4107 f &= ~MachO::MH_ALLMODSBOUND;
4109 if (f & MachO::MH_SUBSECTIONS_VIA_SYMBOLS) {
4110 outs() << " SUBSECTIONS_VIA_SYMBOLS";
4111 f &= ~MachO::MH_SUBSECTIONS_VIA_SYMBOLS;
4113 if (f & MachO::MH_CANONICAL) {
4114 outs() << " CANONICAL";
4115 f &= ~MachO::MH_CANONICAL;
4117 if (f & MachO::MH_WEAK_DEFINES) {
4118 outs() << " WEAK_DEFINES";
4119 f &= ~MachO::MH_WEAK_DEFINES;
4121 if (f & MachO::MH_BINDS_TO_WEAK) {
4122 outs() << " BINDS_TO_WEAK";
4123 f &= ~MachO::MH_BINDS_TO_WEAK;
4125 if (f & MachO::MH_ALLOW_STACK_EXECUTION) {
4126 outs() << " ALLOW_STACK_EXECUTION";
4127 f &= ~MachO::MH_ALLOW_STACK_EXECUTION;
4129 if (f & MachO::MH_DEAD_STRIPPABLE_DYLIB) {
4130 outs() << " DEAD_STRIPPABLE_DYLIB";
4131 f &= ~MachO::MH_DEAD_STRIPPABLE_DYLIB;
4133 if (f & MachO::MH_PIE) {
4135 f &= ~MachO::MH_PIE;
4137 if (f & MachO::MH_NO_REEXPORTED_DYLIBS) {
4138 outs() << " NO_REEXPORTED_DYLIBS";
4139 f &= ~MachO::MH_NO_REEXPORTED_DYLIBS;
4141 if (f & MachO::MH_HAS_TLV_DESCRIPTORS) {
4142 outs() << " MH_HAS_TLV_DESCRIPTORS";
4143 f &= ~MachO::MH_HAS_TLV_DESCRIPTORS;
4145 if (f & MachO::MH_NO_HEAP_EXECUTION) {
4146 outs() << " MH_NO_HEAP_EXECUTION";
4147 f &= ~MachO::MH_NO_HEAP_EXECUTION;
4149 if (f & MachO::MH_APP_EXTENSION_SAFE) {
4150 outs() << " APP_EXTENSION_SAFE";
4151 f &= ~MachO::MH_APP_EXTENSION_SAFE;
4153 if (f != 0 || flags == 0)
4154 outs() << format(" 0x%08" PRIx32, f);
4156 outs() << format(" 0x%08" PRIx32, magic);
4157 outs() << format(" %7d", cputype);
4158 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
4159 outs() << format(" 0x%02" PRIx32,
4160 (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24);
4161 outs() << format(" %10u", filetype);
4162 outs() << format(" %5u", ncmds);
4163 outs() << format(" %10u", sizeofcmds);
4164 outs() << format(" 0x%08" PRIx32, flags);
4169 static void PrintSegmentCommand(uint32_t cmd, uint32_t cmdsize,
4170 StringRef SegName, uint64_t vmaddr,
4171 uint64_t vmsize, uint64_t fileoff,
4172 uint64_t filesize, uint32_t maxprot,
4173 uint32_t initprot, uint32_t nsects,
4174 uint32_t flags, uint32_t object_size,
4176 uint64_t expected_cmdsize;
4177 if (cmd == MachO::LC_SEGMENT) {
4178 outs() << " cmd LC_SEGMENT\n";
4179 expected_cmdsize = nsects;
4180 expected_cmdsize *= sizeof(struct MachO::section);
4181 expected_cmdsize += sizeof(struct MachO::segment_command);
4183 outs() << " cmd LC_SEGMENT_64\n";
4184 expected_cmdsize = nsects;
4185 expected_cmdsize *= sizeof(struct MachO::section_64);
4186 expected_cmdsize += sizeof(struct MachO::segment_command_64);
4188 outs() << " cmdsize " << cmdsize;
4189 if (cmdsize != expected_cmdsize)
4190 outs() << " Inconsistent size\n";
4193 outs() << " segname " << SegName << "\n";
4194 if (cmd == MachO::LC_SEGMENT_64) {
4195 outs() << " vmaddr " << format("0x%016" PRIx64, vmaddr) << "\n";
4196 outs() << " vmsize " << format("0x%016" PRIx64, vmsize) << "\n";
4198 outs() << " vmaddr " << format("0x%08" PRIx64, vmaddr) << "\n";
4199 outs() << " vmsize " << format("0x%08" PRIx64, vmsize) << "\n";
4201 outs() << " fileoff " << fileoff;
4202 if (fileoff > object_size)
4203 outs() << " (past end of file)\n";
4206 outs() << " filesize " << filesize;
4207 if (fileoff + filesize > object_size)
4208 outs() << " (past end of file)\n";
4213 ~(MachO::VM_PROT_READ | MachO::VM_PROT_WRITE |
4214 MachO::VM_PROT_EXECUTE)) != 0)
4215 outs() << " maxprot ?" << format("0x%08" PRIx32, maxprot) << "\n";
4217 if (maxprot & MachO::VM_PROT_READ)
4218 outs() << " maxprot r";
4220 outs() << " maxprot -";
4221 if (maxprot & MachO::VM_PROT_WRITE)
4225 if (maxprot & MachO::VM_PROT_EXECUTE)
4231 ~(MachO::VM_PROT_READ | MachO::VM_PROT_WRITE |
4232 MachO::VM_PROT_EXECUTE)) != 0)
4233 outs() << " initprot ?" << format("0x%08" PRIx32, initprot) << "\n";
4235 if (initprot & MachO::VM_PROT_READ)
4236 outs() << " initprot r";
4238 outs() << " initprot -";
4239 if (initprot & MachO::VM_PROT_WRITE)
4243 if (initprot & MachO::VM_PROT_EXECUTE)
4249 outs() << " maxprot " << format("0x%08" PRIx32, maxprot) << "\n";
4250 outs() << " initprot " << format("0x%08" PRIx32, initprot) << "\n";
4252 outs() << " nsects " << nsects << "\n";
4256 outs() << " (none)\n";
4258 if (flags & MachO::SG_HIGHVM) {
4259 outs() << " HIGHVM";
4260 flags &= ~MachO::SG_HIGHVM;
4262 if (flags & MachO::SG_FVMLIB) {
4263 outs() << " FVMLIB";
4264 flags &= ~MachO::SG_FVMLIB;
4266 if (flags & MachO::SG_NORELOC) {
4267 outs() << " NORELOC";
4268 flags &= ~MachO::SG_NORELOC;
4270 if (flags & MachO::SG_PROTECTED_VERSION_1) {
4271 outs() << " PROTECTED_VERSION_1";
4272 flags &= ~MachO::SG_PROTECTED_VERSION_1;
4275 outs() << format(" 0x%08" PRIx32, flags) << " (unknown flags)\n";
4280 outs() << " flags " << format("0x%" PRIx32, flags) << "\n";
4284 static void PrintSection(const char *sectname, const char *segname,
4285 uint64_t addr, uint64_t size, uint32_t offset,
4286 uint32_t align, uint32_t reloff, uint32_t nreloc,
4287 uint32_t flags, uint32_t reserved1, uint32_t reserved2,
4288 uint32_t cmd, const char *sg_segname,
4289 uint32_t filetype, uint32_t object_size,
4291 outs() << "Section\n";
4292 outs() << " sectname " << format("%.16s\n", sectname);
4293 outs() << " segname " << format("%.16s", segname);
4294 if (filetype != MachO::MH_OBJECT && strncmp(sg_segname, segname, 16) != 0)
4295 outs() << " (does not match segment)\n";
4298 if (cmd == MachO::LC_SEGMENT_64) {
4299 outs() << " addr " << format("0x%016" PRIx64, addr) << "\n";
4300 outs() << " size " << format("0x%016" PRIx64, size);
4302 outs() << " addr " << format("0x%08" PRIx64, addr) << "\n";
4303 outs() << " size " << format("0x%08" PRIx64, size);
4305 if ((flags & MachO::S_ZEROFILL) != 0 && offset + size > object_size)
4306 outs() << " (past end of file)\n";
4309 outs() << " offset " << offset;
4310 if (offset > object_size)
4311 outs() << " (past end of file)\n";
4314 uint32_t align_shifted = 1 << align;
4315 outs() << " align 2^" << align << " (" << align_shifted << ")\n";
4316 outs() << " reloff " << reloff;
4317 if (reloff > object_size)
4318 outs() << " (past end of file)\n";
4321 outs() << " nreloc " << nreloc;
4322 if (reloff + nreloc * sizeof(struct MachO::relocation_info) > object_size)
4323 outs() << " (past end of file)\n";
4326 uint32_t section_type = flags & MachO::SECTION_TYPE;
4329 if (section_type == MachO::S_REGULAR)
4330 outs() << " S_REGULAR\n";
4331 else if (section_type == MachO::S_ZEROFILL)
4332 outs() << " S_ZEROFILL\n";
4333 else if (section_type == MachO::S_CSTRING_LITERALS)
4334 outs() << " S_CSTRING_LITERALS\n";
4335 else if (section_type == MachO::S_4BYTE_LITERALS)
4336 outs() << " S_4BYTE_LITERALS\n";
4337 else if (section_type == MachO::S_8BYTE_LITERALS)
4338 outs() << " S_8BYTE_LITERALS\n";
4339 else if (section_type == MachO::S_16BYTE_LITERALS)
4340 outs() << " S_16BYTE_LITERALS\n";
4341 else if (section_type == MachO::S_LITERAL_POINTERS)
4342 outs() << " S_LITERAL_POINTERS\n";
4343 else if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS)
4344 outs() << " S_NON_LAZY_SYMBOL_POINTERS\n";
4345 else if (section_type == MachO::S_LAZY_SYMBOL_POINTERS)
4346 outs() << " S_LAZY_SYMBOL_POINTERS\n";
4347 else if (section_type == MachO::S_SYMBOL_STUBS)
4348 outs() << " S_SYMBOL_STUBS\n";
4349 else if (section_type == MachO::S_MOD_INIT_FUNC_POINTERS)
4350 outs() << " S_MOD_INIT_FUNC_POINTERS\n";
4351 else if (section_type == MachO::S_MOD_TERM_FUNC_POINTERS)
4352 outs() << " S_MOD_TERM_FUNC_POINTERS\n";
4353 else if (section_type == MachO::S_COALESCED)
4354 outs() << " S_COALESCED\n";
4355 else if (section_type == MachO::S_INTERPOSING)
4356 outs() << " S_INTERPOSING\n";
4357 else if (section_type == MachO::S_DTRACE_DOF)
4358 outs() << " S_DTRACE_DOF\n";
4359 else if (section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS)
4360 outs() << " S_LAZY_DYLIB_SYMBOL_POINTERS\n";
4361 else if (section_type == MachO::S_THREAD_LOCAL_REGULAR)
4362 outs() << " S_THREAD_LOCAL_REGULAR\n";
4363 else if (section_type == MachO::S_THREAD_LOCAL_ZEROFILL)
4364 outs() << " S_THREAD_LOCAL_ZEROFILL\n";
4365 else if (section_type == MachO::S_THREAD_LOCAL_VARIABLES)
4366 outs() << " S_THREAD_LOCAL_VARIABLES\n";
4367 else if (section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS)
4368 outs() << " S_THREAD_LOCAL_VARIABLE_POINTERS\n";
4369 else if (section_type == MachO::S_THREAD_LOCAL_INIT_FUNCTION_POINTERS)
4370 outs() << " S_THREAD_LOCAL_INIT_FUNCTION_POINTERS\n";
4372 outs() << format("0x%08" PRIx32, section_type) << "\n";
4373 outs() << "attributes";
4374 uint32_t section_attributes = flags & MachO::SECTION_ATTRIBUTES;
4375 if (section_attributes & MachO::S_ATTR_PURE_INSTRUCTIONS)
4376 outs() << " PURE_INSTRUCTIONS";
4377 if (section_attributes & MachO::S_ATTR_NO_TOC)
4378 outs() << " NO_TOC";
4379 if (section_attributes & MachO::S_ATTR_STRIP_STATIC_SYMS)
4380 outs() << " STRIP_STATIC_SYMS";
4381 if (section_attributes & MachO::S_ATTR_NO_DEAD_STRIP)
4382 outs() << " NO_DEAD_STRIP";
4383 if (section_attributes & MachO::S_ATTR_LIVE_SUPPORT)
4384 outs() << " LIVE_SUPPORT";
4385 if (section_attributes & MachO::S_ATTR_SELF_MODIFYING_CODE)
4386 outs() << " SELF_MODIFYING_CODE";
4387 if (section_attributes & MachO::S_ATTR_DEBUG)
4389 if (section_attributes & MachO::S_ATTR_SOME_INSTRUCTIONS)
4390 outs() << " SOME_INSTRUCTIONS";
4391 if (section_attributes & MachO::S_ATTR_EXT_RELOC)
4392 outs() << " EXT_RELOC";
4393 if (section_attributes & MachO::S_ATTR_LOC_RELOC)
4394 outs() << " LOC_RELOC";
4395 if (section_attributes == 0)
4396 outs() << " (none)";
4399 outs() << " flags " << format("0x%08" PRIx32, flags) << "\n";
4400 outs() << " reserved1 " << reserved1;
4401 if (section_type == MachO::S_SYMBOL_STUBS ||
4402 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
4403 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
4404 section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
4405 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS)
4406 outs() << " (index into indirect symbol table)\n";
4409 outs() << " reserved2 " << reserved2;
4410 if (section_type == MachO::S_SYMBOL_STUBS)
4411 outs() << " (size of stubs)\n";
4416 static void PrintSymtabLoadCommand(MachO::symtab_command st, bool Is64Bit,
4417 uint32_t object_size) {
4418 outs() << " cmd LC_SYMTAB\n";
4419 outs() << " cmdsize " << st.cmdsize;
4420 if (st.cmdsize != sizeof(struct MachO::symtab_command))
4421 outs() << " Incorrect size\n";
4424 outs() << " symoff " << st.symoff;
4425 if (st.symoff > object_size)
4426 outs() << " (past end of file)\n";
4429 outs() << " nsyms " << st.nsyms;
4432 big_size = st.nsyms;
4433 big_size *= sizeof(struct MachO::nlist_64);
4434 big_size += st.symoff;
4435 if (big_size > object_size)
4436 outs() << " (past end of file)\n";
4440 big_size = st.nsyms;
4441 big_size *= sizeof(struct MachO::nlist);
4442 big_size += st.symoff;
4443 if (big_size > object_size)
4444 outs() << " (past end of file)\n";
4448 outs() << " stroff " << st.stroff;
4449 if (st.stroff > object_size)
4450 outs() << " (past end of file)\n";
4453 outs() << " strsize " << st.strsize;
4454 big_size = st.stroff;
4455 big_size += st.strsize;
4456 if (big_size > object_size)
4457 outs() << " (past end of file)\n";
4462 static void PrintDysymtabLoadCommand(MachO::dysymtab_command dyst,
4463 uint32_t nsyms, uint32_t object_size,
4465 outs() << " cmd LC_DYSYMTAB\n";
4466 outs() << " cmdsize " << dyst.cmdsize;
4467 if (dyst.cmdsize != sizeof(struct MachO::dysymtab_command))
4468 outs() << " Incorrect size\n";
4471 outs() << " ilocalsym " << dyst.ilocalsym;
4472 if (dyst.ilocalsym > nsyms)
4473 outs() << " (greater than the number of symbols)\n";
4476 outs() << " nlocalsym " << dyst.nlocalsym;
4478 big_size = dyst.ilocalsym;
4479 big_size += dyst.nlocalsym;
4480 if (big_size > nsyms)
4481 outs() << " (past the end of the symbol table)\n";
4484 outs() << " iextdefsym " << dyst.iextdefsym;
4485 if (dyst.iextdefsym > nsyms)
4486 outs() << " (greater than the number of symbols)\n";
4489 outs() << " nextdefsym " << dyst.nextdefsym;
4490 big_size = dyst.iextdefsym;
4491 big_size += dyst.nextdefsym;
4492 if (big_size > nsyms)
4493 outs() << " (past the end of the symbol table)\n";
4496 outs() << " iundefsym " << dyst.iundefsym;
4497 if (dyst.iundefsym > nsyms)
4498 outs() << " (greater than the number of symbols)\n";
4501 outs() << " nundefsym " << dyst.nundefsym;
4502 big_size = dyst.iundefsym;
4503 big_size += dyst.nundefsym;
4504 if (big_size > nsyms)
4505 outs() << " (past the end of the symbol table)\n";
4508 outs() << " tocoff " << dyst.tocoff;
4509 if (dyst.tocoff > object_size)
4510 outs() << " (past end of file)\n";
4513 outs() << " ntoc " << dyst.ntoc;
4514 big_size = dyst.ntoc;
4515 big_size *= sizeof(struct MachO::dylib_table_of_contents);
4516 big_size += dyst.tocoff;
4517 if (big_size > object_size)
4518 outs() << " (past end of file)\n";
4521 outs() << " modtaboff " << dyst.modtaboff;
4522 if (dyst.modtaboff > object_size)
4523 outs() << " (past end of file)\n";
4526 outs() << " nmodtab " << dyst.nmodtab;
4529 modtabend = dyst.nmodtab;
4530 modtabend *= sizeof(struct MachO::dylib_module_64);
4531 modtabend += dyst.modtaboff;
4533 modtabend = dyst.nmodtab;
4534 modtabend *= sizeof(struct MachO::dylib_module);
4535 modtabend += dyst.modtaboff;
4537 if (modtabend > object_size)
4538 outs() << " (past end of file)\n";
4541 outs() << " extrefsymoff " << dyst.extrefsymoff;
4542 if (dyst.extrefsymoff > object_size)
4543 outs() << " (past end of file)\n";
4546 outs() << " nextrefsyms " << dyst.nextrefsyms;
4547 big_size = dyst.nextrefsyms;
4548 big_size *= sizeof(struct MachO::dylib_reference);
4549 big_size += dyst.extrefsymoff;
4550 if (big_size > object_size)
4551 outs() << " (past end of file)\n";
4554 outs() << " indirectsymoff " << dyst.indirectsymoff;
4555 if (dyst.indirectsymoff > object_size)
4556 outs() << " (past end of file)\n";
4559 outs() << " nindirectsyms " << dyst.nindirectsyms;
4560 big_size = dyst.nindirectsyms;
4561 big_size *= sizeof(uint32_t);
4562 big_size += dyst.indirectsymoff;
4563 if (big_size > object_size)
4564 outs() << " (past end of file)\n";
4567 outs() << " extreloff " << dyst.extreloff;
4568 if (dyst.extreloff > object_size)
4569 outs() << " (past end of file)\n";
4572 outs() << " nextrel " << dyst.nextrel;
4573 big_size = dyst.nextrel;
4574 big_size *= sizeof(struct MachO::relocation_info);
4575 big_size += dyst.extreloff;
4576 if (big_size > object_size)
4577 outs() << " (past end of file)\n";
4580 outs() << " locreloff " << dyst.locreloff;
4581 if (dyst.locreloff > object_size)
4582 outs() << " (past end of file)\n";
4585 outs() << " nlocrel " << dyst.nlocrel;
4586 big_size = dyst.nlocrel;
4587 big_size *= sizeof(struct MachO::relocation_info);
4588 big_size += dyst.locreloff;
4589 if (big_size > object_size)
4590 outs() << " (past end of file)\n";
4595 static void PrintDyldInfoLoadCommand(MachO::dyld_info_command dc,
4596 uint32_t object_size) {
4597 if (dc.cmd == MachO::LC_DYLD_INFO)
4598 outs() << " cmd LC_DYLD_INFO\n";
4600 outs() << " cmd LC_DYLD_INFO_ONLY\n";
4601 outs() << " cmdsize " << dc.cmdsize;
4602 if (dc.cmdsize != sizeof(struct MachO::dyld_info_command))
4603 outs() << " Incorrect size\n";
4606 outs() << " rebase_off " << dc.rebase_off;
4607 if (dc.rebase_off > object_size)
4608 outs() << " (past end of file)\n";
4611 outs() << " rebase_size " << dc.rebase_size;
4613 big_size = dc.rebase_off;
4614 big_size += dc.rebase_size;
4615 if (big_size > object_size)
4616 outs() << " (past end of file)\n";
4619 outs() << " bind_off " << dc.bind_off;
4620 if (dc.bind_off > object_size)
4621 outs() << " (past end of file)\n";
4624 outs() << " bind_size " << dc.bind_size;
4625 big_size = dc.bind_off;
4626 big_size += dc.bind_size;
4627 if (big_size > object_size)
4628 outs() << " (past end of file)\n";
4631 outs() << " weak_bind_off " << dc.weak_bind_off;
4632 if (dc.weak_bind_off > object_size)
4633 outs() << " (past end of file)\n";
4636 outs() << " weak_bind_size " << dc.weak_bind_size;
4637 big_size = dc.weak_bind_off;
4638 big_size += dc.weak_bind_size;
4639 if (big_size > object_size)
4640 outs() << " (past end of file)\n";
4643 outs() << " lazy_bind_off " << dc.lazy_bind_off;
4644 if (dc.lazy_bind_off > object_size)
4645 outs() << " (past end of file)\n";
4648 outs() << " lazy_bind_size " << dc.lazy_bind_size;
4649 big_size = dc.lazy_bind_off;
4650 big_size += dc.lazy_bind_size;
4651 if (big_size > object_size)
4652 outs() << " (past end of file)\n";
4655 outs() << " export_off " << dc.export_off;
4656 if (dc.export_off > object_size)
4657 outs() << " (past end of file)\n";
4660 outs() << " export_size " << dc.export_size;
4661 big_size = dc.export_off;
4662 big_size += dc.export_size;
4663 if (big_size > object_size)
4664 outs() << " (past end of file)\n";
4669 static void PrintDyldLoadCommand(MachO::dylinker_command dyld,
4671 if (dyld.cmd == MachO::LC_ID_DYLINKER)
4672 outs() << " cmd LC_ID_DYLINKER\n";
4673 else if (dyld.cmd == MachO::LC_LOAD_DYLINKER)
4674 outs() << " cmd LC_LOAD_DYLINKER\n";
4675 else if (dyld.cmd == MachO::LC_DYLD_ENVIRONMENT)
4676 outs() << " cmd LC_DYLD_ENVIRONMENT\n";
4678 outs() << " cmd ?(" << dyld.cmd << ")\n";
4679 outs() << " cmdsize " << dyld.cmdsize;
4680 if (dyld.cmdsize < sizeof(struct MachO::dylinker_command))
4681 outs() << " Incorrect size\n";
4684 if (dyld.name >= dyld.cmdsize)
4685 outs() << " name ?(bad offset " << dyld.name << ")\n";
4687 const char *P = (const char *)(Ptr) + dyld.name;
4688 outs() << " name " << P << " (offset " << dyld.name << ")\n";
4692 static void PrintUuidLoadCommand(MachO::uuid_command uuid) {
4693 outs() << " cmd LC_UUID\n";
4694 outs() << " cmdsize " << uuid.cmdsize;
4695 if (uuid.cmdsize != sizeof(struct MachO::uuid_command))
4696 outs() << " Incorrect size\n";
4700 outs() << format("%02" PRIX32, uuid.uuid[0]);
4701 outs() << format("%02" PRIX32, uuid.uuid[1]);
4702 outs() << format("%02" PRIX32, uuid.uuid[2]);
4703 outs() << format("%02" PRIX32, uuid.uuid[3]);
4705 outs() << format("%02" PRIX32, uuid.uuid[4]);
4706 outs() << format("%02" PRIX32, uuid.uuid[5]);
4708 outs() << format("%02" PRIX32, uuid.uuid[6]);
4709 outs() << format("%02" PRIX32, uuid.uuid[7]);
4711 outs() << format("%02" PRIX32, uuid.uuid[8]);
4712 outs() << format("%02" PRIX32, uuid.uuid[9]);
4714 outs() << format("%02" PRIX32, uuid.uuid[10]);
4715 outs() << format("%02" PRIX32, uuid.uuid[11]);
4716 outs() << format("%02" PRIX32, uuid.uuid[12]);
4717 outs() << format("%02" PRIX32, uuid.uuid[13]);
4718 outs() << format("%02" PRIX32, uuid.uuid[14]);
4719 outs() << format("%02" PRIX32, uuid.uuid[15]);
4723 static void PrintRpathLoadCommand(MachO::rpath_command rpath, const char *Ptr) {
4724 outs() << " cmd LC_RPATH\n";
4725 outs() << " cmdsize " << rpath.cmdsize;
4726 if (rpath.cmdsize < sizeof(struct MachO::rpath_command))
4727 outs() << " Incorrect size\n";
4730 if (rpath.path >= rpath.cmdsize)
4731 outs() << " path ?(bad offset " << rpath.path << ")\n";
4733 const char *P = (const char *)(Ptr) + rpath.path;
4734 outs() << " path " << P << " (offset " << rpath.path << ")\n";
4738 static void PrintVersionMinLoadCommand(MachO::version_min_command vd) {
4739 if (vd.cmd == MachO::LC_VERSION_MIN_MACOSX)
4740 outs() << " cmd LC_VERSION_MIN_MACOSX\n";
4741 else if (vd.cmd == MachO::LC_VERSION_MIN_IPHONEOS)
4742 outs() << " cmd LC_VERSION_MIN_IPHONEOS\n";
4744 outs() << " cmd " << vd.cmd << " (?)\n";
4745 outs() << " cmdsize " << vd.cmdsize;
4746 if (vd.cmdsize != sizeof(struct MachO::version_min_command))
4747 outs() << " Incorrect size\n";
4750 outs() << " version " << ((vd.version >> 16) & 0xffff) << "."
4751 << ((vd.version >> 8) & 0xff);
4752 if ((vd.version & 0xff) != 0)
4753 outs() << "." << (vd.version & 0xff);
4756 outs() << " sdk n/a";
4758 outs() << " sdk " << ((vd.sdk >> 16) & 0xffff) << "."
4759 << ((vd.sdk >> 8) & 0xff);
4761 if ((vd.sdk & 0xff) != 0)
4762 outs() << "." << (vd.sdk & 0xff);
4766 static void PrintSourceVersionCommand(MachO::source_version_command sd) {
4767 outs() << " cmd LC_SOURCE_VERSION\n";
4768 outs() << " cmdsize " << sd.cmdsize;
4769 if (sd.cmdsize != sizeof(struct MachO::source_version_command))
4770 outs() << " Incorrect size\n";
4773 uint64_t a = (sd.version >> 40) & 0xffffff;
4774 uint64_t b = (sd.version >> 30) & 0x3ff;
4775 uint64_t c = (sd.version >> 20) & 0x3ff;
4776 uint64_t d = (sd.version >> 10) & 0x3ff;
4777 uint64_t e = sd.version & 0x3ff;
4778 outs() << " version " << a << "." << b;
4780 outs() << "." << c << "." << d << "." << e;
4782 outs() << "." << c << "." << d;
4788 static void PrintEntryPointCommand(MachO::entry_point_command ep) {
4789 outs() << " cmd LC_MAIN\n";
4790 outs() << " cmdsize " << ep.cmdsize;
4791 if (ep.cmdsize != sizeof(struct MachO::entry_point_command))
4792 outs() << " Incorrect size\n";
4795 outs() << " entryoff " << ep.entryoff << "\n";
4796 outs() << " stacksize " << ep.stacksize << "\n";
4799 static void PrintEncryptionInfoCommand(MachO::encryption_info_command ec,
4800 uint32_t object_size) {
4801 outs() << " cmd LC_ENCRYPTION_INFO\n";
4802 outs() << " cmdsize " << ec.cmdsize;
4803 if (ec.cmdsize != sizeof(struct MachO::encryption_info_command))
4804 outs() << " Incorrect size\n";
4807 outs() << " cryptoff " << ec.cryptoff;
4808 if (ec.cryptoff > object_size)
4809 outs() << " (past end of file)\n";
4812 outs() << " cryptsize " << ec.cryptsize;
4813 if (ec.cryptsize > object_size)
4814 outs() << " (past end of file)\n";
4817 outs() << " cryptid " << ec.cryptid << "\n";
4820 static void PrintEncryptionInfoCommand64(MachO::encryption_info_command_64 ec,
4821 uint32_t object_size) {
4822 outs() << " cmd LC_ENCRYPTION_INFO_64\n";
4823 outs() << " cmdsize " << ec.cmdsize;
4824 if (ec.cmdsize != sizeof(struct MachO::encryption_info_command_64))
4825 outs() << " Incorrect size\n";
4828 outs() << " cryptoff " << ec.cryptoff;
4829 if (ec.cryptoff > object_size)
4830 outs() << " (past end of file)\n";
4833 outs() << " cryptsize " << ec.cryptsize;
4834 if (ec.cryptsize > object_size)
4835 outs() << " (past end of file)\n";
4838 outs() << " cryptid " << ec.cryptid << "\n";
4839 outs() << " pad " << ec.pad << "\n";
4842 static void PrintLinkerOptionCommand(MachO::linker_option_command lo,
4844 outs() << " cmd LC_LINKER_OPTION\n";
4845 outs() << " cmdsize " << lo.cmdsize;
4846 if (lo.cmdsize < sizeof(struct MachO::linker_option_command))
4847 outs() << " Incorrect size\n";
4850 outs() << " count " << lo.count << "\n";
4851 const char *string = Ptr + sizeof(struct MachO::linker_option_command);
4852 uint32_t left = lo.cmdsize - sizeof(struct MachO::linker_option_command);
4855 while (*string == '\0' && left > 0) {
4861 outs() << " string #" << i << " " << format("%.*s\n", left, string);
4862 uint32_t NullPos = StringRef(string, left).find('\0');
4863 uint32_t len = std::min(NullPos, left) + 1;
4869 outs() << " count " << lo.count << " does not match number of strings "
4873 static void PrintSubFrameworkCommand(MachO::sub_framework_command sub,
4875 outs() << " cmd LC_SUB_FRAMEWORK\n";
4876 outs() << " cmdsize " << sub.cmdsize;
4877 if (sub.cmdsize < sizeof(struct MachO::sub_framework_command))
4878 outs() << " Incorrect size\n";
4881 if (sub.umbrella < sub.cmdsize) {
4882 const char *P = Ptr + sub.umbrella;
4883 outs() << " umbrella " << P << " (offset " << sub.umbrella << ")\n";
4885 outs() << " umbrella ?(bad offset " << sub.umbrella << ")\n";
4889 static void PrintSubUmbrellaCommand(MachO::sub_umbrella_command sub,
4891 outs() << " cmd LC_SUB_UMBRELLA\n";
4892 outs() << " cmdsize " << sub.cmdsize;
4893 if (sub.cmdsize < sizeof(struct MachO::sub_umbrella_command))
4894 outs() << " Incorrect size\n";
4897 if (sub.sub_umbrella < sub.cmdsize) {
4898 const char *P = Ptr + sub.sub_umbrella;
4899 outs() << " sub_umbrella " << P << " (offset " << sub.sub_umbrella << ")\n";
4901 outs() << " sub_umbrella ?(bad offset " << sub.sub_umbrella << ")\n";
4905 static void PrintSubLibraryCommand(MachO::sub_library_command sub,
4907 outs() << " cmd LC_SUB_LIBRARY\n";
4908 outs() << " cmdsize " << sub.cmdsize;
4909 if (sub.cmdsize < sizeof(struct MachO::sub_library_command))
4910 outs() << " Incorrect size\n";
4913 if (sub.sub_library < sub.cmdsize) {
4914 const char *P = Ptr + sub.sub_library;
4915 outs() << " sub_library " << P << " (offset " << sub.sub_library << ")\n";
4917 outs() << " sub_library ?(bad offset " << sub.sub_library << ")\n";
4921 static void PrintSubClientCommand(MachO::sub_client_command sub,
4923 outs() << " cmd LC_SUB_CLIENT\n";
4924 outs() << " cmdsize " << sub.cmdsize;
4925 if (sub.cmdsize < sizeof(struct MachO::sub_client_command))
4926 outs() << " Incorrect size\n";
4929 if (sub.client < sub.cmdsize) {
4930 const char *P = Ptr + sub.client;
4931 outs() << " client " << P << " (offset " << sub.client << ")\n";
4933 outs() << " client ?(bad offset " << sub.client << ")\n";
4937 static void PrintRoutinesCommand(MachO::routines_command r) {
4938 outs() << " cmd LC_ROUTINES\n";
4939 outs() << " cmdsize " << r.cmdsize;
4940 if (r.cmdsize != sizeof(struct MachO::routines_command))
4941 outs() << " Incorrect size\n";
4944 outs() << " init_address " << format("0x%08" PRIx32, r.init_address) << "\n";
4945 outs() << " init_module " << r.init_module << "\n";
4946 outs() << " reserved1 " << r.reserved1 << "\n";
4947 outs() << " reserved2 " << r.reserved2 << "\n";
4948 outs() << " reserved3 " << r.reserved3 << "\n";
4949 outs() << " reserved4 " << r.reserved4 << "\n";
4950 outs() << " reserved5 " << r.reserved5 << "\n";
4951 outs() << " reserved6 " << r.reserved6 << "\n";
4954 static void PrintRoutinesCommand64(MachO::routines_command_64 r) {
4955 outs() << " cmd LC_ROUTINES_64\n";
4956 outs() << " cmdsize " << r.cmdsize;
4957 if (r.cmdsize != sizeof(struct MachO::routines_command_64))
4958 outs() << " Incorrect size\n";
4961 outs() << " init_address " << format("0x%016" PRIx64, r.init_address) << "\n";
4962 outs() << " init_module " << r.init_module << "\n";
4963 outs() << " reserved1 " << r.reserved1 << "\n";
4964 outs() << " reserved2 " << r.reserved2 << "\n";
4965 outs() << " reserved3 " << r.reserved3 << "\n";
4966 outs() << " reserved4 " << r.reserved4 << "\n";
4967 outs() << " reserved5 " << r.reserved5 << "\n";
4968 outs() << " reserved6 " << r.reserved6 << "\n";
4971 static void Print_x86_thread_state64_t(MachO::x86_thread_state64_t &cpu64) {
4972 outs() << " rax " << format("0x%016" PRIx64, cpu64.rax);
4973 outs() << " rbx " << format("0x%016" PRIx64, cpu64.rbx);
4974 outs() << " rcx " << format("0x%016" PRIx64, cpu64.rcx) << "\n";
4975 outs() << " rdx " << format("0x%016" PRIx64, cpu64.rdx);
4976 outs() << " rdi " << format("0x%016" PRIx64, cpu64.rdi);
4977 outs() << " rsi " << format("0x%016" PRIx64, cpu64.rsi) << "\n";
4978 outs() << " rbp " << format("0x%016" PRIx64, cpu64.rbp);
4979 outs() << " rsp " << format("0x%016" PRIx64, cpu64.rsp);
4980 outs() << " r8 " << format("0x%016" PRIx64, cpu64.r8) << "\n";
4981 outs() << " r9 " << format("0x%016" PRIx64, cpu64.r9);
4982 outs() << " r10 " << format("0x%016" PRIx64, cpu64.r10);
4983 outs() << " r11 " << format("0x%016" PRIx64, cpu64.r11) << "\n";
4984 outs() << " r12 " << format("0x%016" PRIx64, cpu64.r12);
4985 outs() << " r13 " << format("0x%016" PRIx64, cpu64.r13);
4986 outs() << " r14 " << format("0x%016" PRIx64, cpu64.r14) << "\n";
4987 outs() << " r15 " << format("0x%016" PRIx64, cpu64.r15);
4988 outs() << " rip " << format("0x%016" PRIx64, cpu64.rip) << "\n";
4989 outs() << "rflags " << format("0x%016" PRIx64, cpu64.rflags);
4990 outs() << " cs " << format("0x%016" PRIx64, cpu64.cs);
4991 outs() << " fs " << format("0x%016" PRIx64, cpu64.fs) << "\n";
4992 outs() << " gs " << format("0x%016" PRIx64, cpu64.gs) << "\n";
4995 static void Print_mmst_reg(MachO::mmst_reg_t &r) {
4997 outs() << "\t mmst_reg ";
4998 for (f = 0; f < 10; f++)
4999 outs() << format("%02" PRIx32, (r.mmst_reg[f] & 0xff)) << " ";
5001 outs() << "\t mmst_rsrv ";
5002 for (f = 0; f < 6; f++)
5003 outs() << format("%02" PRIx32, (r.mmst_rsrv[f] & 0xff)) << " ";
5007 static void Print_xmm_reg(MachO::xmm_reg_t &r) {
5009 outs() << "\t xmm_reg ";
5010 for (f = 0; f < 16; f++)
5011 outs() << format("%02" PRIx32, (r.xmm_reg[f] & 0xff)) << " ";
5015 static void Print_x86_float_state_t(MachO::x86_float_state64_t &fpu) {
5016 outs() << "\t fpu_reserved[0] " << fpu.fpu_reserved[0];
5017 outs() << " fpu_reserved[1] " << fpu.fpu_reserved[1] << "\n";
5018 outs() << "\t control: invalid " << fpu.fpu_fcw.invalid;
5019 outs() << " denorm " << fpu.fpu_fcw.denorm;
5020 outs() << " zdiv " << fpu.fpu_fcw.zdiv;
5021 outs() << " ovrfl " << fpu.fpu_fcw.ovrfl;
5022 outs() << " undfl " << fpu.fpu_fcw.undfl;
5023 outs() << " precis " << fpu.fpu_fcw.precis << "\n";
5024 outs() << "\t\t pc ";
5025 if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_24B)
5026 outs() << "FP_PREC_24B ";
5027 else if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_53B)
5028 outs() << "FP_PREC_53B ";
5029 else if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_64B)
5030 outs() << "FP_PREC_64B ";
5032 outs() << fpu.fpu_fcw.pc << " ";
5034 if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_NEAR)
5035 outs() << "FP_RND_NEAR ";
5036 else if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_DOWN)
5037 outs() << "FP_RND_DOWN ";
5038 else if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_UP)
5039 outs() << "FP_RND_UP ";
5040 else if (fpu.fpu_fcw.rc == MachO::x86_FP_CHOP)
5041 outs() << "FP_CHOP ";
5043 outs() << "\t status: invalid " << fpu.fpu_fsw.invalid;
5044 outs() << " denorm " << fpu.fpu_fsw.denorm;
5045 outs() << " zdiv " << fpu.fpu_fsw.zdiv;
5046 outs() << " ovrfl " << fpu.fpu_fsw.ovrfl;
5047 outs() << " undfl " << fpu.fpu_fsw.undfl;
5048 outs() << " precis " << fpu.fpu_fsw.precis;
5049 outs() << " stkflt " << fpu.fpu_fsw.stkflt << "\n";
5050 outs() << "\t errsumm " << fpu.fpu_fsw.errsumm;
5051 outs() << " c0 " << fpu.fpu_fsw.c0;
5052 outs() << " c1 " << fpu.fpu_fsw.c1;
5053 outs() << " c2 " << fpu.fpu_fsw.c2;
5054 outs() << " tos " << fpu.fpu_fsw.tos;
5055 outs() << " c3 " << fpu.fpu_fsw.c3;
5056 outs() << " busy " << fpu.fpu_fsw.busy << "\n";
5057 outs() << "\t fpu_ftw " << format("0x%02" PRIx32, fpu.fpu_ftw);
5058 outs() << " fpu_rsrv1 " << format("0x%02" PRIx32, fpu.fpu_rsrv1);
5059 outs() << " fpu_fop " << format("0x%04" PRIx32, fpu.fpu_fop);
5060 outs() << " fpu_ip " << format("0x%08" PRIx32, fpu.fpu_ip) << "\n";
5061 outs() << "\t fpu_cs " << format("0x%04" PRIx32, fpu.fpu_cs);
5062 outs() << " fpu_rsrv2 " << format("0x%04" PRIx32, fpu.fpu_rsrv2);
5063 outs() << " fpu_dp " << format("0x%08" PRIx32, fpu.fpu_dp);
5064 outs() << " fpu_ds " << format("0x%04" PRIx32, fpu.fpu_ds) << "\n";
5065 outs() << "\t fpu_rsrv3 " << format("0x%04" PRIx32, fpu.fpu_rsrv3);
5066 outs() << " fpu_mxcsr " << format("0x%08" PRIx32, fpu.fpu_mxcsr);
5067 outs() << " fpu_mxcsrmask " << format("0x%08" PRIx32, fpu.fpu_mxcsrmask);
5069 outs() << "\t fpu_stmm0:\n";
5070 Print_mmst_reg(fpu.fpu_stmm0);
5071 outs() << "\t fpu_stmm1:\n";
5072 Print_mmst_reg(fpu.fpu_stmm1);
5073 outs() << "\t fpu_stmm2:\n";
5074 Print_mmst_reg(fpu.fpu_stmm2);
5075 outs() << "\t fpu_stmm3:\n";
5076 Print_mmst_reg(fpu.fpu_stmm3);
5077 outs() << "\t fpu_stmm4:\n";
5078 Print_mmst_reg(fpu.fpu_stmm4);
5079 outs() << "\t fpu_stmm5:\n";
5080 Print_mmst_reg(fpu.fpu_stmm5);
5081 outs() << "\t fpu_stmm6:\n";
5082 Print_mmst_reg(fpu.fpu_stmm6);
5083 outs() << "\t fpu_stmm7:\n";
5084 Print_mmst_reg(fpu.fpu_stmm7);
5085 outs() << "\t fpu_xmm0:\n";
5086 Print_xmm_reg(fpu.fpu_xmm0);
5087 outs() << "\t fpu_xmm1:\n";
5088 Print_xmm_reg(fpu.fpu_xmm1);
5089 outs() << "\t fpu_xmm2:\n";
5090 Print_xmm_reg(fpu.fpu_xmm2);
5091 outs() << "\t fpu_xmm3:\n";
5092 Print_xmm_reg(fpu.fpu_xmm3);
5093 outs() << "\t fpu_xmm4:\n";
5094 Print_xmm_reg(fpu.fpu_xmm4);
5095 outs() << "\t fpu_xmm5:\n";
5096 Print_xmm_reg(fpu.fpu_xmm5);
5097 outs() << "\t fpu_xmm6:\n";
5098 Print_xmm_reg(fpu.fpu_xmm6);
5099 outs() << "\t fpu_xmm7:\n";
5100 Print_xmm_reg(fpu.fpu_xmm7);
5101 outs() << "\t fpu_xmm8:\n";
5102 Print_xmm_reg(fpu.fpu_xmm8);
5103 outs() << "\t fpu_xmm9:\n";
5104 Print_xmm_reg(fpu.fpu_xmm9);
5105 outs() << "\t fpu_xmm10:\n";
5106 Print_xmm_reg(fpu.fpu_xmm10);
5107 outs() << "\t fpu_xmm11:\n";
5108 Print_xmm_reg(fpu.fpu_xmm11);
5109 outs() << "\t fpu_xmm12:\n";
5110 Print_xmm_reg(fpu.fpu_xmm12);
5111 outs() << "\t fpu_xmm13:\n";
5112 Print_xmm_reg(fpu.fpu_xmm13);
5113 outs() << "\t fpu_xmm14:\n";
5114 Print_xmm_reg(fpu.fpu_xmm14);
5115 outs() << "\t fpu_xmm15:\n";
5116 Print_xmm_reg(fpu.fpu_xmm15);
5117 outs() << "\t fpu_rsrv4:\n";
5118 for (uint32_t f = 0; f < 6; f++) {
5120 for (uint32_t g = 0; g < 16; g++)
5121 outs() << format("%02" PRIx32, fpu.fpu_rsrv4[f * g]) << " ";
5124 outs() << "\t fpu_reserved1 " << format("0x%08" PRIx32, fpu.fpu_reserved1);
5128 static void Print_x86_exception_state_t(MachO::x86_exception_state64_t &exc64) {
5129 outs() << "\t trapno " << format("0x%08" PRIx32, exc64.trapno);
5130 outs() << " err " << format("0x%08" PRIx32, exc64.err);
5131 outs() << " faultvaddr " << format("0x%016" PRIx64, exc64.faultvaddr) << "\n";
5134 static void PrintThreadCommand(MachO::thread_command t, const char *Ptr,
5135 bool isLittleEndian, uint32_t cputype) {
5136 if (t.cmd == MachO::LC_THREAD)
5137 outs() << " cmd LC_THREAD\n";
5138 else if (t.cmd == MachO::LC_UNIXTHREAD)
5139 outs() << " cmd LC_UNIXTHREAD\n";
5141 outs() << " cmd " << t.cmd << " (unknown)\n";
5142 outs() << " cmdsize " << t.cmdsize;
5143 if (t.cmdsize < sizeof(struct MachO::thread_command) + 2 * sizeof(uint32_t))
5144 outs() << " Incorrect size\n";
5148 const char *begin = Ptr + sizeof(struct MachO::thread_command);
5149 const char *end = Ptr + t.cmdsize;
5150 uint32_t flavor, count, left;
5151 if (cputype == MachO::CPU_TYPE_X86_64) {
5152 while (begin < end) {
5153 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
5154 memcpy((char *)&flavor, begin, sizeof(uint32_t));
5155 begin += sizeof(uint32_t);
5160 if (isLittleEndian != sys::IsLittleEndianHost)
5161 sys::swapByteOrder(flavor);
5162 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
5163 memcpy((char *)&count, begin, sizeof(uint32_t));
5164 begin += sizeof(uint32_t);
5169 if (isLittleEndian != sys::IsLittleEndianHost)
5170 sys::swapByteOrder(count);
5171 if (flavor == MachO::x86_THREAD_STATE64) {
5172 outs() << " flavor x86_THREAD_STATE64\n";
5173 if (count == MachO::x86_THREAD_STATE64_COUNT)
5174 outs() << " count x86_THREAD_STATE64_COUNT\n";
5176 outs() << " count " << count
5177 << " (not x86_THREAD_STATE64_COUNT)\n";
5178 MachO::x86_thread_state64_t cpu64;
5180 if (left >= sizeof(MachO::x86_thread_state64_t)) {
5181 memcpy(&cpu64, begin, sizeof(MachO::x86_thread_state64_t));
5182 begin += sizeof(MachO::x86_thread_state64_t);
5184 memset(&cpu64, '\0', sizeof(MachO::x86_thread_state64_t));
5185 memcpy(&cpu64, begin, left);
5188 if (isLittleEndian != sys::IsLittleEndianHost)
5190 Print_x86_thread_state64_t(cpu64);
5191 } else if (flavor == MachO::x86_THREAD_STATE) {
5192 outs() << " flavor x86_THREAD_STATE\n";
5193 if (count == MachO::x86_THREAD_STATE_COUNT)
5194 outs() << " count x86_THREAD_STATE_COUNT\n";
5196 outs() << " count " << count
5197 << " (not x86_THREAD_STATE_COUNT)\n";
5198 struct MachO::x86_thread_state_t ts;
5200 if (left >= sizeof(MachO::x86_thread_state_t)) {
5201 memcpy(&ts, begin, sizeof(MachO::x86_thread_state_t));
5202 begin += sizeof(MachO::x86_thread_state_t);
5204 memset(&ts, '\0', sizeof(MachO::x86_thread_state_t));
5205 memcpy(&ts, begin, left);
5208 if (isLittleEndian != sys::IsLittleEndianHost)
5210 if (ts.tsh.flavor == MachO::x86_THREAD_STATE64) {
5211 outs() << "\t tsh.flavor x86_THREAD_STATE64 ";
5212 if (ts.tsh.count == MachO::x86_THREAD_STATE64_COUNT)
5213 outs() << "tsh.count x86_THREAD_STATE64_COUNT\n";
5215 outs() << "tsh.count " << ts.tsh.count
5216 << " (not x86_THREAD_STATE64_COUNT\n";
5217 Print_x86_thread_state64_t(ts.uts.ts64);
5219 outs() << "\t tsh.flavor " << ts.tsh.flavor << " tsh.count "
5220 << ts.tsh.count << "\n";
5222 } else if (flavor == MachO::x86_FLOAT_STATE) {
5223 outs() << " flavor x86_FLOAT_STATE\n";
5224 if (count == MachO::x86_FLOAT_STATE_COUNT)
5225 outs() << " count x86_FLOAT_STATE_COUNT\n";
5227 outs() << " count " << count << " (not x86_FLOAT_STATE_COUNT)\n";
5228 struct MachO::x86_float_state_t fs;
5230 if (left >= sizeof(MachO::x86_float_state_t)) {
5231 memcpy(&fs, begin, sizeof(MachO::x86_float_state_t));
5232 begin += sizeof(MachO::x86_float_state_t);
5234 memset(&fs, '\0', sizeof(MachO::x86_float_state_t));
5235 memcpy(&fs, begin, left);
5238 if (isLittleEndian != sys::IsLittleEndianHost)
5240 if (fs.fsh.flavor == MachO::x86_FLOAT_STATE64) {
5241 outs() << "\t fsh.flavor x86_FLOAT_STATE64 ";
5242 if (fs.fsh.count == MachO::x86_FLOAT_STATE64_COUNT)
5243 outs() << "fsh.count x86_FLOAT_STATE64_COUNT\n";
5245 outs() << "fsh.count " << fs.fsh.count
5246 << " (not x86_FLOAT_STATE64_COUNT\n";
5247 Print_x86_float_state_t(fs.ufs.fs64);
5249 outs() << "\t fsh.flavor " << fs.fsh.flavor << " fsh.count "
5250 << fs.fsh.count << "\n";
5252 } else if (flavor == MachO::x86_EXCEPTION_STATE) {
5253 outs() << " flavor x86_EXCEPTION_STATE\n";
5254 if (count == MachO::x86_EXCEPTION_STATE_COUNT)
5255 outs() << " count x86_EXCEPTION_STATE_COUNT\n";
5257 outs() << " count " << count
5258 << " (not x86_EXCEPTION_STATE_COUNT)\n";
5259 struct MachO::x86_exception_state_t es;
5261 if (left >= sizeof(MachO::x86_exception_state_t)) {
5262 memcpy(&es, begin, sizeof(MachO::x86_exception_state_t));
5263 begin += sizeof(MachO::x86_exception_state_t);
5265 memset(&es, '\0', sizeof(MachO::x86_exception_state_t));
5266 memcpy(&es, begin, left);
5269 if (isLittleEndian != sys::IsLittleEndianHost)
5271 if (es.esh.flavor == MachO::x86_EXCEPTION_STATE64) {
5272 outs() << "\t esh.flavor x86_EXCEPTION_STATE64\n";
5273 if (es.esh.count == MachO::x86_EXCEPTION_STATE64_COUNT)
5274 outs() << "\t esh.count x86_EXCEPTION_STATE64_COUNT\n";
5276 outs() << "\t esh.count " << es.esh.count
5277 << " (not x86_EXCEPTION_STATE64_COUNT\n";
5278 Print_x86_exception_state_t(es.ues.es64);
5280 outs() << "\t esh.flavor " << es.esh.flavor << " esh.count "
5281 << es.esh.count << "\n";
5284 outs() << " flavor " << flavor << " (unknown)\n";
5285 outs() << " count " << count << "\n";
5286 outs() << " state (unknown)\n";
5287 begin += count * sizeof(uint32_t);
5291 while (begin < end) {
5292 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
5293 memcpy((char *)&flavor, begin, sizeof(uint32_t));
5294 begin += sizeof(uint32_t);
5299 if (isLittleEndian != sys::IsLittleEndianHost)
5300 sys::swapByteOrder(flavor);
5301 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
5302 memcpy((char *)&count, begin, sizeof(uint32_t));
5303 begin += sizeof(uint32_t);
5308 if (isLittleEndian != sys::IsLittleEndianHost)
5309 sys::swapByteOrder(count);
5310 outs() << " flavor " << flavor << "\n";
5311 outs() << " count " << count << "\n";
5312 outs() << " state (Unknown cputype/cpusubtype)\n";
5313 begin += count * sizeof(uint32_t);
5318 static void PrintDylibCommand(MachO::dylib_command dl, const char *Ptr) {
5319 if (dl.cmd == MachO::LC_ID_DYLIB)
5320 outs() << " cmd LC_ID_DYLIB\n";
5321 else if (dl.cmd == MachO::LC_LOAD_DYLIB)
5322 outs() << " cmd LC_LOAD_DYLIB\n";
5323 else if (dl.cmd == MachO::LC_LOAD_WEAK_DYLIB)
5324 outs() << " cmd LC_LOAD_WEAK_DYLIB\n";
5325 else if (dl.cmd == MachO::LC_REEXPORT_DYLIB)
5326 outs() << " cmd LC_REEXPORT_DYLIB\n";
5327 else if (dl.cmd == MachO::LC_LAZY_LOAD_DYLIB)
5328 outs() << " cmd LC_LAZY_LOAD_DYLIB\n";
5329 else if (dl.cmd == MachO::LC_LOAD_UPWARD_DYLIB)
5330 outs() << " cmd LC_LOAD_UPWARD_DYLIB\n";
5332 outs() << " cmd " << dl.cmd << " (unknown)\n";
5333 outs() << " cmdsize " << dl.cmdsize;
5334 if (dl.cmdsize < sizeof(struct MachO::dylib_command))
5335 outs() << " Incorrect size\n";
5338 if (dl.dylib.name < dl.cmdsize) {
5339 const char *P = (const char *)(Ptr) + dl.dylib.name;
5340 outs() << " name " << P << " (offset " << dl.dylib.name << ")\n";
5342 outs() << " name ?(bad offset " << dl.dylib.name << ")\n";
5344 outs() << " time stamp " << dl.dylib.timestamp << " ";
5345 time_t t = dl.dylib.timestamp;
5346 outs() << ctime(&t);
5347 outs() << " current version ";
5348 if (dl.dylib.current_version == 0xffffffff)
5351 outs() << ((dl.dylib.current_version >> 16) & 0xffff) << "."
5352 << ((dl.dylib.current_version >> 8) & 0xff) << "."
5353 << (dl.dylib.current_version & 0xff) << "\n";
5354 outs() << "compatibility version ";
5355 if (dl.dylib.compatibility_version == 0xffffffff)
5358 outs() << ((dl.dylib.compatibility_version >> 16) & 0xffff) << "."
5359 << ((dl.dylib.compatibility_version >> 8) & 0xff) << "."
5360 << (dl.dylib.compatibility_version & 0xff) << "\n";
5363 static void PrintLinkEditDataCommand(MachO::linkedit_data_command ld,
5364 uint32_t object_size) {
5365 if (ld.cmd == MachO::LC_CODE_SIGNATURE)
5366 outs() << " cmd LC_FUNCTION_STARTS\n";
5367 else if (ld.cmd == MachO::LC_SEGMENT_SPLIT_INFO)
5368 outs() << " cmd LC_SEGMENT_SPLIT_INFO\n";
5369 else if (ld.cmd == MachO::LC_FUNCTION_STARTS)
5370 outs() << " cmd LC_FUNCTION_STARTS\n";
5371 else if (ld.cmd == MachO::LC_DATA_IN_CODE)
5372 outs() << " cmd LC_DATA_IN_CODE\n";
5373 else if (ld.cmd == MachO::LC_DYLIB_CODE_SIGN_DRS)
5374 outs() << " cmd LC_DYLIB_CODE_SIGN_DRS\n";
5375 else if (ld.cmd == MachO::LC_LINKER_OPTIMIZATION_HINT)
5376 outs() << " cmd LC_LINKER_OPTIMIZATION_HINT\n";
5378 outs() << " cmd " << ld.cmd << " (?)\n";
5379 outs() << " cmdsize " << ld.cmdsize;
5380 if (ld.cmdsize != sizeof(struct MachO::linkedit_data_command))
5381 outs() << " Incorrect size\n";
5384 outs() << " dataoff " << ld.dataoff;
5385 if (ld.dataoff > object_size)
5386 outs() << " (past end of file)\n";
5389 outs() << " datasize " << ld.datasize;
5390 uint64_t big_size = ld.dataoff;
5391 big_size += ld.datasize;
5392 if (big_size > object_size)
5393 outs() << " (past end of file)\n";
5398 static void PrintLoadCommands(const MachOObjectFile *Obj, uint32_t ncmds,
5399 uint32_t filetype, uint32_t cputype,
5403 StringRef Buf = Obj->getData();
5404 MachOObjectFile::LoadCommandInfo Command = Obj->getFirstLoadCommandInfo();
5405 for (unsigned i = 0;; ++i) {
5406 outs() << "Load command " << i << "\n";
5407 if (Command.C.cmd == MachO::LC_SEGMENT) {
5408 MachO::segment_command SLC = Obj->getSegmentLoadCommand(Command);
5409 const char *sg_segname = SLC.segname;
5410 PrintSegmentCommand(SLC.cmd, SLC.cmdsize, SLC.segname, SLC.vmaddr,
5411 SLC.vmsize, SLC.fileoff, SLC.filesize, SLC.maxprot,
5412 SLC.initprot, SLC.nsects, SLC.flags, Buf.size(),
5414 for (unsigned j = 0; j < SLC.nsects; j++) {
5415 MachO::section S = Obj->getSection(Command, j);
5416 PrintSection(S.sectname, S.segname, S.addr, S.size, S.offset, S.align,
5417 S.reloff, S.nreloc, S.flags, S.reserved1, S.reserved2,
5418 SLC.cmd, sg_segname, filetype, Buf.size(), verbose);
5420 } else if (Command.C.cmd == MachO::LC_SEGMENT_64) {
5421 MachO::segment_command_64 SLC_64 = Obj->getSegment64LoadCommand(Command);
5422 const char *sg_segname = SLC_64.segname;
5423 PrintSegmentCommand(SLC_64.cmd, SLC_64.cmdsize, SLC_64.segname,
5424 SLC_64.vmaddr, SLC_64.vmsize, SLC_64.fileoff,
5425 SLC_64.filesize, SLC_64.maxprot, SLC_64.initprot,
5426 SLC_64.nsects, SLC_64.flags, Buf.size(), verbose);
5427 for (unsigned j = 0; j < SLC_64.nsects; j++) {
5428 MachO::section_64 S_64 = Obj->getSection64(Command, j);
5429 PrintSection(S_64.sectname, S_64.segname, S_64.addr, S_64.size,
5430 S_64.offset, S_64.align, S_64.reloff, S_64.nreloc,
5431 S_64.flags, S_64.reserved1, S_64.reserved2, SLC_64.cmd,
5432 sg_segname, filetype, Buf.size(), verbose);
5434 } else if (Command.C.cmd == MachO::LC_SYMTAB) {
5435 MachO::symtab_command Symtab = Obj->getSymtabLoadCommand();
5436 PrintSymtabLoadCommand(Symtab, Obj->is64Bit(), Buf.size());
5437 } else if (Command.C.cmd == MachO::LC_DYSYMTAB) {
5438 MachO::dysymtab_command Dysymtab = Obj->getDysymtabLoadCommand();
5439 MachO::symtab_command Symtab = Obj->getSymtabLoadCommand();
5440 PrintDysymtabLoadCommand(Dysymtab, Symtab.nsyms, Buf.size(),
5442 } else if (Command.C.cmd == MachO::LC_DYLD_INFO ||
5443 Command.C.cmd == MachO::LC_DYLD_INFO_ONLY) {
5444 MachO::dyld_info_command DyldInfo = Obj->getDyldInfoLoadCommand(Command);
5445 PrintDyldInfoLoadCommand(DyldInfo, Buf.size());
5446 } else if (Command.C.cmd == MachO::LC_LOAD_DYLINKER ||
5447 Command.C.cmd == MachO::LC_ID_DYLINKER ||
5448 Command.C.cmd == MachO::LC_DYLD_ENVIRONMENT) {
5449 MachO::dylinker_command Dyld = Obj->getDylinkerCommand(Command);
5450 PrintDyldLoadCommand(Dyld, Command.Ptr);
5451 } else if (Command.C.cmd == MachO::LC_UUID) {
5452 MachO::uuid_command Uuid = Obj->getUuidCommand(Command);
5453 PrintUuidLoadCommand(Uuid);
5454 } else if (Command.C.cmd == MachO::LC_RPATH) {
5455 MachO::rpath_command Rpath = Obj->getRpathCommand(Command);
5456 PrintRpathLoadCommand(Rpath, Command.Ptr);
5457 } else if (Command.C.cmd == MachO::LC_VERSION_MIN_MACOSX ||
5458 Command.C.cmd == MachO::LC_VERSION_MIN_IPHONEOS) {
5459 MachO::version_min_command Vd = Obj->getVersionMinLoadCommand(Command);
5460 PrintVersionMinLoadCommand(Vd);
5461 } else if (Command.C.cmd == MachO::LC_SOURCE_VERSION) {
5462 MachO::source_version_command Sd = Obj->getSourceVersionCommand(Command);
5463 PrintSourceVersionCommand(Sd);
5464 } else if (Command.C.cmd == MachO::LC_MAIN) {
5465 MachO::entry_point_command Ep = Obj->getEntryPointCommand(Command);
5466 PrintEntryPointCommand(Ep);
5467 } else if (Command.C.cmd == MachO::LC_ENCRYPTION_INFO) {
5468 MachO::encryption_info_command Ei =
5469 Obj->getEncryptionInfoCommand(Command);
5470 PrintEncryptionInfoCommand(Ei, Buf.size());
5471 } else if (Command.C.cmd == MachO::LC_ENCRYPTION_INFO_64) {
5472 MachO::encryption_info_command_64 Ei =
5473 Obj->getEncryptionInfoCommand64(Command);
5474 PrintEncryptionInfoCommand64(Ei, Buf.size());
5475 } else if (Command.C.cmd == MachO::LC_LINKER_OPTION) {
5476 MachO::linker_option_command Lo =
5477 Obj->getLinkerOptionLoadCommand(Command);
5478 PrintLinkerOptionCommand(Lo, Command.Ptr);
5479 } else if (Command.C.cmd == MachO::LC_SUB_FRAMEWORK) {
5480 MachO::sub_framework_command Sf = Obj->getSubFrameworkCommand(Command);
5481 PrintSubFrameworkCommand(Sf, Command.Ptr);
5482 } else if (Command.C.cmd == MachO::LC_SUB_UMBRELLA) {
5483 MachO::sub_umbrella_command Sf = Obj->getSubUmbrellaCommand(Command);
5484 PrintSubUmbrellaCommand(Sf, Command.Ptr);
5485 } else if (Command.C.cmd == MachO::LC_SUB_LIBRARY) {
5486 MachO::sub_library_command Sl = Obj->getSubLibraryCommand(Command);
5487 PrintSubLibraryCommand(Sl, Command.Ptr);
5488 } else if (Command.C.cmd == MachO::LC_SUB_CLIENT) {
5489 MachO::sub_client_command Sc = Obj->getSubClientCommand(Command);
5490 PrintSubClientCommand(Sc, Command.Ptr);
5491 } else if (Command.C.cmd == MachO::LC_ROUTINES) {
5492 MachO::routines_command Rc = Obj->getRoutinesCommand(Command);
5493 PrintRoutinesCommand(Rc);
5494 } else if (Command.C.cmd == MachO::LC_ROUTINES_64) {
5495 MachO::routines_command_64 Rc = Obj->getRoutinesCommand64(Command);
5496 PrintRoutinesCommand64(Rc);
5497 } else if (Command.C.cmd == MachO::LC_THREAD ||
5498 Command.C.cmd == MachO::LC_UNIXTHREAD) {
5499 MachO::thread_command Tc = Obj->getThreadCommand(Command);
5500 PrintThreadCommand(Tc, Command.Ptr, Obj->isLittleEndian(), cputype);
5501 } else if (Command.C.cmd == MachO::LC_LOAD_DYLIB ||
5502 Command.C.cmd == MachO::LC_ID_DYLIB ||
5503 Command.C.cmd == MachO::LC_LOAD_WEAK_DYLIB ||
5504 Command.C.cmd == MachO::LC_REEXPORT_DYLIB ||
5505 Command.C.cmd == MachO::LC_LAZY_LOAD_DYLIB ||
5506 Command.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB) {
5507 MachO::dylib_command Dl = Obj->getDylibIDLoadCommand(Command);
5508 PrintDylibCommand(Dl, Command.Ptr);
5509 } else if (Command.C.cmd == MachO::LC_CODE_SIGNATURE ||
5510 Command.C.cmd == MachO::LC_SEGMENT_SPLIT_INFO ||
5511 Command.C.cmd == MachO::LC_FUNCTION_STARTS ||
5512 Command.C.cmd == MachO::LC_DATA_IN_CODE ||
5513 Command.C.cmd == MachO::LC_DYLIB_CODE_SIGN_DRS ||
5514 Command.C.cmd == MachO::LC_LINKER_OPTIMIZATION_HINT) {
5515 MachO::linkedit_data_command Ld =
5516 Obj->getLinkeditDataLoadCommand(Command);
5517 PrintLinkEditDataCommand(Ld, Buf.size());
5519 outs() << " cmd ?(" << format("0x%08" PRIx32, Command.C.cmd)
5521 outs() << " cmdsize " << Command.C.cmdsize << "\n";
5522 // TODO: get and print the raw bytes of the load command.
5524 // TODO: print all the other kinds of load commands.
5528 Command = Obj->getNextLoadCommandInfo(Command);
5532 static void getAndPrintMachHeader(const MachOObjectFile *Obj, uint32_t &ncmds,
5533 uint32_t &filetype, uint32_t &cputype,
5535 if (Obj->is64Bit()) {
5536 MachO::mach_header_64 H_64;
5537 H_64 = Obj->getHeader64();
5538 PrintMachHeader(H_64.magic, H_64.cputype, H_64.cpusubtype, H_64.filetype,
5539 H_64.ncmds, H_64.sizeofcmds, H_64.flags, verbose);
5541 filetype = H_64.filetype;
5542 cputype = H_64.cputype;
5544 MachO::mach_header H;
5545 H = Obj->getHeader();
5546 PrintMachHeader(H.magic, H.cputype, H.cpusubtype, H.filetype, H.ncmds,
5547 H.sizeofcmds, H.flags, verbose);
5549 filetype = H.filetype;
5550 cputype = H.cputype;
5554 void llvm::printMachOFileHeader(const object::ObjectFile *Obj) {
5555 const MachOObjectFile *file = dyn_cast<const MachOObjectFile>(Obj);
5557 uint32_t filetype = 0;
5558 uint32_t cputype = 0;
5559 getAndPrintMachHeader(file, ncmds, filetype, cputype, !NonVerbose);
5560 PrintLoadCommands(file, ncmds, filetype, cputype, !NonVerbose);
5563 //===----------------------------------------------------------------------===//
5564 // export trie dumping
5565 //===----------------------------------------------------------------------===//
5567 void llvm::printMachOExportsTrie(const object::MachOObjectFile *Obj) {
5568 for (const llvm::object::ExportEntry &Entry : Obj->exports()) {
5569 uint64_t Flags = Entry.flags();
5570 bool ReExport = (Flags & MachO::EXPORT_SYMBOL_FLAGS_REEXPORT);
5571 bool WeakDef = (Flags & MachO::EXPORT_SYMBOL_FLAGS_WEAK_DEFINITION);
5572 bool ThreadLocal = ((Flags & MachO::EXPORT_SYMBOL_FLAGS_KIND_MASK) ==
5573 MachO::EXPORT_SYMBOL_FLAGS_KIND_THREAD_LOCAL);
5574 bool Abs = ((Flags & MachO::EXPORT_SYMBOL_FLAGS_KIND_MASK) ==
5575 MachO::EXPORT_SYMBOL_FLAGS_KIND_ABSOLUTE);
5576 bool Resolver = (Flags & MachO::EXPORT_SYMBOL_FLAGS_STUB_AND_RESOLVER);
5578 outs() << "[re-export] ";
5580 outs() << format("0x%08llX ",
5581 Entry.address()); // FIXME:add in base address
5582 outs() << Entry.name();
5583 if (WeakDef || ThreadLocal || Resolver || Abs) {
5584 bool NeedsComma = false;
5587 outs() << "weak_def";
5593 outs() << "per-thread";
5599 outs() << "absolute";
5605 outs() << format("resolver=0x%08llX", Entry.other());
5611 StringRef DylibName = "unknown";
5612 int Ordinal = Entry.other() - 1;
5613 Obj->getLibraryShortNameByIndex(Ordinal, DylibName);
5614 if (Entry.otherName().empty())
5615 outs() << " (from " << DylibName << ")";
5617 outs() << " (" << Entry.otherName() << " from " << DylibName << ")";
5623 //===----------------------------------------------------------------------===//
5624 // rebase table dumping
5625 //===----------------------------------------------------------------------===//
5630 SegInfo(const object::MachOObjectFile *Obj);
5632 StringRef segmentName(uint32_t SegIndex);
5633 StringRef sectionName(uint32_t SegIndex, uint64_t SegOffset);
5634 uint64_t address(uint32_t SegIndex, uint64_t SegOffset);
5637 struct SectionInfo {
5640 StringRef SectionName;
5641 StringRef SegmentName;
5642 uint64_t OffsetInSegment;
5643 uint64_t SegmentStartAddress;
5644 uint32_t SegmentIndex;
5646 const SectionInfo &findSection(uint32_t SegIndex, uint64_t SegOffset);
5647 SmallVector<SectionInfo, 32> Sections;
5651 SegInfo::SegInfo(const object::MachOObjectFile *Obj) {
5652 // Build table of sections so segIndex/offset pairs can be translated.
5653 uint32_t CurSegIndex = Obj->hasPageZeroSegment() ? 1 : 0;
5654 StringRef CurSegName;
5655 uint64_t CurSegAddress;
5656 for (const SectionRef &Section : Obj->sections()) {
5658 if (error(Section.getName(Info.SectionName)))
5660 Info.Address = Section.getAddress();
5661 Info.Size = Section.getSize();
5663 Obj->getSectionFinalSegmentName(Section.getRawDataRefImpl());
5664 if (!Info.SegmentName.equals(CurSegName)) {
5666 CurSegName = Info.SegmentName;
5667 CurSegAddress = Info.Address;
5669 Info.SegmentIndex = CurSegIndex - 1;
5670 Info.OffsetInSegment = Info.Address - CurSegAddress;
5671 Info.SegmentStartAddress = CurSegAddress;
5672 Sections.push_back(Info);
5676 StringRef SegInfo::segmentName(uint32_t SegIndex) {
5677 for (const SectionInfo &SI : Sections) {
5678 if (SI.SegmentIndex == SegIndex)
5679 return SI.SegmentName;
5681 llvm_unreachable("invalid segIndex");
5684 const SegInfo::SectionInfo &SegInfo::findSection(uint32_t SegIndex,
5685 uint64_t OffsetInSeg) {
5686 for (const SectionInfo &SI : Sections) {
5687 if (SI.SegmentIndex != SegIndex)
5689 if (SI.OffsetInSegment > OffsetInSeg)
5691 if (OffsetInSeg >= (SI.OffsetInSegment + SI.Size))
5695 llvm_unreachable("segIndex and offset not in any section");
5698 StringRef SegInfo::sectionName(uint32_t SegIndex, uint64_t OffsetInSeg) {
5699 return findSection(SegIndex, OffsetInSeg).SectionName;
5702 uint64_t SegInfo::address(uint32_t SegIndex, uint64_t OffsetInSeg) {
5703 const SectionInfo &SI = findSection(SegIndex, OffsetInSeg);
5704 return SI.SegmentStartAddress + OffsetInSeg;
5707 void llvm::printMachORebaseTable(const object::MachOObjectFile *Obj) {
5708 // Build table of sections so names can used in final output.
5709 SegInfo sectionTable(Obj);
5711 outs() << "segment section address type\n";
5712 for (const llvm::object::MachORebaseEntry &Entry : Obj->rebaseTable()) {
5713 uint32_t SegIndex = Entry.segmentIndex();
5714 uint64_t OffsetInSeg = Entry.segmentOffset();
5715 StringRef SegmentName = sectionTable.segmentName(SegIndex);
5716 StringRef SectionName = sectionTable.sectionName(SegIndex, OffsetInSeg);
5717 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
5719 // Table lines look like: __DATA __nl_symbol_ptr 0x0000F00C pointer
5720 outs() << format("%-8s %-18s 0x%08" PRIX64 " %s\n",
5721 SegmentName.str().c_str(), SectionName.str().c_str(),
5722 Address, Entry.typeName().str().c_str());
5726 static StringRef ordinalName(const object::MachOObjectFile *Obj, int Ordinal) {
5727 StringRef DylibName;
5729 case MachO::BIND_SPECIAL_DYLIB_SELF:
5730 return "this-image";
5731 case MachO::BIND_SPECIAL_DYLIB_MAIN_EXECUTABLE:
5732 return "main-executable";
5733 case MachO::BIND_SPECIAL_DYLIB_FLAT_LOOKUP:
5734 return "flat-namespace";
5737 std::error_code EC =
5738 Obj->getLibraryShortNameByIndex(Ordinal - 1, DylibName);
5740 return "<<bad library ordinal>>";
5744 return "<<unknown special ordinal>>";
5747 //===----------------------------------------------------------------------===//
5748 // bind table dumping
5749 //===----------------------------------------------------------------------===//
5751 void llvm::printMachOBindTable(const object::MachOObjectFile *Obj) {
5752 // Build table of sections so names can used in final output.
5753 SegInfo sectionTable(Obj);
5755 outs() << "segment section address type "
5756 "addend dylib symbol\n";
5757 for (const llvm::object::MachOBindEntry &Entry : Obj->bindTable()) {
5758 uint32_t SegIndex = Entry.segmentIndex();
5759 uint64_t OffsetInSeg = Entry.segmentOffset();
5760 StringRef SegmentName = sectionTable.segmentName(SegIndex);
5761 StringRef SectionName = sectionTable.sectionName(SegIndex, OffsetInSeg);
5762 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
5764 // Table lines look like:
5765 // __DATA __got 0x00012010 pointer 0 libSystem ___stack_chk_guard
5767 if (Entry.flags() & MachO::BIND_SYMBOL_FLAGS_WEAK_IMPORT)
5768 Attr = " (weak_import)";
5769 outs() << left_justify(SegmentName, 8) << " "
5770 << left_justify(SectionName, 18) << " "
5771 << format_hex(Address, 10, true) << " "
5772 << left_justify(Entry.typeName(), 8) << " "
5773 << format_decimal(Entry.addend(), 8) << " "
5774 << left_justify(ordinalName(Obj, Entry.ordinal()), 16) << " "
5775 << Entry.symbolName() << Attr << "\n";
5779 //===----------------------------------------------------------------------===//
5780 // lazy bind table dumping
5781 //===----------------------------------------------------------------------===//
5783 void llvm::printMachOLazyBindTable(const object::MachOObjectFile *Obj) {
5784 // Build table of sections so names can used in final output.
5785 SegInfo sectionTable(Obj);
5787 outs() << "segment section address "
5789 for (const llvm::object::MachOBindEntry &Entry : Obj->lazyBindTable()) {
5790 uint32_t SegIndex = Entry.segmentIndex();
5791 uint64_t OffsetInSeg = Entry.segmentOffset();
5792 StringRef SegmentName = sectionTable.segmentName(SegIndex);
5793 StringRef SectionName = sectionTable.sectionName(SegIndex, OffsetInSeg);
5794 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
5796 // Table lines look like:
5797 // __DATA __got 0x00012010 libSystem ___stack_chk_guard
5798 outs() << left_justify(SegmentName, 8) << " "
5799 << left_justify(SectionName, 18) << " "
5800 << format_hex(Address, 10, true) << " "
5801 << left_justify(ordinalName(Obj, Entry.ordinal()), 16) << " "
5802 << Entry.symbolName() << "\n";
5806 //===----------------------------------------------------------------------===//
5807 // weak bind table dumping
5808 //===----------------------------------------------------------------------===//
5810 void llvm::printMachOWeakBindTable(const object::MachOObjectFile *Obj) {
5811 // Build table of sections so names can used in final output.
5812 SegInfo sectionTable(Obj);
5814 outs() << "segment section address "
5815 "type addend symbol\n";
5816 for (const llvm::object::MachOBindEntry &Entry : Obj->weakBindTable()) {
5817 // Strong symbols don't have a location to update.
5818 if (Entry.flags() & MachO::BIND_SYMBOL_FLAGS_NON_WEAK_DEFINITION) {
5819 outs() << " strong "
5820 << Entry.symbolName() << "\n";
5823 uint32_t SegIndex = Entry.segmentIndex();
5824 uint64_t OffsetInSeg = Entry.segmentOffset();
5825 StringRef SegmentName = sectionTable.segmentName(SegIndex);
5826 StringRef SectionName = sectionTable.sectionName(SegIndex, OffsetInSeg);
5827 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
5829 // Table lines look like:
5830 // __DATA __data 0x00001000 pointer 0 _foo
5831 outs() << left_justify(SegmentName, 8) << " "
5832 << left_justify(SectionName, 18) << " "
5833 << format_hex(Address, 10, true) << " "
5834 << left_justify(Entry.typeName(), 8) << " "
5835 << format_decimal(Entry.addend(), 8) << " " << Entry.symbolName()
5840 // get_dyld_bind_info_symbolname() is used for disassembly and passed an
5841 // address, ReferenceValue, in the Mach-O file and looks in the dyld bind
5842 // information for that address. If the address is found its binding symbol
5843 // name is returned. If not nullptr is returned.
5844 static const char *get_dyld_bind_info_symbolname(uint64_t ReferenceValue,
5845 struct DisassembleInfo *info) {
5846 if (info->bindtable == nullptr) {
5847 info->bindtable = new (BindTable);
5848 SegInfo sectionTable(info->O);
5849 for (const llvm::object::MachOBindEntry &Entry : info->O->bindTable()) {
5850 uint32_t SegIndex = Entry.segmentIndex();
5851 uint64_t OffsetInSeg = Entry.segmentOffset();
5852 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
5853 const char *SymbolName = nullptr;
5854 StringRef name = Entry.symbolName();
5856 SymbolName = name.data();
5857 info->bindtable->push_back(std::make_pair(Address, SymbolName));
5860 for (bind_table_iterator BI = info->bindtable->begin(),
5861 BE = info->bindtable->end();
5863 uint64_t Address = BI->first;
5864 if (ReferenceValue == Address) {
5865 const char *SymbolName = BI->second;