1 //===-- MachODump.cpp - Object file dumping utility for llvm --------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the MachO-specific dumper for llvm-objdump.
12 //===----------------------------------------------------------------------===//
14 #include "llvm-objdump.h"
15 #include "llvm-c/Disassembler.h"
16 #include "llvm/ADT/STLExtras.h"
17 #include "llvm/ADT/StringExtras.h"
18 #include "llvm/ADT/Triple.h"
19 #include "llvm/Config/config.h"
20 #include "llvm/DebugInfo/DWARF/DIContext.h"
21 #include "llvm/MC/MCAsmInfo.h"
22 #include "llvm/MC/MCContext.h"
23 #include "llvm/MC/MCDisassembler.h"
24 #include "llvm/MC/MCInst.h"
25 #include "llvm/MC/MCInstPrinter.h"
26 #include "llvm/MC/MCInstrDesc.h"
27 #include "llvm/MC/MCInstrInfo.h"
28 #include "llvm/MC/MCRegisterInfo.h"
29 #include "llvm/MC/MCSubtargetInfo.h"
30 #include "llvm/Object/MachO.h"
31 #include "llvm/Object/MachOUniversal.h"
32 #include "llvm/Support/Casting.h"
33 #include "llvm/Support/CommandLine.h"
34 #include "llvm/Support/Debug.h"
35 #include "llvm/Support/Endian.h"
36 #include "llvm/Support/Format.h"
37 #include "llvm/Support/FormattedStream.h"
38 #include "llvm/Support/GraphWriter.h"
39 #include "llvm/Support/LEB128.h"
40 #include "llvm/Support/MachO.h"
41 #include "llvm/Support/MemoryBuffer.h"
42 #include "llvm/Support/TargetRegistry.h"
43 #include "llvm/Support/TargetSelect.h"
44 #include "llvm/Support/raw_ostream.h"
47 #include <system_error>
54 using namespace object;
58 cl::desc("Print line information from debug info if available"));
60 static cl::opt<std::string> DSYMFile("dsym",
61 cl::desc("Use .dSYM file for debug info"));
63 static cl::opt<bool> FullLeadingAddr("full-leading-addr",
64 cl::desc("Print full leading address"));
67 PrintImmHex("print-imm-hex",
68 cl::desc("Use hex format for immediate values"));
70 cl::opt<bool> llvm::UniversalHeaders("universal-headers",
71 cl::desc("Print Mach-O universal headers "
72 "(requires -macho)"));
75 llvm::ArchiveHeaders("archive-headers",
76 cl::desc("Print archive headers for Mach-O archives "
77 "(requires -macho)"));
80 llvm::IndirectSymbols("indirect-symbols",
81 cl::desc("Print indirect symbol table for Mach-O "
82 "objects (requires -macho)"));
85 llvm::DataInCode("data-in-code",
86 cl::desc("Print the data in code table for Mach-O objects "
87 "(requires -macho)"));
90 llvm::LinkOptHints("link-opt-hints",
91 cl::desc("Print the linker optimization hints for "
92 "Mach-O objects (requires -macho)"));
95 llvm::DumpSections("section",
96 cl::desc("Prints the specified segment,section for "
97 "Mach-O objects (requires -macho)"));
100 llvm::InfoPlist("info-plist",
101 cl::desc("Print the info plist section as strings for "
102 "Mach-O objects (requires -macho)"));
105 llvm::DylibsUsed("dylibs-used",
106 cl::desc("Print the shared libraries used for linked "
107 "Mach-O files (requires -macho)"));
110 llvm::DylibId("dylib-id",
111 cl::desc("Print the shared library's id for the dylib Mach-O "
112 "file (requires -macho)"));
115 llvm::NonVerbose("non-verbose",
116 cl::desc("Print the info for Mach-O objects in "
117 "non-verbose or numeric form (requires -macho)"));
119 static cl::list<std::string>
120 ArchFlags("arch", cl::desc("architecture(s) from a Mach-O file to dump"),
122 bool ArchAll = false;
124 static std::string ThumbTripleName;
126 static const Target *GetTarget(const MachOObjectFile *MachOObj,
127 const char **McpuDefault,
128 const Target **ThumbTarget) {
129 // Figure out the target triple.
130 if (TripleName.empty()) {
131 llvm::Triple TT("unknown-unknown-unknown");
132 llvm::Triple ThumbTriple = Triple();
133 TT = MachOObj->getArch(McpuDefault, &ThumbTriple);
134 TripleName = TT.str();
135 ThumbTripleName = ThumbTriple.str();
138 // Get the target specific parser.
140 const Target *TheTarget = TargetRegistry::lookupTarget(TripleName, Error);
141 if (TheTarget && ThumbTripleName.empty())
144 *ThumbTarget = TargetRegistry::lookupTarget(ThumbTripleName, Error);
148 errs() << "llvm-objdump: error: unable to get target for '";
150 errs() << TripleName;
152 errs() << ThumbTripleName;
153 errs() << "', see --version and --triple.\n";
157 struct SymbolSorter {
158 bool operator()(const SymbolRef &A, const SymbolRef &B) {
159 SymbolRef::Type AType, BType;
163 uint64_t AAddr, BAddr;
164 if (AType != SymbolRef::ST_Function)
168 if (BType != SymbolRef::ST_Function)
172 return AAddr < BAddr;
176 // Types for the storted data in code table that is built before disassembly
177 // and the predicate function to sort them.
178 typedef std::pair<uint64_t, DiceRef> DiceTableEntry;
179 typedef std::vector<DiceTableEntry> DiceTable;
180 typedef DiceTable::iterator dice_table_iterator;
182 // This is used to search for a data in code table entry for the PC being
183 // disassembled. The j parameter has the PC in j.first. A single data in code
184 // table entry can cover many bytes for each of its Kind's. So if the offset,
185 // aka the i.first value, of the data in code table entry plus its Length
186 // covers the PC being searched for this will return true. If not it will
188 static bool compareDiceTableEntries(const DiceTableEntry &i,
189 const DiceTableEntry &j) {
191 i.second.getLength(Length);
193 return j.first >= i.first && j.first < i.first + Length;
196 static uint64_t DumpDataInCode(const char *bytes, uint64_t Length,
197 unsigned short Kind) {
198 uint32_t Value, Size = 1;
202 case MachO::DICE_KIND_DATA:
205 DumpBytes(StringRef(bytes, 4));
206 Value = bytes[3] << 24 | bytes[2] << 16 | bytes[1] << 8 | bytes[0];
207 outs() << "\t.long " << Value;
209 } else if (Length >= 2) {
211 DumpBytes(StringRef(bytes, 2));
212 Value = bytes[1] << 8 | bytes[0];
213 outs() << "\t.short " << Value;
217 DumpBytes(StringRef(bytes, 2));
219 outs() << "\t.byte " << Value;
222 if (Kind == MachO::DICE_KIND_DATA)
223 outs() << "\t@ KIND_DATA\n";
225 outs() << "\t@ data in code kind = " << Kind << "\n";
227 case MachO::DICE_KIND_JUMP_TABLE8:
229 DumpBytes(StringRef(bytes, 1));
231 outs() << "\t.byte " << format("%3u", Value) << "\t@ KIND_JUMP_TABLE8\n";
234 case MachO::DICE_KIND_JUMP_TABLE16:
236 DumpBytes(StringRef(bytes, 2));
237 Value = bytes[1] << 8 | bytes[0];
238 outs() << "\t.short " << format("%5u", Value & 0xffff)
239 << "\t@ KIND_JUMP_TABLE16\n";
242 case MachO::DICE_KIND_JUMP_TABLE32:
243 case MachO::DICE_KIND_ABS_JUMP_TABLE32:
245 DumpBytes(StringRef(bytes, 4));
246 Value = bytes[3] << 24 | bytes[2] << 16 | bytes[1] << 8 | bytes[0];
247 outs() << "\t.long " << Value;
248 if (Kind == MachO::DICE_KIND_JUMP_TABLE32)
249 outs() << "\t@ KIND_JUMP_TABLE32\n";
251 outs() << "\t@ KIND_ABS_JUMP_TABLE32\n";
258 static void getSectionsAndSymbols(const MachO::mach_header Header,
259 MachOObjectFile *MachOObj,
260 std::vector<SectionRef> &Sections,
261 std::vector<SymbolRef> &Symbols,
262 SmallVectorImpl<uint64_t> &FoundFns,
263 uint64_t &BaseSegmentAddress) {
264 for (const SymbolRef &Symbol : MachOObj->symbols()) {
266 Symbol.getName(SymName);
267 if (!SymName.startswith("ltmp"))
268 Symbols.push_back(Symbol);
271 for (const SectionRef &Section : MachOObj->sections()) {
273 Section.getName(SectName);
274 Sections.push_back(Section);
277 MachOObjectFile::LoadCommandInfo Command =
278 MachOObj->getFirstLoadCommandInfo();
279 bool BaseSegmentAddressSet = false;
280 for (unsigned i = 0;; ++i) {
281 if (Command.C.cmd == MachO::LC_FUNCTION_STARTS) {
282 // We found a function starts segment, parse the addresses for later
284 MachO::linkedit_data_command LLC =
285 MachOObj->getLinkeditDataLoadCommand(Command);
287 MachOObj->ReadULEB128s(LLC.dataoff, FoundFns);
288 } else if (Command.C.cmd == MachO::LC_SEGMENT) {
289 MachO::segment_command SLC = MachOObj->getSegmentLoadCommand(Command);
290 StringRef SegName = SLC.segname;
291 if (!BaseSegmentAddressSet && SegName != "__PAGEZERO") {
292 BaseSegmentAddressSet = true;
293 BaseSegmentAddress = SLC.vmaddr;
297 if (i == Header.ncmds - 1)
300 Command = MachOObj->getNextLoadCommandInfo(Command);
304 static void PrintIndirectSymbolTable(MachOObjectFile *O, bool verbose,
305 uint32_t n, uint32_t count,
306 uint32_t stride, uint64_t addr) {
307 MachO::dysymtab_command Dysymtab = O->getDysymtabLoadCommand();
308 uint32_t nindirectsyms = Dysymtab.nindirectsyms;
309 if (n > nindirectsyms)
310 outs() << " (entries start past the end of the indirect symbol "
311 "table) (reserved1 field greater than the table size)";
312 else if (n + count > nindirectsyms)
313 outs() << " (entries extends past the end of the indirect symbol "
316 uint32_t cputype = O->getHeader().cputype;
317 if (cputype & MachO::CPU_ARCH_ABI64)
318 outs() << "address index";
320 outs() << "address index";
325 for (uint32_t j = 0; j < count && n + j < nindirectsyms; j++) {
326 if (cputype & MachO::CPU_ARCH_ABI64)
327 outs() << format("0x%016" PRIx64, addr + j * stride) << " ";
329 outs() << format("0x%08" PRIx32, addr + j * stride) << " ";
330 MachO::dysymtab_command Dysymtab = O->getDysymtabLoadCommand();
331 uint32_t indirect_symbol = O->getIndirectSymbolTableEntry(Dysymtab, n + j);
332 if (indirect_symbol == MachO::INDIRECT_SYMBOL_LOCAL) {
336 if (indirect_symbol ==
337 (MachO::INDIRECT_SYMBOL_LOCAL | MachO::INDIRECT_SYMBOL_ABS)) {
338 outs() << "LOCAL ABSOLUTE\n";
341 if (indirect_symbol == MachO::INDIRECT_SYMBOL_ABS) {
342 outs() << "ABSOLUTE\n";
345 outs() << format("%5u ", indirect_symbol);
347 MachO::symtab_command Symtab = O->getSymtabLoadCommand();
348 if (indirect_symbol < Symtab.nsyms) {
349 symbol_iterator Sym = O->getSymbolByIndex(indirect_symbol);
350 SymbolRef Symbol = *Sym;
352 Symbol.getName(SymName);
362 static void PrintIndirectSymbols(MachOObjectFile *O, bool verbose) {
363 uint32_t LoadCommandCount = O->getHeader().ncmds;
364 MachOObjectFile::LoadCommandInfo Load = O->getFirstLoadCommandInfo();
365 for (unsigned I = 0;; ++I) {
366 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
367 MachO::segment_command_64 Seg = O->getSegment64LoadCommand(Load);
368 for (unsigned J = 0; J < Seg.nsects; ++J) {
369 MachO::section_64 Sec = O->getSection64(Load, J);
370 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
371 if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
372 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
373 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
374 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
375 section_type == MachO::S_SYMBOL_STUBS) {
377 if (section_type == MachO::S_SYMBOL_STUBS)
378 stride = Sec.reserved2;
382 outs() << "Can't print indirect symbols for (" << Sec.segname << ","
383 << Sec.sectname << ") "
384 << "(size of stubs in reserved2 field is zero)\n";
387 uint32_t count = Sec.size / stride;
388 outs() << "Indirect symbols for (" << Sec.segname << ","
389 << Sec.sectname << ") " << count << " entries";
390 uint32_t n = Sec.reserved1;
391 PrintIndirectSymbolTable(O, verbose, n, count, stride, Sec.addr);
394 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
395 MachO::segment_command Seg = O->getSegmentLoadCommand(Load);
396 for (unsigned J = 0; J < Seg.nsects; ++J) {
397 MachO::section Sec = O->getSection(Load, J);
398 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
399 if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
400 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
401 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
402 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
403 section_type == MachO::S_SYMBOL_STUBS) {
405 if (section_type == MachO::S_SYMBOL_STUBS)
406 stride = Sec.reserved2;
410 outs() << "Can't print indirect symbols for (" << Sec.segname << ","
411 << Sec.sectname << ") "
412 << "(size of stubs in reserved2 field is zero)\n";
415 uint32_t count = Sec.size / stride;
416 outs() << "Indirect symbols for (" << Sec.segname << ","
417 << Sec.sectname << ") " << count << " entries";
418 uint32_t n = Sec.reserved1;
419 PrintIndirectSymbolTable(O, verbose, n, count, stride, Sec.addr);
423 if (I == LoadCommandCount - 1)
426 Load = O->getNextLoadCommandInfo(Load);
430 static void PrintDataInCodeTable(MachOObjectFile *O, bool verbose) {
431 MachO::linkedit_data_command DIC = O->getDataInCodeLoadCommand();
432 uint32_t nentries = DIC.datasize / sizeof(struct MachO::data_in_code_entry);
433 outs() << "Data in code table (" << nentries << " entries)\n";
434 outs() << "offset length kind\n";
435 for (dice_iterator DI = O->begin_dices(), DE = O->end_dices(); DI != DE;
438 DI->getOffset(Offset);
439 outs() << format("0x%08" PRIx32, Offset) << " ";
441 DI->getLength(Length);
442 outs() << format("%6u", Length) << " ";
447 case MachO::DICE_KIND_DATA:
450 case MachO::DICE_KIND_JUMP_TABLE8:
451 outs() << "JUMP_TABLE8";
453 case MachO::DICE_KIND_JUMP_TABLE16:
454 outs() << "JUMP_TABLE16";
456 case MachO::DICE_KIND_JUMP_TABLE32:
457 outs() << "JUMP_TABLE32";
459 case MachO::DICE_KIND_ABS_JUMP_TABLE32:
460 outs() << "ABS_JUMP_TABLE32";
463 outs() << format("0x%04" PRIx32, Kind);
467 outs() << format("0x%04" PRIx32, Kind);
472 static void PrintLinkOptHints(MachOObjectFile *O) {
473 MachO::linkedit_data_command LohLC = O->getLinkOptHintsLoadCommand();
474 const char *loh = O->getData().substr(LohLC.dataoff, 1).data();
475 uint32_t nloh = LohLC.datasize;
476 outs() << "Linker optimiztion hints (" << nloh << " total bytes)\n";
477 for (uint32_t i = 0; i < nloh;) {
479 uint64_t identifier = decodeULEB128((const uint8_t *)(loh + i), &n);
481 outs() << " identifier " << identifier << " ";
484 switch (identifier) {
486 outs() << "AdrpAdrp\n";
489 outs() << "AdrpLdr\n";
492 outs() << "AdrpAddLdr\n";
495 outs() << "AdrpLdrGotLdr\n";
498 outs() << "AdrpAddStr\n";
501 outs() << "AdrpLdrGotStr\n";
504 outs() << "AdrpAdd\n";
507 outs() << "AdrpLdrGot\n";
510 outs() << "Unknown identifier value\n";
513 uint64_t narguments = decodeULEB128((const uint8_t *)(loh + i), &n);
515 outs() << " narguments " << narguments << "\n";
519 for (uint32_t j = 0; j < narguments; j++) {
520 uint64_t value = decodeULEB128((const uint8_t *)(loh + i), &n);
522 outs() << "\tvalue " << format("0x%" PRIx64, value) << "\n";
529 static void PrintDylibs(MachOObjectFile *O, bool JustId) {
530 uint32_t LoadCommandCount = O->getHeader().ncmds;
531 MachOObjectFile::LoadCommandInfo Load = O->getFirstLoadCommandInfo();
532 for (unsigned I = 0;; ++I) {
533 if ((JustId && Load.C.cmd == MachO::LC_ID_DYLIB) ||
534 (!JustId && (Load.C.cmd == MachO::LC_ID_DYLIB ||
535 Load.C.cmd == MachO::LC_LOAD_DYLIB ||
536 Load.C.cmd == MachO::LC_LOAD_WEAK_DYLIB ||
537 Load.C.cmd == MachO::LC_REEXPORT_DYLIB ||
538 Load.C.cmd == MachO::LC_LAZY_LOAD_DYLIB ||
539 Load.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB))) {
540 MachO::dylib_command dl = O->getDylibIDLoadCommand(Load);
541 if (dl.dylib.name < dl.cmdsize) {
542 const char *p = (const char *)(Load.Ptr) + dl.dylib.name;
547 outs() << " (compatibility version "
548 << ((dl.dylib.compatibility_version >> 16) & 0xffff) << "."
549 << ((dl.dylib.compatibility_version >> 8) & 0xff) << "."
550 << (dl.dylib.compatibility_version & 0xff) << ",";
551 outs() << " current version "
552 << ((dl.dylib.current_version >> 16) & 0xffff) << "."
553 << ((dl.dylib.current_version >> 8) & 0xff) << "."
554 << (dl.dylib.current_version & 0xff) << ")\n";
557 outs() << "\tBad offset (" << dl.dylib.name << ") for name of ";
558 if (Load.C.cmd == MachO::LC_ID_DYLIB)
559 outs() << "LC_ID_DYLIB ";
560 else if (Load.C.cmd == MachO::LC_LOAD_DYLIB)
561 outs() << "LC_LOAD_DYLIB ";
562 else if (Load.C.cmd == MachO::LC_LOAD_WEAK_DYLIB)
563 outs() << "LC_LOAD_WEAK_DYLIB ";
564 else if (Load.C.cmd == MachO::LC_LAZY_LOAD_DYLIB)
565 outs() << "LC_LAZY_LOAD_DYLIB ";
566 else if (Load.C.cmd == MachO::LC_REEXPORT_DYLIB)
567 outs() << "LC_REEXPORT_DYLIB ";
568 else if (Load.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB)
569 outs() << "LC_LOAD_UPWARD_DYLIB ";
572 outs() << "command " << I << "\n";
575 if (I == LoadCommandCount - 1)
578 Load = O->getNextLoadCommandInfo(Load);
582 typedef DenseMap<uint64_t, StringRef> SymbolAddressMap;
584 static void CreateSymbolAddressMap(MachOObjectFile *O,
585 SymbolAddressMap *AddrMap) {
586 // Create a map of symbol addresses to symbol names.
587 for (const SymbolRef &Symbol : O->symbols()) {
590 if (ST == SymbolRef::ST_Function || ST == SymbolRef::ST_Data ||
591 ST == SymbolRef::ST_Other) {
593 Symbol.getAddress(Address);
595 Symbol.getName(SymName);
596 (*AddrMap)[Address] = SymName;
601 // GuessSymbolName is passed the address of what might be a symbol and a
602 // pointer to the SymbolAddressMap. It returns the name of a symbol
603 // with that address or nullptr if no symbol is found with that address.
604 static const char *GuessSymbolName(uint64_t value, SymbolAddressMap *AddrMap) {
605 const char *SymbolName = nullptr;
606 // A DenseMap can't lookup up some values.
607 if (value != 0xffffffffffffffffULL && value != 0xfffffffffffffffeULL) {
608 StringRef name = AddrMap->lookup(value);
610 SymbolName = name.data();
615 static void DumpCstringChar(const char c) {
619 outs().write_escaped(p);
622 static void DumpCstringSection(MachOObjectFile *O, const char *sect,
623 uint32_t sect_size, uint64_t sect_addr,
624 bool print_addresses) {
625 for (uint32_t i = 0; i < sect_size; i++) {
626 if (print_addresses) {
628 outs() << format("%016" PRIx64, sect_addr + i) << " ";
630 outs() << format("%08" PRIx64, sect_addr + i) << " ";
632 for (; i < sect_size && sect[i] != '\0'; i++)
633 DumpCstringChar(sect[i]);
634 if (i < sect_size && sect[i] == '\0')
639 static void DumpLiteral4(uint32_t l, float f) {
640 outs() << format("0x%08" PRIx32, l);
641 if ((l & 0x7f800000) != 0x7f800000)
642 outs() << format(" (%.16e)\n", f);
645 outs() << " (+Infinity)\n";
646 else if (l == 0xff800000)
647 outs() << " (-Infinity)\n";
648 else if ((l & 0x00400000) == 0x00400000)
649 outs() << " (non-signaling Not-a-Number)\n";
651 outs() << " (signaling Not-a-Number)\n";
655 static void DumpLiteral4Section(MachOObjectFile *O, const char *sect,
656 uint32_t sect_size, uint64_t sect_addr,
657 bool print_addresses) {
658 for (uint32_t i = 0; i < sect_size; i += sizeof(float)) {
659 if (print_addresses) {
661 outs() << format("%016" PRIx64, sect_addr + i) << " ";
663 outs() << format("%08" PRIx64, sect_addr + i) << " ";
666 memcpy(&f, sect + i, sizeof(float));
667 if (O->isLittleEndian() != sys::IsLittleEndianHost)
668 sys::swapByteOrder(f);
670 memcpy(&l, sect + i, sizeof(uint32_t));
671 if (O->isLittleEndian() != sys::IsLittleEndianHost)
672 sys::swapByteOrder(l);
677 static void DumpLiteral8(MachOObjectFile *O, uint32_t l0, uint32_t l1,
679 outs() << format("0x%08" PRIx32, l0) << " " << format("0x%08" PRIx32, l1);
681 if (O->isLittleEndian()) {
688 // Hi is the high word, so this is equivalent to if(isfinite(d))
689 if ((Hi & 0x7ff00000) != 0x7ff00000)
690 outs() << format(" (%.16e)\n", d);
692 if (Hi == 0x7ff00000 && Lo == 0)
693 outs() << " (+Infinity)\n";
694 else if (Hi == 0xfff00000 && Lo == 0)
695 outs() << " (-Infinity)\n";
696 else if ((Hi & 0x00080000) == 0x00080000)
697 outs() << " (non-signaling Not-a-Number)\n";
699 outs() << " (signaling Not-a-Number)\n";
703 static void DumpLiteral8Section(MachOObjectFile *O, const char *sect,
704 uint32_t sect_size, uint64_t sect_addr,
705 bool print_addresses) {
706 for (uint32_t i = 0; i < sect_size; i += sizeof(double)) {
707 if (print_addresses) {
709 outs() << format("%016" PRIx64, sect_addr + i) << " ";
711 outs() << format("%08" PRIx64, sect_addr + i) << " ";
714 memcpy(&d, sect + i, sizeof(double));
715 if (O->isLittleEndian() != sys::IsLittleEndianHost)
716 sys::swapByteOrder(d);
718 memcpy(&l0, sect + i, sizeof(uint32_t));
719 memcpy(&l1, sect + i + sizeof(uint32_t), sizeof(uint32_t));
720 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
721 sys::swapByteOrder(l0);
722 sys::swapByteOrder(l1);
724 DumpLiteral8(O, l0, l1, d);
728 static void DumpLiteral16(uint32_t l0, uint32_t l1, uint32_t l2, uint32_t l3) {
729 outs() << format("0x%08" PRIx32, l0) << " ";
730 outs() << format("0x%08" PRIx32, l1) << " ";
731 outs() << format("0x%08" PRIx32, l2) << " ";
732 outs() << format("0x%08" PRIx32, l3) << "\n";
735 static void DumpLiteral16Section(MachOObjectFile *O, const char *sect,
736 uint32_t sect_size, uint64_t sect_addr,
737 bool print_addresses) {
738 for (uint32_t i = 0; i < sect_size; i += 16) {
739 if (print_addresses) {
741 outs() << format("%016" PRIx64, sect_addr + i) << " ";
743 outs() << format("%08" PRIx64, sect_addr + i) << " ";
745 uint32_t l0, l1, l2, l3;
746 memcpy(&l0, sect + i, sizeof(uint32_t));
747 memcpy(&l1, sect + i + sizeof(uint32_t), sizeof(uint32_t));
748 memcpy(&l2, sect + i + 2 * sizeof(uint32_t), sizeof(uint32_t));
749 memcpy(&l3, sect + i + 3 * sizeof(uint32_t), sizeof(uint32_t));
750 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
751 sys::swapByteOrder(l0);
752 sys::swapByteOrder(l1);
753 sys::swapByteOrder(l2);
754 sys::swapByteOrder(l3);
756 DumpLiteral16(l0, l1, l2, l3);
760 static void DumpLiteralPointerSection(MachOObjectFile *O,
761 const SectionRef &Section,
762 const char *sect, uint32_t sect_size,
764 bool print_addresses) {
765 // Collect the literal sections in this Mach-O file.
766 std::vector<SectionRef> LiteralSections;
767 for (const SectionRef &Section : O->sections()) {
768 DataRefImpl Ref = Section.getRawDataRefImpl();
769 uint32_t section_type;
771 const MachO::section_64 Sec = O->getSection64(Ref);
772 section_type = Sec.flags & MachO::SECTION_TYPE;
774 const MachO::section Sec = O->getSection(Ref);
775 section_type = Sec.flags & MachO::SECTION_TYPE;
777 if (section_type == MachO::S_CSTRING_LITERALS ||
778 section_type == MachO::S_4BYTE_LITERALS ||
779 section_type == MachO::S_8BYTE_LITERALS ||
780 section_type == MachO::S_16BYTE_LITERALS)
781 LiteralSections.push_back(Section);
784 // Set the size of the literal pointer.
785 uint32_t lp_size = O->is64Bit() ? 8 : 4;
787 // Collect the external relocation symbols for the the literal pointers.
788 std::vector<std::pair<uint64_t, SymbolRef>> Relocs;
789 for (const RelocationRef &Reloc : Section.relocations()) {
791 MachO::any_relocation_info RE;
792 bool isExtern = false;
793 Rel = Reloc.getRawDataRefImpl();
794 RE = O->getRelocation(Rel);
795 isExtern = O->getPlainRelocationExternal(RE);
797 uint64_t RelocOffset;
798 Reloc.getOffset(RelocOffset);
799 symbol_iterator RelocSym = Reloc.getSymbol();
800 Relocs.push_back(std::make_pair(RelocOffset, *RelocSym));
803 array_pod_sort(Relocs.begin(), Relocs.end());
805 // Dump each literal pointer.
806 for (uint32_t i = 0; i < sect_size; i += lp_size) {
807 if (print_addresses) {
809 outs() << format("%016" PRIx64, sect_addr + i) << " ";
811 outs() << format("%08" PRIx64, sect_addr + i) << " ";
815 memcpy(&lp, sect + i, sizeof(uint64_t));
816 if (O->isLittleEndian() != sys::IsLittleEndianHost)
817 sys::swapByteOrder(lp);
820 memcpy(&li, sect + i, sizeof(uint32_t));
821 if (O->isLittleEndian() != sys::IsLittleEndianHost)
822 sys::swapByteOrder(li);
826 // First look for an external relocation entry for this literal pointer.
827 bool reloc_found = false;
828 for (unsigned j = 0, e = Relocs.size(); j != e; ++j) {
829 if (Relocs[i].first == i) {
830 symbol_iterator RelocSym = Relocs[j].second;
832 RelocSym->getName(SymName);
833 outs() << "external relocation entry for symbol:" << SymName << "\n";
837 if (reloc_found == true)
840 // For local references see what the section the literal pointer points to.
842 for (unsigned SectIdx = 0; SectIdx != LiteralSections.size(); SectIdx++) {
843 uint64_t SectAddress = LiteralSections[SectIdx].getAddress();
844 uint64_t SectSize = LiteralSections[SectIdx].getSize();
845 if (lp >= SectAddress && lp < SectAddress + SectSize) {
849 LiteralSections[SectIdx].getName(SectName);
850 DataRefImpl Ref = LiteralSections[SectIdx].getRawDataRefImpl();
851 StringRef SegmentName = O->getSectionFinalSegmentName(Ref);
852 outs() << SegmentName << ":" << SectName << ":";
854 uint32_t section_type;
856 const MachO::section_64 Sec = O->getSection64(Ref);
857 section_type = Sec.flags & MachO::SECTION_TYPE;
859 const MachO::section Sec = O->getSection(Ref);
860 section_type = Sec.flags & MachO::SECTION_TYPE;
864 LiteralSections[SectIdx].getContents(BytesStr);
865 const char *Contents = reinterpret_cast<const char *>(BytesStr.data());
867 switch (section_type) {
868 case MachO::S_CSTRING_LITERALS:
869 for (uint64_t i = lp - SectAddress;
870 i < SectSize && Contents[i] != '\0'; i++) {
871 DumpCstringChar(Contents[i]);
875 case MachO::S_4BYTE_LITERALS:
877 memcpy(&f, Contents + (lp - SectAddress), sizeof(float));
879 memcpy(&l, Contents + (lp - SectAddress), sizeof(uint32_t));
880 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
881 sys::swapByteOrder(f);
882 sys::swapByteOrder(l);
886 case MachO::S_8BYTE_LITERALS: {
888 memcpy(&d, Contents + (lp - SectAddress), sizeof(double));
890 memcpy(&l0, Contents + (lp - SectAddress), sizeof(uint32_t));
891 memcpy(&l1, Contents + (lp - SectAddress) + sizeof(uint32_t),
893 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
894 sys::swapByteOrder(f);
895 sys::swapByteOrder(l0);
896 sys::swapByteOrder(l1);
898 DumpLiteral8(O, l0, l1, d);
901 case MachO::S_16BYTE_LITERALS: {
902 uint32_t l0, l1, l2, l3;
903 memcpy(&l0, Contents + (lp - SectAddress), sizeof(uint32_t));
904 memcpy(&l1, Contents + (lp - SectAddress) + sizeof(uint32_t),
906 memcpy(&l2, Contents + (lp - SectAddress) + 2 * sizeof(uint32_t),
908 memcpy(&l3, Contents + (lp - SectAddress) + 3 * sizeof(uint32_t),
910 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
911 sys::swapByteOrder(l0);
912 sys::swapByteOrder(l1);
913 sys::swapByteOrder(l2);
914 sys::swapByteOrder(l3);
916 DumpLiteral16(l0, l1, l2, l3);
923 outs() << format("0x%" PRIx64, lp) << " (not in a literal section)\n";
927 static void DumpInitTermPointerSection(MachOObjectFile *O, const char *sect,
928 uint32_t sect_size, uint64_t sect_addr,
929 SymbolAddressMap *AddrMap,
933 stride = sizeof(uint64_t);
935 stride = sizeof(uint32_t);
936 for (uint32_t i = 0; i < sect_size; i += stride) {
937 const char *SymbolName = nullptr;
939 outs() << format("0x%016" PRIx64, sect_addr + i * stride) << " ";
940 uint64_t pointer_value;
941 memcpy(&pointer_value, sect + i, stride);
942 if (O->isLittleEndian() != sys::IsLittleEndianHost)
943 sys::swapByteOrder(pointer_value);
944 outs() << format("0x%016" PRIx64, pointer_value);
946 SymbolName = GuessSymbolName(pointer_value, AddrMap);
948 outs() << format("0x%08" PRIx64, sect_addr + i * stride) << " ";
949 uint32_t pointer_value;
950 memcpy(&pointer_value, sect + i, stride);
951 if (O->isLittleEndian() != sys::IsLittleEndianHost)
952 sys::swapByteOrder(pointer_value);
953 outs() << format("0x%08" PRIx32, pointer_value);
955 SymbolName = GuessSymbolName(pointer_value, AddrMap);
958 outs() << " " << SymbolName;
963 static void DumpRawSectionContents(MachOObjectFile *O, const char *sect,
964 uint32_t size, uint64_t addr) {
965 uint32_t cputype = O->getHeader().cputype;
966 if (cputype == MachO::CPU_TYPE_I386 || cputype == MachO::CPU_TYPE_X86_64) {
968 for (uint32_t i = 0; i < size; i += j, addr += j) {
970 outs() << format("%016" PRIx64, addr) << "\t";
972 outs() << format("%08" PRIx64, addr) << "\t";
973 for (j = 0; j < 16 && i + j < size; j++) {
974 uint8_t byte_word = *(sect + i + j);
975 outs() << format("%02" PRIx32, (uint32_t)byte_word) << " ";
981 for (uint32_t i = 0; i < size; i += j, addr += j) {
983 outs() << format("%016" PRIx64, addr) << "\t";
985 outs() << format("%08" PRIx64, sect) << "\t";
986 for (j = 0; j < 4 * sizeof(int32_t) && i + j < size;
987 j += sizeof(int32_t)) {
988 if (i + j + sizeof(int32_t) < size) {
990 memcpy(&long_word, sect + i + j, sizeof(int32_t));
991 if (O->isLittleEndian() != sys::IsLittleEndianHost)
992 sys::swapByteOrder(long_word);
993 outs() << format("%08" PRIx32, long_word) << " ";
995 for (uint32_t k = 0; i + j + k < size; k++) {
996 uint8_t byte_word = *(sect + i + j);
997 outs() << format("%02" PRIx32, (uint32_t)byte_word) << " ";
1006 static void DisassembleMachO(StringRef Filename, MachOObjectFile *MachOOF,
1007 StringRef DisSegName, StringRef DisSectName);
1009 static void DumpSectionContents(StringRef Filename, MachOObjectFile *O,
1011 SymbolAddressMap AddrMap;
1013 CreateSymbolAddressMap(O, &AddrMap);
1015 for (unsigned i = 0; i < DumpSections.size(); ++i) {
1016 StringRef DumpSection = DumpSections[i];
1017 std::pair<StringRef, StringRef> DumpSegSectName;
1018 DumpSegSectName = DumpSection.split(',');
1019 StringRef DumpSegName, DumpSectName;
1020 if (DumpSegSectName.second.size()) {
1021 DumpSegName = DumpSegSectName.first;
1022 DumpSectName = DumpSegSectName.second;
1025 DumpSectName = DumpSegSectName.first;
1027 for (const SectionRef &Section : O->sections()) {
1029 Section.getName(SectName);
1030 DataRefImpl Ref = Section.getRawDataRefImpl();
1031 StringRef SegName = O->getSectionFinalSegmentName(Ref);
1032 if ((DumpSegName.empty() || SegName == DumpSegName) &&
1033 (SectName == DumpSectName)) {
1034 outs() << "Contents of (" << SegName << "," << SectName
1036 uint32_t section_flags;
1038 const MachO::section_64 Sec = O->getSection64(Ref);
1039 section_flags = Sec.flags;
1042 const MachO::section Sec = O->getSection(Ref);
1043 section_flags = Sec.flags;
1045 uint32_t section_type = section_flags & MachO::SECTION_TYPE;
1048 Section.getContents(BytesStr);
1049 const char *sect = reinterpret_cast<const char *>(BytesStr.data());
1050 uint32_t sect_size = BytesStr.size();
1051 uint64_t sect_addr = Section.getAddress();
1054 if ((section_flags & MachO::S_ATTR_PURE_INSTRUCTIONS) ||
1055 (section_flags & MachO::S_ATTR_SOME_INSTRUCTIONS)) {
1056 DisassembleMachO(Filename, O, SegName, SectName);
1059 if (SegName == "__TEXT" && SectName == "__info_plist") {
1063 switch (section_type) {
1064 case MachO::S_REGULAR:
1065 DumpRawSectionContents(O, sect, sect_size, sect_addr);
1067 case MachO::S_ZEROFILL:
1068 outs() << "zerofill section and has no contents in the file\n";
1070 case MachO::S_CSTRING_LITERALS:
1071 DumpCstringSection(O, sect, sect_size, sect_addr, verbose);
1073 case MachO::S_4BYTE_LITERALS:
1074 DumpLiteral4Section(O, sect, sect_size, sect_addr, verbose);
1076 case MachO::S_8BYTE_LITERALS:
1077 DumpLiteral8Section(O, sect, sect_size, sect_addr, verbose);
1079 case MachO::S_16BYTE_LITERALS:
1080 DumpLiteral16Section(O, sect, sect_size, sect_addr, verbose);
1082 case MachO::S_LITERAL_POINTERS:
1083 DumpLiteralPointerSection(O, Section, sect, sect_size, sect_addr,
1086 case MachO::S_MOD_INIT_FUNC_POINTERS:
1087 case MachO::S_MOD_TERM_FUNC_POINTERS:
1088 DumpInitTermPointerSection(O, sect, sect_size, sect_addr, &AddrMap,
1092 outs() << "Unknown section type ("
1093 << format("0x%08" PRIx32, section_type) << ")\n";
1094 DumpRawSectionContents(O, sect, sect_size, sect_addr);
1098 if (section_type == MachO::S_ZEROFILL)
1099 outs() << "zerofill section and has no contents in the file\n";
1101 DumpRawSectionContents(O, sect, sect_size, sect_addr);
1108 static void DumpInfoPlistSectionContents(StringRef Filename,
1109 MachOObjectFile *O) {
1110 for (const SectionRef &Section : O->sections()) {
1112 Section.getName(SectName);
1113 DataRefImpl Ref = Section.getRawDataRefImpl();
1114 StringRef SegName = O->getSectionFinalSegmentName(Ref);
1115 if (SegName == "__TEXT" && SectName == "__info_plist") {
1116 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
1118 Section.getContents(BytesStr);
1119 const char *sect = reinterpret_cast<const char *>(BytesStr.data());
1126 // checkMachOAndArchFlags() checks to see if the ObjectFile is a Mach-O file
1127 // and if it is and there is a list of architecture flags is specified then
1128 // check to make sure this Mach-O file is one of those architectures or all
1129 // architectures were specified. If not then an error is generated and this
1130 // routine returns false. Else it returns true.
1131 static bool checkMachOAndArchFlags(ObjectFile *O, StringRef Filename) {
1132 if (isa<MachOObjectFile>(O) && !ArchAll && ArchFlags.size() != 0) {
1133 MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(O);
1134 bool ArchFound = false;
1135 MachO::mach_header H;
1136 MachO::mach_header_64 H_64;
1138 if (MachO->is64Bit()) {
1139 H_64 = MachO->MachOObjectFile::getHeader64();
1140 T = MachOObjectFile::getArch(H_64.cputype, H_64.cpusubtype);
1142 H = MachO->MachOObjectFile::getHeader();
1143 T = MachOObjectFile::getArch(H.cputype, H.cpusubtype);
1146 for (i = 0; i < ArchFlags.size(); ++i) {
1147 if (ArchFlags[i] == T.getArchName())
1152 errs() << "llvm-objdump: file: " + Filename + " does not contain "
1153 << "architecture: " + ArchFlags[i] + "\n";
1160 // ProcessMachO() is passed a single opened Mach-O file, which may be an
1161 // archive member and or in a slice of a universal file. It prints the
1162 // the file name and header info and then processes it according to the
1163 // command line options.
1164 static void ProcessMachO(StringRef Filename, MachOObjectFile *MachOOF,
1165 StringRef ArchiveMemberName = StringRef(),
1166 StringRef ArchitectureName = StringRef()) {
1167 // If we are doing some processing here on the Mach-O file print the header
1168 // info. And don't print it otherwise like in the case of printing the
1169 // UniversalHeaders or ArchiveHeaders.
1170 if (Disassemble || PrivateHeaders || ExportsTrie || Rebase || Bind ||
1171 LazyBind || WeakBind || IndirectSymbols || DataInCode || LinkOptHints ||
1172 DylibsUsed || DylibId || DumpSections.size() != 0) {
1174 if (!ArchiveMemberName.empty())
1175 outs() << '(' << ArchiveMemberName << ')';
1176 if (!ArchitectureName.empty())
1177 outs() << " (architecture " << ArchitectureName << ")";
1182 DisassembleMachO(Filename, MachOOF, "__TEXT", "__text");
1183 if (IndirectSymbols)
1184 PrintIndirectSymbols(MachOOF, !NonVerbose);
1186 PrintDataInCodeTable(MachOOF, !NonVerbose);
1188 PrintLinkOptHints(MachOOF);
1190 PrintRelocations(MachOOF);
1192 PrintSectionHeaders(MachOOF);
1193 if (SectionContents)
1194 PrintSectionContents(MachOOF);
1195 if (DumpSections.size() != 0)
1196 DumpSectionContents(Filename, MachOOF, !NonVerbose);
1198 DumpInfoPlistSectionContents(Filename, MachOOF);
1200 PrintDylibs(MachOOF, false);
1202 PrintDylibs(MachOOF, true);
1204 PrintSymbolTable(MachOOF);
1206 printMachOUnwindInfo(MachOOF);
1208 printMachOFileHeader(MachOOF);
1210 printExportsTrie(MachOOF);
1212 printRebaseTable(MachOOF);
1214 printBindTable(MachOOF);
1216 printLazyBindTable(MachOOF);
1218 printWeakBindTable(MachOOF);
1221 // printUnknownCPUType() helps print_fat_headers for unknown CPU's.
1222 static void printUnknownCPUType(uint32_t cputype, uint32_t cpusubtype) {
1223 outs() << " cputype (" << cputype << ")\n";
1224 outs() << " cpusubtype (" << cpusubtype << ")\n";
1227 // printCPUType() helps print_fat_headers by printing the cputype and
1228 // pusubtype (symbolically for the one's it knows about).
1229 static void printCPUType(uint32_t cputype, uint32_t cpusubtype) {
1231 case MachO::CPU_TYPE_I386:
1232 switch (cpusubtype) {
1233 case MachO::CPU_SUBTYPE_I386_ALL:
1234 outs() << " cputype CPU_TYPE_I386\n";
1235 outs() << " cpusubtype CPU_SUBTYPE_I386_ALL\n";
1238 printUnknownCPUType(cputype, cpusubtype);
1242 case MachO::CPU_TYPE_X86_64:
1243 switch (cpusubtype) {
1244 case MachO::CPU_SUBTYPE_X86_64_ALL:
1245 outs() << " cputype CPU_TYPE_X86_64\n";
1246 outs() << " cpusubtype CPU_SUBTYPE_X86_64_ALL\n";
1248 case MachO::CPU_SUBTYPE_X86_64_H:
1249 outs() << " cputype CPU_TYPE_X86_64\n";
1250 outs() << " cpusubtype CPU_SUBTYPE_X86_64_H\n";
1253 printUnknownCPUType(cputype, cpusubtype);
1257 case MachO::CPU_TYPE_ARM:
1258 switch (cpusubtype) {
1259 case MachO::CPU_SUBTYPE_ARM_ALL:
1260 outs() << " cputype CPU_TYPE_ARM\n";
1261 outs() << " cpusubtype CPU_SUBTYPE_ARM_ALL\n";
1263 case MachO::CPU_SUBTYPE_ARM_V4T:
1264 outs() << " cputype CPU_TYPE_ARM\n";
1265 outs() << " cpusubtype CPU_SUBTYPE_ARM_V4T\n";
1267 case MachO::CPU_SUBTYPE_ARM_V5TEJ:
1268 outs() << " cputype CPU_TYPE_ARM\n";
1269 outs() << " cpusubtype CPU_SUBTYPE_ARM_V5TEJ\n";
1271 case MachO::CPU_SUBTYPE_ARM_XSCALE:
1272 outs() << " cputype CPU_TYPE_ARM\n";
1273 outs() << " cpusubtype CPU_SUBTYPE_ARM_XSCALE\n";
1275 case MachO::CPU_SUBTYPE_ARM_V6:
1276 outs() << " cputype CPU_TYPE_ARM\n";
1277 outs() << " cpusubtype CPU_SUBTYPE_ARM_V6\n";
1279 case MachO::CPU_SUBTYPE_ARM_V6M:
1280 outs() << " cputype CPU_TYPE_ARM\n";
1281 outs() << " cpusubtype CPU_SUBTYPE_ARM_V6M\n";
1283 case MachO::CPU_SUBTYPE_ARM_V7:
1284 outs() << " cputype CPU_TYPE_ARM\n";
1285 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7\n";
1287 case MachO::CPU_SUBTYPE_ARM_V7EM:
1288 outs() << " cputype CPU_TYPE_ARM\n";
1289 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7EM\n";
1291 case MachO::CPU_SUBTYPE_ARM_V7K:
1292 outs() << " cputype CPU_TYPE_ARM\n";
1293 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7K\n";
1295 case MachO::CPU_SUBTYPE_ARM_V7M:
1296 outs() << " cputype CPU_TYPE_ARM\n";
1297 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7M\n";
1299 case MachO::CPU_SUBTYPE_ARM_V7S:
1300 outs() << " cputype CPU_TYPE_ARM\n";
1301 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7S\n";
1304 printUnknownCPUType(cputype, cpusubtype);
1308 case MachO::CPU_TYPE_ARM64:
1309 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
1310 case MachO::CPU_SUBTYPE_ARM64_ALL:
1311 outs() << " cputype CPU_TYPE_ARM64\n";
1312 outs() << " cpusubtype CPU_SUBTYPE_ARM64_ALL\n";
1315 printUnknownCPUType(cputype, cpusubtype);
1320 printUnknownCPUType(cputype, cpusubtype);
1325 static void printMachOUniversalHeaders(const object::MachOUniversalBinary *UB,
1327 outs() << "Fat headers\n";
1329 outs() << "fat_magic FAT_MAGIC\n";
1331 outs() << "fat_magic " << format("0x%" PRIx32, MachO::FAT_MAGIC) << "\n";
1333 uint32_t nfat_arch = UB->getNumberOfObjects();
1334 StringRef Buf = UB->getData();
1335 uint64_t size = Buf.size();
1336 uint64_t big_size = sizeof(struct MachO::fat_header) +
1337 nfat_arch * sizeof(struct MachO::fat_arch);
1338 outs() << "nfat_arch " << UB->getNumberOfObjects();
1340 outs() << " (malformed, contains zero architecture types)\n";
1341 else if (big_size > size)
1342 outs() << " (malformed, architectures past end of file)\n";
1346 for (uint32_t i = 0; i < nfat_arch; ++i) {
1347 MachOUniversalBinary::ObjectForArch OFA(UB, i);
1348 uint32_t cputype = OFA.getCPUType();
1349 uint32_t cpusubtype = OFA.getCPUSubType();
1350 outs() << "architecture ";
1351 for (uint32_t j = 0; i != 0 && j <= i - 1; j++) {
1352 MachOUniversalBinary::ObjectForArch other_OFA(UB, j);
1353 uint32_t other_cputype = other_OFA.getCPUType();
1354 uint32_t other_cpusubtype = other_OFA.getCPUSubType();
1355 if (cputype != 0 && cpusubtype != 0 && cputype == other_cputype &&
1356 (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) ==
1357 (other_cpusubtype & ~MachO::CPU_SUBTYPE_MASK)) {
1358 outs() << "(illegal duplicate architecture) ";
1363 outs() << OFA.getArchTypeName() << "\n";
1364 printCPUType(cputype, cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
1366 outs() << i << "\n";
1367 outs() << " cputype " << cputype << "\n";
1368 outs() << " cpusubtype " << (cpusubtype & ~MachO::CPU_SUBTYPE_MASK)
1372 (cpusubtype & MachO::CPU_SUBTYPE_MASK) == MachO::CPU_SUBTYPE_LIB64)
1373 outs() << " capabilities CPU_SUBTYPE_LIB64\n";
1375 outs() << " capabilities "
1376 << format("0x%" PRIx32,
1377 (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24) << "\n";
1378 outs() << " offset " << OFA.getOffset();
1379 if (OFA.getOffset() > size)
1380 outs() << " (past end of file)";
1381 if (OFA.getOffset() % (1 << OFA.getAlign()) != 0)
1382 outs() << " (not aligned on it's alignment (2^" << OFA.getAlign() << ")";
1384 outs() << " size " << OFA.getSize();
1385 big_size = OFA.getOffset() + OFA.getSize();
1386 if (big_size > size)
1387 outs() << " (past end of file)";
1389 outs() << " align 2^" << OFA.getAlign() << " (" << (1 << OFA.getAlign())
1394 static void printArchiveChild(Archive::Child &C, bool verbose,
1395 bool print_offset) {
1397 outs() << C.getChildOffset() << "\t";
1398 sys::fs::perms Mode = C.getAccessMode();
1400 // FIXME: this first dash, "-", is for (Mode & S_IFMT) == S_IFREG.
1401 // But there is nothing in sys::fs::perms for S_IFMT or S_IFREG.
1403 if (Mode & sys::fs::owner_read)
1407 if (Mode & sys::fs::owner_write)
1411 if (Mode & sys::fs::owner_exe)
1415 if (Mode & sys::fs::group_read)
1419 if (Mode & sys::fs::group_write)
1423 if (Mode & sys::fs::group_exe)
1427 if (Mode & sys::fs::others_read)
1431 if (Mode & sys::fs::others_write)
1435 if (Mode & sys::fs::others_exe)
1440 outs() << format("0%o ", Mode);
1443 unsigned UID = C.getUID();
1444 outs() << format("%3d/", UID);
1445 unsigned GID = C.getGID();
1446 outs() << format("%-3d ", GID);
1447 uint64_t Size = C.getRawSize();
1448 outs() << format("%5" PRId64, Size) << " ";
1450 StringRef RawLastModified = C.getRawLastModified();
1453 if (RawLastModified.getAsInteger(10, Seconds))
1454 outs() << "(date: \"%s\" contains non-decimal chars) " << RawLastModified;
1456 // Since cime(3) returns a 26 character string of the form:
1457 // "Sun Sep 16 01:03:52 1973\n\0"
1458 // just print 24 characters.
1460 outs() << format("%.24s ", ctime(&t));
1463 outs() << RawLastModified << " ";
1467 ErrorOr<StringRef> NameOrErr = C.getName();
1468 if (NameOrErr.getError()) {
1469 StringRef RawName = C.getRawName();
1470 outs() << RawName << "\n";
1472 StringRef Name = NameOrErr.get();
1473 outs() << Name << "\n";
1476 StringRef RawName = C.getRawName();
1477 outs() << RawName << "\n";
1481 static void printArchiveHeaders(Archive *A, bool verbose, bool print_offset) {
1482 if (A->hasSymbolTable()) {
1483 Archive::child_iterator S = A->getSymbolTableChild();
1484 Archive::Child C = *S;
1485 printArchiveChild(C, verbose, print_offset);
1487 for (Archive::child_iterator I = A->child_begin(), E = A->child_end(); I != E;
1489 Archive::Child C = *I;
1490 printArchiveChild(C, verbose, print_offset);
1494 // ParseInputMachO() parses the named Mach-O file in Filename and handles the
1495 // -arch flags selecting just those slices as specified by them and also parses
1496 // archive files. Then for each individual Mach-O file ProcessMachO() is
1497 // called to process the file based on the command line options.
1498 void llvm::ParseInputMachO(StringRef Filename) {
1499 // Check for -arch all and verifiy the -arch flags are valid.
1500 for (unsigned i = 0; i < ArchFlags.size(); ++i) {
1501 if (ArchFlags[i] == "all") {
1504 if (!MachOObjectFile::isValidArch(ArchFlags[i])) {
1505 errs() << "llvm-objdump: Unknown architecture named '" + ArchFlags[i] +
1506 "'for the -arch option\n";
1512 // Attempt to open the binary.
1513 ErrorOr<OwningBinary<Binary>> BinaryOrErr = createBinary(Filename);
1514 if (std::error_code EC = BinaryOrErr.getError()) {
1515 errs() << "llvm-objdump: '" << Filename << "': " << EC.message() << ".\n";
1518 Binary &Bin = *BinaryOrErr.get().getBinary();
1520 if (Archive *A = dyn_cast<Archive>(&Bin)) {
1521 outs() << "Archive : " << Filename << "\n";
1523 printArchiveHeaders(A, true, false);
1524 for (Archive::child_iterator I = A->child_begin(), E = A->child_end();
1526 ErrorOr<std::unique_ptr<Binary>> ChildOrErr = I->getAsBinary();
1527 if (ChildOrErr.getError())
1529 if (MachOObjectFile *O = dyn_cast<MachOObjectFile>(&*ChildOrErr.get())) {
1530 if (!checkMachOAndArchFlags(O, Filename))
1532 ProcessMachO(Filename, O, O->getFileName());
1537 if (UniversalHeaders) {
1538 if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(&Bin))
1539 printMachOUniversalHeaders(UB, !NonVerbose);
1541 if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(&Bin)) {
1542 // If we have a list of architecture flags specified dump only those.
1543 if (!ArchAll && ArchFlags.size() != 0) {
1544 // Look for a slice in the universal binary that matches each ArchFlag.
1546 for (unsigned i = 0; i < ArchFlags.size(); ++i) {
1548 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
1549 E = UB->end_objects();
1551 if (ArchFlags[i] == I->getArchTypeName()) {
1553 ErrorOr<std::unique_ptr<ObjectFile>> ObjOrErr =
1554 I->getAsObjectFile();
1555 std::string ArchitectureName = "";
1556 if (ArchFlags.size() > 1)
1557 ArchitectureName = I->getArchTypeName();
1559 ObjectFile &O = *ObjOrErr.get();
1560 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&O))
1561 ProcessMachO(Filename, MachOOF, "", ArchitectureName);
1562 } else if (ErrorOr<std::unique_ptr<Archive>> AOrErr =
1563 I->getAsArchive()) {
1564 std::unique_ptr<Archive> &A = *AOrErr;
1565 outs() << "Archive : " << Filename;
1566 if (!ArchitectureName.empty())
1567 outs() << " (architecture " << ArchitectureName << ")";
1570 printArchiveHeaders(A.get(), true, false);
1571 for (Archive::child_iterator AI = A->child_begin(),
1572 AE = A->child_end();
1574 ErrorOr<std::unique_ptr<Binary>> ChildOrErr = AI->getAsBinary();
1575 if (ChildOrErr.getError())
1577 if (MachOObjectFile *O =
1578 dyn_cast<MachOObjectFile>(&*ChildOrErr.get()))
1579 ProcessMachO(Filename, O, O->getFileName(), ArchitectureName);
1585 errs() << "llvm-objdump: file: " + Filename + " does not contain "
1586 << "architecture: " + ArchFlags[i] + "\n";
1592 // No architecture flags were specified so if this contains a slice that
1593 // matches the host architecture dump only that.
1595 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
1596 E = UB->end_objects();
1598 if (MachOObjectFile::getHostArch().getArchName() ==
1599 I->getArchTypeName()) {
1600 ErrorOr<std::unique_ptr<ObjectFile>> ObjOrErr = I->getAsObjectFile();
1601 std::string ArchiveName;
1602 ArchiveName.clear();
1604 ObjectFile &O = *ObjOrErr.get();
1605 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&O))
1606 ProcessMachO(Filename, MachOOF);
1607 } else if (ErrorOr<std::unique_ptr<Archive>> AOrErr =
1608 I->getAsArchive()) {
1609 std::unique_ptr<Archive> &A = *AOrErr;
1610 outs() << "Archive : " << Filename << "\n";
1612 printArchiveHeaders(A.get(), true, false);
1613 for (Archive::child_iterator AI = A->child_begin(),
1614 AE = A->child_end();
1616 ErrorOr<std::unique_ptr<Binary>> ChildOrErr = AI->getAsBinary();
1617 if (ChildOrErr.getError())
1619 if (MachOObjectFile *O =
1620 dyn_cast<MachOObjectFile>(&*ChildOrErr.get()))
1621 ProcessMachO(Filename, O, O->getFileName());
1628 // Either all architectures have been specified or none have been specified
1629 // and this does not contain the host architecture so dump all the slices.
1630 bool moreThanOneArch = UB->getNumberOfObjects() > 1;
1631 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
1632 E = UB->end_objects();
1634 ErrorOr<std::unique_ptr<ObjectFile>> ObjOrErr = I->getAsObjectFile();
1635 std::string ArchitectureName = "";
1636 if (moreThanOneArch)
1637 ArchitectureName = I->getArchTypeName();
1639 ObjectFile &Obj = *ObjOrErr.get();
1640 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&Obj))
1641 ProcessMachO(Filename, MachOOF, "", ArchitectureName);
1642 } else if (ErrorOr<std::unique_ptr<Archive>> AOrErr = I->getAsArchive()) {
1643 std::unique_ptr<Archive> &A = *AOrErr;
1644 outs() << "Archive : " << Filename;
1645 if (!ArchitectureName.empty())
1646 outs() << " (architecture " << ArchitectureName << ")";
1649 printArchiveHeaders(A.get(), true, false);
1650 for (Archive::child_iterator AI = A->child_begin(), AE = A->child_end();
1652 ErrorOr<std::unique_ptr<Binary>> ChildOrErr = AI->getAsBinary();
1653 if (ChildOrErr.getError())
1655 if (MachOObjectFile *O =
1656 dyn_cast<MachOObjectFile>(&*ChildOrErr.get())) {
1657 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(O))
1658 ProcessMachO(Filename, MachOOF, MachOOF->getFileName(),
1666 if (ObjectFile *O = dyn_cast<ObjectFile>(&Bin)) {
1667 if (!checkMachOAndArchFlags(O, Filename))
1669 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&*O)) {
1670 ProcessMachO(Filename, MachOOF);
1672 errs() << "llvm-objdump: '" << Filename << "': "
1673 << "Object is not a Mach-O file type.\n";
1675 errs() << "llvm-objdump: '" << Filename << "': "
1676 << "Unrecognized file type.\n";
1679 typedef std::pair<uint64_t, const char *> BindInfoEntry;
1680 typedef std::vector<BindInfoEntry> BindTable;
1681 typedef BindTable::iterator bind_table_iterator;
1683 // The block of info used by the Symbolizer call backs.
1684 struct DisassembleInfo {
1688 SymbolAddressMap *AddrMap;
1689 std::vector<SectionRef> *Sections;
1690 const char *class_name;
1691 const char *selector_name;
1693 char *demangled_name;
1696 BindTable *bindtable;
1699 // SymbolizerGetOpInfo() is the operand information call back function.
1700 // This is called to get the symbolic information for operand(s) of an
1701 // instruction when it is being done. This routine does this from
1702 // the relocation information, symbol table, etc. That block of information
1703 // is a pointer to the struct DisassembleInfo that was passed when the
1704 // disassembler context was created and passed to back to here when
1705 // called back by the disassembler for instruction operands that could have
1706 // relocation information. The address of the instruction containing operand is
1707 // at the Pc parameter. The immediate value the operand has is passed in
1708 // op_info->Value and is at Offset past the start of the instruction and has a
1709 // byte Size of 1, 2 or 4. The symbolc information is returned in TagBuf is the
1710 // LLVMOpInfo1 struct defined in the header "llvm-c/Disassembler.h" as symbol
1711 // names and addends of the symbolic expression to add for the operand. The
1712 // value of TagType is currently 1 (for the LLVMOpInfo1 struct). If symbolic
1713 // information is returned then this function returns 1 else it returns 0.
1714 static int SymbolizerGetOpInfo(void *DisInfo, uint64_t Pc, uint64_t Offset,
1715 uint64_t Size, int TagType, void *TagBuf) {
1716 struct DisassembleInfo *info = (struct DisassembleInfo *)DisInfo;
1717 struct LLVMOpInfo1 *op_info = (struct LLVMOpInfo1 *)TagBuf;
1718 uint64_t value = op_info->Value;
1720 // Make sure all fields returned are zero if we don't set them.
1721 memset((void *)op_info, '\0', sizeof(struct LLVMOpInfo1));
1722 op_info->Value = value;
1724 // If the TagType is not the value 1 which it code knows about or if no
1725 // verbose symbolic information is wanted then just return 0, indicating no
1726 // information is being returned.
1727 if (TagType != 1 || info->verbose == false)
1730 unsigned int Arch = info->O->getArch();
1731 if (Arch == Triple::x86) {
1732 if (Size != 1 && Size != 2 && Size != 4 && Size != 0)
1734 // First search the section's relocation entries (if any) for an entry
1735 // for this section offset.
1736 uint32_t sect_addr = info->S.getAddress();
1737 uint32_t sect_offset = (Pc + Offset) - sect_addr;
1738 bool reloc_found = false;
1740 MachO::any_relocation_info RE;
1741 bool isExtern = false;
1743 bool r_scattered = false;
1744 uint32_t r_value, pair_r_value, r_type;
1745 for (const RelocationRef &Reloc : info->S.relocations()) {
1746 uint64_t RelocOffset;
1747 Reloc.getOffset(RelocOffset);
1748 if (RelocOffset == sect_offset) {
1749 Rel = Reloc.getRawDataRefImpl();
1750 RE = info->O->getRelocation(Rel);
1751 r_type = info->O->getAnyRelocationType(RE);
1752 r_scattered = info->O->isRelocationScattered(RE);
1754 r_value = info->O->getScatteredRelocationValue(RE);
1755 if (r_type == MachO::GENERIC_RELOC_SECTDIFF ||
1756 r_type == MachO::GENERIC_RELOC_LOCAL_SECTDIFF) {
1757 DataRefImpl RelNext = Rel;
1758 info->O->moveRelocationNext(RelNext);
1759 MachO::any_relocation_info RENext;
1760 RENext = info->O->getRelocation(RelNext);
1761 if (info->O->isRelocationScattered(RENext))
1762 pair_r_value = info->O->getScatteredRelocationValue(RENext);
1767 isExtern = info->O->getPlainRelocationExternal(RE);
1769 symbol_iterator RelocSym = Reloc.getSymbol();
1777 if (reloc_found && isExtern) {
1779 Symbol.getName(SymName);
1780 const char *name = SymName.data();
1781 op_info->AddSymbol.Present = 1;
1782 op_info->AddSymbol.Name = name;
1783 // For i386 extern relocation entries the value in the instruction is
1784 // the offset from the symbol, and value is already set in op_info->Value.
1787 if (reloc_found && (r_type == MachO::GENERIC_RELOC_SECTDIFF ||
1788 r_type == MachO::GENERIC_RELOC_LOCAL_SECTDIFF)) {
1789 const char *add = GuessSymbolName(r_value, info->AddrMap);
1790 const char *sub = GuessSymbolName(pair_r_value, info->AddrMap);
1791 uint32_t offset = value - (r_value - pair_r_value);
1792 op_info->AddSymbol.Present = 1;
1794 op_info->AddSymbol.Name = add;
1796 op_info->AddSymbol.Value = r_value;
1797 op_info->SubtractSymbol.Present = 1;
1799 op_info->SubtractSymbol.Name = sub;
1801 op_info->SubtractSymbol.Value = pair_r_value;
1802 op_info->Value = offset;
1806 // Second search the external relocation entries of a fully linked image
1807 // (if any) for an entry that matches this segment offset.
1808 // uint32_t seg_offset = (Pc + Offset);
1810 } else if (Arch == Triple::x86_64) {
1811 if (Size != 1 && Size != 2 && Size != 4 && Size != 0)
1813 // First search the section's relocation entries (if any) for an entry
1814 // for this section offset.
1815 uint64_t sect_addr = info->S.getAddress();
1816 uint64_t sect_offset = (Pc + Offset) - sect_addr;
1817 bool reloc_found = false;
1819 MachO::any_relocation_info RE;
1820 bool isExtern = false;
1822 for (const RelocationRef &Reloc : info->S.relocations()) {
1823 uint64_t RelocOffset;
1824 Reloc.getOffset(RelocOffset);
1825 if (RelocOffset == sect_offset) {
1826 Rel = Reloc.getRawDataRefImpl();
1827 RE = info->O->getRelocation(Rel);
1828 // NOTE: Scattered relocations don't exist on x86_64.
1829 isExtern = info->O->getPlainRelocationExternal(RE);
1831 symbol_iterator RelocSym = Reloc.getSymbol();
1838 if (reloc_found && isExtern) {
1839 // The Value passed in will be adjusted by the Pc if the instruction
1840 // adds the Pc. But for x86_64 external relocation entries the Value
1841 // is the offset from the external symbol.
1842 if (info->O->getAnyRelocationPCRel(RE))
1843 op_info->Value -= Pc + Offset + Size;
1845 Symbol.getName(SymName);
1846 const char *name = SymName.data();
1847 unsigned Type = info->O->getAnyRelocationType(RE);
1848 if (Type == MachO::X86_64_RELOC_SUBTRACTOR) {
1849 DataRefImpl RelNext = Rel;
1850 info->O->moveRelocationNext(RelNext);
1851 MachO::any_relocation_info RENext = info->O->getRelocation(RelNext);
1852 unsigned TypeNext = info->O->getAnyRelocationType(RENext);
1853 bool isExternNext = info->O->getPlainRelocationExternal(RENext);
1854 unsigned SymbolNum = info->O->getPlainRelocationSymbolNum(RENext);
1855 if (TypeNext == MachO::X86_64_RELOC_UNSIGNED && isExternNext) {
1856 op_info->SubtractSymbol.Present = 1;
1857 op_info->SubtractSymbol.Name = name;
1858 symbol_iterator RelocSymNext = info->O->getSymbolByIndex(SymbolNum);
1859 Symbol = *RelocSymNext;
1860 StringRef SymNameNext;
1861 Symbol.getName(SymNameNext);
1862 name = SymNameNext.data();
1865 // TODO: add the VariantKinds to op_info->VariantKind for relocation types
1866 // like: X86_64_RELOC_TLV, X86_64_RELOC_GOT_LOAD and X86_64_RELOC_GOT.
1867 op_info->AddSymbol.Present = 1;
1868 op_info->AddSymbol.Name = name;
1872 // Second search the external relocation entries of a fully linked image
1873 // (if any) for an entry that matches this segment offset.
1874 // uint64_t seg_offset = (Pc + Offset);
1876 } else if (Arch == Triple::arm) {
1877 if (Offset != 0 || (Size != 4 && Size != 2))
1879 // First search the section's relocation entries (if any) for an entry
1880 // for this section offset.
1881 uint32_t sect_addr = info->S.getAddress();
1882 uint32_t sect_offset = (Pc + Offset) - sect_addr;
1883 bool reloc_found = false;
1885 MachO::any_relocation_info RE;
1886 bool isExtern = false;
1888 bool r_scattered = false;
1889 uint32_t r_value, pair_r_value, r_type, r_length, other_half;
1890 for (const RelocationRef &Reloc : info->S.relocations()) {
1891 uint64_t RelocOffset;
1892 Reloc.getOffset(RelocOffset);
1893 if (RelocOffset == sect_offset) {
1894 Rel = Reloc.getRawDataRefImpl();
1895 RE = info->O->getRelocation(Rel);
1896 r_length = info->O->getAnyRelocationLength(RE);
1897 r_scattered = info->O->isRelocationScattered(RE);
1899 r_value = info->O->getScatteredRelocationValue(RE);
1900 r_type = info->O->getScatteredRelocationType(RE);
1902 r_type = info->O->getAnyRelocationType(RE);
1903 isExtern = info->O->getPlainRelocationExternal(RE);
1905 symbol_iterator RelocSym = Reloc.getSymbol();
1909 if (r_type == MachO::ARM_RELOC_HALF ||
1910 r_type == MachO::ARM_RELOC_SECTDIFF ||
1911 r_type == MachO::ARM_RELOC_LOCAL_SECTDIFF ||
1912 r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
1913 DataRefImpl RelNext = Rel;
1914 info->O->moveRelocationNext(RelNext);
1915 MachO::any_relocation_info RENext;
1916 RENext = info->O->getRelocation(RelNext);
1917 other_half = info->O->getAnyRelocationAddress(RENext) & 0xffff;
1918 if (info->O->isRelocationScattered(RENext))
1919 pair_r_value = info->O->getScatteredRelocationValue(RENext);
1925 if (reloc_found && isExtern) {
1927 Symbol.getName(SymName);
1928 const char *name = SymName.data();
1929 op_info->AddSymbol.Present = 1;
1930 op_info->AddSymbol.Name = name;
1932 case MachO::ARM_RELOC_HALF:
1933 if ((r_length & 0x1) == 1) {
1934 op_info->Value = value << 16 | other_half;
1935 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
1937 op_info->Value = other_half << 16 | value;
1938 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
1946 // If we have a branch that is not an external relocation entry then
1947 // return 0 so the code in tryAddingSymbolicOperand() can use the
1948 // SymbolLookUp call back with the branch target address to look up the
1949 // symbol and possiblity add an annotation for a symbol stub.
1950 if (reloc_found && isExtern == 0 && (r_type == MachO::ARM_RELOC_BR24 ||
1951 r_type == MachO::ARM_THUMB_RELOC_BR22))
1954 uint32_t offset = 0;
1956 if (r_type == MachO::ARM_RELOC_HALF ||
1957 r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
1958 if ((r_length & 0x1) == 1)
1959 value = value << 16 | other_half;
1961 value = other_half << 16 | value;
1963 if (r_scattered && (r_type != MachO::ARM_RELOC_HALF &&
1964 r_type != MachO::ARM_RELOC_HALF_SECTDIFF)) {
1965 offset = value - r_value;
1970 if (reloc_found && r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
1971 if ((r_length & 0x1) == 1)
1972 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
1974 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
1975 const char *add = GuessSymbolName(r_value, info->AddrMap);
1976 const char *sub = GuessSymbolName(pair_r_value, info->AddrMap);
1977 int32_t offset = value - (r_value - pair_r_value);
1978 op_info->AddSymbol.Present = 1;
1980 op_info->AddSymbol.Name = add;
1982 op_info->AddSymbol.Value = r_value;
1983 op_info->SubtractSymbol.Present = 1;
1985 op_info->SubtractSymbol.Name = sub;
1987 op_info->SubtractSymbol.Value = pair_r_value;
1988 op_info->Value = offset;
1992 if (reloc_found == false)
1995 op_info->AddSymbol.Present = 1;
1996 op_info->Value = offset;
1998 if (r_type == MachO::ARM_RELOC_HALF) {
1999 if ((r_length & 0x1) == 1)
2000 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
2002 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
2005 const char *add = GuessSymbolName(value, info->AddrMap);
2006 if (add != nullptr) {
2007 op_info->AddSymbol.Name = add;
2010 op_info->AddSymbol.Value = value;
2012 } else if (Arch == Triple::aarch64) {
2013 if (Offset != 0 || Size != 4)
2015 // First search the section's relocation entries (if any) for an entry
2016 // for this section offset.
2017 uint64_t sect_addr = info->S.getAddress();
2018 uint64_t sect_offset = (Pc + Offset) - sect_addr;
2019 bool reloc_found = false;
2021 MachO::any_relocation_info RE;
2022 bool isExtern = false;
2024 uint32_t r_type = 0;
2025 for (const RelocationRef &Reloc : info->S.relocations()) {
2026 uint64_t RelocOffset;
2027 Reloc.getOffset(RelocOffset);
2028 if (RelocOffset == sect_offset) {
2029 Rel = Reloc.getRawDataRefImpl();
2030 RE = info->O->getRelocation(Rel);
2031 r_type = info->O->getAnyRelocationType(RE);
2032 if (r_type == MachO::ARM64_RELOC_ADDEND) {
2033 DataRefImpl RelNext = Rel;
2034 info->O->moveRelocationNext(RelNext);
2035 MachO::any_relocation_info RENext = info->O->getRelocation(RelNext);
2037 value = info->O->getPlainRelocationSymbolNum(RENext);
2038 op_info->Value = value;
2041 // NOTE: Scattered relocations don't exist on arm64.
2042 isExtern = info->O->getPlainRelocationExternal(RE);
2044 symbol_iterator RelocSym = Reloc.getSymbol();
2051 if (reloc_found && isExtern) {
2053 Symbol.getName(SymName);
2054 const char *name = SymName.data();
2055 op_info->AddSymbol.Present = 1;
2056 op_info->AddSymbol.Name = name;
2059 case MachO::ARM64_RELOC_PAGE21:
2061 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_PAGE;
2063 case MachO::ARM64_RELOC_PAGEOFF12:
2065 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_PAGEOFF;
2067 case MachO::ARM64_RELOC_GOT_LOAD_PAGE21:
2069 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_GOTPAGE;
2071 case MachO::ARM64_RELOC_GOT_LOAD_PAGEOFF12:
2073 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_GOTPAGEOFF;
2075 case MachO::ARM64_RELOC_TLVP_LOAD_PAGE21:
2076 /* @tvlppage is not implemented in llvm-mc */
2077 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_TLVP;
2079 case MachO::ARM64_RELOC_TLVP_LOAD_PAGEOFF12:
2080 /* @tvlppageoff is not implemented in llvm-mc */
2081 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_TLVOFF;
2084 case MachO::ARM64_RELOC_BRANCH26:
2085 op_info->VariantKind = LLVMDisassembler_VariantKind_None;
2096 // GuessCstringPointer is passed the address of what might be a pointer to a
2097 // literal string in a cstring section. If that address is in a cstring section
2098 // it returns a pointer to that string. Else it returns nullptr.
2099 static const char *GuessCstringPointer(uint64_t ReferenceValue,
2100 struct DisassembleInfo *info) {
2101 uint32_t LoadCommandCount = info->O->getHeader().ncmds;
2102 MachOObjectFile::LoadCommandInfo Load = info->O->getFirstLoadCommandInfo();
2103 for (unsigned I = 0;; ++I) {
2104 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
2105 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
2106 for (unsigned J = 0; J < Seg.nsects; ++J) {
2107 MachO::section_64 Sec = info->O->getSection64(Load, J);
2108 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
2109 if (section_type == MachO::S_CSTRING_LITERALS &&
2110 ReferenceValue >= Sec.addr &&
2111 ReferenceValue < Sec.addr + Sec.size) {
2112 uint64_t sect_offset = ReferenceValue - Sec.addr;
2113 uint64_t object_offset = Sec.offset + sect_offset;
2114 StringRef MachOContents = info->O->getData();
2115 uint64_t object_size = MachOContents.size();
2116 const char *object_addr = (const char *)MachOContents.data();
2117 if (object_offset < object_size) {
2118 const char *name = object_addr + object_offset;
2125 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
2126 MachO::segment_command Seg = info->O->getSegmentLoadCommand(Load);
2127 for (unsigned J = 0; J < Seg.nsects; ++J) {
2128 MachO::section Sec = info->O->getSection(Load, J);
2129 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
2130 if (section_type == MachO::S_CSTRING_LITERALS &&
2131 ReferenceValue >= Sec.addr &&
2132 ReferenceValue < Sec.addr + Sec.size) {
2133 uint64_t sect_offset = ReferenceValue - Sec.addr;
2134 uint64_t object_offset = Sec.offset + sect_offset;
2135 StringRef MachOContents = info->O->getData();
2136 uint64_t object_size = MachOContents.size();
2137 const char *object_addr = (const char *)MachOContents.data();
2138 if (object_offset < object_size) {
2139 const char *name = object_addr + object_offset;
2147 if (I == LoadCommandCount - 1)
2150 Load = info->O->getNextLoadCommandInfo(Load);
2155 // GuessIndirectSymbol returns the name of the indirect symbol for the
2156 // ReferenceValue passed in or nullptr. This is used when ReferenceValue maybe
2157 // an address of a symbol stub or a lazy or non-lazy pointer to associate the
2158 // symbol name being referenced by the stub or pointer.
2159 static const char *GuessIndirectSymbol(uint64_t ReferenceValue,
2160 struct DisassembleInfo *info) {
2161 uint32_t LoadCommandCount = info->O->getHeader().ncmds;
2162 MachOObjectFile::LoadCommandInfo Load = info->O->getFirstLoadCommandInfo();
2163 MachO::dysymtab_command Dysymtab = info->O->getDysymtabLoadCommand();
2164 MachO::symtab_command Symtab = info->O->getSymtabLoadCommand();
2165 for (unsigned I = 0;; ++I) {
2166 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
2167 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
2168 for (unsigned J = 0; J < Seg.nsects; ++J) {
2169 MachO::section_64 Sec = info->O->getSection64(Load, J);
2170 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
2171 if ((section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
2172 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
2173 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
2174 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
2175 section_type == MachO::S_SYMBOL_STUBS) &&
2176 ReferenceValue >= Sec.addr &&
2177 ReferenceValue < Sec.addr + Sec.size) {
2179 if (section_type == MachO::S_SYMBOL_STUBS)
2180 stride = Sec.reserved2;
2185 uint32_t index = Sec.reserved1 + (ReferenceValue - Sec.addr) / stride;
2186 if (index < Dysymtab.nindirectsyms) {
2187 uint32_t indirect_symbol =
2188 info->O->getIndirectSymbolTableEntry(Dysymtab, index);
2189 if (indirect_symbol < Symtab.nsyms) {
2190 symbol_iterator Sym = info->O->getSymbolByIndex(indirect_symbol);
2191 SymbolRef Symbol = *Sym;
2193 Symbol.getName(SymName);
2194 const char *name = SymName.data();
2200 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
2201 MachO::segment_command Seg = info->O->getSegmentLoadCommand(Load);
2202 for (unsigned J = 0; J < Seg.nsects; ++J) {
2203 MachO::section Sec = info->O->getSection(Load, J);
2204 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
2205 if ((section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
2206 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
2207 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
2208 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
2209 section_type == MachO::S_SYMBOL_STUBS) &&
2210 ReferenceValue >= Sec.addr &&
2211 ReferenceValue < Sec.addr + Sec.size) {
2213 if (section_type == MachO::S_SYMBOL_STUBS)
2214 stride = Sec.reserved2;
2219 uint32_t index = Sec.reserved1 + (ReferenceValue - Sec.addr) / stride;
2220 if (index < Dysymtab.nindirectsyms) {
2221 uint32_t indirect_symbol =
2222 info->O->getIndirectSymbolTableEntry(Dysymtab, index);
2223 if (indirect_symbol < Symtab.nsyms) {
2224 symbol_iterator Sym = info->O->getSymbolByIndex(indirect_symbol);
2225 SymbolRef Symbol = *Sym;
2227 Symbol.getName(SymName);
2228 const char *name = SymName.data();
2235 if (I == LoadCommandCount - 1)
2238 Load = info->O->getNextLoadCommandInfo(Load);
2243 // method_reference() is called passing it the ReferenceName that might be
2244 // a reference it to an Objective-C method call. If so then it allocates and
2245 // assembles a method call string with the values last seen and saved in
2246 // the DisassembleInfo's class_name and selector_name fields. This is saved
2247 // into the method field of the info and any previous string is free'ed.
2248 // Then the class_name field in the info is set to nullptr. The method call
2249 // string is set into ReferenceName and ReferenceType is set to
2250 // LLVMDisassembler_ReferenceType_Out_Objc_Message. If this not a method call
2251 // then both ReferenceType and ReferenceName are left unchanged.
2252 static void method_reference(struct DisassembleInfo *info,
2253 uint64_t *ReferenceType,
2254 const char **ReferenceName) {
2255 unsigned int Arch = info->O->getArch();
2256 if (*ReferenceName != nullptr) {
2257 if (strcmp(*ReferenceName, "_objc_msgSend") == 0) {
2258 if (info->selector_name != nullptr) {
2259 if (info->method != nullptr)
2261 if (info->class_name != nullptr) {
2262 info->method = (char *)malloc(5 + strlen(info->class_name) +
2263 strlen(info->selector_name));
2264 if (info->method != nullptr) {
2265 strcpy(info->method, "+[");
2266 strcat(info->method, info->class_name);
2267 strcat(info->method, " ");
2268 strcat(info->method, info->selector_name);
2269 strcat(info->method, "]");
2270 *ReferenceName = info->method;
2271 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
2274 info->method = (char *)malloc(9 + strlen(info->selector_name));
2275 if (info->method != nullptr) {
2276 if (Arch == Triple::x86_64)
2277 strcpy(info->method, "-[%rdi ");
2278 else if (Arch == Triple::aarch64)
2279 strcpy(info->method, "-[x0 ");
2281 strcpy(info->method, "-[r? ");
2282 strcat(info->method, info->selector_name);
2283 strcat(info->method, "]");
2284 *ReferenceName = info->method;
2285 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
2288 info->class_name = nullptr;
2290 } else if (strcmp(*ReferenceName, "_objc_msgSendSuper2") == 0) {
2291 if (info->selector_name != nullptr) {
2292 if (info->method != nullptr)
2294 info->method = (char *)malloc(17 + strlen(info->selector_name));
2295 if (info->method != nullptr) {
2296 if (Arch == Triple::x86_64)
2297 strcpy(info->method, "-[[%rdi super] ");
2298 else if (Arch == Triple::aarch64)
2299 strcpy(info->method, "-[[x0 super] ");
2301 strcpy(info->method, "-[[r? super] ");
2302 strcat(info->method, info->selector_name);
2303 strcat(info->method, "]");
2304 *ReferenceName = info->method;
2305 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
2307 info->class_name = nullptr;
2313 // GuessPointerPointer() is passed the address of what might be a pointer to
2314 // a reference to an Objective-C class, selector, message ref or cfstring.
2315 // If so the value of the pointer is returned and one of the booleans are set
2316 // to true. If not zero is returned and all the booleans are set to false.
2317 static uint64_t GuessPointerPointer(uint64_t ReferenceValue,
2318 struct DisassembleInfo *info,
2319 bool &classref, bool &selref, bool &msgref,
2325 uint32_t LoadCommandCount = info->O->getHeader().ncmds;
2326 MachOObjectFile::LoadCommandInfo Load = info->O->getFirstLoadCommandInfo();
2327 for (unsigned I = 0;; ++I) {
2328 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
2329 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
2330 for (unsigned J = 0; J < Seg.nsects; ++J) {
2331 MachO::section_64 Sec = info->O->getSection64(Load, J);
2332 if ((strncmp(Sec.sectname, "__objc_selrefs", 16) == 0 ||
2333 strncmp(Sec.sectname, "__objc_classrefs", 16) == 0 ||
2334 strncmp(Sec.sectname, "__objc_superrefs", 16) == 0 ||
2335 strncmp(Sec.sectname, "__objc_msgrefs", 16) == 0 ||
2336 strncmp(Sec.sectname, "__cfstring", 16) == 0) &&
2337 ReferenceValue >= Sec.addr &&
2338 ReferenceValue < Sec.addr + Sec.size) {
2339 uint64_t sect_offset = ReferenceValue - Sec.addr;
2340 uint64_t object_offset = Sec.offset + sect_offset;
2341 StringRef MachOContents = info->O->getData();
2342 uint64_t object_size = MachOContents.size();
2343 const char *object_addr = (const char *)MachOContents.data();
2344 if (object_offset < object_size) {
2345 uint64_t pointer_value;
2346 memcpy(&pointer_value, object_addr + object_offset,
2348 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
2349 sys::swapByteOrder(pointer_value);
2350 if (strncmp(Sec.sectname, "__objc_selrefs", 16) == 0)
2352 else if (strncmp(Sec.sectname, "__objc_classrefs", 16) == 0 ||
2353 strncmp(Sec.sectname, "__objc_superrefs", 16) == 0)
2355 else if (strncmp(Sec.sectname, "__objc_msgrefs", 16) == 0 &&
2356 ReferenceValue + 8 < Sec.addr + Sec.size) {
2358 memcpy(&pointer_value, object_addr + object_offset + 8,
2360 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
2361 sys::swapByteOrder(pointer_value);
2362 } else if (strncmp(Sec.sectname, "__cfstring", 16) == 0)
2364 return pointer_value;
2371 // TODO: Look for LC_SEGMENT for 32-bit Mach-O files.
2372 if (I == LoadCommandCount - 1)
2375 Load = info->O->getNextLoadCommandInfo(Load);
2380 // get_pointer_64 returns a pointer to the bytes in the object file at the
2381 // Address from a section in the Mach-O file. And indirectly returns the
2382 // offset into the section, number of bytes left in the section past the offset
2383 // and which section is was being referenced. If the Address is not in a
2384 // section nullptr is returned.
2385 static const char *get_pointer_64(uint64_t Address, uint32_t &offset,
2386 uint32_t &left, SectionRef &S,
2387 DisassembleInfo *info) {
2391 for (unsigned SectIdx = 0; SectIdx != info->Sections->size(); SectIdx++) {
2392 uint64_t SectAddress = ((*(info->Sections))[SectIdx]).getAddress();
2393 uint64_t SectSize = ((*(info->Sections))[SectIdx]).getSize();
2394 if (Address >= SectAddress && Address < SectAddress + SectSize) {
2395 S = (*(info->Sections))[SectIdx];
2396 offset = Address - SectAddress;
2397 left = SectSize - offset;
2398 StringRef SectContents;
2399 ((*(info->Sections))[SectIdx]).getContents(SectContents);
2400 return SectContents.data() + offset;
2406 // get_symbol_64() returns the name of a symbol (or nullptr) and the address of
2407 // the symbol indirectly through n_value. Based on the relocation information
2408 // for the specified section offset in the specified section reference.
2409 static const char *get_symbol_64(uint32_t sect_offset, SectionRef S,
2410 DisassembleInfo *info, uint64_t &n_value) {
2412 if (info->verbose == false)
2415 // See if there is an external relocation entry at the sect_offset.
2416 bool reloc_found = false;
2418 MachO::any_relocation_info RE;
2419 bool isExtern = false;
2421 for (const RelocationRef &Reloc : S.relocations()) {
2422 uint64_t RelocOffset;
2423 Reloc.getOffset(RelocOffset);
2424 if (RelocOffset == sect_offset) {
2425 Rel = Reloc.getRawDataRefImpl();
2426 RE = info->O->getRelocation(Rel);
2427 if (info->O->isRelocationScattered(RE))
2429 isExtern = info->O->getPlainRelocationExternal(RE);
2431 symbol_iterator RelocSym = Reloc.getSymbol();
2438 // If there is an external relocation entry for a symbol in this section
2439 // at this section_offset then use that symbol's value for the n_value
2440 // and return its name.
2441 const char *SymbolName = nullptr;
2442 if (reloc_found && isExtern) {
2443 Symbol.getAddress(n_value);
2445 Symbol.getName(name);
2446 if (!name.empty()) {
2447 SymbolName = name.data();
2452 // TODO: For fully linked images, look through the external relocation
2453 // entries off the dynamic symtab command. For these the r_offset is from the
2454 // start of the first writeable segment in the Mach-O file. So the offset
2455 // to this section from that segment is passed to this routine by the caller,
2456 // as the database_offset. Which is the difference of the section's starting
2457 // address and the first writable segment.
2459 // NOTE: need add passing the database_offset to this routine.
2461 // TODO: We did not find an external relocation entry so look up the
2462 // ReferenceValue as an address of a symbol and if found return that symbol's
2465 // NOTE: need add passing the ReferenceValue to this routine. Then that code
2466 // would simply be this:
2467 // SymbolName = GuessSymbolName(ReferenceValue, info->AddrMap);
2472 // These are structs in the Objective-C meta data and read to produce the
2473 // comments for disassembly. While these are part of the ABI they are no
2474 // public defintions. So the are here not in include/llvm/Support/MachO.h .
2476 // The cfstring object in a 64-bit Mach-O file.
2477 struct cfstring64_t {
2478 uint64_t isa; // class64_t * (64-bit pointer)
2479 uint64_t flags; // flag bits
2480 uint64_t characters; // char * (64-bit pointer)
2481 uint64_t length; // number of non-NULL characters in above
2484 // The class object in a 64-bit Mach-O file.
2486 uint64_t isa; // class64_t * (64-bit pointer)
2487 uint64_t superclass; // class64_t * (64-bit pointer)
2488 uint64_t cache; // Cache (64-bit pointer)
2489 uint64_t vtable; // IMP * (64-bit pointer)
2490 uint64_t data; // class_ro64_t * (64-bit pointer)
2493 struct class_ro64_t {
2495 uint32_t instanceStart;
2496 uint32_t instanceSize;
2498 uint64_t ivarLayout; // const uint8_t * (64-bit pointer)
2499 uint64_t name; // const char * (64-bit pointer)
2500 uint64_t baseMethods; // const method_list_t * (64-bit pointer)
2501 uint64_t baseProtocols; // const protocol_list_t * (64-bit pointer)
2502 uint64_t ivars; // const ivar_list_t * (64-bit pointer)
2503 uint64_t weakIvarLayout; // const uint8_t * (64-bit pointer)
2504 uint64_t baseProperties; // const struct objc_property_list (64-bit pointer)
2507 inline void swapStruct(struct cfstring64_t &cfs) {
2508 sys::swapByteOrder(cfs.isa);
2509 sys::swapByteOrder(cfs.flags);
2510 sys::swapByteOrder(cfs.characters);
2511 sys::swapByteOrder(cfs.length);
2514 inline void swapStruct(struct class64_t &c) {
2515 sys::swapByteOrder(c.isa);
2516 sys::swapByteOrder(c.superclass);
2517 sys::swapByteOrder(c.cache);
2518 sys::swapByteOrder(c.vtable);
2519 sys::swapByteOrder(c.data);
2522 inline void swapStruct(struct class_ro64_t &cro) {
2523 sys::swapByteOrder(cro.flags);
2524 sys::swapByteOrder(cro.instanceStart);
2525 sys::swapByteOrder(cro.instanceSize);
2526 sys::swapByteOrder(cro.reserved);
2527 sys::swapByteOrder(cro.ivarLayout);
2528 sys::swapByteOrder(cro.name);
2529 sys::swapByteOrder(cro.baseMethods);
2530 sys::swapByteOrder(cro.baseProtocols);
2531 sys::swapByteOrder(cro.ivars);
2532 sys::swapByteOrder(cro.weakIvarLayout);
2533 sys::swapByteOrder(cro.baseProperties);
2536 static const char *get_dyld_bind_info_symbolname(uint64_t ReferenceValue,
2537 struct DisassembleInfo *info);
2539 // get_objc2_64bit_class_name() is used for disassembly and is passed a pointer
2540 // to an Objective-C class and returns the class name. It is also passed the
2541 // address of the pointer, so when the pointer is zero as it can be in an .o
2542 // file, that is used to look for an external relocation entry with a symbol
2544 static const char *get_objc2_64bit_class_name(uint64_t pointer_value,
2545 uint64_t ReferenceValue,
2546 struct DisassembleInfo *info) {
2548 uint32_t offset, left;
2551 // The pointer_value can be 0 in an object file and have a relocation
2552 // entry for the class symbol at the ReferenceValue (the address of the
2554 if (pointer_value == 0) {
2555 r = get_pointer_64(ReferenceValue, offset, left, S, info);
2556 if (r == nullptr || left < sizeof(uint64_t))
2559 const char *symbol_name = get_symbol_64(offset, S, info, n_value);
2560 if (symbol_name == nullptr)
2562 const char *class_name = strrchr(symbol_name, '$');
2563 if (class_name != nullptr && class_name[1] == '_' && class_name[2] != '\0')
2564 return class_name + 2;
2569 // The case were the pointer_value is non-zero and points to a class defined
2570 // in this Mach-O file.
2571 r = get_pointer_64(pointer_value, offset, left, S, info);
2572 if (r == nullptr || left < sizeof(struct class64_t))
2575 memcpy(&c, r, sizeof(struct class64_t));
2576 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
2580 r = get_pointer_64(c.data, offset, left, S, info);
2581 if (r == nullptr || left < sizeof(struct class_ro64_t))
2583 struct class_ro64_t cro;
2584 memcpy(&cro, r, sizeof(struct class_ro64_t));
2585 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
2589 const char *name = get_pointer_64(cro.name, offset, left, S, info);
2593 // get_objc2_64bit_cfstring_name is used for disassembly and is passed a
2594 // pointer to a cfstring and returns its name or nullptr.
2595 static const char *get_objc2_64bit_cfstring_name(uint64_t ReferenceValue,
2596 struct DisassembleInfo *info) {
2597 const char *r, *name;
2598 uint32_t offset, left;
2600 struct cfstring64_t cfs;
2601 uint64_t cfs_characters;
2603 r = get_pointer_64(ReferenceValue, offset, left, S, info);
2604 if (r == nullptr || left < sizeof(struct cfstring64_t))
2606 memcpy(&cfs, r, sizeof(struct cfstring64_t));
2607 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
2609 if (cfs.characters == 0) {
2611 const char *symbol_name = get_symbol_64(
2612 offset + offsetof(struct cfstring64_t, characters), S, info, n_value);
2613 if (symbol_name == nullptr)
2615 cfs_characters = n_value;
2617 cfs_characters = cfs.characters;
2618 name = get_pointer_64(cfs_characters, offset, left, S, info);
2623 // get_objc2_64bit_selref() is used for disassembly and is passed a the address
2624 // of a pointer to an Objective-C selector reference when the pointer value is
2625 // zero as in a .o file and is likely to have a external relocation entry with
2626 // who's symbol's n_value is the real pointer to the selector name. If that is
2627 // the case the real pointer to the selector name is returned else 0 is
2629 static uint64_t get_objc2_64bit_selref(uint64_t ReferenceValue,
2630 struct DisassembleInfo *info) {
2631 uint32_t offset, left;
2634 const char *r = get_pointer_64(ReferenceValue, offset, left, S, info);
2635 if (r == nullptr || left < sizeof(uint64_t))
2638 const char *symbol_name = get_symbol_64(offset, S, info, n_value);
2639 if (symbol_name == nullptr)
2644 // GuessLiteralPointer returns a string which for the item in the Mach-O file
2645 // for the address passed in as ReferenceValue for printing as a comment with
2646 // the instruction and also returns the corresponding type of that item
2647 // indirectly through ReferenceType.
2649 // If ReferenceValue is an address of literal cstring then a pointer to the
2650 // cstring is returned and ReferenceType is set to
2651 // LLVMDisassembler_ReferenceType_Out_LitPool_CstrAddr .
2653 // If ReferenceValue is an address of an Objective-C CFString, Selector ref or
2654 // Class ref that name is returned and the ReferenceType is set accordingly.
2656 // Lastly, literals which are Symbol address in a literal pool are looked for
2657 // and if found the symbol name is returned and ReferenceType is set to
2658 // LLVMDisassembler_ReferenceType_Out_LitPool_SymAddr .
2660 // If there is no item in the Mach-O file for the address passed in as
2661 // ReferenceValue nullptr is returned and ReferenceType is unchanged.
2662 static const char *GuessLiteralPointer(uint64_t ReferenceValue,
2663 uint64_t ReferencePC,
2664 uint64_t *ReferenceType,
2665 struct DisassembleInfo *info) {
2666 // First see if there is an external relocation entry at the ReferencePC.
2667 uint64_t sect_addr = info->S.getAddress();
2668 uint64_t sect_offset = ReferencePC - sect_addr;
2669 bool reloc_found = false;
2671 MachO::any_relocation_info RE;
2672 bool isExtern = false;
2674 for (const RelocationRef &Reloc : info->S.relocations()) {
2675 uint64_t RelocOffset;
2676 Reloc.getOffset(RelocOffset);
2677 if (RelocOffset == sect_offset) {
2678 Rel = Reloc.getRawDataRefImpl();
2679 RE = info->O->getRelocation(Rel);
2680 if (info->O->isRelocationScattered(RE))
2682 isExtern = info->O->getPlainRelocationExternal(RE);
2684 symbol_iterator RelocSym = Reloc.getSymbol();
2691 // If there is an external relocation entry for a symbol in a section
2692 // then used that symbol's value for the value of the reference.
2693 if (reloc_found && isExtern) {
2694 if (info->O->getAnyRelocationPCRel(RE)) {
2695 unsigned Type = info->O->getAnyRelocationType(RE);
2696 if (Type == MachO::X86_64_RELOC_SIGNED) {
2697 Symbol.getAddress(ReferenceValue);
2702 // Look for literals such as Objective-C CFStrings refs, Selector refs,
2703 // Message refs and Class refs.
2704 bool classref, selref, msgref, cfstring;
2705 uint64_t pointer_value = GuessPointerPointer(ReferenceValue, info, classref,
2706 selref, msgref, cfstring);
2707 if (classref == true && pointer_value == 0) {
2708 // Note the ReferenceValue is a pointer into the __objc_classrefs section.
2709 // And the pointer_value in that section is typically zero as it will be
2710 // set by dyld as part of the "bind information".
2711 const char *name = get_dyld_bind_info_symbolname(ReferenceValue, info);
2712 if (name != nullptr) {
2713 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Class_Ref;
2714 const char *class_name = strrchr(name, '$');
2715 if (class_name != nullptr && class_name[1] == '_' &&
2716 class_name[2] != '\0') {
2717 info->class_name = class_name + 2;
2723 if (classref == true) {
2724 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Class_Ref;
2726 get_objc2_64bit_class_name(pointer_value, ReferenceValue, info);
2727 if (name != nullptr)
2728 info->class_name = name;
2730 name = "bad class ref";
2734 if (cfstring == true) {
2735 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_CFString_Ref;
2736 const char *name = get_objc2_64bit_cfstring_name(ReferenceValue, info);
2740 if (selref == true && pointer_value == 0)
2741 pointer_value = get_objc2_64bit_selref(ReferenceValue, info);
2743 if (pointer_value != 0)
2744 ReferenceValue = pointer_value;
2746 const char *name = GuessCstringPointer(ReferenceValue, info);
2748 if (pointer_value != 0 && selref == true) {
2749 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Selector_Ref;
2750 info->selector_name = name;
2751 } else if (pointer_value != 0 && msgref == true) {
2752 info->class_name = nullptr;
2753 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message_Ref;
2754 info->selector_name = name;
2756 *ReferenceType = LLVMDisassembler_ReferenceType_Out_LitPool_CstrAddr;
2760 // Lastly look for an indirect symbol with this ReferenceValue which is in
2761 // a literal pool. If found return that symbol name.
2762 name = GuessIndirectSymbol(ReferenceValue, info);
2764 *ReferenceType = LLVMDisassembler_ReferenceType_Out_LitPool_SymAddr;
2771 // SymbolizerSymbolLookUp is the symbol lookup function passed when creating
2772 // the Symbolizer. It looks up the ReferenceValue using the info passed via the
2773 // pointer to the struct DisassembleInfo that was passed when MCSymbolizer
2774 // is created and returns the symbol name that matches the ReferenceValue or
2775 // nullptr if none. The ReferenceType is passed in for the IN type of
2776 // reference the instruction is making from the values in defined in the header
2777 // "llvm-c/Disassembler.h". On return the ReferenceType can set to a specific
2778 // Out type and the ReferenceName will also be set which is added as a comment
2779 // to the disassembled instruction.
2782 // If the symbol name is a C++ mangled name then the demangled name is
2783 // returned through ReferenceName and ReferenceType is set to
2784 // LLVMDisassembler_ReferenceType_DeMangled_Name .
2787 // When this is called to get a symbol name for a branch target then the
2788 // ReferenceType will be LLVMDisassembler_ReferenceType_In_Branch and then
2789 // SymbolValue will be looked for in the indirect symbol table to determine if
2790 // it is an address for a symbol stub. If so then the symbol name for that
2791 // stub is returned indirectly through ReferenceName and then ReferenceType is
2792 // set to LLVMDisassembler_ReferenceType_Out_SymbolStub.
2794 // When this is called with an value loaded via a PC relative load then
2795 // ReferenceType will be LLVMDisassembler_ReferenceType_In_PCrel_Load then the
2796 // SymbolValue is checked to be an address of literal pointer, symbol pointer,
2797 // or an Objective-C meta data reference. If so the output ReferenceType is
2798 // set to correspond to that as well as setting the ReferenceName.
2799 static const char *SymbolizerSymbolLookUp(void *DisInfo,
2800 uint64_t ReferenceValue,
2801 uint64_t *ReferenceType,
2802 uint64_t ReferencePC,
2803 const char **ReferenceName) {
2804 struct DisassembleInfo *info = (struct DisassembleInfo *)DisInfo;
2805 // If no verbose symbolic information is wanted then just return nullptr.
2806 if (info->verbose == false) {
2807 *ReferenceName = nullptr;
2808 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
2812 const char *SymbolName = GuessSymbolName(ReferenceValue, info->AddrMap);
2814 if (*ReferenceType == LLVMDisassembler_ReferenceType_In_Branch) {
2815 *ReferenceName = GuessIndirectSymbol(ReferenceValue, info);
2816 if (*ReferenceName != nullptr) {
2817 method_reference(info, ReferenceType, ReferenceName);
2818 if (*ReferenceType != LLVMDisassembler_ReferenceType_Out_Objc_Message)
2819 *ReferenceType = LLVMDisassembler_ReferenceType_Out_SymbolStub;
2822 if (SymbolName != nullptr && strncmp(SymbolName, "__Z", 3) == 0) {
2823 if (info->demangled_name != nullptr)
2824 free(info->demangled_name);
2826 info->demangled_name =
2827 abi::__cxa_demangle(SymbolName + 1, nullptr, nullptr, &status);
2828 if (info->demangled_name != nullptr) {
2829 *ReferenceName = info->demangled_name;
2830 *ReferenceType = LLVMDisassembler_ReferenceType_DeMangled_Name;
2832 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
2835 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
2836 } else if (*ReferenceType == LLVMDisassembler_ReferenceType_In_PCrel_Load) {
2838 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
2840 method_reference(info, ReferenceType, ReferenceName);
2842 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
2843 // If this is arm64 and the reference is an adrp instruction save the
2844 // instruction, passed in ReferenceValue and the address of the instruction
2845 // for use later if we see and add immediate instruction.
2846 } else if (info->O->getArch() == Triple::aarch64 &&
2847 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADRP) {
2848 info->adrp_inst = ReferenceValue;
2849 info->adrp_addr = ReferencePC;
2850 SymbolName = nullptr;
2851 *ReferenceName = nullptr;
2852 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
2853 // If this is arm64 and reference is an add immediate instruction and we
2855 // seen an adrp instruction just before it and the adrp's Xd register
2857 // this add's Xn register reconstruct the value being referenced and look to
2858 // see if it is a literal pointer. Note the add immediate instruction is
2859 // passed in ReferenceValue.
2860 } else if (info->O->getArch() == Triple::aarch64 &&
2861 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADDXri &&
2862 ReferencePC - 4 == info->adrp_addr &&
2863 (info->adrp_inst & 0x9f000000) == 0x90000000 &&
2864 (info->adrp_inst & 0x1f) == ((ReferenceValue >> 5) & 0x1f)) {
2865 uint32_t addxri_inst;
2866 uint64_t adrp_imm, addxri_imm;
2869 ((info->adrp_inst & 0x00ffffe0) >> 3) | ((info->adrp_inst >> 29) & 0x3);
2870 if (info->adrp_inst & 0x0200000)
2871 adrp_imm |= 0xfffffffffc000000LL;
2873 addxri_inst = ReferenceValue;
2874 addxri_imm = (addxri_inst >> 10) & 0xfff;
2875 if (((addxri_inst >> 22) & 0x3) == 1)
2878 ReferenceValue = (info->adrp_addr & 0xfffffffffffff000LL) +
2879 (adrp_imm << 12) + addxri_imm;
2882 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
2883 if (*ReferenceName == nullptr)
2884 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
2885 // If this is arm64 and the reference is a load register instruction and we
2886 // have seen an adrp instruction just before it and the adrp's Xd register
2887 // matches this add's Xn register reconstruct the value being referenced and
2888 // look to see if it is a literal pointer. Note the load register
2889 // instruction is passed in ReferenceValue.
2890 } else if (info->O->getArch() == Triple::aarch64 &&
2891 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_LDRXui &&
2892 ReferencePC - 4 == info->adrp_addr &&
2893 (info->adrp_inst & 0x9f000000) == 0x90000000 &&
2894 (info->adrp_inst & 0x1f) == ((ReferenceValue >> 5) & 0x1f)) {
2895 uint32_t ldrxui_inst;
2896 uint64_t adrp_imm, ldrxui_imm;
2899 ((info->adrp_inst & 0x00ffffe0) >> 3) | ((info->adrp_inst >> 29) & 0x3);
2900 if (info->adrp_inst & 0x0200000)
2901 adrp_imm |= 0xfffffffffc000000LL;
2903 ldrxui_inst = ReferenceValue;
2904 ldrxui_imm = (ldrxui_inst >> 10) & 0xfff;
2906 ReferenceValue = (info->adrp_addr & 0xfffffffffffff000LL) +
2907 (adrp_imm << 12) + (ldrxui_imm << 3);
2910 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
2911 if (*ReferenceName == nullptr)
2912 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
2914 // If this arm64 and is an load register (PC-relative) instruction the
2915 // ReferenceValue is the PC plus the immediate value.
2916 else if (info->O->getArch() == Triple::aarch64 &&
2917 (*ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_LDRXl ||
2918 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADR)) {
2920 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
2921 if (*ReferenceName == nullptr)
2922 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
2925 else if (SymbolName != nullptr && strncmp(SymbolName, "__Z", 3) == 0) {
2926 if (info->demangled_name != nullptr)
2927 free(info->demangled_name);
2929 info->demangled_name =
2930 abi::__cxa_demangle(SymbolName + 1, nullptr, nullptr, &status);
2931 if (info->demangled_name != nullptr) {
2932 *ReferenceName = info->demangled_name;
2933 *ReferenceType = LLVMDisassembler_ReferenceType_DeMangled_Name;
2938 *ReferenceName = nullptr;
2939 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
2945 /// \brief Emits the comments that are stored in the CommentStream.
2946 /// Each comment in the CommentStream must end with a newline.
2947 static void emitComments(raw_svector_ostream &CommentStream,
2948 SmallString<128> &CommentsToEmit,
2949 formatted_raw_ostream &FormattedOS,
2950 const MCAsmInfo &MAI) {
2951 // Flush the stream before taking its content.
2952 CommentStream.flush();
2953 StringRef Comments = CommentsToEmit.str();
2954 // Get the default information for printing a comment.
2955 const char *CommentBegin = MAI.getCommentString();
2956 unsigned CommentColumn = MAI.getCommentColumn();
2957 bool IsFirst = true;
2958 while (!Comments.empty()) {
2960 FormattedOS << '\n';
2961 // Emit a line of comments.
2962 FormattedOS.PadToColumn(CommentColumn);
2963 size_t Position = Comments.find('\n');
2964 FormattedOS << CommentBegin << ' ' << Comments.substr(0, Position);
2965 // Move after the newline character.
2966 Comments = Comments.substr(Position + 1);
2969 FormattedOS.flush();
2971 // Tell the comment stream that the vector changed underneath it.
2972 CommentsToEmit.clear();
2973 CommentStream.resync();
2976 static void DisassembleMachO(StringRef Filename, MachOObjectFile *MachOOF,
2977 StringRef DisSegName, StringRef DisSectName) {
2978 const char *McpuDefault = nullptr;
2979 const Target *ThumbTarget = nullptr;
2980 const Target *TheTarget = GetTarget(MachOOF, &McpuDefault, &ThumbTarget);
2982 // GetTarget prints out stuff.
2985 if (MCPU.empty() && McpuDefault)
2988 std::unique_ptr<const MCInstrInfo> InstrInfo(TheTarget->createMCInstrInfo());
2989 std::unique_ptr<const MCInstrInfo> ThumbInstrInfo;
2991 ThumbInstrInfo.reset(ThumbTarget->createMCInstrInfo());
2993 // Package up features to be passed to target/subtarget
2994 std::string FeaturesStr;
2995 if (MAttrs.size()) {
2996 SubtargetFeatures Features;
2997 for (unsigned i = 0; i != MAttrs.size(); ++i)
2998 Features.AddFeature(MAttrs[i]);
2999 FeaturesStr = Features.getString();
3002 // Set up disassembler.
3003 std::unique_ptr<const MCRegisterInfo> MRI(
3004 TheTarget->createMCRegInfo(TripleName));
3005 std::unique_ptr<const MCAsmInfo> AsmInfo(
3006 TheTarget->createMCAsmInfo(*MRI, TripleName));
3007 std::unique_ptr<const MCSubtargetInfo> STI(
3008 TheTarget->createMCSubtargetInfo(TripleName, MCPU, FeaturesStr));
3009 MCContext Ctx(AsmInfo.get(), MRI.get(), nullptr);
3010 std::unique_ptr<MCDisassembler> DisAsm(
3011 TheTarget->createMCDisassembler(*STI, Ctx));
3012 std::unique_ptr<MCSymbolizer> Symbolizer;
3013 struct DisassembleInfo SymbolizerInfo;
3014 std::unique_ptr<MCRelocationInfo> RelInfo(
3015 TheTarget->createMCRelocationInfo(TripleName, Ctx));
3017 Symbolizer.reset(TheTarget->createMCSymbolizer(
3018 TripleName, SymbolizerGetOpInfo, SymbolizerSymbolLookUp,
3019 &SymbolizerInfo, &Ctx, std::move(RelInfo)));
3020 DisAsm->setSymbolizer(std::move(Symbolizer));
3022 int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
3023 std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
3024 AsmPrinterVariant, *AsmInfo, *InstrInfo, *MRI, *STI));
3025 // Set the display preference for hex vs. decimal immediates.
3026 IP->setPrintImmHex(PrintImmHex);
3027 // Comment stream and backing vector.
3028 SmallString<128> CommentsToEmit;
3029 raw_svector_ostream CommentStream(CommentsToEmit);
3030 // FIXME: Setting the CommentStream in the InstPrinter is problematic in that
3031 // if it is done then arm64 comments for string literals don't get printed
3032 // and some constant get printed instead and not setting it causes intel
3033 // (32-bit and 64-bit) comments printed with different spacing before the
3034 // comment causing different diffs with the 'C' disassembler library API.
3035 // IP->setCommentStream(CommentStream);
3037 if (!AsmInfo || !STI || !DisAsm || !IP) {
3038 errs() << "error: couldn't initialize disassembler for target "
3039 << TripleName << '\n';
3043 // Set up thumb disassembler.
3044 std::unique_ptr<const MCRegisterInfo> ThumbMRI;
3045 std::unique_ptr<const MCAsmInfo> ThumbAsmInfo;
3046 std::unique_ptr<const MCSubtargetInfo> ThumbSTI;
3047 std::unique_ptr<MCDisassembler> ThumbDisAsm;
3048 std::unique_ptr<MCInstPrinter> ThumbIP;
3049 std::unique_ptr<MCContext> ThumbCtx;
3050 std::unique_ptr<MCSymbolizer> ThumbSymbolizer;
3051 struct DisassembleInfo ThumbSymbolizerInfo;
3052 std::unique_ptr<MCRelocationInfo> ThumbRelInfo;
3054 ThumbMRI.reset(ThumbTarget->createMCRegInfo(ThumbTripleName));
3056 ThumbTarget->createMCAsmInfo(*ThumbMRI, ThumbTripleName));
3058 ThumbTarget->createMCSubtargetInfo(ThumbTripleName, MCPU, FeaturesStr));
3059 ThumbCtx.reset(new MCContext(ThumbAsmInfo.get(), ThumbMRI.get(), nullptr));
3060 ThumbDisAsm.reset(ThumbTarget->createMCDisassembler(*ThumbSTI, *ThumbCtx));
3061 MCContext *PtrThumbCtx = ThumbCtx.get();
3063 ThumbTarget->createMCRelocationInfo(ThumbTripleName, *PtrThumbCtx));
3065 ThumbSymbolizer.reset(ThumbTarget->createMCSymbolizer(
3066 ThumbTripleName, SymbolizerGetOpInfo, SymbolizerSymbolLookUp,
3067 &ThumbSymbolizerInfo, PtrThumbCtx, std::move(ThumbRelInfo)));
3068 ThumbDisAsm->setSymbolizer(std::move(ThumbSymbolizer));
3070 int ThumbAsmPrinterVariant = ThumbAsmInfo->getAssemblerDialect();
3071 ThumbIP.reset(ThumbTarget->createMCInstPrinter(
3072 ThumbAsmPrinterVariant, *ThumbAsmInfo, *ThumbInstrInfo, *ThumbMRI,
3074 // Set the display preference for hex vs. decimal immediates.
3075 ThumbIP->setPrintImmHex(PrintImmHex);
3078 if (ThumbTarget && (!ThumbAsmInfo || !ThumbSTI || !ThumbDisAsm || !ThumbIP)) {
3079 errs() << "error: couldn't initialize disassembler for target "
3080 << ThumbTripleName << '\n';
3084 MachO::mach_header Header = MachOOF->getHeader();
3086 // FIXME: Using the -cfg command line option, this code used to be able to
3087 // annotate relocations with the referenced symbol's name, and if this was
3088 // inside a __[cf]string section, the data it points to. This is now replaced
3089 // by the upcoming MCSymbolizer, which needs the appropriate setup done above.
3090 std::vector<SectionRef> Sections;
3091 std::vector<SymbolRef> Symbols;
3092 SmallVector<uint64_t, 8> FoundFns;
3093 uint64_t BaseSegmentAddress;
3095 getSectionsAndSymbols(Header, MachOOF, Sections, Symbols, FoundFns,
3096 BaseSegmentAddress);
3098 // Sort the symbols by address, just in case they didn't come in that way.
3099 std::sort(Symbols.begin(), Symbols.end(), SymbolSorter());
3101 // Build a data in code table that is sorted on by the address of each entry.
3102 uint64_t BaseAddress = 0;
3103 if (Header.filetype == MachO::MH_OBJECT)
3104 BaseAddress = Sections[0].getAddress();
3106 BaseAddress = BaseSegmentAddress;
3108 for (dice_iterator DI = MachOOF->begin_dices(), DE = MachOOF->end_dices();
3111 DI->getOffset(Offset);
3112 Dices.push_back(std::make_pair(BaseAddress + Offset, *DI));
3114 array_pod_sort(Dices.begin(), Dices.end());
3117 raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls();
3119 raw_ostream &DebugOut = nulls();
3122 std::unique_ptr<DIContext> diContext;
3123 ObjectFile *DbgObj = MachOOF;
3124 // Try to find debug info and set up the DIContext for it.
3126 // A separate DSym file path was specified, parse it as a macho file,
3127 // get the sections and supply it to the section name parsing machinery.
3128 if (!DSYMFile.empty()) {
3129 ErrorOr<std::unique_ptr<MemoryBuffer>> BufOrErr =
3130 MemoryBuffer::getFileOrSTDIN(DSYMFile);
3131 if (std::error_code EC = BufOrErr.getError()) {
3132 errs() << "llvm-objdump: " << Filename << ": " << EC.message() << '\n';
3136 ObjectFile::createMachOObjectFile(BufOrErr.get()->getMemBufferRef())
3141 // Setup the DIContext
3142 diContext.reset(DIContext::getDWARFContext(*DbgObj));
3145 if (DumpSections.size() == 0)
3146 outs() << "(" << DisSegName << "," << DisSectName << ") section\n";
3148 for (unsigned SectIdx = 0; SectIdx != Sections.size(); SectIdx++) {
3150 if (Sections[SectIdx].getName(SectName) || SectName != DisSectName)
3153 DataRefImpl DR = Sections[SectIdx].getRawDataRefImpl();
3155 StringRef SegmentName = MachOOF->getSectionFinalSegmentName(DR);
3156 if (SegmentName != DisSegName)
3160 Sections[SectIdx].getContents(BytesStr);
3161 ArrayRef<uint8_t> Bytes(reinterpret_cast<const uint8_t *>(BytesStr.data()),
3163 uint64_t SectAddress = Sections[SectIdx].getAddress();
3165 bool symbolTableWorked = false;
3167 // Parse relocations.
3168 std::vector<std::pair<uint64_t, SymbolRef>> Relocs;
3169 for (const RelocationRef &Reloc : Sections[SectIdx].relocations()) {
3170 uint64_t RelocOffset;
3171 Reloc.getOffset(RelocOffset);
3172 uint64_t SectionAddress = Sections[SectIdx].getAddress();
3173 RelocOffset -= SectionAddress;
3175 symbol_iterator RelocSym = Reloc.getSymbol();
3177 Relocs.push_back(std::make_pair(RelocOffset, *RelocSym));
3179 array_pod_sort(Relocs.begin(), Relocs.end());
3181 // Create a map of symbol addresses to symbol names for use by
3182 // the SymbolizerSymbolLookUp() routine.
3183 SymbolAddressMap AddrMap;
3184 for (const SymbolRef &Symbol : MachOOF->symbols()) {
3187 if (ST == SymbolRef::ST_Function || ST == SymbolRef::ST_Data ||
3188 ST == SymbolRef::ST_Other) {
3190 Symbol.getAddress(Address);
3192 Symbol.getName(SymName);
3193 AddrMap[Address] = SymName;
3196 // Set up the block of info used by the Symbolizer call backs.
3197 SymbolizerInfo.verbose = true;
3198 SymbolizerInfo.O = MachOOF;
3199 SymbolizerInfo.S = Sections[SectIdx];
3200 SymbolizerInfo.AddrMap = &AddrMap;
3201 SymbolizerInfo.Sections = &Sections;
3202 SymbolizerInfo.class_name = nullptr;
3203 SymbolizerInfo.selector_name = nullptr;
3204 SymbolizerInfo.method = nullptr;
3205 SymbolizerInfo.demangled_name = nullptr;
3206 SymbolizerInfo.bindtable = nullptr;
3207 SymbolizerInfo.adrp_addr = 0;
3208 SymbolizerInfo.adrp_inst = 0;
3209 // Same for the ThumbSymbolizer
3210 ThumbSymbolizerInfo.verbose = true;
3211 ThumbSymbolizerInfo.O = MachOOF;
3212 ThumbSymbolizerInfo.S = Sections[SectIdx];
3213 ThumbSymbolizerInfo.AddrMap = &AddrMap;
3214 ThumbSymbolizerInfo.Sections = &Sections;
3215 ThumbSymbolizerInfo.class_name = nullptr;
3216 ThumbSymbolizerInfo.selector_name = nullptr;
3217 ThumbSymbolizerInfo.method = nullptr;
3218 ThumbSymbolizerInfo.demangled_name = nullptr;
3219 ThumbSymbolizerInfo.bindtable = nullptr;
3220 ThumbSymbolizerInfo.adrp_addr = 0;
3221 ThumbSymbolizerInfo.adrp_inst = 0;
3223 // Disassemble symbol by symbol.
3224 for (unsigned SymIdx = 0; SymIdx != Symbols.size(); SymIdx++) {
3226 Symbols[SymIdx].getName(SymName);
3229 Symbols[SymIdx].getType(ST);
3230 if (ST != SymbolRef::ST_Function)
3233 // Make sure the symbol is defined in this section.
3234 bool containsSym = Sections[SectIdx].containsSymbol(Symbols[SymIdx]);
3238 // Start at the address of the symbol relative to the section's address.
3240 uint64_t SectionAddress = Sections[SectIdx].getAddress();
3241 Symbols[SymIdx].getAddress(Start);
3242 Start -= SectionAddress;
3244 // Stop disassembling either at the beginning of the next symbol or at
3245 // the end of the section.
3246 bool containsNextSym = false;
3247 uint64_t NextSym = 0;
3248 uint64_t NextSymIdx = SymIdx + 1;
3249 while (Symbols.size() > NextSymIdx) {
3250 SymbolRef::Type NextSymType;
3251 Symbols[NextSymIdx].getType(NextSymType);
3252 if (NextSymType == SymbolRef::ST_Function) {
3254 Sections[SectIdx].containsSymbol(Symbols[NextSymIdx]);
3255 Symbols[NextSymIdx].getAddress(NextSym);
3256 NextSym -= SectionAddress;
3262 uint64_t SectSize = Sections[SectIdx].getSize();
3263 uint64_t End = containsNextSym ? NextSym : SectSize;
3266 symbolTableWorked = true;
3268 DataRefImpl Symb = Symbols[SymIdx].getRawDataRefImpl();
3270 (MachOOF->getSymbolFlags(Symb) & SymbolRef::SF_Thumb) && ThumbTarget;
3272 outs() << SymName << ":\n";
3273 DILineInfo lastLine;
3274 for (uint64_t Index = Start; Index < End; Index += Size) {
3277 uint64_t PC = SectAddress + Index;
3278 if (FullLeadingAddr) {
3279 if (MachOOF->is64Bit())
3280 outs() << format("%016" PRIx64, PC);
3282 outs() << format("%08" PRIx64, PC);
3284 outs() << format("%8" PRIx64 ":", PC);
3289 // Check the data in code table here to see if this is data not an
3290 // instruction to be disassembled.
3292 Dice.push_back(std::make_pair(PC, DiceRef()));
3293 dice_table_iterator DTI =
3294 std::search(Dices.begin(), Dices.end(), Dice.begin(), Dice.end(),
3295 compareDiceTableEntries);
3296 if (DTI != Dices.end()) {
3298 DTI->second.getLength(Length);
3300 DTI->second.getKind(Kind);
3301 Size = DumpDataInCode(reinterpret_cast<const char *>(Bytes.data()) +
3304 if ((Kind == MachO::DICE_KIND_JUMP_TABLE8) &&
3305 (PC == (DTI->first + Length - 1)) && (Length & 1))
3310 SmallVector<char, 64> AnnotationsBytes;
3311 raw_svector_ostream Annotations(AnnotationsBytes);
3315 gotInst = ThumbDisAsm->getInstruction(Inst, Size, Bytes.slice(Index),
3316 PC, DebugOut, Annotations);
3318 gotInst = DisAsm->getInstruction(Inst, Size, Bytes.slice(Index), PC,
3319 DebugOut, Annotations);
3321 if (!NoShowRawInsn) {
3322 DumpBytes(StringRef(
3323 reinterpret_cast<const char *>(Bytes.data()) + Index, Size));
3325 formatted_raw_ostream FormattedOS(outs());
3326 Annotations.flush();
3327 StringRef AnnotationsStr = Annotations.str();
3329 ThumbIP->printInst(&Inst, FormattedOS, AnnotationsStr);
3331 IP->printInst(&Inst, FormattedOS, AnnotationsStr);
3332 emitComments(CommentStream, CommentsToEmit, FormattedOS, *AsmInfo);
3334 // Print debug info.
3336 DILineInfo dli = diContext->getLineInfoForAddress(PC);
3337 // Print valid line info if it changed.
3338 if (dli != lastLine && dli.Line != 0)
3339 outs() << "\t## " << dli.FileName << ':' << dli.Line << ':'
3345 unsigned int Arch = MachOOF->getArch();
3346 if (Arch == Triple::x86_64 || Arch == Triple::x86) {
3347 outs() << format("\t.byte 0x%02x #bad opcode\n",
3348 *(Bytes.data() + Index) & 0xff);
3349 Size = 1; // skip exactly one illegible byte and move on.
3350 } else if (Arch == Triple::aarch64) {
3351 uint32_t opcode = (*(Bytes.data() + Index) & 0xff) |
3352 (*(Bytes.data() + Index + 1) & 0xff) << 8 |
3353 (*(Bytes.data() + Index + 2) & 0xff) << 16 |
3354 (*(Bytes.data() + Index + 3) & 0xff) << 24;
3355 outs() << format("\t.long\t0x%08x\n", opcode);
3358 errs() << "llvm-objdump: warning: invalid instruction encoding\n";
3360 Size = 1; // skip illegible bytes
3365 if (!symbolTableWorked) {
3366 // Reading the symbol table didn't work, disassemble the whole section.
3367 uint64_t SectAddress = Sections[SectIdx].getAddress();
3368 uint64_t SectSize = Sections[SectIdx].getSize();
3370 for (uint64_t Index = 0; Index < SectSize; Index += InstSize) {
3373 uint64_t PC = SectAddress + Index;
3374 if (DisAsm->getInstruction(Inst, InstSize, Bytes.slice(Index), PC,
3375 DebugOut, nulls())) {
3376 if (FullLeadingAddr) {
3377 if (MachOOF->is64Bit())
3378 outs() << format("%016" PRIx64, PC);
3380 outs() << format("%08" PRIx64, PC);
3382 outs() << format("%8" PRIx64 ":", PC);
3384 if (!NoShowRawInsn) {
3387 StringRef(reinterpret_cast<const char *>(Bytes.data()) + Index,
3390 IP->printInst(&Inst, outs(), "");
3393 unsigned int Arch = MachOOF->getArch();
3394 if (Arch == Triple::x86_64 || Arch == Triple::x86) {
3395 outs() << format("\t.byte 0x%02x #bad opcode\n",
3396 *(Bytes.data() + Index) & 0xff);
3397 InstSize = 1; // skip exactly one illegible byte and move on.
3399 errs() << "llvm-objdump: warning: invalid instruction encoding\n";
3401 InstSize = 1; // skip illegible bytes
3406 // The TripleName's need to be reset if we are called again for a different
3409 ThumbTripleName = "";
3411 if (SymbolizerInfo.method != nullptr)
3412 free(SymbolizerInfo.method);
3413 if (SymbolizerInfo.demangled_name != nullptr)
3414 free(SymbolizerInfo.demangled_name);
3415 if (SymbolizerInfo.bindtable != nullptr)
3416 delete SymbolizerInfo.bindtable;
3417 if (ThumbSymbolizerInfo.method != nullptr)
3418 free(ThumbSymbolizerInfo.method);
3419 if (ThumbSymbolizerInfo.demangled_name != nullptr)
3420 free(ThumbSymbolizerInfo.demangled_name);
3421 if (ThumbSymbolizerInfo.bindtable != nullptr)
3422 delete ThumbSymbolizerInfo.bindtable;
3426 //===----------------------------------------------------------------------===//
3427 // __compact_unwind section dumping
3428 //===----------------------------------------------------------------------===//
3432 template <typename T> static uint64_t readNext(const char *&Buf) {
3433 using llvm::support::little;
3434 using llvm::support::unaligned;
3436 uint64_t Val = support::endian::read<T, little, unaligned>(Buf);
3441 struct CompactUnwindEntry {
3442 uint32_t OffsetInSection;
3444 uint64_t FunctionAddr;
3446 uint32_t CompactEncoding;
3447 uint64_t PersonalityAddr;
3450 RelocationRef FunctionReloc;
3451 RelocationRef PersonalityReloc;
3452 RelocationRef LSDAReloc;
3454 CompactUnwindEntry(StringRef Contents, unsigned Offset, bool Is64)
3455 : OffsetInSection(Offset) {
3457 read<uint64_t>(Contents.data() + Offset);
3459 read<uint32_t>(Contents.data() + Offset);
3463 template <typename UIntPtr> void read(const char *Buf) {
3464 FunctionAddr = readNext<UIntPtr>(Buf);
3465 Length = readNext<uint32_t>(Buf);
3466 CompactEncoding = readNext<uint32_t>(Buf);
3467 PersonalityAddr = readNext<UIntPtr>(Buf);
3468 LSDAAddr = readNext<UIntPtr>(Buf);
3473 /// Given a relocation from __compact_unwind, consisting of the RelocationRef
3474 /// and data being relocated, determine the best base Name and Addend to use for
3475 /// display purposes.
3477 /// 1. An Extern relocation will directly reference a symbol (and the data is
3478 /// then already an addend), so use that.
3479 /// 2. Otherwise the data is an offset in the object file's layout; try to find
3480 // a symbol before it in the same section, and use the offset from there.
3481 /// 3. Finally, if all that fails, fall back to an offset from the start of the
3482 /// referenced section.
3483 static void findUnwindRelocNameAddend(const MachOObjectFile *Obj,
3484 std::map<uint64_t, SymbolRef> &Symbols,
3485 const RelocationRef &Reloc, uint64_t Addr,
3486 StringRef &Name, uint64_t &Addend) {
3487 if (Reloc.getSymbol() != Obj->symbol_end()) {
3488 Reloc.getSymbol()->getName(Name);
3493 auto RE = Obj->getRelocation(Reloc.getRawDataRefImpl());
3494 SectionRef RelocSection = Obj->getRelocationSection(RE);
3496 uint64_t SectionAddr = RelocSection.getAddress();
3498 auto Sym = Symbols.upper_bound(Addr);
3499 if (Sym == Symbols.begin()) {
3500 // The first symbol in the object is after this reference, the best we can
3501 // do is section-relative notation.
3502 RelocSection.getName(Name);
3503 Addend = Addr - SectionAddr;
3507 // Go back one so that SymbolAddress <= Addr.
3510 section_iterator SymSection = Obj->section_end();
3511 Sym->second.getSection(SymSection);
3512 if (RelocSection == *SymSection) {
3513 // There's a valid symbol in the same section before this reference.
3514 Sym->second.getName(Name);
3515 Addend = Addr - Sym->first;
3519 // There is a symbol before this reference, but it's in a different
3520 // section. Probably not helpful to mention it, so use the section name.
3521 RelocSection.getName(Name);
3522 Addend = Addr - SectionAddr;
3525 static void printUnwindRelocDest(const MachOObjectFile *Obj,
3526 std::map<uint64_t, SymbolRef> &Symbols,
3527 const RelocationRef &Reloc, uint64_t Addr) {
3531 if (!Reloc.getObjectFile())
3534 findUnwindRelocNameAddend(Obj, Symbols, Reloc, Addr, Name, Addend);
3538 outs() << " + " << format("0x%" PRIx64, Addend);
3542 printMachOCompactUnwindSection(const MachOObjectFile *Obj,
3543 std::map<uint64_t, SymbolRef> &Symbols,
3544 const SectionRef &CompactUnwind) {
3546 assert(Obj->isLittleEndian() &&
3547 "There should not be a big-endian .o with __compact_unwind");
3549 bool Is64 = Obj->is64Bit();
3550 uint32_t PointerSize = Is64 ? sizeof(uint64_t) : sizeof(uint32_t);
3551 uint32_t EntrySize = 3 * PointerSize + 2 * sizeof(uint32_t);
3554 CompactUnwind.getContents(Contents);
3556 SmallVector<CompactUnwindEntry, 4> CompactUnwinds;
3558 // First populate the initial raw offsets, encodings and so on from the entry.
3559 for (unsigned Offset = 0; Offset < Contents.size(); Offset += EntrySize) {
3560 CompactUnwindEntry Entry(Contents.data(), Offset, Is64);
3561 CompactUnwinds.push_back(Entry);
3564 // Next we need to look at the relocations to find out what objects are
3565 // actually being referred to.
3566 for (const RelocationRef &Reloc : CompactUnwind.relocations()) {
3567 uint64_t RelocAddress;
3568 Reloc.getOffset(RelocAddress);
3570 uint32_t EntryIdx = RelocAddress / EntrySize;
3571 uint32_t OffsetInEntry = RelocAddress - EntryIdx * EntrySize;
3572 CompactUnwindEntry &Entry = CompactUnwinds[EntryIdx];
3574 if (OffsetInEntry == 0)
3575 Entry.FunctionReloc = Reloc;
3576 else if (OffsetInEntry == PointerSize + 2 * sizeof(uint32_t))
3577 Entry.PersonalityReloc = Reloc;
3578 else if (OffsetInEntry == 2 * PointerSize + 2 * sizeof(uint32_t))
3579 Entry.LSDAReloc = Reloc;
3581 llvm_unreachable("Unexpected relocation in __compact_unwind section");
3584 // Finally, we're ready to print the data we've gathered.
3585 outs() << "Contents of __compact_unwind section:\n";
3586 for (auto &Entry : CompactUnwinds) {
3587 outs() << " Entry at offset "
3588 << format("0x%" PRIx32, Entry.OffsetInSection) << ":\n";
3590 // 1. Start of the region this entry applies to.
3591 outs() << " start: " << format("0x%" PRIx64,
3592 Entry.FunctionAddr) << ' ';
3593 printUnwindRelocDest(Obj, Symbols, Entry.FunctionReloc, Entry.FunctionAddr);
3596 // 2. Length of the region this entry applies to.
3597 outs() << " length: " << format("0x%" PRIx32, Entry.Length)
3599 // 3. The 32-bit compact encoding.
3600 outs() << " compact encoding: "
3601 << format("0x%08" PRIx32, Entry.CompactEncoding) << '\n';
3603 // 4. The personality function, if present.
3604 if (Entry.PersonalityReloc.getObjectFile()) {
3605 outs() << " personality function: "
3606 << format("0x%" PRIx64, Entry.PersonalityAddr) << ' ';
3607 printUnwindRelocDest(Obj, Symbols, Entry.PersonalityReloc,
3608 Entry.PersonalityAddr);
3612 // 5. This entry's language-specific data area.
3613 if (Entry.LSDAReloc.getObjectFile()) {
3614 outs() << " LSDA: " << format("0x%" PRIx64,
3615 Entry.LSDAAddr) << ' ';
3616 printUnwindRelocDest(Obj, Symbols, Entry.LSDAReloc, Entry.LSDAAddr);
3622 //===----------------------------------------------------------------------===//
3623 // __unwind_info section dumping
3624 //===----------------------------------------------------------------------===//
3626 static void printRegularSecondLevelUnwindPage(const char *PageStart) {
3627 const char *Pos = PageStart;
3628 uint32_t Kind = readNext<uint32_t>(Pos);
3630 assert(Kind == 2 && "kind for a regular 2nd level index should be 2");
3632 uint16_t EntriesStart = readNext<uint16_t>(Pos);
3633 uint16_t NumEntries = readNext<uint16_t>(Pos);
3635 Pos = PageStart + EntriesStart;
3636 for (unsigned i = 0; i < NumEntries; ++i) {
3637 uint32_t FunctionOffset = readNext<uint32_t>(Pos);
3638 uint32_t Encoding = readNext<uint32_t>(Pos);
3640 outs() << " [" << i << "]: "
3641 << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
3643 << "encoding=" << format("0x%08" PRIx32, Encoding) << '\n';
3647 static void printCompressedSecondLevelUnwindPage(
3648 const char *PageStart, uint32_t FunctionBase,
3649 const SmallVectorImpl<uint32_t> &CommonEncodings) {
3650 const char *Pos = PageStart;
3651 uint32_t Kind = readNext<uint32_t>(Pos);
3653 assert(Kind == 3 && "kind for a compressed 2nd level index should be 3");
3655 uint16_t EntriesStart = readNext<uint16_t>(Pos);
3656 uint16_t NumEntries = readNext<uint16_t>(Pos);
3658 uint16_t EncodingsStart = readNext<uint16_t>(Pos);
3659 readNext<uint16_t>(Pos);
3660 const auto *PageEncodings = reinterpret_cast<const support::ulittle32_t *>(
3661 PageStart + EncodingsStart);
3663 Pos = PageStart + EntriesStart;
3664 for (unsigned i = 0; i < NumEntries; ++i) {
3665 uint32_t Entry = readNext<uint32_t>(Pos);
3666 uint32_t FunctionOffset = FunctionBase + (Entry & 0xffffff);
3667 uint32_t EncodingIdx = Entry >> 24;
3670 if (EncodingIdx < CommonEncodings.size())
3671 Encoding = CommonEncodings[EncodingIdx];
3673 Encoding = PageEncodings[EncodingIdx - CommonEncodings.size()];
3675 outs() << " [" << i << "]: "
3676 << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
3678 << "encoding[" << EncodingIdx
3679 << "]=" << format("0x%08" PRIx32, Encoding) << '\n';
3683 static void printMachOUnwindInfoSection(const MachOObjectFile *Obj,
3684 std::map<uint64_t, SymbolRef> &Symbols,
3685 const SectionRef &UnwindInfo) {
3687 assert(Obj->isLittleEndian() &&
3688 "There should not be a big-endian .o with __unwind_info");
3690 outs() << "Contents of __unwind_info section:\n";
3693 UnwindInfo.getContents(Contents);
3694 const char *Pos = Contents.data();
3696 //===----------------------------------
3698 //===----------------------------------
3700 uint32_t Version = readNext<uint32_t>(Pos);
3701 outs() << " Version: "
3702 << format("0x%" PRIx32, Version) << '\n';
3703 assert(Version == 1 && "only understand version 1");
3705 uint32_t CommonEncodingsStart = readNext<uint32_t>(Pos);
3706 outs() << " Common encodings array section offset: "
3707 << format("0x%" PRIx32, CommonEncodingsStart) << '\n';
3708 uint32_t NumCommonEncodings = readNext<uint32_t>(Pos);
3709 outs() << " Number of common encodings in array: "
3710 << format("0x%" PRIx32, NumCommonEncodings) << '\n';
3712 uint32_t PersonalitiesStart = readNext<uint32_t>(Pos);
3713 outs() << " Personality function array section offset: "
3714 << format("0x%" PRIx32, PersonalitiesStart) << '\n';
3715 uint32_t NumPersonalities = readNext<uint32_t>(Pos);
3716 outs() << " Number of personality functions in array: "
3717 << format("0x%" PRIx32, NumPersonalities) << '\n';
3719 uint32_t IndicesStart = readNext<uint32_t>(Pos);
3720 outs() << " Index array section offset: "
3721 << format("0x%" PRIx32, IndicesStart) << '\n';
3722 uint32_t NumIndices = readNext<uint32_t>(Pos);
3723 outs() << " Number of indices in array: "
3724 << format("0x%" PRIx32, NumIndices) << '\n';
3726 //===----------------------------------
3727 // A shared list of common encodings
3728 //===----------------------------------
3730 // These occupy indices in the range [0, N] whenever an encoding is referenced
3731 // from a compressed 2nd level index table. In practice the linker only
3732 // creates ~128 of these, so that indices are available to embed encodings in
3733 // the 2nd level index.
3735 SmallVector<uint32_t, 64> CommonEncodings;
3736 outs() << " Common encodings: (count = " << NumCommonEncodings << ")\n";
3737 Pos = Contents.data() + CommonEncodingsStart;
3738 for (unsigned i = 0; i < NumCommonEncodings; ++i) {
3739 uint32_t Encoding = readNext<uint32_t>(Pos);
3740 CommonEncodings.push_back(Encoding);
3742 outs() << " encoding[" << i << "]: " << format("0x%08" PRIx32, Encoding)
3746 //===----------------------------------
3747 // Personality functions used in this executable
3748 //===----------------------------------
3750 // There should be only a handful of these (one per source language,
3751 // roughly). Particularly since they only get 2 bits in the compact encoding.
3753 outs() << " Personality functions: (count = " << NumPersonalities << ")\n";
3754 Pos = Contents.data() + PersonalitiesStart;
3755 for (unsigned i = 0; i < NumPersonalities; ++i) {
3756 uint32_t PersonalityFn = readNext<uint32_t>(Pos);
3757 outs() << " personality[" << i + 1
3758 << "]: " << format("0x%08" PRIx32, PersonalityFn) << '\n';
3761 //===----------------------------------
3762 // The level 1 index entries
3763 //===----------------------------------
3765 // These specify an approximate place to start searching for the more detailed
3766 // information, sorted by PC.
3769 uint32_t FunctionOffset;
3770 uint32_t SecondLevelPageStart;
3774 SmallVector<IndexEntry, 4> IndexEntries;
3776 outs() << " Top level indices: (count = " << NumIndices << ")\n";
3777 Pos = Contents.data() + IndicesStart;
3778 for (unsigned i = 0; i < NumIndices; ++i) {
3781 Entry.FunctionOffset = readNext<uint32_t>(Pos);
3782 Entry.SecondLevelPageStart = readNext<uint32_t>(Pos);
3783 Entry.LSDAStart = readNext<uint32_t>(Pos);
3784 IndexEntries.push_back(Entry);
3786 outs() << " [" << i << "]: "
3787 << "function offset=" << format("0x%08" PRIx32, Entry.FunctionOffset)
3789 << "2nd level page offset="
3790 << format("0x%08" PRIx32, Entry.SecondLevelPageStart) << ", "
3791 << "LSDA offset=" << format("0x%08" PRIx32, Entry.LSDAStart) << '\n';
3794 //===----------------------------------
3795 // Next come the LSDA tables
3796 //===----------------------------------
3798 // The LSDA layout is rather implicit: it's a contiguous array of entries from
3799 // the first top-level index's LSDAOffset to the last (sentinel).
3801 outs() << " LSDA descriptors:\n";
3802 Pos = Contents.data() + IndexEntries[0].LSDAStart;
3803 int NumLSDAs = (IndexEntries.back().LSDAStart - IndexEntries[0].LSDAStart) /
3804 (2 * sizeof(uint32_t));
3805 for (int i = 0; i < NumLSDAs; ++i) {
3806 uint32_t FunctionOffset = readNext<uint32_t>(Pos);
3807 uint32_t LSDAOffset = readNext<uint32_t>(Pos);
3808 outs() << " [" << i << "]: "
3809 << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
3811 << "LSDA offset=" << format("0x%08" PRIx32, LSDAOffset) << '\n';
3814 //===----------------------------------
3815 // Finally, the 2nd level indices
3816 //===----------------------------------
3818 // Generally these are 4K in size, and have 2 possible forms:
3819 // + Regular stores up to 511 entries with disparate encodings
3820 // + Compressed stores up to 1021 entries if few enough compact encoding
3822 outs() << " Second level indices:\n";
3823 for (unsigned i = 0; i < IndexEntries.size() - 1; ++i) {
3824 // The final sentinel top-level index has no associated 2nd level page
3825 if (IndexEntries[i].SecondLevelPageStart == 0)
3828 outs() << " Second level index[" << i << "]: "
3829 << "offset in section="
3830 << format("0x%08" PRIx32, IndexEntries[i].SecondLevelPageStart)
3832 << "base function offset="
3833 << format("0x%08" PRIx32, IndexEntries[i].FunctionOffset) << '\n';
3835 Pos = Contents.data() + IndexEntries[i].SecondLevelPageStart;
3836 uint32_t Kind = *reinterpret_cast<const support::ulittle32_t *>(Pos);
3838 printRegularSecondLevelUnwindPage(Pos);
3840 printCompressedSecondLevelUnwindPage(Pos, IndexEntries[i].FunctionOffset,
3843 llvm_unreachable("Do not know how to print this kind of 2nd level page");
3847 void llvm::printMachOUnwindInfo(const MachOObjectFile *Obj) {
3848 std::map<uint64_t, SymbolRef> Symbols;
3849 for (const SymbolRef &SymRef : Obj->symbols()) {
3850 // Discard any undefined or absolute symbols. They're not going to take part
3851 // in the convenience lookup for unwind info and just take up resources.
3852 section_iterator Section = Obj->section_end();
3853 SymRef.getSection(Section);
3854 if (Section == Obj->section_end())
3858 SymRef.getAddress(Addr);
3859 Symbols.insert(std::make_pair(Addr, SymRef));
3862 for (const SectionRef &Section : Obj->sections()) {
3864 Section.getName(SectName);
3865 if (SectName == "__compact_unwind")
3866 printMachOCompactUnwindSection(Obj, Symbols, Section);
3867 else if (SectName == "__unwind_info")
3868 printMachOUnwindInfoSection(Obj, Symbols, Section);
3869 else if (SectName == "__eh_frame")
3870 outs() << "llvm-objdump: warning: unhandled __eh_frame section\n";
3874 static void PrintMachHeader(uint32_t magic, uint32_t cputype,
3875 uint32_t cpusubtype, uint32_t filetype,
3876 uint32_t ncmds, uint32_t sizeofcmds, uint32_t flags,
3878 outs() << "Mach header\n";
3879 outs() << " magic cputype cpusubtype caps filetype ncmds "
3880 "sizeofcmds flags\n";
3882 if (magic == MachO::MH_MAGIC)
3883 outs() << " MH_MAGIC";
3884 else if (magic == MachO::MH_MAGIC_64)
3885 outs() << "MH_MAGIC_64";
3887 outs() << format(" 0x%08" PRIx32, magic);
3889 case MachO::CPU_TYPE_I386:
3891 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
3892 case MachO::CPU_SUBTYPE_I386_ALL:
3896 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
3900 case MachO::CPU_TYPE_X86_64:
3901 outs() << " X86_64";
3902 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
3903 case MachO::CPU_SUBTYPE_X86_64_ALL:
3906 case MachO::CPU_SUBTYPE_X86_64_H:
3907 outs() << " Haswell";
3910 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
3914 case MachO::CPU_TYPE_ARM:
3916 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
3917 case MachO::CPU_SUBTYPE_ARM_ALL:
3920 case MachO::CPU_SUBTYPE_ARM_V4T:
3923 case MachO::CPU_SUBTYPE_ARM_V5TEJ:
3926 case MachO::CPU_SUBTYPE_ARM_XSCALE:
3927 outs() << " XSCALE";
3929 case MachO::CPU_SUBTYPE_ARM_V6:
3932 case MachO::CPU_SUBTYPE_ARM_V6M:
3935 case MachO::CPU_SUBTYPE_ARM_V7:
3938 case MachO::CPU_SUBTYPE_ARM_V7EM:
3941 case MachO::CPU_SUBTYPE_ARM_V7K:
3944 case MachO::CPU_SUBTYPE_ARM_V7M:
3947 case MachO::CPU_SUBTYPE_ARM_V7S:
3951 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
3955 case MachO::CPU_TYPE_ARM64:
3957 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
3958 case MachO::CPU_SUBTYPE_ARM64_ALL:
3962 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
3966 case MachO::CPU_TYPE_POWERPC:
3968 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
3969 case MachO::CPU_SUBTYPE_POWERPC_ALL:
3973 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
3977 case MachO::CPU_TYPE_POWERPC64:
3979 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
3980 case MachO::CPU_SUBTYPE_POWERPC_ALL:
3984 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
3989 if ((cpusubtype & MachO::CPU_SUBTYPE_MASK) == MachO::CPU_SUBTYPE_LIB64) {
3992 outs() << format(" 0x%02" PRIx32,
3993 (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24);
3996 case MachO::MH_OBJECT:
3997 outs() << " OBJECT";
3999 case MachO::MH_EXECUTE:
4000 outs() << " EXECUTE";
4002 case MachO::MH_FVMLIB:
4003 outs() << " FVMLIB";
4005 case MachO::MH_CORE:
4008 case MachO::MH_PRELOAD:
4009 outs() << " PRELOAD";
4011 case MachO::MH_DYLIB:
4014 case MachO::MH_DYLIB_STUB:
4015 outs() << " DYLIB_STUB";
4017 case MachO::MH_DYLINKER:
4018 outs() << " DYLINKER";
4020 case MachO::MH_BUNDLE:
4021 outs() << " BUNDLE";
4023 case MachO::MH_DSYM:
4026 case MachO::MH_KEXT_BUNDLE:
4027 outs() << " KEXTBUNDLE";
4030 outs() << format(" %10u", filetype);
4033 outs() << format(" %5u", ncmds);
4034 outs() << format(" %10u", sizeofcmds);
4036 if (f & MachO::MH_NOUNDEFS) {
4037 outs() << " NOUNDEFS";
4038 f &= ~MachO::MH_NOUNDEFS;
4040 if (f & MachO::MH_INCRLINK) {
4041 outs() << " INCRLINK";
4042 f &= ~MachO::MH_INCRLINK;
4044 if (f & MachO::MH_DYLDLINK) {
4045 outs() << " DYLDLINK";
4046 f &= ~MachO::MH_DYLDLINK;
4048 if (f & MachO::MH_BINDATLOAD) {
4049 outs() << " BINDATLOAD";
4050 f &= ~MachO::MH_BINDATLOAD;
4052 if (f & MachO::MH_PREBOUND) {
4053 outs() << " PREBOUND";
4054 f &= ~MachO::MH_PREBOUND;
4056 if (f & MachO::MH_SPLIT_SEGS) {
4057 outs() << " SPLIT_SEGS";
4058 f &= ~MachO::MH_SPLIT_SEGS;
4060 if (f & MachO::MH_LAZY_INIT) {
4061 outs() << " LAZY_INIT";
4062 f &= ~MachO::MH_LAZY_INIT;
4064 if (f & MachO::MH_TWOLEVEL) {
4065 outs() << " TWOLEVEL";
4066 f &= ~MachO::MH_TWOLEVEL;
4068 if (f & MachO::MH_FORCE_FLAT) {
4069 outs() << " FORCE_FLAT";
4070 f &= ~MachO::MH_FORCE_FLAT;
4072 if (f & MachO::MH_NOMULTIDEFS) {
4073 outs() << " NOMULTIDEFS";
4074 f &= ~MachO::MH_NOMULTIDEFS;
4076 if (f & MachO::MH_NOFIXPREBINDING) {
4077 outs() << " NOFIXPREBINDING";
4078 f &= ~MachO::MH_NOFIXPREBINDING;
4080 if (f & MachO::MH_PREBINDABLE) {
4081 outs() << " PREBINDABLE";
4082 f &= ~MachO::MH_PREBINDABLE;
4084 if (f & MachO::MH_ALLMODSBOUND) {
4085 outs() << " ALLMODSBOUND";
4086 f &= ~MachO::MH_ALLMODSBOUND;
4088 if (f & MachO::MH_SUBSECTIONS_VIA_SYMBOLS) {
4089 outs() << " SUBSECTIONS_VIA_SYMBOLS";
4090 f &= ~MachO::MH_SUBSECTIONS_VIA_SYMBOLS;
4092 if (f & MachO::MH_CANONICAL) {
4093 outs() << " CANONICAL";
4094 f &= ~MachO::MH_CANONICAL;
4096 if (f & MachO::MH_WEAK_DEFINES) {
4097 outs() << " WEAK_DEFINES";
4098 f &= ~MachO::MH_WEAK_DEFINES;
4100 if (f & MachO::MH_BINDS_TO_WEAK) {
4101 outs() << " BINDS_TO_WEAK";
4102 f &= ~MachO::MH_BINDS_TO_WEAK;
4104 if (f & MachO::MH_ALLOW_STACK_EXECUTION) {
4105 outs() << " ALLOW_STACK_EXECUTION";
4106 f &= ~MachO::MH_ALLOW_STACK_EXECUTION;
4108 if (f & MachO::MH_DEAD_STRIPPABLE_DYLIB) {
4109 outs() << " DEAD_STRIPPABLE_DYLIB";
4110 f &= ~MachO::MH_DEAD_STRIPPABLE_DYLIB;
4112 if (f & MachO::MH_PIE) {
4114 f &= ~MachO::MH_PIE;
4116 if (f & MachO::MH_NO_REEXPORTED_DYLIBS) {
4117 outs() << " NO_REEXPORTED_DYLIBS";
4118 f &= ~MachO::MH_NO_REEXPORTED_DYLIBS;
4120 if (f & MachO::MH_HAS_TLV_DESCRIPTORS) {
4121 outs() << " MH_HAS_TLV_DESCRIPTORS";
4122 f &= ~MachO::MH_HAS_TLV_DESCRIPTORS;
4124 if (f & MachO::MH_NO_HEAP_EXECUTION) {
4125 outs() << " MH_NO_HEAP_EXECUTION";
4126 f &= ~MachO::MH_NO_HEAP_EXECUTION;
4128 if (f & MachO::MH_APP_EXTENSION_SAFE) {
4129 outs() << " APP_EXTENSION_SAFE";
4130 f &= ~MachO::MH_APP_EXTENSION_SAFE;
4132 if (f != 0 || flags == 0)
4133 outs() << format(" 0x%08" PRIx32, f);
4135 outs() << format(" 0x%08" PRIx32, magic);
4136 outs() << format(" %7d", cputype);
4137 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
4138 outs() << format(" 0x%02" PRIx32,
4139 (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24);
4140 outs() << format(" %10u", filetype);
4141 outs() << format(" %5u", ncmds);
4142 outs() << format(" %10u", sizeofcmds);
4143 outs() << format(" 0x%08" PRIx32, flags);
4148 static void PrintSegmentCommand(uint32_t cmd, uint32_t cmdsize,
4149 StringRef SegName, uint64_t vmaddr,
4150 uint64_t vmsize, uint64_t fileoff,
4151 uint64_t filesize, uint32_t maxprot,
4152 uint32_t initprot, uint32_t nsects,
4153 uint32_t flags, uint32_t object_size,
4155 uint64_t expected_cmdsize;
4156 if (cmd == MachO::LC_SEGMENT) {
4157 outs() << " cmd LC_SEGMENT\n";
4158 expected_cmdsize = nsects;
4159 expected_cmdsize *= sizeof(struct MachO::section);
4160 expected_cmdsize += sizeof(struct MachO::segment_command);
4162 outs() << " cmd LC_SEGMENT_64\n";
4163 expected_cmdsize = nsects;
4164 expected_cmdsize *= sizeof(struct MachO::section_64);
4165 expected_cmdsize += sizeof(struct MachO::segment_command_64);
4167 outs() << " cmdsize " << cmdsize;
4168 if (cmdsize != expected_cmdsize)
4169 outs() << " Inconsistent size\n";
4172 outs() << " segname " << SegName << "\n";
4173 if (cmd == MachO::LC_SEGMENT_64) {
4174 outs() << " vmaddr " << format("0x%016" PRIx64, vmaddr) << "\n";
4175 outs() << " vmsize " << format("0x%016" PRIx64, vmsize) << "\n";
4177 outs() << " vmaddr " << format("0x%08" PRIx64, vmaddr) << "\n";
4178 outs() << " vmsize " << format("0x%08" PRIx64, vmsize) << "\n";
4180 outs() << " fileoff " << fileoff;
4181 if (fileoff > object_size)
4182 outs() << " (past end of file)\n";
4185 outs() << " filesize " << filesize;
4186 if (fileoff + filesize > object_size)
4187 outs() << " (past end of file)\n";
4192 ~(MachO::VM_PROT_READ | MachO::VM_PROT_WRITE |
4193 MachO::VM_PROT_EXECUTE)) != 0)
4194 outs() << " maxprot ?" << format("0x%08" PRIx32, maxprot) << "\n";
4196 if (maxprot & MachO::VM_PROT_READ)
4197 outs() << " maxprot r";
4199 outs() << " maxprot -";
4200 if (maxprot & MachO::VM_PROT_WRITE)
4204 if (maxprot & MachO::VM_PROT_EXECUTE)
4210 ~(MachO::VM_PROT_READ | MachO::VM_PROT_WRITE |
4211 MachO::VM_PROT_EXECUTE)) != 0)
4212 outs() << " initprot ?" << format("0x%08" PRIx32, initprot) << "\n";
4214 if (initprot & MachO::VM_PROT_READ)
4215 outs() << " initprot r";
4217 outs() << " initprot -";
4218 if (initprot & MachO::VM_PROT_WRITE)
4222 if (initprot & MachO::VM_PROT_EXECUTE)
4228 outs() << " maxprot " << format("0x%08" PRIx32, maxprot) << "\n";
4229 outs() << " initprot " << format("0x%08" PRIx32, initprot) << "\n";
4231 outs() << " nsects " << nsects << "\n";
4235 outs() << " (none)\n";
4237 if (flags & MachO::SG_HIGHVM) {
4238 outs() << " HIGHVM";
4239 flags &= ~MachO::SG_HIGHVM;
4241 if (flags & MachO::SG_FVMLIB) {
4242 outs() << " FVMLIB";
4243 flags &= ~MachO::SG_FVMLIB;
4245 if (flags & MachO::SG_NORELOC) {
4246 outs() << " NORELOC";
4247 flags &= ~MachO::SG_NORELOC;
4249 if (flags & MachO::SG_PROTECTED_VERSION_1) {
4250 outs() << " PROTECTED_VERSION_1";
4251 flags &= ~MachO::SG_PROTECTED_VERSION_1;
4254 outs() << format(" 0x%08" PRIx32, flags) << " (unknown flags)\n";
4259 outs() << " flags " << format("0x%" PRIx32, flags) << "\n";
4263 static void PrintSection(const char *sectname, const char *segname,
4264 uint64_t addr, uint64_t size, uint32_t offset,
4265 uint32_t align, uint32_t reloff, uint32_t nreloc,
4266 uint32_t flags, uint32_t reserved1, uint32_t reserved2,
4267 uint32_t cmd, const char *sg_segname,
4268 uint32_t filetype, uint32_t object_size,
4270 outs() << "Section\n";
4271 outs() << " sectname " << format("%.16s\n", sectname);
4272 outs() << " segname " << format("%.16s", segname);
4273 if (filetype != MachO::MH_OBJECT && strncmp(sg_segname, segname, 16) != 0)
4274 outs() << " (does not match segment)\n";
4277 if (cmd == MachO::LC_SEGMENT_64) {
4278 outs() << " addr " << format("0x%016" PRIx64, addr) << "\n";
4279 outs() << " size " << format("0x%016" PRIx64, size);
4281 outs() << " addr " << format("0x%08" PRIx64, addr) << "\n";
4282 outs() << " size " << format("0x%08" PRIx64, size);
4284 if ((flags & MachO::S_ZEROFILL) != 0 && offset + size > object_size)
4285 outs() << " (past end of file)\n";
4288 outs() << " offset " << offset;
4289 if (offset > object_size)
4290 outs() << " (past end of file)\n";
4293 uint32_t align_shifted = 1 << align;
4294 outs() << " align 2^" << align << " (" << align_shifted << ")\n";
4295 outs() << " reloff " << reloff;
4296 if (reloff > object_size)
4297 outs() << " (past end of file)\n";
4300 outs() << " nreloc " << nreloc;
4301 if (reloff + nreloc * sizeof(struct MachO::relocation_info) > object_size)
4302 outs() << " (past end of file)\n";
4305 uint32_t section_type = flags & MachO::SECTION_TYPE;
4308 if (section_type == MachO::S_REGULAR)
4309 outs() << " S_REGULAR\n";
4310 else if (section_type == MachO::S_ZEROFILL)
4311 outs() << " S_ZEROFILL\n";
4312 else if (section_type == MachO::S_CSTRING_LITERALS)
4313 outs() << " S_CSTRING_LITERALS\n";
4314 else if (section_type == MachO::S_4BYTE_LITERALS)
4315 outs() << " S_4BYTE_LITERALS\n";
4316 else if (section_type == MachO::S_8BYTE_LITERALS)
4317 outs() << " S_8BYTE_LITERALS\n";
4318 else if (section_type == MachO::S_16BYTE_LITERALS)
4319 outs() << " S_16BYTE_LITERALS\n";
4320 else if (section_type == MachO::S_LITERAL_POINTERS)
4321 outs() << " S_LITERAL_POINTERS\n";
4322 else if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS)
4323 outs() << " S_NON_LAZY_SYMBOL_POINTERS\n";
4324 else if (section_type == MachO::S_LAZY_SYMBOL_POINTERS)
4325 outs() << " S_LAZY_SYMBOL_POINTERS\n";
4326 else if (section_type == MachO::S_SYMBOL_STUBS)
4327 outs() << " S_SYMBOL_STUBS\n";
4328 else if (section_type == MachO::S_MOD_INIT_FUNC_POINTERS)
4329 outs() << " S_MOD_INIT_FUNC_POINTERS\n";
4330 else if (section_type == MachO::S_MOD_TERM_FUNC_POINTERS)
4331 outs() << " S_MOD_TERM_FUNC_POINTERS\n";
4332 else if (section_type == MachO::S_COALESCED)
4333 outs() << " S_COALESCED\n";
4334 else if (section_type == MachO::S_INTERPOSING)
4335 outs() << " S_INTERPOSING\n";
4336 else if (section_type == MachO::S_DTRACE_DOF)
4337 outs() << " S_DTRACE_DOF\n";
4338 else if (section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS)
4339 outs() << " S_LAZY_DYLIB_SYMBOL_POINTERS\n";
4340 else if (section_type == MachO::S_THREAD_LOCAL_REGULAR)
4341 outs() << " S_THREAD_LOCAL_REGULAR\n";
4342 else if (section_type == MachO::S_THREAD_LOCAL_ZEROFILL)
4343 outs() << " S_THREAD_LOCAL_ZEROFILL\n";
4344 else if (section_type == MachO::S_THREAD_LOCAL_VARIABLES)
4345 outs() << " S_THREAD_LOCAL_VARIABLES\n";
4346 else if (section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS)
4347 outs() << " S_THREAD_LOCAL_VARIABLE_POINTERS\n";
4348 else if (section_type == MachO::S_THREAD_LOCAL_INIT_FUNCTION_POINTERS)
4349 outs() << " S_THREAD_LOCAL_INIT_FUNCTION_POINTERS\n";
4351 outs() << format("0x%08" PRIx32, section_type) << "\n";
4352 outs() << "attributes";
4353 uint32_t section_attributes = flags & MachO::SECTION_ATTRIBUTES;
4354 if (section_attributes & MachO::S_ATTR_PURE_INSTRUCTIONS)
4355 outs() << " PURE_INSTRUCTIONS";
4356 if (section_attributes & MachO::S_ATTR_NO_TOC)
4357 outs() << " NO_TOC";
4358 if (section_attributes & MachO::S_ATTR_STRIP_STATIC_SYMS)
4359 outs() << " STRIP_STATIC_SYMS";
4360 if (section_attributes & MachO::S_ATTR_NO_DEAD_STRIP)
4361 outs() << " NO_DEAD_STRIP";
4362 if (section_attributes & MachO::S_ATTR_LIVE_SUPPORT)
4363 outs() << " LIVE_SUPPORT";
4364 if (section_attributes & MachO::S_ATTR_SELF_MODIFYING_CODE)
4365 outs() << " SELF_MODIFYING_CODE";
4366 if (section_attributes & MachO::S_ATTR_DEBUG)
4368 if (section_attributes & MachO::S_ATTR_SOME_INSTRUCTIONS)
4369 outs() << " SOME_INSTRUCTIONS";
4370 if (section_attributes & MachO::S_ATTR_EXT_RELOC)
4371 outs() << " EXT_RELOC";
4372 if (section_attributes & MachO::S_ATTR_LOC_RELOC)
4373 outs() << " LOC_RELOC";
4374 if (section_attributes == 0)
4375 outs() << " (none)";
4378 outs() << " flags " << format("0x%08" PRIx32, flags) << "\n";
4379 outs() << " reserved1 " << reserved1;
4380 if (section_type == MachO::S_SYMBOL_STUBS ||
4381 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
4382 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
4383 section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
4384 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS)
4385 outs() << " (index into indirect symbol table)\n";
4388 outs() << " reserved2 " << reserved2;
4389 if (section_type == MachO::S_SYMBOL_STUBS)
4390 outs() << " (size of stubs)\n";
4395 static void PrintSymtabLoadCommand(MachO::symtab_command st, bool Is64Bit,
4396 uint32_t object_size) {
4397 outs() << " cmd LC_SYMTAB\n";
4398 outs() << " cmdsize " << st.cmdsize;
4399 if (st.cmdsize != sizeof(struct MachO::symtab_command))
4400 outs() << " Incorrect size\n";
4403 outs() << " symoff " << st.symoff;
4404 if (st.symoff > object_size)
4405 outs() << " (past end of file)\n";
4408 outs() << " nsyms " << st.nsyms;
4411 big_size = st.nsyms;
4412 big_size *= sizeof(struct MachO::nlist_64);
4413 big_size += st.symoff;
4414 if (big_size > object_size)
4415 outs() << " (past end of file)\n";
4419 big_size = st.nsyms;
4420 big_size *= sizeof(struct MachO::nlist);
4421 big_size += st.symoff;
4422 if (big_size > object_size)
4423 outs() << " (past end of file)\n";
4427 outs() << " stroff " << st.stroff;
4428 if (st.stroff > object_size)
4429 outs() << " (past end of file)\n";
4432 outs() << " strsize " << st.strsize;
4433 big_size = st.stroff;
4434 big_size += st.strsize;
4435 if (big_size > object_size)
4436 outs() << " (past end of file)\n";
4441 static void PrintDysymtabLoadCommand(MachO::dysymtab_command dyst,
4442 uint32_t nsyms, uint32_t object_size,
4444 outs() << " cmd LC_DYSYMTAB\n";
4445 outs() << " cmdsize " << dyst.cmdsize;
4446 if (dyst.cmdsize != sizeof(struct MachO::dysymtab_command))
4447 outs() << " Incorrect size\n";
4450 outs() << " ilocalsym " << dyst.ilocalsym;
4451 if (dyst.ilocalsym > nsyms)
4452 outs() << " (greater than the number of symbols)\n";
4455 outs() << " nlocalsym " << dyst.nlocalsym;
4457 big_size = dyst.ilocalsym;
4458 big_size += dyst.nlocalsym;
4459 if (big_size > nsyms)
4460 outs() << " (past the end of the symbol table)\n";
4463 outs() << " iextdefsym " << dyst.iextdefsym;
4464 if (dyst.iextdefsym > nsyms)
4465 outs() << " (greater than the number of symbols)\n";
4468 outs() << " nextdefsym " << dyst.nextdefsym;
4469 big_size = dyst.iextdefsym;
4470 big_size += dyst.nextdefsym;
4471 if (big_size > nsyms)
4472 outs() << " (past the end of the symbol table)\n";
4475 outs() << " iundefsym " << dyst.iundefsym;
4476 if (dyst.iundefsym > nsyms)
4477 outs() << " (greater than the number of symbols)\n";
4480 outs() << " nundefsym " << dyst.nundefsym;
4481 big_size = dyst.iundefsym;
4482 big_size += dyst.nundefsym;
4483 if (big_size > nsyms)
4484 outs() << " (past the end of the symbol table)\n";
4487 outs() << " tocoff " << dyst.tocoff;
4488 if (dyst.tocoff > object_size)
4489 outs() << " (past end of file)\n";
4492 outs() << " ntoc " << dyst.ntoc;
4493 big_size = dyst.ntoc;
4494 big_size *= sizeof(struct MachO::dylib_table_of_contents);
4495 big_size += dyst.tocoff;
4496 if (big_size > object_size)
4497 outs() << " (past end of file)\n";
4500 outs() << " modtaboff " << dyst.modtaboff;
4501 if (dyst.modtaboff > object_size)
4502 outs() << " (past end of file)\n";
4505 outs() << " nmodtab " << dyst.nmodtab;
4508 modtabend = dyst.nmodtab;
4509 modtabend *= sizeof(struct MachO::dylib_module_64);
4510 modtabend += dyst.modtaboff;
4512 modtabend = dyst.nmodtab;
4513 modtabend *= sizeof(struct MachO::dylib_module);
4514 modtabend += dyst.modtaboff;
4516 if (modtabend > object_size)
4517 outs() << " (past end of file)\n";
4520 outs() << " extrefsymoff " << dyst.extrefsymoff;
4521 if (dyst.extrefsymoff > object_size)
4522 outs() << " (past end of file)\n";
4525 outs() << " nextrefsyms " << dyst.nextrefsyms;
4526 big_size = dyst.nextrefsyms;
4527 big_size *= sizeof(struct MachO::dylib_reference);
4528 big_size += dyst.extrefsymoff;
4529 if (big_size > object_size)
4530 outs() << " (past end of file)\n";
4533 outs() << " indirectsymoff " << dyst.indirectsymoff;
4534 if (dyst.indirectsymoff > object_size)
4535 outs() << " (past end of file)\n";
4538 outs() << " nindirectsyms " << dyst.nindirectsyms;
4539 big_size = dyst.nindirectsyms;
4540 big_size *= sizeof(uint32_t);
4541 big_size += dyst.indirectsymoff;
4542 if (big_size > object_size)
4543 outs() << " (past end of file)\n";
4546 outs() << " extreloff " << dyst.extreloff;
4547 if (dyst.extreloff > object_size)
4548 outs() << " (past end of file)\n";
4551 outs() << " nextrel " << dyst.nextrel;
4552 big_size = dyst.nextrel;
4553 big_size *= sizeof(struct MachO::relocation_info);
4554 big_size += dyst.extreloff;
4555 if (big_size > object_size)
4556 outs() << " (past end of file)\n";
4559 outs() << " locreloff " << dyst.locreloff;
4560 if (dyst.locreloff > object_size)
4561 outs() << " (past end of file)\n";
4564 outs() << " nlocrel " << dyst.nlocrel;
4565 big_size = dyst.nlocrel;
4566 big_size *= sizeof(struct MachO::relocation_info);
4567 big_size += dyst.locreloff;
4568 if (big_size > object_size)
4569 outs() << " (past end of file)\n";
4574 static void PrintDyldInfoLoadCommand(MachO::dyld_info_command dc,
4575 uint32_t object_size) {
4576 if (dc.cmd == MachO::LC_DYLD_INFO)
4577 outs() << " cmd LC_DYLD_INFO\n";
4579 outs() << " cmd LC_DYLD_INFO_ONLY\n";
4580 outs() << " cmdsize " << dc.cmdsize;
4581 if (dc.cmdsize != sizeof(struct MachO::dyld_info_command))
4582 outs() << " Incorrect size\n";
4585 outs() << " rebase_off " << dc.rebase_off;
4586 if (dc.rebase_off > object_size)
4587 outs() << " (past end of file)\n";
4590 outs() << " rebase_size " << dc.rebase_size;
4592 big_size = dc.rebase_off;
4593 big_size += dc.rebase_size;
4594 if (big_size > object_size)
4595 outs() << " (past end of file)\n";
4598 outs() << " bind_off " << dc.bind_off;
4599 if (dc.bind_off > object_size)
4600 outs() << " (past end of file)\n";
4603 outs() << " bind_size " << dc.bind_size;
4604 big_size = dc.bind_off;
4605 big_size += dc.bind_size;
4606 if (big_size > object_size)
4607 outs() << " (past end of file)\n";
4610 outs() << " weak_bind_off " << dc.weak_bind_off;
4611 if (dc.weak_bind_off > object_size)
4612 outs() << " (past end of file)\n";
4615 outs() << " weak_bind_size " << dc.weak_bind_size;
4616 big_size = dc.weak_bind_off;
4617 big_size += dc.weak_bind_size;
4618 if (big_size > object_size)
4619 outs() << " (past end of file)\n";
4622 outs() << " lazy_bind_off " << dc.lazy_bind_off;
4623 if (dc.lazy_bind_off > object_size)
4624 outs() << " (past end of file)\n";
4627 outs() << " lazy_bind_size " << dc.lazy_bind_size;
4628 big_size = dc.lazy_bind_off;
4629 big_size += dc.lazy_bind_size;
4630 if (big_size > object_size)
4631 outs() << " (past end of file)\n";
4634 outs() << " export_off " << dc.export_off;
4635 if (dc.export_off > object_size)
4636 outs() << " (past end of file)\n";
4639 outs() << " export_size " << dc.export_size;
4640 big_size = dc.export_off;
4641 big_size += dc.export_size;
4642 if (big_size > object_size)
4643 outs() << " (past end of file)\n";
4648 static void PrintDyldLoadCommand(MachO::dylinker_command dyld,
4650 if (dyld.cmd == MachO::LC_ID_DYLINKER)
4651 outs() << " cmd LC_ID_DYLINKER\n";
4652 else if (dyld.cmd == MachO::LC_LOAD_DYLINKER)
4653 outs() << " cmd LC_LOAD_DYLINKER\n";
4654 else if (dyld.cmd == MachO::LC_DYLD_ENVIRONMENT)
4655 outs() << " cmd LC_DYLD_ENVIRONMENT\n";
4657 outs() << " cmd ?(" << dyld.cmd << ")\n";
4658 outs() << " cmdsize " << dyld.cmdsize;
4659 if (dyld.cmdsize < sizeof(struct MachO::dylinker_command))
4660 outs() << " Incorrect size\n";
4663 if (dyld.name >= dyld.cmdsize)
4664 outs() << " name ?(bad offset " << dyld.name << ")\n";
4666 const char *P = (const char *)(Ptr) + dyld.name;
4667 outs() << " name " << P << " (offset " << dyld.name << ")\n";
4671 static void PrintUuidLoadCommand(MachO::uuid_command uuid) {
4672 outs() << " cmd LC_UUID\n";
4673 outs() << " cmdsize " << uuid.cmdsize;
4674 if (uuid.cmdsize != sizeof(struct MachO::uuid_command))
4675 outs() << " Incorrect size\n";
4679 outs() << format("%02" PRIX32, uuid.uuid[0]);
4680 outs() << format("%02" PRIX32, uuid.uuid[1]);
4681 outs() << format("%02" PRIX32, uuid.uuid[2]);
4682 outs() << format("%02" PRIX32, uuid.uuid[3]);
4684 outs() << format("%02" PRIX32, uuid.uuid[4]);
4685 outs() << format("%02" PRIX32, uuid.uuid[5]);
4687 outs() << format("%02" PRIX32, uuid.uuid[6]);
4688 outs() << format("%02" PRIX32, uuid.uuid[7]);
4690 outs() << format("%02" PRIX32, uuid.uuid[8]);
4691 outs() << format("%02" PRIX32, uuid.uuid[9]);
4693 outs() << format("%02" PRIX32, uuid.uuid[10]);
4694 outs() << format("%02" PRIX32, uuid.uuid[11]);
4695 outs() << format("%02" PRIX32, uuid.uuid[12]);
4696 outs() << format("%02" PRIX32, uuid.uuid[13]);
4697 outs() << format("%02" PRIX32, uuid.uuid[14]);
4698 outs() << format("%02" PRIX32, uuid.uuid[15]);
4702 static void PrintRpathLoadCommand(MachO::rpath_command rpath, const char *Ptr) {
4703 outs() << " cmd LC_RPATH\n";
4704 outs() << " cmdsize " << rpath.cmdsize;
4705 if (rpath.cmdsize < sizeof(struct MachO::rpath_command))
4706 outs() << " Incorrect size\n";
4709 if (rpath.path >= rpath.cmdsize)
4710 outs() << " path ?(bad offset " << rpath.path << ")\n";
4712 const char *P = (const char *)(Ptr) + rpath.path;
4713 outs() << " path " << P << " (offset " << rpath.path << ")\n";
4717 static void PrintVersionMinLoadCommand(MachO::version_min_command vd) {
4718 if (vd.cmd == MachO::LC_VERSION_MIN_MACOSX)
4719 outs() << " cmd LC_VERSION_MIN_MACOSX\n";
4720 else if (vd.cmd == MachO::LC_VERSION_MIN_IPHONEOS)
4721 outs() << " cmd LC_VERSION_MIN_IPHONEOS\n";
4723 outs() << " cmd " << vd.cmd << " (?)\n";
4724 outs() << " cmdsize " << vd.cmdsize;
4725 if (vd.cmdsize != sizeof(struct MachO::version_min_command))
4726 outs() << " Incorrect size\n";
4729 outs() << " version " << ((vd.version >> 16) & 0xffff) << "."
4730 << ((vd.version >> 8) & 0xff);
4731 if ((vd.version & 0xff) != 0)
4732 outs() << "." << (vd.version & 0xff);
4735 outs() << " sdk n/a";
4737 outs() << " sdk " << ((vd.sdk >> 16) & 0xffff) << "."
4738 << ((vd.sdk >> 8) & 0xff);
4740 if ((vd.sdk & 0xff) != 0)
4741 outs() << "." << (vd.sdk & 0xff);
4745 static void PrintSourceVersionCommand(MachO::source_version_command sd) {
4746 outs() << " cmd LC_SOURCE_VERSION\n";
4747 outs() << " cmdsize " << sd.cmdsize;
4748 if (sd.cmdsize != sizeof(struct MachO::source_version_command))
4749 outs() << " Incorrect size\n";
4752 uint64_t a = (sd.version >> 40) & 0xffffff;
4753 uint64_t b = (sd.version >> 30) & 0x3ff;
4754 uint64_t c = (sd.version >> 20) & 0x3ff;
4755 uint64_t d = (sd.version >> 10) & 0x3ff;
4756 uint64_t e = sd.version & 0x3ff;
4757 outs() << " version " << a << "." << b;
4759 outs() << "." << c << "." << d << "." << e;
4761 outs() << "." << c << "." << d;
4767 static void PrintEntryPointCommand(MachO::entry_point_command ep) {
4768 outs() << " cmd LC_MAIN\n";
4769 outs() << " cmdsize " << ep.cmdsize;
4770 if (ep.cmdsize != sizeof(struct MachO::entry_point_command))
4771 outs() << " Incorrect size\n";
4774 outs() << " entryoff " << ep.entryoff << "\n";
4775 outs() << " stacksize " << ep.stacksize << "\n";
4778 static void PrintEncryptionInfoCommand(MachO::encryption_info_command ec,
4779 uint32_t object_size) {
4780 outs() << " cmd LC_ENCRYPTION_INFO\n";
4781 outs() << " cmdsize " << ec.cmdsize;
4782 if (ec.cmdsize != sizeof(struct MachO::encryption_info_command))
4783 outs() << " Incorrect size\n";
4786 outs() << " cryptoff " << ec.cryptoff;
4787 if (ec.cryptoff > object_size)
4788 outs() << " (past end of file)\n";
4791 outs() << " cryptsize " << ec.cryptsize;
4792 if (ec.cryptsize > object_size)
4793 outs() << " (past end of file)\n";
4796 outs() << " cryptid " << ec.cryptid << "\n";
4799 static void PrintEncryptionInfoCommand64(MachO::encryption_info_command_64 ec,
4800 uint32_t object_size) {
4801 outs() << " cmd LC_ENCRYPTION_INFO_64\n";
4802 outs() << " cmdsize " << ec.cmdsize;
4803 if (ec.cmdsize != sizeof(struct MachO::encryption_info_command_64))
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";
4818 outs() << " pad " << ec.pad << "\n";
4821 static void PrintLinkerOptionCommand(MachO::linker_option_command lo,
4823 outs() << " cmd LC_LINKER_OPTION\n";
4824 outs() << " cmdsize " << lo.cmdsize;
4825 if (lo.cmdsize < sizeof(struct MachO::linker_option_command))
4826 outs() << " Incorrect size\n";
4829 outs() << " count " << lo.count << "\n";
4830 const char *string = Ptr + sizeof(struct MachO::linker_option_command);
4831 uint32_t left = lo.cmdsize - sizeof(struct MachO::linker_option_command);
4834 while (*string == '\0' && left > 0) {
4840 outs() << " string #" << i << " " << format("%.*s\n", left, string);
4841 uint32_t NullPos = StringRef(string, left).find('\0');
4842 uint32_t len = std::min(NullPos, left) + 1;
4848 outs() << " count " << lo.count << " does not match number of strings "
4852 static void PrintSubFrameworkCommand(MachO::sub_framework_command sub,
4854 outs() << " cmd LC_SUB_FRAMEWORK\n";
4855 outs() << " cmdsize " << sub.cmdsize;
4856 if (sub.cmdsize < sizeof(struct MachO::sub_framework_command))
4857 outs() << " Incorrect size\n";
4860 if (sub.umbrella < sub.cmdsize) {
4861 const char *P = Ptr + sub.umbrella;
4862 outs() << " umbrella " << P << " (offset " << sub.umbrella << ")\n";
4864 outs() << " umbrella ?(bad offset " << sub.umbrella << ")\n";
4868 static void PrintSubUmbrellaCommand(MachO::sub_umbrella_command sub,
4870 outs() << " cmd LC_SUB_UMBRELLA\n";
4871 outs() << " cmdsize " << sub.cmdsize;
4872 if (sub.cmdsize < sizeof(struct MachO::sub_umbrella_command))
4873 outs() << " Incorrect size\n";
4876 if (sub.sub_umbrella < sub.cmdsize) {
4877 const char *P = Ptr + sub.sub_umbrella;
4878 outs() << " sub_umbrella " << P << " (offset " << sub.sub_umbrella << ")\n";
4880 outs() << " sub_umbrella ?(bad offset " << sub.sub_umbrella << ")\n";
4884 static void PrintSubLibraryCommand(MachO::sub_library_command sub,
4886 outs() << " cmd LC_SUB_LIBRARY\n";
4887 outs() << " cmdsize " << sub.cmdsize;
4888 if (sub.cmdsize < sizeof(struct MachO::sub_library_command))
4889 outs() << " Incorrect size\n";
4892 if (sub.sub_library < sub.cmdsize) {
4893 const char *P = Ptr + sub.sub_library;
4894 outs() << " sub_library " << P << " (offset " << sub.sub_library << ")\n";
4896 outs() << " sub_library ?(bad offset " << sub.sub_library << ")\n";
4900 static void PrintSubClientCommand(MachO::sub_client_command sub,
4902 outs() << " cmd LC_SUB_CLIENT\n";
4903 outs() << " cmdsize " << sub.cmdsize;
4904 if (sub.cmdsize < sizeof(struct MachO::sub_client_command))
4905 outs() << " Incorrect size\n";
4908 if (sub.client < sub.cmdsize) {
4909 const char *P = Ptr + sub.client;
4910 outs() << " client " << P << " (offset " << sub.client << ")\n";
4912 outs() << " client ?(bad offset " << sub.client << ")\n";
4916 static void PrintRoutinesCommand(MachO::routines_command r) {
4917 outs() << " cmd LC_ROUTINES\n";
4918 outs() << " cmdsize " << r.cmdsize;
4919 if (r.cmdsize != sizeof(struct MachO::routines_command))
4920 outs() << " Incorrect size\n";
4923 outs() << " init_address " << format("0x%08" PRIx32, r.init_address) << "\n";
4924 outs() << " init_module " << r.init_module << "\n";
4925 outs() << " reserved1 " << r.reserved1 << "\n";
4926 outs() << " reserved2 " << r.reserved2 << "\n";
4927 outs() << " reserved3 " << r.reserved3 << "\n";
4928 outs() << " reserved4 " << r.reserved4 << "\n";
4929 outs() << " reserved5 " << r.reserved5 << "\n";
4930 outs() << " reserved6 " << r.reserved6 << "\n";
4933 static void PrintRoutinesCommand64(MachO::routines_command_64 r) {
4934 outs() << " cmd LC_ROUTINES_64\n";
4935 outs() << " cmdsize " << r.cmdsize;
4936 if (r.cmdsize != sizeof(struct MachO::routines_command_64))
4937 outs() << " Incorrect size\n";
4940 outs() << " init_address " << format("0x%016" PRIx64, r.init_address) << "\n";
4941 outs() << " init_module " << r.init_module << "\n";
4942 outs() << " reserved1 " << r.reserved1 << "\n";
4943 outs() << " reserved2 " << r.reserved2 << "\n";
4944 outs() << " reserved3 " << r.reserved3 << "\n";
4945 outs() << " reserved4 " << r.reserved4 << "\n";
4946 outs() << " reserved5 " << r.reserved5 << "\n";
4947 outs() << " reserved6 " << r.reserved6 << "\n";
4950 static void Print_x86_thread_state64_t(MachO::x86_thread_state64_t &cpu64) {
4951 outs() << " rax " << format("0x%016" PRIx64, cpu64.rax);
4952 outs() << " rbx " << format("0x%016" PRIx64, cpu64.rbx);
4953 outs() << " rcx " << format("0x%016" PRIx64, cpu64.rcx) << "\n";
4954 outs() << " rdx " << format("0x%016" PRIx64, cpu64.rdx);
4955 outs() << " rdi " << format("0x%016" PRIx64, cpu64.rdi);
4956 outs() << " rsi " << format("0x%016" PRIx64, cpu64.rsi) << "\n";
4957 outs() << " rbp " << format("0x%016" PRIx64, cpu64.rbp);
4958 outs() << " rsp " << format("0x%016" PRIx64, cpu64.rsp);
4959 outs() << " r8 " << format("0x%016" PRIx64, cpu64.r8) << "\n";
4960 outs() << " r9 " << format("0x%016" PRIx64, cpu64.r9);
4961 outs() << " r10 " << format("0x%016" PRIx64, cpu64.r10);
4962 outs() << " r11 " << format("0x%016" PRIx64, cpu64.r11) << "\n";
4963 outs() << " r12 " << format("0x%016" PRIx64, cpu64.r12);
4964 outs() << " r13 " << format("0x%016" PRIx64, cpu64.r13);
4965 outs() << " r14 " << format("0x%016" PRIx64, cpu64.r14) << "\n";
4966 outs() << " r15 " << format("0x%016" PRIx64, cpu64.r15);
4967 outs() << " rip " << format("0x%016" PRIx64, cpu64.rip) << "\n";
4968 outs() << "rflags " << format("0x%016" PRIx64, cpu64.rflags);
4969 outs() << " cs " << format("0x%016" PRIx64, cpu64.cs);
4970 outs() << " fs " << format("0x%016" PRIx64, cpu64.fs) << "\n";
4971 outs() << " gs " << format("0x%016" PRIx64, cpu64.gs) << "\n";
4974 static void Print_mmst_reg(MachO::mmst_reg_t &r) {
4976 outs() << "\t mmst_reg ";
4977 for (f = 0; f < 10; f++)
4978 outs() << format("%02" PRIx32, (r.mmst_reg[f] & 0xff)) << " ";
4980 outs() << "\t mmst_rsrv ";
4981 for (f = 0; f < 6; f++)
4982 outs() << format("%02" PRIx32, (r.mmst_rsrv[f] & 0xff)) << " ";
4986 static void Print_xmm_reg(MachO::xmm_reg_t &r) {
4988 outs() << "\t xmm_reg ";
4989 for (f = 0; f < 16; f++)
4990 outs() << format("%02" PRIx32, (r.xmm_reg[f] & 0xff)) << " ";
4994 static void Print_x86_float_state_t(MachO::x86_float_state64_t &fpu) {
4995 outs() << "\t fpu_reserved[0] " << fpu.fpu_reserved[0];
4996 outs() << " fpu_reserved[1] " << fpu.fpu_reserved[1] << "\n";
4997 outs() << "\t control: invalid " << fpu.fpu_fcw.invalid;
4998 outs() << " denorm " << fpu.fpu_fcw.denorm;
4999 outs() << " zdiv " << fpu.fpu_fcw.zdiv;
5000 outs() << " ovrfl " << fpu.fpu_fcw.ovrfl;
5001 outs() << " undfl " << fpu.fpu_fcw.undfl;
5002 outs() << " precis " << fpu.fpu_fcw.precis << "\n";
5003 outs() << "\t\t pc ";
5004 if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_24B)
5005 outs() << "FP_PREC_24B ";
5006 else if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_53B)
5007 outs() << "FP_PREC_53B ";
5008 else if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_64B)
5009 outs() << "FP_PREC_64B ";
5011 outs() << fpu.fpu_fcw.pc << " ";
5013 if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_NEAR)
5014 outs() << "FP_RND_NEAR ";
5015 else if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_DOWN)
5016 outs() << "FP_RND_DOWN ";
5017 else if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_UP)
5018 outs() << "FP_RND_UP ";
5019 else if (fpu.fpu_fcw.rc == MachO::x86_FP_CHOP)
5020 outs() << "FP_CHOP ";
5022 outs() << "\t status: invalid " << fpu.fpu_fsw.invalid;
5023 outs() << " denorm " << fpu.fpu_fsw.denorm;
5024 outs() << " zdiv " << fpu.fpu_fsw.zdiv;
5025 outs() << " ovrfl " << fpu.fpu_fsw.ovrfl;
5026 outs() << " undfl " << fpu.fpu_fsw.undfl;
5027 outs() << " precis " << fpu.fpu_fsw.precis;
5028 outs() << " stkflt " << fpu.fpu_fsw.stkflt << "\n";
5029 outs() << "\t errsumm " << fpu.fpu_fsw.errsumm;
5030 outs() << " c0 " << fpu.fpu_fsw.c0;
5031 outs() << " c1 " << fpu.fpu_fsw.c1;
5032 outs() << " c2 " << fpu.fpu_fsw.c2;
5033 outs() << " tos " << fpu.fpu_fsw.tos;
5034 outs() << " c3 " << fpu.fpu_fsw.c3;
5035 outs() << " busy " << fpu.fpu_fsw.busy << "\n";
5036 outs() << "\t fpu_ftw " << format("0x%02" PRIx32, fpu.fpu_ftw);
5037 outs() << " fpu_rsrv1 " << format("0x%02" PRIx32, fpu.fpu_rsrv1);
5038 outs() << " fpu_fop " << format("0x%04" PRIx32, fpu.fpu_fop);
5039 outs() << " fpu_ip " << format("0x%08" PRIx32, fpu.fpu_ip) << "\n";
5040 outs() << "\t fpu_cs " << format("0x%04" PRIx32, fpu.fpu_cs);
5041 outs() << " fpu_rsrv2 " << format("0x%04" PRIx32, fpu.fpu_rsrv2);
5042 outs() << " fpu_dp " << format("0x%08" PRIx32, fpu.fpu_dp);
5043 outs() << " fpu_ds " << format("0x%04" PRIx32, fpu.fpu_ds) << "\n";
5044 outs() << "\t fpu_rsrv3 " << format("0x%04" PRIx32, fpu.fpu_rsrv3);
5045 outs() << " fpu_mxcsr " << format("0x%08" PRIx32, fpu.fpu_mxcsr);
5046 outs() << " fpu_mxcsrmask " << format("0x%08" PRIx32, fpu.fpu_mxcsrmask);
5048 outs() << "\t fpu_stmm0:\n";
5049 Print_mmst_reg(fpu.fpu_stmm0);
5050 outs() << "\t fpu_stmm1:\n";
5051 Print_mmst_reg(fpu.fpu_stmm1);
5052 outs() << "\t fpu_stmm2:\n";
5053 Print_mmst_reg(fpu.fpu_stmm2);
5054 outs() << "\t fpu_stmm3:\n";
5055 Print_mmst_reg(fpu.fpu_stmm3);
5056 outs() << "\t fpu_stmm4:\n";
5057 Print_mmst_reg(fpu.fpu_stmm4);
5058 outs() << "\t fpu_stmm5:\n";
5059 Print_mmst_reg(fpu.fpu_stmm5);
5060 outs() << "\t fpu_stmm6:\n";
5061 Print_mmst_reg(fpu.fpu_stmm6);
5062 outs() << "\t fpu_stmm7:\n";
5063 Print_mmst_reg(fpu.fpu_stmm7);
5064 outs() << "\t fpu_xmm0:\n";
5065 Print_xmm_reg(fpu.fpu_xmm0);
5066 outs() << "\t fpu_xmm1:\n";
5067 Print_xmm_reg(fpu.fpu_xmm1);
5068 outs() << "\t fpu_xmm2:\n";
5069 Print_xmm_reg(fpu.fpu_xmm2);
5070 outs() << "\t fpu_xmm3:\n";
5071 Print_xmm_reg(fpu.fpu_xmm3);
5072 outs() << "\t fpu_xmm4:\n";
5073 Print_xmm_reg(fpu.fpu_xmm4);
5074 outs() << "\t fpu_xmm5:\n";
5075 Print_xmm_reg(fpu.fpu_xmm5);
5076 outs() << "\t fpu_xmm6:\n";
5077 Print_xmm_reg(fpu.fpu_xmm6);
5078 outs() << "\t fpu_xmm7:\n";
5079 Print_xmm_reg(fpu.fpu_xmm7);
5080 outs() << "\t fpu_xmm8:\n";
5081 Print_xmm_reg(fpu.fpu_xmm8);
5082 outs() << "\t fpu_xmm9:\n";
5083 Print_xmm_reg(fpu.fpu_xmm9);
5084 outs() << "\t fpu_xmm10:\n";
5085 Print_xmm_reg(fpu.fpu_xmm10);
5086 outs() << "\t fpu_xmm11:\n";
5087 Print_xmm_reg(fpu.fpu_xmm11);
5088 outs() << "\t fpu_xmm12:\n";
5089 Print_xmm_reg(fpu.fpu_xmm12);
5090 outs() << "\t fpu_xmm13:\n";
5091 Print_xmm_reg(fpu.fpu_xmm13);
5092 outs() << "\t fpu_xmm14:\n";
5093 Print_xmm_reg(fpu.fpu_xmm14);
5094 outs() << "\t fpu_xmm15:\n";
5095 Print_xmm_reg(fpu.fpu_xmm15);
5096 outs() << "\t fpu_rsrv4:\n";
5097 for (uint32_t f = 0; f < 6; f++) {
5099 for (uint32_t g = 0; g < 16; g++)
5100 outs() << format("%02" PRIx32, fpu.fpu_rsrv4[f * g]) << " ";
5103 outs() << "\t fpu_reserved1 " << format("0x%08" PRIx32, fpu.fpu_reserved1);
5107 static void Print_x86_exception_state_t(MachO::x86_exception_state64_t &exc64) {
5108 outs() << "\t trapno " << format("0x%08" PRIx32, exc64.trapno);
5109 outs() << " err " << format("0x%08" PRIx32, exc64.err);
5110 outs() << " faultvaddr " << format("0x%016" PRIx64, exc64.faultvaddr) << "\n";
5113 static void PrintThreadCommand(MachO::thread_command t, const char *Ptr,
5114 bool isLittleEndian, uint32_t cputype) {
5115 if (t.cmd == MachO::LC_THREAD)
5116 outs() << " cmd LC_THREAD\n";
5117 else if (t.cmd == MachO::LC_UNIXTHREAD)
5118 outs() << " cmd LC_UNIXTHREAD\n";
5120 outs() << " cmd " << t.cmd << " (unknown)\n";
5121 outs() << " cmdsize " << t.cmdsize;
5122 if (t.cmdsize < sizeof(struct MachO::thread_command) + 2 * sizeof(uint32_t))
5123 outs() << " Incorrect size\n";
5127 const char *begin = Ptr + sizeof(struct MachO::thread_command);
5128 const char *end = Ptr + t.cmdsize;
5129 uint32_t flavor, count, left;
5130 if (cputype == MachO::CPU_TYPE_X86_64) {
5131 while (begin < end) {
5132 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
5133 memcpy((char *)&flavor, begin, sizeof(uint32_t));
5134 begin += sizeof(uint32_t);
5139 if (isLittleEndian != sys::IsLittleEndianHost)
5140 sys::swapByteOrder(flavor);
5141 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
5142 memcpy((char *)&count, begin, sizeof(uint32_t));
5143 begin += sizeof(uint32_t);
5148 if (isLittleEndian != sys::IsLittleEndianHost)
5149 sys::swapByteOrder(count);
5150 if (flavor == MachO::x86_THREAD_STATE64) {
5151 outs() << " flavor x86_THREAD_STATE64\n";
5152 if (count == MachO::x86_THREAD_STATE64_COUNT)
5153 outs() << " count x86_THREAD_STATE64_COUNT\n";
5155 outs() << " count " << count
5156 << " (not x86_THREAD_STATE64_COUNT)\n";
5157 MachO::x86_thread_state64_t cpu64;
5159 if (left >= sizeof(MachO::x86_thread_state64_t)) {
5160 memcpy(&cpu64, begin, sizeof(MachO::x86_thread_state64_t));
5161 begin += sizeof(MachO::x86_thread_state64_t);
5163 memset(&cpu64, '\0', sizeof(MachO::x86_thread_state64_t));
5164 memcpy(&cpu64, begin, left);
5167 if (isLittleEndian != sys::IsLittleEndianHost)
5169 Print_x86_thread_state64_t(cpu64);
5170 } else if (flavor == MachO::x86_THREAD_STATE) {
5171 outs() << " flavor x86_THREAD_STATE\n";
5172 if (count == MachO::x86_THREAD_STATE_COUNT)
5173 outs() << " count x86_THREAD_STATE_COUNT\n";
5175 outs() << " count " << count
5176 << " (not x86_THREAD_STATE_COUNT)\n";
5177 struct MachO::x86_thread_state_t ts;
5179 if (left >= sizeof(MachO::x86_thread_state_t)) {
5180 memcpy(&ts, begin, sizeof(MachO::x86_thread_state_t));
5181 begin += sizeof(MachO::x86_thread_state_t);
5183 memset(&ts, '\0', sizeof(MachO::x86_thread_state_t));
5184 memcpy(&ts, begin, left);
5187 if (isLittleEndian != sys::IsLittleEndianHost)
5189 if (ts.tsh.flavor == MachO::x86_THREAD_STATE64) {
5190 outs() << "\t tsh.flavor x86_THREAD_STATE64 ";
5191 if (ts.tsh.count == MachO::x86_THREAD_STATE64_COUNT)
5192 outs() << "tsh.count x86_THREAD_STATE64_COUNT\n";
5194 outs() << "tsh.count " << ts.tsh.count
5195 << " (not x86_THREAD_STATE64_COUNT\n";
5196 Print_x86_thread_state64_t(ts.uts.ts64);
5198 outs() << "\t tsh.flavor " << ts.tsh.flavor << " tsh.count "
5199 << ts.tsh.count << "\n";
5201 } else if (flavor == MachO::x86_FLOAT_STATE) {
5202 outs() << " flavor x86_FLOAT_STATE\n";
5203 if (count == MachO::x86_FLOAT_STATE_COUNT)
5204 outs() << " count x86_FLOAT_STATE_COUNT\n";
5206 outs() << " count " << count << " (not x86_FLOAT_STATE_COUNT)\n";
5207 struct MachO::x86_float_state_t fs;
5209 if (left >= sizeof(MachO::x86_float_state_t)) {
5210 memcpy(&fs, begin, sizeof(MachO::x86_float_state_t));
5211 begin += sizeof(MachO::x86_float_state_t);
5213 memset(&fs, '\0', sizeof(MachO::x86_float_state_t));
5214 memcpy(&fs, begin, left);
5217 if (isLittleEndian != sys::IsLittleEndianHost)
5219 if (fs.fsh.flavor == MachO::x86_FLOAT_STATE64) {
5220 outs() << "\t fsh.flavor x86_FLOAT_STATE64 ";
5221 if (fs.fsh.count == MachO::x86_FLOAT_STATE64_COUNT)
5222 outs() << "fsh.count x86_FLOAT_STATE64_COUNT\n";
5224 outs() << "fsh.count " << fs.fsh.count
5225 << " (not x86_FLOAT_STATE64_COUNT\n";
5226 Print_x86_float_state_t(fs.ufs.fs64);
5228 outs() << "\t fsh.flavor " << fs.fsh.flavor << " fsh.count "
5229 << fs.fsh.count << "\n";
5231 } else if (flavor == MachO::x86_EXCEPTION_STATE) {
5232 outs() << " flavor x86_EXCEPTION_STATE\n";
5233 if (count == MachO::x86_EXCEPTION_STATE_COUNT)
5234 outs() << " count x86_EXCEPTION_STATE_COUNT\n";
5236 outs() << " count " << count
5237 << " (not x86_EXCEPTION_STATE_COUNT)\n";
5238 struct MachO::x86_exception_state_t es;
5240 if (left >= sizeof(MachO::x86_exception_state_t)) {
5241 memcpy(&es, begin, sizeof(MachO::x86_exception_state_t));
5242 begin += sizeof(MachO::x86_exception_state_t);
5244 memset(&es, '\0', sizeof(MachO::x86_exception_state_t));
5245 memcpy(&es, begin, left);
5248 if (isLittleEndian != sys::IsLittleEndianHost)
5250 if (es.esh.flavor == MachO::x86_EXCEPTION_STATE64) {
5251 outs() << "\t esh.flavor x86_EXCEPTION_STATE64\n";
5252 if (es.esh.count == MachO::x86_EXCEPTION_STATE64_COUNT)
5253 outs() << "\t esh.count x86_EXCEPTION_STATE64_COUNT\n";
5255 outs() << "\t esh.count " << es.esh.count
5256 << " (not x86_EXCEPTION_STATE64_COUNT\n";
5257 Print_x86_exception_state_t(es.ues.es64);
5259 outs() << "\t esh.flavor " << es.esh.flavor << " esh.count "
5260 << es.esh.count << "\n";
5263 outs() << " flavor " << flavor << " (unknown)\n";
5264 outs() << " count " << count << "\n";
5265 outs() << " state (unknown)\n";
5266 begin += count * sizeof(uint32_t);
5270 while (begin < end) {
5271 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
5272 memcpy((char *)&flavor, begin, sizeof(uint32_t));
5273 begin += sizeof(uint32_t);
5278 if (isLittleEndian != sys::IsLittleEndianHost)
5279 sys::swapByteOrder(flavor);
5280 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
5281 memcpy((char *)&count, begin, sizeof(uint32_t));
5282 begin += sizeof(uint32_t);
5287 if (isLittleEndian != sys::IsLittleEndianHost)
5288 sys::swapByteOrder(count);
5289 outs() << " flavor " << flavor << "\n";
5290 outs() << " count " << count << "\n";
5291 outs() << " state (Unknown cputype/cpusubtype)\n";
5292 begin += count * sizeof(uint32_t);
5297 static void PrintDylibCommand(MachO::dylib_command dl, const char *Ptr) {
5298 if (dl.cmd == MachO::LC_ID_DYLIB)
5299 outs() << " cmd LC_ID_DYLIB\n";
5300 else if (dl.cmd == MachO::LC_LOAD_DYLIB)
5301 outs() << " cmd LC_LOAD_DYLIB\n";
5302 else if (dl.cmd == MachO::LC_LOAD_WEAK_DYLIB)
5303 outs() << " cmd LC_LOAD_WEAK_DYLIB\n";
5304 else if (dl.cmd == MachO::LC_REEXPORT_DYLIB)
5305 outs() << " cmd LC_REEXPORT_DYLIB\n";
5306 else if (dl.cmd == MachO::LC_LAZY_LOAD_DYLIB)
5307 outs() << " cmd LC_LAZY_LOAD_DYLIB\n";
5308 else if (dl.cmd == MachO::LC_LOAD_UPWARD_DYLIB)
5309 outs() << " cmd LC_LOAD_UPWARD_DYLIB\n";
5311 outs() << " cmd " << dl.cmd << " (unknown)\n";
5312 outs() << " cmdsize " << dl.cmdsize;
5313 if (dl.cmdsize < sizeof(struct MachO::dylib_command))
5314 outs() << " Incorrect size\n";
5317 if (dl.dylib.name < dl.cmdsize) {
5318 const char *P = (const char *)(Ptr) + dl.dylib.name;
5319 outs() << " name " << P << " (offset " << dl.dylib.name << ")\n";
5321 outs() << " name ?(bad offset " << dl.dylib.name << ")\n";
5323 outs() << " time stamp " << dl.dylib.timestamp << " ";
5324 time_t t = dl.dylib.timestamp;
5325 outs() << ctime(&t);
5326 outs() << " current version ";
5327 if (dl.dylib.current_version == 0xffffffff)
5330 outs() << ((dl.dylib.current_version >> 16) & 0xffff) << "."
5331 << ((dl.dylib.current_version >> 8) & 0xff) << "."
5332 << (dl.dylib.current_version & 0xff) << "\n";
5333 outs() << "compatibility version ";
5334 if (dl.dylib.compatibility_version == 0xffffffff)
5337 outs() << ((dl.dylib.compatibility_version >> 16) & 0xffff) << "."
5338 << ((dl.dylib.compatibility_version >> 8) & 0xff) << "."
5339 << (dl.dylib.compatibility_version & 0xff) << "\n";
5342 static void PrintLinkEditDataCommand(MachO::linkedit_data_command ld,
5343 uint32_t object_size) {
5344 if (ld.cmd == MachO::LC_CODE_SIGNATURE)
5345 outs() << " cmd LC_FUNCTION_STARTS\n";
5346 else if (ld.cmd == MachO::LC_SEGMENT_SPLIT_INFO)
5347 outs() << " cmd LC_SEGMENT_SPLIT_INFO\n";
5348 else if (ld.cmd == MachO::LC_FUNCTION_STARTS)
5349 outs() << " cmd LC_FUNCTION_STARTS\n";
5350 else if (ld.cmd == MachO::LC_DATA_IN_CODE)
5351 outs() << " cmd LC_DATA_IN_CODE\n";
5352 else if (ld.cmd == MachO::LC_DYLIB_CODE_SIGN_DRS)
5353 outs() << " cmd LC_DYLIB_CODE_SIGN_DRS\n";
5354 else if (ld.cmd == MachO::LC_LINKER_OPTIMIZATION_HINT)
5355 outs() << " cmd LC_LINKER_OPTIMIZATION_HINT\n";
5357 outs() << " cmd " << ld.cmd << " (?)\n";
5358 outs() << " cmdsize " << ld.cmdsize;
5359 if (ld.cmdsize != sizeof(struct MachO::linkedit_data_command))
5360 outs() << " Incorrect size\n";
5363 outs() << " dataoff " << ld.dataoff;
5364 if (ld.dataoff > object_size)
5365 outs() << " (past end of file)\n";
5368 outs() << " datasize " << ld.datasize;
5369 uint64_t big_size = ld.dataoff;
5370 big_size += ld.datasize;
5371 if (big_size > object_size)
5372 outs() << " (past end of file)\n";
5377 static void PrintLoadCommands(const MachOObjectFile *Obj, uint32_t ncmds,
5378 uint32_t filetype, uint32_t cputype,
5382 StringRef Buf = Obj->getData();
5383 MachOObjectFile::LoadCommandInfo Command = Obj->getFirstLoadCommandInfo();
5384 for (unsigned i = 0;; ++i) {
5385 outs() << "Load command " << i << "\n";
5386 if (Command.C.cmd == MachO::LC_SEGMENT) {
5387 MachO::segment_command SLC = Obj->getSegmentLoadCommand(Command);
5388 const char *sg_segname = SLC.segname;
5389 PrintSegmentCommand(SLC.cmd, SLC.cmdsize, SLC.segname, SLC.vmaddr,
5390 SLC.vmsize, SLC.fileoff, SLC.filesize, SLC.maxprot,
5391 SLC.initprot, SLC.nsects, SLC.flags, Buf.size(),
5393 for (unsigned j = 0; j < SLC.nsects; j++) {
5394 MachO::section S = Obj->getSection(Command, j);
5395 PrintSection(S.sectname, S.segname, S.addr, S.size, S.offset, S.align,
5396 S.reloff, S.nreloc, S.flags, S.reserved1, S.reserved2,
5397 SLC.cmd, sg_segname, filetype, Buf.size(), verbose);
5399 } else if (Command.C.cmd == MachO::LC_SEGMENT_64) {
5400 MachO::segment_command_64 SLC_64 = Obj->getSegment64LoadCommand(Command);
5401 const char *sg_segname = SLC_64.segname;
5402 PrintSegmentCommand(SLC_64.cmd, SLC_64.cmdsize, SLC_64.segname,
5403 SLC_64.vmaddr, SLC_64.vmsize, SLC_64.fileoff,
5404 SLC_64.filesize, SLC_64.maxprot, SLC_64.initprot,
5405 SLC_64.nsects, SLC_64.flags, Buf.size(), verbose);
5406 for (unsigned j = 0; j < SLC_64.nsects; j++) {
5407 MachO::section_64 S_64 = Obj->getSection64(Command, j);
5408 PrintSection(S_64.sectname, S_64.segname, S_64.addr, S_64.size,
5409 S_64.offset, S_64.align, S_64.reloff, S_64.nreloc,
5410 S_64.flags, S_64.reserved1, S_64.reserved2, SLC_64.cmd,
5411 sg_segname, filetype, Buf.size(), verbose);
5413 } else if (Command.C.cmd == MachO::LC_SYMTAB) {
5414 MachO::symtab_command Symtab = Obj->getSymtabLoadCommand();
5415 PrintSymtabLoadCommand(Symtab, Obj->is64Bit(), Buf.size());
5416 } else if (Command.C.cmd == MachO::LC_DYSYMTAB) {
5417 MachO::dysymtab_command Dysymtab = Obj->getDysymtabLoadCommand();
5418 MachO::symtab_command Symtab = Obj->getSymtabLoadCommand();
5419 PrintDysymtabLoadCommand(Dysymtab, Symtab.nsyms, Buf.size(),
5421 } else if (Command.C.cmd == MachO::LC_DYLD_INFO ||
5422 Command.C.cmd == MachO::LC_DYLD_INFO_ONLY) {
5423 MachO::dyld_info_command DyldInfo = Obj->getDyldInfoLoadCommand(Command);
5424 PrintDyldInfoLoadCommand(DyldInfo, Buf.size());
5425 } else if (Command.C.cmd == MachO::LC_LOAD_DYLINKER ||
5426 Command.C.cmd == MachO::LC_ID_DYLINKER ||
5427 Command.C.cmd == MachO::LC_DYLD_ENVIRONMENT) {
5428 MachO::dylinker_command Dyld = Obj->getDylinkerCommand(Command);
5429 PrintDyldLoadCommand(Dyld, Command.Ptr);
5430 } else if (Command.C.cmd == MachO::LC_UUID) {
5431 MachO::uuid_command Uuid = Obj->getUuidCommand(Command);
5432 PrintUuidLoadCommand(Uuid);
5433 } else if (Command.C.cmd == MachO::LC_RPATH) {
5434 MachO::rpath_command Rpath = Obj->getRpathCommand(Command);
5435 PrintRpathLoadCommand(Rpath, Command.Ptr);
5436 } else if (Command.C.cmd == MachO::LC_VERSION_MIN_MACOSX ||
5437 Command.C.cmd == MachO::LC_VERSION_MIN_IPHONEOS) {
5438 MachO::version_min_command Vd = Obj->getVersionMinLoadCommand(Command);
5439 PrintVersionMinLoadCommand(Vd);
5440 } else if (Command.C.cmd == MachO::LC_SOURCE_VERSION) {
5441 MachO::source_version_command Sd = Obj->getSourceVersionCommand(Command);
5442 PrintSourceVersionCommand(Sd);
5443 } else if (Command.C.cmd == MachO::LC_MAIN) {
5444 MachO::entry_point_command Ep = Obj->getEntryPointCommand(Command);
5445 PrintEntryPointCommand(Ep);
5446 } else if (Command.C.cmd == MachO::LC_ENCRYPTION_INFO) {
5447 MachO::encryption_info_command Ei =
5448 Obj->getEncryptionInfoCommand(Command);
5449 PrintEncryptionInfoCommand(Ei, Buf.size());
5450 } else if (Command.C.cmd == MachO::LC_ENCRYPTION_INFO_64) {
5451 MachO::encryption_info_command_64 Ei =
5452 Obj->getEncryptionInfoCommand64(Command);
5453 PrintEncryptionInfoCommand64(Ei, Buf.size());
5454 } else if (Command.C.cmd == MachO::LC_LINKER_OPTION) {
5455 MachO::linker_option_command Lo =
5456 Obj->getLinkerOptionLoadCommand(Command);
5457 PrintLinkerOptionCommand(Lo, Command.Ptr);
5458 } else if (Command.C.cmd == MachO::LC_SUB_FRAMEWORK) {
5459 MachO::sub_framework_command Sf = Obj->getSubFrameworkCommand(Command);
5460 PrintSubFrameworkCommand(Sf, Command.Ptr);
5461 } else if (Command.C.cmd == MachO::LC_SUB_UMBRELLA) {
5462 MachO::sub_umbrella_command Sf = Obj->getSubUmbrellaCommand(Command);
5463 PrintSubUmbrellaCommand(Sf, Command.Ptr);
5464 } else if (Command.C.cmd == MachO::LC_SUB_LIBRARY) {
5465 MachO::sub_library_command Sl = Obj->getSubLibraryCommand(Command);
5466 PrintSubLibraryCommand(Sl, Command.Ptr);
5467 } else if (Command.C.cmd == MachO::LC_SUB_CLIENT) {
5468 MachO::sub_client_command Sc = Obj->getSubClientCommand(Command);
5469 PrintSubClientCommand(Sc, Command.Ptr);
5470 } else if (Command.C.cmd == MachO::LC_ROUTINES) {
5471 MachO::routines_command Rc = Obj->getRoutinesCommand(Command);
5472 PrintRoutinesCommand(Rc);
5473 } else if (Command.C.cmd == MachO::LC_ROUTINES_64) {
5474 MachO::routines_command_64 Rc = Obj->getRoutinesCommand64(Command);
5475 PrintRoutinesCommand64(Rc);
5476 } else if (Command.C.cmd == MachO::LC_THREAD ||
5477 Command.C.cmd == MachO::LC_UNIXTHREAD) {
5478 MachO::thread_command Tc = Obj->getThreadCommand(Command);
5479 PrintThreadCommand(Tc, Command.Ptr, Obj->isLittleEndian(), cputype);
5480 } else if (Command.C.cmd == MachO::LC_LOAD_DYLIB ||
5481 Command.C.cmd == MachO::LC_ID_DYLIB ||
5482 Command.C.cmd == MachO::LC_LOAD_WEAK_DYLIB ||
5483 Command.C.cmd == MachO::LC_REEXPORT_DYLIB ||
5484 Command.C.cmd == MachO::LC_LAZY_LOAD_DYLIB ||
5485 Command.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB) {
5486 MachO::dylib_command Dl = Obj->getDylibIDLoadCommand(Command);
5487 PrintDylibCommand(Dl, Command.Ptr);
5488 } else if (Command.C.cmd == MachO::LC_CODE_SIGNATURE ||
5489 Command.C.cmd == MachO::LC_SEGMENT_SPLIT_INFO ||
5490 Command.C.cmd == MachO::LC_FUNCTION_STARTS ||
5491 Command.C.cmd == MachO::LC_DATA_IN_CODE ||
5492 Command.C.cmd == MachO::LC_DYLIB_CODE_SIGN_DRS ||
5493 Command.C.cmd == MachO::LC_LINKER_OPTIMIZATION_HINT) {
5494 MachO::linkedit_data_command Ld =
5495 Obj->getLinkeditDataLoadCommand(Command);
5496 PrintLinkEditDataCommand(Ld, Buf.size());
5498 outs() << " cmd ?(" << format("0x%08" PRIx32, Command.C.cmd)
5500 outs() << " cmdsize " << Command.C.cmdsize << "\n";
5501 // TODO: get and print the raw bytes of the load command.
5503 // TODO: print all the other kinds of load commands.
5507 Command = Obj->getNextLoadCommandInfo(Command);
5511 static void getAndPrintMachHeader(const MachOObjectFile *Obj, uint32_t &ncmds,
5512 uint32_t &filetype, uint32_t &cputype,
5514 if (Obj->is64Bit()) {
5515 MachO::mach_header_64 H_64;
5516 H_64 = Obj->getHeader64();
5517 PrintMachHeader(H_64.magic, H_64.cputype, H_64.cpusubtype, H_64.filetype,
5518 H_64.ncmds, H_64.sizeofcmds, H_64.flags, verbose);
5520 filetype = H_64.filetype;
5521 cputype = H_64.cputype;
5523 MachO::mach_header H;
5524 H = Obj->getHeader();
5525 PrintMachHeader(H.magic, H.cputype, H.cpusubtype, H.filetype, H.ncmds,
5526 H.sizeofcmds, H.flags, verbose);
5528 filetype = H.filetype;
5529 cputype = H.cputype;
5533 void llvm::printMachOFileHeader(const object::ObjectFile *Obj) {
5534 const MachOObjectFile *file = dyn_cast<const MachOObjectFile>(Obj);
5536 uint32_t filetype = 0;
5537 uint32_t cputype = 0;
5538 getAndPrintMachHeader(file, ncmds, filetype, cputype, !NonVerbose);
5539 PrintLoadCommands(file, ncmds, filetype, cputype, !NonVerbose);
5542 //===----------------------------------------------------------------------===//
5543 // export trie dumping
5544 //===----------------------------------------------------------------------===//
5546 void llvm::printMachOExportsTrie(const object::MachOObjectFile *Obj) {
5547 for (const llvm::object::ExportEntry &Entry : Obj->exports()) {
5548 uint64_t Flags = Entry.flags();
5549 bool ReExport = (Flags & MachO::EXPORT_SYMBOL_FLAGS_REEXPORT);
5550 bool WeakDef = (Flags & MachO::EXPORT_SYMBOL_FLAGS_WEAK_DEFINITION);
5551 bool ThreadLocal = ((Flags & MachO::EXPORT_SYMBOL_FLAGS_KIND_MASK) ==
5552 MachO::EXPORT_SYMBOL_FLAGS_KIND_THREAD_LOCAL);
5553 bool Abs = ((Flags & MachO::EXPORT_SYMBOL_FLAGS_KIND_MASK) ==
5554 MachO::EXPORT_SYMBOL_FLAGS_KIND_ABSOLUTE);
5555 bool Resolver = (Flags & MachO::EXPORT_SYMBOL_FLAGS_STUB_AND_RESOLVER);
5557 outs() << "[re-export] ";
5559 outs() << format("0x%08llX ",
5560 Entry.address()); // FIXME:add in base address
5561 outs() << Entry.name();
5562 if (WeakDef || ThreadLocal || Resolver || Abs) {
5563 bool NeedsComma = false;
5566 outs() << "weak_def";
5572 outs() << "per-thread";
5578 outs() << "absolute";
5584 outs() << format("resolver=0x%08llX", Entry.other());
5590 StringRef DylibName = "unknown";
5591 int Ordinal = Entry.other() - 1;
5592 Obj->getLibraryShortNameByIndex(Ordinal, DylibName);
5593 if (Entry.otherName().empty())
5594 outs() << " (from " << DylibName << ")";
5596 outs() << " (" << Entry.otherName() << " from " << DylibName << ")";
5602 //===----------------------------------------------------------------------===//
5603 // rebase table dumping
5604 //===----------------------------------------------------------------------===//
5609 SegInfo(const object::MachOObjectFile *Obj);
5611 StringRef segmentName(uint32_t SegIndex);
5612 StringRef sectionName(uint32_t SegIndex, uint64_t SegOffset);
5613 uint64_t address(uint32_t SegIndex, uint64_t SegOffset);
5616 struct SectionInfo {
5619 StringRef SectionName;
5620 StringRef SegmentName;
5621 uint64_t OffsetInSegment;
5622 uint64_t SegmentStartAddress;
5623 uint32_t SegmentIndex;
5625 const SectionInfo &findSection(uint32_t SegIndex, uint64_t SegOffset);
5626 SmallVector<SectionInfo, 32> Sections;
5630 SegInfo::SegInfo(const object::MachOObjectFile *Obj) {
5631 // Build table of sections so segIndex/offset pairs can be translated.
5632 uint32_t CurSegIndex = Obj->hasPageZeroSegment() ? 1 : 0;
5633 StringRef CurSegName;
5634 uint64_t CurSegAddress;
5635 for (const SectionRef &Section : Obj->sections()) {
5637 if (error(Section.getName(Info.SectionName)))
5639 Info.Address = Section.getAddress();
5640 Info.Size = Section.getSize();
5642 Obj->getSectionFinalSegmentName(Section.getRawDataRefImpl());
5643 if (!Info.SegmentName.equals(CurSegName)) {
5645 CurSegName = Info.SegmentName;
5646 CurSegAddress = Info.Address;
5648 Info.SegmentIndex = CurSegIndex - 1;
5649 Info.OffsetInSegment = Info.Address - CurSegAddress;
5650 Info.SegmentStartAddress = CurSegAddress;
5651 Sections.push_back(Info);
5655 StringRef SegInfo::segmentName(uint32_t SegIndex) {
5656 for (const SectionInfo &SI : Sections) {
5657 if (SI.SegmentIndex == SegIndex)
5658 return SI.SegmentName;
5660 llvm_unreachable("invalid segIndex");
5663 const SegInfo::SectionInfo &SegInfo::findSection(uint32_t SegIndex,
5664 uint64_t OffsetInSeg) {
5665 for (const SectionInfo &SI : Sections) {
5666 if (SI.SegmentIndex != SegIndex)
5668 if (SI.OffsetInSegment > OffsetInSeg)
5670 if (OffsetInSeg >= (SI.OffsetInSegment + SI.Size))
5674 llvm_unreachable("segIndex and offset not in any section");
5677 StringRef SegInfo::sectionName(uint32_t SegIndex, uint64_t OffsetInSeg) {
5678 return findSection(SegIndex, OffsetInSeg).SectionName;
5681 uint64_t SegInfo::address(uint32_t SegIndex, uint64_t OffsetInSeg) {
5682 const SectionInfo &SI = findSection(SegIndex, OffsetInSeg);
5683 return SI.SegmentStartAddress + OffsetInSeg;
5686 void llvm::printMachORebaseTable(const object::MachOObjectFile *Obj) {
5687 // Build table of sections so names can used in final output.
5688 SegInfo sectionTable(Obj);
5690 outs() << "segment section address type\n";
5691 for (const llvm::object::MachORebaseEntry &Entry : Obj->rebaseTable()) {
5692 uint32_t SegIndex = Entry.segmentIndex();
5693 uint64_t OffsetInSeg = Entry.segmentOffset();
5694 StringRef SegmentName = sectionTable.segmentName(SegIndex);
5695 StringRef SectionName = sectionTable.sectionName(SegIndex, OffsetInSeg);
5696 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
5698 // Table lines look like: __DATA __nl_symbol_ptr 0x0000F00C pointer
5699 outs() << format("%-8s %-18s 0x%08" PRIX64 " %s\n",
5700 SegmentName.str().c_str(), SectionName.str().c_str(),
5701 Address, Entry.typeName().str().c_str());
5705 static StringRef ordinalName(const object::MachOObjectFile *Obj, int Ordinal) {
5706 StringRef DylibName;
5708 case MachO::BIND_SPECIAL_DYLIB_SELF:
5709 return "this-image";
5710 case MachO::BIND_SPECIAL_DYLIB_MAIN_EXECUTABLE:
5711 return "main-executable";
5712 case MachO::BIND_SPECIAL_DYLIB_FLAT_LOOKUP:
5713 return "flat-namespace";
5716 std::error_code EC =
5717 Obj->getLibraryShortNameByIndex(Ordinal - 1, DylibName);
5719 return "<<bad library ordinal>>";
5723 return "<<unknown special ordinal>>";
5726 //===----------------------------------------------------------------------===//
5727 // bind table dumping
5728 //===----------------------------------------------------------------------===//
5730 void llvm::printMachOBindTable(const object::MachOObjectFile *Obj) {
5731 // Build table of sections so names can used in final output.
5732 SegInfo sectionTable(Obj);
5734 outs() << "segment section address type "
5735 "addend dylib symbol\n";
5736 for (const llvm::object::MachOBindEntry &Entry : Obj->bindTable()) {
5737 uint32_t SegIndex = Entry.segmentIndex();
5738 uint64_t OffsetInSeg = Entry.segmentOffset();
5739 StringRef SegmentName = sectionTable.segmentName(SegIndex);
5740 StringRef SectionName = sectionTable.sectionName(SegIndex, OffsetInSeg);
5741 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
5743 // Table lines look like:
5744 // __DATA __got 0x00012010 pointer 0 libSystem ___stack_chk_guard
5746 if (Entry.flags() & MachO::BIND_SYMBOL_FLAGS_WEAK_IMPORT)
5747 Attr = " (weak_import)";
5748 outs() << left_justify(SegmentName, 8) << " "
5749 << left_justify(SectionName, 18) << " "
5750 << format_hex(Address, 10, true) << " "
5751 << left_justify(Entry.typeName(), 8) << " "
5752 << format_decimal(Entry.addend(), 8) << " "
5753 << left_justify(ordinalName(Obj, Entry.ordinal()), 16) << " "
5754 << Entry.symbolName() << Attr << "\n";
5758 //===----------------------------------------------------------------------===//
5759 // lazy bind table dumping
5760 //===----------------------------------------------------------------------===//
5762 void llvm::printMachOLazyBindTable(const object::MachOObjectFile *Obj) {
5763 // Build table of sections so names can used in final output.
5764 SegInfo sectionTable(Obj);
5766 outs() << "segment section address "
5768 for (const llvm::object::MachOBindEntry &Entry : Obj->lazyBindTable()) {
5769 uint32_t SegIndex = Entry.segmentIndex();
5770 uint64_t OffsetInSeg = Entry.segmentOffset();
5771 StringRef SegmentName = sectionTable.segmentName(SegIndex);
5772 StringRef SectionName = sectionTable.sectionName(SegIndex, OffsetInSeg);
5773 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
5775 // Table lines look like:
5776 // __DATA __got 0x00012010 libSystem ___stack_chk_guard
5777 outs() << left_justify(SegmentName, 8) << " "
5778 << left_justify(SectionName, 18) << " "
5779 << format_hex(Address, 10, true) << " "
5780 << left_justify(ordinalName(Obj, Entry.ordinal()), 16) << " "
5781 << Entry.symbolName() << "\n";
5785 //===----------------------------------------------------------------------===//
5786 // weak bind table dumping
5787 //===----------------------------------------------------------------------===//
5789 void llvm::printMachOWeakBindTable(const object::MachOObjectFile *Obj) {
5790 // Build table of sections so names can used in final output.
5791 SegInfo sectionTable(Obj);
5793 outs() << "segment section address "
5794 "type addend symbol\n";
5795 for (const llvm::object::MachOBindEntry &Entry : Obj->weakBindTable()) {
5796 // Strong symbols don't have a location to update.
5797 if (Entry.flags() & MachO::BIND_SYMBOL_FLAGS_NON_WEAK_DEFINITION) {
5798 outs() << " strong "
5799 << Entry.symbolName() << "\n";
5802 uint32_t SegIndex = Entry.segmentIndex();
5803 uint64_t OffsetInSeg = Entry.segmentOffset();
5804 StringRef SegmentName = sectionTable.segmentName(SegIndex);
5805 StringRef SectionName = sectionTable.sectionName(SegIndex, OffsetInSeg);
5806 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
5808 // Table lines look like:
5809 // __DATA __data 0x00001000 pointer 0 _foo
5810 outs() << left_justify(SegmentName, 8) << " "
5811 << left_justify(SectionName, 18) << " "
5812 << format_hex(Address, 10, true) << " "
5813 << left_justify(Entry.typeName(), 8) << " "
5814 << format_decimal(Entry.addend(), 8) << " " << Entry.symbolName()
5819 // get_dyld_bind_info_symbolname() is used for disassembly and passed an
5820 // address, ReferenceValue, in the Mach-O file and looks in the dyld bind
5821 // information for that address. If the address is found its binding symbol
5822 // name is returned. If not nullptr is returned.
5823 static const char *get_dyld_bind_info_symbolname(uint64_t ReferenceValue,
5824 struct DisassembleInfo *info) {
5825 if (info->bindtable == nullptr) {
5826 info->bindtable = new (BindTable);
5827 SegInfo sectionTable(info->O);
5828 for (const llvm::object::MachOBindEntry &Entry : info->O->bindTable()) {
5829 uint32_t SegIndex = Entry.segmentIndex();
5830 uint64_t OffsetInSeg = Entry.segmentOffset();
5831 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
5832 const char *SymbolName = nullptr;
5833 StringRef name = Entry.symbolName();
5835 SymbolName = name.data();
5836 info->bindtable->push_back(std::make_pair(Address, SymbolName));
5839 for (bind_table_iterator BI = info->bindtable->begin(),
5840 BE = info->bindtable->end();
5842 uint64_t Address = BI->first;
5843 if (ReferenceValue == Address) {
5844 const char *SymbolName = BI->second;