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/GraphWriter.h"
38 #include "llvm/Support/MachO.h"
39 #include "llvm/Support/MemoryBuffer.h"
40 #include "llvm/Support/FormattedStream.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 static cl::list<std::string>
70 ArchFlags("arch", cl::desc("architecture(s) from a Mach-O file to dump"),
74 static std::string ThumbTripleName;
76 static const Target *GetTarget(const MachOObjectFile *MachOObj,
77 const char **McpuDefault,
78 const Target **ThumbTarget) {
79 // Figure out the target triple.
80 if (TripleName.empty()) {
81 llvm::Triple TT("unknown-unknown-unknown");
82 llvm::Triple ThumbTriple = Triple();
83 TT = MachOObj->getArch(McpuDefault, &ThumbTriple);
84 TripleName = TT.str();
85 ThumbTripleName = ThumbTriple.str();
88 // Get the target specific parser.
90 const Target *TheTarget = TargetRegistry::lookupTarget(TripleName, Error);
91 if (TheTarget && ThumbTripleName.empty())
94 *ThumbTarget = TargetRegistry::lookupTarget(ThumbTripleName, Error);
98 errs() << "llvm-objdump: error: unable to get target for '";
100 errs() << TripleName;
102 errs() << ThumbTripleName;
103 errs() << "', see --version and --triple.\n";
107 struct SymbolSorter {
108 bool operator()(const SymbolRef &A, const SymbolRef &B) {
109 SymbolRef::Type AType, BType;
113 uint64_t AAddr, BAddr;
114 if (AType != SymbolRef::ST_Function)
118 if (BType != SymbolRef::ST_Function)
122 return AAddr < BAddr;
126 // Types for the storted data in code table that is built before disassembly
127 // and the predicate function to sort them.
128 typedef std::pair<uint64_t, DiceRef> DiceTableEntry;
129 typedef std::vector<DiceTableEntry> DiceTable;
130 typedef DiceTable::iterator dice_table_iterator;
132 // This is used to search for a data in code table entry for the PC being
133 // disassembled. The j parameter has the PC in j.first. A single data in code
134 // table entry can cover many bytes for each of its Kind's. So if the offset,
135 // aka the i.first value, of the data in code table entry plus its Length
136 // covers the PC being searched for this will return true. If not it will
138 static bool compareDiceTableEntries(const DiceTableEntry &i,
139 const DiceTableEntry &j) {
141 i.second.getLength(Length);
143 return j.first >= i.first && j.first < i.first + Length;
146 static uint64_t DumpDataInCode(const char *bytes, uint64_t Length,
147 unsigned short Kind) {
148 uint32_t Value, Size = 1;
152 case MachO::DICE_KIND_DATA:
155 DumpBytes(StringRef(bytes, 4));
156 Value = bytes[3] << 24 | bytes[2] << 16 | bytes[1] << 8 | bytes[0];
157 outs() << "\t.long " << Value;
159 } else if (Length >= 2) {
161 DumpBytes(StringRef(bytes, 2));
162 Value = bytes[1] << 8 | bytes[0];
163 outs() << "\t.short " << Value;
167 DumpBytes(StringRef(bytes, 2));
169 outs() << "\t.byte " << Value;
172 if (Kind == MachO::DICE_KIND_DATA)
173 outs() << "\t@ KIND_DATA\n";
175 outs() << "\t@ data in code kind = " << Kind << "\n";
177 case MachO::DICE_KIND_JUMP_TABLE8:
179 DumpBytes(StringRef(bytes, 1));
181 outs() << "\t.byte " << format("%3u", Value) << "\t@ KIND_JUMP_TABLE8\n";
184 case MachO::DICE_KIND_JUMP_TABLE16:
186 DumpBytes(StringRef(bytes, 2));
187 Value = bytes[1] << 8 | bytes[0];
188 outs() << "\t.short " << format("%5u", Value & 0xffff)
189 << "\t@ KIND_JUMP_TABLE16\n";
192 case MachO::DICE_KIND_JUMP_TABLE32:
193 case MachO::DICE_KIND_ABS_JUMP_TABLE32:
195 DumpBytes(StringRef(bytes, 4));
196 Value = bytes[3] << 24 | bytes[2] << 16 | bytes[1] << 8 | bytes[0];
197 outs() << "\t.long " << Value;
198 if (Kind == MachO::DICE_KIND_JUMP_TABLE32)
199 outs() << "\t@ KIND_JUMP_TABLE32\n";
201 outs() << "\t@ KIND_ABS_JUMP_TABLE32\n";
208 static void getSectionsAndSymbols(const MachO::mach_header Header,
209 MachOObjectFile *MachOObj,
210 std::vector<SectionRef> &Sections,
211 std::vector<SymbolRef> &Symbols,
212 SmallVectorImpl<uint64_t> &FoundFns,
213 uint64_t &BaseSegmentAddress) {
214 for (const SymbolRef &Symbol : MachOObj->symbols()) {
216 Symbol.getName(SymName);
217 if (!SymName.startswith("ltmp"))
218 Symbols.push_back(Symbol);
221 for (const SectionRef &Section : MachOObj->sections()) {
223 Section.getName(SectName);
224 Sections.push_back(Section);
227 MachOObjectFile::LoadCommandInfo Command =
228 MachOObj->getFirstLoadCommandInfo();
229 bool BaseSegmentAddressSet = false;
230 for (unsigned i = 0;; ++i) {
231 if (Command.C.cmd == MachO::LC_FUNCTION_STARTS) {
232 // We found a function starts segment, parse the addresses for later
234 MachO::linkedit_data_command LLC =
235 MachOObj->getLinkeditDataLoadCommand(Command);
237 MachOObj->ReadULEB128s(LLC.dataoff, FoundFns);
238 } else if (Command.C.cmd == MachO::LC_SEGMENT) {
239 MachO::segment_command SLC = MachOObj->getSegmentLoadCommand(Command);
240 StringRef SegName = SLC.segname;
241 if (!BaseSegmentAddressSet && SegName != "__PAGEZERO") {
242 BaseSegmentAddressSet = true;
243 BaseSegmentAddress = SLC.vmaddr;
247 if (i == Header.ncmds - 1)
250 Command = MachOObj->getNextLoadCommandInfo(Command);
254 // checkMachOAndArchFlags() checks to see if the ObjectFile is a Mach-O file
255 // and if it is and there is a list of architecture flags is specified then
256 // check to make sure this Mach-O file is one of those architectures or all
257 // architectures were specified. If not then an error is generated and this
258 // routine returns false. Else it returns true.
259 static bool checkMachOAndArchFlags(ObjectFile *O, StringRef Filename) {
260 if (isa<MachOObjectFile>(O) && !ArchAll && ArchFlags.size() != 0) {
261 MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(O);
262 bool ArchFound = false;
263 MachO::mach_header H;
264 MachO::mach_header_64 H_64;
266 if (MachO->is64Bit()) {
267 H_64 = MachO->MachOObjectFile::getHeader64();
268 T = MachOObjectFile::getArch(H_64.cputype, H_64.cpusubtype);
270 H = MachO->MachOObjectFile::getHeader();
271 T = MachOObjectFile::getArch(H.cputype, H.cpusubtype);
274 for (i = 0; i < ArchFlags.size(); ++i) {
275 if (ArchFlags[i] == T.getArchName())
280 errs() << "llvm-objdump: file: " + Filename + " does not contain "
281 << "architecture: " + ArchFlags[i] + "\n";
288 static void DisassembleInputMachO2(StringRef Filename, MachOObjectFile *MachOOF,
289 StringRef ArchiveMemberName = StringRef(),
290 StringRef ArchitectureName = StringRef());
292 void llvm::DisassembleInputMachO(StringRef Filename) {
293 // Check for -arch all and verifiy the -arch flags are valid.
294 for (unsigned i = 0; i < ArchFlags.size(); ++i) {
295 if (ArchFlags[i] == "all") {
298 if (!MachOObjectFile::isValidArch(ArchFlags[i])) {
299 errs() << "llvm-objdump: Unknown architecture named '" + ArchFlags[i] +
300 "'for the -arch option\n";
306 // Attempt to open the binary.
307 ErrorOr<OwningBinary<Binary>> BinaryOrErr = createBinary(Filename);
308 if (std::error_code EC = BinaryOrErr.getError()) {
309 errs() << "llvm-objdump: '" << Filename << "': " << EC.message() << ".\n";
312 Binary &Bin = *BinaryOrErr.get().getBinary();
314 if (Archive *A = dyn_cast<Archive>(&Bin)) {
315 outs() << "Archive : " << Filename << "\n";
316 for (Archive::child_iterator I = A->child_begin(), E = A->child_end();
318 ErrorOr<std::unique_ptr<Binary>> ChildOrErr = I->getAsBinary();
319 if (ChildOrErr.getError())
321 if (MachOObjectFile *O = dyn_cast<MachOObjectFile>(&*ChildOrErr.get())) {
322 if (!checkMachOAndArchFlags(O, Filename))
324 DisassembleInputMachO2(Filename, O, O->getFileName());
329 if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(&Bin)) {
330 // If we have a list of architecture flags specified dump only those.
331 if (!ArchAll && ArchFlags.size() != 0) {
332 // Look for a slice in the universal binary that matches each ArchFlag.
334 for (unsigned i = 0; i < ArchFlags.size(); ++i) {
336 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
337 E = UB->end_objects();
339 if (ArchFlags[i] == I->getArchTypeName()) {
341 ErrorOr<std::unique_ptr<ObjectFile>> ObjOrErr =
342 I->getAsObjectFile();
343 std::unique_ptr<Archive> A;
344 StringRef ArchitectureName = StringRef();
345 if (ArchFlags.size() > 1)
346 ArchitectureName = I->getArchTypeName();
348 ObjectFile &O = *ObjOrErr.get();
349 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&O))
350 DisassembleInputMachO2(Filename, MachOOF, "", ArchitectureName);
351 } else if (!I->getAsArchive(A)) {
352 outs() << "Archive : " << Filename;
353 if (!ArchitectureName.empty())
354 outs() << " (architecture " << ArchitectureName << ")";
356 for (Archive::child_iterator AI = A->child_begin(),
359 ErrorOr<std::unique_ptr<Binary>> ChildOrErr = AI->getAsBinary();
360 if (ChildOrErr.getError())
362 if (MachOObjectFile *O =
363 dyn_cast<MachOObjectFile>(&*ChildOrErr.get()))
364 DisassembleInputMachO2(Filename, O, O->getFileName(),
371 errs() << "llvm-objdump: file: " + Filename + " does not contain "
372 << "architecture: " + ArchFlags[i] + "\n";
378 // No architecture flags were specified so if this contains a slice that
379 // matches the host architecture dump only that.
381 StringRef HostArchName = MachOObjectFile::getHostArch().getArchName();
382 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
383 E = UB->end_objects();
385 if (HostArchName == I->getArchTypeName()) {
386 ErrorOr<std::unique_ptr<ObjectFile>> ObjOrErr = I->getAsObjectFile();
387 std::unique_ptr<Archive> A;
388 std::string ArchiveName;
391 ObjectFile &O = *ObjOrErr.get();
392 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&O))
393 DisassembleInputMachO2(Filename, MachOOF);
394 } else if (!I->getAsArchive(A)) {
395 outs() << "Archive : " << Filename << "\n";
396 for (Archive::child_iterator AI = A->child_begin(),
399 ErrorOr<std::unique_ptr<Binary>> ChildOrErr = AI->getAsBinary();
400 if (ChildOrErr.getError())
402 if (MachOObjectFile *O =
403 dyn_cast<MachOObjectFile>(&*ChildOrErr.get()))
404 DisassembleInputMachO2(Filename, O, O->getFileName());
411 // Either all architectures have been specified or none have been specified
412 // and this does not contain the host architecture so dump all the slices.
413 bool moreThanOneArch = UB->getNumberOfObjects() > 1;
414 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
415 E = UB->end_objects();
417 ErrorOr<std::unique_ptr<ObjectFile>> ObjOrErr = I->getAsObjectFile();
418 std::unique_ptr<Archive> A;
419 StringRef ArchitectureName = StringRef();
421 ArchitectureName = I->getArchTypeName();
423 ObjectFile &Obj = *ObjOrErr.get();
424 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&Obj))
425 DisassembleInputMachO2(Filename, MachOOF, "", ArchitectureName);
426 } else if (!I->getAsArchive(A)) {
427 outs() << "Archive : " << Filename;
428 if (!ArchitectureName.empty())
429 outs() << " (architecture " << ArchitectureName << ")";
431 for (Archive::child_iterator AI = A->child_begin(), AE = A->child_end();
433 ErrorOr<std::unique_ptr<Binary>> ChildOrErr = AI->getAsBinary();
434 if (ChildOrErr.getError())
436 if (MachOObjectFile *O =
437 dyn_cast<MachOObjectFile>(&*ChildOrErr.get())) {
438 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(O))
439 DisassembleInputMachO2(Filename, MachOOF, MachOOF->getFileName(),
447 if (ObjectFile *O = dyn_cast<ObjectFile>(&Bin)) {
448 if (!checkMachOAndArchFlags(O, Filename))
450 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&*O)) {
451 DisassembleInputMachO2(Filename, MachOOF);
453 errs() << "llvm-objdump: '" << Filename << "': "
454 << "Object is not a Mach-O file type.\n";
456 errs() << "llvm-objdump: '" << Filename << "': "
457 << "Unrecognized file type.\n";
460 typedef DenseMap<uint64_t, StringRef> SymbolAddressMap;
461 typedef std::pair<uint64_t, const char *> BindInfoEntry;
462 typedef std::vector<BindInfoEntry> BindTable;
463 typedef BindTable::iterator bind_table_iterator;
465 // The block of info used by the Symbolizer call backs.
466 struct DisassembleInfo {
470 SymbolAddressMap *AddrMap;
471 std::vector<SectionRef> *Sections;
472 const char *class_name;
473 const char *selector_name;
475 char *demangled_name;
478 BindTable *bindtable;
481 // GuessSymbolName is passed the address of what might be a symbol and a
482 // pointer to the DisassembleInfo struct. It returns the name of a symbol
483 // with that address or nullptr if no symbol is found with that address.
484 static const char *GuessSymbolName(uint64_t value,
485 struct DisassembleInfo *info) {
486 const char *SymbolName = nullptr;
487 // A DenseMap can't lookup up some values.
488 if (value != 0xffffffffffffffffULL && value != 0xfffffffffffffffeULL) {
489 StringRef name = info->AddrMap->lookup(value);
491 SymbolName = name.data();
496 // SymbolizerGetOpInfo() is the operand information call back function.
497 // This is called to get the symbolic information for operand(s) of an
498 // instruction when it is being done. This routine does this from
499 // the relocation information, symbol table, etc. That block of information
500 // is a pointer to the struct DisassembleInfo that was passed when the
501 // disassembler context was created and passed to back to here when
502 // called back by the disassembler for instruction operands that could have
503 // relocation information. The address of the instruction containing operand is
504 // at the Pc parameter. The immediate value the operand has is passed in
505 // op_info->Value and is at Offset past the start of the instruction and has a
506 // byte Size of 1, 2 or 4. The symbolc information is returned in TagBuf is the
507 // LLVMOpInfo1 struct defined in the header "llvm-c/Disassembler.h" as symbol
508 // names and addends of the symbolic expression to add for the operand. The
509 // value of TagType is currently 1 (for the LLVMOpInfo1 struct). If symbolic
510 // information is returned then this function returns 1 else it returns 0.
511 int SymbolizerGetOpInfo(void *DisInfo, uint64_t Pc, uint64_t Offset,
512 uint64_t Size, int TagType, void *TagBuf) {
513 struct DisassembleInfo *info = (struct DisassembleInfo *)DisInfo;
514 struct LLVMOpInfo1 *op_info = (struct LLVMOpInfo1 *)TagBuf;
515 uint64_t value = op_info->Value;
517 // Make sure all fields returned are zero if we don't set them.
518 memset((void *)op_info, '\0', sizeof(struct LLVMOpInfo1));
519 op_info->Value = value;
521 // If the TagType is not the value 1 which it code knows about or if no
522 // verbose symbolic information is wanted then just return 0, indicating no
523 // information is being returned.
524 if (TagType != 1 || info->verbose == false)
527 unsigned int Arch = info->O->getArch();
528 if (Arch == Triple::x86) {
529 if (Size != 1 && Size != 2 && Size != 4 && Size != 0)
531 // First search the section's relocation entries (if any) for an entry
532 // for this section offset.
533 uint32_t sect_addr = info->S.getAddress();
534 uint32_t sect_offset = (Pc + Offset) - sect_addr;
535 bool reloc_found = false;
537 MachO::any_relocation_info RE;
538 bool isExtern = false;
540 bool r_scattered = false;
541 uint32_t r_value, pair_r_value, r_type;
542 for (const RelocationRef &Reloc : info->S.relocations()) {
543 uint64_t RelocOffset;
544 Reloc.getOffset(RelocOffset);
545 if (RelocOffset == sect_offset) {
546 Rel = Reloc.getRawDataRefImpl();
547 RE = info->O->getRelocation(Rel);
548 r_type = info->O->getAnyRelocationType(RE);
549 r_scattered = info->O->isRelocationScattered(RE);
551 r_value = info->O->getScatteredRelocationValue(RE);
552 if (r_type == MachO::GENERIC_RELOC_SECTDIFF ||
553 r_type == MachO::GENERIC_RELOC_LOCAL_SECTDIFF) {
554 DataRefImpl RelNext = Rel;
555 info->O->moveRelocationNext(RelNext);
556 MachO::any_relocation_info RENext;
557 RENext = info->O->getRelocation(RelNext);
558 if (info->O->isRelocationScattered(RENext))
559 pair_r_value = info->O->getScatteredRelocationValue(RENext);
564 isExtern = info->O->getPlainRelocationExternal(RE);
566 symbol_iterator RelocSym = Reloc.getSymbol();
574 if (reloc_found && isExtern) {
576 Symbol.getName(SymName);
577 const char *name = SymName.data();
578 op_info->AddSymbol.Present = 1;
579 op_info->AddSymbol.Name = name;
580 // For i386 extern relocation entries the value in the instruction is
581 // the offset from the symbol, and value is already set in op_info->Value.
584 if (reloc_found && (r_type == MachO::GENERIC_RELOC_SECTDIFF ||
585 r_type == MachO::GENERIC_RELOC_LOCAL_SECTDIFF)) {
586 const char *add = GuessSymbolName(r_value, info);
587 const char *sub = GuessSymbolName(pair_r_value, info);
588 uint32_t offset = value - (r_value - pair_r_value);
589 op_info->AddSymbol.Present = 1;
591 op_info->AddSymbol.Name = add;
593 op_info->AddSymbol.Value = r_value;
594 op_info->SubtractSymbol.Present = 1;
596 op_info->SubtractSymbol.Name = sub;
598 op_info->SubtractSymbol.Value = pair_r_value;
599 op_info->Value = offset;
603 // Second search the external relocation entries of a fully linked image
604 // (if any) for an entry that matches this segment offset.
605 // uint32_t seg_offset = (Pc + Offset);
607 } else if (Arch == Triple::x86_64) {
608 if (Size != 1 && Size != 2 && Size != 4 && Size != 0)
610 // First search the section's relocation entries (if any) for an entry
611 // for this section offset.
612 uint64_t sect_addr = info->S.getAddress();
613 uint64_t sect_offset = (Pc + Offset) - sect_addr;
614 bool reloc_found = false;
616 MachO::any_relocation_info RE;
617 bool isExtern = false;
619 for (const RelocationRef &Reloc : info->S.relocations()) {
620 uint64_t RelocOffset;
621 Reloc.getOffset(RelocOffset);
622 if (RelocOffset == sect_offset) {
623 Rel = Reloc.getRawDataRefImpl();
624 RE = info->O->getRelocation(Rel);
625 // NOTE: Scattered relocations don't exist on x86_64.
626 isExtern = info->O->getPlainRelocationExternal(RE);
628 symbol_iterator RelocSym = Reloc.getSymbol();
635 if (reloc_found && isExtern) {
636 // The Value passed in will be adjusted by the Pc if the instruction
637 // adds the Pc. But for x86_64 external relocation entries the Value
638 // is the offset from the external symbol.
639 if (info->O->getAnyRelocationPCRel(RE))
640 op_info->Value -= Pc + Offset + Size;
642 Symbol.getName(SymName);
643 const char *name = SymName.data();
644 unsigned Type = info->O->getAnyRelocationType(RE);
645 if (Type == MachO::X86_64_RELOC_SUBTRACTOR) {
646 DataRefImpl RelNext = Rel;
647 info->O->moveRelocationNext(RelNext);
648 MachO::any_relocation_info RENext = info->O->getRelocation(RelNext);
649 unsigned TypeNext = info->O->getAnyRelocationType(RENext);
650 bool isExternNext = info->O->getPlainRelocationExternal(RENext);
651 unsigned SymbolNum = info->O->getPlainRelocationSymbolNum(RENext);
652 if (TypeNext == MachO::X86_64_RELOC_UNSIGNED && isExternNext) {
653 op_info->SubtractSymbol.Present = 1;
654 op_info->SubtractSymbol.Name = name;
655 symbol_iterator RelocSymNext = info->O->getSymbolByIndex(SymbolNum);
656 Symbol = *RelocSymNext;
657 StringRef SymNameNext;
658 Symbol.getName(SymNameNext);
659 name = SymNameNext.data();
662 // TODO: add the VariantKinds to op_info->VariantKind for relocation types
663 // like: X86_64_RELOC_TLV, X86_64_RELOC_GOT_LOAD and X86_64_RELOC_GOT.
664 op_info->AddSymbol.Present = 1;
665 op_info->AddSymbol.Name = name;
669 // Second search the external relocation entries of a fully linked image
670 // (if any) for an entry that matches this segment offset.
671 // uint64_t seg_offset = (Pc + Offset);
673 } else if (Arch == Triple::arm) {
674 if (Offset != 0 || (Size != 4 && Size != 2))
676 // First search the section's relocation entries (if any) for an entry
677 // for this section offset.
678 uint32_t sect_addr = info->S.getAddress();
679 uint32_t sect_offset = (Pc + Offset) - sect_addr;
680 bool reloc_found = false;
682 MachO::any_relocation_info RE;
683 bool isExtern = false;
685 bool r_scattered = false;
686 uint32_t r_value, pair_r_value, r_type, r_length, other_half;
687 for (const RelocationRef &Reloc : info->S.relocations()) {
688 uint64_t RelocOffset;
689 Reloc.getOffset(RelocOffset);
690 if (RelocOffset == sect_offset) {
691 Rel = Reloc.getRawDataRefImpl();
692 RE = info->O->getRelocation(Rel);
693 r_length = info->O->getAnyRelocationLength(RE);
694 r_scattered = info->O->isRelocationScattered(RE);
696 r_value = info->O->getScatteredRelocationValue(RE);
697 r_type = info->O->getScatteredRelocationType(RE);
699 r_type = info->O->getAnyRelocationType(RE);
700 isExtern = info->O->getPlainRelocationExternal(RE);
702 symbol_iterator RelocSym = Reloc.getSymbol();
706 if (r_type == MachO::ARM_RELOC_HALF ||
707 r_type == MachO::ARM_RELOC_SECTDIFF ||
708 r_type == MachO::ARM_RELOC_LOCAL_SECTDIFF ||
709 r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
710 DataRefImpl RelNext = Rel;
711 info->O->moveRelocationNext(RelNext);
712 MachO::any_relocation_info RENext;
713 RENext = info->O->getRelocation(RelNext);
714 other_half = info->O->getAnyRelocationAddress(RENext) & 0xffff;
715 if (info->O->isRelocationScattered(RENext))
716 pair_r_value = info->O->getScatteredRelocationValue(RENext);
722 if (reloc_found && isExtern) {
724 Symbol.getName(SymName);
725 const char *name = SymName.data();
726 op_info->AddSymbol.Present = 1;
727 op_info->AddSymbol.Name = name;
730 case MachO::ARM_RELOC_HALF:
731 if ((r_length & 0x1) == 1) {
732 op_info->Value = value << 16 | other_half;
733 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
735 op_info->Value = other_half << 16 | value;
736 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
744 case MachO::ARM_RELOC_HALF:
745 if ((r_length & 0x1) == 1) {
746 op_info->Value = value << 16 | other_half;
747 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
749 op_info->Value = other_half << 16 | value;
750 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
759 // If we have a branch that is not an external relocation entry then
760 // return 0 so the code in tryAddingSymbolicOperand() can use the
761 // SymbolLookUp call back with the branch target address to look up the
762 // symbol and possiblity add an annotation for a symbol stub.
763 if (reloc_found && isExtern == 0 && (r_type == MachO::ARM_RELOC_BR24 ||
764 r_type == MachO::ARM_THUMB_RELOC_BR22))
769 if (r_type == MachO::ARM_RELOC_HALF ||
770 r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
771 if ((r_length & 0x1) == 1)
772 value = value << 16 | other_half;
774 value = other_half << 16 | value;
776 if (r_scattered && (r_type != MachO::ARM_RELOC_HALF &&
777 r_type != MachO::ARM_RELOC_HALF_SECTDIFF)) {
778 offset = value - r_value;
783 if (reloc_found && r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
784 if ((r_length & 0x1) == 1)
785 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
787 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
788 const char *add = GuessSymbolName(r_value, info);
789 const char *sub = GuessSymbolName(pair_r_value, info);
790 int32_t offset = value - (r_value - pair_r_value);
791 op_info->AddSymbol.Present = 1;
793 op_info->AddSymbol.Name = add;
795 op_info->AddSymbol.Value = r_value;
796 op_info->SubtractSymbol.Present = 1;
798 op_info->SubtractSymbol.Name = sub;
800 op_info->SubtractSymbol.Value = pair_r_value;
801 op_info->Value = offset;
805 if (reloc_found == false)
808 op_info->AddSymbol.Present = 1;
809 op_info->Value = offset;
811 if (r_type == MachO::ARM_RELOC_HALF) {
812 if ((r_length & 0x1) == 1)
813 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
815 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
818 const char *add = GuessSymbolName(value, info);
819 if (add != nullptr) {
820 op_info->AddSymbol.Name = add;
823 op_info->AddSymbol.Value = value;
825 } else if (Arch == Triple::aarch64) {
826 if (Offset != 0 || Size != 4)
828 // First search the section's relocation entries (if any) for an entry
829 // for this section offset.
830 uint64_t sect_addr = info->S.getAddress();
831 uint64_t sect_offset = (Pc + Offset) - sect_addr;
832 bool reloc_found = false;
834 MachO::any_relocation_info RE;
835 bool isExtern = false;
838 for (const RelocationRef &Reloc : info->S.relocations()) {
839 uint64_t RelocOffset;
840 Reloc.getOffset(RelocOffset);
841 if (RelocOffset == sect_offset) {
842 Rel = Reloc.getRawDataRefImpl();
843 RE = info->O->getRelocation(Rel);
844 r_type = info->O->getAnyRelocationType(RE);
845 if (r_type == MachO::ARM64_RELOC_ADDEND) {
846 DataRefImpl RelNext = Rel;
847 info->O->moveRelocationNext(RelNext);
848 MachO::any_relocation_info RENext = info->O->getRelocation(RelNext);
850 value = info->O->getPlainRelocationSymbolNum(RENext);
851 op_info->Value = value;
854 // NOTE: Scattered relocations don't exist on arm64.
855 isExtern = info->O->getPlainRelocationExternal(RE);
857 symbol_iterator RelocSym = Reloc.getSymbol();
864 if (reloc_found && isExtern) {
866 Symbol.getName(SymName);
867 const char *name = SymName.data();
868 op_info->AddSymbol.Present = 1;
869 op_info->AddSymbol.Name = name;
872 case MachO::ARM64_RELOC_PAGE21:
874 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_PAGE;
876 case MachO::ARM64_RELOC_PAGEOFF12:
878 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_PAGEOFF;
880 case MachO::ARM64_RELOC_GOT_LOAD_PAGE21:
882 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_GOTPAGE;
884 case MachO::ARM64_RELOC_GOT_LOAD_PAGEOFF12:
886 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_GOTPAGEOFF;
888 case MachO::ARM64_RELOC_TLVP_LOAD_PAGE21:
889 /* @tvlppage is not implemented in llvm-mc */
890 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_TLVP;
892 case MachO::ARM64_RELOC_TLVP_LOAD_PAGEOFF12:
893 /* @tvlppageoff is not implemented in llvm-mc */
894 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_TLVOFF;
897 case MachO::ARM64_RELOC_BRANCH26:
898 op_info->VariantKind = LLVMDisassembler_VariantKind_None;
909 // GuessCstringPointer is passed the address of what might be a pointer to a
910 // literal string in a cstring section. If that address is in a cstring section
911 // it returns a pointer to that string. Else it returns nullptr.
912 const char *GuessCstringPointer(uint64_t ReferenceValue,
913 struct DisassembleInfo *info) {
914 uint32_t LoadCommandCount = info->O->getHeader().ncmds;
915 MachOObjectFile::LoadCommandInfo Load = info->O->getFirstLoadCommandInfo();
916 for (unsigned I = 0;; ++I) {
917 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
918 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
919 for (unsigned J = 0; J < Seg.nsects; ++J) {
920 MachO::section_64 Sec = info->O->getSection64(Load, J);
921 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
922 if (section_type == MachO::S_CSTRING_LITERALS &&
923 ReferenceValue >= Sec.addr &&
924 ReferenceValue < Sec.addr + Sec.size) {
925 uint64_t sect_offset = ReferenceValue - Sec.addr;
926 uint64_t object_offset = Sec.offset + sect_offset;
927 StringRef MachOContents = info->O->getData();
928 uint64_t object_size = MachOContents.size();
929 const char *object_addr = (const char *)MachOContents.data();
930 if (object_offset < object_size) {
931 const char *name = object_addr + object_offset;
938 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
939 MachO::segment_command Seg = info->O->getSegmentLoadCommand(Load);
940 for (unsigned J = 0; J < Seg.nsects; ++J) {
941 MachO::section Sec = info->O->getSection(Load, J);
942 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
943 if (section_type == MachO::S_CSTRING_LITERALS &&
944 ReferenceValue >= Sec.addr &&
945 ReferenceValue < Sec.addr + Sec.size) {
946 uint64_t sect_offset = ReferenceValue - Sec.addr;
947 uint64_t object_offset = Sec.offset + sect_offset;
948 StringRef MachOContents = info->O->getData();
949 uint64_t object_size = MachOContents.size();
950 const char *object_addr = (const char *)MachOContents.data();
951 if (object_offset < object_size) {
952 const char *name = object_addr + object_offset;
960 if (I == LoadCommandCount - 1)
963 Load = info->O->getNextLoadCommandInfo(Load);
968 // GuessIndirectSymbol returns the name of the indirect symbol for the
969 // ReferenceValue passed in or nullptr. This is used when ReferenceValue maybe
970 // an address of a symbol stub or a lazy or non-lazy pointer to associate the
971 // symbol name being referenced by the stub or pointer.
972 static const char *GuessIndirectSymbol(uint64_t ReferenceValue,
973 struct DisassembleInfo *info) {
974 uint32_t LoadCommandCount = info->O->getHeader().ncmds;
975 MachOObjectFile::LoadCommandInfo Load = info->O->getFirstLoadCommandInfo();
976 MachO::dysymtab_command Dysymtab = info->O->getDysymtabLoadCommand();
977 MachO::symtab_command Symtab = info->O->getSymtabLoadCommand();
978 for (unsigned I = 0;; ++I) {
979 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
980 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
981 for (unsigned J = 0; J < Seg.nsects; ++J) {
982 MachO::section_64 Sec = info->O->getSection64(Load, J);
983 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
984 if ((section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
985 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
986 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
987 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
988 section_type == MachO::S_SYMBOL_STUBS) &&
989 ReferenceValue >= Sec.addr &&
990 ReferenceValue < Sec.addr + Sec.size) {
992 if (section_type == MachO::S_SYMBOL_STUBS)
993 stride = Sec.reserved2;
998 uint32_t index = Sec.reserved1 + (ReferenceValue - Sec.addr) / stride;
999 if (index < Dysymtab.nindirectsyms) {
1000 uint32_t indirect_symbol =
1001 info->O->getIndirectSymbolTableEntry(Dysymtab, index);
1002 if (indirect_symbol < Symtab.nsyms) {
1003 symbol_iterator Sym = info->O->getSymbolByIndex(indirect_symbol);
1004 SymbolRef Symbol = *Sym;
1006 Symbol.getName(SymName);
1007 const char *name = SymName.data();
1013 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
1014 MachO::segment_command Seg = info->O->getSegmentLoadCommand(Load);
1015 for (unsigned J = 0; J < Seg.nsects; ++J) {
1016 MachO::section Sec = info->O->getSection(Load, J);
1017 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
1018 if ((section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
1019 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
1020 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
1021 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
1022 section_type == MachO::S_SYMBOL_STUBS) &&
1023 ReferenceValue >= Sec.addr &&
1024 ReferenceValue < Sec.addr + Sec.size) {
1026 if (section_type == MachO::S_SYMBOL_STUBS)
1027 stride = Sec.reserved2;
1032 uint32_t index = Sec.reserved1 + (ReferenceValue - Sec.addr) / stride;
1033 if (index < Dysymtab.nindirectsyms) {
1034 uint32_t indirect_symbol =
1035 info->O->getIndirectSymbolTableEntry(Dysymtab, index);
1036 if (indirect_symbol < Symtab.nsyms) {
1037 symbol_iterator Sym = info->O->getSymbolByIndex(indirect_symbol);
1038 SymbolRef Symbol = *Sym;
1040 Symbol.getName(SymName);
1041 const char *name = SymName.data();
1048 if (I == LoadCommandCount - 1)
1051 Load = info->O->getNextLoadCommandInfo(Load);
1056 // method_reference() is called passing it the ReferenceName that might be
1057 // a reference it to an Objective-C method call. If so then it allocates and
1058 // assembles a method call string with the values last seen and saved in
1059 // the DisassembleInfo's class_name and selector_name fields. This is saved
1060 // into the method field of the info and any previous string is free'ed.
1061 // Then the class_name field in the info is set to nullptr. The method call
1062 // string is set into ReferenceName and ReferenceType is set to
1063 // LLVMDisassembler_ReferenceType_Out_Objc_Message. If this not a method call
1064 // then both ReferenceType and ReferenceName are left unchanged.
1065 static void method_reference(struct DisassembleInfo *info,
1066 uint64_t *ReferenceType,
1067 const char **ReferenceName) {
1068 unsigned int Arch = info->O->getArch();
1069 if (*ReferenceName != nullptr) {
1070 if (strcmp(*ReferenceName, "_objc_msgSend") == 0) {
1071 if (info->selector_name != nullptr) {
1072 if (info->method != nullptr)
1074 if (info->class_name != nullptr) {
1075 info->method = (char *)malloc(5 + strlen(info->class_name) +
1076 strlen(info->selector_name));
1077 if (info->method != nullptr) {
1078 strcpy(info->method, "+[");
1079 strcat(info->method, info->class_name);
1080 strcat(info->method, " ");
1081 strcat(info->method, info->selector_name);
1082 strcat(info->method, "]");
1083 *ReferenceName = info->method;
1084 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
1087 info->method = (char *)malloc(9 + strlen(info->selector_name));
1088 if (info->method != nullptr) {
1089 if (Arch == Triple::x86_64)
1090 strcpy(info->method, "-[%rdi ");
1091 else if (Arch == Triple::aarch64)
1092 strcpy(info->method, "-[x0 ");
1094 strcpy(info->method, "-[r? ");
1095 strcat(info->method, info->selector_name);
1096 strcat(info->method, "]");
1097 *ReferenceName = info->method;
1098 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
1101 info->class_name = nullptr;
1103 } else if (strcmp(*ReferenceName, "_objc_msgSendSuper2") == 0) {
1104 if (info->selector_name != nullptr) {
1105 if (info->method != nullptr)
1107 info->method = (char *)malloc(17 + strlen(info->selector_name));
1108 if (info->method != nullptr) {
1109 if (Arch == Triple::x86_64)
1110 strcpy(info->method, "-[[%rdi super] ");
1111 else if (Arch == Triple::aarch64)
1112 strcpy(info->method, "-[[x0 super] ");
1114 strcpy(info->method, "-[[r? super] ");
1115 strcat(info->method, info->selector_name);
1116 strcat(info->method, "]");
1117 *ReferenceName = info->method;
1118 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
1120 info->class_name = nullptr;
1126 // GuessPointerPointer() is passed the address of what might be a pointer to
1127 // a reference to an Objective-C class, selector, message ref or cfstring.
1128 // If so the value of the pointer is returned and one of the booleans are set
1129 // to true. If not zero is returned and all the booleans are set to false.
1130 static uint64_t GuessPointerPointer(uint64_t ReferenceValue,
1131 struct DisassembleInfo *info,
1132 bool &classref, bool &selref, bool &msgref,
1138 uint32_t LoadCommandCount = info->O->getHeader().ncmds;
1139 MachOObjectFile::LoadCommandInfo Load = info->O->getFirstLoadCommandInfo();
1140 for (unsigned I = 0;; ++I) {
1141 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
1142 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
1143 for (unsigned J = 0; J < Seg.nsects; ++J) {
1144 MachO::section_64 Sec = info->O->getSection64(Load, J);
1145 if ((strncmp(Sec.sectname, "__objc_selrefs", 16) == 0 ||
1146 strncmp(Sec.sectname, "__objc_classrefs", 16) == 0 ||
1147 strncmp(Sec.sectname, "__objc_superrefs", 16) == 0 ||
1148 strncmp(Sec.sectname, "__objc_msgrefs", 16) == 0 ||
1149 strncmp(Sec.sectname, "__cfstring", 16) == 0) &&
1150 ReferenceValue >= Sec.addr &&
1151 ReferenceValue < Sec.addr + Sec.size) {
1152 uint64_t sect_offset = ReferenceValue - Sec.addr;
1153 uint64_t object_offset = Sec.offset + sect_offset;
1154 StringRef MachOContents = info->O->getData();
1155 uint64_t object_size = MachOContents.size();
1156 const char *object_addr = (const char *)MachOContents.data();
1157 if (object_offset < object_size) {
1158 uint64_t pointer_value;
1159 memcpy(&pointer_value, object_addr + object_offset,
1161 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
1162 sys::swapByteOrder(pointer_value);
1163 if (strncmp(Sec.sectname, "__objc_selrefs", 16) == 0)
1165 else if (strncmp(Sec.sectname, "__objc_classrefs", 16) == 0 ||
1166 strncmp(Sec.sectname, "__objc_superrefs", 16) == 0)
1168 else if (strncmp(Sec.sectname, "__objc_msgrefs", 16) == 0 &&
1169 ReferenceValue + 8 < Sec.addr + Sec.size) {
1171 memcpy(&pointer_value, object_addr + object_offset + 8,
1173 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
1174 sys::swapByteOrder(pointer_value);
1175 } else if (strncmp(Sec.sectname, "__cfstring", 16) == 0)
1177 return pointer_value;
1184 // TODO: Look for LC_SEGMENT for 32-bit Mach-O files.
1185 if (I == LoadCommandCount - 1)
1188 Load = info->O->getNextLoadCommandInfo(Load);
1193 // get_pointer_64 returns a pointer to the bytes in the object file at the
1194 // Address from a section in the Mach-O file. And indirectly returns the
1195 // offset into the section, number of bytes left in the section past the offset
1196 // and which section is was being referenced. If the Address is not in a
1197 // section nullptr is returned.
1198 const char *get_pointer_64(uint64_t Address, uint32_t &offset, uint32_t &left,
1199 SectionRef &S, DisassembleInfo *info) {
1203 for (unsigned SectIdx = 0; SectIdx != info->Sections->size(); SectIdx++) {
1204 uint64_t SectAddress = ((*(info->Sections))[SectIdx]).getAddress();
1205 uint64_t SectSize = ((*(info->Sections))[SectIdx]).getSize();
1206 if (Address >= SectAddress && Address < SectAddress + SectSize) {
1207 S = (*(info->Sections))[SectIdx];
1208 offset = Address - SectAddress;
1209 left = SectSize - offset;
1210 StringRef SectContents;
1211 ((*(info->Sections))[SectIdx]).getContents(SectContents);
1212 return SectContents.data() + offset;
1218 // get_symbol_64() returns the name of a symbol (or nullptr) and the address of
1219 // the symbol indirectly through n_value. Based on the relocation information
1220 // for the specified section offset in the specified section reference.
1221 const char *get_symbol_64(uint32_t sect_offset, SectionRef S,
1222 DisassembleInfo *info, uint64_t &n_value) {
1224 if (info->verbose == false)
1227 // See if there is an external relocation entry at the sect_offset.
1228 bool reloc_found = false;
1230 MachO::any_relocation_info RE;
1231 bool isExtern = false;
1233 for (const RelocationRef &Reloc : S.relocations()) {
1234 uint64_t RelocOffset;
1235 Reloc.getOffset(RelocOffset);
1236 if (RelocOffset == sect_offset) {
1237 Rel = Reloc.getRawDataRefImpl();
1238 RE = info->O->getRelocation(Rel);
1239 if (info->O->isRelocationScattered(RE))
1241 isExtern = info->O->getPlainRelocationExternal(RE);
1243 symbol_iterator RelocSym = Reloc.getSymbol();
1250 // If there is an external relocation entry for a symbol in this section
1251 // at this section_offset then use that symbol's value for the n_value
1252 // and return its name.
1253 const char *SymbolName = nullptr;
1254 if (reloc_found && isExtern) {
1255 Symbol.getAddress(n_value);
1257 Symbol.getName(name);
1258 if (!name.empty()) {
1259 SymbolName = name.data();
1264 // TODO: For fully linked images, look through the external relocation
1265 // entries off the dynamic symtab command. For these the r_offset is from the
1266 // start of the first writeable segment in the Mach-O file. So the offset
1267 // to this section from that segment is passed to this routine by the caller,
1268 // as the database_offset. Which is the difference of the section's starting
1269 // address and the first writable segment.
1271 // NOTE: need add passing the database_offset to this routine.
1273 // TODO: We did not find an external relocation entry so look up the
1274 // ReferenceValue as an address of a symbol and if found return that symbol's
1277 // NOTE: need add passing the ReferenceValue to this routine. Then that code
1278 // would simply be this:
1279 // SymbolName = GuessSymbolName(ReferenceValue, info);
1284 // These are structs in the Objective-C meta data and read to produce the
1285 // comments for disassembly. While these are part of the ABI they are no
1286 // public defintions. So the are here not in include/llvm/Support/MachO.h .
1288 // The cfstring object in a 64-bit Mach-O file.
1289 struct cfstring64_t {
1290 uint64_t isa; // class64_t * (64-bit pointer)
1291 uint64_t flags; // flag bits
1292 uint64_t characters; // char * (64-bit pointer)
1293 uint64_t length; // number of non-NULL characters in above
1296 // The class object in a 64-bit Mach-O file.
1298 uint64_t isa; // class64_t * (64-bit pointer)
1299 uint64_t superclass; // class64_t * (64-bit pointer)
1300 uint64_t cache; // Cache (64-bit pointer)
1301 uint64_t vtable; // IMP * (64-bit pointer)
1302 uint64_t data; // class_ro64_t * (64-bit pointer)
1305 struct class_ro64_t {
1307 uint32_t instanceStart;
1308 uint32_t instanceSize;
1310 uint64_t ivarLayout; // const uint8_t * (64-bit pointer)
1311 uint64_t name; // const char * (64-bit pointer)
1312 uint64_t baseMethods; // const method_list_t * (64-bit pointer)
1313 uint64_t baseProtocols; // const protocol_list_t * (64-bit pointer)
1314 uint64_t ivars; // const ivar_list_t * (64-bit pointer)
1315 uint64_t weakIvarLayout; // const uint8_t * (64-bit pointer)
1316 uint64_t baseProperties; // const struct objc_property_list (64-bit pointer)
1319 inline void swapStruct(struct cfstring64_t &cfs) {
1320 sys::swapByteOrder(cfs.isa);
1321 sys::swapByteOrder(cfs.flags);
1322 sys::swapByteOrder(cfs.characters);
1323 sys::swapByteOrder(cfs.length);
1326 inline void swapStruct(struct class64_t &c) {
1327 sys::swapByteOrder(c.isa);
1328 sys::swapByteOrder(c.superclass);
1329 sys::swapByteOrder(c.cache);
1330 sys::swapByteOrder(c.vtable);
1331 sys::swapByteOrder(c.data);
1334 inline void swapStruct(struct class_ro64_t &cro) {
1335 sys::swapByteOrder(cro.flags);
1336 sys::swapByteOrder(cro.instanceStart);
1337 sys::swapByteOrder(cro.instanceSize);
1338 sys::swapByteOrder(cro.reserved);
1339 sys::swapByteOrder(cro.ivarLayout);
1340 sys::swapByteOrder(cro.name);
1341 sys::swapByteOrder(cro.baseMethods);
1342 sys::swapByteOrder(cro.baseProtocols);
1343 sys::swapByteOrder(cro.ivars);
1344 sys::swapByteOrder(cro.weakIvarLayout);
1345 sys::swapByteOrder(cro.baseProperties);
1348 static const char *get_dyld_bind_info_symbolname(uint64_t ReferenceValue,
1349 struct DisassembleInfo *info);
1351 // get_objc2_64bit_class_name() is used for disassembly and is passed a pointer
1352 // to an Objective-C class and returns the class name. It is also passed the
1353 // address of the pointer, so when the pointer is zero as it can be in an .o
1354 // file, that is used to look for an external relocation entry with a symbol
1356 const char *get_objc2_64bit_class_name(uint64_t pointer_value,
1357 uint64_t ReferenceValue,
1358 struct DisassembleInfo *info) {
1360 uint32_t offset, left;
1363 // The pointer_value can be 0 in an object file and have a relocation
1364 // entry for the class symbol at the ReferenceValue (the address of the
1366 if (pointer_value == 0) {
1367 r = get_pointer_64(ReferenceValue, offset, left, S, info);
1368 if (r == nullptr || left < sizeof(uint64_t))
1371 const char *symbol_name = get_symbol_64(offset, S, info, n_value);
1372 if (symbol_name == nullptr)
1374 const char *class_name = strrchr(symbol_name, '$');
1375 if (class_name != nullptr && class_name[1] == '_' && class_name[2] != '\0')
1376 return class_name + 2;
1381 // The case were the pointer_value is non-zero and points to a class defined
1382 // in this Mach-O file.
1383 r = get_pointer_64(pointer_value, offset, left, S, info);
1384 if (r == nullptr || left < sizeof(struct class64_t))
1387 memcpy(&c, r, sizeof(struct class64_t));
1388 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
1392 r = get_pointer_64(c.data, offset, left, S, info);
1393 if (r == nullptr || left < sizeof(struct class_ro64_t))
1395 struct class_ro64_t cro;
1396 memcpy(&cro, r, sizeof(struct class_ro64_t));
1397 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
1401 const char *name = get_pointer_64(cro.name, offset, left, S, info);
1405 // get_objc2_64bit_cfstring_name is used for disassembly and is passed a
1406 // pointer to a cfstring and returns its name or nullptr.
1407 const char *get_objc2_64bit_cfstring_name(uint64_t ReferenceValue,
1408 struct DisassembleInfo *info) {
1409 const char *r, *name;
1410 uint32_t offset, left;
1412 struct cfstring64_t cfs;
1413 uint64_t cfs_characters;
1415 r = get_pointer_64(ReferenceValue, offset, left, S, info);
1416 if (r == nullptr || left < sizeof(struct cfstring64_t))
1418 memcpy(&cfs, r, sizeof(struct cfstring64_t));
1419 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
1421 if (cfs.characters == 0) {
1423 const char *symbol_name = get_symbol_64(
1424 offset + offsetof(struct cfstring64_t, characters), S, info, n_value);
1425 if (symbol_name == nullptr)
1427 cfs_characters = n_value;
1429 cfs_characters = cfs.characters;
1430 name = get_pointer_64(cfs_characters, offset, left, S, info);
1435 // get_objc2_64bit_selref() is used for disassembly and is passed a the address
1436 // of a pointer to an Objective-C selector reference when the pointer value is
1437 // zero as in a .o file and is likely to have a external relocation entry with
1438 // who's symbol's n_value is the real pointer to the selector name. If that is
1439 // the case the real pointer to the selector name is returned else 0 is
1441 uint64_t get_objc2_64bit_selref(uint64_t ReferenceValue,
1442 struct DisassembleInfo *info) {
1443 uint32_t offset, left;
1446 const char *r = get_pointer_64(ReferenceValue, offset, left, S, info);
1447 if (r == nullptr || left < sizeof(uint64_t))
1450 const char *symbol_name = get_symbol_64(offset, S, info, n_value);
1451 if (symbol_name == nullptr)
1456 // GuessLiteralPointer returns a string which for the item in the Mach-O file
1457 // for the address passed in as ReferenceValue for printing as a comment with
1458 // the instruction and also returns the corresponding type of that item
1459 // indirectly through ReferenceType.
1461 // If ReferenceValue is an address of literal cstring then a pointer to the
1462 // cstring is returned and ReferenceType is set to
1463 // LLVMDisassembler_ReferenceType_Out_LitPool_CstrAddr .
1465 // If ReferenceValue is an address of an Objective-C CFString, Selector ref or
1466 // Class ref that name is returned and the ReferenceType is set accordingly.
1468 // Lastly, literals which are Symbol address in a literal pool are looked for
1469 // and if found the symbol name is returned and ReferenceType is set to
1470 // LLVMDisassembler_ReferenceType_Out_LitPool_SymAddr .
1472 // If there is no item in the Mach-O file for the address passed in as
1473 // ReferenceValue nullptr is returned and ReferenceType is unchanged.
1474 const char *GuessLiteralPointer(uint64_t ReferenceValue, uint64_t ReferencePC,
1475 uint64_t *ReferenceType,
1476 struct DisassembleInfo *info) {
1477 // First see if there is an external relocation entry at the ReferencePC.
1478 uint64_t sect_addr = info->S.getAddress();
1479 uint64_t sect_offset = ReferencePC - sect_addr;
1480 bool reloc_found = false;
1482 MachO::any_relocation_info RE;
1483 bool isExtern = false;
1485 for (const RelocationRef &Reloc : info->S.relocations()) {
1486 uint64_t RelocOffset;
1487 Reloc.getOffset(RelocOffset);
1488 if (RelocOffset == sect_offset) {
1489 Rel = Reloc.getRawDataRefImpl();
1490 RE = info->O->getRelocation(Rel);
1491 if (info->O->isRelocationScattered(RE))
1493 isExtern = info->O->getPlainRelocationExternal(RE);
1495 symbol_iterator RelocSym = Reloc.getSymbol();
1502 // If there is an external relocation entry for a symbol in a section
1503 // then used that symbol's value for the value of the reference.
1504 if (reloc_found && isExtern) {
1505 if (info->O->getAnyRelocationPCRel(RE)) {
1506 unsigned Type = info->O->getAnyRelocationType(RE);
1507 if (Type == MachO::X86_64_RELOC_SIGNED) {
1508 Symbol.getAddress(ReferenceValue);
1513 // Look for literals such as Objective-C CFStrings refs, Selector refs,
1514 // Message refs and Class refs.
1515 bool classref, selref, msgref, cfstring;
1516 uint64_t pointer_value = GuessPointerPointer(ReferenceValue, info, classref,
1517 selref, msgref, cfstring);
1518 if (classref == true && pointer_value == 0) {
1519 // Note the ReferenceValue is a pointer into the __objc_classrefs section.
1520 // And the pointer_value in that section is typically zero as it will be
1521 // set by dyld as part of the "bind information".
1522 const char *name = get_dyld_bind_info_symbolname(ReferenceValue, info);
1523 if (name != nullptr) {
1524 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Class_Ref;
1525 const char *class_name = strrchr(name, '$');
1526 if (class_name != nullptr && class_name[1] == '_' &&
1527 class_name[2] != '\0') {
1528 info->class_name = class_name + 2;
1534 if (classref == true) {
1535 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Class_Ref;
1537 get_objc2_64bit_class_name(pointer_value, ReferenceValue, info);
1538 if (name != nullptr)
1539 info->class_name = name;
1541 name = "bad class ref";
1545 if (cfstring == true) {
1546 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_CFString_Ref;
1547 const char *name = get_objc2_64bit_cfstring_name(ReferenceValue, info);
1551 if (selref == true && pointer_value == 0)
1552 pointer_value = get_objc2_64bit_selref(ReferenceValue, info);
1554 if (pointer_value != 0)
1555 ReferenceValue = pointer_value;
1557 const char *name = GuessCstringPointer(ReferenceValue, info);
1559 if (pointer_value != 0 && selref == true) {
1560 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Selector_Ref;
1561 info->selector_name = name;
1562 } else if (pointer_value != 0 && msgref == true) {
1563 info->class_name = nullptr;
1564 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message_Ref;
1565 info->selector_name = name;
1567 *ReferenceType = LLVMDisassembler_ReferenceType_Out_LitPool_CstrAddr;
1571 // Lastly look for an indirect symbol with this ReferenceValue which is in
1572 // a literal pool. If found return that symbol name.
1573 name = GuessIndirectSymbol(ReferenceValue, info);
1575 *ReferenceType = LLVMDisassembler_ReferenceType_Out_LitPool_SymAddr;
1582 // SymbolizerSymbolLookUp is the symbol lookup function passed when creating
1583 // the Symbolizer. It looks up the ReferenceValue using the info passed via the
1584 // pointer to the struct DisassembleInfo that was passed when MCSymbolizer
1585 // is created and returns the symbol name that matches the ReferenceValue or
1586 // nullptr if none. The ReferenceType is passed in for the IN type of
1587 // reference the instruction is making from the values in defined in the header
1588 // "llvm-c/Disassembler.h". On return the ReferenceType can set to a specific
1589 // Out type and the ReferenceName will also be set which is added as a comment
1590 // to the disassembled instruction.
1593 // If the symbol name is a C++ mangled name then the demangled name is
1594 // returned through ReferenceName and ReferenceType is set to
1595 // LLVMDisassembler_ReferenceType_DeMangled_Name .
1598 // When this is called to get a symbol name for a branch target then the
1599 // ReferenceType will be LLVMDisassembler_ReferenceType_In_Branch and then
1600 // SymbolValue will be looked for in the indirect symbol table to determine if
1601 // it is an address for a symbol stub. If so then the symbol name for that
1602 // stub is returned indirectly through ReferenceName and then ReferenceType is
1603 // set to LLVMDisassembler_ReferenceType_Out_SymbolStub.
1605 // When this is called with an value loaded via a PC relative load then
1606 // ReferenceType will be LLVMDisassembler_ReferenceType_In_PCrel_Load then the
1607 // SymbolValue is checked to be an address of literal pointer, symbol pointer,
1608 // or an Objective-C meta data reference. If so the output ReferenceType is
1609 // set to correspond to that as well as setting the ReferenceName.
1610 const char *SymbolizerSymbolLookUp(void *DisInfo, uint64_t ReferenceValue,
1611 uint64_t *ReferenceType,
1612 uint64_t ReferencePC,
1613 const char **ReferenceName) {
1614 struct DisassembleInfo *info = (struct DisassembleInfo *)DisInfo;
1615 // If no verbose symbolic information is wanted then just return nullptr.
1616 if (info->verbose == false) {
1617 *ReferenceName = nullptr;
1618 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
1622 const char *SymbolName = GuessSymbolName(ReferenceValue, info);
1624 if (*ReferenceType == LLVMDisassembler_ReferenceType_In_Branch) {
1625 *ReferenceName = GuessIndirectSymbol(ReferenceValue, info);
1626 if (*ReferenceName != nullptr) {
1627 method_reference(info, ReferenceType, ReferenceName);
1628 if (*ReferenceType != LLVMDisassembler_ReferenceType_Out_Objc_Message)
1629 *ReferenceType = LLVMDisassembler_ReferenceType_Out_SymbolStub;
1632 if (SymbolName != nullptr && strncmp(SymbolName, "__Z", 3) == 0) {
1633 if (info->demangled_name != nullptr)
1634 free(info->demangled_name);
1636 info->demangled_name =
1637 abi::__cxa_demangle(SymbolName + 1, nullptr, nullptr, &status);
1638 if (info->demangled_name != nullptr) {
1639 *ReferenceName = info->demangled_name;
1640 *ReferenceType = LLVMDisassembler_ReferenceType_DeMangled_Name;
1642 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
1645 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
1646 } else if (*ReferenceType == LLVMDisassembler_ReferenceType_In_PCrel_Load) {
1648 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
1650 method_reference(info, ReferenceType, ReferenceName);
1652 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
1653 // If this is arm64 and the reference is an adrp instruction save the
1654 // instruction, passed in ReferenceValue and the address of the instruction
1655 // for use later if we see and add immediate instruction.
1656 } else if (info->O->getArch() == Triple::aarch64 &&
1657 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADRP) {
1658 info->adrp_inst = ReferenceValue;
1659 info->adrp_addr = ReferencePC;
1660 SymbolName = nullptr;
1661 *ReferenceName = nullptr;
1662 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
1663 // If this is arm64 and reference is an add immediate instruction and we
1665 // seen an adrp instruction just before it and the adrp's Xd register
1667 // this add's Xn register reconstruct the value being referenced and look to
1668 // see if it is a literal pointer. Note the add immediate instruction is
1669 // passed in ReferenceValue.
1670 } else if (info->O->getArch() == Triple::aarch64 &&
1671 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADDXri &&
1672 ReferencePC - 4 == info->adrp_addr &&
1673 (info->adrp_inst & 0x9f000000) == 0x90000000 &&
1674 (info->adrp_inst & 0x1f) == ((ReferenceValue >> 5) & 0x1f)) {
1675 uint32_t addxri_inst;
1676 uint64_t adrp_imm, addxri_imm;
1679 ((info->adrp_inst & 0x00ffffe0) >> 3) | ((info->adrp_inst >> 29) & 0x3);
1680 if (info->adrp_inst & 0x0200000)
1681 adrp_imm |= 0xfffffffffc000000LL;
1683 addxri_inst = ReferenceValue;
1684 addxri_imm = (addxri_inst >> 10) & 0xfff;
1685 if (((addxri_inst >> 22) & 0x3) == 1)
1688 ReferenceValue = (info->adrp_addr & 0xfffffffffffff000LL) +
1689 (adrp_imm << 12) + addxri_imm;
1692 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
1693 if (*ReferenceName == nullptr)
1694 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
1695 // If this is arm64 and the reference is a load register instruction and we
1696 // have seen an adrp instruction just before it and the adrp's Xd register
1697 // matches this add's Xn register reconstruct the value being referenced and
1698 // look to see if it is a literal pointer. Note the load register
1699 // instruction is passed in ReferenceValue.
1700 } else if (info->O->getArch() == Triple::aarch64 &&
1701 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_LDRXui &&
1702 ReferencePC - 4 == info->adrp_addr &&
1703 (info->adrp_inst & 0x9f000000) == 0x90000000 &&
1704 (info->adrp_inst & 0x1f) == ((ReferenceValue >> 5) & 0x1f)) {
1705 uint32_t ldrxui_inst;
1706 uint64_t adrp_imm, ldrxui_imm;
1709 ((info->adrp_inst & 0x00ffffe0) >> 3) | ((info->adrp_inst >> 29) & 0x3);
1710 if (info->adrp_inst & 0x0200000)
1711 adrp_imm |= 0xfffffffffc000000LL;
1713 ldrxui_inst = ReferenceValue;
1714 ldrxui_imm = (ldrxui_inst >> 10) & 0xfff;
1716 ReferenceValue = (info->adrp_addr & 0xfffffffffffff000LL) +
1717 (adrp_imm << 12) + (ldrxui_imm << 3);
1720 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
1721 if (*ReferenceName == nullptr)
1722 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
1724 // If this arm64 and is an load register (PC-relative) instruction the
1725 // ReferenceValue is the PC plus the immediate value.
1726 else if (info->O->getArch() == Triple::aarch64 &&
1727 (*ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_LDRXl ||
1728 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADR)) {
1730 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
1731 if (*ReferenceName == nullptr)
1732 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
1735 else if (SymbolName != nullptr && strncmp(SymbolName, "__Z", 3) == 0) {
1736 if (info->demangled_name != nullptr)
1737 free(info->demangled_name);
1739 info->demangled_name =
1740 abi::__cxa_demangle(SymbolName + 1, nullptr, nullptr, &status);
1741 if (info->demangled_name != nullptr) {
1742 *ReferenceName = info->demangled_name;
1743 *ReferenceType = LLVMDisassembler_ReferenceType_DeMangled_Name;
1748 *ReferenceName = nullptr;
1749 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
1755 /// \brief Emits the comments that are stored in the CommentStream.
1756 /// Each comment in the CommentStream must end with a newline.
1757 static void emitComments(raw_svector_ostream &CommentStream,
1758 SmallString<128> &CommentsToEmit,
1759 formatted_raw_ostream &FormattedOS,
1760 const MCAsmInfo &MAI) {
1761 // Flush the stream before taking its content.
1762 CommentStream.flush();
1763 StringRef Comments = CommentsToEmit.str();
1764 // Get the default information for printing a comment.
1765 const char *CommentBegin = MAI.getCommentString();
1766 unsigned CommentColumn = MAI.getCommentColumn();
1767 bool IsFirst = true;
1768 while (!Comments.empty()) {
1770 FormattedOS << '\n';
1771 // Emit a line of comments.
1772 FormattedOS.PadToColumn(CommentColumn);
1773 size_t Position = Comments.find('\n');
1774 FormattedOS << CommentBegin << ' ' << Comments.substr(0, Position);
1775 // Move after the newline character.
1776 Comments = Comments.substr(Position + 1);
1779 FormattedOS.flush();
1781 // Tell the comment stream that the vector changed underneath it.
1782 CommentsToEmit.clear();
1783 CommentStream.resync();
1786 static void DisassembleInputMachO2(StringRef Filename, MachOObjectFile *MachOOF,
1787 StringRef ArchiveMemberName,
1788 StringRef ArchitectureName) {
1789 const char *McpuDefault = nullptr;
1790 const Target *ThumbTarget = nullptr;
1791 const Target *TheTarget = GetTarget(MachOOF, &McpuDefault, &ThumbTarget);
1793 // GetTarget prints out stuff.
1796 if (MCPU.empty() && McpuDefault)
1799 std::unique_ptr<const MCInstrInfo> InstrInfo(TheTarget->createMCInstrInfo());
1800 std::unique_ptr<const MCInstrInfo> ThumbInstrInfo;
1802 ThumbInstrInfo.reset(ThumbTarget->createMCInstrInfo());
1804 // Package up features to be passed to target/subtarget
1805 std::string FeaturesStr;
1806 if (MAttrs.size()) {
1807 SubtargetFeatures Features;
1808 for (unsigned i = 0; i != MAttrs.size(); ++i)
1809 Features.AddFeature(MAttrs[i]);
1810 FeaturesStr = Features.getString();
1813 // Set up disassembler.
1814 std::unique_ptr<const MCRegisterInfo> MRI(
1815 TheTarget->createMCRegInfo(TripleName));
1816 std::unique_ptr<const MCAsmInfo> AsmInfo(
1817 TheTarget->createMCAsmInfo(*MRI, TripleName));
1818 std::unique_ptr<const MCSubtargetInfo> STI(
1819 TheTarget->createMCSubtargetInfo(TripleName, MCPU, FeaturesStr));
1820 MCContext Ctx(AsmInfo.get(), MRI.get(), nullptr);
1821 std::unique_ptr<MCDisassembler> DisAsm(
1822 TheTarget->createMCDisassembler(*STI, Ctx));
1823 std::unique_ptr<MCSymbolizer> Symbolizer;
1824 struct DisassembleInfo SymbolizerInfo;
1825 std::unique_ptr<MCRelocationInfo> RelInfo(
1826 TheTarget->createMCRelocationInfo(TripleName, Ctx));
1828 Symbolizer.reset(TheTarget->createMCSymbolizer(
1829 TripleName, SymbolizerGetOpInfo, SymbolizerSymbolLookUp,
1830 &SymbolizerInfo, &Ctx, RelInfo.release()));
1831 DisAsm->setSymbolizer(std::move(Symbolizer));
1833 int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
1834 std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
1835 AsmPrinterVariant, *AsmInfo, *InstrInfo, *MRI, *STI));
1836 // Set the display preference for hex vs. decimal immediates.
1837 IP->setPrintImmHex(PrintImmHex);
1838 // Comment stream and backing vector.
1839 SmallString<128> CommentsToEmit;
1840 raw_svector_ostream CommentStream(CommentsToEmit);
1841 // FIXME: Setting the CommentStream in the InstPrinter is problematic in that
1842 // if it is done then arm64 comments for string literals don't get printed
1843 // and some constant get printed instead and not setting it causes intel
1844 // (32-bit and 64-bit) comments printed with different spacing before the
1845 // comment causing different diffs with the 'C' disassembler library API.
1846 // IP->setCommentStream(CommentStream);
1848 if (!AsmInfo || !STI || !DisAsm || !IP) {
1849 errs() << "error: couldn't initialize disassembler for target "
1850 << TripleName << '\n';
1854 // Set up thumb disassembler.
1855 std::unique_ptr<const MCRegisterInfo> ThumbMRI;
1856 std::unique_ptr<const MCAsmInfo> ThumbAsmInfo;
1857 std::unique_ptr<const MCSubtargetInfo> ThumbSTI;
1858 std::unique_ptr<MCDisassembler> ThumbDisAsm;
1859 std::unique_ptr<MCInstPrinter> ThumbIP;
1860 std::unique_ptr<MCContext> ThumbCtx;
1861 std::unique_ptr<MCSymbolizer> ThumbSymbolizer;
1862 struct DisassembleInfo ThumbSymbolizerInfo;
1863 std::unique_ptr<MCRelocationInfo> ThumbRelInfo;
1865 ThumbMRI.reset(ThumbTarget->createMCRegInfo(ThumbTripleName));
1867 ThumbTarget->createMCAsmInfo(*ThumbMRI, ThumbTripleName));
1869 ThumbTarget->createMCSubtargetInfo(ThumbTripleName, MCPU, FeaturesStr));
1870 ThumbCtx.reset(new MCContext(ThumbAsmInfo.get(), ThumbMRI.get(), nullptr));
1871 ThumbDisAsm.reset(ThumbTarget->createMCDisassembler(*ThumbSTI, *ThumbCtx));
1872 MCContext *PtrThumbCtx = ThumbCtx.get();
1874 ThumbTarget->createMCRelocationInfo(ThumbTripleName, *PtrThumbCtx));
1876 ThumbSymbolizer.reset(ThumbTarget->createMCSymbolizer(
1877 ThumbTripleName, SymbolizerGetOpInfo, SymbolizerSymbolLookUp,
1878 &ThumbSymbolizerInfo, PtrThumbCtx, ThumbRelInfo.release()));
1879 ThumbDisAsm->setSymbolizer(std::move(ThumbSymbolizer));
1881 int ThumbAsmPrinterVariant = ThumbAsmInfo->getAssemblerDialect();
1882 ThumbIP.reset(ThumbTarget->createMCInstPrinter(
1883 ThumbAsmPrinterVariant, *ThumbAsmInfo, *ThumbInstrInfo, *ThumbMRI,
1885 // Set the display preference for hex vs. decimal immediates.
1886 ThumbIP->setPrintImmHex(PrintImmHex);
1889 if (ThumbTarget && (!ThumbAsmInfo || !ThumbSTI || !ThumbDisAsm || !ThumbIP)) {
1890 errs() << "error: couldn't initialize disassembler for target "
1891 << ThumbTripleName << '\n';
1896 if (!ArchiveMemberName.empty())
1897 outs() << '(' << ArchiveMemberName << ')';
1898 if (!ArchitectureName.empty())
1899 outs() << " (architecture " << ArchitectureName << ")";
1902 MachO::mach_header Header = MachOOF->getHeader();
1904 // FIXME: Using the -cfg command line option, this code used to be able to
1905 // annotate relocations with the referenced symbol's name, and if this was
1906 // inside a __[cf]string section, the data it points to. This is now replaced
1907 // by the upcoming MCSymbolizer, which needs the appropriate setup done above.
1908 std::vector<SectionRef> Sections;
1909 std::vector<SymbolRef> Symbols;
1910 SmallVector<uint64_t, 8> FoundFns;
1911 uint64_t BaseSegmentAddress;
1913 getSectionsAndSymbols(Header, MachOOF, Sections, Symbols, FoundFns,
1914 BaseSegmentAddress);
1916 // Sort the symbols by address, just in case they didn't come in that way.
1917 std::sort(Symbols.begin(), Symbols.end(), SymbolSorter());
1919 // Build a data in code table that is sorted on by the address of each entry.
1920 uint64_t BaseAddress = 0;
1921 if (Header.filetype == MachO::MH_OBJECT)
1922 BaseAddress = Sections[0].getAddress();
1924 BaseAddress = BaseSegmentAddress;
1926 for (dice_iterator DI = MachOOF->begin_dices(), DE = MachOOF->end_dices();
1929 DI->getOffset(Offset);
1930 Dices.push_back(std::make_pair(BaseAddress + Offset, *DI));
1932 array_pod_sort(Dices.begin(), Dices.end());
1935 raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls();
1937 raw_ostream &DebugOut = nulls();
1940 std::unique_ptr<DIContext> diContext;
1941 ObjectFile *DbgObj = MachOOF;
1942 // Try to find debug info and set up the DIContext for it.
1944 // A separate DSym file path was specified, parse it as a macho file,
1945 // get the sections and supply it to the section name parsing machinery.
1946 if (!DSYMFile.empty()) {
1947 ErrorOr<std::unique_ptr<MemoryBuffer>> BufOrErr =
1948 MemoryBuffer::getFileOrSTDIN(DSYMFile);
1949 if (std::error_code EC = BufOrErr.getError()) {
1950 errs() << "llvm-objdump: " << Filename << ": " << EC.message() << '\n';
1954 ObjectFile::createMachOObjectFile(BufOrErr.get()->getMemBufferRef())
1959 // Setup the DIContext
1960 diContext.reset(DIContext::getDWARFContext(*DbgObj));
1963 // TODO: For now this only disassembles the (__TEXT,__text) section (see the
1964 // checks in the code below at the top of this loop). It should allow a
1965 // darwin otool(1) like -s option to disassemble any named segment & section
1966 // that is marked as containing instructions with the attributes
1967 // S_ATTR_PURE_INSTRUCTIONS or S_ATTR_SOME_INSTRUCTIONS in the flags field of
1968 // the section structure.
1969 outs() << "(__TEXT,__text) section\n";
1971 for (unsigned SectIdx = 0; SectIdx != Sections.size(); SectIdx++) {
1973 bool SectIsText = Sections[SectIdx].isText();
1974 if (SectIsText == false)
1978 if (Sections[SectIdx].getName(SectName) || SectName != "__text")
1979 continue; // Skip non-text sections
1981 DataRefImpl DR = Sections[SectIdx].getRawDataRefImpl();
1983 StringRef SegmentName = MachOOF->getSectionFinalSegmentName(DR);
1984 if (SegmentName != "__TEXT")
1988 Sections[SectIdx].getContents(BytesStr);
1989 ArrayRef<uint8_t> Bytes(reinterpret_cast<const uint8_t *>(BytesStr.data()),
1991 uint64_t SectAddress = Sections[SectIdx].getAddress();
1993 bool symbolTableWorked = false;
1995 // Parse relocations.
1996 std::vector<std::pair<uint64_t, SymbolRef>> Relocs;
1997 for (const RelocationRef &Reloc : Sections[SectIdx].relocations()) {
1998 uint64_t RelocOffset;
1999 Reloc.getOffset(RelocOffset);
2000 uint64_t SectionAddress = Sections[SectIdx].getAddress();
2001 RelocOffset -= SectionAddress;
2003 symbol_iterator RelocSym = Reloc.getSymbol();
2005 Relocs.push_back(std::make_pair(RelocOffset, *RelocSym));
2007 array_pod_sort(Relocs.begin(), Relocs.end());
2009 // Create a map of symbol addresses to symbol names for use by
2010 // the SymbolizerSymbolLookUp() routine.
2011 SymbolAddressMap AddrMap;
2012 for (const SymbolRef &Symbol : MachOOF->symbols()) {
2015 if (ST == SymbolRef::ST_Function || ST == SymbolRef::ST_Data ||
2016 ST == SymbolRef::ST_Other) {
2018 Symbol.getAddress(Address);
2020 Symbol.getName(SymName);
2021 AddrMap[Address] = SymName;
2024 // Set up the block of info used by the Symbolizer call backs.
2025 SymbolizerInfo.verbose = true;
2026 SymbolizerInfo.O = MachOOF;
2027 SymbolizerInfo.S = Sections[SectIdx];
2028 SymbolizerInfo.AddrMap = &AddrMap;
2029 SymbolizerInfo.Sections = &Sections;
2030 SymbolizerInfo.class_name = nullptr;
2031 SymbolizerInfo.selector_name = nullptr;
2032 SymbolizerInfo.method = nullptr;
2033 SymbolizerInfo.demangled_name = nullptr;
2034 SymbolizerInfo.bindtable = nullptr;
2035 SymbolizerInfo.adrp_addr = 0;
2036 SymbolizerInfo.adrp_inst = 0;
2037 // Same for the ThumbSymbolizer
2038 ThumbSymbolizerInfo.verbose = true;
2039 ThumbSymbolizerInfo.O = MachOOF;
2040 ThumbSymbolizerInfo.S = Sections[SectIdx];
2041 ThumbSymbolizerInfo.AddrMap = &AddrMap;
2042 ThumbSymbolizerInfo.Sections = &Sections;
2043 ThumbSymbolizerInfo.class_name = nullptr;
2044 ThumbSymbolizerInfo.selector_name = nullptr;
2045 ThumbSymbolizerInfo.method = nullptr;
2046 ThumbSymbolizerInfo.demangled_name = nullptr;
2047 ThumbSymbolizerInfo.bindtable = nullptr;
2048 ThumbSymbolizerInfo.adrp_addr = 0;
2049 ThumbSymbolizerInfo.adrp_inst = 0;
2051 // Disassemble symbol by symbol.
2052 for (unsigned SymIdx = 0; SymIdx != Symbols.size(); SymIdx++) {
2054 Symbols[SymIdx].getName(SymName);
2057 Symbols[SymIdx].getType(ST);
2058 if (ST != SymbolRef::ST_Function)
2061 // Make sure the symbol is defined in this section.
2062 bool containsSym = Sections[SectIdx].containsSymbol(Symbols[SymIdx]);
2066 // Start at the address of the symbol relative to the section's address.
2068 uint64_t SectionAddress = Sections[SectIdx].getAddress();
2069 Symbols[SymIdx].getAddress(Start);
2070 Start -= SectionAddress;
2072 // Stop disassembling either at the beginning of the next symbol or at
2073 // the end of the section.
2074 bool containsNextSym = false;
2075 uint64_t NextSym = 0;
2076 uint64_t NextSymIdx = SymIdx + 1;
2077 while (Symbols.size() > NextSymIdx) {
2078 SymbolRef::Type NextSymType;
2079 Symbols[NextSymIdx].getType(NextSymType);
2080 if (NextSymType == SymbolRef::ST_Function) {
2082 Sections[SectIdx].containsSymbol(Symbols[NextSymIdx]);
2083 Symbols[NextSymIdx].getAddress(NextSym);
2084 NextSym -= SectionAddress;
2090 uint64_t SectSize = Sections[SectIdx].getSize();
2091 uint64_t End = containsNextSym ? NextSym : SectSize;
2094 symbolTableWorked = true;
2096 DataRefImpl Symb = Symbols[SymIdx].getRawDataRefImpl();
2098 (MachOOF->getSymbolFlags(Symb) & SymbolRef::SF_Thumb) && ThumbTarget;
2100 outs() << SymName << ":\n";
2101 DILineInfo lastLine;
2102 for (uint64_t Index = Start; Index < End; Index += Size) {
2105 uint64_t PC = SectAddress + Index;
2106 if (FullLeadingAddr) {
2107 if (MachOOF->is64Bit())
2108 outs() << format("%016" PRIx64, PC);
2110 outs() << format("%08" PRIx64, PC);
2112 outs() << format("%8" PRIx64 ":", PC);
2117 // Check the data in code table here to see if this is data not an
2118 // instruction to be disassembled.
2120 Dice.push_back(std::make_pair(PC, DiceRef()));
2121 dice_table_iterator DTI =
2122 std::search(Dices.begin(), Dices.end(), Dice.begin(), Dice.end(),
2123 compareDiceTableEntries);
2124 if (DTI != Dices.end()) {
2126 DTI->second.getLength(Length);
2128 DTI->second.getKind(Kind);
2129 Size = DumpDataInCode(reinterpret_cast<const char *>(Bytes.data()) +
2132 if ((Kind == MachO::DICE_KIND_JUMP_TABLE8) &&
2133 (PC == (DTI->first + Length - 1)) && (Length & 1))
2138 SmallVector<char, 64> AnnotationsBytes;
2139 raw_svector_ostream Annotations(AnnotationsBytes);
2143 gotInst = ThumbDisAsm->getInstruction(Inst, Size, Bytes.slice(Index),
2144 PC, DebugOut, Annotations);
2146 gotInst = DisAsm->getInstruction(Inst, Size, Bytes.slice(Index), PC,
2147 DebugOut, Annotations);
2149 if (!NoShowRawInsn) {
2150 DumpBytes(StringRef(
2151 reinterpret_cast<const char *>(Bytes.data()) + Index, Size));
2153 formatted_raw_ostream FormattedOS(outs());
2154 Annotations.flush();
2155 StringRef AnnotationsStr = Annotations.str();
2157 ThumbIP->printInst(&Inst, FormattedOS, AnnotationsStr);
2159 IP->printInst(&Inst, FormattedOS, AnnotationsStr);
2160 emitComments(CommentStream, CommentsToEmit, FormattedOS, *AsmInfo);
2162 // Print debug info.
2164 DILineInfo dli = diContext->getLineInfoForAddress(PC);
2165 // Print valid line info if it changed.
2166 if (dli != lastLine && dli.Line != 0)
2167 outs() << "\t## " << dli.FileName << ':' << dli.Line << ':'
2173 unsigned int Arch = MachOOF->getArch();
2174 if (Arch == Triple::x86_64 || Arch == Triple::x86) {
2175 outs() << format("\t.byte 0x%02x #bad opcode\n",
2176 *(Bytes.data() + Index) & 0xff);
2177 Size = 1; // skip exactly one illegible byte and move on.
2178 } else if (Arch == Triple::aarch64) {
2179 uint32_t opcode = (*(Bytes.data() + Index) & 0xff) |
2180 (*(Bytes.data() + Index + 1) & 0xff) << 8 |
2181 (*(Bytes.data() + Index + 2) & 0xff) << 16 |
2182 (*(Bytes.data() + Index + 3) & 0xff) << 24;
2183 outs() << format("\t.long\t0x%08x\n", opcode);
2186 errs() << "llvm-objdump: warning: invalid instruction encoding\n";
2188 Size = 1; // skip illegible bytes
2193 if (!symbolTableWorked) {
2194 // Reading the symbol table didn't work, disassemble the whole section.
2195 uint64_t SectAddress = Sections[SectIdx].getAddress();
2196 uint64_t SectSize = Sections[SectIdx].getSize();
2198 for (uint64_t Index = 0; Index < SectSize; Index += InstSize) {
2201 uint64_t PC = SectAddress + Index;
2202 if (DisAsm->getInstruction(Inst, InstSize, Bytes.slice(Index), PC,
2203 DebugOut, nulls())) {
2204 if (FullLeadingAddr) {
2205 if (MachOOF->is64Bit())
2206 outs() << format("%016" PRIx64, PC);
2208 outs() << format("%08" PRIx64, PC);
2210 outs() << format("%8" PRIx64 ":", PC);
2212 if (!NoShowRawInsn) {
2215 StringRef(reinterpret_cast<const char *>(Bytes.data()) + Index,
2218 IP->printInst(&Inst, outs(), "");
2221 unsigned int Arch = MachOOF->getArch();
2222 if (Arch == Triple::x86_64 || Arch == Triple::x86) {
2223 outs() << format("\t.byte 0x%02x #bad opcode\n",
2224 *(Bytes.data() + Index) & 0xff);
2225 InstSize = 1; // skip exactly one illegible byte and move on.
2227 errs() << "llvm-objdump: warning: invalid instruction encoding\n";
2229 InstSize = 1; // skip illegible bytes
2234 // The TripleName's need to be reset if we are called again for a different
2237 ThumbTripleName = "";
2239 if (SymbolizerInfo.method != nullptr)
2240 free(SymbolizerInfo.method);
2241 if (SymbolizerInfo.demangled_name != nullptr)
2242 free(SymbolizerInfo.demangled_name);
2243 if (SymbolizerInfo.bindtable != nullptr)
2244 delete SymbolizerInfo.bindtable;
2245 if (ThumbSymbolizerInfo.method != nullptr)
2246 free(ThumbSymbolizerInfo.method);
2247 if (ThumbSymbolizerInfo.demangled_name != nullptr)
2248 free(ThumbSymbolizerInfo.demangled_name);
2249 if (ThumbSymbolizerInfo.bindtable != nullptr)
2250 delete ThumbSymbolizerInfo.bindtable;
2254 //===----------------------------------------------------------------------===//
2255 // __compact_unwind section dumping
2256 //===----------------------------------------------------------------------===//
2260 template <typename T> static uint64_t readNext(const char *&Buf) {
2261 using llvm::support::little;
2262 using llvm::support::unaligned;
2264 uint64_t Val = support::endian::read<T, little, unaligned>(Buf);
2269 struct CompactUnwindEntry {
2270 uint32_t OffsetInSection;
2272 uint64_t FunctionAddr;
2274 uint32_t CompactEncoding;
2275 uint64_t PersonalityAddr;
2278 RelocationRef FunctionReloc;
2279 RelocationRef PersonalityReloc;
2280 RelocationRef LSDAReloc;
2282 CompactUnwindEntry(StringRef Contents, unsigned Offset, bool Is64)
2283 : OffsetInSection(Offset) {
2285 read<uint64_t>(Contents.data() + Offset);
2287 read<uint32_t>(Contents.data() + Offset);
2291 template <typename UIntPtr> void read(const char *Buf) {
2292 FunctionAddr = readNext<UIntPtr>(Buf);
2293 Length = readNext<uint32_t>(Buf);
2294 CompactEncoding = readNext<uint32_t>(Buf);
2295 PersonalityAddr = readNext<UIntPtr>(Buf);
2296 LSDAAddr = readNext<UIntPtr>(Buf);
2301 /// Given a relocation from __compact_unwind, consisting of the RelocationRef
2302 /// and data being relocated, determine the best base Name and Addend to use for
2303 /// display purposes.
2305 /// 1. An Extern relocation will directly reference a symbol (and the data is
2306 /// then already an addend), so use that.
2307 /// 2. Otherwise the data is an offset in the object file's layout; try to find
2308 // a symbol before it in the same section, and use the offset from there.
2309 /// 3. Finally, if all that fails, fall back to an offset from the start of the
2310 /// referenced section.
2311 static void findUnwindRelocNameAddend(const MachOObjectFile *Obj,
2312 std::map<uint64_t, SymbolRef> &Symbols,
2313 const RelocationRef &Reloc, uint64_t Addr,
2314 StringRef &Name, uint64_t &Addend) {
2315 if (Reloc.getSymbol() != Obj->symbol_end()) {
2316 Reloc.getSymbol()->getName(Name);
2321 auto RE = Obj->getRelocation(Reloc.getRawDataRefImpl());
2322 SectionRef RelocSection = Obj->getRelocationSection(RE);
2324 uint64_t SectionAddr = RelocSection.getAddress();
2326 auto Sym = Symbols.upper_bound(Addr);
2327 if (Sym == Symbols.begin()) {
2328 // The first symbol in the object is after this reference, the best we can
2329 // do is section-relative notation.
2330 RelocSection.getName(Name);
2331 Addend = Addr - SectionAddr;
2335 // Go back one so that SymbolAddress <= Addr.
2338 section_iterator SymSection = Obj->section_end();
2339 Sym->second.getSection(SymSection);
2340 if (RelocSection == *SymSection) {
2341 // There's a valid symbol in the same section before this reference.
2342 Sym->second.getName(Name);
2343 Addend = Addr - Sym->first;
2347 // There is a symbol before this reference, but it's in a different
2348 // section. Probably not helpful to mention it, so use the section name.
2349 RelocSection.getName(Name);
2350 Addend = Addr - SectionAddr;
2353 static void printUnwindRelocDest(const MachOObjectFile *Obj,
2354 std::map<uint64_t, SymbolRef> &Symbols,
2355 const RelocationRef &Reloc, uint64_t Addr) {
2359 if (!Reloc.getObjectFile())
2362 findUnwindRelocNameAddend(Obj, Symbols, Reloc, Addr, Name, Addend);
2366 outs() << " + " << format("0x%" PRIx64, Addend);
2370 printMachOCompactUnwindSection(const MachOObjectFile *Obj,
2371 std::map<uint64_t, SymbolRef> &Symbols,
2372 const SectionRef &CompactUnwind) {
2374 assert(Obj->isLittleEndian() &&
2375 "There should not be a big-endian .o with __compact_unwind");
2377 bool Is64 = Obj->is64Bit();
2378 uint32_t PointerSize = Is64 ? sizeof(uint64_t) : sizeof(uint32_t);
2379 uint32_t EntrySize = 3 * PointerSize + 2 * sizeof(uint32_t);
2382 CompactUnwind.getContents(Contents);
2384 SmallVector<CompactUnwindEntry, 4> CompactUnwinds;
2386 // First populate the initial raw offsets, encodings and so on from the entry.
2387 for (unsigned Offset = 0; Offset < Contents.size(); Offset += EntrySize) {
2388 CompactUnwindEntry Entry(Contents.data(), Offset, Is64);
2389 CompactUnwinds.push_back(Entry);
2392 // Next we need to look at the relocations to find out what objects are
2393 // actually being referred to.
2394 for (const RelocationRef &Reloc : CompactUnwind.relocations()) {
2395 uint64_t RelocAddress;
2396 Reloc.getOffset(RelocAddress);
2398 uint32_t EntryIdx = RelocAddress / EntrySize;
2399 uint32_t OffsetInEntry = RelocAddress - EntryIdx * EntrySize;
2400 CompactUnwindEntry &Entry = CompactUnwinds[EntryIdx];
2402 if (OffsetInEntry == 0)
2403 Entry.FunctionReloc = Reloc;
2404 else if (OffsetInEntry == PointerSize + 2 * sizeof(uint32_t))
2405 Entry.PersonalityReloc = Reloc;
2406 else if (OffsetInEntry == 2 * PointerSize + 2 * sizeof(uint32_t))
2407 Entry.LSDAReloc = Reloc;
2409 llvm_unreachable("Unexpected relocation in __compact_unwind section");
2412 // Finally, we're ready to print the data we've gathered.
2413 outs() << "Contents of __compact_unwind section:\n";
2414 for (auto &Entry : CompactUnwinds) {
2415 outs() << " Entry at offset "
2416 << format("0x%" PRIx32, Entry.OffsetInSection) << ":\n";
2418 // 1. Start of the region this entry applies to.
2419 outs() << " start: " << format("0x%" PRIx64,
2420 Entry.FunctionAddr) << ' ';
2421 printUnwindRelocDest(Obj, Symbols, Entry.FunctionReloc, Entry.FunctionAddr);
2424 // 2. Length of the region this entry applies to.
2425 outs() << " length: " << format("0x%" PRIx32, Entry.Length)
2427 // 3. The 32-bit compact encoding.
2428 outs() << " compact encoding: "
2429 << format("0x%08" PRIx32, Entry.CompactEncoding) << '\n';
2431 // 4. The personality function, if present.
2432 if (Entry.PersonalityReloc.getObjectFile()) {
2433 outs() << " personality function: "
2434 << format("0x%" PRIx64, Entry.PersonalityAddr) << ' ';
2435 printUnwindRelocDest(Obj, Symbols, Entry.PersonalityReloc,
2436 Entry.PersonalityAddr);
2440 // 5. This entry's language-specific data area.
2441 if (Entry.LSDAReloc.getObjectFile()) {
2442 outs() << " LSDA: " << format("0x%" PRIx64,
2443 Entry.LSDAAddr) << ' ';
2444 printUnwindRelocDest(Obj, Symbols, Entry.LSDAReloc, Entry.LSDAAddr);
2450 //===----------------------------------------------------------------------===//
2451 // __unwind_info section dumping
2452 //===----------------------------------------------------------------------===//
2454 static void printRegularSecondLevelUnwindPage(const char *PageStart) {
2455 const char *Pos = PageStart;
2456 uint32_t Kind = readNext<uint32_t>(Pos);
2458 assert(Kind == 2 && "kind for a regular 2nd level index should be 2");
2460 uint16_t EntriesStart = readNext<uint16_t>(Pos);
2461 uint16_t NumEntries = readNext<uint16_t>(Pos);
2463 Pos = PageStart + EntriesStart;
2464 for (unsigned i = 0; i < NumEntries; ++i) {
2465 uint32_t FunctionOffset = readNext<uint32_t>(Pos);
2466 uint32_t Encoding = readNext<uint32_t>(Pos);
2468 outs() << " [" << i << "]: "
2469 << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
2471 << "encoding=" << format("0x%08" PRIx32, Encoding) << '\n';
2475 static void printCompressedSecondLevelUnwindPage(
2476 const char *PageStart, uint32_t FunctionBase,
2477 const SmallVectorImpl<uint32_t> &CommonEncodings) {
2478 const char *Pos = PageStart;
2479 uint32_t Kind = readNext<uint32_t>(Pos);
2481 assert(Kind == 3 && "kind for a compressed 2nd level index should be 3");
2483 uint16_t EntriesStart = readNext<uint16_t>(Pos);
2484 uint16_t NumEntries = readNext<uint16_t>(Pos);
2486 uint16_t EncodingsStart = readNext<uint16_t>(Pos);
2487 readNext<uint16_t>(Pos);
2488 const auto *PageEncodings = reinterpret_cast<const support::ulittle32_t *>(
2489 PageStart + EncodingsStart);
2491 Pos = PageStart + EntriesStart;
2492 for (unsigned i = 0; i < NumEntries; ++i) {
2493 uint32_t Entry = readNext<uint32_t>(Pos);
2494 uint32_t FunctionOffset = FunctionBase + (Entry & 0xffffff);
2495 uint32_t EncodingIdx = Entry >> 24;
2498 if (EncodingIdx < CommonEncodings.size())
2499 Encoding = CommonEncodings[EncodingIdx];
2501 Encoding = PageEncodings[EncodingIdx - CommonEncodings.size()];
2503 outs() << " [" << i << "]: "
2504 << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
2506 << "encoding[" << EncodingIdx
2507 << "]=" << format("0x%08" PRIx32, Encoding) << '\n';
2511 static void printMachOUnwindInfoSection(const MachOObjectFile *Obj,
2512 std::map<uint64_t, SymbolRef> &Symbols,
2513 const SectionRef &UnwindInfo) {
2515 assert(Obj->isLittleEndian() &&
2516 "There should not be a big-endian .o with __unwind_info");
2518 outs() << "Contents of __unwind_info section:\n";
2521 UnwindInfo.getContents(Contents);
2522 const char *Pos = Contents.data();
2524 //===----------------------------------
2526 //===----------------------------------
2528 uint32_t Version = readNext<uint32_t>(Pos);
2529 outs() << " Version: "
2530 << format("0x%" PRIx32, Version) << '\n';
2531 assert(Version == 1 && "only understand version 1");
2533 uint32_t CommonEncodingsStart = readNext<uint32_t>(Pos);
2534 outs() << " Common encodings array section offset: "
2535 << format("0x%" PRIx32, CommonEncodingsStart) << '\n';
2536 uint32_t NumCommonEncodings = readNext<uint32_t>(Pos);
2537 outs() << " Number of common encodings in array: "
2538 << format("0x%" PRIx32, NumCommonEncodings) << '\n';
2540 uint32_t PersonalitiesStart = readNext<uint32_t>(Pos);
2541 outs() << " Personality function array section offset: "
2542 << format("0x%" PRIx32, PersonalitiesStart) << '\n';
2543 uint32_t NumPersonalities = readNext<uint32_t>(Pos);
2544 outs() << " Number of personality functions in array: "
2545 << format("0x%" PRIx32, NumPersonalities) << '\n';
2547 uint32_t IndicesStart = readNext<uint32_t>(Pos);
2548 outs() << " Index array section offset: "
2549 << format("0x%" PRIx32, IndicesStart) << '\n';
2550 uint32_t NumIndices = readNext<uint32_t>(Pos);
2551 outs() << " Number of indices in array: "
2552 << format("0x%" PRIx32, NumIndices) << '\n';
2554 //===----------------------------------
2555 // A shared list of common encodings
2556 //===----------------------------------
2558 // These occupy indices in the range [0, N] whenever an encoding is referenced
2559 // from a compressed 2nd level index table. In practice the linker only
2560 // creates ~128 of these, so that indices are available to embed encodings in
2561 // the 2nd level index.
2563 SmallVector<uint32_t, 64> CommonEncodings;
2564 outs() << " Common encodings: (count = " << NumCommonEncodings << ")\n";
2565 Pos = Contents.data() + CommonEncodingsStart;
2566 for (unsigned i = 0; i < NumCommonEncodings; ++i) {
2567 uint32_t Encoding = readNext<uint32_t>(Pos);
2568 CommonEncodings.push_back(Encoding);
2570 outs() << " encoding[" << i << "]: " << format("0x%08" PRIx32, Encoding)
2574 //===----------------------------------
2575 // Personality functions used in this executable
2576 //===----------------------------------
2578 // There should be only a handful of these (one per source language,
2579 // roughly). Particularly since they only get 2 bits in the compact encoding.
2581 outs() << " Personality functions: (count = " << NumPersonalities << ")\n";
2582 Pos = Contents.data() + PersonalitiesStart;
2583 for (unsigned i = 0; i < NumPersonalities; ++i) {
2584 uint32_t PersonalityFn = readNext<uint32_t>(Pos);
2585 outs() << " personality[" << i + 1
2586 << "]: " << format("0x%08" PRIx32, PersonalityFn) << '\n';
2589 //===----------------------------------
2590 // The level 1 index entries
2591 //===----------------------------------
2593 // These specify an approximate place to start searching for the more detailed
2594 // information, sorted by PC.
2597 uint32_t FunctionOffset;
2598 uint32_t SecondLevelPageStart;
2602 SmallVector<IndexEntry, 4> IndexEntries;
2604 outs() << " Top level indices: (count = " << NumIndices << ")\n";
2605 Pos = Contents.data() + IndicesStart;
2606 for (unsigned i = 0; i < NumIndices; ++i) {
2609 Entry.FunctionOffset = readNext<uint32_t>(Pos);
2610 Entry.SecondLevelPageStart = readNext<uint32_t>(Pos);
2611 Entry.LSDAStart = readNext<uint32_t>(Pos);
2612 IndexEntries.push_back(Entry);
2614 outs() << " [" << i << "]: "
2615 << "function offset=" << format("0x%08" PRIx32, Entry.FunctionOffset)
2617 << "2nd level page offset="
2618 << format("0x%08" PRIx32, Entry.SecondLevelPageStart) << ", "
2619 << "LSDA offset=" << format("0x%08" PRIx32, Entry.LSDAStart) << '\n';
2622 //===----------------------------------
2623 // Next come the LSDA tables
2624 //===----------------------------------
2626 // The LSDA layout is rather implicit: it's a contiguous array of entries from
2627 // the first top-level index's LSDAOffset to the last (sentinel).
2629 outs() << " LSDA descriptors:\n";
2630 Pos = Contents.data() + IndexEntries[0].LSDAStart;
2631 int NumLSDAs = (IndexEntries.back().LSDAStart - IndexEntries[0].LSDAStart) /
2632 (2 * sizeof(uint32_t));
2633 for (int i = 0; i < NumLSDAs; ++i) {
2634 uint32_t FunctionOffset = readNext<uint32_t>(Pos);
2635 uint32_t LSDAOffset = readNext<uint32_t>(Pos);
2636 outs() << " [" << i << "]: "
2637 << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
2639 << "LSDA offset=" << format("0x%08" PRIx32, LSDAOffset) << '\n';
2642 //===----------------------------------
2643 // Finally, the 2nd level indices
2644 //===----------------------------------
2646 // Generally these are 4K in size, and have 2 possible forms:
2647 // + Regular stores up to 511 entries with disparate encodings
2648 // + Compressed stores up to 1021 entries if few enough compact encoding
2650 outs() << " Second level indices:\n";
2651 for (unsigned i = 0; i < IndexEntries.size() - 1; ++i) {
2652 // The final sentinel top-level index has no associated 2nd level page
2653 if (IndexEntries[i].SecondLevelPageStart == 0)
2656 outs() << " Second level index[" << i << "]: "
2657 << "offset in section="
2658 << format("0x%08" PRIx32, IndexEntries[i].SecondLevelPageStart)
2660 << "base function offset="
2661 << format("0x%08" PRIx32, IndexEntries[i].FunctionOffset) << '\n';
2663 Pos = Contents.data() + IndexEntries[i].SecondLevelPageStart;
2664 uint32_t Kind = *reinterpret_cast<const support::ulittle32_t *>(Pos);
2666 printRegularSecondLevelUnwindPage(Pos);
2668 printCompressedSecondLevelUnwindPage(Pos, IndexEntries[i].FunctionOffset,
2671 llvm_unreachable("Do not know how to print this kind of 2nd level page");
2675 void llvm::printMachOUnwindInfo(const MachOObjectFile *Obj) {
2676 std::map<uint64_t, SymbolRef> Symbols;
2677 for (const SymbolRef &SymRef : Obj->symbols()) {
2678 // Discard any undefined or absolute symbols. They're not going to take part
2679 // in the convenience lookup for unwind info and just take up resources.
2680 section_iterator Section = Obj->section_end();
2681 SymRef.getSection(Section);
2682 if (Section == Obj->section_end())
2686 SymRef.getAddress(Addr);
2687 Symbols.insert(std::make_pair(Addr, SymRef));
2690 for (const SectionRef &Section : Obj->sections()) {
2692 Section.getName(SectName);
2693 if (SectName == "__compact_unwind")
2694 printMachOCompactUnwindSection(Obj, Symbols, Section);
2695 else if (SectName == "__unwind_info")
2696 printMachOUnwindInfoSection(Obj, Symbols, Section);
2697 else if (SectName == "__eh_frame")
2698 outs() << "llvm-objdump: warning: unhandled __eh_frame section\n";
2702 static void PrintMachHeader(uint32_t magic, uint32_t cputype,
2703 uint32_t cpusubtype, uint32_t filetype,
2704 uint32_t ncmds, uint32_t sizeofcmds, uint32_t flags,
2706 outs() << "Mach header\n";
2707 outs() << " magic cputype cpusubtype caps filetype ncmds "
2708 "sizeofcmds flags\n";
2710 if (magic == MachO::MH_MAGIC)
2711 outs() << " MH_MAGIC";
2712 else if (magic == MachO::MH_MAGIC_64)
2713 outs() << "MH_MAGIC_64";
2715 outs() << format(" 0x%08" PRIx32, magic);
2717 case MachO::CPU_TYPE_I386:
2719 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
2720 case MachO::CPU_SUBTYPE_I386_ALL:
2724 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
2728 case MachO::CPU_TYPE_X86_64:
2729 outs() << " X86_64";
2730 case MachO::CPU_SUBTYPE_X86_64_ALL:
2733 case MachO::CPU_SUBTYPE_X86_64_H:
2734 outs() << " Haswell";
2735 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
2737 case MachO::CPU_TYPE_ARM:
2739 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
2740 case MachO::CPU_SUBTYPE_ARM_ALL:
2743 case MachO::CPU_SUBTYPE_ARM_V4T:
2746 case MachO::CPU_SUBTYPE_ARM_V5TEJ:
2749 case MachO::CPU_SUBTYPE_ARM_XSCALE:
2750 outs() << " XSCALE";
2752 case MachO::CPU_SUBTYPE_ARM_V6:
2755 case MachO::CPU_SUBTYPE_ARM_V6M:
2758 case MachO::CPU_SUBTYPE_ARM_V7:
2761 case MachO::CPU_SUBTYPE_ARM_V7EM:
2764 case MachO::CPU_SUBTYPE_ARM_V7K:
2767 case MachO::CPU_SUBTYPE_ARM_V7M:
2770 case MachO::CPU_SUBTYPE_ARM_V7S:
2774 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
2778 case MachO::CPU_TYPE_ARM64:
2780 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
2781 case MachO::CPU_SUBTYPE_ARM64_ALL:
2785 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
2789 case MachO::CPU_TYPE_POWERPC:
2791 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
2792 case MachO::CPU_SUBTYPE_POWERPC_ALL:
2796 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
2800 case MachO::CPU_TYPE_POWERPC64:
2802 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
2803 case MachO::CPU_SUBTYPE_POWERPC_ALL:
2807 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
2812 if ((cpusubtype & MachO::CPU_SUBTYPE_MASK) == MachO::CPU_SUBTYPE_LIB64) {
2815 outs() << format(" 0x%02" PRIx32,
2816 (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24);
2819 case MachO::MH_OBJECT:
2820 outs() << " OBJECT";
2822 case MachO::MH_EXECUTE:
2823 outs() << " EXECUTE";
2825 case MachO::MH_FVMLIB:
2826 outs() << " FVMLIB";
2828 case MachO::MH_CORE:
2831 case MachO::MH_PRELOAD:
2832 outs() << " PRELOAD";
2834 case MachO::MH_DYLIB:
2837 case MachO::MH_DYLIB_STUB:
2838 outs() << " DYLIB_STUB";
2840 case MachO::MH_DYLINKER:
2841 outs() << " DYLINKER";
2843 case MachO::MH_BUNDLE:
2844 outs() << " BUNDLE";
2846 case MachO::MH_DSYM:
2849 case MachO::MH_KEXT_BUNDLE:
2850 outs() << " KEXTBUNDLE";
2853 outs() << format(" %10u", filetype);
2856 outs() << format(" %5u", ncmds);
2857 outs() << format(" %10u", sizeofcmds);
2859 if (f & MachO::MH_NOUNDEFS) {
2860 outs() << " NOUNDEFS";
2861 f &= ~MachO::MH_NOUNDEFS;
2863 if (f & MachO::MH_INCRLINK) {
2864 outs() << " INCRLINK";
2865 f &= ~MachO::MH_INCRLINK;
2867 if (f & MachO::MH_DYLDLINK) {
2868 outs() << " DYLDLINK";
2869 f &= ~MachO::MH_DYLDLINK;
2871 if (f & MachO::MH_BINDATLOAD) {
2872 outs() << " BINDATLOAD";
2873 f &= ~MachO::MH_BINDATLOAD;
2875 if (f & MachO::MH_PREBOUND) {
2876 outs() << " PREBOUND";
2877 f &= ~MachO::MH_PREBOUND;
2879 if (f & MachO::MH_SPLIT_SEGS) {
2880 outs() << " SPLIT_SEGS";
2881 f &= ~MachO::MH_SPLIT_SEGS;
2883 if (f & MachO::MH_LAZY_INIT) {
2884 outs() << " LAZY_INIT";
2885 f &= ~MachO::MH_LAZY_INIT;
2887 if (f & MachO::MH_TWOLEVEL) {
2888 outs() << " TWOLEVEL";
2889 f &= ~MachO::MH_TWOLEVEL;
2891 if (f & MachO::MH_FORCE_FLAT) {
2892 outs() << " FORCE_FLAT";
2893 f &= ~MachO::MH_FORCE_FLAT;
2895 if (f & MachO::MH_NOMULTIDEFS) {
2896 outs() << " NOMULTIDEFS";
2897 f &= ~MachO::MH_NOMULTIDEFS;
2899 if (f & MachO::MH_NOFIXPREBINDING) {
2900 outs() << " NOFIXPREBINDING";
2901 f &= ~MachO::MH_NOFIXPREBINDING;
2903 if (f & MachO::MH_PREBINDABLE) {
2904 outs() << " PREBINDABLE";
2905 f &= ~MachO::MH_PREBINDABLE;
2907 if (f & MachO::MH_ALLMODSBOUND) {
2908 outs() << " ALLMODSBOUND";
2909 f &= ~MachO::MH_ALLMODSBOUND;
2911 if (f & MachO::MH_SUBSECTIONS_VIA_SYMBOLS) {
2912 outs() << " SUBSECTIONS_VIA_SYMBOLS";
2913 f &= ~MachO::MH_SUBSECTIONS_VIA_SYMBOLS;
2915 if (f & MachO::MH_CANONICAL) {
2916 outs() << " CANONICAL";
2917 f &= ~MachO::MH_CANONICAL;
2919 if (f & MachO::MH_WEAK_DEFINES) {
2920 outs() << " WEAK_DEFINES";
2921 f &= ~MachO::MH_WEAK_DEFINES;
2923 if (f & MachO::MH_BINDS_TO_WEAK) {
2924 outs() << " BINDS_TO_WEAK";
2925 f &= ~MachO::MH_BINDS_TO_WEAK;
2927 if (f & MachO::MH_ALLOW_STACK_EXECUTION) {
2928 outs() << " ALLOW_STACK_EXECUTION";
2929 f &= ~MachO::MH_ALLOW_STACK_EXECUTION;
2931 if (f & MachO::MH_DEAD_STRIPPABLE_DYLIB) {
2932 outs() << " DEAD_STRIPPABLE_DYLIB";
2933 f &= ~MachO::MH_DEAD_STRIPPABLE_DYLIB;
2935 if (f & MachO::MH_PIE) {
2937 f &= ~MachO::MH_PIE;
2939 if (f & MachO::MH_NO_REEXPORTED_DYLIBS) {
2940 outs() << " NO_REEXPORTED_DYLIBS";
2941 f &= ~MachO::MH_NO_REEXPORTED_DYLIBS;
2943 if (f & MachO::MH_HAS_TLV_DESCRIPTORS) {
2944 outs() << " MH_HAS_TLV_DESCRIPTORS";
2945 f &= ~MachO::MH_HAS_TLV_DESCRIPTORS;
2947 if (f & MachO::MH_NO_HEAP_EXECUTION) {
2948 outs() << " MH_NO_HEAP_EXECUTION";
2949 f &= ~MachO::MH_NO_HEAP_EXECUTION;
2951 if (f & MachO::MH_APP_EXTENSION_SAFE) {
2952 outs() << " APP_EXTENSION_SAFE";
2953 f &= ~MachO::MH_APP_EXTENSION_SAFE;
2955 if (f != 0 || flags == 0)
2956 outs() << format(" 0x%08" PRIx32, f);
2958 outs() << format(" 0x%08" PRIx32, magic);
2959 outs() << format(" %7d", cputype);
2960 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
2961 outs() << format(" 0x%02" PRIx32,
2962 (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24);
2963 outs() << format(" %10u", filetype);
2964 outs() << format(" %5u", ncmds);
2965 outs() << format(" %10u", sizeofcmds);
2966 outs() << format(" 0x%08" PRIx32, flags);
2971 static void PrintSegmentCommand(uint32_t cmd, uint32_t cmdsize,
2972 StringRef SegName, uint64_t vmaddr,
2973 uint64_t vmsize, uint64_t fileoff,
2974 uint64_t filesize, uint32_t maxprot,
2975 uint32_t initprot, uint32_t nsects,
2976 uint32_t flags, uint32_t object_size,
2978 uint64_t expected_cmdsize;
2979 if (cmd == MachO::LC_SEGMENT) {
2980 outs() << " cmd LC_SEGMENT\n";
2981 expected_cmdsize = nsects;
2982 expected_cmdsize *= sizeof(struct MachO::section);
2983 expected_cmdsize += sizeof(struct MachO::segment_command);
2985 outs() << " cmd LC_SEGMENT_64\n";
2986 expected_cmdsize = nsects;
2987 expected_cmdsize *= sizeof(struct MachO::section_64);
2988 expected_cmdsize += sizeof(struct MachO::segment_command_64);
2990 outs() << " cmdsize " << cmdsize;
2991 if (cmdsize != expected_cmdsize)
2992 outs() << " Inconsistent size\n";
2995 outs() << " segname " << SegName << "\n";
2996 if (cmd == MachO::LC_SEGMENT_64) {
2997 outs() << " vmaddr " << format("0x%016" PRIx64, vmaddr) << "\n";
2998 outs() << " vmsize " << format("0x%016" PRIx64, vmsize) << "\n";
3000 outs() << " vmaddr " << format("0x%08" PRIx32, vmaddr) << "\n";
3001 outs() << " vmsize " << format("0x%08" PRIx32, vmsize) << "\n";
3003 outs() << " fileoff " << fileoff;
3004 if (fileoff > object_size)
3005 outs() << " (past end of file)\n";
3008 outs() << " filesize " << filesize;
3009 if (fileoff + filesize > object_size)
3010 outs() << " (past end of file)\n";
3015 ~(MachO::VM_PROT_READ | MachO::VM_PROT_WRITE |
3016 MachO::VM_PROT_EXECUTE)) != 0)
3017 outs() << " maxprot ?" << format("0x%08" PRIx32, maxprot) << "\n";
3019 if (maxprot & MachO::VM_PROT_READ)
3020 outs() << " maxprot r";
3022 outs() << " maxprot -";
3023 if (maxprot & MachO::VM_PROT_WRITE)
3027 if (maxprot & MachO::VM_PROT_EXECUTE)
3033 ~(MachO::VM_PROT_READ | MachO::VM_PROT_WRITE |
3034 MachO::VM_PROT_EXECUTE)) != 0)
3035 outs() << " initprot ?" << format("0x%08" PRIx32, initprot) << "\n";
3037 if (initprot & MachO::VM_PROT_READ)
3038 outs() << " initprot r";
3040 outs() << " initprot -";
3041 if (initprot & MachO::VM_PROT_WRITE)
3045 if (initprot & MachO::VM_PROT_EXECUTE)
3051 outs() << " maxprot " << format("0x%08" PRIx32, maxprot) << "\n";
3052 outs() << " initprot " << format("0x%08" PRIx32, initprot) << "\n";
3054 outs() << " nsects " << nsects << "\n";
3058 outs() << " (none)\n";
3060 if (flags & MachO::SG_HIGHVM) {
3061 outs() << " HIGHVM";
3062 flags &= ~MachO::SG_HIGHVM;
3064 if (flags & MachO::SG_FVMLIB) {
3065 outs() << " FVMLIB";
3066 flags &= ~MachO::SG_FVMLIB;
3068 if (flags & MachO::SG_NORELOC) {
3069 outs() << " NORELOC";
3070 flags &= ~MachO::SG_NORELOC;
3072 if (flags & MachO::SG_PROTECTED_VERSION_1) {
3073 outs() << " PROTECTED_VERSION_1";
3074 flags &= ~MachO::SG_PROTECTED_VERSION_1;
3077 outs() << format(" 0x%08" PRIx32, flags) << " (unknown flags)\n";
3082 outs() << " flags " << format("0x%" PRIx32, flags) << "\n";
3086 static void PrintSection(const char *sectname, const char *segname,
3087 uint64_t addr, uint64_t size, uint32_t offset,
3088 uint32_t align, uint32_t reloff, uint32_t nreloc,
3089 uint32_t flags, uint32_t reserved1, uint32_t reserved2,
3090 uint32_t cmd, const char *sg_segname,
3091 uint32_t filetype, uint32_t object_size,
3093 outs() << "Section\n";
3094 outs() << " sectname " << format("%.16s\n", sectname);
3095 outs() << " segname " << format("%.16s", segname);
3096 if (filetype != MachO::MH_OBJECT && strncmp(sg_segname, segname, 16) != 0)
3097 outs() << " (does not match segment)\n";
3100 if (cmd == MachO::LC_SEGMENT_64) {
3101 outs() << " addr " << format("0x%016" PRIx64, addr) << "\n";
3102 outs() << " size " << format("0x%016" PRIx64, size);
3104 outs() << " addr " << format("0x%08" PRIx32, addr) << "\n";
3105 outs() << " size " << format("0x%08" PRIx32, size);
3107 if ((flags & MachO::S_ZEROFILL) != 0 && offset + size > object_size)
3108 outs() << " (past end of file)\n";
3111 outs() << " offset " << offset;
3112 if (offset > object_size)
3113 outs() << " (past end of file)\n";
3116 uint32_t align_shifted = 1 << align;
3117 outs() << " align 2^" << align << " (" << align_shifted << ")\n";
3118 outs() << " reloff " << reloff;
3119 if (reloff > object_size)
3120 outs() << " (past end of file)\n";
3123 outs() << " nreloc " << nreloc;
3124 if (reloff + nreloc * sizeof(struct MachO::relocation_info) > object_size)
3125 outs() << " (past end of file)\n";
3128 uint32_t section_type = flags & MachO::SECTION_TYPE;
3131 if (section_type == MachO::S_REGULAR)
3132 outs() << " S_REGULAR\n";
3133 else if (section_type == MachO::S_ZEROFILL)
3134 outs() << " S_ZEROFILL\n";
3135 else if (section_type == MachO::S_CSTRING_LITERALS)
3136 outs() << " S_CSTRING_LITERALS\n";
3137 else if (section_type == MachO::S_4BYTE_LITERALS)
3138 outs() << " S_4BYTE_LITERALS\n";
3139 else if (section_type == MachO::S_8BYTE_LITERALS)
3140 outs() << " S_8BYTE_LITERALS\n";
3141 else if (section_type == MachO::S_16BYTE_LITERALS)
3142 outs() << " S_16BYTE_LITERALS\n";
3143 else if (section_type == MachO::S_LITERAL_POINTERS)
3144 outs() << " S_LITERAL_POINTERS\n";
3145 else if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS)
3146 outs() << " S_NON_LAZY_SYMBOL_POINTERS\n";
3147 else if (section_type == MachO::S_LAZY_SYMBOL_POINTERS)
3148 outs() << " S_LAZY_SYMBOL_POINTERS\n";
3149 else if (section_type == MachO::S_SYMBOL_STUBS)
3150 outs() << " S_SYMBOL_STUBS\n";
3151 else if (section_type == MachO::S_MOD_INIT_FUNC_POINTERS)
3152 outs() << " S_MOD_INIT_FUNC_POINTERS\n";
3153 else if (section_type == MachO::S_MOD_TERM_FUNC_POINTERS)
3154 outs() << " S_MOD_TERM_FUNC_POINTERS\n";
3155 else if (section_type == MachO::S_COALESCED)
3156 outs() << " S_COALESCED\n";
3157 else if (section_type == MachO::S_INTERPOSING)
3158 outs() << " S_INTERPOSING\n";
3159 else if (section_type == MachO::S_DTRACE_DOF)
3160 outs() << " S_DTRACE_DOF\n";
3161 else if (section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS)
3162 outs() << " S_LAZY_DYLIB_SYMBOL_POINTERS\n";
3163 else if (section_type == MachO::S_THREAD_LOCAL_REGULAR)
3164 outs() << " S_THREAD_LOCAL_REGULAR\n";
3165 else if (section_type == MachO::S_THREAD_LOCAL_ZEROFILL)
3166 outs() << " S_THREAD_LOCAL_ZEROFILL\n";
3167 else if (section_type == MachO::S_THREAD_LOCAL_VARIABLES)
3168 outs() << " S_THREAD_LOCAL_VARIABLES\n";
3169 else if (section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS)
3170 outs() << " S_THREAD_LOCAL_VARIABLE_POINTERS\n";
3171 else if (section_type == MachO::S_THREAD_LOCAL_INIT_FUNCTION_POINTERS)
3172 outs() << " S_THREAD_LOCAL_INIT_FUNCTION_POINTERS\n";
3174 outs() << format("0x%08" PRIx32, section_type) << "\n";
3175 outs() << "attributes";
3176 uint32_t section_attributes = flags & MachO::SECTION_ATTRIBUTES;
3177 if (section_attributes & MachO::S_ATTR_PURE_INSTRUCTIONS)
3178 outs() << " PURE_INSTRUCTIONS";
3179 if (section_attributes & MachO::S_ATTR_NO_TOC)
3180 outs() << " NO_TOC";
3181 if (section_attributes & MachO::S_ATTR_STRIP_STATIC_SYMS)
3182 outs() << " STRIP_STATIC_SYMS";
3183 if (section_attributes & MachO::S_ATTR_NO_DEAD_STRIP)
3184 outs() << " NO_DEAD_STRIP";
3185 if (section_attributes & MachO::S_ATTR_LIVE_SUPPORT)
3186 outs() << " LIVE_SUPPORT";
3187 if (section_attributes & MachO::S_ATTR_SELF_MODIFYING_CODE)
3188 outs() << " SELF_MODIFYING_CODE";
3189 if (section_attributes & MachO::S_ATTR_DEBUG)
3191 if (section_attributes & MachO::S_ATTR_SOME_INSTRUCTIONS)
3192 outs() << " SOME_INSTRUCTIONS";
3193 if (section_attributes & MachO::S_ATTR_EXT_RELOC)
3194 outs() << " EXT_RELOC";
3195 if (section_attributes & MachO::S_ATTR_LOC_RELOC)
3196 outs() << " LOC_RELOC";
3197 if (section_attributes == 0)
3198 outs() << " (none)";
3201 outs() << " flags " << format("0x%08" PRIx32, flags) << "\n";
3202 outs() << " reserved1 " << reserved1;
3203 if (section_type == MachO::S_SYMBOL_STUBS ||
3204 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
3205 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
3206 section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
3207 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS)
3208 outs() << " (index into indirect symbol table)\n";
3211 outs() << " reserved2 " << reserved2;
3212 if (section_type == MachO::S_SYMBOL_STUBS)
3213 outs() << " (size of stubs)\n";
3218 static void PrintSymtabLoadCommand(MachO::symtab_command st, bool Is64Bit,
3219 uint32_t object_size) {
3220 outs() << " cmd LC_SYMTAB\n";
3221 outs() << " cmdsize " << st.cmdsize;
3222 if (st.cmdsize != sizeof(struct MachO::symtab_command))
3223 outs() << " Incorrect size\n";
3226 outs() << " symoff " << st.symoff;
3227 if (st.symoff > object_size)
3228 outs() << " (past end of file)\n";
3231 outs() << " nsyms " << st.nsyms;
3234 big_size = st.nsyms;
3235 big_size *= sizeof(struct MachO::nlist_64);
3236 big_size += st.symoff;
3237 if (big_size > object_size)
3238 outs() << " (past end of file)\n";
3242 big_size = st.nsyms;
3243 big_size *= sizeof(struct MachO::nlist);
3244 big_size += st.symoff;
3245 if (big_size > object_size)
3246 outs() << " (past end of file)\n";
3250 outs() << " stroff " << st.stroff;
3251 if (st.stroff > object_size)
3252 outs() << " (past end of file)\n";
3255 outs() << " strsize " << st.strsize;
3256 big_size = st.stroff;
3257 big_size += st.strsize;
3258 if (big_size > object_size)
3259 outs() << " (past end of file)\n";
3264 static void PrintDysymtabLoadCommand(MachO::dysymtab_command dyst,
3265 uint32_t nsyms, uint32_t object_size,
3267 outs() << " cmd LC_DYSYMTAB\n";
3268 outs() << " cmdsize " << dyst.cmdsize;
3269 if (dyst.cmdsize != sizeof(struct MachO::dysymtab_command))
3270 outs() << " Incorrect size\n";
3273 outs() << " ilocalsym " << dyst.ilocalsym;
3274 if (dyst.ilocalsym > nsyms)
3275 outs() << " (greater than the number of symbols)\n";
3278 outs() << " nlocalsym " << dyst.nlocalsym;
3280 big_size = dyst.ilocalsym;
3281 big_size += dyst.nlocalsym;
3282 if (big_size > nsyms)
3283 outs() << " (past the end of the symbol table)\n";
3286 outs() << " iextdefsym " << dyst.iextdefsym;
3287 if (dyst.iextdefsym > nsyms)
3288 outs() << " (greater than the number of symbols)\n";
3291 outs() << " nextdefsym " << dyst.nextdefsym;
3292 big_size = dyst.iextdefsym;
3293 big_size += dyst.nextdefsym;
3294 if (big_size > nsyms)
3295 outs() << " (past the end of the symbol table)\n";
3298 outs() << " iundefsym " << dyst.iundefsym;
3299 if (dyst.iundefsym > nsyms)
3300 outs() << " (greater than the number of symbols)\n";
3303 outs() << " nundefsym " << dyst.nundefsym;
3304 big_size = dyst.iundefsym;
3305 big_size += dyst.nundefsym;
3306 if (big_size > nsyms)
3307 outs() << " (past the end of the symbol table)\n";
3310 outs() << " tocoff " << dyst.tocoff;
3311 if (dyst.tocoff > object_size)
3312 outs() << " (past end of file)\n";
3315 outs() << " ntoc " << dyst.ntoc;
3316 big_size = dyst.ntoc;
3317 big_size *= sizeof(struct MachO::dylib_table_of_contents);
3318 big_size += dyst.tocoff;
3319 if (big_size > object_size)
3320 outs() << " (past end of file)\n";
3323 outs() << " modtaboff " << dyst.modtaboff;
3324 if (dyst.modtaboff > object_size)
3325 outs() << " (past end of file)\n";
3328 outs() << " nmodtab " << dyst.nmodtab;
3331 modtabend = dyst.nmodtab;
3332 modtabend *= sizeof(struct MachO::dylib_module_64);
3333 modtabend += dyst.modtaboff;
3335 modtabend = dyst.nmodtab;
3336 modtabend *= sizeof(struct MachO::dylib_module);
3337 modtabend += dyst.modtaboff;
3339 if (modtabend > object_size)
3340 outs() << " (past end of file)\n";
3343 outs() << " extrefsymoff " << dyst.extrefsymoff;
3344 if (dyst.extrefsymoff > object_size)
3345 outs() << " (past end of file)\n";
3348 outs() << " nextrefsyms " << dyst.nextrefsyms;
3349 big_size = dyst.nextrefsyms;
3350 big_size *= sizeof(struct MachO::dylib_reference);
3351 big_size += dyst.extrefsymoff;
3352 if (big_size > object_size)
3353 outs() << " (past end of file)\n";
3356 outs() << " indirectsymoff " << dyst.indirectsymoff;
3357 if (dyst.indirectsymoff > object_size)
3358 outs() << " (past end of file)\n";
3361 outs() << " nindirectsyms " << dyst.nindirectsyms;
3362 big_size = dyst.nindirectsyms;
3363 big_size *= sizeof(uint32_t);
3364 big_size += dyst.indirectsymoff;
3365 if (big_size > object_size)
3366 outs() << " (past end of file)\n";
3369 outs() << " extreloff " << dyst.extreloff;
3370 if (dyst.extreloff > object_size)
3371 outs() << " (past end of file)\n";
3374 outs() << " nextrel " << dyst.nextrel;
3375 big_size = dyst.nextrel;
3376 big_size *= sizeof(struct MachO::relocation_info);
3377 big_size += dyst.extreloff;
3378 if (big_size > object_size)
3379 outs() << " (past end of file)\n";
3382 outs() << " locreloff " << dyst.locreloff;
3383 if (dyst.locreloff > object_size)
3384 outs() << " (past end of file)\n";
3387 outs() << " nlocrel " << dyst.nlocrel;
3388 big_size = dyst.nlocrel;
3389 big_size *= sizeof(struct MachO::relocation_info);
3390 big_size += dyst.locreloff;
3391 if (big_size > object_size)
3392 outs() << " (past end of file)\n";
3397 static void PrintDyldInfoLoadCommand(MachO::dyld_info_command dc,
3398 uint32_t object_size) {
3399 if (dc.cmd == MachO::LC_DYLD_INFO)
3400 outs() << " cmd LC_DYLD_INFO\n";
3402 outs() << " cmd LC_DYLD_INFO_ONLY\n";
3403 outs() << " cmdsize " << dc.cmdsize;
3404 if (dc.cmdsize != sizeof(struct MachO::dyld_info_command))
3405 outs() << " Incorrect size\n";
3408 outs() << " rebase_off " << dc.rebase_off;
3409 if (dc.rebase_off > object_size)
3410 outs() << " (past end of file)\n";
3413 outs() << " rebase_size " << dc.rebase_size;
3415 big_size = dc.rebase_off;
3416 big_size += dc.rebase_size;
3417 if (big_size > object_size)
3418 outs() << " (past end of file)\n";
3421 outs() << " bind_off " << dc.bind_off;
3422 if (dc.bind_off > object_size)
3423 outs() << " (past end of file)\n";
3426 outs() << " bind_size " << dc.bind_size;
3427 big_size = dc.bind_off;
3428 big_size += dc.bind_size;
3429 if (big_size > object_size)
3430 outs() << " (past end of file)\n";
3433 outs() << " weak_bind_off " << dc.weak_bind_off;
3434 if (dc.weak_bind_off > object_size)
3435 outs() << " (past end of file)\n";
3438 outs() << " weak_bind_size " << dc.weak_bind_size;
3439 big_size = dc.weak_bind_off;
3440 big_size += dc.weak_bind_size;
3441 if (big_size > object_size)
3442 outs() << " (past end of file)\n";
3445 outs() << " lazy_bind_off " << dc.lazy_bind_off;
3446 if (dc.lazy_bind_off > object_size)
3447 outs() << " (past end of file)\n";
3450 outs() << " lazy_bind_size " << dc.lazy_bind_size;
3451 big_size = dc.lazy_bind_off;
3452 big_size += dc.lazy_bind_size;
3453 if (big_size > object_size)
3454 outs() << " (past end of file)\n";
3457 outs() << " export_off " << dc.export_off;
3458 if (dc.export_off > object_size)
3459 outs() << " (past end of file)\n";
3462 outs() << " export_size " << dc.export_size;
3463 big_size = dc.export_off;
3464 big_size += dc.export_size;
3465 if (big_size > object_size)
3466 outs() << " (past end of file)\n";
3471 static void PrintDyldLoadCommand(MachO::dylinker_command dyld,
3473 if (dyld.cmd == MachO::LC_ID_DYLINKER)
3474 outs() << " cmd LC_ID_DYLINKER\n";
3475 else if (dyld.cmd == MachO::LC_LOAD_DYLINKER)
3476 outs() << " cmd LC_LOAD_DYLINKER\n";
3477 else if (dyld.cmd == MachO::LC_DYLD_ENVIRONMENT)
3478 outs() << " cmd LC_DYLD_ENVIRONMENT\n";
3480 outs() << " cmd ?(" << dyld.cmd << ")\n";
3481 outs() << " cmdsize " << dyld.cmdsize;
3482 if (dyld.cmdsize < sizeof(struct MachO::dylinker_command))
3483 outs() << " Incorrect size\n";
3486 if (dyld.name >= dyld.cmdsize)
3487 outs() << " name ?(bad offset " << dyld.name << ")\n";
3489 const char *P = (const char *)(Ptr) + dyld.name;
3490 outs() << " name " << P << " (offset " << dyld.name << ")\n";
3494 static void PrintUuidLoadCommand(MachO::uuid_command uuid) {
3495 outs() << " cmd LC_UUID\n";
3496 outs() << " cmdsize " << uuid.cmdsize;
3497 if (uuid.cmdsize != sizeof(struct MachO::uuid_command))
3498 outs() << " Incorrect size\n";
3502 outs() << format("%02" PRIX32, uuid.uuid[0]);
3503 outs() << format("%02" PRIX32, uuid.uuid[1]);
3504 outs() << format("%02" PRIX32, uuid.uuid[2]);
3505 outs() << format("%02" PRIX32, uuid.uuid[3]);
3507 outs() << format("%02" PRIX32, uuid.uuid[4]);
3508 outs() << format("%02" PRIX32, uuid.uuid[5]);
3510 outs() << format("%02" PRIX32, uuid.uuid[6]);
3511 outs() << format("%02" PRIX32, uuid.uuid[7]);
3513 outs() << format("%02" PRIX32, uuid.uuid[8]);
3514 outs() << format("%02" PRIX32, uuid.uuid[9]);
3516 outs() << format("%02" PRIX32, uuid.uuid[10]);
3517 outs() << format("%02" PRIX32, uuid.uuid[11]);
3518 outs() << format("%02" PRIX32, uuid.uuid[12]);
3519 outs() << format("%02" PRIX32, uuid.uuid[13]);
3520 outs() << format("%02" PRIX32, uuid.uuid[14]);
3521 outs() << format("%02" PRIX32, uuid.uuid[15]);
3525 static void PrintVersionMinLoadCommand(MachO::version_min_command vd) {
3526 if (vd.cmd == MachO::LC_VERSION_MIN_MACOSX)
3527 outs() << " cmd LC_VERSION_MIN_MACOSX\n";
3528 else if (vd.cmd == MachO::LC_VERSION_MIN_IPHONEOS)
3529 outs() << " cmd LC_VERSION_MIN_IPHONEOS\n";
3531 outs() << " cmd " << vd.cmd << " (?)\n";
3532 outs() << " cmdsize " << vd.cmdsize;
3533 if (vd.cmdsize != sizeof(struct MachO::version_min_command))
3534 outs() << " Incorrect size\n";
3537 outs() << " version " << ((vd.version >> 16) & 0xffff) << "."
3538 << ((vd.version >> 8) & 0xff);
3539 if ((vd.version & 0xff) != 0)
3540 outs() << "." << (vd.version & 0xff);
3543 outs() << " sdk n/a\n";
3545 outs() << " sdk " << ((vd.sdk >> 16) & 0xffff) << "."
3546 << ((vd.sdk >> 8) & 0xff);
3548 if ((vd.sdk & 0xff) != 0)
3549 outs() << "." << (vd.sdk & 0xff);
3553 static void PrintSourceVersionCommand(MachO::source_version_command sd) {
3554 outs() << " cmd LC_SOURCE_VERSION\n";
3555 outs() << " cmdsize " << sd.cmdsize;
3556 if (sd.cmdsize != sizeof(struct MachO::source_version_command))
3557 outs() << " Incorrect size\n";
3560 uint64_t a = (sd.version >> 40) & 0xffffff;
3561 uint64_t b = (sd.version >> 30) & 0x3ff;
3562 uint64_t c = (sd.version >> 20) & 0x3ff;
3563 uint64_t d = (sd.version >> 10) & 0x3ff;
3564 uint64_t e = sd.version & 0x3ff;
3565 outs() << " version " << a << "." << b;
3567 outs() << "." << c << "." << d << "." << e;
3569 outs() << "." << c << "." << d;
3575 static void PrintEntryPointCommand(MachO::entry_point_command ep) {
3576 outs() << " cmd LC_MAIN\n";
3577 outs() << " cmdsize " << ep.cmdsize;
3578 if (ep.cmdsize != sizeof(struct MachO::entry_point_command))
3579 outs() << " Incorrect size\n";
3582 outs() << " entryoff " << ep.entryoff << "\n";
3583 outs() << " stacksize " << ep.stacksize << "\n";
3586 static void PrintDylibCommand(MachO::dylib_command dl, const char *Ptr) {
3587 if (dl.cmd == MachO::LC_ID_DYLIB)
3588 outs() << " cmd LC_ID_DYLIB\n";
3589 else if (dl.cmd == MachO::LC_LOAD_DYLIB)
3590 outs() << " cmd LC_LOAD_DYLIB\n";
3591 else if (dl.cmd == MachO::LC_LOAD_WEAK_DYLIB)
3592 outs() << " cmd LC_LOAD_WEAK_DYLIB\n";
3593 else if (dl.cmd == MachO::LC_REEXPORT_DYLIB)
3594 outs() << " cmd LC_REEXPORT_DYLIB\n";
3595 else if (dl.cmd == MachO::LC_LAZY_LOAD_DYLIB)
3596 outs() << " cmd LC_LAZY_LOAD_DYLIB\n";
3597 else if (dl.cmd == MachO::LC_LOAD_UPWARD_DYLIB)
3598 outs() << " cmd LC_LOAD_UPWARD_DYLIB\n";
3600 outs() << " cmd " << dl.cmd << " (unknown)\n";
3601 outs() << " cmdsize " << dl.cmdsize;
3602 if (dl.cmdsize < sizeof(struct MachO::dylib_command))
3603 outs() << " Incorrect size\n";
3606 if (dl.dylib.name < dl.cmdsize) {
3607 const char *P = (const char *)(Ptr) + dl.dylib.name;
3608 outs() << " name " << P << " (offset " << dl.dylib.name << ")\n";
3610 outs() << " name ?(bad offset " << dl.dylib.name << ")\n";
3612 outs() << " time stamp " << dl.dylib.timestamp << " ";
3613 time_t t = dl.dylib.timestamp;
3614 outs() << ctime(&t);
3615 outs() << " current version ";
3616 if (dl.dylib.current_version == 0xffffffff)
3619 outs() << ((dl.dylib.current_version >> 16) & 0xffff) << "."
3620 << ((dl.dylib.current_version >> 8) & 0xff) << "."
3621 << (dl.dylib.current_version & 0xff) << "\n";
3622 outs() << "compatibility version ";
3623 if (dl.dylib.compatibility_version == 0xffffffff)
3626 outs() << ((dl.dylib.compatibility_version >> 16) & 0xffff) << "."
3627 << ((dl.dylib.compatibility_version >> 8) & 0xff) << "."
3628 << (dl.dylib.compatibility_version & 0xff) << "\n";
3631 static void PrintLinkEditDataCommand(MachO::linkedit_data_command ld,
3632 uint32_t object_size) {
3633 if (ld.cmd == MachO::LC_CODE_SIGNATURE)
3634 outs() << " cmd LC_FUNCTION_STARTS\n";
3635 else if (ld.cmd == MachO::LC_SEGMENT_SPLIT_INFO)
3636 outs() << " cmd LC_SEGMENT_SPLIT_INFO\n";
3637 else if (ld.cmd == MachO::LC_FUNCTION_STARTS)
3638 outs() << " cmd LC_FUNCTION_STARTS\n";
3639 else if (ld.cmd == MachO::LC_DATA_IN_CODE)
3640 outs() << " cmd LC_DATA_IN_CODE\n";
3641 else if (ld.cmd == MachO::LC_DYLIB_CODE_SIGN_DRS)
3642 outs() << " cmd LC_DYLIB_CODE_SIGN_DRS\n";
3643 else if (ld.cmd == MachO::LC_LINKER_OPTIMIZATION_HINT)
3644 outs() << " cmd LC_LINKER_OPTIMIZATION_HINT\n";
3646 outs() << " cmd " << ld.cmd << " (?)\n";
3647 outs() << " cmdsize " << ld.cmdsize;
3648 if (ld.cmdsize != sizeof(struct MachO::linkedit_data_command))
3649 outs() << " Incorrect size\n";
3652 outs() << " dataoff " << ld.dataoff;
3653 if (ld.dataoff > object_size)
3654 outs() << " (past end of file)\n";
3657 outs() << " datasize " << ld.datasize;
3658 uint64_t big_size = ld.dataoff;
3659 big_size += ld.datasize;
3660 if (big_size > object_size)
3661 outs() << " (past end of file)\n";
3666 static void PrintLoadCommands(const MachOObjectFile *Obj, uint32_t ncmds,
3667 uint32_t filetype, uint32_t cputype,
3669 StringRef Buf = Obj->getData();
3670 MachOObjectFile::LoadCommandInfo Command = Obj->getFirstLoadCommandInfo();
3671 for (unsigned i = 0;; ++i) {
3672 outs() << "Load command " << i << "\n";
3673 if (Command.C.cmd == MachO::LC_SEGMENT) {
3674 MachO::segment_command SLC = Obj->getSegmentLoadCommand(Command);
3675 const char *sg_segname = SLC.segname;
3676 PrintSegmentCommand(SLC.cmd, SLC.cmdsize, SLC.segname, SLC.vmaddr,
3677 SLC.vmsize, SLC.fileoff, SLC.filesize, SLC.maxprot,
3678 SLC.initprot, SLC.nsects, SLC.flags, Buf.size(),
3680 for (unsigned j = 0; j < SLC.nsects; j++) {
3681 MachO::section_64 S = Obj->getSection64(Command, j);
3682 PrintSection(S.sectname, S.segname, S.addr, S.size, S.offset, S.align,
3683 S.reloff, S.nreloc, S.flags, S.reserved1, S.reserved2,
3684 SLC.cmd, sg_segname, filetype, Buf.size(), verbose);
3686 } else if (Command.C.cmd == MachO::LC_SEGMENT_64) {
3687 MachO::segment_command_64 SLC_64 = Obj->getSegment64LoadCommand(Command);
3688 const char *sg_segname = SLC_64.segname;
3689 PrintSegmentCommand(SLC_64.cmd, SLC_64.cmdsize, SLC_64.segname,
3690 SLC_64.vmaddr, SLC_64.vmsize, SLC_64.fileoff,
3691 SLC_64.filesize, SLC_64.maxprot, SLC_64.initprot,
3692 SLC_64.nsects, SLC_64.flags, Buf.size(), verbose);
3693 for (unsigned j = 0; j < SLC_64.nsects; j++) {
3694 MachO::section_64 S_64 = Obj->getSection64(Command, j);
3695 PrintSection(S_64.sectname, S_64.segname, S_64.addr, S_64.size,
3696 S_64.offset, S_64.align, S_64.reloff, S_64.nreloc,
3697 S_64.flags, S_64.reserved1, S_64.reserved2, SLC_64.cmd,
3698 sg_segname, filetype, Buf.size(), verbose);
3700 } else if (Command.C.cmd == MachO::LC_SYMTAB) {
3701 MachO::symtab_command Symtab = Obj->getSymtabLoadCommand();
3702 PrintSymtabLoadCommand(Symtab, Obj->is64Bit(), Buf.size());
3703 } else if (Command.C.cmd == MachO::LC_DYSYMTAB) {
3704 MachO::dysymtab_command Dysymtab = Obj->getDysymtabLoadCommand();
3705 MachO::symtab_command Symtab = Obj->getSymtabLoadCommand();
3706 PrintDysymtabLoadCommand(Dysymtab, Symtab.nsyms, Buf.size(),
3708 } else if (Command.C.cmd == MachO::LC_DYLD_INFO ||
3709 Command.C.cmd == MachO::LC_DYLD_INFO_ONLY) {
3710 MachO::dyld_info_command DyldInfo = Obj->getDyldInfoLoadCommand(Command);
3711 PrintDyldInfoLoadCommand(DyldInfo, Buf.size());
3712 } else if (Command.C.cmd == MachO::LC_LOAD_DYLINKER ||
3713 Command.C.cmd == MachO::LC_ID_DYLINKER ||
3714 Command.C.cmd == MachO::LC_DYLD_ENVIRONMENT) {
3715 MachO::dylinker_command Dyld = Obj->getDylinkerCommand(Command);
3716 PrintDyldLoadCommand(Dyld, Command.Ptr);
3717 } else if (Command.C.cmd == MachO::LC_UUID) {
3718 MachO::uuid_command Uuid = Obj->getUuidCommand(Command);
3719 PrintUuidLoadCommand(Uuid);
3720 } else if (Command.C.cmd == MachO::LC_VERSION_MIN_MACOSX) {
3721 MachO::version_min_command Vd = Obj->getVersionMinLoadCommand(Command);
3722 PrintVersionMinLoadCommand(Vd);
3723 } else if (Command.C.cmd == MachO::LC_SOURCE_VERSION) {
3724 MachO::source_version_command Sd = Obj->getSourceVersionCommand(Command);
3725 PrintSourceVersionCommand(Sd);
3726 } else if (Command.C.cmd == MachO::LC_MAIN) {
3727 MachO::entry_point_command Ep = Obj->getEntryPointCommand(Command);
3728 PrintEntryPointCommand(Ep);
3729 } else if (Command.C.cmd == MachO::LC_LOAD_DYLIB ||
3730 Command.C.cmd == MachO::LC_ID_DYLIB ||
3731 Command.C.cmd == MachO::LC_LOAD_WEAK_DYLIB ||
3732 Command.C.cmd == MachO::LC_REEXPORT_DYLIB ||
3733 Command.C.cmd == MachO::LC_LAZY_LOAD_DYLIB ||
3734 Command.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB) {
3735 MachO::dylib_command Dl = Obj->getDylibIDLoadCommand(Command);
3736 PrintDylibCommand(Dl, Command.Ptr);
3737 } else if (Command.C.cmd == MachO::LC_CODE_SIGNATURE ||
3738 Command.C.cmd == MachO::LC_SEGMENT_SPLIT_INFO ||
3739 Command.C.cmd == MachO::LC_FUNCTION_STARTS ||
3740 Command.C.cmd == MachO::LC_DATA_IN_CODE ||
3741 Command.C.cmd == MachO::LC_DYLIB_CODE_SIGN_DRS ||
3742 Command.C.cmd == MachO::LC_LINKER_OPTIMIZATION_HINT) {
3743 MachO::linkedit_data_command Ld =
3744 Obj->getLinkeditDataLoadCommand(Command);
3745 PrintLinkEditDataCommand(Ld, Buf.size());
3747 outs() << " cmd ?(" << format("0x%08" PRIx32, Command.C.cmd)
3749 outs() << " cmdsize " << Command.C.cmdsize << "\n";
3750 // TODO: get and print the raw bytes of the load command.
3752 // TODO: print all the other kinds of load commands.
3756 Command = Obj->getNextLoadCommandInfo(Command);
3760 static void getAndPrintMachHeader(const MachOObjectFile *Obj, uint32_t &ncmds,
3761 uint32_t &filetype, uint32_t &cputype,
3763 if (Obj->is64Bit()) {
3764 MachO::mach_header_64 H_64;
3765 H_64 = Obj->getHeader64();
3766 PrintMachHeader(H_64.magic, H_64.cputype, H_64.cpusubtype, H_64.filetype,
3767 H_64.ncmds, H_64.sizeofcmds, H_64.flags, verbose);
3769 filetype = H_64.filetype;
3770 cputype = H_64.cputype;
3772 MachO::mach_header H;
3773 H = Obj->getHeader();
3774 PrintMachHeader(H.magic, H.cputype, H.cpusubtype, H.filetype, H.ncmds,
3775 H.sizeofcmds, H.flags, verbose);
3777 filetype = H.filetype;
3778 cputype = H.cputype;
3782 void llvm::printMachOFileHeader(const object::ObjectFile *Obj) {
3783 const MachOObjectFile *file = dyn_cast<const MachOObjectFile>(Obj);
3785 uint32_t filetype = 0;
3786 uint32_t cputype = 0;
3787 getAndPrintMachHeader(file, ncmds, filetype, cputype, true);
3788 PrintLoadCommands(file, ncmds, filetype, cputype, true);
3791 //===----------------------------------------------------------------------===//
3792 // export trie dumping
3793 //===----------------------------------------------------------------------===//
3795 void llvm::printMachOExportsTrie(const object::MachOObjectFile *Obj) {
3796 for (const llvm::object::ExportEntry &Entry : Obj->exports()) {
3797 uint64_t Flags = Entry.flags();
3798 bool ReExport = (Flags & MachO::EXPORT_SYMBOL_FLAGS_REEXPORT);
3799 bool WeakDef = (Flags & MachO::EXPORT_SYMBOL_FLAGS_WEAK_DEFINITION);
3800 bool ThreadLocal = ((Flags & MachO::EXPORT_SYMBOL_FLAGS_KIND_MASK) ==
3801 MachO::EXPORT_SYMBOL_FLAGS_KIND_THREAD_LOCAL);
3802 bool Abs = ((Flags & MachO::EXPORT_SYMBOL_FLAGS_KIND_MASK) ==
3803 MachO::EXPORT_SYMBOL_FLAGS_KIND_ABSOLUTE);
3804 bool Resolver = (Flags & MachO::EXPORT_SYMBOL_FLAGS_STUB_AND_RESOLVER);
3806 outs() << "[re-export] ";
3808 outs() << format("0x%08llX ",
3809 Entry.address()); // FIXME:add in base address
3810 outs() << Entry.name();
3811 if (WeakDef || ThreadLocal || Resolver || Abs) {
3812 bool NeedsComma = false;
3815 outs() << "weak_def";
3821 outs() << "per-thread";
3827 outs() << "absolute";
3833 outs() << format("resolver=0x%08llX", Entry.other());
3839 StringRef DylibName = "unknown";
3840 int Ordinal = Entry.other() - 1;
3841 Obj->getLibraryShortNameByIndex(Ordinal, DylibName);
3842 if (Entry.otherName().empty())
3843 outs() << " (from " << DylibName << ")";
3845 outs() << " (" << Entry.otherName() << " from " << DylibName << ")";
3851 //===----------------------------------------------------------------------===//
3852 // rebase table dumping
3853 //===----------------------------------------------------------------------===//
3858 SegInfo(const object::MachOObjectFile *Obj);
3860 StringRef segmentName(uint32_t SegIndex);
3861 StringRef sectionName(uint32_t SegIndex, uint64_t SegOffset);
3862 uint64_t address(uint32_t SegIndex, uint64_t SegOffset);
3865 struct SectionInfo {
3868 StringRef SectionName;
3869 StringRef SegmentName;
3870 uint64_t OffsetInSegment;
3871 uint64_t SegmentStartAddress;
3872 uint32_t SegmentIndex;
3874 const SectionInfo &findSection(uint32_t SegIndex, uint64_t SegOffset);
3875 SmallVector<SectionInfo, 32> Sections;
3879 SegInfo::SegInfo(const object::MachOObjectFile *Obj) {
3880 // Build table of sections so segIndex/offset pairs can be translated.
3881 uint32_t CurSegIndex = Obj->hasPageZeroSegment() ? 1 : 0;
3882 StringRef CurSegName;
3883 uint64_t CurSegAddress;
3884 for (const SectionRef &Section : Obj->sections()) {
3886 if (error(Section.getName(Info.SectionName)))
3888 Info.Address = Section.getAddress();
3889 Info.Size = Section.getSize();
3891 Obj->getSectionFinalSegmentName(Section.getRawDataRefImpl());
3892 if (!Info.SegmentName.equals(CurSegName)) {
3894 CurSegName = Info.SegmentName;
3895 CurSegAddress = Info.Address;
3897 Info.SegmentIndex = CurSegIndex - 1;
3898 Info.OffsetInSegment = Info.Address - CurSegAddress;
3899 Info.SegmentStartAddress = CurSegAddress;
3900 Sections.push_back(Info);
3904 StringRef SegInfo::segmentName(uint32_t SegIndex) {
3905 for (const SectionInfo &SI : Sections) {
3906 if (SI.SegmentIndex == SegIndex)
3907 return SI.SegmentName;
3909 llvm_unreachable("invalid segIndex");
3912 const SegInfo::SectionInfo &SegInfo::findSection(uint32_t SegIndex,
3913 uint64_t OffsetInSeg) {
3914 for (const SectionInfo &SI : Sections) {
3915 if (SI.SegmentIndex != SegIndex)
3917 if (SI.OffsetInSegment > OffsetInSeg)
3919 if (OffsetInSeg >= (SI.OffsetInSegment + SI.Size))
3923 llvm_unreachable("segIndex and offset not in any section");
3926 StringRef SegInfo::sectionName(uint32_t SegIndex, uint64_t OffsetInSeg) {
3927 return findSection(SegIndex, OffsetInSeg).SectionName;
3930 uint64_t SegInfo::address(uint32_t SegIndex, uint64_t OffsetInSeg) {
3931 const SectionInfo &SI = findSection(SegIndex, OffsetInSeg);
3932 return SI.SegmentStartAddress + OffsetInSeg;
3935 void llvm::printMachORebaseTable(const object::MachOObjectFile *Obj) {
3936 // Build table of sections so names can used in final output.
3937 SegInfo sectionTable(Obj);
3939 outs() << "segment section address type\n";
3940 for (const llvm::object::MachORebaseEntry &Entry : Obj->rebaseTable()) {
3941 uint32_t SegIndex = Entry.segmentIndex();
3942 uint64_t OffsetInSeg = Entry.segmentOffset();
3943 StringRef SegmentName = sectionTable.segmentName(SegIndex);
3944 StringRef SectionName = sectionTable.sectionName(SegIndex, OffsetInSeg);
3945 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
3947 // Table lines look like: __DATA __nl_symbol_ptr 0x0000F00C pointer
3948 outs() << format("%-8s %-18s 0x%08" PRIX64 " %s\n",
3949 SegmentName.str().c_str(), SectionName.str().c_str(),
3950 Address, Entry.typeName().str().c_str());
3954 static StringRef ordinalName(const object::MachOObjectFile *Obj, int Ordinal) {
3955 StringRef DylibName;
3957 case MachO::BIND_SPECIAL_DYLIB_SELF:
3958 return "this-image";
3959 case MachO::BIND_SPECIAL_DYLIB_MAIN_EXECUTABLE:
3960 return "main-executable";
3961 case MachO::BIND_SPECIAL_DYLIB_FLAT_LOOKUP:
3962 return "flat-namespace";
3965 std::error_code EC =
3966 Obj->getLibraryShortNameByIndex(Ordinal - 1, DylibName);
3968 return "<<bad library ordinal>>";
3972 return "<<unknown special ordinal>>";
3975 //===----------------------------------------------------------------------===//
3976 // bind table dumping
3977 //===----------------------------------------------------------------------===//
3979 void llvm::printMachOBindTable(const object::MachOObjectFile *Obj) {
3980 // Build table of sections so names can used in final output.
3981 SegInfo sectionTable(Obj);
3983 outs() << "segment section address type "
3984 "addend dylib symbol\n";
3985 for (const llvm::object::MachOBindEntry &Entry : Obj->bindTable()) {
3986 uint32_t SegIndex = Entry.segmentIndex();
3987 uint64_t OffsetInSeg = Entry.segmentOffset();
3988 StringRef SegmentName = sectionTable.segmentName(SegIndex);
3989 StringRef SectionName = sectionTable.sectionName(SegIndex, OffsetInSeg);
3990 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
3992 // Table lines look like:
3993 // __DATA __got 0x00012010 pointer 0 libSystem ___stack_chk_guard
3995 if (Entry.flags() & MachO::BIND_SYMBOL_FLAGS_WEAK_IMPORT)
3996 Attr = " (weak_import)";
3997 outs() << left_justify(SegmentName, 8) << " "
3998 << left_justify(SectionName, 18) << " "
3999 << format_hex(Address, 10, true) << " "
4000 << left_justify(Entry.typeName(), 8) << " "
4001 << format_decimal(Entry.addend(), 8) << " "
4002 << left_justify(ordinalName(Obj, Entry.ordinal()), 16) << " "
4003 << Entry.symbolName() << Attr << "\n";
4007 //===----------------------------------------------------------------------===//
4008 // lazy bind table dumping
4009 //===----------------------------------------------------------------------===//
4011 void llvm::printMachOLazyBindTable(const object::MachOObjectFile *Obj) {
4012 // Build table of sections so names can used in final output.
4013 SegInfo sectionTable(Obj);
4015 outs() << "segment section address "
4017 for (const llvm::object::MachOBindEntry &Entry : Obj->lazyBindTable()) {
4018 uint32_t SegIndex = Entry.segmentIndex();
4019 uint64_t OffsetInSeg = Entry.segmentOffset();
4020 StringRef SegmentName = sectionTable.segmentName(SegIndex);
4021 StringRef SectionName = sectionTable.sectionName(SegIndex, OffsetInSeg);
4022 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
4024 // Table lines look like:
4025 // __DATA __got 0x00012010 libSystem ___stack_chk_guard
4026 outs() << left_justify(SegmentName, 8) << " "
4027 << left_justify(SectionName, 18) << " "
4028 << format_hex(Address, 10, true) << " "
4029 << left_justify(ordinalName(Obj, Entry.ordinal()), 16) << " "
4030 << Entry.symbolName() << "\n";
4034 //===----------------------------------------------------------------------===//
4035 // weak bind table dumping
4036 //===----------------------------------------------------------------------===//
4038 void llvm::printMachOWeakBindTable(const object::MachOObjectFile *Obj) {
4039 // Build table of sections so names can used in final output.
4040 SegInfo sectionTable(Obj);
4042 outs() << "segment section address "
4043 "type addend symbol\n";
4044 for (const llvm::object::MachOBindEntry &Entry : Obj->weakBindTable()) {
4045 // Strong symbols don't have a location to update.
4046 if (Entry.flags() & MachO::BIND_SYMBOL_FLAGS_NON_WEAK_DEFINITION) {
4047 outs() << " strong "
4048 << Entry.symbolName() << "\n";
4051 uint32_t SegIndex = Entry.segmentIndex();
4052 uint64_t OffsetInSeg = Entry.segmentOffset();
4053 StringRef SegmentName = sectionTable.segmentName(SegIndex);
4054 StringRef SectionName = sectionTable.sectionName(SegIndex, OffsetInSeg);
4055 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
4057 // Table lines look like:
4058 // __DATA __data 0x00001000 pointer 0 _foo
4059 outs() << left_justify(SegmentName, 8) << " "
4060 << left_justify(SectionName, 18) << " "
4061 << format_hex(Address, 10, true) << " "
4062 << left_justify(Entry.typeName(), 8) << " "
4063 << format_decimal(Entry.addend(), 8) << " " << Entry.symbolName()
4068 // get_dyld_bind_info_symbolname() is used for disassembly and passed an
4069 // address, ReferenceValue, in the Mach-O file and looks in the dyld bind
4070 // information for that address. If the address is found its binding symbol
4071 // name is returned. If not nullptr is returned.
4072 static const char *get_dyld_bind_info_symbolname(uint64_t ReferenceValue,
4073 struct DisassembleInfo *info) {
4074 if (info->bindtable == nullptr) {
4075 info->bindtable = new (BindTable);
4076 SegInfo sectionTable(info->O);
4077 for (const llvm::object::MachOBindEntry &Entry : info->O->bindTable()) {
4078 uint32_t SegIndex = Entry.segmentIndex();
4079 uint64_t OffsetInSeg = Entry.segmentOffset();
4080 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
4081 const char *SymbolName = nullptr;
4082 StringRef name = Entry.symbolName();
4084 SymbolName = name.data();
4085 info->bindtable->push_back(std::make_pair(Address, SymbolName));
4088 for (bind_table_iterator BI = info->bindtable->begin(),
4089 BE = info->bindtable->end();
4091 uint64_t Address = BI->first;
4092 if (ReferenceValue == Address) {
4093 const char *SymbolName = BI->second;