1 //===-- MachODump.cpp - Object file dumping utility for llvm --------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file implements the MachO-specific dumper for llvm-objdump. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "MachODump.h" 14 15 #include "ObjdumpOptID.h" 16 #include "llvm-objdump.h" 17 #include "llvm-c/Disassembler.h" 18 #include "llvm/ADT/STLExtras.h" 19 #include "llvm/ADT/StringExtras.h" 20 #include "llvm/ADT/Triple.h" 21 #include "llvm/BinaryFormat/MachO.h" 22 #include "llvm/Config/config.h" 23 #include "llvm/DebugInfo/DIContext.h" 24 #include "llvm/DebugInfo/DWARF/DWARFContext.h" 25 #include "llvm/Demangle/Demangle.h" 26 #include "llvm/MC/MCAsmInfo.h" 27 #include "llvm/MC/MCContext.h" 28 #include "llvm/MC/MCDisassembler/MCDisassembler.h" 29 #include "llvm/MC/MCInst.h" 30 #include "llvm/MC/MCInstPrinter.h" 31 #include "llvm/MC/MCInstrDesc.h" 32 #include "llvm/MC/MCInstrInfo.h" 33 #include "llvm/MC/MCRegisterInfo.h" 34 #include "llvm/MC/MCSubtargetInfo.h" 35 #include "llvm/MC/MCTargetOptions.h" 36 #include "llvm/Object/MachO.h" 37 #include "llvm/Object/MachOUniversal.h" 38 #include "llvm/Option/ArgList.h" 39 #include "llvm/Support/Casting.h" 40 #include "llvm/Support/Debug.h" 41 #include "llvm/Support/Endian.h" 42 #include "llvm/Support/Format.h" 43 #include "llvm/Support/FormattedStream.h" 44 #include "llvm/Support/GraphWriter.h" 45 #include "llvm/Support/LEB128.h" 46 #include "llvm/Support/MemoryBuffer.h" 47 #include "llvm/Support/TargetRegistry.h" 48 #include "llvm/Support/TargetSelect.h" 49 #include "llvm/Support/ToolOutputFile.h" 50 #include "llvm/Support/WithColor.h" 51 #include "llvm/Support/raw_ostream.h" 52 #include <algorithm> 53 #include <cstring> 54 #include <system_error> 55 56 #ifdef HAVE_LIBXAR 57 extern "C" { 58 #include <xar/xar.h> 59 } 60 #endif 61 62 using namespace llvm; 63 using namespace llvm::object; 64 using namespace llvm::objdump; 65 66 bool objdump::FirstPrivateHeader; 67 bool objdump::ExportsTrie; 68 bool objdump::Rebase; 69 bool objdump::Bind; 70 bool objdump::LazyBind; 71 bool objdump::WeakBind; 72 static bool UseDbg; 73 static std::string DSYMFile; 74 static bool FullLeadingAddr; 75 static bool NoLeadingHeaders; 76 bool objdump::UniversalHeaders; 77 static bool ArchiveMemberOffsets; 78 bool objdump::IndirectSymbols; 79 bool objdump::DataInCode; 80 bool objdump::FunctionStarts; 81 bool objdump::LinkOptHints; 82 bool objdump::InfoPlist; 83 bool objdump::DylibsUsed; 84 bool objdump::DylibId; 85 static bool NonVerbose; 86 bool objdump::ObjcMetaData; 87 static std::string DisSymName; 88 static bool NoSymbolicOperands; 89 static std::vector<std::string> ArchFlags; 90 91 static bool ArchAll = false; 92 static std::string ThumbTripleName; 93 94 void objdump::parseMachOOptions(const llvm::opt::InputArgList &InputArgs) { 95 FirstPrivateHeader = InputArgs.hasArg(OBJDUMP_private_header); 96 ExportsTrie = InputArgs.hasArg(OBJDUMP_exports_trie); 97 Rebase = InputArgs.hasArg(OBJDUMP_rebase); 98 Bind = InputArgs.hasArg(OBJDUMP_bind); 99 LazyBind = InputArgs.hasArg(OBJDUMP_lazy_bind); 100 WeakBind = InputArgs.hasArg(OBJDUMP_weak_bind); 101 UseDbg = InputArgs.hasArg(OBJDUMP_g); 102 DSYMFile = InputArgs.getLastArgValue(OBJDUMP_dsym_EQ).str(); 103 FullLeadingAddr = InputArgs.hasArg(OBJDUMP_full_leading_addr); 104 NoLeadingHeaders = InputArgs.hasArg(OBJDUMP_no_leading_headers); 105 UniversalHeaders = InputArgs.hasArg(OBJDUMP_universal_headers); 106 ArchiveMemberOffsets = InputArgs.hasArg(OBJDUMP_archive_member_offsets); 107 IndirectSymbols = InputArgs.hasArg(OBJDUMP_indirect_symbols); 108 DataInCode = InputArgs.hasArg(OBJDUMP_data_in_code); 109 FunctionStarts = InputArgs.hasArg(OBJDUMP_function_starts); 110 LinkOptHints = InputArgs.hasArg(OBJDUMP_link_opt_hints); 111 InfoPlist = InputArgs.hasArg(OBJDUMP_info_plist); 112 DylibsUsed = InputArgs.hasArg(OBJDUMP_dylibs_used); 113 DylibId = InputArgs.hasArg(OBJDUMP_dylib_id); 114 NonVerbose = InputArgs.hasArg(OBJDUMP_non_verbose); 115 ObjcMetaData = InputArgs.hasArg(OBJDUMP_objc_meta_data); 116 DisSymName = InputArgs.getLastArgValue(OBJDUMP_dis_symname).str(); 117 NoSymbolicOperands = InputArgs.hasArg(OBJDUMP_no_symbolic_operands); 118 ArchFlags = InputArgs.getAllArgValues(OBJDUMP_arch_EQ); 119 } 120 121 static const Target *GetTarget(const MachOObjectFile *MachOObj, 122 const char **McpuDefault, 123 const Target **ThumbTarget) { 124 // Figure out the target triple. 125 Triple TT(TripleName); 126 if (TripleName.empty()) { 127 TT = MachOObj->getArchTriple(McpuDefault); 128 TripleName = TT.str(); 129 } 130 131 if (TT.getArch() == Triple::arm) { 132 // We've inferred a 32-bit ARM target from the object file. All MachO CPUs 133 // that support ARM are also capable of Thumb mode. 134 Triple ThumbTriple = TT; 135 std::string ThumbName = (Twine("thumb") + TT.getArchName().substr(3)).str(); 136 ThumbTriple.setArchName(ThumbName); 137 ThumbTripleName = ThumbTriple.str(); 138 } 139 140 // Get the target specific parser. 141 std::string Error; 142 const Target *TheTarget = TargetRegistry::lookupTarget(TripleName, Error); 143 if (TheTarget && ThumbTripleName.empty()) 144 return TheTarget; 145 146 *ThumbTarget = TargetRegistry::lookupTarget(ThumbTripleName, Error); 147 if (*ThumbTarget) 148 return TheTarget; 149 150 WithColor::error(errs(), "llvm-objdump") << "unable to get target for '"; 151 if (!TheTarget) 152 errs() << TripleName; 153 else 154 errs() << ThumbTripleName; 155 errs() << "', see --version and --triple.\n"; 156 return nullptr; 157 } 158 159 namespace { 160 struct SymbolSorter { 161 bool operator()(const SymbolRef &A, const SymbolRef &B) { 162 Expected<SymbolRef::Type> ATypeOrErr = A.getType(); 163 if (!ATypeOrErr) 164 reportError(ATypeOrErr.takeError(), A.getObject()->getFileName()); 165 SymbolRef::Type AType = *ATypeOrErr; 166 Expected<SymbolRef::Type> BTypeOrErr = B.getType(); 167 if (!BTypeOrErr) 168 reportError(BTypeOrErr.takeError(), B.getObject()->getFileName()); 169 SymbolRef::Type BType = *BTypeOrErr; 170 uint64_t AAddr = 171 (AType != SymbolRef::ST_Function) ? 0 : cantFail(A.getValue()); 172 uint64_t BAddr = 173 (BType != SymbolRef::ST_Function) ? 0 : cantFail(B.getValue()); 174 return AAddr < BAddr; 175 } 176 }; 177 } // namespace 178 179 // Types for the storted data in code table that is built before disassembly 180 // and the predicate function to sort them. 181 typedef std::pair<uint64_t, DiceRef> DiceTableEntry; 182 typedef std::vector<DiceTableEntry> DiceTable; 183 typedef DiceTable::iterator dice_table_iterator; 184 185 #ifdef HAVE_LIBXAR 186 namespace { 187 struct ScopedXarFile { 188 xar_t xar; 189 ScopedXarFile(const char *filename, int32_t flags) 190 : xar(xar_open(filename, flags)) {} 191 ~ScopedXarFile() { 192 if (xar) 193 xar_close(xar); 194 } 195 ScopedXarFile(const ScopedXarFile &) = delete; 196 ScopedXarFile &operator=(const ScopedXarFile &) = delete; 197 operator xar_t() { return xar; } 198 }; 199 200 struct ScopedXarIter { 201 xar_iter_t iter; 202 ScopedXarIter() : iter(xar_iter_new()) {} 203 ~ScopedXarIter() { 204 if (iter) 205 xar_iter_free(iter); 206 } 207 ScopedXarIter(const ScopedXarIter &) = delete; 208 ScopedXarIter &operator=(const ScopedXarIter &) = delete; 209 operator xar_iter_t() { return iter; } 210 }; 211 } // namespace 212 #endif // defined(HAVE_LIBXAR) 213 214 // This is used to search for a data in code table entry for the PC being 215 // disassembled. The j parameter has the PC in j.first. A single data in code 216 // table entry can cover many bytes for each of its Kind's. So if the offset, 217 // aka the i.first value, of the data in code table entry plus its Length 218 // covers the PC being searched for this will return true. If not it will 219 // return false. 220 static bool compareDiceTableEntries(const DiceTableEntry &i, 221 const DiceTableEntry &j) { 222 uint16_t Length; 223 i.second.getLength(Length); 224 225 return j.first >= i.first && j.first < i.first + Length; 226 } 227 228 static uint64_t DumpDataInCode(const uint8_t *bytes, uint64_t Length, 229 unsigned short Kind) { 230 uint32_t Value, Size = 1; 231 232 switch (Kind) { 233 default: 234 case MachO::DICE_KIND_DATA: 235 if (Length >= 4) { 236 if (!NoShowRawInsn) 237 dumpBytes(makeArrayRef(bytes, 4), outs()); 238 Value = bytes[3] << 24 | bytes[2] << 16 | bytes[1] << 8 | bytes[0]; 239 outs() << "\t.long " << Value; 240 Size = 4; 241 } else if (Length >= 2) { 242 if (!NoShowRawInsn) 243 dumpBytes(makeArrayRef(bytes, 2), outs()); 244 Value = bytes[1] << 8 | bytes[0]; 245 outs() << "\t.short " << Value; 246 Size = 2; 247 } else { 248 if (!NoShowRawInsn) 249 dumpBytes(makeArrayRef(bytes, 2), outs()); 250 Value = bytes[0]; 251 outs() << "\t.byte " << Value; 252 Size = 1; 253 } 254 if (Kind == MachO::DICE_KIND_DATA) 255 outs() << "\t@ KIND_DATA\n"; 256 else 257 outs() << "\t@ data in code kind = " << Kind << "\n"; 258 break; 259 case MachO::DICE_KIND_JUMP_TABLE8: 260 if (!NoShowRawInsn) 261 dumpBytes(makeArrayRef(bytes, 1), outs()); 262 Value = bytes[0]; 263 outs() << "\t.byte " << format("%3u", Value) << "\t@ KIND_JUMP_TABLE8\n"; 264 Size = 1; 265 break; 266 case MachO::DICE_KIND_JUMP_TABLE16: 267 if (!NoShowRawInsn) 268 dumpBytes(makeArrayRef(bytes, 2), outs()); 269 Value = bytes[1] << 8 | bytes[0]; 270 outs() << "\t.short " << format("%5u", Value & 0xffff) 271 << "\t@ KIND_JUMP_TABLE16\n"; 272 Size = 2; 273 break; 274 case MachO::DICE_KIND_JUMP_TABLE32: 275 case MachO::DICE_KIND_ABS_JUMP_TABLE32: 276 if (!NoShowRawInsn) 277 dumpBytes(makeArrayRef(bytes, 4), outs()); 278 Value = bytes[3] << 24 | bytes[2] << 16 | bytes[1] << 8 | bytes[0]; 279 outs() << "\t.long " << Value; 280 if (Kind == MachO::DICE_KIND_JUMP_TABLE32) 281 outs() << "\t@ KIND_JUMP_TABLE32\n"; 282 else 283 outs() << "\t@ KIND_ABS_JUMP_TABLE32\n"; 284 Size = 4; 285 break; 286 } 287 return Size; 288 } 289 290 static void getSectionsAndSymbols(MachOObjectFile *MachOObj, 291 std::vector<SectionRef> &Sections, 292 std::vector<SymbolRef> &Symbols, 293 SmallVectorImpl<uint64_t> &FoundFns, 294 uint64_t &BaseSegmentAddress) { 295 const StringRef FileName = MachOObj->getFileName(); 296 for (const SymbolRef &Symbol : MachOObj->symbols()) { 297 StringRef SymName = unwrapOrError(Symbol.getName(), FileName); 298 if (!SymName.startswith("ltmp")) 299 Symbols.push_back(Symbol); 300 } 301 302 append_range(Sections, MachOObj->sections()); 303 304 bool BaseSegmentAddressSet = false; 305 for (const auto &Command : MachOObj->load_commands()) { 306 if (Command.C.cmd == MachO::LC_FUNCTION_STARTS) { 307 // We found a function starts segment, parse the addresses for later 308 // consumption. 309 MachO::linkedit_data_command LLC = 310 MachOObj->getLinkeditDataLoadCommand(Command); 311 312 MachOObj->ReadULEB128s(LLC.dataoff, FoundFns); 313 } else if (Command.C.cmd == MachO::LC_SEGMENT) { 314 MachO::segment_command SLC = MachOObj->getSegmentLoadCommand(Command); 315 StringRef SegName = SLC.segname; 316 if (!BaseSegmentAddressSet && SegName != "__PAGEZERO") { 317 BaseSegmentAddressSet = true; 318 BaseSegmentAddress = SLC.vmaddr; 319 } 320 } else if (Command.C.cmd == MachO::LC_SEGMENT_64) { 321 MachO::segment_command_64 SLC = MachOObj->getSegment64LoadCommand(Command); 322 StringRef SegName = SLC.segname; 323 if (!BaseSegmentAddressSet && SegName != "__PAGEZERO") { 324 BaseSegmentAddressSet = true; 325 BaseSegmentAddress = SLC.vmaddr; 326 } 327 } 328 } 329 } 330 331 static bool DumpAndSkipDataInCode(uint64_t PC, const uint8_t *bytes, 332 DiceTable &Dices, uint64_t &InstSize) { 333 // Check the data in code table here to see if this is data not an 334 // instruction to be disassembled. 335 DiceTable Dice; 336 Dice.push_back(std::make_pair(PC, DiceRef())); 337 dice_table_iterator DTI = 338 std::search(Dices.begin(), Dices.end(), Dice.begin(), Dice.end(), 339 compareDiceTableEntries); 340 if (DTI != Dices.end()) { 341 uint16_t Length; 342 DTI->second.getLength(Length); 343 uint16_t Kind; 344 DTI->second.getKind(Kind); 345 InstSize = DumpDataInCode(bytes, Length, Kind); 346 if ((Kind == MachO::DICE_KIND_JUMP_TABLE8) && 347 (PC == (DTI->first + Length - 1)) && (Length & 1)) 348 InstSize++; 349 return true; 350 } 351 return false; 352 } 353 354 static void printRelocationTargetName(const MachOObjectFile *O, 355 const MachO::any_relocation_info &RE, 356 raw_string_ostream &Fmt) { 357 // Target of a scattered relocation is an address. In the interest of 358 // generating pretty output, scan through the symbol table looking for a 359 // symbol that aligns with that address. If we find one, print it. 360 // Otherwise, we just print the hex address of the target. 361 const StringRef FileName = O->getFileName(); 362 if (O->isRelocationScattered(RE)) { 363 uint32_t Val = O->getPlainRelocationSymbolNum(RE); 364 365 for (const SymbolRef &Symbol : O->symbols()) { 366 uint64_t Addr = unwrapOrError(Symbol.getAddress(), FileName); 367 if (Addr != Val) 368 continue; 369 Fmt << unwrapOrError(Symbol.getName(), FileName); 370 return; 371 } 372 373 // If we couldn't find a symbol that this relocation refers to, try 374 // to find a section beginning instead. 375 for (const SectionRef &Section : ToolSectionFilter(*O)) { 376 uint64_t Addr = Section.getAddress(); 377 if (Addr != Val) 378 continue; 379 StringRef NameOrErr = unwrapOrError(Section.getName(), O->getFileName()); 380 Fmt << NameOrErr; 381 return; 382 } 383 384 Fmt << format("0x%x", Val); 385 return; 386 } 387 388 StringRef S; 389 bool isExtern = O->getPlainRelocationExternal(RE); 390 uint64_t Val = O->getPlainRelocationSymbolNum(RE); 391 392 if (O->getAnyRelocationType(RE) == MachO::ARM64_RELOC_ADDEND && 393 (O->getArch() == Triple::aarch64 || O->getArch() == Triple::aarch64_be)) { 394 Fmt << format("0x%0" PRIx64, Val); 395 return; 396 } 397 398 if (isExtern) { 399 symbol_iterator SI = O->symbol_begin(); 400 std::advance(SI, Val); 401 S = unwrapOrError(SI->getName(), FileName); 402 } else { 403 section_iterator SI = O->section_begin(); 404 // Adjust for the fact that sections are 1-indexed. 405 if (Val == 0) { 406 Fmt << "0 (?,?)"; 407 return; 408 } 409 uint32_t I = Val - 1; 410 while (I != 0 && SI != O->section_end()) { 411 --I; 412 std::advance(SI, 1); 413 } 414 if (SI == O->section_end()) { 415 Fmt << Val << " (?,?)"; 416 } else { 417 if (Expected<StringRef> NameOrErr = SI->getName()) 418 S = *NameOrErr; 419 else 420 consumeError(NameOrErr.takeError()); 421 } 422 } 423 424 Fmt << S; 425 } 426 427 Error objdump::getMachORelocationValueString(const MachOObjectFile *Obj, 428 const RelocationRef &RelRef, 429 SmallVectorImpl<char> &Result) { 430 DataRefImpl Rel = RelRef.getRawDataRefImpl(); 431 MachO::any_relocation_info RE = Obj->getRelocation(Rel); 432 433 unsigned Arch = Obj->getArch(); 434 435 std::string FmtBuf; 436 raw_string_ostream Fmt(FmtBuf); 437 unsigned Type = Obj->getAnyRelocationType(RE); 438 bool IsPCRel = Obj->getAnyRelocationPCRel(RE); 439 440 // Determine any addends that should be displayed with the relocation. 441 // These require decoding the relocation type, which is triple-specific. 442 443 // X86_64 has entirely custom relocation types. 444 if (Arch == Triple::x86_64) { 445 switch (Type) { 446 case MachO::X86_64_RELOC_GOT_LOAD: 447 case MachO::X86_64_RELOC_GOT: { 448 printRelocationTargetName(Obj, RE, Fmt); 449 Fmt << "@GOT"; 450 if (IsPCRel) 451 Fmt << "PCREL"; 452 break; 453 } 454 case MachO::X86_64_RELOC_SUBTRACTOR: { 455 DataRefImpl RelNext = Rel; 456 Obj->moveRelocationNext(RelNext); 457 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext); 458 459 // X86_64_RELOC_SUBTRACTOR must be followed by a relocation of type 460 // X86_64_RELOC_UNSIGNED. 461 // NOTE: Scattered relocations don't exist on x86_64. 462 unsigned RType = Obj->getAnyRelocationType(RENext); 463 if (RType != MachO::X86_64_RELOC_UNSIGNED) 464 reportError(Obj->getFileName(), "Expected X86_64_RELOC_UNSIGNED after " 465 "X86_64_RELOC_SUBTRACTOR."); 466 467 // The X86_64_RELOC_UNSIGNED contains the minuend symbol; 468 // X86_64_RELOC_SUBTRACTOR contains the subtrahend. 469 printRelocationTargetName(Obj, RENext, Fmt); 470 Fmt << "-"; 471 printRelocationTargetName(Obj, RE, Fmt); 472 break; 473 } 474 case MachO::X86_64_RELOC_TLV: 475 printRelocationTargetName(Obj, RE, Fmt); 476 Fmt << "@TLV"; 477 if (IsPCRel) 478 Fmt << "P"; 479 break; 480 case MachO::X86_64_RELOC_SIGNED_1: 481 printRelocationTargetName(Obj, RE, Fmt); 482 Fmt << "-1"; 483 break; 484 case MachO::X86_64_RELOC_SIGNED_2: 485 printRelocationTargetName(Obj, RE, Fmt); 486 Fmt << "-2"; 487 break; 488 case MachO::X86_64_RELOC_SIGNED_4: 489 printRelocationTargetName(Obj, RE, Fmt); 490 Fmt << "-4"; 491 break; 492 default: 493 printRelocationTargetName(Obj, RE, Fmt); 494 break; 495 } 496 // X86 and ARM share some relocation types in common. 497 } else if (Arch == Triple::x86 || Arch == Triple::arm || 498 Arch == Triple::ppc) { 499 // Generic relocation types... 500 switch (Type) { 501 case MachO::GENERIC_RELOC_PAIR: // prints no info 502 return Error::success(); 503 case MachO::GENERIC_RELOC_SECTDIFF: { 504 DataRefImpl RelNext = Rel; 505 Obj->moveRelocationNext(RelNext); 506 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext); 507 508 // X86 sect diff's must be followed by a relocation of type 509 // GENERIC_RELOC_PAIR. 510 unsigned RType = Obj->getAnyRelocationType(RENext); 511 512 if (RType != MachO::GENERIC_RELOC_PAIR) 513 reportError(Obj->getFileName(), "Expected GENERIC_RELOC_PAIR after " 514 "GENERIC_RELOC_SECTDIFF."); 515 516 printRelocationTargetName(Obj, RE, Fmt); 517 Fmt << "-"; 518 printRelocationTargetName(Obj, RENext, Fmt); 519 break; 520 } 521 } 522 523 if (Arch == Triple::x86 || Arch == Triple::ppc) { 524 switch (Type) { 525 case MachO::GENERIC_RELOC_LOCAL_SECTDIFF: { 526 DataRefImpl RelNext = Rel; 527 Obj->moveRelocationNext(RelNext); 528 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext); 529 530 // X86 sect diff's must be followed by a relocation of type 531 // GENERIC_RELOC_PAIR. 532 unsigned RType = Obj->getAnyRelocationType(RENext); 533 if (RType != MachO::GENERIC_RELOC_PAIR) 534 reportError(Obj->getFileName(), "Expected GENERIC_RELOC_PAIR after " 535 "GENERIC_RELOC_LOCAL_SECTDIFF."); 536 537 printRelocationTargetName(Obj, RE, Fmt); 538 Fmt << "-"; 539 printRelocationTargetName(Obj, RENext, Fmt); 540 break; 541 } 542 case MachO::GENERIC_RELOC_TLV: { 543 printRelocationTargetName(Obj, RE, Fmt); 544 Fmt << "@TLV"; 545 if (IsPCRel) 546 Fmt << "P"; 547 break; 548 } 549 default: 550 printRelocationTargetName(Obj, RE, Fmt); 551 } 552 } else { // ARM-specific relocations 553 switch (Type) { 554 case MachO::ARM_RELOC_HALF: 555 case MachO::ARM_RELOC_HALF_SECTDIFF: { 556 // Half relocations steal a bit from the length field to encode 557 // whether this is an upper16 or a lower16 relocation. 558 bool isUpper = (Obj->getAnyRelocationLength(RE) & 0x1) == 1; 559 560 if (isUpper) 561 Fmt << ":upper16:("; 562 else 563 Fmt << ":lower16:("; 564 printRelocationTargetName(Obj, RE, Fmt); 565 566 DataRefImpl RelNext = Rel; 567 Obj->moveRelocationNext(RelNext); 568 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext); 569 570 // ARM half relocs must be followed by a relocation of type 571 // ARM_RELOC_PAIR. 572 unsigned RType = Obj->getAnyRelocationType(RENext); 573 if (RType != MachO::ARM_RELOC_PAIR) 574 reportError(Obj->getFileName(), "Expected ARM_RELOC_PAIR after " 575 "ARM_RELOC_HALF"); 576 577 // NOTE: The half of the target virtual address is stashed in the 578 // address field of the secondary relocation, but we can't reverse 579 // engineer the constant offset from it without decoding the movw/movt 580 // instruction to find the other half in its immediate field. 581 582 // ARM_RELOC_HALF_SECTDIFF encodes the second section in the 583 // symbol/section pointer of the follow-on relocation. 584 if (Type == MachO::ARM_RELOC_HALF_SECTDIFF) { 585 Fmt << "-"; 586 printRelocationTargetName(Obj, RENext, Fmt); 587 } 588 589 Fmt << ")"; 590 break; 591 } 592 default: { 593 printRelocationTargetName(Obj, RE, Fmt); 594 } 595 } 596 } 597 } else 598 printRelocationTargetName(Obj, RE, Fmt); 599 600 Fmt.flush(); 601 Result.append(FmtBuf.begin(), FmtBuf.end()); 602 return Error::success(); 603 } 604 605 static void PrintIndirectSymbolTable(MachOObjectFile *O, bool verbose, 606 uint32_t n, uint32_t count, 607 uint32_t stride, uint64_t addr) { 608 MachO::dysymtab_command Dysymtab = O->getDysymtabLoadCommand(); 609 uint32_t nindirectsyms = Dysymtab.nindirectsyms; 610 if (n > nindirectsyms) 611 outs() << " (entries start past the end of the indirect symbol " 612 "table) (reserved1 field greater than the table size)"; 613 else if (n + count > nindirectsyms) 614 outs() << " (entries extends past the end of the indirect symbol " 615 "table)"; 616 outs() << "\n"; 617 uint32_t cputype = O->getHeader().cputype; 618 if (cputype & MachO::CPU_ARCH_ABI64) 619 outs() << "address index"; 620 else 621 outs() << "address index"; 622 if (verbose) 623 outs() << " name\n"; 624 else 625 outs() << "\n"; 626 for (uint32_t j = 0; j < count && n + j < nindirectsyms; j++) { 627 if (cputype & MachO::CPU_ARCH_ABI64) 628 outs() << format("0x%016" PRIx64, addr + j * stride) << " "; 629 else 630 outs() << format("0x%08" PRIx32, (uint32_t)addr + j * stride) << " "; 631 MachO::dysymtab_command Dysymtab = O->getDysymtabLoadCommand(); 632 uint32_t indirect_symbol = O->getIndirectSymbolTableEntry(Dysymtab, n + j); 633 if (indirect_symbol == MachO::INDIRECT_SYMBOL_LOCAL) { 634 outs() << "LOCAL\n"; 635 continue; 636 } 637 if (indirect_symbol == 638 (MachO::INDIRECT_SYMBOL_LOCAL | MachO::INDIRECT_SYMBOL_ABS)) { 639 outs() << "LOCAL ABSOLUTE\n"; 640 continue; 641 } 642 if (indirect_symbol == MachO::INDIRECT_SYMBOL_ABS) { 643 outs() << "ABSOLUTE\n"; 644 continue; 645 } 646 outs() << format("%5u ", indirect_symbol); 647 if (verbose) { 648 MachO::symtab_command Symtab = O->getSymtabLoadCommand(); 649 if (indirect_symbol < Symtab.nsyms) { 650 symbol_iterator Sym = O->getSymbolByIndex(indirect_symbol); 651 SymbolRef Symbol = *Sym; 652 outs() << unwrapOrError(Symbol.getName(), O->getFileName()); 653 } else { 654 outs() << "?"; 655 } 656 } 657 outs() << "\n"; 658 } 659 } 660 661 static void PrintIndirectSymbols(MachOObjectFile *O, bool verbose) { 662 for (const auto &Load : O->load_commands()) { 663 if (Load.C.cmd == MachO::LC_SEGMENT_64) { 664 MachO::segment_command_64 Seg = O->getSegment64LoadCommand(Load); 665 for (unsigned J = 0; J < Seg.nsects; ++J) { 666 MachO::section_64 Sec = O->getSection64(Load, J); 667 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE; 668 if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS || 669 section_type == MachO::S_LAZY_SYMBOL_POINTERS || 670 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS || 671 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS || 672 section_type == MachO::S_SYMBOL_STUBS) { 673 uint32_t stride; 674 if (section_type == MachO::S_SYMBOL_STUBS) 675 stride = Sec.reserved2; 676 else 677 stride = 8; 678 if (stride == 0) { 679 outs() << "Can't print indirect symbols for (" << Sec.segname << "," 680 << Sec.sectname << ") " 681 << "(size of stubs in reserved2 field is zero)\n"; 682 continue; 683 } 684 uint32_t count = Sec.size / stride; 685 outs() << "Indirect symbols for (" << Sec.segname << "," 686 << Sec.sectname << ") " << count << " entries"; 687 uint32_t n = Sec.reserved1; 688 PrintIndirectSymbolTable(O, verbose, n, count, stride, Sec.addr); 689 } 690 } 691 } else if (Load.C.cmd == MachO::LC_SEGMENT) { 692 MachO::segment_command Seg = O->getSegmentLoadCommand(Load); 693 for (unsigned J = 0; J < Seg.nsects; ++J) { 694 MachO::section Sec = O->getSection(Load, J); 695 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE; 696 if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS || 697 section_type == MachO::S_LAZY_SYMBOL_POINTERS || 698 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS || 699 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS || 700 section_type == MachO::S_SYMBOL_STUBS) { 701 uint32_t stride; 702 if (section_type == MachO::S_SYMBOL_STUBS) 703 stride = Sec.reserved2; 704 else 705 stride = 4; 706 if (stride == 0) { 707 outs() << "Can't print indirect symbols for (" << Sec.segname << "," 708 << Sec.sectname << ") " 709 << "(size of stubs in reserved2 field is zero)\n"; 710 continue; 711 } 712 uint32_t count = Sec.size / stride; 713 outs() << "Indirect symbols for (" << Sec.segname << "," 714 << Sec.sectname << ") " << count << " entries"; 715 uint32_t n = Sec.reserved1; 716 PrintIndirectSymbolTable(O, verbose, n, count, stride, Sec.addr); 717 } 718 } 719 } 720 } 721 } 722 723 static void PrintRType(const uint64_t cputype, const unsigned r_type) { 724 static char const *generic_r_types[] = { 725 "VANILLA ", "PAIR ", "SECTDIF ", "PBLAPTR ", "LOCSDIF ", "TLV ", 726 " 6 (?) ", " 7 (?) ", " 8 (?) ", " 9 (?) ", " 10 (?) ", " 11 (?) ", 727 " 12 (?) ", " 13 (?) ", " 14 (?) ", " 15 (?) " 728 }; 729 static char const *x86_64_r_types[] = { 730 "UNSIGND ", "SIGNED ", "BRANCH ", "GOT_LD ", "GOT ", "SUB ", 731 "SIGNED1 ", "SIGNED2 ", "SIGNED4 ", "TLV ", " 10 (?) ", " 11 (?) ", 732 " 12 (?) ", " 13 (?) ", " 14 (?) ", " 15 (?) " 733 }; 734 static char const *arm_r_types[] = { 735 "VANILLA ", "PAIR ", "SECTDIFF", "LOCSDIF ", "PBLAPTR ", 736 "BR24 ", "T_BR22 ", "T_BR32 ", "HALF ", "HALFDIF ", 737 " 10 (?) ", " 11 (?) ", " 12 (?) ", " 13 (?) ", " 14 (?) ", " 15 (?) " 738 }; 739 static char const *arm64_r_types[] = { 740 "UNSIGND ", "SUB ", "BR26 ", "PAGE21 ", "PAGOF12 ", 741 "GOTLDP ", "GOTLDPOF", "PTRTGOT ", "TLVLDP ", "TLVLDPOF", 742 "ADDEND ", " 11 (?) ", " 12 (?) ", " 13 (?) ", " 14 (?) ", " 15 (?) " 743 }; 744 745 if (r_type > 0xf){ 746 outs() << format("%-7u", r_type) << " "; 747 return; 748 } 749 switch (cputype) { 750 case MachO::CPU_TYPE_I386: 751 outs() << generic_r_types[r_type]; 752 break; 753 case MachO::CPU_TYPE_X86_64: 754 outs() << x86_64_r_types[r_type]; 755 break; 756 case MachO::CPU_TYPE_ARM: 757 outs() << arm_r_types[r_type]; 758 break; 759 case MachO::CPU_TYPE_ARM64: 760 case MachO::CPU_TYPE_ARM64_32: 761 outs() << arm64_r_types[r_type]; 762 break; 763 default: 764 outs() << format("%-7u ", r_type); 765 } 766 } 767 768 static void PrintRLength(const uint64_t cputype, const unsigned r_type, 769 const unsigned r_length, const bool previous_arm_half){ 770 if (cputype == MachO::CPU_TYPE_ARM && 771 (r_type == MachO::ARM_RELOC_HALF || 772 r_type == MachO::ARM_RELOC_HALF_SECTDIFF || previous_arm_half == true)) { 773 if ((r_length & 0x1) == 0) 774 outs() << "lo/"; 775 else 776 outs() << "hi/"; 777 if ((r_length & 0x1) == 0) 778 outs() << "arm "; 779 else 780 outs() << "thm "; 781 } else { 782 switch (r_length) { 783 case 0: 784 outs() << "byte "; 785 break; 786 case 1: 787 outs() << "word "; 788 break; 789 case 2: 790 outs() << "long "; 791 break; 792 case 3: 793 if (cputype == MachO::CPU_TYPE_X86_64) 794 outs() << "quad "; 795 else 796 outs() << format("?(%2d) ", r_length); 797 break; 798 default: 799 outs() << format("?(%2d) ", r_length); 800 } 801 } 802 } 803 804 static void PrintRelocationEntries(const MachOObjectFile *O, 805 const relocation_iterator Begin, 806 const relocation_iterator End, 807 const uint64_t cputype, 808 const bool verbose) { 809 const MachO::symtab_command Symtab = O->getSymtabLoadCommand(); 810 bool previous_arm_half = false; 811 bool previous_sectdiff = false; 812 uint32_t sectdiff_r_type = 0; 813 814 for (relocation_iterator Reloc = Begin; Reloc != End; ++Reloc) { 815 const DataRefImpl Rel = Reloc->getRawDataRefImpl(); 816 const MachO::any_relocation_info RE = O->getRelocation(Rel); 817 const unsigned r_type = O->getAnyRelocationType(RE); 818 const bool r_scattered = O->isRelocationScattered(RE); 819 const unsigned r_pcrel = O->getAnyRelocationPCRel(RE); 820 const unsigned r_length = O->getAnyRelocationLength(RE); 821 const unsigned r_address = O->getAnyRelocationAddress(RE); 822 const bool r_extern = (r_scattered ? false : 823 O->getPlainRelocationExternal(RE)); 824 const uint32_t r_value = (r_scattered ? 825 O->getScatteredRelocationValue(RE) : 0); 826 const unsigned r_symbolnum = (r_scattered ? 0 : 827 O->getPlainRelocationSymbolNum(RE)); 828 829 if (r_scattered && cputype != MachO::CPU_TYPE_X86_64) { 830 if (verbose) { 831 // scattered: address 832 if ((cputype == MachO::CPU_TYPE_I386 && 833 r_type == MachO::GENERIC_RELOC_PAIR) || 834 (cputype == MachO::CPU_TYPE_ARM && r_type == MachO::ARM_RELOC_PAIR)) 835 outs() << " "; 836 else 837 outs() << format("%08x ", (unsigned int)r_address); 838 839 // scattered: pcrel 840 if (r_pcrel) 841 outs() << "True "; 842 else 843 outs() << "False "; 844 845 // scattered: length 846 PrintRLength(cputype, r_type, r_length, previous_arm_half); 847 848 // scattered: extern & type 849 outs() << "n/a "; 850 PrintRType(cputype, r_type); 851 852 // scattered: scattered & value 853 outs() << format("True 0x%08x", (unsigned int)r_value); 854 if (previous_sectdiff == false) { 855 if ((cputype == MachO::CPU_TYPE_ARM && 856 r_type == MachO::ARM_RELOC_PAIR)) 857 outs() << format(" half = 0x%04x ", (unsigned int)r_address); 858 } else if (cputype == MachO::CPU_TYPE_ARM && 859 sectdiff_r_type == MachO::ARM_RELOC_HALF_SECTDIFF) 860 outs() << format(" other_half = 0x%04x ", (unsigned int)r_address); 861 if ((cputype == MachO::CPU_TYPE_I386 && 862 (r_type == MachO::GENERIC_RELOC_SECTDIFF || 863 r_type == MachO::GENERIC_RELOC_LOCAL_SECTDIFF)) || 864 (cputype == MachO::CPU_TYPE_ARM && 865 (sectdiff_r_type == MachO::ARM_RELOC_SECTDIFF || 866 sectdiff_r_type == MachO::ARM_RELOC_LOCAL_SECTDIFF || 867 sectdiff_r_type == MachO::ARM_RELOC_HALF_SECTDIFF))) { 868 previous_sectdiff = true; 869 sectdiff_r_type = r_type; 870 } else { 871 previous_sectdiff = false; 872 sectdiff_r_type = 0; 873 } 874 if (cputype == MachO::CPU_TYPE_ARM && 875 (r_type == MachO::ARM_RELOC_HALF || 876 r_type == MachO::ARM_RELOC_HALF_SECTDIFF)) 877 previous_arm_half = true; 878 else 879 previous_arm_half = false; 880 outs() << "\n"; 881 } 882 else { 883 // scattered: address pcrel length extern type scattered value 884 outs() << format("%08x %1d %-2d n/a %-7d 1 0x%08x\n", 885 (unsigned int)r_address, r_pcrel, r_length, r_type, 886 (unsigned int)r_value); 887 } 888 } 889 else { 890 if (verbose) { 891 // plain: address 892 if (cputype == MachO::CPU_TYPE_ARM && r_type == MachO::ARM_RELOC_PAIR) 893 outs() << " "; 894 else 895 outs() << format("%08x ", (unsigned int)r_address); 896 897 // plain: pcrel 898 if (r_pcrel) 899 outs() << "True "; 900 else 901 outs() << "False "; 902 903 // plain: length 904 PrintRLength(cputype, r_type, r_length, previous_arm_half); 905 906 if (r_extern) { 907 // plain: extern & type & scattered 908 outs() << "True "; 909 PrintRType(cputype, r_type); 910 outs() << "False "; 911 912 // plain: symbolnum/value 913 if (r_symbolnum > Symtab.nsyms) 914 outs() << format("?(%d)\n", r_symbolnum); 915 else { 916 SymbolRef Symbol = *O->getSymbolByIndex(r_symbolnum); 917 Expected<StringRef> SymNameNext = Symbol.getName(); 918 const char *name = NULL; 919 if (SymNameNext) 920 name = SymNameNext->data(); 921 if (name == NULL) 922 outs() << format("?(%d)\n", r_symbolnum); 923 else 924 outs() << name << "\n"; 925 } 926 } 927 else { 928 // plain: extern & type & scattered 929 outs() << "False "; 930 PrintRType(cputype, r_type); 931 outs() << "False "; 932 933 // plain: symbolnum/value 934 if (cputype == MachO::CPU_TYPE_ARM && r_type == MachO::ARM_RELOC_PAIR) 935 outs() << format("other_half = 0x%04x\n", (unsigned int)r_address); 936 else if ((cputype == MachO::CPU_TYPE_ARM64 || 937 cputype == MachO::CPU_TYPE_ARM64_32) && 938 r_type == MachO::ARM64_RELOC_ADDEND) 939 outs() << format("addend = 0x%06x\n", (unsigned int)r_symbolnum); 940 else { 941 outs() << format("%d ", r_symbolnum); 942 if (r_symbolnum == MachO::R_ABS) 943 outs() << "R_ABS\n"; 944 else { 945 // in this case, r_symbolnum is actually a 1-based section number 946 uint32_t nsects = O->section_end()->getRawDataRefImpl().d.a; 947 if (r_symbolnum > 0 && r_symbolnum <= nsects) { 948 object::DataRefImpl DRI; 949 DRI.d.a = r_symbolnum-1; 950 StringRef SegName = O->getSectionFinalSegmentName(DRI); 951 if (Expected<StringRef> NameOrErr = O->getSectionName(DRI)) 952 outs() << "(" << SegName << "," << *NameOrErr << ")\n"; 953 else 954 outs() << "(?,?)\n"; 955 } 956 else { 957 outs() << "(?,?)\n"; 958 } 959 } 960 } 961 } 962 if (cputype == MachO::CPU_TYPE_ARM && 963 (r_type == MachO::ARM_RELOC_HALF || 964 r_type == MachO::ARM_RELOC_HALF_SECTDIFF)) 965 previous_arm_half = true; 966 else 967 previous_arm_half = false; 968 } 969 else { 970 // plain: address pcrel length extern type scattered symbolnum/section 971 outs() << format("%08x %1d %-2d %1d %-7d 0 %d\n", 972 (unsigned int)r_address, r_pcrel, r_length, r_extern, 973 r_type, r_symbolnum); 974 } 975 } 976 } 977 } 978 979 static void PrintRelocations(const MachOObjectFile *O, const bool verbose) { 980 const uint64_t cputype = O->getHeader().cputype; 981 const MachO::dysymtab_command Dysymtab = O->getDysymtabLoadCommand(); 982 if (Dysymtab.nextrel != 0) { 983 outs() << "External relocation information " << Dysymtab.nextrel 984 << " entries"; 985 outs() << "\naddress pcrel length extern type scattered " 986 "symbolnum/value\n"; 987 PrintRelocationEntries(O, O->extrel_begin(), O->extrel_end(), cputype, 988 verbose); 989 } 990 if (Dysymtab.nlocrel != 0) { 991 outs() << format("Local relocation information %u entries", 992 Dysymtab.nlocrel); 993 outs() << "\naddress pcrel length extern type scattered " 994 "symbolnum/value\n"; 995 PrintRelocationEntries(O, O->locrel_begin(), O->locrel_end(), cputype, 996 verbose); 997 } 998 for (const auto &Load : O->load_commands()) { 999 if (Load.C.cmd == MachO::LC_SEGMENT_64) { 1000 const MachO::segment_command_64 Seg = O->getSegment64LoadCommand(Load); 1001 for (unsigned J = 0; J < Seg.nsects; ++J) { 1002 const MachO::section_64 Sec = O->getSection64(Load, J); 1003 if (Sec.nreloc != 0) { 1004 DataRefImpl DRI; 1005 DRI.d.a = J; 1006 const StringRef SegName = O->getSectionFinalSegmentName(DRI); 1007 if (Expected<StringRef> NameOrErr = O->getSectionName(DRI)) 1008 outs() << "Relocation information (" << SegName << "," << *NameOrErr 1009 << format(") %u entries", Sec.nreloc); 1010 else 1011 outs() << "Relocation information (" << SegName << ",?) " 1012 << format("%u entries", Sec.nreloc); 1013 outs() << "\naddress pcrel length extern type scattered " 1014 "symbolnum/value\n"; 1015 PrintRelocationEntries(O, O->section_rel_begin(DRI), 1016 O->section_rel_end(DRI), cputype, verbose); 1017 } 1018 } 1019 } else if (Load.C.cmd == MachO::LC_SEGMENT) { 1020 const MachO::segment_command Seg = O->getSegmentLoadCommand(Load); 1021 for (unsigned J = 0; J < Seg.nsects; ++J) { 1022 const MachO::section Sec = O->getSection(Load, J); 1023 if (Sec.nreloc != 0) { 1024 DataRefImpl DRI; 1025 DRI.d.a = J; 1026 const StringRef SegName = O->getSectionFinalSegmentName(DRI); 1027 if (Expected<StringRef> NameOrErr = O->getSectionName(DRI)) 1028 outs() << "Relocation information (" << SegName << "," << *NameOrErr 1029 << format(") %u entries", Sec.nreloc); 1030 else 1031 outs() << "Relocation information (" << SegName << ",?) " 1032 << format("%u entries", Sec.nreloc); 1033 outs() << "\naddress pcrel length extern type scattered " 1034 "symbolnum/value\n"; 1035 PrintRelocationEntries(O, O->section_rel_begin(DRI), 1036 O->section_rel_end(DRI), cputype, verbose); 1037 } 1038 } 1039 } 1040 } 1041 } 1042 1043 static void PrintFunctionStarts(MachOObjectFile *O) { 1044 uint64_t BaseSegmentAddress = 0; 1045 for (const MachOObjectFile::LoadCommandInfo &Command : O->load_commands()) { 1046 if (Command.C.cmd == MachO::LC_SEGMENT) { 1047 MachO::segment_command SLC = O->getSegmentLoadCommand(Command); 1048 if (StringRef(SLC.segname) == "__TEXT") { 1049 BaseSegmentAddress = SLC.vmaddr; 1050 break; 1051 } 1052 } else if (Command.C.cmd == MachO::LC_SEGMENT_64) { 1053 MachO::segment_command_64 SLC = O->getSegment64LoadCommand(Command); 1054 if (StringRef(SLC.segname) == "__TEXT") { 1055 BaseSegmentAddress = SLC.vmaddr; 1056 break; 1057 } 1058 } 1059 } 1060 1061 SmallVector<uint64_t, 8> FunctionStarts; 1062 for (const MachOObjectFile::LoadCommandInfo &LC : O->load_commands()) { 1063 if (LC.C.cmd == MachO::LC_FUNCTION_STARTS) { 1064 MachO::linkedit_data_command FunctionStartsLC = 1065 O->getLinkeditDataLoadCommand(LC); 1066 O->ReadULEB128s(FunctionStartsLC.dataoff, FunctionStarts); 1067 break; 1068 } 1069 } 1070 1071 for (uint64_t S : FunctionStarts) { 1072 uint64_t Addr = BaseSegmentAddress + S; 1073 if (O->is64Bit()) 1074 outs() << format("%016" PRIx64, Addr) << "\n"; 1075 else 1076 outs() << format("%08" PRIx32, static_cast<uint32_t>(Addr)) << "\n"; 1077 } 1078 } 1079 1080 static void PrintDataInCodeTable(MachOObjectFile *O, bool verbose) { 1081 MachO::linkedit_data_command DIC = O->getDataInCodeLoadCommand(); 1082 uint32_t nentries = DIC.datasize / sizeof(struct MachO::data_in_code_entry); 1083 outs() << "Data in code table (" << nentries << " entries)\n"; 1084 outs() << "offset length kind\n"; 1085 for (dice_iterator DI = O->begin_dices(), DE = O->end_dices(); DI != DE; 1086 ++DI) { 1087 uint32_t Offset; 1088 DI->getOffset(Offset); 1089 outs() << format("0x%08" PRIx32, Offset) << " "; 1090 uint16_t Length; 1091 DI->getLength(Length); 1092 outs() << format("%6u", Length) << " "; 1093 uint16_t Kind; 1094 DI->getKind(Kind); 1095 if (verbose) { 1096 switch (Kind) { 1097 case MachO::DICE_KIND_DATA: 1098 outs() << "DATA"; 1099 break; 1100 case MachO::DICE_KIND_JUMP_TABLE8: 1101 outs() << "JUMP_TABLE8"; 1102 break; 1103 case MachO::DICE_KIND_JUMP_TABLE16: 1104 outs() << "JUMP_TABLE16"; 1105 break; 1106 case MachO::DICE_KIND_JUMP_TABLE32: 1107 outs() << "JUMP_TABLE32"; 1108 break; 1109 case MachO::DICE_KIND_ABS_JUMP_TABLE32: 1110 outs() << "ABS_JUMP_TABLE32"; 1111 break; 1112 default: 1113 outs() << format("0x%04" PRIx32, Kind); 1114 break; 1115 } 1116 } else 1117 outs() << format("0x%04" PRIx32, Kind); 1118 outs() << "\n"; 1119 } 1120 } 1121 1122 static void PrintLinkOptHints(MachOObjectFile *O) { 1123 MachO::linkedit_data_command LohLC = O->getLinkOptHintsLoadCommand(); 1124 const char *loh = O->getData().substr(LohLC.dataoff, 1).data(); 1125 uint32_t nloh = LohLC.datasize; 1126 outs() << "Linker optimiztion hints (" << nloh << " total bytes)\n"; 1127 for (uint32_t i = 0; i < nloh;) { 1128 unsigned n; 1129 uint64_t identifier = decodeULEB128((const uint8_t *)(loh + i), &n); 1130 i += n; 1131 outs() << " identifier " << identifier << " "; 1132 if (i >= nloh) 1133 return; 1134 switch (identifier) { 1135 case 1: 1136 outs() << "AdrpAdrp\n"; 1137 break; 1138 case 2: 1139 outs() << "AdrpLdr\n"; 1140 break; 1141 case 3: 1142 outs() << "AdrpAddLdr\n"; 1143 break; 1144 case 4: 1145 outs() << "AdrpLdrGotLdr\n"; 1146 break; 1147 case 5: 1148 outs() << "AdrpAddStr\n"; 1149 break; 1150 case 6: 1151 outs() << "AdrpLdrGotStr\n"; 1152 break; 1153 case 7: 1154 outs() << "AdrpAdd\n"; 1155 break; 1156 case 8: 1157 outs() << "AdrpLdrGot\n"; 1158 break; 1159 default: 1160 outs() << "Unknown identifier value\n"; 1161 break; 1162 } 1163 uint64_t narguments = decodeULEB128((const uint8_t *)(loh + i), &n); 1164 i += n; 1165 outs() << " narguments " << narguments << "\n"; 1166 if (i >= nloh) 1167 return; 1168 1169 for (uint32_t j = 0; j < narguments; j++) { 1170 uint64_t value = decodeULEB128((const uint8_t *)(loh + i), &n); 1171 i += n; 1172 outs() << "\tvalue " << format("0x%" PRIx64, value) << "\n"; 1173 if (i >= nloh) 1174 return; 1175 } 1176 } 1177 } 1178 1179 static void PrintDylibs(MachOObjectFile *O, bool JustId) { 1180 unsigned Index = 0; 1181 for (const auto &Load : O->load_commands()) { 1182 if ((JustId && Load.C.cmd == MachO::LC_ID_DYLIB) || 1183 (!JustId && (Load.C.cmd == MachO::LC_ID_DYLIB || 1184 Load.C.cmd == MachO::LC_LOAD_DYLIB || 1185 Load.C.cmd == MachO::LC_LOAD_WEAK_DYLIB || 1186 Load.C.cmd == MachO::LC_REEXPORT_DYLIB || 1187 Load.C.cmd == MachO::LC_LAZY_LOAD_DYLIB || 1188 Load.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB))) { 1189 MachO::dylib_command dl = O->getDylibIDLoadCommand(Load); 1190 if (dl.dylib.name < dl.cmdsize) { 1191 const char *p = (const char *)(Load.Ptr) + dl.dylib.name; 1192 if (JustId) 1193 outs() << p << "\n"; 1194 else { 1195 outs() << "\t" << p; 1196 outs() << " (compatibility version " 1197 << ((dl.dylib.compatibility_version >> 16) & 0xffff) << "." 1198 << ((dl.dylib.compatibility_version >> 8) & 0xff) << "." 1199 << (dl.dylib.compatibility_version & 0xff) << ","; 1200 outs() << " current version " 1201 << ((dl.dylib.current_version >> 16) & 0xffff) << "." 1202 << ((dl.dylib.current_version >> 8) & 0xff) << "." 1203 << (dl.dylib.current_version & 0xff); 1204 if (Load.C.cmd == MachO::LC_LOAD_WEAK_DYLIB) 1205 outs() << ", weak"; 1206 if (Load.C.cmd == MachO::LC_REEXPORT_DYLIB) 1207 outs() << ", reexport"; 1208 if (Load.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB) 1209 outs() << ", upward"; 1210 if (Load.C.cmd == MachO::LC_LAZY_LOAD_DYLIB) 1211 outs() << ", lazy"; 1212 outs() << ")\n"; 1213 } 1214 } else { 1215 outs() << "\tBad offset (" << dl.dylib.name << ") for name of "; 1216 if (Load.C.cmd == MachO::LC_ID_DYLIB) 1217 outs() << "LC_ID_DYLIB "; 1218 else if (Load.C.cmd == MachO::LC_LOAD_DYLIB) 1219 outs() << "LC_LOAD_DYLIB "; 1220 else if (Load.C.cmd == MachO::LC_LOAD_WEAK_DYLIB) 1221 outs() << "LC_LOAD_WEAK_DYLIB "; 1222 else if (Load.C.cmd == MachO::LC_LAZY_LOAD_DYLIB) 1223 outs() << "LC_LAZY_LOAD_DYLIB "; 1224 else if (Load.C.cmd == MachO::LC_REEXPORT_DYLIB) 1225 outs() << "LC_REEXPORT_DYLIB "; 1226 else if (Load.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB) 1227 outs() << "LC_LOAD_UPWARD_DYLIB "; 1228 else 1229 outs() << "LC_??? "; 1230 outs() << "command " << Index++ << "\n"; 1231 } 1232 } 1233 } 1234 } 1235 1236 typedef DenseMap<uint64_t, StringRef> SymbolAddressMap; 1237 1238 static void CreateSymbolAddressMap(MachOObjectFile *O, 1239 SymbolAddressMap *AddrMap) { 1240 // Create a map of symbol addresses to symbol names. 1241 const StringRef FileName = O->getFileName(); 1242 for (const SymbolRef &Symbol : O->symbols()) { 1243 SymbolRef::Type ST = unwrapOrError(Symbol.getType(), FileName); 1244 if (ST == SymbolRef::ST_Function || ST == SymbolRef::ST_Data || 1245 ST == SymbolRef::ST_Other) { 1246 uint64_t Address = cantFail(Symbol.getValue()); 1247 StringRef SymName = unwrapOrError(Symbol.getName(), FileName); 1248 if (!SymName.startswith(".objc")) 1249 (*AddrMap)[Address] = SymName; 1250 } 1251 } 1252 } 1253 1254 // GuessSymbolName is passed the address of what might be a symbol and a 1255 // pointer to the SymbolAddressMap. It returns the name of a symbol 1256 // with that address or nullptr if no symbol is found with that address. 1257 static const char *GuessSymbolName(uint64_t value, SymbolAddressMap *AddrMap) { 1258 const char *SymbolName = nullptr; 1259 // A DenseMap can't lookup up some values. 1260 if (value != 0xffffffffffffffffULL && value != 0xfffffffffffffffeULL) { 1261 StringRef name = AddrMap->lookup(value); 1262 if (!name.empty()) 1263 SymbolName = name.data(); 1264 } 1265 return SymbolName; 1266 } 1267 1268 static void DumpCstringChar(const char c) { 1269 char p[2]; 1270 p[0] = c; 1271 p[1] = '\0'; 1272 outs().write_escaped(p); 1273 } 1274 1275 static void DumpCstringSection(MachOObjectFile *O, const char *sect, 1276 uint32_t sect_size, uint64_t sect_addr, 1277 bool print_addresses) { 1278 for (uint32_t i = 0; i < sect_size; i++) { 1279 if (print_addresses) { 1280 if (O->is64Bit()) 1281 outs() << format("%016" PRIx64, sect_addr + i) << " "; 1282 else 1283 outs() << format("%08" PRIx64, sect_addr + i) << " "; 1284 } 1285 for (; i < sect_size && sect[i] != '\0'; i++) 1286 DumpCstringChar(sect[i]); 1287 if (i < sect_size && sect[i] == '\0') 1288 outs() << "\n"; 1289 } 1290 } 1291 1292 static void DumpLiteral4(uint32_t l, float f) { 1293 outs() << format("0x%08" PRIx32, l); 1294 if ((l & 0x7f800000) != 0x7f800000) 1295 outs() << format(" (%.16e)\n", f); 1296 else { 1297 if (l == 0x7f800000) 1298 outs() << " (+Infinity)\n"; 1299 else if (l == 0xff800000) 1300 outs() << " (-Infinity)\n"; 1301 else if ((l & 0x00400000) == 0x00400000) 1302 outs() << " (non-signaling Not-a-Number)\n"; 1303 else 1304 outs() << " (signaling Not-a-Number)\n"; 1305 } 1306 } 1307 1308 static void DumpLiteral4Section(MachOObjectFile *O, const char *sect, 1309 uint32_t sect_size, uint64_t sect_addr, 1310 bool print_addresses) { 1311 for (uint32_t i = 0; i < sect_size; i += sizeof(float)) { 1312 if (print_addresses) { 1313 if (O->is64Bit()) 1314 outs() << format("%016" PRIx64, sect_addr + i) << " "; 1315 else 1316 outs() << format("%08" PRIx64, sect_addr + i) << " "; 1317 } 1318 float f; 1319 memcpy(&f, sect + i, sizeof(float)); 1320 if (O->isLittleEndian() != sys::IsLittleEndianHost) 1321 sys::swapByteOrder(f); 1322 uint32_t l; 1323 memcpy(&l, sect + i, sizeof(uint32_t)); 1324 if (O->isLittleEndian() != sys::IsLittleEndianHost) 1325 sys::swapByteOrder(l); 1326 DumpLiteral4(l, f); 1327 } 1328 } 1329 1330 static void DumpLiteral8(MachOObjectFile *O, uint32_t l0, uint32_t l1, 1331 double d) { 1332 outs() << format("0x%08" PRIx32, l0) << " " << format("0x%08" PRIx32, l1); 1333 uint32_t Hi, Lo; 1334 Hi = (O->isLittleEndian()) ? l1 : l0; 1335 Lo = (O->isLittleEndian()) ? l0 : l1; 1336 1337 // Hi is the high word, so this is equivalent to if(isfinite(d)) 1338 if ((Hi & 0x7ff00000) != 0x7ff00000) 1339 outs() << format(" (%.16e)\n", d); 1340 else { 1341 if (Hi == 0x7ff00000 && Lo == 0) 1342 outs() << " (+Infinity)\n"; 1343 else if (Hi == 0xfff00000 && Lo == 0) 1344 outs() << " (-Infinity)\n"; 1345 else if ((Hi & 0x00080000) == 0x00080000) 1346 outs() << " (non-signaling Not-a-Number)\n"; 1347 else 1348 outs() << " (signaling Not-a-Number)\n"; 1349 } 1350 } 1351 1352 static void DumpLiteral8Section(MachOObjectFile *O, const char *sect, 1353 uint32_t sect_size, uint64_t sect_addr, 1354 bool print_addresses) { 1355 for (uint32_t i = 0; i < sect_size; i += sizeof(double)) { 1356 if (print_addresses) { 1357 if (O->is64Bit()) 1358 outs() << format("%016" PRIx64, sect_addr + i) << " "; 1359 else 1360 outs() << format("%08" PRIx64, sect_addr + i) << " "; 1361 } 1362 double d; 1363 memcpy(&d, sect + i, sizeof(double)); 1364 if (O->isLittleEndian() != sys::IsLittleEndianHost) 1365 sys::swapByteOrder(d); 1366 uint32_t l0, l1; 1367 memcpy(&l0, sect + i, sizeof(uint32_t)); 1368 memcpy(&l1, sect + i + sizeof(uint32_t), sizeof(uint32_t)); 1369 if (O->isLittleEndian() != sys::IsLittleEndianHost) { 1370 sys::swapByteOrder(l0); 1371 sys::swapByteOrder(l1); 1372 } 1373 DumpLiteral8(O, l0, l1, d); 1374 } 1375 } 1376 1377 static void DumpLiteral16(uint32_t l0, uint32_t l1, uint32_t l2, uint32_t l3) { 1378 outs() << format("0x%08" PRIx32, l0) << " "; 1379 outs() << format("0x%08" PRIx32, l1) << " "; 1380 outs() << format("0x%08" PRIx32, l2) << " "; 1381 outs() << format("0x%08" PRIx32, l3) << "\n"; 1382 } 1383 1384 static void DumpLiteral16Section(MachOObjectFile *O, const char *sect, 1385 uint32_t sect_size, uint64_t sect_addr, 1386 bool print_addresses) { 1387 for (uint32_t i = 0; i < sect_size; i += 16) { 1388 if (print_addresses) { 1389 if (O->is64Bit()) 1390 outs() << format("%016" PRIx64, sect_addr + i) << " "; 1391 else 1392 outs() << format("%08" PRIx64, sect_addr + i) << " "; 1393 } 1394 uint32_t l0, l1, l2, l3; 1395 memcpy(&l0, sect + i, sizeof(uint32_t)); 1396 memcpy(&l1, sect + i + sizeof(uint32_t), sizeof(uint32_t)); 1397 memcpy(&l2, sect + i + 2 * sizeof(uint32_t), sizeof(uint32_t)); 1398 memcpy(&l3, sect + i + 3 * sizeof(uint32_t), sizeof(uint32_t)); 1399 if (O->isLittleEndian() != sys::IsLittleEndianHost) { 1400 sys::swapByteOrder(l0); 1401 sys::swapByteOrder(l1); 1402 sys::swapByteOrder(l2); 1403 sys::swapByteOrder(l3); 1404 } 1405 DumpLiteral16(l0, l1, l2, l3); 1406 } 1407 } 1408 1409 static void DumpLiteralPointerSection(MachOObjectFile *O, 1410 const SectionRef &Section, 1411 const char *sect, uint32_t sect_size, 1412 uint64_t sect_addr, 1413 bool print_addresses) { 1414 // Collect the literal sections in this Mach-O file. 1415 std::vector<SectionRef> LiteralSections; 1416 for (const SectionRef &Section : O->sections()) { 1417 DataRefImpl Ref = Section.getRawDataRefImpl(); 1418 uint32_t section_type; 1419 if (O->is64Bit()) { 1420 const MachO::section_64 Sec = O->getSection64(Ref); 1421 section_type = Sec.flags & MachO::SECTION_TYPE; 1422 } else { 1423 const MachO::section Sec = O->getSection(Ref); 1424 section_type = Sec.flags & MachO::SECTION_TYPE; 1425 } 1426 if (section_type == MachO::S_CSTRING_LITERALS || 1427 section_type == MachO::S_4BYTE_LITERALS || 1428 section_type == MachO::S_8BYTE_LITERALS || 1429 section_type == MachO::S_16BYTE_LITERALS) 1430 LiteralSections.push_back(Section); 1431 } 1432 1433 // Set the size of the literal pointer. 1434 uint32_t lp_size = O->is64Bit() ? 8 : 4; 1435 1436 // Collect the external relocation symbols for the literal pointers. 1437 std::vector<std::pair<uint64_t, SymbolRef>> Relocs; 1438 for (const RelocationRef &Reloc : Section.relocations()) { 1439 DataRefImpl Rel; 1440 MachO::any_relocation_info RE; 1441 bool isExtern = false; 1442 Rel = Reloc.getRawDataRefImpl(); 1443 RE = O->getRelocation(Rel); 1444 isExtern = O->getPlainRelocationExternal(RE); 1445 if (isExtern) { 1446 uint64_t RelocOffset = Reloc.getOffset(); 1447 symbol_iterator RelocSym = Reloc.getSymbol(); 1448 Relocs.push_back(std::make_pair(RelocOffset, *RelocSym)); 1449 } 1450 } 1451 array_pod_sort(Relocs.begin(), Relocs.end()); 1452 1453 // Dump each literal pointer. 1454 for (uint32_t i = 0; i < sect_size; i += lp_size) { 1455 if (print_addresses) { 1456 if (O->is64Bit()) 1457 outs() << format("%016" PRIx64, sect_addr + i) << " "; 1458 else 1459 outs() << format("%08" PRIx64, sect_addr + i) << " "; 1460 } 1461 uint64_t lp; 1462 if (O->is64Bit()) { 1463 memcpy(&lp, sect + i, sizeof(uint64_t)); 1464 if (O->isLittleEndian() != sys::IsLittleEndianHost) 1465 sys::swapByteOrder(lp); 1466 } else { 1467 uint32_t li; 1468 memcpy(&li, sect + i, sizeof(uint32_t)); 1469 if (O->isLittleEndian() != sys::IsLittleEndianHost) 1470 sys::swapByteOrder(li); 1471 lp = li; 1472 } 1473 1474 // First look for an external relocation entry for this literal pointer. 1475 auto Reloc = find_if(Relocs, [&](const std::pair<uint64_t, SymbolRef> &P) { 1476 return P.first == i; 1477 }); 1478 if (Reloc != Relocs.end()) { 1479 symbol_iterator RelocSym = Reloc->second; 1480 StringRef SymName = unwrapOrError(RelocSym->getName(), O->getFileName()); 1481 outs() << "external relocation entry for symbol:" << SymName << "\n"; 1482 continue; 1483 } 1484 1485 // For local references see what the section the literal pointer points to. 1486 auto Sect = find_if(LiteralSections, [&](const SectionRef &R) { 1487 return lp >= R.getAddress() && lp < R.getAddress() + R.getSize(); 1488 }); 1489 if (Sect == LiteralSections.end()) { 1490 outs() << format("0x%" PRIx64, lp) << " (not in a literal section)\n"; 1491 continue; 1492 } 1493 1494 uint64_t SectAddress = Sect->getAddress(); 1495 uint64_t SectSize = Sect->getSize(); 1496 1497 StringRef SectName; 1498 Expected<StringRef> SectNameOrErr = Sect->getName(); 1499 if (SectNameOrErr) 1500 SectName = *SectNameOrErr; 1501 else 1502 consumeError(SectNameOrErr.takeError()); 1503 1504 DataRefImpl Ref = Sect->getRawDataRefImpl(); 1505 StringRef SegmentName = O->getSectionFinalSegmentName(Ref); 1506 outs() << SegmentName << ":" << SectName << ":"; 1507 1508 uint32_t section_type; 1509 if (O->is64Bit()) { 1510 const MachO::section_64 Sec = O->getSection64(Ref); 1511 section_type = Sec.flags & MachO::SECTION_TYPE; 1512 } else { 1513 const MachO::section Sec = O->getSection(Ref); 1514 section_type = Sec.flags & MachO::SECTION_TYPE; 1515 } 1516 1517 StringRef BytesStr = unwrapOrError(Sect->getContents(), O->getFileName()); 1518 1519 const char *Contents = reinterpret_cast<const char *>(BytesStr.data()); 1520 1521 switch (section_type) { 1522 case MachO::S_CSTRING_LITERALS: 1523 for (uint64_t i = lp - SectAddress; i < SectSize && Contents[i] != '\0'; 1524 i++) { 1525 DumpCstringChar(Contents[i]); 1526 } 1527 outs() << "\n"; 1528 break; 1529 case MachO::S_4BYTE_LITERALS: 1530 float f; 1531 memcpy(&f, Contents + (lp - SectAddress), sizeof(float)); 1532 uint32_t l; 1533 memcpy(&l, Contents + (lp - SectAddress), sizeof(uint32_t)); 1534 if (O->isLittleEndian() != sys::IsLittleEndianHost) { 1535 sys::swapByteOrder(f); 1536 sys::swapByteOrder(l); 1537 } 1538 DumpLiteral4(l, f); 1539 break; 1540 case MachO::S_8BYTE_LITERALS: { 1541 double d; 1542 memcpy(&d, Contents + (lp - SectAddress), sizeof(double)); 1543 uint32_t l0, l1; 1544 memcpy(&l0, Contents + (lp - SectAddress), sizeof(uint32_t)); 1545 memcpy(&l1, Contents + (lp - SectAddress) + sizeof(uint32_t), 1546 sizeof(uint32_t)); 1547 if (O->isLittleEndian() != sys::IsLittleEndianHost) { 1548 sys::swapByteOrder(f); 1549 sys::swapByteOrder(l0); 1550 sys::swapByteOrder(l1); 1551 } 1552 DumpLiteral8(O, l0, l1, d); 1553 break; 1554 } 1555 case MachO::S_16BYTE_LITERALS: { 1556 uint32_t l0, l1, l2, l3; 1557 memcpy(&l0, Contents + (lp - SectAddress), sizeof(uint32_t)); 1558 memcpy(&l1, Contents + (lp - SectAddress) + sizeof(uint32_t), 1559 sizeof(uint32_t)); 1560 memcpy(&l2, Contents + (lp - SectAddress) + 2 * sizeof(uint32_t), 1561 sizeof(uint32_t)); 1562 memcpy(&l3, Contents + (lp - SectAddress) + 3 * sizeof(uint32_t), 1563 sizeof(uint32_t)); 1564 if (O->isLittleEndian() != sys::IsLittleEndianHost) { 1565 sys::swapByteOrder(l0); 1566 sys::swapByteOrder(l1); 1567 sys::swapByteOrder(l2); 1568 sys::swapByteOrder(l3); 1569 } 1570 DumpLiteral16(l0, l1, l2, l3); 1571 break; 1572 } 1573 } 1574 } 1575 } 1576 1577 static void DumpInitTermPointerSection(MachOObjectFile *O, 1578 const SectionRef &Section, 1579 const char *sect, 1580 uint32_t sect_size, uint64_t sect_addr, 1581 SymbolAddressMap *AddrMap, 1582 bool verbose) { 1583 uint32_t stride; 1584 stride = (O->is64Bit()) ? sizeof(uint64_t) : sizeof(uint32_t); 1585 1586 // Collect the external relocation symbols for the pointers. 1587 std::vector<std::pair<uint64_t, SymbolRef>> Relocs; 1588 for (const RelocationRef &Reloc : Section.relocations()) { 1589 DataRefImpl Rel; 1590 MachO::any_relocation_info RE; 1591 bool isExtern = false; 1592 Rel = Reloc.getRawDataRefImpl(); 1593 RE = O->getRelocation(Rel); 1594 isExtern = O->getPlainRelocationExternal(RE); 1595 if (isExtern) { 1596 uint64_t RelocOffset = Reloc.getOffset(); 1597 symbol_iterator RelocSym = Reloc.getSymbol(); 1598 Relocs.push_back(std::make_pair(RelocOffset, *RelocSym)); 1599 } 1600 } 1601 array_pod_sort(Relocs.begin(), Relocs.end()); 1602 1603 for (uint32_t i = 0; i < sect_size; i += stride) { 1604 const char *SymbolName = nullptr; 1605 uint64_t p; 1606 if (O->is64Bit()) { 1607 outs() << format("0x%016" PRIx64, sect_addr + i * stride) << " "; 1608 uint64_t pointer_value; 1609 memcpy(&pointer_value, sect + i, stride); 1610 if (O->isLittleEndian() != sys::IsLittleEndianHost) 1611 sys::swapByteOrder(pointer_value); 1612 outs() << format("0x%016" PRIx64, pointer_value); 1613 p = pointer_value; 1614 } else { 1615 outs() << format("0x%08" PRIx64, sect_addr + i * stride) << " "; 1616 uint32_t pointer_value; 1617 memcpy(&pointer_value, sect + i, stride); 1618 if (O->isLittleEndian() != sys::IsLittleEndianHost) 1619 sys::swapByteOrder(pointer_value); 1620 outs() << format("0x%08" PRIx32, pointer_value); 1621 p = pointer_value; 1622 } 1623 if (verbose) { 1624 // First look for an external relocation entry for this pointer. 1625 auto Reloc = find_if(Relocs, [&](const std::pair<uint64_t, SymbolRef> &P) { 1626 return P.first == i; 1627 }); 1628 if (Reloc != Relocs.end()) { 1629 symbol_iterator RelocSym = Reloc->second; 1630 outs() << " " << unwrapOrError(RelocSym->getName(), O->getFileName()); 1631 } else { 1632 SymbolName = GuessSymbolName(p, AddrMap); 1633 if (SymbolName) 1634 outs() << " " << SymbolName; 1635 } 1636 } 1637 outs() << "\n"; 1638 } 1639 } 1640 1641 static void DumpRawSectionContents(MachOObjectFile *O, const char *sect, 1642 uint32_t size, uint64_t addr) { 1643 uint32_t cputype = O->getHeader().cputype; 1644 if (cputype == MachO::CPU_TYPE_I386 || cputype == MachO::CPU_TYPE_X86_64) { 1645 uint32_t j; 1646 for (uint32_t i = 0; i < size; i += j, addr += j) { 1647 if (O->is64Bit()) 1648 outs() << format("%016" PRIx64, addr) << "\t"; 1649 else 1650 outs() << format("%08" PRIx64, addr) << "\t"; 1651 for (j = 0; j < 16 && i + j < size; j++) { 1652 uint8_t byte_word = *(sect + i + j); 1653 outs() << format("%02" PRIx32, (uint32_t)byte_word) << " "; 1654 } 1655 outs() << "\n"; 1656 } 1657 } else { 1658 uint32_t j; 1659 for (uint32_t i = 0; i < size; i += j, addr += j) { 1660 if (O->is64Bit()) 1661 outs() << format("%016" PRIx64, addr) << "\t"; 1662 else 1663 outs() << format("%08" PRIx64, addr) << "\t"; 1664 for (j = 0; j < 4 * sizeof(int32_t) && i + j < size; 1665 j += sizeof(int32_t)) { 1666 if (i + j + sizeof(int32_t) <= size) { 1667 uint32_t long_word; 1668 memcpy(&long_word, sect + i + j, sizeof(int32_t)); 1669 if (O->isLittleEndian() != sys::IsLittleEndianHost) 1670 sys::swapByteOrder(long_word); 1671 outs() << format("%08" PRIx32, long_word) << " "; 1672 } else { 1673 for (uint32_t k = 0; i + j + k < size; k++) { 1674 uint8_t byte_word = *(sect + i + j + k); 1675 outs() << format("%02" PRIx32, (uint32_t)byte_word) << " "; 1676 } 1677 } 1678 } 1679 outs() << "\n"; 1680 } 1681 } 1682 } 1683 1684 static void DisassembleMachO(StringRef Filename, MachOObjectFile *MachOOF, 1685 StringRef DisSegName, StringRef DisSectName); 1686 static void DumpProtocolSection(MachOObjectFile *O, const char *sect, 1687 uint32_t size, uint32_t addr); 1688 #ifdef HAVE_LIBXAR 1689 static void DumpBitcodeSection(MachOObjectFile *O, const char *sect, 1690 uint32_t size, bool verbose, 1691 bool PrintXarHeader, bool PrintXarFileHeaders, 1692 std::string XarMemberName); 1693 #endif // defined(HAVE_LIBXAR) 1694 1695 static void DumpSectionContents(StringRef Filename, MachOObjectFile *O, 1696 bool verbose) { 1697 SymbolAddressMap AddrMap; 1698 if (verbose) 1699 CreateSymbolAddressMap(O, &AddrMap); 1700 1701 for (unsigned i = 0; i < FilterSections.size(); ++i) { 1702 StringRef DumpSection = FilterSections[i]; 1703 std::pair<StringRef, StringRef> DumpSegSectName; 1704 DumpSegSectName = DumpSection.split(','); 1705 StringRef DumpSegName, DumpSectName; 1706 if (!DumpSegSectName.second.empty()) { 1707 DumpSegName = DumpSegSectName.first; 1708 DumpSectName = DumpSegSectName.second; 1709 } else { 1710 DumpSegName = ""; 1711 DumpSectName = DumpSegSectName.first; 1712 } 1713 for (const SectionRef &Section : O->sections()) { 1714 StringRef SectName; 1715 Expected<StringRef> SecNameOrErr = Section.getName(); 1716 if (SecNameOrErr) 1717 SectName = *SecNameOrErr; 1718 else 1719 consumeError(SecNameOrErr.takeError()); 1720 1721 if (!DumpSection.empty()) 1722 FoundSectionSet.insert(DumpSection); 1723 1724 DataRefImpl Ref = Section.getRawDataRefImpl(); 1725 StringRef SegName = O->getSectionFinalSegmentName(Ref); 1726 if ((DumpSegName.empty() || SegName == DumpSegName) && 1727 (SectName == DumpSectName)) { 1728 1729 uint32_t section_flags; 1730 if (O->is64Bit()) { 1731 const MachO::section_64 Sec = O->getSection64(Ref); 1732 section_flags = Sec.flags; 1733 1734 } else { 1735 const MachO::section Sec = O->getSection(Ref); 1736 section_flags = Sec.flags; 1737 } 1738 uint32_t section_type = section_flags & MachO::SECTION_TYPE; 1739 1740 StringRef BytesStr = 1741 unwrapOrError(Section.getContents(), O->getFileName()); 1742 const char *sect = reinterpret_cast<const char *>(BytesStr.data()); 1743 uint32_t sect_size = BytesStr.size(); 1744 uint64_t sect_addr = Section.getAddress(); 1745 1746 if (!NoLeadingHeaders) 1747 outs() << "Contents of (" << SegName << "," << SectName 1748 << ") section\n"; 1749 1750 if (verbose) { 1751 if ((section_flags & MachO::S_ATTR_PURE_INSTRUCTIONS) || 1752 (section_flags & MachO::S_ATTR_SOME_INSTRUCTIONS)) { 1753 DisassembleMachO(Filename, O, SegName, SectName); 1754 continue; 1755 } 1756 if (SegName == "__TEXT" && SectName == "__info_plist") { 1757 outs() << sect; 1758 continue; 1759 } 1760 if (SegName == "__OBJC" && SectName == "__protocol") { 1761 DumpProtocolSection(O, sect, sect_size, sect_addr); 1762 continue; 1763 } 1764 #ifdef HAVE_LIBXAR 1765 if (SegName == "__LLVM" && SectName == "__bundle") { 1766 DumpBitcodeSection(O, sect, sect_size, verbose, !NoSymbolicOperands, 1767 ArchiveHeaders, ""); 1768 continue; 1769 } 1770 #endif // defined(HAVE_LIBXAR) 1771 switch (section_type) { 1772 case MachO::S_REGULAR: 1773 DumpRawSectionContents(O, sect, sect_size, sect_addr); 1774 break; 1775 case MachO::S_ZEROFILL: 1776 outs() << "zerofill section and has no contents in the file\n"; 1777 break; 1778 case MachO::S_CSTRING_LITERALS: 1779 DumpCstringSection(O, sect, sect_size, sect_addr, !NoLeadingAddr); 1780 break; 1781 case MachO::S_4BYTE_LITERALS: 1782 DumpLiteral4Section(O, sect, sect_size, sect_addr, !NoLeadingAddr); 1783 break; 1784 case MachO::S_8BYTE_LITERALS: 1785 DumpLiteral8Section(O, sect, sect_size, sect_addr, !NoLeadingAddr); 1786 break; 1787 case MachO::S_16BYTE_LITERALS: 1788 DumpLiteral16Section(O, sect, sect_size, sect_addr, !NoLeadingAddr); 1789 break; 1790 case MachO::S_LITERAL_POINTERS: 1791 DumpLiteralPointerSection(O, Section, sect, sect_size, sect_addr, 1792 !NoLeadingAddr); 1793 break; 1794 case MachO::S_MOD_INIT_FUNC_POINTERS: 1795 case MachO::S_MOD_TERM_FUNC_POINTERS: 1796 DumpInitTermPointerSection(O, Section, sect, sect_size, sect_addr, 1797 &AddrMap, verbose); 1798 break; 1799 default: 1800 outs() << "Unknown section type (" 1801 << format("0x%08" PRIx32, section_type) << ")\n"; 1802 DumpRawSectionContents(O, sect, sect_size, sect_addr); 1803 break; 1804 } 1805 } else { 1806 if (section_type == MachO::S_ZEROFILL) 1807 outs() << "zerofill section and has no contents in the file\n"; 1808 else 1809 DumpRawSectionContents(O, sect, sect_size, sect_addr); 1810 } 1811 } 1812 } 1813 } 1814 } 1815 1816 static void DumpInfoPlistSectionContents(StringRef Filename, 1817 MachOObjectFile *O) { 1818 for (const SectionRef &Section : O->sections()) { 1819 StringRef SectName; 1820 Expected<StringRef> SecNameOrErr = Section.getName(); 1821 if (SecNameOrErr) 1822 SectName = *SecNameOrErr; 1823 else 1824 consumeError(SecNameOrErr.takeError()); 1825 1826 DataRefImpl Ref = Section.getRawDataRefImpl(); 1827 StringRef SegName = O->getSectionFinalSegmentName(Ref); 1828 if (SegName == "__TEXT" && SectName == "__info_plist") { 1829 if (!NoLeadingHeaders) 1830 outs() << "Contents of (" << SegName << "," << SectName << ") section\n"; 1831 StringRef BytesStr = 1832 unwrapOrError(Section.getContents(), O->getFileName()); 1833 const char *sect = reinterpret_cast<const char *>(BytesStr.data()); 1834 outs() << format("%.*s", BytesStr.size(), sect) << "\n"; 1835 return; 1836 } 1837 } 1838 } 1839 1840 // checkMachOAndArchFlags() checks to see if the ObjectFile is a Mach-O file 1841 // and if it is and there is a list of architecture flags is specified then 1842 // check to make sure this Mach-O file is one of those architectures or all 1843 // architectures were specified. If not then an error is generated and this 1844 // routine returns false. Else it returns true. 1845 static bool checkMachOAndArchFlags(ObjectFile *O, StringRef Filename) { 1846 auto *MachO = dyn_cast<MachOObjectFile>(O); 1847 1848 if (!MachO || ArchAll || ArchFlags.empty()) 1849 return true; 1850 1851 MachO::mach_header H; 1852 MachO::mach_header_64 H_64; 1853 Triple T; 1854 const char *McpuDefault, *ArchFlag; 1855 if (MachO->is64Bit()) { 1856 H_64 = MachO->MachOObjectFile::getHeader64(); 1857 T = MachOObjectFile::getArchTriple(H_64.cputype, H_64.cpusubtype, 1858 &McpuDefault, &ArchFlag); 1859 } else { 1860 H = MachO->MachOObjectFile::getHeader(); 1861 T = MachOObjectFile::getArchTriple(H.cputype, H.cpusubtype, 1862 &McpuDefault, &ArchFlag); 1863 } 1864 const std::string ArchFlagName(ArchFlag); 1865 if (!llvm::is_contained(ArchFlags, ArchFlagName)) { 1866 WithColor::error(errs(), "llvm-objdump") 1867 << Filename << ": no architecture specified.\n"; 1868 return false; 1869 } 1870 return true; 1871 } 1872 1873 static void printObjcMetaData(MachOObjectFile *O, bool verbose); 1874 1875 // ProcessMachO() is passed a single opened Mach-O file, which may be an 1876 // archive member and or in a slice of a universal file. It prints the 1877 // the file name and header info and then processes it according to the 1878 // command line options. 1879 static void ProcessMachO(StringRef Name, MachOObjectFile *MachOOF, 1880 StringRef ArchiveMemberName = StringRef(), 1881 StringRef ArchitectureName = StringRef()) { 1882 // If we are doing some processing here on the Mach-O file print the header 1883 // info. And don't print it otherwise like in the case of printing the 1884 // UniversalHeaders or ArchiveHeaders. 1885 if (Disassemble || Relocations || PrivateHeaders || ExportsTrie || Rebase || 1886 Bind || SymbolTable || LazyBind || WeakBind || IndirectSymbols || 1887 DataInCode || FunctionStarts || LinkOptHints || DylibsUsed || DylibId || 1888 ObjcMetaData || (!FilterSections.empty())) { 1889 if (!NoLeadingHeaders) { 1890 outs() << Name; 1891 if (!ArchiveMemberName.empty()) 1892 outs() << '(' << ArchiveMemberName << ')'; 1893 if (!ArchitectureName.empty()) 1894 outs() << " (architecture " << ArchitectureName << ")"; 1895 outs() << ":\n"; 1896 } 1897 } 1898 // To use the report_error() form with an ArchiveName and FileName set 1899 // these up based on what is passed for Name and ArchiveMemberName. 1900 StringRef ArchiveName; 1901 StringRef FileName; 1902 if (!ArchiveMemberName.empty()) { 1903 ArchiveName = Name; 1904 FileName = ArchiveMemberName; 1905 } else { 1906 ArchiveName = StringRef(); 1907 FileName = Name; 1908 } 1909 1910 // If we need the symbol table to do the operation then check it here to 1911 // produce a good error message as to where the Mach-O file comes from in 1912 // the error message. 1913 if (Disassemble || IndirectSymbols || !FilterSections.empty() || UnwindInfo) 1914 if (Error Err = MachOOF->checkSymbolTable()) 1915 reportError(std::move(Err), FileName, ArchiveName, ArchitectureName); 1916 1917 if (DisassembleAll) { 1918 for (const SectionRef &Section : MachOOF->sections()) { 1919 StringRef SectName; 1920 if (Expected<StringRef> NameOrErr = Section.getName()) 1921 SectName = *NameOrErr; 1922 else 1923 consumeError(NameOrErr.takeError()); 1924 1925 if (SectName.equals("__text")) { 1926 DataRefImpl Ref = Section.getRawDataRefImpl(); 1927 StringRef SegName = MachOOF->getSectionFinalSegmentName(Ref); 1928 DisassembleMachO(FileName, MachOOF, SegName, SectName); 1929 } 1930 } 1931 } 1932 else if (Disassemble) { 1933 if (MachOOF->getHeader().filetype == MachO::MH_KEXT_BUNDLE && 1934 MachOOF->getHeader().cputype == MachO::CPU_TYPE_ARM64) 1935 DisassembleMachO(FileName, MachOOF, "__TEXT_EXEC", "__text"); 1936 else 1937 DisassembleMachO(FileName, MachOOF, "__TEXT", "__text"); 1938 } 1939 if (IndirectSymbols) 1940 PrintIndirectSymbols(MachOOF, !NonVerbose); 1941 if (DataInCode) 1942 PrintDataInCodeTable(MachOOF, !NonVerbose); 1943 if (FunctionStarts) 1944 PrintFunctionStarts(MachOOF); 1945 if (LinkOptHints) 1946 PrintLinkOptHints(MachOOF); 1947 if (Relocations) 1948 PrintRelocations(MachOOF, !NonVerbose); 1949 if (SectionHeaders) 1950 printSectionHeaders(MachOOF); 1951 if (SectionContents) 1952 printSectionContents(MachOOF); 1953 if (!FilterSections.empty()) 1954 DumpSectionContents(FileName, MachOOF, !NonVerbose); 1955 if (InfoPlist) 1956 DumpInfoPlistSectionContents(FileName, MachOOF); 1957 if (DylibsUsed) 1958 PrintDylibs(MachOOF, false); 1959 if (DylibId) 1960 PrintDylibs(MachOOF, true); 1961 if (SymbolTable) 1962 printSymbolTable(MachOOF, ArchiveName, ArchitectureName); 1963 if (UnwindInfo) 1964 printMachOUnwindInfo(MachOOF); 1965 if (PrivateHeaders) { 1966 printMachOFileHeader(MachOOF); 1967 printMachOLoadCommands(MachOOF); 1968 } 1969 if (FirstPrivateHeader) 1970 printMachOFileHeader(MachOOF); 1971 if (ObjcMetaData) 1972 printObjcMetaData(MachOOF, !NonVerbose); 1973 if (ExportsTrie) 1974 printExportsTrie(MachOOF); 1975 if (Rebase) 1976 printRebaseTable(MachOOF); 1977 if (Bind) 1978 printBindTable(MachOOF); 1979 if (LazyBind) 1980 printLazyBindTable(MachOOF); 1981 if (WeakBind) 1982 printWeakBindTable(MachOOF); 1983 1984 if (DwarfDumpType != DIDT_Null) { 1985 std::unique_ptr<DIContext> DICtx = DWARFContext::create(*MachOOF); 1986 // Dump the complete DWARF structure. 1987 DIDumpOptions DumpOpts; 1988 DumpOpts.DumpType = DwarfDumpType; 1989 DICtx->dump(outs(), DumpOpts); 1990 } 1991 } 1992 1993 // printUnknownCPUType() helps print_fat_headers for unknown CPU's. 1994 static void printUnknownCPUType(uint32_t cputype, uint32_t cpusubtype) { 1995 outs() << " cputype (" << cputype << ")\n"; 1996 outs() << " cpusubtype (" << cpusubtype << ")\n"; 1997 } 1998 1999 // printCPUType() helps print_fat_headers by printing the cputype and 2000 // pusubtype (symbolically for the one's it knows about). 2001 static void printCPUType(uint32_t cputype, uint32_t cpusubtype) { 2002 switch (cputype) { 2003 case MachO::CPU_TYPE_I386: 2004 switch (cpusubtype) { 2005 case MachO::CPU_SUBTYPE_I386_ALL: 2006 outs() << " cputype CPU_TYPE_I386\n"; 2007 outs() << " cpusubtype CPU_SUBTYPE_I386_ALL\n"; 2008 break; 2009 default: 2010 printUnknownCPUType(cputype, cpusubtype); 2011 break; 2012 } 2013 break; 2014 case MachO::CPU_TYPE_X86_64: 2015 switch (cpusubtype) { 2016 case MachO::CPU_SUBTYPE_X86_64_ALL: 2017 outs() << " cputype CPU_TYPE_X86_64\n"; 2018 outs() << " cpusubtype CPU_SUBTYPE_X86_64_ALL\n"; 2019 break; 2020 case MachO::CPU_SUBTYPE_X86_64_H: 2021 outs() << " cputype CPU_TYPE_X86_64\n"; 2022 outs() << " cpusubtype CPU_SUBTYPE_X86_64_H\n"; 2023 break; 2024 default: 2025 printUnknownCPUType(cputype, cpusubtype); 2026 break; 2027 } 2028 break; 2029 case MachO::CPU_TYPE_ARM: 2030 switch (cpusubtype) { 2031 case MachO::CPU_SUBTYPE_ARM_ALL: 2032 outs() << " cputype CPU_TYPE_ARM\n"; 2033 outs() << " cpusubtype CPU_SUBTYPE_ARM_ALL\n"; 2034 break; 2035 case MachO::CPU_SUBTYPE_ARM_V4T: 2036 outs() << " cputype CPU_TYPE_ARM\n"; 2037 outs() << " cpusubtype CPU_SUBTYPE_ARM_V4T\n"; 2038 break; 2039 case MachO::CPU_SUBTYPE_ARM_V5TEJ: 2040 outs() << " cputype CPU_TYPE_ARM\n"; 2041 outs() << " cpusubtype CPU_SUBTYPE_ARM_V5TEJ\n"; 2042 break; 2043 case MachO::CPU_SUBTYPE_ARM_XSCALE: 2044 outs() << " cputype CPU_TYPE_ARM\n"; 2045 outs() << " cpusubtype CPU_SUBTYPE_ARM_XSCALE\n"; 2046 break; 2047 case MachO::CPU_SUBTYPE_ARM_V6: 2048 outs() << " cputype CPU_TYPE_ARM\n"; 2049 outs() << " cpusubtype CPU_SUBTYPE_ARM_V6\n"; 2050 break; 2051 case MachO::CPU_SUBTYPE_ARM_V6M: 2052 outs() << " cputype CPU_TYPE_ARM\n"; 2053 outs() << " cpusubtype CPU_SUBTYPE_ARM_V6M\n"; 2054 break; 2055 case MachO::CPU_SUBTYPE_ARM_V7: 2056 outs() << " cputype CPU_TYPE_ARM\n"; 2057 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7\n"; 2058 break; 2059 case MachO::CPU_SUBTYPE_ARM_V7EM: 2060 outs() << " cputype CPU_TYPE_ARM\n"; 2061 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7EM\n"; 2062 break; 2063 case MachO::CPU_SUBTYPE_ARM_V7K: 2064 outs() << " cputype CPU_TYPE_ARM\n"; 2065 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7K\n"; 2066 break; 2067 case MachO::CPU_SUBTYPE_ARM_V7M: 2068 outs() << " cputype CPU_TYPE_ARM\n"; 2069 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7M\n"; 2070 break; 2071 case MachO::CPU_SUBTYPE_ARM_V7S: 2072 outs() << " cputype CPU_TYPE_ARM\n"; 2073 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7S\n"; 2074 break; 2075 default: 2076 printUnknownCPUType(cputype, cpusubtype); 2077 break; 2078 } 2079 break; 2080 case MachO::CPU_TYPE_ARM64: 2081 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) { 2082 case MachO::CPU_SUBTYPE_ARM64_ALL: 2083 outs() << " cputype CPU_TYPE_ARM64\n"; 2084 outs() << " cpusubtype CPU_SUBTYPE_ARM64_ALL\n"; 2085 break; 2086 case MachO::CPU_SUBTYPE_ARM64_V8: 2087 outs() << " cputype CPU_TYPE_ARM64\n"; 2088 outs() << " cpusubtype CPU_SUBTYPE_ARM64_V8\n"; 2089 break; 2090 case MachO::CPU_SUBTYPE_ARM64E: 2091 outs() << " cputype CPU_TYPE_ARM64\n"; 2092 outs() << " cpusubtype CPU_SUBTYPE_ARM64E\n"; 2093 break; 2094 default: 2095 printUnknownCPUType(cputype, cpusubtype); 2096 break; 2097 } 2098 break; 2099 case MachO::CPU_TYPE_ARM64_32: 2100 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) { 2101 case MachO::CPU_SUBTYPE_ARM64_32_V8: 2102 outs() << " cputype CPU_TYPE_ARM64_32\n"; 2103 outs() << " cpusubtype CPU_SUBTYPE_ARM64_32_V8\n"; 2104 break; 2105 default: 2106 printUnknownCPUType(cputype, cpusubtype); 2107 break; 2108 } 2109 break; 2110 default: 2111 printUnknownCPUType(cputype, cpusubtype); 2112 break; 2113 } 2114 } 2115 2116 static void printMachOUniversalHeaders(const object::MachOUniversalBinary *UB, 2117 bool verbose) { 2118 outs() << "Fat headers\n"; 2119 if (verbose) { 2120 if (UB->getMagic() == MachO::FAT_MAGIC) 2121 outs() << "fat_magic FAT_MAGIC\n"; 2122 else // UB->getMagic() == MachO::FAT_MAGIC_64 2123 outs() << "fat_magic FAT_MAGIC_64\n"; 2124 } else 2125 outs() << "fat_magic " << format("0x%" PRIx32, MachO::FAT_MAGIC) << "\n"; 2126 2127 uint32_t nfat_arch = UB->getNumberOfObjects(); 2128 StringRef Buf = UB->getData(); 2129 uint64_t size = Buf.size(); 2130 uint64_t big_size = sizeof(struct MachO::fat_header) + 2131 nfat_arch * sizeof(struct MachO::fat_arch); 2132 outs() << "nfat_arch " << UB->getNumberOfObjects(); 2133 if (nfat_arch == 0) 2134 outs() << " (malformed, contains zero architecture types)\n"; 2135 else if (big_size > size) 2136 outs() << " (malformed, architectures past end of file)\n"; 2137 else 2138 outs() << "\n"; 2139 2140 for (uint32_t i = 0; i < nfat_arch; ++i) { 2141 MachOUniversalBinary::ObjectForArch OFA(UB, i); 2142 uint32_t cputype = OFA.getCPUType(); 2143 uint32_t cpusubtype = OFA.getCPUSubType(); 2144 outs() << "architecture "; 2145 for (uint32_t j = 0; i != 0 && j <= i - 1; j++) { 2146 MachOUniversalBinary::ObjectForArch other_OFA(UB, j); 2147 uint32_t other_cputype = other_OFA.getCPUType(); 2148 uint32_t other_cpusubtype = other_OFA.getCPUSubType(); 2149 if (cputype != 0 && cpusubtype != 0 && cputype == other_cputype && 2150 (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) == 2151 (other_cpusubtype & ~MachO::CPU_SUBTYPE_MASK)) { 2152 outs() << "(illegal duplicate architecture) "; 2153 break; 2154 } 2155 } 2156 if (verbose) { 2157 outs() << OFA.getArchFlagName() << "\n"; 2158 printCPUType(cputype, cpusubtype & ~MachO::CPU_SUBTYPE_MASK); 2159 } else { 2160 outs() << i << "\n"; 2161 outs() << " cputype " << cputype << "\n"; 2162 outs() << " cpusubtype " << (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) 2163 << "\n"; 2164 } 2165 if (verbose && 2166 (cpusubtype & MachO::CPU_SUBTYPE_MASK) == MachO::CPU_SUBTYPE_LIB64) 2167 outs() << " capabilities CPU_SUBTYPE_LIB64\n"; 2168 else 2169 outs() << " capabilities " 2170 << format("0x%" PRIx32, 2171 (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24) << "\n"; 2172 outs() << " offset " << OFA.getOffset(); 2173 if (OFA.getOffset() > size) 2174 outs() << " (past end of file)"; 2175 if (OFA.getOffset() % (1ull << OFA.getAlign()) != 0) 2176 outs() << " (not aligned on it's alignment (2^" << OFA.getAlign() << ")"; 2177 outs() << "\n"; 2178 outs() << " size " << OFA.getSize(); 2179 big_size = OFA.getOffset() + OFA.getSize(); 2180 if (big_size > size) 2181 outs() << " (past end of file)"; 2182 outs() << "\n"; 2183 outs() << " align 2^" << OFA.getAlign() << " (" << (1 << OFA.getAlign()) 2184 << ")\n"; 2185 } 2186 } 2187 2188 static void printArchiveChild(StringRef Filename, const Archive::Child &C, 2189 size_t ChildIndex, bool verbose, 2190 bool print_offset, 2191 StringRef ArchitectureName = StringRef()) { 2192 if (print_offset) 2193 outs() << C.getChildOffset() << "\t"; 2194 sys::fs::perms Mode = 2195 unwrapOrError(C.getAccessMode(), getFileNameForError(C, ChildIndex), 2196 Filename, ArchitectureName); 2197 if (verbose) { 2198 // FIXME: this first dash, "-", is for (Mode & S_IFMT) == S_IFREG. 2199 // But there is nothing in sys::fs::perms for S_IFMT or S_IFREG. 2200 outs() << "-"; 2201 outs() << ((Mode & sys::fs::owner_read) ? "r" : "-"); 2202 outs() << ((Mode & sys::fs::owner_write) ? "w" : "-"); 2203 outs() << ((Mode & sys::fs::owner_exe) ? "x" : "-"); 2204 outs() << ((Mode & sys::fs::group_read) ? "r" : "-"); 2205 outs() << ((Mode & sys::fs::group_write) ? "w" : "-"); 2206 outs() << ((Mode & sys::fs::group_exe) ? "x" : "-"); 2207 outs() << ((Mode & sys::fs::others_read) ? "r" : "-"); 2208 outs() << ((Mode & sys::fs::others_write) ? "w" : "-"); 2209 outs() << ((Mode & sys::fs::others_exe) ? "x" : "-"); 2210 } else { 2211 outs() << format("0%o ", Mode); 2212 } 2213 2214 outs() << format("%3d/%-3d %5" PRId64 " ", 2215 unwrapOrError(C.getUID(), getFileNameForError(C, ChildIndex), 2216 Filename, ArchitectureName), 2217 unwrapOrError(C.getGID(), getFileNameForError(C, ChildIndex), 2218 Filename, ArchitectureName), 2219 unwrapOrError(C.getRawSize(), 2220 getFileNameForError(C, ChildIndex), Filename, 2221 ArchitectureName)); 2222 2223 StringRef RawLastModified = C.getRawLastModified(); 2224 if (verbose) { 2225 unsigned Seconds; 2226 if (RawLastModified.getAsInteger(10, Seconds)) 2227 outs() << "(date: \"" << RawLastModified 2228 << "\" contains non-decimal chars) "; 2229 else { 2230 // Since cime(3) returns a 26 character string of the form: 2231 // "Sun Sep 16 01:03:52 1973\n\0" 2232 // just print 24 characters. 2233 time_t t = Seconds; 2234 outs() << format("%.24s ", ctime(&t)); 2235 } 2236 } else { 2237 outs() << RawLastModified << " "; 2238 } 2239 2240 if (verbose) { 2241 Expected<StringRef> NameOrErr = C.getName(); 2242 if (!NameOrErr) { 2243 consumeError(NameOrErr.takeError()); 2244 outs() << unwrapOrError(C.getRawName(), 2245 getFileNameForError(C, ChildIndex), Filename, 2246 ArchitectureName) 2247 << "\n"; 2248 } else { 2249 StringRef Name = NameOrErr.get(); 2250 outs() << Name << "\n"; 2251 } 2252 } else { 2253 outs() << unwrapOrError(C.getRawName(), getFileNameForError(C, ChildIndex), 2254 Filename, ArchitectureName) 2255 << "\n"; 2256 } 2257 } 2258 2259 static void printArchiveHeaders(StringRef Filename, Archive *A, bool verbose, 2260 bool print_offset, 2261 StringRef ArchitectureName = StringRef()) { 2262 Error Err = Error::success(); 2263 size_t I = 0; 2264 for (const auto &C : A->children(Err, false)) 2265 printArchiveChild(Filename, C, I++, verbose, print_offset, 2266 ArchitectureName); 2267 2268 if (Err) 2269 reportError(std::move(Err), Filename, "", ArchitectureName); 2270 } 2271 2272 static bool ValidateArchFlags() { 2273 // Check for -arch all and verifiy the -arch flags are valid. 2274 for (unsigned i = 0; i < ArchFlags.size(); ++i) { 2275 if (ArchFlags[i] == "all") { 2276 ArchAll = true; 2277 } else { 2278 if (!MachOObjectFile::isValidArch(ArchFlags[i])) { 2279 WithColor::error(errs(), "llvm-objdump") 2280 << "unknown architecture named '" + ArchFlags[i] + 2281 "'for the -arch option\n"; 2282 return false; 2283 } 2284 } 2285 } 2286 return true; 2287 } 2288 2289 // ParseInputMachO() parses the named Mach-O file in Filename and handles the 2290 // -arch flags selecting just those slices as specified by them and also parses 2291 // archive files. Then for each individual Mach-O file ProcessMachO() is 2292 // called to process the file based on the command line options. 2293 void objdump::parseInputMachO(StringRef Filename) { 2294 if (!ValidateArchFlags()) 2295 return; 2296 2297 // Attempt to open the binary. 2298 Expected<OwningBinary<Binary>> BinaryOrErr = createBinary(Filename); 2299 if (!BinaryOrErr) { 2300 if (Error E = isNotObjectErrorInvalidFileType(BinaryOrErr.takeError())) 2301 reportError(std::move(E), Filename); 2302 else 2303 outs() << Filename << ": is not an object file\n"; 2304 return; 2305 } 2306 Binary &Bin = *BinaryOrErr.get().getBinary(); 2307 2308 if (Archive *A = dyn_cast<Archive>(&Bin)) { 2309 outs() << "Archive : " << Filename << "\n"; 2310 if (ArchiveHeaders) 2311 printArchiveHeaders(Filename, A, !NonVerbose, ArchiveMemberOffsets); 2312 2313 Error Err = Error::success(); 2314 unsigned I = -1; 2315 for (auto &C : A->children(Err)) { 2316 ++I; 2317 Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary(); 2318 if (!ChildOrErr) { 2319 if (Error E = isNotObjectErrorInvalidFileType(ChildOrErr.takeError())) 2320 reportError(std::move(E), getFileNameForError(C, I), Filename); 2321 continue; 2322 } 2323 if (MachOObjectFile *O = dyn_cast<MachOObjectFile>(&*ChildOrErr.get())) { 2324 if (!checkMachOAndArchFlags(O, Filename)) 2325 return; 2326 ProcessMachO(Filename, O, O->getFileName()); 2327 } 2328 } 2329 if (Err) 2330 reportError(std::move(Err), Filename); 2331 return; 2332 } 2333 if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(&Bin)) { 2334 parseInputMachO(UB); 2335 return; 2336 } 2337 if (ObjectFile *O = dyn_cast<ObjectFile>(&Bin)) { 2338 if (!checkMachOAndArchFlags(O, Filename)) 2339 return; 2340 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&*O)) 2341 ProcessMachO(Filename, MachOOF); 2342 else 2343 WithColor::error(errs(), "llvm-objdump") 2344 << Filename << "': " 2345 << "object is not a Mach-O file type.\n"; 2346 return; 2347 } 2348 llvm_unreachable("Input object can't be invalid at this point"); 2349 } 2350 2351 void objdump::parseInputMachO(MachOUniversalBinary *UB) { 2352 if (!ValidateArchFlags()) 2353 return; 2354 2355 auto Filename = UB->getFileName(); 2356 2357 if (UniversalHeaders) 2358 printMachOUniversalHeaders(UB, !NonVerbose); 2359 2360 // If we have a list of architecture flags specified dump only those. 2361 if (!ArchAll && !ArchFlags.empty()) { 2362 // Look for a slice in the universal binary that matches each ArchFlag. 2363 bool ArchFound; 2364 for (unsigned i = 0; i < ArchFlags.size(); ++i) { 2365 ArchFound = false; 2366 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(), 2367 E = UB->end_objects(); 2368 I != E; ++I) { 2369 if (ArchFlags[i] == I->getArchFlagName()) { 2370 ArchFound = true; 2371 Expected<std::unique_ptr<ObjectFile>> ObjOrErr = 2372 I->getAsObjectFile(); 2373 std::string ArchitectureName; 2374 if (ArchFlags.size() > 1) 2375 ArchitectureName = I->getArchFlagName(); 2376 if (ObjOrErr) { 2377 ObjectFile &O = *ObjOrErr.get(); 2378 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&O)) 2379 ProcessMachO(Filename, MachOOF, "", ArchitectureName); 2380 } else if (Error E = isNotObjectErrorInvalidFileType( 2381 ObjOrErr.takeError())) { 2382 reportError(std::move(E), "", Filename, ArchitectureName); 2383 continue; 2384 } else if (Expected<std::unique_ptr<Archive>> AOrErr = 2385 I->getAsArchive()) { 2386 std::unique_ptr<Archive> &A = *AOrErr; 2387 outs() << "Archive : " << Filename; 2388 if (!ArchitectureName.empty()) 2389 outs() << " (architecture " << ArchitectureName << ")"; 2390 outs() << "\n"; 2391 if (ArchiveHeaders) 2392 printArchiveHeaders(Filename, A.get(), !NonVerbose, 2393 ArchiveMemberOffsets, ArchitectureName); 2394 Error Err = Error::success(); 2395 unsigned I = -1; 2396 for (auto &C : A->children(Err)) { 2397 ++I; 2398 Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary(); 2399 if (!ChildOrErr) { 2400 if (Error E = 2401 isNotObjectErrorInvalidFileType(ChildOrErr.takeError())) 2402 reportError(std::move(E), getFileNameForError(C, I), Filename, 2403 ArchitectureName); 2404 continue; 2405 } 2406 if (MachOObjectFile *O = 2407 dyn_cast<MachOObjectFile>(&*ChildOrErr.get())) 2408 ProcessMachO(Filename, O, O->getFileName(), ArchitectureName); 2409 } 2410 if (Err) 2411 reportError(std::move(Err), Filename); 2412 } else { 2413 consumeError(AOrErr.takeError()); 2414 reportError(Filename, 2415 "Mach-O universal file for architecture " + 2416 StringRef(I->getArchFlagName()) + 2417 " is not a Mach-O file or an archive file"); 2418 } 2419 } 2420 } 2421 if (!ArchFound) { 2422 WithColor::error(errs(), "llvm-objdump") 2423 << "file: " + Filename + " does not contain " 2424 << "architecture: " + ArchFlags[i] + "\n"; 2425 return; 2426 } 2427 } 2428 return; 2429 } 2430 // No architecture flags were specified so if this contains a slice that 2431 // matches the host architecture dump only that. 2432 if (!ArchAll) { 2433 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(), 2434 E = UB->end_objects(); 2435 I != E; ++I) { 2436 if (MachOObjectFile::getHostArch().getArchName() == 2437 I->getArchFlagName()) { 2438 Expected<std::unique_ptr<ObjectFile>> ObjOrErr = I->getAsObjectFile(); 2439 std::string ArchiveName; 2440 ArchiveName.clear(); 2441 if (ObjOrErr) { 2442 ObjectFile &O = *ObjOrErr.get(); 2443 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&O)) 2444 ProcessMachO(Filename, MachOOF); 2445 } else if (Error E = 2446 isNotObjectErrorInvalidFileType(ObjOrErr.takeError())) { 2447 reportError(std::move(E), Filename); 2448 } else if (Expected<std::unique_ptr<Archive>> AOrErr = 2449 I->getAsArchive()) { 2450 std::unique_ptr<Archive> &A = *AOrErr; 2451 outs() << "Archive : " << Filename << "\n"; 2452 if (ArchiveHeaders) 2453 printArchiveHeaders(Filename, A.get(), !NonVerbose, 2454 ArchiveMemberOffsets); 2455 Error Err = Error::success(); 2456 unsigned I = -1; 2457 for (auto &C : A->children(Err)) { 2458 ++I; 2459 Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary(); 2460 if (!ChildOrErr) { 2461 if (Error E = 2462 isNotObjectErrorInvalidFileType(ChildOrErr.takeError())) 2463 reportError(std::move(E), getFileNameForError(C, I), Filename); 2464 continue; 2465 } 2466 if (MachOObjectFile *O = 2467 dyn_cast<MachOObjectFile>(&*ChildOrErr.get())) 2468 ProcessMachO(Filename, O, O->getFileName()); 2469 } 2470 if (Err) 2471 reportError(std::move(Err), Filename); 2472 } else { 2473 consumeError(AOrErr.takeError()); 2474 reportError(Filename, "Mach-O universal file for architecture " + 2475 StringRef(I->getArchFlagName()) + 2476 " is not a Mach-O file or an archive file"); 2477 } 2478 return; 2479 } 2480 } 2481 } 2482 // Either all architectures have been specified or none have been specified 2483 // and this does not contain the host architecture so dump all the slices. 2484 bool moreThanOneArch = UB->getNumberOfObjects() > 1; 2485 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(), 2486 E = UB->end_objects(); 2487 I != E; ++I) { 2488 Expected<std::unique_ptr<ObjectFile>> ObjOrErr = I->getAsObjectFile(); 2489 std::string ArchitectureName; 2490 if (moreThanOneArch) 2491 ArchitectureName = I->getArchFlagName(); 2492 if (ObjOrErr) { 2493 ObjectFile &Obj = *ObjOrErr.get(); 2494 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&Obj)) 2495 ProcessMachO(Filename, MachOOF, "", ArchitectureName); 2496 } else if (Error E = 2497 isNotObjectErrorInvalidFileType(ObjOrErr.takeError())) { 2498 reportError(std::move(E), Filename, "", ArchitectureName); 2499 } else if (Expected<std::unique_ptr<Archive>> AOrErr = I->getAsArchive()) { 2500 std::unique_ptr<Archive> &A = *AOrErr; 2501 outs() << "Archive : " << Filename; 2502 if (!ArchitectureName.empty()) 2503 outs() << " (architecture " << ArchitectureName << ")"; 2504 outs() << "\n"; 2505 if (ArchiveHeaders) 2506 printArchiveHeaders(Filename, A.get(), !NonVerbose, 2507 ArchiveMemberOffsets, ArchitectureName); 2508 Error Err = Error::success(); 2509 unsigned I = -1; 2510 for (auto &C : A->children(Err)) { 2511 ++I; 2512 Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary(); 2513 if (!ChildOrErr) { 2514 if (Error E = isNotObjectErrorInvalidFileType(ChildOrErr.takeError())) 2515 reportError(std::move(E), getFileNameForError(C, I), Filename, 2516 ArchitectureName); 2517 continue; 2518 } 2519 if (MachOObjectFile *O = 2520 dyn_cast<MachOObjectFile>(&*ChildOrErr.get())) { 2521 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(O)) 2522 ProcessMachO(Filename, MachOOF, MachOOF->getFileName(), 2523 ArchitectureName); 2524 } 2525 } 2526 if (Err) 2527 reportError(std::move(Err), Filename); 2528 } else { 2529 consumeError(AOrErr.takeError()); 2530 reportError(Filename, "Mach-O universal file for architecture " + 2531 StringRef(I->getArchFlagName()) + 2532 " is not a Mach-O file or an archive file"); 2533 } 2534 } 2535 } 2536 2537 namespace { 2538 // The block of info used by the Symbolizer call backs. 2539 struct DisassembleInfo { 2540 DisassembleInfo(MachOObjectFile *O, SymbolAddressMap *AddrMap, 2541 std::vector<SectionRef> *Sections, bool verbose) 2542 : verbose(verbose), O(O), AddrMap(AddrMap), Sections(Sections) {} 2543 bool verbose; 2544 MachOObjectFile *O; 2545 SectionRef S; 2546 SymbolAddressMap *AddrMap; 2547 std::vector<SectionRef> *Sections; 2548 const char *class_name = nullptr; 2549 const char *selector_name = nullptr; 2550 std::unique_ptr<char[]> method = nullptr; 2551 char *demangled_name = nullptr; 2552 uint64_t adrp_addr = 0; 2553 uint32_t adrp_inst = 0; 2554 std::unique_ptr<SymbolAddressMap> bindtable; 2555 uint32_t depth = 0; 2556 }; 2557 } // namespace 2558 2559 // SymbolizerGetOpInfo() is the operand information call back function. 2560 // This is called to get the symbolic information for operand(s) of an 2561 // instruction when it is being done. This routine does this from 2562 // the relocation information, symbol table, etc. That block of information 2563 // is a pointer to the struct DisassembleInfo that was passed when the 2564 // disassembler context was created and passed to back to here when 2565 // called back by the disassembler for instruction operands that could have 2566 // relocation information. The address of the instruction containing operand is 2567 // at the Pc parameter. The immediate value the operand has is passed in 2568 // op_info->Value and is at Offset past the start of the instruction and has a 2569 // byte Size of 1, 2 or 4. The symbolc information is returned in TagBuf is the 2570 // LLVMOpInfo1 struct defined in the header "llvm-c/Disassembler.h" as symbol 2571 // names and addends of the symbolic expression to add for the operand. The 2572 // value of TagType is currently 1 (for the LLVMOpInfo1 struct). If symbolic 2573 // information is returned then this function returns 1 else it returns 0. 2574 static int SymbolizerGetOpInfo(void *DisInfo, uint64_t Pc, uint64_t Offset, 2575 uint64_t Size, int TagType, void *TagBuf) { 2576 struct DisassembleInfo *info = (struct DisassembleInfo *)DisInfo; 2577 struct LLVMOpInfo1 *op_info = (struct LLVMOpInfo1 *)TagBuf; 2578 uint64_t value = op_info->Value; 2579 2580 // Make sure all fields returned are zero if we don't set them. 2581 memset((void *)op_info, '\0', sizeof(struct LLVMOpInfo1)); 2582 op_info->Value = value; 2583 2584 // If the TagType is not the value 1 which it code knows about or if no 2585 // verbose symbolic information is wanted then just return 0, indicating no 2586 // information is being returned. 2587 if (TagType != 1 || !info->verbose) 2588 return 0; 2589 2590 unsigned int Arch = info->O->getArch(); 2591 if (Arch == Triple::x86) { 2592 if (Size != 1 && Size != 2 && Size != 4 && Size != 0) 2593 return 0; 2594 if (info->O->getHeader().filetype != MachO::MH_OBJECT) { 2595 // TODO: 2596 // Search the external relocation entries of a fully linked image 2597 // (if any) for an entry that matches this segment offset. 2598 // uint32_t seg_offset = (Pc + Offset); 2599 return 0; 2600 } 2601 // In MH_OBJECT filetypes search the section's relocation entries (if any) 2602 // for an entry for this section offset. 2603 uint32_t sect_addr = info->S.getAddress(); 2604 uint32_t sect_offset = (Pc + Offset) - sect_addr; 2605 bool reloc_found = false; 2606 DataRefImpl Rel; 2607 MachO::any_relocation_info RE; 2608 bool isExtern = false; 2609 SymbolRef Symbol; 2610 bool r_scattered = false; 2611 uint32_t r_value, pair_r_value, r_type; 2612 for (const RelocationRef &Reloc : info->S.relocations()) { 2613 uint64_t RelocOffset = Reloc.getOffset(); 2614 if (RelocOffset == sect_offset) { 2615 Rel = Reloc.getRawDataRefImpl(); 2616 RE = info->O->getRelocation(Rel); 2617 r_type = info->O->getAnyRelocationType(RE); 2618 r_scattered = info->O->isRelocationScattered(RE); 2619 if (r_scattered) { 2620 r_value = info->O->getScatteredRelocationValue(RE); 2621 if (r_type == MachO::GENERIC_RELOC_SECTDIFF || 2622 r_type == MachO::GENERIC_RELOC_LOCAL_SECTDIFF) { 2623 DataRefImpl RelNext = Rel; 2624 info->O->moveRelocationNext(RelNext); 2625 MachO::any_relocation_info RENext; 2626 RENext = info->O->getRelocation(RelNext); 2627 if (info->O->isRelocationScattered(RENext)) 2628 pair_r_value = info->O->getScatteredRelocationValue(RENext); 2629 else 2630 return 0; 2631 } 2632 } else { 2633 isExtern = info->O->getPlainRelocationExternal(RE); 2634 if (isExtern) { 2635 symbol_iterator RelocSym = Reloc.getSymbol(); 2636 Symbol = *RelocSym; 2637 } 2638 } 2639 reloc_found = true; 2640 break; 2641 } 2642 } 2643 if (reloc_found && isExtern) { 2644 op_info->AddSymbol.Present = 1; 2645 op_info->AddSymbol.Name = 2646 unwrapOrError(Symbol.getName(), info->O->getFileName()).data(); 2647 // For i386 extern relocation entries the value in the instruction is 2648 // the offset from the symbol, and value is already set in op_info->Value. 2649 return 1; 2650 } 2651 if (reloc_found && (r_type == MachO::GENERIC_RELOC_SECTDIFF || 2652 r_type == MachO::GENERIC_RELOC_LOCAL_SECTDIFF)) { 2653 const char *add = GuessSymbolName(r_value, info->AddrMap); 2654 const char *sub = GuessSymbolName(pair_r_value, info->AddrMap); 2655 uint32_t offset = value - (r_value - pair_r_value); 2656 op_info->AddSymbol.Present = 1; 2657 if (add != nullptr) 2658 op_info->AddSymbol.Name = add; 2659 else 2660 op_info->AddSymbol.Value = r_value; 2661 op_info->SubtractSymbol.Present = 1; 2662 if (sub != nullptr) 2663 op_info->SubtractSymbol.Name = sub; 2664 else 2665 op_info->SubtractSymbol.Value = pair_r_value; 2666 op_info->Value = offset; 2667 return 1; 2668 } 2669 return 0; 2670 } 2671 if (Arch == Triple::x86_64) { 2672 if (Size != 1 && Size != 2 && Size != 4 && Size != 0) 2673 return 0; 2674 // For non MH_OBJECT types, like MH_KEXT_BUNDLE, Search the external 2675 // relocation entries of a linked image (if any) for an entry that matches 2676 // this segment offset. 2677 if (info->O->getHeader().filetype != MachO::MH_OBJECT) { 2678 uint64_t seg_offset = Pc + Offset; 2679 bool reloc_found = false; 2680 DataRefImpl Rel; 2681 MachO::any_relocation_info RE; 2682 bool isExtern = false; 2683 SymbolRef Symbol; 2684 for (const RelocationRef &Reloc : info->O->external_relocations()) { 2685 uint64_t RelocOffset = Reloc.getOffset(); 2686 if (RelocOffset == seg_offset) { 2687 Rel = Reloc.getRawDataRefImpl(); 2688 RE = info->O->getRelocation(Rel); 2689 // external relocation entries should always be external. 2690 isExtern = info->O->getPlainRelocationExternal(RE); 2691 if (isExtern) { 2692 symbol_iterator RelocSym = Reloc.getSymbol(); 2693 Symbol = *RelocSym; 2694 } 2695 reloc_found = true; 2696 break; 2697 } 2698 } 2699 if (reloc_found && isExtern) { 2700 // The Value passed in will be adjusted by the Pc if the instruction 2701 // adds the Pc. But for x86_64 external relocation entries the Value 2702 // is the offset from the external symbol. 2703 if (info->O->getAnyRelocationPCRel(RE)) 2704 op_info->Value -= Pc + Offset + Size; 2705 const char *name = 2706 unwrapOrError(Symbol.getName(), info->O->getFileName()).data(); 2707 op_info->AddSymbol.Present = 1; 2708 op_info->AddSymbol.Name = name; 2709 return 1; 2710 } 2711 return 0; 2712 } 2713 // In MH_OBJECT filetypes search the section's relocation entries (if any) 2714 // for an entry for this section offset. 2715 uint64_t sect_addr = info->S.getAddress(); 2716 uint64_t sect_offset = (Pc + Offset) - sect_addr; 2717 bool reloc_found = false; 2718 DataRefImpl Rel; 2719 MachO::any_relocation_info RE; 2720 bool isExtern = false; 2721 SymbolRef Symbol; 2722 for (const RelocationRef &Reloc : info->S.relocations()) { 2723 uint64_t RelocOffset = Reloc.getOffset(); 2724 if (RelocOffset == sect_offset) { 2725 Rel = Reloc.getRawDataRefImpl(); 2726 RE = info->O->getRelocation(Rel); 2727 // NOTE: Scattered relocations don't exist on x86_64. 2728 isExtern = info->O->getPlainRelocationExternal(RE); 2729 if (isExtern) { 2730 symbol_iterator RelocSym = Reloc.getSymbol(); 2731 Symbol = *RelocSym; 2732 } 2733 reloc_found = true; 2734 break; 2735 } 2736 } 2737 if (reloc_found && isExtern) { 2738 // The Value passed in will be adjusted by the Pc if the instruction 2739 // adds the Pc. But for x86_64 external relocation entries the Value 2740 // is the offset from the external symbol. 2741 if (info->O->getAnyRelocationPCRel(RE)) 2742 op_info->Value -= Pc + Offset + Size; 2743 const char *name = 2744 unwrapOrError(Symbol.getName(), info->O->getFileName()).data(); 2745 unsigned Type = info->O->getAnyRelocationType(RE); 2746 if (Type == MachO::X86_64_RELOC_SUBTRACTOR) { 2747 DataRefImpl RelNext = Rel; 2748 info->O->moveRelocationNext(RelNext); 2749 MachO::any_relocation_info RENext = info->O->getRelocation(RelNext); 2750 unsigned TypeNext = info->O->getAnyRelocationType(RENext); 2751 bool isExternNext = info->O->getPlainRelocationExternal(RENext); 2752 unsigned SymbolNum = info->O->getPlainRelocationSymbolNum(RENext); 2753 if (TypeNext == MachO::X86_64_RELOC_UNSIGNED && isExternNext) { 2754 op_info->SubtractSymbol.Present = 1; 2755 op_info->SubtractSymbol.Name = name; 2756 symbol_iterator RelocSymNext = info->O->getSymbolByIndex(SymbolNum); 2757 Symbol = *RelocSymNext; 2758 name = unwrapOrError(Symbol.getName(), info->O->getFileName()).data(); 2759 } 2760 } 2761 // TODO: add the VariantKinds to op_info->VariantKind for relocation types 2762 // like: X86_64_RELOC_TLV, X86_64_RELOC_GOT_LOAD and X86_64_RELOC_GOT. 2763 op_info->AddSymbol.Present = 1; 2764 op_info->AddSymbol.Name = name; 2765 return 1; 2766 } 2767 return 0; 2768 } 2769 if (Arch == Triple::arm) { 2770 if (Offset != 0 || (Size != 4 && Size != 2)) 2771 return 0; 2772 if (info->O->getHeader().filetype != MachO::MH_OBJECT) { 2773 // TODO: 2774 // Search the external relocation entries of a fully linked image 2775 // (if any) for an entry that matches this segment offset. 2776 // uint32_t seg_offset = (Pc + Offset); 2777 return 0; 2778 } 2779 // In MH_OBJECT filetypes search the section's relocation entries (if any) 2780 // for an entry for this section offset. 2781 uint32_t sect_addr = info->S.getAddress(); 2782 uint32_t sect_offset = (Pc + Offset) - sect_addr; 2783 DataRefImpl Rel; 2784 MachO::any_relocation_info RE; 2785 bool isExtern = false; 2786 SymbolRef Symbol; 2787 bool r_scattered = false; 2788 uint32_t r_value, pair_r_value, r_type, r_length, other_half; 2789 auto Reloc = 2790 find_if(info->S.relocations(), [&](const RelocationRef &Reloc) { 2791 uint64_t RelocOffset = Reloc.getOffset(); 2792 return RelocOffset == sect_offset; 2793 }); 2794 2795 if (Reloc == info->S.relocations().end()) 2796 return 0; 2797 2798 Rel = Reloc->getRawDataRefImpl(); 2799 RE = info->O->getRelocation(Rel); 2800 r_length = info->O->getAnyRelocationLength(RE); 2801 r_scattered = info->O->isRelocationScattered(RE); 2802 if (r_scattered) { 2803 r_value = info->O->getScatteredRelocationValue(RE); 2804 r_type = info->O->getScatteredRelocationType(RE); 2805 } else { 2806 r_type = info->O->getAnyRelocationType(RE); 2807 isExtern = info->O->getPlainRelocationExternal(RE); 2808 if (isExtern) { 2809 symbol_iterator RelocSym = Reloc->getSymbol(); 2810 Symbol = *RelocSym; 2811 } 2812 } 2813 if (r_type == MachO::ARM_RELOC_HALF || 2814 r_type == MachO::ARM_RELOC_SECTDIFF || 2815 r_type == MachO::ARM_RELOC_LOCAL_SECTDIFF || 2816 r_type == MachO::ARM_RELOC_HALF_SECTDIFF) { 2817 DataRefImpl RelNext = Rel; 2818 info->O->moveRelocationNext(RelNext); 2819 MachO::any_relocation_info RENext; 2820 RENext = info->O->getRelocation(RelNext); 2821 other_half = info->O->getAnyRelocationAddress(RENext) & 0xffff; 2822 if (info->O->isRelocationScattered(RENext)) 2823 pair_r_value = info->O->getScatteredRelocationValue(RENext); 2824 } 2825 2826 if (isExtern) { 2827 const char *name = 2828 unwrapOrError(Symbol.getName(), info->O->getFileName()).data(); 2829 op_info->AddSymbol.Present = 1; 2830 op_info->AddSymbol.Name = name; 2831 switch (r_type) { 2832 case MachO::ARM_RELOC_HALF: 2833 if ((r_length & 0x1) == 1) { 2834 op_info->Value = value << 16 | other_half; 2835 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16; 2836 } else { 2837 op_info->Value = other_half << 16 | value; 2838 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16; 2839 } 2840 break; 2841 default: 2842 break; 2843 } 2844 return 1; 2845 } 2846 // If we have a branch that is not an external relocation entry then 2847 // return 0 so the code in tryAddingSymbolicOperand() can use the 2848 // SymbolLookUp call back with the branch target address to look up the 2849 // symbol and possibility add an annotation for a symbol stub. 2850 if (isExtern == 0 && (r_type == MachO::ARM_RELOC_BR24 || 2851 r_type == MachO::ARM_THUMB_RELOC_BR22)) 2852 return 0; 2853 2854 uint32_t offset = 0; 2855 if (r_type == MachO::ARM_RELOC_HALF || 2856 r_type == MachO::ARM_RELOC_HALF_SECTDIFF) { 2857 if ((r_length & 0x1) == 1) 2858 value = value << 16 | other_half; 2859 else 2860 value = other_half << 16 | value; 2861 } 2862 if (r_scattered && (r_type != MachO::ARM_RELOC_HALF && 2863 r_type != MachO::ARM_RELOC_HALF_SECTDIFF)) { 2864 offset = value - r_value; 2865 value = r_value; 2866 } 2867 2868 if (r_type == MachO::ARM_RELOC_HALF_SECTDIFF) { 2869 if ((r_length & 0x1) == 1) 2870 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16; 2871 else 2872 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16; 2873 const char *add = GuessSymbolName(r_value, info->AddrMap); 2874 const char *sub = GuessSymbolName(pair_r_value, info->AddrMap); 2875 int32_t offset = value - (r_value - pair_r_value); 2876 op_info->AddSymbol.Present = 1; 2877 if (add != nullptr) 2878 op_info->AddSymbol.Name = add; 2879 else 2880 op_info->AddSymbol.Value = r_value; 2881 op_info->SubtractSymbol.Present = 1; 2882 if (sub != nullptr) 2883 op_info->SubtractSymbol.Name = sub; 2884 else 2885 op_info->SubtractSymbol.Value = pair_r_value; 2886 op_info->Value = offset; 2887 return 1; 2888 } 2889 2890 op_info->AddSymbol.Present = 1; 2891 op_info->Value = offset; 2892 if (r_type == MachO::ARM_RELOC_HALF) { 2893 if ((r_length & 0x1) == 1) 2894 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16; 2895 else 2896 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16; 2897 } 2898 const char *add = GuessSymbolName(value, info->AddrMap); 2899 if (add != nullptr) { 2900 op_info->AddSymbol.Name = add; 2901 return 1; 2902 } 2903 op_info->AddSymbol.Value = value; 2904 return 1; 2905 } 2906 if (Arch == Triple::aarch64) { 2907 if (Offset != 0 || Size != 4) 2908 return 0; 2909 if (info->O->getHeader().filetype != MachO::MH_OBJECT) { 2910 // TODO: 2911 // Search the external relocation entries of a fully linked image 2912 // (if any) for an entry that matches this segment offset. 2913 // uint64_t seg_offset = (Pc + Offset); 2914 return 0; 2915 } 2916 // In MH_OBJECT filetypes search the section's relocation entries (if any) 2917 // for an entry for this section offset. 2918 uint64_t sect_addr = info->S.getAddress(); 2919 uint64_t sect_offset = (Pc + Offset) - sect_addr; 2920 auto Reloc = 2921 find_if(info->S.relocations(), [&](const RelocationRef &Reloc) { 2922 uint64_t RelocOffset = Reloc.getOffset(); 2923 return RelocOffset == sect_offset; 2924 }); 2925 2926 if (Reloc == info->S.relocations().end()) 2927 return 0; 2928 2929 DataRefImpl Rel = Reloc->getRawDataRefImpl(); 2930 MachO::any_relocation_info RE = info->O->getRelocation(Rel); 2931 uint32_t r_type = info->O->getAnyRelocationType(RE); 2932 if (r_type == MachO::ARM64_RELOC_ADDEND) { 2933 DataRefImpl RelNext = Rel; 2934 info->O->moveRelocationNext(RelNext); 2935 MachO::any_relocation_info RENext = info->O->getRelocation(RelNext); 2936 if (value == 0) { 2937 value = info->O->getPlainRelocationSymbolNum(RENext); 2938 op_info->Value = value; 2939 } 2940 } 2941 // NOTE: Scattered relocations don't exist on arm64. 2942 if (!info->O->getPlainRelocationExternal(RE)) 2943 return 0; 2944 const char *name = 2945 unwrapOrError(Reloc->getSymbol()->getName(), info->O->getFileName()) 2946 .data(); 2947 op_info->AddSymbol.Present = 1; 2948 op_info->AddSymbol.Name = name; 2949 2950 switch (r_type) { 2951 case MachO::ARM64_RELOC_PAGE21: 2952 /* @page */ 2953 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_PAGE; 2954 break; 2955 case MachO::ARM64_RELOC_PAGEOFF12: 2956 /* @pageoff */ 2957 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_PAGEOFF; 2958 break; 2959 case MachO::ARM64_RELOC_GOT_LOAD_PAGE21: 2960 /* @gotpage */ 2961 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_GOTPAGE; 2962 break; 2963 case MachO::ARM64_RELOC_GOT_LOAD_PAGEOFF12: 2964 /* @gotpageoff */ 2965 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_GOTPAGEOFF; 2966 break; 2967 case MachO::ARM64_RELOC_TLVP_LOAD_PAGE21: 2968 /* @tvlppage is not implemented in llvm-mc */ 2969 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_TLVP; 2970 break; 2971 case MachO::ARM64_RELOC_TLVP_LOAD_PAGEOFF12: 2972 /* @tvlppageoff is not implemented in llvm-mc */ 2973 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_TLVOFF; 2974 break; 2975 default: 2976 case MachO::ARM64_RELOC_BRANCH26: 2977 op_info->VariantKind = LLVMDisassembler_VariantKind_None; 2978 break; 2979 } 2980 return 1; 2981 } 2982 return 0; 2983 } 2984 2985 // GuessCstringPointer is passed the address of what might be a pointer to a 2986 // literal string in a cstring section. If that address is in a cstring section 2987 // it returns a pointer to that string. Else it returns nullptr. 2988 static const char *GuessCstringPointer(uint64_t ReferenceValue, 2989 struct DisassembleInfo *info) { 2990 for (const auto &Load : info->O->load_commands()) { 2991 if (Load.C.cmd == MachO::LC_SEGMENT_64) { 2992 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load); 2993 for (unsigned J = 0; J < Seg.nsects; ++J) { 2994 MachO::section_64 Sec = info->O->getSection64(Load, J); 2995 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE; 2996 if (section_type == MachO::S_CSTRING_LITERALS && 2997 ReferenceValue >= Sec.addr && 2998 ReferenceValue < Sec.addr + Sec.size) { 2999 uint64_t sect_offset = ReferenceValue - Sec.addr; 3000 uint64_t object_offset = Sec.offset + sect_offset; 3001 StringRef MachOContents = info->O->getData(); 3002 uint64_t object_size = MachOContents.size(); 3003 const char *object_addr = (const char *)MachOContents.data(); 3004 if (object_offset < object_size) { 3005 const char *name = object_addr + object_offset; 3006 return name; 3007 } else { 3008 return nullptr; 3009 } 3010 } 3011 } 3012 } else if (Load.C.cmd == MachO::LC_SEGMENT) { 3013 MachO::segment_command Seg = info->O->getSegmentLoadCommand(Load); 3014 for (unsigned J = 0; J < Seg.nsects; ++J) { 3015 MachO::section Sec = info->O->getSection(Load, J); 3016 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE; 3017 if (section_type == MachO::S_CSTRING_LITERALS && 3018 ReferenceValue >= Sec.addr && 3019 ReferenceValue < Sec.addr + Sec.size) { 3020 uint64_t sect_offset = ReferenceValue - Sec.addr; 3021 uint64_t object_offset = Sec.offset + sect_offset; 3022 StringRef MachOContents = info->O->getData(); 3023 uint64_t object_size = MachOContents.size(); 3024 const char *object_addr = (const char *)MachOContents.data(); 3025 if (object_offset < object_size) { 3026 const char *name = object_addr + object_offset; 3027 return name; 3028 } else { 3029 return nullptr; 3030 } 3031 } 3032 } 3033 } 3034 } 3035 return nullptr; 3036 } 3037 3038 // GuessIndirectSymbol returns the name of the indirect symbol for the 3039 // ReferenceValue passed in or nullptr. This is used when ReferenceValue maybe 3040 // an address of a symbol stub or a lazy or non-lazy pointer to associate the 3041 // symbol name being referenced by the stub or pointer. 3042 static const char *GuessIndirectSymbol(uint64_t ReferenceValue, 3043 struct DisassembleInfo *info) { 3044 MachO::dysymtab_command Dysymtab = info->O->getDysymtabLoadCommand(); 3045 MachO::symtab_command Symtab = info->O->getSymtabLoadCommand(); 3046 for (const auto &Load : info->O->load_commands()) { 3047 if (Load.C.cmd == MachO::LC_SEGMENT_64) { 3048 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load); 3049 for (unsigned J = 0; J < Seg.nsects; ++J) { 3050 MachO::section_64 Sec = info->O->getSection64(Load, J); 3051 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE; 3052 if ((section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS || 3053 section_type == MachO::S_LAZY_SYMBOL_POINTERS || 3054 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS || 3055 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS || 3056 section_type == MachO::S_SYMBOL_STUBS) && 3057 ReferenceValue >= Sec.addr && 3058 ReferenceValue < Sec.addr + Sec.size) { 3059 uint32_t stride; 3060 if (section_type == MachO::S_SYMBOL_STUBS) 3061 stride = Sec.reserved2; 3062 else 3063 stride = 8; 3064 if (stride == 0) 3065 return nullptr; 3066 uint32_t index = Sec.reserved1 + (ReferenceValue - Sec.addr) / stride; 3067 if (index < Dysymtab.nindirectsyms) { 3068 uint32_t indirect_symbol = 3069 info->O->getIndirectSymbolTableEntry(Dysymtab, index); 3070 if (indirect_symbol < Symtab.nsyms) { 3071 symbol_iterator Sym = info->O->getSymbolByIndex(indirect_symbol); 3072 return unwrapOrError(Sym->getName(), info->O->getFileName()) 3073 .data(); 3074 } 3075 } 3076 } 3077 } 3078 } else if (Load.C.cmd == MachO::LC_SEGMENT) { 3079 MachO::segment_command Seg = info->O->getSegmentLoadCommand(Load); 3080 for (unsigned J = 0; J < Seg.nsects; ++J) { 3081 MachO::section Sec = info->O->getSection(Load, J); 3082 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE; 3083 if ((section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS || 3084 section_type == MachO::S_LAZY_SYMBOL_POINTERS || 3085 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS || 3086 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS || 3087 section_type == MachO::S_SYMBOL_STUBS) && 3088 ReferenceValue >= Sec.addr && 3089 ReferenceValue < Sec.addr + Sec.size) { 3090 uint32_t stride; 3091 if (section_type == MachO::S_SYMBOL_STUBS) 3092 stride = Sec.reserved2; 3093 else 3094 stride = 4; 3095 if (stride == 0) 3096 return nullptr; 3097 uint32_t index = Sec.reserved1 + (ReferenceValue - Sec.addr) / stride; 3098 if (index < Dysymtab.nindirectsyms) { 3099 uint32_t indirect_symbol = 3100 info->O->getIndirectSymbolTableEntry(Dysymtab, index); 3101 if (indirect_symbol < Symtab.nsyms) { 3102 symbol_iterator Sym = info->O->getSymbolByIndex(indirect_symbol); 3103 return unwrapOrError(Sym->getName(), info->O->getFileName()) 3104 .data(); 3105 } 3106 } 3107 } 3108 } 3109 } 3110 } 3111 return nullptr; 3112 } 3113 3114 // method_reference() is called passing it the ReferenceName that might be 3115 // a reference it to an Objective-C method call. If so then it allocates and 3116 // assembles a method call string with the values last seen and saved in 3117 // the DisassembleInfo's class_name and selector_name fields. This is saved 3118 // into the method field of the info and any previous string is free'ed. 3119 // Then the class_name field in the info is set to nullptr. The method call 3120 // string is set into ReferenceName and ReferenceType is set to 3121 // LLVMDisassembler_ReferenceType_Out_Objc_Message. If this not a method call 3122 // then both ReferenceType and ReferenceName are left unchanged. 3123 static void method_reference(struct DisassembleInfo *info, 3124 uint64_t *ReferenceType, 3125 const char **ReferenceName) { 3126 unsigned int Arch = info->O->getArch(); 3127 if (*ReferenceName != nullptr) { 3128 if (strcmp(*ReferenceName, "_objc_msgSend") == 0) { 3129 if (info->selector_name != nullptr) { 3130 if (info->class_name != nullptr) { 3131 info->method = std::make_unique<char[]>( 3132 5 + strlen(info->class_name) + strlen(info->selector_name)); 3133 char *method = info->method.get(); 3134 if (method != nullptr) { 3135 strcpy(method, "+["); 3136 strcat(method, info->class_name); 3137 strcat(method, " "); 3138 strcat(method, info->selector_name); 3139 strcat(method, "]"); 3140 *ReferenceName = method; 3141 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message; 3142 } 3143 } else { 3144 info->method = 3145 std::make_unique<char[]>(9 + strlen(info->selector_name)); 3146 char *method = info->method.get(); 3147 if (method != nullptr) { 3148 if (Arch == Triple::x86_64) 3149 strcpy(method, "-[%rdi "); 3150 else if (Arch == Triple::aarch64) 3151 strcpy(method, "-[x0 "); 3152 else 3153 strcpy(method, "-[r? "); 3154 strcat(method, info->selector_name); 3155 strcat(method, "]"); 3156 *ReferenceName = method; 3157 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message; 3158 } 3159 } 3160 info->class_name = nullptr; 3161 } 3162 } else if (strcmp(*ReferenceName, "_objc_msgSendSuper2") == 0) { 3163 if (info->selector_name != nullptr) { 3164 info->method = 3165 std::make_unique<char[]>(17 + strlen(info->selector_name)); 3166 char *method = info->method.get(); 3167 if (method != nullptr) { 3168 if (Arch == Triple::x86_64) 3169 strcpy(method, "-[[%rdi super] "); 3170 else if (Arch == Triple::aarch64) 3171 strcpy(method, "-[[x0 super] "); 3172 else 3173 strcpy(method, "-[[r? super] "); 3174 strcat(method, info->selector_name); 3175 strcat(method, "]"); 3176 *ReferenceName = method; 3177 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message; 3178 } 3179 info->class_name = nullptr; 3180 } 3181 } 3182 } 3183 } 3184 3185 // GuessPointerPointer() is passed the address of what might be a pointer to 3186 // a reference to an Objective-C class, selector, message ref or cfstring. 3187 // If so the value of the pointer is returned and one of the booleans are set 3188 // to true. If not zero is returned and all the booleans are set to false. 3189 static uint64_t GuessPointerPointer(uint64_t ReferenceValue, 3190 struct DisassembleInfo *info, 3191 bool &classref, bool &selref, bool &msgref, 3192 bool &cfstring) { 3193 classref = false; 3194 selref = false; 3195 msgref = false; 3196 cfstring = false; 3197 for (const auto &Load : info->O->load_commands()) { 3198 if (Load.C.cmd == MachO::LC_SEGMENT_64) { 3199 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load); 3200 for (unsigned J = 0; J < Seg.nsects; ++J) { 3201 MachO::section_64 Sec = info->O->getSection64(Load, J); 3202 if ((strncmp(Sec.sectname, "__objc_selrefs", 16) == 0 || 3203 strncmp(Sec.sectname, "__objc_classrefs", 16) == 0 || 3204 strncmp(Sec.sectname, "__objc_superrefs", 16) == 0 || 3205 strncmp(Sec.sectname, "__objc_msgrefs", 16) == 0 || 3206 strncmp(Sec.sectname, "__cfstring", 16) == 0) && 3207 ReferenceValue >= Sec.addr && 3208 ReferenceValue < Sec.addr + Sec.size) { 3209 uint64_t sect_offset = ReferenceValue - Sec.addr; 3210 uint64_t object_offset = Sec.offset + sect_offset; 3211 StringRef MachOContents = info->O->getData(); 3212 uint64_t object_size = MachOContents.size(); 3213 const char *object_addr = (const char *)MachOContents.data(); 3214 if (object_offset < object_size) { 3215 uint64_t pointer_value; 3216 memcpy(&pointer_value, object_addr + object_offset, 3217 sizeof(uint64_t)); 3218 if (info->O->isLittleEndian() != sys::IsLittleEndianHost) 3219 sys::swapByteOrder(pointer_value); 3220 if (strncmp(Sec.sectname, "__objc_selrefs", 16) == 0) 3221 selref = true; 3222 else if (strncmp(Sec.sectname, "__objc_classrefs", 16) == 0 || 3223 strncmp(Sec.sectname, "__objc_superrefs", 16) == 0) 3224 classref = true; 3225 else if (strncmp(Sec.sectname, "__objc_msgrefs", 16) == 0 && 3226 ReferenceValue + 8 < Sec.addr + Sec.size) { 3227 msgref = true; 3228 memcpy(&pointer_value, object_addr + object_offset + 8, 3229 sizeof(uint64_t)); 3230 if (info->O->isLittleEndian() != sys::IsLittleEndianHost) 3231 sys::swapByteOrder(pointer_value); 3232 } else if (strncmp(Sec.sectname, "__cfstring", 16) == 0) 3233 cfstring = true; 3234 return pointer_value; 3235 } else { 3236 return 0; 3237 } 3238 } 3239 } 3240 } 3241 // TODO: Look for LC_SEGMENT for 32-bit Mach-O files. 3242 } 3243 return 0; 3244 } 3245 3246 // get_pointer_64 returns a pointer to the bytes in the object file at the 3247 // Address from a section in the Mach-O file. And indirectly returns the 3248 // offset into the section, number of bytes left in the section past the offset 3249 // and which section is was being referenced. If the Address is not in a 3250 // section nullptr is returned. 3251 static const char *get_pointer_64(uint64_t Address, uint32_t &offset, 3252 uint32_t &left, SectionRef &S, 3253 DisassembleInfo *info, 3254 bool objc_only = false) { 3255 offset = 0; 3256 left = 0; 3257 S = SectionRef(); 3258 for (unsigned SectIdx = 0; SectIdx != info->Sections->size(); SectIdx++) { 3259 uint64_t SectAddress = ((*(info->Sections))[SectIdx]).getAddress(); 3260 uint64_t SectSize = ((*(info->Sections))[SectIdx]).getSize(); 3261 if (SectSize == 0) 3262 continue; 3263 if (objc_only) { 3264 StringRef SectName; 3265 Expected<StringRef> SecNameOrErr = 3266 ((*(info->Sections))[SectIdx]).getName(); 3267 if (SecNameOrErr) 3268 SectName = *SecNameOrErr; 3269 else 3270 consumeError(SecNameOrErr.takeError()); 3271 3272 DataRefImpl Ref = ((*(info->Sections))[SectIdx]).getRawDataRefImpl(); 3273 StringRef SegName = info->O->getSectionFinalSegmentName(Ref); 3274 if (SegName != "__OBJC" && SectName != "__cstring") 3275 continue; 3276 } 3277 if (Address >= SectAddress && Address < SectAddress + SectSize) { 3278 S = (*(info->Sections))[SectIdx]; 3279 offset = Address - SectAddress; 3280 left = SectSize - offset; 3281 StringRef SectContents = unwrapOrError( 3282 ((*(info->Sections))[SectIdx]).getContents(), info->O->getFileName()); 3283 return SectContents.data() + offset; 3284 } 3285 } 3286 return nullptr; 3287 } 3288 3289 static const char *get_pointer_32(uint32_t Address, uint32_t &offset, 3290 uint32_t &left, SectionRef &S, 3291 DisassembleInfo *info, 3292 bool objc_only = false) { 3293 return get_pointer_64(Address, offset, left, S, info, objc_only); 3294 } 3295 3296 // get_symbol_64() returns the name of a symbol (or nullptr) and the address of 3297 // the symbol indirectly through n_value. Based on the relocation information 3298 // for the specified section offset in the specified section reference. 3299 // If no relocation information is found and a non-zero ReferenceValue for the 3300 // symbol is passed, look up that address in the info's AddrMap. 3301 static const char *get_symbol_64(uint32_t sect_offset, SectionRef S, 3302 DisassembleInfo *info, uint64_t &n_value, 3303 uint64_t ReferenceValue = 0) { 3304 n_value = 0; 3305 if (!info->verbose) 3306 return nullptr; 3307 3308 // See if there is an external relocation entry at the sect_offset. 3309 bool reloc_found = false; 3310 DataRefImpl Rel; 3311 MachO::any_relocation_info RE; 3312 bool isExtern = false; 3313 SymbolRef Symbol; 3314 for (const RelocationRef &Reloc : S.relocations()) { 3315 uint64_t RelocOffset = Reloc.getOffset(); 3316 if (RelocOffset == sect_offset) { 3317 Rel = Reloc.getRawDataRefImpl(); 3318 RE = info->O->getRelocation(Rel); 3319 if (info->O->isRelocationScattered(RE)) 3320 continue; 3321 isExtern = info->O->getPlainRelocationExternal(RE); 3322 if (isExtern) { 3323 symbol_iterator RelocSym = Reloc.getSymbol(); 3324 Symbol = *RelocSym; 3325 } 3326 reloc_found = true; 3327 break; 3328 } 3329 } 3330 // If there is an external relocation entry for a symbol in this section 3331 // at this section_offset then use that symbol's value for the n_value 3332 // and return its name. 3333 const char *SymbolName = nullptr; 3334 if (reloc_found && isExtern) { 3335 n_value = cantFail(Symbol.getValue()); 3336 StringRef Name = unwrapOrError(Symbol.getName(), info->O->getFileName()); 3337 if (!Name.empty()) { 3338 SymbolName = Name.data(); 3339 return SymbolName; 3340 } 3341 } 3342 3343 // TODO: For fully linked images, look through the external relocation 3344 // entries off the dynamic symtab command. For these the r_offset is from the 3345 // start of the first writeable segment in the Mach-O file. So the offset 3346 // to this section from that segment is passed to this routine by the caller, 3347 // as the database_offset. Which is the difference of the section's starting 3348 // address and the first writable segment. 3349 // 3350 // NOTE: need add passing the database_offset to this routine. 3351 3352 // We did not find an external relocation entry so look up the ReferenceValue 3353 // as an address of a symbol and if found return that symbol's name. 3354 SymbolName = GuessSymbolName(ReferenceValue, info->AddrMap); 3355 3356 return SymbolName; 3357 } 3358 3359 static const char *get_symbol_32(uint32_t sect_offset, SectionRef S, 3360 DisassembleInfo *info, 3361 uint32_t ReferenceValue) { 3362 uint64_t n_value64; 3363 return get_symbol_64(sect_offset, S, info, n_value64, ReferenceValue); 3364 } 3365 3366 namespace { 3367 3368 // These are structs in the Objective-C meta data and read to produce the 3369 // comments for disassembly. While these are part of the ABI they are no 3370 // public defintions. So the are here not in include/llvm/BinaryFormat/MachO.h 3371 // . 3372 3373 // The cfstring object in a 64-bit Mach-O file. 3374 struct cfstring64_t { 3375 uint64_t isa; // class64_t * (64-bit pointer) 3376 uint64_t flags; // flag bits 3377 uint64_t characters; // char * (64-bit pointer) 3378 uint64_t length; // number of non-NULL characters in above 3379 }; 3380 3381 // The class object in a 64-bit Mach-O file. 3382 struct class64_t { 3383 uint64_t isa; // class64_t * (64-bit pointer) 3384 uint64_t superclass; // class64_t * (64-bit pointer) 3385 uint64_t cache; // Cache (64-bit pointer) 3386 uint64_t vtable; // IMP * (64-bit pointer) 3387 uint64_t data; // class_ro64_t * (64-bit pointer) 3388 }; 3389 3390 struct class32_t { 3391 uint32_t isa; /* class32_t * (32-bit pointer) */ 3392 uint32_t superclass; /* class32_t * (32-bit pointer) */ 3393 uint32_t cache; /* Cache (32-bit pointer) */ 3394 uint32_t vtable; /* IMP * (32-bit pointer) */ 3395 uint32_t data; /* class_ro32_t * (32-bit pointer) */ 3396 }; 3397 3398 struct class_ro64_t { 3399 uint32_t flags; 3400 uint32_t instanceStart; 3401 uint32_t instanceSize; 3402 uint32_t reserved; 3403 uint64_t ivarLayout; // const uint8_t * (64-bit pointer) 3404 uint64_t name; // const char * (64-bit pointer) 3405 uint64_t baseMethods; // const method_list_t * (64-bit pointer) 3406 uint64_t baseProtocols; // const protocol_list_t * (64-bit pointer) 3407 uint64_t ivars; // const ivar_list_t * (64-bit pointer) 3408 uint64_t weakIvarLayout; // const uint8_t * (64-bit pointer) 3409 uint64_t baseProperties; // const struct objc_property_list (64-bit pointer) 3410 }; 3411 3412 struct class_ro32_t { 3413 uint32_t flags; 3414 uint32_t instanceStart; 3415 uint32_t instanceSize; 3416 uint32_t ivarLayout; /* const uint8_t * (32-bit pointer) */ 3417 uint32_t name; /* const char * (32-bit pointer) */ 3418 uint32_t baseMethods; /* const method_list_t * (32-bit pointer) */ 3419 uint32_t baseProtocols; /* const protocol_list_t * (32-bit pointer) */ 3420 uint32_t ivars; /* const ivar_list_t * (32-bit pointer) */ 3421 uint32_t weakIvarLayout; /* const uint8_t * (32-bit pointer) */ 3422 uint32_t baseProperties; /* const struct objc_property_list * 3423 (32-bit pointer) */ 3424 }; 3425 3426 /* Values for class_ro{64,32}_t->flags */ 3427 #define RO_META (1 << 0) 3428 #define RO_ROOT (1 << 1) 3429 #define RO_HAS_CXX_STRUCTORS (1 << 2) 3430 3431 struct method_list64_t { 3432 uint32_t entsize; 3433 uint32_t count; 3434 /* struct method64_t first; These structures follow inline */ 3435 }; 3436 3437 struct method_list32_t { 3438 uint32_t entsize; 3439 uint32_t count; 3440 /* struct method32_t first; These structures follow inline */ 3441 }; 3442 3443 struct method64_t { 3444 uint64_t name; /* SEL (64-bit pointer) */ 3445 uint64_t types; /* const char * (64-bit pointer) */ 3446 uint64_t imp; /* IMP (64-bit pointer) */ 3447 }; 3448 3449 struct method32_t { 3450 uint32_t name; /* SEL (32-bit pointer) */ 3451 uint32_t types; /* const char * (32-bit pointer) */ 3452 uint32_t imp; /* IMP (32-bit pointer) */ 3453 }; 3454 3455 struct protocol_list64_t { 3456 uint64_t count; /* uintptr_t (a 64-bit value) */ 3457 /* struct protocol64_t * list[0]; These pointers follow inline */ 3458 }; 3459 3460 struct protocol_list32_t { 3461 uint32_t count; /* uintptr_t (a 32-bit value) */ 3462 /* struct protocol32_t * list[0]; These pointers follow inline */ 3463 }; 3464 3465 struct protocol64_t { 3466 uint64_t isa; /* id * (64-bit pointer) */ 3467 uint64_t name; /* const char * (64-bit pointer) */ 3468 uint64_t protocols; /* struct protocol_list64_t * 3469 (64-bit pointer) */ 3470 uint64_t instanceMethods; /* method_list_t * (64-bit pointer) */ 3471 uint64_t classMethods; /* method_list_t * (64-bit pointer) */ 3472 uint64_t optionalInstanceMethods; /* method_list_t * (64-bit pointer) */ 3473 uint64_t optionalClassMethods; /* method_list_t * (64-bit pointer) */ 3474 uint64_t instanceProperties; /* struct objc_property_list * 3475 (64-bit pointer) */ 3476 }; 3477 3478 struct protocol32_t { 3479 uint32_t isa; /* id * (32-bit pointer) */ 3480 uint32_t name; /* const char * (32-bit pointer) */ 3481 uint32_t protocols; /* struct protocol_list_t * 3482 (32-bit pointer) */ 3483 uint32_t instanceMethods; /* method_list_t * (32-bit pointer) */ 3484 uint32_t classMethods; /* method_list_t * (32-bit pointer) */ 3485 uint32_t optionalInstanceMethods; /* method_list_t * (32-bit pointer) */ 3486 uint32_t optionalClassMethods; /* method_list_t * (32-bit pointer) */ 3487 uint32_t instanceProperties; /* struct objc_property_list * 3488 (32-bit pointer) */ 3489 }; 3490 3491 struct ivar_list64_t { 3492 uint32_t entsize; 3493 uint32_t count; 3494 /* struct ivar64_t first; These structures follow inline */ 3495 }; 3496 3497 struct ivar_list32_t { 3498 uint32_t entsize; 3499 uint32_t count; 3500 /* struct ivar32_t first; These structures follow inline */ 3501 }; 3502 3503 struct ivar64_t { 3504 uint64_t offset; /* uintptr_t * (64-bit pointer) */ 3505 uint64_t name; /* const char * (64-bit pointer) */ 3506 uint64_t type; /* const char * (64-bit pointer) */ 3507 uint32_t alignment; 3508 uint32_t size; 3509 }; 3510 3511 struct ivar32_t { 3512 uint32_t offset; /* uintptr_t * (32-bit pointer) */ 3513 uint32_t name; /* const char * (32-bit pointer) */ 3514 uint32_t type; /* const char * (32-bit pointer) */ 3515 uint32_t alignment; 3516 uint32_t size; 3517 }; 3518 3519 struct objc_property_list64 { 3520 uint32_t entsize; 3521 uint32_t count; 3522 /* struct objc_property64 first; These structures follow inline */ 3523 }; 3524 3525 struct objc_property_list32 { 3526 uint32_t entsize; 3527 uint32_t count; 3528 /* struct objc_property32 first; These structures follow inline */ 3529 }; 3530 3531 struct objc_property64 { 3532 uint64_t name; /* const char * (64-bit pointer) */ 3533 uint64_t attributes; /* const char * (64-bit pointer) */ 3534 }; 3535 3536 struct objc_property32 { 3537 uint32_t name; /* const char * (32-bit pointer) */ 3538 uint32_t attributes; /* const char * (32-bit pointer) */ 3539 }; 3540 3541 struct category64_t { 3542 uint64_t name; /* const char * (64-bit pointer) */ 3543 uint64_t cls; /* struct class_t * (64-bit pointer) */ 3544 uint64_t instanceMethods; /* struct method_list_t * (64-bit pointer) */ 3545 uint64_t classMethods; /* struct method_list_t * (64-bit pointer) */ 3546 uint64_t protocols; /* struct protocol_list_t * (64-bit pointer) */ 3547 uint64_t instanceProperties; /* struct objc_property_list * 3548 (64-bit pointer) */ 3549 }; 3550 3551 struct category32_t { 3552 uint32_t name; /* const char * (32-bit pointer) */ 3553 uint32_t cls; /* struct class_t * (32-bit pointer) */ 3554 uint32_t instanceMethods; /* struct method_list_t * (32-bit pointer) */ 3555 uint32_t classMethods; /* struct method_list_t * (32-bit pointer) */ 3556 uint32_t protocols; /* struct protocol_list_t * (32-bit pointer) */ 3557 uint32_t instanceProperties; /* struct objc_property_list * 3558 (32-bit pointer) */ 3559 }; 3560 3561 struct objc_image_info64 { 3562 uint32_t version; 3563 uint32_t flags; 3564 }; 3565 struct objc_image_info32 { 3566 uint32_t version; 3567 uint32_t flags; 3568 }; 3569 struct imageInfo_t { 3570 uint32_t version; 3571 uint32_t flags; 3572 }; 3573 /* masks for objc_image_info.flags */ 3574 #define OBJC_IMAGE_IS_REPLACEMENT (1 << 0) 3575 #define OBJC_IMAGE_SUPPORTS_GC (1 << 1) 3576 #define OBJC_IMAGE_IS_SIMULATED (1 << 5) 3577 #define OBJC_IMAGE_HAS_CATEGORY_CLASS_PROPERTIES (1 << 6) 3578 3579 struct message_ref64 { 3580 uint64_t imp; /* IMP (64-bit pointer) */ 3581 uint64_t sel; /* SEL (64-bit pointer) */ 3582 }; 3583 3584 struct message_ref32 { 3585 uint32_t imp; /* IMP (32-bit pointer) */ 3586 uint32_t sel; /* SEL (32-bit pointer) */ 3587 }; 3588 3589 // Objective-C 1 (32-bit only) meta data structs. 3590 3591 struct objc_module_t { 3592 uint32_t version; 3593 uint32_t size; 3594 uint32_t name; /* char * (32-bit pointer) */ 3595 uint32_t symtab; /* struct objc_symtab * (32-bit pointer) */ 3596 }; 3597 3598 struct objc_symtab_t { 3599 uint32_t sel_ref_cnt; 3600 uint32_t refs; /* SEL * (32-bit pointer) */ 3601 uint16_t cls_def_cnt; 3602 uint16_t cat_def_cnt; 3603 // uint32_t defs[1]; /* void * (32-bit pointer) variable size */ 3604 }; 3605 3606 struct objc_class_t { 3607 uint32_t isa; /* struct objc_class * (32-bit pointer) */ 3608 uint32_t super_class; /* struct objc_class * (32-bit pointer) */ 3609 uint32_t name; /* const char * (32-bit pointer) */ 3610 int32_t version; 3611 int32_t info; 3612 int32_t instance_size; 3613 uint32_t ivars; /* struct objc_ivar_list * (32-bit pointer) */ 3614 uint32_t methodLists; /* struct objc_method_list ** (32-bit pointer) */ 3615 uint32_t cache; /* struct objc_cache * (32-bit pointer) */ 3616 uint32_t protocols; /* struct objc_protocol_list * (32-bit pointer) */ 3617 }; 3618 3619 #define CLS_GETINFO(cls, infomask) ((cls)->info & (infomask)) 3620 // class is not a metaclass 3621 #define CLS_CLASS 0x1 3622 // class is a metaclass 3623 #define CLS_META 0x2 3624 3625 struct objc_category_t { 3626 uint32_t category_name; /* char * (32-bit pointer) */ 3627 uint32_t class_name; /* char * (32-bit pointer) */ 3628 uint32_t instance_methods; /* struct objc_method_list * (32-bit pointer) */ 3629 uint32_t class_methods; /* struct objc_method_list * (32-bit pointer) */ 3630 uint32_t protocols; /* struct objc_protocol_list * (32-bit ptr) */ 3631 }; 3632 3633 struct objc_ivar_t { 3634 uint32_t ivar_name; /* char * (32-bit pointer) */ 3635 uint32_t ivar_type; /* char * (32-bit pointer) */ 3636 int32_t ivar_offset; 3637 }; 3638 3639 struct objc_ivar_list_t { 3640 int32_t ivar_count; 3641 // struct objc_ivar_t ivar_list[1]; /* variable length structure */ 3642 }; 3643 3644 struct objc_method_list_t { 3645 uint32_t obsolete; /* struct objc_method_list * (32-bit pointer) */ 3646 int32_t method_count; 3647 // struct objc_method_t method_list[1]; /* variable length structure */ 3648 }; 3649 3650 struct objc_method_t { 3651 uint32_t method_name; /* SEL, aka struct objc_selector * (32-bit pointer) */ 3652 uint32_t method_types; /* char * (32-bit pointer) */ 3653 uint32_t method_imp; /* IMP, aka function pointer, (*IMP)(id, SEL, ...) 3654 (32-bit pointer) */ 3655 }; 3656 3657 struct objc_protocol_list_t { 3658 uint32_t next; /* struct objc_protocol_list * (32-bit pointer) */ 3659 int32_t count; 3660 // uint32_t list[1]; /* Protocol *, aka struct objc_protocol_t * 3661 // (32-bit pointer) */ 3662 }; 3663 3664 struct objc_protocol_t { 3665 uint32_t isa; /* struct objc_class * (32-bit pointer) */ 3666 uint32_t protocol_name; /* char * (32-bit pointer) */ 3667 uint32_t protocol_list; /* struct objc_protocol_list * (32-bit pointer) */ 3668 uint32_t instance_methods; /* struct objc_method_description_list * 3669 (32-bit pointer) */ 3670 uint32_t class_methods; /* struct objc_method_description_list * 3671 (32-bit pointer) */ 3672 }; 3673 3674 struct objc_method_description_list_t { 3675 int32_t count; 3676 // struct objc_method_description_t list[1]; 3677 }; 3678 3679 struct objc_method_description_t { 3680 uint32_t name; /* SEL, aka struct objc_selector * (32-bit pointer) */ 3681 uint32_t types; /* char * (32-bit pointer) */ 3682 }; 3683 3684 inline void swapStruct(struct cfstring64_t &cfs) { 3685 sys::swapByteOrder(cfs.isa); 3686 sys::swapByteOrder(cfs.flags); 3687 sys::swapByteOrder(cfs.characters); 3688 sys::swapByteOrder(cfs.length); 3689 } 3690 3691 inline void swapStruct(struct class64_t &c) { 3692 sys::swapByteOrder(c.isa); 3693 sys::swapByteOrder(c.superclass); 3694 sys::swapByteOrder(c.cache); 3695 sys::swapByteOrder(c.vtable); 3696 sys::swapByteOrder(c.data); 3697 } 3698 3699 inline void swapStruct(struct class32_t &c) { 3700 sys::swapByteOrder(c.isa); 3701 sys::swapByteOrder(c.superclass); 3702 sys::swapByteOrder(c.cache); 3703 sys::swapByteOrder(c.vtable); 3704 sys::swapByteOrder(c.data); 3705 } 3706 3707 inline void swapStruct(struct class_ro64_t &cro) { 3708 sys::swapByteOrder(cro.flags); 3709 sys::swapByteOrder(cro.instanceStart); 3710 sys::swapByteOrder(cro.instanceSize); 3711 sys::swapByteOrder(cro.reserved); 3712 sys::swapByteOrder(cro.ivarLayout); 3713 sys::swapByteOrder(cro.name); 3714 sys::swapByteOrder(cro.baseMethods); 3715 sys::swapByteOrder(cro.baseProtocols); 3716 sys::swapByteOrder(cro.ivars); 3717 sys::swapByteOrder(cro.weakIvarLayout); 3718 sys::swapByteOrder(cro.baseProperties); 3719 } 3720 3721 inline void swapStruct(struct class_ro32_t &cro) { 3722 sys::swapByteOrder(cro.flags); 3723 sys::swapByteOrder(cro.instanceStart); 3724 sys::swapByteOrder(cro.instanceSize); 3725 sys::swapByteOrder(cro.ivarLayout); 3726 sys::swapByteOrder(cro.name); 3727 sys::swapByteOrder(cro.baseMethods); 3728 sys::swapByteOrder(cro.baseProtocols); 3729 sys::swapByteOrder(cro.ivars); 3730 sys::swapByteOrder(cro.weakIvarLayout); 3731 sys::swapByteOrder(cro.baseProperties); 3732 } 3733 3734 inline void swapStruct(struct method_list64_t &ml) { 3735 sys::swapByteOrder(ml.entsize); 3736 sys::swapByteOrder(ml.count); 3737 } 3738 3739 inline void swapStruct(struct method_list32_t &ml) { 3740 sys::swapByteOrder(ml.entsize); 3741 sys::swapByteOrder(ml.count); 3742 } 3743 3744 inline void swapStruct(struct method64_t &m) { 3745 sys::swapByteOrder(m.name); 3746 sys::swapByteOrder(m.types); 3747 sys::swapByteOrder(m.imp); 3748 } 3749 3750 inline void swapStruct(struct method32_t &m) { 3751 sys::swapByteOrder(m.name); 3752 sys::swapByteOrder(m.types); 3753 sys::swapByteOrder(m.imp); 3754 } 3755 3756 inline void swapStruct(struct protocol_list64_t &pl) { 3757 sys::swapByteOrder(pl.count); 3758 } 3759 3760 inline void swapStruct(struct protocol_list32_t &pl) { 3761 sys::swapByteOrder(pl.count); 3762 } 3763 3764 inline void swapStruct(struct protocol64_t &p) { 3765 sys::swapByteOrder(p.isa); 3766 sys::swapByteOrder(p.name); 3767 sys::swapByteOrder(p.protocols); 3768 sys::swapByteOrder(p.instanceMethods); 3769 sys::swapByteOrder(p.classMethods); 3770 sys::swapByteOrder(p.optionalInstanceMethods); 3771 sys::swapByteOrder(p.optionalClassMethods); 3772 sys::swapByteOrder(p.instanceProperties); 3773 } 3774 3775 inline void swapStruct(struct protocol32_t &p) { 3776 sys::swapByteOrder(p.isa); 3777 sys::swapByteOrder(p.name); 3778 sys::swapByteOrder(p.protocols); 3779 sys::swapByteOrder(p.instanceMethods); 3780 sys::swapByteOrder(p.classMethods); 3781 sys::swapByteOrder(p.optionalInstanceMethods); 3782 sys::swapByteOrder(p.optionalClassMethods); 3783 sys::swapByteOrder(p.instanceProperties); 3784 } 3785 3786 inline void swapStruct(struct ivar_list64_t &il) { 3787 sys::swapByteOrder(il.entsize); 3788 sys::swapByteOrder(il.count); 3789 } 3790 3791 inline void swapStruct(struct ivar_list32_t &il) { 3792 sys::swapByteOrder(il.entsize); 3793 sys::swapByteOrder(il.count); 3794 } 3795 3796 inline void swapStruct(struct ivar64_t &i) { 3797 sys::swapByteOrder(i.offset); 3798 sys::swapByteOrder(i.name); 3799 sys::swapByteOrder(i.type); 3800 sys::swapByteOrder(i.alignment); 3801 sys::swapByteOrder(i.size); 3802 } 3803 3804 inline void swapStruct(struct ivar32_t &i) { 3805 sys::swapByteOrder(i.offset); 3806 sys::swapByteOrder(i.name); 3807 sys::swapByteOrder(i.type); 3808 sys::swapByteOrder(i.alignment); 3809 sys::swapByteOrder(i.size); 3810 } 3811 3812 inline void swapStruct(struct objc_property_list64 &pl) { 3813 sys::swapByteOrder(pl.entsize); 3814 sys::swapByteOrder(pl.count); 3815 } 3816 3817 inline void swapStruct(struct objc_property_list32 &pl) { 3818 sys::swapByteOrder(pl.entsize); 3819 sys::swapByteOrder(pl.count); 3820 } 3821 3822 inline void swapStruct(struct objc_property64 &op) { 3823 sys::swapByteOrder(op.name); 3824 sys::swapByteOrder(op.attributes); 3825 } 3826 3827 inline void swapStruct(struct objc_property32 &op) { 3828 sys::swapByteOrder(op.name); 3829 sys::swapByteOrder(op.attributes); 3830 } 3831 3832 inline void swapStruct(struct category64_t &c) { 3833 sys::swapByteOrder(c.name); 3834 sys::swapByteOrder(c.cls); 3835 sys::swapByteOrder(c.instanceMethods); 3836 sys::swapByteOrder(c.classMethods); 3837 sys::swapByteOrder(c.protocols); 3838 sys::swapByteOrder(c.instanceProperties); 3839 } 3840 3841 inline void swapStruct(struct category32_t &c) { 3842 sys::swapByteOrder(c.name); 3843 sys::swapByteOrder(c.cls); 3844 sys::swapByteOrder(c.instanceMethods); 3845 sys::swapByteOrder(c.classMethods); 3846 sys::swapByteOrder(c.protocols); 3847 sys::swapByteOrder(c.instanceProperties); 3848 } 3849 3850 inline void swapStruct(struct objc_image_info64 &o) { 3851 sys::swapByteOrder(o.version); 3852 sys::swapByteOrder(o.flags); 3853 } 3854 3855 inline void swapStruct(struct objc_image_info32 &o) { 3856 sys::swapByteOrder(o.version); 3857 sys::swapByteOrder(o.flags); 3858 } 3859 3860 inline void swapStruct(struct imageInfo_t &o) { 3861 sys::swapByteOrder(o.version); 3862 sys::swapByteOrder(o.flags); 3863 } 3864 3865 inline void swapStruct(struct message_ref64 &mr) { 3866 sys::swapByteOrder(mr.imp); 3867 sys::swapByteOrder(mr.sel); 3868 } 3869 3870 inline void swapStruct(struct message_ref32 &mr) { 3871 sys::swapByteOrder(mr.imp); 3872 sys::swapByteOrder(mr.sel); 3873 } 3874 3875 inline void swapStruct(struct objc_module_t &module) { 3876 sys::swapByteOrder(module.version); 3877 sys::swapByteOrder(module.size); 3878 sys::swapByteOrder(module.name); 3879 sys::swapByteOrder(module.symtab); 3880 } 3881 3882 inline void swapStruct(struct objc_symtab_t &symtab) { 3883 sys::swapByteOrder(symtab.sel_ref_cnt); 3884 sys::swapByteOrder(symtab.refs); 3885 sys::swapByteOrder(symtab.cls_def_cnt); 3886 sys::swapByteOrder(symtab.cat_def_cnt); 3887 } 3888 3889 inline void swapStruct(struct objc_class_t &objc_class) { 3890 sys::swapByteOrder(objc_class.isa); 3891 sys::swapByteOrder(objc_class.super_class); 3892 sys::swapByteOrder(objc_class.name); 3893 sys::swapByteOrder(objc_class.version); 3894 sys::swapByteOrder(objc_class.info); 3895 sys::swapByteOrder(objc_class.instance_size); 3896 sys::swapByteOrder(objc_class.ivars); 3897 sys::swapByteOrder(objc_class.methodLists); 3898 sys::swapByteOrder(objc_class.cache); 3899 sys::swapByteOrder(objc_class.protocols); 3900 } 3901 3902 inline void swapStruct(struct objc_category_t &objc_category) { 3903 sys::swapByteOrder(objc_category.category_name); 3904 sys::swapByteOrder(objc_category.class_name); 3905 sys::swapByteOrder(objc_category.instance_methods); 3906 sys::swapByteOrder(objc_category.class_methods); 3907 sys::swapByteOrder(objc_category.protocols); 3908 } 3909 3910 inline void swapStruct(struct objc_ivar_list_t &objc_ivar_list) { 3911 sys::swapByteOrder(objc_ivar_list.ivar_count); 3912 } 3913 3914 inline void swapStruct(struct objc_ivar_t &objc_ivar) { 3915 sys::swapByteOrder(objc_ivar.ivar_name); 3916 sys::swapByteOrder(objc_ivar.ivar_type); 3917 sys::swapByteOrder(objc_ivar.ivar_offset); 3918 } 3919 3920 inline void swapStruct(struct objc_method_list_t &method_list) { 3921 sys::swapByteOrder(method_list.obsolete); 3922 sys::swapByteOrder(method_list.method_count); 3923 } 3924 3925 inline void swapStruct(struct objc_method_t &method) { 3926 sys::swapByteOrder(method.method_name); 3927 sys::swapByteOrder(method.method_types); 3928 sys::swapByteOrder(method.method_imp); 3929 } 3930 3931 inline void swapStruct(struct objc_protocol_list_t &protocol_list) { 3932 sys::swapByteOrder(protocol_list.next); 3933 sys::swapByteOrder(protocol_list.count); 3934 } 3935 3936 inline void swapStruct(struct objc_protocol_t &protocol) { 3937 sys::swapByteOrder(protocol.isa); 3938 sys::swapByteOrder(protocol.protocol_name); 3939 sys::swapByteOrder(protocol.protocol_list); 3940 sys::swapByteOrder(protocol.instance_methods); 3941 sys::swapByteOrder(protocol.class_methods); 3942 } 3943 3944 inline void swapStruct(struct objc_method_description_list_t &mdl) { 3945 sys::swapByteOrder(mdl.count); 3946 } 3947 3948 inline void swapStruct(struct objc_method_description_t &md) { 3949 sys::swapByteOrder(md.name); 3950 sys::swapByteOrder(md.types); 3951 } 3952 3953 } // namespace 3954 3955 static const char *get_dyld_bind_info_symbolname(uint64_t ReferenceValue, 3956 struct DisassembleInfo *info); 3957 3958 // get_objc2_64bit_class_name() is used for disassembly and is passed a pointer 3959 // to an Objective-C class and returns the class name. It is also passed the 3960 // address of the pointer, so when the pointer is zero as it can be in an .o 3961 // file, that is used to look for an external relocation entry with a symbol 3962 // name. 3963 static const char *get_objc2_64bit_class_name(uint64_t pointer_value, 3964 uint64_t ReferenceValue, 3965 struct DisassembleInfo *info) { 3966 const char *r; 3967 uint32_t offset, left; 3968 SectionRef S; 3969 3970 // The pointer_value can be 0 in an object file and have a relocation 3971 // entry for the class symbol at the ReferenceValue (the address of the 3972 // pointer). 3973 if (pointer_value == 0) { 3974 r = get_pointer_64(ReferenceValue, offset, left, S, info); 3975 if (r == nullptr || left < sizeof(uint64_t)) 3976 return nullptr; 3977 uint64_t n_value; 3978 const char *symbol_name = get_symbol_64(offset, S, info, n_value); 3979 if (symbol_name == nullptr) 3980 return nullptr; 3981 const char *class_name = strrchr(symbol_name, '$'); 3982 if (class_name != nullptr && class_name[1] == '_' && class_name[2] != '\0') 3983 return class_name + 2; 3984 else 3985 return nullptr; 3986 } 3987 3988 // The case were the pointer_value is non-zero and points to a class defined 3989 // in this Mach-O file. 3990 r = get_pointer_64(pointer_value, offset, left, S, info); 3991 if (r == nullptr || left < sizeof(struct class64_t)) 3992 return nullptr; 3993 struct class64_t c; 3994 memcpy(&c, r, sizeof(struct class64_t)); 3995 if (info->O->isLittleEndian() != sys::IsLittleEndianHost) 3996 swapStruct(c); 3997 if (c.data == 0) 3998 return nullptr; 3999 r = get_pointer_64(c.data, offset, left, S, info); 4000 if (r == nullptr || left < sizeof(struct class_ro64_t)) 4001 return nullptr; 4002 struct class_ro64_t cro; 4003 memcpy(&cro, r, sizeof(struct class_ro64_t)); 4004 if (info->O->isLittleEndian() != sys::IsLittleEndianHost) 4005 swapStruct(cro); 4006 if (cro.name == 0) 4007 return nullptr; 4008 const char *name = get_pointer_64(cro.name, offset, left, S, info); 4009 return name; 4010 } 4011 4012 // get_objc2_64bit_cfstring_name is used for disassembly and is passed a 4013 // pointer to a cfstring and returns its name or nullptr. 4014 static const char *get_objc2_64bit_cfstring_name(uint64_t ReferenceValue, 4015 struct DisassembleInfo *info) { 4016 const char *r, *name; 4017 uint32_t offset, left; 4018 SectionRef S; 4019 struct cfstring64_t cfs; 4020 uint64_t cfs_characters; 4021 4022 r = get_pointer_64(ReferenceValue, offset, left, S, info); 4023 if (r == nullptr || left < sizeof(struct cfstring64_t)) 4024 return nullptr; 4025 memcpy(&cfs, r, sizeof(struct cfstring64_t)); 4026 if (info->O->isLittleEndian() != sys::IsLittleEndianHost) 4027 swapStruct(cfs); 4028 if (cfs.characters == 0) { 4029 uint64_t n_value; 4030 const char *symbol_name = get_symbol_64( 4031 offset + offsetof(struct cfstring64_t, characters), S, info, n_value); 4032 if (symbol_name == nullptr) 4033 return nullptr; 4034 cfs_characters = n_value; 4035 } else 4036 cfs_characters = cfs.characters; 4037 name = get_pointer_64(cfs_characters, offset, left, S, info); 4038 4039 return name; 4040 } 4041 4042 // get_objc2_64bit_selref() is used for disassembly and is passed a the address 4043 // of a pointer to an Objective-C selector reference when the pointer value is 4044 // zero as in a .o file and is likely to have a external relocation entry with 4045 // who's symbol's n_value is the real pointer to the selector name. If that is 4046 // the case the real pointer to the selector name is returned else 0 is 4047 // returned 4048 static uint64_t get_objc2_64bit_selref(uint64_t ReferenceValue, 4049 struct DisassembleInfo *info) { 4050 uint32_t offset, left; 4051 SectionRef S; 4052 4053 const char *r = get_pointer_64(ReferenceValue, offset, left, S, info); 4054 if (r == nullptr || left < sizeof(uint64_t)) 4055 return 0; 4056 uint64_t n_value; 4057 const char *symbol_name = get_symbol_64(offset, S, info, n_value); 4058 if (symbol_name == nullptr) 4059 return 0; 4060 return n_value; 4061 } 4062 4063 static const SectionRef get_section(MachOObjectFile *O, const char *segname, 4064 const char *sectname) { 4065 for (const SectionRef &Section : O->sections()) { 4066 StringRef SectName; 4067 Expected<StringRef> SecNameOrErr = Section.getName(); 4068 if (SecNameOrErr) 4069 SectName = *SecNameOrErr; 4070 else 4071 consumeError(SecNameOrErr.takeError()); 4072 4073 DataRefImpl Ref = Section.getRawDataRefImpl(); 4074 StringRef SegName = O->getSectionFinalSegmentName(Ref); 4075 if (SegName == segname && SectName == sectname) 4076 return Section; 4077 } 4078 return SectionRef(); 4079 } 4080 4081 static void 4082 walk_pointer_list_64(const char *listname, const SectionRef S, 4083 MachOObjectFile *O, struct DisassembleInfo *info, 4084 void (*func)(uint64_t, struct DisassembleInfo *info)) { 4085 if (S == SectionRef()) 4086 return; 4087 4088 StringRef SectName; 4089 Expected<StringRef> SecNameOrErr = S.getName(); 4090 if (SecNameOrErr) 4091 SectName = *SecNameOrErr; 4092 else 4093 consumeError(SecNameOrErr.takeError()); 4094 4095 DataRefImpl Ref = S.getRawDataRefImpl(); 4096 StringRef SegName = O->getSectionFinalSegmentName(Ref); 4097 outs() << "Contents of (" << SegName << "," << SectName << ") section\n"; 4098 4099 StringRef BytesStr = unwrapOrError(S.getContents(), O->getFileName()); 4100 const char *Contents = reinterpret_cast<const char *>(BytesStr.data()); 4101 4102 for (uint32_t i = 0; i < S.getSize(); i += sizeof(uint64_t)) { 4103 uint32_t left = S.getSize() - i; 4104 uint32_t size = left < sizeof(uint64_t) ? left : sizeof(uint64_t); 4105 uint64_t p = 0; 4106 memcpy(&p, Contents + i, size); 4107 if (i + sizeof(uint64_t) > S.getSize()) 4108 outs() << listname << " list pointer extends past end of (" << SegName 4109 << "," << SectName << ") section\n"; 4110 outs() << format("%016" PRIx64, S.getAddress() + i) << " "; 4111 4112 if (O->isLittleEndian() != sys::IsLittleEndianHost) 4113 sys::swapByteOrder(p); 4114 4115 uint64_t n_value = 0; 4116 const char *name = get_symbol_64(i, S, info, n_value, p); 4117 if (name == nullptr) 4118 name = get_dyld_bind_info_symbolname(S.getAddress() + i, info); 4119 4120 if (n_value != 0) { 4121 outs() << format("0x%" PRIx64, n_value); 4122 if (p != 0) 4123 outs() << " + " << format("0x%" PRIx64, p); 4124 } else 4125 outs() << format("0x%" PRIx64, p); 4126 if (name != nullptr) 4127 outs() << " " << name; 4128 outs() << "\n"; 4129 4130 p += n_value; 4131 if (func) 4132 func(p, info); 4133 } 4134 } 4135 4136 static void 4137 walk_pointer_list_32(const char *listname, const SectionRef S, 4138 MachOObjectFile *O, struct DisassembleInfo *info, 4139 void (*func)(uint32_t, struct DisassembleInfo *info)) { 4140 if (S == SectionRef()) 4141 return; 4142 4143 StringRef SectName = unwrapOrError(S.getName(), O->getFileName()); 4144 DataRefImpl Ref = S.getRawDataRefImpl(); 4145 StringRef SegName = O->getSectionFinalSegmentName(Ref); 4146 outs() << "Contents of (" << SegName << "," << SectName << ") section\n"; 4147 4148 StringRef BytesStr = unwrapOrError(S.getContents(), O->getFileName()); 4149 const char *Contents = reinterpret_cast<const char *>(BytesStr.data()); 4150 4151 for (uint32_t i = 0; i < S.getSize(); i += sizeof(uint32_t)) { 4152 uint32_t left = S.getSize() - i; 4153 uint32_t size = left < sizeof(uint32_t) ? left : sizeof(uint32_t); 4154 uint32_t p = 0; 4155 memcpy(&p, Contents + i, size); 4156 if (i + sizeof(uint32_t) > S.getSize()) 4157 outs() << listname << " list pointer extends past end of (" << SegName 4158 << "," << SectName << ") section\n"; 4159 uint32_t Address = S.getAddress() + i; 4160 outs() << format("%08" PRIx32, Address) << " "; 4161 4162 if (O->isLittleEndian() != sys::IsLittleEndianHost) 4163 sys::swapByteOrder(p); 4164 outs() << format("0x%" PRIx32, p); 4165 4166 const char *name = get_symbol_32(i, S, info, p); 4167 if (name != nullptr) 4168 outs() << " " << name; 4169 outs() << "\n"; 4170 4171 if (func) 4172 func(p, info); 4173 } 4174 } 4175 4176 static void print_layout_map(const char *layout_map, uint32_t left) { 4177 if (layout_map == nullptr) 4178 return; 4179 outs() << " layout map: "; 4180 do { 4181 outs() << format("0x%02" PRIx32, (*layout_map) & 0xff) << " "; 4182 left--; 4183 layout_map++; 4184 } while (*layout_map != '\0' && left != 0); 4185 outs() << "\n"; 4186 } 4187 4188 static void print_layout_map64(uint64_t p, struct DisassembleInfo *info) { 4189 uint32_t offset, left; 4190 SectionRef S; 4191 const char *layout_map; 4192 4193 if (p == 0) 4194 return; 4195 layout_map = get_pointer_64(p, offset, left, S, info); 4196 print_layout_map(layout_map, left); 4197 } 4198 4199 static void print_layout_map32(uint32_t p, struct DisassembleInfo *info) { 4200 uint32_t offset, left; 4201 SectionRef S; 4202 const char *layout_map; 4203 4204 if (p == 0) 4205 return; 4206 layout_map = get_pointer_32(p, offset, left, S, info); 4207 print_layout_map(layout_map, left); 4208 } 4209 4210 static void print_method_list64_t(uint64_t p, struct DisassembleInfo *info, 4211 const char *indent) { 4212 struct method_list64_t ml; 4213 struct method64_t m; 4214 const char *r; 4215 uint32_t offset, xoffset, left, i; 4216 SectionRef S, xS; 4217 const char *name, *sym_name; 4218 uint64_t n_value; 4219 4220 r = get_pointer_64(p, offset, left, S, info); 4221 if (r == nullptr) 4222 return; 4223 memset(&ml, '\0', sizeof(struct method_list64_t)); 4224 if (left < sizeof(struct method_list64_t)) { 4225 memcpy(&ml, r, left); 4226 outs() << " (method_list_t entends past the end of the section)\n"; 4227 } else 4228 memcpy(&ml, r, sizeof(struct method_list64_t)); 4229 if (info->O->isLittleEndian() != sys::IsLittleEndianHost) 4230 swapStruct(ml); 4231 outs() << indent << "\t\t entsize " << ml.entsize << "\n"; 4232 outs() << indent << "\t\t count " << ml.count << "\n"; 4233 4234 p += sizeof(struct method_list64_t); 4235 offset += sizeof(struct method_list64_t); 4236 for (i = 0; i < ml.count; i++) { 4237 r = get_pointer_64(p, offset, left, S, info); 4238 if (r == nullptr) 4239 return; 4240 memset(&m, '\0', sizeof(struct method64_t)); 4241 if (left < sizeof(struct method64_t)) { 4242 memcpy(&m, r, left); 4243 outs() << indent << " (method_t extends past the end of the section)\n"; 4244 } else 4245 memcpy(&m, r, sizeof(struct method64_t)); 4246 if (info->O->isLittleEndian() != sys::IsLittleEndianHost) 4247 swapStruct(m); 4248 4249 outs() << indent << "\t\t name "; 4250 sym_name = get_symbol_64(offset + offsetof(struct method64_t, name), S, 4251 info, n_value, m.name); 4252 if (n_value != 0) { 4253 if (info->verbose && sym_name != nullptr) 4254 outs() << sym_name; 4255 else 4256 outs() << format("0x%" PRIx64, n_value); 4257 if (m.name != 0) 4258 outs() << " + " << format("0x%" PRIx64, m.name); 4259 } else 4260 outs() << format("0x%" PRIx64, m.name); 4261 name = get_pointer_64(m.name + n_value, xoffset, left, xS, info); 4262 if (name != nullptr) 4263 outs() << format(" %.*s", left, name); 4264 outs() << "\n"; 4265 4266 outs() << indent << "\t\t types "; 4267 sym_name = get_symbol_64(offset + offsetof(struct method64_t, types), S, 4268 info, n_value, m.types); 4269 if (n_value != 0) { 4270 if (info->verbose && sym_name != nullptr) 4271 outs() << sym_name; 4272 else 4273 outs() << format("0x%" PRIx64, n_value); 4274 if (m.types != 0) 4275 outs() << " + " << format("0x%" PRIx64, m.types); 4276 } else 4277 outs() << format("0x%" PRIx64, m.types); 4278 name = get_pointer_64(m.types + n_value, xoffset, left, xS, info); 4279 if (name != nullptr) 4280 outs() << format(" %.*s", left, name); 4281 outs() << "\n"; 4282 4283 outs() << indent << "\t\t imp "; 4284 name = get_symbol_64(offset + offsetof(struct method64_t, imp), S, info, 4285 n_value, m.imp); 4286 if (info->verbose && name == nullptr) { 4287 if (n_value != 0) { 4288 outs() << format("0x%" PRIx64, n_value) << " "; 4289 if (m.imp != 0) 4290 outs() << "+ " << format("0x%" PRIx64, m.imp) << " "; 4291 } else 4292 outs() << format("0x%" PRIx64, m.imp) << " "; 4293 } 4294 if (name != nullptr) 4295 outs() << name; 4296 outs() << "\n"; 4297 4298 p += sizeof(struct method64_t); 4299 offset += sizeof(struct method64_t); 4300 } 4301 } 4302 4303 static void print_method_list32_t(uint64_t p, struct DisassembleInfo *info, 4304 const char *indent) { 4305 struct method_list32_t ml; 4306 struct method32_t m; 4307 const char *r, *name; 4308 uint32_t offset, xoffset, left, i; 4309 SectionRef S, xS; 4310 4311 r = get_pointer_32(p, offset, left, S, info); 4312 if (r == nullptr) 4313 return; 4314 memset(&ml, '\0', sizeof(struct method_list32_t)); 4315 if (left < sizeof(struct method_list32_t)) { 4316 memcpy(&ml, r, left); 4317 outs() << " (method_list_t entends past the end of the section)\n"; 4318 } else 4319 memcpy(&ml, r, sizeof(struct method_list32_t)); 4320 if (info->O->isLittleEndian() != sys::IsLittleEndianHost) 4321 swapStruct(ml); 4322 outs() << indent << "\t\t entsize " << ml.entsize << "\n"; 4323 outs() << indent << "\t\t count " << ml.count << "\n"; 4324 4325 p += sizeof(struct method_list32_t); 4326 offset += sizeof(struct method_list32_t); 4327 for (i = 0; i < ml.count; i++) { 4328 r = get_pointer_32(p, offset, left, S, info); 4329 if (r == nullptr) 4330 return; 4331 memset(&m, '\0', sizeof(struct method32_t)); 4332 if (left < sizeof(struct method32_t)) { 4333 memcpy(&ml, r, left); 4334 outs() << indent << " (method_t entends past the end of the section)\n"; 4335 } else 4336 memcpy(&m, r, sizeof(struct method32_t)); 4337 if (info->O->isLittleEndian() != sys::IsLittleEndianHost) 4338 swapStruct(m); 4339 4340 outs() << indent << "\t\t name " << format("0x%" PRIx32, m.name); 4341 name = get_pointer_32(m.name, xoffset, left, xS, info); 4342 if (name != nullptr) 4343 outs() << format(" %.*s", left, name); 4344 outs() << "\n"; 4345 4346 outs() << indent << "\t\t types " << format("0x%" PRIx32, m.types); 4347 name = get_pointer_32(m.types, xoffset, left, xS, info); 4348 if (name != nullptr) 4349 outs() << format(" %.*s", left, name); 4350 outs() << "\n"; 4351 4352 outs() << indent << "\t\t imp " << format("0x%" PRIx32, m.imp); 4353 name = get_symbol_32(offset + offsetof(struct method32_t, imp), S, info, 4354 m.imp); 4355 if (name != nullptr) 4356 outs() << " " << name; 4357 outs() << "\n"; 4358 4359 p += sizeof(struct method32_t); 4360 offset += sizeof(struct method32_t); 4361 } 4362 } 4363 4364 static bool print_method_list(uint32_t p, struct DisassembleInfo *info) { 4365 uint32_t offset, left, xleft; 4366 SectionRef S; 4367 struct objc_method_list_t method_list; 4368 struct objc_method_t method; 4369 const char *r, *methods, *name, *SymbolName; 4370 int32_t i; 4371 4372 r = get_pointer_32(p, offset, left, S, info, true); 4373 if (r == nullptr) 4374 return true; 4375 4376 outs() << "\n"; 4377 if (left > sizeof(struct objc_method_list_t)) { 4378 memcpy(&method_list, r, sizeof(struct objc_method_list_t)); 4379 } else { 4380 outs() << "\t\t objc_method_list extends past end of the section\n"; 4381 memset(&method_list, '\0', sizeof(struct objc_method_list_t)); 4382 memcpy(&method_list, r, left); 4383 } 4384 if (info->O->isLittleEndian() != sys::IsLittleEndianHost) 4385 swapStruct(method_list); 4386 4387 outs() << "\t\t obsolete " 4388 << format("0x%08" PRIx32, method_list.obsolete) << "\n"; 4389 outs() << "\t\t method_count " << method_list.method_count << "\n"; 4390 4391 methods = r + sizeof(struct objc_method_list_t); 4392 for (i = 0; i < method_list.method_count; i++) { 4393 if ((i + 1) * sizeof(struct objc_method_t) > left) { 4394 outs() << "\t\t remaining method's extend past the of the section\n"; 4395 break; 4396 } 4397 memcpy(&method, methods + i * sizeof(struct objc_method_t), 4398 sizeof(struct objc_method_t)); 4399 if (info->O->isLittleEndian() != sys::IsLittleEndianHost) 4400 swapStruct(method); 4401 4402 outs() << "\t\t method_name " 4403 << format("0x%08" PRIx32, method.method_name); 4404 if (info->verbose) { 4405 name = get_pointer_32(method.method_name, offset, xleft, S, info, true); 4406 if (name != nullptr) 4407 outs() << format(" %.*s", xleft, name); 4408 else 4409 outs() << " (not in an __OBJC section)"; 4410 } 4411 outs() << "\n"; 4412 4413 outs() << "\t\t method_types " 4414 << format("0x%08" PRIx32, method.method_types); 4415 if (info->verbose) { 4416 name = get_pointer_32(method.method_types, offset, xleft, S, info, true); 4417 if (name != nullptr) 4418 outs() << format(" %.*s", xleft, name); 4419 else 4420 outs() << " (not in an __OBJC section)"; 4421 } 4422 outs() << "\n"; 4423 4424 outs() << "\t\t method_imp " 4425 << format("0x%08" PRIx32, method.method_imp) << " "; 4426 if (info->verbose) { 4427 SymbolName = GuessSymbolName(method.method_imp, info->AddrMap); 4428 if (SymbolName != nullptr) 4429 outs() << SymbolName; 4430 } 4431 outs() << "\n"; 4432 } 4433 return false; 4434 } 4435 4436 static void print_protocol_list64_t(uint64_t p, struct DisassembleInfo *info) { 4437 struct protocol_list64_t pl; 4438 uint64_t q, n_value; 4439 struct protocol64_t pc; 4440 const char *r; 4441 uint32_t offset, xoffset, left, i; 4442 SectionRef S, xS; 4443 const char *name, *sym_name; 4444 4445 r = get_pointer_64(p, offset, left, S, info); 4446 if (r == nullptr) 4447 return; 4448 memset(&pl, '\0', sizeof(struct protocol_list64_t)); 4449 if (left < sizeof(struct protocol_list64_t)) { 4450 memcpy(&pl, r, left); 4451 outs() << " (protocol_list_t entends past the end of the section)\n"; 4452 } else 4453 memcpy(&pl, r, sizeof(struct protocol_list64_t)); 4454 if (info->O->isLittleEndian() != sys::IsLittleEndianHost) 4455 swapStruct(pl); 4456 outs() << " count " << pl.count << "\n"; 4457 4458 p += sizeof(struct protocol_list64_t); 4459 offset += sizeof(struct protocol_list64_t); 4460 for (i = 0; i < pl.count; i++) { 4461 r = get_pointer_64(p, offset, left, S, info); 4462 if (r == nullptr) 4463 return; 4464 q = 0; 4465 if (left < sizeof(uint64_t)) { 4466 memcpy(&q, r, left); 4467 outs() << " (protocol_t * entends past the end of the section)\n"; 4468 } else 4469 memcpy(&q, r, sizeof(uint64_t)); 4470 if (info->O->isLittleEndian() != sys::IsLittleEndianHost) 4471 sys::swapByteOrder(q); 4472 4473 outs() << "\t\t list[" << i << "] "; 4474 sym_name = get_symbol_64(offset, S, info, n_value, q); 4475 if (n_value != 0) { 4476 if (info->verbose && sym_name != nullptr) 4477 outs() << sym_name; 4478 else 4479 outs() << format("0x%" PRIx64, n_value); 4480 if (q != 0) 4481 outs() << " + " << format("0x%" PRIx64, q); 4482 } else 4483 outs() << format("0x%" PRIx64, q); 4484 outs() << " (struct protocol_t *)\n"; 4485 4486 r = get_pointer_64(q + n_value, offset, left, S, info); 4487 if (r == nullptr) 4488 return; 4489 memset(&pc, '\0', sizeof(struct protocol64_t)); 4490 if (left < sizeof(struct protocol64_t)) { 4491 memcpy(&pc, r, left); 4492 outs() << " (protocol_t entends past the end of the section)\n"; 4493 } else 4494 memcpy(&pc, r, sizeof(struct protocol64_t)); 4495 if (info->O->isLittleEndian() != sys::IsLittleEndianHost) 4496 swapStruct(pc); 4497 4498 outs() << "\t\t\t isa " << format("0x%" PRIx64, pc.isa) << "\n"; 4499 4500 outs() << "\t\t\t name "; 4501 sym_name = get_symbol_64(offset + offsetof(struct protocol64_t, name), S, 4502 info, n_value, pc.name); 4503 if (n_value != 0) { 4504 if (info->verbose && sym_name != nullptr) 4505 outs() << sym_name; 4506 else 4507 outs() << format("0x%" PRIx64, n_value); 4508 if (pc.name != 0) 4509 outs() << " + " << format("0x%" PRIx64, pc.name); 4510 } else 4511 outs() << format("0x%" PRIx64, pc.name); 4512 name = get_pointer_64(pc.name + n_value, xoffset, left, xS, info); 4513 if (name != nullptr) 4514 outs() << format(" %.*s", left, name); 4515 outs() << "\n"; 4516 4517 outs() << "\t\t\tprotocols " << format("0x%" PRIx64, pc.protocols) << "\n"; 4518 4519 outs() << "\t\t instanceMethods "; 4520 sym_name = 4521 get_symbol_64(offset + offsetof(struct protocol64_t, instanceMethods), 4522 S, info, n_value, pc.instanceMethods); 4523 if (n_value != 0) { 4524 if (info->verbose && sym_name != nullptr) 4525 outs() << sym_name; 4526 else 4527 outs() << format("0x%" PRIx64, n_value); 4528 if (pc.instanceMethods != 0) 4529 outs() << " + " << format("0x%" PRIx64, pc.instanceMethods); 4530 } else 4531 outs() << format("0x%" PRIx64, pc.instanceMethods); 4532 outs() << " (struct method_list_t *)\n"; 4533 if (pc.instanceMethods + n_value != 0) 4534 print_method_list64_t(pc.instanceMethods + n_value, info, "\t"); 4535 4536 outs() << "\t\t classMethods "; 4537 sym_name = 4538 get_symbol_64(offset + offsetof(struct protocol64_t, classMethods), S, 4539 info, n_value, pc.classMethods); 4540 if (n_value != 0) { 4541 if (info->verbose && sym_name != nullptr) 4542 outs() << sym_name; 4543 else 4544 outs() << format("0x%" PRIx64, n_value); 4545 if (pc.classMethods != 0) 4546 outs() << " + " << format("0x%" PRIx64, pc.classMethods); 4547 } else 4548 outs() << format("0x%" PRIx64, pc.classMethods); 4549 outs() << " (struct method_list_t *)\n"; 4550 if (pc.classMethods + n_value != 0) 4551 print_method_list64_t(pc.classMethods + n_value, info, "\t"); 4552 4553 outs() << "\t optionalInstanceMethods " 4554 << format("0x%" PRIx64, pc.optionalInstanceMethods) << "\n"; 4555 outs() << "\t optionalClassMethods " 4556 << format("0x%" PRIx64, pc.optionalClassMethods) << "\n"; 4557 outs() << "\t instanceProperties " 4558 << format("0x%" PRIx64, pc.instanceProperties) << "\n"; 4559 4560 p += sizeof(uint64_t); 4561 offset += sizeof(uint64_t); 4562 } 4563 } 4564 4565 static void print_protocol_list32_t(uint32_t p, struct DisassembleInfo *info) { 4566 struct protocol_list32_t pl; 4567 uint32_t q; 4568 struct protocol32_t pc; 4569 const char *r; 4570 uint32_t offset, xoffset, left, i; 4571 SectionRef S, xS; 4572 const char *name; 4573 4574 r = get_pointer_32(p, offset, left, S, info); 4575 if (r == nullptr) 4576 return; 4577 memset(&pl, '\0', sizeof(struct protocol_list32_t)); 4578 if (left < sizeof(struct protocol_list32_t)) { 4579 memcpy(&pl, r, left); 4580 outs() << " (protocol_list_t entends past the end of the section)\n"; 4581 } else 4582 memcpy(&pl, r, sizeof(struct protocol_list32_t)); 4583 if (info->O->isLittleEndian() != sys::IsLittleEndianHost) 4584 swapStruct(pl); 4585 outs() << " count " << pl.count << "\n"; 4586 4587 p += sizeof(struct protocol_list32_t); 4588 offset += sizeof(struct protocol_list32_t); 4589 for (i = 0; i < pl.count; i++) { 4590 r = get_pointer_32(p, offset, left, S, info); 4591 if (r == nullptr) 4592 return; 4593 q = 0; 4594 if (left < sizeof(uint32_t)) { 4595 memcpy(&q, r, left); 4596 outs() << " (protocol_t * entends past the end of the section)\n"; 4597 } else 4598 memcpy(&q, r, sizeof(uint32_t)); 4599 if (info->O->isLittleEndian() != sys::IsLittleEndianHost) 4600 sys::swapByteOrder(q); 4601 outs() << "\t\t list[" << i << "] " << format("0x%" PRIx32, q) 4602 << " (struct protocol_t *)\n"; 4603 r = get_pointer_32(q, offset, left, S, info); 4604 if (r == nullptr) 4605 return; 4606 memset(&pc, '\0', sizeof(struct protocol32_t)); 4607 if (left < sizeof(struct protocol32_t)) { 4608 memcpy(&pc, r, left); 4609 outs() << " (protocol_t entends past the end of the section)\n"; 4610 } else 4611 memcpy(&pc, r, sizeof(struct protocol32_t)); 4612 if (info->O->isLittleEndian() != sys::IsLittleEndianHost) 4613 swapStruct(pc); 4614 outs() << "\t\t\t isa " << format("0x%" PRIx32, pc.isa) << "\n"; 4615 outs() << "\t\t\t name " << format("0x%" PRIx32, pc.name); 4616 name = get_pointer_32(pc.name, xoffset, left, xS, info); 4617 if (name != nullptr) 4618 outs() << format(" %.*s", left, name); 4619 outs() << "\n"; 4620 outs() << "\t\t\tprotocols " << format("0x%" PRIx32, pc.protocols) << "\n"; 4621 outs() << "\t\t instanceMethods " 4622 << format("0x%" PRIx32, pc.instanceMethods) 4623 << " (struct method_list_t *)\n"; 4624 if (pc.instanceMethods != 0) 4625 print_method_list32_t(pc.instanceMethods, info, "\t"); 4626 outs() << "\t\t classMethods " << format("0x%" PRIx32, pc.classMethods) 4627 << " (struct method_list_t *)\n"; 4628 if (pc.classMethods != 0) 4629 print_method_list32_t(pc.classMethods, info, "\t"); 4630 outs() << "\t optionalInstanceMethods " 4631 << format("0x%" PRIx32, pc.optionalInstanceMethods) << "\n"; 4632 outs() << "\t optionalClassMethods " 4633 << format("0x%" PRIx32, pc.optionalClassMethods) << "\n"; 4634 outs() << "\t instanceProperties " 4635 << format("0x%" PRIx32, pc.instanceProperties) << "\n"; 4636 p += sizeof(uint32_t); 4637 offset += sizeof(uint32_t); 4638 } 4639 } 4640 4641 static void print_indent(uint32_t indent) { 4642 for (uint32_t i = 0; i < indent;) { 4643 if (indent - i >= 8) { 4644 outs() << "\t"; 4645 i += 8; 4646 } else { 4647 for (uint32_t j = i; j < indent; j++) 4648 outs() << " "; 4649 return; 4650 } 4651 } 4652 } 4653 4654 static bool print_method_description_list(uint32_t p, uint32_t indent, 4655 struct DisassembleInfo *info) { 4656 uint32_t offset, left, xleft; 4657 SectionRef S; 4658 struct objc_method_description_list_t mdl; 4659 struct objc_method_description_t md; 4660 const char *r, *list, *name; 4661 int32_t i; 4662 4663 r = get_pointer_32(p, offset, left, S, info, true); 4664 if (r == nullptr) 4665 return true; 4666 4667 outs() << "\n"; 4668 if (left > sizeof(struct objc_method_description_list_t)) { 4669 memcpy(&mdl, r, sizeof(struct objc_method_description_list_t)); 4670 } else { 4671 print_indent(indent); 4672 outs() << " objc_method_description_list extends past end of the section\n"; 4673 memset(&mdl, '\0', sizeof(struct objc_method_description_list_t)); 4674 memcpy(&mdl, r, left); 4675 } 4676 if (info->O->isLittleEndian() != sys::IsLittleEndianHost) 4677 swapStruct(mdl); 4678 4679 print_indent(indent); 4680 outs() << " count " << mdl.count << "\n"; 4681 4682 list = r + sizeof(struct objc_method_description_list_t); 4683 for (i = 0; i < mdl.count; i++) { 4684 if ((i + 1) * sizeof(struct objc_method_description_t) > left) { 4685 print_indent(indent); 4686 outs() << " remaining list entries extend past the of the section\n"; 4687 break; 4688 } 4689 print_indent(indent); 4690 outs() << " list[" << i << "]\n"; 4691 memcpy(&md, list + i * sizeof(struct objc_method_description_t), 4692 sizeof(struct objc_method_description_t)); 4693 if (info->O->isLittleEndian() != sys::IsLittleEndianHost) 4694 swapStruct(md); 4695 4696 print_indent(indent); 4697 outs() << " name " << format("0x%08" PRIx32, md.name); 4698 if (info->verbose) { 4699 name = get_pointer_32(md.name, offset, xleft, S, info, true); 4700 if (name != nullptr) 4701 outs() << format(" %.*s", xleft, name); 4702 else 4703 outs() << " (not in an __OBJC section)"; 4704 } 4705 outs() << "\n"; 4706 4707 print_indent(indent); 4708 outs() << " types " << format("0x%08" PRIx32, md.types); 4709 if (info->verbose) { 4710 name = get_pointer_32(md.types, offset, xleft, S, info, true); 4711 if (name != nullptr) 4712 outs() << format(" %.*s", xleft, name); 4713 else 4714 outs() << " (not in an __OBJC section)"; 4715 } 4716 outs() << "\n"; 4717 } 4718 return false; 4719 } 4720 4721 static bool print_protocol_list(uint32_t p, uint32_t indent, 4722 struct DisassembleInfo *info); 4723 4724 static bool print_protocol(uint32_t p, uint32_t indent, 4725 struct DisassembleInfo *info) { 4726 uint32_t offset, left; 4727 SectionRef S; 4728 struct objc_protocol_t protocol; 4729 const char *r, *name; 4730 4731 r = get_pointer_32(p, offset, left, S, info, true); 4732 if (r == nullptr) 4733 return true; 4734 4735 outs() << "\n"; 4736 if (left >= sizeof(struct objc_protocol_t)) { 4737 memcpy(&protocol, r, sizeof(struct objc_protocol_t)); 4738 } else { 4739 print_indent(indent); 4740 outs() << " Protocol extends past end of the section\n"; 4741 memset(&protocol, '\0', sizeof(struct objc_protocol_t)); 4742 memcpy(&protocol, r, left); 4743 } 4744 if (info->O->isLittleEndian() != sys::IsLittleEndianHost) 4745 swapStruct(protocol); 4746 4747 print_indent(indent); 4748 outs() << " isa " << format("0x%08" PRIx32, protocol.isa) 4749 << "\n"; 4750 4751 print_indent(indent); 4752 outs() << " protocol_name " 4753 << format("0x%08" PRIx32, protocol.protocol_name); 4754 if (info->verbose) { 4755 name = get_pointer_32(protocol.protocol_name, offset, left, S, info, true); 4756 if (name != nullptr) 4757 outs() << format(" %.*s", left, name); 4758 else 4759 outs() << " (not in an __OBJC section)"; 4760 } 4761 outs() << "\n"; 4762 4763 print_indent(indent); 4764 outs() << " protocol_list " 4765 << format("0x%08" PRIx32, protocol.protocol_list); 4766 if (print_protocol_list(protocol.protocol_list, indent + 4, info)) 4767 outs() << " (not in an __OBJC section)\n"; 4768 4769 print_indent(indent); 4770 outs() << " instance_methods " 4771 << format("0x%08" PRIx32, protocol.instance_methods); 4772 if (print_method_description_list(protocol.instance_methods, indent, info)) 4773 outs() << " (not in an __OBJC section)\n"; 4774 4775 print_indent(indent); 4776 outs() << " class_methods " 4777 << format("0x%08" PRIx32, protocol.class_methods); 4778 if (print_method_description_list(protocol.class_methods, indent, info)) 4779 outs() << " (not in an __OBJC section)\n"; 4780 4781 return false; 4782 } 4783 4784 static bool print_protocol_list(uint32_t p, uint32_t indent, 4785 struct DisassembleInfo *info) { 4786 uint32_t offset, left, l; 4787 SectionRef S; 4788 struct objc_protocol_list_t protocol_list; 4789 const char *r, *list; 4790 int32_t i; 4791 4792 r = get_pointer_32(p, offset, left, S, info, true); 4793 if (r == nullptr) 4794 return true; 4795 4796 outs() << "\n"; 4797 if (left > sizeof(struct objc_protocol_list_t)) { 4798 memcpy(&protocol_list, r, sizeof(struct objc_protocol_list_t)); 4799 } else { 4800 outs() << "\t\t objc_protocol_list_t extends past end of the section\n"; 4801 memset(&protocol_list, '\0', sizeof(struct objc_protocol_list_t)); 4802 memcpy(&protocol_list, r, left); 4803 } 4804 if (info->O->isLittleEndian() != sys::IsLittleEndianHost) 4805 swapStruct(protocol_list); 4806 4807 print_indent(indent); 4808 outs() << " next " << format("0x%08" PRIx32, protocol_list.next) 4809 << "\n"; 4810 print_indent(indent); 4811 outs() << " count " << protocol_list.count << "\n"; 4812 4813 list = r + sizeof(struct objc_protocol_list_t); 4814 for (i = 0; i < protocol_list.count; i++) { 4815 if ((i + 1) * sizeof(uint32_t) > left) { 4816 outs() << "\t\t remaining list entries extend past the of the section\n"; 4817 break; 4818 } 4819 memcpy(&l, list + i * sizeof(uint32_t), sizeof(uint32_t)); 4820 if (info->O->isLittleEndian() != sys::IsLittleEndianHost) 4821 sys::swapByteOrder(l); 4822 4823 print_indent(indent); 4824 outs() << " list[" << i << "] " << format("0x%08" PRIx32, l); 4825 if (print_protocol(l, indent, info)) 4826 outs() << "(not in an __OBJC section)\n"; 4827 } 4828 return false; 4829 } 4830 4831 static void print_ivar_list64_t(uint64_t p, struct DisassembleInfo *info) { 4832 struct ivar_list64_t il; 4833 struct ivar64_t i; 4834 const char *r; 4835 uint32_t offset, xoffset, left, j; 4836 SectionRef S, xS; 4837 const char *name, *sym_name, *ivar_offset_p; 4838 uint64_t ivar_offset, n_value; 4839 4840 r = get_pointer_64(p, offset, left, S, info); 4841 if (r == nullptr) 4842 return; 4843 memset(&il, '\0', sizeof(struct ivar_list64_t)); 4844 if (left < sizeof(struct ivar_list64_t)) { 4845 memcpy(&il, r, left); 4846 outs() << " (ivar_list_t entends past the end of the section)\n"; 4847 } else 4848 memcpy(&il, r, sizeof(struct ivar_list64_t)); 4849 if (info->O->isLittleEndian() != sys::IsLittleEndianHost) 4850 swapStruct(il); 4851 outs() << " entsize " << il.entsize << "\n"; 4852 outs() << " count " << il.count << "\n"; 4853 4854 p += sizeof(struct ivar_list64_t); 4855 offset += sizeof(struct ivar_list64_t); 4856 for (j = 0; j < il.count; j++) { 4857 r = get_pointer_64(p, offset, left, S, info); 4858 if (r == nullptr) 4859 return; 4860 memset(&i, '\0', sizeof(struct ivar64_t)); 4861 if (left < sizeof(struct ivar64_t)) { 4862 memcpy(&i, r, left); 4863 outs() << " (ivar_t entends past the end of the section)\n"; 4864 } else 4865 memcpy(&i, r, sizeof(struct ivar64_t)); 4866 if (info->O->isLittleEndian() != sys::IsLittleEndianHost) 4867 swapStruct(i); 4868 4869 outs() << "\t\t\t offset "; 4870 sym_name = get_symbol_64(offset + offsetof(struct ivar64_t, offset), S, 4871 info, n_value, i.offset); 4872 if (n_value != 0) { 4873 if (info->verbose && sym_name != nullptr) 4874 outs() << sym_name; 4875 else 4876 outs() << format("0x%" PRIx64, n_value); 4877 if (i.offset != 0) 4878 outs() << " + " << format("0x%" PRIx64, i.offset); 4879 } else 4880 outs() << format("0x%" PRIx64, i.offset); 4881 ivar_offset_p = get_pointer_64(i.offset + n_value, xoffset, left, xS, info); 4882 if (ivar_offset_p != nullptr && left >= sizeof(*ivar_offset_p)) { 4883 memcpy(&ivar_offset, ivar_offset_p, sizeof(ivar_offset)); 4884 if (info->O->isLittleEndian() != sys::IsLittleEndianHost) 4885 sys::swapByteOrder(ivar_offset); 4886 outs() << " " << ivar_offset << "\n"; 4887 } else 4888 outs() << "\n"; 4889 4890 outs() << "\t\t\t name "; 4891 sym_name = get_symbol_64(offset + offsetof(struct ivar64_t, name), S, info, 4892 n_value, i.name); 4893 if (n_value != 0) { 4894 if (info->verbose && sym_name != nullptr) 4895 outs() << sym_name; 4896 else 4897 outs() << format("0x%" PRIx64, n_value); 4898 if (i.name != 0) 4899 outs() << " + " << format("0x%" PRIx64, i.name); 4900 } else 4901 outs() << format("0x%" PRIx64, i.name); 4902 name = get_pointer_64(i.name + n_value, xoffset, left, xS, info); 4903 if (name != nullptr) 4904 outs() << format(" %.*s", left, name); 4905 outs() << "\n"; 4906 4907 outs() << "\t\t\t type "; 4908 sym_name = get_symbol_64(offset + offsetof(struct ivar64_t, type), S, info, 4909 n_value, i.name); 4910 name = get_pointer_64(i.type + n_value, xoffset, left, xS, info); 4911 if (n_value != 0) { 4912 if (info->verbose && sym_name != nullptr) 4913 outs() << sym_name; 4914 else 4915 outs() << format("0x%" PRIx64, n_value); 4916 if (i.type != 0) 4917 outs() << " + " << format("0x%" PRIx64, i.type); 4918 } else 4919 outs() << format("0x%" PRIx64, i.type); 4920 if (name != nullptr) 4921 outs() << format(" %.*s", left, name); 4922 outs() << "\n"; 4923 4924 outs() << "\t\t\talignment " << i.alignment << "\n"; 4925 outs() << "\t\t\t size " << i.size << "\n"; 4926 4927 p += sizeof(struct ivar64_t); 4928 offset += sizeof(struct ivar64_t); 4929 } 4930 } 4931 4932 static void print_ivar_list32_t(uint32_t p, struct DisassembleInfo *info) { 4933 struct ivar_list32_t il; 4934 struct ivar32_t i; 4935 const char *r; 4936 uint32_t offset, xoffset, left, j; 4937 SectionRef S, xS; 4938 const char *name, *ivar_offset_p; 4939 uint32_t ivar_offset; 4940 4941 r = get_pointer_32(p, offset, left, S, info); 4942 if (r == nullptr) 4943 return; 4944 memset(&il, '\0', sizeof(struct ivar_list32_t)); 4945 if (left < sizeof(struct ivar_list32_t)) { 4946 memcpy(&il, r, left); 4947 outs() << " (ivar_list_t entends past the end of the section)\n"; 4948 } else 4949 memcpy(&il, r, sizeof(struct ivar_list32_t)); 4950 if (info->O->isLittleEndian() != sys::IsLittleEndianHost) 4951 swapStruct(il); 4952 outs() << " entsize " << il.entsize << "\n"; 4953 outs() << " count " << il.count << "\n"; 4954 4955 p += sizeof(struct ivar_list32_t); 4956 offset += sizeof(struct ivar_list32_t); 4957 for (j = 0; j < il.count; j++) { 4958 r = get_pointer_32(p, offset, left, S, info); 4959 if (r == nullptr) 4960 return; 4961 memset(&i, '\0', sizeof(struct ivar32_t)); 4962 if (left < sizeof(struct ivar32_t)) { 4963 memcpy(&i, r, left); 4964 outs() << " (ivar_t entends past the end of the section)\n"; 4965 } else 4966 memcpy(&i, r, sizeof(struct ivar32_t)); 4967 if (info->O->isLittleEndian() != sys::IsLittleEndianHost) 4968 swapStruct(i); 4969 4970 outs() << "\t\t\t offset " << format("0x%" PRIx32, i.offset); 4971 ivar_offset_p = get_pointer_32(i.offset, xoffset, left, xS, info); 4972 if (ivar_offset_p != nullptr && left >= sizeof(*ivar_offset_p)) { 4973 memcpy(&ivar_offset, ivar_offset_p, sizeof(ivar_offset)); 4974 if (info->O->isLittleEndian() != sys::IsLittleEndianHost) 4975 sys::swapByteOrder(ivar_offset); 4976 outs() << " " << ivar_offset << "\n"; 4977 } else 4978 outs() << "\n"; 4979 4980 outs() << "\t\t\t name " << format("0x%" PRIx32, i.name); 4981 name = get_pointer_32(i.name, xoffset, left, xS, info); 4982 if (name != nullptr) 4983 outs() << format(" %.*s", left, name); 4984 outs() << "\n"; 4985 4986 outs() << "\t\t\t type " << format("0x%" PRIx32, i.type); 4987 name = get_pointer_32(i.type, xoffset, left, xS, info); 4988 if (name != nullptr) 4989 outs() << format(" %.*s", left, name); 4990 outs() << "\n"; 4991 4992 outs() << "\t\t\talignment " << i.alignment << "\n"; 4993 outs() << "\t\t\t size " << i.size << "\n"; 4994 4995 p += sizeof(struct ivar32_t); 4996 offset += sizeof(struct ivar32_t); 4997 } 4998 } 4999 5000 static void print_objc_property_list64(uint64_t p, 5001 struct DisassembleInfo *info) { 5002 struct objc_property_list64 opl; 5003 struct objc_property64 op; 5004 const char *r; 5005 uint32_t offset, xoffset, left, j; 5006 SectionRef S, xS; 5007 const char *name, *sym_name; 5008 uint64_t n_value; 5009 5010 r = get_pointer_64(p, offset, left, S, info); 5011 if (r == nullptr) 5012 return; 5013 memset(&opl, '\0', sizeof(struct objc_property_list64)); 5014 if (left < sizeof(struct objc_property_list64)) { 5015 memcpy(&opl, r, left); 5016 outs() << " (objc_property_list entends past the end of the section)\n"; 5017 } else 5018 memcpy(&opl, r, sizeof(struct objc_property_list64)); 5019 if (info->O->isLittleEndian() != sys::IsLittleEndianHost) 5020 swapStruct(opl); 5021 outs() << " entsize " << opl.entsize << "\n"; 5022 outs() << " count " << opl.count << "\n"; 5023 5024 p += sizeof(struct objc_property_list64); 5025 offset += sizeof(struct objc_property_list64); 5026 for (j = 0; j < opl.count; j++) { 5027 r = get_pointer_64(p, offset, left, S, info); 5028 if (r == nullptr) 5029 return; 5030 memset(&op, '\0', sizeof(struct objc_property64)); 5031 if (left < sizeof(struct objc_property64)) { 5032 memcpy(&op, r, left); 5033 outs() << " (objc_property entends past the end of the section)\n"; 5034 } else 5035 memcpy(&op, r, sizeof(struct objc_property64)); 5036 if (info->O->isLittleEndian() != sys::IsLittleEndianHost) 5037 swapStruct(op); 5038 5039 outs() << "\t\t\t name "; 5040 sym_name = get_symbol_64(offset + offsetof(struct objc_property64, name), S, 5041 info, n_value, op.name); 5042 if (n_value != 0) { 5043 if (info->verbose && sym_name != nullptr) 5044 outs() << sym_name; 5045 else 5046 outs() << format("0x%" PRIx64, n_value); 5047 if (op.name != 0) 5048 outs() << " + " << format("0x%" PRIx64, op.name); 5049 } else 5050 outs() << format("0x%" PRIx64, op.name); 5051 name = get_pointer_64(op.name + n_value, xoffset, left, xS, info); 5052 if (name != nullptr) 5053 outs() << format(" %.*s", left, name); 5054 outs() << "\n"; 5055 5056 outs() << "\t\t\tattributes "; 5057 sym_name = 5058 get_symbol_64(offset + offsetof(struct objc_property64, attributes), S, 5059 info, n_value, op.attributes); 5060 if (n_value != 0) { 5061 if (info->verbose && sym_name != nullptr) 5062 outs() << sym_name; 5063 else 5064 outs() << format("0x%" PRIx64, n_value); 5065 if (op.attributes != 0) 5066 outs() << " + " << format("0x%" PRIx64, op.attributes); 5067 } else 5068 outs() << format("0x%" PRIx64, op.attributes); 5069 name = get_pointer_64(op.attributes + n_value, xoffset, left, xS, info); 5070 if (name != nullptr) 5071 outs() << format(" %.*s", left, name); 5072 outs() << "\n"; 5073 5074 p += sizeof(struct objc_property64); 5075 offset += sizeof(struct objc_property64); 5076 } 5077 } 5078 5079 static void print_objc_property_list32(uint32_t p, 5080 struct DisassembleInfo *info) { 5081 struct objc_property_list32 opl; 5082 struct objc_property32 op; 5083 const char *r; 5084 uint32_t offset, xoffset, left, j; 5085 SectionRef S, xS; 5086 const char *name; 5087 5088 r = get_pointer_32(p, offset, left, S, info); 5089 if (r == nullptr) 5090 return; 5091 memset(&opl, '\0', sizeof(struct objc_property_list32)); 5092 if (left < sizeof(struct objc_property_list32)) { 5093 memcpy(&opl, r, left); 5094 outs() << " (objc_property_list entends past the end of the section)\n"; 5095 } else 5096 memcpy(&opl, r, sizeof(struct objc_property_list32)); 5097 if (info->O->isLittleEndian() != sys::IsLittleEndianHost) 5098 swapStruct(opl); 5099 outs() << " entsize " << opl.entsize << "\n"; 5100 outs() << " count " << opl.count << "\n"; 5101 5102 p += sizeof(struct objc_property_list32); 5103 offset += sizeof(struct objc_property_list32); 5104 for (j = 0; j < opl.count; j++) { 5105 r = get_pointer_32(p, offset, left, S, info); 5106 if (r == nullptr) 5107 return; 5108 memset(&op, '\0', sizeof(struct objc_property32)); 5109 if (left < sizeof(struct objc_property32)) { 5110 memcpy(&op, r, left); 5111 outs() << " (objc_property entends past the end of the section)\n"; 5112 } else 5113 memcpy(&op, r, sizeof(struct objc_property32)); 5114 if (info->O->isLittleEndian() != sys::IsLittleEndianHost) 5115 swapStruct(op); 5116 5117 outs() << "\t\t\t name " << format("0x%" PRIx32, op.name); 5118 name = get_pointer_32(op.name, xoffset, left, xS, info); 5119 if (name != nullptr) 5120 outs() << format(" %.*s", left, name); 5121 outs() << "\n"; 5122 5123 outs() << "\t\t\tattributes " << format("0x%" PRIx32, op.attributes); 5124 name = get_pointer_32(op.attributes, xoffset, left, xS, info); 5125 if (name != nullptr) 5126 outs() << format(" %.*s", left, name); 5127 outs() << "\n"; 5128 5129 p += sizeof(struct objc_property32); 5130 offset += sizeof(struct objc_property32); 5131 } 5132 } 5133 5134 static bool print_class_ro64_t(uint64_t p, struct DisassembleInfo *info, 5135 bool &is_meta_class) { 5136 struct class_ro64_t cro; 5137 const char *r; 5138 uint32_t offset, xoffset, left; 5139 SectionRef S, xS; 5140 const char *name, *sym_name; 5141 uint64_t n_value; 5142 5143 r = get_pointer_64(p, offset, left, S, info); 5144 if (r == nullptr || left < sizeof(struct class_ro64_t)) 5145 return false; 5146 memcpy(&cro, r, sizeof(struct class_ro64_t)); 5147 if (info->O->isLittleEndian() != sys::IsLittleEndianHost) 5148 swapStruct(cro); 5149 outs() << " flags " << format("0x%" PRIx32, cro.flags); 5150 if (cro.flags & RO_META) 5151 outs() << " RO_META"; 5152 if (cro.flags & RO_ROOT) 5153 outs() << " RO_ROOT"; 5154 if (cro.flags & RO_HAS_CXX_STRUCTORS) 5155 outs() << " RO_HAS_CXX_STRUCTORS"; 5156 outs() << "\n"; 5157 outs() << " instanceStart " << cro.instanceStart << "\n"; 5158 outs() << " instanceSize " << cro.instanceSize << "\n"; 5159 outs() << " reserved " << format("0x%" PRIx32, cro.reserved) 5160 << "\n"; 5161 outs() << " ivarLayout " << format("0x%" PRIx64, cro.ivarLayout) 5162 << "\n"; 5163 print_layout_map64(cro.ivarLayout, info); 5164 5165 outs() << " name "; 5166 sym_name = get_symbol_64(offset + offsetof(struct class_ro64_t, name), S, 5167 info, n_value, cro.name); 5168 if (n_value != 0) { 5169 if (info->verbose && sym_name != nullptr) 5170 outs() << sym_name; 5171 else 5172 outs() << format("0x%" PRIx64, n_value); 5173 if (cro.name != 0) 5174 outs() << " + " << format("0x%" PRIx64, cro.name); 5175 } else 5176 outs() << format("0x%" PRIx64, cro.name); 5177 name = get_pointer_64(cro.name + n_value, xoffset, left, xS, info); 5178 if (name != nullptr) 5179 outs() << format(" %.*s", left, name); 5180 outs() << "\n"; 5181 5182 outs() << " baseMethods "; 5183 sym_name = get_symbol_64(offset + offsetof(struct class_ro64_t, baseMethods), 5184 S, info, n_value, cro.baseMethods); 5185 if (n_value != 0) { 5186 if (info->verbose && sym_name != nullptr) 5187 outs() << sym_name; 5188 else 5189 outs() << format("0x%" PRIx64, n_value); 5190 if (cro.baseMethods != 0) 5191 outs() << " + " << format("0x%" PRIx64, cro.baseMethods); 5192 } else 5193 outs() << format("0x%" PRIx64, cro.baseMethods); 5194 outs() << " (struct method_list_t *)\n"; 5195 if (cro.baseMethods + n_value != 0) 5196 print_method_list64_t(cro.baseMethods + n_value, info, ""); 5197 5198 outs() << " baseProtocols "; 5199 sym_name = 5200 get_symbol_64(offset + offsetof(struct class_ro64_t, baseProtocols), S, 5201 info, n_value, cro.baseProtocols); 5202 if (n_value != 0) { 5203 if (info->verbose && sym_name != nullptr) 5204 outs() << sym_name; 5205 else 5206 outs() << format("0x%" PRIx64, n_value); 5207 if (cro.baseProtocols != 0) 5208 outs() << " + " << format("0x%" PRIx64, cro.baseProtocols); 5209 } else 5210 outs() << format("0x%" PRIx64, cro.baseProtocols); 5211 outs() << "\n"; 5212 if (cro.baseProtocols + n_value != 0) 5213 print_protocol_list64_t(cro.baseProtocols + n_value, info); 5214 5215 outs() << " ivars "; 5216 sym_name = get_symbol_64(offset + offsetof(struct class_ro64_t, ivars), S, 5217 info, n_value, cro.ivars); 5218 if (n_value != 0) { 5219 if (info->verbose && sym_name != nullptr) 5220 outs() << sym_name; 5221 else 5222 outs() << format("0x%" PRIx64, n_value); 5223 if (cro.ivars != 0) 5224 outs() << " + " << format("0x%" PRIx64, cro.ivars); 5225 } else 5226 outs() << format("0x%" PRIx64, cro.ivars); 5227 outs() << "\n"; 5228 if (cro.ivars + n_value != 0) 5229 print_ivar_list64_t(cro.ivars + n_value, info); 5230 5231 outs() << " weakIvarLayout "; 5232 sym_name = 5233 get_symbol_64(offset + offsetof(struct class_ro64_t, weakIvarLayout), S, 5234 info, n_value, cro.weakIvarLayout); 5235 if (n_value != 0) { 5236 if (info->verbose && sym_name != nullptr) 5237 outs() << sym_name; 5238 else 5239 outs() << format("0x%" PRIx64, n_value); 5240 if (cro.weakIvarLayout != 0) 5241 outs() << " + " << format("0x%" PRIx64, cro.weakIvarLayout); 5242 } else 5243 outs() << format("0x%" PRIx64, cro.weakIvarLayout); 5244 outs() << "\n"; 5245 print_layout_map64(cro.weakIvarLayout + n_value, info); 5246 5247 outs() << " baseProperties "; 5248 sym_name = 5249 get_symbol_64(offset + offsetof(struct class_ro64_t, baseProperties), S, 5250 info, n_value, cro.baseProperties); 5251 if (n_value != 0) { 5252 if (info->verbose && sym_name != nullptr) 5253 outs() << sym_name; 5254 else 5255 outs() << format("0x%" PRIx64, n_value); 5256 if (cro.baseProperties != 0) 5257 outs() << " + " << format("0x%" PRIx64, cro.baseProperties); 5258 } else 5259 outs() << format("0x%" PRIx64, cro.baseProperties); 5260 outs() << "\n"; 5261 if (cro.baseProperties + n_value != 0) 5262 print_objc_property_list64(cro.baseProperties + n_value, info); 5263 5264 is_meta_class = (cro.flags & RO_META) != 0; 5265 return true; 5266 } 5267 5268 static bool print_class_ro32_t(uint32_t p, struct DisassembleInfo *info, 5269 bool &is_meta_class) { 5270 struct class_ro32_t cro; 5271 const char *r; 5272 uint32_t offset, xoffset, left; 5273 SectionRef S, xS; 5274 const char *name; 5275 5276 r = get_pointer_32(p, offset, left, S, info); 5277 if (r == nullptr) 5278 return false; 5279 memset(&cro, '\0', sizeof(struct class_ro32_t)); 5280 if (left < sizeof(struct class_ro32_t)) { 5281 memcpy(&cro, r, left); 5282 outs() << " (class_ro_t entends past the end of the section)\n"; 5283 } else 5284 memcpy(&cro, r, sizeof(struct class_ro32_t)); 5285 if (info->O->isLittleEndian() != sys::IsLittleEndianHost) 5286 swapStruct(cro); 5287 outs() << " flags " << format("0x%" PRIx32, cro.flags); 5288 if (cro.flags & RO_META) 5289 outs() << " RO_META"; 5290 if (cro.flags & RO_ROOT) 5291 outs() << " RO_ROOT"; 5292 if (cro.flags & RO_HAS_CXX_STRUCTORS) 5293 outs() << " RO_HAS_CXX_STRUCTORS"; 5294 outs() << "\n"; 5295 outs() << " instanceStart " << cro.instanceStart << "\n"; 5296 outs() << " instanceSize " << cro.instanceSize << "\n"; 5297 outs() << " ivarLayout " << format("0x%" PRIx32, cro.ivarLayout) 5298 << "\n"; 5299 print_layout_map32(cro.ivarLayout, info); 5300 5301 outs() << " name " << format("0x%" PRIx32, cro.name); 5302 name = get_pointer_32(cro.name, xoffset, left, xS, info); 5303 if (name != nullptr) 5304 outs() << format(" %.*s", left, name); 5305 outs() << "\n"; 5306 5307 outs() << " baseMethods " 5308 << format("0x%" PRIx32, cro.baseMethods) 5309 << " (struct method_list_t *)\n"; 5310 if (cro.baseMethods != 0) 5311 print_method_list32_t(cro.baseMethods, info, ""); 5312 5313 outs() << " baseProtocols " 5314 << format("0x%" PRIx32, cro.baseProtocols) << "\n"; 5315 if (cro.baseProtocols != 0) 5316 print_protocol_list32_t(cro.baseProtocols, info); 5317 outs() << " ivars " << format("0x%" PRIx32, cro.ivars) 5318 << "\n"; 5319 if (cro.ivars != 0) 5320 print_ivar_list32_t(cro.ivars, info); 5321 outs() << " weakIvarLayout " 5322 << format("0x%" PRIx32, cro.weakIvarLayout) << "\n"; 5323 print_layout_map32(cro.weakIvarLayout, info); 5324 outs() << " baseProperties " 5325 << format("0x%" PRIx32, cro.baseProperties) << "\n"; 5326 if (cro.baseProperties != 0) 5327 print_objc_property_list32(cro.baseProperties, info); 5328 is_meta_class = (cro.flags & RO_META) != 0; 5329 return true; 5330 } 5331 5332 static void print_class64_t(uint64_t p, struct DisassembleInfo *info) { 5333 struct class64_t c; 5334 const char *r; 5335 uint32_t offset, left; 5336 SectionRef S; 5337 const char *name; 5338 uint64_t isa_n_value, n_value; 5339 5340 r = get_pointer_64(p, offset, left, S, info); 5341 if (r == nullptr || left < sizeof(struct class64_t)) 5342 return; 5343 memcpy(&c, r, sizeof(struct class64_t)); 5344 if (info->O->isLittleEndian() != sys::IsLittleEndianHost) 5345 swapStruct(c); 5346 5347 outs() << " isa " << format("0x%" PRIx64, c.isa); 5348 name = get_symbol_64(offset + offsetof(struct class64_t, isa), S, info, 5349 isa_n_value, c.isa); 5350 if (name != nullptr) 5351 outs() << " " << name; 5352 outs() << "\n"; 5353 5354 outs() << " superclass " << format("0x%" PRIx64, c.superclass); 5355 name = get_symbol_64(offset + offsetof(struct class64_t, superclass), S, info, 5356 n_value, c.superclass); 5357 if (name != nullptr) 5358 outs() << " " << name; 5359 else { 5360 name = get_dyld_bind_info_symbolname(S.getAddress() + 5361 offset + offsetof(struct class64_t, superclass), info); 5362 if (name != nullptr) 5363 outs() << " " << name; 5364 } 5365 outs() << "\n"; 5366 5367 outs() << " cache " << format("0x%" PRIx64, c.cache); 5368 name = get_symbol_64(offset + offsetof(struct class64_t, cache), S, info, 5369 n_value, c.cache); 5370 if (name != nullptr) 5371 outs() << " " << name; 5372 outs() << "\n"; 5373 5374 outs() << " vtable " << format("0x%" PRIx64, c.vtable); 5375 name = get_symbol_64(offset + offsetof(struct class64_t, vtable), S, info, 5376 n_value, c.vtable); 5377 if (name != nullptr) 5378 outs() << " " << name; 5379 outs() << "\n"; 5380 5381 name = get_symbol_64(offset + offsetof(struct class64_t, data), S, info, 5382 n_value, c.data); 5383 outs() << " data "; 5384 if (n_value != 0) { 5385 if (info->verbose && name != nullptr) 5386 outs() << name; 5387 else 5388 outs() << format("0x%" PRIx64, n_value); 5389 if (c.data != 0) 5390 outs() << " + " << format("0x%" PRIx64, c.data); 5391 } else 5392 outs() << format("0x%" PRIx64, c.data); 5393 outs() << " (struct class_ro_t *)"; 5394 5395 // This is a Swift class if some of the low bits of the pointer are set. 5396 if ((c.data + n_value) & 0x7) 5397 outs() << " Swift class"; 5398 outs() << "\n"; 5399 bool is_meta_class; 5400 if (!print_class_ro64_t((c.data + n_value) & ~0x7, info, is_meta_class)) 5401 return; 5402 5403 if (!is_meta_class && 5404 c.isa + isa_n_value != p && 5405 c.isa + isa_n_value != 0 && 5406 info->depth < 100) { 5407 info->depth++; 5408 outs() << "Meta Class\n"; 5409 print_class64_t(c.isa + isa_n_value, info); 5410 } 5411 } 5412 5413 static void print_class32_t(uint32_t p, struct DisassembleInfo *info) { 5414 struct class32_t c; 5415 const char *r; 5416 uint32_t offset, left; 5417 SectionRef S; 5418 const char *name; 5419 5420 r = get_pointer_32(p, offset, left, S, info); 5421 if (r == nullptr) 5422 return; 5423 memset(&c, '\0', sizeof(struct class32_t)); 5424 if (left < sizeof(struct class32_t)) { 5425 memcpy(&c, r, left); 5426 outs() << " (class_t entends past the end of the section)\n"; 5427 } else 5428 memcpy(&c, r, sizeof(struct class32_t)); 5429 if (info->O->isLittleEndian() != sys::IsLittleEndianHost) 5430 swapStruct(c); 5431 5432 outs() << " isa " << format("0x%" PRIx32, c.isa); 5433 name = 5434 get_symbol_32(offset + offsetof(struct class32_t, isa), S, info, c.isa); 5435 if (name != nullptr) 5436 outs() << " " << name; 5437 outs() << "\n"; 5438 5439 outs() << " superclass " << format("0x%" PRIx32, c.superclass); 5440 name = get_symbol_32(offset + offsetof(struct class32_t, superclass), S, info, 5441 c.superclass); 5442 if (name != nullptr) 5443 outs() << " " << name; 5444 outs() << "\n"; 5445 5446 outs() << " cache " << format("0x%" PRIx32, c.cache); 5447 name = get_symbol_32(offset + offsetof(struct class32_t, cache), S, info, 5448 c.cache); 5449 if (name != nullptr) 5450 outs() << " " << name; 5451 outs() << "\n"; 5452 5453 outs() << " vtable " << format("0x%" PRIx32, c.vtable); 5454 name = get_symbol_32(offset + offsetof(struct class32_t, vtable), S, info, 5455 c.vtable); 5456 if (name != nullptr) 5457 outs() << " " << name; 5458 outs() << "\n"; 5459 5460 name = 5461 get_symbol_32(offset + offsetof(struct class32_t, data), S, info, c.data); 5462 outs() << " data " << format("0x%" PRIx32, c.data) 5463 << " (struct class_ro_t *)"; 5464 5465 // This is a Swift class if some of the low bits of the pointer are set. 5466 if (c.data & 0x3) 5467 outs() << " Swift class"; 5468 outs() << "\n"; 5469 bool is_meta_class; 5470 if (!print_class_ro32_t(c.data & ~0x3, info, is_meta_class)) 5471 return; 5472 5473 if (!is_meta_class) { 5474 outs() << "Meta Class\n"; 5475 print_class32_t(c.isa, info); 5476 } 5477 } 5478 5479 static void print_objc_class_t(struct objc_class_t *objc_class, 5480 struct DisassembleInfo *info) { 5481 uint32_t offset, left, xleft; 5482 const char *name, *p, *ivar_list; 5483 SectionRef S; 5484 int32_t i; 5485 struct objc_ivar_list_t objc_ivar_list; 5486 struct objc_ivar_t ivar; 5487 5488 outs() << "\t\t isa " << format("0x%08" PRIx32, objc_class->isa); 5489 if (info->verbose && CLS_GETINFO(objc_class, CLS_META)) { 5490 name = get_pointer_32(objc_class->isa, offset, left, S, info, true); 5491 if (name != nullptr) 5492 outs() << format(" %.*s", left, name); 5493 else 5494 outs() << " (not in an __OBJC section)"; 5495 } 5496 outs() << "\n"; 5497 5498 outs() << "\t super_class " 5499 << format("0x%08" PRIx32, objc_class->super_class); 5500 if (info->verbose) { 5501 name = get_pointer_32(objc_class->super_class, offset, left, S, info, true); 5502 if (name != nullptr) 5503 outs() << format(" %.*s", left, name); 5504 else 5505 outs() << " (not in an __OBJC section)"; 5506 } 5507 outs() << "\n"; 5508 5509 outs() << "\t\t name " << format("0x%08" PRIx32, objc_class->name); 5510 if (info->verbose) { 5511 name = get_pointer_32(objc_class->name, offset, left, S, info, true); 5512 if (name != nullptr) 5513 outs() << format(" %.*s", left, name); 5514 else 5515 outs() << " (not in an __OBJC section)"; 5516 } 5517 outs() << "\n"; 5518 5519 outs() << "\t\t version " << format("0x%08" PRIx32, objc_class->version) 5520 << "\n"; 5521 5522 outs() << "\t\t info " << format("0x%08" PRIx32, objc_class->info); 5523 if (info->verbose) { 5524 if (CLS_GETINFO(objc_class, CLS_CLASS)) 5525 outs() << " CLS_CLASS"; 5526 else if (CLS_GETINFO(objc_class, CLS_META)) 5527 outs() << " CLS_META"; 5528 } 5529 outs() << "\n"; 5530 5531 outs() << "\t instance_size " 5532 << format("0x%08" PRIx32, objc_class->instance_size) << "\n"; 5533 5534 p = get_pointer_32(objc_class->ivars, offset, left, S, info, true); 5535 outs() << "\t\t ivars " << format("0x%08" PRIx32, objc_class->ivars); 5536 if (p != nullptr) { 5537 if (left > sizeof(struct objc_ivar_list_t)) { 5538 outs() << "\n"; 5539 memcpy(&objc_ivar_list, p, sizeof(struct objc_ivar_list_t)); 5540 } else { 5541 outs() << " (entends past the end of the section)\n"; 5542 memset(&objc_ivar_list, '\0', sizeof(struct objc_ivar_list_t)); 5543 memcpy(&objc_ivar_list, p, left); 5544 } 5545 if (info->O->isLittleEndian() != sys::IsLittleEndianHost) 5546 swapStruct(objc_ivar_list); 5547 outs() << "\t\t ivar_count " << objc_ivar_list.ivar_count << "\n"; 5548 ivar_list = p + sizeof(struct objc_ivar_list_t); 5549 for (i = 0; i < objc_ivar_list.ivar_count; i++) { 5550 if ((i + 1) * sizeof(struct objc_ivar_t) > left) { 5551 outs() << "\t\t remaining ivar's extend past the of the section\n"; 5552 break; 5553 } 5554 memcpy(&ivar, ivar_list + i * sizeof(struct objc_ivar_t), 5555 sizeof(struct objc_ivar_t)); 5556 if (info->O->isLittleEndian() != sys::IsLittleEndianHost) 5557 swapStruct(ivar); 5558 5559 outs() << "\t\t\tivar_name " << format("0x%08" PRIx32, ivar.ivar_name); 5560 if (info->verbose) { 5561 name = get_pointer_32(ivar.ivar_name, offset, xleft, S, info, true); 5562 if (name != nullptr) 5563 outs() << format(" %.*s", xleft, name); 5564 else 5565 outs() << " (not in an __OBJC section)"; 5566 } 5567 outs() << "\n"; 5568 5569 outs() << "\t\t\tivar_type " << format("0x%08" PRIx32, ivar.ivar_type); 5570 if (info->verbose) { 5571 name = get_pointer_32(ivar.ivar_type, offset, xleft, S, info, true); 5572 if (name != nullptr) 5573 outs() << format(" %.*s", xleft, name); 5574 else 5575 outs() << " (not in an __OBJC section)"; 5576 } 5577 outs() << "\n"; 5578 5579 outs() << "\t\t ivar_offset " 5580 << format("0x%08" PRIx32, ivar.ivar_offset) << "\n"; 5581 } 5582 } else { 5583 outs() << " (not in an __OBJC section)\n"; 5584 } 5585 5586 outs() << "\t\t methods " << format("0x%08" PRIx32, objc_class->methodLists); 5587 if (print_method_list(objc_class->methodLists, info)) 5588 outs() << " (not in an __OBJC section)\n"; 5589 5590 outs() << "\t\t cache " << format("0x%08" PRIx32, objc_class->cache) 5591 << "\n"; 5592 5593 outs() << "\t\tprotocols " << format("0x%08" PRIx32, objc_class->protocols); 5594 if (print_protocol_list(objc_class->protocols, 16, info)) 5595 outs() << " (not in an __OBJC section)\n"; 5596 } 5597 5598 static void print_objc_objc_category_t(struct objc_category_t *objc_category, 5599 struct DisassembleInfo *info) { 5600 uint32_t offset, left; 5601 const char *name; 5602 SectionRef S; 5603 5604 outs() << "\t category name " 5605 << format("0x%08" PRIx32, objc_category->category_name); 5606 if (info->verbose) { 5607 name = get_pointer_32(objc_category->category_name, offset, left, S, info, 5608 true); 5609 if (name != nullptr) 5610 outs() << format(" %.*s", left, name); 5611 else 5612 outs() << " (not in an __OBJC section)"; 5613 } 5614 outs() << "\n"; 5615 5616 outs() << "\t\t class name " 5617 << format("0x%08" PRIx32, objc_category->class_name); 5618 if (info->verbose) { 5619 name = 5620 get_pointer_32(objc_category->class_name, offset, left, S, info, true); 5621 if (name != nullptr) 5622 outs() << format(" %.*s", left, name); 5623 else 5624 outs() << " (not in an __OBJC section)"; 5625 } 5626 outs() << "\n"; 5627 5628 outs() << "\t instance methods " 5629 << format("0x%08" PRIx32, objc_category->instance_methods); 5630 if (print_method_list(objc_category->instance_methods, info)) 5631 outs() << " (not in an __OBJC section)\n"; 5632 5633 outs() << "\t class methods " 5634 << format("0x%08" PRIx32, objc_category->class_methods); 5635 if (print_method_list(objc_category->class_methods, info)) 5636 outs() << " (not in an __OBJC section)\n"; 5637 } 5638 5639 static void print_category64_t(uint64_t p, struct DisassembleInfo *info) { 5640 struct category64_t c; 5641 const char *r; 5642 uint32_t offset, xoffset, left; 5643 SectionRef S, xS; 5644 const char *name, *sym_name; 5645 uint64_t n_value; 5646 5647 r = get_pointer_64(p, offset, left, S, info); 5648 if (r == nullptr) 5649 return; 5650 memset(&c, '\0', sizeof(struct category64_t)); 5651 if (left < sizeof(struct category64_t)) { 5652 memcpy(&c, r, left); 5653 outs() << " (category_t entends past the end of the section)\n"; 5654 } else 5655 memcpy(&c, r, sizeof(struct category64_t)); 5656 if (info->O->isLittleEndian() != sys::IsLittleEndianHost) 5657 swapStruct(c); 5658 5659 outs() << " name "; 5660 sym_name = get_symbol_64(offset + offsetof(struct category64_t, name), S, 5661 info, n_value, c.name); 5662 if (n_value != 0) { 5663 if (info->verbose && sym_name != nullptr) 5664 outs() << sym_name; 5665 else 5666 outs() << format("0x%" PRIx64, n_value); 5667 if (c.name != 0) 5668 outs() << " + " << format("0x%" PRIx64, c.name); 5669 } else 5670 outs() << format("0x%" PRIx64, c.name); 5671 name = get_pointer_64(c.name + n_value, xoffset, left, xS, info); 5672 if (name != nullptr) 5673 outs() << format(" %.*s", left, name); 5674 outs() << "\n"; 5675 5676 outs() << " cls "; 5677 sym_name = get_symbol_64(offset + offsetof(struct category64_t, cls), S, info, 5678 n_value, c.cls); 5679 if (n_value != 0) { 5680 if (info->verbose && sym_name != nullptr) 5681 outs() << sym_name; 5682 else 5683 outs() << format("0x%" PRIx64, n_value); 5684 if (c.cls != 0) 5685 outs() << " + " << format("0x%" PRIx64, c.cls); 5686 } else 5687 outs() << format("0x%" PRIx64, c.cls); 5688 outs() << "\n"; 5689 if (c.cls + n_value != 0) 5690 print_class64_t(c.cls + n_value, info); 5691 5692 outs() << " instanceMethods "; 5693 sym_name = 5694 get_symbol_64(offset + offsetof(struct category64_t, instanceMethods), S, 5695 info, n_value, c.instanceMethods); 5696 if (n_value != 0) { 5697 if (info->verbose && sym_name != nullptr) 5698 outs() << sym_name; 5699 else 5700 outs() << format("0x%" PRIx64, n_value); 5701 if (c.instanceMethods != 0) 5702 outs() << " + " << format("0x%" PRIx64, c.instanceMethods); 5703 } else 5704 outs() << format("0x%" PRIx64, c.instanceMethods); 5705 outs() << "\n"; 5706 if (c.instanceMethods + n_value != 0) 5707 print_method_list64_t(c.instanceMethods + n_value, info, ""); 5708 5709 outs() << " classMethods "; 5710 sym_name = get_symbol_64(offset + offsetof(struct category64_t, classMethods), 5711 S, info, n_value, c.classMethods); 5712 if (n_value != 0) { 5713 if (info->verbose && sym_name != nullptr) 5714 outs() << sym_name; 5715 else 5716 outs() << format("0x%" PRIx64, n_value); 5717 if (c.classMethods != 0) 5718 outs() << " + " << format("0x%" PRIx64, c.classMethods); 5719 } else 5720 outs() << format("0x%" PRIx64, c.classMethods); 5721 outs() << "\n"; 5722 if (c.classMethods + n_value != 0) 5723 print_method_list64_t(c.classMethods + n_value, info, ""); 5724 5725 outs() << " protocols "; 5726 sym_name = get_symbol_64(offset + offsetof(struct category64_t, protocols), S, 5727 info, n_value, c.protocols); 5728 if (n_value != 0) { 5729 if (info->verbose && sym_name != nullptr) 5730 outs() << sym_name; 5731 else 5732 outs() << format("0x%" PRIx64, n_value); 5733 if (c.protocols != 0) 5734 outs() << " + " << format("0x%" PRIx64, c.protocols); 5735 } else 5736 outs() << format("0x%" PRIx64, c.protocols); 5737 outs() << "\n"; 5738 if (c.protocols + n_value != 0) 5739 print_protocol_list64_t(c.protocols + n_value, info); 5740 5741 outs() << "instanceProperties "; 5742 sym_name = 5743 get_symbol_64(offset + offsetof(struct category64_t, instanceProperties), 5744 S, info, n_value, c.instanceProperties); 5745 if (n_value != 0) { 5746 if (info->verbose && sym_name != nullptr) 5747 outs() << sym_name; 5748 else 5749 outs() << format("0x%" PRIx64, n_value); 5750 if (c.instanceProperties != 0) 5751 outs() << " + " << format("0x%" PRIx64, c.instanceProperties); 5752 } else 5753 outs() << format("0x%" PRIx64, c.instanceProperties); 5754 outs() << "\n"; 5755 if (c.instanceProperties + n_value != 0) 5756 print_objc_property_list64(c.instanceProperties + n_value, info); 5757 } 5758 5759 static void print_category32_t(uint32_t p, struct DisassembleInfo *info) { 5760 struct category32_t c; 5761 const char *r; 5762 uint32_t offset, left; 5763 SectionRef S, xS; 5764 const char *name; 5765 5766 r = get_pointer_32(p, offset, left, S, info); 5767 if (r == nullptr) 5768 return; 5769 memset(&c, '\0', sizeof(struct category32_t)); 5770 if (left < sizeof(struct category32_t)) { 5771 memcpy(&c, r, left); 5772 outs() << " (category_t entends past the end of the section)\n"; 5773 } else 5774 memcpy(&c, r, sizeof(struct category32_t)); 5775 if (info->O->isLittleEndian() != sys::IsLittleEndianHost) 5776 swapStruct(c); 5777 5778 outs() << " name " << format("0x%" PRIx32, c.name); 5779 name = get_symbol_32(offset + offsetof(struct category32_t, name), S, info, 5780 c.name); 5781 if (name) 5782 outs() << " " << name; 5783 outs() << "\n"; 5784 5785 outs() << " cls " << format("0x%" PRIx32, c.cls) << "\n"; 5786 if (c.cls != 0) 5787 print_class32_t(c.cls, info); 5788 outs() << " instanceMethods " << format("0x%" PRIx32, c.instanceMethods) 5789 << "\n"; 5790 if (c.instanceMethods != 0) 5791 print_method_list32_t(c.instanceMethods, info, ""); 5792 outs() << " classMethods " << format("0x%" PRIx32, c.classMethods) 5793 << "\n"; 5794 if (c.classMethods != 0) 5795 print_method_list32_t(c.classMethods, info, ""); 5796 outs() << " protocols " << format("0x%" PRIx32, c.protocols) << "\n"; 5797 if (c.protocols != 0) 5798 print_protocol_list32_t(c.protocols, info); 5799 outs() << "instanceProperties " << format("0x%" PRIx32, c.instanceProperties) 5800 << "\n"; 5801 if (c.instanceProperties != 0) 5802 print_objc_property_list32(c.instanceProperties, info); 5803 } 5804 5805 static void print_message_refs64(SectionRef S, struct DisassembleInfo *info) { 5806 uint32_t i, left, offset, xoffset; 5807 uint64_t p, n_value; 5808 struct message_ref64 mr; 5809 const char *name, *sym_name; 5810 const char *r; 5811 SectionRef xS; 5812 5813 if (S == SectionRef()) 5814 return; 5815 5816 StringRef SectName; 5817 Expected<StringRef> SecNameOrErr = S.getName(); 5818 if (SecNameOrErr) 5819 SectName = *SecNameOrErr; 5820 else 5821 consumeError(SecNameOrErr.takeError()); 5822 5823 DataRefImpl Ref = S.getRawDataRefImpl(); 5824 StringRef SegName = info->O->getSectionFinalSegmentName(Ref); 5825 outs() << "Contents of (" << SegName << "," << SectName << ") section\n"; 5826 offset = 0; 5827 for (i = 0; i < S.getSize(); i += sizeof(struct message_ref64)) { 5828 p = S.getAddress() + i; 5829 r = get_pointer_64(p, offset, left, S, info); 5830 if (r == nullptr) 5831 return; 5832 memset(&mr, '\0', sizeof(struct message_ref64)); 5833 if (left < sizeof(struct message_ref64)) { 5834 memcpy(&mr, r, left); 5835 outs() << " (message_ref entends past the end of the section)\n"; 5836 } else 5837 memcpy(&mr, r, sizeof(struct message_ref64)); 5838 if (info->O->isLittleEndian() != sys::IsLittleEndianHost) 5839 swapStruct(mr); 5840 5841 outs() << " imp "; 5842 name = get_symbol_64(offset + offsetof(struct message_ref64, imp), S, info, 5843 n_value, mr.imp); 5844 if (n_value != 0) { 5845 outs() << format("0x%" PRIx64, n_value) << " "; 5846 if (mr.imp != 0) 5847 outs() << "+ " << format("0x%" PRIx64, mr.imp) << " "; 5848 } else 5849 outs() << format("0x%" PRIx64, mr.imp) << " "; 5850 if (name != nullptr) 5851 outs() << " " << name; 5852 outs() << "\n"; 5853 5854 outs() << " sel "; 5855 sym_name = get_symbol_64(offset + offsetof(struct message_ref64, sel), S, 5856 info, n_value, mr.sel); 5857 if (n_value != 0) { 5858 if (info->verbose && sym_name != nullptr) 5859 outs() << sym_name; 5860 else 5861 outs() << format("0x%" PRIx64, n_value); 5862 if (mr.sel != 0) 5863 outs() << " + " << format("0x%" PRIx64, mr.sel); 5864 } else 5865 outs() << format("0x%" PRIx64, mr.sel); 5866 name = get_pointer_64(mr.sel + n_value, xoffset, left, xS, info); 5867 if (name != nullptr) 5868 outs() << format(" %.*s", left, name); 5869 outs() << "\n"; 5870 5871 offset += sizeof(struct message_ref64); 5872 } 5873 } 5874 5875 static void print_message_refs32(SectionRef S, struct DisassembleInfo *info) { 5876 uint32_t i, left, offset, xoffset, p; 5877 struct message_ref32 mr; 5878 const char *name, *r; 5879 SectionRef xS; 5880 5881 if (S == SectionRef()) 5882 return; 5883 5884 StringRef SectName; 5885 Expected<StringRef> SecNameOrErr = S.getName(); 5886 if (SecNameOrErr) 5887 SectName = *SecNameOrErr; 5888 else 5889 consumeError(SecNameOrErr.takeError()); 5890 5891 DataRefImpl Ref = S.getRawDataRefImpl(); 5892 StringRef SegName = info->O->getSectionFinalSegmentName(Ref); 5893 outs() << "Contents of (" << SegName << "," << SectName << ") section\n"; 5894 offset = 0; 5895 for (i = 0; i < S.getSize(); i += sizeof(struct message_ref64)) { 5896 p = S.getAddress() + i; 5897 r = get_pointer_32(p, offset, left, S, info); 5898 if (r == nullptr) 5899 return; 5900 memset(&mr, '\0', sizeof(struct message_ref32)); 5901 if (left < sizeof(struct message_ref32)) { 5902 memcpy(&mr, r, left); 5903 outs() << " (message_ref entends past the end of the section)\n"; 5904 } else 5905 memcpy(&mr, r, sizeof(struct message_ref32)); 5906 if (info->O->isLittleEndian() != sys::IsLittleEndianHost) 5907 swapStruct(mr); 5908 5909 outs() << " imp " << format("0x%" PRIx32, mr.imp); 5910 name = get_symbol_32(offset + offsetof(struct message_ref32, imp), S, info, 5911 mr.imp); 5912 if (name != nullptr) 5913 outs() << " " << name; 5914 outs() << "\n"; 5915 5916 outs() << " sel " << format("0x%" PRIx32, mr.sel); 5917 name = get_pointer_32(mr.sel, xoffset, left, xS, info); 5918 if (name != nullptr) 5919 outs() << " " << name; 5920 outs() << "\n"; 5921 5922 offset += sizeof(struct message_ref32); 5923 } 5924 } 5925 5926 static void print_image_info64(SectionRef S, struct DisassembleInfo *info) { 5927 uint32_t left, offset, swift_version; 5928 uint64_t p; 5929 struct objc_image_info64 o; 5930 const char *r; 5931 5932 if (S == SectionRef()) 5933 return; 5934 5935 StringRef SectName; 5936 Expected<StringRef> SecNameOrErr = S.getName(); 5937 if (SecNameOrErr) 5938 SectName = *SecNameOrErr; 5939 else 5940 consumeError(SecNameOrErr.takeError()); 5941 5942 DataRefImpl Ref = S.getRawDataRefImpl(); 5943 StringRef SegName = info->O->getSectionFinalSegmentName(Ref); 5944 outs() << "Contents of (" << SegName << "," << SectName << ") section\n"; 5945 p = S.getAddress(); 5946 r = get_pointer_64(p, offset, left, S, info); 5947 if (r == nullptr) 5948 return; 5949 memset(&o, '\0', sizeof(struct objc_image_info64)); 5950 if (left < sizeof(struct objc_image_info64)) { 5951 memcpy(&o, r, left); 5952 outs() << " (objc_image_info entends past the end of the section)\n"; 5953 } else 5954 memcpy(&o, r, sizeof(struct objc_image_info64)); 5955 if (info->O->isLittleEndian() != sys::IsLittleEndianHost) 5956 swapStruct(o); 5957 outs() << " version " << o.version << "\n"; 5958 outs() << " flags " << format("0x%" PRIx32, o.flags); 5959 if (o.flags & OBJC_IMAGE_IS_REPLACEMENT) 5960 outs() << " OBJC_IMAGE_IS_REPLACEMENT"; 5961 if (o.flags & OBJC_IMAGE_SUPPORTS_GC) 5962 outs() << " OBJC_IMAGE_SUPPORTS_GC"; 5963 if (o.flags & OBJC_IMAGE_IS_SIMULATED) 5964 outs() << " OBJC_IMAGE_IS_SIMULATED"; 5965 if (o.flags & OBJC_IMAGE_HAS_CATEGORY_CLASS_PROPERTIES) 5966 outs() << " OBJC_IMAGE_HAS_CATEGORY_CLASS_PROPERTIES"; 5967 swift_version = (o.flags >> 8) & 0xff; 5968 if (swift_version != 0) { 5969 if (swift_version == 1) 5970 outs() << " Swift 1.0"; 5971 else if (swift_version == 2) 5972 outs() << " Swift 1.1"; 5973 else if(swift_version == 3) 5974 outs() << " Swift 2.0"; 5975 else if(swift_version == 4) 5976 outs() << " Swift 3.0"; 5977 else if(swift_version == 5) 5978 outs() << " Swift 4.0"; 5979 else if(swift_version == 6) 5980 outs() << " Swift 4.1/Swift 4.2"; 5981 else if(swift_version == 7) 5982 outs() << " Swift 5 or later"; 5983 else 5984 outs() << " unknown future Swift version (" << swift_version << ")"; 5985 } 5986 outs() << "\n"; 5987 } 5988 5989 static void print_image_info32(SectionRef S, struct DisassembleInfo *info) { 5990 uint32_t left, offset, swift_version, p; 5991 struct objc_image_info32 o; 5992 const char *r; 5993 5994 if (S == SectionRef()) 5995 return; 5996 5997 StringRef SectName; 5998 Expected<StringRef> SecNameOrErr = S.getName(); 5999 if (SecNameOrErr) 6000 SectName = *SecNameOrErr; 6001 else 6002 consumeError(SecNameOrErr.takeError()); 6003 6004 DataRefImpl Ref = S.getRawDataRefImpl(); 6005 StringRef SegName = info->O->getSectionFinalSegmentName(Ref); 6006 outs() << "Contents of (" << SegName << "," << SectName << ") section\n"; 6007 p = S.getAddress(); 6008 r = get_pointer_32(p, offset, left, S, info); 6009 if (r == nullptr) 6010 return; 6011 memset(&o, '\0', sizeof(struct objc_image_info32)); 6012 if (left < sizeof(struct objc_image_info32)) { 6013 memcpy(&o, r, left); 6014 outs() << " (objc_image_info entends past the end of the section)\n"; 6015 } else 6016 memcpy(&o, r, sizeof(struct objc_image_info32)); 6017 if (info->O->isLittleEndian() != sys::IsLittleEndianHost) 6018 swapStruct(o); 6019 outs() << " version " << o.version << "\n"; 6020 outs() << " flags " << format("0x%" PRIx32, o.flags); 6021 if (o.flags & OBJC_IMAGE_IS_REPLACEMENT) 6022 outs() << " OBJC_IMAGE_IS_REPLACEMENT"; 6023 if (o.flags & OBJC_IMAGE_SUPPORTS_GC) 6024 outs() << " OBJC_IMAGE_SUPPORTS_GC"; 6025 swift_version = (o.flags >> 8) & 0xff; 6026 if (swift_version != 0) { 6027 if (swift_version == 1) 6028 outs() << " Swift 1.0"; 6029 else if (swift_version == 2) 6030 outs() << " Swift 1.1"; 6031 else if(swift_version == 3) 6032 outs() << " Swift 2.0"; 6033 else if(swift_version == 4) 6034 outs() << " Swift 3.0"; 6035 else if(swift_version == 5) 6036 outs() << " Swift 4.0"; 6037 else if(swift_version == 6) 6038 outs() << " Swift 4.1/Swift 4.2"; 6039 else if(swift_version == 7) 6040 outs() << " Swift 5 or later"; 6041 else 6042 outs() << " unknown future Swift version (" << swift_version << ")"; 6043 } 6044 outs() << "\n"; 6045 } 6046 6047 static void print_image_info(SectionRef S, struct DisassembleInfo *info) { 6048 uint32_t left, offset, p; 6049 struct imageInfo_t o; 6050 const char *r; 6051 6052 StringRef SectName; 6053 Expected<StringRef> SecNameOrErr = S.getName(); 6054 if (SecNameOrErr) 6055 SectName = *SecNameOrErr; 6056 else 6057 consumeError(SecNameOrErr.takeError()); 6058 6059 DataRefImpl Ref = S.getRawDataRefImpl(); 6060 StringRef SegName = info->O->getSectionFinalSegmentName(Ref); 6061 outs() << "Contents of (" << SegName << "," << SectName << ") section\n"; 6062 p = S.getAddress(); 6063 r = get_pointer_32(p, offset, left, S, info); 6064 if (r == nullptr) 6065 return; 6066 memset(&o, '\0', sizeof(struct imageInfo_t)); 6067 if (left < sizeof(struct imageInfo_t)) { 6068 memcpy(&o, r, left); 6069 outs() << " (imageInfo entends past the end of the section)\n"; 6070 } else 6071 memcpy(&o, r, sizeof(struct imageInfo_t)); 6072 if (info->O->isLittleEndian() != sys::IsLittleEndianHost) 6073 swapStruct(o); 6074 outs() << " version " << o.version << "\n"; 6075 outs() << " flags " << format("0x%" PRIx32, o.flags); 6076 if (o.flags & 0x1) 6077 outs() << " F&C"; 6078 if (o.flags & 0x2) 6079 outs() << " GC"; 6080 if (o.flags & 0x4) 6081 outs() << " GC-only"; 6082 else 6083 outs() << " RR"; 6084 outs() << "\n"; 6085 } 6086 6087 static void printObjc2_64bit_MetaData(MachOObjectFile *O, bool verbose) { 6088 SymbolAddressMap AddrMap; 6089 if (verbose) 6090 CreateSymbolAddressMap(O, &AddrMap); 6091 6092 std::vector<SectionRef> Sections; 6093 append_range(Sections, O->sections()); 6094 6095 struct DisassembleInfo info(O, &AddrMap, &Sections, verbose); 6096 6097 SectionRef CL = get_section(O, "__OBJC2", "__class_list"); 6098 if (CL == SectionRef()) 6099 CL = get_section(O, "__DATA", "__objc_classlist"); 6100 if (CL == SectionRef()) 6101 CL = get_section(O, "__DATA_CONST", "__objc_classlist"); 6102 if (CL == SectionRef()) 6103 CL = get_section(O, "__DATA_DIRTY", "__objc_classlist"); 6104 info.S = CL; 6105 walk_pointer_list_64("class", CL, O, &info, print_class64_t); 6106 6107 SectionRef CR = get_section(O, "__OBJC2", "__class_refs"); 6108 if (CR == SectionRef()) 6109 CR = get_section(O, "__DATA", "__objc_classrefs"); 6110 if (CR == SectionRef()) 6111 CR = get_section(O, "__DATA_CONST", "__objc_classrefs"); 6112 if (CR == SectionRef()) 6113 CR = get_section(O, "__DATA_DIRTY", "__objc_classrefs"); 6114 info.S = CR; 6115 walk_pointer_list_64("class refs", CR, O, &info, nullptr); 6116 6117 SectionRef SR = get_section(O, "__OBJC2", "__super_refs"); 6118 if (SR == SectionRef()) 6119 SR = get_section(O, "__DATA", "__objc_superrefs"); 6120 if (SR == SectionRef()) 6121 SR = get_section(O, "__DATA_CONST", "__objc_superrefs"); 6122 if (SR == SectionRef()) 6123 SR = get_section(O, "__DATA_DIRTY", "__objc_superrefs"); 6124 info.S = SR; 6125 walk_pointer_list_64("super refs", SR, O, &info, nullptr); 6126 6127 SectionRef CA = get_section(O, "__OBJC2", "__category_list"); 6128 if (CA == SectionRef()) 6129 CA = get_section(O, "__DATA", "__objc_catlist"); 6130 if (CA == SectionRef()) 6131 CA = get_section(O, "__DATA_CONST", "__objc_catlist"); 6132 if (CA == SectionRef()) 6133 CA = get_section(O, "__DATA_DIRTY", "__objc_catlist"); 6134 info.S = CA; 6135 walk_pointer_list_64("category", CA, O, &info, print_category64_t); 6136 6137 SectionRef PL = get_section(O, "__OBJC2", "__protocol_list"); 6138 if (PL == SectionRef()) 6139 PL = get_section(O, "__DATA", "__objc_protolist"); 6140 if (PL == SectionRef()) 6141 PL = get_section(O, "__DATA_CONST", "__objc_protolist"); 6142 if (PL == SectionRef()) 6143 PL = get_section(O, "__DATA_DIRTY", "__objc_protolist"); 6144 info.S = PL; 6145 walk_pointer_list_64("protocol", PL, O, &info, nullptr); 6146 6147 SectionRef MR = get_section(O, "__OBJC2", "__message_refs"); 6148 if (MR == SectionRef()) 6149 MR = get_section(O, "__DATA", "__objc_msgrefs"); 6150 if (MR == SectionRef()) 6151 MR = get_section(O, "__DATA_CONST", "__objc_msgrefs"); 6152 if (MR == SectionRef()) 6153 MR = get_section(O, "__DATA_DIRTY", "__objc_msgrefs"); 6154 info.S = MR; 6155 print_message_refs64(MR, &info); 6156 6157 SectionRef II = get_section(O, "__OBJC2", "__image_info"); 6158 if (II == SectionRef()) 6159 II = get_section(O, "__DATA", "__objc_imageinfo"); 6160 if (II == SectionRef()) 6161 II = get_section(O, "__DATA_CONST", "__objc_imageinfo"); 6162 if (II == SectionRef()) 6163 II = get_section(O, "__DATA_DIRTY", "__objc_imageinfo"); 6164 info.S = II; 6165 print_image_info64(II, &info); 6166 } 6167 6168 static void printObjc2_32bit_MetaData(MachOObjectFile *O, bool verbose) { 6169 SymbolAddressMap AddrMap; 6170 if (verbose) 6171 CreateSymbolAddressMap(O, &AddrMap); 6172 6173 std::vector<SectionRef> Sections; 6174 append_range(Sections, O->sections()); 6175 6176 struct DisassembleInfo info(O, &AddrMap, &Sections, verbose); 6177 6178 SectionRef CL = get_section(O, "__OBJC2", "__class_list"); 6179 if (CL == SectionRef()) 6180 CL = get_section(O, "__DATA", "__objc_classlist"); 6181 if (CL == SectionRef()) 6182 CL = get_section(O, "__DATA_CONST", "__objc_classlist"); 6183 if (CL == SectionRef()) 6184 CL = get_section(O, "__DATA_DIRTY", "__objc_classlist"); 6185 info.S = CL; 6186 walk_pointer_list_32("class", CL, O, &info, print_class32_t); 6187 6188 SectionRef CR = get_section(O, "__OBJC2", "__class_refs"); 6189 if (CR == SectionRef()) 6190 CR = get_section(O, "__DATA", "__objc_classrefs"); 6191 if (CR == SectionRef()) 6192 CR = get_section(O, "__DATA_CONST", "__objc_classrefs"); 6193 if (CR == SectionRef()) 6194 CR = get_section(O, "__DATA_DIRTY", "__objc_classrefs"); 6195 info.S = CR; 6196 walk_pointer_list_32("class refs", CR, O, &info, nullptr); 6197 6198 SectionRef SR = get_section(O, "__OBJC2", "__super_refs"); 6199 if (SR == SectionRef()) 6200 SR = get_section(O, "__DATA", "__objc_superrefs"); 6201 if (SR == SectionRef()) 6202 SR = get_section(O, "__DATA_CONST", "__objc_superrefs"); 6203 if (SR == SectionRef()) 6204 SR = get_section(O, "__DATA_DIRTY", "__objc_superrefs"); 6205 info.S = SR; 6206 walk_pointer_list_32("super refs", SR, O, &info, nullptr); 6207 6208 SectionRef CA = get_section(O, "__OBJC2", "__category_list"); 6209 if (CA == SectionRef()) 6210 CA = get_section(O, "__DATA", "__objc_catlist"); 6211 if (CA == SectionRef()) 6212 CA = get_section(O, "__DATA_CONST", "__objc_catlist"); 6213 if (CA == SectionRef()) 6214 CA = get_section(O, "__DATA_DIRTY", "__objc_catlist"); 6215 info.S = CA; 6216 walk_pointer_list_32("category", CA, O, &info, print_category32_t); 6217 6218 SectionRef PL = get_section(O, "__OBJC2", "__protocol_list"); 6219 if (PL == SectionRef()) 6220 PL = get_section(O, "__DATA", "__objc_protolist"); 6221 if (PL == SectionRef()) 6222 PL = get_section(O, "__DATA_CONST", "__objc_protolist"); 6223 if (PL == SectionRef()) 6224 PL = get_section(O, "__DATA_DIRTY", "__objc_protolist"); 6225 info.S = PL; 6226 walk_pointer_list_32("protocol", PL, O, &info, nullptr); 6227 6228 SectionRef MR = get_section(O, "__OBJC2", "__message_refs"); 6229 if (MR == SectionRef()) 6230 MR = get_section(O, "__DATA", "__objc_msgrefs"); 6231 if (MR == SectionRef()) 6232 MR = get_section(O, "__DATA_CONST", "__objc_msgrefs"); 6233 if (MR == SectionRef()) 6234 MR = get_section(O, "__DATA_DIRTY", "__objc_msgrefs"); 6235 info.S = MR; 6236 print_message_refs32(MR, &info); 6237 6238 SectionRef II = get_section(O, "__OBJC2", "__image_info"); 6239 if (II == SectionRef()) 6240 II = get_section(O, "__DATA", "__objc_imageinfo"); 6241 if (II == SectionRef()) 6242 II = get_section(O, "__DATA_CONST", "__objc_imageinfo"); 6243 if (II == SectionRef()) 6244 II = get_section(O, "__DATA_DIRTY", "__objc_imageinfo"); 6245 info.S = II; 6246 print_image_info32(II, &info); 6247 } 6248 6249 static bool printObjc1_32bit_MetaData(MachOObjectFile *O, bool verbose) { 6250 uint32_t i, j, p, offset, xoffset, left, defs_left, def; 6251 const char *r, *name, *defs; 6252 struct objc_module_t module; 6253 SectionRef S, xS; 6254 struct objc_symtab_t symtab; 6255 struct objc_class_t objc_class; 6256 struct objc_category_t objc_category; 6257 6258 outs() << "Objective-C segment\n"; 6259 S = get_section(O, "__OBJC", "__module_info"); 6260 if (S == SectionRef()) 6261 return false; 6262 6263 SymbolAddressMap AddrMap; 6264 if (verbose) 6265 CreateSymbolAddressMap(O, &AddrMap); 6266 6267 std::vector<SectionRef> Sections; 6268 append_range(Sections, O->sections()); 6269 6270 struct DisassembleInfo info(O, &AddrMap, &Sections, verbose); 6271 6272 for (i = 0; i < S.getSize(); i += sizeof(struct objc_module_t)) { 6273 p = S.getAddress() + i; 6274 r = get_pointer_32(p, offset, left, S, &info, true); 6275 if (r == nullptr) 6276 return true; 6277 memset(&module, '\0', sizeof(struct objc_module_t)); 6278 if (left < sizeof(struct objc_module_t)) { 6279 memcpy(&module, r, left); 6280 outs() << " (module extends past end of __module_info section)\n"; 6281 } else 6282 memcpy(&module, r, sizeof(struct objc_module_t)); 6283 if (O->isLittleEndian() != sys::IsLittleEndianHost) 6284 swapStruct(module); 6285 6286 outs() << "Module " << format("0x%" PRIx32, p) << "\n"; 6287 outs() << " version " << module.version << "\n"; 6288 outs() << " size " << module.size << "\n"; 6289 outs() << " name "; 6290 name = get_pointer_32(module.name, xoffset, left, xS, &info, true); 6291 if (name != nullptr) 6292 outs() << format("%.*s", left, name); 6293 else 6294 outs() << format("0x%08" PRIx32, module.name) 6295 << "(not in an __OBJC section)"; 6296 outs() << "\n"; 6297 6298 r = get_pointer_32(module.symtab, xoffset, left, xS, &info, true); 6299 if (module.symtab == 0 || r == nullptr) { 6300 outs() << " symtab " << format("0x%08" PRIx32, module.symtab) 6301 << " (not in an __OBJC section)\n"; 6302 continue; 6303 } 6304 outs() << " symtab " << format("0x%08" PRIx32, module.symtab) << "\n"; 6305 memset(&symtab, '\0', sizeof(struct objc_symtab_t)); 6306 defs_left = 0; 6307 defs = nullptr; 6308 if (left < sizeof(struct objc_symtab_t)) { 6309 memcpy(&symtab, r, left); 6310 outs() << "\tsymtab extends past end of an __OBJC section)\n"; 6311 } else { 6312 memcpy(&symtab, r, sizeof(struct objc_symtab_t)); 6313 if (left > sizeof(struct objc_symtab_t)) { 6314 defs_left = left - sizeof(struct objc_symtab_t); 6315 defs = r + sizeof(struct objc_symtab_t); 6316 } 6317 } 6318 if (O->isLittleEndian() != sys::IsLittleEndianHost) 6319 swapStruct(symtab); 6320 6321 outs() << "\tsel_ref_cnt " << symtab.sel_ref_cnt << "\n"; 6322 r = get_pointer_32(symtab.refs, xoffset, left, xS, &info, true); 6323 outs() << "\trefs " << format("0x%08" PRIx32, symtab.refs); 6324 if (r == nullptr) 6325 outs() << " (not in an __OBJC section)"; 6326 outs() << "\n"; 6327 outs() << "\tcls_def_cnt " << symtab.cls_def_cnt << "\n"; 6328 outs() << "\tcat_def_cnt " << symtab.cat_def_cnt << "\n"; 6329 if (symtab.cls_def_cnt > 0) 6330 outs() << "\tClass Definitions\n"; 6331 for (j = 0; j < symtab.cls_def_cnt; j++) { 6332 if ((j + 1) * sizeof(uint32_t) > defs_left) { 6333 outs() << "\t(remaining class defs entries entends past the end of the " 6334 << "section)\n"; 6335 break; 6336 } 6337 memcpy(&def, defs + j * sizeof(uint32_t), sizeof(uint32_t)); 6338 if (O->isLittleEndian() != sys::IsLittleEndianHost) 6339 sys::swapByteOrder(def); 6340 6341 r = get_pointer_32(def, xoffset, left, xS, &info, true); 6342 outs() << "\tdefs[" << j << "] " << format("0x%08" PRIx32, def); 6343 if (r != nullptr) { 6344 if (left > sizeof(struct objc_class_t)) { 6345 outs() << "\n"; 6346 memcpy(&objc_class, r, sizeof(struct objc_class_t)); 6347 } else { 6348 outs() << " (entends past the end of the section)\n"; 6349 memset(&objc_class, '\0', sizeof(struct objc_class_t)); 6350 memcpy(&objc_class, r, left); 6351 } 6352 if (O->isLittleEndian() != sys::IsLittleEndianHost) 6353 swapStruct(objc_class); 6354 print_objc_class_t(&objc_class, &info); 6355 } else { 6356 outs() << "(not in an __OBJC section)\n"; 6357 } 6358 6359 if (CLS_GETINFO(&objc_class, CLS_CLASS)) { 6360 outs() << "\tMeta Class"; 6361 r = get_pointer_32(objc_class.isa, xoffset, left, xS, &info, true); 6362 if (r != nullptr) { 6363 if (left > sizeof(struct objc_class_t)) { 6364 outs() << "\n"; 6365 memcpy(&objc_class, r, sizeof(struct objc_class_t)); 6366 } else { 6367 outs() << " (entends past the end of the section)\n"; 6368 memset(&objc_class, '\0', sizeof(struct objc_class_t)); 6369 memcpy(&objc_class, r, left); 6370 } 6371 if (O->isLittleEndian() != sys::IsLittleEndianHost) 6372 swapStruct(objc_class); 6373 print_objc_class_t(&objc_class, &info); 6374 } else { 6375 outs() << "(not in an __OBJC section)\n"; 6376 } 6377 } 6378 } 6379 if (symtab.cat_def_cnt > 0) 6380 outs() << "\tCategory Definitions\n"; 6381 for (j = 0; j < symtab.cat_def_cnt; j++) { 6382 if ((j + symtab.cls_def_cnt + 1) * sizeof(uint32_t) > defs_left) { 6383 outs() << "\t(remaining category defs entries entends past the end of " 6384 << "the section)\n"; 6385 break; 6386 } 6387 memcpy(&def, defs + (j + symtab.cls_def_cnt) * sizeof(uint32_t), 6388 sizeof(uint32_t)); 6389 if (O->isLittleEndian() != sys::IsLittleEndianHost) 6390 sys::swapByteOrder(def); 6391 6392 r = get_pointer_32(def, xoffset, left, xS, &info, true); 6393 outs() << "\tdefs[" << j + symtab.cls_def_cnt << "] " 6394 << format("0x%08" PRIx32, def); 6395 if (r != nullptr) { 6396 if (left > sizeof(struct objc_category_t)) { 6397 outs() << "\n"; 6398 memcpy(&objc_category, r, sizeof(struct objc_category_t)); 6399 } else { 6400 outs() << " (entends past the end of the section)\n"; 6401 memset(&objc_category, '\0', sizeof(struct objc_category_t)); 6402 memcpy(&objc_category, r, left); 6403 } 6404 if (O->isLittleEndian() != sys::IsLittleEndianHost) 6405 swapStruct(objc_category); 6406 print_objc_objc_category_t(&objc_category, &info); 6407 } else { 6408 outs() << "(not in an __OBJC section)\n"; 6409 } 6410 } 6411 } 6412 const SectionRef II = get_section(O, "__OBJC", "__image_info"); 6413 if (II != SectionRef()) 6414 print_image_info(II, &info); 6415 6416 return true; 6417 } 6418 6419 static void DumpProtocolSection(MachOObjectFile *O, const char *sect, 6420 uint32_t size, uint32_t addr) { 6421 SymbolAddressMap AddrMap; 6422 CreateSymbolAddressMap(O, &AddrMap); 6423 6424 std::vector<SectionRef> Sections; 6425 append_range(Sections, O->sections()); 6426 6427 struct DisassembleInfo info(O, &AddrMap, &Sections, true); 6428 6429 const char *p; 6430 struct objc_protocol_t protocol; 6431 uint32_t left, paddr; 6432 for (p = sect; p < sect + size; p += sizeof(struct objc_protocol_t)) { 6433 memset(&protocol, '\0', sizeof(struct objc_protocol_t)); 6434 left = size - (p - sect); 6435 if (left < sizeof(struct objc_protocol_t)) { 6436 outs() << "Protocol extends past end of __protocol section\n"; 6437 memcpy(&protocol, p, left); 6438 } else 6439 memcpy(&protocol, p, sizeof(struct objc_protocol_t)); 6440 if (O->isLittleEndian() != sys::IsLittleEndianHost) 6441 swapStruct(protocol); 6442 paddr = addr + (p - sect); 6443 outs() << "Protocol " << format("0x%" PRIx32, paddr); 6444 if (print_protocol(paddr, 0, &info)) 6445 outs() << "(not in an __OBJC section)\n"; 6446 } 6447 } 6448 6449 #ifdef HAVE_LIBXAR 6450 static inline void swapStruct(struct xar_header &xar) { 6451 sys::swapByteOrder(xar.magic); 6452 sys::swapByteOrder(xar.size); 6453 sys::swapByteOrder(xar.version); 6454 sys::swapByteOrder(xar.toc_length_compressed); 6455 sys::swapByteOrder(xar.toc_length_uncompressed); 6456 sys::swapByteOrder(xar.cksum_alg); 6457 } 6458 6459 static void PrintModeVerbose(uint32_t mode) { 6460 switch(mode & S_IFMT){ 6461 case S_IFDIR: 6462 outs() << "d"; 6463 break; 6464 case S_IFCHR: 6465 outs() << "c"; 6466 break; 6467 case S_IFBLK: 6468 outs() << "b"; 6469 break; 6470 case S_IFREG: 6471 outs() << "-"; 6472 break; 6473 case S_IFLNK: 6474 outs() << "l"; 6475 break; 6476 case S_IFSOCK: 6477 outs() << "s"; 6478 break; 6479 default: 6480 outs() << "?"; 6481 break; 6482 } 6483 6484 /* owner permissions */ 6485 if(mode & S_IREAD) 6486 outs() << "r"; 6487 else 6488 outs() << "-"; 6489 if(mode & S_IWRITE) 6490 outs() << "w"; 6491 else 6492 outs() << "-"; 6493 if(mode & S_ISUID) 6494 outs() << "s"; 6495 else if(mode & S_IEXEC) 6496 outs() << "x"; 6497 else 6498 outs() << "-"; 6499 6500 /* group permissions */ 6501 if(mode & (S_IREAD >> 3)) 6502 outs() << "r"; 6503 else 6504 outs() << "-"; 6505 if(mode & (S_IWRITE >> 3)) 6506 outs() << "w"; 6507 else 6508 outs() << "-"; 6509 if(mode & S_ISGID) 6510 outs() << "s"; 6511 else if(mode & (S_IEXEC >> 3)) 6512 outs() << "x"; 6513 else 6514 outs() << "-"; 6515 6516 /* other permissions */ 6517 if(mode & (S_IREAD >> 6)) 6518 outs() << "r"; 6519 else 6520 outs() << "-"; 6521 if(mode & (S_IWRITE >> 6)) 6522 outs() << "w"; 6523 else 6524 outs() << "-"; 6525 if(mode & S_ISVTX) 6526 outs() << "t"; 6527 else if(mode & (S_IEXEC >> 6)) 6528 outs() << "x"; 6529 else 6530 outs() << "-"; 6531 } 6532 6533 static void PrintXarFilesSummary(const char *XarFilename, xar_t xar) { 6534 xar_file_t xf; 6535 const char *key, *type, *mode, *user, *group, *size, *mtime, *name, *m; 6536 char *endp; 6537 uint32_t mode_value; 6538 6539 ScopedXarIter xi; 6540 if (!xi) { 6541 WithColor::error(errs(), "llvm-objdump") 6542 << "can't obtain an xar iterator for xar archive " << XarFilename 6543 << "\n"; 6544 return; 6545 } 6546 6547 // Go through the xar's files. 6548 for (xf = xar_file_first(xar, xi); xf; xf = xar_file_next(xi)) { 6549 ScopedXarIter xp; 6550 if(!xp){ 6551 WithColor::error(errs(), "llvm-objdump") 6552 << "can't obtain an xar iterator for xar archive " << XarFilename 6553 << "\n"; 6554 return; 6555 } 6556 type = nullptr; 6557 mode = nullptr; 6558 user = nullptr; 6559 group = nullptr; 6560 size = nullptr; 6561 mtime = nullptr; 6562 name = nullptr; 6563 for(key = xar_prop_first(xf, xp); key; key = xar_prop_next(xp)){ 6564 const char *val = nullptr; 6565 xar_prop_get(xf, key, &val); 6566 #if 0 // Useful for debugging. 6567 outs() << "key: " << key << " value: " << val << "\n"; 6568 #endif 6569 if(strcmp(key, "type") == 0) 6570 type = val; 6571 if(strcmp(key, "mode") == 0) 6572 mode = val; 6573 if(strcmp(key, "user") == 0) 6574 user = val; 6575 if(strcmp(key, "group") == 0) 6576 group = val; 6577 if(strcmp(key, "data/size") == 0) 6578 size = val; 6579 if(strcmp(key, "mtime") == 0) 6580 mtime = val; 6581 if(strcmp(key, "name") == 0) 6582 name = val; 6583 } 6584 if(mode != nullptr){ 6585 mode_value = strtoul(mode, &endp, 8); 6586 if(*endp != '\0') 6587 outs() << "(mode: \"" << mode << "\" contains non-octal chars) "; 6588 if(strcmp(type, "file") == 0) 6589 mode_value |= S_IFREG; 6590 PrintModeVerbose(mode_value); 6591 outs() << " "; 6592 } 6593 if(user != nullptr) 6594 outs() << format("%10s/", user); 6595 if(group != nullptr) 6596 outs() << format("%-10s ", group); 6597 if(size != nullptr) 6598 outs() << format("%7s ", size); 6599 if(mtime != nullptr){ 6600 for(m = mtime; *m != 'T' && *m != '\0'; m++) 6601 outs() << *m; 6602 if(*m == 'T') 6603 m++; 6604 outs() << " "; 6605 for( ; *m != 'Z' && *m != '\0'; m++) 6606 outs() << *m; 6607 outs() << " "; 6608 } 6609 if(name != nullptr) 6610 outs() << name; 6611 outs() << "\n"; 6612 } 6613 } 6614 6615 static void DumpBitcodeSection(MachOObjectFile *O, const char *sect, 6616 uint32_t size, bool verbose, 6617 bool PrintXarHeader, bool PrintXarFileHeaders, 6618 std::string XarMemberName) { 6619 if(size < sizeof(struct xar_header)) { 6620 outs() << "size of (__LLVM,__bundle) section too small (smaller than size " 6621 "of struct xar_header)\n"; 6622 return; 6623 } 6624 struct xar_header XarHeader; 6625 memcpy(&XarHeader, sect, sizeof(struct xar_header)); 6626 if (sys::IsLittleEndianHost) 6627 swapStruct(XarHeader); 6628 if (PrintXarHeader) { 6629 if (!XarMemberName.empty()) 6630 outs() << "In xar member " << XarMemberName << ": "; 6631 else 6632 outs() << "For (__LLVM,__bundle) section: "; 6633 outs() << "xar header\n"; 6634 if (XarHeader.magic == XAR_HEADER_MAGIC) 6635 outs() << " magic XAR_HEADER_MAGIC\n"; 6636 else 6637 outs() << " magic " 6638 << format_hex(XarHeader.magic, 10, true) 6639 << " (not XAR_HEADER_MAGIC)\n"; 6640 outs() << " size " << XarHeader.size << "\n"; 6641 outs() << " version " << XarHeader.version << "\n"; 6642 outs() << " toc_length_compressed " << XarHeader.toc_length_compressed 6643 << "\n"; 6644 outs() << "toc_length_uncompressed " << XarHeader.toc_length_uncompressed 6645 << "\n"; 6646 outs() << " cksum_alg "; 6647 switch (XarHeader.cksum_alg) { 6648 case XAR_CKSUM_NONE: 6649 outs() << "XAR_CKSUM_NONE\n"; 6650 break; 6651 case XAR_CKSUM_SHA1: 6652 outs() << "XAR_CKSUM_SHA1\n"; 6653 break; 6654 case XAR_CKSUM_MD5: 6655 outs() << "XAR_CKSUM_MD5\n"; 6656 break; 6657 #ifdef XAR_CKSUM_SHA256 6658 case XAR_CKSUM_SHA256: 6659 outs() << "XAR_CKSUM_SHA256\n"; 6660 break; 6661 #endif 6662 #ifdef XAR_CKSUM_SHA512 6663 case XAR_CKSUM_SHA512: 6664 outs() << "XAR_CKSUM_SHA512\n"; 6665 break; 6666 #endif 6667 default: 6668 outs() << XarHeader.cksum_alg << "\n"; 6669 } 6670 } 6671 6672 SmallString<128> XarFilename; 6673 int FD; 6674 std::error_code XarEC = 6675 sys::fs::createTemporaryFile("llvm-objdump", "xar", FD, XarFilename); 6676 if (XarEC) { 6677 WithColor::error(errs(), "llvm-objdump") << XarEC.message() << "\n"; 6678 return; 6679 } 6680 ToolOutputFile XarFile(XarFilename, FD); 6681 raw_fd_ostream &XarOut = XarFile.os(); 6682 StringRef XarContents(sect, size); 6683 XarOut << XarContents; 6684 XarOut.close(); 6685 if (XarOut.has_error()) 6686 return; 6687 6688 ScopedXarFile xar(XarFilename.c_str(), READ); 6689 if (!xar) { 6690 WithColor::error(errs(), "llvm-objdump") 6691 << "can't create temporary xar archive " << XarFilename << "\n"; 6692 return; 6693 } 6694 6695 SmallString<128> TocFilename; 6696 std::error_code TocEC = 6697 sys::fs::createTemporaryFile("llvm-objdump", "toc", TocFilename); 6698 if (TocEC) { 6699 WithColor::error(errs(), "llvm-objdump") << TocEC.message() << "\n"; 6700 return; 6701 } 6702 xar_serialize(xar, TocFilename.c_str()); 6703 6704 if (PrintXarFileHeaders) { 6705 if (!XarMemberName.empty()) 6706 outs() << "In xar member " << XarMemberName << ": "; 6707 else 6708 outs() << "For (__LLVM,__bundle) section: "; 6709 outs() << "xar archive files:\n"; 6710 PrintXarFilesSummary(XarFilename.c_str(), xar); 6711 } 6712 6713 ErrorOr<std::unique_ptr<MemoryBuffer>> FileOrErr = 6714 MemoryBuffer::getFileOrSTDIN(TocFilename.c_str()); 6715 if (std::error_code EC = FileOrErr.getError()) { 6716 WithColor::error(errs(), "llvm-objdump") << EC.message() << "\n"; 6717 return; 6718 } 6719 std::unique_ptr<MemoryBuffer> &Buffer = FileOrErr.get(); 6720 6721 if (!XarMemberName.empty()) 6722 outs() << "In xar member " << XarMemberName << ": "; 6723 else 6724 outs() << "For (__LLVM,__bundle) section: "; 6725 outs() << "xar table of contents:\n"; 6726 outs() << Buffer->getBuffer() << "\n"; 6727 6728 // TODO: Go through the xar's files. 6729 ScopedXarIter xi; 6730 if(!xi){ 6731 WithColor::error(errs(), "llvm-objdump") 6732 << "can't obtain an xar iterator for xar archive " 6733 << XarFilename.c_str() << "\n"; 6734 return; 6735 } 6736 for(xar_file_t xf = xar_file_first(xar, xi); xf; xf = xar_file_next(xi)){ 6737 const char *key; 6738 const char *member_name, *member_type, *member_size_string; 6739 size_t member_size; 6740 6741 ScopedXarIter xp; 6742 if(!xp){ 6743 WithColor::error(errs(), "llvm-objdump") 6744 << "can't obtain an xar iterator for xar archive " 6745 << XarFilename.c_str() << "\n"; 6746 return; 6747 } 6748 member_name = NULL; 6749 member_type = NULL; 6750 member_size_string = NULL; 6751 for(key = xar_prop_first(xf, xp); key; key = xar_prop_next(xp)){ 6752 const char *val = nullptr; 6753 xar_prop_get(xf, key, &val); 6754 #if 0 // Useful for debugging. 6755 outs() << "key: " << key << " value: " << val << "\n"; 6756 #endif 6757 if (strcmp(key, "name") == 0) 6758 member_name = val; 6759 if (strcmp(key, "type") == 0) 6760 member_type = val; 6761 if (strcmp(key, "data/size") == 0) 6762 member_size_string = val; 6763 } 6764 /* 6765 * If we find a file with a name, date/size and type properties 6766 * and with the type being "file" see if that is a xar file. 6767 */ 6768 if (member_name != NULL && member_type != NULL && 6769 strcmp(member_type, "file") == 0 && 6770 member_size_string != NULL){ 6771 // Extract the file into a buffer. 6772 char *endptr; 6773 member_size = strtoul(member_size_string, &endptr, 10); 6774 if (*endptr == '\0' && member_size != 0) { 6775 char *buffer; 6776 if (xar_extract_tobuffersz(xar, xf, &buffer, &member_size) == 0) { 6777 #if 0 // Useful for debugging. 6778 outs() << "xar member: " << member_name << " extracted\n"; 6779 #endif 6780 // Set the XarMemberName we want to see printed in the header. 6781 std::string OldXarMemberName; 6782 // If XarMemberName is already set this is nested. So 6783 // save the old name and create the nested name. 6784 if (!XarMemberName.empty()) { 6785 OldXarMemberName = XarMemberName; 6786 XarMemberName = 6787 (Twine("[") + XarMemberName + "]" + member_name).str(); 6788 } else { 6789 OldXarMemberName = ""; 6790 XarMemberName = member_name; 6791 } 6792 // See if this is could be a xar file (nested). 6793 if (member_size >= sizeof(struct xar_header)) { 6794 #if 0 // Useful for debugging. 6795 outs() << "could be a xar file: " << member_name << "\n"; 6796 #endif 6797 memcpy((char *)&XarHeader, buffer, sizeof(struct xar_header)); 6798 if (sys::IsLittleEndianHost) 6799 swapStruct(XarHeader); 6800 if (XarHeader.magic == XAR_HEADER_MAGIC) 6801 DumpBitcodeSection(O, buffer, member_size, verbose, 6802 PrintXarHeader, PrintXarFileHeaders, 6803 XarMemberName); 6804 } 6805 XarMemberName = OldXarMemberName; 6806 delete buffer; 6807 } 6808 } 6809 } 6810 } 6811 } 6812 #endif // defined(HAVE_LIBXAR) 6813 6814 static void printObjcMetaData(MachOObjectFile *O, bool verbose) { 6815 if (O->is64Bit()) 6816 printObjc2_64bit_MetaData(O, verbose); 6817 else { 6818 MachO::mach_header H; 6819 H = O->getHeader(); 6820 if (H.cputype == MachO::CPU_TYPE_ARM) 6821 printObjc2_32bit_MetaData(O, verbose); 6822 else { 6823 // This is the 32-bit non-arm cputype case. Which is normally 6824 // the first Objective-C ABI. But it may be the case of a 6825 // binary for the iOS simulator which is the second Objective-C 6826 // ABI. In that case printObjc1_32bit_MetaData() will determine that 6827 // and return false. 6828 if (!printObjc1_32bit_MetaData(O, verbose)) 6829 printObjc2_32bit_MetaData(O, verbose); 6830 } 6831 } 6832 } 6833 6834 // GuessLiteralPointer returns a string which for the item in the Mach-O file 6835 // for the address passed in as ReferenceValue for printing as a comment with 6836 // the instruction and also returns the corresponding type of that item 6837 // indirectly through ReferenceType. 6838 // 6839 // If ReferenceValue is an address of literal cstring then a pointer to the 6840 // cstring is returned and ReferenceType is set to 6841 // LLVMDisassembler_ReferenceType_Out_LitPool_CstrAddr . 6842 // 6843 // If ReferenceValue is an address of an Objective-C CFString, Selector ref or 6844 // Class ref that name is returned and the ReferenceType is set accordingly. 6845 // 6846 // Lastly, literals which are Symbol address in a literal pool are looked for 6847 // and if found the symbol name is returned and ReferenceType is set to 6848 // LLVMDisassembler_ReferenceType_Out_LitPool_SymAddr . 6849 // 6850 // If there is no item in the Mach-O file for the address passed in as 6851 // ReferenceValue nullptr is returned and ReferenceType is unchanged. 6852 static const char *GuessLiteralPointer(uint64_t ReferenceValue, 6853 uint64_t ReferencePC, 6854 uint64_t *ReferenceType, 6855 struct DisassembleInfo *info) { 6856 // First see if there is an external relocation entry at the ReferencePC. 6857 if (info->O->getHeader().filetype == MachO::MH_OBJECT) { 6858 uint64_t sect_addr = info->S.getAddress(); 6859 uint64_t sect_offset = ReferencePC - sect_addr; 6860 bool reloc_found = false; 6861 DataRefImpl Rel; 6862 MachO::any_relocation_info RE; 6863 bool isExtern = false; 6864 SymbolRef Symbol; 6865 for (const RelocationRef &Reloc : info->S.relocations()) { 6866 uint64_t RelocOffset = Reloc.getOffset(); 6867 if (RelocOffset == sect_offset) { 6868 Rel = Reloc.getRawDataRefImpl(); 6869 RE = info->O->getRelocation(Rel); 6870 if (info->O->isRelocationScattered(RE)) 6871 continue; 6872 isExtern = info->O->getPlainRelocationExternal(RE); 6873 if (isExtern) { 6874 symbol_iterator RelocSym = Reloc.getSymbol(); 6875 Symbol = *RelocSym; 6876 } 6877 reloc_found = true; 6878 break; 6879 } 6880 } 6881 // If there is an external relocation entry for a symbol in a section 6882 // then used that symbol's value for the value of the reference. 6883 if (reloc_found && isExtern) { 6884 if (info->O->getAnyRelocationPCRel(RE)) { 6885 unsigned Type = info->O->getAnyRelocationType(RE); 6886 if (Type == MachO::X86_64_RELOC_SIGNED) { 6887 ReferenceValue = cantFail(Symbol.getValue()); 6888 } 6889 } 6890 } 6891 } 6892 6893 // Look for literals such as Objective-C CFStrings refs, Selector refs, 6894 // Message refs and Class refs. 6895 bool classref, selref, msgref, cfstring; 6896 uint64_t pointer_value = GuessPointerPointer(ReferenceValue, info, classref, 6897 selref, msgref, cfstring); 6898 if (classref && pointer_value == 0) { 6899 // Note the ReferenceValue is a pointer into the __objc_classrefs section. 6900 // And the pointer_value in that section is typically zero as it will be 6901 // set by dyld as part of the "bind information". 6902 const char *name = get_dyld_bind_info_symbolname(ReferenceValue, info); 6903 if (name != nullptr) { 6904 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Class_Ref; 6905 const char *class_name = strrchr(name, '$'); 6906 if (class_name != nullptr && class_name[1] == '_' && 6907 class_name[2] != '\0') { 6908 info->class_name = class_name + 2; 6909 return name; 6910 } 6911 } 6912 } 6913 6914 if (classref) { 6915 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Class_Ref; 6916 const char *name = 6917 get_objc2_64bit_class_name(pointer_value, ReferenceValue, info); 6918 if (name != nullptr) 6919 info->class_name = name; 6920 else 6921 name = "bad class ref"; 6922 return name; 6923 } 6924 6925 if (cfstring) { 6926 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_CFString_Ref; 6927 const char *name = get_objc2_64bit_cfstring_name(ReferenceValue, info); 6928 return name; 6929 } 6930 6931 if (selref && pointer_value == 0) 6932 pointer_value = get_objc2_64bit_selref(ReferenceValue, info); 6933 6934 if (pointer_value != 0) 6935 ReferenceValue = pointer_value; 6936 6937 const char *name = GuessCstringPointer(ReferenceValue, info); 6938 if (name) { 6939 if (pointer_value != 0 && selref) { 6940 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Selector_Ref; 6941 info->selector_name = name; 6942 } else if (pointer_value != 0 && msgref) { 6943 info->class_name = nullptr; 6944 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message_Ref; 6945 info->selector_name = name; 6946 } else 6947 *ReferenceType = LLVMDisassembler_ReferenceType_Out_LitPool_CstrAddr; 6948 return name; 6949 } 6950 6951 // Lastly look for an indirect symbol with this ReferenceValue which is in 6952 // a literal pool. If found return that symbol name. 6953 name = GuessIndirectSymbol(ReferenceValue, info); 6954 if (name) { 6955 *ReferenceType = LLVMDisassembler_ReferenceType_Out_LitPool_SymAddr; 6956 return name; 6957 } 6958 6959 return nullptr; 6960 } 6961 6962 // SymbolizerSymbolLookUp is the symbol lookup function passed when creating 6963 // the Symbolizer. It looks up the ReferenceValue using the info passed via the 6964 // pointer to the struct DisassembleInfo that was passed when MCSymbolizer 6965 // is created and returns the symbol name that matches the ReferenceValue or 6966 // nullptr if none. The ReferenceType is passed in for the IN type of 6967 // reference the instruction is making from the values in defined in the header 6968 // "llvm-c/Disassembler.h". On return the ReferenceType can set to a specific 6969 // Out type and the ReferenceName will also be set which is added as a comment 6970 // to the disassembled instruction. 6971 // 6972 // If the symbol name is a C++ mangled name then the demangled name is 6973 // returned through ReferenceName and ReferenceType is set to 6974 // LLVMDisassembler_ReferenceType_DeMangled_Name . 6975 // 6976 // When this is called to get a symbol name for a branch target then the 6977 // ReferenceType will be LLVMDisassembler_ReferenceType_In_Branch and then 6978 // SymbolValue will be looked for in the indirect symbol table to determine if 6979 // it is an address for a symbol stub. If so then the symbol name for that 6980 // stub is returned indirectly through ReferenceName and then ReferenceType is 6981 // set to LLVMDisassembler_ReferenceType_Out_SymbolStub. 6982 // 6983 // When this is called with an value loaded via a PC relative load then 6984 // ReferenceType will be LLVMDisassembler_ReferenceType_In_PCrel_Load then the 6985 // SymbolValue is checked to be an address of literal pointer, symbol pointer, 6986 // or an Objective-C meta data reference. If so the output ReferenceType is 6987 // set to correspond to that as well as setting the ReferenceName. 6988 static const char *SymbolizerSymbolLookUp(void *DisInfo, 6989 uint64_t ReferenceValue, 6990 uint64_t *ReferenceType, 6991 uint64_t ReferencePC, 6992 const char **ReferenceName) { 6993 struct DisassembleInfo *info = (struct DisassembleInfo *)DisInfo; 6994 // If no verbose symbolic information is wanted then just return nullptr. 6995 if (!info->verbose) { 6996 *ReferenceName = nullptr; 6997 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None; 6998 return nullptr; 6999 } 7000 7001 const char *SymbolName = GuessSymbolName(ReferenceValue, info->AddrMap); 7002 7003 if (*ReferenceType == LLVMDisassembler_ReferenceType_In_Branch) { 7004 *ReferenceName = GuessIndirectSymbol(ReferenceValue, info); 7005 if (*ReferenceName != nullptr) { 7006 method_reference(info, ReferenceType, ReferenceName); 7007 if (*ReferenceType != LLVMDisassembler_ReferenceType_Out_Objc_Message) 7008 *ReferenceType = LLVMDisassembler_ReferenceType_Out_SymbolStub; 7009 } else if (SymbolName != nullptr && strncmp(SymbolName, "__Z", 3) == 0) { 7010 if (info->demangled_name != nullptr) 7011 free(info->demangled_name); 7012 int status; 7013 info->demangled_name = 7014 itaniumDemangle(SymbolName + 1, nullptr, nullptr, &status); 7015 if (info->demangled_name != nullptr) { 7016 *ReferenceName = info->demangled_name; 7017 *ReferenceType = LLVMDisassembler_ReferenceType_DeMangled_Name; 7018 } else 7019 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None; 7020 } else 7021 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None; 7022 } else if (*ReferenceType == LLVMDisassembler_ReferenceType_In_PCrel_Load) { 7023 *ReferenceName = 7024 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info); 7025 if (*ReferenceName) 7026 method_reference(info, ReferenceType, ReferenceName); 7027 else 7028 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None; 7029 // If this is arm64 and the reference is an adrp instruction save the 7030 // instruction, passed in ReferenceValue and the address of the instruction 7031 // for use later if we see and add immediate instruction. 7032 } else if (info->O->getArch() == Triple::aarch64 && 7033 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADRP) { 7034 info->adrp_inst = ReferenceValue; 7035 info->adrp_addr = ReferencePC; 7036 SymbolName = nullptr; 7037 *ReferenceName = nullptr; 7038 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None; 7039 // If this is arm64 and reference is an add immediate instruction and we 7040 // have 7041 // seen an adrp instruction just before it and the adrp's Xd register 7042 // matches 7043 // this add's Xn register reconstruct the value being referenced and look to 7044 // see if it is a literal pointer. Note the add immediate instruction is 7045 // passed in ReferenceValue. 7046 } else if (info->O->getArch() == Triple::aarch64 && 7047 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADDXri && 7048 ReferencePC - 4 == info->adrp_addr && 7049 (info->adrp_inst & 0x9f000000) == 0x90000000 && 7050 (info->adrp_inst & 0x1f) == ((ReferenceValue >> 5) & 0x1f)) { 7051 uint32_t addxri_inst; 7052 uint64_t adrp_imm, addxri_imm; 7053 7054 adrp_imm = 7055 ((info->adrp_inst & 0x00ffffe0) >> 3) | ((info->adrp_inst >> 29) & 0x3); 7056 if (info->adrp_inst & 0x0200000) 7057 adrp_imm |= 0xfffffffffc000000LL; 7058 7059 addxri_inst = ReferenceValue; 7060 addxri_imm = (addxri_inst >> 10) & 0xfff; 7061 if (((addxri_inst >> 22) & 0x3) == 1) 7062 addxri_imm <<= 12; 7063 7064 ReferenceValue = (info->adrp_addr & 0xfffffffffffff000LL) + 7065 (adrp_imm << 12) + addxri_imm; 7066 7067 *ReferenceName = 7068 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info); 7069 if (*ReferenceName == nullptr) 7070 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None; 7071 // If this is arm64 and the reference is a load register instruction and we 7072 // have seen an adrp instruction just before it and the adrp's Xd register 7073 // matches this add's Xn register reconstruct the value being referenced and 7074 // look to see if it is a literal pointer. Note the load register 7075 // instruction is passed in ReferenceValue. 7076 } else if (info->O->getArch() == Triple::aarch64 && 7077 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_LDRXui && 7078 ReferencePC - 4 == info->adrp_addr && 7079 (info->adrp_inst & 0x9f000000) == 0x90000000 && 7080 (info->adrp_inst & 0x1f) == ((ReferenceValue >> 5) & 0x1f)) { 7081 uint32_t ldrxui_inst; 7082 uint64_t adrp_imm, ldrxui_imm; 7083 7084 adrp_imm = 7085 ((info->adrp_inst & 0x00ffffe0) >> 3) | ((info->adrp_inst >> 29) & 0x3); 7086 if (info->adrp_inst & 0x0200000) 7087 adrp_imm |= 0xfffffffffc000000LL; 7088 7089 ldrxui_inst = ReferenceValue; 7090 ldrxui_imm = (ldrxui_inst >> 10) & 0xfff; 7091 7092 ReferenceValue = (info->adrp_addr & 0xfffffffffffff000LL) + 7093 (adrp_imm << 12) + (ldrxui_imm << 3); 7094 7095 *ReferenceName = 7096 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info); 7097 if (*ReferenceName == nullptr) 7098 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None; 7099 } 7100 // If this arm64 and is an load register (PC-relative) instruction the 7101 // ReferenceValue is the PC plus the immediate value. 7102 else if (info->O->getArch() == Triple::aarch64 && 7103 (*ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_LDRXl || 7104 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADR)) { 7105 *ReferenceName = 7106 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info); 7107 if (*ReferenceName == nullptr) 7108 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None; 7109 } else if (SymbolName != nullptr && strncmp(SymbolName, "__Z", 3) == 0) { 7110 if (info->demangled_name != nullptr) 7111 free(info->demangled_name); 7112 int status; 7113 info->demangled_name = 7114 itaniumDemangle(SymbolName + 1, nullptr, nullptr, &status); 7115 if (info->demangled_name != nullptr) { 7116 *ReferenceName = info->demangled_name; 7117 *ReferenceType = LLVMDisassembler_ReferenceType_DeMangled_Name; 7118 } 7119 } 7120 else { 7121 *ReferenceName = nullptr; 7122 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None; 7123 } 7124 7125 return SymbolName; 7126 } 7127 7128 /// Emits the comments that are stored in the CommentStream. 7129 /// Each comment in the CommentStream must end with a newline. 7130 static void emitComments(raw_svector_ostream &CommentStream, 7131 SmallString<128> &CommentsToEmit, 7132 formatted_raw_ostream &FormattedOS, 7133 const MCAsmInfo &MAI) { 7134 // Flush the stream before taking its content. 7135 StringRef Comments = CommentsToEmit.str(); 7136 // Get the default information for printing a comment. 7137 StringRef CommentBegin = MAI.getCommentString(); 7138 unsigned CommentColumn = MAI.getCommentColumn(); 7139 ListSeparator LS("\n"); 7140 while (!Comments.empty()) { 7141 FormattedOS << LS; 7142 // Emit a line of comments. 7143 FormattedOS.PadToColumn(CommentColumn); 7144 size_t Position = Comments.find('\n'); 7145 FormattedOS << CommentBegin << ' ' << Comments.substr(0, Position); 7146 // Move after the newline character. 7147 Comments = Comments.substr(Position + 1); 7148 } 7149 FormattedOS.flush(); 7150 7151 // Tell the comment stream that the vector changed underneath it. 7152 CommentsToEmit.clear(); 7153 } 7154 7155 static void DisassembleMachO(StringRef Filename, MachOObjectFile *MachOOF, 7156 StringRef DisSegName, StringRef DisSectName) { 7157 const char *McpuDefault = nullptr; 7158 const Target *ThumbTarget = nullptr; 7159 const Target *TheTarget = GetTarget(MachOOF, &McpuDefault, &ThumbTarget); 7160 if (!TheTarget) { 7161 // GetTarget prints out stuff. 7162 return; 7163 } 7164 std::string MachOMCPU; 7165 if (MCPU.empty() && McpuDefault) 7166 MachOMCPU = McpuDefault; 7167 else 7168 MachOMCPU = MCPU; 7169 7170 #define CHECK_TARGET_INFO_CREATION(NAME) \ 7171 do { \ 7172 if (!NAME) { \ 7173 WithColor::error(errs(), "llvm-objdump") \ 7174 << "couldn't initialize disassembler for target " << TripleName \ 7175 << '\n'; \ 7176 return; \ 7177 } \ 7178 } while (false) 7179 #define CHECK_THUMB_TARGET_INFO_CREATION(NAME) \ 7180 do { \ 7181 if (!NAME) { \ 7182 WithColor::error(errs(), "llvm-objdump") \ 7183 << "couldn't initialize disassembler for target " << ThumbTripleName \ 7184 << '\n'; \ 7185 return; \ 7186 } \ 7187 } while (false) 7188 7189 std::unique_ptr<const MCInstrInfo> InstrInfo(TheTarget->createMCInstrInfo()); 7190 CHECK_TARGET_INFO_CREATION(InstrInfo); 7191 std::unique_ptr<const MCInstrInfo> ThumbInstrInfo; 7192 if (ThumbTarget) { 7193 ThumbInstrInfo.reset(ThumbTarget->createMCInstrInfo()); 7194 CHECK_THUMB_TARGET_INFO_CREATION(ThumbInstrInfo); 7195 } 7196 7197 // Package up features to be passed to target/subtarget 7198 std::string FeaturesStr; 7199 if (!MAttrs.empty()) { 7200 SubtargetFeatures Features; 7201 for (unsigned i = 0; i != MAttrs.size(); ++i) 7202 Features.AddFeature(MAttrs[i]); 7203 FeaturesStr = Features.getString(); 7204 } 7205 7206 MCTargetOptions MCOptions; 7207 // Set up disassembler. 7208 std::unique_ptr<const MCRegisterInfo> MRI( 7209 TheTarget->createMCRegInfo(TripleName)); 7210 CHECK_TARGET_INFO_CREATION(MRI); 7211 std::unique_ptr<const MCAsmInfo> AsmInfo( 7212 TheTarget->createMCAsmInfo(*MRI, TripleName, MCOptions)); 7213 CHECK_TARGET_INFO_CREATION(AsmInfo); 7214 std::unique_ptr<const MCSubtargetInfo> STI( 7215 TheTarget->createMCSubtargetInfo(TripleName, MachOMCPU, FeaturesStr)); 7216 CHECK_TARGET_INFO_CREATION(STI); 7217 MCContext Ctx(AsmInfo.get(), MRI.get(), nullptr); 7218 std::unique_ptr<MCDisassembler> DisAsm( 7219 TheTarget->createMCDisassembler(*STI, Ctx)); 7220 CHECK_TARGET_INFO_CREATION(DisAsm); 7221 std::unique_ptr<MCSymbolizer> Symbolizer; 7222 struct DisassembleInfo SymbolizerInfo(nullptr, nullptr, nullptr, false); 7223 std::unique_ptr<MCRelocationInfo> RelInfo( 7224 TheTarget->createMCRelocationInfo(TripleName, Ctx)); 7225 if (RelInfo) { 7226 Symbolizer.reset(TheTarget->createMCSymbolizer( 7227 TripleName, SymbolizerGetOpInfo, SymbolizerSymbolLookUp, 7228 &SymbolizerInfo, &Ctx, std::move(RelInfo))); 7229 DisAsm->setSymbolizer(std::move(Symbolizer)); 7230 } 7231 int AsmPrinterVariant = AsmInfo->getAssemblerDialect(); 7232 std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter( 7233 Triple(TripleName), AsmPrinterVariant, *AsmInfo, *InstrInfo, *MRI)); 7234 CHECK_TARGET_INFO_CREATION(IP); 7235 // Set the display preference for hex vs. decimal immediates. 7236 IP->setPrintImmHex(PrintImmHex); 7237 // Comment stream and backing vector. 7238 SmallString<128> CommentsToEmit; 7239 raw_svector_ostream CommentStream(CommentsToEmit); 7240 // FIXME: Setting the CommentStream in the InstPrinter is problematic in that 7241 // if it is done then arm64 comments for string literals don't get printed 7242 // and some constant get printed instead and not setting it causes intel 7243 // (32-bit and 64-bit) comments printed with different spacing before the 7244 // comment causing different diffs with the 'C' disassembler library API. 7245 // IP->setCommentStream(CommentStream); 7246 7247 // Set up separate thumb disassembler if needed. 7248 std::unique_ptr<const MCRegisterInfo> ThumbMRI; 7249 std::unique_ptr<const MCAsmInfo> ThumbAsmInfo; 7250 std::unique_ptr<const MCSubtargetInfo> ThumbSTI; 7251 std::unique_ptr<MCDisassembler> ThumbDisAsm; 7252 std::unique_ptr<MCInstPrinter> ThumbIP; 7253 std::unique_ptr<MCContext> ThumbCtx; 7254 std::unique_ptr<MCSymbolizer> ThumbSymbolizer; 7255 struct DisassembleInfo ThumbSymbolizerInfo(nullptr, nullptr, nullptr, false); 7256 std::unique_ptr<MCRelocationInfo> ThumbRelInfo; 7257 if (ThumbTarget) { 7258 ThumbMRI.reset(ThumbTarget->createMCRegInfo(ThumbTripleName)); 7259 CHECK_THUMB_TARGET_INFO_CREATION(ThumbMRI); 7260 ThumbAsmInfo.reset( 7261 ThumbTarget->createMCAsmInfo(*ThumbMRI, ThumbTripleName, MCOptions)); 7262 CHECK_THUMB_TARGET_INFO_CREATION(ThumbAsmInfo); 7263 ThumbSTI.reset( 7264 ThumbTarget->createMCSubtargetInfo(ThumbTripleName, MachOMCPU, 7265 FeaturesStr)); 7266 CHECK_THUMB_TARGET_INFO_CREATION(ThumbSTI); 7267 ThumbCtx.reset(new MCContext(ThumbAsmInfo.get(), ThumbMRI.get(), nullptr)); 7268 ThumbDisAsm.reset(ThumbTarget->createMCDisassembler(*ThumbSTI, *ThumbCtx)); 7269 CHECK_THUMB_TARGET_INFO_CREATION(ThumbDisAsm); 7270 MCContext *PtrThumbCtx = ThumbCtx.get(); 7271 ThumbRelInfo.reset( 7272 ThumbTarget->createMCRelocationInfo(ThumbTripleName, *PtrThumbCtx)); 7273 if (ThumbRelInfo) { 7274 ThumbSymbolizer.reset(ThumbTarget->createMCSymbolizer( 7275 ThumbTripleName, SymbolizerGetOpInfo, SymbolizerSymbolLookUp, 7276 &ThumbSymbolizerInfo, PtrThumbCtx, std::move(ThumbRelInfo))); 7277 ThumbDisAsm->setSymbolizer(std::move(ThumbSymbolizer)); 7278 } 7279 int ThumbAsmPrinterVariant = ThumbAsmInfo->getAssemblerDialect(); 7280 ThumbIP.reset(ThumbTarget->createMCInstPrinter( 7281 Triple(ThumbTripleName), ThumbAsmPrinterVariant, *ThumbAsmInfo, 7282 *ThumbInstrInfo, *ThumbMRI)); 7283 CHECK_THUMB_TARGET_INFO_CREATION(ThumbIP); 7284 // Set the display preference for hex vs. decimal immediates. 7285 ThumbIP->setPrintImmHex(PrintImmHex); 7286 } 7287 7288 #undef CHECK_TARGET_INFO_CREATION 7289 #undef CHECK_THUMB_TARGET_INFO_CREATION 7290 7291 MachO::mach_header Header = MachOOF->getHeader(); 7292 7293 // FIXME: Using the -cfg command line option, this code used to be able to 7294 // annotate relocations with the referenced symbol's name, and if this was 7295 // inside a __[cf]string section, the data it points to. This is now replaced 7296 // by the upcoming MCSymbolizer, which needs the appropriate setup done above. 7297 std::vector<SectionRef> Sections; 7298 std::vector<SymbolRef> Symbols; 7299 SmallVector<uint64_t, 8> FoundFns; 7300 uint64_t BaseSegmentAddress = 0; 7301 7302 getSectionsAndSymbols(MachOOF, Sections, Symbols, FoundFns, 7303 BaseSegmentAddress); 7304 7305 // Sort the symbols by address, just in case they didn't come in that way. 7306 llvm::sort(Symbols, SymbolSorter()); 7307 7308 // Build a data in code table that is sorted on by the address of each entry. 7309 uint64_t BaseAddress = 0; 7310 if (Header.filetype == MachO::MH_OBJECT) 7311 BaseAddress = Sections[0].getAddress(); 7312 else 7313 BaseAddress = BaseSegmentAddress; 7314 DiceTable Dices; 7315 for (dice_iterator DI = MachOOF->begin_dices(), DE = MachOOF->end_dices(); 7316 DI != DE; ++DI) { 7317 uint32_t Offset; 7318 DI->getOffset(Offset); 7319 Dices.push_back(std::make_pair(BaseAddress + Offset, *DI)); 7320 } 7321 array_pod_sort(Dices.begin(), Dices.end()); 7322 7323 // Try to find debug info and set up the DIContext for it. 7324 std::unique_ptr<DIContext> diContext; 7325 std::unique_ptr<Binary> DSYMBinary; 7326 std::unique_ptr<MemoryBuffer> DSYMBuf; 7327 if (UseDbg) { 7328 ObjectFile *DbgObj = MachOOF; 7329 7330 // A separate DSym file path was specified, parse it as a macho file, 7331 // get the sections and supply it to the section name parsing machinery. 7332 if (!DSYMFile.empty()) { 7333 std::string DSYMPath(DSYMFile); 7334 7335 // If DSYMPath is a .dSYM directory, append the Mach-O file. 7336 if (llvm::sys::fs::is_directory(DSYMPath) && 7337 llvm::sys::path::extension(DSYMPath) == ".dSYM") { 7338 SmallString<128> ShortName(llvm::sys::path::filename(DSYMPath)); 7339 llvm::sys::path::replace_extension(ShortName, ""); 7340 SmallString<1024> FullPath(DSYMPath); 7341 llvm::sys::path::append(FullPath, "Contents", "Resources", "DWARF", 7342 ShortName); 7343 DSYMPath = std::string(FullPath.str()); 7344 } 7345 7346 // Load the file. 7347 ErrorOr<std::unique_ptr<MemoryBuffer>> BufOrErr = 7348 MemoryBuffer::getFileOrSTDIN(DSYMPath); 7349 if (std::error_code EC = BufOrErr.getError()) { 7350 reportError(errorCodeToError(EC), DSYMPath); 7351 return; 7352 } 7353 7354 // We need to keep the file alive, because we're replacing DbgObj with it. 7355 DSYMBuf = std::move(BufOrErr.get()); 7356 7357 Expected<std::unique_ptr<Binary>> BinaryOrErr = 7358 createBinary(DSYMBuf.get()->getMemBufferRef()); 7359 if (!BinaryOrErr) { 7360 reportError(BinaryOrErr.takeError(), DSYMPath); 7361 return; 7362 } 7363 7364 // We need to keep the Binary alive with the buffer 7365 DSYMBinary = std::move(BinaryOrErr.get()); 7366 if (ObjectFile *O = dyn_cast<ObjectFile>(DSYMBinary.get())) { 7367 // this is a Mach-O object file, use it 7368 if (MachOObjectFile *MachDSYM = dyn_cast<MachOObjectFile>(&*O)) { 7369 DbgObj = MachDSYM; 7370 } 7371 else { 7372 WithColor::error(errs(), "llvm-objdump") 7373 << DSYMPath << " is not a Mach-O file type.\n"; 7374 return; 7375 } 7376 } 7377 else if (auto UB = dyn_cast<MachOUniversalBinary>(DSYMBinary.get())){ 7378 // this is a Universal Binary, find a Mach-O for this architecture 7379 uint32_t CPUType, CPUSubType; 7380 const char *ArchFlag; 7381 if (MachOOF->is64Bit()) { 7382 const MachO::mach_header_64 H_64 = MachOOF->getHeader64(); 7383 CPUType = H_64.cputype; 7384 CPUSubType = H_64.cpusubtype; 7385 } else { 7386 const MachO::mach_header H = MachOOF->getHeader(); 7387 CPUType = H.cputype; 7388 CPUSubType = H.cpusubtype; 7389 } 7390 Triple T = MachOObjectFile::getArchTriple(CPUType, CPUSubType, nullptr, 7391 &ArchFlag); 7392 Expected<std::unique_ptr<MachOObjectFile>> MachDSYM = 7393 UB->getMachOObjectForArch(ArchFlag); 7394 if (!MachDSYM) { 7395 reportError(MachDSYM.takeError(), DSYMPath); 7396 return; 7397 } 7398 7399 // We need to keep the Binary alive with the buffer 7400 DbgObj = &*MachDSYM.get(); 7401 DSYMBinary = std::move(*MachDSYM); 7402 } 7403 else { 7404 WithColor::error(errs(), "llvm-objdump") 7405 << DSYMPath << " is not a Mach-O or Universal file type.\n"; 7406 return; 7407 } 7408 } 7409 7410 // Setup the DIContext 7411 diContext = DWARFContext::create(*DbgObj); 7412 } 7413 7414 if (FilterSections.empty()) 7415 outs() << "(" << DisSegName << "," << DisSectName << ") section\n"; 7416 7417 for (unsigned SectIdx = 0; SectIdx != Sections.size(); SectIdx++) { 7418 Expected<StringRef> SecNameOrErr = Sections[SectIdx].getName(); 7419 if (!SecNameOrErr) { 7420 consumeError(SecNameOrErr.takeError()); 7421 continue; 7422 } 7423 if (*SecNameOrErr != DisSectName) 7424 continue; 7425 7426 DataRefImpl DR = Sections[SectIdx].getRawDataRefImpl(); 7427 7428 StringRef SegmentName = MachOOF->getSectionFinalSegmentName(DR); 7429 if (SegmentName != DisSegName) 7430 continue; 7431 7432 StringRef BytesStr = 7433 unwrapOrError(Sections[SectIdx].getContents(), Filename); 7434 ArrayRef<uint8_t> Bytes = arrayRefFromStringRef(BytesStr); 7435 uint64_t SectAddress = Sections[SectIdx].getAddress(); 7436 7437 bool symbolTableWorked = false; 7438 7439 // Create a map of symbol addresses to symbol names for use by 7440 // the SymbolizerSymbolLookUp() routine. 7441 SymbolAddressMap AddrMap; 7442 bool DisSymNameFound = false; 7443 for (const SymbolRef &Symbol : MachOOF->symbols()) { 7444 SymbolRef::Type ST = 7445 unwrapOrError(Symbol.getType(), MachOOF->getFileName()); 7446 if (ST == SymbolRef::ST_Function || ST == SymbolRef::ST_Data || 7447 ST == SymbolRef::ST_Other) { 7448 uint64_t Address = cantFail(Symbol.getValue()); 7449 StringRef SymName = 7450 unwrapOrError(Symbol.getName(), MachOOF->getFileName()); 7451 AddrMap[Address] = SymName; 7452 if (!DisSymName.empty() && DisSymName == SymName) 7453 DisSymNameFound = true; 7454 } 7455 } 7456 if (!DisSymName.empty() && !DisSymNameFound) { 7457 outs() << "Can't find -dis-symname: " << DisSymName << "\n"; 7458 return; 7459 } 7460 // Set up the block of info used by the Symbolizer call backs. 7461 SymbolizerInfo.verbose = !NoSymbolicOperands; 7462 SymbolizerInfo.O = MachOOF; 7463 SymbolizerInfo.S = Sections[SectIdx]; 7464 SymbolizerInfo.AddrMap = &AddrMap; 7465 SymbolizerInfo.Sections = &Sections; 7466 // Same for the ThumbSymbolizer 7467 ThumbSymbolizerInfo.verbose = !NoSymbolicOperands; 7468 ThumbSymbolizerInfo.O = MachOOF; 7469 ThumbSymbolizerInfo.S = Sections[SectIdx]; 7470 ThumbSymbolizerInfo.AddrMap = &AddrMap; 7471 ThumbSymbolizerInfo.Sections = &Sections; 7472 7473 unsigned int Arch = MachOOF->getArch(); 7474 7475 // Skip all symbols if this is a stubs file. 7476 if (Bytes.empty()) 7477 return; 7478 7479 // If the section has symbols but no symbol at the start of the section 7480 // these are used to make sure the bytes before the first symbol are 7481 // disassembled. 7482 bool FirstSymbol = true; 7483 bool FirstSymbolAtSectionStart = true; 7484 7485 // Disassemble symbol by symbol. 7486 for (unsigned SymIdx = 0; SymIdx != Symbols.size(); SymIdx++) { 7487 StringRef SymName = 7488 unwrapOrError(Symbols[SymIdx].getName(), MachOOF->getFileName()); 7489 SymbolRef::Type ST = 7490 unwrapOrError(Symbols[SymIdx].getType(), MachOOF->getFileName()); 7491 if (ST != SymbolRef::ST_Function && ST != SymbolRef::ST_Data) 7492 continue; 7493 7494 // Make sure the symbol is defined in this section. 7495 bool containsSym = Sections[SectIdx].containsSymbol(Symbols[SymIdx]); 7496 if (!containsSym) { 7497 if (!DisSymName.empty() && DisSymName == SymName) { 7498 outs() << "-dis-symname: " << DisSymName << " not in the section\n"; 7499 return; 7500 } 7501 continue; 7502 } 7503 // The __mh_execute_header is special and we need to deal with that fact 7504 // this symbol is before the start of the (__TEXT,__text) section and at the 7505 // address of the start of the __TEXT segment. This is because this symbol 7506 // is an N_SECT symbol in the (__TEXT,__text) but its address is before the 7507 // start of the section in a standard MH_EXECUTE filetype. 7508 if (!DisSymName.empty() && DisSymName == "__mh_execute_header") { 7509 outs() << "-dis-symname: __mh_execute_header not in any section\n"; 7510 return; 7511 } 7512 // When this code is trying to disassemble a symbol at a time and in the 7513 // case there is only the __mh_execute_header symbol left as in a stripped 7514 // executable, we need to deal with this by ignoring this symbol so the 7515 // whole section is disassembled and this symbol is then not displayed. 7516 if (SymName == "__mh_execute_header" || SymName == "__mh_dylib_header" || 7517 SymName == "__mh_bundle_header" || SymName == "__mh_object_header" || 7518 SymName == "__mh_preload_header" || SymName == "__mh_dylinker_header") 7519 continue; 7520 7521 // If we are only disassembling one symbol see if this is that symbol. 7522 if (!DisSymName.empty() && DisSymName != SymName) 7523 continue; 7524 7525 // Start at the address of the symbol relative to the section's address. 7526 uint64_t SectSize = Sections[SectIdx].getSize(); 7527 uint64_t Start = cantFail(Symbols[SymIdx].getValue()); 7528 uint64_t SectionAddress = Sections[SectIdx].getAddress(); 7529 Start -= SectionAddress; 7530 7531 if (Start > SectSize) { 7532 outs() << "section data ends, " << SymName 7533 << " lies outside valid range\n"; 7534 return; 7535 } 7536 7537 // Stop disassembling either at the beginning of the next symbol or at 7538 // the end of the section. 7539 bool containsNextSym = false; 7540 uint64_t NextSym = 0; 7541 uint64_t NextSymIdx = SymIdx + 1; 7542 while (Symbols.size() > NextSymIdx) { 7543 SymbolRef::Type NextSymType = unwrapOrError( 7544 Symbols[NextSymIdx].getType(), MachOOF->getFileName()); 7545 if (NextSymType == SymbolRef::ST_Function) { 7546 containsNextSym = 7547 Sections[SectIdx].containsSymbol(Symbols[NextSymIdx]); 7548 NextSym = cantFail(Symbols[NextSymIdx].getValue()); 7549 NextSym -= SectionAddress; 7550 break; 7551 } 7552 ++NextSymIdx; 7553 } 7554 7555 uint64_t End = containsNextSym ? std::min(NextSym, SectSize) : SectSize; 7556 uint64_t Size; 7557 7558 symbolTableWorked = true; 7559 7560 DataRefImpl Symb = Symbols[SymIdx].getRawDataRefImpl(); 7561 uint32_t SymbolFlags = cantFail(MachOOF->getSymbolFlags(Symb)); 7562 bool IsThumb = SymbolFlags & SymbolRef::SF_Thumb; 7563 7564 // We only need the dedicated Thumb target if there's a real choice 7565 // (i.e. we're not targeting M-class) and the function is Thumb. 7566 bool UseThumbTarget = IsThumb && ThumbTarget; 7567 7568 // If we are not specifying a symbol to start disassembly with and this 7569 // is the first symbol in the section but not at the start of the section 7570 // then move the disassembly index to the start of the section and 7571 // don't print the symbol name just yet. This is so the bytes before the 7572 // first symbol are disassembled. 7573 uint64_t SymbolStart = Start; 7574 if (DisSymName.empty() && FirstSymbol && Start != 0) { 7575 FirstSymbolAtSectionStart = false; 7576 Start = 0; 7577 } 7578 else 7579 outs() << SymName << ":\n"; 7580 7581 DILineInfo lastLine; 7582 for (uint64_t Index = Start; Index < End; Index += Size) { 7583 MCInst Inst; 7584 7585 // If this is the first symbol in the section and it was not at the 7586 // start of the section, see if we are at its Index now and if so print 7587 // the symbol name. 7588 if (FirstSymbol && !FirstSymbolAtSectionStart && Index == SymbolStart) 7589 outs() << SymName << ":\n"; 7590 7591 uint64_t PC = SectAddress + Index; 7592 if (!NoLeadingAddr) { 7593 if (FullLeadingAddr) { 7594 if (MachOOF->is64Bit()) 7595 outs() << format("%016" PRIx64, PC); 7596 else 7597 outs() << format("%08" PRIx64, PC); 7598 } else { 7599 outs() << format("%8" PRIx64 ":", PC); 7600 } 7601 } 7602 if (!NoShowRawInsn || Arch == Triple::arm) 7603 outs() << "\t"; 7604 7605 if (DumpAndSkipDataInCode(PC, Bytes.data() + Index, Dices, Size)) 7606 continue; 7607 7608 SmallVector<char, 64> AnnotationsBytes; 7609 raw_svector_ostream Annotations(AnnotationsBytes); 7610 7611 bool gotInst; 7612 if (UseThumbTarget) 7613 gotInst = ThumbDisAsm->getInstruction(Inst, Size, Bytes.slice(Index), 7614 PC, Annotations); 7615 else 7616 gotInst = DisAsm->getInstruction(Inst, Size, Bytes.slice(Index), PC, 7617 Annotations); 7618 if (gotInst) { 7619 if (!NoShowRawInsn || Arch == Triple::arm) { 7620 dumpBytes(makeArrayRef(Bytes.data() + Index, Size), outs()); 7621 } 7622 formatted_raw_ostream FormattedOS(outs()); 7623 StringRef AnnotationsStr = Annotations.str(); 7624 if (UseThumbTarget) 7625 ThumbIP->printInst(&Inst, PC, AnnotationsStr, *ThumbSTI, 7626 FormattedOS); 7627 else 7628 IP->printInst(&Inst, PC, AnnotationsStr, *STI, FormattedOS); 7629 emitComments(CommentStream, CommentsToEmit, FormattedOS, *AsmInfo); 7630 7631 // Print debug info. 7632 if (diContext) { 7633 DILineInfo dli = diContext->getLineInfoForAddress({PC, SectIdx}); 7634 // Print valid line info if it changed. 7635 if (dli != lastLine && dli.Line != 0) 7636 outs() << "\t## " << dli.FileName << ':' << dli.Line << ':' 7637 << dli.Column; 7638 lastLine = dli; 7639 } 7640 outs() << "\n"; 7641 } else { 7642 if (MachOOF->getArchTriple().isX86()) { 7643 outs() << format("\t.byte 0x%02x #bad opcode\n", 7644 *(Bytes.data() + Index) & 0xff); 7645 Size = 1; // skip exactly one illegible byte and move on. 7646 } else if (Arch == Triple::aarch64 || 7647 (Arch == Triple::arm && !IsThumb)) { 7648 uint32_t opcode = (*(Bytes.data() + Index) & 0xff) | 7649 (*(Bytes.data() + Index + 1) & 0xff) << 8 | 7650 (*(Bytes.data() + Index + 2) & 0xff) << 16 | 7651 (*(Bytes.data() + Index + 3) & 0xff) << 24; 7652 outs() << format("\t.long\t0x%08x\n", opcode); 7653 Size = 4; 7654 } else if (Arch == Triple::arm) { 7655 assert(IsThumb && "ARM mode should have been dealt with above"); 7656 uint32_t opcode = (*(Bytes.data() + Index) & 0xff) | 7657 (*(Bytes.data() + Index + 1) & 0xff) << 8; 7658 outs() << format("\t.short\t0x%04x\n", opcode); 7659 Size = 2; 7660 } else{ 7661 WithColor::warning(errs(), "llvm-objdump") 7662 << "invalid instruction encoding\n"; 7663 if (Size == 0) 7664 Size = 1; // skip illegible bytes 7665 } 7666 } 7667 } 7668 // Now that we are done disassembled the first symbol set the bool that 7669 // were doing this to false. 7670 FirstSymbol = false; 7671 } 7672 if (!symbolTableWorked) { 7673 // Reading the symbol table didn't work, disassemble the whole section. 7674 uint64_t SectAddress = Sections[SectIdx].getAddress(); 7675 uint64_t SectSize = Sections[SectIdx].getSize(); 7676 uint64_t InstSize; 7677 for (uint64_t Index = 0; Index < SectSize; Index += InstSize) { 7678 MCInst Inst; 7679 7680 uint64_t PC = SectAddress + Index; 7681 7682 if (DumpAndSkipDataInCode(PC, Bytes.data() + Index, Dices, InstSize)) 7683 continue; 7684 7685 SmallVector<char, 64> AnnotationsBytes; 7686 raw_svector_ostream Annotations(AnnotationsBytes); 7687 if (DisAsm->getInstruction(Inst, InstSize, Bytes.slice(Index), PC, 7688 Annotations)) { 7689 if (!NoLeadingAddr) { 7690 if (FullLeadingAddr) { 7691 if (MachOOF->is64Bit()) 7692 outs() << format("%016" PRIx64, PC); 7693 else 7694 outs() << format("%08" PRIx64, PC); 7695 } else { 7696 outs() << format("%8" PRIx64 ":", PC); 7697 } 7698 } 7699 if (!NoShowRawInsn || Arch == Triple::arm) { 7700 outs() << "\t"; 7701 dumpBytes(makeArrayRef(Bytes.data() + Index, InstSize), outs()); 7702 } 7703 StringRef AnnotationsStr = Annotations.str(); 7704 IP->printInst(&Inst, PC, AnnotationsStr, *STI, outs()); 7705 outs() << "\n"; 7706 } else { 7707 if (MachOOF->getArchTriple().isX86()) { 7708 outs() << format("\t.byte 0x%02x #bad opcode\n", 7709 *(Bytes.data() + Index) & 0xff); 7710 InstSize = 1; // skip exactly one illegible byte and move on. 7711 } else { 7712 WithColor::warning(errs(), "llvm-objdump") 7713 << "invalid instruction encoding\n"; 7714 if (InstSize == 0) 7715 InstSize = 1; // skip illegible bytes 7716 } 7717 } 7718 } 7719 } 7720 // The TripleName's need to be reset if we are called again for a different 7721 // architecture. 7722 TripleName = ""; 7723 ThumbTripleName = ""; 7724 7725 if (SymbolizerInfo.demangled_name != nullptr) 7726 free(SymbolizerInfo.demangled_name); 7727 if (ThumbSymbolizerInfo.demangled_name != nullptr) 7728 free(ThumbSymbolizerInfo.demangled_name); 7729 } 7730 } 7731 7732 //===----------------------------------------------------------------------===// 7733 // __compact_unwind section dumping 7734 //===----------------------------------------------------------------------===// 7735 7736 namespace { 7737 7738 template <typename T> 7739 static uint64_t read(StringRef Contents, ptrdiff_t Offset) { 7740 using llvm::support::little; 7741 using llvm::support::unaligned; 7742 7743 if (Offset + sizeof(T) > Contents.size()) { 7744 outs() << "warning: attempt to read past end of buffer\n"; 7745 return T(); 7746 } 7747 7748 uint64_t Val = 7749 support::endian::read<T, little, unaligned>(Contents.data() + Offset); 7750 return Val; 7751 } 7752 7753 template <typename T> 7754 static uint64_t readNext(StringRef Contents, ptrdiff_t &Offset) { 7755 T Val = read<T>(Contents, Offset); 7756 Offset += sizeof(T); 7757 return Val; 7758 } 7759 7760 struct CompactUnwindEntry { 7761 uint32_t OffsetInSection; 7762 7763 uint64_t FunctionAddr; 7764 uint32_t Length; 7765 uint32_t CompactEncoding; 7766 uint64_t PersonalityAddr; 7767 uint64_t LSDAAddr; 7768 7769 RelocationRef FunctionReloc; 7770 RelocationRef PersonalityReloc; 7771 RelocationRef LSDAReloc; 7772 7773 CompactUnwindEntry(StringRef Contents, unsigned Offset, bool Is64) 7774 : OffsetInSection(Offset) { 7775 if (Is64) 7776 read<uint64_t>(Contents, Offset); 7777 else 7778 read<uint32_t>(Contents, Offset); 7779 } 7780 7781 private: 7782 template <typename UIntPtr> void read(StringRef Contents, ptrdiff_t Offset) { 7783 FunctionAddr = readNext<UIntPtr>(Contents, Offset); 7784 Length = readNext<uint32_t>(Contents, Offset); 7785 CompactEncoding = readNext<uint32_t>(Contents, Offset); 7786 PersonalityAddr = readNext<UIntPtr>(Contents, Offset); 7787 LSDAAddr = readNext<UIntPtr>(Contents, Offset); 7788 } 7789 }; 7790 } 7791 7792 /// Given a relocation from __compact_unwind, consisting of the RelocationRef 7793 /// and data being relocated, determine the best base Name and Addend to use for 7794 /// display purposes. 7795 /// 7796 /// 1. An Extern relocation will directly reference a symbol (and the data is 7797 /// then already an addend), so use that. 7798 /// 2. Otherwise the data is an offset in the object file's layout; try to find 7799 // a symbol before it in the same section, and use the offset from there. 7800 /// 3. Finally, if all that fails, fall back to an offset from the start of the 7801 /// referenced section. 7802 static void findUnwindRelocNameAddend(const MachOObjectFile *Obj, 7803 std::map<uint64_t, SymbolRef> &Symbols, 7804 const RelocationRef &Reloc, uint64_t Addr, 7805 StringRef &Name, uint64_t &Addend) { 7806 if (Reloc.getSymbol() != Obj->symbol_end()) { 7807 Name = unwrapOrError(Reloc.getSymbol()->getName(), Obj->getFileName()); 7808 Addend = Addr; 7809 return; 7810 } 7811 7812 auto RE = Obj->getRelocation(Reloc.getRawDataRefImpl()); 7813 SectionRef RelocSection = Obj->getAnyRelocationSection(RE); 7814 7815 uint64_t SectionAddr = RelocSection.getAddress(); 7816 7817 auto Sym = Symbols.upper_bound(Addr); 7818 if (Sym == Symbols.begin()) { 7819 // The first symbol in the object is after this reference, the best we can 7820 // do is section-relative notation. 7821 if (Expected<StringRef> NameOrErr = RelocSection.getName()) 7822 Name = *NameOrErr; 7823 else 7824 consumeError(NameOrErr.takeError()); 7825 7826 Addend = Addr - SectionAddr; 7827 return; 7828 } 7829 7830 // Go back one so that SymbolAddress <= Addr. 7831 --Sym; 7832 7833 section_iterator SymSection = 7834 unwrapOrError(Sym->second.getSection(), Obj->getFileName()); 7835 if (RelocSection == *SymSection) { 7836 // There's a valid symbol in the same section before this reference. 7837 Name = unwrapOrError(Sym->second.getName(), Obj->getFileName()); 7838 Addend = Addr - Sym->first; 7839 return; 7840 } 7841 7842 // There is a symbol before this reference, but it's in a different 7843 // section. Probably not helpful to mention it, so use the section name. 7844 if (Expected<StringRef> NameOrErr = RelocSection.getName()) 7845 Name = *NameOrErr; 7846 else 7847 consumeError(NameOrErr.takeError()); 7848 7849 Addend = Addr - SectionAddr; 7850 } 7851 7852 static void printUnwindRelocDest(const MachOObjectFile *Obj, 7853 std::map<uint64_t, SymbolRef> &Symbols, 7854 const RelocationRef &Reloc, uint64_t Addr) { 7855 StringRef Name; 7856 uint64_t Addend; 7857 7858 if (!Reloc.getObject()) 7859 return; 7860 7861 findUnwindRelocNameAddend(Obj, Symbols, Reloc, Addr, Name, Addend); 7862 7863 outs() << Name; 7864 if (Addend) 7865 outs() << " + " << format("0x%" PRIx64, Addend); 7866 } 7867 7868 static void 7869 printMachOCompactUnwindSection(const MachOObjectFile *Obj, 7870 std::map<uint64_t, SymbolRef> &Symbols, 7871 const SectionRef &CompactUnwind) { 7872 7873 if (!Obj->isLittleEndian()) { 7874 outs() << "Skipping big-endian __compact_unwind section\n"; 7875 return; 7876 } 7877 7878 bool Is64 = Obj->is64Bit(); 7879 uint32_t PointerSize = Is64 ? sizeof(uint64_t) : sizeof(uint32_t); 7880 uint32_t EntrySize = 3 * PointerSize + 2 * sizeof(uint32_t); 7881 7882 StringRef Contents = 7883 unwrapOrError(CompactUnwind.getContents(), Obj->getFileName()); 7884 SmallVector<CompactUnwindEntry, 4> CompactUnwinds; 7885 7886 // First populate the initial raw offsets, encodings and so on from the entry. 7887 for (unsigned Offset = 0; Offset < Contents.size(); Offset += EntrySize) { 7888 CompactUnwindEntry Entry(Contents, Offset, Is64); 7889 CompactUnwinds.push_back(Entry); 7890 } 7891 7892 // Next we need to look at the relocations to find out what objects are 7893 // actually being referred to. 7894 for (const RelocationRef &Reloc : CompactUnwind.relocations()) { 7895 uint64_t RelocAddress = Reloc.getOffset(); 7896 7897 uint32_t EntryIdx = RelocAddress / EntrySize; 7898 uint32_t OffsetInEntry = RelocAddress - EntryIdx * EntrySize; 7899 CompactUnwindEntry &Entry = CompactUnwinds[EntryIdx]; 7900 7901 if (OffsetInEntry == 0) 7902 Entry.FunctionReloc = Reloc; 7903 else if (OffsetInEntry == PointerSize + 2 * sizeof(uint32_t)) 7904 Entry.PersonalityReloc = Reloc; 7905 else if (OffsetInEntry == 2 * PointerSize + 2 * sizeof(uint32_t)) 7906 Entry.LSDAReloc = Reloc; 7907 else { 7908 outs() << "Invalid relocation in __compact_unwind section\n"; 7909 return; 7910 } 7911 } 7912 7913 // Finally, we're ready to print the data we've gathered. 7914 outs() << "Contents of __compact_unwind section:\n"; 7915 for (auto &Entry : CompactUnwinds) { 7916 outs() << " Entry at offset " 7917 << format("0x%" PRIx32, Entry.OffsetInSection) << ":\n"; 7918 7919 // 1. Start of the region this entry applies to. 7920 outs() << " start: " << format("0x%" PRIx64, 7921 Entry.FunctionAddr) << ' '; 7922 printUnwindRelocDest(Obj, Symbols, Entry.FunctionReloc, Entry.FunctionAddr); 7923 outs() << '\n'; 7924 7925 // 2. Length of the region this entry applies to. 7926 outs() << " length: " << format("0x%" PRIx32, Entry.Length) 7927 << '\n'; 7928 // 3. The 32-bit compact encoding. 7929 outs() << " compact encoding: " 7930 << format("0x%08" PRIx32, Entry.CompactEncoding) << '\n'; 7931 7932 // 4. The personality function, if present. 7933 if (Entry.PersonalityReloc.getObject()) { 7934 outs() << " personality function: " 7935 << format("0x%" PRIx64, Entry.PersonalityAddr) << ' '; 7936 printUnwindRelocDest(Obj, Symbols, Entry.PersonalityReloc, 7937 Entry.PersonalityAddr); 7938 outs() << '\n'; 7939 } 7940 7941 // 5. This entry's language-specific data area. 7942 if (Entry.LSDAReloc.getObject()) { 7943 outs() << " LSDA: " << format("0x%" PRIx64, 7944 Entry.LSDAAddr) << ' '; 7945 printUnwindRelocDest(Obj, Symbols, Entry.LSDAReloc, Entry.LSDAAddr); 7946 outs() << '\n'; 7947 } 7948 } 7949 } 7950 7951 //===----------------------------------------------------------------------===// 7952 // __unwind_info section dumping 7953 //===----------------------------------------------------------------------===// 7954 7955 static void printRegularSecondLevelUnwindPage(StringRef PageData) { 7956 ptrdiff_t Pos = 0; 7957 uint32_t Kind = readNext<uint32_t>(PageData, Pos); 7958 (void)Kind; 7959 assert(Kind == 2 && "kind for a regular 2nd level index should be 2"); 7960 7961 uint16_t EntriesStart = readNext<uint16_t>(PageData, Pos); 7962 uint16_t NumEntries = readNext<uint16_t>(PageData, Pos); 7963 7964 Pos = EntriesStart; 7965 for (unsigned i = 0; i < NumEntries; ++i) { 7966 uint32_t FunctionOffset = readNext<uint32_t>(PageData, Pos); 7967 uint32_t Encoding = readNext<uint32_t>(PageData, Pos); 7968 7969 outs() << " [" << i << "]: " 7970 << "function offset=" << format("0x%08" PRIx32, FunctionOffset) 7971 << ", " 7972 << "encoding=" << format("0x%08" PRIx32, Encoding) << '\n'; 7973 } 7974 } 7975 7976 static void printCompressedSecondLevelUnwindPage( 7977 StringRef PageData, uint32_t FunctionBase, 7978 const SmallVectorImpl<uint32_t> &CommonEncodings) { 7979 ptrdiff_t Pos = 0; 7980 uint32_t Kind = readNext<uint32_t>(PageData, Pos); 7981 (void)Kind; 7982 assert(Kind == 3 && "kind for a compressed 2nd level index should be 3"); 7983 7984 uint32_t NumCommonEncodings = CommonEncodings.size(); 7985 uint16_t EntriesStart = readNext<uint16_t>(PageData, Pos); 7986 uint16_t NumEntries = readNext<uint16_t>(PageData, Pos); 7987 7988 uint16_t PageEncodingsStart = readNext<uint16_t>(PageData, Pos); 7989 uint16_t NumPageEncodings = readNext<uint16_t>(PageData, Pos); 7990 SmallVector<uint32_t, 64> PageEncodings; 7991 if (NumPageEncodings) { 7992 outs() << " Page encodings: (count = " << NumPageEncodings << ")\n"; 7993 Pos = PageEncodingsStart; 7994 for (unsigned i = 0; i < NumPageEncodings; ++i) { 7995 uint32_t Encoding = readNext<uint32_t>(PageData, Pos); 7996 PageEncodings.push_back(Encoding); 7997 outs() << " encoding[" << (i + NumCommonEncodings) 7998 << "]: " << format("0x%08" PRIx32, Encoding) << '\n'; 7999 } 8000 } 8001 8002 Pos = EntriesStart; 8003 for (unsigned i = 0; i < NumEntries; ++i) { 8004 uint32_t Entry = readNext<uint32_t>(PageData, Pos); 8005 uint32_t FunctionOffset = FunctionBase + (Entry & 0xffffff); 8006 uint32_t EncodingIdx = Entry >> 24; 8007 8008 uint32_t Encoding; 8009 if (EncodingIdx < NumCommonEncodings) 8010 Encoding = CommonEncodings[EncodingIdx]; 8011 else 8012 Encoding = PageEncodings[EncodingIdx - NumCommonEncodings]; 8013 8014 outs() << " [" << i << "]: " 8015 << "function offset=" << format("0x%08" PRIx32, FunctionOffset) 8016 << ", " 8017 << "encoding[" << EncodingIdx 8018 << "]=" << format("0x%08" PRIx32, Encoding) << '\n'; 8019 } 8020 } 8021 8022 static void printMachOUnwindInfoSection(const MachOObjectFile *Obj, 8023 std::map<uint64_t, SymbolRef> &Symbols, 8024 const SectionRef &UnwindInfo) { 8025 8026 if (!Obj->isLittleEndian()) { 8027 outs() << "Skipping big-endian __unwind_info section\n"; 8028 return; 8029 } 8030 8031 outs() << "Contents of __unwind_info section:\n"; 8032 8033 StringRef Contents = 8034 unwrapOrError(UnwindInfo.getContents(), Obj->getFileName()); 8035 ptrdiff_t Pos = 0; 8036 8037 //===---------------------------------- 8038 // Section header 8039 //===---------------------------------- 8040 8041 uint32_t Version = readNext<uint32_t>(Contents, Pos); 8042 outs() << " Version: " 8043 << format("0x%" PRIx32, Version) << '\n'; 8044 if (Version != 1) { 8045 outs() << " Skipping section with unknown version\n"; 8046 return; 8047 } 8048 8049 uint32_t CommonEncodingsStart = readNext<uint32_t>(Contents, Pos); 8050 outs() << " Common encodings array section offset: " 8051 << format("0x%" PRIx32, CommonEncodingsStart) << '\n'; 8052 uint32_t NumCommonEncodings = readNext<uint32_t>(Contents, Pos); 8053 outs() << " Number of common encodings in array: " 8054 << format("0x%" PRIx32, NumCommonEncodings) << '\n'; 8055 8056 uint32_t PersonalitiesStart = readNext<uint32_t>(Contents, Pos); 8057 outs() << " Personality function array section offset: " 8058 << format("0x%" PRIx32, PersonalitiesStart) << '\n'; 8059 uint32_t NumPersonalities = readNext<uint32_t>(Contents, Pos); 8060 outs() << " Number of personality functions in array: " 8061 << format("0x%" PRIx32, NumPersonalities) << '\n'; 8062 8063 uint32_t IndicesStart = readNext<uint32_t>(Contents, Pos); 8064 outs() << " Index array section offset: " 8065 << format("0x%" PRIx32, IndicesStart) << '\n'; 8066 uint32_t NumIndices = readNext<uint32_t>(Contents, Pos); 8067 outs() << " Number of indices in array: " 8068 << format("0x%" PRIx32, NumIndices) << '\n'; 8069 8070 //===---------------------------------- 8071 // A shared list of common encodings 8072 //===---------------------------------- 8073 8074 // These occupy indices in the range [0, N] whenever an encoding is referenced 8075 // from a compressed 2nd level index table. In practice the linker only 8076 // creates ~128 of these, so that indices are available to embed encodings in 8077 // the 2nd level index. 8078 8079 SmallVector<uint32_t, 64> CommonEncodings; 8080 outs() << " Common encodings: (count = " << NumCommonEncodings << ")\n"; 8081 Pos = CommonEncodingsStart; 8082 for (unsigned i = 0; i < NumCommonEncodings; ++i) { 8083 uint32_t Encoding = readNext<uint32_t>(Contents, Pos); 8084 CommonEncodings.push_back(Encoding); 8085 8086 outs() << " encoding[" << i << "]: " << format("0x%08" PRIx32, Encoding) 8087 << '\n'; 8088 } 8089 8090 //===---------------------------------- 8091 // Personality functions used in this executable 8092 //===---------------------------------- 8093 8094 // There should be only a handful of these (one per source language, 8095 // roughly). Particularly since they only get 2 bits in the compact encoding. 8096 8097 outs() << " Personality functions: (count = " << NumPersonalities << ")\n"; 8098 Pos = PersonalitiesStart; 8099 for (unsigned i = 0; i < NumPersonalities; ++i) { 8100 uint32_t PersonalityFn = readNext<uint32_t>(Contents, Pos); 8101 outs() << " personality[" << i + 1 8102 << "]: " << format("0x%08" PRIx32, PersonalityFn) << '\n'; 8103 } 8104 8105 //===---------------------------------- 8106 // The level 1 index entries 8107 //===---------------------------------- 8108 8109 // These specify an approximate place to start searching for the more detailed 8110 // information, sorted by PC. 8111 8112 struct IndexEntry { 8113 uint32_t FunctionOffset; 8114 uint32_t SecondLevelPageStart; 8115 uint32_t LSDAStart; 8116 }; 8117 8118 SmallVector<IndexEntry, 4> IndexEntries; 8119 8120 outs() << " Top level indices: (count = " << NumIndices << ")\n"; 8121 Pos = IndicesStart; 8122 for (unsigned i = 0; i < NumIndices; ++i) { 8123 IndexEntry Entry; 8124 8125 Entry.FunctionOffset = readNext<uint32_t>(Contents, Pos); 8126 Entry.SecondLevelPageStart = readNext<uint32_t>(Contents, Pos); 8127 Entry.LSDAStart = readNext<uint32_t>(Contents, Pos); 8128 IndexEntries.push_back(Entry); 8129 8130 outs() << " [" << i << "]: " 8131 << "function offset=" << format("0x%08" PRIx32, Entry.FunctionOffset) 8132 << ", " 8133 << "2nd level page offset=" 8134 << format("0x%08" PRIx32, Entry.SecondLevelPageStart) << ", " 8135 << "LSDA offset=" << format("0x%08" PRIx32, Entry.LSDAStart) << '\n'; 8136 } 8137 8138 //===---------------------------------- 8139 // Next come the LSDA tables 8140 //===---------------------------------- 8141 8142 // The LSDA layout is rather implicit: it's a contiguous array of entries from 8143 // the first top-level index's LSDAOffset to the last (sentinel). 8144 8145 outs() << " LSDA descriptors:\n"; 8146 Pos = IndexEntries[0].LSDAStart; 8147 const uint32_t LSDASize = 2 * sizeof(uint32_t); 8148 int NumLSDAs = 8149 (IndexEntries.back().LSDAStart - IndexEntries[0].LSDAStart) / LSDASize; 8150 8151 for (int i = 0; i < NumLSDAs; ++i) { 8152 uint32_t FunctionOffset = readNext<uint32_t>(Contents, Pos); 8153 uint32_t LSDAOffset = readNext<uint32_t>(Contents, Pos); 8154 outs() << " [" << i << "]: " 8155 << "function offset=" << format("0x%08" PRIx32, FunctionOffset) 8156 << ", " 8157 << "LSDA offset=" << format("0x%08" PRIx32, LSDAOffset) << '\n'; 8158 } 8159 8160 //===---------------------------------- 8161 // Finally, the 2nd level indices 8162 //===---------------------------------- 8163 8164 // Generally these are 4K in size, and have 2 possible forms: 8165 // + Regular stores up to 511 entries with disparate encodings 8166 // + Compressed stores up to 1021 entries if few enough compact encoding 8167 // values are used. 8168 outs() << " Second level indices:\n"; 8169 for (unsigned i = 0; i < IndexEntries.size() - 1; ++i) { 8170 // The final sentinel top-level index has no associated 2nd level page 8171 if (IndexEntries[i].SecondLevelPageStart == 0) 8172 break; 8173 8174 outs() << " Second level index[" << i << "]: " 8175 << "offset in section=" 8176 << format("0x%08" PRIx32, IndexEntries[i].SecondLevelPageStart) 8177 << ", " 8178 << "base function offset=" 8179 << format("0x%08" PRIx32, IndexEntries[i].FunctionOffset) << '\n'; 8180 8181 Pos = IndexEntries[i].SecondLevelPageStart; 8182 if (Pos + sizeof(uint32_t) > Contents.size()) { 8183 outs() << "warning: invalid offset for second level page: " << Pos << '\n'; 8184 continue; 8185 } 8186 8187 uint32_t Kind = 8188 *reinterpret_cast<const support::ulittle32_t *>(Contents.data() + Pos); 8189 if (Kind == 2) 8190 printRegularSecondLevelUnwindPage(Contents.substr(Pos, 4096)); 8191 else if (Kind == 3) 8192 printCompressedSecondLevelUnwindPage(Contents.substr(Pos, 4096), 8193 IndexEntries[i].FunctionOffset, 8194 CommonEncodings); 8195 else 8196 outs() << " Skipping 2nd level page with unknown kind " << Kind 8197 << '\n'; 8198 } 8199 } 8200 8201 void objdump::printMachOUnwindInfo(const MachOObjectFile *Obj) { 8202 std::map<uint64_t, SymbolRef> Symbols; 8203 for (const SymbolRef &SymRef : Obj->symbols()) { 8204 // Discard any undefined or absolute symbols. They're not going to take part 8205 // in the convenience lookup for unwind info and just take up resources. 8206 auto SectOrErr = SymRef.getSection(); 8207 if (!SectOrErr) { 8208 // TODO: Actually report errors helpfully. 8209 consumeError(SectOrErr.takeError()); 8210 continue; 8211 } 8212 section_iterator Section = *SectOrErr; 8213 if (Section == Obj->section_end()) 8214 continue; 8215 8216 uint64_t Addr = cantFail(SymRef.getValue()); 8217 Symbols.insert(std::make_pair(Addr, SymRef)); 8218 } 8219 8220 for (const SectionRef &Section : Obj->sections()) { 8221 StringRef SectName; 8222 if (Expected<StringRef> NameOrErr = Section.getName()) 8223 SectName = *NameOrErr; 8224 else 8225 consumeError(NameOrErr.takeError()); 8226 8227 if (SectName == "__compact_unwind") 8228 printMachOCompactUnwindSection(Obj, Symbols, Section); 8229 else if (SectName == "__unwind_info") 8230 printMachOUnwindInfoSection(Obj, Symbols, Section); 8231 } 8232 } 8233 8234 static void PrintMachHeader(uint32_t magic, uint32_t cputype, 8235 uint32_t cpusubtype, uint32_t filetype, 8236 uint32_t ncmds, uint32_t sizeofcmds, uint32_t flags, 8237 bool verbose) { 8238 outs() << "Mach header\n"; 8239 outs() << " magic cputype cpusubtype caps filetype ncmds " 8240 "sizeofcmds flags\n"; 8241 if (verbose) { 8242 if (magic == MachO::MH_MAGIC) 8243 outs() << " MH_MAGIC"; 8244 else if (magic == MachO::MH_MAGIC_64) 8245 outs() << "MH_MAGIC_64"; 8246 else 8247 outs() << format(" 0x%08" PRIx32, magic); 8248 switch (cputype) { 8249 case MachO::CPU_TYPE_I386: 8250 outs() << " I386"; 8251 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) { 8252 case MachO::CPU_SUBTYPE_I386_ALL: 8253 outs() << " ALL"; 8254 break; 8255 default: 8256 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK); 8257 break; 8258 } 8259 break; 8260 case MachO::CPU_TYPE_X86_64: 8261 outs() << " X86_64"; 8262 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) { 8263 case MachO::CPU_SUBTYPE_X86_64_ALL: 8264 outs() << " ALL"; 8265 break; 8266 case MachO::CPU_SUBTYPE_X86_64_H: 8267 outs() << " Haswell"; 8268 break; 8269 default: 8270 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK); 8271 break; 8272 } 8273 break; 8274 case MachO::CPU_TYPE_ARM: 8275 outs() << " ARM"; 8276 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) { 8277 case MachO::CPU_SUBTYPE_ARM_ALL: 8278 outs() << " ALL"; 8279 break; 8280 case MachO::CPU_SUBTYPE_ARM_V4T: 8281 outs() << " V4T"; 8282 break; 8283 case MachO::CPU_SUBTYPE_ARM_V5TEJ: 8284 outs() << " V5TEJ"; 8285 break; 8286 case MachO::CPU_SUBTYPE_ARM_XSCALE: 8287 outs() << " XSCALE"; 8288 break; 8289 case MachO::CPU_SUBTYPE_ARM_V6: 8290 outs() << " V6"; 8291 break; 8292 case MachO::CPU_SUBTYPE_ARM_V6M: 8293 outs() << " V6M"; 8294 break; 8295 case MachO::CPU_SUBTYPE_ARM_V7: 8296 outs() << " V7"; 8297 break; 8298 case MachO::CPU_SUBTYPE_ARM_V7EM: 8299 outs() << " V7EM"; 8300 break; 8301 case MachO::CPU_SUBTYPE_ARM_V7K: 8302 outs() << " V7K"; 8303 break; 8304 case MachO::CPU_SUBTYPE_ARM_V7M: 8305 outs() << " V7M"; 8306 break; 8307 case MachO::CPU_SUBTYPE_ARM_V7S: 8308 outs() << " V7S"; 8309 break; 8310 default: 8311 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK); 8312 break; 8313 } 8314 break; 8315 case MachO::CPU_TYPE_ARM64: 8316 outs() << " ARM64"; 8317 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) { 8318 case MachO::CPU_SUBTYPE_ARM64_ALL: 8319 outs() << " ALL"; 8320 break; 8321 case MachO::CPU_SUBTYPE_ARM64_V8: 8322 outs() << " V8"; 8323 break; 8324 case MachO::CPU_SUBTYPE_ARM64E: 8325 outs() << " E"; 8326 break; 8327 default: 8328 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK); 8329 break; 8330 } 8331 break; 8332 case MachO::CPU_TYPE_ARM64_32: 8333 outs() << " ARM64_32"; 8334 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) { 8335 case MachO::CPU_SUBTYPE_ARM64_32_V8: 8336 outs() << " V8"; 8337 break; 8338 default: 8339 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK); 8340 break; 8341 } 8342 break; 8343 case MachO::CPU_TYPE_POWERPC: 8344 outs() << " PPC"; 8345 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) { 8346 case MachO::CPU_SUBTYPE_POWERPC_ALL: 8347 outs() << " ALL"; 8348 break; 8349 default: 8350 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK); 8351 break; 8352 } 8353 break; 8354 case MachO::CPU_TYPE_POWERPC64: 8355 outs() << " PPC64"; 8356 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) { 8357 case MachO::CPU_SUBTYPE_POWERPC_ALL: 8358 outs() << " ALL"; 8359 break; 8360 default: 8361 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK); 8362 break; 8363 } 8364 break; 8365 default: 8366 outs() << format(" %7d", cputype); 8367 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK); 8368 break; 8369 } 8370 if ((cpusubtype & MachO::CPU_SUBTYPE_MASK) == MachO::CPU_SUBTYPE_LIB64) { 8371 outs() << " LIB64"; 8372 } else { 8373 outs() << format(" 0x%02" PRIx32, 8374 (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24); 8375 } 8376 switch (filetype) { 8377 case MachO::MH_OBJECT: 8378 outs() << " OBJECT"; 8379 break; 8380 case MachO::MH_EXECUTE: 8381 outs() << " EXECUTE"; 8382 break; 8383 case MachO::MH_FVMLIB: 8384 outs() << " FVMLIB"; 8385 break; 8386 case MachO::MH_CORE: 8387 outs() << " CORE"; 8388 break; 8389 case MachO::MH_PRELOAD: 8390 outs() << " PRELOAD"; 8391 break; 8392 case MachO::MH_DYLIB: 8393 outs() << " DYLIB"; 8394 break; 8395 case MachO::MH_DYLIB_STUB: 8396 outs() << " DYLIB_STUB"; 8397 break; 8398 case MachO::MH_DYLINKER: 8399 outs() << " DYLINKER"; 8400 break; 8401 case MachO::MH_BUNDLE: 8402 outs() << " BUNDLE"; 8403 break; 8404 case MachO::MH_DSYM: 8405 outs() << " DSYM"; 8406 break; 8407 case MachO::MH_KEXT_BUNDLE: 8408 outs() << " KEXTBUNDLE"; 8409 break; 8410 default: 8411 outs() << format(" %10u", filetype); 8412 break; 8413 } 8414 outs() << format(" %5u", ncmds); 8415 outs() << format(" %10u", sizeofcmds); 8416 uint32_t f = flags; 8417 if (f & MachO::MH_NOUNDEFS) { 8418 outs() << " NOUNDEFS"; 8419 f &= ~MachO::MH_NOUNDEFS; 8420 } 8421 if (f & MachO::MH_INCRLINK) { 8422 outs() << " INCRLINK"; 8423 f &= ~MachO::MH_INCRLINK; 8424 } 8425 if (f & MachO::MH_DYLDLINK) { 8426 outs() << " DYLDLINK"; 8427 f &= ~MachO::MH_DYLDLINK; 8428 } 8429 if (f & MachO::MH_BINDATLOAD) { 8430 outs() << " BINDATLOAD"; 8431 f &= ~MachO::MH_BINDATLOAD; 8432 } 8433 if (f & MachO::MH_PREBOUND) { 8434 outs() << " PREBOUND"; 8435 f &= ~MachO::MH_PREBOUND; 8436 } 8437 if (f & MachO::MH_SPLIT_SEGS) { 8438 outs() << " SPLIT_SEGS"; 8439 f &= ~MachO::MH_SPLIT_SEGS; 8440 } 8441 if (f & MachO::MH_LAZY_INIT) { 8442 outs() << " LAZY_INIT"; 8443 f &= ~MachO::MH_LAZY_INIT; 8444 } 8445 if (f & MachO::MH_TWOLEVEL) { 8446 outs() << " TWOLEVEL"; 8447 f &= ~MachO::MH_TWOLEVEL; 8448 } 8449 if (f & MachO::MH_FORCE_FLAT) { 8450 outs() << " FORCE_FLAT"; 8451 f &= ~MachO::MH_FORCE_FLAT; 8452 } 8453 if (f & MachO::MH_NOMULTIDEFS) { 8454 outs() << " NOMULTIDEFS"; 8455 f &= ~MachO::MH_NOMULTIDEFS; 8456 } 8457 if (f & MachO::MH_NOFIXPREBINDING) { 8458 outs() << " NOFIXPREBINDING"; 8459 f &= ~MachO::MH_NOFIXPREBINDING; 8460 } 8461 if (f & MachO::MH_PREBINDABLE) { 8462 outs() << " PREBINDABLE"; 8463 f &= ~MachO::MH_PREBINDABLE; 8464 } 8465 if (f & MachO::MH_ALLMODSBOUND) { 8466 outs() << " ALLMODSBOUND"; 8467 f &= ~MachO::MH_ALLMODSBOUND; 8468 } 8469 if (f & MachO::MH_SUBSECTIONS_VIA_SYMBOLS) { 8470 outs() << " SUBSECTIONS_VIA_SYMBOLS"; 8471 f &= ~MachO::MH_SUBSECTIONS_VIA_SYMBOLS; 8472 } 8473 if (f & MachO::MH_CANONICAL) { 8474 outs() << " CANONICAL"; 8475 f &= ~MachO::MH_CANONICAL; 8476 } 8477 if (f & MachO::MH_WEAK_DEFINES) { 8478 outs() << " WEAK_DEFINES"; 8479 f &= ~MachO::MH_WEAK_DEFINES; 8480 } 8481 if (f & MachO::MH_BINDS_TO_WEAK) { 8482 outs() << " BINDS_TO_WEAK"; 8483 f &= ~MachO::MH_BINDS_TO_WEAK; 8484 } 8485 if (f & MachO::MH_ALLOW_STACK_EXECUTION) { 8486 outs() << " ALLOW_STACK_EXECUTION"; 8487 f &= ~MachO::MH_ALLOW_STACK_EXECUTION; 8488 } 8489 if (f & MachO::MH_DEAD_STRIPPABLE_DYLIB) { 8490 outs() << " DEAD_STRIPPABLE_DYLIB"; 8491 f &= ~MachO::MH_DEAD_STRIPPABLE_DYLIB; 8492 } 8493 if (f & MachO::MH_PIE) { 8494 outs() << " PIE"; 8495 f &= ~MachO::MH_PIE; 8496 } 8497 if (f & MachO::MH_NO_REEXPORTED_DYLIBS) { 8498 outs() << " NO_REEXPORTED_DYLIBS"; 8499 f &= ~MachO::MH_NO_REEXPORTED_DYLIBS; 8500 } 8501 if (f & MachO::MH_HAS_TLV_DESCRIPTORS) { 8502 outs() << " MH_HAS_TLV_DESCRIPTORS"; 8503 f &= ~MachO::MH_HAS_TLV_DESCRIPTORS; 8504 } 8505 if (f & MachO::MH_NO_HEAP_EXECUTION) { 8506 outs() << " MH_NO_HEAP_EXECUTION"; 8507 f &= ~MachO::MH_NO_HEAP_EXECUTION; 8508 } 8509 if (f & MachO::MH_APP_EXTENSION_SAFE) { 8510 outs() << " APP_EXTENSION_SAFE"; 8511 f &= ~MachO::MH_APP_EXTENSION_SAFE; 8512 } 8513 if (f & MachO::MH_NLIST_OUTOFSYNC_WITH_DYLDINFO) { 8514 outs() << " NLIST_OUTOFSYNC_WITH_DYLDINFO"; 8515 f &= ~MachO::MH_NLIST_OUTOFSYNC_WITH_DYLDINFO; 8516 } 8517 if (f != 0 || flags == 0) 8518 outs() << format(" 0x%08" PRIx32, f); 8519 } else { 8520 outs() << format(" 0x%08" PRIx32, magic); 8521 outs() << format(" %7d", cputype); 8522 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK); 8523 outs() << format(" 0x%02" PRIx32, 8524 (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24); 8525 outs() << format(" %10u", filetype); 8526 outs() << format(" %5u", ncmds); 8527 outs() << format(" %10u", sizeofcmds); 8528 outs() << format(" 0x%08" PRIx32, flags); 8529 } 8530 outs() << "\n"; 8531 } 8532 8533 static void PrintSegmentCommand(uint32_t cmd, uint32_t cmdsize, 8534 StringRef SegName, uint64_t vmaddr, 8535 uint64_t vmsize, uint64_t fileoff, 8536 uint64_t filesize, uint32_t maxprot, 8537 uint32_t initprot, uint32_t nsects, 8538 uint32_t flags, uint32_t object_size, 8539 bool verbose) { 8540 uint64_t expected_cmdsize; 8541 if (cmd == MachO::LC_SEGMENT) { 8542 outs() << " cmd LC_SEGMENT\n"; 8543 expected_cmdsize = nsects; 8544 expected_cmdsize *= sizeof(struct MachO::section); 8545 expected_cmdsize += sizeof(struct MachO::segment_command); 8546 } else { 8547 outs() << " cmd LC_SEGMENT_64\n"; 8548 expected_cmdsize = nsects; 8549 expected_cmdsize *= sizeof(struct MachO::section_64); 8550 expected_cmdsize += sizeof(struct MachO::segment_command_64); 8551 } 8552 outs() << " cmdsize " << cmdsize; 8553 if (cmdsize != expected_cmdsize) 8554 outs() << " Inconsistent size\n"; 8555 else 8556 outs() << "\n"; 8557 outs() << " segname " << SegName << "\n"; 8558 if (cmd == MachO::LC_SEGMENT_64) { 8559 outs() << " vmaddr " << format("0x%016" PRIx64, vmaddr) << "\n"; 8560 outs() << " vmsize " << format("0x%016" PRIx64, vmsize) << "\n"; 8561 } else { 8562 outs() << " vmaddr " << format("0x%08" PRIx64, vmaddr) << "\n"; 8563 outs() << " vmsize " << format("0x%08" PRIx64, vmsize) << "\n"; 8564 } 8565 outs() << " fileoff " << fileoff; 8566 if (fileoff > object_size) 8567 outs() << " (past end of file)\n"; 8568 else 8569 outs() << "\n"; 8570 outs() << " filesize " << filesize; 8571 if (fileoff + filesize > object_size) 8572 outs() << " (past end of file)\n"; 8573 else 8574 outs() << "\n"; 8575 if (verbose) { 8576 if ((maxprot & 8577 ~(MachO::VM_PROT_READ | MachO::VM_PROT_WRITE | 8578 MachO::VM_PROT_EXECUTE)) != 0) 8579 outs() << " maxprot ?" << format("0x%08" PRIx32, maxprot) << "\n"; 8580 else { 8581 outs() << " maxprot "; 8582 outs() << ((maxprot & MachO::VM_PROT_READ) ? "r" : "-"); 8583 outs() << ((maxprot & MachO::VM_PROT_WRITE) ? "w" : "-"); 8584 outs() << ((maxprot & MachO::VM_PROT_EXECUTE) ? "x\n" : "-\n"); 8585 } 8586 if ((initprot & 8587 ~(MachO::VM_PROT_READ | MachO::VM_PROT_WRITE | 8588 MachO::VM_PROT_EXECUTE)) != 0) 8589 outs() << " initprot ?" << format("0x%08" PRIx32, initprot) << "\n"; 8590 else { 8591 outs() << " initprot "; 8592 outs() << ((initprot & MachO::VM_PROT_READ) ? "r" : "-"); 8593 outs() << ((initprot & MachO::VM_PROT_WRITE) ? "w" : "-"); 8594 outs() << ((initprot & MachO::VM_PROT_EXECUTE) ? "x\n" : "-\n"); 8595 } 8596 } else { 8597 outs() << " maxprot " << format("0x%08" PRIx32, maxprot) << "\n"; 8598 outs() << " initprot " << format("0x%08" PRIx32, initprot) << "\n"; 8599 } 8600 outs() << " nsects " << nsects << "\n"; 8601 if (verbose) { 8602 outs() << " flags"; 8603 if (flags == 0) 8604 outs() << " (none)\n"; 8605 else { 8606 if (flags & MachO::SG_HIGHVM) { 8607 outs() << " HIGHVM"; 8608 flags &= ~MachO::SG_HIGHVM; 8609 } 8610 if (flags & MachO::SG_FVMLIB) { 8611 outs() << " FVMLIB"; 8612 flags &= ~MachO::SG_FVMLIB; 8613 } 8614 if (flags & MachO::SG_NORELOC) { 8615 outs() << " NORELOC"; 8616 flags &= ~MachO::SG_NORELOC; 8617 } 8618 if (flags & MachO::SG_PROTECTED_VERSION_1) { 8619 outs() << " PROTECTED_VERSION_1"; 8620 flags &= ~MachO::SG_PROTECTED_VERSION_1; 8621 } 8622 if (flags) 8623 outs() << format(" 0x%08" PRIx32, flags) << " (unknown flags)\n"; 8624 else 8625 outs() << "\n"; 8626 } 8627 } else { 8628 outs() << " flags " << format("0x%" PRIx32, flags) << "\n"; 8629 } 8630 } 8631 8632 static void PrintSection(const char *sectname, const char *segname, 8633 uint64_t addr, uint64_t size, uint32_t offset, 8634 uint32_t align, uint32_t reloff, uint32_t nreloc, 8635 uint32_t flags, uint32_t reserved1, uint32_t reserved2, 8636 uint32_t cmd, const char *sg_segname, 8637 uint32_t filetype, uint32_t object_size, 8638 bool verbose) { 8639 outs() << "Section\n"; 8640 outs() << " sectname " << format("%.16s\n", sectname); 8641 outs() << " segname " << format("%.16s", segname); 8642 if (filetype != MachO::MH_OBJECT && strncmp(sg_segname, segname, 16) != 0) 8643 outs() << " (does not match segment)\n"; 8644 else 8645 outs() << "\n"; 8646 if (cmd == MachO::LC_SEGMENT_64) { 8647 outs() << " addr " << format("0x%016" PRIx64, addr) << "\n"; 8648 outs() << " size " << format("0x%016" PRIx64, size); 8649 } else { 8650 outs() << " addr " << format("0x%08" PRIx64, addr) << "\n"; 8651 outs() << " size " << format("0x%08" PRIx64, size); 8652 } 8653 if ((flags & MachO::S_ZEROFILL) != 0 && offset + size > object_size) 8654 outs() << " (past end of file)\n"; 8655 else 8656 outs() << "\n"; 8657 outs() << " offset " << offset; 8658 if (offset > object_size) 8659 outs() << " (past end of file)\n"; 8660 else 8661 outs() << "\n"; 8662 uint32_t align_shifted = 1 << align; 8663 outs() << " align 2^" << align << " (" << align_shifted << ")\n"; 8664 outs() << " reloff " << reloff; 8665 if (reloff > object_size) 8666 outs() << " (past end of file)\n"; 8667 else 8668 outs() << "\n"; 8669 outs() << " nreloc " << nreloc; 8670 if (reloff + nreloc * sizeof(struct MachO::relocation_info) > object_size) 8671 outs() << " (past end of file)\n"; 8672 else 8673 outs() << "\n"; 8674 uint32_t section_type = flags & MachO::SECTION_TYPE; 8675 if (verbose) { 8676 outs() << " type"; 8677 if (section_type == MachO::S_REGULAR) 8678 outs() << " S_REGULAR\n"; 8679 else if (section_type == MachO::S_ZEROFILL) 8680 outs() << " S_ZEROFILL\n"; 8681 else if (section_type == MachO::S_CSTRING_LITERALS) 8682 outs() << " S_CSTRING_LITERALS\n"; 8683 else if (section_type == MachO::S_4BYTE_LITERALS) 8684 outs() << " S_4BYTE_LITERALS\n"; 8685 else if (section_type == MachO::S_8BYTE_LITERALS) 8686 outs() << " S_8BYTE_LITERALS\n"; 8687 else if (section_type == MachO::S_16BYTE_LITERALS) 8688 outs() << " S_16BYTE_LITERALS\n"; 8689 else if (section_type == MachO::S_LITERAL_POINTERS) 8690 outs() << " S_LITERAL_POINTERS\n"; 8691 else if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS) 8692 outs() << " S_NON_LAZY_SYMBOL_POINTERS\n"; 8693 else if (section_type == MachO::S_LAZY_SYMBOL_POINTERS) 8694 outs() << " S_LAZY_SYMBOL_POINTERS\n"; 8695 else if (section_type == MachO::S_SYMBOL_STUBS) 8696 outs() << " S_SYMBOL_STUBS\n"; 8697 else if (section_type == MachO::S_MOD_INIT_FUNC_POINTERS) 8698 outs() << " S_MOD_INIT_FUNC_POINTERS\n"; 8699 else if (section_type == MachO::S_MOD_TERM_FUNC_POINTERS) 8700 outs() << " S_MOD_TERM_FUNC_POINTERS\n"; 8701 else if (section_type == MachO::S_COALESCED) 8702 outs() << " S_COALESCED\n"; 8703 else if (section_type == MachO::S_INTERPOSING) 8704 outs() << " S_INTERPOSING\n"; 8705 else if (section_type == MachO::S_DTRACE_DOF) 8706 outs() << " S_DTRACE_DOF\n"; 8707 else if (section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS) 8708 outs() << " S_LAZY_DYLIB_SYMBOL_POINTERS\n"; 8709 else if (section_type == MachO::S_THREAD_LOCAL_REGULAR) 8710 outs() << " S_THREAD_LOCAL_REGULAR\n"; 8711 else if (section_type == MachO::S_THREAD_LOCAL_ZEROFILL) 8712 outs() << " S_THREAD_LOCAL_ZEROFILL\n"; 8713 else if (section_type == MachO::S_THREAD_LOCAL_VARIABLES) 8714 outs() << " S_THREAD_LOCAL_VARIABLES\n"; 8715 else if (section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS) 8716 outs() << " S_THREAD_LOCAL_VARIABLE_POINTERS\n"; 8717 else if (section_type == MachO::S_THREAD_LOCAL_INIT_FUNCTION_POINTERS) 8718 outs() << " S_THREAD_LOCAL_INIT_FUNCTION_POINTERS\n"; 8719 else 8720 outs() << format("0x%08" PRIx32, section_type) << "\n"; 8721 outs() << "attributes"; 8722 uint32_t section_attributes = flags & MachO::SECTION_ATTRIBUTES; 8723 if (section_attributes & MachO::S_ATTR_PURE_INSTRUCTIONS) 8724 outs() << " PURE_INSTRUCTIONS"; 8725 if (section_attributes & MachO::S_ATTR_NO_TOC) 8726 outs() << " NO_TOC"; 8727 if (section_attributes & MachO::S_ATTR_STRIP_STATIC_SYMS) 8728 outs() << " STRIP_STATIC_SYMS"; 8729 if (section_attributes & MachO::S_ATTR_NO_DEAD_STRIP) 8730 outs() << " NO_DEAD_STRIP"; 8731 if (section_attributes & MachO::S_ATTR_LIVE_SUPPORT) 8732 outs() << " LIVE_SUPPORT"; 8733 if (section_attributes & MachO::S_ATTR_SELF_MODIFYING_CODE) 8734 outs() << " SELF_MODIFYING_CODE"; 8735 if (section_attributes & MachO::S_ATTR_DEBUG) 8736 outs() << " DEBUG"; 8737 if (section_attributes & MachO::S_ATTR_SOME_INSTRUCTIONS) 8738 outs() << " SOME_INSTRUCTIONS"; 8739 if (section_attributes & MachO::S_ATTR_EXT_RELOC) 8740 outs() << " EXT_RELOC"; 8741 if (section_attributes & MachO::S_ATTR_LOC_RELOC) 8742 outs() << " LOC_RELOC"; 8743 if (section_attributes == 0) 8744 outs() << " (none)"; 8745 outs() << "\n"; 8746 } else 8747 outs() << " flags " << format("0x%08" PRIx32, flags) << "\n"; 8748 outs() << " reserved1 " << reserved1; 8749 if (section_type == MachO::S_SYMBOL_STUBS || 8750 section_type == MachO::S_LAZY_SYMBOL_POINTERS || 8751 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS || 8752 section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS || 8753 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS) 8754 outs() << " (index into indirect symbol table)\n"; 8755 else 8756 outs() << "\n"; 8757 outs() << " reserved2 " << reserved2; 8758 if (section_type == MachO::S_SYMBOL_STUBS) 8759 outs() << " (size of stubs)\n"; 8760 else 8761 outs() << "\n"; 8762 } 8763 8764 static void PrintSymtabLoadCommand(MachO::symtab_command st, bool Is64Bit, 8765 uint32_t object_size) { 8766 outs() << " cmd LC_SYMTAB\n"; 8767 outs() << " cmdsize " << st.cmdsize; 8768 if (st.cmdsize != sizeof(struct MachO::symtab_command)) 8769 outs() << " Incorrect size\n"; 8770 else 8771 outs() << "\n"; 8772 outs() << " symoff " << st.symoff; 8773 if (st.symoff > object_size) 8774 outs() << " (past end of file)\n"; 8775 else 8776 outs() << "\n"; 8777 outs() << " nsyms " << st.nsyms; 8778 uint64_t big_size; 8779 if (Is64Bit) { 8780 big_size = st.nsyms; 8781 big_size *= sizeof(struct MachO::nlist_64); 8782 big_size += st.symoff; 8783 if (big_size > object_size) 8784 outs() << " (past end of file)\n"; 8785 else 8786 outs() << "\n"; 8787 } else { 8788 big_size = st.nsyms; 8789 big_size *= sizeof(struct MachO::nlist); 8790 big_size += st.symoff; 8791 if (big_size > object_size) 8792 outs() << " (past end of file)\n"; 8793 else 8794 outs() << "\n"; 8795 } 8796 outs() << " stroff " << st.stroff; 8797 if (st.stroff > object_size) 8798 outs() << " (past end of file)\n"; 8799 else 8800 outs() << "\n"; 8801 outs() << " strsize " << st.strsize; 8802 big_size = st.stroff; 8803 big_size += st.strsize; 8804 if (big_size > object_size) 8805 outs() << " (past end of file)\n"; 8806 else 8807 outs() << "\n"; 8808 } 8809 8810 static void PrintDysymtabLoadCommand(MachO::dysymtab_command dyst, 8811 uint32_t nsyms, uint32_t object_size, 8812 bool Is64Bit) { 8813 outs() << " cmd LC_DYSYMTAB\n"; 8814 outs() << " cmdsize " << dyst.cmdsize; 8815 if (dyst.cmdsize != sizeof(struct MachO::dysymtab_command)) 8816 outs() << " Incorrect size\n"; 8817 else 8818 outs() << "\n"; 8819 outs() << " ilocalsym " << dyst.ilocalsym; 8820 if (dyst.ilocalsym > nsyms) 8821 outs() << " (greater than the number of symbols)\n"; 8822 else 8823 outs() << "\n"; 8824 outs() << " nlocalsym " << dyst.nlocalsym; 8825 uint64_t big_size; 8826 big_size = dyst.ilocalsym; 8827 big_size += dyst.nlocalsym; 8828 if (big_size > nsyms) 8829 outs() << " (past the end of the symbol table)\n"; 8830 else 8831 outs() << "\n"; 8832 outs() << " iextdefsym " << dyst.iextdefsym; 8833 if (dyst.iextdefsym > nsyms) 8834 outs() << " (greater than the number of symbols)\n"; 8835 else 8836 outs() << "\n"; 8837 outs() << " nextdefsym " << dyst.nextdefsym; 8838 big_size = dyst.iextdefsym; 8839 big_size += dyst.nextdefsym; 8840 if (big_size > nsyms) 8841 outs() << " (past the end of the symbol table)\n"; 8842 else 8843 outs() << "\n"; 8844 outs() << " iundefsym " << dyst.iundefsym; 8845 if (dyst.iundefsym > nsyms) 8846 outs() << " (greater than the number of symbols)\n"; 8847 else 8848 outs() << "\n"; 8849 outs() << " nundefsym " << dyst.nundefsym; 8850 big_size = dyst.iundefsym; 8851 big_size += dyst.nundefsym; 8852 if (big_size > nsyms) 8853 outs() << " (past the end of the symbol table)\n"; 8854 else 8855 outs() << "\n"; 8856 outs() << " tocoff " << dyst.tocoff; 8857 if (dyst.tocoff > object_size) 8858 outs() << " (past end of file)\n"; 8859 else 8860 outs() << "\n"; 8861 outs() << " ntoc " << dyst.ntoc; 8862 big_size = dyst.ntoc; 8863 big_size *= sizeof(struct MachO::dylib_table_of_contents); 8864 big_size += dyst.tocoff; 8865 if (big_size > object_size) 8866 outs() << " (past end of file)\n"; 8867 else 8868 outs() << "\n"; 8869 outs() << " modtaboff " << dyst.modtaboff; 8870 if (dyst.modtaboff > object_size) 8871 outs() << " (past end of file)\n"; 8872 else 8873 outs() << "\n"; 8874 outs() << " nmodtab " << dyst.nmodtab; 8875 uint64_t modtabend; 8876 if (Is64Bit) { 8877 modtabend = dyst.nmodtab; 8878 modtabend *= sizeof(struct MachO::dylib_module_64); 8879 modtabend += dyst.modtaboff; 8880 } else { 8881 modtabend = dyst.nmodtab; 8882 modtabend *= sizeof(struct MachO::dylib_module); 8883 modtabend += dyst.modtaboff; 8884 } 8885 if (modtabend > object_size) 8886 outs() << " (past end of file)\n"; 8887 else 8888 outs() << "\n"; 8889 outs() << " extrefsymoff " << dyst.extrefsymoff; 8890 if (dyst.extrefsymoff > object_size) 8891 outs() << " (past end of file)\n"; 8892 else 8893 outs() << "\n"; 8894 outs() << " nextrefsyms " << dyst.nextrefsyms; 8895 big_size = dyst.nextrefsyms; 8896 big_size *= sizeof(struct MachO::dylib_reference); 8897 big_size += dyst.extrefsymoff; 8898 if (big_size > object_size) 8899 outs() << " (past end of file)\n"; 8900 else 8901 outs() << "\n"; 8902 outs() << " indirectsymoff " << dyst.indirectsymoff; 8903 if (dyst.indirectsymoff > object_size) 8904 outs() << " (past end of file)\n"; 8905 else 8906 outs() << "\n"; 8907 outs() << " nindirectsyms " << dyst.nindirectsyms; 8908 big_size = dyst.nindirectsyms; 8909 big_size *= sizeof(uint32_t); 8910 big_size += dyst.indirectsymoff; 8911 if (big_size > object_size) 8912 outs() << " (past end of file)\n"; 8913 else 8914 outs() << "\n"; 8915 outs() << " extreloff " << dyst.extreloff; 8916 if (dyst.extreloff > object_size) 8917 outs() << " (past end of file)\n"; 8918 else 8919 outs() << "\n"; 8920 outs() << " nextrel " << dyst.nextrel; 8921 big_size = dyst.nextrel; 8922 big_size *= sizeof(struct MachO::relocation_info); 8923 big_size += dyst.extreloff; 8924 if (big_size > object_size) 8925 outs() << " (past end of file)\n"; 8926 else 8927 outs() << "\n"; 8928 outs() << " locreloff " << dyst.locreloff; 8929 if (dyst.locreloff > object_size) 8930 outs() << " (past end of file)\n"; 8931 else 8932 outs() << "\n"; 8933 outs() << " nlocrel " << dyst.nlocrel; 8934 big_size = dyst.nlocrel; 8935 big_size *= sizeof(struct MachO::relocation_info); 8936 big_size += dyst.locreloff; 8937 if (big_size > object_size) 8938 outs() << " (past end of file)\n"; 8939 else 8940 outs() << "\n"; 8941 } 8942 8943 static void PrintDyldInfoLoadCommand(MachO::dyld_info_command dc, 8944 uint32_t object_size) { 8945 if (dc.cmd == MachO::LC_DYLD_INFO) 8946 outs() << " cmd LC_DYLD_INFO\n"; 8947 else 8948 outs() << " cmd LC_DYLD_INFO_ONLY\n"; 8949 outs() << " cmdsize " << dc.cmdsize; 8950 if (dc.cmdsize != sizeof(struct MachO::dyld_info_command)) 8951 outs() << " Incorrect size\n"; 8952 else 8953 outs() << "\n"; 8954 outs() << " rebase_off " << dc.rebase_off; 8955 if (dc.rebase_off > object_size) 8956 outs() << " (past end of file)\n"; 8957 else 8958 outs() << "\n"; 8959 outs() << " rebase_size " << dc.rebase_size; 8960 uint64_t big_size; 8961 big_size = dc.rebase_off; 8962 big_size += dc.rebase_size; 8963 if (big_size > object_size) 8964 outs() << " (past end of file)\n"; 8965 else 8966 outs() << "\n"; 8967 outs() << " bind_off " << dc.bind_off; 8968 if (dc.bind_off > object_size) 8969 outs() << " (past end of file)\n"; 8970 else 8971 outs() << "\n"; 8972 outs() << " bind_size " << dc.bind_size; 8973 big_size = dc.bind_off; 8974 big_size += dc.bind_size; 8975 if (big_size > object_size) 8976 outs() << " (past end of file)\n"; 8977 else 8978 outs() << "\n"; 8979 outs() << " weak_bind_off " << dc.weak_bind_off; 8980 if (dc.weak_bind_off > object_size) 8981 outs() << " (past end of file)\n"; 8982 else 8983 outs() << "\n"; 8984 outs() << " weak_bind_size " << dc.weak_bind_size; 8985 big_size = dc.weak_bind_off; 8986 big_size += dc.weak_bind_size; 8987 if (big_size > object_size) 8988 outs() << " (past end of file)\n"; 8989 else 8990 outs() << "\n"; 8991 outs() << " lazy_bind_off " << dc.lazy_bind_off; 8992 if (dc.lazy_bind_off > object_size) 8993 outs() << " (past end of file)\n"; 8994 else 8995 outs() << "\n"; 8996 outs() << " lazy_bind_size " << dc.lazy_bind_size; 8997 big_size = dc.lazy_bind_off; 8998 big_size += dc.lazy_bind_size; 8999 if (big_size > object_size) 9000 outs() << " (past end of file)\n"; 9001 else 9002 outs() << "\n"; 9003 outs() << " export_off " << dc.export_off; 9004 if (dc.export_off > object_size) 9005 outs() << " (past end of file)\n"; 9006 else 9007 outs() << "\n"; 9008 outs() << " export_size " << dc.export_size; 9009 big_size = dc.export_off; 9010 big_size += dc.export_size; 9011 if (big_size > object_size) 9012 outs() << " (past end of file)\n"; 9013 else 9014 outs() << "\n"; 9015 } 9016 9017 static void PrintDyldLoadCommand(MachO::dylinker_command dyld, 9018 const char *Ptr) { 9019 if (dyld.cmd == MachO::LC_ID_DYLINKER) 9020 outs() << " cmd LC_ID_DYLINKER\n"; 9021 else if (dyld.cmd == MachO::LC_LOAD_DYLINKER) 9022 outs() << " cmd LC_LOAD_DYLINKER\n"; 9023 else if (dyld.cmd == MachO::LC_DYLD_ENVIRONMENT) 9024 outs() << " cmd LC_DYLD_ENVIRONMENT\n"; 9025 else 9026 outs() << " cmd ?(" << dyld.cmd << ")\n"; 9027 outs() << " cmdsize " << dyld.cmdsize; 9028 if (dyld.cmdsize < sizeof(struct MachO::dylinker_command)) 9029 outs() << " Incorrect size\n"; 9030 else 9031 outs() << "\n"; 9032 if (dyld.name >= dyld.cmdsize) 9033 outs() << " name ?(bad offset " << dyld.name << ")\n"; 9034 else { 9035 const char *P = (const char *)(Ptr) + dyld.name; 9036 outs() << " name " << P << " (offset " << dyld.name << ")\n"; 9037 } 9038 } 9039 9040 static void PrintUuidLoadCommand(MachO::uuid_command uuid) { 9041 outs() << " cmd LC_UUID\n"; 9042 outs() << " cmdsize " << uuid.cmdsize; 9043 if (uuid.cmdsize != sizeof(struct MachO::uuid_command)) 9044 outs() << " Incorrect size\n"; 9045 else 9046 outs() << "\n"; 9047 outs() << " uuid "; 9048 for (int i = 0; i < 16; ++i) { 9049 outs() << format("%02" PRIX32, uuid.uuid[i]); 9050 if (i == 3 || i == 5 || i == 7 || i == 9) 9051 outs() << "-"; 9052 } 9053 outs() << "\n"; 9054 } 9055 9056 static void PrintRpathLoadCommand(MachO::rpath_command rpath, const char *Ptr) { 9057 outs() << " cmd LC_RPATH\n"; 9058 outs() << " cmdsize " << rpath.cmdsize; 9059 if (rpath.cmdsize < sizeof(struct MachO::rpath_command)) 9060 outs() << " Incorrect size\n"; 9061 else 9062 outs() << "\n"; 9063 if (rpath.path >= rpath.cmdsize) 9064 outs() << " path ?(bad offset " << rpath.path << ")\n"; 9065 else { 9066 const char *P = (const char *)(Ptr) + rpath.path; 9067 outs() << " path " << P << " (offset " << rpath.path << ")\n"; 9068 } 9069 } 9070 9071 static void PrintVersionMinLoadCommand(MachO::version_min_command vd) { 9072 StringRef LoadCmdName; 9073 switch (vd.cmd) { 9074 case MachO::LC_VERSION_MIN_MACOSX: 9075 LoadCmdName = "LC_VERSION_MIN_MACOSX"; 9076 break; 9077 case MachO::LC_VERSION_MIN_IPHONEOS: 9078 LoadCmdName = "LC_VERSION_MIN_IPHONEOS"; 9079 break; 9080 case MachO::LC_VERSION_MIN_TVOS: 9081 LoadCmdName = "LC_VERSION_MIN_TVOS"; 9082 break; 9083 case MachO::LC_VERSION_MIN_WATCHOS: 9084 LoadCmdName = "LC_VERSION_MIN_WATCHOS"; 9085 break; 9086 default: 9087 llvm_unreachable("Unknown version min load command"); 9088 } 9089 9090 outs() << " cmd " << LoadCmdName << '\n'; 9091 outs() << " cmdsize " << vd.cmdsize; 9092 if (vd.cmdsize != sizeof(struct MachO::version_min_command)) 9093 outs() << " Incorrect size\n"; 9094 else 9095 outs() << "\n"; 9096 outs() << " version " 9097 << MachOObjectFile::getVersionMinMajor(vd, false) << "." 9098 << MachOObjectFile::getVersionMinMinor(vd, false); 9099 uint32_t Update = MachOObjectFile::getVersionMinUpdate(vd, false); 9100 if (Update != 0) 9101 outs() << "." << Update; 9102 outs() << "\n"; 9103 if (vd.sdk == 0) 9104 outs() << " sdk n/a"; 9105 else { 9106 outs() << " sdk " 9107 << MachOObjectFile::getVersionMinMajor(vd, true) << "." 9108 << MachOObjectFile::getVersionMinMinor(vd, true); 9109 } 9110 Update = MachOObjectFile::getVersionMinUpdate(vd, true); 9111 if (Update != 0) 9112 outs() << "." << Update; 9113 outs() << "\n"; 9114 } 9115 9116 static void PrintNoteLoadCommand(MachO::note_command Nt) { 9117 outs() << " cmd LC_NOTE\n"; 9118 outs() << " cmdsize " << Nt.cmdsize; 9119 if (Nt.cmdsize != sizeof(struct MachO::note_command)) 9120 outs() << " Incorrect size\n"; 9121 else 9122 outs() << "\n"; 9123 const char *d = Nt.data_owner; 9124 outs() << "data_owner " << format("%.16s\n", d); 9125 outs() << " offset " << Nt.offset << "\n"; 9126 outs() << " size " << Nt.size << "\n"; 9127 } 9128 9129 static void PrintBuildToolVersion(MachO::build_tool_version bv) { 9130 outs() << " tool " << MachOObjectFile::getBuildTool(bv.tool) << "\n"; 9131 outs() << " version " << MachOObjectFile::getVersionString(bv.version) 9132 << "\n"; 9133 } 9134 9135 static void PrintBuildVersionLoadCommand(const MachOObjectFile *obj, 9136 MachO::build_version_command bd) { 9137 outs() << " cmd LC_BUILD_VERSION\n"; 9138 outs() << " cmdsize " << bd.cmdsize; 9139 if (bd.cmdsize != 9140 sizeof(struct MachO::build_version_command) + 9141 bd.ntools * sizeof(struct MachO::build_tool_version)) 9142 outs() << " Incorrect size\n"; 9143 else 9144 outs() << "\n"; 9145 outs() << " platform " << MachOObjectFile::getBuildPlatform(bd.platform) 9146 << "\n"; 9147 if (bd.sdk) 9148 outs() << " sdk " << MachOObjectFile::getVersionString(bd.sdk) 9149 << "\n"; 9150 else 9151 outs() << " sdk n/a\n"; 9152 outs() << " minos " << MachOObjectFile::getVersionString(bd.minos) 9153 << "\n"; 9154 outs() << " ntools " << bd.ntools << "\n"; 9155 for (unsigned i = 0; i < bd.ntools; ++i) { 9156 MachO::build_tool_version bv = obj->getBuildToolVersion(i); 9157 PrintBuildToolVersion(bv); 9158 } 9159 } 9160 9161 static void PrintSourceVersionCommand(MachO::source_version_command sd) { 9162 outs() << " cmd LC_SOURCE_VERSION\n"; 9163 outs() << " cmdsize " << sd.cmdsize; 9164 if (sd.cmdsize != sizeof(struct MachO::source_version_command)) 9165 outs() << " Incorrect size\n"; 9166 else 9167 outs() << "\n"; 9168 uint64_t a = (sd.version >> 40) & 0xffffff; 9169 uint64_t b = (sd.version >> 30) & 0x3ff; 9170 uint64_t c = (sd.version >> 20) & 0x3ff; 9171 uint64_t d = (sd.version >> 10) & 0x3ff; 9172 uint64_t e = sd.version & 0x3ff; 9173 outs() << " version " << a << "." << b; 9174 if (e != 0) 9175 outs() << "." << c << "." << d << "." << e; 9176 else if (d != 0) 9177 outs() << "." << c << "." << d; 9178 else if (c != 0) 9179 outs() << "." << c; 9180 outs() << "\n"; 9181 } 9182 9183 static void PrintEntryPointCommand(MachO::entry_point_command ep) { 9184 outs() << " cmd LC_MAIN\n"; 9185 outs() << " cmdsize " << ep.cmdsize; 9186 if (ep.cmdsize != sizeof(struct MachO::entry_point_command)) 9187 outs() << " Incorrect size\n"; 9188 else 9189 outs() << "\n"; 9190 outs() << " entryoff " << ep.entryoff << "\n"; 9191 outs() << " stacksize " << ep.stacksize << "\n"; 9192 } 9193 9194 static void PrintEncryptionInfoCommand(MachO::encryption_info_command ec, 9195 uint32_t object_size) { 9196 outs() << " cmd LC_ENCRYPTION_INFO\n"; 9197 outs() << " cmdsize " << ec.cmdsize; 9198 if (ec.cmdsize != sizeof(struct MachO::encryption_info_command)) 9199 outs() << " Incorrect size\n"; 9200 else 9201 outs() << "\n"; 9202 outs() << " cryptoff " << ec.cryptoff; 9203 if (ec.cryptoff > object_size) 9204 outs() << " (past end of file)\n"; 9205 else 9206 outs() << "\n"; 9207 outs() << " cryptsize " << ec.cryptsize; 9208 if (ec.cryptsize > object_size) 9209 outs() << " (past end of file)\n"; 9210 else 9211 outs() << "\n"; 9212 outs() << " cryptid " << ec.cryptid << "\n"; 9213 } 9214 9215 static void PrintEncryptionInfoCommand64(MachO::encryption_info_command_64 ec, 9216 uint32_t object_size) { 9217 outs() << " cmd LC_ENCRYPTION_INFO_64\n"; 9218 outs() << " cmdsize " << ec.cmdsize; 9219 if (ec.cmdsize != sizeof(struct MachO::encryption_info_command_64)) 9220 outs() << " Incorrect size\n"; 9221 else 9222 outs() << "\n"; 9223 outs() << " cryptoff " << ec.cryptoff; 9224 if (ec.cryptoff > object_size) 9225 outs() << " (past end of file)\n"; 9226 else 9227 outs() << "\n"; 9228 outs() << " cryptsize " << ec.cryptsize; 9229 if (ec.cryptsize > object_size) 9230 outs() << " (past end of file)\n"; 9231 else 9232 outs() << "\n"; 9233 outs() << " cryptid " << ec.cryptid << "\n"; 9234 outs() << " pad " << ec.pad << "\n"; 9235 } 9236 9237 static void PrintLinkerOptionCommand(MachO::linker_option_command lo, 9238 const char *Ptr) { 9239 outs() << " cmd LC_LINKER_OPTION\n"; 9240 outs() << " cmdsize " << lo.cmdsize; 9241 if (lo.cmdsize < sizeof(struct MachO::linker_option_command)) 9242 outs() << " Incorrect size\n"; 9243 else 9244 outs() << "\n"; 9245 outs() << " count " << lo.count << "\n"; 9246 const char *string = Ptr + sizeof(struct MachO::linker_option_command); 9247 uint32_t left = lo.cmdsize - sizeof(struct MachO::linker_option_command); 9248 uint32_t i = 0; 9249 while (left > 0) { 9250 while (*string == '\0' && left > 0) { 9251 string++; 9252 left--; 9253 } 9254 if (left > 0) { 9255 i++; 9256 outs() << " string #" << i << " " << format("%.*s\n", left, string); 9257 uint32_t NullPos = StringRef(string, left).find('\0'); 9258 uint32_t len = std::min(NullPos, left) + 1; 9259 string += len; 9260 left -= len; 9261 } 9262 } 9263 if (lo.count != i) 9264 outs() << " count " << lo.count << " does not match number of strings " 9265 << i << "\n"; 9266 } 9267 9268 static void PrintSubFrameworkCommand(MachO::sub_framework_command sub, 9269 const char *Ptr) { 9270 outs() << " cmd LC_SUB_FRAMEWORK\n"; 9271 outs() << " cmdsize " << sub.cmdsize; 9272 if (sub.cmdsize < sizeof(struct MachO::sub_framework_command)) 9273 outs() << " Incorrect size\n"; 9274 else 9275 outs() << "\n"; 9276 if (sub.umbrella < sub.cmdsize) { 9277 const char *P = Ptr + sub.umbrella; 9278 outs() << " umbrella " << P << " (offset " << sub.umbrella << ")\n"; 9279 } else { 9280 outs() << " umbrella ?(bad offset " << sub.umbrella << ")\n"; 9281 } 9282 } 9283 9284 static void PrintSubUmbrellaCommand(MachO::sub_umbrella_command sub, 9285 const char *Ptr) { 9286 outs() << " cmd LC_SUB_UMBRELLA\n"; 9287 outs() << " cmdsize " << sub.cmdsize; 9288 if (sub.cmdsize < sizeof(struct MachO::sub_umbrella_command)) 9289 outs() << " Incorrect size\n"; 9290 else 9291 outs() << "\n"; 9292 if (sub.sub_umbrella < sub.cmdsize) { 9293 const char *P = Ptr + sub.sub_umbrella; 9294 outs() << " sub_umbrella " << P << " (offset " << sub.sub_umbrella << ")\n"; 9295 } else { 9296 outs() << " sub_umbrella ?(bad offset " << sub.sub_umbrella << ")\n"; 9297 } 9298 } 9299 9300 static void PrintSubLibraryCommand(MachO::sub_library_command sub, 9301 const char *Ptr) { 9302 outs() << " cmd LC_SUB_LIBRARY\n"; 9303 outs() << " cmdsize " << sub.cmdsize; 9304 if (sub.cmdsize < sizeof(struct MachO::sub_library_command)) 9305 outs() << " Incorrect size\n"; 9306 else 9307 outs() << "\n"; 9308 if (sub.sub_library < sub.cmdsize) { 9309 const char *P = Ptr + sub.sub_library; 9310 outs() << " sub_library " << P << " (offset " << sub.sub_library << ")\n"; 9311 } else { 9312 outs() << " sub_library ?(bad offset " << sub.sub_library << ")\n"; 9313 } 9314 } 9315 9316 static void PrintSubClientCommand(MachO::sub_client_command sub, 9317 const char *Ptr) { 9318 outs() << " cmd LC_SUB_CLIENT\n"; 9319 outs() << " cmdsize " << sub.cmdsize; 9320 if (sub.cmdsize < sizeof(struct MachO::sub_client_command)) 9321 outs() << " Incorrect size\n"; 9322 else 9323 outs() << "\n"; 9324 if (sub.client < sub.cmdsize) { 9325 const char *P = Ptr + sub.client; 9326 outs() << " client " << P << " (offset " << sub.client << ")\n"; 9327 } else { 9328 outs() << " client ?(bad offset " << sub.client << ")\n"; 9329 } 9330 } 9331 9332 static void PrintRoutinesCommand(MachO::routines_command r) { 9333 outs() << " cmd LC_ROUTINES\n"; 9334 outs() << " cmdsize " << r.cmdsize; 9335 if (r.cmdsize != sizeof(struct MachO::routines_command)) 9336 outs() << " Incorrect size\n"; 9337 else 9338 outs() << "\n"; 9339 outs() << " init_address " << format("0x%08" PRIx32, r.init_address) << "\n"; 9340 outs() << " init_module " << r.init_module << "\n"; 9341 outs() << " reserved1 " << r.reserved1 << "\n"; 9342 outs() << " reserved2 " << r.reserved2 << "\n"; 9343 outs() << " reserved3 " << r.reserved3 << "\n"; 9344 outs() << " reserved4 " << r.reserved4 << "\n"; 9345 outs() << " reserved5 " << r.reserved5 << "\n"; 9346 outs() << " reserved6 " << r.reserved6 << "\n"; 9347 } 9348 9349 static void PrintRoutinesCommand64(MachO::routines_command_64 r) { 9350 outs() << " cmd LC_ROUTINES_64\n"; 9351 outs() << " cmdsize " << r.cmdsize; 9352 if (r.cmdsize != sizeof(struct MachO::routines_command_64)) 9353 outs() << " Incorrect size\n"; 9354 else 9355 outs() << "\n"; 9356 outs() << " init_address " << format("0x%016" PRIx64, r.init_address) << "\n"; 9357 outs() << " init_module " << r.init_module << "\n"; 9358 outs() << " reserved1 " << r.reserved1 << "\n"; 9359 outs() << " reserved2 " << r.reserved2 << "\n"; 9360 outs() << " reserved3 " << r.reserved3 << "\n"; 9361 outs() << " reserved4 " << r.reserved4 << "\n"; 9362 outs() << " reserved5 " << r.reserved5 << "\n"; 9363 outs() << " reserved6 " << r.reserved6 << "\n"; 9364 } 9365 9366 static void Print_x86_thread_state32_t(MachO::x86_thread_state32_t &cpu32) { 9367 outs() << "\t eax " << format("0x%08" PRIx32, cpu32.eax); 9368 outs() << " ebx " << format("0x%08" PRIx32, cpu32.ebx); 9369 outs() << " ecx " << format("0x%08" PRIx32, cpu32.ecx); 9370 outs() << " edx " << format("0x%08" PRIx32, cpu32.edx) << "\n"; 9371 outs() << "\t edi " << format("0x%08" PRIx32, cpu32.edi); 9372 outs() << " esi " << format("0x%08" PRIx32, cpu32.esi); 9373 outs() << " ebp " << format("0x%08" PRIx32, cpu32.ebp); 9374 outs() << " esp " << format("0x%08" PRIx32, cpu32.esp) << "\n"; 9375 outs() << "\t ss " << format("0x%08" PRIx32, cpu32.ss); 9376 outs() << " eflags " << format("0x%08" PRIx32, cpu32.eflags); 9377 outs() << " eip " << format("0x%08" PRIx32, cpu32.eip); 9378 outs() << " cs " << format("0x%08" PRIx32, cpu32.cs) << "\n"; 9379 outs() << "\t ds " << format("0x%08" PRIx32, cpu32.ds); 9380 outs() << " es " << format("0x%08" PRIx32, cpu32.es); 9381 outs() << " fs " << format("0x%08" PRIx32, cpu32.fs); 9382 outs() << " gs " << format("0x%08" PRIx32, cpu32.gs) << "\n"; 9383 } 9384 9385 static void Print_x86_thread_state64_t(MachO::x86_thread_state64_t &cpu64) { 9386 outs() << " rax " << format("0x%016" PRIx64, cpu64.rax); 9387 outs() << " rbx " << format("0x%016" PRIx64, cpu64.rbx); 9388 outs() << " rcx " << format("0x%016" PRIx64, cpu64.rcx) << "\n"; 9389 outs() << " rdx " << format("0x%016" PRIx64, cpu64.rdx); 9390 outs() << " rdi " << format("0x%016" PRIx64, cpu64.rdi); 9391 outs() << " rsi " << format("0x%016" PRIx64, cpu64.rsi) << "\n"; 9392 outs() << " rbp " << format("0x%016" PRIx64, cpu64.rbp); 9393 outs() << " rsp " << format("0x%016" PRIx64, cpu64.rsp); 9394 outs() << " r8 " << format("0x%016" PRIx64, cpu64.r8) << "\n"; 9395 outs() << " r9 " << format("0x%016" PRIx64, cpu64.r9); 9396 outs() << " r10 " << format("0x%016" PRIx64, cpu64.r10); 9397 outs() << " r11 " << format("0x%016" PRIx64, cpu64.r11) << "\n"; 9398 outs() << " r12 " << format("0x%016" PRIx64, cpu64.r12); 9399 outs() << " r13 " << format("0x%016" PRIx64, cpu64.r13); 9400 outs() << " r14 " << format("0x%016" PRIx64, cpu64.r14) << "\n"; 9401 outs() << " r15 " << format("0x%016" PRIx64, cpu64.r15); 9402 outs() << " rip " << format("0x%016" PRIx64, cpu64.rip) << "\n"; 9403 outs() << "rflags " << format("0x%016" PRIx64, cpu64.rflags); 9404 outs() << " cs " << format("0x%016" PRIx64, cpu64.cs); 9405 outs() << " fs " << format("0x%016" PRIx64, cpu64.fs) << "\n"; 9406 outs() << " gs " << format("0x%016" PRIx64, cpu64.gs) << "\n"; 9407 } 9408 9409 static void Print_mmst_reg(MachO::mmst_reg_t &r) { 9410 uint32_t f; 9411 outs() << "\t mmst_reg "; 9412 for (f = 0; f < 10; f++) 9413 outs() << format("%02" PRIx32, (r.mmst_reg[f] & 0xff)) << " "; 9414 outs() << "\n"; 9415 outs() << "\t mmst_rsrv "; 9416 for (f = 0; f < 6; f++) 9417 outs() << format("%02" PRIx32, (r.mmst_rsrv[f] & 0xff)) << " "; 9418 outs() << "\n"; 9419 } 9420 9421 static void Print_xmm_reg(MachO::xmm_reg_t &r) { 9422 uint32_t f; 9423 outs() << "\t xmm_reg "; 9424 for (f = 0; f < 16; f++) 9425 outs() << format("%02" PRIx32, (r.xmm_reg[f] & 0xff)) << " "; 9426 outs() << "\n"; 9427 } 9428 9429 static void Print_x86_float_state_t(MachO::x86_float_state64_t &fpu) { 9430 outs() << "\t fpu_reserved[0] " << fpu.fpu_reserved[0]; 9431 outs() << " fpu_reserved[1] " << fpu.fpu_reserved[1] << "\n"; 9432 outs() << "\t control: invalid " << fpu.fpu_fcw.invalid; 9433 outs() << " denorm " << fpu.fpu_fcw.denorm; 9434 outs() << " zdiv " << fpu.fpu_fcw.zdiv; 9435 outs() << " ovrfl " << fpu.fpu_fcw.ovrfl; 9436 outs() << " undfl " << fpu.fpu_fcw.undfl; 9437 outs() << " precis " << fpu.fpu_fcw.precis << "\n"; 9438 outs() << "\t\t pc "; 9439 if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_24B) 9440 outs() << "FP_PREC_24B "; 9441 else if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_53B) 9442 outs() << "FP_PREC_53B "; 9443 else if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_64B) 9444 outs() << "FP_PREC_64B "; 9445 else 9446 outs() << fpu.fpu_fcw.pc << " "; 9447 outs() << "rc "; 9448 if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_NEAR) 9449 outs() << "FP_RND_NEAR "; 9450 else if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_DOWN) 9451 outs() << "FP_RND_DOWN "; 9452 else if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_UP) 9453 outs() << "FP_RND_UP "; 9454 else if (fpu.fpu_fcw.rc == MachO::x86_FP_CHOP) 9455 outs() << "FP_CHOP "; 9456 outs() << "\n"; 9457 outs() << "\t status: invalid " << fpu.fpu_fsw.invalid; 9458 outs() << " denorm " << fpu.fpu_fsw.denorm; 9459 outs() << " zdiv " << fpu.fpu_fsw.zdiv; 9460 outs() << " ovrfl " << fpu.fpu_fsw.ovrfl; 9461 outs() << " undfl " << fpu.fpu_fsw.undfl; 9462 outs() << " precis " << fpu.fpu_fsw.precis; 9463 outs() << " stkflt " << fpu.fpu_fsw.stkflt << "\n"; 9464 outs() << "\t errsumm " << fpu.fpu_fsw.errsumm; 9465 outs() << " c0 " << fpu.fpu_fsw.c0; 9466 outs() << " c1 " << fpu.fpu_fsw.c1; 9467 outs() << " c2 " << fpu.fpu_fsw.c2; 9468 outs() << " tos " << fpu.fpu_fsw.tos; 9469 outs() << " c3 " << fpu.fpu_fsw.c3; 9470 outs() << " busy " << fpu.fpu_fsw.busy << "\n"; 9471 outs() << "\t fpu_ftw " << format("0x%02" PRIx32, fpu.fpu_ftw); 9472 outs() << " fpu_rsrv1 " << format("0x%02" PRIx32, fpu.fpu_rsrv1); 9473 outs() << " fpu_fop " << format("0x%04" PRIx32, fpu.fpu_fop); 9474 outs() << " fpu_ip " << format("0x%08" PRIx32, fpu.fpu_ip) << "\n"; 9475 outs() << "\t fpu_cs " << format("0x%04" PRIx32, fpu.fpu_cs); 9476 outs() << " fpu_rsrv2 " << format("0x%04" PRIx32, fpu.fpu_rsrv2); 9477 outs() << " fpu_dp " << format("0x%08" PRIx32, fpu.fpu_dp); 9478 outs() << " fpu_ds " << format("0x%04" PRIx32, fpu.fpu_ds) << "\n"; 9479 outs() << "\t fpu_rsrv3 " << format("0x%04" PRIx32, fpu.fpu_rsrv3); 9480 outs() << " fpu_mxcsr " << format("0x%08" PRIx32, fpu.fpu_mxcsr); 9481 outs() << " fpu_mxcsrmask " << format("0x%08" PRIx32, fpu.fpu_mxcsrmask); 9482 outs() << "\n"; 9483 outs() << "\t fpu_stmm0:\n"; 9484 Print_mmst_reg(fpu.fpu_stmm0); 9485 outs() << "\t fpu_stmm1:\n"; 9486 Print_mmst_reg(fpu.fpu_stmm1); 9487 outs() << "\t fpu_stmm2:\n"; 9488 Print_mmst_reg(fpu.fpu_stmm2); 9489 outs() << "\t fpu_stmm3:\n"; 9490 Print_mmst_reg(fpu.fpu_stmm3); 9491 outs() << "\t fpu_stmm4:\n"; 9492 Print_mmst_reg(fpu.fpu_stmm4); 9493 outs() << "\t fpu_stmm5:\n"; 9494 Print_mmst_reg(fpu.fpu_stmm5); 9495 outs() << "\t fpu_stmm6:\n"; 9496 Print_mmst_reg(fpu.fpu_stmm6); 9497 outs() << "\t fpu_stmm7:\n"; 9498 Print_mmst_reg(fpu.fpu_stmm7); 9499 outs() << "\t fpu_xmm0:\n"; 9500 Print_xmm_reg(fpu.fpu_xmm0); 9501 outs() << "\t fpu_xmm1:\n"; 9502 Print_xmm_reg(fpu.fpu_xmm1); 9503 outs() << "\t fpu_xmm2:\n"; 9504 Print_xmm_reg(fpu.fpu_xmm2); 9505 outs() << "\t fpu_xmm3:\n"; 9506 Print_xmm_reg(fpu.fpu_xmm3); 9507 outs() << "\t fpu_xmm4:\n"; 9508 Print_xmm_reg(fpu.fpu_xmm4); 9509 outs() << "\t fpu_xmm5:\n"; 9510 Print_xmm_reg(fpu.fpu_xmm5); 9511 outs() << "\t fpu_xmm6:\n"; 9512 Print_xmm_reg(fpu.fpu_xmm6); 9513 outs() << "\t fpu_xmm7:\n"; 9514 Print_xmm_reg(fpu.fpu_xmm7); 9515 outs() << "\t fpu_xmm8:\n"; 9516 Print_xmm_reg(fpu.fpu_xmm8); 9517 outs() << "\t fpu_xmm9:\n"; 9518 Print_xmm_reg(fpu.fpu_xmm9); 9519 outs() << "\t fpu_xmm10:\n"; 9520 Print_xmm_reg(fpu.fpu_xmm10); 9521 outs() << "\t fpu_xmm11:\n"; 9522 Print_xmm_reg(fpu.fpu_xmm11); 9523 outs() << "\t fpu_xmm12:\n"; 9524 Print_xmm_reg(fpu.fpu_xmm12); 9525 outs() << "\t fpu_xmm13:\n"; 9526 Print_xmm_reg(fpu.fpu_xmm13); 9527 outs() << "\t fpu_xmm14:\n"; 9528 Print_xmm_reg(fpu.fpu_xmm14); 9529 outs() << "\t fpu_xmm15:\n"; 9530 Print_xmm_reg(fpu.fpu_xmm15); 9531 outs() << "\t fpu_rsrv4:\n"; 9532 for (uint32_t f = 0; f < 6; f++) { 9533 outs() << "\t "; 9534 for (uint32_t g = 0; g < 16; g++) 9535 outs() << format("%02" PRIx32, fpu.fpu_rsrv4[f * g]) << " "; 9536 outs() << "\n"; 9537 } 9538 outs() << "\t fpu_reserved1 " << format("0x%08" PRIx32, fpu.fpu_reserved1); 9539 outs() << "\n"; 9540 } 9541 9542 static void Print_x86_exception_state_t(MachO::x86_exception_state64_t &exc64) { 9543 outs() << "\t trapno " << format("0x%08" PRIx32, exc64.trapno); 9544 outs() << " err " << format("0x%08" PRIx32, exc64.err); 9545 outs() << " faultvaddr " << format("0x%016" PRIx64, exc64.faultvaddr) << "\n"; 9546 } 9547 9548 static void Print_arm_thread_state32_t(MachO::arm_thread_state32_t &cpu32) { 9549 outs() << "\t r0 " << format("0x%08" PRIx32, cpu32.r[0]); 9550 outs() << " r1 " << format("0x%08" PRIx32, cpu32.r[1]); 9551 outs() << " r2 " << format("0x%08" PRIx32, cpu32.r[2]); 9552 outs() << " r3 " << format("0x%08" PRIx32, cpu32.r[3]) << "\n"; 9553 outs() << "\t r4 " << format("0x%08" PRIx32, cpu32.r[4]); 9554 outs() << " r5 " << format("0x%08" PRIx32, cpu32.r[5]); 9555 outs() << " r6 " << format("0x%08" PRIx32, cpu32.r[6]); 9556 outs() << " r7 " << format("0x%08" PRIx32, cpu32.r[7]) << "\n"; 9557 outs() << "\t r8 " << format("0x%08" PRIx32, cpu32.r[8]); 9558 outs() << " r9 " << format("0x%08" PRIx32, cpu32.r[9]); 9559 outs() << " r10 " << format("0x%08" PRIx32, cpu32.r[10]); 9560 outs() << " r11 " << format("0x%08" PRIx32, cpu32.r[11]) << "\n"; 9561 outs() << "\t r12 " << format("0x%08" PRIx32, cpu32.r[12]); 9562 outs() << " sp " << format("0x%08" PRIx32, cpu32.sp); 9563 outs() << " lr " << format("0x%08" PRIx32, cpu32.lr); 9564 outs() << " pc " << format("0x%08" PRIx32, cpu32.pc) << "\n"; 9565 outs() << "\t cpsr " << format("0x%08" PRIx32, cpu32.cpsr) << "\n"; 9566 } 9567 9568 static void Print_arm_thread_state64_t(MachO::arm_thread_state64_t &cpu64) { 9569 outs() << "\t x0 " << format("0x%016" PRIx64, cpu64.x[0]); 9570 outs() << " x1 " << format("0x%016" PRIx64, cpu64.x[1]); 9571 outs() << " x2 " << format("0x%016" PRIx64, cpu64.x[2]) << "\n"; 9572 outs() << "\t x3 " << format("0x%016" PRIx64, cpu64.x[3]); 9573 outs() << " x4 " << format("0x%016" PRIx64, cpu64.x[4]); 9574 outs() << " x5 " << format("0x%016" PRIx64, cpu64.x[5]) << "\n"; 9575 outs() << "\t x6 " << format("0x%016" PRIx64, cpu64.x[6]); 9576 outs() << " x7 " << format("0x%016" PRIx64, cpu64.x[7]); 9577 outs() << " x8 " << format("0x%016" PRIx64, cpu64.x[8]) << "\n"; 9578 outs() << "\t x9 " << format("0x%016" PRIx64, cpu64.x[9]); 9579 outs() << " x10 " << format("0x%016" PRIx64, cpu64.x[10]); 9580 outs() << " x11 " << format("0x%016" PRIx64, cpu64.x[11]) << "\n"; 9581 outs() << "\t x12 " << format("0x%016" PRIx64, cpu64.x[12]); 9582 outs() << " x13 " << format("0x%016" PRIx64, cpu64.x[13]); 9583 outs() << " x14 " << format("0x%016" PRIx64, cpu64.x[14]) << "\n"; 9584 outs() << "\t x15 " << format("0x%016" PRIx64, cpu64.x[15]); 9585 outs() << " x16 " << format("0x%016" PRIx64, cpu64.x[16]); 9586 outs() << " x17 " << format("0x%016" PRIx64, cpu64.x[17]) << "\n"; 9587 outs() << "\t x18 " << format("0x%016" PRIx64, cpu64.x[18]); 9588 outs() << " x19 " << format("0x%016" PRIx64, cpu64.x[19]); 9589 outs() << " x20 " << format("0x%016" PRIx64, cpu64.x[20]) << "\n"; 9590 outs() << "\t x21 " << format("0x%016" PRIx64, cpu64.x[21]); 9591 outs() << " x22 " << format("0x%016" PRIx64, cpu64.x[22]); 9592 outs() << " x23 " << format("0x%016" PRIx64, cpu64.x[23]) << "\n"; 9593 outs() << "\t x24 " << format("0x%016" PRIx64, cpu64.x[24]); 9594 outs() << " x25 " << format("0x%016" PRIx64, cpu64.x[25]); 9595 outs() << " x26 " << format("0x%016" PRIx64, cpu64.x[26]) << "\n"; 9596 outs() << "\t x27 " << format("0x%016" PRIx64, cpu64.x[27]); 9597 outs() << " x28 " << format("0x%016" PRIx64, cpu64.x[28]); 9598 outs() << " fp " << format("0x%016" PRIx64, cpu64.fp) << "\n"; 9599 outs() << "\t lr " << format("0x%016" PRIx64, cpu64.lr); 9600 outs() << " sp " << format("0x%016" PRIx64, cpu64.sp); 9601 outs() << " pc " << format("0x%016" PRIx64, cpu64.pc) << "\n"; 9602 outs() << "\t cpsr " << format("0x%08" PRIx32, cpu64.cpsr) << "\n"; 9603 } 9604 9605 static void PrintThreadCommand(MachO::thread_command t, const char *Ptr, 9606 bool isLittleEndian, uint32_t cputype) { 9607 if (t.cmd == MachO::LC_THREAD) 9608 outs() << " cmd LC_THREAD\n"; 9609 else if (t.cmd == MachO::LC_UNIXTHREAD) 9610 outs() << " cmd LC_UNIXTHREAD\n"; 9611 else 9612 outs() << " cmd " << t.cmd << " (unknown)\n"; 9613 outs() << " cmdsize " << t.cmdsize; 9614 if (t.cmdsize < sizeof(struct MachO::thread_command) + 2 * sizeof(uint32_t)) 9615 outs() << " Incorrect size\n"; 9616 else 9617 outs() << "\n"; 9618 9619 const char *begin = Ptr + sizeof(struct MachO::thread_command); 9620 const char *end = Ptr + t.cmdsize; 9621 uint32_t flavor, count, left; 9622 if (cputype == MachO::CPU_TYPE_I386) { 9623 while (begin < end) { 9624 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) { 9625 memcpy((char *)&flavor, begin, sizeof(uint32_t)); 9626 begin += sizeof(uint32_t); 9627 } else { 9628 flavor = 0; 9629 begin = end; 9630 } 9631 if (isLittleEndian != sys::IsLittleEndianHost) 9632 sys::swapByteOrder(flavor); 9633 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) { 9634 memcpy((char *)&count, begin, sizeof(uint32_t)); 9635 begin += sizeof(uint32_t); 9636 } else { 9637 count = 0; 9638 begin = end; 9639 } 9640 if (isLittleEndian != sys::IsLittleEndianHost) 9641 sys::swapByteOrder(count); 9642 if (flavor == MachO::x86_THREAD_STATE32) { 9643 outs() << " flavor i386_THREAD_STATE\n"; 9644 if (count == MachO::x86_THREAD_STATE32_COUNT) 9645 outs() << " count i386_THREAD_STATE_COUNT\n"; 9646 else 9647 outs() << " count " << count 9648 << " (not x86_THREAD_STATE32_COUNT)\n"; 9649 MachO::x86_thread_state32_t cpu32; 9650 left = end - begin; 9651 if (left >= sizeof(MachO::x86_thread_state32_t)) { 9652 memcpy(&cpu32, begin, sizeof(MachO::x86_thread_state32_t)); 9653 begin += sizeof(MachO::x86_thread_state32_t); 9654 } else { 9655 memset(&cpu32, '\0', sizeof(MachO::x86_thread_state32_t)); 9656 memcpy(&cpu32, begin, left); 9657 begin += left; 9658 } 9659 if (isLittleEndian != sys::IsLittleEndianHost) 9660 swapStruct(cpu32); 9661 Print_x86_thread_state32_t(cpu32); 9662 } else if (flavor == MachO::x86_THREAD_STATE) { 9663 outs() << " flavor x86_THREAD_STATE\n"; 9664 if (count == MachO::x86_THREAD_STATE_COUNT) 9665 outs() << " count x86_THREAD_STATE_COUNT\n"; 9666 else 9667 outs() << " count " << count 9668 << " (not x86_THREAD_STATE_COUNT)\n"; 9669 struct MachO::x86_thread_state_t ts; 9670 left = end - begin; 9671 if (left >= sizeof(MachO::x86_thread_state_t)) { 9672 memcpy(&ts, begin, sizeof(MachO::x86_thread_state_t)); 9673 begin += sizeof(MachO::x86_thread_state_t); 9674 } else { 9675 memset(&ts, '\0', sizeof(MachO::x86_thread_state_t)); 9676 memcpy(&ts, begin, left); 9677 begin += left; 9678 } 9679 if (isLittleEndian != sys::IsLittleEndianHost) 9680 swapStruct(ts); 9681 if (ts.tsh.flavor == MachO::x86_THREAD_STATE32) { 9682 outs() << "\t tsh.flavor x86_THREAD_STATE32 "; 9683 if (ts.tsh.count == MachO::x86_THREAD_STATE32_COUNT) 9684 outs() << "tsh.count x86_THREAD_STATE32_COUNT\n"; 9685 else 9686 outs() << "tsh.count " << ts.tsh.count 9687 << " (not x86_THREAD_STATE32_COUNT\n"; 9688 Print_x86_thread_state32_t(ts.uts.ts32); 9689 } else { 9690 outs() << "\t tsh.flavor " << ts.tsh.flavor << " tsh.count " 9691 << ts.tsh.count << "\n"; 9692 } 9693 } else { 9694 outs() << " flavor " << flavor << " (unknown)\n"; 9695 outs() << " count " << count << "\n"; 9696 outs() << " state (unknown)\n"; 9697 begin += count * sizeof(uint32_t); 9698 } 9699 } 9700 } else if (cputype == MachO::CPU_TYPE_X86_64) { 9701 while (begin < end) { 9702 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) { 9703 memcpy((char *)&flavor, begin, sizeof(uint32_t)); 9704 begin += sizeof(uint32_t); 9705 } else { 9706 flavor = 0; 9707 begin = end; 9708 } 9709 if (isLittleEndian != sys::IsLittleEndianHost) 9710 sys::swapByteOrder(flavor); 9711 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) { 9712 memcpy((char *)&count, begin, sizeof(uint32_t)); 9713 begin += sizeof(uint32_t); 9714 } else { 9715 count = 0; 9716 begin = end; 9717 } 9718 if (isLittleEndian != sys::IsLittleEndianHost) 9719 sys::swapByteOrder(count); 9720 if (flavor == MachO::x86_THREAD_STATE64) { 9721 outs() << " flavor x86_THREAD_STATE64\n"; 9722 if (count == MachO::x86_THREAD_STATE64_COUNT) 9723 outs() << " count x86_THREAD_STATE64_COUNT\n"; 9724 else 9725 outs() << " count " << count 9726 << " (not x86_THREAD_STATE64_COUNT)\n"; 9727 MachO::x86_thread_state64_t cpu64; 9728 left = end - begin; 9729 if (left >= sizeof(MachO::x86_thread_state64_t)) { 9730 memcpy(&cpu64, begin, sizeof(MachO::x86_thread_state64_t)); 9731 begin += sizeof(MachO::x86_thread_state64_t); 9732 } else { 9733 memset(&cpu64, '\0', sizeof(MachO::x86_thread_state64_t)); 9734 memcpy(&cpu64, begin, left); 9735 begin += left; 9736 } 9737 if (isLittleEndian != sys::IsLittleEndianHost) 9738 swapStruct(cpu64); 9739 Print_x86_thread_state64_t(cpu64); 9740 } else if (flavor == MachO::x86_THREAD_STATE) { 9741 outs() << " flavor x86_THREAD_STATE\n"; 9742 if (count == MachO::x86_THREAD_STATE_COUNT) 9743 outs() << " count x86_THREAD_STATE_COUNT\n"; 9744 else 9745 outs() << " count " << count 9746 << " (not x86_THREAD_STATE_COUNT)\n"; 9747 struct MachO::x86_thread_state_t ts; 9748 left = end - begin; 9749 if (left >= sizeof(MachO::x86_thread_state_t)) { 9750 memcpy(&ts, begin, sizeof(MachO::x86_thread_state_t)); 9751 begin += sizeof(MachO::x86_thread_state_t); 9752 } else { 9753 memset(&ts, '\0', sizeof(MachO::x86_thread_state_t)); 9754 memcpy(&ts, begin, left); 9755 begin += left; 9756 } 9757 if (isLittleEndian != sys::IsLittleEndianHost) 9758 swapStruct(ts); 9759 if (ts.tsh.flavor == MachO::x86_THREAD_STATE64) { 9760 outs() << "\t tsh.flavor x86_THREAD_STATE64 "; 9761 if (ts.tsh.count == MachO::x86_THREAD_STATE64_COUNT) 9762 outs() << "tsh.count x86_THREAD_STATE64_COUNT\n"; 9763 else 9764 outs() << "tsh.count " << ts.tsh.count 9765 << " (not x86_THREAD_STATE64_COUNT\n"; 9766 Print_x86_thread_state64_t(ts.uts.ts64); 9767 } else { 9768 outs() << "\t tsh.flavor " << ts.tsh.flavor << " tsh.count " 9769 << ts.tsh.count << "\n"; 9770 } 9771 } else if (flavor == MachO::x86_FLOAT_STATE) { 9772 outs() << " flavor x86_FLOAT_STATE\n"; 9773 if (count == MachO::x86_FLOAT_STATE_COUNT) 9774 outs() << " count x86_FLOAT_STATE_COUNT\n"; 9775 else 9776 outs() << " count " << count << " (not x86_FLOAT_STATE_COUNT)\n"; 9777 struct MachO::x86_float_state_t fs; 9778 left = end - begin; 9779 if (left >= sizeof(MachO::x86_float_state_t)) { 9780 memcpy(&fs, begin, sizeof(MachO::x86_float_state_t)); 9781 begin += sizeof(MachO::x86_float_state_t); 9782 } else { 9783 memset(&fs, '\0', sizeof(MachO::x86_float_state_t)); 9784 memcpy(&fs, begin, left); 9785 begin += left; 9786 } 9787 if (isLittleEndian != sys::IsLittleEndianHost) 9788 swapStruct(fs); 9789 if (fs.fsh.flavor == MachO::x86_FLOAT_STATE64) { 9790 outs() << "\t fsh.flavor x86_FLOAT_STATE64 "; 9791 if (fs.fsh.count == MachO::x86_FLOAT_STATE64_COUNT) 9792 outs() << "fsh.count x86_FLOAT_STATE64_COUNT\n"; 9793 else 9794 outs() << "fsh.count " << fs.fsh.count 9795 << " (not x86_FLOAT_STATE64_COUNT\n"; 9796 Print_x86_float_state_t(fs.ufs.fs64); 9797 } else { 9798 outs() << "\t fsh.flavor " << fs.fsh.flavor << " fsh.count " 9799 << fs.fsh.count << "\n"; 9800 } 9801 } else if (flavor == MachO::x86_EXCEPTION_STATE) { 9802 outs() << " flavor x86_EXCEPTION_STATE\n"; 9803 if (count == MachO::x86_EXCEPTION_STATE_COUNT) 9804 outs() << " count x86_EXCEPTION_STATE_COUNT\n"; 9805 else 9806 outs() << " count " << count 9807 << " (not x86_EXCEPTION_STATE_COUNT)\n"; 9808 struct MachO::x86_exception_state_t es; 9809 left = end - begin; 9810 if (left >= sizeof(MachO::x86_exception_state_t)) { 9811 memcpy(&es, begin, sizeof(MachO::x86_exception_state_t)); 9812 begin += sizeof(MachO::x86_exception_state_t); 9813 } else { 9814 memset(&es, '\0', sizeof(MachO::x86_exception_state_t)); 9815 memcpy(&es, begin, left); 9816 begin += left; 9817 } 9818 if (isLittleEndian != sys::IsLittleEndianHost) 9819 swapStruct(es); 9820 if (es.esh.flavor == MachO::x86_EXCEPTION_STATE64) { 9821 outs() << "\t esh.flavor x86_EXCEPTION_STATE64\n"; 9822 if (es.esh.count == MachO::x86_EXCEPTION_STATE64_COUNT) 9823 outs() << "\t esh.count x86_EXCEPTION_STATE64_COUNT\n"; 9824 else 9825 outs() << "\t esh.count " << es.esh.count 9826 << " (not x86_EXCEPTION_STATE64_COUNT\n"; 9827 Print_x86_exception_state_t(es.ues.es64); 9828 } else { 9829 outs() << "\t esh.flavor " << es.esh.flavor << " esh.count " 9830 << es.esh.count << "\n"; 9831 } 9832 } else if (flavor == MachO::x86_EXCEPTION_STATE64) { 9833 outs() << " flavor x86_EXCEPTION_STATE64\n"; 9834 if (count == MachO::x86_EXCEPTION_STATE64_COUNT) 9835 outs() << " count x86_EXCEPTION_STATE64_COUNT\n"; 9836 else 9837 outs() << " count " << count 9838 << " (not x86_EXCEPTION_STATE64_COUNT)\n"; 9839 struct MachO::x86_exception_state64_t es64; 9840 left = end - begin; 9841 if (left >= sizeof(MachO::x86_exception_state64_t)) { 9842 memcpy(&es64, begin, sizeof(MachO::x86_exception_state64_t)); 9843 begin += sizeof(MachO::x86_exception_state64_t); 9844 } else { 9845 memset(&es64, '\0', sizeof(MachO::x86_exception_state64_t)); 9846 memcpy(&es64, begin, left); 9847 begin += left; 9848 } 9849 if (isLittleEndian != sys::IsLittleEndianHost) 9850 swapStruct(es64); 9851 Print_x86_exception_state_t(es64); 9852 } else { 9853 outs() << " flavor " << flavor << " (unknown)\n"; 9854 outs() << " count " << count << "\n"; 9855 outs() << " state (unknown)\n"; 9856 begin += count * sizeof(uint32_t); 9857 } 9858 } 9859 } else if (cputype == MachO::CPU_TYPE_ARM) { 9860 while (begin < end) { 9861 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) { 9862 memcpy((char *)&flavor, begin, sizeof(uint32_t)); 9863 begin += sizeof(uint32_t); 9864 } else { 9865 flavor = 0; 9866 begin = end; 9867 } 9868 if (isLittleEndian != sys::IsLittleEndianHost) 9869 sys::swapByteOrder(flavor); 9870 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) { 9871 memcpy((char *)&count, begin, sizeof(uint32_t)); 9872 begin += sizeof(uint32_t); 9873 } else { 9874 count = 0; 9875 begin = end; 9876 } 9877 if (isLittleEndian != sys::IsLittleEndianHost) 9878 sys::swapByteOrder(count); 9879 if (flavor == MachO::ARM_THREAD_STATE) { 9880 outs() << " flavor ARM_THREAD_STATE\n"; 9881 if (count == MachO::ARM_THREAD_STATE_COUNT) 9882 outs() << " count ARM_THREAD_STATE_COUNT\n"; 9883 else 9884 outs() << " count " << count 9885 << " (not ARM_THREAD_STATE_COUNT)\n"; 9886 MachO::arm_thread_state32_t cpu32; 9887 left = end - begin; 9888 if (left >= sizeof(MachO::arm_thread_state32_t)) { 9889 memcpy(&cpu32, begin, sizeof(MachO::arm_thread_state32_t)); 9890 begin += sizeof(MachO::arm_thread_state32_t); 9891 } else { 9892 memset(&cpu32, '\0', sizeof(MachO::arm_thread_state32_t)); 9893 memcpy(&cpu32, begin, left); 9894 begin += left; 9895 } 9896 if (isLittleEndian != sys::IsLittleEndianHost) 9897 swapStruct(cpu32); 9898 Print_arm_thread_state32_t(cpu32); 9899 } else { 9900 outs() << " flavor " << flavor << " (unknown)\n"; 9901 outs() << " count " << count << "\n"; 9902 outs() << " state (unknown)\n"; 9903 begin += count * sizeof(uint32_t); 9904 } 9905 } 9906 } else if (cputype == MachO::CPU_TYPE_ARM64 || 9907 cputype == MachO::CPU_TYPE_ARM64_32) { 9908 while (begin < end) { 9909 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) { 9910 memcpy((char *)&flavor, begin, sizeof(uint32_t)); 9911 begin += sizeof(uint32_t); 9912 } else { 9913 flavor = 0; 9914 begin = end; 9915 } 9916 if (isLittleEndian != sys::IsLittleEndianHost) 9917 sys::swapByteOrder(flavor); 9918 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) { 9919 memcpy((char *)&count, begin, sizeof(uint32_t)); 9920 begin += sizeof(uint32_t); 9921 } else { 9922 count = 0; 9923 begin = end; 9924 } 9925 if (isLittleEndian != sys::IsLittleEndianHost) 9926 sys::swapByteOrder(count); 9927 if (flavor == MachO::ARM_THREAD_STATE64) { 9928 outs() << " flavor ARM_THREAD_STATE64\n"; 9929 if (count == MachO::ARM_THREAD_STATE64_COUNT) 9930 outs() << " count ARM_THREAD_STATE64_COUNT\n"; 9931 else 9932 outs() << " count " << count 9933 << " (not ARM_THREAD_STATE64_COUNT)\n"; 9934 MachO::arm_thread_state64_t cpu64; 9935 left = end - begin; 9936 if (left >= sizeof(MachO::arm_thread_state64_t)) { 9937 memcpy(&cpu64, begin, sizeof(MachO::arm_thread_state64_t)); 9938 begin += sizeof(MachO::arm_thread_state64_t); 9939 } else { 9940 memset(&cpu64, '\0', sizeof(MachO::arm_thread_state64_t)); 9941 memcpy(&cpu64, begin, left); 9942 begin += left; 9943 } 9944 if (isLittleEndian != sys::IsLittleEndianHost) 9945 swapStruct(cpu64); 9946 Print_arm_thread_state64_t(cpu64); 9947 } else { 9948 outs() << " flavor " << flavor << " (unknown)\n"; 9949 outs() << " count " << count << "\n"; 9950 outs() << " state (unknown)\n"; 9951 begin += count * sizeof(uint32_t); 9952 } 9953 } 9954 } else { 9955 while (begin < end) { 9956 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) { 9957 memcpy((char *)&flavor, begin, sizeof(uint32_t)); 9958 begin += sizeof(uint32_t); 9959 } else { 9960 flavor = 0; 9961 begin = end; 9962 } 9963 if (isLittleEndian != sys::IsLittleEndianHost) 9964 sys::swapByteOrder(flavor); 9965 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) { 9966 memcpy((char *)&count, begin, sizeof(uint32_t)); 9967 begin += sizeof(uint32_t); 9968 } else { 9969 count = 0; 9970 begin = end; 9971 } 9972 if (isLittleEndian != sys::IsLittleEndianHost) 9973 sys::swapByteOrder(count); 9974 outs() << " flavor " << flavor << "\n"; 9975 outs() << " count " << count << "\n"; 9976 outs() << " state (Unknown cputype/cpusubtype)\n"; 9977 begin += count * sizeof(uint32_t); 9978 } 9979 } 9980 } 9981 9982 static void PrintDylibCommand(MachO::dylib_command dl, const char *Ptr) { 9983 if (dl.cmd == MachO::LC_ID_DYLIB) 9984 outs() << " cmd LC_ID_DYLIB\n"; 9985 else if (dl.cmd == MachO::LC_LOAD_DYLIB) 9986 outs() << " cmd LC_LOAD_DYLIB\n"; 9987 else if (dl.cmd == MachO::LC_LOAD_WEAK_DYLIB) 9988 outs() << " cmd LC_LOAD_WEAK_DYLIB\n"; 9989 else if (dl.cmd == MachO::LC_REEXPORT_DYLIB) 9990 outs() << " cmd LC_REEXPORT_DYLIB\n"; 9991 else if (dl.cmd == MachO::LC_LAZY_LOAD_DYLIB) 9992 outs() << " cmd LC_LAZY_LOAD_DYLIB\n"; 9993 else if (dl.cmd == MachO::LC_LOAD_UPWARD_DYLIB) 9994 outs() << " cmd LC_LOAD_UPWARD_DYLIB\n"; 9995 else 9996 outs() << " cmd " << dl.cmd << " (unknown)\n"; 9997 outs() << " cmdsize " << dl.cmdsize; 9998 if (dl.cmdsize < sizeof(struct MachO::dylib_command)) 9999 outs() << " Incorrect size\n"; 10000 else 10001 outs() << "\n"; 10002 if (dl.dylib.name < dl.cmdsize) { 10003 const char *P = (const char *)(Ptr) + dl.dylib.name; 10004 outs() << " name " << P << " (offset " << dl.dylib.name << ")\n"; 10005 } else { 10006 outs() << " name ?(bad offset " << dl.dylib.name << ")\n"; 10007 } 10008 outs() << " time stamp " << dl.dylib.timestamp << " "; 10009 time_t t = dl.dylib.timestamp; 10010 outs() << ctime(&t); 10011 outs() << " current version "; 10012 if (dl.dylib.current_version == 0xffffffff) 10013 outs() << "n/a\n"; 10014 else 10015 outs() << ((dl.dylib.current_version >> 16) & 0xffff) << "." 10016 << ((dl.dylib.current_version >> 8) & 0xff) << "." 10017 << (dl.dylib.current_version & 0xff) << "\n"; 10018 outs() << "compatibility version "; 10019 if (dl.dylib.compatibility_version == 0xffffffff) 10020 outs() << "n/a\n"; 10021 else 10022 outs() << ((dl.dylib.compatibility_version >> 16) & 0xffff) << "." 10023 << ((dl.dylib.compatibility_version >> 8) & 0xff) << "." 10024 << (dl.dylib.compatibility_version & 0xff) << "\n"; 10025 } 10026 10027 static void PrintLinkEditDataCommand(MachO::linkedit_data_command ld, 10028 uint32_t object_size) { 10029 if (ld.cmd == MachO::LC_CODE_SIGNATURE) 10030 outs() << " cmd LC_CODE_SIGNATURE\n"; 10031 else if (ld.cmd == MachO::LC_SEGMENT_SPLIT_INFO) 10032 outs() << " cmd LC_SEGMENT_SPLIT_INFO\n"; 10033 else if (ld.cmd == MachO::LC_FUNCTION_STARTS) 10034 outs() << " cmd LC_FUNCTION_STARTS\n"; 10035 else if (ld.cmd == MachO::LC_DATA_IN_CODE) 10036 outs() << " cmd LC_DATA_IN_CODE\n"; 10037 else if (ld.cmd == MachO::LC_DYLIB_CODE_SIGN_DRS) 10038 outs() << " cmd LC_DYLIB_CODE_SIGN_DRS\n"; 10039 else if (ld.cmd == MachO::LC_LINKER_OPTIMIZATION_HINT) 10040 outs() << " cmd LC_LINKER_OPTIMIZATION_HINT\n"; 10041 else 10042 outs() << " cmd " << ld.cmd << " (?)\n"; 10043 outs() << " cmdsize " << ld.cmdsize; 10044 if (ld.cmdsize != sizeof(struct MachO::linkedit_data_command)) 10045 outs() << " Incorrect size\n"; 10046 else 10047 outs() << "\n"; 10048 outs() << " dataoff " << ld.dataoff; 10049 if (ld.dataoff > object_size) 10050 outs() << " (past end of file)\n"; 10051 else 10052 outs() << "\n"; 10053 outs() << " datasize " << ld.datasize; 10054 uint64_t big_size = ld.dataoff; 10055 big_size += ld.datasize; 10056 if (big_size > object_size) 10057 outs() << " (past end of file)\n"; 10058 else 10059 outs() << "\n"; 10060 } 10061 10062 static void PrintLoadCommands(const MachOObjectFile *Obj, uint32_t filetype, 10063 uint32_t cputype, bool verbose) { 10064 StringRef Buf = Obj->getData(); 10065 unsigned Index = 0; 10066 for (const auto &Command : Obj->load_commands()) { 10067 outs() << "Load command " << Index++ << "\n"; 10068 if (Command.C.cmd == MachO::LC_SEGMENT) { 10069 MachO::segment_command SLC = Obj->getSegmentLoadCommand(Command); 10070 const char *sg_segname = SLC.segname; 10071 PrintSegmentCommand(SLC.cmd, SLC.cmdsize, SLC.segname, SLC.vmaddr, 10072 SLC.vmsize, SLC.fileoff, SLC.filesize, SLC.maxprot, 10073 SLC.initprot, SLC.nsects, SLC.flags, Buf.size(), 10074 verbose); 10075 for (unsigned j = 0; j < SLC.nsects; j++) { 10076 MachO::section S = Obj->getSection(Command, j); 10077 PrintSection(S.sectname, S.segname, S.addr, S.size, S.offset, S.align, 10078 S.reloff, S.nreloc, S.flags, S.reserved1, S.reserved2, 10079 SLC.cmd, sg_segname, filetype, Buf.size(), verbose); 10080 } 10081 } else if (Command.C.cmd == MachO::LC_SEGMENT_64) { 10082 MachO::segment_command_64 SLC_64 = Obj->getSegment64LoadCommand(Command); 10083 const char *sg_segname = SLC_64.segname; 10084 PrintSegmentCommand(SLC_64.cmd, SLC_64.cmdsize, SLC_64.segname, 10085 SLC_64.vmaddr, SLC_64.vmsize, SLC_64.fileoff, 10086 SLC_64.filesize, SLC_64.maxprot, SLC_64.initprot, 10087 SLC_64.nsects, SLC_64.flags, Buf.size(), verbose); 10088 for (unsigned j = 0; j < SLC_64.nsects; j++) { 10089 MachO::section_64 S_64 = Obj->getSection64(Command, j); 10090 PrintSection(S_64.sectname, S_64.segname, S_64.addr, S_64.size, 10091 S_64.offset, S_64.align, S_64.reloff, S_64.nreloc, 10092 S_64.flags, S_64.reserved1, S_64.reserved2, SLC_64.cmd, 10093 sg_segname, filetype, Buf.size(), verbose); 10094 } 10095 } else if (Command.C.cmd == MachO::LC_SYMTAB) { 10096 MachO::symtab_command Symtab = Obj->getSymtabLoadCommand(); 10097 PrintSymtabLoadCommand(Symtab, Obj->is64Bit(), Buf.size()); 10098 } else if (Command.C.cmd == MachO::LC_DYSYMTAB) { 10099 MachO::dysymtab_command Dysymtab = Obj->getDysymtabLoadCommand(); 10100 MachO::symtab_command Symtab = Obj->getSymtabLoadCommand(); 10101 PrintDysymtabLoadCommand(Dysymtab, Symtab.nsyms, Buf.size(), 10102 Obj->is64Bit()); 10103 } else if (Command.C.cmd == MachO::LC_DYLD_INFO || 10104 Command.C.cmd == MachO::LC_DYLD_INFO_ONLY) { 10105 MachO::dyld_info_command DyldInfo = Obj->getDyldInfoLoadCommand(Command); 10106 PrintDyldInfoLoadCommand(DyldInfo, Buf.size()); 10107 } else if (Command.C.cmd == MachO::LC_LOAD_DYLINKER || 10108 Command.C.cmd == MachO::LC_ID_DYLINKER || 10109 Command.C.cmd == MachO::LC_DYLD_ENVIRONMENT) { 10110 MachO::dylinker_command Dyld = Obj->getDylinkerCommand(Command); 10111 PrintDyldLoadCommand(Dyld, Command.Ptr); 10112 } else if (Command.C.cmd == MachO::LC_UUID) { 10113 MachO::uuid_command Uuid = Obj->getUuidCommand(Command); 10114 PrintUuidLoadCommand(Uuid); 10115 } else if (Command.C.cmd == MachO::LC_RPATH) { 10116 MachO::rpath_command Rpath = Obj->getRpathCommand(Command); 10117 PrintRpathLoadCommand(Rpath, Command.Ptr); 10118 } else if (Command.C.cmd == MachO::LC_VERSION_MIN_MACOSX || 10119 Command.C.cmd == MachO::LC_VERSION_MIN_IPHONEOS || 10120 Command.C.cmd == MachO::LC_VERSION_MIN_TVOS || 10121 Command.C.cmd == MachO::LC_VERSION_MIN_WATCHOS) { 10122 MachO::version_min_command Vd = Obj->getVersionMinLoadCommand(Command); 10123 PrintVersionMinLoadCommand(Vd); 10124 } else if (Command.C.cmd == MachO::LC_NOTE) { 10125 MachO::note_command Nt = Obj->getNoteLoadCommand(Command); 10126 PrintNoteLoadCommand(Nt); 10127 } else if (Command.C.cmd == MachO::LC_BUILD_VERSION) { 10128 MachO::build_version_command Bv = 10129 Obj->getBuildVersionLoadCommand(Command); 10130 PrintBuildVersionLoadCommand(Obj, Bv); 10131 } else if (Command.C.cmd == MachO::LC_SOURCE_VERSION) { 10132 MachO::source_version_command Sd = Obj->getSourceVersionCommand(Command); 10133 PrintSourceVersionCommand(Sd); 10134 } else if (Command.C.cmd == MachO::LC_MAIN) { 10135 MachO::entry_point_command Ep = Obj->getEntryPointCommand(Command); 10136 PrintEntryPointCommand(Ep); 10137 } else if (Command.C.cmd == MachO::LC_ENCRYPTION_INFO) { 10138 MachO::encryption_info_command Ei = 10139 Obj->getEncryptionInfoCommand(Command); 10140 PrintEncryptionInfoCommand(Ei, Buf.size()); 10141 } else if (Command.C.cmd == MachO::LC_ENCRYPTION_INFO_64) { 10142 MachO::encryption_info_command_64 Ei = 10143 Obj->getEncryptionInfoCommand64(Command); 10144 PrintEncryptionInfoCommand64(Ei, Buf.size()); 10145 } else if (Command.C.cmd == MachO::LC_LINKER_OPTION) { 10146 MachO::linker_option_command Lo = 10147 Obj->getLinkerOptionLoadCommand(Command); 10148 PrintLinkerOptionCommand(Lo, Command.Ptr); 10149 } else if (Command.C.cmd == MachO::LC_SUB_FRAMEWORK) { 10150 MachO::sub_framework_command Sf = Obj->getSubFrameworkCommand(Command); 10151 PrintSubFrameworkCommand(Sf, Command.Ptr); 10152 } else if (Command.C.cmd == MachO::LC_SUB_UMBRELLA) { 10153 MachO::sub_umbrella_command Sf = Obj->getSubUmbrellaCommand(Command); 10154 PrintSubUmbrellaCommand(Sf, Command.Ptr); 10155 } else if (Command.C.cmd == MachO::LC_SUB_LIBRARY) { 10156 MachO::sub_library_command Sl = Obj->getSubLibraryCommand(Command); 10157 PrintSubLibraryCommand(Sl, Command.Ptr); 10158 } else if (Command.C.cmd == MachO::LC_SUB_CLIENT) { 10159 MachO::sub_client_command Sc = Obj->getSubClientCommand(Command); 10160 PrintSubClientCommand(Sc, Command.Ptr); 10161 } else if (Command.C.cmd == MachO::LC_ROUTINES) { 10162 MachO::routines_command Rc = Obj->getRoutinesCommand(Command); 10163 PrintRoutinesCommand(Rc); 10164 } else if (Command.C.cmd == MachO::LC_ROUTINES_64) { 10165 MachO::routines_command_64 Rc = Obj->getRoutinesCommand64(Command); 10166 PrintRoutinesCommand64(Rc); 10167 } else if (Command.C.cmd == MachO::LC_THREAD || 10168 Command.C.cmd == MachO::LC_UNIXTHREAD) { 10169 MachO::thread_command Tc = Obj->getThreadCommand(Command); 10170 PrintThreadCommand(Tc, Command.Ptr, Obj->isLittleEndian(), cputype); 10171 } else if (Command.C.cmd == MachO::LC_LOAD_DYLIB || 10172 Command.C.cmd == MachO::LC_ID_DYLIB || 10173 Command.C.cmd == MachO::LC_LOAD_WEAK_DYLIB || 10174 Command.C.cmd == MachO::LC_REEXPORT_DYLIB || 10175 Command.C.cmd == MachO::LC_LAZY_LOAD_DYLIB || 10176 Command.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB) { 10177 MachO::dylib_command Dl = Obj->getDylibIDLoadCommand(Command); 10178 PrintDylibCommand(Dl, Command.Ptr); 10179 } else if (Command.C.cmd == MachO::LC_CODE_SIGNATURE || 10180 Command.C.cmd == MachO::LC_SEGMENT_SPLIT_INFO || 10181 Command.C.cmd == MachO::LC_FUNCTION_STARTS || 10182 Command.C.cmd == MachO::LC_DATA_IN_CODE || 10183 Command.C.cmd == MachO::LC_DYLIB_CODE_SIGN_DRS || 10184 Command.C.cmd == MachO::LC_LINKER_OPTIMIZATION_HINT) { 10185 MachO::linkedit_data_command Ld = 10186 Obj->getLinkeditDataLoadCommand(Command); 10187 PrintLinkEditDataCommand(Ld, Buf.size()); 10188 } else { 10189 outs() << " cmd ?(" << format("0x%08" PRIx32, Command.C.cmd) 10190 << ")\n"; 10191 outs() << " cmdsize " << Command.C.cmdsize << "\n"; 10192 // TODO: get and print the raw bytes of the load command. 10193 } 10194 // TODO: print all the other kinds of load commands. 10195 } 10196 } 10197 10198 static void PrintMachHeader(const MachOObjectFile *Obj, bool verbose) { 10199 if (Obj->is64Bit()) { 10200 MachO::mach_header_64 H_64; 10201 H_64 = Obj->getHeader64(); 10202 PrintMachHeader(H_64.magic, H_64.cputype, H_64.cpusubtype, H_64.filetype, 10203 H_64.ncmds, H_64.sizeofcmds, H_64.flags, verbose); 10204 } else { 10205 MachO::mach_header H; 10206 H = Obj->getHeader(); 10207 PrintMachHeader(H.magic, H.cputype, H.cpusubtype, H.filetype, H.ncmds, 10208 H.sizeofcmds, H.flags, verbose); 10209 } 10210 } 10211 10212 void objdump::printMachOFileHeader(const object::ObjectFile *Obj) { 10213 const MachOObjectFile *file = dyn_cast<const MachOObjectFile>(Obj); 10214 PrintMachHeader(file, !NonVerbose); 10215 } 10216 10217 void objdump::printMachOLoadCommands(const object::ObjectFile *Obj) { 10218 const MachOObjectFile *file = dyn_cast<const MachOObjectFile>(Obj); 10219 uint32_t filetype = 0; 10220 uint32_t cputype = 0; 10221 if (file->is64Bit()) { 10222 MachO::mach_header_64 H_64; 10223 H_64 = file->getHeader64(); 10224 filetype = H_64.filetype; 10225 cputype = H_64.cputype; 10226 } else { 10227 MachO::mach_header H; 10228 H = file->getHeader(); 10229 filetype = H.filetype; 10230 cputype = H.cputype; 10231 } 10232 PrintLoadCommands(file, filetype, cputype, !NonVerbose); 10233 } 10234 10235 //===----------------------------------------------------------------------===// 10236 // export trie dumping 10237 //===----------------------------------------------------------------------===// 10238 10239 static void printMachOExportsTrie(const object::MachOObjectFile *Obj) { 10240 uint64_t BaseSegmentAddress = 0; 10241 for (const auto &Command : Obj->load_commands()) { 10242 if (Command.C.cmd == MachO::LC_SEGMENT) { 10243 MachO::segment_command Seg = Obj->getSegmentLoadCommand(Command); 10244 if (Seg.fileoff == 0 && Seg.filesize != 0) { 10245 BaseSegmentAddress = Seg.vmaddr; 10246 break; 10247 } 10248 } else if (Command.C.cmd == MachO::LC_SEGMENT_64) { 10249 MachO::segment_command_64 Seg = Obj->getSegment64LoadCommand(Command); 10250 if (Seg.fileoff == 0 && Seg.filesize != 0) { 10251 BaseSegmentAddress = Seg.vmaddr; 10252 break; 10253 } 10254 } 10255 } 10256 Error Err = Error::success(); 10257 for (const object::ExportEntry &Entry : Obj->exports(Err)) { 10258 uint64_t Flags = Entry.flags(); 10259 bool ReExport = (Flags & MachO::EXPORT_SYMBOL_FLAGS_REEXPORT); 10260 bool WeakDef = (Flags & MachO::EXPORT_SYMBOL_FLAGS_WEAK_DEFINITION); 10261 bool ThreadLocal = ((Flags & MachO::EXPORT_SYMBOL_FLAGS_KIND_MASK) == 10262 MachO::EXPORT_SYMBOL_FLAGS_KIND_THREAD_LOCAL); 10263 bool Abs = ((Flags & MachO::EXPORT_SYMBOL_FLAGS_KIND_MASK) == 10264 MachO::EXPORT_SYMBOL_FLAGS_KIND_ABSOLUTE); 10265 bool Resolver = (Flags & MachO::EXPORT_SYMBOL_FLAGS_STUB_AND_RESOLVER); 10266 if (ReExport) 10267 outs() << "[re-export] "; 10268 else 10269 outs() << format("0x%08llX ", 10270 Entry.address() + BaseSegmentAddress); 10271 outs() << Entry.name(); 10272 if (WeakDef || ThreadLocal || Resolver || Abs) { 10273 ListSeparator LS; 10274 outs() << " ["; 10275 if (WeakDef) 10276 outs() << LS << "weak_def"; 10277 if (ThreadLocal) 10278 outs() << LS << "per-thread"; 10279 if (Abs) 10280 outs() << LS << "absolute"; 10281 if (Resolver) 10282 outs() << LS << format("resolver=0x%08llX", Entry.other()); 10283 outs() << "]"; 10284 } 10285 if (ReExport) { 10286 StringRef DylibName = "unknown"; 10287 int Ordinal = Entry.other() - 1; 10288 Obj->getLibraryShortNameByIndex(Ordinal, DylibName); 10289 if (Entry.otherName().empty()) 10290 outs() << " (from " << DylibName << ")"; 10291 else 10292 outs() << " (" << Entry.otherName() << " from " << DylibName << ")"; 10293 } 10294 outs() << "\n"; 10295 } 10296 if (Err) 10297 reportError(std::move(Err), Obj->getFileName()); 10298 } 10299 10300 //===----------------------------------------------------------------------===// 10301 // rebase table dumping 10302 //===----------------------------------------------------------------------===// 10303 10304 static void printMachORebaseTable(object::MachOObjectFile *Obj) { 10305 outs() << "segment section address type\n"; 10306 Error Err = Error::success(); 10307 for (const object::MachORebaseEntry &Entry : Obj->rebaseTable(Err)) { 10308 StringRef SegmentName = Entry.segmentName(); 10309 StringRef SectionName = Entry.sectionName(); 10310 uint64_t Address = Entry.address(); 10311 10312 // Table lines look like: __DATA __nl_symbol_ptr 0x0000F00C pointer 10313 outs() << format("%-8s %-18s 0x%08" PRIX64 " %s\n", 10314 SegmentName.str().c_str(), SectionName.str().c_str(), 10315 Address, Entry.typeName().str().c_str()); 10316 } 10317 if (Err) 10318 reportError(std::move(Err), Obj->getFileName()); 10319 } 10320 10321 static StringRef ordinalName(const object::MachOObjectFile *Obj, int Ordinal) { 10322 StringRef DylibName; 10323 switch (Ordinal) { 10324 case MachO::BIND_SPECIAL_DYLIB_SELF: 10325 return "this-image"; 10326 case MachO::BIND_SPECIAL_DYLIB_MAIN_EXECUTABLE: 10327 return "main-executable"; 10328 case MachO::BIND_SPECIAL_DYLIB_FLAT_LOOKUP: 10329 return "flat-namespace"; 10330 default: 10331 if (Ordinal > 0) { 10332 std::error_code EC = 10333 Obj->getLibraryShortNameByIndex(Ordinal - 1, DylibName); 10334 if (EC) 10335 return "<<bad library ordinal>>"; 10336 return DylibName; 10337 } 10338 } 10339 return "<<unknown special ordinal>>"; 10340 } 10341 10342 //===----------------------------------------------------------------------===// 10343 // bind table dumping 10344 //===----------------------------------------------------------------------===// 10345 10346 static void printMachOBindTable(object::MachOObjectFile *Obj) { 10347 // Build table of sections so names can used in final output. 10348 outs() << "segment section address type " 10349 "addend dylib symbol\n"; 10350 Error Err = Error::success(); 10351 for (const object::MachOBindEntry &Entry : Obj->bindTable(Err)) { 10352 StringRef SegmentName = Entry.segmentName(); 10353 StringRef SectionName = Entry.sectionName(); 10354 uint64_t Address = Entry.address(); 10355 10356 // Table lines look like: 10357 // __DATA __got 0x00012010 pointer 0 libSystem ___stack_chk_guard 10358 StringRef Attr; 10359 if (Entry.flags() & MachO::BIND_SYMBOL_FLAGS_WEAK_IMPORT) 10360 Attr = " (weak_import)"; 10361 outs() << left_justify(SegmentName, 8) << " " 10362 << left_justify(SectionName, 18) << " " 10363 << format_hex(Address, 10, true) << " " 10364 << left_justify(Entry.typeName(), 8) << " " 10365 << format_decimal(Entry.addend(), 8) << " " 10366 << left_justify(ordinalName(Obj, Entry.ordinal()), 16) << " " 10367 << Entry.symbolName() << Attr << "\n"; 10368 } 10369 if (Err) 10370 reportError(std::move(Err), Obj->getFileName()); 10371 } 10372 10373 //===----------------------------------------------------------------------===// 10374 // lazy bind table dumping 10375 //===----------------------------------------------------------------------===// 10376 10377 static void printMachOLazyBindTable(object::MachOObjectFile *Obj) { 10378 outs() << "segment section address " 10379 "dylib symbol\n"; 10380 Error Err = Error::success(); 10381 for (const object::MachOBindEntry &Entry : Obj->lazyBindTable(Err)) { 10382 StringRef SegmentName = Entry.segmentName(); 10383 StringRef SectionName = Entry.sectionName(); 10384 uint64_t Address = Entry.address(); 10385 10386 // Table lines look like: 10387 // __DATA __got 0x00012010 libSystem ___stack_chk_guard 10388 outs() << left_justify(SegmentName, 8) << " " 10389 << left_justify(SectionName, 18) << " " 10390 << format_hex(Address, 10, true) << " " 10391 << left_justify(ordinalName(Obj, Entry.ordinal()), 16) << " " 10392 << Entry.symbolName() << "\n"; 10393 } 10394 if (Err) 10395 reportError(std::move(Err), Obj->getFileName()); 10396 } 10397 10398 //===----------------------------------------------------------------------===// 10399 // weak bind table dumping 10400 //===----------------------------------------------------------------------===// 10401 10402 static void printMachOWeakBindTable(object::MachOObjectFile *Obj) { 10403 outs() << "segment section address " 10404 "type addend symbol\n"; 10405 Error Err = Error::success(); 10406 for (const object::MachOBindEntry &Entry : Obj->weakBindTable(Err)) { 10407 // Strong symbols don't have a location to update. 10408 if (Entry.flags() & MachO::BIND_SYMBOL_FLAGS_NON_WEAK_DEFINITION) { 10409 outs() << " strong " 10410 << Entry.symbolName() << "\n"; 10411 continue; 10412 } 10413 StringRef SegmentName = Entry.segmentName(); 10414 StringRef SectionName = Entry.sectionName(); 10415 uint64_t Address = Entry.address(); 10416 10417 // Table lines look like: 10418 // __DATA __data 0x00001000 pointer 0 _foo 10419 outs() << left_justify(SegmentName, 8) << " " 10420 << left_justify(SectionName, 18) << " " 10421 << format_hex(Address, 10, true) << " " 10422 << left_justify(Entry.typeName(), 8) << " " 10423 << format_decimal(Entry.addend(), 8) << " " << Entry.symbolName() 10424 << "\n"; 10425 } 10426 if (Err) 10427 reportError(std::move(Err), Obj->getFileName()); 10428 } 10429 10430 // get_dyld_bind_info_symbolname() is used for disassembly and passed an 10431 // address, ReferenceValue, in the Mach-O file and looks in the dyld bind 10432 // information for that address. If the address is found its binding symbol 10433 // name is returned. If not nullptr is returned. 10434 static const char *get_dyld_bind_info_symbolname(uint64_t ReferenceValue, 10435 struct DisassembleInfo *info) { 10436 if (info->bindtable == nullptr) { 10437 info->bindtable = std::make_unique<SymbolAddressMap>(); 10438 Error Err = Error::success(); 10439 for (const object::MachOBindEntry &Entry : info->O->bindTable(Err)) { 10440 uint64_t Address = Entry.address(); 10441 StringRef name = Entry.symbolName(); 10442 if (!name.empty()) 10443 (*info->bindtable)[Address] = name; 10444 } 10445 if (Err) 10446 reportError(std::move(Err), info->O->getFileName()); 10447 } 10448 auto name = info->bindtable->lookup(ReferenceValue); 10449 return !name.empty() ? name.data() : nullptr; 10450 } 10451 10452 void objdump::printLazyBindTable(ObjectFile *o) { 10453 outs() << "Lazy bind table:\n"; 10454 if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o)) 10455 printMachOLazyBindTable(MachO); 10456 else 10457 WithColor::error() 10458 << "This operation is only currently supported " 10459 "for Mach-O executable files.\n"; 10460 } 10461 10462 void objdump::printWeakBindTable(ObjectFile *o) { 10463 outs() << "Weak bind table:\n"; 10464 if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o)) 10465 printMachOWeakBindTable(MachO); 10466 else 10467 WithColor::error() 10468 << "This operation is only currently supported " 10469 "for Mach-O executable files.\n"; 10470 } 10471 10472 void objdump::printExportsTrie(const ObjectFile *o) { 10473 outs() << "Exports trie:\n"; 10474 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o)) 10475 printMachOExportsTrie(MachO); 10476 else 10477 WithColor::error() 10478 << "This operation is only currently supported " 10479 "for Mach-O executable files.\n"; 10480 } 10481 10482 void objdump::printRebaseTable(ObjectFile *o) { 10483 outs() << "Rebase table:\n"; 10484 if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o)) 10485 printMachORebaseTable(MachO); 10486 else 10487 WithColor::error() 10488 << "This operation is only currently supported " 10489 "for Mach-O executable files.\n"; 10490 } 10491 10492 void objdump::printBindTable(ObjectFile *o) { 10493 outs() << "Bind table:\n"; 10494 if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o)) 10495 printMachOBindTable(MachO); 10496 else 10497 WithColor::error() 10498 << "This operation is only currently supported " 10499 "for Mach-O executable files.\n"; 10500 } 10501