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 // GuessSymbolName is passed the address of what might be a symbol and a
252 // pointer to the DisassembleInfo struct. It returns the name of a symbol
253 // with that address or nullptr if no symbol is found with that address.
254 static const char *GuessSymbolName(uint64_t value,
255 struct DisassembleInfo *info) {
256 const char *SymbolName = nullptr;
257 // A DenseMap can't lookup up some values.
258 if (value != 0xffffffffffffffffULL && value != 0xfffffffffffffffeULL) {
259 StringRef name = info->AddrMap->lookup(value);
261 SymbolName = name.data();
266 // SymbolizerGetOpInfo() is the operand information call back function.
267 // This is called to get the symbolic information for operand(s) of an
268 // instruction when it is being done. This routine does this from
269 // the relocation information, symbol table, etc. That block of information
270 // is a pointer to the struct DisassembleInfo that was passed when the
271 // disassembler context was created and passed to back to here when
272 // called back by the disassembler for instruction operands that could have
273 // relocation information. The address of the instruction containing operand is
274 // at the Pc parameter. The immediate value the operand has is passed in
275 // op_info->Value and is at Offset past the start of the instruction and has a
276 // byte Size of 1, 2 or 4. The symbolc information is returned in TagBuf is the
277 // LLVMOpInfo1 struct defined in the header "llvm-c/Disassembler.h" as symbol
278 // names and addends of the symbolic expression to add for the operand. The
279 // value of TagType is currently 1 (for the LLVMOpInfo1 struct). If symbolic
280 // information is returned then this function returns 1 else it returns 0.
281 int SymbolizerGetOpInfo(void *DisInfo, uint64_t Pc, uint64_t Offset,
282 uint64_t Size, int TagType, void *TagBuf) {
283 struct DisassembleInfo *info = (struct DisassembleInfo *)DisInfo;
284 struct LLVMOpInfo1 *op_info = (struct LLVMOpInfo1 *)TagBuf;
285 unsigned int value = op_info->Value;
287 // Make sure all fields returned are zero if we don't set them.
288 memset((void *)op_info, '\0', sizeof(struct LLVMOpInfo1));
289 op_info->Value = value;
291 // If the TagType is not the value 1 which it code knows about or if no
292 // verbose symbolic information is wanted then just return 0, indicating no
293 // information is being returned.
294 if (TagType != 1 || info->verbose == false)
297 unsigned int Arch = info->O->getArch();
298 if (Arch == Triple::x86) {
299 if (Size != 1 && Size != 2 && Size != 4 && Size != 0)
301 // First search the section's relocation entries (if any) for an entry
302 // for this section offset.
303 uint32_t sect_addr = info->S.getAddress();
304 uint32_t sect_offset = (Pc + Offset) - sect_addr;
305 bool reloc_found = false;
307 MachO::any_relocation_info RE;
308 bool isExtern = false;
310 bool r_scattered = false;
311 uint32_t r_value, pair_r_value, r_type;
312 for (const RelocationRef &Reloc : info->S.relocations()) {
313 uint64_t RelocOffset;
314 Reloc.getOffset(RelocOffset);
315 if (RelocOffset == sect_offset) {
316 Rel = Reloc.getRawDataRefImpl();
317 RE = info->O->getRelocation(Rel);
318 r_scattered = info->O->isRelocationScattered(RE);
320 r_value = info->O->getScatteredRelocationValue(RE);
321 r_type = info->O->getScatteredRelocationType(RE);
322 if (r_type == MachO::GENERIC_RELOC_SECTDIFF ||
323 r_type == MachO::GENERIC_RELOC_LOCAL_SECTDIFF) {
324 DataRefImpl RelNext = Rel;
325 info->O->moveRelocationNext(RelNext);
326 MachO::any_relocation_info RENext;
327 RENext = info->O->getRelocation(RelNext);
328 if (info->O->isRelocationScattered(RENext))
329 pair_r_value = info->O->getPlainRelocationSymbolNum(RENext);
334 isExtern = info->O->getPlainRelocationExternal(RE);
336 symbol_iterator RelocSym = Reloc.getSymbol();
344 if (reloc_found && isExtern) {
346 Symbol.getName(SymName);
347 const char *name = SymName.data();
348 op_info->AddSymbol.Present = 1;
349 op_info->AddSymbol.Name = name;
350 // For i386 extern relocation entries the value in the instruction is
351 // the offset from the symbol, and value is already set in op_info->Value.
354 if (reloc_found && (r_type == MachO::GENERIC_RELOC_SECTDIFF ||
355 r_type == MachO::GENERIC_RELOC_LOCAL_SECTDIFF)) {
356 const char *add = GuessSymbolName(r_value, info);
357 const char *sub = GuessSymbolName(pair_r_value, info);
358 uint32_t offset = value - (r_value - pair_r_value);
359 op_info->AddSymbol.Present = 1;
361 op_info->AddSymbol.Name = add;
363 op_info->AddSymbol.Value = r_value;
364 op_info->SubtractSymbol.Present = 1;
366 op_info->SubtractSymbol.Name = sub;
368 op_info->SubtractSymbol.Value = pair_r_value;
369 op_info->Value = offset;
373 // Second search the external relocation entries of a fully linked image
374 // (if any) for an entry that matches this segment offset.
375 // uint32_t seg_offset = (Pc + Offset);
377 } else if (Arch == Triple::x86_64) {
378 if (Size != 1 && Size != 2 && Size != 4 && Size != 0)
380 // First search the section's relocation entries (if any) for an entry
381 // for this section offset.
382 uint64_t sect_addr = info->S.getAddress();
383 uint64_t sect_offset = (Pc + Offset) - sect_addr;
384 bool reloc_found = false;
386 MachO::any_relocation_info RE;
387 bool isExtern = false;
389 for (const RelocationRef &Reloc : info->S.relocations()) {
390 uint64_t RelocOffset;
391 Reloc.getOffset(RelocOffset);
392 if (RelocOffset == sect_offset) {
393 Rel = Reloc.getRawDataRefImpl();
394 RE = info->O->getRelocation(Rel);
395 // NOTE: Scattered relocations don't exist on x86_64.
396 isExtern = info->O->getPlainRelocationExternal(RE);
398 symbol_iterator RelocSym = Reloc.getSymbol();
405 if (reloc_found && isExtern) {
406 // The Value passed in will be adjusted by the Pc if the instruction
407 // adds the Pc. But for x86_64 external relocation entries the Value
408 // is the offset from the external symbol.
409 if (info->O->getAnyRelocationPCRel(RE))
410 op_info->Value -= Pc + Offset + Size;
412 Symbol.getName(SymName);
413 const char *name = SymName.data();
414 unsigned Type = info->O->getAnyRelocationType(RE);
415 if (Type == MachO::X86_64_RELOC_SUBTRACTOR) {
416 DataRefImpl RelNext = Rel;
417 info->O->moveRelocationNext(RelNext);
418 MachO::any_relocation_info RENext = info->O->getRelocation(RelNext);
419 unsigned TypeNext = info->O->getAnyRelocationType(RENext);
420 bool isExternNext = info->O->getPlainRelocationExternal(RENext);
421 unsigned SymbolNum = info->O->getPlainRelocationSymbolNum(RENext);
422 if (TypeNext == MachO::X86_64_RELOC_UNSIGNED && isExternNext) {
423 op_info->SubtractSymbol.Present = 1;
424 op_info->SubtractSymbol.Name = name;
425 symbol_iterator RelocSymNext = info->O->getSymbolByIndex(SymbolNum);
426 Symbol = *RelocSymNext;
427 StringRef SymNameNext;
428 Symbol.getName(SymNameNext);
429 name = SymNameNext.data();
432 // TODO: add the VariantKinds to op_info->VariantKind for relocation types
433 // like: X86_64_RELOC_TLV, X86_64_RELOC_GOT_LOAD and X86_64_RELOC_GOT.
434 op_info->AddSymbol.Present = 1;
435 op_info->AddSymbol.Name = name;
439 // Second search the external relocation entries of a fully linked image
440 // (if any) for an entry that matches this segment offset.
441 // uint64_t seg_offset = (Pc + Offset);
443 } else if (Arch == Triple::arm) {
445 } else if (Arch == Triple::aarch64) {
452 // GuessCstringPointer is passed the address of what might be a pointer to a
453 // literal string in a cstring section. If that address is in a cstring section
454 // it returns a pointer to that string. Else it returns nullptr.
455 const char *GuessCstringPointer(uint64_t ReferenceValue,
456 struct DisassembleInfo *info) {
457 uint32_t LoadCommandCount = info->O->getHeader().ncmds;
458 MachOObjectFile::LoadCommandInfo Load = info->O->getFirstLoadCommandInfo();
459 for (unsigned I = 0;; ++I) {
460 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
461 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
462 for (unsigned J = 0; J < Seg.nsects; ++J) {
463 MachO::section_64 Sec = info->O->getSection64(Load, J);
464 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
465 if (section_type == MachO::S_CSTRING_LITERALS &&
466 ReferenceValue >= Sec.addr &&
467 ReferenceValue < Sec.addr + Sec.size) {
468 uint64_t sect_offset = ReferenceValue - Sec.addr;
469 uint64_t object_offset = Sec.offset + sect_offset;
470 StringRef MachOContents = info->O->getData();
471 uint64_t object_size = MachOContents.size();
472 const char *object_addr = (const char *)MachOContents.data();
473 if (object_offset < object_size) {
474 const char *name = object_addr + object_offset;
481 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
482 MachO::segment_command Seg = info->O->getSegmentLoadCommand(Load);
483 for (unsigned J = 0; J < Seg.nsects; ++J) {
484 MachO::section Sec = info->O->getSection(Load, J);
485 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
486 if (section_type == MachO::S_CSTRING_LITERALS &&
487 ReferenceValue >= Sec.addr &&
488 ReferenceValue < Sec.addr + Sec.size) {
489 uint64_t sect_offset = ReferenceValue - Sec.addr;
490 uint64_t object_offset = Sec.offset + sect_offset;
491 StringRef MachOContents = info->O->getData();
492 uint64_t object_size = MachOContents.size();
493 const char *object_addr = (const char *)MachOContents.data();
494 if (object_offset < object_size) {
495 const char *name = object_addr + object_offset;
503 if (I == LoadCommandCount - 1)
506 Load = info->O->getNextLoadCommandInfo(Load);
511 // GuessIndirectSymbol returns the name of the indirect symbol for the
512 // ReferenceValue passed in or nullptr. This is used when ReferenceValue maybe
513 // an address of a symbol stub or a lazy or non-lazy pointer to associate the
514 // symbol name being referenced by the stub or pointer.
515 static const char *GuessIndirectSymbol(uint64_t ReferenceValue,
516 struct DisassembleInfo *info) {
517 uint32_t LoadCommandCount = info->O->getHeader().ncmds;
518 MachOObjectFile::LoadCommandInfo Load = info->O->getFirstLoadCommandInfo();
519 MachO::dysymtab_command Dysymtab = info->O->getDysymtabLoadCommand();
520 MachO::symtab_command Symtab = info->O->getSymtabLoadCommand();
521 for (unsigned I = 0;; ++I) {
522 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
523 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
524 for (unsigned J = 0; J < Seg.nsects; ++J) {
525 MachO::section_64 Sec = info->O->getSection64(Load, J);
526 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
527 if ((section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
528 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
529 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
530 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
531 section_type == MachO::S_SYMBOL_STUBS) &&
532 ReferenceValue >= Sec.addr &&
533 ReferenceValue < Sec.addr + Sec.size) {
535 if (section_type == MachO::S_SYMBOL_STUBS)
536 stride = Sec.reserved2;
541 uint32_t index = Sec.reserved1 + (ReferenceValue - Sec.addr) / stride;
542 if (index < Dysymtab.nindirectsyms) {
543 uint32_t indirect_symbol =
544 info->O->getIndirectSymbolTableEntry(Dysymtab, index);
545 if (indirect_symbol < Symtab.nsyms) {
546 symbol_iterator Sym = info->O->getSymbolByIndex(indirect_symbol);
547 SymbolRef Symbol = *Sym;
549 Symbol.getName(SymName);
550 const char *name = SymName.data();
556 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
557 MachO::segment_command Seg = info->O->getSegmentLoadCommand(Load);
558 for (unsigned J = 0; J < Seg.nsects; ++J) {
559 MachO::section Sec = info->O->getSection(Load, J);
560 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
561 if ((section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
562 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
563 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
564 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
565 section_type == MachO::S_SYMBOL_STUBS) &&
566 ReferenceValue >= Sec.addr &&
567 ReferenceValue < Sec.addr + Sec.size) {
569 if (section_type == MachO::S_SYMBOL_STUBS)
570 stride = Sec.reserved2;
575 uint32_t index = Sec.reserved1 + (ReferenceValue - Sec.addr) / stride;
576 if (index < Dysymtab.nindirectsyms) {
577 uint32_t indirect_symbol =
578 info->O->getIndirectSymbolTableEntry(Dysymtab, index);
579 if (indirect_symbol < Symtab.nsyms) {
580 symbol_iterator Sym = info->O->getSymbolByIndex(indirect_symbol);
581 SymbolRef Symbol = *Sym;
583 Symbol.getName(SymName);
584 const char *name = SymName.data();
591 if (I == LoadCommandCount - 1)
594 Load = info->O->getNextLoadCommandInfo(Load);
599 // method_reference() is called passing it the ReferenceName that might be
600 // a reference it to an Objective-C method call. If so then it allocates and
601 // assembles a method call string with the values last seen and saved in
602 // the DisassembleInfo's class_name and selector_name fields. This is saved
603 // into the method field of the info and any previous string is free'ed.
604 // Then the class_name field in the info is set to nullptr. The method call
605 // string is set into ReferenceName and ReferenceType is set to
606 // LLVMDisassembler_ReferenceType_Out_Objc_Message. If this not a method call
607 // then both ReferenceType and ReferenceName are left unchanged.
608 static void method_reference(struct DisassembleInfo *info,
609 uint64_t *ReferenceType,
610 const char **ReferenceName) {
611 if (*ReferenceName != nullptr) {
612 if (strcmp(*ReferenceName, "_objc_msgSend") == 0) {
613 if (info->selector_name != NULL) {
614 if (info->method != nullptr)
616 if (info->class_name != nullptr) {
617 info->method = (char *)malloc(5 + strlen(info->class_name) +
618 strlen(info->selector_name));
619 if (info->method != nullptr) {
620 strcpy(info->method, "+[");
621 strcat(info->method, info->class_name);
622 strcat(info->method, " ");
623 strcat(info->method, info->selector_name);
624 strcat(info->method, "]");
625 *ReferenceName = info->method;
626 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
629 info->method = (char *)malloc(9 + strlen(info->selector_name));
630 if (info->method != nullptr) {
631 strcpy(info->method, "-[%rdi ");
632 strcat(info->method, info->selector_name);
633 strcat(info->method, "]");
634 *ReferenceName = info->method;
635 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
638 info->class_name = nullptr;
640 } else if (strcmp(*ReferenceName, "_objc_msgSendSuper2") == 0) {
641 if (info->selector_name != NULL) {
642 if (info->method != nullptr)
644 info->method = (char *)malloc(17 + strlen(info->selector_name));
645 if (info->method != nullptr) {
646 strcpy(info->method, "-[[%rdi super] ");
647 strcat(info->method, info->selector_name);
648 strcat(info->method, "]");
649 *ReferenceName = info->method;
650 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
652 info->class_name = nullptr;
658 // GuessPointerPointer() is passed the address of what might be a pointer to
659 // a reference to an Objective-C class, selector, message ref or cfstring.
660 // If so the value of the pointer is returned and one of the booleans are set
661 // to true. If not zero is returned and all the booleans are set to false.
662 static uint64_t GuessPointerPointer(uint64_t ReferenceValue,
663 struct DisassembleInfo *info,
664 bool &classref, bool &selref, bool &msgref,
670 uint32_t LoadCommandCount = info->O->getHeader().ncmds;
671 MachOObjectFile::LoadCommandInfo Load = info->O->getFirstLoadCommandInfo();
672 for (unsigned I = 0;; ++I) {
673 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
674 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
675 for (unsigned J = 0; J < Seg.nsects; ++J) {
676 MachO::section_64 Sec = info->O->getSection64(Load, J);
677 if ((strncmp(Sec.sectname, "__objc_selrefs", 16) == 0 ||
678 strncmp(Sec.sectname, "__objc_classrefs", 16) == 0 ||
679 strncmp(Sec.sectname, "__objc_superrefs", 16) == 0 ||
680 strncmp(Sec.sectname, "__objc_msgrefs", 16) == 0 ||
681 strncmp(Sec.sectname, "__cfstring", 16) == 0) &&
682 ReferenceValue >= Sec.addr &&
683 ReferenceValue < Sec.addr + Sec.size) {
684 uint64_t sect_offset = ReferenceValue - Sec.addr;
685 uint64_t object_offset = Sec.offset + sect_offset;
686 StringRef MachOContents = info->O->getData();
687 uint64_t object_size = MachOContents.size();
688 const char *object_addr = (const char *)MachOContents.data();
689 if (object_offset < object_size) {
690 uint64_t pointer_value;
691 memcpy(&pointer_value, object_addr + object_offset,
693 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
694 sys::swapByteOrder(pointer_value);
695 if (strncmp(Sec.sectname, "__objc_selrefs", 16) == 0)
697 else if (strncmp(Sec.sectname, "__objc_classrefs", 16) == 0 ||
698 strncmp(Sec.sectname, "__objc_superrefs", 16) == 0)
700 else if (strncmp(Sec.sectname, "__objc_msgrefs", 16) == 0 &&
701 ReferenceValue + 8 < Sec.addr + Sec.size) {
703 memcpy(&pointer_value, object_addr + object_offset + 8,
705 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
706 sys::swapByteOrder(pointer_value);
707 } else if (strncmp(Sec.sectname, "__cfstring", 16) == 0)
709 return pointer_value;
716 // TODO: Look for LC_SEGMENT for 32-bit Mach-O files.
717 if (I == LoadCommandCount - 1)
720 Load = info->O->getNextLoadCommandInfo(Load);
725 // get_pointer_64 returns a pointer to the bytes in the object file at the
726 // Address from a section in the Mach-O file. And indirectly returns the
727 // offset into the section, number of bytes left in the section past the offset
728 // and which section is was being referenced. If the Address is not in a
729 // section nullptr is returned.
730 const char *get_pointer_64(uint64_t Address, uint32_t &offset, uint32_t &left,
731 SectionRef &S, DisassembleInfo *info) {
735 for (unsigned SectIdx = 0; SectIdx != info->Sections->size(); SectIdx++) {
736 uint64_t SectAddress = ((*(info->Sections))[SectIdx]).getAddress();
737 uint64_t SectSize = ((*(info->Sections))[SectIdx]).getSize();
738 if (Address >= SectAddress && Address < SectAddress + SectSize) {
739 S = (*(info->Sections))[SectIdx];
740 offset = Address - SectAddress;
741 left = SectSize - offset;
742 StringRef SectContents;
743 ((*(info->Sections))[SectIdx]).getContents(SectContents);
744 return SectContents.data() + offset;
750 // get_symbol_64() returns the name of a symbol (or nullptr) and the address of
751 // the symbol indirectly through n_value. Based on the relocation information
752 // for the specified section offset in the specified section reference.
753 const char *get_symbol_64(uint32_t sect_offset, SectionRef S,
754 DisassembleInfo *info, uint64_t &n_value) {
756 if (info->verbose == false)
759 // See if there is an external relocation entry at the sect_offset.
760 bool reloc_found = false;
762 MachO::any_relocation_info RE;
763 bool isExtern = false;
765 for (const RelocationRef &Reloc : S.relocations()) {
766 uint64_t RelocOffset;
767 Reloc.getOffset(RelocOffset);
768 if (RelocOffset == sect_offset) {
769 Rel = Reloc.getRawDataRefImpl();
770 RE = info->O->getRelocation(Rel);
771 if (info->O->isRelocationScattered(RE))
773 isExtern = info->O->getPlainRelocationExternal(RE);
775 symbol_iterator RelocSym = Reloc.getSymbol();
782 // If there is an external relocation entry for a symbol in this section
783 // at this section_offset then use that symbol's value for the n_value
784 // and return its name.
785 const char *SymbolName = nullptr;
786 if (reloc_found && isExtern) {
787 Symbol.getAddress(n_value);
789 Symbol.getName(name);
791 SymbolName = name.data();
796 // TODO: For fully linked images, look through the external relocation
797 // entries off the dynamic symtab command. For these the r_offset is from the
798 // start of the first writeable segment in the Mach-O file. So the offset
799 // to this section from that segment is passed to this routine by the caller,
800 // as the database_offset. Which is the difference of the section's starting
801 // address and the first writable segment.
803 // NOTE: need add passing the database_offset to this routine.
805 // TODO: We did not find an external relocation entry so look up the
806 // ReferenceValue as an address of a symbol and if found return that symbol's
809 // NOTE: need add passing the ReferenceValue to this routine. Then that code
810 // would simply be this:
811 // SymbolName = GuessSymbolName(ReferenceValue, info);
816 // These are structs in the Objective-C meta data and read to produce the
817 // comments for disassembly. While these are part of the ABI they are no
818 // public defintions. So the are here not in include/llvm/Support/MachO.h .
820 // The cfstring object in a 64-bit Mach-O file.
821 struct cfstring64_t {
822 uint64_t isa; // class64_t * (64-bit pointer)
823 uint64_t flags; // flag bits
824 uint64_t characters; // char * (64-bit pointer)
825 uint64_t length; // number of non-NULL characters in above
828 // The class object in a 64-bit Mach-O file.
830 uint64_t isa; // class64_t * (64-bit pointer)
831 uint64_t superclass; // class64_t * (64-bit pointer)
832 uint64_t cache; // Cache (64-bit pointer)
833 uint64_t vtable; // IMP * (64-bit pointer)
834 uint64_t data; // class_ro64_t * (64-bit pointer)
837 struct class_ro64_t {
839 uint32_t instanceStart;
840 uint32_t instanceSize;
842 uint64_t ivarLayout; // const uint8_t * (64-bit pointer)
843 uint64_t name; // const char * (64-bit pointer)
844 uint64_t baseMethods; // const method_list_t * (64-bit pointer)
845 uint64_t baseProtocols; // const protocol_list_t * (64-bit pointer)
846 uint64_t ivars; // const ivar_list_t * (64-bit pointer)
847 uint64_t weakIvarLayout; // const uint8_t * (64-bit pointer)
848 uint64_t baseProperties; // const struct objc_property_list (64-bit pointer)
851 inline void swapStruct(struct cfstring64_t &cfs) {
852 sys::swapByteOrder(cfs.isa);
853 sys::swapByteOrder(cfs.flags);
854 sys::swapByteOrder(cfs.characters);
855 sys::swapByteOrder(cfs.length);
858 inline void swapStruct(struct class64_t &c) {
859 sys::swapByteOrder(c.isa);
860 sys::swapByteOrder(c.superclass);
861 sys::swapByteOrder(c.cache);
862 sys::swapByteOrder(c.vtable);
863 sys::swapByteOrder(c.data);
866 inline void swapStruct(struct class_ro64_t &cro) {
867 sys::swapByteOrder(cro.flags);
868 sys::swapByteOrder(cro.instanceStart);
869 sys::swapByteOrder(cro.instanceSize);
870 sys::swapByteOrder(cro.reserved);
871 sys::swapByteOrder(cro.ivarLayout);
872 sys::swapByteOrder(cro.name);
873 sys::swapByteOrder(cro.baseMethods);
874 sys::swapByteOrder(cro.baseProtocols);
875 sys::swapByteOrder(cro.ivars);
876 sys::swapByteOrder(cro.weakIvarLayout);
877 sys::swapByteOrder(cro.baseProperties);
880 static const char *get_dyld_bind_info_symbolname(uint64_t ReferenceValue,
881 struct DisassembleInfo *info);
883 // get_objc2_64bit_class_name() is used for disassembly and is passed a pointer
884 // to an Objective-C class and returns the class name. It is also passed the
885 // address of the pointer, so when the pointer is zero as it can be in an .o
886 // file, that is used to look for an external relocation entry with a symbol
888 const char *get_objc2_64bit_class_name(uint64_t pointer_value,
889 uint64_t ReferenceValue,
890 struct DisassembleInfo *info) {
892 uint32_t offset, left;
895 // The pointer_value can be 0 in an object file and have a relocation
896 // entry for the class symbol at the ReferenceValue (the address of the
898 if (pointer_value == 0) {
899 r = get_pointer_64(ReferenceValue, offset, left, S, info);
900 if (r == nullptr || left < sizeof(uint64_t))
903 const char *symbol_name = get_symbol_64(offset, S, info, n_value);
904 if (symbol_name == nullptr)
906 const char *class_name = strrchr(symbol_name, '$');
907 if (class_name != nullptr && class_name[1] == '_' && class_name[2] != '\0')
908 return class_name + 2;
913 // The case were the pointer_value is non-zero and points to a class defined
914 // in this Mach-O file.
915 r = get_pointer_64(pointer_value, offset, left, S, info);
916 if (r == nullptr || left < sizeof(struct class64_t))
919 memcpy(&c, r, sizeof(struct class64_t));
920 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
924 r = get_pointer_64(c.data, offset, left, S, info);
925 if (r == nullptr || left < sizeof(struct class_ro64_t))
927 struct class_ro64_t cro;
928 memcpy(&cro, r, sizeof(struct class_ro64_t));
929 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
933 const char *name = get_pointer_64(cro.name, offset, left, S, info);
937 // get_objc2_64bit_cfstring_name is used for disassembly and is passed a
938 // pointer to a cfstring and returns its name or nullptr.
939 const char *get_objc2_64bit_cfstring_name(uint64_t ReferenceValue,
940 struct DisassembleInfo *info) {
941 const char *r, *name;
942 uint32_t offset, left;
944 struct cfstring64_t cfs;
945 uint64_t cfs_characters;
947 r = get_pointer_64(ReferenceValue, offset, left, S, info);
948 if (r == nullptr || left < sizeof(struct cfstring64_t))
950 memcpy(&cfs, r, sizeof(struct cfstring64_t));
951 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
953 if (cfs.characters == 0) {
955 const char *symbol_name = get_symbol_64(
956 offset + offsetof(struct cfstring64_t, characters), S, info, n_value);
957 if (symbol_name == nullptr)
959 cfs_characters = n_value;
961 cfs_characters = cfs.characters;
962 name = get_pointer_64(cfs_characters, offset, left, S, info);
967 // get_objc2_64bit_selref() is used for disassembly and is passed a the address
968 // of a pointer to an Objective-C selector reference when the pointer value is
969 // zero as in a .o file and is likely to have a external relocation entry with
970 // who's symbol's n_value is the real pointer to the selector name. If that is
971 // the case the real pointer to the selector name is returned else 0 is
973 uint64_t get_objc2_64bit_selref(uint64_t ReferenceValue,
974 struct DisassembleInfo *info) {
975 uint32_t offset, left;
978 const char *r = get_pointer_64(ReferenceValue, offset, left, S, info);
979 if (r == nullptr || left < sizeof(uint64_t))
982 const char *symbol_name = get_symbol_64(offset, S, info, n_value);
983 if (symbol_name == nullptr)
988 // GuessLiteralPointer returns a string which for the item in the Mach-O file
989 // for the address passed in as ReferenceValue for printing as a comment with
990 // the instruction and also returns the corresponding type of that item
991 // indirectly through ReferenceType.
993 // If ReferenceValue is an address of literal cstring then a pointer to the
994 // cstring is returned and ReferenceType is set to
995 // LLVMDisassembler_ReferenceType_Out_LitPool_CstrAddr .
997 // If ReferenceValue is an address of an Objective-C CFString, Selector ref or
998 // Class ref that name is returned and the ReferenceType is set accordingly.
1000 // Lastly, literals which are Symbol address in a literal pool are looked for
1001 // and if found the symbol name is returned and ReferenceType is set to
1002 // LLVMDisassembler_ReferenceType_Out_LitPool_SymAddr .
1004 // If there is no item in the Mach-O file for the address passed in as
1005 // ReferenceValue nullptr is returned and ReferenceType is unchanged.
1006 const char *GuessLiteralPointer(uint64_t ReferenceValue, uint64_t ReferencePC,
1007 uint64_t *ReferenceType,
1008 struct DisassembleInfo *info) {
1009 // TODO: This rouine's code and the routines it calls are only work with
1010 // x86_64 Mach-O files for now.
1011 unsigned int Arch = info->O->getArch();
1012 if (Arch != Triple::x86_64)
1015 // First see if there is an external relocation entry at the ReferencePC.
1016 uint64_t sect_addr = info->S.getAddress();
1017 uint64_t sect_offset = ReferencePC - sect_addr;
1018 bool reloc_found = false;
1020 MachO::any_relocation_info RE;
1021 bool isExtern = false;
1023 for (const RelocationRef &Reloc : info->S.relocations()) {
1024 uint64_t RelocOffset;
1025 Reloc.getOffset(RelocOffset);
1026 if (RelocOffset == sect_offset) {
1027 Rel = Reloc.getRawDataRefImpl();
1028 RE = info->O->getRelocation(Rel);
1029 if (info->O->isRelocationScattered(RE))
1031 isExtern = info->O->getPlainRelocationExternal(RE);
1033 symbol_iterator RelocSym = Reloc.getSymbol();
1040 // If there is an external relocation entry for a symbol in a section
1041 // then used that symbol's value for the value of the reference.
1042 if (reloc_found && isExtern) {
1043 if (info->O->getAnyRelocationPCRel(RE)) {
1044 unsigned Type = info->O->getAnyRelocationType(RE);
1045 if (Type == MachO::X86_64_RELOC_SIGNED) {
1046 Symbol.getAddress(ReferenceValue);
1051 // Look for literals such as Objective-C CFStrings refs, Selector refs,
1052 // Message refs and Class refs.
1053 bool classref, selref, msgref, cfstring;
1054 uint64_t pointer_value = GuessPointerPointer(ReferenceValue, info, classref,
1055 selref, msgref, cfstring);
1056 if (classref == true && pointer_value == 0) {
1057 // Note the ReferenceValue is a pointer into the __objc_classrefs section.
1058 // And the pointer_value in that section is typically zero as it will be
1059 // set by dyld as part of the "bind information".
1060 const char *name = get_dyld_bind_info_symbolname(ReferenceValue, info);
1061 if (name != nullptr) {
1062 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Class_Ref;
1063 const char *class_name = strrchr(name, '$');
1064 if (class_name != nullptr && class_name[1] == '_' &&
1065 class_name[2] != '\0') {
1066 info->class_name = class_name + 2;
1072 if (classref == true) {
1073 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Class_Ref;
1075 get_objc2_64bit_class_name(pointer_value, ReferenceValue, info);
1076 if (name != nullptr)
1077 info->class_name = name;
1079 name = "bad class ref";
1083 if (cfstring == true) {
1084 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_CFString_Ref;
1085 const char *name = get_objc2_64bit_cfstring_name(ReferenceValue, info);
1089 if (selref == true && pointer_value == 0)
1090 pointer_value = get_objc2_64bit_selref(ReferenceValue, info);
1092 if (pointer_value != 0)
1093 ReferenceValue = pointer_value;
1095 const char *name = GuessCstringPointer(ReferenceValue, info);
1097 if (pointer_value != 0 && selref == true) {
1098 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Selector_Ref;
1099 info->selector_name = name;
1100 } else if (pointer_value != 0 && msgref == true) {
1101 info->class_name = nullptr;
1102 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message_Ref;
1103 info->selector_name = name;
1105 *ReferenceType = LLVMDisassembler_ReferenceType_Out_LitPool_CstrAddr;
1109 // Lastly look for an indirect symbol with this ReferenceValue which is in
1110 // a literal pool. If found return that symbol name.
1111 name = GuessIndirectSymbol(ReferenceValue, info);
1113 *ReferenceType = LLVMDisassembler_ReferenceType_Out_LitPool_SymAddr;
1120 // SymbolizerSymbolLookUp is the symbol lookup function passed when creating
1121 // the Symbolizer. It looks up the ReferenceValue using the info passed via the
1122 // pointer to the struct DisassembleInfo that was passed when MCSymbolizer
1123 // is created and returns the symbol name that matches the ReferenceValue or
1124 // nullptr if none. The ReferenceType is passed in for the IN type of
1125 // reference the instruction is making from the values in defined in the header
1126 // "llvm-c/Disassembler.h". On return the ReferenceType can set to a specific
1127 // Out type and the ReferenceName will also be set which is added as a comment
1128 // to the disassembled instruction.
1131 // If the symbol name is a C++ mangled name then the demangled name is
1132 // returned through ReferenceName and ReferenceType is set to
1133 // LLVMDisassembler_ReferenceType_DeMangled_Name .
1136 // When this is called to get a symbol name for a branch target then the
1137 // ReferenceType will be LLVMDisassembler_ReferenceType_In_Branch and then
1138 // SymbolValue will be looked for in the indirect symbol table to determine if
1139 // it is an address for a symbol stub. If so then the symbol name for that
1140 // stub is returned indirectly through ReferenceName and then ReferenceType is
1141 // set to LLVMDisassembler_ReferenceType_Out_SymbolStub.
1143 // When this is called with an value loaded via a PC relative load then
1144 // ReferenceType will be LLVMDisassembler_ReferenceType_In_PCrel_Load then the
1145 // SymbolValue is checked to be an address of literal pointer, symbol pointer,
1146 // or an Objective-C meta data reference. If so the output ReferenceType is
1147 // set to correspond to that as well as setting the ReferenceName.
1148 const char *SymbolizerSymbolLookUp(void *DisInfo, uint64_t ReferenceValue,
1149 uint64_t *ReferenceType,
1150 uint64_t ReferencePC,
1151 const char **ReferenceName) {
1152 struct DisassembleInfo *info = (struct DisassembleInfo *)DisInfo;
1153 // If no verbose symbolic information is wanted then just return nullptr.
1154 if (info->verbose == false) {
1155 *ReferenceName = nullptr;
1156 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
1160 const char *SymbolName = GuessSymbolName(ReferenceValue, info);
1162 if (*ReferenceType == LLVMDisassembler_ReferenceType_In_Branch) {
1163 *ReferenceName = GuessIndirectSymbol(ReferenceValue, info);
1164 if (*ReferenceName != nullptr) {
1165 method_reference(info, ReferenceType, ReferenceName);
1166 if (*ReferenceType != LLVMDisassembler_ReferenceType_Out_Objc_Message)
1167 *ReferenceType = LLVMDisassembler_ReferenceType_Out_SymbolStub;
1170 if (SymbolName != nullptr && strncmp(SymbolName, "__Z", 3) == 0) {
1171 if (info->demangled_name != nullptr)
1172 free(info->demangled_name);
1174 info->demangled_name =
1175 abi::__cxa_demangle(SymbolName + 1, nullptr, nullptr, &status);
1176 if (info->demangled_name != nullptr) {
1177 *ReferenceName = info->demangled_name;
1178 *ReferenceType = LLVMDisassembler_ReferenceType_DeMangled_Name;
1180 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
1183 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
1184 } else if (*ReferenceType == LLVMDisassembler_ReferenceType_In_PCrel_Load) {
1186 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
1188 method_reference(info, ReferenceType, ReferenceName);
1190 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
1193 else if (SymbolName != nullptr && strncmp(SymbolName, "__Z", 3) == 0) {
1194 if (info->demangled_name != nullptr)
1195 free(info->demangled_name);
1197 info->demangled_name =
1198 abi::__cxa_demangle(SymbolName + 1, nullptr, nullptr, &status);
1199 if (info->demangled_name != nullptr) {
1200 *ReferenceName = info->demangled_name;
1201 *ReferenceType = LLVMDisassembler_ReferenceType_DeMangled_Name;
1206 *ReferenceName = nullptr;
1207 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
1214 // This is the memory object used by DisAsm->getInstruction() which has its
1215 // BasePC. This then allows the 'address' parameter to getInstruction() to
1216 // be the actual PC of the instruction. Then when a branch dispacement is
1217 // added to the PC of an instruction, the 'ReferenceValue' passed to the
1218 // SymbolizerSymbolLookUp() routine is the correct target addresses. As in
1219 // the case of a fully linked Mach-O file where a section being disassembled
1220 // generally not linked at address zero.
1222 class DisasmMemoryObject : public MemoryObject {
1223 const uint8_t *Bytes;
1228 DisasmMemoryObject(const uint8_t *bytes, uint64_t size, uint64_t basePC)
1229 : Bytes(bytes), Size(size), BasePC(basePC) {}
1231 uint64_t getBase() const override { return BasePC; }
1232 uint64_t getExtent() const override { return Size; }
1234 int readByte(uint64_t Addr, uint8_t *Byte) const override {
1235 if (Addr - BasePC >= Size)
1237 *Byte = Bytes[Addr - BasePC];
1242 /// \brief Emits the comments that are stored in the CommentStream.
1243 /// Each comment in the CommentStream must end with a newline.
1244 static void emitComments(raw_svector_ostream &CommentStream,
1245 SmallString<128> &CommentsToEmit,
1246 formatted_raw_ostream &FormattedOS,
1247 const MCAsmInfo &MAI) {
1248 // Flush the stream before taking its content.
1249 CommentStream.flush();
1250 StringRef Comments = CommentsToEmit.str();
1251 // Get the default information for printing a comment.
1252 const char *CommentBegin = MAI.getCommentString();
1253 unsigned CommentColumn = MAI.getCommentColumn();
1254 bool IsFirst = true;
1255 while (!Comments.empty()) {
1257 FormattedOS << '\n';
1258 // Emit a line of comments.
1259 FormattedOS.PadToColumn(CommentColumn);
1260 size_t Position = Comments.find('\n');
1261 FormattedOS << CommentBegin << ' ' << Comments.substr(0, Position);
1262 // Move after the newline character.
1263 Comments = Comments.substr(Position + 1);
1266 FormattedOS.flush();
1268 // Tell the comment stream that the vector changed underneath it.
1269 CommentsToEmit.clear();
1270 CommentStream.resync();
1273 static void DisassembleInputMachO2(StringRef Filename,
1274 MachOObjectFile *MachOOF) {
1275 const char *McpuDefault = nullptr;
1276 const Target *ThumbTarget = nullptr;
1277 const Target *TheTarget = GetTarget(MachOOF, &McpuDefault, &ThumbTarget);
1279 // GetTarget prints out stuff.
1282 if (MCPU.empty() && McpuDefault)
1285 std::unique_ptr<const MCInstrInfo> InstrInfo(TheTarget->createMCInstrInfo());
1286 std::unique_ptr<MCInstrAnalysis> InstrAnalysis(
1287 TheTarget->createMCInstrAnalysis(InstrInfo.get()));
1288 std::unique_ptr<const MCInstrInfo> ThumbInstrInfo;
1289 std::unique_ptr<MCInstrAnalysis> ThumbInstrAnalysis;
1291 ThumbInstrInfo.reset(ThumbTarget->createMCInstrInfo());
1292 ThumbInstrAnalysis.reset(
1293 ThumbTarget->createMCInstrAnalysis(ThumbInstrInfo.get()));
1296 // Package up features to be passed to target/subtarget
1297 std::string FeaturesStr;
1298 if (MAttrs.size()) {
1299 SubtargetFeatures Features;
1300 for (unsigned i = 0; i != MAttrs.size(); ++i)
1301 Features.AddFeature(MAttrs[i]);
1302 FeaturesStr = Features.getString();
1305 // Set up disassembler.
1306 std::unique_ptr<const MCRegisterInfo> MRI(
1307 TheTarget->createMCRegInfo(TripleName));
1308 std::unique_ptr<const MCAsmInfo> AsmInfo(
1309 TheTarget->createMCAsmInfo(*MRI, TripleName));
1310 std::unique_ptr<const MCSubtargetInfo> STI(
1311 TheTarget->createMCSubtargetInfo(TripleName, MCPU, FeaturesStr));
1312 MCContext Ctx(AsmInfo.get(), MRI.get(), nullptr);
1313 std::unique_ptr<MCDisassembler> DisAsm(
1314 TheTarget->createMCDisassembler(*STI, Ctx));
1315 std::unique_ptr<MCSymbolizer> Symbolizer;
1316 struct DisassembleInfo SymbolizerInfo;
1317 std::unique_ptr<MCRelocationInfo> RelInfo(
1318 TheTarget->createMCRelocationInfo(TripleName, Ctx));
1320 Symbolizer.reset(TheTarget->createMCSymbolizer(
1321 TripleName, SymbolizerGetOpInfo, SymbolizerSymbolLookUp,
1322 &SymbolizerInfo, &Ctx, RelInfo.release()));
1323 DisAsm->setSymbolizer(std::move(Symbolizer));
1325 int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
1326 std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
1327 AsmPrinterVariant, *AsmInfo, *InstrInfo, *MRI, *STI));
1328 // Set the display preference for hex vs. decimal immediates.
1329 IP->setPrintImmHex(PrintImmHex);
1330 // Comment stream and backing vector.
1331 SmallString<128> CommentsToEmit;
1332 raw_svector_ostream CommentStream(CommentsToEmit);
1333 IP->setCommentStream(CommentStream);
1335 if (!InstrAnalysis || !AsmInfo || !STI || !DisAsm || !IP) {
1336 errs() << "error: couldn't initialize disassembler for target "
1337 << TripleName << '\n';
1341 // Set up thumb disassembler.
1342 std::unique_ptr<const MCRegisterInfo> ThumbMRI;
1343 std::unique_ptr<const MCAsmInfo> ThumbAsmInfo;
1344 std::unique_ptr<const MCSubtargetInfo> ThumbSTI;
1345 std::unique_ptr<const MCDisassembler> ThumbDisAsm;
1346 std::unique_ptr<MCInstPrinter> ThumbIP;
1347 std::unique_ptr<MCContext> ThumbCtx;
1349 ThumbMRI.reset(ThumbTarget->createMCRegInfo(ThumbTripleName));
1351 ThumbTarget->createMCAsmInfo(*ThumbMRI, ThumbTripleName));
1353 ThumbTarget->createMCSubtargetInfo(ThumbTripleName, MCPU, FeaturesStr));
1354 ThumbCtx.reset(new MCContext(ThumbAsmInfo.get(), ThumbMRI.get(), nullptr));
1355 ThumbDisAsm.reset(ThumbTarget->createMCDisassembler(*ThumbSTI, *ThumbCtx));
1356 // TODO: add MCSymbolizer here for the ThumbTarget like above for TheTarget.
1357 int ThumbAsmPrinterVariant = ThumbAsmInfo->getAssemblerDialect();
1358 ThumbIP.reset(ThumbTarget->createMCInstPrinter(
1359 ThumbAsmPrinterVariant, *ThumbAsmInfo, *ThumbInstrInfo, *ThumbMRI,
1361 // Set the display preference for hex vs. decimal immediates.
1362 ThumbIP->setPrintImmHex(PrintImmHex);
1365 if (ThumbTarget && (!ThumbInstrAnalysis || !ThumbAsmInfo || !ThumbSTI ||
1366 !ThumbDisAsm || !ThumbIP)) {
1367 errs() << "error: couldn't initialize disassembler for target "
1368 << ThumbTripleName << '\n';
1372 outs() << '\n' << Filename << ":\n\n";
1374 MachO::mach_header Header = MachOOF->getHeader();
1376 // FIXME: Using the -cfg command line option, this code used to be able to
1377 // annotate relocations with the referenced symbol's name, and if this was
1378 // inside a __[cf]string section, the data it points to. This is now replaced
1379 // by the upcoming MCSymbolizer, which needs the appropriate setup done above.
1380 std::vector<SectionRef> Sections;
1381 std::vector<SymbolRef> Symbols;
1382 SmallVector<uint64_t, 8> FoundFns;
1383 uint64_t BaseSegmentAddress;
1385 getSectionsAndSymbols(Header, MachOOF, Sections, Symbols, FoundFns,
1386 BaseSegmentAddress);
1388 // Sort the symbols by address, just in case they didn't come in that way.
1389 std::sort(Symbols.begin(), Symbols.end(), SymbolSorter());
1391 // Build a data in code table that is sorted on by the address of each entry.
1392 uint64_t BaseAddress = 0;
1393 if (Header.filetype == MachO::MH_OBJECT)
1394 BaseAddress = Sections[0].getAddress();
1396 BaseAddress = BaseSegmentAddress;
1398 for (dice_iterator DI = MachOOF->begin_dices(), DE = MachOOF->end_dices();
1401 DI->getOffset(Offset);
1402 Dices.push_back(std::make_pair(BaseAddress + Offset, *DI));
1404 array_pod_sort(Dices.begin(), Dices.end());
1407 raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls();
1409 raw_ostream &DebugOut = nulls();
1412 std::unique_ptr<DIContext> diContext;
1413 ObjectFile *DbgObj = MachOOF;
1414 // Try to find debug info and set up the DIContext for it.
1416 // A separate DSym file path was specified, parse it as a macho file,
1417 // get the sections and supply it to the section name parsing machinery.
1418 if (!DSYMFile.empty()) {
1419 ErrorOr<std::unique_ptr<MemoryBuffer>> BufOrErr =
1420 MemoryBuffer::getFileOrSTDIN(DSYMFile);
1421 if (std::error_code EC = BufOrErr.getError()) {
1422 errs() << "llvm-objdump: " << Filename << ": " << EC.message() << '\n';
1426 ObjectFile::createMachOObjectFile(BufOrErr.get()->getMemBufferRef())
1431 // Setup the DIContext
1432 diContext.reset(DIContext::getDWARFContext(*DbgObj));
1435 for (unsigned SectIdx = 0; SectIdx != Sections.size(); SectIdx++) {
1437 bool SectIsText = Sections[SectIdx].isText();
1438 if (SectIsText == false)
1442 if (Sections[SectIdx].getName(SectName) || SectName != "__text")
1443 continue; // Skip non-text sections
1445 DataRefImpl DR = Sections[SectIdx].getRawDataRefImpl();
1447 StringRef SegmentName = MachOOF->getSectionFinalSegmentName(DR);
1448 if (SegmentName != "__TEXT")
1452 Sections[SectIdx].getContents(Bytes);
1453 uint64_t SectAddress = Sections[SectIdx].getAddress();
1454 DisasmMemoryObject MemoryObject((const uint8_t *)Bytes.data(), Bytes.size(),
1456 bool symbolTableWorked = false;
1458 // Parse relocations.
1459 std::vector<std::pair<uint64_t, SymbolRef>> Relocs;
1460 for (const RelocationRef &Reloc : Sections[SectIdx].relocations()) {
1461 uint64_t RelocOffset;
1462 Reloc.getOffset(RelocOffset);
1463 uint64_t SectionAddress = Sections[SectIdx].getAddress();
1464 RelocOffset -= SectionAddress;
1466 symbol_iterator RelocSym = Reloc.getSymbol();
1468 Relocs.push_back(std::make_pair(RelocOffset, *RelocSym));
1470 array_pod_sort(Relocs.begin(), Relocs.end());
1472 // Create a map of symbol addresses to symbol names for use by
1473 // the SymbolizerSymbolLookUp() routine.
1474 SymbolAddressMap AddrMap;
1475 for (const SymbolRef &Symbol : MachOOF->symbols()) {
1478 if (ST == SymbolRef::ST_Function || ST == SymbolRef::ST_Data ||
1479 ST == SymbolRef::ST_Other) {
1481 Symbol.getAddress(Address);
1483 Symbol.getName(SymName);
1484 AddrMap[Address] = SymName;
1487 // Set up the block of info used by the Symbolizer call backs.
1488 SymbolizerInfo.verbose = true;
1489 SymbolizerInfo.O = MachOOF;
1490 SymbolizerInfo.S = Sections[SectIdx];
1491 SymbolizerInfo.AddrMap = &AddrMap;
1492 SymbolizerInfo.Sections = &Sections;
1493 SymbolizerInfo.class_name = nullptr;
1494 SymbolizerInfo.selector_name = nullptr;
1495 SymbolizerInfo.method = nullptr;
1496 SymbolizerInfo.demangled_name = nullptr;
1497 SymbolizerInfo.bindtable = nullptr;
1499 // Disassemble symbol by symbol.
1500 for (unsigned SymIdx = 0; SymIdx != Symbols.size(); SymIdx++) {
1502 Symbols[SymIdx].getName(SymName);
1505 Symbols[SymIdx].getType(ST);
1506 if (ST != SymbolRef::ST_Function)
1509 // Make sure the symbol is defined in this section.
1510 bool containsSym = Sections[SectIdx].containsSymbol(Symbols[SymIdx]);
1514 // Start at the address of the symbol relative to the section's address.
1516 uint64_t SectionAddress = Sections[SectIdx].getAddress();
1517 Symbols[SymIdx].getAddress(Start);
1518 Start -= SectionAddress;
1520 // Stop disassembling either at the beginning of the next symbol or at
1521 // the end of the section.
1522 bool containsNextSym = false;
1523 uint64_t NextSym = 0;
1524 uint64_t NextSymIdx = SymIdx + 1;
1525 while (Symbols.size() > NextSymIdx) {
1526 SymbolRef::Type NextSymType;
1527 Symbols[NextSymIdx].getType(NextSymType);
1528 if (NextSymType == SymbolRef::ST_Function) {
1530 Sections[SectIdx].containsSymbol(Symbols[NextSymIdx]);
1531 Symbols[NextSymIdx].getAddress(NextSym);
1532 NextSym -= SectionAddress;
1538 uint64_t SectSize = Sections[SectIdx].getSize();
1539 uint64_t End = containsNextSym ? NextSym : SectSize;
1542 symbolTableWorked = true;
1543 DisasmMemoryObject SectionMemoryObject((const uint8_t *)Bytes.data() +
1545 End - Start, SectAddress + Start);
1547 DataRefImpl Symb = Symbols[SymIdx].getRawDataRefImpl();
1549 (MachOOF->getSymbolFlags(Symb) & SymbolRef::SF_Thumb) && ThumbTarget;
1551 outs() << SymName << ":\n";
1552 DILineInfo lastLine;
1553 for (uint64_t Index = Start; Index < End; Index += Size) {
1556 uint64_t PC = SectAddress + Index;
1557 if (FullLeadingAddr) {
1558 if (MachOOF->is64Bit())
1559 outs() << format("%016" PRIx64, PC);
1561 outs() << format("%08" PRIx64, PC);
1563 outs() << format("%8" PRIx64 ":", PC);
1568 // Check the data in code table here to see if this is data not an
1569 // instruction to be disassembled.
1571 Dice.push_back(std::make_pair(PC, DiceRef()));
1572 dice_table_iterator DTI =
1573 std::search(Dices.begin(), Dices.end(), Dice.begin(), Dice.end(),
1574 compareDiceTableEntries);
1575 if (DTI != Dices.end()) {
1577 DTI->second.getLength(Length);
1578 DumpBytes(StringRef(Bytes.data() + Index, Length));
1580 DTI->second.getKind(Kind);
1581 DumpDataInCode(Bytes.data() + Index, Length, Kind);
1585 SmallVector<char, 64> AnnotationsBytes;
1586 raw_svector_ostream Annotations(AnnotationsBytes);
1590 gotInst = ThumbDisAsm->getInstruction(Inst, Size, SectionMemoryObject,
1591 PC, DebugOut, Annotations);
1593 gotInst = DisAsm->getInstruction(Inst, Size, SectionMemoryObject, PC,
1594 DebugOut, Annotations);
1596 if (!NoShowRawInsn) {
1597 DumpBytes(StringRef(Bytes.data() + Index, Size));
1599 formatted_raw_ostream FormattedOS(outs());
1600 Annotations.flush();
1601 StringRef AnnotationsStr = Annotations.str();
1603 ThumbIP->printInst(&Inst, FormattedOS, AnnotationsStr);
1605 IP->printInst(&Inst, FormattedOS, AnnotationsStr);
1606 emitComments(CommentStream, CommentsToEmit, FormattedOS, *AsmInfo);
1608 // Print debug info.
1610 DILineInfo dli = diContext->getLineInfoForAddress(PC);
1611 // Print valid line info if it changed.
1612 if (dli != lastLine && dli.Line != 0)
1613 outs() << "\t## " << dli.FileName << ':' << dli.Line << ':'
1619 unsigned int Arch = MachOOF->getArch();
1620 if (Arch == Triple::x86_64 || Arch == Triple::x86) {
1621 outs() << format("\t.byte 0x%02x #bad opcode\n",
1622 *(Bytes.data() + Index) & 0xff);
1623 Size = 1; // skip exactly one illegible byte and move on.
1625 errs() << "llvm-objdump: warning: invalid instruction encoding\n";
1627 Size = 1; // skip illegible bytes
1632 if (!symbolTableWorked) {
1633 // Reading the symbol table didn't work, disassemble the whole section.
1634 uint64_t SectAddress = Sections[SectIdx].getAddress();
1635 uint64_t SectSize = Sections[SectIdx].getSize();
1637 for (uint64_t Index = 0; Index < SectSize; Index += InstSize) {
1640 uint64_t PC = SectAddress + Index;
1641 if (DisAsm->getInstruction(Inst, InstSize, MemoryObject, PC, DebugOut,
1643 if (FullLeadingAddr) {
1644 if (MachOOF->is64Bit())
1645 outs() << format("%016" PRIx64, PC);
1647 outs() << format("%08" PRIx64, PC);
1649 outs() << format("%8" PRIx64 ":", PC);
1651 if (!NoShowRawInsn) {
1653 DumpBytes(StringRef(Bytes.data() + Index, InstSize));
1655 IP->printInst(&Inst, outs(), "");
1658 unsigned int Arch = MachOOF->getArch();
1659 if (Arch == Triple::x86_64 || Arch == Triple::x86) {
1660 outs() << format("\t.byte 0x%02x #bad opcode\n",
1661 *(Bytes.data() + Index) & 0xff);
1662 InstSize = 1; // skip exactly one illegible byte and move on.
1664 errs() << "llvm-objdump: warning: invalid instruction encoding\n";
1666 InstSize = 1; // skip illegible bytes
1671 if (SymbolizerInfo.method != nullptr)
1672 free(SymbolizerInfo.method);
1673 if (SymbolizerInfo.demangled_name != nullptr)
1674 free(SymbolizerInfo.demangled_name);
1675 if (SymbolizerInfo.bindtable != nullptr)
1676 delete SymbolizerInfo.bindtable;
1680 //===----------------------------------------------------------------------===//
1681 // __compact_unwind section dumping
1682 //===----------------------------------------------------------------------===//
1686 template <typename T> static uint64_t readNext(const char *&Buf) {
1687 using llvm::support::little;
1688 using llvm::support::unaligned;
1690 uint64_t Val = support::endian::read<T, little, unaligned>(Buf);
1695 struct CompactUnwindEntry {
1696 uint32_t OffsetInSection;
1698 uint64_t FunctionAddr;
1700 uint32_t CompactEncoding;
1701 uint64_t PersonalityAddr;
1704 RelocationRef FunctionReloc;
1705 RelocationRef PersonalityReloc;
1706 RelocationRef LSDAReloc;
1708 CompactUnwindEntry(StringRef Contents, unsigned Offset, bool Is64)
1709 : OffsetInSection(Offset) {
1711 read<uint64_t>(Contents.data() + Offset);
1713 read<uint32_t>(Contents.data() + Offset);
1717 template <typename UIntPtr> void read(const char *Buf) {
1718 FunctionAddr = readNext<UIntPtr>(Buf);
1719 Length = readNext<uint32_t>(Buf);
1720 CompactEncoding = readNext<uint32_t>(Buf);
1721 PersonalityAddr = readNext<UIntPtr>(Buf);
1722 LSDAAddr = readNext<UIntPtr>(Buf);
1727 /// Given a relocation from __compact_unwind, consisting of the RelocationRef
1728 /// and data being relocated, determine the best base Name and Addend to use for
1729 /// display purposes.
1731 /// 1. An Extern relocation will directly reference a symbol (and the data is
1732 /// then already an addend), so use that.
1733 /// 2. Otherwise the data is an offset in the object file's layout; try to find
1734 // a symbol before it in the same section, and use the offset from there.
1735 /// 3. Finally, if all that fails, fall back to an offset from the start of the
1736 /// referenced section.
1737 static void findUnwindRelocNameAddend(const MachOObjectFile *Obj,
1738 std::map<uint64_t, SymbolRef> &Symbols,
1739 const RelocationRef &Reloc, uint64_t Addr,
1740 StringRef &Name, uint64_t &Addend) {
1741 if (Reloc.getSymbol() != Obj->symbol_end()) {
1742 Reloc.getSymbol()->getName(Name);
1747 auto RE = Obj->getRelocation(Reloc.getRawDataRefImpl());
1748 SectionRef RelocSection = Obj->getRelocationSection(RE);
1750 uint64_t SectionAddr = RelocSection.getAddress();
1752 auto Sym = Symbols.upper_bound(Addr);
1753 if (Sym == Symbols.begin()) {
1754 // The first symbol in the object is after this reference, the best we can
1755 // do is section-relative notation.
1756 RelocSection.getName(Name);
1757 Addend = Addr - SectionAddr;
1761 // Go back one so that SymbolAddress <= Addr.
1764 section_iterator SymSection = Obj->section_end();
1765 Sym->second.getSection(SymSection);
1766 if (RelocSection == *SymSection) {
1767 // There's a valid symbol in the same section before this reference.
1768 Sym->second.getName(Name);
1769 Addend = Addr - Sym->first;
1773 // There is a symbol before this reference, but it's in a different
1774 // section. Probably not helpful to mention it, so use the section name.
1775 RelocSection.getName(Name);
1776 Addend = Addr - SectionAddr;
1779 static void printUnwindRelocDest(const MachOObjectFile *Obj,
1780 std::map<uint64_t, SymbolRef> &Symbols,
1781 const RelocationRef &Reloc, uint64_t Addr) {
1785 if (!Reloc.getObjectFile())
1788 findUnwindRelocNameAddend(Obj, Symbols, Reloc, Addr, Name, Addend);
1792 outs() << " + " << format("0x%" PRIx64, Addend);
1796 printMachOCompactUnwindSection(const MachOObjectFile *Obj,
1797 std::map<uint64_t, SymbolRef> &Symbols,
1798 const SectionRef &CompactUnwind) {
1800 assert(Obj->isLittleEndian() &&
1801 "There should not be a big-endian .o with __compact_unwind");
1803 bool Is64 = Obj->is64Bit();
1804 uint32_t PointerSize = Is64 ? sizeof(uint64_t) : sizeof(uint32_t);
1805 uint32_t EntrySize = 3 * PointerSize + 2 * sizeof(uint32_t);
1808 CompactUnwind.getContents(Contents);
1810 SmallVector<CompactUnwindEntry, 4> CompactUnwinds;
1812 // First populate the initial raw offsets, encodings and so on from the entry.
1813 for (unsigned Offset = 0; Offset < Contents.size(); Offset += EntrySize) {
1814 CompactUnwindEntry Entry(Contents.data(), Offset, Is64);
1815 CompactUnwinds.push_back(Entry);
1818 // Next we need to look at the relocations to find out what objects are
1819 // actually being referred to.
1820 for (const RelocationRef &Reloc : CompactUnwind.relocations()) {
1821 uint64_t RelocAddress;
1822 Reloc.getOffset(RelocAddress);
1824 uint32_t EntryIdx = RelocAddress / EntrySize;
1825 uint32_t OffsetInEntry = RelocAddress - EntryIdx * EntrySize;
1826 CompactUnwindEntry &Entry = CompactUnwinds[EntryIdx];
1828 if (OffsetInEntry == 0)
1829 Entry.FunctionReloc = Reloc;
1830 else if (OffsetInEntry == PointerSize + 2 * sizeof(uint32_t))
1831 Entry.PersonalityReloc = Reloc;
1832 else if (OffsetInEntry == 2 * PointerSize + 2 * sizeof(uint32_t))
1833 Entry.LSDAReloc = Reloc;
1835 llvm_unreachable("Unexpected relocation in __compact_unwind section");
1838 // Finally, we're ready to print the data we've gathered.
1839 outs() << "Contents of __compact_unwind section:\n";
1840 for (auto &Entry : CompactUnwinds) {
1841 outs() << " Entry at offset "
1842 << format("0x%" PRIx32, Entry.OffsetInSection) << ":\n";
1844 // 1. Start of the region this entry applies to.
1845 outs() << " start: " << format("0x%" PRIx64,
1846 Entry.FunctionAddr) << ' ';
1847 printUnwindRelocDest(Obj, Symbols, Entry.FunctionReloc, Entry.FunctionAddr);
1850 // 2. Length of the region this entry applies to.
1851 outs() << " length: " << format("0x%" PRIx32, Entry.Length)
1853 // 3. The 32-bit compact encoding.
1854 outs() << " compact encoding: "
1855 << format("0x%08" PRIx32, Entry.CompactEncoding) << '\n';
1857 // 4. The personality function, if present.
1858 if (Entry.PersonalityReloc.getObjectFile()) {
1859 outs() << " personality function: "
1860 << format("0x%" PRIx64, Entry.PersonalityAddr) << ' ';
1861 printUnwindRelocDest(Obj, Symbols, Entry.PersonalityReloc,
1862 Entry.PersonalityAddr);
1866 // 5. This entry's language-specific data area.
1867 if (Entry.LSDAReloc.getObjectFile()) {
1868 outs() << " LSDA: " << format("0x%" PRIx64,
1869 Entry.LSDAAddr) << ' ';
1870 printUnwindRelocDest(Obj, Symbols, Entry.LSDAReloc, Entry.LSDAAddr);
1876 //===----------------------------------------------------------------------===//
1877 // __unwind_info section dumping
1878 //===----------------------------------------------------------------------===//
1880 static void printRegularSecondLevelUnwindPage(const char *PageStart) {
1881 const char *Pos = PageStart;
1882 uint32_t Kind = readNext<uint32_t>(Pos);
1884 assert(Kind == 2 && "kind for a regular 2nd level index should be 2");
1886 uint16_t EntriesStart = readNext<uint16_t>(Pos);
1887 uint16_t NumEntries = readNext<uint16_t>(Pos);
1889 Pos = PageStart + EntriesStart;
1890 for (unsigned i = 0; i < NumEntries; ++i) {
1891 uint32_t FunctionOffset = readNext<uint32_t>(Pos);
1892 uint32_t Encoding = readNext<uint32_t>(Pos);
1894 outs() << " [" << i << "]: "
1895 << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
1897 << "encoding=" << format("0x%08" PRIx32, Encoding) << '\n';
1901 static void printCompressedSecondLevelUnwindPage(
1902 const char *PageStart, uint32_t FunctionBase,
1903 const SmallVectorImpl<uint32_t> &CommonEncodings) {
1904 const char *Pos = PageStart;
1905 uint32_t Kind = readNext<uint32_t>(Pos);
1907 assert(Kind == 3 && "kind for a compressed 2nd level index should be 3");
1909 uint16_t EntriesStart = readNext<uint16_t>(Pos);
1910 uint16_t NumEntries = readNext<uint16_t>(Pos);
1912 uint16_t EncodingsStart = readNext<uint16_t>(Pos);
1913 readNext<uint16_t>(Pos);
1914 const auto *PageEncodings = reinterpret_cast<const support::ulittle32_t *>(
1915 PageStart + EncodingsStart);
1917 Pos = PageStart + EntriesStart;
1918 for (unsigned i = 0; i < NumEntries; ++i) {
1919 uint32_t Entry = readNext<uint32_t>(Pos);
1920 uint32_t FunctionOffset = FunctionBase + (Entry & 0xffffff);
1921 uint32_t EncodingIdx = Entry >> 24;
1924 if (EncodingIdx < CommonEncodings.size())
1925 Encoding = CommonEncodings[EncodingIdx];
1927 Encoding = PageEncodings[EncodingIdx - CommonEncodings.size()];
1929 outs() << " [" << i << "]: "
1930 << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
1932 << "encoding[" << EncodingIdx
1933 << "]=" << format("0x%08" PRIx32, Encoding) << '\n';
1937 static void printMachOUnwindInfoSection(const MachOObjectFile *Obj,
1938 std::map<uint64_t, SymbolRef> &Symbols,
1939 const SectionRef &UnwindInfo) {
1941 assert(Obj->isLittleEndian() &&
1942 "There should not be a big-endian .o with __unwind_info");
1944 outs() << "Contents of __unwind_info section:\n";
1947 UnwindInfo.getContents(Contents);
1948 const char *Pos = Contents.data();
1950 //===----------------------------------
1952 //===----------------------------------
1954 uint32_t Version = readNext<uint32_t>(Pos);
1955 outs() << " Version: "
1956 << format("0x%" PRIx32, Version) << '\n';
1957 assert(Version == 1 && "only understand version 1");
1959 uint32_t CommonEncodingsStart = readNext<uint32_t>(Pos);
1960 outs() << " Common encodings array section offset: "
1961 << format("0x%" PRIx32, CommonEncodingsStart) << '\n';
1962 uint32_t NumCommonEncodings = readNext<uint32_t>(Pos);
1963 outs() << " Number of common encodings in array: "
1964 << format("0x%" PRIx32, NumCommonEncodings) << '\n';
1966 uint32_t PersonalitiesStart = readNext<uint32_t>(Pos);
1967 outs() << " Personality function array section offset: "
1968 << format("0x%" PRIx32, PersonalitiesStart) << '\n';
1969 uint32_t NumPersonalities = readNext<uint32_t>(Pos);
1970 outs() << " Number of personality functions in array: "
1971 << format("0x%" PRIx32, NumPersonalities) << '\n';
1973 uint32_t IndicesStart = readNext<uint32_t>(Pos);
1974 outs() << " Index array section offset: "
1975 << format("0x%" PRIx32, IndicesStart) << '\n';
1976 uint32_t NumIndices = readNext<uint32_t>(Pos);
1977 outs() << " Number of indices in array: "
1978 << format("0x%" PRIx32, NumIndices) << '\n';
1980 //===----------------------------------
1981 // A shared list of common encodings
1982 //===----------------------------------
1984 // These occupy indices in the range [0, N] whenever an encoding is referenced
1985 // from a compressed 2nd level index table. In practice the linker only
1986 // creates ~128 of these, so that indices are available to embed encodings in
1987 // the 2nd level index.
1989 SmallVector<uint32_t, 64> CommonEncodings;
1990 outs() << " Common encodings: (count = " << NumCommonEncodings << ")\n";
1991 Pos = Contents.data() + CommonEncodingsStart;
1992 for (unsigned i = 0; i < NumCommonEncodings; ++i) {
1993 uint32_t Encoding = readNext<uint32_t>(Pos);
1994 CommonEncodings.push_back(Encoding);
1996 outs() << " encoding[" << i << "]: " << format("0x%08" PRIx32, Encoding)
2000 //===----------------------------------
2001 // Personality functions used in this executable
2002 //===----------------------------------
2004 // There should be only a handful of these (one per source language,
2005 // roughly). Particularly since they only get 2 bits in the compact encoding.
2007 outs() << " Personality functions: (count = " << NumPersonalities << ")\n";
2008 Pos = Contents.data() + PersonalitiesStart;
2009 for (unsigned i = 0; i < NumPersonalities; ++i) {
2010 uint32_t PersonalityFn = readNext<uint32_t>(Pos);
2011 outs() << " personality[" << i + 1
2012 << "]: " << format("0x%08" PRIx32, PersonalityFn) << '\n';
2015 //===----------------------------------
2016 // The level 1 index entries
2017 //===----------------------------------
2019 // These specify an approximate place to start searching for the more detailed
2020 // information, sorted by PC.
2023 uint32_t FunctionOffset;
2024 uint32_t SecondLevelPageStart;
2028 SmallVector<IndexEntry, 4> IndexEntries;
2030 outs() << " Top level indices: (count = " << NumIndices << ")\n";
2031 Pos = Contents.data() + IndicesStart;
2032 for (unsigned i = 0; i < NumIndices; ++i) {
2035 Entry.FunctionOffset = readNext<uint32_t>(Pos);
2036 Entry.SecondLevelPageStart = readNext<uint32_t>(Pos);
2037 Entry.LSDAStart = readNext<uint32_t>(Pos);
2038 IndexEntries.push_back(Entry);
2040 outs() << " [" << i << "]: "
2041 << "function offset=" << format("0x%08" PRIx32, Entry.FunctionOffset)
2043 << "2nd level page offset="
2044 << format("0x%08" PRIx32, Entry.SecondLevelPageStart) << ", "
2045 << "LSDA offset=" << format("0x%08" PRIx32, Entry.LSDAStart) << '\n';
2048 //===----------------------------------
2049 // Next come the LSDA tables
2050 //===----------------------------------
2052 // The LSDA layout is rather implicit: it's a contiguous array of entries from
2053 // the first top-level index's LSDAOffset to the last (sentinel).
2055 outs() << " LSDA descriptors:\n";
2056 Pos = Contents.data() + IndexEntries[0].LSDAStart;
2057 int NumLSDAs = (IndexEntries.back().LSDAStart - IndexEntries[0].LSDAStart) /
2058 (2 * sizeof(uint32_t));
2059 for (int i = 0; i < NumLSDAs; ++i) {
2060 uint32_t FunctionOffset = readNext<uint32_t>(Pos);
2061 uint32_t LSDAOffset = readNext<uint32_t>(Pos);
2062 outs() << " [" << i << "]: "
2063 << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
2065 << "LSDA offset=" << format("0x%08" PRIx32, LSDAOffset) << '\n';
2068 //===----------------------------------
2069 // Finally, the 2nd level indices
2070 //===----------------------------------
2072 // Generally these are 4K in size, and have 2 possible forms:
2073 // + Regular stores up to 511 entries with disparate encodings
2074 // + Compressed stores up to 1021 entries if few enough compact encoding
2076 outs() << " Second level indices:\n";
2077 for (unsigned i = 0; i < IndexEntries.size() - 1; ++i) {
2078 // The final sentinel top-level index has no associated 2nd level page
2079 if (IndexEntries[i].SecondLevelPageStart == 0)
2082 outs() << " Second level index[" << i << "]: "
2083 << "offset in section="
2084 << format("0x%08" PRIx32, IndexEntries[i].SecondLevelPageStart)
2086 << "base function offset="
2087 << format("0x%08" PRIx32, IndexEntries[i].FunctionOffset) << '\n';
2089 Pos = Contents.data() + IndexEntries[i].SecondLevelPageStart;
2090 uint32_t Kind = *reinterpret_cast<const support::ulittle32_t *>(Pos);
2092 printRegularSecondLevelUnwindPage(Pos);
2094 printCompressedSecondLevelUnwindPage(Pos, IndexEntries[i].FunctionOffset,
2097 llvm_unreachable("Do not know how to print this kind of 2nd level page");
2101 void llvm::printMachOUnwindInfo(const MachOObjectFile *Obj) {
2102 std::map<uint64_t, SymbolRef> Symbols;
2103 for (const SymbolRef &SymRef : Obj->symbols()) {
2104 // Discard any undefined or absolute symbols. They're not going to take part
2105 // in the convenience lookup for unwind info and just take up resources.
2106 section_iterator Section = Obj->section_end();
2107 SymRef.getSection(Section);
2108 if (Section == Obj->section_end())
2112 SymRef.getAddress(Addr);
2113 Symbols.insert(std::make_pair(Addr, SymRef));
2116 for (const SectionRef &Section : Obj->sections()) {
2118 Section.getName(SectName);
2119 if (SectName == "__compact_unwind")
2120 printMachOCompactUnwindSection(Obj, Symbols, Section);
2121 else if (SectName == "__unwind_info")
2122 printMachOUnwindInfoSection(Obj, Symbols, Section);
2123 else if (SectName == "__eh_frame")
2124 outs() << "llvm-objdump: warning: unhandled __eh_frame section\n";
2128 static void PrintMachHeader(uint32_t magic, uint32_t cputype,
2129 uint32_t cpusubtype, uint32_t filetype,
2130 uint32_t ncmds, uint32_t sizeofcmds, uint32_t flags,
2132 outs() << "Mach header\n";
2133 outs() << " magic cputype cpusubtype caps filetype ncmds "
2134 "sizeofcmds flags\n";
2136 if (magic == MachO::MH_MAGIC)
2137 outs() << " MH_MAGIC";
2138 else if (magic == MachO::MH_MAGIC_64)
2139 outs() << "MH_MAGIC_64";
2141 outs() << format(" 0x%08" PRIx32, magic);
2143 case MachO::CPU_TYPE_I386:
2145 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
2146 case MachO::CPU_SUBTYPE_I386_ALL:
2150 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
2154 case MachO::CPU_TYPE_X86_64:
2155 outs() << " X86_64";
2156 case MachO::CPU_SUBTYPE_X86_64_ALL:
2159 case MachO::CPU_SUBTYPE_X86_64_H:
2160 outs() << " Haswell";
2161 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
2163 case MachO::CPU_TYPE_ARM:
2165 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
2166 case MachO::CPU_SUBTYPE_ARM_ALL:
2169 case MachO::CPU_SUBTYPE_ARM_V4T:
2172 case MachO::CPU_SUBTYPE_ARM_V5TEJ:
2175 case MachO::CPU_SUBTYPE_ARM_XSCALE:
2176 outs() << " XSCALE";
2178 case MachO::CPU_SUBTYPE_ARM_V6:
2181 case MachO::CPU_SUBTYPE_ARM_V6M:
2184 case MachO::CPU_SUBTYPE_ARM_V7:
2187 case MachO::CPU_SUBTYPE_ARM_V7EM:
2190 case MachO::CPU_SUBTYPE_ARM_V7K:
2193 case MachO::CPU_SUBTYPE_ARM_V7M:
2196 case MachO::CPU_SUBTYPE_ARM_V7S:
2200 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
2204 case MachO::CPU_TYPE_ARM64:
2206 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
2207 case MachO::CPU_SUBTYPE_ARM64_ALL:
2211 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
2215 case MachO::CPU_TYPE_POWERPC:
2217 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
2218 case MachO::CPU_SUBTYPE_POWERPC_ALL:
2222 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
2226 case MachO::CPU_TYPE_POWERPC64:
2228 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
2229 case MachO::CPU_SUBTYPE_POWERPC_ALL:
2233 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
2238 if ((cpusubtype & MachO::CPU_SUBTYPE_MASK) == MachO::CPU_SUBTYPE_LIB64) {
2241 outs() << format(" 0x%02" PRIx32,
2242 (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24);
2245 case MachO::MH_OBJECT:
2246 outs() << " OBJECT";
2248 case MachO::MH_EXECUTE:
2249 outs() << " EXECUTE";
2251 case MachO::MH_FVMLIB:
2252 outs() << " FVMLIB";
2254 case MachO::MH_CORE:
2257 case MachO::MH_PRELOAD:
2258 outs() << " PRELOAD";
2260 case MachO::MH_DYLIB:
2263 case MachO::MH_DYLIB_STUB:
2264 outs() << " DYLIB_STUB";
2266 case MachO::MH_DYLINKER:
2267 outs() << " DYLINKER";
2269 case MachO::MH_BUNDLE:
2270 outs() << " BUNDLE";
2272 case MachO::MH_DSYM:
2275 case MachO::MH_KEXT_BUNDLE:
2276 outs() << " KEXTBUNDLE";
2279 outs() << format(" %10u", filetype);
2282 outs() << format(" %5u", ncmds);
2283 outs() << format(" %10u", sizeofcmds);
2285 if (f & MachO::MH_NOUNDEFS) {
2286 outs() << " NOUNDEFS";
2287 f &= ~MachO::MH_NOUNDEFS;
2289 if (f & MachO::MH_INCRLINK) {
2290 outs() << " INCRLINK";
2291 f &= ~MachO::MH_INCRLINK;
2293 if (f & MachO::MH_DYLDLINK) {
2294 outs() << " DYLDLINK";
2295 f &= ~MachO::MH_DYLDLINK;
2297 if (f & MachO::MH_BINDATLOAD) {
2298 outs() << " BINDATLOAD";
2299 f &= ~MachO::MH_BINDATLOAD;
2301 if (f & MachO::MH_PREBOUND) {
2302 outs() << " PREBOUND";
2303 f &= ~MachO::MH_PREBOUND;
2305 if (f & MachO::MH_SPLIT_SEGS) {
2306 outs() << " SPLIT_SEGS";
2307 f &= ~MachO::MH_SPLIT_SEGS;
2309 if (f & MachO::MH_LAZY_INIT) {
2310 outs() << " LAZY_INIT";
2311 f &= ~MachO::MH_LAZY_INIT;
2313 if (f & MachO::MH_TWOLEVEL) {
2314 outs() << " TWOLEVEL";
2315 f &= ~MachO::MH_TWOLEVEL;
2317 if (f & MachO::MH_FORCE_FLAT) {
2318 outs() << " FORCE_FLAT";
2319 f &= ~MachO::MH_FORCE_FLAT;
2321 if (f & MachO::MH_NOMULTIDEFS) {
2322 outs() << " NOMULTIDEFS";
2323 f &= ~MachO::MH_NOMULTIDEFS;
2325 if (f & MachO::MH_NOFIXPREBINDING) {
2326 outs() << " NOFIXPREBINDING";
2327 f &= ~MachO::MH_NOFIXPREBINDING;
2329 if (f & MachO::MH_PREBINDABLE) {
2330 outs() << " PREBINDABLE";
2331 f &= ~MachO::MH_PREBINDABLE;
2333 if (f & MachO::MH_ALLMODSBOUND) {
2334 outs() << " ALLMODSBOUND";
2335 f &= ~MachO::MH_ALLMODSBOUND;
2337 if (f & MachO::MH_SUBSECTIONS_VIA_SYMBOLS) {
2338 outs() << " SUBSECTIONS_VIA_SYMBOLS";
2339 f &= ~MachO::MH_SUBSECTIONS_VIA_SYMBOLS;
2341 if (f & MachO::MH_CANONICAL) {
2342 outs() << " CANONICAL";
2343 f &= ~MachO::MH_CANONICAL;
2345 if (f & MachO::MH_WEAK_DEFINES) {
2346 outs() << " WEAK_DEFINES";
2347 f &= ~MachO::MH_WEAK_DEFINES;
2349 if (f & MachO::MH_BINDS_TO_WEAK) {
2350 outs() << " BINDS_TO_WEAK";
2351 f &= ~MachO::MH_BINDS_TO_WEAK;
2353 if (f & MachO::MH_ALLOW_STACK_EXECUTION) {
2354 outs() << " ALLOW_STACK_EXECUTION";
2355 f &= ~MachO::MH_ALLOW_STACK_EXECUTION;
2357 if (f & MachO::MH_DEAD_STRIPPABLE_DYLIB) {
2358 outs() << " DEAD_STRIPPABLE_DYLIB";
2359 f &= ~MachO::MH_DEAD_STRIPPABLE_DYLIB;
2361 if (f & MachO::MH_PIE) {
2363 f &= ~MachO::MH_PIE;
2365 if (f & MachO::MH_NO_REEXPORTED_DYLIBS) {
2366 outs() << " NO_REEXPORTED_DYLIBS";
2367 f &= ~MachO::MH_NO_REEXPORTED_DYLIBS;
2369 if (f & MachO::MH_HAS_TLV_DESCRIPTORS) {
2370 outs() << " MH_HAS_TLV_DESCRIPTORS";
2371 f &= ~MachO::MH_HAS_TLV_DESCRIPTORS;
2373 if (f & MachO::MH_NO_HEAP_EXECUTION) {
2374 outs() << " MH_NO_HEAP_EXECUTION";
2375 f &= ~MachO::MH_NO_HEAP_EXECUTION;
2377 if (f & MachO::MH_APP_EXTENSION_SAFE) {
2378 outs() << " APP_EXTENSION_SAFE";
2379 f &= ~MachO::MH_APP_EXTENSION_SAFE;
2381 if (f != 0 || flags == 0)
2382 outs() << format(" 0x%08" PRIx32, f);
2384 outs() << format(" 0x%08" PRIx32, magic);
2385 outs() << format(" %7d", cputype);
2386 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
2387 outs() << format(" 0x%02" PRIx32,
2388 (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24);
2389 outs() << format(" %10u", filetype);
2390 outs() << format(" %5u", ncmds);
2391 outs() << format(" %10u", sizeofcmds);
2392 outs() << format(" 0x%08" PRIx32, flags);
2397 static void PrintSegmentCommand(uint32_t cmd, uint32_t cmdsize,
2398 StringRef SegName, uint64_t vmaddr,
2399 uint64_t vmsize, uint64_t fileoff,
2400 uint64_t filesize, uint32_t maxprot,
2401 uint32_t initprot, uint32_t nsects,
2402 uint32_t flags, uint32_t object_size,
2404 uint64_t expected_cmdsize;
2405 if (cmd == MachO::LC_SEGMENT) {
2406 outs() << " cmd LC_SEGMENT\n";
2407 expected_cmdsize = nsects;
2408 expected_cmdsize *= sizeof(struct MachO::section);
2409 expected_cmdsize += sizeof(struct MachO::segment_command);
2411 outs() << " cmd LC_SEGMENT_64\n";
2412 expected_cmdsize = nsects;
2413 expected_cmdsize *= sizeof(struct MachO::section_64);
2414 expected_cmdsize += sizeof(struct MachO::segment_command_64);
2416 outs() << " cmdsize " << cmdsize;
2417 if (cmdsize != expected_cmdsize)
2418 outs() << " Inconsistent size\n";
2421 outs() << " segname " << SegName << "\n";
2422 if (cmd == MachO::LC_SEGMENT_64) {
2423 outs() << " vmaddr " << format("0x%016" PRIx64, vmaddr) << "\n";
2424 outs() << " vmsize " << format("0x%016" PRIx64, vmsize) << "\n";
2426 outs() << " vmaddr " << format("0x%08" PRIx32, vmaddr) << "\n";
2427 outs() << " vmsize " << format("0x%08" PRIx32, vmsize) << "\n";
2429 outs() << " fileoff " << fileoff;
2430 if (fileoff > object_size)
2431 outs() << " (past end of file)\n";
2434 outs() << " filesize " << filesize;
2435 if (fileoff + filesize > object_size)
2436 outs() << " (past end of file)\n";
2441 ~(MachO::VM_PROT_READ | MachO::VM_PROT_WRITE |
2442 MachO::VM_PROT_EXECUTE)) != 0)
2443 outs() << " maxprot ?" << format("0x%08" PRIx32, maxprot) << "\n";
2445 if (maxprot & MachO::VM_PROT_READ)
2446 outs() << " maxprot r";
2448 outs() << " maxprot -";
2449 if (maxprot & MachO::VM_PROT_WRITE)
2453 if (maxprot & MachO::VM_PROT_EXECUTE)
2459 ~(MachO::VM_PROT_READ | MachO::VM_PROT_WRITE |
2460 MachO::VM_PROT_EXECUTE)) != 0)
2461 outs() << " initprot ?" << format("0x%08" PRIx32, initprot) << "\n";
2463 if (initprot & MachO::VM_PROT_READ)
2464 outs() << " initprot r";
2466 outs() << " initprot -";
2467 if (initprot & MachO::VM_PROT_WRITE)
2471 if (initprot & MachO::VM_PROT_EXECUTE)
2477 outs() << " maxprot " << format("0x%08" PRIx32, maxprot) << "\n";
2478 outs() << " initprot " << format("0x%08" PRIx32, initprot) << "\n";
2480 outs() << " nsects " << nsects << "\n";
2484 outs() << " (none)\n";
2486 if (flags & MachO::SG_HIGHVM) {
2487 outs() << " HIGHVM";
2488 flags &= ~MachO::SG_HIGHVM;
2490 if (flags & MachO::SG_FVMLIB) {
2491 outs() << " FVMLIB";
2492 flags &= ~MachO::SG_FVMLIB;
2494 if (flags & MachO::SG_NORELOC) {
2495 outs() << " NORELOC";
2496 flags &= ~MachO::SG_NORELOC;
2498 if (flags & MachO::SG_PROTECTED_VERSION_1) {
2499 outs() << " PROTECTED_VERSION_1";
2500 flags &= ~MachO::SG_PROTECTED_VERSION_1;
2503 outs() << format(" 0x%08" PRIx32, flags) << " (unknown flags)\n";
2508 outs() << " flags " << format("0x%" PRIx32, flags) << "\n";
2512 static void PrintSection(const char *sectname, const char *segname,
2513 uint64_t addr, uint64_t size, uint32_t offset,
2514 uint32_t align, uint32_t reloff, uint32_t nreloc,
2515 uint32_t flags, uint32_t reserved1, uint32_t reserved2,
2516 uint32_t cmd, const char *sg_segname,
2517 uint32_t filetype, uint32_t object_size,
2519 outs() << "Section\n";
2520 outs() << " sectname " << format("%.16s\n", sectname);
2521 outs() << " segname " << format("%.16s", segname);
2522 if (filetype != MachO::MH_OBJECT && strncmp(sg_segname, segname, 16) != 0)
2523 outs() << " (does not match segment)\n";
2526 if (cmd == MachO::LC_SEGMENT_64) {
2527 outs() << " addr " << format("0x%016" PRIx64, addr) << "\n";
2528 outs() << " size " << format("0x%016" PRIx64, size);
2530 outs() << " addr " << format("0x%08" PRIx32, addr) << "\n";
2531 outs() << " size " << format("0x%08" PRIx32, size);
2533 if ((flags & MachO::S_ZEROFILL) != 0 && offset + size > object_size)
2534 outs() << " (past end of file)\n";
2537 outs() << " offset " << offset;
2538 if (offset > object_size)
2539 outs() << " (past end of file)\n";
2542 uint32_t align_shifted = 1 << align;
2543 outs() << " align 2^" << align << " (" << align_shifted << ")\n";
2544 outs() << " reloff " << reloff;
2545 if (reloff > object_size)
2546 outs() << " (past end of file)\n";
2549 outs() << " nreloc " << nreloc;
2550 if (reloff + nreloc * sizeof(struct MachO::relocation_info) > object_size)
2551 outs() << " (past end of file)\n";
2554 uint32_t section_type = flags & MachO::SECTION_TYPE;
2557 if (section_type == MachO::S_REGULAR)
2558 outs() << " S_REGULAR\n";
2559 else if (section_type == MachO::S_ZEROFILL)
2560 outs() << " S_ZEROFILL\n";
2561 else if (section_type == MachO::S_CSTRING_LITERALS)
2562 outs() << " S_CSTRING_LITERALS\n";
2563 else if (section_type == MachO::S_4BYTE_LITERALS)
2564 outs() << " S_4BYTE_LITERALS\n";
2565 else if (section_type == MachO::S_8BYTE_LITERALS)
2566 outs() << " S_8BYTE_LITERALS\n";
2567 else if (section_type == MachO::S_16BYTE_LITERALS)
2568 outs() << " S_16BYTE_LITERALS\n";
2569 else if (section_type == MachO::S_LITERAL_POINTERS)
2570 outs() << " S_LITERAL_POINTERS\n";
2571 else if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS)
2572 outs() << " S_NON_LAZY_SYMBOL_POINTERS\n";
2573 else if (section_type == MachO::S_LAZY_SYMBOL_POINTERS)
2574 outs() << " S_LAZY_SYMBOL_POINTERS\n";
2575 else if (section_type == MachO::S_SYMBOL_STUBS)
2576 outs() << " S_SYMBOL_STUBS\n";
2577 else if (section_type == MachO::S_MOD_INIT_FUNC_POINTERS)
2578 outs() << " S_MOD_INIT_FUNC_POINTERS\n";
2579 else if (section_type == MachO::S_MOD_TERM_FUNC_POINTERS)
2580 outs() << " S_MOD_TERM_FUNC_POINTERS\n";
2581 else if (section_type == MachO::S_COALESCED)
2582 outs() << " S_COALESCED\n";
2583 else if (section_type == MachO::S_INTERPOSING)
2584 outs() << " S_INTERPOSING\n";
2585 else if (section_type == MachO::S_DTRACE_DOF)
2586 outs() << " S_DTRACE_DOF\n";
2587 else if (section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS)
2588 outs() << " S_LAZY_DYLIB_SYMBOL_POINTERS\n";
2589 else if (section_type == MachO::S_THREAD_LOCAL_REGULAR)
2590 outs() << " S_THREAD_LOCAL_REGULAR\n";
2591 else if (section_type == MachO::S_THREAD_LOCAL_ZEROFILL)
2592 outs() << " S_THREAD_LOCAL_ZEROFILL\n";
2593 else if (section_type == MachO::S_THREAD_LOCAL_VARIABLES)
2594 outs() << " S_THREAD_LOCAL_VARIABLES\n";
2595 else if (section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS)
2596 outs() << " S_THREAD_LOCAL_VARIABLE_POINTERS\n";
2597 else if (section_type == MachO::S_THREAD_LOCAL_INIT_FUNCTION_POINTERS)
2598 outs() << " S_THREAD_LOCAL_INIT_FUNCTION_POINTERS\n";
2600 outs() << format("0x%08" PRIx32, section_type) << "\n";
2601 outs() << "attributes";
2602 uint32_t section_attributes = flags & MachO::SECTION_ATTRIBUTES;
2603 if (section_attributes & MachO::S_ATTR_PURE_INSTRUCTIONS)
2604 outs() << " PURE_INSTRUCTIONS";
2605 if (section_attributes & MachO::S_ATTR_NO_TOC)
2606 outs() << " NO_TOC";
2607 if (section_attributes & MachO::S_ATTR_STRIP_STATIC_SYMS)
2608 outs() << " STRIP_STATIC_SYMS";
2609 if (section_attributes & MachO::S_ATTR_NO_DEAD_STRIP)
2610 outs() << " NO_DEAD_STRIP";
2611 if (section_attributes & MachO::S_ATTR_LIVE_SUPPORT)
2612 outs() << " LIVE_SUPPORT";
2613 if (section_attributes & MachO::S_ATTR_SELF_MODIFYING_CODE)
2614 outs() << " SELF_MODIFYING_CODE";
2615 if (section_attributes & MachO::S_ATTR_DEBUG)
2617 if (section_attributes & MachO::S_ATTR_SOME_INSTRUCTIONS)
2618 outs() << " SOME_INSTRUCTIONS";
2619 if (section_attributes & MachO::S_ATTR_EXT_RELOC)
2620 outs() << " EXT_RELOC";
2621 if (section_attributes & MachO::S_ATTR_LOC_RELOC)
2622 outs() << " LOC_RELOC";
2623 if (section_attributes == 0)
2624 outs() << " (none)";
2627 outs() << " flags " << format("0x%08" PRIx32, flags) << "\n";
2628 outs() << " reserved1 " << reserved1;
2629 if (section_type == MachO::S_SYMBOL_STUBS ||
2630 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
2631 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
2632 section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
2633 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS)
2634 outs() << " (index into indirect symbol table)\n";
2637 outs() << " reserved2 " << reserved2;
2638 if (section_type == MachO::S_SYMBOL_STUBS)
2639 outs() << " (size of stubs)\n";
2644 static void PrintSymtabLoadCommand(MachO::symtab_command st, uint32_t cputype,
2645 uint32_t object_size) {
2646 outs() << " cmd LC_SYMTAB\n";
2647 outs() << " cmdsize " << st.cmdsize;
2648 if (st.cmdsize != sizeof(struct MachO::symtab_command))
2649 outs() << " Incorrect size\n";
2652 outs() << " symoff " << st.symoff;
2653 if (st.symoff > object_size)
2654 outs() << " (past end of file)\n";
2657 outs() << " nsyms " << st.nsyms;
2659 if (cputype & MachO::CPU_ARCH_ABI64) {
2660 big_size = st.nsyms;
2661 big_size *= sizeof(struct MachO::nlist_64);
2662 big_size += st.symoff;
2663 if (big_size > object_size)
2664 outs() << " (past end of file)\n";
2668 big_size = st.nsyms;
2669 big_size *= sizeof(struct MachO::nlist);
2670 big_size += st.symoff;
2671 if (big_size > object_size)
2672 outs() << " (past end of file)\n";
2676 outs() << " stroff " << st.stroff;
2677 if (st.stroff > object_size)
2678 outs() << " (past end of file)\n";
2681 outs() << " strsize " << st.strsize;
2682 big_size = st.stroff;
2683 big_size += st.strsize;
2684 if (big_size > object_size)
2685 outs() << " (past end of file)\n";
2690 static void PrintDysymtabLoadCommand(MachO::dysymtab_command dyst,
2691 uint32_t nsyms, uint32_t object_size,
2693 outs() << " cmd LC_DYSYMTAB\n";
2694 outs() << " cmdsize " << dyst.cmdsize;
2695 if (dyst.cmdsize != sizeof(struct MachO::dysymtab_command))
2696 outs() << " Incorrect size\n";
2699 outs() << " ilocalsym " << dyst.ilocalsym;
2700 if (dyst.ilocalsym > nsyms)
2701 outs() << " (greater than the number of symbols)\n";
2704 outs() << " nlocalsym " << dyst.nlocalsym;
2706 big_size = dyst.ilocalsym;
2707 big_size += dyst.nlocalsym;
2708 if (big_size > nsyms)
2709 outs() << " (past the end of the symbol table)\n";
2712 outs() << " iextdefsym " << dyst.iextdefsym;
2713 if (dyst.iextdefsym > nsyms)
2714 outs() << " (greater than the number of symbols)\n";
2717 outs() << " nextdefsym " << dyst.nextdefsym;
2718 big_size = dyst.iextdefsym;
2719 big_size += dyst.nextdefsym;
2720 if (big_size > nsyms)
2721 outs() << " (past the end of the symbol table)\n";
2724 outs() << " iundefsym " << dyst.iundefsym;
2725 if (dyst.iundefsym > nsyms)
2726 outs() << " (greater than the number of symbols)\n";
2729 outs() << " nundefsym " << dyst.nundefsym;
2730 big_size = dyst.iundefsym;
2731 big_size += dyst.nundefsym;
2732 if (big_size > nsyms)
2733 outs() << " (past the end of the symbol table)\n";
2736 outs() << " tocoff " << dyst.tocoff;
2737 if (dyst.tocoff > object_size)
2738 outs() << " (past end of file)\n";
2741 outs() << " ntoc " << dyst.ntoc;
2742 big_size = dyst.ntoc;
2743 big_size *= sizeof(struct MachO::dylib_table_of_contents);
2744 big_size += dyst.tocoff;
2745 if (big_size > object_size)
2746 outs() << " (past end of file)\n";
2749 outs() << " modtaboff " << dyst.modtaboff;
2750 if (dyst.modtaboff > object_size)
2751 outs() << " (past end of file)\n";
2754 outs() << " nmodtab " << dyst.nmodtab;
2756 if (cputype & MachO::CPU_ARCH_ABI64) {
2757 modtabend = dyst.nmodtab;
2758 modtabend *= sizeof(struct MachO::dylib_module_64);
2759 modtabend += dyst.modtaboff;
2761 modtabend = dyst.nmodtab;
2762 modtabend *= sizeof(struct MachO::dylib_module);
2763 modtabend += dyst.modtaboff;
2765 if (modtabend > object_size)
2766 outs() << " (past end of file)\n";
2769 outs() << " extrefsymoff " << dyst.extrefsymoff;
2770 if (dyst.extrefsymoff > object_size)
2771 outs() << " (past end of file)\n";
2774 outs() << " nextrefsyms " << dyst.nextrefsyms;
2775 big_size = dyst.nextrefsyms;
2776 big_size *= sizeof(struct MachO::dylib_reference);
2777 big_size += dyst.extrefsymoff;
2778 if (big_size > object_size)
2779 outs() << " (past end of file)\n";
2782 outs() << " indirectsymoff " << dyst.indirectsymoff;
2783 if (dyst.indirectsymoff > object_size)
2784 outs() << " (past end of file)\n";
2787 outs() << " nindirectsyms " << dyst.nindirectsyms;
2788 big_size = dyst.nindirectsyms;
2789 big_size *= sizeof(uint32_t);
2790 big_size += dyst.indirectsymoff;
2791 if (big_size > object_size)
2792 outs() << " (past end of file)\n";
2795 outs() << " extreloff " << dyst.extreloff;
2796 if (dyst.extreloff > object_size)
2797 outs() << " (past end of file)\n";
2800 outs() << " nextrel " << dyst.nextrel;
2801 big_size = dyst.nextrel;
2802 big_size *= sizeof(struct MachO::relocation_info);
2803 big_size += dyst.extreloff;
2804 if (big_size > object_size)
2805 outs() << " (past end of file)\n";
2808 outs() << " locreloff " << dyst.locreloff;
2809 if (dyst.locreloff > object_size)
2810 outs() << " (past end of file)\n";
2813 outs() << " nlocrel " << dyst.nlocrel;
2814 big_size = dyst.nlocrel;
2815 big_size *= sizeof(struct MachO::relocation_info);
2816 big_size += dyst.locreloff;
2817 if (big_size > object_size)
2818 outs() << " (past end of file)\n";
2823 static void PrintDyldInfoLoadCommand(MachO::dyld_info_command dc,
2824 uint32_t object_size) {
2825 if (dc.cmd == MachO::LC_DYLD_INFO)
2826 outs() << " cmd LC_DYLD_INFO\n";
2828 outs() << " cmd LC_DYLD_INFO_ONLY\n";
2829 outs() << " cmdsize " << dc.cmdsize;
2830 if (dc.cmdsize != sizeof(struct MachO::dyld_info_command))
2831 outs() << " Incorrect size\n";
2834 outs() << " rebase_off " << dc.rebase_off;
2835 if (dc.rebase_off > object_size)
2836 outs() << " (past end of file)\n";
2839 outs() << " rebase_size " << dc.rebase_size;
2841 big_size = dc.rebase_off;
2842 big_size += dc.rebase_size;
2843 if (big_size > object_size)
2844 outs() << " (past end of file)\n";
2847 outs() << " bind_off " << dc.bind_off;
2848 if (dc.bind_off > object_size)
2849 outs() << " (past end of file)\n";
2852 outs() << " bind_size " << dc.bind_size;
2853 big_size = dc.bind_off;
2854 big_size += dc.bind_size;
2855 if (big_size > object_size)
2856 outs() << " (past end of file)\n";
2859 outs() << " weak_bind_off " << dc.weak_bind_off;
2860 if (dc.weak_bind_off > object_size)
2861 outs() << " (past end of file)\n";
2864 outs() << " weak_bind_size " << dc.weak_bind_size;
2865 big_size = dc.weak_bind_off;
2866 big_size += dc.weak_bind_size;
2867 if (big_size > object_size)
2868 outs() << " (past end of file)\n";
2871 outs() << " lazy_bind_off " << dc.lazy_bind_off;
2872 if (dc.lazy_bind_off > object_size)
2873 outs() << " (past end of file)\n";
2876 outs() << " lazy_bind_size " << dc.lazy_bind_size;
2877 big_size = dc.lazy_bind_off;
2878 big_size += dc.lazy_bind_size;
2879 if (big_size > object_size)
2880 outs() << " (past end of file)\n";
2883 outs() << " export_off " << dc.export_off;
2884 if (dc.export_off > object_size)
2885 outs() << " (past end of file)\n";
2888 outs() << " export_size " << dc.export_size;
2889 big_size = dc.export_off;
2890 big_size += dc.export_size;
2891 if (big_size > object_size)
2892 outs() << " (past end of file)\n";
2897 static void PrintDyldLoadCommand(MachO::dylinker_command dyld,
2899 if (dyld.cmd == MachO::LC_ID_DYLINKER)
2900 outs() << " cmd LC_ID_DYLINKER\n";
2901 else if (dyld.cmd == MachO::LC_LOAD_DYLINKER)
2902 outs() << " cmd LC_LOAD_DYLINKER\n";
2903 else if (dyld.cmd == MachO::LC_DYLD_ENVIRONMENT)
2904 outs() << " cmd LC_DYLD_ENVIRONMENT\n";
2906 outs() << " cmd ?(" << dyld.cmd << ")\n";
2907 outs() << " cmdsize " << dyld.cmdsize;
2908 if (dyld.cmdsize < sizeof(struct MachO::dylinker_command))
2909 outs() << " Incorrect size\n";
2912 if (dyld.name >= dyld.cmdsize)
2913 outs() << " name ?(bad offset " << dyld.name << ")\n";
2915 const char *P = (const char *)(Ptr) + dyld.name;
2916 outs() << " name " << P << " (offset " << dyld.name << ")\n";
2920 static void PrintUuidLoadCommand(MachO::uuid_command uuid) {
2921 outs() << " cmd LC_UUID\n";
2922 outs() << " cmdsize " << uuid.cmdsize;
2923 if (uuid.cmdsize != sizeof(struct MachO::uuid_command))
2924 outs() << " Incorrect size\n";
2928 outs() << format("%02" PRIX32, uuid.uuid[0]);
2929 outs() << format("%02" PRIX32, uuid.uuid[1]);
2930 outs() << format("%02" PRIX32, uuid.uuid[2]);
2931 outs() << format("%02" PRIX32, uuid.uuid[3]);
2933 outs() << format("%02" PRIX32, uuid.uuid[4]);
2934 outs() << format("%02" PRIX32, uuid.uuid[5]);
2936 outs() << format("%02" PRIX32, uuid.uuid[6]);
2937 outs() << format("%02" PRIX32, uuid.uuid[7]);
2939 outs() << format("%02" PRIX32, uuid.uuid[8]);
2940 outs() << format("%02" PRIX32, uuid.uuid[9]);
2942 outs() << format("%02" PRIX32, uuid.uuid[10]);
2943 outs() << format("%02" PRIX32, uuid.uuid[11]);
2944 outs() << format("%02" PRIX32, uuid.uuid[12]);
2945 outs() << format("%02" PRIX32, uuid.uuid[13]);
2946 outs() << format("%02" PRIX32, uuid.uuid[14]);
2947 outs() << format("%02" PRIX32, uuid.uuid[15]);
2951 static void PrintVersionMinLoadCommand(MachO::version_min_command vd) {
2952 if (vd.cmd == MachO::LC_VERSION_MIN_MACOSX)
2953 outs() << " cmd LC_VERSION_MIN_MACOSX\n";
2954 else if (vd.cmd == MachO::LC_VERSION_MIN_IPHONEOS)
2955 outs() << " cmd LC_VERSION_MIN_IPHONEOS\n";
2957 outs() << " cmd " << vd.cmd << " (?)\n";
2958 outs() << " cmdsize " << vd.cmdsize;
2959 if (vd.cmdsize != sizeof(struct MachO::version_min_command))
2960 outs() << " Incorrect size\n";
2963 outs() << " version " << ((vd.version >> 16) & 0xffff) << "."
2964 << ((vd.version >> 8) & 0xff);
2965 if ((vd.version & 0xff) != 0)
2966 outs() << "." << (vd.version & 0xff);
2969 outs() << " sdk n/a\n";
2971 outs() << " sdk " << ((vd.sdk >> 16) & 0xffff) << "."
2972 << ((vd.sdk >> 8) & 0xff);
2974 if ((vd.sdk & 0xff) != 0)
2975 outs() << "." << (vd.sdk & 0xff);
2979 static void PrintSourceVersionCommand(MachO::source_version_command sd) {
2980 outs() << " cmd LC_SOURCE_VERSION\n";
2981 outs() << " cmdsize " << sd.cmdsize;
2982 if (sd.cmdsize != sizeof(struct MachO::source_version_command))
2983 outs() << " Incorrect size\n";
2986 uint64_t a = (sd.version >> 40) & 0xffffff;
2987 uint64_t b = (sd.version >> 30) & 0x3ff;
2988 uint64_t c = (sd.version >> 20) & 0x3ff;
2989 uint64_t d = (sd.version >> 10) & 0x3ff;
2990 uint64_t e = sd.version & 0x3ff;
2991 outs() << " version " << a << "." << b;
2993 outs() << "." << c << "." << d << "." << e;
2995 outs() << "." << c << "." << d;
3001 static void PrintEntryPointCommand(MachO::entry_point_command ep) {
3002 outs() << " cmd LC_MAIN\n";
3003 outs() << " cmdsize " << ep.cmdsize;
3004 if (ep.cmdsize != sizeof(struct MachO::entry_point_command))
3005 outs() << " Incorrect size\n";
3008 outs() << " entryoff " << ep.entryoff << "\n";
3009 outs() << " stacksize " << ep.stacksize << "\n";
3012 static void PrintDylibCommand(MachO::dylib_command dl, const char *Ptr) {
3013 if (dl.cmd == MachO::LC_ID_DYLIB)
3014 outs() << " cmd LC_ID_DYLIB\n";
3015 else if (dl.cmd == MachO::LC_LOAD_DYLIB)
3016 outs() << " cmd LC_LOAD_DYLIB\n";
3017 else if (dl.cmd == MachO::LC_LOAD_WEAK_DYLIB)
3018 outs() << " cmd LC_LOAD_WEAK_DYLIB\n";
3019 else if (dl.cmd == MachO::LC_REEXPORT_DYLIB)
3020 outs() << " cmd LC_REEXPORT_DYLIB\n";
3021 else if (dl.cmd == MachO::LC_LAZY_LOAD_DYLIB)
3022 outs() << " cmd LC_LAZY_LOAD_DYLIB\n";
3023 else if (dl.cmd == MachO::LC_LOAD_UPWARD_DYLIB)
3024 outs() << " cmd LC_LOAD_UPWARD_DYLIB\n";
3026 outs() << " cmd " << dl.cmd << " (unknown)\n";
3027 outs() << " cmdsize " << dl.cmdsize;
3028 if (dl.cmdsize < sizeof(struct MachO::dylib_command))
3029 outs() << " Incorrect size\n";
3032 if (dl.dylib.name < dl.cmdsize) {
3033 const char *P = (const char *)(Ptr) + dl.dylib.name;
3034 outs() << " name " << P << " (offset " << dl.dylib.name << ")\n";
3036 outs() << " name ?(bad offset " << dl.dylib.name << ")\n";
3038 outs() << " time stamp " << dl.dylib.timestamp << " ";
3039 time_t t = dl.dylib.timestamp;
3040 outs() << ctime(&t);
3041 outs() << " current version ";
3042 if (dl.dylib.current_version == 0xffffffff)
3045 outs() << ((dl.dylib.current_version >> 16) & 0xffff) << "."
3046 << ((dl.dylib.current_version >> 8) & 0xff) << "."
3047 << (dl.dylib.current_version & 0xff) << "\n";
3048 outs() << "compatibility version ";
3049 if (dl.dylib.compatibility_version == 0xffffffff)
3052 outs() << ((dl.dylib.compatibility_version >> 16) & 0xffff) << "."
3053 << ((dl.dylib.compatibility_version >> 8) & 0xff) << "."
3054 << (dl.dylib.compatibility_version & 0xff) << "\n";
3057 static void PrintLinkEditDataCommand(MachO::linkedit_data_command ld,
3058 uint32_t object_size) {
3059 if (ld.cmd == MachO::LC_CODE_SIGNATURE)
3060 outs() << " cmd LC_FUNCTION_STARTS\n";
3061 else if (ld.cmd == MachO::LC_SEGMENT_SPLIT_INFO)
3062 outs() << " cmd LC_SEGMENT_SPLIT_INFO\n";
3063 else if (ld.cmd == MachO::LC_FUNCTION_STARTS)
3064 outs() << " cmd LC_FUNCTION_STARTS\n";
3065 else if (ld.cmd == MachO::LC_DATA_IN_CODE)
3066 outs() << " cmd LC_DATA_IN_CODE\n";
3067 else if (ld.cmd == MachO::LC_DYLIB_CODE_SIGN_DRS)
3068 outs() << " cmd LC_DYLIB_CODE_SIGN_DRS\n";
3069 else if (ld.cmd == MachO::LC_LINKER_OPTIMIZATION_HINT)
3070 outs() << " cmd LC_LINKER_OPTIMIZATION_HINT\n";
3072 outs() << " cmd " << ld.cmd << " (?)\n";
3073 outs() << " cmdsize " << ld.cmdsize;
3074 if (ld.cmdsize != sizeof(struct MachO::linkedit_data_command))
3075 outs() << " Incorrect size\n";
3078 outs() << " dataoff " << ld.dataoff;
3079 if (ld.dataoff > object_size)
3080 outs() << " (past end of file)\n";
3083 outs() << " datasize " << ld.datasize;
3084 uint64_t big_size = ld.dataoff;
3085 big_size += ld.datasize;
3086 if (big_size > object_size)
3087 outs() << " (past end of file)\n";
3092 static void PrintLoadCommands(const MachOObjectFile *Obj, uint32_t ncmds,
3093 uint32_t filetype, uint32_t cputype,
3095 StringRef Buf = Obj->getData();
3096 MachOObjectFile::LoadCommandInfo Command = Obj->getFirstLoadCommandInfo();
3097 for (unsigned i = 0;; ++i) {
3098 outs() << "Load command " << i << "\n";
3099 if (Command.C.cmd == MachO::LC_SEGMENT) {
3100 MachO::segment_command SLC = Obj->getSegmentLoadCommand(Command);
3101 const char *sg_segname = SLC.segname;
3102 PrintSegmentCommand(SLC.cmd, SLC.cmdsize, SLC.segname, SLC.vmaddr,
3103 SLC.vmsize, SLC.fileoff, SLC.filesize, SLC.maxprot,
3104 SLC.initprot, SLC.nsects, SLC.flags, Buf.size(),
3106 for (unsigned j = 0; j < SLC.nsects; j++) {
3107 MachO::section_64 S = Obj->getSection64(Command, j);
3108 PrintSection(S.sectname, S.segname, S.addr, S.size, S.offset, S.align,
3109 S.reloff, S.nreloc, S.flags, S.reserved1, S.reserved2,
3110 SLC.cmd, sg_segname, filetype, Buf.size(), verbose);
3112 } else if (Command.C.cmd == MachO::LC_SEGMENT_64) {
3113 MachO::segment_command_64 SLC_64 = Obj->getSegment64LoadCommand(Command);
3114 const char *sg_segname = SLC_64.segname;
3115 PrintSegmentCommand(SLC_64.cmd, SLC_64.cmdsize, SLC_64.segname,
3116 SLC_64.vmaddr, SLC_64.vmsize, SLC_64.fileoff,
3117 SLC_64.filesize, SLC_64.maxprot, SLC_64.initprot,
3118 SLC_64.nsects, SLC_64.flags, Buf.size(), verbose);
3119 for (unsigned j = 0; j < SLC_64.nsects; j++) {
3120 MachO::section_64 S_64 = Obj->getSection64(Command, j);
3121 PrintSection(S_64.sectname, S_64.segname, S_64.addr, S_64.size,
3122 S_64.offset, S_64.align, S_64.reloff, S_64.nreloc,
3123 S_64.flags, S_64.reserved1, S_64.reserved2, SLC_64.cmd,
3124 sg_segname, filetype, Buf.size(), verbose);
3126 } else if (Command.C.cmd == MachO::LC_SYMTAB) {
3127 MachO::symtab_command Symtab = Obj->getSymtabLoadCommand();
3128 PrintSymtabLoadCommand(Symtab, cputype, Buf.size());
3129 } else if (Command.C.cmd == MachO::LC_DYSYMTAB) {
3130 MachO::dysymtab_command Dysymtab = Obj->getDysymtabLoadCommand();
3131 MachO::symtab_command Symtab = Obj->getSymtabLoadCommand();
3132 PrintDysymtabLoadCommand(Dysymtab, Symtab.nsyms, Buf.size(), cputype);
3133 } else if (Command.C.cmd == MachO::LC_DYLD_INFO ||
3134 Command.C.cmd == MachO::LC_DYLD_INFO_ONLY) {
3135 MachO::dyld_info_command DyldInfo = Obj->getDyldInfoLoadCommand(Command);
3136 PrintDyldInfoLoadCommand(DyldInfo, Buf.size());
3137 } else if (Command.C.cmd == MachO::LC_LOAD_DYLINKER ||
3138 Command.C.cmd == MachO::LC_ID_DYLINKER ||
3139 Command.C.cmd == MachO::LC_DYLD_ENVIRONMENT) {
3140 MachO::dylinker_command Dyld = Obj->getDylinkerCommand(Command);
3141 PrintDyldLoadCommand(Dyld, Command.Ptr);
3142 } else if (Command.C.cmd == MachO::LC_UUID) {
3143 MachO::uuid_command Uuid = Obj->getUuidCommand(Command);
3144 PrintUuidLoadCommand(Uuid);
3145 } else if (Command.C.cmd == MachO::LC_VERSION_MIN_MACOSX) {
3146 MachO::version_min_command Vd = Obj->getVersionMinLoadCommand(Command);
3147 PrintVersionMinLoadCommand(Vd);
3148 } else if (Command.C.cmd == MachO::LC_SOURCE_VERSION) {
3149 MachO::source_version_command Sd = Obj->getSourceVersionCommand(Command);
3150 PrintSourceVersionCommand(Sd);
3151 } else if (Command.C.cmd == MachO::LC_MAIN) {
3152 MachO::entry_point_command Ep = Obj->getEntryPointCommand(Command);
3153 PrintEntryPointCommand(Ep);
3154 } else if (Command.C.cmd == MachO::LC_LOAD_DYLIB ||
3155 Command.C.cmd == MachO::LC_ID_DYLIB ||
3156 Command.C.cmd == MachO::LC_LOAD_WEAK_DYLIB ||
3157 Command.C.cmd == MachO::LC_REEXPORT_DYLIB ||
3158 Command.C.cmd == MachO::LC_LAZY_LOAD_DYLIB ||
3159 Command.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB) {
3160 MachO::dylib_command Dl = Obj->getDylibIDLoadCommand(Command);
3161 PrintDylibCommand(Dl, Command.Ptr);
3162 } else if (Command.C.cmd == MachO::LC_CODE_SIGNATURE ||
3163 Command.C.cmd == MachO::LC_SEGMENT_SPLIT_INFO ||
3164 Command.C.cmd == MachO::LC_FUNCTION_STARTS ||
3165 Command.C.cmd == MachO::LC_DATA_IN_CODE ||
3166 Command.C.cmd == MachO::LC_DYLIB_CODE_SIGN_DRS ||
3167 Command.C.cmd == MachO::LC_LINKER_OPTIMIZATION_HINT) {
3168 MachO::linkedit_data_command Ld =
3169 Obj->getLinkeditDataLoadCommand(Command);
3170 PrintLinkEditDataCommand(Ld, Buf.size());
3172 outs() << " cmd ?(" << format("0x%08" PRIx32, Command.C.cmd)
3174 outs() << " cmdsize " << Command.C.cmdsize << "\n";
3175 // TODO: get and print the raw bytes of the load command.
3177 // TODO: print all the other kinds of load commands.
3181 Command = Obj->getNextLoadCommandInfo(Command);
3185 static void getAndPrintMachHeader(const MachOObjectFile *Obj, uint32_t &ncmds,
3186 uint32_t &filetype, uint32_t &cputype,
3188 if (Obj->is64Bit()) {
3189 MachO::mach_header_64 H_64;
3190 H_64 = Obj->getHeader64();
3191 PrintMachHeader(H_64.magic, H_64.cputype, H_64.cpusubtype, H_64.filetype,
3192 H_64.ncmds, H_64.sizeofcmds, H_64.flags, verbose);
3194 filetype = H_64.filetype;
3195 cputype = H_64.cputype;
3197 MachO::mach_header H;
3198 H = Obj->getHeader();
3199 PrintMachHeader(H.magic, H.cputype, H.cpusubtype, H.filetype, H.ncmds,
3200 H.sizeofcmds, H.flags, verbose);
3202 filetype = H.filetype;
3203 cputype = H.cputype;
3207 void llvm::printMachOFileHeader(const object::ObjectFile *Obj) {
3208 const MachOObjectFile *file = dyn_cast<const MachOObjectFile>(Obj);
3210 uint32_t filetype = 0;
3211 uint32_t cputype = 0;
3212 getAndPrintMachHeader(file, ncmds, filetype, cputype, true);
3213 PrintLoadCommands(file, ncmds, filetype, cputype, true);
3216 //===----------------------------------------------------------------------===//
3217 // export trie dumping
3218 //===----------------------------------------------------------------------===//
3220 void llvm::printMachOExportsTrie(const object::MachOObjectFile *Obj) {
3221 for (const llvm::object::ExportEntry &Entry : Obj->exports()) {
3222 uint64_t Flags = Entry.flags();
3223 bool ReExport = (Flags & MachO::EXPORT_SYMBOL_FLAGS_REEXPORT);
3224 bool WeakDef = (Flags & MachO::EXPORT_SYMBOL_FLAGS_WEAK_DEFINITION);
3225 bool ThreadLocal = ((Flags & MachO::EXPORT_SYMBOL_FLAGS_KIND_MASK) ==
3226 MachO::EXPORT_SYMBOL_FLAGS_KIND_THREAD_LOCAL);
3227 bool Abs = ((Flags & MachO::EXPORT_SYMBOL_FLAGS_KIND_MASK) ==
3228 MachO::EXPORT_SYMBOL_FLAGS_KIND_ABSOLUTE);
3229 bool Resolver = (Flags & MachO::EXPORT_SYMBOL_FLAGS_STUB_AND_RESOLVER);
3231 outs() << "[re-export] ";
3233 outs() << format("0x%08llX ",
3234 Entry.address()); // FIXME:add in base address
3235 outs() << Entry.name();
3236 if (WeakDef || ThreadLocal || Resolver || Abs) {
3237 bool NeedsComma = false;
3240 outs() << "weak_def";
3246 outs() << "per-thread";
3252 outs() << "absolute";
3258 outs() << format("resolver=0x%08llX", Entry.other());
3264 StringRef DylibName = "unknown";
3265 int Ordinal = Entry.other() - 1;
3266 Obj->getLibraryShortNameByIndex(Ordinal, DylibName);
3267 if (Entry.otherName().empty())
3268 outs() << " (from " << DylibName << ")";
3270 outs() << " (" << Entry.otherName() << " from " << DylibName << ")";
3276 //===----------------------------------------------------------------------===//
3277 // rebase table dumping
3278 //===----------------------------------------------------------------------===//
3283 SegInfo(const object::MachOObjectFile *Obj);
3285 StringRef segmentName(uint32_t SegIndex);
3286 StringRef sectionName(uint32_t SegIndex, uint64_t SegOffset);
3287 uint64_t address(uint32_t SegIndex, uint64_t SegOffset);
3290 struct SectionInfo {
3293 StringRef SectionName;
3294 StringRef SegmentName;
3295 uint64_t OffsetInSegment;
3296 uint64_t SegmentStartAddress;
3297 uint32_t SegmentIndex;
3299 const SectionInfo &findSection(uint32_t SegIndex, uint64_t SegOffset);
3300 SmallVector<SectionInfo, 32> Sections;
3304 SegInfo::SegInfo(const object::MachOObjectFile *Obj) {
3305 // Build table of sections so segIndex/offset pairs can be translated.
3306 uint32_t CurSegIndex = Obj->hasPageZeroSegment() ? 1 : 0;
3307 StringRef CurSegName;
3308 uint64_t CurSegAddress;
3309 for (const SectionRef &Section : Obj->sections()) {
3311 if (error(Section.getName(Info.SectionName)))
3313 Info.Address = Section.getAddress();
3314 Info.Size = Section.getSize();
3316 Obj->getSectionFinalSegmentName(Section.getRawDataRefImpl());
3317 if (!Info.SegmentName.equals(CurSegName)) {
3319 CurSegName = Info.SegmentName;
3320 CurSegAddress = Info.Address;
3322 Info.SegmentIndex = CurSegIndex - 1;
3323 Info.OffsetInSegment = Info.Address - CurSegAddress;
3324 Info.SegmentStartAddress = CurSegAddress;
3325 Sections.push_back(Info);
3329 StringRef SegInfo::segmentName(uint32_t SegIndex) {
3330 for (const SectionInfo &SI : Sections) {
3331 if (SI.SegmentIndex == SegIndex)
3332 return SI.SegmentName;
3334 llvm_unreachable("invalid segIndex");
3337 const SegInfo::SectionInfo &SegInfo::findSection(uint32_t SegIndex,
3338 uint64_t OffsetInSeg) {
3339 for (const SectionInfo &SI : Sections) {
3340 if (SI.SegmentIndex != SegIndex)
3342 if (SI.OffsetInSegment > OffsetInSeg)
3344 if (OffsetInSeg >= (SI.OffsetInSegment + SI.Size))
3348 llvm_unreachable("segIndex and offset not in any section");
3351 StringRef SegInfo::sectionName(uint32_t SegIndex, uint64_t OffsetInSeg) {
3352 return findSection(SegIndex, OffsetInSeg).SectionName;
3355 uint64_t SegInfo::address(uint32_t SegIndex, uint64_t OffsetInSeg) {
3356 const SectionInfo &SI = findSection(SegIndex, OffsetInSeg);
3357 return SI.SegmentStartAddress + OffsetInSeg;
3360 void llvm::printMachORebaseTable(const object::MachOObjectFile *Obj) {
3361 // Build table of sections so names can used in final output.
3362 SegInfo sectionTable(Obj);
3364 outs() << "segment section address type\n";
3365 for (const llvm::object::MachORebaseEntry &Entry : Obj->rebaseTable()) {
3366 uint32_t SegIndex = Entry.segmentIndex();
3367 uint64_t OffsetInSeg = Entry.segmentOffset();
3368 StringRef SegmentName = sectionTable.segmentName(SegIndex);
3369 StringRef SectionName = sectionTable.sectionName(SegIndex, OffsetInSeg);
3370 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
3372 // Table lines look like: __DATA __nl_symbol_ptr 0x0000F00C pointer
3373 outs() << format("%-8s %-18s 0x%08" PRIX64 " %s\n",
3374 SegmentName.str().c_str(), SectionName.str().c_str(),
3375 Address, Entry.typeName().str().c_str());
3379 static StringRef ordinalName(const object::MachOObjectFile *Obj, int Ordinal) {
3380 StringRef DylibName;
3382 case MachO::BIND_SPECIAL_DYLIB_SELF:
3383 return "this-image";
3384 case MachO::BIND_SPECIAL_DYLIB_MAIN_EXECUTABLE:
3385 return "main-executable";
3386 case MachO::BIND_SPECIAL_DYLIB_FLAT_LOOKUP:
3387 return "flat-namespace";
3390 std::error_code EC =
3391 Obj->getLibraryShortNameByIndex(Ordinal - 1, DylibName);
3393 return "<<bad library ordinal>>";
3397 return "<<unknown special ordinal>>";
3400 //===----------------------------------------------------------------------===//
3401 // bind table dumping
3402 //===----------------------------------------------------------------------===//
3404 void llvm::printMachOBindTable(const object::MachOObjectFile *Obj) {
3405 // Build table of sections so names can used in final output.
3406 SegInfo sectionTable(Obj);
3408 outs() << "segment section address type "
3409 "addend dylib symbol\n";
3410 for (const llvm::object::MachOBindEntry &Entry : Obj->bindTable()) {
3411 uint32_t SegIndex = Entry.segmentIndex();
3412 uint64_t OffsetInSeg = Entry.segmentOffset();
3413 StringRef SegmentName = sectionTable.segmentName(SegIndex);
3414 StringRef SectionName = sectionTable.sectionName(SegIndex, OffsetInSeg);
3415 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
3417 // Table lines look like:
3418 // __DATA __got 0x00012010 pointer 0 libSystem ___stack_chk_guard
3420 if (Entry.flags() & MachO::BIND_SYMBOL_FLAGS_WEAK_IMPORT)
3421 Attr = " (weak_import)";
3422 outs() << left_justify(SegmentName, 8) << " "
3423 << left_justify(SectionName, 18) << " "
3424 << format_hex(Address, 10, true) << " "
3425 << left_justify(Entry.typeName(), 8) << " "
3426 << format_decimal(Entry.addend(), 8) << " "
3427 << left_justify(ordinalName(Obj, Entry.ordinal()), 16) << " "
3428 << Entry.symbolName() << Attr << "\n";
3432 //===----------------------------------------------------------------------===//
3433 // lazy bind table dumping
3434 //===----------------------------------------------------------------------===//
3436 void llvm::printMachOLazyBindTable(const object::MachOObjectFile *Obj) {
3437 // Build table of sections so names can used in final output.
3438 SegInfo sectionTable(Obj);
3440 outs() << "segment section address "
3442 for (const llvm::object::MachOBindEntry &Entry : Obj->lazyBindTable()) {
3443 uint32_t SegIndex = Entry.segmentIndex();
3444 uint64_t OffsetInSeg = Entry.segmentOffset();
3445 StringRef SegmentName = sectionTable.segmentName(SegIndex);
3446 StringRef SectionName = sectionTable.sectionName(SegIndex, OffsetInSeg);
3447 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
3449 // Table lines look like:
3450 // __DATA __got 0x00012010 libSystem ___stack_chk_guard
3451 outs() << left_justify(SegmentName, 8) << " "
3452 << left_justify(SectionName, 18) << " "
3453 << format_hex(Address, 10, true) << " "
3454 << left_justify(ordinalName(Obj, Entry.ordinal()), 16) << " "
3455 << Entry.symbolName() << "\n";
3459 //===----------------------------------------------------------------------===//
3460 // weak bind table dumping
3461 //===----------------------------------------------------------------------===//
3463 void llvm::printMachOWeakBindTable(const object::MachOObjectFile *Obj) {
3464 // Build table of sections so names can used in final output.
3465 SegInfo sectionTable(Obj);
3467 outs() << "segment section address "
3468 "type addend symbol\n";
3469 for (const llvm::object::MachOBindEntry &Entry : Obj->weakBindTable()) {
3470 // Strong symbols don't have a location to update.
3471 if (Entry.flags() & MachO::BIND_SYMBOL_FLAGS_NON_WEAK_DEFINITION) {
3472 outs() << " strong "
3473 << Entry.symbolName() << "\n";
3476 uint32_t SegIndex = Entry.segmentIndex();
3477 uint64_t OffsetInSeg = Entry.segmentOffset();
3478 StringRef SegmentName = sectionTable.segmentName(SegIndex);
3479 StringRef SectionName = sectionTable.sectionName(SegIndex, OffsetInSeg);
3480 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
3482 // Table lines look like:
3483 // __DATA __data 0x00001000 pointer 0 _foo
3484 outs() << left_justify(SegmentName, 8) << " "
3485 << left_justify(SectionName, 18) << " "
3486 << format_hex(Address, 10, true) << " "
3487 << left_justify(Entry.typeName(), 8) << " "
3488 << format_decimal(Entry.addend(), 8) << " " << Entry.symbolName()
3493 // get_dyld_bind_info_symbolname() is used for disassembly and passed an
3494 // address, ReferenceValue, in the Mach-O file and looks in the dyld bind
3495 // information for that address. If the address is found its binding symbol
3496 // name is returned. If not nullptr is returned.
3497 static const char *get_dyld_bind_info_symbolname(uint64_t ReferenceValue,
3498 struct DisassembleInfo *info) {
3499 if (info->bindtable == nullptr) {
3500 info->bindtable = new (BindTable);
3501 SegInfo sectionTable(info->O);
3502 for (const llvm::object::MachOBindEntry &Entry : info->O->bindTable()) {
3503 uint32_t SegIndex = Entry.segmentIndex();
3504 uint64_t OffsetInSeg = Entry.segmentOffset();
3505 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
3506 const char *SymbolName = nullptr;
3507 StringRef name = Entry.symbolName();
3509 SymbolName = name.data();
3510 info->bindtable->push_back(std::make_pair(Address, SymbolName));
3513 for (bind_table_iterator BI = info->bindtable->begin(),
3514 BE = info->bindtable->end();
3516 uint64_t Address = BI->first;
3517 if (ReferenceValue == Address) {
3518 const char *SymbolName = BI->second;