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/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/MachO.h"
40 #include "llvm/Support/MemoryBuffer.h"
41 #include "llvm/Support/TargetRegistry.h"
42 #include "llvm/Support/TargetSelect.h"
43 #include "llvm/Support/raw_ostream.h"
46 #include <system_error>
53 using namespace object;
57 cl::desc("Print line information from debug info if available"));
59 static cl::opt<std::string> DSYMFile("dsym",
60 cl::desc("Use .dSYM file for debug info"));
62 static cl::opt<bool> FullLeadingAddr("full-leading-addr",
63 cl::desc("Print full leading address"));
66 PrintImmHex("print-imm-hex",
67 cl::desc("Use hex format for immediate values"));
69 cl::opt<bool> llvm::UniversalHeaders("universal-headers",
70 cl::desc("Print Mach-O universal headers "
71 "(requires -macho)"));
74 llvm::ArchiveHeaders("archive-headers",
75 cl::desc("Print archive headers for Mach-O archives "
76 "(requires -macho)"));
78 static cl::list<std::string>
79 ArchFlags("arch", cl::desc("architecture(s) from a Mach-O file to dump"),
83 static std::string ThumbTripleName;
85 static const Target *GetTarget(const MachOObjectFile *MachOObj,
86 const char **McpuDefault,
87 const Target **ThumbTarget) {
88 // Figure out the target triple.
89 if (TripleName.empty()) {
90 llvm::Triple TT("unknown-unknown-unknown");
91 llvm::Triple ThumbTriple = Triple();
92 TT = MachOObj->getArch(McpuDefault, &ThumbTriple);
93 TripleName = TT.str();
94 ThumbTripleName = ThumbTriple.str();
97 // Get the target specific parser.
99 const Target *TheTarget = TargetRegistry::lookupTarget(TripleName, Error);
100 if (TheTarget && ThumbTripleName.empty())
103 *ThumbTarget = TargetRegistry::lookupTarget(ThumbTripleName, Error);
107 errs() << "llvm-objdump: error: unable to get target for '";
109 errs() << TripleName;
111 errs() << ThumbTripleName;
112 errs() << "', see --version and --triple.\n";
116 struct SymbolSorter {
117 bool operator()(const SymbolRef &A, const SymbolRef &B) {
118 SymbolRef::Type AType, BType;
122 uint64_t AAddr, BAddr;
123 if (AType != SymbolRef::ST_Function)
127 if (BType != SymbolRef::ST_Function)
131 return AAddr < BAddr;
135 // Types for the storted data in code table that is built before disassembly
136 // and the predicate function to sort them.
137 typedef std::pair<uint64_t, DiceRef> DiceTableEntry;
138 typedef std::vector<DiceTableEntry> DiceTable;
139 typedef DiceTable::iterator dice_table_iterator;
141 // This is used to search for a data in code table entry for the PC being
142 // disassembled. The j parameter has the PC in j.first. A single data in code
143 // table entry can cover many bytes for each of its Kind's. So if the offset,
144 // aka the i.first value, of the data in code table entry plus its Length
145 // covers the PC being searched for this will return true. If not it will
147 static bool compareDiceTableEntries(const DiceTableEntry &i,
148 const DiceTableEntry &j) {
150 i.second.getLength(Length);
152 return j.first >= i.first && j.first < i.first + Length;
155 static uint64_t DumpDataInCode(const char *bytes, uint64_t Length,
156 unsigned short Kind) {
157 uint32_t Value, Size = 1;
161 case MachO::DICE_KIND_DATA:
164 DumpBytes(StringRef(bytes, 4));
165 Value = bytes[3] << 24 | bytes[2] << 16 | bytes[1] << 8 | bytes[0];
166 outs() << "\t.long " << Value;
168 } else if (Length >= 2) {
170 DumpBytes(StringRef(bytes, 2));
171 Value = bytes[1] << 8 | bytes[0];
172 outs() << "\t.short " << Value;
176 DumpBytes(StringRef(bytes, 2));
178 outs() << "\t.byte " << Value;
181 if (Kind == MachO::DICE_KIND_DATA)
182 outs() << "\t@ KIND_DATA\n";
184 outs() << "\t@ data in code kind = " << Kind << "\n";
186 case MachO::DICE_KIND_JUMP_TABLE8:
188 DumpBytes(StringRef(bytes, 1));
190 outs() << "\t.byte " << format("%3u", Value) << "\t@ KIND_JUMP_TABLE8\n";
193 case MachO::DICE_KIND_JUMP_TABLE16:
195 DumpBytes(StringRef(bytes, 2));
196 Value = bytes[1] << 8 | bytes[0];
197 outs() << "\t.short " << format("%5u", Value & 0xffff)
198 << "\t@ KIND_JUMP_TABLE16\n";
201 case MachO::DICE_KIND_JUMP_TABLE32:
202 case MachO::DICE_KIND_ABS_JUMP_TABLE32:
204 DumpBytes(StringRef(bytes, 4));
205 Value = bytes[3] << 24 | bytes[2] << 16 | bytes[1] << 8 | bytes[0];
206 outs() << "\t.long " << Value;
207 if (Kind == MachO::DICE_KIND_JUMP_TABLE32)
208 outs() << "\t@ KIND_JUMP_TABLE32\n";
210 outs() << "\t@ KIND_ABS_JUMP_TABLE32\n";
217 static void getSectionsAndSymbols(const MachO::mach_header Header,
218 MachOObjectFile *MachOObj,
219 std::vector<SectionRef> &Sections,
220 std::vector<SymbolRef> &Symbols,
221 SmallVectorImpl<uint64_t> &FoundFns,
222 uint64_t &BaseSegmentAddress) {
223 for (const SymbolRef &Symbol : MachOObj->symbols()) {
225 Symbol.getName(SymName);
226 if (!SymName.startswith("ltmp"))
227 Symbols.push_back(Symbol);
230 for (const SectionRef &Section : MachOObj->sections()) {
232 Section.getName(SectName);
233 Sections.push_back(Section);
236 MachOObjectFile::LoadCommandInfo Command =
237 MachOObj->getFirstLoadCommandInfo();
238 bool BaseSegmentAddressSet = false;
239 for (unsigned i = 0;; ++i) {
240 if (Command.C.cmd == MachO::LC_FUNCTION_STARTS) {
241 // We found a function starts segment, parse the addresses for later
243 MachO::linkedit_data_command LLC =
244 MachOObj->getLinkeditDataLoadCommand(Command);
246 MachOObj->ReadULEB128s(LLC.dataoff, FoundFns);
247 } else if (Command.C.cmd == MachO::LC_SEGMENT) {
248 MachO::segment_command SLC = MachOObj->getSegmentLoadCommand(Command);
249 StringRef SegName = SLC.segname;
250 if (!BaseSegmentAddressSet && SegName != "__PAGEZERO") {
251 BaseSegmentAddressSet = true;
252 BaseSegmentAddress = SLC.vmaddr;
256 if (i == Header.ncmds - 1)
259 Command = MachOObj->getNextLoadCommandInfo(Command);
263 // checkMachOAndArchFlags() checks to see if the ObjectFile is a Mach-O file
264 // and if it is and there is a list of architecture flags is specified then
265 // check to make sure this Mach-O file is one of those architectures or all
266 // architectures were specified. If not then an error is generated and this
267 // routine returns false. Else it returns true.
268 static bool checkMachOAndArchFlags(ObjectFile *O, StringRef Filename) {
269 if (isa<MachOObjectFile>(O) && !ArchAll && ArchFlags.size() != 0) {
270 MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(O);
271 bool ArchFound = false;
272 MachO::mach_header H;
273 MachO::mach_header_64 H_64;
275 if (MachO->is64Bit()) {
276 H_64 = MachO->MachOObjectFile::getHeader64();
277 T = MachOObjectFile::getArch(H_64.cputype, H_64.cpusubtype);
279 H = MachO->MachOObjectFile::getHeader();
280 T = MachOObjectFile::getArch(H.cputype, H.cpusubtype);
283 for (i = 0; i < ArchFlags.size(); ++i) {
284 if (ArchFlags[i] == T.getArchName())
289 errs() << "llvm-objdump: file: " + Filename + " does not contain "
290 << "architecture: " + ArchFlags[i] + "\n";
297 static void DisassembleMachO(StringRef Filename, MachOObjectFile *MachOOF);
299 // ProcessMachO() is passed a single opened Mach-O file, which may be an
300 // archive member and or in a slice of a universal file. It prints the
301 // the file name and header info and then processes it according to the
302 // command line options.
303 static void ProcessMachO(StringRef Filename, MachOObjectFile *MachOOF,
304 StringRef ArchiveMemberName = StringRef(),
305 StringRef ArchitectureName = StringRef()) {
306 // If we are doing some processing here on the Mach-O file print the header
307 // info. And don't print it otherwise like in the case of printing the
309 if (Disassemble || PrivateHeaders || ExportsTrie || Rebase || Bind ||
310 LazyBind || WeakBind) {
312 if (!ArchiveMemberName.empty())
313 outs() << '(' << ArchiveMemberName << ')';
314 if (!ArchitectureName.empty())
315 outs() << " (architecture " << ArchitectureName << ")";
320 DisassembleMachO(Filename, MachOOF);
321 // TODO: These should/could be printed in Darwin's otool(1) or nm(1) style
322 // for -macho. Or just used a new option that maps to the otool(1)
323 // option like -r, -l, etc. Or just the normal llvm-objdump option
324 // but now for this slice so that the -arch options can be used.
326 // PrintRelocations(MachOOF);
327 // if (SectionHeaders)
328 // PrintSectionHeaders(MachOOF);
329 // if (SectionContents)
330 // PrintSectionContents(MachOOF);
332 // PrintSymbolTable(MachOOF);
334 // PrintUnwindInfo(MachOOF);
336 printMachOFileHeader(MachOOF);
338 printExportsTrie(MachOOF);
340 printRebaseTable(MachOOF);
342 printBindTable(MachOOF);
344 printLazyBindTable(MachOOF);
346 printWeakBindTable(MachOOF);
349 // printUnknownCPUType() helps print_fat_headers for unknown CPU's.
350 static void printUnknownCPUType(uint32_t cputype, uint32_t cpusubtype) {
351 outs() << " cputype (" << cputype << ")\n";
352 outs() << " cpusubtype (" << cpusubtype << ")\n";
355 // printCPUType() helps print_fat_headers by printing the cputype and
356 // pusubtype (symbolically for the one's it knows about).
357 static void printCPUType(uint32_t cputype, uint32_t cpusubtype) {
359 case MachO::CPU_TYPE_I386:
360 switch (cpusubtype) {
361 case MachO::CPU_SUBTYPE_I386_ALL:
362 outs() << " cputype CPU_TYPE_I386\n";
363 outs() << " cpusubtype CPU_SUBTYPE_I386_ALL\n";
366 printUnknownCPUType(cputype, cpusubtype);
370 case MachO::CPU_TYPE_X86_64:
371 switch (cpusubtype) {
372 case MachO::CPU_SUBTYPE_X86_64_ALL:
373 outs() << " cputype CPU_TYPE_X86_64\n";
374 outs() << " cpusubtype CPU_SUBTYPE_X86_64_ALL\n";
376 case MachO::CPU_SUBTYPE_X86_64_H:
377 outs() << " cputype CPU_TYPE_X86_64\n";
378 outs() << " cpusubtype CPU_SUBTYPE_X86_64_H\n";
381 printUnknownCPUType(cputype, cpusubtype);
385 case MachO::CPU_TYPE_ARM:
386 switch (cpusubtype) {
387 case MachO::CPU_SUBTYPE_ARM_ALL:
388 outs() << " cputype CPU_TYPE_ARM\n";
389 outs() << " cpusubtype CPU_SUBTYPE_ARM_ALL\n";
391 case MachO::CPU_SUBTYPE_ARM_V4T:
392 outs() << " cputype CPU_TYPE_ARM\n";
393 outs() << " cpusubtype CPU_SUBTYPE_ARM_V4T\n";
395 case MachO::CPU_SUBTYPE_ARM_V5TEJ:
396 outs() << " cputype CPU_TYPE_ARM\n";
397 outs() << " cpusubtype CPU_SUBTYPE_ARM_V5TEJ\n";
399 case MachO::CPU_SUBTYPE_ARM_XSCALE:
400 outs() << " cputype CPU_TYPE_ARM\n";
401 outs() << " cpusubtype CPU_SUBTYPE_ARM_XSCALE\n";
403 case MachO::CPU_SUBTYPE_ARM_V6:
404 outs() << " cputype CPU_TYPE_ARM\n";
405 outs() << " cpusubtype CPU_SUBTYPE_ARM_V6\n";
407 case MachO::CPU_SUBTYPE_ARM_V6M:
408 outs() << " cputype CPU_TYPE_ARM\n";
409 outs() << " cpusubtype CPU_SUBTYPE_ARM_V6M\n";
411 case MachO::CPU_SUBTYPE_ARM_V7:
412 outs() << " cputype CPU_TYPE_ARM\n";
413 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7\n";
415 case MachO::CPU_SUBTYPE_ARM_V7EM:
416 outs() << " cputype CPU_TYPE_ARM\n";
417 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7EM\n";
419 case MachO::CPU_SUBTYPE_ARM_V7K:
420 outs() << " cputype CPU_TYPE_ARM\n";
421 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7K\n";
423 case MachO::CPU_SUBTYPE_ARM_V7M:
424 outs() << " cputype CPU_TYPE_ARM\n";
425 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7M\n";
427 case MachO::CPU_SUBTYPE_ARM_V7S:
428 outs() << " cputype CPU_TYPE_ARM\n";
429 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7S\n";
432 printUnknownCPUType(cputype, cpusubtype);
436 case MachO::CPU_TYPE_ARM64:
437 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
438 case MachO::CPU_SUBTYPE_ARM64_ALL:
439 outs() << " cputype CPU_TYPE_ARM64\n";
440 outs() << " cpusubtype CPU_SUBTYPE_ARM64_ALL\n";
443 printUnknownCPUType(cputype, cpusubtype);
448 printUnknownCPUType(cputype, cpusubtype);
453 static void printMachOUniversalHeaders(const object::MachOUniversalBinary *UB,
455 outs() << "Fat headers\n";
457 outs() << "fat_magic FAT_MAGIC\n";
459 outs() << "fat_magic " << format("0x%" PRIx32, MachO::FAT_MAGIC) << "\n";
461 uint32_t nfat_arch = UB->getNumberOfObjects();
462 StringRef Buf = UB->getData();
463 uint64_t size = Buf.size();
464 uint64_t big_size = sizeof(struct MachO::fat_header) +
465 nfat_arch * sizeof(struct MachO::fat_arch);
466 outs() << "nfat_arch " << UB->getNumberOfObjects();
468 outs() << " (malformed, contains zero architecture types)\n";
469 else if (big_size > size)
470 outs() << " (malformed, architectures past end of file)\n";
474 for (uint32_t i = 0; i < nfat_arch; ++i) {
475 MachOUniversalBinary::ObjectForArch OFA(UB, i);
476 uint32_t cputype = OFA.getCPUType();
477 uint32_t cpusubtype = OFA.getCPUSubType();
478 outs() << "architecture ";
479 for (uint32_t j = 0; i != 0 && j <= i - 1; j++) {
480 MachOUniversalBinary::ObjectForArch other_OFA(UB, j);
481 uint32_t other_cputype = other_OFA.getCPUType();
482 uint32_t other_cpusubtype = other_OFA.getCPUSubType();
483 if (cputype != 0 && cpusubtype != 0 && cputype == other_cputype &&
484 (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) ==
485 (other_cpusubtype & ~MachO::CPU_SUBTYPE_MASK)) {
486 outs() << "(illegal duplicate architecture) ";
491 outs() << OFA.getArchTypeName() << "\n";
492 printCPUType(cputype, cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
495 outs() << " cputype " << cputype << "\n";
496 outs() << " cpusubtype " << (cpusubtype & ~MachO::CPU_SUBTYPE_MASK)
500 (cpusubtype & MachO::CPU_SUBTYPE_MASK) == MachO::CPU_SUBTYPE_LIB64)
501 outs() << " capabilities CPU_SUBTYPE_LIB64\n";
503 outs() << " capabilities "
504 << format("0x%" PRIx32,
505 (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24) << "\n";
506 outs() << " offset " << OFA.getOffset();
507 if (OFA.getOffset() > size)
508 outs() << " (past end of file)";
509 if (OFA.getOffset() % (1 << OFA.getAlign()) != 0)
510 outs() << " (not aligned on it's alignment (2^" << OFA.getAlign() << ")";
512 outs() << " size " << OFA.getSize();
513 big_size = OFA.getOffset() + OFA.getSize();
515 outs() << " (past end of file)";
517 outs() << " align 2^" << OFA.getAlign() << " (" << (1 << OFA.getAlign())
522 static void printArchiveChild(Archive::Child &C, bool verbose,
525 outs() << C.getChildOffset() << "\t";
526 sys::fs::perms Mode = C.getAccessMode();
528 // FIXME: this first dash, "-", is for (Mode & S_IFMT) == S_IFREG.
529 // But there is nothing in sys::fs::perms for S_IFMT or S_IFREG.
531 if (Mode & sys::fs::owner_read)
535 if (Mode & sys::fs::owner_write)
539 if (Mode & sys::fs::owner_exe)
543 if (Mode & sys::fs::group_read)
547 if (Mode & sys::fs::group_write)
551 if (Mode & sys::fs::group_exe)
555 if (Mode & sys::fs::others_read)
559 if (Mode & sys::fs::others_write)
563 if (Mode & sys::fs::others_exe)
568 outs() << format("0%o ", Mode);
571 unsigned UID = C.getUID();
572 outs() << format("%3d/", UID);
573 unsigned GID = C.getGID();
574 outs() << format("%-3d ", GID);
575 uint64_t Size = C.getRawSize() - sizeof(object::ArchiveMemberHeader);
576 outs() << format("%5d ", Size);
578 StringRef RawLastModified = C.getRawLastModified();
581 if (RawLastModified.getAsInteger(10, Seconds))
582 outs() << "(date: \"%s\" contains non-decimal chars) " << RawLastModified;
584 // Since cime(3) returns a 26 character string of the form:
585 // "Sun Sep 16 01:03:52 1973\n\0"
586 // just print 24 characters.
588 outs() << format("%.24s ", ctime(&t));
591 outs() << RawLastModified << " ";
595 ErrorOr<StringRef> NameOrErr = C.getName();
596 if (NameOrErr.getError()) {
597 StringRef RawName = C.getRawName();
598 outs() << RawName << "\n";
600 StringRef Name = NameOrErr.get();
601 outs() << Name << "\n";
604 StringRef RawName = C.getRawName();
605 outs() << RawName << "\n";
609 static void printArchiveHeaders(Archive *A, bool verbose, bool print_offset) {
610 if (A->hasSymbolTable()) {
611 Archive::child_iterator S = A->getSymbolTableChild();
612 Archive::Child C = *S;
613 printArchiveChild(C, verbose, print_offset);
615 for (Archive::child_iterator I = A->child_begin(), E = A->child_end(); I != E;
617 Archive::Child C = *I;
618 printArchiveChild(C, verbose, print_offset);
622 // ParseInputMachO() parses the named Mach-O file in Filename and handles the
623 // -arch flags selecting just those slices as specified by them and also parses
624 // archive files. Then for each individual Mach-O file ProcessMachO() is
625 // called to process the file based on the command line options.
626 void llvm::ParseInputMachO(StringRef Filename) {
627 // Check for -arch all and verifiy the -arch flags are valid.
628 for (unsigned i = 0; i < ArchFlags.size(); ++i) {
629 if (ArchFlags[i] == "all") {
632 if (!MachOObjectFile::isValidArch(ArchFlags[i])) {
633 errs() << "llvm-objdump: Unknown architecture named '" + ArchFlags[i] +
634 "'for the -arch option\n";
640 // Attempt to open the binary.
641 ErrorOr<OwningBinary<Binary>> BinaryOrErr = createBinary(Filename);
642 if (std::error_code EC = BinaryOrErr.getError()) {
643 errs() << "llvm-objdump: '" << Filename << "': " << EC.message() << ".\n";
646 Binary &Bin = *BinaryOrErr.get().getBinary();
648 if (Archive *A = dyn_cast<Archive>(&Bin)) {
649 outs() << "Archive : " << Filename << "\n";
651 printArchiveHeaders(A, true, false);
652 for (Archive::child_iterator I = A->child_begin(), E = A->child_end();
654 ErrorOr<std::unique_ptr<Binary>> ChildOrErr = I->getAsBinary();
655 if (ChildOrErr.getError())
657 if (MachOObjectFile *O = dyn_cast<MachOObjectFile>(&*ChildOrErr.get())) {
658 if (!checkMachOAndArchFlags(O, Filename))
660 ProcessMachO(Filename, O, O->getFileName());
665 if (UniversalHeaders) {
666 if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(&Bin))
667 printMachOUniversalHeaders(UB, true);
669 if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(&Bin)) {
670 // If we have a list of architecture flags specified dump only those.
671 if (!ArchAll && ArchFlags.size() != 0) {
672 // Look for a slice in the universal binary that matches each ArchFlag.
674 for (unsigned i = 0; i < ArchFlags.size(); ++i) {
676 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
677 E = UB->end_objects();
679 if (ArchFlags[i] == I->getArchTypeName()) {
681 ErrorOr<std::unique_ptr<ObjectFile>> ObjOrErr =
682 I->getAsObjectFile();
683 std::string ArchitectureName = "";
684 if (ArchFlags.size() > 1)
685 ArchitectureName = I->getArchTypeName();
687 ObjectFile &O = *ObjOrErr.get();
688 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&O))
689 ProcessMachO(Filename, MachOOF, "", ArchitectureName);
690 } else if (ErrorOr<std::unique_ptr<Archive>> AOrErr =
692 std::unique_ptr<Archive> &A = *AOrErr;
693 outs() << "Archive : " << Filename;
694 if (!ArchitectureName.empty())
695 outs() << " (architecture " << ArchitectureName << ")";
698 printArchiveHeaders(A.get(), true, false);
699 for (Archive::child_iterator AI = A->child_begin(),
702 ErrorOr<std::unique_ptr<Binary>> ChildOrErr = AI->getAsBinary();
703 if (ChildOrErr.getError())
705 if (MachOObjectFile *O =
706 dyn_cast<MachOObjectFile>(&*ChildOrErr.get()))
707 ProcessMachO(Filename, O, O->getFileName(), ArchitectureName);
713 errs() << "llvm-objdump: file: " + Filename + " does not contain "
714 << "architecture: " + ArchFlags[i] + "\n";
720 // No architecture flags were specified so if this contains a slice that
721 // matches the host architecture dump only that.
723 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
724 E = UB->end_objects();
726 if (MachOObjectFile::getHostArch().getArchName() ==
727 I->getArchTypeName()) {
728 ErrorOr<std::unique_ptr<ObjectFile>> ObjOrErr = I->getAsObjectFile();
729 std::string ArchiveName;
732 ObjectFile &O = *ObjOrErr.get();
733 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&O))
734 ProcessMachO(Filename, MachOOF);
735 } else if (ErrorOr<std::unique_ptr<Archive>> AOrErr =
737 std::unique_ptr<Archive> &A = *AOrErr;
738 outs() << "Archive : " << Filename << "\n";
740 printArchiveHeaders(A.get(), true, false);
741 for (Archive::child_iterator AI = A->child_begin(),
744 ErrorOr<std::unique_ptr<Binary>> ChildOrErr = AI->getAsBinary();
745 if (ChildOrErr.getError())
747 if (MachOObjectFile *O =
748 dyn_cast<MachOObjectFile>(&*ChildOrErr.get()))
749 ProcessMachO(Filename, O, O->getFileName());
756 // Either all architectures have been specified or none have been specified
757 // and this does not contain the host architecture so dump all the slices.
758 bool moreThanOneArch = UB->getNumberOfObjects() > 1;
759 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
760 E = UB->end_objects();
762 ErrorOr<std::unique_ptr<ObjectFile>> ObjOrErr = I->getAsObjectFile();
763 std::string ArchitectureName = "";
765 ArchitectureName = I->getArchTypeName();
767 ObjectFile &Obj = *ObjOrErr.get();
768 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&Obj))
769 ProcessMachO(Filename, MachOOF, "", ArchitectureName);
770 } else if (ErrorOr<std::unique_ptr<Archive>> AOrErr = I->getAsArchive()) {
771 std::unique_ptr<Archive> &A = *AOrErr;
772 outs() << "Archive : " << Filename;
773 if (!ArchitectureName.empty())
774 outs() << " (architecture " << ArchitectureName << ")";
777 printArchiveHeaders(A.get(), true, false);
778 for (Archive::child_iterator AI = A->child_begin(), AE = A->child_end();
780 ErrorOr<std::unique_ptr<Binary>> ChildOrErr = AI->getAsBinary();
781 if (ChildOrErr.getError())
783 if (MachOObjectFile *O =
784 dyn_cast<MachOObjectFile>(&*ChildOrErr.get())) {
785 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(O))
786 ProcessMachO(Filename, MachOOF, MachOOF->getFileName(),
794 if (ObjectFile *O = dyn_cast<ObjectFile>(&Bin)) {
795 if (!checkMachOAndArchFlags(O, Filename))
797 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&*O)) {
798 ProcessMachO(Filename, MachOOF);
800 errs() << "llvm-objdump: '" << Filename << "': "
801 << "Object is not a Mach-O file type.\n";
803 errs() << "llvm-objdump: '" << Filename << "': "
804 << "Unrecognized file type.\n";
807 typedef DenseMap<uint64_t, StringRef> SymbolAddressMap;
808 typedef std::pair<uint64_t, const char *> BindInfoEntry;
809 typedef std::vector<BindInfoEntry> BindTable;
810 typedef BindTable::iterator bind_table_iterator;
812 // The block of info used by the Symbolizer call backs.
813 struct DisassembleInfo {
817 SymbolAddressMap *AddrMap;
818 std::vector<SectionRef> *Sections;
819 const char *class_name;
820 const char *selector_name;
822 char *demangled_name;
825 BindTable *bindtable;
828 // GuessSymbolName is passed the address of what might be a symbol and a
829 // pointer to the DisassembleInfo struct. It returns the name of a symbol
830 // with that address or nullptr if no symbol is found with that address.
831 static const char *GuessSymbolName(uint64_t value,
832 struct DisassembleInfo *info) {
833 const char *SymbolName = nullptr;
834 // A DenseMap can't lookup up some values.
835 if (value != 0xffffffffffffffffULL && value != 0xfffffffffffffffeULL) {
836 StringRef name = info->AddrMap->lookup(value);
838 SymbolName = name.data();
843 // SymbolizerGetOpInfo() is the operand information call back function.
844 // This is called to get the symbolic information for operand(s) of an
845 // instruction when it is being done. This routine does this from
846 // the relocation information, symbol table, etc. That block of information
847 // is a pointer to the struct DisassembleInfo that was passed when the
848 // disassembler context was created and passed to back to here when
849 // called back by the disassembler for instruction operands that could have
850 // relocation information. The address of the instruction containing operand is
851 // at the Pc parameter. The immediate value the operand has is passed in
852 // op_info->Value and is at Offset past the start of the instruction and has a
853 // byte Size of 1, 2 or 4. The symbolc information is returned in TagBuf is the
854 // LLVMOpInfo1 struct defined in the header "llvm-c/Disassembler.h" as symbol
855 // names and addends of the symbolic expression to add for the operand. The
856 // value of TagType is currently 1 (for the LLVMOpInfo1 struct). If symbolic
857 // information is returned then this function returns 1 else it returns 0.
858 int SymbolizerGetOpInfo(void *DisInfo, uint64_t Pc, uint64_t Offset,
859 uint64_t Size, int TagType, void *TagBuf) {
860 struct DisassembleInfo *info = (struct DisassembleInfo *)DisInfo;
861 struct LLVMOpInfo1 *op_info = (struct LLVMOpInfo1 *)TagBuf;
862 uint64_t value = op_info->Value;
864 // Make sure all fields returned are zero if we don't set them.
865 memset((void *)op_info, '\0', sizeof(struct LLVMOpInfo1));
866 op_info->Value = value;
868 // If the TagType is not the value 1 which it code knows about or if no
869 // verbose symbolic information is wanted then just return 0, indicating no
870 // information is being returned.
871 if (TagType != 1 || info->verbose == false)
874 unsigned int Arch = info->O->getArch();
875 if (Arch == Triple::x86) {
876 if (Size != 1 && Size != 2 && Size != 4 && Size != 0)
878 // First search the section's relocation entries (if any) for an entry
879 // for this section offset.
880 uint32_t sect_addr = info->S.getAddress();
881 uint32_t sect_offset = (Pc + Offset) - sect_addr;
882 bool reloc_found = false;
884 MachO::any_relocation_info RE;
885 bool isExtern = false;
887 bool r_scattered = false;
888 uint32_t r_value, pair_r_value, r_type;
889 for (const RelocationRef &Reloc : info->S.relocations()) {
890 uint64_t RelocOffset;
891 Reloc.getOffset(RelocOffset);
892 if (RelocOffset == sect_offset) {
893 Rel = Reloc.getRawDataRefImpl();
894 RE = info->O->getRelocation(Rel);
895 r_type = info->O->getAnyRelocationType(RE);
896 r_scattered = info->O->isRelocationScattered(RE);
898 r_value = info->O->getScatteredRelocationValue(RE);
899 if (r_type == MachO::GENERIC_RELOC_SECTDIFF ||
900 r_type == MachO::GENERIC_RELOC_LOCAL_SECTDIFF) {
901 DataRefImpl RelNext = Rel;
902 info->O->moveRelocationNext(RelNext);
903 MachO::any_relocation_info RENext;
904 RENext = info->O->getRelocation(RelNext);
905 if (info->O->isRelocationScattered(RENext))
906 pair_r_value = info->O->getScatteredRelocationValue(RENext);
911 isExtern = info->O->getPlainRelocationExternal(RE);
913 symbol_iterator RelocSym = Reloc.getSymbol();
921 if (reloc_found && isExtern) {
923 Symbol.getName(SymName);
924 const char *name = SymName.data();
925 op_info->AddSymbol.Present = 1;
926 op_info->AddSymbol.Name = name;
927 // For i386 extern relocation entries the value in the instruction is
928 // the offset from the symbol, and value is already set in op_info->Value.
931 if (reloc_found && (r_type == MachO::GENERIC_RELOC_SECTDIFF ||
932 r_type == MachO::GENERIC_RELOC_LOCAL_SECTDIFF)) {
933 const char *add = GuessSymbolName(r_value, info);
934 const char *sub = GuessSymbolName(pair_r_value, info);
935 uint32_t offset = value - (r_value - pair_r_value);
936 op_info->AddSymbol.Present = 1;
938 op_info->AddSymbol.Name = add;
940 op_info->AddSymbol.Value = r_value;
941 op_info->SubtractSymbol.Present = 1;
943 op_info->SubtractSymbol.Name = sub;
945 op_info->SubtractSymbol.Value = pair_r_value;
946 op_info->Value = offset;
950 // Second search the external relocation entries of a fully linked image
951 // (if any) for an entry that matches this segment offset.
952 // uint32_t seg_offset = (Pc + Offset);
954 } else if (Arch == Triple::x86_64) {
955 if (Size != 1 && Size != 2 && Size != 4 && Size != 0)
957 // First search the section's relocation entries (if any) for an entry
958 // for this section offset.
959 uint64_t sect_addr = info->S.getAddress();
960 uint64_t sect_offset = (Pc + Offset) - sect_addr;
961 bool reloc_found = false;
963 MachO::any_relocation_info RE;
964 bool isExtern = false;
966 for (const RelocationRef &Reloc : info->S.relocations()) {
967 uint64_t RelocOffset;
968 Reloc.getOffset(RelocOffset);
969 if (RelocOffset == sect_offset) {
970 Rel = Reloc.getRawDataRefImpl();
971 RE = info->O->getRelocation(Rel);
972 // NOTE: Scattered relocations don't exist on x86_64.
973 isExtern = info->O->getPlainRelocationExternal(RE);
975 symbol_iterator RelocSym = Reloc.getSymbol();
982 if (reloc_found && isExtern) {
983 // The Value passed in will be adjusted by the Pc if the instruction
984 // adds the Pc. But for x86_64 external relocation entries the Value
985 // is the offset from the external symbol.
986 if (info->O->getAnyRelocationPCRel(RE))
987 op_info->Value -= Pc + Offset + Size;
989 Symbol.getName(SymName);
990 const char *name = SymName.data();
991 unsigned Type = info->O->getAnyRelocationType(RE);
992 if (Type == MachO::X86_64_RELOC_SUBTRACTOR) {
993 DataRefImpl RelNext = Rel;
994 info->O->moveRelocationNext(RelNext);
995 MachO::any_relocation_info RENext = info->O->getRelocation(RelNext);
996 unsigned TypeNext = info->O->getAnyRelocationType(RENext);
997 bool isExternNext = info->O->getPlainRelocationExternal(RENext);
998 unsigned SymbolNum = info->O->getPlainRelocationSymbolNum(RENext);
999 if (TypeNext == MachO::X86_64_RELOC_UNSIGNED && isExternNext) {
1000 op_info->SubtractSymbol.Present = 1;
1001 op_info->SubtractSymbol.Name = name;
1002 symbol_iterator RelocSymNext = info->O->getSymbolByIndex(SymbolNum);
1003 Symbol = *RelocSymNext;
1004 StringRef SymNameNext;
1005 Symbol.getName(SymNameNext);
1006 name = SymNameNext.data();
1009 // TODO: add the VariantKinds to op_info->VariantKind for relocation types
1010 // like: X86_64_RELOC_TLV, X86_64_RELOC_GOT_LOAD and X86_64_RELOC_GOT.
1011 op_info->AddSymbol.Present = 1;
1012 op_info->AddSymbol.Name = name;
1016 // Second search the external relocation entries of a fully linked image
1017 // (if any) for an entry that matches this segment offset.
1018 // uint64_t seg_offset = (Pc + Offset);
1020 } else if (Arch == Triple::arm) {
1021 if (Offset != 0 || (Size != 4 && Size != 2))
1023 // First search the section's relocation entries (if any) for an entry
1024 // for this section offset.
1025 uint32_t sect_addr = info->S.getAddress();
1026 uint32_t sect_offset = (Pc + Offset) - sect_addr;
1027 bool reloc_found = false;
1029 MachO::any_relocation_info RE;
1030 bool isExtern = false;
1032 bool r_scattered = false;
1033 uint32_t r_value, pair_r_value, r_type, r_length, other_half;
1034 for (const RelocationRef &Reloc : info->S.relocations()) {
1035 uint64_t RelocOffset;
1036 Reloc.getOffset(RelocOffset);
1037 if (RelocOffset == sect_offset) {
1038 Rel = Reloc.getRawDataRefImpl();
1039 RE = info->O->getRelocation(Rel);
1040 r_length = info->O->getAnyRelocationLength(RE);
1041 r_scattered = info->O->isRelocationScattered(RE);
1043 r_value = info->O->getScatteredRelocationValue(RE);
1044 r_type = info->O->getScatteredRelocationType(RE);
1046 r_type = info->O->getAnyRelocationType(RE);
1047 isExtern = info->O->getPlainRelocationExternal(RE);
1049 symbol_iterator RelocSym = Reloc.getSymbol();
1053 if (r_type == MachO::ARM_RELOC_HALF ||
1054 r_type == MachO::ARM_RELOC_SECTDIFF ||
1055 r_type == MachO::ARM_RELOC_LOCAL_SECTDIFF ||
1056 r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
1057 DataRefImpl RelNext = Rel;
1058 info->O->moveRelocationNext(RelNext);
1059 MachO::any_relocation_info RENext;
1060 RENext = info->O->getRelocation(RelNext);
1061 other_half = info->O->getAnyRelocationAddress(RENext) & 0xffff;
1062 if (info->O->isRelocationScattered(RENext))
1063 pair_r_value = info->O->getScatteredRelocationValue(RENext);
1069 if (reloc_found && isExtern) {
1071 Symbol.getName(SymName);
1072 const char *name = SymName.data();
1073 op_info->AddSymbol.Present = 1;
1074 op_info->AddSymbol.Name = name;
1077 case MachO::ARM_RELOC_HALF:
1078 if ((r_length & 0x1) == 1) {
1079 op_info->Value = value << 16 | other_half;
1080 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
1082 op_info->Value = other_half << 16 | value;
1083 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
1091 case MachO::ARM_RELOC_HALF:
1092 if ((r_length & 0x1) == 1) {
1093 op_info->Value = value << 16 | other_half;
1094 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
1096 op_info->Value = other_half << 16 | value;
1097 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
1106 // If we have a branch that is not an external relocation entry then
1107 // return 0 so the code in tryAddingSymbolicOperand() can use the
1108 // SymbolLookUp call back with the branch target address to look up the
1109 // symbol and possiblity add an annotation for a symbol stub.
1110 if (reloc_found && isExtern == 0 && (r_type == MachO::ARM_RELOC_BR24 ||
1111 r_type == MachO::ARM_THUMB_RELOC_BR22))
1114 uint32_t offset = 0;
1116 if (r_type == MachO::ARM_RELOC_HALF ||
1117 r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
1118 if ((r_length & 0x1) == 1)
1119 value = value << 16 | other_half;
1121 value = other_half << 16 | value;
1123 if (r_scattered && (r_type != MachO::ARM_RELOC_HALF &&
1124 r_type != MachO::ARM_RELOC_HALF_SECTDIFF)) {
1125 offset = value - r_value;
1130 if (reloc_found && r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
1131 if ((r_length & 0x1) == 1)
1132 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
1134 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
1135 const char *add = GuessSymbolName(r_value, info);
1136 const char *sub = GuessSymbolName(pair_r_value, info);
1137 int32_t offset = value - (r_value - pair_r_value);
1138 op_info->AddSymbol.Present = 1;
1140 op_info->AddSymbol.Name = add;
1142 op_info->AddSymbol.Value = r_value;
1143 op_info->SubtractSymbol.Present = 1;
1145 op_info->SubtractSymbol.Name = sub;
1147 op_info->SubtractSymbol.Value = pair_r_value;
1148 op_info->Value = offset;
1152 if (reloc_found == false)
1155 op_info->AddSymbol.Present = 1;
1156 op_info->Value = offset;
1158 if (r_type == MachO::ARM_RELOC_HALF) {
1159 if ((r_length & 0x1) == 1)
1160 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
1162 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
1165 const char *add = GuessSymbolName(value, info);
1166 if (add != nullptr) {
1167 op_info->AddSymbol.Name = add;
1170 op_info->AddSymbol.Value = value;
1172 } else if (Arch == Triple::aarch64) {
1173 if (Offset != 0 || Size != 4)
1175 // First search the section's relocation entries (if any) for an entry
1176 // for this section offset.
1177 uint64_t sect_addr = info->S.getAddress();
1178 uint64_t sect_offset = (Pc + Offset) - sect_addr;
1179 bool reloc_found = false;
1181 MachO::any_relocation_info RE;
1182 bool isExtern = false;
1184 uint32_t r_type = 0;
1185 for (const RelocationRef &Reloc : info->S.relocations()) {
1186 uint64_t RelocOffset;
1187 Reloc.getOffset(RelocOffset);
1188 if (RelocOffset == sect_offset) {
1189 Rel = Reloc.getRawDataRefImpl();
1190 RE = info->O->getRelocation(Rel);
1191 r_type = info->O->getAnyRelocationType(RE);
1192 if (r_type == MachO::ARM64_RELOC_ADDEND) {
1193 DataRefImpl RelNext = Rel;
1194 info->O->moveRelocationNext(RelNext);
1195 MachO::any_relocation_info RENext = info->O->getRelocation(RelNext);
1197 value = info->O->getPlainRelocationSymbolNum(RENext);
1198 op_info->Value = value;
1201 // NOTE: Scattered relocations don't exist on arm64.
1202 isExtern = info->O->getPlainRelocationExternal(RE);
1204 symbol_iterator RelocSym = Reloc.getSymbol();
1211 if (reloc_found && isExtern) {
1213 Symbol.getName(SymName);
1214 const char *name = SymName.data();
1215 op_info->AddSymbol.Present = 1;
1216 op_info->AddSymbol.Name = name;
1219 case MachO::ARM64_RELOC_PAGE21:
1221 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_PAGE;
1223 case MachO::ARM64_RELOC_PAGEOFF12:
1225 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_PAGEOFF;
1227 case MachO::ARM64_RELOC_GOT_LOAD_PAGE21:
1229 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_GOTPAGE;
1231 case MachO::ARM64_RELOC_GOT_LOAD_PAGEOFF12:
1233 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_GOTPAGEOFF;
1235 case MachO::ARM64_RELOC_TLVP_LOAD_PAGE21:
1236 /* @tvlppage is not implemented in llvm-mc */
1237 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_TLVP;
1239 case MachO::ARM64_RELOC_TLVP_LOAD_PAGEOFF12:
1240 /* @tvlppageoff is not implemented in llvm-mc */
1241 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_TLVOFF;
1244 case MachO::ARM64_RELOC_BRANCH26:
1245 op_info->VariantKind = LLVMDisassembler_VariantKind_None;
1256 // GuessCstringPointer is passed the address of what might be a pointer to a
1257 // literal string in a cstring section. If that address is in a cstring section
1258 // it returns a pointer to that string. Else it returns nullptr.
1259 const char *GuessCstringPointer(uint64_t ReferenceValue,
1260 struct DisassembleInfo *info) {
1261 uint32_t LoadCommandCount = info->O->getHeader().ncmds;
1262 MachOObjectFile::LoadCommandInfo Load = info->O->getFirstLoadCommandInfo();
1263 for (unsigned I = 0;; ++I) {
1264 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
1265 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
1266 for (unsigned J = 0; J < Seg.nsects; ++J) {
1267 MachO::section_64 Sec = info->O->getSection64(Load, J);
1268 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
1269 if (section_type == MachO::S_CSTRING_LITERALS &&
1270 ReferenceValue >= Sec.addr &&
1271 ReferenceValue < Sec.addr + Sec.size) {
1272 uint64_t sect_offset = ReferenceValue - Sec.addr;
1273 uint64_t object_offset = Sec.offset + sect_offset;
1274 StringRef MachOContents = info->O->getData();
1275 uint64_t object_size = MachOContents.size();
1276 const char *object_addr = (const char *)MachOContents.data();
1277 if (object_offset < object_size) {
1278 const char *name = object_addr + object_offset;
1285 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
1286 MachO::segment_command Seg = info->O->getSegmentLoadCommand(Load);
1287 for (unsigned J = 0; J < Seg.nsects; ++J) {
1288 MachO::section Sec = info->O->getSection(Load, J);
1289 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
1290 if (section_type == MachO::S_CSTRING_LITERALS &&
1291 ReferenceValue >= Sec.addr &&
1292 ReferenceValue < Sec.addr + Sec.size) {
1293 uint64_t sect_offset = ReferenceValue - Sec.addr;
1294 uint64_t object_offset = Sec.offset + sect_offset;
1295 StringRef MachOContents = info->O->getData();
1296 uint64_t object_size = MachOContents.size();
1297 const char *object_addr = (const char *)MachOContents.data();
1298 if (object_offset < object_size) {
1299 const char *name = object_addr + object_offset;
1307 if (I == LoadCommandCount - 1)
1310 Load = info->O->getNextLoadCommandInfo(Load);
1315 // GuessIndirectSymbol returns the name of the indirect symbol for the
1316 // ReferenceValue passed in or nullptr. This is used when ReferenceValue maybe
1317 // an address of a symbol stub or a lazy or non-lazy pointer to associate the
1318 // symbol name being referenced by the stub or pointer.
1319 static const char *GuessIndirectSymbol(uint64_t ReferenceValue,
1320 struct DisassembleInfo *info) {
1321 uint32_t LoadCommandCount = info->O->getHeader().ncmds;
1322 MachOObjectFile::LoadCommandInfo Load = info->O->getFirstLoadCommandInfo();
1323 MachO::dysymtab_command Dysymtab = info->O->getDysymtabLoadCommand();
1324 MachO::symtab_command Symtab = info->O->getSymtabLoadCommand();
1325 for (unsigned I = 0;; ++I) {
1326 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
1327 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
1328 for (unsigned J = 0; J < Seg.nsects; ++J) {
1329 MachO::section_64 Sec = info->O->getSection64(Load, J);
1330 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
1331 if ((section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
1332 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
1333 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
1334 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
1335 section_type == MachO::S_SYMBOL_STUBS) &&
1336 ReferenceValue >= Sec.addr &&
1337 ReferenceValue < Sec.addr + Sec.size) {
1339 if (section_type == MachO::S_SYMBOL_STUBS)
1340 stride = Sec.reserved2;
1345 uint32_t index = Sec.reserved1 + (ReferenceValue - Sec.addr) / stride;
1346 if (index < Dysymtab.nindirectsyms) {
1347 uint32_t indirect_symbol =
1348 info->O->getIndirectSymbolTableEntry(Dysymtab, index);
1349 if (indirect_symbol < Symtab.nsyms) {
1350 symbol_iterator Sym = info->O->getSymbolByIndex(indirect_symbol);
1351 SymbolRef Symbol = *Sym;
1353 Symbol.getName(SymName);
1354 const char *name = SymName.data();
1360 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
1361 MachO::segment_command Seg = info->O->getSegmentLoadCommand(Load);
1362 for (unsigned J = 0; J < Seg.nsects; ++J) {
1363 MachO::section Sec = info->O->getSection(Load, J);
1364 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
1365 if ((section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
1366 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
1367 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
1368 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
1369 section_type == MachO::S_SYMBOL_STUBS) &&
1370 ReferenceValue >= Sec.addr &&
1371 ReferenceValue < Sec.addr + Sec.size) {
1373 if (section_type == MachO::S_SYMBOL_STUBS)
1374 stride = Sec.reserved2;
1379 uint32_t index = Sec.reserved1 + (ReferenceValue - Sec.addr) / stride;
1380 if (index < Dysymtab.nindirectsyms) {
1381 uint32_t indirect_symbol =
1382 info->O->getIndirectSymbolTableEntry(Dysymtab, index);
1383 if (indirect_symbol < Symtab.nsyms) {
1384 symbol_iterator Sym = info->O->getSymbolByIndex(indirect_symbol);
1385 SymbolRef Symbol = *Sym;
1387 Symbol.getName(SymName);
1388 const char *name = SymName.data();
1395 if (I == LoadCommandCount - 1)
1398 Load = info->O->getNextLoadCommandInfo(Load);
1403 // method_reference() is called passing it the ReferenceName that might be
1404 // a reference it to an Objective-C method call. If so then it allocates and
1405 // assembles a method call string with the values last seen and saved in
1406 // the DisassembleInfo's class_name and selector_name fields. This is saved
1407 // into the method field of the info and any previous string is free'ed.
1408 // Then the class_name field in the info is set to nullptr. The method call
1409 // string is set into ReferenceName and ReferenceType is set to
1410 // LLVMDisassembler_ReferenceType_Out_Objc_Message. If this not a method call
1411 // then both ReferenceType and ReferenceName are left unchanged.
1412 static void method_reference(struct DisassembleInfo *info,
1413 uint64_t *ReferenceType,
1414 const char **ReferenceName) {
1415 unsigned int Arch = info->O->getArch();
1416 if (*ReferenceName != nullptr) {
1417 if (strcmp(*ReferenceName, "_objc_msgSend") == 0) {
1418 if (info->selector_name != nullptr) {
1419 if (info->method != nullptr)
1421 if (info->class_name != nullptr) {
1422 info->method = (char *)malloc(5 + strlen(info->class_name) +
1423 strlen(info->selector_name));
1424 if (info->method != nullptr) {
1425 strcpy(info->method, "+[");
1426 strcat(info->method, info->class_name);
1427 strcat(info->method, " ");
1428 strcat(info->method, info->selector_name);
1429 strcat(info->method, "]");
1430 *ReferenceName = info->method;
1431 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
1434 info->method = (char *)malloc(9 + strlen(info->selector_name));
1435 if (info->method != nullptr) {
1436 if (Arch == Triple::x86_64)
1437 strcpy(info->method, "-[%rdi ");
1438 else if (Arch == Triple::aarch64)
1439 strcpy(info->method, "-[x0 ");
1441 strcpy(info->method, "-[r? ");
1442 strcat(info->method, info->selector_name);
1443 strcat(info->method, "]");
1444 *ReferenceName = info->method;
1445 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
1448 info->class_name = nullptr;
1450 } else if (strcmp(*ReferenceName, "_objc_msgSendSuper2") == 0) {
1451 if (info->selector_name != nullptr) {
1452 if (info->method != nullptr)
1454 info->method = (char *)malloc(17 + strlen(info->selector_name));
1455 if (info->method != nullptr) {
1456 if (Arch == Triple::x86_64)
1457 strcpy(info->method, "-[[%rdi super] ");
1458 else if (Arch == Triple::aarch64)
1459 strcpy(info->method, "-[[x0 super] ");
1461 strcpy(info->method, "-[[r? super] ");
1462 strcat(info->method, info->selector_name);
1463 strcat(info->method, "]");
1464 *ReferenceName = info->method;
1465 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
1467 info->class_name = nullptr;
1473 // GuessPointerPointer() is passed the address of what might be a pointer to
1474 // a reference to an Objective-C class, selector, message ref or cfstring.
1475 // If so the value of the pointer is returned and one of the booleans are set
1476 // to true. If not zero is returned and all the booleans are set to false.
1477 static uint64_t GuessPointerPointer(uint64_t ReferenceValue,
1478 struct DisassembleInfo *info,
1479 bool &classref, bool &selref, bool &msgref,
1485 uint32_t LoadCommandCount = info->O->getHeader().ncmds;
1486 MachOObjectFile::LoadCommandInfo Load = info->O->getFirstLoadCommandInfo();
1487 for (unsigned I = 0;; ++I) {
1488 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
1489 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
1490 for (unsigned J = 0; J < Seg.nsects; ++J) {
1491 MachO::section_64 Sec = info->O->getSection64(Load, J);
1492 if ((strncmp(Sec.sectname, "__objc_selrefs", 16) == 0 ||
1493 strncmp(Sec.sectname, "__objc_classrefs", 16) == 0 ||
1494 strncmp(Sec.sectname, "__objc_superrefs", 16) == 0 ||
1495 strncmp(Sec.sectname, "__objc_msgrefs", 16) == 0 ||
1496 strncmp(Sec.sectname, "__cfstring", 16) == 0) &&
1497 ReferenceValue >= Sec.addr &&
1498 ReferenceValue < Sec.addr + Sec.size) {
1499 uint64_t sect_offset = ReferenceValue - Sec.addr;
1500 uint64_t object_offset = Sec.offset + sect_offset;
1501 StringRef MachOContents = info->O->getData();
1502 uint64_t object_size = MachOContents.size();
1503 const char *object_addr = (const char *)MachOContents.data();
1504 if (object_offset < object_size) {
1505 uint64_t pointer_value;
1506 memcpy(&pointer_value, object_addr + object_offset,
1508 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
1509 sys::swapByteOrder(pointer_value);
1510 if (strncmp(Sec.sectname, "__objc_selrefs", 16) == 0)
1512 else if (strncmp(Sec.sectname, "__objc_classrefs", 16) == 0 ||
1513 strncmp(Sec.sectname, "__objc_superrefs", 16) == 0)
1515 else if (strncmp(Sec.sectname, "__objc_msgrefs", 16) == 0 &&
1516 ReferenceValue + 8 < Sec.addr + Sec.size) {
1518 memcpy(&pointer_value, object_addr + object_offset + 8,
1520 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
1521 sys::swapByteOrder(pointer_value);
1522 } else if (strncmp(Sec.sectname, "__cfstring", 16) == 0)
1524 return pointer_value;
1531 // TODO: Look for LC_SEGMENT for 32-bit Mach-O files.
1532 if (I == LoadCommandCount - 1)
1535 Load = info->O->getNextLoadCommandInfo(Load);
1540 // get_pointer_64 returns a pointer to the bytes in the object file at the
1541 // Address from a section in the Mach-O file. And indirectly returns the
1542 // offset into the section, number of bytes left in the section past the offset
1543 // and which section is was being referenced. If the Address is not in a
1544 // section nullptr is returned.
1545 const char *get_pointer_64(uint64_t Address, uint32_t &offset, uint32_t &left,
1546 SectionRef &S, DisassembleInfo *info) {
1550 for (unsigned SectIdx = 0; SectIdx != info->Sections->size(); SectIdx++) {
1551 uint64_t SectAddress = ((*(info->Sections))[SectIdx]).getAddress();
1552 uint64_t SectSize = ((*(info->Sections))[SectIdx]).getSize();
1553 if (Address >= SectAddress && Address < SectAddress + SectSize) {
1554 S = (*(info->Sections))[SectIdx];
1555 offset = Address - SectAddress;
1556 left = SectSize - offset;
1557 StringRef SectContents;
1558 ((*(info->Sections))[SectIdx]).getContents(SectContents);
1559 return SectContents.data() + offset;
1565 // get_symbol_64() returns the name of a symbol (or nullptr) and the address of
1566 // the symbol indirectly through n_value. Based on the relocation information
1567 // for the specified section offset in the specified section reference.
1568 const char *get_symbol_64(uint32_t sect_offset, SectionRef S,
1569 DisassembleInfo *info, uint64_t &n_value) {
1571 if (info->verbose == false)
1574 // See if there is an external relocation entry at the sect_offset.
1575 bool reloc_found = false;
1577 MachO::any_relocation_info RE;
1578 bool isExtern = false;
1580 for (const RelocationRef &Reloc : S.relocations()) {
1581 uint64_t RelocOffset;
1582 Reloc.getOffset(RelocOffset);
1583 if (RelocOffset == sect_offset) {
1584 Rel = Reloc.getRawDataRefImpl();
1585 RE = info->O->getRelocation(Rel);
1586 if (info->O->isRelocationScattered(RE))
1588 isExtern = info->O->getPlainRelocationExternal(RE);
1590 symbol_iterator RelocSym = Reloc.getSymbol();
1597 // If there is an external relocation entry for a symbol in this section
1598 // at this section_offset then use that symbol's value for the n_value
1599 // and return its name.
1600 const char *SymbolName = nullptr;
1601 if (reloc_found && isExtern) {
1602 Symbol.getAddress(n_value);
1604 Symbol.getName(name);
1605 if (!name.empty()) {
1606 SymbolName = name.data();
1611 // TODO: For fully linked images, look through the external relocation
1612 // entries off the dynamic symtab command. For these the r_offset is from the
1613 // start of the first writeable segment in the Mach-O file. So the offset
1614 // to this section from that segment is passed to this routine by the caller,
1615 // as the database_offset. Which is the difference of the section's starting
1616 // address and the first writable segment.
1618 // NOTE: need add passing the database_offset to this routine.
1620 // TODO: We did not find an external relocation entry so look up the
1621 // ReferenceValue as an address of a symbol and if found return that symbol's
1624 // NOTE: need add passing the ReferenceValue to this routine. Then that code
1625 // would simply be this:
1626 // SymbolName = GuessSymbolName(ReferenceValue, info);
1631 // These are structs in the Objective-C meta data and read to produce the
1632 // comments for disassembly. While these are part of the ABI they are no
1633 // public defintions. So the are here not in include/llvm/Support/MachO.h .
1635 // The cfstring object in a 64-bit Mach-O file.
1636 struct cfstring64_t {
1637 uint64_t isa; // class64_t * (64-bit pointer)
1638 uint64_t flags; // flag bits
1639 uint64_t characters; // char * (64-bit pointer)
1640 uint64_t length; // number of non-NULL characters in above
1643 // The class object in a 64-bit Mach-O file.
1645 uint64_t isa; // class64_t * (64-bit pointer)
1646 uint64_t superclass; // class64_t * (64-bit pointer)
1647 uint64_t cache; // Cache (64-bit pointer)
1648 uint64_t vtable; // IMP * (64-bit pointer)
1649 uint64_t data; // class_ro64_t * (64-bit pointer)
1652 struct class_ro64_t {
1654 uint32_t instanceStart;
1655 uint32_t instanceSize;
1657 uint64_t ivarLayout; // const uint8_t * (64-bit pointer)
1658 uint64_t name; // const char * (64-bit pointer)
1659 uint64_t baseMethods; // const method_list_t * (64-bit pointer)
1660 uint64_t baseProtocols; // const protocol_list_t * (64-bit pointer)
1661 uint64_t ivars; // const ivar_list_t * (64-bit pointer)
1662 uint64_t weakIvarLayout; // const uint8_t * (64-bit pointer)
1663 uint64_t baseProperties; // const struct objc_property_list (64-bit pointer)
1666 inline void swapStruct(struct cfstring64_t &cfs) {
1667 sys::swapByteOrder(cfs.isa);
1668 sys::swapByteOrder(cfs.flags);
1669 sys::swapByteOrder(cfs.characters);
1670 sys::swapByteOrder(cfs.length);
1673 inline void swapStruct(struct class64_t &c) {
1674 sys::swapByteOrder(c.isa);
1675 sys::swapByteOrder(c.superclass);
1676 sys::swapByteOrder(c.cache);
1677 sys::swapByteOrder(c.vtable);
1678 sys::swapByteOrder(c.data);
1681 inline void swapStruct(struct class_ro64_t &cro) {
1682 sys::swapByteOrder(cro.flags);
1683 sys::swapByteOrder(cro.instanceStart);
1684 sys::swapByteOrder(cro.instanceSize);
1685 sys::swapByteOrder(cro.reserved);
1686 sys::swapByteOrder(cro.ivarLayout);
1687 sys::swapByteOrder(cro.name);
1688 sys::swapByteOrder(cro.baseMethods);
1689 sys::swapByteOrder(cro.baseProtocols);
1690 sys::swapByteOrder(cro.ivars);
1691 sys::swapByteOrder(cro.weakIvarLayout);
1692 sys::swapByteOrder(cro.baseProperties);
1695 static const char *get_dyld_bind_info_symbolname(uint64_t ReferenceValue,
1696 struct DisassembleInfo *info);
1698 // get_objc2_64bit_class_name() is used for disassembly and is passed a pointer
1699 // to an Objective-C class and returns the class name. It is also passed the
1700 // address of the pointer, so when the pointer is zero as it can be in an .o
1701 // file, that is used to look for an external relocation entry with a symbol
1703 const char *get_objc2_64bit_class_name(uint64_t pointer_value,
1704 uint64_t ReferenceValue,
1705 struct DisassembleInfo *info) {
1707 uint32_t offset, left;
1710 // The pointer_value can be 0 in an object file and have a relocation
1711 // entry for the class symbol at the ReferenceValue (the address of the
1713 if (pointer_value == 0) {
1714 r = get_pointer_64(ReferenceValue, offset, left, S, info);
1715 if (r == nullptr || left < sizeof(uint64_t))
1718 const char *symbol_name = get_symbol_64(offset, S, info, n_value);
1719 if (symbol_name == nullptr)
1721 const char *class_name = strrchr(symbol_name, '$');
1722 if (class_name != nullptr && class_name[1] == '_' && class_name[2] != '\0')
1723 return class_name + 2;
1728 // The case were the pointer_value is non-zero and points to a class defined
1729 // in this Mach-O file.
1730 r = get_pointer_64(pointer_value, offset, left, S, info);
1731 if (r == nullptr || left < sizeof(struct class64_t))
1734 memcpy(&c, r, sizeof(struct class64_t));
1735 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
1739 r = get_pointer_64(c.data, offset, left, S, info);
1740 if (r == nullptr || left < sizeof(struct class_ro64_t))
1742 struct class_ro64_t cro;
1743 memcpy(&cro, r, sizeof(struct class_ro64_t));
1744 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
1748 const char *name = get_pointer_64(cro.name, offset, left, S, info);
1752 // get_objc2_64bit_cfstring_name is used for disassembly and is passed a
1753 // pointer to a cfstring and returns its name or nullptr.
1754 const char *get_objc2_64bit_cfstring_name(uint64_t ReferenceValue,
1755 struct DisassembleInfo *info) {
1756 const char *r, *name;
1757 uint32_t offset, left;
1759 struct cfstring64_t cfs;
1760 uint64_t cfs_characters;
1762 r = get_pointer_64(ReferenceValue, offset, left, S, info);
1763 if (r == nullptr || left < sizeof(struct cfstring64_t))
1765 memcpy(&cfs, r, sizeof(struct cfstring64_t));
1766 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
1768 if (cfs.characters == 0) {
1770 const char *symbol_name = get_symbol_64(
1771 offset + offsetof(struct cfstring64_t, characters), S, info, n_value);
1772 if (symbol_name == nullptr)
1774 cfs_characters = n_value;
1776 cfs_characters = cfs.characters;
1777 name = get_pointer_64(cfs_characters, offset, left, S, info);
1782 // get_objc2_64bit_selref() is used for disassembly and is passed a the address
1783 // of a pointer to an Objective-C selector reference when the pointer value is
1784 // zero as in a .o file and is likely to have a external relocation entry with
1785 // who's symbol's n_value is the real pointer to the selector name. If that is
1786 // the case the real pointer to the selector name is returned else 0 is
1788 uint64_t get_objc2_64bit_selref(uint64_t ReferenceValue,
1789 struct DisassembleInfo *info) {
1790 uint32_t offset, left;
1793 const char *r = get_pointer_64(ReferenceValue, offset, left, S, info);
1794 if (r == nullptr || left < sizeof(uint64_t))
1797 const char *symbol_name = get_symbol_64(offset, S, info, n_value);
1798 if (symbol_name == nullptr)
1803 // GuessLiteralPointer returns a string which for the item in the Mach-O file
1804 // for the address passed in as ReferenceValue for printing as a comment with
1805 // the instruction and also returns the corresponding type of that item
1806 // indirectly through ReferenceType.
1808 // If ReferenceValue is an address of literal cstring then a pointer to the
1809 // cstring is returned and ReferenceType is set to
1810 // LLVMDisassembler_ReferenceType_Out_LitPool_CstrAddr .
1812 // If ReferenceValue is an address of an Objective-C CFString, Selector ref or
1813 // Class ref that name is returned and the ReferenceType is set accordingly.
1815 // Lastly, literals which are Symbol address in a literal pool are looked for
1816 // and if found the symbol name is returned and ReferenceType is set to
1817 // LLVMDisassembler_ReferenceType_Out_LitPool_SymAddr .
1819 // If there is no item in the Mach-O file for the address passed in as
1820 // ReferenceValue nullptr is returned and ReferenceType is unchanged.
1821 const char *GuessLiteralPointer(uint64_t ReferenceValue, uint64_t ReferencePC,
1822 uint64_t *ReferenceType,
1823 struct DisassembleInfo *info) {
1824 // First see if there is an external relocation entry at the ReferencePC.
1825 uint64_t sect_addr = info->S.getAddress();
1826 uint64_t sect_offset = ReferencePC - sect_addr;
1827 bool reloc_found = false;
1829 MachO::any_relocation_info RE;
1830 bool isExtern = false;
1832 for (const RelocationRef &Reloc : info->S.relocations()) {
1833 uint64_t RelocOffset;
1834 Reloc.getOffset(RelocOffset);
1835 if (RelocOffset == sect_offset) {
1836 Rel = Reloc.getRawDataRefImpl();
1837 RE = info->O->getRelocation(Rel);
1838 if (info->O->isRelocationScattered(RE))
1840 isExtern = info->O->getPlainRelocationExternal(RE);
1842 symbol_iterator RelocSym = Reloc.getSymbol();
1849 // If there is an external relocation entry for a symbol in a section
1850 // then used that symbol's value for the value of the reference.
1851 if (reloc_found && isExtern) {
1852 if (info->O->getAnyRelocationPCRel(RE)) {
1853 unsigned Type = info->O->getAnyRelocationType(RE);
1854 if (Type == MachO::X86_64_RELOC_SIGNED) {
1855 Symbol.getAddress(ReferenceValue);
1860 // Look for literals such as Objective-C CFStrings refs, Selector refs,
1861 // Message refs and Class refs.
1862 bool classref, selref, msgref, cfstring;
1863 uint64_t pointer_value = GuessPointerPointer(ReferenceValue, info, classref,
1864 selref, msgref, cfstring);
1865 if (classref == true && pointer_value == 0) {
1866 // Note the ReferenceValue is a pointer into the __objc_classrefs section.
1867 // And the pointer_value in that section is typically zero as it will be
1868 // set by dyld as part of the "bind information".
1869 const char *name = get_dyld_bind_info_symbolname(ReferenceValue, info);
1870 if (name != nullptr) {
1871 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Class_Ref;
1872 const char *class_name = strrchr(name, '$');
1873 if (class_name != nullptr && class_name[1] == '_' &&
1874 class_name[2] != '\0') {
1875 info->class_name = class_name + 2;
1881 if (classref == true) {
1882 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Class_Ref;
1884 get_objc2_64bit_class_name(pointer_value, ReferenceValue, info);
1885 if (name != nullptr)
1886 info->class_name = name;
1888 name = "bad class ref";
1892 if (cfstring == true) {
1893 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_CFString_Ref;
1894 const char *name = get_objc2_64bit_cfstring_name(ReferenceValue, info);
1898 if (selref == true && pointer_value == 0)
1899 pointer_value = get_objc2_64bit_selref(ReferenceValue, info);
1901 if (pointer_value != 0)
1902 ReferenceValue = pointer_value;
1904 const char *name = GuessCstringPointer(ReferenceValue, info);
1906 if (pointer_value != 0 && selref == true) {
1907 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Selector_Ref;
1908 info->selector_name = name;
1909 } else if (pointer_value != 0 && msgref == true) {
1910 info->class_name = nullptr;
1911 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message_Ref;
1912 info->selector_name = name;
1914 *ReferenceType = LLVMDisassembler_ReferenceType_Out_LitPool_CstrAddr;
1918 // Lastly look for an indirect symbol with this ReferenceValue which is in
1919 // a literal pool. If found return that symbol name.
1920 name = GuessIndirectSymbol(ReferenceValue, info);
1922 *ReferenceType = LLVMDisassembler_ReferenceType_Out_LitPool_SymAddr;
1929 // SymbolizerSymbolLookUp is the symbol lookup function passed when creating
1930 // the Symbolizer. It looks up the ReferenceValue using the info passed via the
1931 // pointer to the struct DisassembleInfo that was passed when MCSymbolizer
1932 // is created and returns the symbol name that matches the ReferenceValue or
1933 // nullptr if none. The ReferenceType is passed in for the IN type of
1934 // reference the instruction is making from the values in defined in the header
1935 // "llvm-c/Disassembler.h". On return the ReferenceType can set to a specific
1936 // Out type and the ReferenceName will also be set which is added as a comment
1937 // to the disassembled instruction.
1940 // If the symbol name is a C++ mangled name then the demangled name is
1941 // returned through ReferenceName and ReferenceType is set to
1942 // LLVMDisassembler_ReferenceType_DeMangled_Name .
1945 // When this is called to get a symbol name for a branch target then the
1946 // ReferenceType will be LLVMDisassembler_ReferenceType_In_Branch and then
1947 // SymbolValue will be looked for in the indirect symbol table to determine if
1948 // it is an address for a symbol stub. If so then the symbol name for that
1949 // stub is returned indirectly through ReferenceName and then ReferenceType is
1950 // set to LLVMDisassembler_ReferenceType_Out_SymbolStub.
1952 // When this is called with an value loaded via a PC relative load then
1953 // ReferenceType will be LLVMDisassembler_ReferenceType_In_PCrel_Load then the
1954 // SymbolValue is checked to be an address of literal pointer, symbol pointer,
1955 // or an Objective-C meta data reference. If so the output ReferenceType is
1956 // set to correspond to that as well as setting the ReferenceName.
1957 const char *SymbolizerSymbolLookUp(void *DisInfo, uint64_t ReferenceValue,
1958 uint64_t *ReferenceType,
1959 uint64_t ReferencePC,
1960 const char **ReferenceName) {
1961 struct DisassembleInfo *info = (struct DisassembleInfo *)DisInfo;
1962 // If no verbose symbolic information is wanted then just return nullptr.
1963 if (info->verbose == false) {
1964 *ReferenceName = nullptr;
1965 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
1969 const char *SymbolName = GuessSymbolName(ReferenceValue, info);
1971 if (*ReferenceType == LLVMDisassembler_ReferenceType_In_Branch) {
1972 *ReferenceName = GuessIndirectSymbol(ReferenceValue, info);
1973 if (*ReferenceName != nullptr) {
1974 method_reference(info, ReferenceType, ReferenceName);
1975 if (*ReferenceType != LLVMDisassembler_ReferenceType_Out_Objc_Message)
1976 *ReferenceType = LLVMDisassembler_ReferenceType_Out_SymbolStub;
1979 if (SymbolName != nullptr && strncmp(SymbolName, "__Z", 3) == 0) {
1980 if (info->demangled_name != nullptr)
1981 free(info->demangled_name);
1983 info->demangled_name =
1984 abi::__cxa_demangle(SymbolName + 1, nullptr, nullptr, &status);
1985 if (info->demangled_name != nullptr) {
1986 *ReferenceName = info->demangled_name;
1987 *ReferenceType = LLVMDisassembler_ReferenceType_DeMangled_Name;
1989 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
1992 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
1993 } else if (*ReferenceType == LLVMDisassembler_ReferenceType_In_PCrel_Load) {
1995 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
1997 method_reference(info, ReferenceType, ReferenceName);
1999 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
2000 // If this is arm64 and the reference is an adrp instruction save the
2001 // instruction, passed in ReferenceValue and the address of the instruction
2002 // for use later if we see and add immediate instruction.
2003 } else if (info->O->getArch() == Triple::aarch64 &&
2004 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADRP) {
2005 info->adrp_inst = ReferenceValue;
2006 info->adrp_addr = ReferencePC;
2007 SymbolName = nullptr;
2008 *ReferenceName = nullptr;
2009 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
2010 // If this is arm64 and reference is an add immediate instruction and we
2012 // seen an adrp instruction just before it and the adrp's Xd register
2014 // this add's Xn register reconstruct the value being referenced and look to
2015 // see if it is a literal pointer. Note the add immediate instruction is
2016 // passed in ReferenceValue.
2017 } else if (info->O->getArch() == Triple::aarch64 &&
2018 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADDXri &&
2019 ReferencePC - 4 == info->adrp_addr &&
2020 (info->adrp_inst & 0x9f000000) == 0x90000000 &&
2021 (info->adrp_inst & 0x1f) == ((ReferenceValue >> 5) & 0x1f)) {
2022 uint32_t addxri_inst;
2023 uint64_t adrp_imm, addxri_imm;
2026 ((info->adrp_inst & 0x00ffffe0) >> 3) | ((info->adrp_inst >> 29) & 0x3);
2027 if (info->adrp_inst & 0x0200000)
2028 adrp_imm |= 0xfffffffffc000000LL;
2030 addxri_inst = ReferenceValue;
2031 addxri_imm = (addxri_inst >> 10) & 0xfff;
2032 if (((addxri_inst >> 22) & 0x3) == 1)
2035 ReferenceValue = (info->adrp_addr & 0xfffffffffffff000LL) +
2036 (adrp_imm << 12) + addxri_imm;
2039 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
2040 if (*ReferenceName == nullptr)
2041 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
2042 // If this is arm64 and the reference is a load register instruction and we
2043 // have seen an adrp instruction just before it and the adrp's Xd register
2044 // matches this add's Xn register reconstruct the value being referenced and
2045 // look to see if it is a literal pointer. Note the load register
2046 // instruction is passed in ReferenceValue.
2047 } else if (info->O->getArch() == Triple::aarch64 &&
2048 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_LDRXui &&
2049 ReferencePC - 4 == info->adrp_addr &&
2050 (info->adrp_inst & 0x9f000000) == 0x90000000 &&
2051 (info->adrp_inst & 0x1f) == ((ReferenceValue >> 5) & 0x1f)) {
2052 uint32_t ldrxui_inst;
2053 uint64_t adrp_imm, ldrxui_imm;
2056 ((info->adrp_inst & 0x00ffffe0) >> 3) | ((info->adrp_inst >> 29) & 0x3);
2057 if (info->adrp_inst & 0x0200000)
2058 adrp_imm |= 0xfffffffffc000000LL;
2060 ldrxui_inst = ReferenceValue;
2061 ldrxui_imm = (ldrxui_inst >> 10) & 0xfff;
2063 ReferenceValue = (info->adrp_addr & 0xfffffffffffff000LL) +
2064 (adrp_imm << 12) + (ldrxui_imm << 3);
2067 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
2068 if (*ReferenceName == nullptr)
2069 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
2071 // If this arm64 and is an load register (PC-relative) instruction the
2072 // ReferenceValue is the PC plus the immediate value.
2073 else if (info->O->getArch() == Triple::aarch64 &&
2074 (*ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_LDRXl ||
2075 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADR)) {
2077 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
2078 if (*ReferenceName == nullptr)
2079 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
2082 else if (SymbolName != nullptr && strncmp(SymbolName, "__Z", 3) == 0) {
2083 if (info->demangled_name != nullptr)
2084 free(info->demangled_name);
2086 info->demangled_name =
2087 abi::__cxa_demangle(SymbolName + 1, nullptr, nullptr, &status);
2088 if (info->demangled_name != nullptr) {
2089 *ReferenceName = info->demangled_name;
2090 *ReferenceType = LLVMDisassembler_ReferenceType_DeMangled_Name;
2095 *ReferenceName = nullptr;
2096 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
2102 /// \brief Emits the comments that are stored in the CommentStream.
2103 /// Each comment in the CommentStream must end with a newline.
2104 static void emitComments(raw_svector_ostream &CommentStream,
2105 SmallString<128> &CommentsToEmit,
2106 formatted_raw_ostream &FormattedOS,
2107 const MCAsmInfo &MAI) {
2108 // Flush the stream before taking its content.
2109 CommentStream.flush();
2110 StringRef Comments = CommentsToEmit.str();
2111 // Get the default information for printing a comment.
2112 const char *CommentBegin = MAI.getCommentString();
2113 unsigned CommentColumn = MAI.getCommentColumn();
2114 bool IsFirst = true;
2115 while (!Comments.empty()) {
2117 FormattedOS << '\n';
2118 // Emit a line of comments.
2119 FormattedOS.PadToColumn(CommentColumn);
2120 size_t Position = Comments.find('\n');
2121 FormattedOS << CommentBegin << ' ' << Comments.substr(0, Position);
2122 // Move after the newline character.
2123 Comments = Comments.substr(Position + 1);
2126 FormattedOS.flush();
2128 // Tell the comment stream that the vector changed underneath it.
2129 CommentsToEmit.clear();
2130 CommentStream.resync();
2133 static void DisassembleMachO(StringRef Filename, MachOObjectFile *MachOOF) {
2134 const char *McpuDefault = nullptr;
2135 const Target *ThumbTarget = nullptr;
2136 const Target *TheTarget = GetTarget(MachOOF, &McpuDefault, &ThumbTarget);
2138 // GetTarget prints out stuff.
2141 if (MCPU.empty() && McpuDefault)
2144 std::unique_ptr<const MCInstrInfo> InstrInfo(TheTarget->createMCInstrInfo());
2145 std::unique_ptr<const MCInstrInfo> ThumbInstrInfo;
2147 ThumbInstrInfo.reset(ThumbTarget->createMCInstrInfo());
2149 // Package up features to be passed to target/subtarget
2150 std::string FeaturesStr;
2151 if (MAttrs.size()) {
2152 SubtargetFeatures Features;
2153 for (unsigned i = 0; i != MAttrs.size(); ++i)
2154 Features.AddFeature(MAttrs[i]);
2155 FeaturesStr = Features.getString();
2158 // Set up disassembler.
2159 std::unique_ptr<const MCRegisterInfo> MRI(
2160 TheTarget->createMCRegInfo(TripleName));
2161 std::unique_ptr<const MCAsmInfo> AsmInfo(
2162 TheTarget->createMCAsmInfo(*MRI, TripleName));
2163 std::unique_ptr<const MCSubtargetInfo> STI(
2164 TheTarget->createMCSubtargetInfo(TripleName, MCPU, FeaturesStr));
2165 MCContext Ctx(AsmInfo.get(), MRI.get(), nullptr);
2166 std::unique_ptr<MCDisassembler> DisAsm(
2167 TheTarget->createMCDisassembler(*STI, Ctx));
2168 std::unique_ptr<MCSymbolizer> Symbolizer;
2169 struct DisassembleInfo SymbolizerInfo;
2170 std::unique_ptr<MCRelocationInfo> RelInfo(
2171 TheTarget->createMCRelocationInfo(TripleName, Ctx));
2173 Symbolizer.reset(TheTarget->createMCSymbolizer(
2174 TripleName, SymbolizerGetOpInfo, SymbolizerSymbolLookUp,
2175 &SymbolizerInfo, &Ctx, RelInfo.release()));
2176 DisAsm->setSymbolizer(std::move(Symbolizer));
2178 int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
2179 std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
2180 AsmPrinterVariant, *AsmInfo, *InstrInfo, *MRI, *STI));
2181 // Set the display preference for hex vs. decimal immediates.
2182 IP->setPrintImmHex(PrintImmHex);
2183 // Comment stream and backing vector.
2184 SmallString<128> CommentsToEmit;
2185 raw_svector_ostream CommentStream(CommentsToEmit);
2186 // FIXME: Setting the CommentStream in the InstPrinter is problematic in that
2187 // if it is done then arm64 comments for string literals don't get printed
2188 // and some constant get printed instead and not setting it causes intel
2189 // (32-bit and 64-bit) comments printed with different spacing before the
2190 // comment causing different diffs with the 'C' disassembler library API.
2191 // IP->setCommentStream(CommentStream);
2193 if (!AsmInfo || !STI || !DisAsm || !IP) {
2194 errs() << "error: couldn't initialize disassembler for target "
2195 << TripleName << '\n';
2199 // Set up thumb disassembler.
2200 std::unique_ptr<const MCRegisterInfo> ThumbMRI;
2201 std::unique_ptr<const MCAsmInfo> ThumbAsmInfo;
2202 std::unique_ptr<const MCSubtargetInfo> ThumbSTI;
2203 std::unique_ptr<MCDisassembler> ThumbDisAsm;
2204 std::unique_ptr<MCInstPrinter> ThumbIP;
2205 std::unique_ptr<MCContext> ThumbCtx;
2206 std::unique_ptr<MCSymbolizer> ThumbSymbolizer;
2207 struct DisassembleInfo ThumbSymbolizerInfo;
2208 std::unique_ptr<MCRelocationInfo> ThumbRelInfo;
2210 ThumbMRI.reset(ThumbTarget->createMCRegInfo(ThumbTripleName));
2212 ThumbTarget->createMCAsmInfo(*ThumbMRI, ThumbTripleName));
2214 ThumbTarget->createMCSubtargetInfo(ThumbTripleName, MCPU, FeaturesStr));
2215 ThumbCtx.reset(new MCContext(ThumbAsmInfo.get(), ThumbMRI.get(), nullptr));
2216 ThumbDisAsm.reset(ThumbTarget->createMCDisassembler(*ThumbSTI, *ThumbCtx));
2217 MCContext *PtrThumbCtx = ThumbCtx.get();
2219 ThumbTarget->createMCRelocationInfo(ThumbTripleName, *PtrThumbCtx));
2221 ThumbSymbolizer.reset(ThumbTarget->createMCSymbolizer(
2222 ThumbTripleName, SymbolizerGetOpInfo, SymbolizerSymbolLookUp,
2223 &ThumbSymbolizerInfo, PtrThumbCtx, ThumbRelInfo.release()));
2224 ThumbDisAsm->setSymbolizer(std::move(ThumbSymbolizer));
2226 int ThumbAsmPrinterVariant = ThumbAsmInfo->getAssemblerDialect();
2227 ThumbIP.reset(ThumbTarget->createMCInstPrinter(
2228 ThumbAsmPrinterVariant, *ThumbAsmInfo, *ThumbInstrInfo, *ThumbMRI,
2230 // Set the display preference for hex vs. decimal immediates.
2231 ThumbIP->setPrintImmHex(PrintImmHex);
2234 if (ThumbTarget && (!ThumbAsmInfo || !ThumbSTI || !ThumbDisAsm || !ThumbIP)) {
2235 errs() << "error: couldn't initialize disassembler for target "
2236 << ThumbTripleName << '\n';
2240 MachO::mach_header Header = MachOOF->getHeader();
2242 // FIXME: Using the -cfg command line option, this code used to be able to
2243 // annotate relocations with the referenced symbol's name, and if this was
2244 // inside a __[cf]string section, the data it points to. This is now replaced
2245 // by the upcoming MCSymbolizer, which needs the appropriate setup done above.
2246 std::vector<SectionRef> Sections;
2247 std::vector<SymbolRef> Symbols;
2248 SmallVector<uint64_t, 8> FoundFns;
2249 uint64_t BaseSegmentAddress;
2251 getSectionsAndSymbols(Header, MachOOF, Sections, Symbols, FoundFns,
2252 BaseSegmentAddress);
2254 // Sort the symbols by address, just in case they didn't come in that way.
2255 std::sort(Symbols.begin(), Symbols.end(), SymbolSorter());
2257 // Build a data in code table that is sorted on by the address of each entry.
2258 uint64_t BaseAddress = 0;
2259 if (Header.filetype == MachO::MH_OBJECT)
2260 BaseAddress = Sections[0].getAddress();
2262 BaseAddress = BaseSegmentAddress;
2264 for (dice_iterator DI = MachOOF->begin_dices(), DE = MachOOF->end_dices();
2267 DI->getOffset(Offset);
2268 Dices.push_back(std::make_pair(BaseAddress + Offset, *DI));
2270 array_pod_sort(Dices.begin(), Dices.end());
2273 raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls();
2275 raw_ostream &DebugOut = nulls();
2278 std::unique_ptr<DIContext> diContext;
2279 ObjectFile *DbgObj = MachOOF;
2280 // Try to find debug info and set up the DIContext for it.
2282 // A separate DSym file path was specified, parse it as a macho file,
2283 // get the sections and supply it to the section name parsing machinery.
2284 if (!DSYMFile.empty()) {
2285 ErrorOr<std::unique_ptr<MemoryBuffer>> BufOrErr =
2286 MemoryBuffer::getFileOrSTDIN(DSYMFile);
2287 if (std::error_code EC = BufOrErr.getError()) {
2288 errs() << "llvm-objdump: " << Filename << ": " << EC.message() << '\n';
2292 ObjectFile::createMachOObjectFile(BufOrErr.get()->getMemBufferRef())
2297 // Setup the DIContext
2298 diContext.reset(DIContext::getDWARFContext(*DbgObj));
2301 // TODO: For now this only disassembles the (__TEXT,__text) section (see the
2302 // checks in the code below at the top of this loop). It should allow a
2303 // darwin otool(1) like -s option to disassemble any named segment & section
2304 // that is marked as containing instructions with the attributes
2305 // S_ATTR_PURE_INSTRUCTIONS or S_ATTR_SOME_INSTRUCTIONS in the flags field of
2306 // the section structure.
2307 outs() << "(__TEXT,__text) section\n";
2309 for (unsigned SectIdx = 0; SectIdx != Sections.size(); SectIdx++) {
2311 bool SectIsText = Sections[SectIdx].isText();
2312 if (SectIsText == false)
2316 if (Sections[SectIdx].getName(SectName) || SectName != "__text")
2317 continue; // Skip non-text sections
2319 DataRefImpl DR = Sections[SectIdx].getRawDataRefImpl();
2321 StringRef SegmentName = MachOOF->getSectionFinalSegmentName(DR);
2322 if (SegmentName != "__TEXT")
2326 Sections[SectIdx].getContents(BytesStr);
2327 ArrayRef<uint8_t> Bytes(reinterpret_cast<const uint8_t *>(BytesStr.data()),
2329 uint64_t SectAddress = Sections[SectIdx].getAddress();
2331 bool symbolTableWorked = false;
2333 // Parse relocations.
2334 std::vector<std::pair<uint64_t, SymbolRef>> Relocs;
2335 for (const RelocationRef &Reloc : Sections[SectIdx].relocations()) {
2336 uint64_t RelocOffset;
2337 Reloc.getOffset(RelocOffset);
2338 uint64_t SectionAddress = Sections[SectIdx].getAddress();
2339 RelocOffset -= SectionAddress;
2341 symbol_iterator RelocSym = Reloc.getSymbol();
2343 Relocs.push_back(std::make_pair(RelocOffset, *RelocSym));
2345 array_pod_sort(Relocs.begin(), Relocs.end());
2347 // Create a map of symbol addresses to symbol names for use by
2348 // the SymbolizerSymbolLookUp() routine.
2349 SymbolAddressMap AddrMap;
2350 for (const SymbolRef &Symbol : MachOOF->symbols()) {
2353 if (ST == SymbolRef::ST_Function || ST == SymbolRef::ST_Data ||
2354 ST == SymbolRef::ST_Other) {
2356 Symbol.getAddress(Address);
2358 Symbol.getName(SymName);
2359 AddrMap[Address] = SymName;
2362 // Set up the block of info used by the Symbolizer call backs.
2363 SymbolizerInfo.verbose = true;
2364 SymbolizerInfo.O = MachOOF;
2365 SymbolizerInfo.S = Sections[SectIdx];
2366 SymbolizerInfo.AddrMap = &AddrMap;
2367 SymbolizerInfo.Sections = &Sections;
2368 SymbolizerInfo.class_name = nullptr;
2369 SymbolizerInfo.selector_name = nullptr;
2370 SymbolizerInfo.method = nullptr;
2371 SymbolizerInfo.demangled_name = nullptr;
2372 SymbolizerInfo.bindtable = nullptr;
2373 SymbolizerInfo.adrp_addr = 0;
2374 SymbolizerInfo.adrp_inst = 0;
2375 // Same for the ThumbSymbolizer
2376 ThumbSymbolizerInfo.verbose = true;
2377 ThumbSymbolizerInfo.O = MachOOF;
2378 ThumbSymbolizerInfo.S = Sections[SectIdx];
2379 ThumbSymbolizerInfo.AddrMap = &AddrMap;
2380 ThumbSymbolizerInfo.Sections = &Sections;
2381 ThumbSymbolizerInfo.class_name = nullptr;
2382 ThumbSymbolizerInfo.selector_name = nullptr;
2383 ThumbSymbolizerInfo.method = nullptr;
2384 ThumbSymbolizerInfo.demangled_name = nullptr;
2385 ThumbSymbolizerInfo.bindtable = nullptr;
2386 ThumbSymbolizerInfo.adrp_addr = 0;
2387 ThumbSymbolizerInfo.adrp_inst = 0;
2389 // Disassemble symbol by symbol.
2390 for (unsigned SymIdx = 0; SymIdx != Symbols.size(); SymIdx++) {
2392 Symbols[SymIdx].getName(SymName);
2395 Symbols[SymIdx].getType(ST);
2396 if (ST != SymbolRef::ST_Function)
2399 // Make sure the symbol is defined in this section.
2400 bool containsSym = Sections[SectIdx].containsSymbol(Symbols[SymIdx]);
2404 // Start at the address of the symbol relative to the section's address.
2406 uint64_t SectionAddress = Sections[SectIdx].getAddress();
2407 Symbols[SymIdx].getAddress(Start);
2408 Start -= SectionAddress;
2410 // Stop disassembling either at the beginning of the next symbol or at
2411 // the end of the section.
2412 bool containsNextSym = false;
2413 uint64_t NextSym = 0;
2414 uint64_t NextSymIdx = SymIdx + 1;
2415 while (Symbols.size() > NextSymIdx) {
2416 SymbolRef::Type NextSymType;
2417 Symbols[NextSymIdx].getType(NextSymType);
2418 if (NextSymType == SymbolRef::ST_Function) {
2420 Sections[SectIdx].containsSymbol(Symbols[NextSymIdx]);
2421 Symbols[NextSymIdx].getAddress(NextSym);
2422 NextSym -= SectionAddress;
2428 uint64_t SectSize = Sections[SectIdx].getSize();
2429 uint64_t End = containsNextSym ? NextSym : SectSize;
2432 symbolTableWorked = true;
2434 DataRefImpl Symb = Symbols[SymIdx].getRawDataRefImpl();
2436 (MachOOF->getSymbolFlags(Symb) & SymbolRef::SF_Thumb) && ThumbTarget;
2438 outs() << SymName << ":\n";
2439 DILineInfo lastLine;
2440 for (uint64_t Index = Start; Index < End; Index += Size) {
2443 uint64_t PC = SectAddress + Index;
2444 if (FullLeadingAddr) {
2445 if (MachOOF->is64Bit())
2446 outs() << format("%016" PRIx64, PC);
2448 outs() << format("%08" PRIx64, PC);
2450 outs() << format("%8" PRIx64 ":", PC);
2455 // Check the data in code table here to see if this is data not an
2456 // instruction to be disassembled.
2458 Dice.push_back(std::make_pair(PC, DiceRef()));
2459 dice_table_iterator DTI =
2460 std::search(Dices.begin(), Dices.end(), Dice.begin(), Dice.end(),
2461 compareDiceTableEntries);
2462 if (DTI != Dices.end()) {
2464 DTI->second.getLength(Length);
2466 DTI->second.getKind(Kind);
2467 Size = DumpDataInCode(reinterpret_cast<const char *>(Bytes.data()) +
2470 if ((Kind == MachO::DICE_KIND_JUMP_TABLE8) &&
2471 (PC == (DTI->first + Length - 1)) && (Length & 1))
2476 SmallVector<char, 64> AnnotationsBytes;
2477 raw_svector_ostream Annotations(AnnotationsBytes);
2481 gotInst = ThumbDisAsm->getInstruction(Inst, Size, Bytes.slice(Index),
2482 PC, DebugOut, Annotations);
2484 gotInst = DisAsm->getInstruction(Inst, Size, Bytes.slice(Index), PC,
2485 DebugOut, Annotations);
2487 if (!NoShowRawInsn) {
2488 DumpBytes(StringRef(
2489 reinterpret_cast<const char *>(Bytes.data()) + Index, Size));
2491 formatted_raw_ostream FormattedOS(outs());
2492 Annotations.flush();
2493 StringRef AnnotationsStr = Annotations.str();
2495 ThumbIP->printInst(&Inst, FormattedOS, AnnotationsStr);
2497 IP->printInst(&Inst, FormattedOS, AnnotationsStr);
2498 emitComments(CommentStream, CommentsToEmit, FormattedOS, *AsmInfo);
2500 // Print debug info.
2502 DILineInfo dli = diContext->getLineInfoForAddress(PC);
2503 // Print valid line info if it changed.
2504 if (dli != lastLine && dli.Line != 0)
2505 outs() << "\t## " << dli.FileName << ':' << dli.Line << ':'
2511 unsigned int Arch = MachOOF->getArch();
2512 if (Arch == Triple::x86_64 || Arch == Triple::x86) {
2513 outs() << format("\t.byte 0x%02x #bad opcode\n",
2514 *(Bytes.data() + Index) & 0xff);
2515 Size = 1; // skip exactly one illegible byte and move on.
2516 } else if (Arch == Triple::aarch64) {
2517 uint32_t opcode = (*(Bytes.data() + Index) & 0xff) |
2518 (*(Bytes.data() + Index + 1) & 0xff) << 8 |
2519 (*(Bytes.data() + Index + 2) & 0xff) << 16 |
2520 (*(Bytes.data() + Index + 3) & 0xff) << 24;
2521 outs() << format("\t.long\t0x%08x\n", opcode);
2524 errs() << "llvm-objdump: warning: invalid instruction encoding\n";
2526 Size = 1; // skip illegible bytes
2531 if (!symbolTableWorked) {
2532 // Reading the symbol table didn't work, disassemble the whole section.
2533 uint64_t SectAddress = Sections[SectIdx].getAddress();
2534 uint64_t SectSize = Sections[SectIdx].getSize();
2536 for (uint64_t Index = 0; Index < SectSize; Index += InstSize) {
2539 uint64_t PC = SectAddress + Index;
2540 if (DisAsm->getInstruction(Inst, InstSize, Bytes.slice(Index), PC,
2541 DebugOut, nulls())) {
2542 if (FullLeadingAddr) {
2543 if (MachOOF->is64Bit())
2544 outs() << format("%016" PRIx64, PC);
2546 outs() << format("%08" PRIx64, PC);
2548 outs() << format("%8" PRIx64 ":", PC);
2550 if (!NoShowRawInsn) {
2553 StringRef(reinterpret_cast<const char *>(Bytes.data()) + Index,
2556 IP->printInst(&Inst, outs(), "");
2559 unsigned int Arch = MachOOF->getArch();
2560 if (Arch == Triple::x86_64 || Arch == Triple::x86) {
2561 outs() << format("\t.byte 0x%02x #bad opcode\n",
2562 *(Bytes.data() + Index) & 0xff);
2563 InstSize = 1; // skip exactly one illegible byte and move on.
2565 errs() << "llvm-objdump: warning: invalid instruction encoding\n";
2567 InstSize = 1; // skip illegible bytes
2572 // The TripleName's need to be reset if we are called again for a different
2575 ThumbTripleName = "";
2577 if (SymbolizerInfo.method != nullptr)
2578 free(SymbolizerInfo.method);
2579 if (SymbolizerInfo.demangled_name != nullptr)
2580 free(SymbolizerInfo.demangled_name);
2581 if (SymbolizerInfo.bindtable != nullptr)
2582 delete SymbolizerInfo.bindtable;
2583 if (ThumbSymbolizerInfo.method != nullptr)
2584 free(ThumbSymbolizerInfo.method);
2585 if (ThumbSymbolizerInfo.demangled_name != nullptr)
2586 free(ThumbSymbolizerInfo.demangled_name);
2587 if (ThumbSymbolizerInfo.bindtable != nullptr)
2588 delete ThumbSymbolizerInfo.bindtable;
2592 //===----------------------------------------------------------------------===//
2593 // __compact_unwind section dumping
2594 //===----------------------------------------------------------------------===//
2598 template <typename T> static uint64_t readNext(const char *&Buf) {
2599 using llvm::support::little;
2600 using llvm::support::unaligned;
2602 uint64_t Val = support::endian::read<T, little, unaligned>(Buf);
2607 struct CompactUnwindEntry {
2608 uint32_t OffsetInSection;
2610 uint64_t FunctionAddr;
2612 uint32_t CompactEncoding;
2613 uint64_t PersonalityAddr;
2616 RelocationRef FunctionReloc;
2617 RelocationRef PersonalityReloc;
2618 RelocationRef LSDAReloc;
2620 CompactUnwindEntry(StringRef Contents, unsigned Offset, bool Is64)
2621 : OffsetInSection(Offset) {
2623 read<uint64_t>(Contents.data() + Offset);
2625 read<uint32_t>(Contents.data() + Offset);
2629 template <typename UIntPtr> void read(const char *Buf) {
2630 FunctionAddr = readNext<UIntPtr>(Buf);
2631 Length = readNext<uint32_t>(Buf);
2632 CompactEncoding = readNext<uint32_t>(Buf);
2633 PersonalityAddr = readNext<UIntPtr>(Buf);
2634 LSDAAddr = readNext<UIntPtr>(Buf);
2639 /// Given a relocation from __compact_unwind, consisting of the RelocationRef
2640 /// and data being relocated, determine the best base Name and Addend to use for
2641 /// display purposes.
2643 /// 1. An Extern relocation will directly reference a symbol (and the data is
2644 /// then already an addend), so use that.
2645 /// 2. Otherwise the data is an offset in the object file's layout; try to find
2646 // a symbol before it in the same section, and use the offset from there.
2647 /// 3. Finally, if all that fails, fall back to an offset from the start of the
2648 /// referenced section.
2649 static void findUnwindRelocNameAddend(const MachOObjectFile *Obj,
2650 std::map<uint64_t, SymbolRef> &Symbols,
2651 const RelocationRef &Reloc, uint64_t Addr,
2652 StringRef &Name, uint64_t &Addend) {
2653 if (Reloc.getSymbol() != Obj->symbol_end()) {
2654 Reloc.getSymbol()->getName(Name);
2659 auto RE = Obj->getRelocation(Reloc.getRawDataRefImpl());
2660 SectionRef RelocSection = Obj->getRelocationSection(RE);
2662 uint64_t SectionAddr = RelocSection.getAddress();
2664 auto Sym = Symbols.upper_bound(Addr);
2665 if (Sym == Symbols.begin()) {
2666 // The first symbol in the object is after this reference, the best we can
2667 // do is section-relative notation.
2668 RelocSection.getName(Name);
2669 Addend = Addr - SectionAddr;
2673 // Go back one so that SymbolAddress <= Addr.
2676 section_iterator SymSection = Obj->section_end();
2677 Sym->second.getSection(SymSection);
2678 if (RelocSection == *SymSection) {
2679 // There's a valid symbol in the same section before this reference.
2680 Sym->second.getName(Name);
2681 Addend = Addr - Sym->first;
2685 // There is a symbol before this reference, but it's in a different
2686 // section. Probably not helpful to mention it, so use the section name.
2687 RelocSection.getName(Name);
2688 Addend = Addr - SectionAddr;
2691 static void printUnwindRelocDest(const MachOObjectFile *Obj,
2692 std::map<uint64_t, SymbolRef> &Symbols,
2693 const RelocationRef &Reloc, uint64_t Addr) {
2697 if (!Reloc.getObjectFile())
2700 findUnwindRelocNameAddend(Obj, Symbols, Reloc, Addr, Name, Addend);
2704 outs() << " + " << format("0x%" PRIx64, Addend);
2708 printMachOCompactUnwindSection(const MachOObjectFile *Obj,
2709 std::map<uint64_t, SymbolRef> &Symbols,
2710 const SectionRef &CompactUnwind) {
2712 assert(Obj->isLittleEndian() &&
2713 "There should not be a big-endian .o with __compact_unwind");
2715 bool Is64 = Obj->is64Bit();
2716 uint32_t PointerSize = Is64 ? sizeof(uint64_t) : sizeof(uint32_t);
2717 uint32_t EntrySize = 3 * PointerSize + 2 * sizeof(uint32_t);
2720 CompactUnwind.getContents(Contents);
2722 SmallVector<CompactUnwindEntry, 4> CompactUnwinds;
2724 // First populate the initial raw offsets, encodings and so on from the entry.
2725 for (unsigned Offset = 0; Offset < Contents.size(); Offset += EntrySize) {
2726 CompactUnwindEntry Entry(Contents.data(), Offset, Is64);
2727 CompactUnwinds.push_back(Entry);
2730 // Next we need to look at the relocations to find out what objects are
2731 // actually being referred to.
2732 for (const RelocationRef &Reloc : CompactUnwind.relocations()) {
2733 uint64_t RelocAddress;
2734 Reloc.getOffset(RelocAddress);
2736 uint32_t EntryIdx = RelocAddress / EntrySize;
2737 uint32_t OffsetInEntry = RelocAddress - EntryIdx * EntrySize;
2738 CompactUnwindEntry &Entry = CompactUnwinds[EntryIdx];
2740 if (OffsetInEntry == 0)
2741 Entry.FunctionReloc = Reloc;
2742 else if (OffsetInEntry == PointerSize + 2 * sizeof(uint32_t))
2743 Entry.PersonalityReloc = Reloc;
2744 else if (OffsetInEntry == 2 * PointerSize + 2 * sizeof(uint32_t))
2745 Entry.LSDAReloc = Reloc;
2747 llvm_unreachable("Unexpected relocation in __compact_unwind section");
2750 // Finally, we're ready to print the data we've gathered.
2751 outs() << "Contents of __compact_unwind section:\n";
2752 for (auto &Entry : CompactUnwinds) {
2753 outs() << " Entry at offset "
2754 << format("0x%" PRIx32, Entry.OffsetInSection) << ":\n";
2756 // 1. Start of the region this entry applies to.
2757 outs() << " start: " << format("0x%" PRIx64,
2758 Entry.FunctionAddr) << ' ';
2759 printUnwindRelocDest(Obj, Symbols, Entry.FunctionReloc, Entry.FunctionAddr);
2762 // 2. Length of the region this entry applies to.
2763 outs() << " length: " << format("0x%" PRIx32, Entry.Length)
2765 // 3. The 32-bit compact encoding.
2766 outs() << " compact encoding: "
2767 << format("0x%08" PRIx32, Entry.CompactEncoding) << '\n';
2769 // 4. The personality function, if present.
2770 if (Entry.PersonalityReloc.getObjectFile()) {
2771 outs() << " personality function: "
2772 << format("0x%" PRIx64, Entry.PersonalityAddr) << ' ';
2773 printUnwindRelocDest(Obj, Symbols, Entry.PersonalityReloc,
2774 Entry.PersonalityAddr);
2778 // 5. This entry's language-specific data area.
2779 if (Entry.LSDAReloc.getObjectFile()) {
2780 outs() << " LSDA: " << format("0x%" PRIx64,
2781 Entry.LSDAAddr) << ' ';
2782 printUnwindRelocDest(Obj, Symbols, Entry.LSDAReloc, Entry.LSDAAddr);
2788 //===----------------------------------------------------------------------===//
2789 // __unwind_info section dumping
2790 //===----------------------------------------------------------------------===//
2792 static void printRegularSecondLevelUnwindPage(const char *PageStart) {
2793 const char *Pos = PageStart;
2794 uint32_t Kind = readNext<uint32_t>(Pos);
2796 assert(Kind == 2 && "kind for a regular 2nd level index should be 2");
2798 uint16_t EntriesStart = readNext<uint16_t>(Pos);
2799 uint16_t NumEntries = readNext<uint16_t>(Pos);
2801 Pos = PageStart + EntriesStart;
2802 for (unsigned i = 0; i < NumEntries; ++i) {
2803 uint32_t FunctionOffset = readNext<uint32_t>(Pos);
2804 uint32_t Encoding = readNext<uint32_t>(Pos);
2806 outs() << " [" << i << "]: "
2807 << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
2809 << "encoding=" << format("0x%08" PRIx32, Encoding) << '\n';
2813 static void printCompressedSecondLevelUnwindPage(
2814 const char *PageStart, uint32_t FunctionBase,
2815 const SmallVectorImpl<uint32_t> &CommonEncodings) {
2816 const char *Pos = PageStart;
2817 uint32_t Kind = readNext<uint32_t>(Pos);
2819 assert(Kind == 3 && "kind for a compressed 2nd level index should be 3");
2821 uint16_t EntriesStart = readNext<uint16_t>(Pos);
2822 uint16_t NumEntries = readNext<uint16_t>(Pos);
2824 uint16_t EncodingsStart = readNext<uint16_t>(Pos);
2825 readNext<uint16_t>(Pos);
2826 const auto *PageEncodings = reinterpret_cast<const support::ulittle32_t *>(
2827 PageStart + EncodingsStart);
2829 Pos = PageStart + EntriesStart;
2830 for (unsigned i = 0; i < NumEntries; ++i) {
2831 uint32_t Entry = readNext<uint32_t>(Pos);
2832 uint32_t FunctionOffset = FunctionBase + (Entry & 0xffffff);
2833 uint32_t EncodingIdx = Entry >> 24;
2836 if (EncodingIdx < CommonEncodings.size())
2837 Encoding = CommonEncodings[EncodingIdx];
2839 Encoding = PageEncodings[EncodingIdx - CommonEncodings.size()];
2841 outs() << " [" << i << "]: "
2842 << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
2844 << "encoding[" << EncodingIdx
2845 << "]=" << format("0x%08" PRIx32, Encoding) << '\n';
2849 static void printMachOUnwindInfoSection(const MachOObjectFile *Obj,
2850 std::map<uint64_t, SymbolRef> &Symbols,
2851 const SectionRef &UnwindInfo) {
2853 assert(Obj->isLittleEndian() &&
2854 "There should not be a big-endian .o with __unwind_info");
2856 outs() << "Contents of __unwind_info section:\n";
2859 UnwindInfo.getContents(Contents);
2860 const char *Pos = Contents.data();
2862 //===----------------------------------
2864 //===----------------------------------
2866 uint32_t Version = readNext<uint32_t>(Pos);
2867 outs() << " Version: "
2868 << format("0x%" PRIx32, Version) << '\n';
2869 assert(Version == 1 && "only understand version 1");
2871 uint32_t CommonEncodingsStart = readNext<uint32_t>(Pos);
2872 outs() << " Common encodings array section offset: "
2873 << format("0x%" PRIx32, CommonEncodingsStart) << '\n';
2874 uint32_t NumCommonEncodings = readNext<uint32_t>(Pos);
2875 outs() << " Number of common encodings in array: "
2876 << format("0x%" PRIx32, NumCommonEncodings) << '\n';
2878 uint32_t PersonalitiesStart = readNext<uint32_t>(Pos);
2879 outs() << " Personality function array section offset: "
2880 << format("0x%" PRIx32, PersonalitiesStart) << '\n';
2881 uint32_t NumPersonalities = readNext<uint32_t>(Pos);
2882 outs() << " Number of personality functions in array: "
2883 << format("0x%" PRIx32, NumPersonalities) << '\n';
2885 uint32_t IndicesStart = readNext<uint32_t>(Pos);
2886 outs() << " Index array section offset: "
2887 << format("0x%" PRIx32, IndicesStart) << '\n';
2888 uint32_t NumIndices = readNext<uint32_t>(Pos);
2889 outs() << " Number of indices in array: "
2890 << format("0x%" PRIx32, NumIndices) << '\n';
2892 //===----------------------------------
2893 // A shared list of common encodings
2894 //===----------------------------------
2896 // These occupy indices in the range [0, N] whenever an encoding is referenced
2897 // from a compressed 2nd level index table. In practice the linker only
2898 // creates ~128 of these, so that indices are available to embed encodings in
2899 // the 2nd level index.
2901 SmallVector<uint32_t, 64> CommonEncodings;
2902 outs() << " Common encodings: (count = " << NumCommonEncodings << ")\n";
2903 Pos = Contents.data() + CommonEncodingsStart;
2904 for (unsigned i = 0; i < NumCommonEncodings; ++i) {
2905 uint32_t Encoding = readNext<uint32_t>(Pos);
2906 CommonEncodings.push_back(Encoding);
2908 outs() << " encoding[" << i << "]: " << format("0x%08" PRIx32, Encoding)
2912 //===----------------------------------
2913 // Personality functions used in this executable
2914 //===----------------------------------
2916 // There should be only a handful of these (one per source language,
2917 // roughly). Particularly since they only get 2 bits in the compact encoding.
2919 outs() << " Personality functions: (count = " << NumPersonalities << ")\n";
2920 Pos = Contents.data() + PersonalitiesStart;
2921 for (unsigned i = 0; i < NumPersonalities; ++i) {
2922 uint32_t PersonalityFn = readNext<uint32_t>(Pos);
2923 outs() << " personality[" << i + 1
2924 << "]: " << format("0x%08" PRIx32, PersonalityFn) << '\n';
2927 //===----------------------------------
2928 // The level 1 index entries
2929 //===----------------------------------
2931 // These specify an approximate place to start searching for the more detailed
2932 // information, sorted by PC.
2935 uint32_t FunctionOffset;
2936 uint32_t SecondLevelPageStart;
2940 SmallVector<IndexEntry, 4> IndexEntries;
2942 outs() << " Top level indices: (count = " << NumIndices << ")\n";
2943 Pos = Contents.data() + IndicesStart;
2944 for (unsigned i = 0; i < NumIndices; ++i) {
2947 Entry.FunctionOffset = readNext<uint32_t>(Pos);
2948 Entry.SecondLevelPageStart = readNext<uint32_t>(Pos);
2949 Entry.LSDAStart = readNext<uint32_t>(Pos);
2950 IndexEntries.push_back(Entry);
2952 outs() << " [" << i << "]: "
2953 << "function offset=" << format("0x%08" PRIx32, Entry.FunctionOffset)
2955 << "2nd level page offset="
2956 << format("0x%08" PRIx32, Entry.SecondLevelPageStart) << ", "
2957 << "LSDA offset=" << format("0x%08" PRIx32, Entry.LSDAStart) << '\n';
2960 //===----------------------------------
2961 // Next come the LSDA tables
2962 //===----------------------------------
2964 // The LSDA layout is rather implicit: it's a contiguous array of entries from
2965 // the first top-level index's LSDAOffset to the last (sentinel).
2967 outs() << " LSDA descriptors:\n";
2968 Pos = Contents.data() + IndexEntries[0].LSDAStart;
2969 int NumLSDAs = (IndexEntries.back().LSDAStart - IndexEntries[0].LSDAStart) /
2970 (2 * sizeof(uint32_t));
2971 for (int i = 0; i < NumLSDAs; ++i) {
2972 uint32_t FunctionOffset = readNext<uint32_t>(Pos);
2973 uint32_t LSDAOffset = readNext<uint32_t>(Pos);
2974 outs() << " [" << i << "]: "
2975 << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
2977 << "LSDA offset=" << format("0x%08" PRIx32, LSDAOffset) << '\n';
2980 //===----------------------------------
2981 // Finally, the 2nd level indices
2982 //===----------------------------------
2984 // Generally these are 4K in size, and have 2 possible forms:
2985 // + Regular stores up to 511 entries with disparate encodings
2986 // + Compressed stores up to 1021 entries if few enough compact encoding
2988 outs() << " Second level indices:\n";
2989 for (unsigned i = 0; i < IndexEntries.size() - 1; ++i) {
2990 // The final sentinel top-level index has no associated 2nd level page
2991 if (IndexEntries[i].SecondLevelPageStart == 0)
2994 outs() << " Second level index[" << i << "]: "
2995 << "offset in section="
2996 << format("0x%08" PRIx32, IndexEntries[i].SecondLevelPageStart)
2998 << "base function offset="
2999 << format("0x%08" PRIx32, IndexEntries[i].FunctionOffset) << '\n';
3001 Pos = Contents.data() + IndexEntries[i].SecondLevelPageStart;
3002 uint32_t Kind = *reinterpret_cast<const support::ulittle32_t *>(Pos);
3004 printRegularSecondLevelUnwindPage(Pos);
3006 printCompressedSecondLevelUnwindPage(Pos, IndexEntries[i].FunctionOffset,
3009 llvm_unreachable("Do not know how to print this kind of 2nd level page");
3013 void llvm::printMachOUnwindInfo(const MachOObjectFile *Obj) {
3014 std::map<uint64_t, SymbolRef> Symbols;
3015 for (const SymbolRef &SymRef : Obj->symbols()) {
3016 // Discard any undefined or absolute symbols. They're not going to take part
3017 // in the convenience lookup for unwind info and just take up resources.
3018 section_iterator Section = Obj->section_end();
3019 SymRef.getSection(Section);
3020 if (Section == Obj->section_end())
3024 SymRef.getAddress(Addr);
3025 Symbols.insert(std::make_pair(Addr, SymRef));
3028 for (const SectionRef &Section : Obj->sections()) {
3030 Section.getName(SectName);
3031 if (SectName == "__compact_unwind")
3032 printMachOCompactUnwindSection(Obj, Symbols, Section);
3033 else if (SectName == "__unwind_info")
3034 printMachOUnwindInfoSection(Obj, Symbols, Section);
3035 else if (SectName == "__eh_frame")
3036 outs() << "llvm-objdump: warning: unhandled __eh_frame section\n";
3040 static void PrintMachHeader(uint32_t magic, uint32_t cputype,
3041 uint32_t cpusubtype, uint32_t filetype,
3042 uint32_t ncmds, uint32_t sizeofcmds, uint32_t flags,
3044 outs() << "Mach header\n";
3045 outs() << " magic cputype cpusubtype caps filetype ncmds "
3046 "sizeofcmds flags\n";
3048 if (magic == MachO::MH_MAGIC)
3049 outs() << " MH_MAGIC";
3050 else if (magic == MachO::MH_MAGIC_64)
3051 outs() << "MH_MAGIC_64";
3053 outs() << format(" 0x%08" PRIx32, magic);
3055 case MachO::CPU_TYPE_I386:
3057 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
3058 case MachO::CPU_SUBTYPE_I386_ALL:
3062 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
3066 case MachO::CPU_TYPE_X86_64:
3067 outs() << " X86_64";
3068 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
3069 case MachO::CPU_SUBTYPE_X86_64_ALL:
3072 case MachO::CPU_SUBTYPE_X86_64_H:
3073 outs() << " Haswell";
3076 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
3080 case MachO::CPU_TYPE_ARM:
3082 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
3083 case MachO::CPU_SUBTYPE_ARM_ALL:
3086 case MachO::CPU_SUBTYPE_ARM_V4T:
3089 case MachO::CPU_SUBTYPE_ARM_V5TEJ:
3092 case MachO::CPU_SUBTYPE_ARM_XSCALE:
3093 outs() << " XSCALE";
3095 case MachO::CPU_SUBTYPE_ARM_V6:
3098 case MachO::CPU_SUBTYPE_ARM_V6M:
3101 case MachO::CPU_SUBTYPE_ARM_V7:
3104 case MachO::CPU_SUBTYPE_ARM_V7EM:
3107 case MachO::CPU_SUBTYPE_ARM_V7K:
3110 case MachO::CPU_SUBTYPE_ARM_V7M:
3113 case MachO::CPU_SUBTYPE_ARM_V7S:
3117 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
3121 case MachO::CPU_TYPE_ARM64:
3123 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
3124 case MachO::CPU_SUBTYPE_ARM64_ALL:
3128 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
3132 case MachO::CPU_TYPE_POWERPC:
3134 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
3135 case MachO::CPU_SUBTYPE_POWERPC_ALL:
3139 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
3143 case MachO::CPU_TYPE_POWERPC64:
3145 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
3146 case MachO::CPU_SUBTYPE_POWERPC_ALL:
3150 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
3155 if ((cpusubtype & MachO::CPU_SUBTYPE_MASK) == MachO::CPU_SUBTYPE_LIB64) {
3158 outs() << format(" 0x%02" PRIx32,
3159 (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24);
3162 case MachO::MH_OBJECT:
3163 outs() << " OBJECT";
3165 case MachO::MH_EXECUTE:
3166 outs() << " EXECUTE";
3168 case MachO::MH_FVMLIB:
3169 outs() << " FVMLIB";
3171 case MachO::MH_CORE:
3174 case MachO::MH_PRELOAD:
3175 outs() << " PRELOAD";
3177 case MachO::MH_DYLIB:
3180 case MachO::MH_DYLIB_STUB:
3181 outs() << " DYLIB_STUB";
3183 case MachO::MH_DYLINKER:
3184 outs() << " DYLINKER";
3186 case MachO::MH_BUNDLE:
3187 outs() << " BUNDLE";
3189 case MachO::MH_DSYM:
3192 case MachO::MH_KEXT_BUNDLE:
3193 outs() << " KEXTBUNDLE";
3196 outs() << format(" %10u", filetype);
3199 outs() << format(" %5u", ncmds);
3200 outs() << format(" %10u", sizeofcmds);
3202 if (f & MachO::MH_NOUNDEFS) {
3203 outs() << " NOUNDEFS";
3204 f &= ~MachO::MH_NOUNDEFS;
3206 if (f & MachO::MH_INCRLINK) {
3207 outs() << " INCRLINK";
3208 f &= ~MachO::MH_INCRLINK;
3210 if (f & MachO::MH_DYLDLINK) {
3211 outs() << " DYLDLINK";
3212 f &= ~MachO::MH_DYLDLINK;
3214 if (f & MachO::MH_BINDATLOAD) {
3215 outs() << " BINDATLOAD";
3216 f &= ~MachO::MH_BINDATLOAD;
3218 if (f & MachO::MH_PREBOUND) {
3219 outs() << " PREBOUND";
3220 f &= ~MachO::MH_PREBOUND;
3222 if (f & MachO::MH_SPLIT_SEGS) {
3223 outs() << " SPLIT_SEGS";
3224 f &= ~MachO::MH_SPLIT_SEGS;
3226 if (f & MachO::MH_LAZY_INIT) {
3227 outs() << " LAZY_INIT";
3228 f &= ~MachO::MH_LAZY_INIT;
3230 if (f & MachO::MH_TWOLEVEL) {
3231 outs() << " TWOLEVEL";
3232 f &= ~MachO::MH_TWOLEVEL;
3234 if (f & MachO::MH_FORCE_FLAT) {
3235 outs() << " FORCE_FLAT";
3236 f &= ~MachO::MH_FORCE_FLAT;
3238 if (f & MachO::MH_NOMULTIDEFS) {
3239 outs() << " NOMULTIDEFS";
3240 f &= ~MachO::MH_NOMULTIDEFS;
3242 if (f & MachO::MH_NOFIXPREBINDING) {
3243 outs() << " NOFIXPREBINDING";
3244 f &= ~MachO::MH_NOFIXPREBINDING;
3246 if (f & MachO::MH_PREBINDABLE) {
3247 outs() << " PREBINDABLE";
3248 f &= ~MachO::MH_PREBINDABLE;
3250 if (f & MachO::MH_ALLMODSBOUND) {
3251 outs() << " ALLMODSBOUND";
3252 f &= ~MachO::MH_ALLMODSBOUND;
3254 if (f & MachO::MH_SUBSECTIONS_VIA_SYMBOLS) {
3255 outs() << " SUBSECTIONS_VIA_SYMBOLS";
3256 f &= ~MachO::MH_SUBSECTIONS_VIA_SYMBOLS;
3258 if (f & MachO::MH_CANONICAL) {
3259 outs() << " CANONICAL";
3260 f &= ~MachO::MH_CANONICAL;
3262 if (f & MachO::MH_WEAK_DEFINES) {
3263 outs() << " WEAK_DEFINES";
3264 f &= ~MachO::MH_WEAK_DEFINES;
3266 if (f & MachO::MH_BINDS_TO_WEAK) {
3267 outs() << " BINDS_TO_WEAK";
3268 f &= ~MachO::MH_BINDS_TO_WEAK;
3270 if (f & MachO::MH_ALLOW_STACK_EXECUTION) {
3271 outs() << " ALLOW_STACK_EXECUTION";
3272 f &= ~MachO::MH_ALLOW_STACK_EXECUTION;
3274 if (f & MachO::MH_DEAD_STRIPPABLE_DYLIB) {
3275 outs() << " DEAD_STRIPPABLE_DYLIB";
3276 f &= ~MachO::MH_DEAD_STRIPPABLE_DYLIB;
3278 if (f & MachO::MH_PIE) {
3280 f &= ~MachO::MH_PIE;
3282 if (f & MachO::MH_NO_REEXPORTED_DYLIBS) {
3283 outs() << " NO_REEXPORTED_DYLIBS";
3284 f &= ~MachO::MH_NO_REEXPORTED_DYLIBS;
3286 if (f & MachO::MH_HAS_TLV_DESCRIPTORS) {
3287 outs() << " MH_HAS_TLV_DESCRIPTORS";
3288 f &= ~MachO::MH_HAS_TLV_DESCRIPTORS;
3290 if (f & MachO::MH_NO_HEAP_EXECUTION) {
3291 outs() << " MH_NO_HEAP_EXECUTION";
3292 f &= ~MachO::MH_NO_HEAP_EXECUTION;
3294 if (f & MachO::MH_APP_EXTENSION_SAFE) {
3295 outs() << " APP_EXTENSION_SAFE";
3296 f &= ~MachO::MH_APP_EXTENSION_SAFE;
3298 if (f != 0 || flags == 0)
3299 outs() << format(" 0x%08" PRIx32, f);
3301 outs() << format(" 0x%08" PRIx32, magic);
3302 outs() << format(" %7d", cputype);
3303 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
3304 outs() << format(" 0x%02" PRIx32,
3305 (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24);
3306 outs() << format(" %10u", filetype);
3307 outs() << format(" %5u", ncmds);
3308 outs() << format(" %10u", sizeofcmds);
3309 outs() << format(" 0x%08" PRIx32, flags);
3314 static void PrintSegmentCommand(uint32_t cmd, uint32_t cmdsize,
3315 StringRef SegName, uint64_t vmaddr,
3316 uint64_t vmsize, uint64_t fileoff,
3317 uint64_t filesize, uint32_t maxprot,
3318 uint32_t initprot, uint32_t nsects,
3319 uint32_t flags, uint32_t object_size,
3321 uint64_t expected_cmdsize;
3322 if (cmd == MachO::LC_SEGMENT) {
3323 outs() << " cmd LC_SEGMENT\n";
3324 expected_cmdsize = nsects;
3325 expected_cmdsize *= sizeof(struct MachO::section);
3326 expected_cmdsize += sizeof(struct MachO::segment_command);
3328 outs() << " cmd LC_SEGMENT_64\n";
3329 expected_cmdsize = nsects;
3330 expected_cmdsize *= sizeof(struct MachO::section_64);
3331 expected_cmdsize += sizeof(struct MachO::segment_command_64);
3333 outs() << " cmdsize " << cmdsize;
3334 if (cmdsize != expected_cmdsize)
3335 outs() << " Inconsistent size\n";
3338 outs() << " segname " << SegName << "\n";
3339 if (cmd == MachO::LC_SEGMENT_64) {
3340 outs() << " vmaddr " << format("0x%016" PRIx64, vmaddr) << "\n";
3341 outs() << " vmsize " << format("0x%016" PRIx64, vmsize) << "\n";
3343 outs() << " vmaddr " << format("0x%08" PRIx64, vmaddr) << "\n";
3344 outs() << " vmsize " << format("0x%08" PRIx64, vmsize) << "\n";
3346 outs() << " fileoff " << fileoff;
3347 if (fileoff > object_size)
3348 outs() << " (past end of file)\n";
3351 outs() << " filesize " << filesize;
3352 if (fileoff + filesize > object_size)
3353 outs() << " (past end of file)\n";
3358 ~(MachO::VM_PROT_READ | MachO::VM_PROT_WRITE |
3359 MachO::VM_PROT_EXECUTE)) != 0)
3360 outs() << " maxprot ?" << format("0x%08" PRIx32, maxprot) << "\n";
3362 if (maxprot & MachO::VM_PROT_READ)
3363 outs() << " maxprot r";
3365 outs() << " maxprot -";
3366 if (maxprot & MachO::VM_PROT_WRITE)
3370 if (maxprot & MachO::VM_PROT_EXECUTE)
3376 ~(MachO::VM_PROT_READ | MachO::VM_PROT_WRITE |
3377 MachO::VM_PROT_EXECUTE)) != 0)
3378 outs() << " initprot ?" << format("0x%08" PRIx32, initprot) << "\n";
3380 if (initprot & MachO::VM_PROT_READ)
3381 outs() << " initprot r";
3383 outs() << " initprot -";
3384 if (initprot & MachO::VM_PROT_WRITE)
3388 if (initprot & MachO::VM_PROT_EXECUTE)
3394 outs() << " maxprot " << format("0x%08" PRIx32, maxprot) << "\n";
3395 outs() << " initprot " << format("0x%08" PRIx32, initprot) << "\n";
3397 outs() << " nsects " << nsects << "\n";
3401 outs() << " (none)\n";
3403 if (flags & MachO::SG_HIGHVM) {
3404 outs() << " HIGHVM";
3405 flags &= ~MachO::SG_HIGHVM;
3407 if (flags & MachO::SG_FVMLIB) {
3408 outs() << " FVMLIB";
3409 flags &= ~MachO::SG_FVMLIB;
3411 if (flags & MachO::SG_NORELOC) {
3412 outs() << " NORELOC";
3413 flags &= ~MachO::SG_NORELOC;
3415 if (flags & MachO::SG_PROTECTED_VERSION_1) {
3416 outs() << " PROTECTED_VERSION_1";
3417 flags &= ~MachO::SG_PROTECTED_VERSION_1;
3420 outs() << format(" 0x%08" PRIx32, flags) << " (unknown flags)\n";
3425 outs() << " flags " << format("0x%" PRIx32, flags) << "\n";
3429 static void PrintSection(const char *sectname, const char *segname,
3430 uint64_t addr, uint64_t size, uint32_t offset,
3431 uint32_t align, uint32_t reloff, uint32_t nreloc,
3432 uint32_t flags, uint32_t reserved1, uint32_t reserved2,
3433 uint32_t cmd, const char *sg_segname,
3434 uint32_t filetype, uint32_t object_size,
3436 outs() << "Section\n";
3437 outs() << " sectname " << format("%.16s\n", sectname);
3438 outs() << " segname " << format("%.16s", segname);
3439 if (filetype != MachO::MH_OBJECT && strncmp(sg_segname, segname, 16) != 0)
3440 outs() << " (does not match segment)\n";
3443 if (cmd == MachO::LC_SEGMENT_64) {
3444 outs() << " addr " << format("0x%016" PRIx64, addr) << "\n";
3445 outs() << " size " << format("0x%016" PRIx64, size);
3447 outs() << " addr " << format("0x%08" PRIx64, addr) << "\n";
3448 outs() << " size " << format("0x%08" PRIx64, size);
3450 if ((flags & MachO::S_ZEROFILL) != 0 && offset + size > object_size)
3451 outs() << " (past end of file)\n";
3454 outs() << " offset " << offset;
3455 if (offset > object_size)
3456 outs() << " (past end of file)\n";
3459 uint32_t align_shifted = 1 << align;
3460 outs() << " align 2^" << align << " (" << align_shifted << ")\n";
3461 outs() << " reloff " << reloff;
3462 if (reloff > object_size)
3463 outs() << " (past end of file)\n";
3466 outs() << " nreloc " << nreloc;
3467 if (reloff + nreloc * sizeof(struct MachO::relocation_info) > object_size)
3468 outs() << " (past end of file)\n";
3471 uint32_t section_type = flags & MachO::SECTION_TYPE;
3474 if (section_type == MachO::S_REGULAR)
3475 outs() << " S_REGULAR\n";
3476 else if (section_type == MachO::S_ZEROFILL)
3477 outs() << " S_ZEROFILL\n";
3478 else if (section_type == MachO::S_CSTRING_LITERALS)
3479 outs() << " S_CSTRING_LITERALS\n";
3480 else if (section_type == MachO::S_4BYTE_LITERALS)
3481 outs() << " S_4BYTE_LITERALS\n";
3482 else if (section_type == MachO::S_8BYTE_LITERALS)
3483 outs() << " S_8BYTE_LITERALS\n";
3484 else if (section_type == MachO::S_16BYTE_LITERALS)
3485 outs() << " S_16BYTE_LITERALS\n";
3486 else if (section_type == MachO::S_LITERAL_POINTERS)
3487 outs() << " S_LITERAL_POINTERS\n";
3488 else if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS)
3489 outs() << " S_NON_LAZY_SYMBOL_POINTERS\n";
3490 else if (section_type == MachO::S_LAZY_SYMBOL_POINTERS)
3491 outs() << " S_LAZY_SYMBOL_POINTERS\n";
3492 else if (section_type == MachO::S_SYMBOL_STUBS)
3493 outs() << " S_SYMBOL_STUBS\n";
3494 else if (section_type == MachO::S_MOD_INIT_FUNC_POINTERS)
3495 outs() << " S_MOD_INIT_FUNC_POINTERS\n";
3496 else if (section_type == MachO::S_MOD_TERM_FUNC_POINTERS)
3497 outs() << " S_MOD_TERM_FUNC_POINTERS\n";
3498 else if (section_type == MachO::S_COALESCED)
3499 outs() << " S_COALESCED\n";
3500 else if (section_type == MachO::S_INTERPOSING)
3501 outs() << " S_INTERPOSING\n";
3502 else if (section_type == MachO::S_DTRACE_DOF)
3503 outs() << " S_DTRACE_DOF\n";
3504 else if (section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS)
3505 outs() << " S_LAZY_DYLIB_SYMBOL_POINTERS\n";
3506 else if (section_type == MachO::S_THREAD_LOCAL_REGULAR)
3507 outs() << " S_THREAD_LOCAL_REGULAR\n";
3508 else if (section_type == MachO::S_THREAD_LOCAL_ZEROFILL)
3509 outs() << " S_THREAD_LOCAL_ZEROFILL\n";
3510 else if (section_type == MachO::S_THREAD_LOCAL_VARIABLES)
3511 outs() << " S_THREAD_LOCAL_VARIABLES\n";
3512 else if (section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS)
3513 outs() << " S_THREAD_LOCAL_VARIABLE_POINTERS\n";
3514 else if (section_type == MachO::S_THREAD_LOCAL_INIT_FUNCTION_POINTERS)
3515 outs() << " S_THREAD_LOCAL_INIT_FUNCTION_POINTERS\n";
3517 outs() << format("0x%08" PRIx32, section_type) << "\n";
3518 outs() << "attributes";
3519 uint32_t section_attributes = flags & MachO::SECTION_ATTRIBUTES;
3520 if (section_attributes & MachO::S_ATTR_PURE_INSTRUCTIONS)
3521 outs() << " PURE_INSTRUCTIONS";
3522 if (section_attributes & MachO::S_ATTR_NO_TOC)
3523 outs() << " NO_TOC";
3524 if (section_attributes & MachO::S_ATTR_STRIP_STATIC_SYMS)
3525 outs() << " STRIP_STATIC_SYMS";
3526 if (section_attributes & MachO::S_ATTR_NO_DEAD_STRIP)
3527 outs() << " NO_DEAD_STRIP";
3528 if (section_attributes & MachO::S_ATTR_LIVE_SUPPORT)
3529 outs() << " LIVE_SUPPORT";
3530 if (section_attributes & MachO::S_ATTR_SELF_MODIFYING_CODE)
3531 outs() << " SELF_MODIFYING_CODE";
3532 if (section_attributes & MachO::S_ATTR_DEBUG)
3534 if (section_attributes & MachO::S_ATTR_SOME_INSTRUCTIONS)
3535 outs() << " SOME_INSTRUCTIONS";
3536 if (section_attributes & MachO::S_ATTR_EXT_RELOC)
3537 outs() << " EXT_RELOC";
3538 if (section_attributes & MachO::S_ATTR_LOC_RELOC)
3539 outs() << " LOC_RELOC";
3540 if (section_attributes == 0)
3541 outs() << " (none)";
3544 outs() << " flags " << format("0x%08" PRIx32, flags) << "\n";
3545 outs() << " reserved1 " << reserved1;
3546 if (section_type == MachO::S_SYMBOL_STUBS ||
3547 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
3548 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
3549 section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
3550 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS)
3551 outs() << " (index into indirect symbol table)\n";
3554 outs() << " reserved2 " << reserved2;
3555 if (section_type == MachO::S_SYMBOL_STUBS)
3556 outs() << " (size of stubs)\n";
3561 static void PrintSymtabLoadCommand(MachO::symtab_command st, bool Is64Bit,
3562 uint32_t object_size) {
3563 outs() << " cmd LC_SYMTAB\n";
3564 outs() << " cmdsize " << st.cmdsize;
3565 if (st.cmdsize != sizeof(struct MachO::symtab_command))
3566 outs() << " Incorrect size\n";
3569 outs() << " symoff " << st.symoff;
3570 if (st.symoff > object_size)
3571 outs() << " (past end of file)\n";
3574 outs() << " nsyms " << st.nsyms;
3577 big_size = st.nsyms;
3578 big_size *= sizeof(struct MachO::nlist_64);
3579 big_size += st.symoff;
3580 if (big_size > object_size)
3581 outs() << " (past end of file)\n";
3585 big_size = st.nsyms;
3586 big_size *= sizeof(struct MachO::nlist);
3587 big_size += st.symoff;
3588 if (big_size > object_size)
3589 outs() << " (past end of file)\n";
3593 outs() << " stroff " << st.stroff;
3594 if (st.stroff > object_size)
3595 outs() << " (past end of file)\n";
3598 outs() << " strsize " << st.strsize;
3599 big_size = st.stroff;
3600 big_size += st.strsize;
3601 if (big_size > object_size)
3602 outs() << " (past end of file)\n";
3607 static void PrintDysymtabLoadCommand(MachO::dysymtab_command dyst,
3608 uint32_t nsyms, uint32_t object_size,
3610 outs() << " cmd LC_DYSYMTAB\n";
3611 outs() << " cmdsize " << dyst.cmdsize;
3612 if (dyst.cmdsize != sizeof(struct MachO::dysymtab_command))
3613 outs() << " Incorrect size\n";
3616 outs() << " ilocalsym " << dyst.ilocalsym;
3617 if (dyst.ilocalsym > nsyms)
3618 outs() << " (greater than the number of symbols)\n";
3621 outs() << " nlocalsym " << dyst.nlocalsym;
3623 big_size = dyst.ilocalsym;
3624 big_size += dyst.nlocalsym;
3625 if (big_size > nsyms)
3626 outs() << " (past the end of the symbol table)\n";
3629 outs() << " iextdefsym " << dyst.iextdefsym;
3630 if (dyst.iextdefsym > nsyms)
3631 outs() << " (greater than the number of symbols)\n";
3634 outs() << " nextdefsym " << dyst.nextdefsym;
3635 big_size = dyst.iextdefsym;
3636 big_size += dyst.nextdefsym;
3637 if (big_size > nsyms)
3638 outs() << " (past the end of the symbol table)\n";
3641 outs() << " iundefsym " << dyst.iundefsym;
3642 if (dyst.iundefsym > nsyms)
3643 outs() << " (greater than the number of symbols)\n";
3646 outs() << " nundefsym " << dyst.nundefsym;
3647 big_size = dyst.iundefsym;
3648 big_size += dyst.nundefsym;
3649 if (big_size > nsyms)
3650 outs() << " (past the end of the symbol table)\n";
3653 outs() << " tocoff " << dyst.tocoff;
3654 if (dyst.tocoff > object_size)
3655 outs() << " (past end of file)\n";
3658 outs() << " ntoc " << dyst.ntoc;
3659 big_size = dyst.ntoc;
3660 big_size *= sizeof(struct MachO::dylib_table_of_contents);
3661 big_size += dyst.tocoff;
3662 if (big_size > object_size)
3663 outs() << " (past end of file)\n";
3666 outs() << " modtaboff " << dyst.modtaboff;
3667 if (dyst.modtaboff > object_size)
3668 outs() << " (past end of file)\n";
3671 outs() << " nmodtab " << dyst.nmodtab;
3674 modtabend = dyst.nmodtab;
3675 modtabend *= sizeof(struct MachO::dylib_module_64);
3676 modtabend += dyst.modtaboff;
3678 modtabend = dyst.nmodtab;
3679 modtabend *= sizeof(struct MachO::dylib_module);
3680 modtabend += dyst.modtaboff;
3682 if (modtabend > object_size)
3683 outs() << " (past end of file)\n";
3686 outs() << " extrefsymoff " << dyst.extrefsymoff;
3687 if (dyst.extrefsymoff > object_size)
3688 outs() << " (past end of file)\n";
3691 outs() << " nextrefsyms " << dyst.nextrefsyms;
3692 big_size = dyst.nextrefsyms;
3693 big_size *= sizeof(struct MachO::dylib_reference);
3694 big_size += dyst.extrefsymoff;
3695 if (big_size > object_size)
3696 outs() << " (past end of file)\n";
3699 outs() << " indirectsymoff " << dyst.indirectsymoff;
3700 if (dyst.indirectsymoff > object_size)
3701 outs() << " (past end of file)\n";
3704 outs() << " nindirectsyms " << dyst.nindirectsyms;
3705 big_size = dyst.nindirectsyms;
3706 big_size *= sizeof(uint32_t);
3707 big_size += dyst.indirectsymoff;
3708 if (big_size > object_size)
3709 outs() << " (past end of file)\n";
3712 outs() << " extreloff " << dyst.extreloff;
3713 if (dyst.extreloff > object_size)
3714 outs() << " (past end of file)\n";
3717 outs() << " nextrel " << dyst.nextrel;
3718 big_size = dyst.nextrel;
3719 big_size *= sizeof(struct MachO::relocation_info);
3720 big_size += dyst.extreloff;
3721 if (big_size > object_size)
3722 outs() << " (past end of file)\n";
3725 outs() << " locreloff " << dyst.locreloff;
3726 if (dyst.locreloff > object_size)
3727 outs() << " (past end of file)\n";
3730 outs() << " nlocrel " << dyst.nlocrel;
3731 big_size = dyst.nlocrel;
3732 big_size *= sizeof(struct MachO::relocation_info);
3733 big_size += dyst.locreloff;
3734 if (big_size > object_size)
3735 outs() << " (past end of file)\n";
3740 static void PrintDyldInfoLoadCommand(MachO::dyld_info_command dc,
3741 uint32_t object_size) {
3742 if (dc.cmd == MachO::LC_DYLD_INFO)
3743 outs() << " cmd LC_DYLD_INFO\n";
3745 outs() << " cmd LC_DYLD_INFO_ONLY\n";
3746 outs() << " cmdsize " << dc.cmdsize;
3747 if (dc.cmdsize != sizeof(struct MachO::dyld_info_command))
3748 outs() << " Incorrect size\n";
3751 outs() << " rebase_off " << dc.rebase_off;
3752 if (dc.rebase_off > object_size)
3753 outs() << " (past end of file)\n";
3756 outs() << " rebase_size " << dc.rebase_size;
3758 big_size = dc.rebase_off;
3759 big_size += dc.rebase_size;
3760 if (big_size > object_size)
3761 outs() << " (past end of file)\n";
3764 outs() << " bind_off " << dc.bind_off;
3765 if (dc.bind_off > object_size)
3766 outs() << " (past end of file)\n";
3769 outs() << " bind_size " << dc.bind_size;
3770 big_size = dc.bind_off;
3771 big_size += dc.bind_size;
3772 if (big_size > object_size)
3773 outs() << " (past end of file)\n";
3776 outs() << " weak_bind_off " << dc.weak_bind_off;
3777 if (dc.weak_bind_off > object_size)
3778 outs() << " (past end of file)\n";
3781 outs() << " weak_bind_size " << dc.weak_bind_size;
3782 big_size = dc.weak_bind_off;
3783 big_size += dc.weak_bind_size;
3784 if (big_size > object_size)
3785 outs() << " (past end of file)\n";
3788 outs() << " lazy_bind_off " << dc.lazy_bind_off;
3789 if (dc.lazy_bind_off > object_size)
3790 outs() << " (past end of file)\n";
3793 outs() << " lazy_bind_size " << dc.lazy_bind_size;
3794 big_size = dc.lazy_bind_off;
3795 big_size += dc.lazy_bind_size;
3796 if (big_size > object_size)
3797 outs() << " (past end of file)\n";
3800 outs() << " export_off " << dc.export_off;
3801 if (dc.export_off > object_size)
3802 outs() << " (past end of file)\n";
3805 outs() << " export_size " << dc.export_size;
3806 big_size = dc.export_off;
3807 big_size += dc.export_size;
3808 if (big_size > object_size)
3809 outs() << " (past end of file)\n";
3814 static void PrintDyldLoadCommand(MachO::dylinker_command dyld,
3816 if (dyld.cmd == MachO::LC_ID_DYLINKER)
3817 outs() << " cmd LC_ID_DYLINKER\n";
3818 else if (dyld.cmd == MachO::LC_LOAD_DYLINKER)
3819 outs() << " cmd LC_LOAD_DYLINKER\n";
3820 else if (dyld.cmd == MachO::LC_DYLD_ENVIRONMENT)
3821 outs() << " cmd LC_DYLD_ENVIRONMENT\n";
3823 outs() << " cmd ?(" << dyld.cmd << ")\n";
3824 outs() << " cmdsize " << dyld.cmdsize;
3825 if (dyld.cmdsize < sizeof(struct MachO::dylinker_command))
3826 outs() << " Incorrect size\n";
3829 if (dyld.name >= dyld.cmdsize)
3830 outs() << " name ?(bad offset " << dyld.name << ")\n";
3832 const char *P = (const char *)(Ptr) + dyld.name;
3833 outs() << " name " << P << " (offset " << dyld.name << ")\n";
3837 static void PrintUuidLoadCommand(MachO::uuid_command uuid) {
3838 outs() << " cmd LC_UUID\n";
3839 outs() << " cmdsize " << uuid.cmdsize;
3840 if (uuid.cmdsize != sizeof(struct MachO::uuid_command))
3841 outs() << " Incorrect size\n";
3845 outs() << format("%02" PRIX32, uuid.uuid[0]);
3846 outs() << format("%02" PRIX32, uuid.uuid[1]);
3847 outs() << format("%02" PRIX32, uuid.uuid[2]);
3848 outs() << format("%02" PRIX32, uuid.uuid[3]);
3850 outs() << format("%02" PRIX32, uuid.uuid[4]);
3851 outs() << format("%02" PRIX32, uuid.uuid[5]);
3853 outs() << format("%02" PRIX32, uuid.uuid[6]);
3854 outs() << format("%02" PRIX32, uuid.uuid[7]);
3856 outs() << format("%02" PRIX32, uuid.uuid[8]);
3857 outs() << format("%02" PRIX32, uuid.uuid[9]);
3859 outs() << format("%02" PRIX32, uuid.uuid[10]);
3860 outs() << format("%02" PRIX32, uuid.uuid[11]);
3861 outs() << format("%02" PRIX32, uuid.uuid[12]);
3862 outs() << format("%02" PRIX32, uuid.uuid[13]);
3863 outs() << format("%02" PRIX32, uuid.uuid[14]);
3864 outs() << format("%02" PRIX32, uuid.uuid[15]);
3868 static void PrintRpathLoadCommand(MachO::rpath_command rpath, const char *Ptr) {
3869 outs() << " cmd LC_RPATH\n";
3870 outs() << " cmdsize " << rpath.cmdsize;
3871 if (rpath.cmdsize < sizeof(struct MachO::rpath_command))
3872 outs() << " Incorrect size\n";
3875 if (rpath.path >= rpath.cmdsize)
3876 outs() << " path ?(bad offset " << rpath.path << ")\n";
3878 const char *P = (const char *)(Ptr) + rpath.path;
3879 outs() << " path " << P << " (offset " << rpath.path << ")\n";
3883 static void PrintVersionMinLoadCommand(MachO::version_min_command vd) {
3884 if (vd.cmd == MachO::LC_VERSION_MIN_MACOSX)
3885 outs() << " cmd LC_VERSION_MIN_MACOSX\n";
3886 else if (vd.cmd == MachO::LC_VERSION_MIN_IPHONEOS)
3887 outs() << " cmd LC_VERSION_MIN_IPHONEOS\n";
3889 outs() << " cmd " << vd.cmd << " (?)\n";
3890 outs() << " cmdsize " << vd.cmdsize;
3891 if (vd.cmdsize != sizeof(struct MachO::version_min_command))
3892 outs() << " Incorrect size\n";
3895 outs() << " version " << ((vd.version >> 16) & 0xffff) << "."
3896 << ((vd.version >> 8) & 0xff);
3897 if ((vd.version & 0xff) != 0)
3898 outs() << "." << (vd.version & 0xff);
3901 outs() << " sdk n/a";
3903 outs() << " sdk " << ((vd.sdk >> 16) & 0xffff) << "."
3904 << ((vd.sdk >> 8) & 0xff);
3906 if ((vd.sdk & 0xff) != 0)
3907 outs() << "." << (vd.sdk & 0xff);
3911 static void PrintSourceVersionCommand(MachO::source_version_command sd) {
3912 outs() << " cmd LC_SOURCE_VERSION\n";
3913 outs() << " cmdsize " << sd.cmdsize;
3914 if (sd.cmdsize != sizeof(struct MachO::source_version_command))
3915 outs() << " Incorrect size\n";
3918 uint64_t a = (sd.version >> 40) & 0xffffff;
3919 uint64_t b = (sd.version >> 30) & 0x3ff;
3920 uint64_t c = (sd.version >> 20) & 0x3ff;
3921 uint64_t d = (sd.version >> 10) & 0x3ff;
3922 uint64_t e = sd.version & 0x3ff;
3923 outs() << " version " << a << "." << b;
3925 outs() << "." << c << "." << d << "." << e;
3927 outs() << "." << c << "." << d;
3933 static void PrintEntryPointCommand(MachO::entry_point_command ep) {
3934 outs() << " cmd LC_MAIN\n";
3935 outs() << " cmdsize " << ep.cmdsize;
3936 if (ep.cmdsize != sizeof(struct MachO::entry_point_command))
3937 outs() << " Incorrect size\n";
3940 outs() << " entryoff " << ep.entryoff << "\n";
3941 outs() << " stacksize " << ep.stacksize << "\n";
3944 static void PrintEncryptionInfoCommand(MachO::encryption_info_command ec,
3945 uint32_t object_size) {
3946 outs() << " cmd LC_ENCRYPTION_INFO\n";
3947 outs() << " cmdsize " << ec.cmdsize;
3948 if (ec.cmdsize != sizeof(struct MachO::encryption_info_command))
3949 outs() << " Incorrect size\n";
3952 outs() << " cryptoff " << ec.cryptoff;
3953 if (ec.cryptoff > object_size)
3954 outs() << " (past end of file)\n";
3957 outs() << " cryptsize " << ec.cryptsize;
3958 if (ec.cryptsize > object_size)
3959 outs() << " (past end of file)\n";
3962 outs() << " cryptid " << ec.cryptid << "\n";
3965 static void PrintEncryptionInfoCommand64(MachO::encryption_info_command_64 ec,
3966 uint32_t object_size) {
3967 outs() << " cmd LC_ENCRYPTION_INFO_64\n";
3968 outs() << " cmdsize " << ec.cmdsize;
3969 if (ec.cmdsize != sizeof(struct MachO::encryption_info_command_64))
3970 outs() << " Incorrect size\n";
3973 outs() << " cryptoff " << ec.cryptoff;
3974 if (ec.cryptoff > object_size)
3975 outs() << " (past end of file)\n";
3978 outs() << " cryptsize " << ec.cryptsize;
3979 if (ec.cryptsize > object_size)
3980 outs() << " (past end of file)\n";
3983 outs() << " cryptid " << ec.cryptid << "\n";
3984 outs() << " pad " << ec.pad << "\n";
3987 static void PrintLinkerOptionCommand(MachO::linker_option_command lo,
3989 outs() << " cmd LC_LINKER_OPTION\n";
3990 outs() << " cmdsize " << lo.cmdsize;
3991 if (lo.cmdsize < sizeof(struct MachO::linker_option_command))
3992 outs() << " Incorrect size\n";
3995 outs() << " count " << lo.count << "\n";
3996 const char *string = Ptr + sizeof(struct MachO::linker_option_command);
3997 uint32_t left = lo.cmdsize - sizeof(struct MachO::linker_option_command);
4000 while (*string == '\0' && left > 0) {
4006 outs() << " string #" << i << " " << format("%.*s\n", left, string);
4007 uint32_t NullPos = StringRef(string, left).find('\0');
4008 uint32_t len = std::min(NullPos, left) + 1;
4014 outs() << " count " << lo.count << " does not match number of strings "
4018 static void PrintSubFrameworkCommand(MachO::sub_framework_command sub,
4020 outs() << " cmd LC_SUB_FRAMEWORK\n";
4021 outs() << " cmdsize " << sub.cmdsize;
4022 if (sub.cmdsize < sizeof(struct MachO::sub_framework_command))
4023 outs() << " Incorrect size\n";
4026 if (sub.umbrella < sub.cmdsize) {
4027 const char *P = Ptr + sub.umbrella;
4028 outs() << " umbrella " << P << " (offset " << sub.umbrella << ")\n";
4030 outs() << " umbrella ?(bad offset " << sub.umbrella << ")\n";
4034 static void PrintSubUmbrellaCommand(MachO::sub_umbrella_command sub,
4036 outs() << " cmd LC_SUB_UMBRELLA\n";
4037 outs() << " cmdsize " << sub.cmdsize;
4038 if (sub.cmdsize < sizeof(struct MachO::sub_umbrella_command))
4039 outs() << " Incorrect size\n";
4042 if (sub.sub_umbrella < sub.cmdsize) {
4043 const char *P = Ptr + sub.sub_umbrella;
4044 outs() << " sub_umbrella " << P << " (offset " << sub.sub_umbrella << ")\n";
4046 outs() << " sub_umbrella ?(bad offset " << sub.sub_umbrella << ")\n";
4050 static void PrintSubLibraryCommand(MachO::sub_library_command sub,
4052 outs() << " cmd LC_SUB_LIBRARY\n";
4053 outs() << " cmdsize " << sub.cmdsize;
4054 if (sub.cmdsize < sizeof(struct MachO::sub_library_command))
4055 outs() << " Incorrect size\n";
4058 if (sub.sub_library < sub.cmdsize) {
4059 const char *P = Ptr + sub.sub_library;
4060 outs() << " sub_library " << P << " (offset " << sub.sub_library << ")\n";
4062 outs() << " sub_library ?(bad offset " << sub.sub_library << ")\n";
4066 static void PrintSubClientCommand(MachO::sub_client_command sub,
4068 outs() << " cmd LC_SUB_CLIENT\n";
4069 outs() << " cmdsize " << sub.cmdsize;
4070 if (sub.cmdsize < sizeof(struct MachO::sub_client_command))
4071 outs() << " Incorrect size\n";
4074 if (sub.client < sub.cmdsize) {
4075 const char *P = Ptr + sub.client;
4076 outs() << " client " << P << " (offset " << sub.client << ")\n";
4078 outs() << " client ?(bad offset " << sub.client << ")\n";
4082 static void PrintRoutinesCommand(MachO::routines_command r) {
4083 outs() << " cmd LC_ROUTINES\n";
4084 outs() << " cmdsize " << r.cmdsize;
4085 if (r.cmdsize != sizeof(struct MachO::routines_command))
4086 outs() << " Incorrect size\n";
4089 outs() << " init_address " << format("0x%08" PRIx32, r.init_address) << "\n";
4090 outs() << " init_module " << r.init_module << "\n";
4091 outs() << " reserved1 " << r.reserved1 << "\n";
4092 outs() << " reserved2 " << r.reserved2 << "\n";
4093 outs() << " reserved3 " << r.reserved3 << "\n";
4094 outs() << " reserved4 " << r.reserved4 << "\n";
4095 outs() << " reserved5 " << r.reserved5 << "\n";
4096 outs() << " reserved6 " << r.reserved6 << "\n";
4099 static void PrintRoutinesCommand64(MachO::routines_command_64 r) {
4100 outs() << " cmd LC_ROUTINES_64\n";
4101 outs() << " cmdsize " << r.cmdsize;
4102 if (r.cmdsize != sizeof(struct MachO::routines_command_64))
4103 outs() << " Incorrect size\n";
4106 outs() << " init_address " << format("0x%016" PRIx64, r.init_address) << "\n";
4107 outs() << " init_module " << r.init_module << "\n";
4108 outs() << " reserved1 " << r.reserved1 << "\n";
4109 outs() << " reserved2 " << r.reserved2 << "\n";
4110 outs() << " reserved3 " << r.reserved3 << "\n";
4111 outs() << " reserved4 " << r.reserved4 << "\n";
4112 outs() << " reserved5 " << r.reserved5 << "\n";
4113 outs() << " reserved6 " << r.reserved6 << "\n";
4116 static void Print_x86_thread_state64_t(MachO::x86_thread_state64_t &cpu64) {
4117 outs() << " rax " << format("0x%016" PRIx64, cpu64.rax);
4118 outs() << " rbx " << format("0x%016" PRIx64, cpu64.rbx);
4119 outs() << " rcx " << format("0x%016" PRIx64, cpu64.rcx) << "\n";
4120 outs() << " rdx " << format("0x%016" PRIx64, cpu64.rdx);
4121 outs() << " rdi " << format("0x%016" PRIx64, cpu64.rdi);
4122 outs() << " rsi " << format("0x%016" PRIx64, cpu64.rsi) << "\n";
4123 outs() << " rbp " << format("0x%016" PRIx64, cpu64.rbp);
4124 outs() << " rsp " << format("0x%016" PRIx64, cpu64.rsp);
4125 outs() << " r8 " << format("0x%016" PRIx64, cpu64.r8) << "\n";
4126 outs() << " r9 " << format("0x%016" PRIx64, cpu64.r9);
4127 outs() << " r10 " << format("0x%016" PRIx64, cpu64.r10);
4128 outs() << " r11 " << format("0x%016" PRIx64, cpu64.r11) << "\n";
4129 outs() << " r12 " << format("0x%016" PRIx64, cpu64.r12);
4130 outs() << " r13 " << format("0x%016" PRIx64, cpu64.r13);
4131 outs() << " r14 " << format("0x%016" PRIx64, cpu64.r14) << "\n";
4132 outs() << " r15 " << format("0x%016" PRIx64, cpu64.r15);
4133 outs() << " rip " << format("0x%016" PRIx64, cpu64.rip) << "\n";
4134 outs() << "rflags " << format("0x%016" PRIx64, cpu64.rflags);
4135 outs() << " cs " << format("0x%016" PRIx64, cpu64.cs);
4136 outs() << " fs " << format("0x%016" PRIx64, cpu64.fs) << "\n";
4137 outs() << " gs " << format("0x%016" PRIx64, cpu64.gs) << "\n";
4140 static void Print_mmst_reg(MachO::mmst_reg_t &r) {
4142 outs() << "\t mmst_reg ";
4143 for (f = 0; f < 10; f++)
4144 outs() << format("%02" PRIx32, (r.mmst_reg[f] & 0xff)) << " ";
4146 outs() << "\t mmst_rsrv ";
4147 for (f = 0; f < 6; f++)
4148 outs() << format("%02" PRIx32, (r.mmst_rsrv[f] & 0xff)) << " ";
4152 static void Print_xmm_reg(MachO::xmm_reg_t &r) {
4154 outs() << "\t xmm_reg ";
4155 for (f = 0; f < 16; f++)
4156 outs() << format("%02" PRIx32, (r.xmm_reg[f] & 0xff)) << " ";
4160 static void Print_x86_float_state_t(MachO::x86_float_state64_t &fpu) {
4161 outs() << "\t fpu_reserved[0] " << fpu.fpu_reserved[0];
4162 outs() << " fpu_reserved[1] " << fpu.fpu_reserved[1] << "\n";
4163 outs() << "\t control: invalid " << fpu.fpu_fcw.invalid;
4164 outs() << " denorm " << fpu.fpu_fcw.denorm;
4165 outs() << " zdiv " << fpu.fpu_fcw.zdiv;
4166 outs() << " ovrfl " << fpu.fpu_fcw.ovrfl;
4167 outs() << " undfl " << fpu.fpu_fcw.undfl;
4168 outs() << " precis " << fpu.fpu_fcw.precis << "\n";
4169 outs() << "\t\t pc ";
4170 if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_24B)
4171 outs() << "FP_PREC_24B ";
4172 else if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_53B)
4173 outs() << "FP_PREC_53B ";
4174 else if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_64B)
4175 outs() << "FP_PREC_64B ";
4177 outs() << fpu.fpu_fcw.pc << " ";
4179 if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_NEAR)
4180 outs() << "FP_RND_NEAR ";
4181 else if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_DOWN)
4182 outs() << "FP_RND_DOWN ";
4183 else if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_UP)
4184 outs() << "FP_RND_UP ";
4185 else if (fpu.fpu_fcw.rc == MachO::x86_FP_CHOP)
4186 outs() << "FP_CHOP ";
4188 outs() << "\t status: invalid " << fpu.fpu_fsw.invalid;
4189 outs() << " denorm " << fpu.fpu_fsw.denorm;
4190 outs() << " zdiv " << fpu.fpu_fsw.zdiv;
4191 outs() << " ovrfl " << fpu.fpu_fsw.ovrfl;
4192 outs() << " undfl " << fpu.fpu_fsw.undfl;
4193 outs() << " precis " << fpu.fpu_fsw.precis;
4194 outs() << " stkflt " << fpu.fpu_fsw.stkflt << "\n";
4195 outs() << "\t errsumm " << fpu.fpu_fsw.errsumm;
4196 outs() << " c0 " << fpu.fpu_fsw.c0;
4197 outs() << " c1 " << fpu.fpu_fsw.c1;
4198 outs() << " c2 " << fpu.fpu_fsw.c2;
4199 outs() << " tos " << fpu.fpu_fsw.tos;
4200 outs() << " c3 " << fpu.fpu_fsw.c3;
4201 outs() << " busy " << fpu.fpu_fsw.busy << "\n";
4202 outs() << "\t fpu_ftw " << format("0x%02" PRIx32, fpu.fpu_ftw);
4203 outs() << " fpu_rsrv1 " << format("0x%02" PRIx32, fpu.fpu_rsrv1);
4204 outs() << " fpu_fop " << format("0x%04" PRIx32, fpu.fpu_fop);
4205 outs() << " fpu_ip " << format("0x%08" PRIx32, fpu.fpu_ip) << "\n";
4206 outs() << "\t fpu_cs " << format("0x%04" PRIx32, fpu.fpu_cs);
4207 outs() << " fpu_rsrv2 " << format("0x%04" PRIx32, fpu.fpu_rsrv2);
4208 outs() << " fpu_dp " << format("0x%08" PRIx32, fpu.fpu_dp);
4209 outs() << " fpu_ds " << format("0x%04" PRIx32, fpu.fpu_ds) << "\n";
4210 outs() << "\t fpu_rsrv3 " << format("0x%04" PRIx32, fpu.fpu_rsrv3);
4211 outs() << " fpu_mxcsr " << format("0x%08" PRIx32, fpu.fpu_mxcsr);
4212 outs() << " fpu_mxcsrmask " << format("0x%08" PRIx32, fpu.fpu_mxcsrmask);
4214 outs() << "\t fpu_stmm0:\n";
4215 Print_mmst_reg(fpu.fpu_stmm0);
4216 outs() << "\t fpu_stmm1:\n";
4217 Print_mmst_reg(fpu.fpu_stmm1);
4218 outs() << "\t fpu_stmm2:\n";
4219 Print_mmst_reg(fpu.fpu_stmm2);
4220 outs() << "\t fpu_stmm3:\n";
4221 Print_mmst_reg(fpu.fpu_stmm3);
4222 outs() << "\t fpu_stmm4:\n";
4223 Print_mmst_reg(fpu.fpu_stmm4);
4224 outs() << "\t fpu_stmm5:\n";
4225 Print_mmst_reg(fpu.fpu_stmm5);
4226 outs() << "\t fpu_stmm6:\n";
4227 Print_mmst_reg(fpu.fpu_stmm6);
4228 outs() << "\t fpu_stmm7:\n";
4229 Print_mmst_reg(fpu.fpu_stmm7);
4230 outs() << "\t fpu_xmm0:\n";
4231 Print_xmm_reg(fpu.fpu_xmm0);
4232 outs() << "\t fpu_xmm1:\n";
4233 Print_xmm_reg(fpu.fpu_xmm1);
4234 outs() << "\t fpu_xmm2:\n";
4235 Print_xmm_reg(fpu.fpu_xmm2);
4236 outs() << "\t fpu_xmm3:\n";
4237 Print_xmm_reg(fpu.fpu_xmm3);
4238 outs() << "\t fpu_xmm4:\n";
4239 Print_xmm_reg(fpu.fpu_xmm4);
4240 outs() << "\t fpu_xmm5:\n";
4241 Print_xmm_reg(fpu.fpu_xmm5);
4242 outs() << "\t fpu_xmm6:\n";
4243 Print_xmm_reg(fpu.fpu_xmm6);
4244 outs() << "\t fpu_xmm7:\n";
4245 Print_xmm_reg(fpu.fpu_xmm7);
4246 outs() << "\t fpu_xmm8:\n";
4247 Print_xmm_reg(fpu.fpu_xmm8);
4248 outs() << "\t fpu_xmm9:\n";
4249 Print_xmm_reg(fpu.fpu_xmm9);
4250 outs() << "\t fpu_xmm10:\n";
4251 Print_xmm_reg(fpu.fpu_xmm10);
4252 outs() << "\t fpu_xmm11:\n";
4253 Print_xmm_reg(fpu.fpu_xmm11);
4254 outs() << "\t fpu_xmm12:\n";
4255 Print_xmm_reg(fpu.fpu_xmm12);
4256 outs() << "\t fpu_xmm13:\n";
4257 Print_xmm_reg(fpu.fpu_xmm13);
4258 outs() << "\t fpu_xmm14:\n";
4259 Print_xmm_reg(fpu.fpu_xmm14);
4260 outs() << "\t fpu_xmm15:\n";
4261 Print_xmm_reg(fpu.fpu_xmm15);
4262 outs() << "\t fpu_rsrv4:\n";
4263 for (uint32_t f = 0; f < 6; f++) {
4265 for (uint32_t g = 0; g < 16; g++)
4266 outs() << format("%02" PRIx32, fpu.fpu_rsrv4[f * g]) << " ";
4269 outs() << "\t fpu_reserved1 " << format("0x%08" PRIx32, fpu.fpu_reserved1);
4273 static void Print_x86_exception_state_t(MachO::x86_exception_state64_t &exc64) {
4274 outs() << "\t trapno " << format("0x%08" PRIx32, exc64.trapno);
4275 outs() << " err " << format("0x%08" PRIx32, exc64.err);
4276 outs() << " faultvaddr " << format("0x%016" PRIx64, exc64.faultvaddr) << "\n";
4279 static void PrintThreadCommand(MachO::thread_command t, const char *Ptr,
4280 bool isLittleEndian, uint32_t cputype) {
4281 if (t.cmd == MachO::LC_THREAD)
4282 outs() << " cmd LC_THREAD\n";
4283 else if (t.cmd == MachO::LC_UNIXTHREAD)
4284 outs() << " cmd LC_UNIXTHREAD\n";
4286 outs() << " cmd " << t.cmd << " (unknown)\n";
4287 outs() << " cmdsize " << t.cmdsize;
4288 if (t.cmdsize < sizeof(struct MachO::thread_command) + 2 * sizeof(uint32_t))
4289 outs() << " Incorrect size\n";
4293 const char *begin = Ptr + sizeof(struct MachO::thread_command);
4294 const char *end = Ptr + t.cmdsize;
4295 uint32_t flavor, count, left;
4296 if (cputype == MachO::CPU_TYPE_X86_64) {
4297 while (begin < end) {
4298 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
4299 memcpy((char *)&flavor, begin, sizeof(uint32_t));
4300 begin += sizeof(uint32_t);
4305 if (isLittleEndian != sys::IsLittleEndianHost)
4306 sys::swapByteOrder(flavor);
4307 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
4308 memcpy((char *)&count, begin, sizeof(uint32_t));
4309 begin += sizeof(uint32_t);
4314 if (isLittleEndian != sys::IsLittleEndianHost)
4315 sys::swapByteOrder(count);
4316 if (flavor == MachO::x86_THREAD_STATE64) {
4317 outs() << " flavor x86_THREAD_STATE64\n";
4318 if (count == MachO::x86_THREAD_STATE64_COUNT)
4319 outs() << " count x86_THREAD_STATE64_COUNT\n";
4321 outs() << " count " << count
4322 << " (not x86_THREAD_STATE64_COUNT)\n";
4323 MachO::x86_thread_state64_t cpu64;
4325 if (left >= sizeof(MachO::x86_thread_state64_t)) {
4326 memcpy(&cpu64, begin, sizeof(MachO::x86_thread_state64_t));
4327 begin += sizeof(MachO::x86_thread_state64_t);
4329 memset(&cpu64, '\0', sizeof(MachO::x86_thread_state64_t));
4330 memcpy(&cpu64, begin, left);
4333 if (isLittleEndian != sys::IsLittleEndianHost)
4335 Print_x86_thread_state64_t(cpu64);
4336 } else if (flavor == MachO::x86_THREAD_STATE) {
4337 outs() << " flavor x86_THREAD_STATE\n";
4338 if (count == MachO::x86_THREAD_STATE_COUNT)
4339 outs() << " count x86_THREAD_STATE_COUNT\n";
4341 outs() << " count " << count
4342 << " (not x86_THREAD_STATE_COUNT)\n";
4343 struct MachO::x86_thread_state_t ts;
4345 if (left >= sizeof(MachO::x86_thread_state_t)) {
4346 memcpy(&ts, begin, sizeof(MachO::x86_thread_state_t));
4347 begin += sizeof(MachO::x86_thread_state_t);
4349 memset(&ts, '\0', sizeof(MachO::x86_thread_state_t));
4350 memcpy(&ts, begin, left);
4353 if (isLittleEndian != sys::IsLittleEndianHost)
4355 if (ts.tsh.flavor == MachO::x86_THREAD_STATE64) {
4356 outs() << "\t tsh.flavor x86_THREAD_STATE64 ";
4357 if (ts.tsh.count == MachO::x86_THREAD_STATE64_COUNT)
4358 outs() << "tsh.count x86_THREAD_STATE64_COUNT\n";
4360 outs() << "tsh.count " << ts.tsh.count
4361 << " (not x86_THREAD_STATE64_COUNT\n";
4362 Print_x86_thread_state64_t(ts.uts.ts64);
4364 outs() << "\t tsh.flavor " << ts.tsh.flavor << " tsh.count "
4365 << ts.tsh.count << "\n";
4367 } else if (flavor == MachO::x86_FLOAT_STATE) {
4368 outs() << " flavor x86_FLOAT_STATE\n";
4369 if (count == MachO::x86_FLOAT_STATE_COUNT)
4370 outs() << " count x86_FLOAT_STATE_COUNT\n";
4372 outs() << " count " << count << " (not x86_FLOAT_STATE_COUNT)\n";
4373 struct MachO::x86_float_state_t fs;
4375 if (left >= sizeof(MachO::x86_float_state_t)) {
4376 memcpy(&fs, begin, sizeof(MachO::x86_float_state_t));
4377 begin += sizeof(MachO::x86_float_state_t);
4379 memset(&fs, '\0', sizeof(MachO::x86_float_state_t));
4380 memcpy(&fs, begin, left);
4383 if (isLittleEndian != sys::IsLittleEndianHost)
4385 if (fs.fsh.flavor == MachO::x86_FLOAT_STATE64) {
4386 outs() << "\t fsh.flavor x86_FLOAT_STATE64 ";
4387 if (fs.fsh.count == MachO::x86_FLOAT_STATE64_COUNT)
4388 outs() << "fsh.count x86_FLOAT_STATE64_COUNT\n";
4390 outs() << "fsh.count " << fs.fsh.count
4391 << " (not x86_FLOAT_STATE64_COUNT\n";
4392 Print_x86_float_state_t(fs.ufs.fs64);
4394 outs() << "\t fsh.flavor " << fs.fsh.flavor << " fsh.count "
4395 << fs.fsh.count << "\n";
4397 } else if (flavor == MachO::x86_EXCEPTION_STATE) {
4398 outs() << " flavor x86_EXCEPTION_STATE\n";
4399 if (count == MachO::x86_EXCEPTION_STATE_COUNT)
4400 outs() << " count x86_EXCEPTION_STATE_COUNT\n";
4402 outs() << " count " << count
4403 << " (not x86_EXCEPTION_STATE_COUNT)\n";
4404 struct MachO::x86_exception_state_t es;
4406 if (left >= sizeof(MachO::x86_exception_state_t)) {
4407 memcpy(&es, begin, sizeof(MachO::x86_exception_state_t));
4408 begin += sizeof(MachO::x86_exception_state_t);
4410 memset(&es, '\0', sizeof(MachO::x86_exception_state_t));
4411 memcpy(&es, begin, left);
4414 if (isLittleEndian != sys::IsLittleEndianHost)
4416 if (es.esh.flavor == MachO::x86_EXCEPTION_STATE64) {
4417 outs() << "\t esh.flavor x86_EXCEPTION_STATE64\n";
4418 if (es.esh.count == MachO::x86_EXCEPTION_STATE64_COUNT)
4419 outs() << "\t esh.count x86_EXCEPTION_STATE64_COUNT\n";
4421 outs() << "\t esh.count " << es.esh.count
4422 << " (not x86_EXCEPTION_STATE64_COUNT\n";
4423 Print_x86_exception_state_t(es.ues.es64);
4425 outs() << "\t esh.flavor " << es.esh.flavor << " esh.count "
4426 << es.esh.count << "\n";
4429 outs() << " flavor " << flavor << " (unknown)\n";
4430 outs() << " count " << count << "\n";
4431 outs() << " state (unknown)\n";
4432 begin += count * sizeof(uint32_t);
4436 while (begin < end) {
4437 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
4438 memcpy((char *)&flavor, begin, sizeof(uint32_t));
4439 begin += sizeof(uint32_t);
4444 if (isLittleEndian != sys::IsLittleEndianHost)
4445 sys::swapByteOrder(flavor);
4446 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
4447 memcpy((char *)&count, begin, sizeof(uint32_t));
4448 begin += sizeof(uint32_t);
4453 if (isLittleEndian != sys::IsLittleEndianHost)
4454 sys::swapByteOrder(count);
4455 outs() << " flavor " << flavor << "\n";
4456 outs() << " count " << count << "\n";
4457 outs() << " state (Unknown cputype/cpusubtype)\n";
4458 begin += count * sizeof(uint32_t);
4463 static void PrintDylibCommand(MachO::dylib_command dl, const char *Ptr) {
4464 if (dl.cmd == MachO::LC_ID_DYLIB)
4465 outs() << " cmd LC_ID_DYLIB\n";
4466 else if (dl.cmd == MachO::LC_LOAD_DYLIB)
4467 outs() << " cmd LC_LOAD_DYLIB\n";
4468 else if (dl.cmd == MachO::LC_LOAD_WEAK_DYLIB)
4469 outs() << " cmd LC_LOAD_WEAK_DYLIB\n";
4470 else if (dl.cmd == MachO::LC_REEXPORT_DYLIB)
4471 outs() << " cmd LC_REEXPORT_DYLIB\n";
4472 else if (dl.cmd == MachO::LC_LAZY_LOAD_DYLIB)
4473 outs() << " cmd LC_LAZY_LOAD_DYLIB\n";
4474 else if (dl.cmd == MachO::LC_LOAD_UPWARD_DYLIB)
4475 outs() << " cmd LC_LOAD_UPWARD_DYLIB\n";
4477 outs() << " cmd " << dl.cmd << " (unknown)\n";
4478 outs() << " cmdsize " << dl.cmdsize;
4479 if (dl.cmdsize < sizeof(struct MachO::dylib_command))
4480 outs() << " Incorrect size\n";
4483 if (dl.dylib.name < dl.cmdsize) {
4484 const char *P = (const char *)(Ptr) + dl.dylib.name;
4485 outs() << " name " << P << " (offset " << dl.dylib.name << ")\n";
4487 outs() << " name ?(bad offset " << dl.dylib.name << ")\n";
4489 outs() << " time stamp " << dl.dylib.timestamp << " ";
4490 time_t t = dl.dylib.timestamp;
4491 outs() << ctime(&t);
4492 outs() << " current version ";
4493 if (dl.dylib.current_version == 0xffffffff)
4496 outs() << ((dl.dylib.current_version >> 16) & 0xffff) << "."
4497 << ((dl.dylib.current_version >> 8) & 0xff) << "."
4498 << (dl.dylib.current_version & 0xff) << "\n";
4499 outs() << "compatibility version ";
4500 if (dl.dylib.compatibility_version == 0xffffffff)
4503 outs() << ((dl.dylib.compatibility_version >> 16) & 0xffff) << "."
4504 << ((dl.dylib.compatibility_version >> 8) & 0xff) << "."
4505 << (dl.dylib.compatibility_version & 0xff) << "\n";
4508 static void PrintLinkEditDataCommand(MachO::linkedit_data_command ld,
4509 uint32_t object_size) {
4510 if (ld.cmd == MachO::LC_CODE_SIGNATURE)
4511 outs() << " cmd LC_FUNCTION_STARTS\n";
4512 else if (ld.cmd == MachO::LC_SEGMENT_SPLIT_INFO)
4513 outs() << " cmd LC_SEGMENT_SPLIT_INFO\n";
4514 else if (ld.cmd == MachO::LC_FUNCTION_STARTS)
4515 outs() << " cmd LC_FUNCTION_STARTS\n";
4516 else if (ld.cmd == MachO::LC_DATA_IN_CODE)
4517 outs() << " cmd LC_DATA_IN_CODE\n";
4518 else if (ld.cmd == MachO::LC_DYLIB_CODE_SIGN_DRS)
4519 outs() << " cmd LC_DYLIB_CODE_SIGN_DRS\n";
4520 else if (ld.cmd == MachO::LC_LINKER_OPTIMIZATION_HINT)
4521 outs() << " cmd LC_LINKER_OPTIMIZATION_HINT\n";
4523 outs() << " cmd " << ld.cmd << " (?)\n";
4524 outs() << " cmdsize " << ld.cmdsize;
4525 if (ld.cmdsize != sizeof(struct MachO::linkedit_data_command))
4526 outs() << " Incorrect size\n";
4529 outs() << " dataoff " << ld.dataoff;
4530 if (ld.dataoff > object_size)
4531 outs() << " (past end of file)\n";
4534 outs() << " datasize " << ld.datasize;
4535 uint64_t big_size = ld.dataoff;
4536 big_size += ld.datasize;
4537 if (big_size > object_size)
4538 outs() << " (past end of file)\n";
4543 static void PrintLoadCommands(const MachOObjectFile *Obj, uint32_t ncmds,
4544 uint32_t filetype, uint32_t cputype,
4548 StringRef Buf = Obj->getData();
4549 MachOObjectFile::LoadCommandInfo Command = Obj->getFirstLoadCommandInfo();
4550 for (unsigned i = 0;; ++i) {
4551 outs() << "Load command " << i << "\n";
4552 if (Command.C.cmd == MachO::LC_SEGMENT) {
4553 MachO::segment_command SLC = Obj->getSegmentLoadCommand(Command);
4554 const char *sg_segname = SLC.segname;
4555 PrintSegmentCommand(SLC.cmd, SLC.cmdsize, SLC.segname, SLC.vmaddr,
4556 SLC.vmsize, SLC.fileoff, SLC.filesize, SLC.maxprot,
4557 SLC.initprot, SLC.nsects, SLC.flags, Buf.size(),
4559 for (unsigned j = 0; j < SLC.nsects; j++) {
4560 MachO::section S = Obj->getSection(Command, j);
4561 PrintSection(S.sectname, S.segname, S.addr, S.size, S.offset, S.align,
4562 S.reloff, S.nreloc, S.flags, S.reserved1, S.reserved2,
4563 SLC.cmd, sg_segname, filetype, Buf.size(), verbose);
4565 } else if (Command.C.cmd == MachO::LC_SEGMENT_64) {
4566 MachO::segment_command_64 SLC_64 = Obj->getSegment64LoadCommand(Command);
4567 const char *sg_segname = SLC_64.segname;
4568 PrintSegmentCommand(SLC_64.cmd, SLC_64.cmdsize, SLC_64.segname,
4569 SLC_64.vmaddr, SLC_64.vmsize, SLC_64.fileoff,
4570 SLC_64.filesize, SLC_64.maxprot, SLC_64.initprot,
4571 SLC_64.nsects, SLC_64.flags, Buf.size(), verbose);
4572 for (unsigned j = 0; j < SLC_64.nsects; j++) {
4573 MachO::section_64 S_64 = Obj->getSection64(Command, j);
4574 PrintSection(S_64.sectname, S_64.segname, S_64.addr, S_64.size,
4575 S_64.offset, S_64.align, S_64.reloff, S_64.nreloc,
4576 S_64.flags, S_64.reserved1, S_64.reserved2, SLC_64.cmd,
4577 sg_segname, filetype, Buf.size(), verbose);
4579 } else if (Command.C.cmd == MachO::LC_SYMTAB) {
4580 MachO::symtab_command Symtab = Obj->getSymtabLoadCommand();
4581 PrintSymtabLoadCommand(Symtab, Obj->is64Bit(), Buf.size());
4582 } else if (Command.C.cmd == MachO::LC_DYSYMTAB) {
4583 MachO::dysymtab_command Dysymtab = Obj->getDysymtabLoadCommand();
4584 MachO::symtab_command Symtab = Obj->getSymtabLoadCommand();
4585 PrintDysymtabLoadCommand(Dysymtab, Symtab.nsyms, Buf.size(),
4587 } else if (Command.C.cmd == MachO::LC_DYLD_INFO ||
4588 Command.C.cmd == MachO::LC_DYLD_INFO_ONLY) {
4589 MachO::dyld_info_command DyldInfo = Obj->getDyldInfoLoadCommand(Command);
4590 PrintDyldInfoLoadCommand(DyldInfo, Buf.size());
4591 } else if (Command.C.cmd == MachO::LC_LOAD_DYLINKER ||
4592 Command.C.cmd == MachO::LC_ID_DYLINKER ||
4593 Command.C.cmd == MachO::LC_DYLD_ENVIRONMENT) {
4594 MachO::dylinker_command Dyld = Obj->getDylinkerCommand(Command);
4595 PrintDyldLoadCommand(Dyld, Command.Ptr);
4596 } else if (Command.C.cmd == MachO::LC_UUID) {
4597 MachO::uuid_command Uuid = Obj->getUuidCommand(Command);
4598 PrintUuidLoadCommand(Uuid);
4599 } else if (Command.C.cmd == MachO::LC_RPATH) {
4600 MachO::rpath_command Rpath = Obj->getRpathCommand(Command);
4601 PrintRpathLoadCommand(Rpath, Command.Ptr);
4602 } else if (Command.C.cmd == MachO::LC_VERSION_MIN_MACOSX ||
4603 Command.C.cmd == MachO::LC_VERSION_MIN_IPHONEOS) {
4604 MachO::version_min_command Vd = Obj->getVersionMinLoadCommand(Command);
4605 PrintVersionMinLoadCommand(Vd);
4606 } else if (Command.C.cmd == MachO::LC_SOURCE_VERSION) {
4607 MachO::source_version_command Sd = Obj->getSourceVersionCommand(Command);
4608 PrintSourceVersionCommand(Sd);
4609 } else if (Command.C.cmd == MachO::LC_MAIN) {
4610 MachO::entry_point_command Ep = Obj->getEntryPointCommand(Command);
4611 PrintEntryPointCommand(Ep);
4612 } else if (Command.C.cmd == MachO::LC_ENCRYPTION_INFO) {
4613 MachO::encryption_info_command Ei =
4614 Obj->getEncryptionInfoCommand(Command);
4615 PrintEncryptionInfoCommand(Ei, Buf.size());
4616 } else if (Command.C.cmd == MachO::LC_ENCRYPTION_INFO_64) {
4617 MachO::encryption_info_command_64 Ei =
4618 Obj->getEncryptionInfoCommand64(Command);
4619 PrintEncryptionInfoCommand64(Ei, Buf.size());
4620 } else if (Command.C.cmd == MachO::LC_LINKER_OPTION) {
4621 MachO::linker_option_command Lo =
4622 Obj->getLinkerOptionLoadCommand(Command);
4623 PrintLinkerOptionCommand(Lo, Command.Ptr);
4624 } else if (Command.C.cmd == MachO::LC_SUB_FRAMEWORK) {
4625 MachO::sub_framework_command Sf = Obj->getSubFrameworkCommand(Command);
4626 PrintSubFrameworkCommand(Sf, Command.Ptr);
4627 } else if (Command.C.cmd == MachO::LC_SUB_UMBRELLA) {
4628 MachO::sub_umbrella_command Sf = Obj->getSubUmbrellaCommand(Command);
4629 PrintSubUmbrellaCommand(Sf, Command.Ptr);
4630 } else if (Command.C.cmd == MachO::LC_SUB_LIBRARY) {
4631 MachO::sub_library_command Sl = Obj->getSubLibraryCommand(Command);
4632 PrintSubLibraryCommand(Sl, Command.Ptr);
4633 } else if (Command.C.cmd == MachO::LC_SUB_CLIENT) {
4634 MachO::sub_client_command Sc = Obj->getSubClientCommand(Command);
4635 PrintSubClientCommand(Sc, Command.Ptr);
4636 } else if (Command.C.cmd == MachO::LC_ROUTINES) {
4637 MachO::routines_command Rc = Obj->getRoutinesCommand(Command);
4638 PrintRoutinesCommand(Rc);
4639 } else if (Command.C.cmd == MachO::LC_ROUTINES_64) {
4640 MachO::routines_command_64 Rc = Obj->getRoutinesCommand64(Command);
4641 PrintRoutinesCommand64(Rc);
4642 } else if (Command.C.cmd == MachO::LC_THREAD ||
4643 Command.C.cmd == MachO::LC_UNIXTHREAD) {
4644 MachO::thread_command Tc = Obj->getThreadCommand(Command);
4645 PrintThreadCommand(Tc, Command.Ptr, Obj->isLittleEndian(), cputype);
4646 } else if (Command.C.cmd == MachO::LC_LOAD_DYLIB ||
4647 Command.C.cmd == MachO::LC_ID_DYLIB ||
4648 Command.C.cmd == MachO::LC_LOAD_WEAK_DYLIB ||
4649 Command.C.cmd == MachO::LC_REEXPORT_DYLIB ||
4650 Command.C.cmd == MachO::LC_LAZY_LOAD_DYLIB ||
4651 Command.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB) {
4652 MachO::dylib_command Dl = Obj->getDylibIDLoadCommand(Command);
4653 PrintDylibCommand(Dl, Command.Ptr);
4654 } else if (Command.C.cmd == MachO::LC_CODE_SIGNATURE ||
4655 Command.C.cmd == MachO::LC_SEGMENT_SPLIT_INFO ||
4656 Command.C.cmd == MachO::LC_FUNCTION_STARTS ||
4657 Command.C.cmd == MachO::LC_DATA_IN_CODE ||
4658 Command.C.cmd == MachO::LC_DYLIB_CODE_SIGN_DRS ||
4659 Command.C.cmd == MachO::LC_LINKER_OPTIMIZATION_HINT) {
4660 MachO::linkedit_data_command Ld =
4661 Obj->getLinkeditDataLoadCommand(Command);
4662 PrintLinkEditDataCommand(Ld, Buf.size());
4664 outs() << " cmd ?(" << format("0x%08" PRIx32, Command.C.cmd)
4666 outs() << " cmdsize " << Command.C.cmdsize << "\n";
4667 // TODO: get and print the raw bytes of the load command.
4669 // TODO: print all the other kinds of load commands.
4673 Command = Obj->getNextLoadCommandInfo(Command);
4677 static void getAndPrintMachHeader(const MachOObjectFile *Obj, uint32_t &ncmds,
4678 uint32_t &filetype, uint32_t &cputype,
4680 if (Obj->is64Bit()) {
4681 MachO::mach_header_64 H_64;
4682 H_64 = Obj->getHeader64();
4683 PrintMachHeader(H_64.magic, H_64.cputype, H_64.cpusubtype, H_64.filetype,
4684 H_64.ncmds, H_64.sizeofcmds, H_64.flags, verbose);
4686 filetype = H_64.filetype;
4687 cputype = H_64.cputype;
4689 MachO::mach_header H;
4690 H = Obj->getHeader();
4691 PrintMachHeader(H.magic, H.cputype, H.cpusubtype, H.filetype, H.ncmds,
4692 H.sizeofcmds, H.flags, verbose);
4694 filetype = H.filetype;
4695 cputype = H.cputype;
4699 void llvm::printMachOFileHeader(const object::ObjectFile *Obj) {
4700 const MachOObjectFile *file = dyn_cast<const MachOObjectFile>(Obj);
4702 uint32_t filetype = 0;
4703 uint32_t cputype = 0;
4704 getAndPrintMachHeader(file, ncmds, filetype, cputype, true);
4705 PrintLoadCommands(file, ncmds, filetype, cputype, true);
4708 //===----------------------------------------------------------------------===//
4709 // export trie dumping
4710 //===----------------------------------------------------------------------===//
4712 void llvm::printMachOExportsTrie(const object::MachOObjectFile *Obj) {
4713 for (const llvm::object::ExportEntry &Entry : Obj->exports()) {
4714 uint64_t Flags = Entry.flags();
4715 bool ReExport = (Flags & MachO::EXPORT_SYMBOL_FLAGS_REEXPORT);
4716 bool WeakDef = (Flags & MachO::EXPORT_SYMBOL_FLAGS_WEAK_DEFINITION);
4717 bool ThreadLocal = ((Flags & MachO::EXPORT_SYMBOL_FLAGS_KIND_MASK) ==
4718 MachO::EXPORT_SYMBOL_FLAGS_KIND_THREAD_LOCAL);
4719 bool Abs = ((Flags & MachO::EXPORT_SYMBOL_FLAGS_KIND_MASK) ==
4720 MachO::EXPORT_SYMBOL_FLAGS_KIND_ABSOLUTE);
4721 bool Resolver = (Flags & MachO::EXPORT_SYMBOL_FLAGS_STUB_AND_RESOLVER);
4723 outs() << "[re-export] ";
4725 outs() << format("0x%08llX ",
4726 Entry.address()); // FIXME:add in base address
4727 outs() << Entry.name();
4728 if (WeakDef || ThreadLocal || Resolver || Abs) {
4729 bool NeedsComma = false;
4732 outs() << "weak_def";
4738 outs() << "per-thread";
4744 outs() << "absolute";
4750 outs() << format("resolver=0x%08llX", Entry.other());
4756 StringRef DylibName = "unknown";
4757 int Ordinal = Entry.other() - 1;
4758 Obj->getLibraryShortNameByIndex(Ordinal, DylibName);
4759 if (Entry.otherName().empty())
4760 outs() << " (from " << DylibName << ")";
4762 outs() << " (" << Entry.otherName() << " from " << DylibName << ")";
4768 //===----------------------------------------------------------------------===//
4769 // rebase table dumping
4770 //===----------------------------------------------------------------------===//
4775 SegInfo(const object::MachOObjectFile *Obj);
4777 StringRef segmentName(uint32_t SegIndex);
4778 StringRef sectionName(uint32_t SegIndex, uint64_t SegOffset);
4779 uint64_t address(uint32_t SegIndex, uint64_t SegOffset);
4782 struct SectionInfo {
4785 StringRef SectionName;
4786 StringRef SegmentName;
4787 uint64_t OffsetInSegment;
4788 uint64_t SegmentStartAddress;
4789 uint32_t SegmentIndex;
4791 const SectionInfo &findSection(uint32_t SegIndex, uint64_t SegOffset);
4792 SmallVector<SectionInfo, 32> Sections;
4796 SegInfo::SegInfo(const object::MachOObjectFile *Obj) {
4797 // Build table of sections so segIndex/offset pairs can be translated.
4798 uint32_t CurSegIndex = Obj->hasPageZeroSegment() ? 1 : 0;
4799 StringRef CurSegName;
4800 uint64_t CurSegAddress;
4801 for (const SectionRef &Section : Obj->sections()) {
4803 if (error(Section.getName(Info.SectionName)))
4805 Info.Address = Section.getAddress();
4806 Info.Size = Section.getSize();
4808 Obj->getSectionFinalSegmentName(Section.getRawDataRefImpl());
4809 if (!Info.SegmentName.equals(CurSegName)) {
4811 CurSegName = Info.SegmentName;
4812 CurSegAddress = Info.Address;
4814 Info.SegmentIndex = CurSegIndex - 1;
4815 Info.OffsetInSegment = Info.Address - CurSegAddress;
4816 Info.SegmentStartAddress = CurSegAddress;
4817 Sections.push_back(Info);
4821 StringRef SegInfo::segmentName(uint32_t SegIndex) {
4822 for (const SectionInfo &SI : Sections) {
4823 if (SI.SegmentIndex == SegIndex)
4824 return SI.SegmentName;
4826 llvm_unreachable("invalid segIndex");
4829 const SegInfo::SectionInfo &SegInfo::findSection(uint32_t SegIndex,
4830 uint64_t OffsetInSeg) {
4831 for (const SectionInfo &SI : Sections) {
4832 if (SI.SegmentIndex != SegIndex)
4834 if (SI.OffsetInSegment > OffsetInSeg)
4836 if (OffsetInSeg >= (SI.OffsetInSegment + SI.Size))
4840 llvm_unreachable("segIndex and offset not in any section");
4843 StringRef SegInfo::sectionName(uint32_t SegIndex, uint64_t OffsetInSeg) {
4844 return findSection(SegIndex, OffsetInSeg).SectionName;
4847 uint64_t SegInfo::address(uint32_t SegIndex, uint64_t OffsetInSeg) {
4848 const SectionInfo &SI = findSection(SegIndex, OffsetInSeg);
4849 return SI.SegmentStartAddress + OffsetInSeg;
4852 void llvm::printMachORebaseTable(const object::MachOObjectFile *Obj) {
4853 // Build table of sections so names can used in final output.
4854 SegInfo sectionTable(Obj);
4856 outs() << "segment section address type\n";
4857 for (const llvm::object::MachORebaseEntry &Entry : Obj->rebaseTable()) {
4858 uint32_t SegIndex = Entry.segmentIndex();
4859 uint64_t OffsetInSeg = Entry.segmentOffset();
4860 StringRef SegmentName = sectionTable.segmentName(SegIndex);
4861 StringRef SectionName = sectionTable.sectionName(SegIndex, OffsetInSeg);
4862 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
4864 // Table lines look like: __DATA __nl_symbol_ptr 0x0000F00C pointer
4865 outs() << format("%-8s %-18s 0x%08" PRIX64 " %s\n",
4866 SegmentName.str().c_str(), SectionName.str().c_str(),
4867 Address, Entry.typeName().str().c_str());
4871 static StringRef ordinalName(const object::MachOObjectFile *Obj, int Ordinal) {
4872 StringRef DylibName;
4874 case MachO::BIND_SPECIAL_DYLIB_SELF:
4875 return "this-image";
4876 case MachO::BIND_SPECIAL_DYLIB_MAIN_EXECUTABLE:
4877 return "main-executable";
4878 case MachO::BIND_SPECIAL_DYLIB_FLAT_LOOKUP:
4879 return "flat-namespace";
4882 std::error_code EC =
4883 Obj->getLibraryShortNameByIndex(Ordinal - 1, DylibName);
4885 return "<<bad library ordinal>>";
4889 return "<<unknown special ordinal>>";
4892 //===----------------------------------------------------------------------===//
4893 // bind table dumping
4894 //===----------------------------------------------------------------------===//
4896 void llvm::printMachOBindTable(const object::MachOObjectFile *Obj) {
4897 // Build table of sections so names can used in final output.
4898 SegInfo sectionTable(Obj);
4900 outs() << "segment section address type "
4901 "addend dylib symbol\n";
4902 for (const llvm::object::MachOBindEntry &Entry : Obj->bindTable()) {
4903 uint32_t SegIndex = Entry.segmentIndex();
4904 uint64_t OffsetInSeg = Entry.segmentOffset();
4905 StringRef SegmentName = sectionTable.segmentName(SegIndex);
4906 StringRef SectionName = sectionTable.sectionName(SegIndex, OffsetInSeg);
4907 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
4909 // Table lines look like:
4910 // __DATA __got 0x00012010 pointer 0 libSystem ___stack_chk_guard
4912 if (Entry.flags() & MachO::BIND_SYMBOL_FLAGS_WEAK_IMPORT)
4913 Attr = " (weak_import)";
4914 outs() << left_justify(SegmentName, 8) << " "
4915 << left_justify(SectionName, 18) << " "
4916 << format_hex(Address, 10, true) << " "
4917 << left_justify(Entry.typeName(), 8) << " "
4918 << format_decimal(Entry.addend(), 8) << " "
4919 << left_justify(ordinalName(Obj, Entry.ordinal()), 16) << " "
4920 << Entry.symbolName() << Attr << "\n";
4924 //===----------------------------------------------------------------------===//
4925 // lazy bind table dumping
4926 //===----------------------------------------------------------------------===//
4928 void llvm::printMachOLazyBindTable(const object::MachOObjectFile *Obj) {
4929 // Build table of sections so names can used in final output.
4930 SegInfo sectionTable(Obj);
4932 outs() << "segment section address "
4934 for (const llvm::object::MachOBindEntry &Entry : Obj->lazyBindTable()) {
4935 uint32_t SegIndex = Entry.segmentIndex();
4936 uint64_t OffsetInSeg = Entry.segmentOffset();
4937 StringRef SegmentName = sectionTable.segmentName(SegIndex);
4938 StringRef SectionName = sectionTable.sectionName(SegIndex, OffsetInSeg);
4939 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
4941 // Table lines look like:
4942 // __DATA __got 0x00012010 libSystem ___stack_chk_guard
4943 outs() << left_justify(SegmentName, 8) << " "
4944 << left_justify(SectionName, 18) << " "
4945 << format_hex(Address, 10, true) << " "
4946 << left_justify(ordinalName(Obj, Entry.ordinal()), 16) << " "
4947 << Entry.symbolName() << "\n";
4951 //===----------------------------------------------------------------------===//
4952 // weak bind table dumping
4953 //===----------------------------------------------------------------------===//
4955 void llvm::printMachOWeakBindTable(const object::MachOObjectFile *Obj) {
4956 // Build table of sections so names can used in final output.
4957 SegInfo sectionTable(Obj);
4959 outs() << "segment section address "
4960 "type addend symbol\n";
4961 for (const llvm::object::MachOBindEntry &Entry : Obj->weakBindTable()) {
4962 // Strong symbols don't have a location to update.
4963 if (Entry.flags() & MachO::BIND_SYMBOL_FLAGS_NON_WEAK_DEFINITION) {
4964 outs() << " strong "
4965 << Entry.symbolName() << "\n";
4968 uint32_t SegIndex = Entry.segmentIndex();
4969 uint64_t OffsetInSeg = Entry.segmentOffset();
4970 StringRef SegmentName = sectionTable.segmentName(SegIndex);
4971 StringRef SectionName = sectionTable.sectionName(SegIndex, OffsetInSeg);
4972 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
4974 // Table lines look like:
4975 // __DATA __data 0x00001000 pointer 0 _foo
4976 outs() << left_justify(SegmentName, 8) << " "
4977 << left_justify(SectionName, 18) << " "
4978 << format_hex(Address, 10, true) << " "
4979 << left_justify(Entry.typeName(), 8) << " "
4980 << format_decimal(Entry.addend(), 8) << " " << Entry.symbolName()
4985 // get_dyld_bind_info_symbolname() is used for disassembly and passed an
4986 // address, ReferenceValue, in the Mach-O file and looks in the dyld bind
4987 // information for that address. If the address is found its binding symbol
4988 // name is returned. If not nullptr is returned.
4989 static const char *get_dyld_bind_info_symbolname(uint64_t ReferenceValue,
4990 struct DisassembleInfo *info) {
4991 if (info->bindtable == nullptr) {
4992 info->bindtable = new (BindTable);
4993 SegInfo sectionTable(info->O);
4994 for (const llvm::object::MachOBindEntry &Entry : info->O->bindTable()) {
4995 uint32_t SegIndex = Entry.segmentIndex();
4996 uint64_t OffsetInSeg = Entry.segmentOffset();
4997 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
4998 const char *SymbolName = nullptr;
4999 StringRef name = Entry.symbolName();
5001 SymbolName = name.data();
5002 info->bindtable->push_back(std::make_pair(Address, SymbolName));
5005 for (bind_table_iterator BI = info->bindtable->begin(),
5006 BE = info->bindtable->end();
5008 uint64_t Address = BI->first;
5009 if (ReferenceValue == Address) {
5010 const char *SymbolName = BI->second;