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;
57 cl::desc("Print line information from debug info if available"));
59 static cl::opt<std::string> DSYMFile("dsym",
60 cl::desc("Use .dSYM file for debug info"));
62 static cl::opt<bool> FullLeadingAddr("full-leading-addr",
63 cl::desc("Print full leading address"));
66 PrintImmHex("print-imm-hex",
67 cl::desc("Use hex format for immediate values"));
69 static 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;
127 static bool compareDiceTableEntries(const DiceTableEntry i,
128 const DiceTableEntry j) {
129 return i.first == j.first;
132 static void DumpDataInCode(const char *bytes, uint64_t Size,
133 unsigned short Kind) {
137 case MachO::DICE_KIND_DATA:
140 Value = bytes[3] << 24 | bytes[2] << 16 | bytes[1] << 8 | bytes[0];
141 outs() << "\t.long " << Value;
144 Value = bytes[1] << 8 | bytes[0];
145 outs() << "\t.short " << Value;
149 outs() << "\t.byte " << Value;
152 outs() << "\t@ KIND_DATA\n";
154 case MachO::DICE_KIND_JUMP_TABLE8:
156 outs() << "\t.byte " << Value << "\t@ KIND_JUMP_TABLE8";
158 case MachO::DICE_KIND_JUMP_TABLE16:
159 Value = bytes[1] << 8 | bytes[0];
160 outs() << "\t.short " << Value << "\t@ KIND_JUMP_TABLE16";
162 case MachO::DICE_KIND_JUMP_TABLE32:
163 Value = bytes[3] << 24 | bytes[2] << 16 | bytes[1] << 8 | bytes[0];
164 outs() << "\t.long " << Value << "\t@ KIND_JUMP_TABLE32";
167 outs() << "\t@ data in code kind = " << Kind << "\n";
172 static void getSectionsAndSymbols(const MachO::mach_header Header,
173 MachOObjectFile *MachOObj,
174 std::vector<SectionRef> &Sections,
175 std::vector<SymbolRef> &Symbols,
176 SmallVectorImpl<uint64_t> &FoundFns,
177 uint64_t &BaseSegmentAddress) {
178 for (const SymbolRef &Symbol : MachOObj->symbols())
179 Symbols.push_back(Symbol);
181 for (const SectionRef &Section : MachOObj->sections()) {
183 Section.getName(SectName);
184 Sections.push_back(Section);
187 MachOObjectFile::LoadCommandInfo Command =
188 MachOObj->getFirstLoadCommandInfo();
189 bool BaseSegmentAddressSet = false;
190 for (unsigned i = 0;; ++i) {
191 if (Command.C.cmd == MachO::LC_FUNCTION_STARTS) {
192 // We found a function starts segment, parse the addresses for later
194 MachO::linkedit_data_command LLC =
195 MachOObj->getLinkeditDataLoadCommand(Command);
197 MachOObj->ReadULEB128s(LLC.dataoff, FoundFns);
198 } else if (Command.C.cmd == MachO::LC_SEGMENT) {
199 MachO::segment_command SLC = MachOObj->getSegmentLoadCommand(Command);
200 StringRef SegName = SLC.segname;
201 if (!BaseSegmentAddressSet && SegName != "__PAGEZERO") {
202 BaseSegmentAddressSet = true;
203 BaseSegmentAddress = SLC.vmaddr;
207 if (i == Header.ncmds - 1)
210 Command = MachOObj->getNextLoadCommandInfo(Command);
214 static void DisassembleInputMachO2(StringRef Filename,
215 MachOObjectFile *MachOOF);
217 void llvm::DisassembleInputMachO(StringRef Filename) {
218 ErrorOr<std::unique_ptr<MemoryBuffer>> BuffOrErr =
219 MemoryBuffer::getFileOrSTDIN(Filename);
220 if (std::error_code EC = BuffOrErr.getError()) {
221 errs() << "llvm-objdump: " << Filename << ": " << EC.message() << "\n";
224 std::unique_ptr<MemoryBuffer> Buff = std::move(BuffOrErr.get());
226 std::unique_ptr<MachOObjectFile> MachOOF = std::move(
227 ObjectFile::createMachOObjectFile(Buff.get()->getMemBufferRef()).get());
229 DisassembleInputMachO2(Filename, MachOOF.get());
232 typedef DenseMap<uint64_t, StringRef> SymbolAddressMap;
233 typedef std::pair<uint64_t, const char *> BindInfoEntry;
234 typedef std::vector<BindInfoEntry> BindTable;
235 typedef BindTable::iterator bind_table_iterator;
237 // The block of info used by the Symbolizer call backs.
238 struct DisassembleInfo {
242 SymbolAddressMap *AddrMap;
243 std::vector<SectionRef> *Sections;
244 const char *class_name;
245 const char *selector_name;
247 char *demangled_name;
248 BindTable *bindtable;
251 // SymbolizerGetOpInfo() is the operand information call back function.
252 // This is called to get the symbolic information for operand(s) of an
253 // instruction when it is being done. This routine does this from
254 // the relocation information, symbol table, etc. That block of information
255 // is a pointer to the struct DisassembleInfo that was passed when the
256 // disassembler context was created and passed to back to here when
257 // called back by the disassembler for instruction operands that could have
258 // relocation information. The address of the instruction containing operand is
259 // at the Pc parameter. The immediate value the operand has is passed in
260 // op_info->Value and is at Offset past the start of the instruction and has a
261 // byte Size of 1, 2 or 4. The symbolc information is returned in TagBuf is the
262 // LLVMOpInfo1 struct defined in the header "llvm-c/Disassembler.h" as symbol
263 // names and addends of the symbolic expression to add for the operand. The
264 // value of TagType is currently 1 (for the LLVMOpInfo1 struct). If symbolic
265 // information is returned then this function returns 1 else it returns 0.
266 int SymbolizerGetOpInfo(void *DisInfo, uint64_t Pc, uint64_t Offset,
267 uint64_t Size, int TagType, void *TagBuf) {
268 struct DisassembleInfo *info = (struct DisassembleInfo *)DisInfo;
269 struct LLVMOpInfo1 *op_info = (struct LLVMOpInfo1 *)TagBuf;
270 unsigned int value = op_info->Value;
272 // Make sure all fields returned are zero if we don't set them.
273 memset((void *)op_info, '\0', sizeof(struct LLVMOpInfo1));
274 op_info->Value = value;
276 // If the TagType is not the value 1 which it code knows about or if no
277 // verbose symbolic information is wanted then just return 0, indicating no
278 // information is being returned.
279 if (TagType != 1 || info->verbose == false)
282 unsigned int Arch = info->O->getArch();
283 if (Arch == Triple::x86) {
285 } else if (Arch == Triple::x86_64) {
286 if (Size != 1 && Size != 2 && Size != 4 && Size != 0)
288 // First search the section's relocation entries (if any) for an entry
289 // for this section offset.
290 uint64_t sect_addr = info->S.getAddress();
291 uint64_t sect_offset = (Pc + Offset) - sect_addr;
292 bool reloc_found = false;
294 MachO::any_relocation_info RE;
295 bool isExtern = false;
297 for (const RelocationRef &Reloc : info->S.relocations()) {
298 uint64_t RelocOffset;
299 Reloc.getOffset(RelocOffset);
300 if (RelocOffset == sect_offset) {
301 Rel = Reloc.getRawDataRefImpl();
302 RE = info->O->getRelocation(Rel);
303 // NOTE: Scattered relocations don't exist on x86_64.
304 isExtern = info->O->getPlainRelocationExternal(RE);
306 symbol_iterator RelocSym = Reloc.getSymbol();
313 if (reloc_found && isExtern) {
314 // The Value passed in will be adjusted by the Pc if the instruction
315 // adds the Pc. But for x86_64 external relocation entries the Value
316 // is the offset from the external symbol.
317 if (info->O->getAnyRelocationPCRel(RE))
318 op_info->Value -= Pc + Offset + Size;
320 Symbol.getName(SymName);
321 const char *name = SymName.data();
322 unsigned Type = info->O->getAnyRelocationType(RE);
323 if (Type == MachO::X86_64_RELOC_SUBTRACTOR) {
324 DataRefImpl RelNext = Rel;
325 info->O->moveRelocationNext(RelNext);
326 MachO::any_relocation_info RENext = info->O->getRelocation(RelNext);
327 unsigned TypeNext = info->O->getAnyRelocationType(RENext);
328 bool isExternNext = info->O->getPlainRelocationExternal(RENext);
329 unsigned SymbolNum = info->O->getPlainRelocationSymbolNum(RENext);
330 if (TypeNext == MachO::X86_64_RELOC_UNSIGNED && isExternNext) {
331 op_info->SubtractSymbol.Present = 1;
332 op_info->SubtractSymbol.Name = name;
333 symbol_iterator RelocSymNext = info->O->getSymbolByIndex(SymbolNum);
334 Symbol = *RelocSymNext;
335 StringRef SymNameNext;
336 Symbol.getName(SymNameNext);
337 name = SymNameNext.data();
340 // TODO: add the VariantKinds to op_info->VariantKind for relocation types
341 // like: X86_64_RELOC_TLV, X86_64_RELOC_GOT_LOAD and X86_64_RELOC_GOT.
342 op_info->AddSymbol.Present = 1;
343 op_info->AddSymbol.Name = name;
347 // Second search the external relocation entries of a fully linked image
348 // (if any) for an entry that matches this segment offset.
349 // uint64_t seg_offset = (Pc + Offset);
351 } else if (Arch == Triple::arm) {
353 } else if (Arch == Triple::aarch64) {
360 // GuessCstringPointer is passed the address of what might be a pointer to a
361 // literal string in a cstring section. If that address is in a cstring section
362 // it returns a pointer to that string. Else it returns nullptr.
363 const char *GuessCstringPointer(uint64_t ReferenceValue,
364 struct DisassembleInfo *info) {
365 uint32_t LoadCommandCount = info->O->getHeader().ncmds;
366 MachOObjectFile::LoadCommandInfo Load = info->O->getFirstLoadCommandInfo();
367 for (unsigned I = 0;; ++I) {
368 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
369 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
370 for (unsigned J = 0; J < Seg.nsects; ++J) {
371 MachO::section_64 Sec = info->O->getSection64(Load, J);
372 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
373 if (section_type == MachO::S_CSTRING_LITERALS &&
374 ReferenceValue >= Sec.addr &&
375 ReferenceValue < Sec.addr + Sec.size) {
376 uint64_t sect_offset = ReferenceValue - Sec.addr;
377 uint64_t object_offset = Sec.offset + sect_offset;
378 StringRef MachOContents = info->O->getData();
379 uint64_t object_size = MachOContents.size();
380 const char *object_addr = (const char *)MachOContents.data();
381 if (object_offset < object_size) {
382 const char *name = object_addr + object_offset;
389 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
390 MachO::segment_command Seg = info->O->getSegmentLoadCommand(Load);
391 for (unsigned J = 0; J < Seg.nsects; ++J) {
392 MachO::section Sec = info->O->getSection(Load, J);
393 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
394 if (section_type == MachO::S_CSTRING_LITERALS &&
395 ReferenceValue >= Sec.addr &&
396 ReferenceValue < Sec.addr + Sec.size) {
397 uint64_t sect_offset = ReferenceValue - Sec.addr;
398 uint64_t object_offset = Sec.offset + sect_offset;
399 StringRef MachOContents = info->O->getData();
400 uint64_t object_size = MachOContents.size();
401 const char *object_addr = (const char *)MachOContents.data();
402 if (object_offset < object_size) {
403 const char *name = object_addr + object_offset;
411 if (I == LoadCommandCount - 1)
414 Load = info->O->getNextLoadCommandInfo(Load);
419 // GuessIndirectSymbol returns the name of the indirect symbol for the
420 // ReferenceValue passed in or nullptr. This is used when ReferenceValue maybe
421 // an address of a symbol stub or a lazy or non-lazy pointer to associate the
422 // symbol name being referenced by the stub or pointer.
423 static const char *GuessIndirectSymbol(uint64_t ReferenceValue,
424 struct DisassembleInfo *info) {
425 uint32_t LoadCommandCount = info->O->getHeader().ncmds;
426 MachOObjectFile::LoadCommandInfo Load = info->O->getFirstLoadCommandInfo();
427 MachO::dysymtab_command Dysymtab = info->O->getDysymtabLoadCommand();
428 MachO::symtab_command Symtab = info->O->getSymtabLoadCommand();
429 for (unsigned I = 0;; ++I) {
430 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
431 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
432 for (unsigned J = 0; J < Seg.nsects; ++J) {
433 MachO::section_64 Sec = info->O->getSection64(Load, J);
434 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
435 if ((section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
436 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
437 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
438 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
439 section_type == MachO::S_SYMBOL_STUBS) &&
440 ReferenceValue >= Sec.addr &&
441 ReferenceValue < Sec.addr + Sec.size) {
443 if (section_type == MachO::S_SYMBOL_STUBS)
444 stride = Sec.reserved2;
449 uint32_t index = Sec.reserved1 + (ReferenceValue - Sec.addr) / stride;
450 if (index < Dysymtab.nindirectsyms) {
451 uint32_t indirect_symbol =
452 info->O->getIndirectSymbolTableEntry(Dysymtab, index);
453 if (indirect_symbol < Symtab.nsyms) {
454 symbol_iterator Sym = info->O->getSymbolByIndex(indirect_symbol);
455 SymbolRef Symbol = *Sym;
457 Symbol.getName(SymName);
458 const char *name = SymName.data();
464 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
465 MachO::segment_command Seg = info->O->getSegmentLoadCommand(Load);
466 for (unsigned J = 0; J < Seg.nsects; ++J) {
467 MachO::section Sec = info->O->getSection(Load, J);
468 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
469 if ((section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
470 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
471 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
472 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
473 section_type == MachO::S_SYMBOL_STUBS) &&
474 ReferenceValue >= Sec.addr &&
475 ReferenceValue < Sec.addr + Sec.size) {
477 if (section_type == MachO::S_SYMBOL_STUBS)
478 stride = Sec.reserved2;
483 uint32_t index = Sec.reserved1 + (ReferenceValue - Sec.addr) / stride;
484 if (index < Dysymtab.nindirectsyms) {
485 uint32_t indirect_symbol =
486 info->O->getIndirectSymbolTableEntry(Dysymtab, index);
487 if (indirect_symbol < Symtab.nsyms) {
488 symbol_iterator Sym = info->O->getSymbolByIndex(indirect_symbol);
489 SymbolRef Symbol = *Sym;
491 Symbol.getName(SymName);
492 const char *name = SymName.data();
499 if (I == LoadCommandCount - 1)
502 Load = info->O->getNextLoadCommandInfo(Load);
507 // method_reference() is called passing it the ReferenceName that might be
508 // a reference it to an Objective-C method call. If so then it allocates and
509 // assembles a method call string with the values last seen and saved in
510 // the DisassembleInfo's class_name and selector_name fields. This is saved
511 // into the method field of the info and any previous string is free'ed.
512 // Then the class_name field in the info is set to nullptr. The method call
513 // string is set into ReferenceName and ReferenceType is set to
514 // LLVMDisassembler_ReferenceType_Out_Objc_Message. If this not a method call
515 // then both ReferenceType and ReferenceName are left unchanged.
516 static void method_reference(struct DisassembleInfo *info,
517 uint64_t *ReferenceType,
518 const char **ReferenceName) {
519 if (*ReferenceName != nullptr) {
520 if (strcmp(*ReferenceName, "_objc_msgSend") == 0) {
521 if (info->selector_name != NULL) {
522 if (info->method != nullptr)
524 if (info->class_name != nullptr) {
525 info->method = (char *)malloc(5 + strlen(info->class_name) +
526 strlen(info->selector_name));
527 if (info->method != nullptr) {
528 strcpy(info->method, "+[");
529 strcat(info->method, info->class_name);
530 strcat(info->method, " ");
531 strcat(info->method, info->selector_name);
532 strcat(info->method, "]");
533 *ReferenceName = info->method;
534 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
537 info->method = (char *)malloc(9 + strlen(info->selector_name));
538 if (info->method != nullptr) {
539 strcpy(info->method, "-[%rdi ");
540 strcat(info->method, info->selector_name);
541 strcat(info->method, "]");
542 *ReferenceName = info->method;
543 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
546 info->class_name = nullptr;
548 } else if (strcmp(*ReferenceName, "_objc_msgSendSuper2") == 0) {
549 if (info->selector_name != NULL) {
550 if (info->method != nullptr)
552 info->method = (char *)malloc(17 + strlen(info->selector_name));
553 if (info->method != nullptr) {
554 strcpy(info->method, "-[[%rdi super] ");
555 strcat(info->method, info->selector_name);
556 strcat(info->method, "]");
557 *ReferenceName = info->method;
558 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
560 info->class_name = nullptr;
566 // GuessPointerPointer() is passed the address of what might be a pointer to
567 // a reference to an Objective-C class, selector, message ref or cfstring.
568 // If so the value of the pointer is returned and one of the booleans are set
569 // to true. If not zero is returned and all the booleans are set to false.
570 static uint64_t GuessPointerPointer(uint64_t ReferenceValue,
571 struct DisassembleInfo *info,
572 bool &classref, bool &selref, bool &msgref,
578 uint32_t LoadCommandCount = info->O->getHeader().ncmds;
579 MachOObjectFile::LoadCommandInfo Load = info->O->getFirstLoadCommandInfo();
580 for (unsigned I = 0;; ++I) {
581 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
582 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
583 for (unsigned J = 0; J < Seg.nsects; ++J) {
584 MachO::section_64 Sec = info->O->getSection64(Load, J);
585 if ((strncmp(Sec.sectname, "__objc_selrefs", 16) == 0 ||
586 strncmp(Sec.sectname, "__objc_classrefs", 16) == 0 ||
587 strncmp(Sec.sectname, "__objc_superrefs", 16) == 0 ||
588 strncmp(Sec.sectname, "__objc_msgrefs", 16) == 0 ||
589 strncmp(Sec.sectname, "__cfstring", 16) == 0) &&
590 ReferenceValue >= Sec.addr &&
591 ReferenceValue < Sec.addr + Sec.size) {
592 uint64_t sect_offset = ReferenceValue - Sec.addr;
593 uint64_t object_offset = Sec.offset + sect_offset;
594 StringRef MachOContents = info->O->getData();
595 uint64_t object_size = MachOContents.size();
596 const char *object_addr = (const char *)MachOContents.data();
597 if (object_offset < object_size) {
598 uint64_t pointer_value;
599 memcpy(&pointer_value, object_addr + object_offset,
601 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
602 sys::swapByteOrder(pointer_value);
603 if (strncmp(Sec.sectname, "__objc_selrefs", 16) == 0)
605 else if (strncmp(Sec.sectname, "__objc_classrefs", 16) == 0 ||
606 strncmp(Sec.sectname, "__objc_superrefs", 16) == 0)
608 else if (strncmp(Sec.sectname, "__objc_msgrefs", 16) == 0 &&
609 ReferenceValue + 8 < Sec.addr + Sec.size) {
611 memcpy(&pointer_value, object_addr + object_offset + 8,
613 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
614 sys::swapByteOrder(pointer_value);
615 } else if (strncmp(Sec.sectname, "__cfstring", 16) == 0)
617 return pointer_value;
624 // TODO: Look for LC_SEGMENT for 32-bit Mach-O files.
625 if (I == LoadCommandCount - 1)
628 Load = info->O->getNextLoadCommandInfo(Load);
633 // get_pointer_64 returns a pointer to the bytes in the object file at the
634 // Address from a section in the Mach-O file. And indirectly returns the
635 // offset into the section, number of bytes left in the section past the offset
636 // and which section is was being referenced. If the Address is not in a
637 // section nullptr is returned.
638 const char *get_pointer_64(uint64_t Address, uint32_t &offset, uint32_t &left,
639 SectionRef &S, DisassembleInfo *info) {
643 for (unsigned SectIdx = 0; SectIdx != info->Sections->size(); SectIdx++) {
644 uint64_t SectAddress = ((*(info->Sections))[SectIdx]).getAddress();
645 uint64_t SectSize = ((*(info->Sections))[SectIdx]).getSize();
646 if (Address >= SectAddress && Address < SectAddress + SectSize) {
647 S = (*(info->Sections))[SectIdx];
648 offset = Address - SectAddress;
649 left = SectSize - offset;
650 StringRef SectContents;
651 ((*(info->Sections))[SectIdx]).getContents(SectContents);
652 return SectContents.data() + offset;
658 // get_symbol_64() returns the name of a symbol (or nullptr) and the address of
659 // the symbol indirectly through n_value. Based on the relocation information
660 // for the specified section offset in the specified section reference.
661 const char *get_symbol_64(uint32_t sect_offset, SectionRef S,
662 DisassembleInfo *info, uint64_t &n_value) {
664 if (info->verbose == false)
667 // See if there is an external relocation entry at the sect_offset.
668 bool reloc_found = false;
670 MachO::any_relocation_info RE;
671 bool isExtern = false;
673 for (const RelocationRef &Reloc : S.relocations()) {
674 uint64_t RelocOffset;
675 Reloc.getOffset(RelocOffset);
676 if (RelocOffset == sect_offset) {
677 Rel = Reloc.getRawDataRefImpl();
678 RE = info->O->getRelocation(Rel);
679 if (info->O->isRelocationScattered(RE))
681 isExtern = info->O->getPlainRelocationExternal(RE);
683 symbol_iterator RelocSym = Reloc.getSymbol();
690 // If there is an external relocation entry for a symbol in this section
691 // at this section_offset then use that symbol's value for the n_value
692 // and return its name.
693 const char *SymbolName = nullptr;
694 if (reloc_found && isExtern) {
695 Symbol.getAddress(n_value);
697 Symbol.getName(name);
699 SymbolName = name.data();
704 // TODO: For fully linked images, look through the external relocation
705 // entries off the dynamic symtab command. For these the r_offset is from the
706 // start of the first writeable segment in the Mach-O file. So the offset
707 // to this section from that segment is passed to this routine by the caller,
708 // as the database_offset. Which is the difference of the section's starting
709 // address and the first writable segment.
711 // NOTE: need add passing the database_offset to this routine.
713 // TODO: We did not find an external relocation entry so look up the
714 // ReferenceValue as an address of a symbol and if found return that symbol's
717 // NOTE: need add passing the ReferenceValue to this routine. Then that code
718 // would simply be this:
720 // if (ReferenceValue != 0xffffffffffffffffLLU &&
721 // ReferenceValue != 0xfffffffffffffffeLLU) {
722 // StringRef name = info->AddrMap->lookup(ReferenceValue);
723 // if (!name.empty())
724 // SymbolName = name.data();
730 // These are structs in the Objective-C meta data and read to produce the
731 // comments for disassembly. While these are part of the ABI they are no
732 // public defintions. So the are here not in include/llvm/Support/MachO.h .
734 // The cfstring object in a 64-bit Mach-O file.
735 struct cfstring64_t {
736 uint64_t isa; // class64_t * (64-bit pointer)
737 uint64_t flags; // flag bits
738 uint64_t characters; // char * (64-bit pointer)
739 uint64_t length; // number of non-NULL characters in above
742 // The class object in a 64-bit Mach-O file.
744 uint64_t isa; // class64_t * (64-bit pointer)
745 uint64_t superclass; // class64_t * (64-bit pointer)
746 uint64_t cache; // Cache (64-bit pointer)
747 uint64_t vtable; // IMP * (64-bit pointer)
748 uint64_t data; // class_ro64_t * (64-bit pointer)
751 struct class_ro64_t {
753 uint32_t instanceStart;
754 uint32_t instanceSize;
756 uint64_t ivarLayout; // const uint8_t * (64-bit pointer)
757 uint64_t name; // const char * (64-bit pointer)
758 uint64_t baseMethods; // const method_list_t * (64-bit pointer)
759 uint64_t baseProtocols; // const protocol_list_t * (64-bit pointer)
760 uint64_t ivars; // const ivar_list_t * (64-bit pointer)
761 uint64_t weakIvarLayout; // const uint8_t * (64-bit pointer)
762 uint64_t baseProperties; // const struct objc_property_list (64-bit pointer)
765 inline void swapStruct(struct cfstring64_t &cfs) {
766 sys::swapByteOrder(cfs.isa);
767 sys::swapByteOrder(cfs.flags);
768 sys::swapByteOrder(cfs.characters);
769 sys::swapByteOrder(cfs.length);
772 inline void swapStruct(struct class64_t &c) {
773 sys::swapByteOrder(c.isa);
774 sys::swapByteOrder(c.superclass);
775 sys::swapByteOrder(c.cache);
776 sys::swapByteOrder(c.vtable);
777 sys::swapByteOrder(c.data);
780 inline void swapStruct(struct class_ro64_t &cro) {
781 sys::swapByteOrder(cro.flags);
782 sys::swapByteOrder(cro.instanceStart);
783 sys::swapByteOrder(cro.instanceSize);
784 sys::swapByteOrder(cro.reserved);
785 sys::swapByteOrder(cro.ivarLayout);
786 sys::swapByteOrder(cro.name);
787 sys::swapByteOrder(cro.baseMethods);
788 sys::swapByteOrder(cro.baseProtocols);
789 sys::swapByteOrder(cro.ivars);
790 sys::swapByteOrder(cro.weakIvarLayout);
791 sys::swapByteOrder(cro.baseProperties);
794 static const char *get_dyld_bind_info_symbolname(uint64_t ReferenceValue,
795 struct DisassembleInfo *info);
797 // get_objc2_64bit_class_name() is used for disassembly and is passed a pointer
798 // to an Objective-C class and returns the class name. It is also passed the
799 // address of the pointer, so when the pointer is zero as it can be in an .o
800 // file, that is used to look for an external relocation entry with a symbol
802 const char *get_objc2_64bit_class_name(uint64_t pointer_value,
803 uint64_t ReferenceValue,
804 struct DisassembleInfo *info) {
806 uint32_t offset, left;
809 // The pointer_value can be 0 in an object file and have a relocation
810 // entry for the class symbol at the ReferenceValue (the address of the
812 if (pointer_value == 0) {
813 r = get_pointer_64(ReferenceValue, offset, left, S, info);
814 if (r == nullptr || left < sizeof(uint64_t))
817 const char *symbol_name = get_symbol_64(offset, S, info, n_value);
818 if (symbol_name == nullptr)
820 const char *class_name = strrchr(symbol_name, '$');
821 if (class_name != nullptr && class_name[1] == '_' && class_name[2] != '\0')
822 return class_name + 2;
827 // The case were the pointer_value is non-zero and points to a class defined
828 // in this Mach-O file.
829 r = get_pointer_64(pointer_value, offset, left, S, info);
830 if (r == nullptr || left < sizeof(struct class64_t))
833 memcpy(&c, r, sizeof(struct class64_t));
834 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
838 r = get_pointer_64(c.data, offset, left, S, info);
839 if (r == nullptr || left < sizeof(struct class_ro64_t))
841 struct class_ro64_t cro;
842 memcpy(&cro, r, sizeof(struct class_ro64_t));
843 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
847 const char *name = get_pointer_64(cro.name, offset, left, S, info);
851 // get_objc2_64bit_cfstring_name is used for disassembly and is passed a
852 // pointer to a cfstring and returns its name or nullptr.
853 const char *get_objc2_64bit_cfstring_name(uint64_t ReferenceValue,
854 struct DisassembleInfo *info) {
855 const char *r, *name;
856 uint32_t offset, left;
858 struct cfstring64_t cfs;
859 uint64_t cfs_characters;
861 r = get_pointer_64(ReferenceValue, offset, left, S, info);
862 if (r == nullptr || left < sizeof(struct cfstring64_t))
864 memcpy(&cfs, r, sizeof(struct cfstring64_t));
865 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
867 if (cfs.characters == 0) {
869 const char *symbol_name = get_symbol_64(
870 offset + offsetof(struct cfstring64_t, characters), S, info, n_value);
871 if (symbol_name == nullptr)
873 cfs_characters = n_value;
875 cfs_characters = cfs.characters;
876 name = get_pointer_64(cfs_characters, offset, left, S, info);
881 // get_objc2_64bit_selref() is used for disassembly and is passed a the address
882 // of a pointer to an Objective-C selector reference when the pointer value is
883 // zero as in a .o file and is likely to have a external relocation entry with
884 // who's symbol's n_value is the real pointer to the selector name. If that is
885 // the case the real pointer to the selector name is returned else 0 is
887 uint64_t get_objc2_64bit_selref(uint64_t ReferenceValue,
888 struct DisassembleInfo *info) {
889 uint32_t offset, left;
892 const char *r = get_pointer_64(ReferenceValue, offset, left, S, info);
893 if (r == nullptr || left < sizeof(uint64_t))
896 const char *symbol_name = get_symbol_64(offset, S, info, n_value);
897 if (symbol_name == nullptr)
902 // GuessLiteralPointer returns a string which for the item in the Mach-O file
903 // for the address passed in as ReferenceValue for printing as a comment with
904 // the instruction and also returns the corresponding type of that item
905 // indirectly through ReferenceType.
907 // If ReferenceValue is an address of literal cstring then a pointer to the
908 // cstring is returned and ReferenceType is set to
909 // LLVMDisassembler_ReferenceType_Out_LitPool_CstrAddr .
911 // If ReferenceValue is an address of an Objective-C CFString, Selector ref or
912 // Class ref that name is returned and the ReferenceType is set accordingly.
914 // Lastly, literals which are Symbol address in a literal pool are looked for
915 // and if found the symbol name is returned and ReferenceType is set to
916 // LLVMDisassembler_ReferenceType_Out_LitPool_SymAddr .
918 // If there is no item in the Mach-O file for the address passed in as
919 // ReferenceValue nullptr is returned and ReferenceType is unchanged.
920 const char *GuessLiteralPointer(uint64_t ReferenceValue, uint64_t ReferencePC,
921 uint64_t *ReferenceType,
922 struct DisassembleInfo *info) {
923 // TODO: This rouine's code and the routines it calls are only work with
924 // x86_64 Mach-O files for now.
925 unsigned int Arch = info->O->getArch();
926 if (Arch != Triple::x86_64)
929 // First see if there is an external relocation entry at the ReferencePC.
930 uint64_t sect_addr = info->S.getAddress();
931 uint64_t sect_offset = ReferencePC - sect_addr;
932 bool reloc_found = false;
934 MachO::any_relocation_info RE;
935 bool isExtern = false;
937 for (const RelocationRef &Reloc : info->S.relocations()) {
938 uint64_t RelocOffset;
939 Reloc.getOffset(RelocOffset);
940 if (RelocOffset == sect_offset) {
941 Rel = Reloc.getRawDataRefImpl();
942 RE = info->O->getRelocation(Rel);
943 if (info->O->isRelocationScattered(RE))
945 isExtern = info->O->getPlainRelocationExternal(RE);
947 symbol_iterator RelocSym = Reloc.getSymbol();
954 // If there is an external relocation entry for a symbol in a section
955 // then used that symbol's value for the value of the reference.
956 if (reloc_found && isExtern) {
957 if (info->O->getAnyRelocationPCRel(RE)) {
958 unsigned Type = info->O->getAnyRelocationType(RE);
959 if (Type == MachO::X86_64_RELOC_SIGNED) {
960 Symbol.getAddress(ReferenceValue);
965 // Look for literals such as Objective-C CFStrings refs, Selector refs,
966 // Message refs and Class refs.
967 bool classref, selref, msgref, cfstring;
968 uint64_t pointer_value = GuessPointerPointer(ReferenceValue, info, classref,
969 selref, msgref, cfstring);
970 if (classref == true && pointer_value == 0) {
971 // Note the ReferenceValue is a pointer into the __objc_classrefs section.
972 // And the pointer_value in that section is typically zero as it will be
973 // set by dyld as part of the "bind information".
974 const char *name = get_dyld_bind_info_symbolname(ReferenceValue, info);
975 if (name != nullptr) {
976 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Class_Ref;
977 const char *class_name = strrchr(name, '$');
978 if (class_name != nullptr && class_name[1] == '_' &&
979 class_name[2] != '\0') {
980 info->class_name = class_name + 2;
986 if (classref == true) {
987 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Class_Ref;
989 get_objc2_64bit_class_name(pointer_value, ReferenceValue, info);
991 info->class_name = name;
993 name = "bad class ref";
997 if (cfstring == true) {
998 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_CFString_Ref;
999 const char *name = get_objc2_64bit_cfstring_name(ReferenceValue, info);
1003 if (selref == true && pointer_value == 0)
1004 pointer_value = get_objc2_64bit_selref(ReferenceValue, info);
1006 if (pointer_value != 0)
1007 ReferenceValue = pointer_value;
1009 const char *name = GuessCstringPointer(ReferenceValue, info);
1011 if (pointer_value != 0 && selref == true) {
1012 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Selector_Ref;
1013 info->selector_name = name;
1014 } else if (pointer_value != 0 && msgref == true) {
1015 info->class_name = nullptr;
1016 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message_Ref;
1017 info->selector_name = name;
1019 *ReferenceType = LLVMDisassembler_ReferenceType_Out_LitPool_CstrAddr;
1023 // Lastly look for an indirect symbol with this ReferenceValue which is in
1024 // a literal pool. If found return that symbol name.
1025 name = GuessIndirectSymbol(ReferenceValue, info);
1027 *ReferenceType = LLVMDisassembler_ReferenceType_Out_LitPool_SymAddr;
1034 // SymbolizerSymbolLookUp is the symbol lookup function passed when creating
1035 // the Symbolizer. It looks up the ReferenceValue using the info passed via the
1036 // pointer to the struct DisassembleInfo that was passed when MCSymbolizer
1037 // is created and returns the symbol name that matches the ReferenceValue or
1038 // nullptr if none. The ReferenceType is passed in for the IN type of
1039 // reference the instruction is making from the values in defined in the header
1040 // "llvm-c/Disassembler.h". On return the ReferenceType can set to a specific
1041 // Out type and the ReferenceName will also be set which is added as a comment
1042 // to the disassembled instruction.
1045 // If the symbol name is a C++ mangled name then the demangled name is
1046 // returned through ReferenceName and ReferenceType is set to
1047 // LLVMDisassembler_ReferenceType_DeMangled_Name .
1050 // When this is called to get a symbol name for a branch target then the
1051 // ReferenceType will be LLVMDisassembler_ReferenceType_In_Branch and then
1052 // SymbolValue will be looked for in the indirect symbol table to determine if
1053 // it is an address for a symbol stub. If so then the symbol name for that
1054 // stub is returned indirectly through ReferenceName and then ReferenceType is
1055 // set to LLVMDisassembler_ReferenceType_Out_SymbolStub.
1057 // When this is called with an value loaded via a PC relative load then
1058 // ReferenceType will be LLVMDisassembler_ReferenceType_In_PCrel_Load then the
1059 // SymbolValue is checked to be an address of literal pointer, symbol pointer,
1060 // or an Objective-C meta data reference. If so the output ReferenceType is
1061 // set to correspond to that as well as setting the ReferenceName.
1062 const char *SymbolizerSymbolLookUp(void *DisInfo, uint64_t ReferenceValue,
1063 uint64_t *ReferenceType,
1064 uint64_t ReferencePC,
1065 const char **ReferenceName) {
1066 struct DisassembleInfo *info = (struct DisassembleInfo *)DisInfo;
1067 // If no verbose symbolic information is wanted then just return nullptr.
1068 if (info->verbose == false) {
1069 *ReferenceName = nullptr;
1070 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
1074 const char *SymbolName = nullptr;
1075 if (ReferenceValue != 0xffffffffffffffffULL &&
1076 ReferenceValue != 0xfffffffffffffffeULL) {
1077 StringRef name = info->AddrMap->lookup(ReferenceValue);
1079 SymbolName = name.data();
1082 if (*ReferenceType == LLVMDisassembler_ReferenceType_In_Branch) {
1083 *ReferenceName = GuessIndirectSymbol(ReferenceValue, info);
1084 if (*ReferenceName != nullptr) {
1085 method_reference(info, ReferenceType, ReferenceName);
1086 if (*ReferenceType != LLVMDisassembler_ReferenceType_Out_Objc_Message)
1087 *ReferenceType = LLVMDisassembler_ReferenceType_Out_SymbolStub;
1090 if (SymbolName != nullptr && strncmp(SymbolName, "__Z", 3) == 0) {
1091 if (info->demangled_name != nullptr)
1092 free(info->demangled_name);
1094 info->demangled_name =
1095 abi::__cxa_demangle(SymbolName + 1, nullptr, nullptr, &status);
1096 if (info->demangled_name != nullptr) {
1097 *ReferenceName = info->demangled_name;
1098 *ReferenceType = LLVMDisassembler_ReferenceType_DeMangled_Name;
1100 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
1103 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
1104 } else if (*ReferenceType == LLVMDisassembler_ReferenceType_In_PCrel_Load) {
1106 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
1108 method_reference(info, ReferenceType, ReferenceName);
1110 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
1113 else if (SymbolName != nullptr && strncmp(SymbolName, "__Z", 3) == 0) {
1114 if (info->demangled_name != nullptr)
1115 free(info->demangled_name);
1117 info->demangled_name =
1118 abi::__cxa_demangle(SymbolName + 1, nullptr, nullptr, &status);
1119 if (info->demangled_name != nullptr) {
1120 *ReferenceName = info->demangled_name;
1121 *ReferenceType = LLVMDisassembler_ReferenceType_DeMangled_Name;
1126 *ReferenceName = nullptr;
1127 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
1134 // This is the memory object used by DisAsm->getInstruction() which has its
1135 // BasePC. This then allows the 'address' parameter to getInstruction() to
1136 // be the actual PC of the instruction. Then when a branch dispacement is
1137 // added to the PC of an instruction, the 'ReferenceValue' passed to the
1138 // SymbolizerSymbolLookUp() routine is the correct target addresses. As in
1139 // the case of a fully linked Mach-O file where a section being disassembled
1140 // generally not linked at address zero.
1142 class DisasmMemoryObject : public MemoryObject {
1143 const uint8_t *Bytes;
1148 DisasmMemoryObject(const uint8_t *bytes, uint64_t size, uint64_t basePC)
1149 : Bytes(bytes), Size(size), BasePC(basePC) {}
1151 uint64_t getBase() const override { return BasePC; }
1152 uint64_t getExtent() const override { return Size; }
1154 int readByte(uint64_t Addr, uint8_t *Byte) const override {
1155 if (Addr - BasePC >= Size)
1157 *Byte = Bytes[Addr - BasePC];
1162 /// \brief Emits the comments that are stored in the CommentStream.
1163 /// Each comment in the CommentStream must end with a newline.
1164 static void emitComments(raw_svector_ostream &CommentStream,
1165 SmallString<128> &CommentsToEmit,
1166 formatted_raw_ostream &FormattedOS,
1167 const MCAsmInfo &MAI) {
1168 // Flush the stream before taking its content.
1169 CommentStream.flush();
1170 StringRef Comments = CommentsToEmit.str();
1171 // Get the default information for printing a comment.
1172 const char *CommentBegin = MAI.getCommentString();
1173 unsigned CommentColumn = MAI.getCommentColumn();
1174 bool IsFirst = true;
1175 while (!Comments.empty()) {
1177 FormattedOS << '\n';
1178 // Emit a line of comments.
1179 FormattedOS.PadToColumn(CommentColumn);
1180 size_t Position = Comments.find('\n');
1181 FormattedOS << CommentBegin << ' ' << Comments.substr(0, Position);
1182 // Move after the newline character.
1183 Comments = Comments.substr(Position + 1);
1186 FormattedOS.flush();
1188 // Tell the comment stream that the vector changed underneath it.
1189 CommentsToEmit.clear();
1190 CommentStream.resync();
1193 static void DisassembleInputMachO2(StringRef Filename,
1194 MachOObjectFile *MachOOF) {
1195 const char *McpuDefault = nullptr;
1196 const Target *ThumbTarget = nullptr;
1197 const Target *TheTarget = GetTarget(MachOOF, &McpuDefault, &ThumbTarget);
1199 // GetTarget prints out stuff.
1202 if (MCPU.empty() && McpuDefault)
1205 std::unique_ptr<const MCInstrInfo> InstrInfo(TheTarget->createMCInstrInfo());
1206 std::unique_ptr<MCInstrAnalysis> InstrAnalysis(
1207 TheTarget->createMCInstrAnalysis(InstrInfo.get()));
1208 std::unique_ptr<const MCInstrInfo> ThumbInstrInfo;
1209 std::unique_ptr<MCInstrAnalysis> ThumbInstrAnalysis;
1211 ThumbInstrInfo.reset(ThumbTarget->createMCInstrInfo());
1212 ThumbInstrAnalysis.reset(
1213 ThumbTarget->createMCInstrAnalysis(ThumbInstrInfo.get()));
1216 // Package up features to be passed to target/subtarget
1217 std::string FeaturesStr;
1218 if (MAttrs.size()) {
1219 SubtargetFeatures Features;
1220 for (unsigned i = 0; i != MAttrs.size(); ++i)
1221 Features.AddFeature(MAttrs[i]);
1222 FeaturesStr = Features.getString();
1225 // Set up disassembler.
1226 std::unique_ptr<const MCRegisterInfo> MRI(
1227 TheTarget->createMCRegInfo(TripleName));
1228 std::unique_ptr<const MCAsmInfo> AsmInfo(
1229 TheTarget->createMCAsmInfo(*MRI, TripleName));
1230 std::unique_ptr<const MCSubtargetInfo> STI(
1231 TheTarget->createMCSubtargetInfo(TripleName, MCPU, FeaturesStr));
1232 MCContext Ctx(AsmInfo.get(), MRI.get(), nullptr);
1233 std::unique_ptr<MCDisassembler> DisAsm(
1234 TheTarget->createMCDisassembler(*STI, Ctx));
1235 std::unique_ptr<MCSymbolizer> Symbolizer;
1236 struct DisassembleInfo SymbolizerInfo;
1237 std::unique_ptr<MCRelocationInfo> RelInfo(
1238 TheTarget->createMCRelocationInfo(TripleName, Ctx));
1240 Symbolizer.reset(TheTarget->createMCSymbolizer(
1241 TripleName, SymbolizerGetOpInfo, SymbolizerSymbolLookUp,
1242 &SymbolizerInfo, &Ctx, RelInfo.release()));
1243 DisAsm->setSymbolizer(std::move(Symbolizer));
1245 int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
1246 std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
1247 AsmPrinterVariant, *AsmInfo, *InstrInfo, *MRI, *STI));
1248 // Set the display preference for hex vs. decimal immediates.
1249 IP->setPrintImmHex(PrintImmHex);
1250 // Comment stream and backing vector.
1251 SmallString<128> CommentsToEmit;
1252 raw_svector_ostream CommentStream(CommentsToEmit);
1253 IP->setCommentStream(CommentStream);
1255 if (!InstrAnalysis || !AsmInfo || !STI || !DisAsm || !IP) {
1256 errs() << "error: couldn't initialize disassembler for target "
1257 << TripleName << '\n';
1261 // Set up thumb disassembler.
1262 std::unique_ptr<const MCRegisterInfo> ThumbMRI;
1263 std::unique_ptr<const MCAsmInfo> ThumbAsmInfo;
1264 std::unique_ptr<const MCSubtargetInfo> ThumbSTI;
1265 std::unique_ptr<const MCDisassembler> ThumbDisAsm;
1266 std::unique_ptr<MCInstPrinter> ThumbIP;
1267 std::unique_ptr<MCContext> ThumbCtx;
1269 ThumbMRI.reset(ThumbTarget->createMCRegInfo(ThumbTripleName));
1271 ThumbTarget->createMCAsmInfo(*ThumbMRI, ThumbTripleName));
1273 ThumbTarget->createMCSubtargetInfo(ThumbTripleName, MCPU, FeaturesStr));
1274 ThumbCtx.reset(new MCContext(ThumbAsmInfo.get(), ThumbMRI.get(), nullptr));
1275 ThumbDisAsm.reset(ThumbTarget->createMCDisassembler(*ThumbSTI, *ThumbCtx));
1276 // TODO: add MCSymbolizer here for the ThumbTarget like above for TheTarget.
1277 int ThumbAsmPrinterVariant = ThumbAsmInfo->getAssemblerDialect();
1278 ThumbIP.reset(ThumbTarget->createMCInstPrinter(
1279 ThumbAsmPrinterVariant, *ThumbAsmInfo, *ThumbInstrInfo, *ThumbMRI,
1281 // Set the display preference for hex vs. decimal immediates.
1282 ThumbIP->setPrintImmHex(PrintImmHex);
1285 if (ThumbTarget && (!ThumbInstrAnalysis || !ThumbAsmInfo || !ThumbSTI ||
1286 !ThumbDisAsm || !ThumbIP)) {
1287 errs() << "error: couldn't initialize disassembler for target "
1288 << ThumbTripleName << '\n';
1292 outs() << '\n' << Filename << ":\n\n";
1294 MachO::mach_header Header = MachOOF->getHeader();
1296 // FIXME: Using the -cfg command line option, this code used to be able to
1297 // annotate relocations with the referenced symbol's name, and if this was
1298 // inside a __[cf]string section, the data it points to. This is now replaced
1299 // by the upcoming MCSymbolizer, which needs the appropriate setup done above.
1300 std::vector<SectionRef> Sections;
1301 std::vector<SymbolRef> Symbols;
1302 SmallVector<uint64_t, 8> FoundFns;
1303 uint64_t BaseSegmentAddress;
1305 getSectionsAndSymbols(Header, MachOOF, Sections, Symbols, FoundFns,
1306 BaseSegmentAddress);
1308 // Sort the symbols by address, just in case they didn't come in that way.
1309 std::sort(Symbols.begin(), Symbols.end(), SymbolSorter());
1311 // Build a data in code table that is sorted on by the address of each entry.
1312 uint64_t BaseAddress = 0;
1313 if (Header.filetype == MachO::MH_OBJECT)
1314 BaseAddress = Sections[0].getAddress();
1316 BaseAddress = BaseSegmentAddress;
1318 for (dice_iterator DI = MachOOF->begin_dices(), DE = MachOOF->end_dices();
1321 DI->getOffset(Offset);
1322 Dices.push_back(std::make_pair(BaseAddress + Offset, *DI));
1324 array_pod_sort(Dices.begin(), Dices.end());
1327 raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls();
1329 raw_ostream &DebugOut = nulls();
1332 std::unique_ptr<DIContext> diContext;
1333 ObjectFile *DbgObj = MachOOF;
1334 // Try to find debug info and set up the DIContext for it.
1336 // A separate DSym file path was specified, parse it as a macho file,
1337 // get the sections and supply it to the section name parsing machinery.
1338 if (!DSYMFile.empty()) {
1339 ErrorOr<std::unique_ptr<MemoryBuffer>> BufOrErr =
1340 MemoryBuffer::getFileOrSTDIN(DSYMFile);
1341 if (std::error_code EC = BufOrErr.getError()) {
1342 errs() << "llvm-objdump: " << Filename << ": " << EC.message() << '\n';
1346 ObjectFile::createMachOObjectFile(BufOrErr.get()->getMemBufferRef())
1351 // Setup the DIContext
1352 diContext.reset(DIContext::getDWARFContext(*DbgObj));
1355 for (unsigned SectIdx = 0; SectIdx != Sections.size(); SectIdx++) {
1357 bool SectIsText = Sections[SectIdx].isText();
1358 if (SectIsText == false)
1362 if (Sections[SectIdx].getName(SectName) || SectName != "__text")
1363 continue; // Skip non-text sections
1365 DataRefImpl DR = Sections[SectIdx].getRawDataRefImpl();
1367 StringRef SegmentName = MachOOF->getSectionFinalSegmentName(DR);
1368 if (SegmentName != "__TEXT")
1372 Sections[SectIdx].getContents(Bytes);
1373 uint64_t SectAddress = Sections[SectIdx].getAddress();
1374 DisasmMemoryObject MemoryObject((const uint8_t *)Bytes.data(), Bytes.size(),
1376 bool symbolTableWorked = false;
1378 // Parse relocations.
1379 std::vector<std::pair<uint64_t, SymbolRef>> Relocs;
1380 for (const RelocationRef &Reloc : Sections[SectIdx].relocations()) {
1381 uint64_t RelocOffset;
1382 Reloc.getOffset(RelocOffset);
1383 uint64_t SectionAddress = Sections[SectIdx].getAddress();
1384 RelocOffset -= SectionAddress;
1386 symbol_iterator RelocSym = Reloc.getSymbol();
1388 Relocs.push_back(std::make_pair(RelocOffset, *RelocSym));
1390 array_pod_sort(Relocs.begin(), Relocs.end());
1392 // Create a map of symbol addresses to symbol names for use by
1393 // the SymbolizerSymbolLookUp() routine.
1394 SymbolAddressMap AddrMap;
1395 for (const SymbolRef &Symbol : MachOOF->symbols()) {
1398 if (ST == SymbolRef::ST_Function || ST == SymbolRef::ST_Data ||
1399 ST == SymbolRef::ST_Other) {
1401 Symbol.getAddress(Address);
1403 Symbol.getName(SymName);
1404 AddrMap[Address] = SymName;
1407 // Set up the block of info used by the Symbolizer call backs.
1408 SymbolizerInfo.verbose = true;
1409 SymbolizerInfo.O = MachOOF;
1410 SymbolizerInfo.S = Sections[SectIdx];
1411 SymbolizerInfo.AddrMap = &AddrMap;
1412 SymbolizerInfo.Sections = &Sections;
1413 SymbolizerInfo.class_name = nullptr;
1414 SymbolizerInfo.selector_name = nullptr;
1415 SymbolizerInfo.method = nullptr;
1416 SymbolizerInfo.demangled_name = nullptr;
1417 SymbolizerInfo.bindtable = nullptr;
1419 // Disassemble symbol by symbol.
1420 for (unsigned SymIdx = 0; SymIdx != Symbols.size(); SymIdx++) {
1422 Symbols[SymIdx].getName(SymName);
1425 Symbols[SymIdx].getType(ST);
1426 if (ST != SymbolRef::ST_Function)
1429 // Make sure the symbol is defined in this section.
1430 bool containsSym = Sections[SectIdx].containsSymbol(Symbols[SymIdx]);
1434 // Start at the address of the symbol relative to the section's address.
1436 uint64_t SectionAddress = Sections[SectIdx].getAddress();
1437 Symbols[SymIdx].getAddress(Start);
1438 Start -= SectionAddress;
1440 // Stop disassembling either at the beginning of the next symbol or at
1441 // the end of the section.
1442 bool containsNextSym = false;
1443 uint64_t NextSym = 0;
1444 uint64_t NextSymIdx = SymIdx + 1;
1445 while (Symbols.size() > NextSymIdx) {
1446 SymbolRef::Type NextSymType;
1447 Symbols[NextSymIdx].getType(NextSymType);
1448 if (NextSymType == SymbolRef::ST_Function) {
1450 Sections[SectIdx].containsSymbol(Symbols[NextSymIdx]);
1451 Symbols[NextSymIdx].getAddress(NextSym);
1452 NextSym -= SectionAddress;
1458 uint64_t SectSize = Sections[SectIdx].getSize();
1459 uint64_t End = containsNextSym ? NextSym : SectSize;
1462 symbolTableWorked = true;
1463 DisasmMemoryObject SectionMemoryObject((const uint8_t *)Bytes.data() +
1465 End - Start, SectAddress + Start);
1467 DataRefImpl Symb = Symbols[SymIdx].getRawDataRefImpl();
1469 (MachOOF->getSymbolFlags(Symb) & SymbolRef::SF_Thumb) && ThumbTarget;
1471 outs() << SymName << ":\n";
1472 DILineInfo lastLine;
1473 for (uint64_t Index = Start; Index < End; Index += Size) {
1476 uint64_t PC = SectAddress + Index;
1477 if (FullLeadingAddr) {
1478 if (MachOOF->is64Bit())
1479 outs() << format("%016" PRIx64, PC);
1481 outs() << format("%08" PRIx64, PC);
1483 outs() << format("%8" PRIx64 ":", PC);
1488 // Check the data in code table here to see if this is data not an
1489 // instruction to be disassembled.
1491 Dice.push_back(std::make_pair(PC, DiceRef()));
1492 dice_table_iterator DTI =
1493 std::search(Dices.begin(), Dices.end(), Dice.begin(), Dice.end(),
1494 compareDiceTableEntries);
1495 if (DTI != Dices.end()) {
1497 DTI->second.getLength(Length);
1498 DumpBytes(StringRef(Bytes.data() + Index, Length));
1500 DTI->second.getKind(Kind);
1501 DumpDataInCode(Bytes.data() + Index, Length, Kind);
1505 SmallVector<char, 64> AnnotationsBytes;
1506 raw_svector_ostream Annotations(AnnotationsBytes);
1510 gotInst = ThumbDisAsm->getInstruction(Inst, Size, SectionMemoryObject,
1511 PC, DebugOut, Annotations);
1513 gotInst = DisAsm->getInstruction(Inst, Size, SectionMemoryObject, PC,
1514 DebugOut, Annotations);
1516 if (!NoShowRawInsn) {
1517 DumpBytes(StringRef(Bytes.data() + Index, Size));
1519 formatted_raw_ostream FormattedOS(outs());
1520 Annotations.flush();
1521 StringRef AnnotationsStr = Annotations.str();
1523 ThumbIP->printInst(&Inst, FormattedOS, AnnotationsStr);
1525 IP->printInst(&Inst, FormattedOS, AnnotationsStr);
1526 emitComments(CommentStream, CommentsToEmit, FormattedOS, *AsmInfo);
1528 // Print debug info.
1530 DILineInfo dli = diContext->getLineInfoForAddress(PC);
1531 // Print valid line info if it changed.
1532 if (dli != lastLine && dli.Line != 0)
1533 outs() << "\t## " << dli.FileName << ':' << dli.Line << ':'
1539 unsigned int Arch = MachOOF->getArch();
1540 if (Arch == Triple::x86_64 || Arch == Triple::x86) {
1541 outs() << format("\t.byte 0x%02x #bad opcode\n",
1542 *(Bytes.data() + Index) & 0xff);
1543 Size = 1; // skip exactly one illegible byte and move on.
1545 errs() << "llvm-objdump: warning: invalid instruction encoding\n";
1547 Size = 1; // skip illegible bytes
1552 if (!symbolTableWorked) {
1553 // Reading the symbol table didn't work, disassemble the whole section.
1554 uint64_t SectAddress = Sections[SectIdx].getAddress();
1555 uint64_t SectSize = Sections[SectIdx].getSize();
1557 for (uint64_t Index = 0; Index < SectSize; Index += InstSize) {
1560 uint64_t PC = SectAddress + Index;
1561 if (DisAsm->getInstruction(Inst, InstSize, MemoryObject, PC, DebugOut,
1563 if (FullLeadingAddr) {
1564 if (MachOOF->is64Bit())
1565 outs() << format("%016" PRIx64, PC);
1567 outs() << format("%08" PRIx64, PC);
1569 outs() << format("%8" PRIx64 ":", PC);
1571 if (!NoShowRawInsn) {
1573 DumpBytes(StringRef(Bytes.data() + Index, InstSize));
1575 IP->printInst(&Inst, outs(), "");
1578 unsigned int Arch = MachOOF->getArch();
1579 if (Arch == Triple::x86_64 || Arch == Triple::x86) {
1580 outs() << format("\t.byte 0x%02x #bad opcode\n",
1581 *(Bytes.data() + Index) & 0xff);
1582 InstSize = 1; // skip exactly one illegible byte and move on.
1584 errs() << "llvm-objdump: warning: invalid instruction encoding\n";
1586 InstSize = 1; // skip illegible bytes
1591 if (SymbolizerInfo.method != nullptr)
1592 free(SymbolizerInfo.method);
1593 if (SymbolizerInfo.demangled_name != nullptr)
1594 free(SymbolizerInfo.demangled_name);
1595 if (SymbolizerInfo.bindtable != nullptr)
1596 delete SymbolizerInfo.bindtable;
1600 //===----------------------------------------------------------------------===//
1601 // __compact_unwind section dumping
1602 //===----------------------------------------------------------------------===//
1606 template <typename T> static uint64_t readNext(const char *&Buf) {
1607 using llvm::support::little;
1608 using llvm::support::unaligned;
1610 uint64_t Val = support::endian::read<T, little, unaligned>(Buf);
1615 struct CompactUnwindEntry {
1616 uint32_t OffsetInSection;
1618 uint64_t FunctionAddr;
1620 uint32_t CompactEncoding;
1621 uint64_t PersonalityAddr;
1624 RelocationRef FunctionReloc;
1625 RelocationRef PersonalityReloc;
1626 RelocationRef LSDAReloc;
1628 CompactUnwindEntry(StringRef Contents, unsigned Offset, bool Is64)
1629 : OffsetInSection(Offset) {
1631 read<uint64_t>(Contents.data() + Offset);
1633 read<uint32_t>(Contents.data() + Offset);
1637 template <typename UIntPtr> void read(const char *Buf) {
1638 FunctionAddr = readNext<UIntPtr>(Buf);
1639 Length = readNext<uint32_t>(Buf);
1640 CompactEncoding = readNext<uint32_t>(Buf);
1641 PersonalityAddr = readNext<UIntPtr>(Buf);
1642 LSDAAddr = readNext<UIntPtr>(Buf);
1647 /// Given a relocation from __compact_unwind, consisting of the RelocationRef
1648 /// and data being relocated, determine the best base Name and Addend to use for
1649 /// display purposes.
1651 /// 1. An Extern relocation will directly reference a symbol (and the data is
1652 /// then already an addend), so use that.
1653 /// 2. Otherwise the data is an offset in the object file's layout; try to find
1654 // a symbol before it in the same section, and use the offset from there.
1655 /// 3. Finally, if all that fails, fall back to an offset from the start of the
1656 /// referenced section.
1657 static void findUnwindRelocNameAddend(const MachOObjectFile *Obj,
1658 std::map<uint64_t, SymbolRef> &Symbols,
1659 const RelocationRef &Reloc, uint64_t Addr,
1660 StringRef &Name, uint64_t &Addend) {
1661 if (Reloc.getSymbol() != Obj->symbol_end()) {
1662 Reloc.getSymbol()->getName(Name);
1667 auto RE = Obj->getRelocation(Reloc.getRawDataRefImpl());
1668 SectionRef RelocSection = Obj->getRelocationSection(RE);
1670 uint64_t SectionAddr = RelocSection.getAddress();
1672 auto Sym = Symbols.upper_bound(Addr);
1673 if (Sym == Symbols.begin()) {
1674 // The first symbol in the object is after this reference, the best we can
1675 // do is section-relative notation.
1676 RelocSection.getName(Name);
1677 Addend = Addr - SectionAddr;
1681 // Go back one so that SymbolAddress <= Addr.
1684 section_iterator SymSection = Obj->section_end();
1685 Sym->second.getSection(SymSection);
1686 if (RelocSection == *SymSection) {
1687 // There's a valid symbol in the same section before this reference.
1688 Sym->second.getName(Name);
1689 Addend = Addr - Sym->first;
1693 // There is a symbol before this reference, but it's in a different
1694 // section. Probably not helpful to mention it, so use the section name.
1695 RelocSection.getName(Name);
1696 Addend = Addr - SectionAddr;
1699 static void printUnwindRelocDest(const MachOObjectFile *Obj,
1700 std::map<uint64_t, SymbolRef> &Symbols,
1701 const RelocationRef &Reloc, uint64_t Addr) {
1705 if (!Reloc.getObjectFile())
1708 findUnwindRelocNameAddend(Obj, Symbols, Reloc, Addr, Name, Addend);
1712 outs() << " + " << format("0x%" PRIx64, Addend);
1716 printMachOCompactUnwindSection(const MachOObjectFile *Obj,
1717 std::map<uint64_t, SymbolRef> &Symbols,
1718 const SectionRef &CompactUnwind) {
1720 assert(Obj->isLittleEndian() &&
1721 "There should not be a big-endian .o with __compact_unwind");
1723 bool Is64 = Obj->is64Bit();
1724 uint32_t PointerSize = Is64 ? sizeof(uint64_t) : sizeof(uint32_t);
1725 uint32_t EntrySize = 3 * PointerSize + 2 * sizeof(uint32_t);
1728 CompactUnwind.getContents(Contents);
1730 SmallVector<CompactUnwindEntry, 4> CompactUnwinds;
1732 // First populate the initial raw offsets, encodings and so on from the entry.
1733 for (unsigned Offset = 0; Offset < Contents.size(); Offset += EntrySize) {
1734 CompactUnwindEntry Entry(Contents.data(), Offset, Is64);
1735 CompactUnwinds.push_back(Entry);
1738 // Next we need to look at the relocations to find out what objects are
1739 // actually being referred to.
1740 for (const RelocationRef &Reloc : CompactUnwind.relocations()) {
1741 uint64_t RelocAddress;
1742 Reloc.getOffset(RelocAddress);
1744 uint32_t EntryIdx = RelocAddress / EntrySize;
1745 uint32_t OffsetInEntry = RelocAddress - EntryIdx * EntrySize;
1746 CompactUnwindEntry &Entry = CompactUnwinds[EntryIdx];
1748 if (OffsetInEntry == 0)
1749 Entry.FunctionReloc = Reloc;
1750 else if (OffsetInEntry == PointerSize + 2 * sizeof(uint32_t))
1751 Entry.PersonalityReloc = Reloc;
1752 else if (OffsetInEntry == 2 * PointerSize + 2 * sizeof(uint32_t))
1753 Entry.LSDAReloc = Reloc;
1755 llvm_unreachable("Unexpected relocation in __compact_unwind section");
1758 // Finally, we're ready to print the data we've gathered.
1759 outs() << "Contents of __compact_unwind section:\n";
1760 for (auto &Entry : CompactUnwinds) {
1761 outs() << " Entry at offset "
1762 << format("0x%" PRIx32, Entry.OffsetInSection) << ":\n";
1764 // 1. Start of the region this entry applies to.
1765 outs() << " start: " << format("0x%" PRIx64,
1766 Entry.FunctionAddr) << ' ';
1767 printUnwindRelocDest(Obj, Symbols, Entry.FunctionReloc, Entry.FunctionAddr);
1770 // 2. Length of the region this entry applies to.
1771 outs() << " length: " << format("0x%" PRIx32, Entry.Length)
1773 // 3. The 32-bit compact encoding.
1774 outs() << " compact encoding: "
1775 << format("0x%08" PRIx32, Entry.CompactEncoding) << '\n';
1777 // 4. The personality function, if present.
1778 if (Entry.PersonalityReloc.getObjectFile()) {
1779 outs() << " personality function: "
1780 << format("0x%" PRIx64, Entry.PersonalityAddr) << ' ';
1781 printUnwindRelocDest(Obj, Symbols, Entry.PersonalityReloc,
1782 Entry.PersonalityAddr);
1786 // 5. This entry's language-specific data area.
1787 if (Entry.LSDAReloc.getObjectFile()) {
1788 outs() << " LSDA: " << format("0x%" PRIx64,
1789 Entry.LSDAAddr) << ' ';
1790 printUnwindRelocDest(Obj, Symbols, Entry.LSDAReloc, Entry.LSDAAddr);
1796 //===----------------------------------------------------------------------===//
1797 // __unwind_info section dumping
1798 //===----------------------------------------------------------------------===//
1800 static void printRegularSecondLevelUnwindPage(const char *PageStart) {
1801 const char *Pos = PageStart;
1802 uint32_t Kind = readNext<uint32_t>(Pos);
1804 assert(Kind == 2 && "kind for a regular 2nd level index should be 2");
1806 uint16_t EntriesStart = readNext<uint16_t>(Pos);
1807 uint16_t NumEntries = readNext<uint16_t>(Pos);
1809 Pos = PageStart + EntriesStart;
1810 for (unsigned i = 0; i < NumEntries; ++i) {
1811 uint32_t FunctionOffset = readNext<uint32_t>(Pos);
1812 uint32_t Encoding = readNext<uint32_t>(Pos);
1814 outs() << " [" << i << "]: "
1815 << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
1817 << "encoding=" << format("0x%08" PRIx32, Encoding) << '\n';
1821 static void printCompressedSecondLevelUnwindPage(
1822 const char *PageStart, uint32_t FunctionBase,
1823 const SmallVectorImpl<uint32_t> &CommonEncodings) {
1824 const char *Pos = PageStart;
1825 uint32_t Kind = readNext<uint32_t>(Pos);
1827 assert(Kind == 3 && "kind for a compressed 2nd level index should be 3");
1829 uint16_t EntriesStart = readNext<uint16_t>(Pos);
1830 uint16_t NumEntries = readNext<uint16_t>(Pos);
1832 uint16_t EncodingsStart = readNext<uint16_t>(Pos);
1833 readNext<uint16_t>(Pos);
1834 const auto *PageEncodings = reinterpret_cast<const support::ulittle32_t *>(
1835 PageStart + EncodingsStart);
1837 Pos = PageStart + EntriesStart;
1838 for (unsigned i = 0; i < NumEntries; ++i) {
1839 uint32_t Entry = readNext<uint32_t>(Pos);
1840 uint32_t FunctionOffset = FunctionBase + (Entry & 0xffffff);
1841 uint32_t EncodingIdx = Entry >> 24;
1844 if (EncodingIdx < CommonEncodings.size())
1845 Encoding = CommonEncodings[EncodingIdx];
1847 Encoding = PageEncodings[EncodingIdx - CommonEncodings.size()];
1849 outs() << " [" << i << "]: "
1850 << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
1852 << "encoding[" << EncodingIdx
1853 << "]=" << format("0x%08" PRIx32, Encoding) << '\n';
1857 static void printMachOUnwindInfoSection(const MachOObjectFile *Obj,
1858 std::map<uint64_t, SymbolRef> &Symbols,
1859 const SectionRef &UnwindInfo) {
1861 assert(Obj->isLittleEndian() &&
1862 "There should not be a big-endian .o with __unwind_info");
1864 outs() << "Contents of __unwind_info section:\n";
1867 UnwindInfo.getContents(Contents);
1868 const char *Pos = Contents.data();
1870 //===----------------------------------
1872 //===----------------------------------
1874 uint32_t Version = readNext<uint32_t>(Pos);
1875 outs() << " Version: "
1876 << format("0x%" PRIx32, Version) << '\n';
1877 assert(Version == 1 && "only understand version 1");
1879 uint32_t CommonEncodingsStart = readNext<uint32_t>(Pos);
1880 outs() << " Common encodings array section offset: "
1881 << format("0x%" PRIx32, CommonEncodingsStart) << '\n';
1882 uint32_t NumCommonEncodings = readNext<uint32_t>(Pos);
1883 outs() << " Number of common encodings in array: "
1884 << format("0x%" PRIx32, NumCommonEncodings) << '\n';
1886 uint32_t PersonalitiesStart = readNext<uint32_t>(Pos);
1887 outs() << " Personality function array section offset: "
1888 << format("0x%" PRIx32, PersonalitiesStart) << '\n';
1889 uint32_t NumPersonalities = readNext<uint32_t>(Pos);
1890 outs() << " Number of personality functions in array: "
1891 << format("0x%" PRIx32, NumPersonalities) << '\n';
1893 uint32_t IndicesStart = readNext<uint32_t>(Pos);
1894 outs() << " Index array section offset: "
1895 << format("0x%" PRIx32, IndicesStart) << '\n';
1896 uint32_t NumIndices = readNext<uint32_t>(Pos);
1897 outs() << " Number of indices in array: "
1898 << format("0x%" PRIx32, NumIndices) << '\n';
1900 //===----------------------------------
1901 // A shared list of common encodings
1902 //===----------------------------------
1904 // These occupy indices in the range [0, N] whenever an encoding is referenced
1905 // from a compressed 2nd level index table. In practice the linker only
1906 // creates ~128 of these, so that indices are available to embed encodings in
1907 // the 2nd level index.
1909 SmallVector<uint32_t, 64> CommonEncodings;
1910 outs() << " Common encodings: (count = " << NumCommonEncodings << ")\n";
1911 Pos = Contents.data() + CommonEncodingsStart;
1912 for (unsigned i = 0; i < NumCommonEncodings; ++i) {
1913 uint32_t Encoding = readNext<uint32_t>(Pos);
1914 CommonEncodings.push_back(Encoding);
1916 outs() << " encoding[" << i << "]: " << format("0x%08" PRIx32, Encoding)
1920 //===----------------------------------
1921 // Personality functions used in this executable
1922 //===----------------------------------
1924 // There should be only a handful of these (one per source language,
1925 // roughly). Particularly since they only get 2 bits in the compact encoding.
1927 outs() << " Personality functions: (count = " << NumPersonalities << ")\n";
1928 Pos = Contents.data() + PersonalitiesStart;
1929 for (unsigned i = 0; i < NumPersonalities; ++i) {
1930 uint32_t PersonalityFn = readNext<uint32_t>(Pos);
1931 outs() << " personality[" << i + 1
1932 << "]: " << format("0x%08" PRIx32, PersonalityFn) << '\n';
1935 //===----------------------------------
1936 // The level 1 index entries
1937 //===----------------------------------
1939 // These specify an approximate place to start searching for the more detailed
1940 // information, sorted by PC.
1943 uint32_t FunctionOffset;
1944 uint32_t SecondLevelPageStart;
1948 SmallVector<IndexEntry, 4> IndexEntries;
1950 outs() << " Top level indices: (count = " << NumIndices << ")\n";
1951 Pos = Contents.data() + IndicesStart;
1952 for (unsigned i = 0; i < NumIndices; ++i) {
1955 Entry.FunctionOffset = readNext<uint32_t>(Pos);
1956 Entry.SecondLevelPageStart = readNext<uint32_t>(Pos);
1957 Entry.LSDAStart = readNext<uint32_t>(Pos);
1958 IndexEntries.push_back(Entry);
1960 outs() << " [" << i << "]: "
1961 << "function offset=" << format("0x%08" PRIx32, Entry.FunctionOffset)
1963 << "2nd level page offset="
1964 << format("0x%08" PRIx32, Entry.SecondLevelPageStart) << ", "
1965 << "LSDA offset=" << format("0x%08" PRIx32, Entry.LSDAStart) << '\n';
1968 //===----------------------------------
1969 // Next come the LSDA tables
1970 //===----------------------------------
1972 // The LSDA layout is rather implicit: it's a contiguous array of entries from
1973 // the first top-level index's LSDAOffset to the last (sentinel).
1975 outs() << " LSDA descriptors:\n";
1976 Pos = Contents.data() + IndexEntries[0].LSDAStart;
1977 int NumLSDAs = (IndexEntries.back().LSDAStart - IndexEntries[0].LSDAStart) /
1978 (2 * sizeof(uint32_t));
1979 for (int i = 0; i < NumLSDAs; ++i) {
1980 uint32_t FunctionOffset = readNext<uint32_t>(Pos);
1981 uint32_t LSDAOffset = readNext<uint32_t>(Pos);
1982 outs() << " [" << i << "]: "
1983 << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
1985 << "LSDA offset=" << format("0x%08" PRIx32, LSDAOffset) << '\n';
1988 //===----------------------------------
1989 // Finally, the 2nd level indices
1990 //===----------------------------------
1992 // Generally these are 4K in size, and have 2 possible forms:
1993 // + Regular stores up to 511 entries with disparate encodings
1994 // + Compressed stores up to 1021 entries if few enough compact encoding
1996 outs() << " Second level indices:\n";
1997 for (unsigned i = 0; i < IndexEntries.size() - 1; ++i) {
1998 // The final sentinel top-level index has no associated 2nd level page
1999 if (IndexEntries[i].SecondLevelPageStart == 0)
2002 outs() << " Second level index[" << i << "]: "
2003 << "offset in section="
2004 << format("0x%08" PRIx32, IndexEntries[i].SecondLevelPageStart)
2006 << "base function offset="
2007 << format("0x%08" PRIx32, IndexEntries[i].FunctionOffset) << '\n';
2009 Pos = Contents.data() + IndexEntries[i].SecondLevelPageStart;
2010 uint32_t Kind = *reinterpret_cast<const support::ulittle32_t *>(Pos);
2012 printRegularSecondLevelUnwindPage(Pos);
2014 printCompressedSecondLevelUnwindPage(Pos, IndexEntries[i].FunctionOffset,
2017 llvm_unreachable("Do not know how to print this kind of 2nd level page");
2021 void llvm::printMachOUnwindInfo(const MachOObjectFile *Obj) {
2022 std::map<uint64_t, SymbolRef> Symbols;
2023 for (const SymbolRef &SymRef : Obj->symbols()) {
2024 // Discard any undefined or absolute symbols. They're not going to take part
2025 // in the convenience lookup for unwind info and just take up resources.
2026 section_iterator Section = Obj->section_end();
2027 SymRef.getSection(Section);
2028 if (Section == Obj->section_end())
2032 SymRef.getAddress(Addr);
2033 Symbols.insert(std::make_pair(Addr, SymRef));
2036 for (const SectionRef &Section : Obj->sections()) {
2038 Section.getName(SectName);
2039 if (SectName == "__compact_unwind")
2040 printMachOCompactUnwindSection(Obj, Symbols, Section);
2041 else if (SectName == "__unwind_info")
2042 printMachOUnwindInfoSection(Obj, Symbols, Section);
2043 else if (SectName == "__eh_frame")
2044 outs() << "llvm-objdump: warning: unhandled __eh_frame section\n";
2048 static void PrintMachHeader(uint32_t magic, uint32_t cputype,
2049 uint32_t cpusubtype, uint32_t filetype,
2050 uint32_t ncmds, uint32_t sizeofcmds, uint32_t flags,
2052 outs() << "Mach header\n";
2053 outs() << " magic cputype cpusubtype caps filetype ncmds "
2054 "sizeofcmds flags\n";
2056 if (magic == MachO::MH_MAGIC)
2057 outs() << " MH_MAGIC";
2058 else if (magic == MachO::MH_MAGIC_64)
2059 outs() << "MH_MAGIC_64";
2061 outs() << format(" 0x%08" PRIx32, magic);
2063 case MachO::CPU_TYPE_I386:
2065 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
2066 case MachO::CPU_SUBTYPE_I386_ALL:
2070 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
2074 case MachO::CPU_TYPE_X86_64:
2075 outs() << " X86_64";
2076 case MachO::CPU_SUBTYPE_X86_64_ALL:
2079 case MachO::CPU_SUBTYPE_X86_64_H:
2080 outs() << " Haswell";
2081 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
2083 case MachO::CPU_TYPE_ARM:
2085 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
2086 case MachO::CPU_SUBTYPE_ARM_ALL:
2089 case MachO::CPU_SUBTYPE_ARM_V4T:
2092 case MachO::CPU_SUBTYPE_ARM_V5TEJ:
2095 case MachO::CPU_SUBTYPE_ARM_XSCALE:
2096 outs() << " XSCALE";
2098 case MachO::CPU_SUBTYPE_ARM_V6:
2101 case MachO::CPU_SUBTYPE_ARM_V6M:
2104 case MachO::CPU_SUBTYPE_ARM_V7:
2107 case MachO::CPU_SUBTYPE_ARM_V7EM:
2110 case MachO::CPU_SUBTYPE_ARM_V7K:
2113 case MachO::CPU_SUBTYPE_ARM_V7M:
2116 case MachO::CPU_SUBTYPE_ARM_V7S:
2120 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
2124 case MachO::CPU_TYPE_ARM64:
2126 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
2127 case MachO::CPU_SUBTYPE_ARM64_ALL:
2131 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
2135 case MachO::CPU_TYPE_POWERPC:
2137 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
2138 case MachO::CPU_SUBTYPE_POWERPC_ALL:
2142 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
2146 case MachO::CPU_TYPE_POWERPC64:
2148 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
2149 case MachO::CPU_SUBTYPE_POWERPC_ALL:
2153 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
2158 if ((cpusubtype & MachO::CPU_SUBTYPE_MASK) == MachO::CPU_SUBTYPE_LIB64) {
2161 outs() << format(" 0x%02" PRIx32,
2162 (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24);
2165 case MachO::MH_OBJECT:
2166 outs() << " OBJECT";
2168 case MachO::MH_EXECUTE:
2169 outs() << " EXECUTE";
2171 case MachO::MH_FVMLIB:
2172 outs() << " FVMLIB";
2174 case MachO::MH_CORE:
2177 case MachO::MH_PRELOAD:
2178 outs() << " PRELOAD";
2180 case MachO::MH_DYLIB:
2183 case MachO::MH_DYLIB_STUB:
2184 outs() << " DYLIB_STUB";
2186 case MachO::MH_DYLINKER:
2187 outs() << " DYLINKER";
2189 case MachO::MH_BUNDLE:
2190 outs() << " BUNDLE";
2192 case MachO::MH_DSYM:
2195 case MachO::MH_KEXT_BUNDLE:
2196 outs() << " KEXTBUNDLE";
2199 outs() << format(" %10u", filetype);
2202 outs() << format(" %5u", ncmds);
2203 outs() << format(" %10u", sizeofcmds);
2205 if (f & MachO::MH_NOUNDEFS) {
2206 outs() << " NOUNDEFS";
2207 f &= ~MachO::MH_NOUNDEFS;
2209 if (f & MachO::MH_INCRLINK) {
2210 outs() << " INCRLINK";
2211 f &= ~MachO::MH_INCRLINK;
2213 if (f & MachO::MH_DYLDLINK) {
2214 outs() << " DYLDLINK";
2215 f &= ~MachO::MH_DYLDLINK;
2217 if (f & MachO::MH_BINDATLOAD) {
2218 outs() << " BINDATLOAD";
2219 f &= ~MachO::MH_BINDATLOAD;
2221 if (f & MachO::MH_PREBOUND) {
2222 outs() << " PREBOUND";
2223 f &= ~MachO::MH_PREBOUND;
2225 if (f & MachO::MH_SPLIT_SEGS) {
2226 outs() << " SPLIT_SEGS";
2227 f &= ~MachO::MH_SPLIT_SEGS;
2229 if (f & MachO::MH_LAZY_INIT) {
2230 outs() << " LAZY_INIT";
2231 f &= ~MachO::MH_LAZY_INIT;
2233 if (f & MachO::MH_TWOLEVEL) {
2234 outs() << " TWOLEVEL";
2235 f &= ~MachO::MH_TWOLEVEL;
2237 if (f & MachO::MH_FORCE_FLAT) {
2238 outs() << " FORCE_FLAT";
2239 f &= ~MachO::MH_FORCE_FLAT;
2241 if (f & MachO::MH_NOMULTIDEFS) {
2242 outs() << " NOMULTIDEFS";
2243 f &= ~MachO::MH_NOMULTIDEFS;
2245 if (f & MachO::MH_NOFIXPREBINDING) {
2246 outs() << " NOFIXPREBINDING";
2247 f &= ~MachO::MH_NOFIXPREBINDING;
2249 if (f & MachO::MH_PREBINDABLE) {
2250 outs() << " PREBINDABLE";
2251 f &= ~MachO::MH_PREBINDABLE;
2253 if (f & MachO::MH_ALLMODSBOUND) {
2254 outs() << " ALLMODSBOUND";
2255 f &= ~MachO::MH_ALLMODSBOUND;
2257 if (f & MachO::MH_SUBSECTIONS_VIA_SYMBOLS) {
2258 outs() << " SUBSECTIONS_VIA_SYMBOLS";
2259 f &= ~MachO::MH_SUBSECTIONS_VIA_SYMBOLS;
2261 if (f & MachO::MH_CANONICAL) {
2262 outs() << " CANONICAL";
2263 f &= ~MachO::MH_CANONICAL;
2265 if (f & MachO::MH_WEAK_DEFINES) {
2266 outs() << " WEAK_DEFINES";
2267 f &= ~MachO::MH_WEAK_DEFINES;
2269 if (f & MachO::MH_BINDS_TO_WEAK) {
2270 outs() << " BINDS_TO_WEAK";
2271 f &= ~MachO::MH_BINDS_TO_WEAK;
2273 if (f & MachO::MH_ALLOW_STACK_EXECUTION) {
2274 outs() << " ALLOW_STACK_EXECUTION";
2275 f &= ~MachO::MH_ALLOW_STACK_EXECUTION;
2277 if (f & MachO::MH_DEAD_STRIPPABLE_DYLIB) {
2278 outs() << " DEAD_STRIPPABLE_DYLIB";
2279 f &= ~MachO::MH_DEAD_STRIPPABLE_DYLIB;
2281 if (f & MachO::MH_PIE) {
2283 f &= ~MachO::MH_PIE;
2285 if (f & MachO::MH_NO_REEXPORTED_DYLIBS) {
2286 outs() << " NO_REEXPORTED_DYLIBS";
2287 f &= ~MachO::MH_NO_REEXPORTED_DYLIBS;
2289 if (f & MachO::MH_HAS_TLV_DESCRIPTORS) {
2290 outs() << " MH_HAS_TLV_DESCRIPTORS";
2291 f &= ~MachO::MH_HAS_TLV_DESCRIPTORS;
2293 if (f & MachO::MH_NO_HEAP_EXECUTION) {
2294 outs() << " MH_NO_HEAP_EXECUTION";
2295 f &= ~MachO::MH_NO_HEAP_EXECUTION;
2297 if (f & MachO::MH_APP_EXTENSION_SAFE) {
2298 outs() << " APP_EXTENSION_SAFE";
2299 f &= ~MachO::MH_APP_EXTENSION_SAFE;
2301 if (f != 0 || flags == 0)
2302 outs() << format(" 0x%08" PRIx32, f);
2304 outs() << format(" 0x%08" PRIx32, magic);
2305 outs() << format(" %7d", cputype);
2306 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
2307 outs() << format(" 0x%02" PRIx32,
2308 (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24);
2309 outs() << format(" %10u", filetype);
2310 outs() << format(" %5u", ncmds);
2311 outs() << format(" %10u", sizeofcmds);
2312 outs() << format(" 0x%08" PRIx32, flags);
2317 static void PrintSegmentCommand(uint32_t cmd, uint32_t cmdsize,
2318 StringRef SegName, uint64_t vmaddr,
2319 uint64_t vmsize, uint64_t fileoff,
2320 uint64_t filesize, uint32_t maxprot,
2321 uint32_t initprot, uint32_t nsects,
2322 uint32_t flags, uint32_t object_size,
2324 uint64_t expected_cmdsize;
2325 if (cmd == MachO::LC_SEGMENT) {
2326 outs() << " cmd LC_SEGMENT\n";
2327 expected_cmdsize = nsects;
2328 expected_cmdsize *= sizeof(struct MachO::section);
2329 expected_cmdsize += sizeof(struct MachO::segment_command);
2331 outs() << " cmd LC_SEGMENT_64\n";
2332 expected_cmdsize = nsects;
2333 expected_cmdsize *= sizeof(struct MachO::section_64);
2334 expected_cmdsize += sizeof(struct MachO::segment_command_64);
2336 outs() << " cmdsize " << cmdsize;
2337 if (cmdsize != expected_cmdsize)
2338 outs() << " Inconsistent size\n";
2341 outs() << " segname " << SegName << "\n";
2342 if (cmd == MachO::LC_SEGMENT_64) {
2343 outs() << " vmaddr " << format("0x%016" PRIx64, vmaddr) << "\n";
2344 outs() << " vmsize " << format("0x%016" PRIx64, vmsize) << "\n";
2346 outs() << " vmaddr " << format("0x%08" PRIx32, vmaddr) << "\n";
2347 outs() << " vmsize " << format("0x%08" PRIx32, vmsize) << "\n";
2349 outs() << " fileoff " << fileoff;
2350 if (fileoff > object_size)
2351 outs() << " (past end of file)\n";
2354 outs() << " filesize " << filesize;
2355 if (fileoff + filesize > object_size)
2356 outs() << " (past end of file)\n";
2361 ~(MachO::VM_PROT_READ | MachO::VM_PROT_WRITE |
2362 MachO::VM_PROT_EXECUTE)) != 0)
2363 outs() << " maxprot ?" << format("0x%08" PRIx32, maxprot) << "\n";
2365 if (maxprot & MachO::VM_PROT_READ)
2366 outs() << " maxprot r";
2368 outs() << " maxprot -";
2369 if (maxprot & MachO::VM_PROT_WRITE)
2373 if (maxprot & MachO::VM_PROT_EXECUTE)
2379 ~(MachO::VM_PROT_READ | MachO::VM_PROT_WRITE |
2380 MachO::VM_PROT_EXECUTE)) != 0)
2381 outs() << " initprot ?" << format("0x%08" PRIx32, initprot) << "\n";
2383 if (initprot & MachO::VM_PROT_READ)
2384 outs() << " initprot r";
2386 outs() << " initprot -";
2387 if (initprot & MachO::VM_PROT_WRITE)
2391 if (initprot & MachO::VM_PROT_EXECUTE)
2397 outs() << " maxprot " << format("0x%08" PRIx32, maxprot) << "\n";
2398 outs() << " initprot " << format("0x%08" PRIx32, initprot) << "\n";
2400 outs() << " nsects " << nsects << "\n";
2404 outs() << " (none)\n";
2406 if (flags & MachO::SG_HIGHVM) {
2407 outs() << " HIGHVM";
2408 flags &= ~MachO::SG_HIGHVM;
2410 if (flags & MachO::SG_FVMLIB) {
2411 outs() << " FVMLIB";
2412 flags &= ~MachO::SG_FVMLIB;
2414 if (flags & MachO::SG_NORELOC) {
2415 outs() << " NORELOC";
2416 flags &= ~MachO::SG_NORELOC;
2418 if (flags & MachO::SG_PROTECTED_VERSION_1) {
2419 outs() << " PROTECTED_VERSION_1";
2420 flags &= ~MachO::SG_PROTECTED_VERSION_1;
2423 outs() << format(" 0x%08" PRIx32, flags) << " (unknown flags)\n";
2428 outs() << " flags " << format("0x%" PRIx32, flags) << "\n";
2432 static void PrintSection(const char *sectname, const char *segname,
2433 uint64_t addr, uint64_t size, uint32_t offset,
2434 uint32_t align, uint32_t reloff, uint32_t nreloc,
2435 uint32_t flags, uint32_t reserved1, uint32_t reserved2,
2436 uint32_t cmd, const char *sg_segname,
2437 uint32_t filetype, uint32_t object_size,
2439 outs() << "Section\n";
2440 outs() << " sectname " << format("%.16s\n", sectname);
2441 outs() << " segname " << format("%.16s", segname);
2442 if (filetype != MachO::MH_OBJECT && strncmp(sg_segname, segname, 16) != 0)
2443 outs() << " (does not match segment)\n";
2446 if (cmd == MachO::LC_SEGMENT_64) {
2447 outs() << " addr " << format("0x%016" PRIx64, addr) << "\n";
2448 outs() << " size " << format("0x%016" PRIx64, size);
2450 outs() << " addr " << format("0x%08" PRIx32, addr) << "\n";
2451 outs() << " size " << format("0x%08" PRIx32, size);
2453 if ((flags & MachO::S_ZEROFILL) != 0 && offset + size > object_size)
2454 outs() << " (past end of file)\n";
2457 outs() << " offset " << offset;
2458 if (offset > object_size)
2459 outs() << " (past end of file)\n";
2462 uint32_t align_shifted = 1 << align;
2463 outs() << " align 2^" << align << " (" << align_shifted << ")\n";
2464 outs() << " reloff " << reloff;
2465 if (reloff > object_size)
2466 outs() << " (past end of file)\n";
2469 outs() << " nreloc " << nreloc;
2470 if (reloff + nreloc * sizeof(struct MachO::relocation_info) > object_size)
2471 outs() << " (past end of file)\n";
2474 uint32_t section_type = flags & MachO::SECTION_TYPE;
2477 if (section_type == MachO::S_REGULAR)
2478 outs() << " S_REGULAR\n";
2479 else if (section_type == MachO::S_ZEROFILL)
2480 outs() << " S_ZEROFILL\n";
2481 else if (section_type == MachO::S_CSTRING_LITERALS)
2482 outs() << " S_CSTRING_LITERALS\n";
2483 else if (section_type == MachO::S_4BYTE_LITERALS)
2484 outs() << " S_4BYTE_LITERALS\n";
2485 else if (section_type == MachO::S_8BYTE_LITERALS)
2486 outs() << " S_8BYTE_LITERALS\n";
2487 else if (section_type == MachO::S_16BYTE_LITERALS)
2488 outs() << " S_16BYTE_LITERALS\n";
2489 else if (section_type == MachO::S_LITERAL_POINTERS)
2490 outs() << " S_LITERAL_POINTERS\n";
2491 else if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS)
2492 outs() << " S_NON_LAZY_SYMBOL_POINTERS\n";
2493 else if (section_type == MachO::S_LAZY_SYMBOL_POINTERS)
2494 outs() << " S_LAZY_SYMBOL_POINTERS\n";
2495 else if (section_type == MachO::S_SYMBOL_STUBS)
2496 outs() << " S_SYMBOL_STUBS\n";
2497 else if (section_type == MachO::S_MOD_INIT_FUNC_POINTERS)
2498 outs() << " S_MOD_INIT_FUNC_POINTERS\n";
2499 else if (section_type == MachO::S_MOD_TERM_FUNC_POINTERS)
2500 outs() << " S_MOD_TERM_FUNC_POINTERS\n";
2501 else if (section_type == MachO::S_COALESCED)
2502 outs() << " S_COALESCED\n";
2503 else if (section_type == MachO::S_INTERPOSING)
2504 outs() << " S_INTERPOSING\n";
2505 else if (section_type == MachO::S_DTRACE_DOF)
2506 outs() << " S_DTRACE_DOF\n";
2507 else if (section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS)
2508 outs() << " S_LAZY_DYLIB_SYMBOL_POINTERS\n";
2509 else if (section_type == MachO::S_THREAD_LOCAL_REGULAR)
2510 outs() << " S_THREAD_LOCAL_REGULAR\n";
2511 else if (section_type == MachO::S_THREAD_LOCAL_ZEROFILL)
2512 outs() << " S_THREAD_LOCAL_ZEROFILL\n";
2513 else if (section_type == MachO::S_THREAD_LOCAL_VARIABLES)
2514 outs() << " S_THREAD_LOCAL_VARIABLES\n";
2515 else if (section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS)
2516 outs() << " S_THREAD_LOCAL_VARIABLE_POINTERS\n";
2517 else if (section_type == MachO::S_THREAD_LOCAL_INIT_FUNCTION_POINTERS)
2518 outs() << " S_THREAD_LOCAL_INIT_FUNCTION_POINTERS\n";
2520 outs() << format("0x%08" PRIx32, section_type) << "\n";
2521 outs() << "attributes";
2522 uint32_t section_attributes = flags & MachO::SECTION_ATTRIBUTES;
2523 if (section_attributes & MachO::S_ATTR_PURE_INSTRUCTIONS)
2524 outs() << " PURE_INSTRUCTIONS";
2525 if (section_attributes & MachO::S_ATTR_NO_TOC)
2526 outs() << " NO_TOC";
2527 if (section_attributes & MachO::S_ATTR_STRIP_STATIC_SYMS)
2528 outs() << " STRIP_STATIC_SYMS";
2529 if (section_attributes & MachO::S_ATTR_NO_DEAD_STRIP)
2530 outs() << " NO_DEAD_STRIP";
2531 if (section_attributes & MachO::S_ATTR_LIVE_SUPPORT)
2532 outs() << " LIVE_SUPPORT";
2533 if (section_attributes & MachO::S_ATTR_SELF_MODIFYING_CODE)
2534 outs() << " SELF_MODIFYING_CODE";
2535 if (section_attributes & MachO::S_ATTR_DEBUG)
2537 if (section_attributes & MachO::S_ATTR_SOME_INSTRUCTIONS)
2538 outs() << " SOME_INSTRUCTIONS";
2539 if (section_attributes & MachO::S_ATTR_EXT_RELOC)
2540 outs() << " EXT_RELOC";
2541 if (section_attributes & MachO::S_ATTR_LOC_RELOC)
2542 outs() << " LOC_RELOC";
2543 if (section_attributes == 0)
2544 outs() << " (none)";
2547 outs() << " flags " << format("0x%08" PRIx32, flags) << "\n";
2548 outs() << " reserved1 " << reserved1;
2549 if (section_type == MachO::S_SYMBOL_STUBS ||
2550 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
2551 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
2552 section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
2553 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS)
2554 outs() << " (index into indirect symbol table)\n";
2557 outs() << " reserved2 " << reserved2;
2558 if (section_type == MachO::S_SYMBOL_STUBS)
2559 outs() << " (size of stubs)\n";
2564 static void PrintSymtabLoadCommand(MachO::symtab_command st, uint32_t cputype,
2565 uint32_t object_size) {
2566 outs() << " cmd LC_SYMTAB\n";
2567 outs() << " cmdsize " << st.cmdsize;
2568 if (st.cmdsize != sizeof(struct MachO::symtab_command))
2569 outs() << " Incorrect size\n";
2572 outs() << " symoff " << st.symoff;
2573 if (st.symoff > object_size)
2574 outs() << " (past end of file)\n";
2577 outs() << " nsyms " << st.nsyms;
2579 if (cputype & MachO::CPU_ARCH_ABI64) {
2580 big_size = st.nsyms;
2581 big_size *= sizeof(struct MachO::nlist_64);
2582 big_size += st.symoff;
2583 if (big_size > object_size)
2584 outs() << " (past end of file)\n";
2588 big_size = st.nsyms;
2589 big_size *= sizeof(struct MachO::nlist);
2590 big_size += st.symoff;
2591 if (big_size > object_size)
2592 outs() << " (past end of file)\n";
2596 outs() << " stroff " << st.stroff;
2597 if (st.stroff > object_size)
2598 outs() << " (past end of file)\n";
2601 outs() << " strsize " << st.strsize;
2602 big_size = st.stroff;
2603 big_size += st.strsize;
2604 if (big_size > object_size)
2605 outs() << " (past end of file)\n";
2610 static void PrintDysymtabLoadCommand(MachO::dysymtab_command dyst,
2611 uint32_t nsyms, uint32_t object_size,
2613 outs() << " cmd LC_DYSYMTAB\n";
2614 outs() << " cmdsize " << dyst.cmdsize;
2615 if (dyst.cmdsize != sizeof(struct MachO::dysymtab_command))
2616 outs() << " Incorrect size\n";
2619 outs() << " ilocalsym " << dyst.ilocalsym;
2620 if (dyst.ilocalsym > nsyms)
2621 outs() << " (greater than the number of symbols)\n";
2624 outs() << " nlocalsym " << dyst.nlocalsym;
2626 big_size = dyst.ilocalsym;
2627 big_size += dyst.nlocalsym;
2628 if (big_size > nsyms)
2629 outs() << " (past the end of the symbol table)\n";
2632 outs() << " iextdefsym " << dyst.iextdefsym;
2633 if (dyst.iextdefsym > nsyms)
2634 outs() << " (greater than the number of symbols)\n";
2637 outs() << " nextdefsym " << dyst.nextdefsym;
2638 big_size = dyst.iextdefsym;
2639 big_size += dyst.nextdefsym;
2640 if (big_size > nsyms)
2641 outs() << " (past the end of the symbol table)\n";
2644 outs() << " iundefsym " << dyst.iundefsym;
2645 if (dyst.iundefsym > nsyms)
2646 outs() << " (greater than the number of symbols)\n";
2649 outs() << " nundefsym " << dyst.nundefsym;
2650 big_size = dyst.iundefsym;
2651 big_size += dyst.nundefsym;
2652 if (big_size > nsyms)
2653 outs() << " (past the end of the symbol table)\n";
2656 outs() << " tocoff " << dyst.tocoff;
2657 if (dyst.tocoff > object_size)
2658 outs() << " (past end of file)\n";
2661 outs() << " ntoc " << dyst.ntoc;
2662 big_size = dyst.ntoc;
2663 big_size *= sizeof(struct MachO::dylib_table_of_contents);
2664 big_size += dyst.tocoff;
2665 if (big_size > object_size)
2666 outs() << " (past end of file)\n";
2669 outs() << " modtaboff " << dyst.modtaboff;
2670 if (dyst.modtaboff > object_size)
2671 outs() << " (past end of file)\n";
2674 outs() << " nmodtab " << dyst.nmodtab;
2676 if (cputype & MachO::CPU_ARCH_ABI64) {
2677 modtabend = dyst.nmodtab;
2678 modtabend *= sizeof(struct MachO::dylib_module_64);
2679 modtabend += dyst.modtaboff;
2681 modtabend = dyst.nmodtab;
2682 modtabend *= sizeof(struct MachO::dylib_module);
2683 modtabend += dyst.modtaboff;
2685 if (modtabend > object_size)
2686 outs() << " (past end of file)\n";
2689 outs() << " extrefsymoff " << dyst.extrefsymoff;
2690 if (dyst.extrefsymoff > object_size)
2691 outs() << " (past end of file)\n";
2694 outs() << " nextrefsyms " << dyst.nextrefsyms;
2695 big_size = dyst.nextrefsyms;
2696 big_size *= sizeof(struct MachO::dylib_reference);
2697 big_size += dyst.extrefsymoff;
2698 if (big_size > object_size)
2699 outs() << " (past end of file)\n";
2702 outs() << " indirectsymoff " << dyst.indirectsymoff;
2703 if (dyst.indirectsymoff > object_size)
2704 outs() << " (past end of file)\n";
2707 outs() << " nindirectsyms " << dyst.nindirectsyms;
2708 big_size = dyst.nindirectsyms;
2709 big_size *= sizeof(uint32_t);
2710 big_size += dyst.indirectsymoff;
2711 if (big_size > object_size)
2712 outs() << " (past end of file)\n";
2715 outs() << " extreloff " << dyst.extreloff;
2716 if (dyst.extreloff > object_size)
2717 outs() << " (past end of file)\n";
2720 outs() << " nextrel " << dyst.nextrel;
2721 big_size = dyst.nextrel;
2722 big_size *= sizeof(struct MachO::relocation_info);
2723 big_size += dyst.extreloff;
2724 if (big_size > object_size)
2725 outs() << " (past end of file)\n";
2728 outs() << " locreloff " << dyst.locreloff;
2729 if (dyst.locreloff > object_size)
2730 outs() << " (past end of file)\n";
2733 outs() << " nlocrel " << dyst.nlocrel;
2734 big_size = dyst.nlocrel;
2735 big_size *= sizeof(struct MachO::relocation_info);
2736 big_size += dyst.locreloff;
2737 if (big_size > object_size)
2738 outs() << " (past end of file)\n";
2743 static void PrintDyldInfoLoadCommand(MachO::dyld_info_command dc,
2744 uint32_t object_size) {
2745 if (dc.cmd == MachO::LC_DYLD_INFO)
2746 outs() << " cmd LC_DYLD_INFO\n";
2748 outs() << " cmd LC_DYLD_INFO_ONLY\n";
2749 outs() << " cmdsize " << dc.cmdsize;
2750 if (dc.cmdsize != sizeof(struct MachO::dyld_info_command))
2751 outs() << " Incorrect size\n";
2754 outs() << " rebase_off " << dc.rebase_off;
2755 if (dc.rebase_off > object_size)
2756 outs() << " (past end of file)\n";
2759 outs() << " rebase_size " << dc.rebase_size;
2761 big_size = dc.rebase_off;
2762 big_size += dc.rebase_size;
2763 if (big_size > object_size)
2764 outs() << " (past end of file)\n";
2767 outs() << " bind_off " << dc.bind_off;
2768 if (dc.bind_off > object_size)
2769 outs() << " (past end of file)\n";
2772 outs() << " bind_size " << dc.bind_size;
2773 big_size = dc.bind_off;
2774 big_size += dc.bind_size;
2775 if (big_size > object_size)
2776 outs() << " (past end of file)\n";
2779 outs() << " weak_bind_off " << dc.weak_bind_off;
2780 if (dc.weak_bind_off > object_size)
2781 outs() << " (past end of file)\n";
2784 outs() << " weak_bind_size " << dc.weak_bind_size;
2785 big_size = dc.weak_bind_off;
2786 big_size += dc.weak_bind_size;
2787 if (big_size > object_size)
2788 outs() << " (past end of file)\n";
2791 outs() << " lazy_bind_off " << dc.lazy_bind_off;
2792 if (dc.lazy_bind_off > object_size)
2793 outs() << " (past end of file)\n";
2796 outs() << " lazy_bind_size " << dc.lazy_bind_size;
2797 big_size = dc.lazy_bind_off;
2798 big_size += dc.lazy_bind_size;
2799 if (big_size > object_size)
2800 outs() << " (past end of file)\n";
2803 outs() << " export_off " << dc.export_off;
2804 if (dc.export_off > object_size)
2805 outs() << " (past end of file)\n";
2808 outs() << " export_size " << dc.export_size;
2809 big_size = dc.export_off;
2810 big_size += dc.export_size;
2811 if (big_size > object_size)
2812 outs() << " (past end of file)\n";
2817 static void PrintDyldLoadCommand(MachO::dylinker_command dyld,
2819 if (dyld.cmd == MachO::LC_ID_DYLINKER)
2820 outs() << " cmd LC_ID_DYLINKER\n";
2821 else if (dyld.cmd == MachO::LC_LOAD_DYLINKER)
2822 outs() << " cmd LC_LOAD_DYLINKER\n";
2823 else if (dyld.cmd == MachO::LC_DYLD_ENVIRONMENT)
2824 outs() << " cmd LC_DYLD_ENVIRONMENT\n";
2826 outs() << " cmd ?(" << dyld.cmd << ")\n";
2827 outs() << " cmdsize " << dyld.cmdsize;
2828 if (dyld.cmdsize < sizeof(struct MachO::dylinker_command))
2829 outs() << " Incorrect size\n";
2832 if (dyld.name >= dyld.cmdsize)
2833 outs() << " name ?(bad offset " << dyld.name << ")\n";
2835 const char *P = (const char *)(Ptr) + dyld.name;
2836 outs() << " name " << P << " (offset " << dyld.name << ")\n";
2840 static void PrintUuidLoadCommand(MachO::uuid_command uuid) {
2841 outs() << " cmd LC_UUID\n";
2842 outs() << " cmdsize " << uuid.cmdsize;
2843 if (uuid.cmdsize != sizeof(struct MachO::uuid_command))
2844 outs() << " Incorrect size\n";
2848 outs() << format("%02" PRIX32, uuid.uuid[0]);
2849 outs() << format("%02" PRIX32, uuid.uuid[1]);
2850 outs() << format("%02" PRIX32, uuid.uuid[2]);
2851 outs() << format("%02" PRIX32, uuid.uuid[3]);
2853 outs() << format("%02" PRIX32, uuid.uuid[4]);
2854 outs() << format("%02" PRIX32, uuid.uuid[5]);
2856 outs() << format("%02" PRIX32, uuid.uuid[6]);
2857 outs() << format("%02" PRIX32, uuid.uuid[7]);
2859 outs() << format("%02" PRIX32, uuid.uuid[8]);
2860 outs() << format("%02" PRIX32, uuid.uuid[9]);
2862 outs() << format("%02" PRIX32, uuid.uuid[10]);
2863 outs() << format("%02" PRIX32, uuid.uuid[11]);
2864 outs() << format("%02" PRIX32, uuid.uuid[12]);
2865 outs() << format("%02" PRIX32, uuid.uuid[13]);
2866 outs() << format("%02" PRIX32, uuid.uuid[14]);
2867 outs() << format("%02" PRIX32, uuid.uuid[15]);
2871 static void PrintVersionMinLoadCommand(MachO::version_min_command vd) {
2872 if (vd.cmd == MachO::LC_VERSION_MIN_MACOSX)
2873 outs() << " cmd LC_VERSION_MIN_MACOSX\n";
2874 else if (vd.cmd == MachO::LC_VERSION_MIN_IPHONEOS)
2875 outs() << " cmd LC_VERSION_MIN_IPHONEOS\n";
2877 outs() << " cmd " << vd.cmd << " (?)\n";
2878 outs() << " cmdsize " << vd.cmdsize;
2879 if (vd.cmdsize != sizeof(struct MachO::version_min_command))
2880 outs() << " Incorrect size\n";
2883 outs() << " version " << ((vd.version >> 16) & 0xffff) << "."
2884 << ((vd.version >> 8) & 0xff);
2885 if ((vd.version & 0xff) != 0)
2886 outs() << "." << (vd.version & 0xff);
2889 outs() << " sdk n/a\n";
2891 outs() << " sdk " << ((vd.sdk >> 16) & 0xffff) << "."
2892 << ((vd.sdk >> 8) & 0xff);
2894 if ((vd.sdk & 0xff) != 0)
2895 outs() << "." << (vd.sdk & 0xff);
2899 static void PrintSourceVersionCommand(MachO::source_version_command sd) {
2900 outs() << " cmd LC_SOURCE_VERSION\n";
2901 outs() << " cmdsize " << sd.cmdsize;
2902 if (sd.cmdsize != sizeof(struct MachO::source_version_command))
2903 outs() << " Incorrect size\n";
2906 uint64_t a = (sd.version >> 40) & 0xffffff;
2907 uint64_t b = (sd.version >> 30) & 0x3ff;
2908 uint64_t c = (sd.version >> 20) & 0x3ff;
2909 uint64_t d = (sd.version >> 10) & 0x3ff;
2910 uint64_t e = sd.version & 0x3ff;
2911 outs() << " version " << a << "." << b;
2913 outs() << "." << c << "." << d << "." << e;
2915 outs() << "." << c << "." << d;
2921 static void PrintEntryPointCommand(MachO::entry_point_command ep) {
2922 outs() << " cmd LC_MAIN\n";
2923 outs() << " cmdsize " << ep.cmdsize;
2924 if (ep.cmdsize != sizeof(struct MachO::entry_point_command))
2925 outs() << " Incorrect size\n";
2928 outs() << " entryoff " << ep.entryoff << "\n";
2929 outs() << " stacksize " << ep.stacksize << "\n";
2932 static void PrintDylibCommand(MachO::dylib_command dl, const char *Ptr) {
2933 if (dl.cmd == MachO::LC_ID_DYLIB)
2934 outs() << " cmd LC_ID_DYLIB\n";
2935 else if (dl.cmd == MachO::LC_LOAD_DYLIB)
2936 outs() << " cmd LC_LOAD_DYLIB\n";
2937 else if (dl.cmd == MachO::LC_LOAD_WEAK_DYLIB)
2938 outs() << " cmd LC_LOAD_WEAK_DYLIB\n";
2939 else if (dl.cmd == MachO::LC_REEXPORT_DYLIB)
2940 outs() << " cmd LC_REEXPORT_DYLIB\n";
2941 else if (dl.cmd == MachO::LC_LAZY_LOAD_DYLIB)
2942 outs() << " cmd LC_LAZY_LOAD_DYLIB\n";
2943 else if (dl.cmd == MachO::LC_LOAD_UPWARD_DYLIB)
2944 outs() << " cmd LC_LOAD_UPWARD_DYLIB\n";
2946 outs() << " cmd " << dl.cmd << " (unknown)\n";
2947 outs() << " cmdsize " << dl.cmdsize;
2948 if (dl.cmdsize < sizeof(struct MachO::dylib_command))
2949 outs() << " Incorrect size\n";
2952 if (dl.dylib.name < dl.cmdsize) {
2953 const char *P = (const char *)(Ptr) + dl.dylib.name;
2954 outs() << " name " << P << " (offset " << dl.dylib.name << ")\n";
2956 outs() << " name ?(bad offset " << dl.dylib.name << ")\n";
2958 outs() << " time stamp " << dl.dylib.timestamp << " ";
2959 time_t t = dl.dylib.timestamp;
2960 outs() << ctime(&t);
2961 outs() << " current version ";
2962 if (dl.dylib.current_version == 0xffffffff)
2965 outs() << ((dl.dylib.current_version >> 16) & 0xffff) << "."
2966 << ((dl.dylib.current_version >> 8) & 0xff) << "."
2967 << (dl.dylib.current_version & 0xff) << "\n";
2968 outs() << "compatibility version ";
2969 if (dl.dylib.compatibility_version == 0xffffffff)
2972 outs() << ((dl.dylib.compatibility_version >> 16) & 0xffff) << "."
2973 << ((dl.dylib.compatibility_version >> 8) & 0xff) << "."
2974 << (dl.dylib.compatibility_version & 0xff) << "\n";
2977 static void PrintLinkEditDataCommand(MachO::linkedit_data_command ld,
2978 uint32_t object_size) {
2979 if (ld.cmd == MachO::LC_CODE_SIGNATURE)
2980 outs() << " cmd LC_FUNCTION_STARTS\n";
2981 else if (ld.cmd == MachO::LC_SEGMENT_SPLIT_INFO)
2982 outs() << " cmd LC_SEGMENT_SPLIT_INFO\n";
2983 else if (ld.cmd == MachO::LC_FUNCTION_STARTS)
2984 outs() << " cmd LC_FUNCTION_STARTS\n";
2985 else if (ld.cmd == MachO::LC_DATA_IN_CODE)
2986 outs() << " cmd LC_DATA_IN_CODE\n";
2987 else if (ld.cmd == MachO::LC_DYLIB_CODE_SIGN_DRS)
2988 outs() << " cmd LC_DYLIB_CODE_SIGN_DRS\n";
2989 else if (ld.cmd == MachO::LC_LINKER_OPTIMIZATION_HINT)
2990 outs() << " cmd LC_LINKER_OPTIMIZATION_HINT\n";
2992 outs() << " cmd " << ld.cmd << " (?)\n";
2993 outs() << " cmdsize " << ld.cmdsize;
2994 if (ld.cmdsize != sizeof(struct MachO::linkedit_data_command))
2995 outs() << " Incorrect size\n";
2998 outs() << " dataoff " << ld.dataoff;
2999 if (ld.dataoff > object_size)
3000 outs() << " (past end of file)\n";
3003 outs() << " datasize " << ld.datasize;
3004 uint64_t big_size = ld.dataoff;
3005 big_size += ld.datasize;
3006 if (big_size > object_size)
3007 outs() << " (past end of file)\n";
3012 static void PrintLoadCommands(const MachOObjectFile *Obj, uint32_t ncmds,
3013 uint32_t filetype, uint32_t cputype,
3015 StringRef Buf = Obj->getData();
3016 MachOObjectFile::LoadCommandInfo Command = Obj->getFirstLoadCommandInfo();
3017 for (unsigned i = 0;; ++i) {
3018 outs() << "Load command " << i << "\n";
3019 if (Command.C.cmd == MachO::LC_SEGMENT) {
3020 MachO::segment_command SLC = Obj->getSegmentLoadCommand(Command);
3021 const char *sg_segname = SLC.segname;
3022 PrintSegmentCommand(SLC.cmd, SLC.cmdsize, SLC.segname, SLC.vmaddr,
3023 SLC.vmsize, SLC.fileoff, SLC.filesize, SLC.maxprot,
3024 SLC.initprot, SLC.nsects, SLC.flags, Buf.size(),
3026 for (unsigned j = 0; j < SLC.nsects; j++) {
3027 MachO::section_64 S = Obj->getSection64(Command, j);
3028 PrintSection(S.sectname, S.segname, S.addr, S.size, S.offset, S.align,
3029 S.reloff, S.nreloc, S.flags, S.reserved1, S.reserved2,
3030 SLC.cmd, sg_segname, filetype, Buf.size(), verbose);
3032 } else if (Command.C.cmd == MachO::LC_SEGMENT_64) {
3033 MachO::segment_command_64 SLC_64 = Obj->getSegment64LoadCommand(Command);
3034 const char *sg_segname = SLC_64.segname;
3035 PrintSegmentCommand(SLC_64.cmd, SLC_64.cmdsize, SLC_64.segname,
3036 SLC_64.vmaddr, SLC_64.vmsize, SLC_64.fileoff,
3037 SLC_64.filesize, SLC_64.maxprot, SLC_64.initprot,
3038 SLC_64.nsects, SLC_64.flags, Buf.size(), verbose);
3039 for (unsigned j = 0; j < SLC_64.nsects; j++) {
3040 MachO::section_64 S_64 = Obj->getSection64(Command, j);
3041 PrintSection(S_64.sectname, S_64.segname, S_64.addr, S_64.size,
3042 S_64.offset, S_64.align, S_64.reloff, S_64.nreloc,
3043 S_64.flags, S_64.reserved1, S_64.reserved2, SLC_64.cmd,
3044 sg_segname, filetype, Buf.size(), verbose);
3046 } else if (Command.C.cmd == MachO::LC_SYMTAB) {
3047 MachO::symtab_command Symtab = Obj->getSymtabLoadCommand();
3048 PrintSymtabLoadCommand(Symtab, cputype, Buf.size());
3049 } else if (Command.C.cmd == MachO::LC_DYSYMTAB) {
3050 MachO::dysymtab_command Dysymtab = Obj->getDysymtabLoadCommand();
3051 MachO::symtab_command Symtab = Obj->getSymtabLoadCommand();
3052 PrintDysymtabLoadCommand(Dysymtab, Symtab.nsyms, Buf.size(), cputype);
3053 } else if (Command.C.cmd == MachO::LC_DYLD_INFO ||
3054 Command.C.cmd == MachO::LC_DYLD_INFO_ONLY) {
3055 MachO::dyld_info_command DyldInfo = Obj->getDyldInfoLoadCommand(Command);
3056 PrintDyldInfoLoadCommand(DyldInfo, Buf.size());
3057 } else if (Command.C.cmd == MachO::LC_LOAD_DYLINKER ||
3058 Command.C.cmd == MachO::LC_ID_DYLINKER ||
3059 Command.C.cmd == MachO::LC_DYLD_ENVIRONMENT) {
3060 MachO::dylinker_command Dyld = Obj->getDylinkerCommand(Command);
3061 PrintDyldLoadCommand(Dyld, Command.Ptr);
3062 } else if (Command.C.cmd == MachO::LC_UUID) {
3063 MachO::uuid_command Uuid = Obj->getUuidCommand(Command);
3064 PrintUuidLoadCommand(Uuid);
3065 } else if (Command.C.cmd == MachO::LC_VERSION_MIN_MACOSX) {
3066 MachO::version_min_command Vd = Obj->getVersionMinLoadCommand(Command);
3067 PrintVersionMinLoadCommand(Vd);
3068 } else if (Command.C.cmd == MachO::LC_SOURCE_VERSION) {
3069 MachO::source_version_command Sd = Obj->getSourceVersionCommand(Command);
3070 PrintSourceVersionCommand(Sd);
3071 } else if (Command.C.cmd == MachO::LC_MAIN) {
3072 MachO::entry_point_command Ep = Obj->getEntryPointCommand(Command);
3073 PrintEntryPointCommand(Ep);
3074 } else if (Command.C.cmd == MachO::LC_LOAD_DYLIB ||
3075 Command.C.cmd == MachO::LC_ID_DYLIB ||
3076 Command.C.cmd == MachO::LC_LOAD_WEAK_DYLIB ||
3077 Command.C.cmd == MachO::LC_REEXPORT_DYLIB ||
3078 Command.C.cmd == MachO::LC_LAZY_LOAD_DYLIB ||
3079 Command.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB) {
3080 MachO::dylib_command Dl = Obj->getDylibIDLoadCommand(Command);
3081 PrintDylibCommand(Dl, Command.Ptr);
3082 } else if (Command.C.cmd == MachO::LC_CODE_SIGNATURE ||
3083 Command.C.cmd == MachO::LC_SEGMENT_SPLIT_INFO ||
3084 Command.C.cmd == MachO::LC_FUNCTION_STARTS ||
3085 Command.C.cmd == MachO::LC_DATA_IN_CODE ||
3086 Command.C.cmd == MachO::LC_DYLIB_CODE_SIGN_DRS ||
3087 Command.C.cmd == MachO::LC_LINKER_OPTIMIZATION_HINT) {
3088 MachO::linkedit_data_command Ld =
3089 Obj->getLinkeditDataLoadCommand(Command);
3090 PrintLinkEditDataCommand(Ld, Buf.size());
3092 outs() << " cmd ?(" << format("0x%08" PRIx32, Command.C.cmd)
3094 outs() << " cmdsize " << Command.C.cmdsize << "\n";
3095 // TODO: get and print the raw bytes of the load command.
3097 // TODO: print all the other kinds of load commands.
3101 Command = Obj->getNextLoadCommandInfo(Command);
3105 static void getAndPrintMachHeader(const MachOObjectFile *Obj, uint32_t &ncmds,
3106 uint32_t &filetype, uint32_t &cputype,
3108 if (Obj->is64Bit()) {
3109 MachO::mach_header_64 H_64;
3110 H_64 = Obj->getHeader64();
3111 PrintMachHeader(H_64.magic, H_64.cputype, H_64.cpusubtype, H_64.filetype,
3112 H_64.ncmds, H_64.sizeofcmds, H_64.flags, verbose);
3114 filetype = H_64.filetype;
3115 cputype = H_64.cputype;
3117 MachO::mach_header H;
3118 H = Obj->getHeader();
3119 PrintMachHeader(H.magic, H.cputype, H.cpusubtype, H.filetype, H.ncmds,
3120 H.sizeofcmds, H.flags, verbose);
3122 filetype = H.filetype;
3123 cputype = H.cputype;
3127 void llvm::printMachOFileHeader(const object::ObjectFile *Obj) {
3128 const MachOObjectFile *file = dyn_cast<const MachOObjectFile>(Obj);
3130 uint32_t filetype = 0;
3131 uint32_t cputype = 0;
3132 getAndPrintMachHeader(file, ncmds, filetype, cputype, true);
3133 PrintLoadCommands(file, ncmds, filetype, cputype, true);
3136 //===----------------------------------------------------------------------===//
3137 // export trie dumping
3138 //===----------------------------------------------------------------------===//
3140 void llvm::printMachOExportsTrie(const object::MachOObjectFile *Obj) {
3141 for (const llvm::object::ExportEntry &Entry : Obj->exports()) {
3142 uint64_t Flags = Entry.flags();
3143 bool ReExport = (Flags & MachO::EXPORT_SYMBOL_FLAGS_REEXPORT);
3144 bool WeakDef = (Flags & MachO::EXPORT_SYMBOL_FLAGS_WEAK_DEFINITION);
3145 bool ThreadLocal = ((Flags & MachO::EXPORT_SYMBOL_FLAGS_KIND_MASK) ==
3146 MachO::EXPORT_SYMBOL_FLAGS_KIND_THREAD_LOCAL);
3147 bool Abs = ((Flags & MachO::EXPORT_SYMBOL_FLAGS_KIND_MASK) ==
3148 MachO::EXPORT_SYMBOL_FLAGS_KIND_ABSOLUTE);
3149 bool Resolver = (Flags & MachO::EXPORT_SYMBOL_FLAGS_STUB_AND_RESOLVER);
3151 outs() << "[re-export] ";
3153 outs() << format("0x%08llX ",
3154 Entry.address()); // FIXME:add in base address
3155 outs() << Entry.name();
3156 if (WeakDef || ThreadLocal || Resolver || Abs) {
3157 bool NeedsComma = false;
3160 outs() << "weak_def";
3166 outs() << "per-thread";
3172 outs() << "absolute";
3178 outs() << format("resolver=0x%08llX", Entry.other());
3184 StringRef DylibName = "unknown";
3185 int Ordinal = Entry.other() - 1;
3186 Obj->getLibraryShortNameByIndex(Ordinal, DylibName);
3187 if (Entry.otherName().empty())
3188 outs() << " (from " << DylibName << ")";
3190 outs() << " (" << Entry.otherName() << " from " << DylibName << ")";
3196 //===----------------------------------------------------------------------===//
3197 // rebase table dumping
3198 //===----------------------------------------------------------------------===//
3203 SegInfo(const object::MachOObjectFile *Obj);
3205 StringRef segmentName(uint32_t SegIndex);
3206 StringRef sectionName(uint32_t SegIndex, uint64_t SegOffset);
3207 uint64_t address(uint32_t SegIndex, uint64_t SegOffset);
3210 struct SectionInfo {
3213 StringRef SectionName;
3214 StringRef SegmentName;
3215 uint64_t OffsetInSegment;
3216 uint64_t SegmentStartAddress;
3217 uint32_t SegmentIndex;
3219 const SectionInfo &findSection(uint32_t SegIndex, uint64_t SegOffset);
3220 SmallVector<SectionInfo, 32> Sections;
3224 SegInfo::SegInfo(const object::MachOObjectFile *Obj) {
3225 // Build table of sections so segIndex/offset pairs can be translated.
3226 uint32_t CurSegIndex = Obj->hasPageZeroSegment() ? 1 : 0;
3227 StringRef CurSegName;
3228 uint64_t CurSegAddress;
3229 for (const SectionRef &Section : Obj->sections()) {
3231 if (error(Section.getName(Info.SectionName)))
3233 Info.Address = Section.getAddress();
3234 Info.Size = Section.getSize();
3236 Obj->getSectionFinalSegmentName(Section.getRawDataRefImpl());
3237 if (!Info.SegmentName.equals(CurSegName)) {
3239 CurSegName = Info.SegmentName;
3240 CurSegAddress = Info.Address;
3242 Info.SegmentIndex = CurSegIndex - 1;
3243 Info.OffsetInSegment = Info.Address - CurSegAddress;
3244 Info.SegmentStartAddress = CurSegAddress;
3245 Sections.push_back(Info);
3249 StringRef SegInfo::segmentName(uint32_t SegIndex) {
3250 for (const SectionInfo &SI : Sections) {
3251 if (SI.SegmentIndex == SegIndex)
3252 return SI.SegmentName;
3254 llvm_unreachable("invalid segIndex");
3257 const SegInfo::SectionInfo &SegInfo::findSection(uint32_t SegIndex,
3258 uint64_t OffsetInSeg) {
3259 for (const SectionInfo &SI : Sections) {
3260 if (SI.SegmentIndex != SegIndex)
3262 if (SI.OffsetInSegment > OffsetInSeg)
3264 if (OffsetInSeg >= (SI.OffsetInSegment + SI.Size))
3268 llvm_unreachable("segIndex and offset not in any section");
3271 StringRef SegInfo::sectionName(uint32_t SegIndex, uint64_t OffsetInSeg) {
3272 return findSection(SegIndex, OffsetInSeg).SectionName;
3275 uint64_t SegInfo::address(uint32_t SegIndex, uint64_t OffsetInSeg) {
3276 const SectionInfo &SI = findSection(SegIndex, OffsetInSeg);
3277 return SI.SegmentStartAddress + OffsetInSeg;
3280 void llvm::printMachORebaseTable(const object::MachOObjectFile *Obj) {
3281 // Build table of sections so names can used in final output.
3282 SegInfo sectionTable(Obj);
3284 outs() << "segment section address type\n";
3285 for (const llvm::object::MachORebaseEntry &Entry : Obj->rebaseTable()) {
3286 uint32_t SegIndex = Entry.segmentIndex();
3287 uint64_t OffsetInSeg = Entry.segmentOffset();
3288 StringRef SegmentName = sectionTable.segmentName(SegIndex);
3289 StringRef SectionName = sectionTable.sectionName(SegIndex, OffsetInSeg);
3290 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
3292 // Table lines look like: __DATA __nl_symbol_ptr 0x0000F00C pointer
3293 outs() << format("%-8s %-18s 0x%08" PRIX64 " %s\n",
3294 SegmentName.str().c_str(), SectionName.str().c_str(),
3295 Address, Entry.typeName().str().c_str());
3299 static StringRef ordinalName(const object::MachOObjectFile *Obj, int Ordinal) {
3300 StringRef DylibName;
3302 case MachO::BIND_SPECIAL_DYLIB_SELF:
3303 return "this-image";
3304 case MachO::BIND_SPECIAL_DYLIB_MAIN_EXECUTABLE:
3305 return "main-executable";
3306 case MachO::BIND_SPECIAL_DYLIB_FLAT_LOOKUP:
3307 return "flat-namespace";
3310 std::error_code EC =
3311 Obj->getLibraryShortNameByIndex(Ordinal - 1, DylibName);
3313 return "<<bad library ordinal>>";
3317 return "<<unknown special ordinal>>";
3320 //===----------------------------------------------------------------------===//
3321 // bind table dumping
3322 //===----------------------------------------------------------------------===//
3324 void llvm::printMachOBindTable(const object::MachOObjectFile *Obj) {
3325 // Build table of sections so names can used in final output.
3326 SegInfo sectionTable(Obj);
3328 outs() << "segment section address type "
3329 "addend dylib symbol\n";
3330 for (const llvm::object::MachOBindEntry &Entry : Obj->bindTable()) {
3331 uint32_t SegIndex = Entry.segmentIndex();
3332 uint64_t OffsetInSeg = Entry.segmentOffset();
3333 StringRef SegmentName = sectionTable.segmentName(SegIndex);
3334 StringRef SectionName = sectionTable.sectionName(SegIndex, OffsetInSeg);
3335 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
3337 // Table lines look like:
3338 // __DATA __got 0x00012010 pointer 0 libSystem ___stack_chk_guard
3340 if (Entry.flags() & MachO::BIND_SYMBOL_FLAGS_WEAK_IMPORT)
3341 Attr = " (weak_import)";
3342 outs() << left_justify(SegmentName, 8) << " "
3343 << left_justify(SectionName, 18) << " "
3344 << format_hex(Address, 10, true) << " "
3345 << left_justify(Entry.typeName(), 8) << " "
3346 << format_decimal(Entry.addend(), 8) << " "
3347 << left_justify(ordinalName(Obj, Entry.ordinal()), 16) << " "
3348 << Entry.symbolName() << Attr << "\n";
3352 //===----------------------------------------------------------------------===//
3353 // lazy bind table dumping
3354 //===----------------------------------------------------------------------===//
3356 void llvm::printMachOLazyBindTable(const object::MachOObjectFile *Obj) {
3357 // Build table of sections so names can used in final output.
3358 SegInfo sectionTable(Obj);
3360 outs() << "segment section address "
3362 for (const llvm::object::MachOBindEntry &Entry : Obj->lazyBindTable()) {
3363 uint32_t SegIndex = Entry.segmentIndex();
3364 uint64_t OffsetInSeg = Entry.segmentOffset();
3365 StringRef SegmentName = sectionTable.segmentName(SegIndex);
3366 StringRef SectionName = sectionTable.sectionName(SegIndex, OffsetInSeg);
3367 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
3369 // Table lines look like:
3370 // __DATA __got 0x00012010 libSystem ___stack_chk_guard
3371 outs() << left_justify(SegmentName, 8) << " "
3372 << left_justify(SectionName, 18) << " "
3373 << format_hex(Address, 10, true) << " "
3374 << left_justify(ordinalName(Obj, Entry.ordinal()), 16) << " "
3375 << Entry.symbolName() << "\n";
3379 //===----------------------------------------------------------------------===//
3380 // weak bind table dumping
3381 //===----------------------------------------------------------------------===//
3383 void llvm::printMachOWeakBindTable(const object::MachOObjectFile *Obj) {
3384 // Build table of sections so names can used in final output.
3385 SegInfo sectionTable(Obj);
3387 outs() << "segment section address "
3388 "type addend symbol\n";
3389 for (const llvm::object::MachOBindEntry &Entry : Obj->weakBindTable()) {
3390 // Strong symbols don't have a location to update.
3391 if (Entry.flags() & MachO::BIND_SYMBOL_FLAGS_NON_WEAK_DEFINITION) {
3392 outs() << " strong "
3393 << Entry.symbolName() << "\n";
3396 uint32_t SegIndex = Entry.segmentIndex();
3397 uint64_t OffsetInSeg = Entry.segmentOffset();
3398 StringRef SegmentName = sectionTable.segmentName(SegIndex);
3399 StringRef SectionName = sectionTable.sectionName(SegIndex, OffsetInSeg);
3400 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
3402 // Table lines look like:
3403 // __DATA __data 0x00001000 pointer 0 _foo
3404 outs() << left_justify(SegmentName, 8) << " "
3405 << left_justify(SectionName, 18) << " "
3406 << format_hex(Address, 10, true) << " "
3407 << left_justify(Entry.typeName(), 8) << " "
3408 << format_decimal(Entry.addend(), 8) << " " << Entry.symbolName()
3413 // get_dyld_bind_info_symbolname() is used for disassembly and passed an
3414 // address, ReferenceValue, in the Mach-O file and looks in the dyld bind
3415 // information for that address. If the address is found its binding symbol
3416 // name is returned. If not nullptr is returned.
3417 static const char *get_dyld_bind_info_symbolname(uint64_t ReferenceValue,
3418 struct DisassembleInfo *info) {
3419 if (info->bindtable == nullptr) {
3420 info->bindtable = new (BindTable);
3421 SegInfo sectionTable(info->O);
3422 for (const llvm::object::MachOBindEntry &Entry : info->O->bindTable()) {
3423 uint32_t SegIndex = Entry.segmentIndex();
3424 uint64_t OffsetInSeg = Entry.segmentOffset();
3425 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
3426 const char *SymbolName = nullptr;
3427 StringRef name = Entry.symbolName();
3429 SymbolName = name.data();
3430 info->bindtable->push_back(std::make_pair(Address, SymbolName));
3433 for (bind_table_iterator BI = info->bindtable->begin(),
3434 BE = info->bindtable->end();
3436 uint64_t Address = BI->first;
3437 if (ReferenceValue == Address) {
3438 const char *SymbolName = BI->second;