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/MCInstrAnalysis.h"
27 #include "llvm/MC/MCInstrDesc.h"
28 #include "llvm/MC/MCInstrInfo.h"
29 #include "llvm/MC/MCRegisterInfo.h"
30 #include "llvm/MC/MCSubtargetInfo.h"
31 #include "llvm/Object/MachO.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;
56 UseDbg("g", cl::desc("Print line information from debug info if available"));
58 static cl::opt<std::string>
59 DSYMFile("dsym", cl::desc("Use .dSYM file for debug info"));
62 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 std::string ThumbTripleName;
71 static const Target *GetTarget(const MachOObjectFile *MachOObj,
72 const char **McpuDefault,
73 const Target **ThumbTarget) {
74 // Figure out the target triple.
75 if (TripleName.empty()) {
76 llvm::Triple TT("unknown-unknown-unknown");
77 llvm::Triple ThumbTriple = Triple();
78 TT = MachOObj->getArch(McpuDefault, &ThumbTriple);
79 TripleName = TT.str();
80 ThumbTripleName = ThumbTriple.str();
83 // Get the target specific parser.
85 const Target *TheTarget = TargetRegistry::lookupTarget(TripleName, Error);
86 if (TheTarget && ThumbTripleName.empty())
89 *ThumbTarget = TargetRegistry::lookupTarget(ThumbTripleName, Error);
93 errs() << "llvm-objdump: error: unable to get target for '";
97 errs() << ThumbTripleName;
98 errs() << "', see --version and --triple.\n";
102 struct SymbolSorter {
103 bool operator()(const SymbolRef &A, const SymbolRef &B) {
104 SymbolRef::Type AType, BType;
108 uint64_t AAddr, BAddr;
109 if (AType != SymbolRef::ST_Function)
113 if (BType != SymbolRef::ST_Function)
117 return AAddr < BAddr;
121 // Types for the storted data in code table that is built before disassembly
122 // and the predicate function to sort them.
123 typedef std::pair<uint64_t, DiceRef> DiceTableEntry;
124 typedef std::vector<DiceTableEntry> DiceTable;
125 typedef DiceTable::iterator dice_table_iterator;
128 compareDiceTableEntries(const DiceTableEntry i,
129 const DiceTableEntry j) {
130 return i.first == j.first;
133 static void DumpDataInCode(const char *bytes, uint64_t Size,
134 unsigned short Kind) {
138 case MachO::DICE_KIND_DATA:
141 Value = bytes[3] << 24 |
145 outs() << "\t.long " << Value;
148 Value = bytes[1] << 8 |
150 outs() << "\t.short " << Value;
154 outs() << "\t.byte " << Value;
157 outs() << "\t@ KIND_DATA\n";
159 case MachO::DICE_KIND_JUMP_TABLE8:
161 outs() << "\t.byte " << Value << "\t@ KIND_JUMP_TABLE8";
163 case MachO::DICE_KIND_JUMP_TABLE16:
164 Value = bytes[1] << 8 |
166 outs() << "\t.short " << Value << "\t@ KIND_JUMP_TABLE16";
168 case MachO::DICE_KIND_JUMP_TABLE32:
169 Value = bytes[3] << 24 |
173 outs() << "\t.long " << Value << "\t@ KIND_JUMP_TABLE32";
176 outs() << "\t@ data in code kind = " << Kind << "\n";
181 static void getSectionsAndSymbols(const MachO::mach_header Header,
182 MachOObjectFile *MachOObj,
183 std::vector<SectionRef> &Sections,
184 std::vector<SymbolRef> &Symbols,
185 SmallVectorImpl<uint64_t> &FoundFns,
186 uint64_t &BaseSegmentAddress) {
187 for (const SymbolRef &Symbol : MachOObj->symbols())
188 Symbols.push_back(Symbol);
190 for (const SectionRef &Section : MachOObj->sections()) {
192 Section.getName(SectName);
193 Sections.push_back(Section);
196 MachOObjectFile::LoadCommandInfo Command =
197 MachOObj->getFirstLoadCommandInfo();
198 bool BaseSegmentAddressSet = false;
199 for (unsigned i = 0; ; ++i) {
200 if (Command.C.cmd == MachO::LC_FUNCTION_STARTS) {
201 // We found a function starts segment, parse the addresses for later
203 MachO::linkedit_data_command LLC =
204 MachOObj->getLinkeditDataLoadCommand(Command);
206 MachOObj->ReadULEB128s(LLC.dataoff, FoundFns);
208 else if (Command.C.cmd == MachO::LC_SEGMENT) {
209 MachO::segment_command SLC =
210 MachOObj->getSegmentLoadCommand(Command);
211 StringRef SegName = SLC.segname;
212 if(!BaseSegmentAddressSet && SegName != "__PAGEZERO") {
213 BaseSegmentAddressSet = true;
214 BaseSegmentAddress = SLC.vmaddr;
218 if (i == Header.ncmds - 1)
221 Command = MachOObj->getNextLoadCommandInfo(Command);
225 static void DisassembleInputMachO2(StringRef Filename,
226 MachOObjectFile *MachOOF);
228 void llvm::DisassembleInputMachO(StringRef Filename) {
229 ErrorOr<std::unique_ptr<MemoryBuffer>> BuffOrErr =
230 MemoryBuffer::getFileOrSTDIN(Filename);
231 if (std::error_code EC = BuffOrErr.getError()) {
232 errs() << "llvm-objdump: " << Filename << ": " << EC.message() << "\n";
235 std::unique_ptr<MemoryBuffer> Buff = std::move(BuffOrErr.get());
237 std::unique_ptr<MachOObjectFile> MachOOF = std::move(
238 ObjectFile::createMachOObjectFile(Buff.get()->getMemBufferRef()).get());
240 DisassembleInputMachO2(Filename, MachOOF.get());
243 typedef DenseMap<uint64_t, StringRef> SymbolAddressMap;
244 typedef std::pair<uint64_t, const char *> BindInfoEntry;
245 typedef std::vector<BindInfoEntry> BindTable;
246 typedef BindTable::iterator bind_table_iterator;
248 // The block of info used by the Symbolizer call backs.
249 struct DisassembleInfo {
253 SymbolAddressMap *AddrMap;
254 std::vector<SectionRef> *Sections;
255 const char *class_name;
256 const char *selector_name;
258 char *demangled_name;
259 BindTable *bindtable;
262 // SymbolizerGetOpInfo() is the operand information call back function.
263 // This is called to get the symbolic information for operand(s) of an
264 // instruction when it is being done. This routine does this from
265 // the relocation information, symbol table, etc. That block of information
266 // is a pointer to the struct DisassembleInfo that was passed when the
267 // disassembler context was created and passed to back to here when
268 // called back by the disassembler for instruction operands that could have
269 // relocation information. The address of the instruction containing operand is
270 // at the Pc parameter. The immediate value the operand has is passed in
271 // op_info->Value and is at Offset past the start of the instruction and has a
272 // byte Size of 1, 2 or 4. The symbolc information is returned in TagBuf is the
273 // LLVMOpInfo1 struct defined in the header "llvm-c/Disassembler.h" as symbol
274 // names and addends of the symbolic expression to add for the operand. The
275 // value of TagType is currently 1 (for the LLVMOpInfo1 struct). If symbolic
276 // information is returned then this function returns 1 else it returns 0.
277 int SymbolizerGetOpInfo(void *DisInfo, uint64_t Pc, uint64_t Offset,
278 uint64_t Size, int TagType, void *TagBuf) {
279 struct DisassembleInfo *info = (struct DisassembleInfo *)DisInfo;
280 struct LLVMOpInfo1 *op_info = (struct LLVMOpInfo1 *)TagBuf;
281 unsigned int value = op_info->Value;
283 // Make sure all fields returned are zero if we don't set them.
284 memset((void *)op_info, '\0', sizeof(struct LLVMOpInfo1));
285 op_info->Value = value;
287 // If the TagType is not the value 1 which it code knows about or if no
288 // verbose symbolic information is wanted then just return 0, indicating no
289 // information is being returned.
290 if (TagType != 1 || info->verbose == false)
293 unsigned int Arch = info->O->getArch();
294 if (Arch == Triple::x86) {
296 } else if (Arch == Triple::x86_64) {
297 if (Size != 1 && Size != 2 && Size != 4 && Size != 0)
299 // First search the section's relocation entries (if any) for an entry
300 // for this section offset.
301 uint64_t sect_addr = info->S.getAddress();
302 uint64_t sect_offset = (Pc + Offset) - sect_addr;
303 bool reloc_found = false;
305 MachO::any_relocation_info RE;
306 bool isExtern = false;
308 for (const RelocationRef &Reloc : info->S.relocations()) {
309 uint64_t RelocOffset;
310 Reloc.getOffset(RelocOffset);
311 if (RelocOffset == sect_offset) {
312 Rel = Reloc.getRawDataRefImpl();
313 RE = info->O->getRelocation(Rel);
314 // NOTE: Scattered relocations don't exist on x86_64.
315 isExtern = info->O->getPlainRelocationExternal(RE);
317 symbol_iterator RelocSym = Reloc.getSymbol();
324 if (reloc_found && isExtern) {
325 // The Value passed in will be adjusted by the Pc if the instruction
326 // adds the Pc. But for x86_64 external relocation entries the Value
327 // is the offset from the external symbol.
328 if (info->O->getAnyRelocationPCRel(RE))
329 op_info->Value -= Pc + Offset + Size;
331 Symbol.getName(SymName);
332 const char *name = SymName.data();
333 unsigned Type = info->O->getAnyRelocationType(RE);
334 if (Type == MachO::X86_64_RELOC_SUBTRACTOR) {
335 DataRefImpl RelNext = Rel;
336 info->O->moveRelocationNext(RelNext);
337 MachO::any_relocation_info RENext = info->O->getRelocation(RelNext);
338 unsigned TypeNext = info->O->getAnyRelocationType(RENext);
339 bool isExternNext = info->O->getPlainRelocationExternal(RENext);
340 unsigned SymbolNum = info->O->getPlainRelocationSymbolNum(RENext);
341 if (TypeNext == MachO::X86_64_RELOC_UNSIGNED && isExternNext) {
342 op_info->SubtractSymbol.Present = 1;
343 op_info->SubtractSymbol.Name = name;
344 symbol_iterator RelocSymNext = info->O->getSymbolByIndex(SymbolNum);
345 Symbol = *RelocSymNext;
346 StringRef SymNameNext;
347 Symbol.getName(SymNameNext);
348 name = SymNameNext.data();
351 // TODO: add the VariantKinds to op_info->VariantKind for relocation types
352 // like: X86_64_RELOC_TLV, X86_64_RELOC_GOT_LOAD and X86_64_RELOC_GOT.
353 op_info->AddSymbol.Present = 1;
354 op_info->AddSymbol.Name = name;
358 // Second search the external relocation entries of a fully linked image
359 // (if any) for an entry that matches this segment offset.
360 // uint64_t seg_offset = (Pc + Offset);
362 } else if (Arch == Triple::arm) {
364 } else if (Arch == Triple::aarch64) {
371 // GuessCstringPointer is passed the address of what might be a pointer to a
372 // literal string in a cstring section. If that address is in a cstring section
373 // it returns a pointer to that string. Else it returns nullptr.
374 const char *GuessCstringPointer(uint64_t ReferenceValue,
375 struct DisassembleInfo *info) {
376 uint32_t LoadCommandCount = info->O->getHeader().ncmds;
377 MachOObjectFile::LoadCommandInfo Load = info->O->getFirstLoadCommandInfo();
378 for (unsigned I = 0;; ++I) {
379 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
380 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
381 for (unsigned J = 0; J < Seg.nsects; ++J) {
382 MachO::section_64 Sec = info->O->getSection64(Load, J);
383 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
384 if (section_type == MachO::S_CSTRING_LITERALS &&
385 ReferenceValue >= Sec.addr &&
386 ReferenceValue < Sec.addr + Sec.size) {
387 uint64_t sect_offset = ReferenceValue - Sec.addr;
388 uint64_t object_offset = Sec.offset + sect_offset;
389 StringRef MachOContents = info->O->getData();
390 uint64_t object_size = MachOContents.size();
391 const char *object_addr = (const char *)MachOContents.data();
392 if (object_offset < object_size) {
393 const char *name = object_addr + object_offset;
400 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
401 MachO::segment_command Seg = info->O->getSegmentLoadCommand(Load);
402 for (unsigned J = 0; J < Seg.nsects; ++J) {
403 MachO::section Sec = info->O->getSection(Load, J);
404 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
405 if (section_type == MachO::S_CSTRING_LITERALS &&
406 ReferenceValue >= Sec.addr &&
407 ReferenceValue < Sec.addr + Sec.size) {
408 uint64_t sect_offset = ReferenceValue - Sec.addr;
409 uint64_t object_offset = Sec.offset + sect_offset;
410 StringRef MachOContents = info->O->getData();
411 uint64_t object_size = MachOContents.size();
412 const char *object_addr = (const char *)MachOContents.data();
413 if (object_offset < object_size) {
414 const char *name = object_addr + object_offset;
422 if (I == LoadCommandCount - 1)
425 Load = info->O->getNextLoadCommandInfo(Load);
430 // GuessIndirectSymbol returns the name of the indirect symbol for the
431 // ReferenceValue passed in or nullptr. This is used when ReferenceValue maybe
432 // an address of a symbol stub or a lazy or non-lazy pointer to associate the
433 // symbol name being referenced by the stub or pointer.
434 static const char *GuessIndirectSymbol(uint64_t ReferenceValue,
435 struct DisassembleInfo *info) {
436 uint32_t LoadCommandCount = info->O->getHeader().ncmds;
437 MachOObjectFile::LoadCommandInfo Load = info->O->getFirstLoadCommandInfo();
438 MachO::dysymtab_command Dysymtab = info->O->getDysymtabLoadCommand();
439 MachO::symtab_command Symtab = info->O->getSymtabLoadCommand();
440 for (unsigned I = 0;; ++I) {
441 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
442 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
443 for (unsigned J = 0; J < Seg.nsects; ++J) {
444 MachO::section_64 Sec = info->O->getSection64(Load, J);
445 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
446 if ((section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
447 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
448 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
449 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
450 section_type == MachO::S_SYMBOL_STUBS) &&
451 ReferenceValue >= Sec.addr &&
452 ReferenceValue < Sec.addr + Sec.size) {
454 if (section_type == MachO::S_SYMBOL_STUBS)
455 stride = Sec.reserved2;
460 uint32_t index = Sec.reserved1 + (ReferenceValue - Sec.addr) / stride;
461 if (index < Dysymtab.nindirectsyms) {
462 uint32_t indirect_symbol =
463 info->O->getIndirectSymbolTableEntry(Dysymtab, index);
464 if (indirect_symbol < Symtab.nsyms) {
465 symbol_iterator Sym = info->O->getSymbolByIndex(indirect_symbol);
466 SymbolRef Symbol = *Sym;
468 Symbol.getName(SymName);
469 const char *name = SymName.data();
475 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
476 MachO::segment_command Seg = info->O->getSegmentLoadCommand(Load);
477 for (unsigned J = 0; J < Seg.nsects; ++J) {
478 MachO::section Sec = info->O->getSection(Load, J);
479 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
480 if ((section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
481 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
482 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
483 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
484 section_type == MachO::S_SYMBOL_STUBS) &&
485 ReferenceValue >= Sec.addr &&
486 ReferenceValue < Sec.addr + Sec.size) {
488 if (section_type == MachO::S_SYMBOL_STUBS)
489 stride = Sec.reserved2;
494 uint32_t index = Sec.reserved1 + (ReferenceValue - Sec.addr) / stride;
495 if (index < Dysymtab.nindirectsyms) {
496 uint32_t indirect_symbol =
497 info->O->getIndirectSymbolTableEntry(Dysymtab, index);
498 if (indirect_symbol < Symtab.nsyms) {
499 symbol_iterator Sym = info->O->getSymbolByIndex(indirect_symbol);
500 SymbolRef Symbol = *Sym;
502 Symbol.getName(SymName);
503 const char *name = SymName.data();
510 if (I == LoadCommandCount - 1)
513 Load = info->O->getNextLoadCommandInfo(Load);
518 // method_reference() is called passing it the ReferenceName that might be
519 // a reference it to an Objective-C method call. If so then it allocates and
520 // assembles a method call string with the values last seen and saved in
521 // the DisassembleInfo's class_name and selector_name fields. This is saved
522 // into the method field of the info and any previous string is free'ed.
523 // Then the class_name field in the info is set to nullptr. The method call
524 // string is set into ReferenceName and ReferenceType is set to
525 // LLVMDisassembler_ReferenceType_Out_Objc_Message. If this not a method call
526 // then both ReferenceType and ReferenceName are left unchanged.
527 static void method_reference(struct DisassembleInfo *info,
528 uint64_t *ReferenceType,
529 const char **ReferenceName) {
530 if (*ReferenceName != nullptr) {
531 if (strcmp(*ReferenceName, "_objc_msgSend") == 0) {
532 if (info->selector_name != NULL) {
533 if (info->method != nullptr)
535 if (info->class_name != nullptr) {
536 info->method = (char *)malloc(5 + strlen(info->class_name) +
537 strlen(info->selector_name));
538 if (info->method != nullptr) {
539 strcpy(info->method, "+[");
540 strcat(info->method, info->class_name);
541 strcat(info->method, " ");
542 strcat(info->method, info->selector_name);
543 strcat(info->method, "]");
544 *ReferenceName = info->method;
545 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
548 info->method = (char *)malloc(9 + strlen(info->selector_name));
549 if (info->method != nullptr) {
550 strcpy(info->method, "-[%rdi ");
551 strcat(info->method, info->selector_name);
552 strcat(info->method, "]");
553 *ReferenceName = info->method;
554 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
557 info->class_name = nullptr;
559 } else if (strcmp(*ReferenceName, "_objc_msgSendSuper2") == 0) {
560 if (info->selector_name != NULL) {
561 if (info->method != nullptr)
563 info->method = (char *)malloc(17 + strlen(info->selector_name));
564 if (info->method != nullptr) {
565 strcpy(info->method, "-[[%rdi super] ");
566 strcat(info->method, info->selector_name);
567 strcat(info->method, "]");
568 *ReferenceName = info->method;
569 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
571 info->class_name = nullptr;
577 // GuessPointerPointer() is passed the address of what might be a pointer to
578 // a reference to an Objective-C class, selector, message ref or cfstring.
579 // If so the value of the pointer is returned and one of the booleans are set
580 // to true. If not zero is returned and all the booleans are set to false.
581 static uint64_t GuessPointerPointer(uint64_t ReferenceValue,
582 struct DisassembleInfo *info,
583 bool &classref, bool &selref, bool &msgref,
589 uint32_t LoadCommandCount = info->O->getHeader().ncmds;
590 MachOObjectFile::LoadCommandInfo Load = info->O->getFirstLoadCommandInfo();
591 for (unsigned I = 0;; ++I) {
592 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
593 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
594 for (unsigned J = 0; J < Seg.nsects; ++J) {
595 MachO::section_64 Sec = info->O->getSection64(Load, J);
596 if ((strncmp(Sec.sectname, "__objc_selrefs", 16) == 0 ||
597 strncmp(Sec.sectname, "__objc_classrefs", 16) == 0 ||
598 strncmp(Sec.sectname, "__objc_superrefs", 16) == 0 ||
599 strncmp(Sec.sectname, "__objc_msgrefs", 16) == 0 ||
600 strncmp(Sec.sectname, "__cfstring", 16) == 0) &&
601 ReferenceValue >= Sec.addr &&
602 ReferenceValue < Sec.addr + Sec.size) {
603 uint64_t sect_offset = ReferenceValue - Sec.addr;
604 uint64_t object_offset = Sec.offset + sect_offset;
605 StringRef MachOContents = info->O->getData();
606 uint64_t object_size = MachOContents.size();
607 const char *object_addr = (const char *)MachOContents.data();
608 if (object_offset < object_size) {
609 uint64_t pointer_value;
610 memcpy(&pointer_value, object_addr + object_offset,
612 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
613 sys::swapByteOrder(pointer_value);
614 if (strncmp(Sec.sectname, "__objc_selrefs", 16) == 0)
616 else if (strncmp(Sec.sectname, "__objc_classrefs", 16) == 0 ||
617 strncmp(Sec.sectname, "__objc_superrefs", 16) == 0)
619 else if (strncmp(Sec.sectname, "__objc_msgrefs", 16) == 0 &&
620 ReferenceValue + 8 < Sec.addr + Sec.size) {
622 memcpy(&pointer_value, object_addr + object_offset + 8,
624 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
625 sys::swapByteOrder(pointer_value);
626 } else if (strncmp(Sec.sectname, "__cfstring", 16) == 0)
628 return pointer_value;
635 // TODO: Look for LC_SEGMENT for 32-bit Mach-O files.
636 if (I == LoadCommandCount - 1)
639 Load = info->O->getNextLoadCommandInfo(Load);
644 // get_pointer_64 returns a pointer to the bytes in the object file at the
645 // Address from a section in the Mach-O file. And indirectly returns the
646 // offset into the section, number of bytes left in the section past the offset
647 // and which section is was being referenced. If the Address is not in a
648 // section nullptr is returned.
649 const char *get_pointer_64(uint64_t Address, uint32_t &offset, uint32_t &left,
650 SectionRef &S, DisassembleInfo *info) {
654 for (unsigned SectIdx = 0; SectIdx != info->Sections->size(); SectIdx++) {
655 uint64_t SectAddress = ((*(info->Sections))[SectIdx]).getAddress();
656 uint64_t SectSize = ((*(info->Sections))[SectIdx]).getSize();
657 if (Address >= SectAddress && Address < SectAddress + SectSize) {
658 S = (*(info->Sections))[SectIdx];
659 offset = Address - SectAddress;
660 left = SectSize - offset;
661 StringRef SectContents;
662 ((*(info->Sections))[SectIdx]).getContents(SectContents);
663 return SectContents.data() + offset;
669 // get_symbol_64() returns the name of a symbol (or nullptr) and the address of
670 // the symbol indirectly through n_value. Based on the relocation information
671 // for the specified section offset in the specified section reference.
672 const char *get_symbol_64(uint32_t sect_offset, SectionRef S,
673 DisassembleInfo *info, uint64_t &n_value) {
675 if (info->verbose == false)
678 // See if there is an external relocation entry at the sect_offset.
679 bool reloc_found = false;
681 MachO::any_relocation_info RE;
682 bool isExtern = false;
684 for (const RelocationRef &Reloc : S.relocations()) {
685 uint64_t RelocOffset;
686 Reloc.getOffset(RelocOffset);
687 if (RelocOffset == sect_offset) {
688 Rel = Reloc.getRawDataRefImpl();
689 RE = info->O->getRelocation(Rel);
690 if (info->O->isRelocationScattered(RE))
692 isExtern = info->O->getPlainRelocationExternal(RE);
694 symbol_iterator RelocSym = Reloc.getSymbol();
701 // If there is an external relocation entry for a symbol in this section
702 // at this section_offset then use that symbol's value for the n_value
703 // and return its name.
704 const char *SymbolName = nullptr;
705 if (reloc_found && isExtern) {
706 Symbol.getAddress(n_value);
708 Symbol.getName(name);
710 SymbolName = name.data();
715 // TODO: For fully linked images, look through the external relocation
716 // entries off the dynamic symtab command. For these the r_offset is from the
717 // start of the first writeable segment in the Mach-O file. So the offset
718 // to this section from that segment is passed to this routine by the caller,
719 // as the database_offset. Which is the difference of the section's starting
720 // address and the first writable segment.
722 // NOTE: need add passing the database_offset to this routine.
724 // TODO: We did not find an external relocation entry so look up the
725 // ReferenceValue as an address of a symbol and if found return that symbol's
728 // NOTE: need add passing the ReferenceValue to this routine. Then that code
729 // would simply be this:
731 // if (ReferenceValue != 0xffffffffffffffffLLU &&
732 // ReferenceValue != 0xfffffffffffffffeLLU) {
733 // StringRef name = info->AddrMap->lookup(ReferenceValue);
734 // if (!name.empty())
735 // SymbolName = name.data();
741 // These are structs in the Objective-C meta data and read to produce the
742 // comments for disassembly. While these are part of the ABI they are no
743 // public defintions. So the are here not in include/llvm/Support/MachO.h .
745 // The cfstring object in a 64-bit Mach-O file.
746 struct cfstring64_t {
747 uint64_t isa; // class64_t * (64-bit pointer)
748 uint64_t flags; // flag bits
749 uint64_t characters; // char * (64-bit pointer)
750 uint64_t length; // number of non-NULL characters in above
753 // The class object in a 64-bit Mach-O file.
755 uint64_t isa; // class64_t * (64-bit pointer)
756 uint64_t superclass; // class64_t * (64-bit pointer)
757 uint64_t cache; // Cache (64-bit pointer)
758 uint64_t vtable; // IMP * (64-bit pointer)
759 uint64_t data; // class_ro64_t * (64-bit pointer)
762 struct class_ro64_t {
764 uint32_t instanceStart;
765 uint32_t instanceSize;
767 uint64_t ivarLayout; // const uint8_t * (64-bit pointer)
768 uint64_t name; // const char * (64-bit pointer)
769 uint64_t baseMethods; // const method_list_t * (64-bit pointer)
770 uint64_t baseProtocols; // const protocol_list_t * (64-bit pointer)
771 uint64_t ivars; // const ivar_list_t * (64-bit pointer)
772 uint64_t weakIvarLayout; // const uint8_t * (64-bit pointer)
773 uint64_t baseProperties; // const struct objc_property_list (64-bit pointer)
776 inline void swapStruct(struct cfstring64_t &cfs) {
777 sys::swapByteOrder(cfs.isa);
778 sys::swapByteOrder(cfs.flags);
779 sys::swapByteOrder(cfs.characters);
780 sys::swapByteOrder(cfs.length);
783 inline void swapStruct(struct class64_t &c) {
784 sys::swapByteOrder(c.isa);
785 sys::swapByteOrder(c.superclass);
786 sys::swapByteOrder(c.cache);
787 sys::swapByteOrder(c.vtable);
788 sys::swapByteOrder(c.data);
791 inline void swapStruct(struct class_ro64_t &cro) {
792 sys::swapByteOrder(cro.flags);
793 sys::swapByteOrder(cro.instanceStart);
794 sys::swapByteOrder(cro.instanceSize);
795 sys::swapByteOrder(cro.reserved);
796 sys::swapByteOrder(cro.ivarLayout);
797 sys::swapByteOrder(cro.name);
798 sys::swapByteOrder(cro.baseMethods);
799 sys::swapByteOrder(cro.baseProtocols);
800 sys::swapByteOrder(cro.ivars);
801 sys::swapByteOrder(cro.weakIvarLayout);
802 sys::swapByteOrder(cro.baseProperties);
805 static const char *get_dyld_bind_info_symbolname(uint64_t ReferenceValue,
806 struct DisassembleInfo *info);
808 // get_objc2_64bit_class_name() is used for disassembly and is passed a pointer
809 // to an Objective-C class and returns the class name. It is also passed the
810 // address of the pointer, so when the pointer is zero as it can be in an .o
811 // file, that is used to look for an external relocation entry with a symbol
813 const char *get_objc2_64bit_class_name(uint64_t pointer_value,
814 uint64_t ReferenceValue,
815 struct DisassembleInfo *info) {
817 uint32_t offset, left;
820 // The pointer_value can be 0 in an object file and have a relocation
821 // entry for the class symbol at the ReferenceValue (the address of the
823 if (pointer_value == 0) {
824 r = get_pointer_64(ReferenceValue, offset, left, S, info);
825 if (r == nullptr || left < sizeof(uint64_t))
828 const char *symbol_name = get_symbol_64(offset, S, info, n_value);
829 if (symbol_name == nullptr)
831 const char *class_name = strrchr(symbol_name, '$');
832 if (class_name != nullptr && class_name[1] == '_' && class_name[2] != '\0')
833 return class_name + 2;
838 // The case were the pointer_value is non-zero and points to a class defined
839 // in this Mach-O file.
840 r = get_pointer_64(pointer_value, offset, left, S, info);
841 if (r == nullptr || left < sizeof(struct class64_t))
844 memcpy(&c, r, sizeof(struct class64_t));
845 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
849 r = get_pointer_64(c.data, offset, left, S, info);
850 if (r == nullptr || left < sizeof(struct class_ro64_t))
852 struct class_ro64_t cro;
853 memcpy(&cro, r, sizeof(struct class_ro64_t));
854 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
858 const char *name = get_pointer_64(cro.name, offset, left, S, info);
862 // get_objc2_64bit_cfstring_name is used for disassembly and is passed a
863 // pointer to a cfstring and returns its name or nullptr.
864 const char *get_objc2_64bit_cfstring_name(uint64_t ReferenceValue,
865 struct DisassembleInfo *info) {
866 const char *r, *name;
867 uint32_t offset, left;
869 struct cfstring64_t cfs;
870 uint64_t cfs_characters;
872 r = get_pointer_64(ReferenceValue, offset, left, S, info);
873 if (r == nullptr || left < sizeof(struct cfstring64_t))
875 memcpy(&cfs, r, sizeof(struct cfstring64_t));
876 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
878 if (cfs.characters == 0) {
880 const char *symbol_name = get_symbol_64(
881 offset + offsetof(struct cfstring64_t, characters), S, info, n_value);
882 if (symbol_name == nullptr)
884 cfs_characters = n_value;
886 cfs_characters = cfs.characters;
887 name = get_pointer_64(cfs_characters, offset, left, S, info);
892 // get_objc2_64bit_selref() is used for disassembly and is passed a the address
893 // of a pointer to an Objective-C selector reference when the pointer value is
894 // zero as in a .o file and is likely to have a external relocation entry with
895 // who's symbol's n_value is the real pointer to the selector name. If that is
896 // the case the real pointer to the selector name is returned else 0 is
898 uint64_t get_objc2_64bit_selref(uint64_t ReferenceValue,
899 struct DisassembleInfo *info) {
900 uint32_t offset, left;
903 const char *r = get_pointer_64(ReferenceValue, offset, left, S, info);
904 if (r == nullptr || left < sizeof(uint64_t))
907 const char *symbol_name = get_symbol_64(offset, S, info, n_value);
908 if (symbol_name == nullptr)
913 // GuessLiteralPointer returns a string which for the item in the Mach-O file
914 // for the address passed in as ReferenceValue for printing as a comment with
915 // the instruction and also returns the corresponding type of that item
916 // indirectly through ReferenceType.
918 // If ReferenceValue is an address of literal cstring then a pointer to the
919 // cstring is returned and ReferenceType is set to
920 // LLVMDisassembler_ReferenceType_Out_LitPool_CstrAddr .
922 // If ReferenceValue is an address of an Objective-C CFString, Selector ref or
923 // Class ref that name is returned and the ReferenceType is set accordingly.
925 // Lastly, literals which are Symbol address in a literal pool are looked for
926 // and if found the symbol name is returned and ReferenceType is set to
927 // LLVMDisassembler_ReferenceType_Out_LitPool_SymAddr .
929 // If there is no item in the Mach-O file for the address passed in as
930 // ReferenceValue nullptr is returned and ReferenceType is unchanged.
931 const char *GuessLiteralPointer(uint64_t ReferenceValue, uint64_t ReferencePC,
932 uint64_t *ReferenceType,
933 struct DisassembleInfo *info) {
934 // TODO: This rouine's code and the routines it calls are only work with
935 // x86_64 Mach-O files for now.
936 unsigned int Arch = info->O->getArch();
937 if (Arch != Triple::x86_64)
940 // First see if there is an external relocation entry at the ReferencePC.
941 uint64_t sect_addr = info->S.getAddress();
942 uint64_t sect_offset = ReferencePC - sect_addr;
943 bool reloc_found = false;
945 MachO::any_relocation_info RE;
946 bool isExtern = false;
948 for (const RelocationRef &Reloc : info->S.relocations()) {
949 uint64_t RelocOffset;
950 Reloc.getOffset(RelocOffset);
951 if (RelocOffset == sect_offset) {
952 Rel = Reloc.getRawDataRefImpl();
953 RE = info->O->getRelocation(Rel);
954 if (info->O->isRelocationScattered(RE))
956 isExtern = info->O->getPlainRelocationExternal(RE);
958 symbol_iterator RelocSym = Reloc.getSymbol();
965 // If there is an external relocation entry for a symbol in a section
966 // then used that symbol's value for the value of the reference.
967 if (reloc_found && isExtern) {
968 if (info->O->getAnyRelocationPCRel(RE)) {
969 unsigned Type = info->O->getAnyRelocationType(RE);
970 if (Type == MachO::X86_64_RELOC_SIGNED) {
971 Symbol.getAddress(ReferenceValue);
976 // Look for literals such as Objective-C CFStrings refs, Selector refs,
977 // Message refs and Class refs.
978 bool classref, selref, msgref, cfstring;
979 uint64_t pointer_value = GuessPointerPointer(ReferenceValue, info, classref,
980 selref, msgref, cfstring);
981 if (classref == true && pointer_value == 0) {
982 // Note the ReferenceValue is a pointer into the __objc_classrefs section.
983 // And the pointer_value in that section is typically zero as it will be
984 // set by dyld as part of the "bind information".
985 const char *name = get_dyld_bind_info_symbolname(ReferenceValue, info);
986 if (name != nullptr) {
987 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Class_Ref;
988 const char *class_name = strrchr(name, '$');
989 if (class_name != nullptr && class_name[1] == '_' &&
990 class_name[2] != '\0') {
991 info->class_name = class_name + 2;
997 if (classref == true) {
998 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Class_Ref;
1000 get_objc2_64bit_class_name(pointer_value, ReferenceValue, info);
1001 if (name != nullptr)
1002 info->class_name = name;
1004 name = "bad class ref";
1008 if (cfstring == true) {
1009 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_CFString_Ref;
1010 const char *name = get_objc2_64bit_cfstring_name(ReferenceValue, info);
1014 if (selref == true && pointer_value == 0)
1015 pointer_value = get_objc2_64bit_selref(ReferenceValue, info);
1017 if (pointer_value != 0)
1018 ReferenceValue = pointer_value;
1020 const char *name = GuessCstringPointer(ReferenceValue, info);
1022 if (pointer_value != 0 && selref == true) {
1023 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Selector_Ref;
1024 info->selector_name = name;
1025 } else if (pointer_value != 0 && msgref == true) {
1026 info->class_name = nullptr;
1027 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message_Ref;
1028 info->selector_name = name;
1030 *ReferenceType = LLVMDisassembler_ReferenceType_Out_LitPool_CstrAddr;
1034 // Lastly look for an indirect symbol with this ReferenceValue which is in
1035 // a literal pool. If found return that symbol name.
1036 name = GuessIndirectSymbol(ReferenceValue, info);
1038 *ReferenceType = LLVMDisassembler_ReferenceType_Out_LitPool_SymAddr;
1045 // SymbolizerSymbolLookUp is the symbol lookup function passed when creating
1046 // the Symbolizer. It looks up the ReferenceValue using the info passed via the
1047 // pointer to the struct DisassembleInfo that was passed when MCSymbolizer
1048 // is created and returns the symbol name that matches the ReferenceValue or
1049 // nullptr if none. The ReferenceType is passed in for the IN type of
1050 // reference the instruction is making from the values in defined in the header
1051 // "llvm-c/Disassembler.h". On return the ReferenceType can set to a specific
1052 // Out type and the ReferenceName will also be set which is added as a comment
1053 // to the disassembled instruction.
1056 // If the symbol name is a C++ mangled name then the demangled name is
1057 // returned through ReferenceName and ReferenceType is set to
1058 // LLVMDisassembler_ReferenceType_DeMangled_Name .
1061 // When this is called to get a symbol name for a branch target then the
1062 // ReferenceType will be LLVMDisassembler_ReferenceType_In_Branch and then
1063 // SymbolValue will be looked for in the indirect symbol table to determine if
1064 // it is an address for a symbol stub. If so then the symbol name for that
1065 // stub is returned indirectly through ReferenceName and then ReferenceType is
1066 // set to LLVMDisassembler_ReferenceType_Out_SymbolStub.
1068 // When this is called with an value loaded via a PC relative load then
1069 // ReferenceType will be LLVMDisassembler_ReferenceType_In_PCrel_Load then the
1070 // SymbolValue is checked to be an address of literal pointer, symbol pointer,
1071 // or an Objective-C meta data reference. If so the output ReferenceType is
1072 // set to correspond to that as well as setting the ReferenceName.
1073 const char *SymbolizerSymbolLookUp(void *DisInfo, uint64_t ReferenceValue,
1074 uint64_t *ReferenceType,
1075 uint64_t ReferencePC,
1076 const char **ReferenceName) {
1077 struct DisassembleInfo *info = (struct DisassembleInfo *)DisInfo;
1078 // If no verbose symbolic information is wanted then just return nullptr.
1079 if (info->verbose == false) {
1080 *ReferenceName = nullptr;
1081 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
1085 const char *SymbolName = nullptr;
1086 if (ReferenceValue != 0xffffffffffffffffULL &&
1087 ReferenceValue != 0xfffffffffffffffeULL) {
1088 StringRef name = info->AddrMap->lookup(ReferenceValue);
1090 SymbolName = name.data();
1093 if (*ReferenceType == LLVMDisassembler_ReferenceType_In_Branch) {
1094 *ReferenceName = GuessIndirectSymbol(ReferenceValue, info);
1095 if (*ReferenceName != nullptr) {
1096 method_reference(info, ReferenceType, ReferenceName);
1097 if (*ReferenceType != LLVMDisassembler_ReferenceType_Out_Objc_Message)
1098 *ReferenceType = LLVMDisassembler_ReferenceType_Out_SymbolStub;
1101 if (SymbolName != nullptr && strncmp(SymbolName, "__Z", 3) == 0) {
1102 if (info->demangled_name != nullptr)
1103 free(info->demangled_name);
1105 info->demangled_name = abi::__cxa_demangle(SymbolName + 1, nullptr,
1107 if (info->demangled_name != nullptr) {
1108 *ReferenceName = info->demangled_name;
1109 *ReferenceType = LLVMDisassembler_ReferenceType_DeMangled_Name;
1111 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
1114 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
1115 } else if (*ReferenceType == LLVMDisassembler_ReferenceType_In_PCrel_Load) {
1117 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
1119 method_reference(info, ReferenceType, ReferenceName);
1121 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
1124 else if (SymbolName != nullptr && strncmp(SymbolName, "__Z", 3) == 0) {
1125 if (info->demangled_name != nullptr)
1126 free(info->demangled_name);
1128 info->demangled_name = abi::__cxa_demangle(SymbolName + 1, nullptr, nullptr,
1130 if (info->demangled_name != nullptr) {
1131 *ReferenceName = info->demangled_name;
1132 *ReferenceType = LLVMDisassembler_ReferenceType_DeMangled_Name;
1137 *ReferenceName = nullptr;
1138 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
1145 // This is the memory object used by DisAsm->getInstruction() which has its
1146 // BasePC. This then allows the 'address' parameter to getInstruction() to
1147 // be the actual PC of the instruction. Then when a branch dispacement is
1148 // added to the PC of an instruction, the 'ReferenceValue' passed to the
1149 // SymbolizerSymbolLookUp() routine is the correct target addresses. As in
1150 // the case of a fully linked Mach-O file where a section being disassembled
1151 // generally not linked at address zero.
1153 class DisasmMemoryObject : public MemoryObject {
1154 const uint8_t *Bytes;
1158 DisasmMemoryObject(const uint8_t *bytes, uint64_t size, uint64_t basePC)
1159 : Bytes(bytes), Size(size), BasePC(basePC) {}
1161 uint64_t getBase() const override { return BasePC; }
1162 uint64_t getExtent() const override { return Size; }
1164 int readByte(uint64_t Addr, uint8_t *Byte) const override {
1165 if (Addr - BasePC >= Size)
1167 *Byte = Bytes[Addr - BasePC];
1172 /// \brief Emits the comments that are stored in the CommentStream.
1173 /// Each comment in the CommentStream must end with a newline.
1174 static void emitComments(raw_svector_ostream &CommentStream,
1175 SmallString<128> &CommentsToEmit,
1176 formatted_raw_ostream &FormattedOS,
1177 const MCAsmInfo &MAI) {
1178 // Flush the stream before taking its content.
1179 CommentStream.flush();
1180 StringRef Comments = CommentsToEmit.str();
1181 // Get the default information for printing a comment.
1182 const char *CommentBegin = MAI.getCommentString();
1183 unsigned CommentColumn = MAI.getCommentColumn();
1184 bool IsFirst = true;
1185 while (!Comments.empty()) {
1187 FormattedOS << '\n';
1188 // Emit a line of comments.
1189 FormattedOS.PadToColumn(CommentColumn);
1190 size_t Position = Comments.find('\n');
1191 FormattedOS << CommentBegin << ' ' << Comments.substr(0, Position);
1192 // Move after the newline character.
1193 Comments = Comments.substr(Position + 1);
1196 FormattedOS.flush();
1198 // Tell the comment stream that the vector changed underneath it.
1199 CommentsToEmit.clear();
1200 CommentStream.resync();
1203 static void DisassembleInputMachO2(StringRef Filename,
1204 MachOObjectFile *MachOOF) {
1205 const char *McpuDefault = nullptr;
1206 const Target *ThumbTarget = nullptr;
1207 const Target *TheTarget = GetTarget(MachOOF, &McpuDefault, &ThumbTarget);
1209 // GetTarget prints out stuff.
1212 if (MCPU.empty() && McpuDefault)
1215 std::unique_ptr<const MCInstrInfo> InstrInfo(TheTarget->createMCInstrInfo());
1216 std::unique_ptr<MCInstrAnalysis> InstrAnalysis(
1217 TheTarget->createMCInstrAnalysis(InstrInfo.get()));
1218 std::unique_ptr<const MCInstrInfo> ThumbInstrInfo;
1219 std::unique_ptr<MCInstrAnalysis> ThumbInstrAnalysis;
1221 ThumbInstrInfo.reset(ThumbTarget->createMCInstrInfo());
1222 ThumbInstrAnalysis.reset(
1223 ThumbTarget->createMCInstrAnalysis(ThumbInstrInfo.get()));
1226 // Package up features to be passed to target/subtarget
1227 std::string FeaturesStr;
1228 if (MAttrs.size()) {
1229 SubtargetFeatures Features;
1230 for (unsigned i = 0; i != MAttrs.size(); ++i)
1231 Features.AddFeature(MAttrs[i]);
1232 FeaturesStr = Features.getString();
1235 // Set up disassembler.
1236 std::unique_ptr<const MCRegisterInfo> MRI(
1237 TheTarget->createMCRegInfo(TripleName));
1238 std::unique_ptr<const MCAsmInfo> AsmInfo(
1239 TheTarget->createMCAsmInfo(*MRI, TripleName));
1240 std::unique_ptr<const MCSubtargetInfo> STI(
1241 TheTarget->createMCSubtargetInfo(TripleName, MCPU, FeaturesStr));
1242 MCContext Ctx(AsmInfo.get(), MRI.get(), nullptr);
1243 std::unique_ptr<MCDisassembler> DisAsm(
1244 TheTarget->createMCDisassembler(*STI, Ctx));
1245 std::unique_ptr<MCSymbolizer> Symbolizer;
1246 struct DisassembleInfo SymbolizerInfo;
1247 std::unique_ptr<MCRelocationInfo> RelInfo(
1248 TheTarget->createMCRelocationInfo(TripleName, Ctx));
1250 Symbolizer.reset(TheTarget->createMCSymbolizer(
1251 TripleName, SymbolizerGetOpInfo, SymbolizerSymbolLookUp,
1252 &SymbolizerInfo, &Ctx, RelInfo.release()));
1253 DisAsm->setSymbolizer(std::move(Symbolizer));
1255 int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
1256 std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
1257 AsmPrinterVariant, *AsmInfo, *InstrInfo, *MRI, *STI));
1258 // Set the display preference for hex vs. decimal immediates.
1259 IP->setPrintImmHex(PrintImmHex);
1260 // Comment stream and backing vector.
1261 SmallString<128> CommentsToEmit;
1262 raw_svector_ostream CommentStream(CommentsToEmit);
1263 IP->setCommentStream(CommentStream);
1265 if (!InstrAnalysis || !AsmInfo || !STI || !DisAsm || !IP) {
1266 errs() << "error: couldn't initialize disassembler for target "
1267 << TripleName << '\n';
1271 // Set up thumb disassembler.
1272 std::unique_ptr<const MCRegisterInfo> ThumbMRI;
1273 std::unique_ptr<const MCAsmInfo> ThumbAsmInfo;
1274 std::unique_ptr<const MCSubtargetInfo> ThumbSTI;
1275 std::unique_ptr<const MCDisassembler> ThumbDisAsm;
1276 std::unique_ptr<MCInstPrinter> ThumbIP;
1277 std::unique_ptr<MCContext> ThumbCtx;
1279 ThumbMRI.reset(ThumbTarget->createMCRegInfo(ThumbTripleName));
1281 ThumbTarget->createMCAsmInfo(*ThumbMRI, ThumbTripleName));
1283 ThumbTarget->createMCSubtargetInfo(ThumbTripleName, MCPU, FeaturesStr));
1284 ThumbCtx.reset(new MCContext(ThumbAsmInfo.get(), ThumbMRI.get(), nullptr));
1285 ThumbDisAsm.reset(ThumbTarget->createMCDisassembler(*ThumbSTI, *ThumbCtx));
1286 // TODO: add MCSymbolizer here for the ThumbTarget like above for TheTarget.
1287 int ThumbAsmPrinterVariant = ThumbAsmInfo->getAssemblerDialect();
1288 ThumbIP.reset(ThumbTarget->createMCInstPrinter(
1289 ThumbAsmPrinterVariant, *ThumbAsmInfo, *ThumbInstrInfo, *ThumbMRI,
1291 // Set the display preference for hex vs. decimal immediates.
1292 ThumbIP->setPrintImmHex(PrintImmHex);
1295 if (ThumbTarget && (!ThumbInstrAnalysis || !ThumbAsmInfo || !ThumbSTI ||
1296 !ThumbDisAsm || !ThumbIP)) {
1297 errs() << "error: couldn't initialize disassembler for target "
1298 << ThumbTripleName << '\n';
1302 outs() << '\n' << Filename << ":\n\n";
1304 MachO::mach_header Header = MachOOF->getHeader();
1306 // FIXME: Using the -cfg command line option, this code used to be able to
1307 // annotate relocations with the referenced symbol's name, and if this was
1308 // inside a __[cf]string section, the data it points to. This is now replaced
1309 // by the upcoming MCSymbolizer, which needs the appropriate setup done above.
1310 std::vector<SectionRef> Sections;
1311 std::vector<SymbolRef> Symbols;
1312 SmallVector<uint64_t, 8> FoundFns;
1313 uint64_t BaseSegmentAddress;
1315 getSectionsAndSymbols(Header, MachOOF, Sections, Symbols, FoundFns,
1316 BaseSegmentAddress);
1318 // Sort the symbols by address, just in case they didn't come in that way.
1319 std::sort(Symbols.begin(), Symbols.end(), SymbolSorter());
1321 // Build a data in code table that is sorted on by the address of each entry.
1322 uint64_t BaseAddress = 0;
1323 if (Header.filetype == MachO::MH_OBJECT)
1324 BaseAddress = Sections[0].getAddress();
1326 BaseAddress = BaseSegmentAddress;
1328 for (dice_iterator DI = MachOOF->begin_dices(), DE = MachOOF->end_dices();
1331 DI->getOffset(Offset);
1332 Dices.push_back(std::make_pair(BaseAddress + Offset, *DI));
1334 array_pod_sort(Dices.begin(), Dices.end());
1337 raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls();
1339 raw_ostream &DebugOut = nulls();
1342 std::unique_ptr<DIContext> diContext;
1343 ObjectFile *DbgObj = MachOOF;
1344 // Try to find debug info and set up the DIContext for it.
1346 // A separate DSym file path was specified, parse it as a macho file,
1347 // get the sections and supply it to the section name parsing machinery.
1348 if (!DSYMFile.empty()) {
1349 ErrorOr<std::unique_ptr<MemoryBuffer>> BufOrErr =
1350 MemoryBuffer::getFileOrSTDIN(DSYMFile);
1351 if (std::error_code EC = BufOrErr.getError()) {
1352 errs() << "llvm-objdump: " << Filename << ": " << EC.message() << '\n';
1356 ObjectFile::createMachOObjectFile(BufOrErr.get()->getMemBufferRef())
1361 // Setup the DIContext
1362 diContext.reset(DIContext::getDWARFContext(*DbgObj));
1365 for (unsigned SectIdx = 0; SectIdx != Sections.size(); SectIdx++) {
1367 bool SectIsText = Sections[SectIdx].isText();
1368 if (SectIsText == false)
1372 if (Sections[SectIdx].getName(SectName) ||
1373 SectName != "__text")
1374 continue; // Skip non-text sections
1376 DataRefImpl DR = Sections[SectIdx].getRawDataRefImpl();
1378 StringRef SegmentName = MachOOF->getSectionFinalSegmentName(DR);
1379 if (SegmentName != "__TEXT")
1383 Sections[SectIdx].getContents(Bytes);
1384 uint64_t SectAddress = Sections[SectIdx].getAddress();
1385 DisasmMemoryObject MemoryObject((const uint8_t *)Bytes.data(), Bytes.size(),
1387 bool symbolTableWorked = false;
1389 // Parse relocations.
1390 std::vector<std::pair<uint64_t, SymbolRef>> Relocs;
1391 for (const RelocationRef &Reloc : Sections[SectIdx].relocations()) {
1392 uint64_t RelocOffset;
1393 Reloc.getOffset(RelocOffset);
1394 uint64_t SectionAddress = Sections[SectIdx].getAddress();
1395 RelocOffset -= SectionAddress;
1397 symbol_iterator RelocSym = Reloc.getSymbol();
1399 Relocs.push_back(std::make_pair(RelocOffset, *RelocSym));
1401 array_pod_sort(Relocs.begin(), Relocs.end());
1403 // Create a map of symbol addresses to symbol names for use by
1404 // the SymbolizerSymbolLookUp() routine.
1405 SymbolAddressMap AddrMap;
1406 for (const SymbolRef &Symbol : MachOOF->symbols()) {
1409 if (ST == SymbolRef::ST_Function || ST == SymbolRef::ST_Data ||
1410 ST == SymbolRef::ST_Other) {
1412 Symbol.getAddress(Address);
1414 Symbol.getName(SymName);
1415 AddrMap[Address] = SymName;
1418 // Set up the block of info used by the Symbolizer call backs.
1419 SymbolizerInfo.verbose = true;
1420 SymbolizerInfo.O = MachOOF;
1421 SymbolizerInfo.S = Sections[SectIdx];
1422 SymbolizerInfo.AddrMap = &AddrMap;
1423 SymbolizerInfo.Sections = &Sections;
1424 SymbolizerInfo.class_name = nullptr;
1425 SymbolizerInfo.selector_name = nullptr;
1426 SymbolizerInfo.method = nullptr;
1427 SymbolizerInfo.demangled_name = nullptr;
1428 SymbolizerInfo.bindtable = nullptr;
1430 // Disassemble symbol by symbol.
1431 for (unsigned SymIdx = 0; SymIdx != Symbols.size(); SymIdx++) {
1433 Symbols[SymIdx].getName(SymName);
1436 Symbols[SymIdx].getType(ST);
1437 if (ST != SymbolRef::ST_Function)
1440 // Make sure the symbol is defined in this section.
1441 bool containsSym = Sections[SectIdx].containsSymbol(Symbols[SymIdx]);
1445 // Start at the address of the symbol relative to the section's address.
1447 uint64_t SectionAddress = Sections[SectIdx].getAddress();
1448 Symbols[SymIdx].getAddress(Start);
1449 Start -= SectionAddress;
1451 // Stop disassembling either at the beginning of the next symbol or at
1452 // the end of the section.
1453 bool containsNextSym = false;
1454 uint64_t NextSym = 0;
1455 uint64_t NextSymIdx = SymIdx+1;
1456 while (Symbols.size() > NextSymIdx) {
1457 SymbolRef::Type NextSymType;
1458 Symbols[NextSymIdx].getType(NextSymType);
1459 if (NextSymType == SymbolRef::ST_Function) {
1461 Sections[SectIdx].containsSymbol(Symbols[NextSymIdx]);
1462 Symbols[NextSymIdx].getAddress(NextSym);
1463 NextSym -= SectionAddress;
1469 uint64_t SectSize = Sections[SectIdx].getSize();
1470 uint64_t End = containsNextSym ? NextSym : SectSize;
1473 symbolTableWorked = true;
1474 DisasmMemoryObject SectionMemoryObject((const uint8_t *)Bytes.data() +
1476 End - Start, SectAddress + Start);
1478 DataRefImpl Symb = Symbols[SymIdx].getRawDataRefImpl();
1480 (MachOOF->getSymbolFlags(Symb) & SymbolRef::SF_Thumb) && ThumbTarget;
1482 outs() << SymName << ":\n";
1483 DILineInfo lastLine;
1484 for (uint64_t Index = Start; Index < End; Index += Size) {
1487 uint64_t PC = SectAddress + Index;
1488 if (FullLeadingAddr) {
1489 if (MachOOF->is64Bit())
1490 outs() << format("%016" PRIx64, PC);
1492 outs() << format("%08" PRIx64, PC);
1494 outs() << format("%8" PRIx64 ":", PC);
1499 // Check the data in code table here to see if this is data not an
1500 // instruction to be disassembled.
1502 Dice.push_back(std::make_pair(PC, DiceRef()));
1503 dice_table_iterator DTI = std::search(Dices.begin(), Dices.end(),
1504 Dice.begin(), Dice.end(),
1505 compareDiceTableEntries);
1506 if (DTI != Dices.end()){
1508 DTI->second.getLength(Length);
1509 DumpBytes(StringRef(Bytes.data() + Index, Length));
1511 DTI->second.getKind(Kind);
1512 DumpDataInCode(Bytes.data() + Index, Length, Kind);
1516 SmallVector<char, 64> AnnotationsBytes;
1517 raw_svector_ostream Annotations(AnnotationsBytes);
1521 gotInst = ThumbDisAsm->getInstruction(Inst, Size, SectionMemoryObject,
1522 PC, DebugOut, Annotations);
1524 gotInst = DisAsm->getInstruction(Inst, Size, SectionMemoryObject, PC,
1525 DebugOut, Annotations);
1527 if (!NoShowRawInsn) {
1528 DumpBytes(StringRef(Bytes.data() + Index, Size));
1530 formatted_raw_ostream FormattedOS(outs());
1531 Annotations.flush();
1532 StringRef AnnotationsStr = Annotations.str();
1534 ThumbIP->printInst(&Inst, FormattedOS, AnnotationsStr);
1536 IP->printInst(&Inst, FormattedOS, AnnotationsStr);
1537 emitComments(CommentStream, CommentsToEmit, FormattedOS, *AsmInfo);
1539 // Print debug info.
1542 diContext->getLineInfoForAddress(PC);
1543 // Print valid line info if it changed.
1544 if (dli != lastLine && dli.Line != 0)
1545 outs() << "\t## " << dli.FileName << ':' << dli.Line << ':'
1551 unsigned int Arch = MachOOF->getArch();
1552 if (Arch == Triple::x86_64 || Arch == Triple::x86){
1553 outs() << format("\t.byte 0x%02x #bad opcode\n",
1554 *(Bytes.data() + Index) & 0xff);
1555 Size = 1; // skip exactly one illegible byte and move on.
1557 errs() << "llvm-objdump: warning: invalid instruction encoding\n";
1559 Size = 1; // skip illegible bytes
1564 if (!symbolTableWorked) {
1565 // Reading the symbol table didn't work, disassemble the whole section.
1566 uint64_t SectAddress = Sections[SectIdx].getAddress();
1567 uint64_t SectSize = Sections[SectIdx].getSize();
1569 for (uint64_t Index = 0; Index < SectSize; Index += InstSize) {
1572 uint64_t PC = SectAddress + Index;
1573 if (DisAsm->getInstruction(Inst, InstSize, MemoryObject, PC, DebugOut,
1575 if (FullLeadingAddr) {
1576 if (MachOOF->is64Bit())
1577 outs() << format("%016" PRIx64, PC);
1579 outs() << format("%08" PRIx64, PC);
1581 outs() << format("%8" PRIx64 ":", PC);
1583 if (!NoShowRawInsn) {
1585 DumpBytes(StringRef(Bytes.data() + Index, InstSize));
1587 IP->printInst(&Inst, outs(), "");
1590 unsigned int Arch = MachOOF->getArch();
1591 if (Arch == Triple::x86_64 || Arch == Triple::x86){
1592 outs() << format("\t.byte 0x%02x #bad opcode\n",
1593 *(Bytes.data() + Index) & 0xff);
1594 InstSize = 1; // skip exactly one illegible byte and move on.
1596 errs() << "llvm-objdump: warning: invalid instruction encoding\n";
1598 InstSize = 1; // skip illegible bytes
1603 if (SymbolizerInfo.method != nullptr)
1604 free(SymbolizerInfo.method);
1605 if (SymbolizerInfo.demangled_name != nullptr)
1606 free(SymbolizerInfo.demangled_name);
1607 if (SymbolizerInfo.bindtable != nullptr)
1608 delete SymbolizerInfo.bindtable;
1613 //===----------------------------------------------------------------------===//
1614 // __compact_unwind section dumping
1615 //===----------------------------------------------------------------------===//
1619 template <typename T> static uint64_t readNext(const char *&Buf) {
1620 using llvm::support::little;
1621 using llvm::support::unaligned;
1623 uint64_t Val = support::endian::read<T, little, unaligned>(Buf);
1628 struct CompactUnwindEntry {
1629 uint32_t OffsetInSection;
1631 uint64_t FunctionAddr;
1633 uint32_t CompactEncoding;
1634 uint64_t PersonalityAddr;
1637 RelocationRef FunctionReloc;
1638 RelocationRef PersonalityReloc;
1639 RelocationRef LSDAReloc;
1641 CompactUnwindEntry(StringRef Contents, unsigned Offset, bool Is64)
1642 : OffsetInSection(Offset) {
1644 read<uint64_t>(Contents.data() + Offset);
1646 read<uint32_t>(Contents.data() + Offset);
1650 template<typename UIntPtr>
1651 void read(const char *Buf) {
1652 FunctionAddr = readNext<UIntPtr>(Buf);
1653 Length = readNext<uint32_t>(Buf);
1654 CompactEncoding = readNext<uint32_t>(Buf);
1655 PersonalityAddr = readNext<UIntPtr>(Buf);
1656 LSDAAddr = readNext<UIntPtr>(Buf);
1661 /// Given a relocation from __compact_unwind, consisting of the RelocationRef
1662 /// and data being relocated, determine the best base Name and Addend to use for
1663 /// display purposes.
1665 /// 1. An Extern relocation will directly reference a symbol (and the data is
1666 /// then already an addend), so use that.
1667 /// 2. Otherwise the data is an offset in the object file's layout; try to find
1668 // a symbol before it in the same section, and use the offset from there.
1669 /// 3. Finally, if all that fails, fall back to an offset from the start of the
1670 /// referenced section.
1671 static void findUnwindRelocNameAddend(const MachOObjectFile *Obj,
1672 std::map<uint64_t, SymbolRef> &Symbols,
1673 const RelocationRef &Reloc,
1675 StringRef &Name, uint64_t &Addend) {
1676 if (Reloc.getSymbol() != Obj->symbol_end()) {
1677 Reloc.getSymbol()->getName(Name);
1682 auto RE = Obj->getRelocation(Reloc.getRawDataRefImpl());
1683 SectionRef RelocSection = Obj->getRelocationSection(RE);
1685 uint64_t SectionAddr = RelocSection.getAddress();
1687 auto Sym = Symbols.upper_bound(Addr);
1688 if (Sym == Symbols.begin()) {
1689 // The first symbol in the object is after this reference, the best we can
1690 // do is section-relative notation.
1691 RelocSection.getName(Name);
1692 Addend = Addr - SectionAddr;
1696 // Go back one so that SymbolAddress <= Addr.
1699 section_iterator SymSection = Obj->section_end();
1700 Sym->second.getSection(SymSection);
1701 if (RelocSection == *SymSection) {
1702 // There's a valid symbol in the same section before this reference.
1703 Sym->second.getName(Name);
1704 Addend = Addr - Sym->first;
1708 // There is a symbol before this reference, but it's in a different
1709 // section. Probably not helpful to mention it, so use the section name.
1710 RelocSection.getName(Name);
1711 Addend = Addr - SectionAddr;
1714 static void printUnwindRelocDest(const MachOObjectFile *Obj,
1715 std::map<uint64_t, SymbolRef> &Symbols,
1716 const RelocationRef &Reloc,
1721 if (!Reloc.getObjectFile())
1724 findUnwindRelocNameAddend(Obj, Symbols, Reloc, Addr, Name, Addend);
1728 outs() << " + " << format("0x%" PRIx64, Addend);
1732 printMachOCompactUnwindSection(const MachOObjectFile *Obj,
1733 std::map<uint64_t, SymbolRef> &Symbols,
1734 const SectionRef &CompactUnwind) {
1736 assert(Obj->isLittleEndian() &&
1737 "There should not be a big-endian .o with __compact_unwind");
1739 bool Is64 = Obj->is64Bit();
1740 uint32_t PointerSize = Is64 ? sizeof(uint64_t) : sizeof(uint32_t);
1741 uint32_t EntrySize = 3 * PointerSize + 2 * sizeof(uint32_t);
1744 CompactUnwind.getContents(Contents);
1746 SmallVector<CompactUnwindEntry, 4> CompactUnwinds;
1748 // First populate the initial raw offsets, encodings and so on from the entry.
1749 for (unsigned Offset = 0; Offset < Contents.size(); Offset += EntrySize) {
1750 CompactUnwindEntry Entry(Contents.data(), Offset, Is64);
1751 CompactUnwinds.push_back(Entry);
1754 // Next we need to look at the relocations to find out what objects are
1755 // actually being referred to.
1756 for (const RelocationRef &Reloc : CompactUnwind.relocations()) {
1757 uint64_t RelocAddress;
1758 Reloc.getOffset(RelocAddress);
1760 uint32_t EntryIdx = RelocAddress / EntrySize;
1761 uint32_t OffsetInEntry = RelocAddress - EntryIdx * EntrySize;
1762 CompactUnwindEntry &Entry = CompactUnwinds[EntryIdx];
1764 if (OffsetInEntry == 0)
1765 Entry.FunctionReloc = Reloc;
1766 else if (OffsetInEntry == PointerSize + 2 * sizeof(uint32_t))
1767 Entry.PersonalityReloc = Reloc;
1768 else if (OffsetInEntry == 2 * PointerSize + 2 * sizeof(uint32_t))
1769 Entry.LSDAReloc = Reloc;
1771 llvm_unreachable("Unexpected relocation in __compact_unwind section");
1774 // Finally, we're ready to print the data we've gathered.
1775 outs() << "Contents of __compact_unwind section:\n";
1776 for (auto &Entry : CompactUnwinds) {
1777 outs() << " Entry at offset "
1778 << format("0x%" PRIx32, Entry.OffsetInSection) << ":\n";
1780 // 1. Start of the region this entry applies to.
1781 outs() << " start: "
1782 << format("0x%" PRIx64, Entry.FunctionAddr) << ' ';
1783 printUnwindRelocDest(Obj, Symbols, Entry.FunctionReloc,
1784 Entry.FunctionAddr);
1787 // 2. Length of the region this entry applies to.
1788 outs() << " length: "
1789 << format("0x%" PRIx32, Entry.Length) << '\n';
1790 // 3. The 32-bit compact encoding.
1791 outs() << " compact encoding: "
1792 << format("0x%08" PRIx32, Entry.CompactEncoding) << '\n';
1794 // 4. The personality function, if present.
1795 if (Entry.PersonalityReloc.getObjectFile()) {
1796 outs() << " personality function: "
1797 << format("0x%" PRIx64, Entry.PersonalityAddr) << ' ';
1798 printUnwindRelocDest(Obj, Symbols, Entry.PersonalityReloc,
1799 Entry.PersonalityAddr);
1803 // 5. This entry's language-specific data area.
1804 if (Entry.LSDAReloc.getObjectFile()) {
1806 << format("0x%" PRIx64, Entry.LSDAAddr) << ' ';
1807 printUnwindRelocDest(Obj, Symbols, Entry.LSDAReloc, Entry.LSDAAddr);
1813 //===----------------------------------------------------------------------===//
1814 // __unwind_info section dumping
1815 //===----------------------------------------------------------------------===//
1817 static void printRegularSecondLevelUnwindPage(const char *PageStart) {
1818 const char *Pos = PageStart;
1819 uint32_t Kind = readNext<uint32_t>(Pos);
1821 assert(Kind == 2 && "kind for a regular 2nd level index should be 2");
1823 uint16_t EntriesStart = readNext<uint16_t>(Pos);
1824 uint16_t NumEntries = readNext<uint16_t>(Pos);
1826 Pos = PageStart + EntriesStart;
1827 for (unsigned i = 0; i < NumEntries; ++i) {
1828 uint32_t FunctionOffset = readNext<uint32_t>(Pos);
1829 uint32_t Encoding = readNext<uint32_t>(Pos);
1831 outs() << " [" << i << "]: "
1832 << "function offset="
1833 << format("0x%08" PRIx32, FunctionOffset) << ", "
1835 << format("0x%08" PRIx32, Encoding)
1840 static void printCompressedSecondLevelUnwindPage(
1841 const char *PageStart, uint32_t FunctionBase,
1842 const SmallVectorImpl<uint32_t> &CommonEncodings) {
1843 const char *Pos = PageStart;
1844 uint32_t Kind = readNext<uint32_t>(Pos);
1846 assert(Kind == 3 && "kind for a compressed 2nd level index should be 3");
1848 uint16_t EntriesStart = readNext<uint16_t>(Pos);
1849 uint16_t NumEntries = readNext<uint16_t>(Pos);
1851 uint16_t EncodingsStart = readNext<uint16_t>(Pos);
1852 readNext<uint16_t>(Pos);
1853 const auto *PageEncodings = reinterpret_cast<const support::ulittle32_t *>(
1854 PageStart + EncodingsStart);
1856 Pos = PageStart + EntriesStart;
1857 for (unsigned i = 0; i < NumEntries; ++i) {
1858 uint32_t Entry = readNext<uint32_t>(Pos);
1859 uint32_t FunctionOffset = FunctionBase + (Entry & 0xffffff);
1860 uint32_t EncodingIdx = Entry >> 24;
1863 if (EncodingIdx < CommonEncodings.size())
1864 Encoding = CommonEncodings[EncodingIdx];
1866 Encoding = PageEncodings[EncodingIdx - CommonEncodings.size()];
1868 outs() << " [" << i << "]: "
1869 << "function offset="
1870 << format("0x%08" PRIx32, FunctionOffset) << ", "
1871 << "encoding[" << EncodingIdx << "]="
1872 << format("0x%08" PRIx32, Encoding)
1878 printMachOUnwindInfoSection(const MachOObjectFile *Obj,
1879 std::map<uint64_t, SymbolRef> &Symbols,
1880 const SectionRef &UnwindInfo) {
1882 assert(Obj->isLittleEndian() &&
1883 "There should not be a big-endian .o with __unwind_info");
1885 outs() << "Contents of __unwind_info section:\n";
1888 UnwindInfo.getContents(Contents);
1889 const char *Pos = Contents.data();
1891 //===----------------------------------
1893 //===----------------------------------
1895 uint32_t Version = readNext<uint32_t>(Pos);
1896 outs() << " Version: "
1897 << format("0x%" PRIx32, Version) << '\n';
1898 assert(Version == 1 && "only understand version 1");
1900 uint32_t CommonEncodingsStart = readNext<uint32_t>(Pos);
1901 outs() << " Common encodings array section offset: "
1902 << format("0x%" PRIx32, CommonEncodingsStart) << '\n';
1903 uint32_t NumCommonEncodings = readNext<uint32_t>(Pos);
1904 outs() << " Number of common encodings in array: "
1905 << format("0x%" PRIx32, NumCommonEncodings) << '\n';
1907 uint32_t PersonalitiesStart = readNext<uint32_t>(Pos);
1908 outs() << " Personality function array section offset: "
1909 << format("0x%" PRIx32, PersonalitiesStart) << '\n';
1910 uint32_t NumPersonalities = readNext<uint32_t>(Pos);
1911 outs() << " Number of personality functions in array: "
1912 << format("0x%" PRIx32, NumPersonalities) << '\n';
1914 uint32_t IndicesStart = readNext<uint32_t>(Pos);
1915 outs() << " Index array section offset: "
1916 << format("0x%" PRIx32, IndicesStart) << '\n';
1917 uint32_t NumIndices = readNext<uint32_t>(Pos);
1918 outs() << " Number of indices in array: "
1919 << format("0x%" PRIx32, NumIndices) << '\n';
1921 //===----------------------------------
1922 // A shared list of common encodings
1923 //===----------------------------------
1925 // These occupy indices in the range [0, N] whenever an encoding is referenced
1926 // from a compressed 2nd level index table. In practice the linker only
1927 // creates ~128 of these, so that indices are available to embed encodings in
1928 // the 2nd level index.
1930 SmallVector<uint32_t, 64> CommonEncodings;
1931 outs() << " Common encodings: (count = " << NumCommonEncodings << ")\n";
1932 Pos = Contents.data() + CommonEncodingsStart;
1933 for (unsigned i = 0; i < NumCommonEncodings; ++i) {
1934 uint32_t Encoding = readNext<uint32_t>(Pos);
1935 CommonEncodings.push_back(Encoding);
1937 outs() << " encoding[" << i << "]: " << format("0x%08" PRIx32, Encoding)
1942 //===----------------------------------
1943 // Personality functions used in this executable
1944 //===----------------------------------
1946 // There should be only a handful of these (one per source language,
1947 // roughly). Particularly since they only get 2 bits in the compact encoding.
1949 outs() << " Personality functions: (count = " << NumPersonalities << ")\n";
1950 Pos = Contents.data() + PersonalitiesStart;
1951 for (unsigned i = 0; i < NumPersonalities; ++i) {
1952 uint32_t PersonalityFn = readNext<uint32_t>(Pos);
1953 outs() << " personality[" << i + 1
1954 << "]: " << format("0x%08" PRIx32, PersonalityFn) << '\n';
1957 //===----------------------------------
1958 // The level 1 index entries
1959 //===----------------------------------
1961 // These specify an approximate place to start searching for the more detailed
1962 // information, sorted by PC.
1965 uint32_t FunctionOffset;
1966 uint32_t SecondLevelPageStart;
1970 SmallVector<IndexEntry, 4> IndexEntries;
1972 outs() << " Top level indices: (count = " << NumIndices << ")\n";
1973 Pos = Contents.data() + IndicesStart;
1974 for (unsigned i = 0; i < NumIndices; ++i) {
1977 Entry.FunctionOffset = readNext<uint32_t>(Pos);
1978 Entry.SecondLevelPageStart = readNext<uint32_t>(Pos);
1979 Entry.LSDAStart = readNext<uint32_t>(Pos);
1980 IndexEntries.push_back(Entry);
1982 outs() << " [" << i << "]: "
1983 << "function offset="
1984 << format("0x%08" PRIx32, Entry.FunctionOffset) << ", "
1985 << "2nd level page offset="
1986 << format("0x%08" PRIx32, Entry.SecondLevelPageStart) << ", "
1988 << format("0x%08" PRIx32, Entry.LSDAStart) << '\n';
1992 //===----------------------------------
1993 // Next come the LSDA tables
1994 //===----------------------------------
1996 // The LSDA layout is rather implicit: it's a contiguous array of entries from
1997 // the first top-level index's LSDAOffset to the last (sentinel).
1999 outs() << " LSDA descriptors:\n";
2000 Pos = Contents.data() + IndexEntries[0].LSDAStart;
2001 int NumLSDAs = (IndexEntries.back().LSDAStart - IndexEntries[0].LSDAStart) /
2002 (2 * sizeof(uint32_t));
2003 for (int i = 0; i < NumLSDAs; ++i) {
2004 uint32_t FunctionOffset = readNext<uint32_t>(Pos);
2005 uint32_t LSDAOffset = readNext<uint32_t>(Pos);
2006 outs() << " [" << i << "]: "
2007 << "function offset="
2008 << format("0x%08" PRIx32, FunctionOffset) << ", "
2010 << format("0x%08" PRIx32, LSDAOffset) << '\n';
2013 //===----------------------------------
2014 // Finally, the 2nd level indices
2015 //===----------------------------------
2017 // Generally these are 4K in size, and have 2 possible forms:
2018 // + Regular stores up to 511 entries with disparate encodings
2019 // + Compressed stores up to 1021 entries if few enough compact encoding
2021 outs() << " Second level indices:\n";
2022 for (unsigned i = 0; i < IndexEntries.size() - 1; ++i) {
2023 // The final sentinel top-level index has no associated 2nd level page
2024 if (IndexEntries[i].SecondLevelPageStart == 0)
2027 outs() << " Second level index[" << i << "]: "
2028 << "offset in section="
2029 << format("0x%08" PRIx32, IndexEntries[i].SecondLevelPageStart)
2031 << "base function offset="
2032 << format("0x%08" PRIx32, IndexEntries[i].FunctionOffset) << '\n';
2034 Pos = Contents.data() + IndexEntries[i].SecondLevelPageStart;
2035 uint32_t Kind = *reinterpret_cast<const support::ulittle32_t *>(Pos);
2037 printRegularSecondLevelUnwindPage(Pos);
2039 printCompressedSecondLevelUnwindPage(Pos, IndexEntries[i].FunctionOffset,
2042 llvm_unreachable("Do not know how to print this kind of 2nd level page");
2047 void llvm::printMachOUnwindInfo(const MachOObjectFile *Obj) {
2048 std::map<uint64_t, SymbolRef> Symbols;
2049 for (const SymbolRef &SymRef : Obj->symbols()) {
2050 // Discard any undefined or absolute symbols. They're not going to take part
2051 // in the convenience lookup for unwind info and just take up resources.
2052 section_iterator Section = Obj->section_end();
2053 SymRef.getSection(Section);
2054 if (Section == Obj->section_end())
2058 SymRef.getAddress(Addr);
2059 Symbols.insert(std::make_pair(Addr, SymRef));
2062 for (const SectionRef &Section : Obj->sections()) {
2064 Section.getName(SectName);
2065 if (SectName == "__compact_unwind")
2066 printMachOCompactUnwindSection(Obj, Symbols, Section);
2067 else if (SectName == "__unwind_info")
2068 printMachOUnwindInfoSection(Obj, Symbols, Section);
2069 else if (SectName == "__eh_frame")
2070 outs() << "llvm-objdump: warning: unhandled __eh_frame section\n";
2075 static void PrintMachHeader(uint32_t magic, uint32_t cputype,
2076 uint32_t cpusubtype, uint32_t filetype,
2077 uint32_t ncmds, uint32_t sizeofcmds, uint32_t flags,
2079 outs() << "Mach header\n";
2080 outs() << " magic cputype cpusubtype caps filetype ncmds "
2081 "sizeofcmds flags\n";
2083 if (magic == MachO::MH_MAGIC)
2084 outs() << " MH_MAGIC";
2085 else if (magic == MachO::MH_MAGIC_64)
2086 outs() << "MH_MAGIC_64";
2088 outs() << format(" 0x%08" PRIx32, magic);
2090 case MachO::CPU_TYPE_I386:
2092 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
2093 case MachO::CPU_SUBTYPE_I386_ALL:
2097 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
2101 case MachO::CPU_TYPE_X86_64:
2102 outs() << " X86_64";
2103 case MachO::CPU_SUBTYPE_X86_64_ALL:
2106 case MachO::CPU_SUBTYPE_X86_64_H:
2107 outs() << " Haswell";
2108 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
2110 case MachO::CPU_TYPE_ARM:
2112 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
2113 case MachO::CPU_SUBTYPE_ARM_ALL:
2116 case MachO::CPU_SUBTYPE_ARM_V4T:
2119 case MachO::CPU_SUBTYPE_ARM_V5TEJ:
2122 case MachO::CPU_SUBTYPE_ARM_XSCALE:
2123 outs() << " XSCALE";
2125 case MachO::CPU_SUBTYPE_ARM_V6:
2128 case MachO::CPU_SUBTYPE_ARM_V6M:
2131 case MachO::CPU_SUBTYPE_ARM_V7:
2134 case MachO::CPU_SUBTYPE_ARM_V7EM:
2137 case MachO::CPU_SUBTYPE_ARM_V7K:
2140 case MachO::CPU_SUBTYPE_ARM_V7M:
2143 case MachO::CPU_SUBTYPE_ARM_V7S:
2147 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
2151 case MachO::CPU_TYPE_ARM64:
2153 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
2154 case MachO::CPU_SUBTYPE_ARM64_ALL:
2158 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
2162 case MachO::CPU_TYPE_POWERPC:
2164 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
2165 case MachO::CPU_SUBTYPE_POWERPC_ALL:
2169 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
2173 case MachO::CPU_TYPE_POWERPC64:
2175 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
2176 case MachO::CPU_SUBTYPE_POWERPC_ALL:
2180 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
2185 if ((cpusubtype & MachO::CPU_SUBTYPE_MASK) == MachO::CPU_SUBTYPE_LIB64) {
2188 outs() << format(" 0x%02" PRIx32,
2189 (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24);
2192 case MachO::MH_OBJECT:
2193 outs() << " OBJECT";
2195 case MachO::MH_EXECUTE:
2196 outs() << " EXECUTE";
2198 case MachO::MH_FVMLIB:
2199 outs() << " FVMLIB";
2201 case MachO::MH_CORE:
2204 case MachO::MH_PRELOAD:
2205 outs() << " PRELOAD";
2207 case MachO::MH_DYLIB:
2210 case MachO::MH_DYLIB_STUB:
2211 outs() << " DYLIB_STUB";
2213 case MachO::MH_DYLINKER:
2214 outs() << " DYLINKER";
2216 case MachO::MH_BUNDLE:
2217 outs() << " BUNDLE";
2219 case MachO::MH_DSYM:
2222 case MachO::MH_KEXT_BUNDLE:
2223 outs() << " KEXTBUNDLE";
2226 outs() << format(" %10u", filetype);
2229 outs() << format(" %5u", ncmds);
2230 outs() << format(" %10u", sizeofcmds);
2232 if (f & MachO::MH_NOUNDEFS) {
2233 outs() << " NOUNDEFS";
2234 f &= ~MachO::MH_NOUNDEFS;
2236 if (f & MachO::MH_INCRLINK) {
2237 outs() << " INCRLINK";
2238 f &= ~MachO::MH_INCRLINK;
2240 if (f & MachO::MH_DYLDLINK) {
2241 outs() << " DYLDLINK";
2242 f &= ~MachO::MH_DYLDLINK;
2244 if (f & MachO::MH_BINDATLOAD) {
2245 outs() << " BINDATLOAD";
2246 f &= ~MachO::MH_BINDATLOAD;
2248 if (f & MachO::MH_PREBOUND) {
2249 outs() << " PREBOUND";
2250 f &= ~MachO::MH_PREBOUND;
2252 if (f & MachO::MH_SPLIT_SEGS) {
2253 outs() << " SPLIT_SEGS";
2254 f &= ~MachO::MH_SPLIT_SEGS;
2256 if (f & MachO::MH_LAZY_INIT) {
2257 outs() << " LAZY_INIT";
2258 f &= ~MachO::MH_LAZY_INIT;
2260 if (f & MachO::MH_TWOLEVEL) {
2261 outs() << " TWOLEVEL";
2262 f &= ~MachO::MH_TWOLEVEL;
2264 if (f & MachO::MH_FORCE_FLAT) {
2265 outs() << " FORCE_FLAT";
2266 f &= ~MachO::MH_FORCE_FLAT;
2268 if (f & MachO::MH_NOMULTIDEFS) {
2269 outs() << " NOMULTIDEFS";
2270 f &= ~MachO::MH_NOMULTIDEFS;
2272 if (f & MachO::MH_NOFIXPREBINDING) {
2273 outs() << " NOFIXPREBINDING";
2274 f &= ~MachO::MH_NOFIXPREBINDING;
2276 if (f & MachO::MH_PREBINDABLE) {
2277 outs() << " PREBINDABLE";
2278 f &= ~MachO::MH_PREBINDABLE;
2280 if (f & MachO::MH_ALLMODSBOUND) {
2281 outs() << " ALLMODSBOUND";
2282 f &= ~MachO::MH_ALLMODSBOUND;
2284 if (f & MachO::MH_SUBSECTIONS_VIA_SYMBOLS) {
2285 outs() << " SUBSECTIONS_VIA_SYMBOLS";
2286 f &= ~MachO::MH_SUBSECTIONS_VIA_SYMBOLS;
2288 if (f & MachO::MH_CANONICAL) {
2289 outs() << " CANONICAL";
2290 f &= ~MachO::MH_CANONICAL;
2292 if (f & MachO::MH_WEAK_DEFINES) {
2293 outs() << " WEAK_DEFINES";
2294 f &= ~MachO::MH_WEAK_DEFINES;
2296 if (f & MachO::MH_BINDS_TO_WEAK) {
2297 outs() << " BINDS_TO_WEAK";
2298 f &= ~MachO::MH_BINDS_TO_WEAK;
2300 if (f & MachO::MH_ALLOW_STACK_EXECUTION) {
2301 outs() << " ALLOW_STACK_EXECUTION";
2302 f &= ~MachO::MH_ALLOW_STACK_EXECUTION;
2304 if (f & MachO::MH_DEAD_STRIPPABLE_DYLIB) {
2305 outs() << " DEAD_STRIPPABLE_DYLIB";
2306 f &= ~MachO::MH_DEAD_STRIPPABLE_DYLIB;
2308 if (f & MachO::MH_PIE) {
2310 f &= ~MachO::MH_PIE;
2312 if (f & MachO::MH_NO_REEXPORTED_DYLIBS) {
2313 outs() << " NO_REEXPORTED_DYLIBS";
2314 f &= ~MachO::MH_NO_REEXPORTED_DYLIBS;
2316 if (f & MachO::MH_HAS_TLV_DESCRIPTORS) {
2317 outs() << " MH_HAS_TLV_DESCRIPTORS";
2318 f &= ~MachO::MH_HAS_TLV_DESCRIPTORS;
2320 if (f & MachO::MH_NO_HEAP_EXECUTION) {
2321 outs() << " MH_NO_HEAP_EXECUTION";
2322 f &= ~MachO::MH_NO_HEAP_EXECUTION;
2324 if (f & MachO::MH_APP_EXTENSION_SAFE) {
2325 outs() << " APP_EXTENSION_SAFE";
2326 f &= ~MachO::MH_APP_EXTENSION_SAFE;
2328 if (f != 0 || flags == 0)
2329 outs() << format(" 0x%08" PRIx32, f);
2331 outs() << format(" 0x%08" PRIx32, magic);
2332 outs() << format(" %7d", cputype);
2333 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
2334 outs() << format(" 0x%02" PRIx32,
2335 (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24);
2336 outs() << format(" %10u", filetype);
2337 outs() << format(" %5u", ncmds);
2338 outs() << format(" %10u", sizeofcmds);
2339 outs() << format(" 0x%08" PRIx32, flags);
2344 static void PrintSegmentCommand(uint32_t cmd, uint32_t cmdsize,
2345 StringRef SegName, uint64_t vmaddr,
2346 uint64_t vmsize, uint64_t fileoff,
2347 uint64_t filesize, uint32_t maxprot,
2348 uint32_t initprot, uint32_t nsects,
2349 uint32_t flags, uint32_t object_size,
2351 uint64_t expected_cmdsize;
2352 if (cmd == MachO::LC_SEGMENT) {
2353 outs() << " cmd LC_SEGMENT\n";
2354 expected_cmdsize = nsects;
2355 expected_cmdsize *= sizeof(struct MachO::section);
2356 expected_cmdsize += sizeof(struct MachO::segment_command);
2358 outs() << " cmd LC_SEGMENT_64\n";
2359 expected_cmdsize = nsects;
2360 expected_cmdsize *= sizeof(struct MachO::section_64);
2361 expected_cmdsize += sizeof(struct MachO::segment_command_64);
2363 outs() << " cmdsize " << cmdsize;
2364 if (cmdsize != expected_cmdsize)
2365 outs() << " Inconsistent size\n";
2368 outs() << " segname " << SegName << "\n";
2369 if (cmd == MachO::LC_SEGMENT_64) {
2370 outs() << " vmaddr " << format("0x%016" PRIx64, vmaddr) << "\n";
2371 outs() << " vmsize " << format("0x%016" PRIx64, vmsize) << "\n";
2373 outs() << " vmaddr " << format("0x%08" PRIx32, vmaddr) << "\n";
2374 outs() << " vmsize " << format("0x%08" PRIx32, vmsize) << "\n";
2376 outs() << " fileoff " << fileoff;
2377 if (fileoff > object_size)
2378 outs() << " (past end of file)\n";
2381 outs() << " filesize " << filesize;
2382 if (fileoff + filesize > object_size)
2383 outs() << " (past end of file)\n";
2388 ~(MachO::VM_PROT_READ | MachO::VM_PROT_WRITE |
2389 MachO::VM_PROT_EXECUTE)) != 0)
2390 outs() << " maxprot ?" << format("0x%08" PRIx32, maxprot) << "\n";
2392 if (maxprot & MachO::VM_PROT_READ)
2393 outs() << " maxprot r";
2395 outs() << " maxprot -";
2396 if (maxprot & MachO::VM_PROT_WRITE)
2400 if (maxprot & MachO::VM_PROT_EXECUTE)
2406 ~(MachO::VM_PROT_READ | MachO::VM_PROT_WRITE |
2407 MachO::VM_PROT_EXECUTE)) != 0)
2408 outs() << " initprot ?" << format("0x%08" PRIx32, initprot) << "\n";
2410 if (initprot & MachO::VM_PROT_READ)
2411 outs() << " initprot r";
2413 outs() << " initprot -";
2414 if (initprot & MachO::VM_PROT_WRITE)
2418 if (initprot & MachO::VM_PROT_EXECUTE)
2424 outs() << " maxprot " << format("0x%08" PRIx32, maxprot) << "\n";
2425 outs() << " initprot " << format("0x%08" PRIx32, initprot) << "\n";
2427 outs() << " nsects " << nsects << "\n";
2431 outs() << " (none)\n";
2433 if (flags & MachO::SG_HIGHVM) {
2434 outs() << " HIGHVM";
2435 flags &= ~MachO::SG_HIGHVM;
2437 if (flags & MachO::SG_FVMLIB) {
2438 outs() << " FVMLIB";
2439 flags &= ~MachO::SG_FVMLIB;
2441 if (flags & MachO::SG_NORELOC) {
2442 outs() << " NORELOC";
2443 flags &= ~MachO::SG_NORELOC;
2445 if (flags & MachO::SG_PROTECTED_VERSION_1) {
2446 outs() << " PROTECTED_VERSION_1";
2447 flags &= ~MachO::SG_PROTECTED_VERSION_1;
2450 outs() << format(" 0x%08" PRIx32, flags) << " (unknown flags)\n";
2455 outs() << " flags " << format("0x%" PRIx32, flags) << "\n";
2459 static void PrintSection(const char *sectname, const char *segname,
2460 uint64_t addr, uint64_t size, uint32_t offset,
2461 uint32_t align, uint32_t reloff, uint32_t nreloc,
2462 uint32_t flags, uint32_t reserved1, uint32_t reserved2,
2463 uint32_t cmd, const char *sg_segname,
2464 uint32_t filetype, uint32_t object_size,
2466 outs() << "Section\n";
2467 outs() << " sectname " << format("%.16s\n", sectname);
2468 outs() << " segname " << format("%.16s", segname);
2469 if (filetype != MachO::MH_OBJECT && strncmp(sg_segname, segname, 16) != 0)
2470 outs() << " (does not match segment)\n";
2473 if (cmd == MachO::LC_SEGMENT_64) {
2474 outs() << " addr " << format("0x%016" PRIx64, addr) << "\n";
2475 outs() << " size " << format("0x%016" PRIx64, size);
2477 outs() << " addr " << format("0x%08" PRIx32, addr) << "\n";
2478 outs() << " size " << format("0x%08" PRIx32, size);
2480 if ((flags & MachO::S_ZEROFILL) != 0 && offset + size > object_size)
2481 outs() << " (past end of file)\n";
2484 outs() << " offset " << offset;
2485 if (offset > object_size)
2486 outs() << " (past end of file)\n";
2489 uint32_t align_shifted = 1 << align;
2490 outs() << " align 2^" << align << " (" << align_shifted << ")\n";
2491 outs() << " reloff " << reloff;
2492 if (reloff > object_size)
2493 outs() << " (past end of file)\n";
2496 outs() << " nreloc " << nreloc;
2497 if (reloff + nreloc * sizeof(struct MachO::relocation_info) > object_size)
2498 outs() << " (past end of file)\n";
2501 uint32_t section_type = flags & MachO::SECTION_TYPE;
2504 if (section_type == MachO::S_REGULAR)
2505 outs() << " S_REGULAR\n";
2506 else if (section_type == MachO::S_ZEROFILL)
2507 outs() << " S_ZEROFILL\n";
2508 else if (section_type == MachO::S_CSTRING_LITERALS)
2509 outs() << " S_CSTRING_LITERALS\n";
2510 else if (section_type == MachO::S_4BYTE_LITERALS)
2511 outs() << " S_4BYTE_LITERALS\n";
2512 else if (section_type == MachO::S_8BYTE_LITERALS)
2513 outs() << " S_8BYTE_LITERALS\n";
2514 else if (section_type == MachO::S_16BYTE_LITERALS)
2515 outs() << " S_16BYTE_LITERALS\n";
2516 else if (section_type == MachO::S_LITERAL_POINTERS)
2517 outs() << " S_LITERAL_POINTERS\n";
2518 else if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS)
2519 outs() << " S_NON_LAZY_SYMBOL_POINTERS\n";
2520 else if (section_type == MachO::S_LAZY_SYMBOL_POINTERS)
2521 outs() << " S_LAZY_SYMBOL_POINTERS\n";
2522 else if (section_type == MachO::S_SYMBOL_STUBS)
2523 outs() << " S_SYMBOL_STUBS\n";
2524 else if (section_type == MachO::S_MOD_INIT_FUNC_POINTERS)
2525 outs() << " S_MOD_INIT_FUNC_POINTERS\n";
2526 else if (section_type == MachO::S_MOD_TERM_FUNC_POINTERS)
2527 outs() << " S_MOD_TERM_FUNC_POINTERS\n";
2528 else if (section_type == MachO::S_COALESCED)
2529 outs() << " S_COALESCED\n";
2530 else if (section_type == MachO::S_INTERPOSING)
2531 outs() << " S_INTERPOSING\n";
2532 else if (section_type == MachO::S_DTRACE_DOF)
2533 outs() << " S_DTRACE_DOF\n";
2534 else if (section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS)
2535 outs() << " S_LAZY_DYLIB_SYMBOL_POINTERS\n";
2536 else if (section_type == MachO::S_THREAD_LOCAL_REGULAR)
2537 outs() << " S_THREAD_LOCAL_REGULAR\n";
2538 else if (section_type == MachO::S_THREAD_LOCAL_ZEROFILL)
2539 outs() << " S_THREAD_LOCAL_ZEROFILL\n";
2540 else if (section_type == MachO::S_THREAD_LOCAL_VARIABLES)
2541 outs() << " S_THREAD_LOCAL_VARIABLES\n";
2542 else if (section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS)
2543 outs() << " S_THREAD_LOCAL_VARIABLE_POINTERS\n";
2544 else if (section_type == MachO::S_THREAD_LOCAL_INIT_FUNCTION_POINTERS)
2545 outs() << " S_THREAD_LOCAL_INIT_FUNCTION_POINTERS\n";
2547 outs() << format("0x%08" PRIx32, section_type) << "\n";
2548 outs() << "attributes";
2549 uint32_t section_attributes = flags & MachO::SECTION_ATTRIBUTES;
2550 if (section_attributes & MachO::S_ATTR_PURE_INSTRUCTIONS)
2551 outs() << " PURE_INSTRUCTIONS";
2552 if (section_attributes & MachO::S_ATTR_NO_TOC)
2553 outs() << " NO_TOC";
2554 if (section_attributes & MachO::S_ATTR_STRIP_STATIC_SYMS)
2555 outs() << " STRIP_STATIC_SYMS";
2556 if (section_attributes & MachO::S_ATTR_NO_DEAD_STRIP)
2557 outs() << " NO_DEAD_STRIP";
2558 if (section_attributes & MachO::S_ATTR_LIVE_SUPPORT)
2559 outs() << " LIVE_SUPPORT";
2560 if (section_attributes & MachO::S_ATTR_SELF_MODIFYING_CODE)
2561 outs() << " SELF_MODIFYING_CODE";
2562 if (section_attributes & MachO::S_ATTR_DEBUG)
2564 if (section_attributes & MachO::S_ATTR_SOME_INSTRUCTIONS)
2565 outs() << " SOME_INSTRUCTIONS";
2566 if (section_attributes & MachO::S_ATTR_EXT_RELOC)
2567 outs() << " EXT_RELOC";
2568 if (section_attributes & MachO::S_ATTR_LOC_RELOC)
2569 outs() << " LOC_RELOC";
2570 if (section_attributes == 0)
2571 outs() << " (none)";
2574 outs() << " flags " << format("0x%08" PRIx32, flags) << "\n";
2575 outs() << " reserved1 " << reserved1;
2576 if (section_type == MachO::S_SYMBOL_STUBS ||
2577 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
2578 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
2579 section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
2580 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS)
2581 outs() << " (index into indirect symbol table)\n";
2584 outs() << " reserved2 " << reserved2;
2585 if (section_type == MachO::S_SYMBOL_STUBS)
2586 outs() << " (size of stubs)\n";
2591 static void PrintSymtabLoadCommand(MachO::symtab_command st, uint32_t cputype,
2592 uint32_t object_size) {
2593 outs() << " cmd LC_SYMTAB\n";
2594 outs() << " cmdsize " << st.cmdsize;
2595 if (st.cmdsize != sizeof(struct MachO::symtab_command))
2596 outs() << " Incorrect size\n";
2599 outs() << " symoff " << st.symoff;
2600 if (st.symoff > object_size)
2601 outs() << " (past end of file)\n";
2604 outs() << " nsyms " << st.nsyms;
2606 if (cputype & MachO::CPU_ARCH_ABI64) {
2607 big_size = st.nsyms;
2608 big_size *= sizeof(struct MachO::nlist_64);
2609 big_size += st.symoff;
2610 if (big_size > object_size)
2611 outs() << " (past end of file)\n";
2615 big_size = st.nsyms;
2616 big_size *= sizeof(struct MachO::nlist);
2617 big_size += st.symoff;
2618 if (big_size > object_size)
2619 outs() << " (past end of file)\n";
2623 outs() << " stroff " << st.stroff;
2624 if (st.stroff > object_size)
2625 outs() << " (past end of file)\n";
2628 outs() << " strsize " << st.strsize;
2629 big_size = st.stroff;
2630 big_size += st.strsize;
2631 if (big_size > object_size)
2632 outs() << " (past end of file)\n";
2637 static void PrintDysymtabLoadCommand(MachO::dysymtab_command dyst,
2638 uint32_t nsyms, uint32_t object_size,
2640 outs() << " cmd LC_DYSYMTAB\n";
2641 outs() << " cmdsize " << dyst.cmdsize;
2642 if (dyst.cmdsize != sizeof(struct MachO::dysymtab_command))
2643 outs() << " Incorrect size\n";
2646 outs() << " ilocalsym " << dyst.ilocalsym;
2647 if (dyst.ilocalsym > nsyms)
2648 outs() << " (greater than the number of symbols)\n";
2651 outs() << " nlocalsym " << dyst.nlocalsym;
2653 big_size = dyst.ilocalsym;
2654 big_size += dyst.nlocalsym;
2655 if (big_size > nsyms)
2656 outs() << " (past the end of the symbol table)\n";
2659 outs() << " iextdefsym " << dyst.iextdefsym;
2660 if (dyst.iextdefsym > nsyms)
2661 outs() << " (greater than the number of symbols)\n";
2664 outs() << " nextdefsym " << dyst.nextdefsym;
2665 big_size = dyst.iextdefsym;
2666 big_size += dyst.nextdefsym;
2667 if (big_size > nsyms)
2668 outs() << " (past the end of the symbol table)\n";
2671 outs() << " iundefsym " << dyst.iundefsym;
2672 if (dyst.iundefsym > nsyms)
2673 outs() << " (greater than the number of symbols)\n";
2676 outs() << " nundefsym " << dyst.nundefsym;
2677 big_size = dyst.iundefsym;
2678 big_size += dyst.nundefsym;
2679 if (big_size > nsyms)
2680 outs() << " (past the end of the symbol table)\n";
2683 outs() << " tocoff " << dyst.tocoff;
2684 if (dyst.tocoff > object_size)
2685 outs() << " (past end of file)\n";
2688 outs() << " ntoc " << dyst.ntoc;
2689 big_size = dyst.ntoc;
2690 big_size *= sizeof(struct MachO::dylib_table_of_contents);
2691 big_size += dyst.tocoff;
2692 if (big_size > object_size)
2693 outs() << " (past end of file)\n";
2696 outs() << " modtaboff " << dyst.modtaboff;
2697 if (dyst.modtaboff > object_size)
2698 outs() << " (past end of file)\n";
2701 outs() << " nmodtab " << dyst.nmodtab;
2703 if (cputype & MachO::CPU_ARCH_ABI64) {
2704 modtabend = dyst.nmodtab;
2705 modtabend *= sizeof(struct MachO::dylib_module_64);
2706 modtabend += dyst.modtaboff;
2708 modtabend = dyst.nmodtab;
2709 modtabend *= sizeof(struct MachO::dylib_module);
2710 modtabend += dyst.modtaboff;
2712 if (modtabend > object_size)
2713 outs() << " (past end of file)\n";
2716 outs() << " extrefsymoff " << dyst.extrefsymoff;
2717 if (dyst.extrefsymoff > object_size)
2718 outs() << " (past end of file)\n";
2721 outs() << " nextrefsyms " << dyst.nextrefsyms;
2722 big_size = dyst.nextrefsyms;
2723 big_size *= sizeof(struct MachO::dylib_reference);
2724 big_size += dyst.extrefsymoff;
2725 if (big_size > object_size)
2726 outs() << " (past end of file)\n";
2729 outs() << " indirectsymoff " << dyst.indirectsymoff;
2730 if (dyst.indirectsymoff > object_size)
2731 outs() << " (past end of file)\n";
2734 outs() << " nindirectsyms " << dyst.nindirectsyms;
2735 big_size = dyst.nindirectsyms;
2736 big_size *= sizeof(uint32_t);
2737 big_size += dyst.indirectsymoff;
2738 if (big_size > object_size)
2739 outs() << " (past end of file)\n";
2742 outs() << " extreloff " << dyst.extreloff;
2743 if (dyst.extreloff > object_size)
2744 outs() << " (past end of file)\n";
2747 outs() << " nextrel " << dyst.nextrel;
2748 big_size = dyst.nextrel;
2749 big_size *= sizeof(struct MachO::relocation_info);
2750 big_size += dyst.extreloff;
2751 if (big_size > object_size)
2752 outs() << " (past end of file)\n";
2755 outs() << " locreloff " << dyst.locreloff;
2756 if (dyst.locreloff > object_size)
2757 outs() << " (past end of file)\n";
2760 outs() << " nlocrel " << dyst.nlocrel;
2761 big_size = dyst.nlocrel;
2762 big_size *= sizeof(struct MachO::relocation_info);
2763 big_size += dyst.locreloff;
2764 if (big_size > object_size)
2765 outs() << " (past end of file)\n";
2770 static void PrintDyldInfoLoadCommand(MachO::dyld_info_command dc,
2771 uint32_t object_size) {
2772 if (dc.cmd == MachO::LC_DYLD_INFO)
2773 outs() << " cmd LC_DYLD_INFO\n";
2775 outs() << " cmd LC_DYLD_INFO_ONLY\n";
2776 outs() << " cmdsize " << dc.cmdsize;
2777 if (dc.cmdsize != sizeof(struct MachO::dyld_info_command))
2778 outs() << " Incorrect size\n";
2781 outs() << " rebase_off " << dc.rebase_off;
2782 if (dc.rebase_off > object_size)
2783 outs() << " (past end of file)\n";
2786 outs() << " rebase_size " << dc.rebase_size;
2788 big_size = dc.rebase_off;
2789 big_size += dc.rebase_size;
2790 if (big_size > object_size)
2791 outs() << " (past end of file)\n";
2794 outs() << " bind_off " << dc.bind_off;
2795 if (dc.bind_off > object_size)
2796 outs() << " (past end of file)\n";
2799 outs() << " bind_size " << dc.bind_size;
2800 big_size = dc.bind_off;
2801 big_size += dc.bind_size;
2802 if (big_size > object_size)
2803 outs() << " (past end of file)\n";
2806 outs() << " weak_bind_off " << dc.weak_bind_off;
2807 if (dc.weak_bind_off > object_size)
2808 outs() << " (past end of file)\n";
2811 outs() << " weak_bind_size " << dc.weak_bind_size;
2812 big_size = dc.weak_bind_off;
2813 big_size += dc.weak_bind_size;
2814 if (big_size > object_size)
2815 outs() << " (past end of file)\n";
2818 outs() << " lazy_bind_off " << dc.lazy_bind_off;
2819 if (dc.lazy_bind_off > object_size)
2820 outs() << " (past end of file)\n";
2823 outs() << " lazy_bind_size " << dc.lazy_bind_size;
2824 big_size = dc.lazy_bind_off;
2825 big_size += dc.lazy_bind_size;
2826 if (big_size > object_size)
2827 outs() << " (past end of file)\n";
2830 outs() << " export_off " << dc.export_off;
2831 if (dc.export_off > object_size)
2832 outs() << " (past end of file)\n";
2835 outs() << " export_size " << dc.export_size;
2836 big_size = dc.export_off;
2837 big_size += dc.export_size;
2838 if (big_size > object_size)
2839 outs() << " (past end of file)\n";
2844 static void PrintDyldLoadCommand(MachO::dylinker_command dyld,
2846 if (dyld.cmd == MachO::LC_ID_DYLINKER)
2847 outs() << " cmd LC_ID_DYLINKER\n";
2848 else if (dyld.cmd == MachO::LC_LOAD_DYLINKER)
2849 outs() << " cmd LC_LOAD_DYLINKER\n";
2850 else if (dyld.cmd == MachO::LC_DYLD_ENVIRONMENT)
2851 outs() << " cmd LC_DYLD_ENVIRONMENT\n";
2853 outs() << " cmd ?(" << dyld.cmd << ")\n";
2854 outs() << " cmdsize " << dyld.cmdsize;
2855 if (dyld.cmdsize < sizeof(struct MachO::dylinker_command))
2856 outs() << " Incorrect size\n";
2859 if (dyld.name >= dyld.cmdsize)
2860 outs() << " name ?(bad offset " << dyld.name << ")\n";
2862 const char *P = (const char *)(Ptr)+dyld.name;
2863 outs() << " name " << P << " (offset " << dyld.name << ")\n";
2867 static void PrintUuidLoadCommand(MachO::uuid_command uuid) {
2868 outs() << " cmd LC_UUID\n";
2869 outs() << " cmdsize " << uuid.cmdsize;
2870 if (uuid.cmdsize != sizeof(struct MachO::uuid_command))
2871 outs() << " Incorrect size\n";
2875 outs() << format("%02" PRIX32, uuid.uuid[0]);
2876 outs() << format("%02" PRIX32, uuid.uuid[1]);
2877 outs() << format("%02" PRIX32, uuid.uuid[2]);
2878 outs() << format("%02" PRIX32, uuid.uuid[3]);
2880 outs() << format("%02" PRIX32, uuid.uuid[4]);
2881 outs() << format("%02" PRIX32, uuid.uuid[5]);
2883 outs() << format("%02" PRIX32, uuid.uuid[6]);
2884 outs() << format("%02" PRIX32, uuid.uuid[7]);
2886 outs() << format("%02" PRIX32, uuid.uuid[8]);
2887 outs() << format("%02" PRIX32, uuid.uuid[9]);
2889 outs() << format("%02" PRIX32, uuid.uuid[10]);
2890 outs() << format("%02" PRIX32, uuid.uuid[11]);
2891 outs() << format("%02" PRIX32, uuid.uuid[12]);
2892 outs() << format("%02" PRIX32, uuid.uuid[13]);
2893 outs() << format("%02" PRIX32, uuid.uuid[14]);
2894 outs() << format("%02" PRIX32, uuid.uuid[15]);
2898 static void PrintVersionMinLoadCommand(MachO::version_min_command vd) {
2899 if (vd.cmd == MachO::LC_VERSION_MIN_MACOSX)
2900 outs() << " cmd LC_VERSION_MIN_MACOSX\n";
2901 else if (vd.cmd == MachO::LC_VERSION_MIN_IPHONEOS)
2902 outs() << " cmd LC_VERSION_MIN_IPHONEOS\n";
2904 outs() << " cmd " << vd.cmd << " (?)\n";
2905 outs() << " cmdsize " << vd.cmdsize;
2906 if (vd.cmdsize != sizeof(struct MachO::version_min_command))
2907 outs() << " Incorrect size\n";
2910 outs() << " version " << ((vd.version >> 16) & 0xffff) << "."
2911 << ((vd.version >> 8) & 0xff);
2912 if ((vd.version & 0xff) != 0)
2913 outs() << "." << (vd.version & 0xff);
2916 outs() << " sdk n/a\n";
2918 outs() << " sdk " << ((vd.sdk >> 16) & 0xffff) << "."
2919 << ((vd.sdk >> 8) & 0xff);
2921 if ((vd.sdk & 0xff) != 0)
2922 outs() << "." << (vd.sdk & 0xff);
2926 static void PrintSourceVersionCommand(MachO::source_version_command sd) {
2927 outs() << " cmd LC_SOURCE_VERSION\n";
2928 outs() << " cmdsize " << sd.cmdsize;
2929 if (sd.cmdsize != sizeof(struct MachO::source_version_command))
2930 outs() << " Incorrect size\n";
2933 uint64_t a = (sd.version >> 40) & 0xffffff;
2934 uint64_t b = (sd.version >> 30) & 0x3ff;
2935 uint64_t c = (sd.version >> 20) & 0x3ff;
2936 uint64_t d = (sd.version >> 10) & 0x3ff;
2937 uint64_t e = sd.version & 0x3ff;
2938 outs() << " version " << a << "." << b;
2940 outs() << "." << c << "." << d << "." << e;
2942 outs() << "." << c << "." << d;
2948 static void PrintEntryPointCommand(MachO::entry_point_command ep) {
2949 outs() << " cmd LC_MAIN\n";
2950 outs() << " cmdsize " << ep.cmdsize;
2951 if (ep.cmdsize != sizeof(struct MachO::entry_point_command))
2952 outs() << " Incorrect size\n";
2955 outs() << " entryoff " << ep.entryoff << "\n";
2956 outs() << " stacksize " << ep.stacksize << "\n";
2959 static void PrintDylibCommand(MachO::dylib_command dl, const char *Ptr) {
2960 if (dl.cmd == MachO::LC_ID_DYLIB)
2961 outs() << " cmd LC_ID_DYLIB\n";
2962 else if (dl.cmd == MachO::LC_LOAD_DYLIB)
2963 outs() << " cmd LC_LOAD_DYLIB\n";
2964 else if (dl.cmd == MachO::LC_LOAD_WEAK_DYLIB)
2965 outs() << " cmd LC_LOAD_WEAK_DYLIB\n";
2966 else if (dl.cmd == MachO::LC_REEXPORT_DYLIB)
2967 outs() << " cmd LC_REEXPORT_DYLIB\n";
2968 else if (dl.cmd == MachO::LC_LAZY_LOAD_DYLIB)
2969 outs() << " cmd LC_LAZY_LOAD_DYLIB\n";
2970 else if (dl.cmd == MachO::LC_LOAD_UPWARD_DYLIB)
2971 outs() << " cmd LC_LOAD_UPWARD_DYLIB\n";
2973 outs() << " cmd " << dl.cmd << " (unknown)\n";
2974 outs() << " cmdsize " << dl.cmdsize;
2975 if (dl.cmdsize < sizeof(struct MachO::dylib_command))
2976 outs() << " Incorrect size\n";
2979 if (dl.dylib.name < dl.cmdsize) {
2980 const char *P = (const char *)(Ptr)+dl.dylib.name;
2981 outs() << " name " << P << " (offset " << dl.dylib.name << ")\n";
2983 outs() << " name ?(bad offset " << dl.dylib.name << ")\n";
2985 outs() << " time stamp " << dl.dylib.timestamp << " ";
2986 time_t t = dl.dylib.timestamp;
2987 outs() << ctime(&t);
2988 outs() << " current version ";
2989 if (dl.dylib.current_version == 0xffffffff)
2992 outs() << ((dl.dylib.current_version >> 16) & 0xffff) << "."
2993 << ((dl.dylib.current_version >> 8) & 0xff) << "."
2994 << (dl.dylib.current_version & 0xff) << "\n";
2995 outs() << "compatibility version ";
2996 if (dl.dylib.compatibility_version == 0xffffffff)
2999 outs() << ((dl.dylib.compatibility_version >> 16) & 0xffff) << "."
3000 << ((dl.dylib.compatibility_version >> 8) & 0xff) << "."
3001 << (dl.dylib.compatibility_version & 0xff) << "\n";
3004 static void PrintLinkEditDataCommand(MachO::linkedit_data_command ld,
3005 uint32_t object_size) {
3006 if (ld.cmd == MachO::LC_CODE_SIGNATURE)
3007 outs() << " cmd LC_FUNCTION_STARTS\n";
3008 else if (ld.cmd == MachO::LC_SEGMENT_SPLIT_INFO)
3009 outs() << " cmd LC_SEGMENT_SPLIT_INFO\n";
3010 else if (ld.cmd == MachO::LC_FUNCTION_STARTS)
3011 outs() << " cmd LC_FUNCTION_STARTS\n";
3012 else if (ld.cmd == MachO::LC_DATA_IN_CODE)
3013 outs() << " cmd LC_DATA_IN_CODE\n";
3014 else if (ld.cmd == MachO::LC_DYLIB_CODE_SIGN_DRS)
3015 outs() << " cmd LC_DYLIB_CODE_SIGN_DRS\n";
3016 else if (ld.cmd == MachO::LC_LINKER_OPTIMIZATION_HINT)
3017 outs() << " cmd LC_LINKER_OPTIMIZATION_HINT\n";
3019 outs() << " cmd " << ld.cmd << " (?)\n";
3020 outs() << " cmdsize " << ld.cmdsize;
3021 if (ld.cmdsize != sizeof(struct MachO::linkedit_data_command))
3022 outs() << " Incorrect size\n";
3025 outs() << " dataoff " << ld.dataoff;
3026 if (ld.dataoff > object_size)
3027 outs() << " (past end of file)\n";
3030 outs() << " datasize " << ld.datasize;
3031 uint64_t big_size = ld.dataoff;
3032 big_size += ld.datasize;
3033 if (big_size > object_size)
3034 outs() << " (past end of file)\n";
3039 static void PrintLoadCommands(const MachOObjectFile *Obj, uint32_t ncmds,
3040 uint32_t filetype, uint32_t cputype,
3042 StringRef Buf = Obj->getData();
3043 MachOObjectFile::LoadCommandInfo Command = Obj->getFirstLoadCommandInfo();
3044 for (unsigned i = 0;; ++i) {
3045 outs() << "Load command " << i << "\n";
3046 if (Command.C.cmd == MachO::LC_SEGMENT) {
3047 MachO::segment_command SLC = Obj->getSegmentLoadCommand(Command);
3048 const char *sg_segname = SLC.segname;
3049 PrintSegmentCommand(SLC.cmd, SLC.cmdsize, SLC.segname, SLC.vmaddr,
3050 SLC.vmsize, SLC.fileoff, SLC.filesize, SLC.maxprot,
3051 SLC.initprot, SLC.nsects, SLC.flags, Buf.size(),
3053 for (unsigned j = 0; j < SLC.nsects; j++) {
3054 MachO::section_64 S = Obj->getSection64(Command, j);
3055 PrintSection(S.sectname, S.segname, S.addr, S.size, S.offset, S.align,
3056 S.reloff, S.nreloc, S.flags, S.reserved1, S.reserved2,
3057 SLC.cmd, sg_segname, filetype, Buf.size(), verbose);
3059 } else if (Command.C.cmd == MachO::LC_SEGMENT_64) {
3060 MachO::segment_command_64 SLC_64 = Obj->getSegment64LoadCommand(Command);
3061 const char *sg_segname = SLC_64.segname;
3062 PrintSegmentCommand(SLC_64.cmd, SLC_64.cmdsize, SLC_64.segname,
3063 SLC_64.vmaddr, SLC_64.vmsize, SLC_64.fileoff,
3064 SLC_64.filesize, SLC_64.maxprot, SLC_64.initprot,
3065 SLC_64.nsects, SLC_64.flags, Buf.size(), verbose);
3066 for (unsigned j = 0; j < SLC_64.nsects; j++) {
3067 MachO::section_64 S_64 = Obj->getSection64(Command, j);
3068 PrintSection(S_64.sectname, S_64.segname, S_64.addr, S_64.size,
3069 S_64.offset, S_64.align, S_64.reloff, S_64.nreloc,
3070 S_64.flags, S_64.reserved1, S_64.reserved2, SLC_64.cmd,
3071 sg_segname, filetype, Buf.size(), verbose);
3073 } else if (Command.C.cmd == MachO::LC_SYMTAB) {
3074 MachO::symtab_command Symtab = Obj->getSymtabLoadCommand();
3075 PrintSymtabLoadCommand(Symtab, cputype, Buf.size());
3076 } else if (Command.C.cmd == MachO::LC_DYSYMTAB) {
3077 MachO::dysymtab_command Dysymtab = Obj->getDysymtabLoadCommand();
3078 MachO::symtab_command Symtab = Obj->getSymtabLoadCommand();
3079 PrintDysymtabLoadCommand(Dysymtab, Symtab.nsyms, Buf.size(), cputype);
3080 } else if (Command.C.cmd == MachO::LC_DYLD_INFO ||
3081 Command.C.cmd == MachO::LC_DYLD_INFO_ONLY) {
3082 MachO::dyld_info_command DyldInfo = Obj->getDyldInfoLoadCommand(Command);
3083 PrintDyldInfoLoadCommand(DyldInfo, Buf.size());
3084 } else if (Command.C.cmd == MachO::LC_LOAD_DYLINKER ||
3085 Command.C.cmd == MachO::LC_ID_DYLINKER ||
3086 Command.C.cmd == MachO::LC_DYLD_ENVIRONMENT) {
3087 MachO::dylinker_command Dyld = Obj->getDylinkerCommand(Command);
3088 PrintDyldLoadCommand(Dyld, Command.Ptr);
3089 } else if (Command.C.cmd == MachO::LC_UUID) {
3090 MachO::uuid_command Uuid = Obj->getUuidCommand(Command);
3091 PrintUuidLoadCommand(Uuid);
3092 } else if (Command.C.cmd == MachO::LC_VERSION_MIN_MACOSX) {
3093 MachO::version_min_command Vd = Obj->getVersionMinLoadCommand(Command);
3094 PrintVersionMinLoadCommand(Vd);
3095 } else if (Command.C.cmd == MachO::LC_SOURCE_VERSION) {
3096 MachO::source_version_command Sd = Obj->getSourceVersionCommand(Command);
3097 PrintSourceVersionCommand(Sd);
3098 } else if (Command.C.cmd == MachO::LC_MAIN) {
3099 MachO::entry_point_command Ep = Obj->getEntryPointCommand(Command);
3100 PrintEntryPointCommand(Ep);
3101 } else if (Command.C.cmd == MachO::LC_LOAD_DYLIB ||
3102 Command.C.cmd == MachO::LC_ID_DYLIB ||
3103 Command.C.cmd == MachO::LC_LOAD_WEAK_DYLIB ||
3104 Command.C.cmd == MachO::LC_REEXPORT_DYLIB ||
3105 Command.C.cmd == MachO::LC_LAZY_LOAD_DYLIB ||
3106 Command.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB) {
3107 MachO::dylib_command Dl = Obj->getDylibIDLoadCommand(Command);
3108 PrintDylibCommand(Dl, Command.Ptr);
3109 } else if (Command.C.cmd == MachO::LC_CODE_SIGNATURE ||
3110 Command.C.cmd == MachO::LC_SEGMENT_SPLIT_INFO ||
3111 Command.C.cmd == MachO::LC_FUNCTION_STARTS ||
3112 Command.C.cmd == MachO::LC_DATA_IN_CODE ||
3113 Command.C.cmd == MachO::LC_DYLIB_CODE_SIGN_DRS ||
3114 Command.C.cmd == MachO::LC_LINKER_OPTIMIZATION_HINT) {
3115 MachO::linkedit_data_command Ld =
3116 Obj->getLinkeditDataLoadCommand(Command);
3117 PrintLinkEditDataCommand(Ld, Buf.size());
3119 outs() << " cmd ?(" << format("0x%08" PRIx32, Command.C.cmd)
3121 outs() << " cmdsize " << Command.C.cmdsize << "\n";
3122 // TODO: get and print the raw bytes of the load command.
3124 // TODO: print all the other kinds of load commands.
3128 Command = Obj->getNextLoadCommandInfo(Command);
3132 static void getAndPrintMachHeader(const MachOObjectFile *Obj, uint32_t &ncmds,
3133 uint32_t &filetype, uint32_t &cputype,
3135 if (Obj->is64Bit()) {
3136 MachO::mach_header_64 H_64;
3137 H_64 = Obj->getHeader64();
3138 PrintMachHeader(H_64.magic, H_64.cputype, H_64.cpusubtype, H_64.filetype,
3139 H_64.ncmds, H_64.sizeofcmds, H_64.flags, verbose);
3141 filetype = H_64.filetype;
3142 cputype = H_64.cputype;
3144 MachO::mach_header H;
3145 H = Obj->getHeader();
3146 PrintMachHeader(H.magic, H.cputype, H.cpusubtype, H.filetype, H.ncmds,
3147 H.sizeofcmds, H.flags, verbose);
3149 filetype = H.filetype;
3150 cputype = H.cputype;
3154 void llvm::printMachOFileHeader(const object::ObjectFile *Obj) {
3155 const MachOObjectFile *file = dyn_cast<const MachOObjectFile>(Obj);
3157 uint32_t filetype = 0;
3158 uint32_t cputype = 0;
3159 getAndPrintMachHeader(file, ncmds, filetype, cputype, true);
3160 PrintLoadCommands(file, ncmds, filetype, cputype, true);
3163 //===----------------------------------------------------------------------===//
3164 // export trie dumping
3165 //===----------------------------------------------------------------------===//
3167 void llvm::printMachOExportsTrie(const object::MachOObjectFile *Obj) {
3168 for (const llvm::object::ExportEntry &Entry : Obj->exports()) {
3169 uint64_t Flags = Entry.flags();
3170 bool ReExport = (Flags & MachO::EXPORT_SYMBOL_FLAGS_REEXPORT);
3171 bool WeakDef = (Flags & MachO::EXPORT_SYMBOL_FLAGS_WEAK_DEFINITION);
3172 bool ThreadLocal = ((Flags & MachO::EXPORT_SYMBOL_FLAGS_KIND_MASK) ==
3173 MachO::EXPORT_SYMBOL_FLAGS_KIND_THREAD_LOCAL);
3174 bool Abs = ((Flags & MachO::EXPORT_SYMBOL_FLAGS_KIND_MASK) ==
3175 MachO::EXPORT_SYMBOL_FLAGS_KIND_ABSOLUTE);
3176 bool Resolver = (Flags & MachO::EXPORT_SYMBOL_FLAGS_STUB_AND_RESOLVER);
3178 outs() << "[re-export] ";
3181 << format("0x%08llX ", Entry.address()); // FIXME:add in base address
3182 outs() << Entry.name();
3183 if (WeakDef || ThreadLocal || Resolver || Abs) {
3184 bool NeedsComma = false;
3187 outs() << "weak_def";
3193 outs() << "per-thread";
3199 outs() << "absolute";
3205 outs() << format("resolver=0x%08llX", Entry.other());
3211 StringRef DylibName = "unknown";
3212 int Ordinal = Entry.other() - 1;
3213 Obj->getLibraryShortNameByIndex(Ordinal, DylibName);
3214 if (Entry.otherName().empty())
3215 outs() << " (from " << DylibName << ")";
3217 outs() << " (" << Entry.otherName() << " from " << DylibName << ")";
3224 //===----------------------------------------------------------------------===//
3225 // rebase table dumping
3226 //===----------------------------------------------------------------------===//
3231 SegInfo(const object::MachOObjectFile *Obj);
3233 StringRef segmentName(uint32_t SegIndex);
3234 StringRef sectionName(uint32_t SegIndex, uint64_t SegOffset);
3235 uint64_t address(uint32_t SegIndex, uint64_t SegOffset);
3238 struct SectionInfo {
3241 StringRef SectionName;
3242 StringRef SegmentName;
3243 uint64_t OffsetInSegment;
3244 uint64_t SegmentStartAddress;
3245 uint32_t SegmentIndex;
3247 const SectionInfo &findSection(uint32_t SegIndex, uint64_t SegOffset);
3248 SmallVector<SectionInfo, 32> Sections;
3252 SegInfo::SegInfo(const object::MachOObjectFile *Obj) {
3253 // Build table of sections so segIndex/offset pairs can be translated.
3254 uint32_t CurSegIndex = Obj->hasPageZeroSegment() ? 1 : 0;
3255 StringRef CurSegName;
3256 uint64_t CurSegAddress;
3257 for (const SectionRef &Section : Obj->sections()) {
3259 if (error(Section.getName(Info.SectionName)))
3261 Info.Address = Section.getAddress();
3262 Info.Size = Section.getSize();
3264 Obj->getSectionFinalSegmentName(Section.getRawDataRefImpl());
3265 if (!Info.SegmentName.equals(CurSegName)) {
3267 CurSegName = Info.SegmentName;
3268 CurSegAddress = Info.Address;
3270 Info.SegmentIndex = CurSegIndex - 1;
3271 Info.OffsetInSegment = Info.Address - CurSegAddress;
3272 Info.SegmentStartAddress = CurSegAddress;
3273 Sections.push_back(Info);
3277 StringRef SegInfo::segmentName(uint32_t SegIndex) {
3278 for (const SectionInfo &SI : Sections) {
3279 if (SI.SegmentIndex == SegIndex)
3280 return SI.SegmentName;
3282 llvm_unreachable("invalid segIndex");
3285 const SegInfo::SectionInfo &SegInfo::findSection(uint32_t SegIndex,
3286 uint64_t OffsetInSeg) {
3287 for (const SectionInfo &SI : Sections) {
3288 if (SI.SegmentIndex != SegIndex)
3290 if (SI.OffsetInSegment > OffsetInSeg)
3292 if (OffsetInSeg >= (SI.OffsetInSegment + SI.Size))
3296 llvm_unreachable("segIndex and offset not in any section");
3299 StringRef SegInfo::sectionName(uint32_t SegIndex, uint64_t OffsetInSeg) {
3300 return findSection(SegIndex, OffsetInSeg).SectionName;
3303 uint64_t SegInfo::address(uint32_t SegIndex, uint64_t OffsetInSeg) {
3304 const SectionInfo &SI = findSection(SegIndex, OffsetInSeg);
3305 return SI.SegmentStartAddress + OffsetInSeg;
3308 void llvm::printMachORebaseTable(const object::MachOObjectFile *Obj) {
3309 // Build table of sections so names can used in final output.
3310 SegInfo sectionTable(Obj);
3312 outs() << "segment section address type\n";
3313 for (const llvm::object::MachORebaseEntry &Entry : Obj->rebaseTable()) {
3314 uint32_t SegIndex = Entry.segmentIndex();
3315 uint64_t OffsetInSeg = Entry.segmentOffset();
3316 StringRef SegmentName = sectionTable.segmentName(SegIndex);
3317 StringRef SectionName = sectionTable.sectionName(SegIndex, OffsetInSeg);
3318 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
3320 // Table lines look like: __DATA __nl_symbol_ptr 0x0000F00C pointer
3321 outs() << format("%-8s %-18s 0x%08" PRIX64 " %s\n",
3322 SegmentName.str().c_str(),
3323 SectionName.str().c_str(), Address,
3324 Entry.typeName().str().c_str());
3328 static StringRef ordinalName(const object::MachOObjectFile *Obj, int Ordinal) {
3329 StringRef DylibName;
3331 case MachO::BIND_SPECIAL_DYLIB_SELF:
3332 return "this-image";
3333 case MachO::BIND_SPECIAL_DYLIB_MAIN_EXECUTABLE:
3334 return "main-executable";
3335 case MachO::BIND_SPECIAL_DYLIB_FLAT_LOOKUP:
3336 return "flat-namespace";
3339 std::error_code EC = Obj->getLibraryShortNameByIndex(Ordinal-1,
3342 return "<<bad library ordinal>>";
3346 return "<<unknown special ordinal>>";
3349 //===----------------------------------------------------------------------===//
3350 // bind table dumping
3351 //===----------------------------------------------------------------------===//
3353 void llvm::printMachOBindTable(const object::MachOObjectFile *Obj) {
3354 // Build table of sections so names can used in final output.
3355 SegInfo sectionTable(Obj);
3357 outs() << "segment section address type "
3358 "addend dylib symbol\n";
3359 for (const llvm::object::MachOBindEntry &Entry : Obj->bindTable()) {
3360 uint32_t SegIndex = Entry.segmentIndex();
3361 uint64_t OffsetInSeg = Entry.segmentOffset();
3362 StringRef SegmentName = sectionTable.segmentName(SegIndex);
3363 StringRef SectionName = sectionTable.sectionName(SegIndex, OffsetInSeg);
3364 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
3366 // Table lines look like:
3367 // __DATA __got 0x00012010 pointer 0 libSystem ___stack_chk_guard
3369 if (Entry.flags() & MachO::BIND_SYMBOL_FLAGS_WEAK_IMPORT)
3370 Attr = " (weak_import)";
3371 outs() << left_justify(SegmentName, 8) << " "
3372 << left_justify(SectionName, 18) << " "
3373 << format_hex(Address, 10, true) << " "
3374 << left_justify(Entry.typeName(), 8) << " "
3375 << format_decimal(Entry.addend(), 8) << " "
3376 << left_justify(ordinalName(Obj, Entry.ordinal()), 16) << " "
3377 << Entry.symbolName()
3382 //===----------------------------------------------------------------------===//
3383 // lazy bind table dumping
3384 //===----------------------------------------------------------------------===//
3386 void llvm::printMachOLazyBindTable(const object::MachOObjectFile *Obj) {
3387 // Build table of sections so names can used in final output.
3388 SegInfo sectionTable(Obj);
3390 outs() << "segment section address "
3392 for (const llvm::object::MachOBindEntry &Entry : Obj->lazyBindTable()) {
3393 uint32_t SegIndex = Entry.segmentIndex();
3394 uint64_t OffsetInSeg = Entry.segmentOffset();
3395 StringRef SegmentName = sectionTable.segmentName(SegIndex);
3396 StringRef SectionName = sectionTable.sectionName(SegIndex, OffsetInSeg);
3397 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
3399 // Table lines look like:
3400 // __DATA __got 0x00012010 libSystem ___stack_chk_guard
3401 outs() << left_justify(SegmentName, 8) << " "
3402 << left_justify(SectionName, 18) << " "
3403 << format_hex(Address, 10, true) << " "
3404 << left_justify(ordinalName(Obj, Entry.ordinal()), 16) << " "
3405 << Entry.symbolName() << "\n";
3410 //===----------------------------------------------------------------------===//
3411 // weak bind table dumping
3412 //===----------------------------------------------------------------------===//
3414 void llvm::printMachOWeakBindTable(const object::MachOObjectFile *Obj) {
3415 // Build table of sections so names can used in final output.
3416 SegInfo sectionTable(Obj);
3418 outs() << "segment section address "
3419 "type addend symbol\n";
3420 for (const llvm::object::MachOBindEntry &Entry : Obj->weakBindTable()) {
3421 // Strong symbols don't have a location to update.
3422 if (Entry.flags() & MachO::BIND_SYMBOL_FLAGS_NON_WEAK_DEFINITION) {
3423 outs() << " strong "
3424 << Entry.symbolName() << "\n";
3427 uint32_t SegIndex = Entry.segmentIndex();
3428 uint64_t OffsetInSeg = Entry.segmentOffset();
3429 StringRef SegmentName = sectionTable.segmentName(SegIndex);
3430 StringRef SectionName = sectionTable.sectionName(SegIndex, OffsetInSeg);
3431 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
3433 // Table lines look like:
3434 // __DATA __data 0x00001000 pointer 0 _foo
3435 outs() << left_justify(SegmentName, 8) << " "
3436 << left_justify(SectionName, 18) << " "
3437 << format_hex(Address, 10, true) << " "
3438 << left_justify(Entry.typeName(), 8) << " "
3439 << format_decimal(Entry.addend(), 8) << " "
3440 << Entry.symbolName() << "\n";
3444 // get_dyld_bind_info_symbolname() is used for disassembly and passed an
3445 // address, ReferenceValue, in the Mach-O file and looks in the dyld bind
3446 // information for that address. If the address is found its binding symbol
3447 // name is returned. If not nullptr is returned.
3448 static const char *get_dyld_bind_info_symbolname(uint64_t ReferenceValue,
3449 struct DisassembleInfo *info) {
3450 if (info->bindtable == nullptr) {
3451 info->bindtable = new (BindTable);
3452 SegInfo sectionTable(info->O);
3453 for (const llvm::object::MachOBindEntry &Entry : info->O->bindTable()) {
3454 uint32_t SegIndex = Entry.segmentIndex();
3455 uint64_t OffsetInSeg = Entry.segmentOffset();
3456 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
3457 const char *SymbolName = nullptr;
3458 StringRef name = Entry.symbolName();
3460 SymbolName = name.data();
3461 info->bindtable->push_back(std::make_pair(Address, SymbolName));
3464 for (bind_table_iterator BI = info->bindtable->begin(),
3465 BE = info->bindtable->end();
3467 uint64_t Address = BI->first;
3468 if (ReferenceValue == Address) {
3469 const char *SymbolName = BI->second;