1 //===- MachO.h - MachO object file implementation ---------------*- C++ -*-===// 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 declares the MachOObjectFile class, which implement the ObjectFile 10 // interface for MachO files. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #ifndef LLVM_OBJECT_MACHO_H 15 #define LLVM_OBJECT_MACHO_H 16 17 #include "llvm/ADT/ArrayRef.h" 18 #include "llvm/ADT/SmallString.h" 19 #include "llvm/ADT/SmallVector.h" 20 #include "llvm/ADT/StringExtras.h" 21 #include "llvm/ADT/StringRef.h" 22 #include "llvm/ADT/Triple.h" 23 #include "llvm/ADT/iterator_range.h" 24 #include "llvm/BinaryFormat/MachO.h" 25 #include "llvm/BinaryFormat/Swift.h" 26 #include "llvm/MC/SubtargetFeature.h" 27 #include "llvm/Object/Binary.h" 28 #include "llvm/Object/ObjectFile.h" 29 #include "llvm/Object/SymbolicFile.h" 30 #include "llvm/Support/Error.h" 31 #include "llvm/Support/Format.h" 32 #include "llvm/Support/MemoryBuffer.h" 33 #include "llvm/Support/raw_ostream.h" 34 #include <cstdint> 35 #include <memory> 36 #include <string> 37 #include <system_error> 38 39 namespace llvm { 40 namespace object { 41 42 /// DiceRef - This is a value type class that represents a single 43 /// data in code entry in the table in a Mach-O object file. 44 class DiceRef { 45 DataRefImpl DicePimpl; 46 const ObjectFile *OwningObject = nullptr; 47 48 public: 49 DiceRef() = default; 50 DiceRef(DataRefImpl DiceP, const ObjectFile *Owner); 51 52 bool operator==(const DiceRef &Other) const; 53 bool operator<(const DiceRef &Other) const; 54 55 void moveNext(); 56 57 std::error_code getOffset(uint32_t &Result) const; 58 std::error_code getLength(uint16_t &Result) const; 59 std::error_code getKind(uint16_t &Result) const; 60 61 DataRefImpl getRawDataRefImpl() const; 62 const ObjectFile *getObjectFile() const; 63 }; 64 using dice_iterator = content_iterator<DiceRef>; 65 66 /// ExportEntry encapsulates the current-state-of-the-walk used when doing a 67 /// non-recursive walk of the trie data structure. This allows you to iterate 68 /// across all exported symbols using: 69 /// Error Err = Error::success(); 70 /// for (const llvm::object::ExportEntry &AnExport : Obj->exports(&Err)) { 71 /// } 72 /// if (Err) { report error ... 73 class ExportEntry { 74 public: 75 ExportEntry(Error *Err, const MachOObjectFile *O, ArrayRef<uint8_t> Trie); 76 77 StringRef name() const; 78 uint64_t flags() const; 79 uint64_t address() const; 80 uint64_t other() const; 81 StringRef otherName() const; 82 uint32_t nodeOffset() const; 83 84 bool operator==(const ExportEntry &) const; 85 86 void moveNext(); 87 88 private: 89 friend class MachOObjectFile; 90 91 void moveToFirst(); 92 void moveToEnd(); 93 uint64_t readULEB128(const uint8_t *&p, const char **error); 94 void pushDownUntilBottom(); 95 void pushNode(uint64_t Offset); 96 97 // Represents a node in the mach-o exports trie. 98 struct NodeState { 99 NodeState(const uint8_t *Ptr); 100 101 const uint8_t *Start; 102 const uint8_t *Current; 103 uint64_t Flags = 0; 104 uint64_t Address = 0; 105 uint64_t Other = 0; 106 const char *ImportName = nullptr; 107 unsigned ChildCount = 0; 108 unsigned NextChildIndex = 0; 109 unsigned ParentStringLength = 0; 110 bool IsExportNode = false; 111 }; 112 using NodeList = SmallVector<NodeState, 16>; 113 using node_iterator = NodeList::const_iterator; 114 115 Error *E; 116 const MachOObjectFile *O; 117 ArrayRef<uint8_t> Trie; 118 SmallString<256> CumulativeString; 119 NodeList Stack; 120 bool Done = false; 121 122 iterator_range<node_iterator> nodes() const { 123 return make_range(Stack.begin(), Stack.end()); 124 } 125 }; 126 using export_iterator = content_iterator<ExportEntry>; 127 128 // Segment info so SegIndex/SegOffset pairs in a Mach-O Bind or Rebase entry 129 // can be checked and translated. Only the SegIndex/SegOffset pairs from 130 // checked entries are to be used with the segmentName(), sectionName() and 131 // address() methods below. 132 class BindRebaseSegInfo { 133 public: 134 BindRebaseSegInfo(const MachOObjectFile *Obj); 135 136 // Used to check a Mach-O Bind or Rebase entry for errors when iterating. 137 const char* checkSegAndOffsets(int32_t SegIndex, uint64_t SegOffset, 138 uint8_t PointerSize, uint32_t Count=1, 139 uint32_t Skip=0); 140 // Used with valid SegIndex/SegOffset values from checked entries. 141 StringRef segmentName(int32_t SegIndex); 142 StringRef sectionName(int32_t SegIndex, uint64_t SegOffset); 143 uint64_t address(uint32_t SegIndex, uint64_t SegOffset); 144 145 private: 146 struct SectionInfo { 147 uint64_t Address; 148 uint64_t Size; 149 StringRef SectionName; 150 StringRef SegmentName; 151 uint64_t OffsetInSegment; 152 uint64_t SegmentStartAddress; 153 int32_t SegmentIndex; 154 }; 155 const SectionInfo &findSection(int32_t SegIndex, uint64_t SegOffset); 156 157 SmallVector<SectionInfo, 32> Sections; 158 int32_t MaxSegIndex; 159 }; 160 161 /// MachORebaseEntry encapsulates the current state in the decompression of 162 /// rebasing opcodes. This allows you to iterate through the compressed table of 163 /// rebasing using: 164 /// Error Err = Error::success(); 165 /// for (const llvm::object::MachORebaseEntry &Entry : Obj->rebaseTable(&Err)) { 166 /// } 167 /// if (Err) { report error ... 168 class MachORebaseEntry { 169 public: 170 MachORebaseEntry(Error *Err, const MachOObjectFile *O, 171 ArrayRef<uint8_t> opcodes, bool is64Bit); 172 173 int32_t segmentIndex() const; 174 uint64_t segmentOffset() const; 175 StringRef typeName() const; 176 StringRef segmentName() const; 177 StringRef sectionName() const; 178 uint64_t address() const; 179 180 bool operator==(const MachORebaseEntry &) const; 181 182 void moveNext(); 183 184 private: 185 friend class MachOObjectFile; 186 187 void moveToFirst(); 188 void moveToEnd(); 189 uint64_t readULEB128(const char **error); 190 191 Error *E; 192 const MachOObjectFile *O; 193 ArrayRef<uint8_t> Opcodes; 194 const uint8_t *Ptr; 195 uint64_t SegmentOffset = 0; 196 int32_t SegmentIndex = -1; 197 uint64_t RemainingLoopCount = 0; 198 uint64_t AdvanceAmount = 0; 199 uint8_t RebaseType = 0; 200 uint8_t PointerSize; 201 bool Done = false; 202 }; 203 using rebase_iterator = content_iterator<MachORebaseEntry>; 204 205 /// MachOBindEntry encapsulates the current state in the decompression of 206 /// binding opcodes. This allows you to iterate through the compressed table of 207 /// bindings using: 208 /// Error Err = Error::success(); 209 /// for (const llvm::object::MachOBindEntry &Entry : Obj->bindTable(&Err)) { 210 /// } 211 /// if (Err) { report error ... 212 class MachOBindEntry { 213 public: 214 enum class Kind { Regular, Lazy, Weak }; 215 216 MachOBindEntry(Error *Err, const MachOObjectFile *O, 217 ArrayRef<uint8_t> Opcodes, bool is64Bit, MachOBindEntry::Kind); 218 219 int32_t segmentIndex() const; 220 uint64_t segmentOffset() const; 221 StringRef typeName() const; 222 StringRef symbolName() const; 223 uint32_t flags() const; 224 int64_t addend() const; 225 int ordinal() const; 226 227 StringRef segmentName() const; 228 StringRef sectionName() const; 229 uint64_t address() const; 230 231 bool operator==(const MachOBindEntry &) const; 232 233 void moveNext(); 234 235 private: 236 friend class MachOObjectFile; 237 238 void moveToFirst(); 239 void moveToEnd(); 240 uint64_t readULEB128(const char **error); 241 int64_t readSLEB128(const char **error); 242 243 Error *E; 244 const MachOObjectFile *O; 245 ArrayRef<uint8_t> Opcodes; 246 const uint8_t *Ptr; 247 uint64_t SegmentOffset = 0; 248 int32_t SegmentIndex = -1; 249 StringRef SymbolName; 250 bool LibraryOrdinalSet = false; 251 int Ordinal = 0; 252 uint32_t Flags = 0; 253 int64_t Addend = 0; 254 uint64_t RemainingLoopCount = 0; 255 uint64_t AdvanceAmount = 0; 256 uint8_t BindType = 0; 257 uint8_t PointerSize; 258 Kind TableKind; 259 bool Done = false; 260 }; 261 using bind_iterator = content_iterator<MachOBindEntry>; 262 263 class MachOObjectFile : public ObjectFile { 264 public: 265 struct LoadCommandInfo { 266 const char *Ptr; // Where in memory the load command is. 267 MachO::load_command C; // The command itself. 268 }; 269 using LoadCommandList = SmallVector<LoadCommandInfo, 4>; 270 using load_command_iterator = LoadCommandList::const_iterator; 271 272 static Expected<std::unique_ptr<MachOObjectFile>> 273 create(MemoryBufferRef Object, bool IsLittleEndian, bool Is64Bits, 274 uint32_t UniversalCputype = 0, uint32_t UniversalIndex = 0); 275 276 void moveSymbolNext(DataRefImpl &Symb) const override; 277 278 uint64_t getNValue(DataRefImpl Sym) const; 279 Expected<StringRef> getSymbolName(DataRefImpl Symb) const override; 280 281 // MachO specific. 282 Error checkSymbolTable() const; 283 284 std::error_code getIndirectName(DataRefImpl Symb, StringRef &Res) const; 285 unsigned getSectionType(SectionRef Sec) const; 286 287 Expected<uint64_t> getSymbolAddress(DataRefImpl Symb) const override; 288 uint32_t getSymbolAlignment(DataRefImpl Symb) const override; 289 uint64_t getCommonSymbolSizeImpl(DataRefImpl Symb) const override; 290 Expected<SymbolRef::Type> getSymbolType(DataRefImpl Symb) const override; 291 Expected<uint32_t> getSymbolFlags(DataRefImpl Symb) const override; 292 Expected<section_iterator> getSymbolSection(DataRefImpl Symb) const override; 293 unsigned getSymbolSectionID(SymbolRef Symb) const; 294 unsigned getSectionID(SectionRef Sec) const; 295 296 void moveSectionNext(DataRefImpl &Sec) const override; 297 Expected<StringRef> getSectionName(DataRefImpl Sec) const override; 298 uint64_t getSectionAddress(DataRefImpl Sec) const override; 299 uint64_t getSectionIndex(DataRefImpl Sec) const override; 300 uint64_t getSectionSize(DataRefImpl Sec) const override; 301 ArrayRef<uint8_t> getSectionContents(uint32_t Offset, uint64_t Size) const; 302 Expected<ArrayRef<uint8_t>> 303 getSectionContents(DataRefImpl Sec) const override; 304 uint64_t getSectionAlignment(DataRefImpl Sec) const override; 305 Expected<SectionRef> getSection(unsigned SectionIndex) const; 306 Expected<SectionRef> getSection(StringRef SectionName) const; 307 bool isSectionCompressed(DataRefImpl Sec) const override; 308 bool isSectionText(DataRefImpl Sec) const override; 309 bool isSectionData(DataRefImpl Sec) const override; 310 bool isSectionBSS(DataRefImpl Sec) const override; 311 bool isSectionVirtual(DataRefImpl Sec) const override; 312 bool isSectionBitcode(DataRefImpl Sec) const override; 313 bool isDebugSection(DataRefImpl Sec) const override; 314 315 /// Return the raw contents of an entire segment. 316 ArrayRef<uint8_t> getSegmentContents(StringRef SegmentName) const; 317 318 /// When dsymutil generates the companion file, it strips all unnecessary 319 /// sections (e.g. everything in the _TEXT segment) by omitting their body 320 /// and setting the offset in their corresponding load command to zero. 321 /// 322 /// While the load command itself is valid, reading the section corresponds 323 /// to reading the number of bytes specified in the load command, starting 324 /// from offset 0 (i.e. the Mach-O header at the beginning of the file). 325 bool isSectionStripped(DataRefImpl Sec) const override; 326 327 relocation_iterator section_rel_begin(DataRefImpl Sec) const override; 328 relocation_iterator section_rel_end(DataRefImpl Sec) const override; 329 330 relocation_iterator extrel_begin() const; 331 relocation_iterator extrel_end() const; 332 iterator_range<relocation_iterator> external_relocations() const { 333 return make_range(extrel_begin(), extrel_end()); 334 } 335 336 relocation_iterator locrel_begin() const; 337 relocation_iterator locrel_end() const; 338 339 void moveRelocationNext(DataRefImpl &Rel) const override; 340 uint64_t getRelocationOffset(DataRefImpl Rel) const override; 341 symbol_iterator getRelocationSymbol(DataRefImpl Rel) const override; 342 section_iterator getRelocationSection(DataRefImpl Rel) const; 343 uint64_t getRelocationType(DataRefImpl Rel) const override; 344 void getRelocationTypeName(DataRefImpl Rel, 345 SmallVectorImpl<char> &Result) const override; 346 uint8_t getRelocationLength(DataRefImpl Rel) const; 347 348 // MachO specific. 349 std::error_code getLibraryShortNameByIndex(unsigned Index, StringRef &) const; 350 uint32_t getLibraryCount() const; 351 352 section_iterator getRelocationRelocatedSection(relocation_iterator Rel) const; 353 354 // TODO: Would be useful to have an iterator based version 355 // of the load command interface too. 356 357 basic_symbol_iterator symbol_begin() const override; 358 basic_symbol_iterator symbol_end() const override; 359 360 // MachO specific. 361 symbol_iterator getSymbolByIndex(unsigned Index) const; 362 uint64_t getSymbolIndex(DataRefImpl Symb) const; 363 364 section_iterator section_begin() const override; 365 section_iterator section_end() const override; 366 367 uint8_t getBytesInAddress() const override; 368 369 StringRef getFileFormatName() const override; 370 Triple::ArchType getArch() const override; 371 SubtargetFeatures getFeatures() const override { return SubtargetFeatures(); } 372 Triple getArchTriple(const char **McpuDefault = nullptr) const; 373 374 relocation_iterator section_rel_begin(unsigned Index) const; 375 relocation_iterator section_rel_end(unsigned Index) const; 376 377 dice_iterator begin_dices() const; 378 dice_iterator end_dices() const; 379 380 load_command_iterator begin_load_commands() const; 381 load_command_iterator end_load_commands() const; 382 iterator_range<load_command_iterator> load_commands() const; 383 384 /// For use iterating over all exported symbols. 385 iterator_range<export_iterator> exports(Error &Err) const; 386 387 /// For use examining a trie not in a MachOObjectFile. 388 static iterator_range<export_iterator> exports(Error &Err, 389 ArrayRef<uint8_t> Trie, 390 const MachOObjectFile *O = 391 nullptr); 392 393 /// For use iterating over all rebase table entries. 394 iterator_range<rebase_iterator> rebaseTable(Error &Err); 395 396 /// For use examining rebase opcodes in a MachOObjectFile. 397 static iterator_range<rebase_iterator> rebaseTable(Error &Err, 398 MachOObjectFile *O, 399 ArrayRef<uint8_t> Opcodes, 400 bool is64); 401 402 /// For use iterating over all bind table entries. 403 iterator_range<bind_iterator> bindTable(Error &Err); 404 405 /// For use iterating over all lazy bind table entries. 406 iterator_range<bind_iterator> lazyBindTable(Error &Err); 407 408 /// For use iterating over all weak bind table entries. 409 iterator_range<bind_iterator> weakBindTable(Error &Err); 410 411 /// For use examining bind opcodes in a MachOObjectFile. 412 static iterator_range<bind_iterator> bindTable(Error &Err, 413 MachOObjectFile *O, 414 ArrayRef<uint8_t> Opcodes, 415 bool is64, 416 MachOBindEntry::Kind); 417 418 // Given a SegIndex, SegOffset, and PointerSize, verify a valid section exists 419 // that fully contains a pointer at that location. Multiple fixups in a bind 420 // (such as with the BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB opcode) can 421 // be tested via the Count and Skip parameters. 422 // 423 // This is used by MachOBindEntry::moveNext() to validate a MachOBindEntry. 424 const char *BindEntryCheckSegAndOffsets(int32_t SegIndex, uint64_t SegOffset, 425 uint8_t PointerSize, uint32_t Count=1, 426 uint32_t Skip=0) const { 427 return BindRebaseSectionTable->checkSegAndOffsets(SegIndex, SegOffset, 428 PointerSize, Count, Skip); 429 } 430 431 // Given a SegIndex, SegOffset, and PointerSize, verify a valid section exists 432 // that fully contains a pointer at that location. Multiple fixups in a rebase 433 // (such as with the REBASE_OPCODE_DO_*_TIMES* opcodes) can be tested via the 434 // Count and Skip parameters. 435 // 436 // This is used by MachORebaseEntry::moveNext() to validate a MachORebaseEntry 437 const char *RebaseEntryCheckSegAndOffsets(int32_t SegIndex, 438 uint64_t SegOffset, 439 uint8_t PointerSize, 440 uint32_t Count=1, 441 uint32_t Skip=0) const { 442 return BindRebaseSectionTable->checkSegAndOffsets(SegIndex, SegOffset, 443 PointerSize, Count, Skip); 444 } 445 446 /// For use with the SegIndex of a checked Mach-O Bind or Rebase entry to 447 /// get the segment name. 448 StringRef BindRebaseSegmentName(int32_t SegIndex) const { 449 return BindRebaseSectionTable->segmentName(SegIndex); 450 } 451 452 /// For use with a SegIndex,SegOffset pair from a checked Mach-O Bind or 453 /// Rebase entry to get the section name. 454 StringRef BindRebaseSectionName(uint32_t SegIndex, uint64_t SegOffset) const { 455 return BindRebaseSectionTable->sectionName(SegIndex, SegOffset); 456 } 457 458 /// For use with a SegIndex,SegOffset pair from a checked Mach-O Bind or 459 /// Rebase entry to get the address. 460 uint64_t BindRebaseAddress(uint32_t SegIndex, uint64_t SegOffset) const { 461 return BindRebaseSectionTable->address(SegIndex, SegOffset); 462 } 463 464 // In a MachO file, sections have a segment name. This is used in the .o 465 // files. They have a single segment, but this field specifies which segment 466 // a section should be put in the final object. 467 StringRef getSectionFinalSegmentName(DataRefImpl Sec) const; 468 469 // Names are stored as 16 bytes. These returns the raw 16 bytes without 470 // interpreting them as a C string. 471 ArrayRef<char> getSectionRawName(DataRefImpl Sec) const; 472 ArrayRef<char> getSectionRawFinalSegmentName(DataRefImpl Sec) const; 473 474 // MachO specific Info about relocations. 475 bool isRelocationScattered(const MachO::any_relocation_info &RE) const; 476 unsigned getPlainRelocationSymbolNum( 477 const MachO::any_relocation_info &RE) const; 478 bool getPlainRelocationExternal(const MachO::any_relocation_info &RE) const; 479 bool getScatteredRelocationScattered( 480 const MachO::any_relocation_info &RE) const; 481 uint32_t getScatteredRelocationValue( 482 const MachO::any_relocation_info &RE) const; 483 uint32_t getScatteredRelocationType( 484 const MachO::any_relocation_info &RE) const; 485 unsigned getAnyRelocationAddress(const MachO::any_relocation_info &RE) const; 486 unsigned getAnyRelocationPCRel(const MachO::any_relocation_info &RE) const; 487 unsigned getAnyRelocationLength(const MachO::any_relocation_info &RE) const; 488 unsigned getAnyRelocationType(const MachO::any_relocation_info &RE) const; 489 SectionRef getAnyRelocationSection(const MachO::any_relocation_info &RE) const; 490 491 // MachO specific structures. 492 MachO::section getSection(DataRefImpl DRI) const; 493 MachO::section_64 getSection64(DataRefImpl DRI) const; 494 MachO::section getSection(const LoadCommandInfo &L, unsigned Index) const; 495 MachO::section_64 getSection64(const LoadCommandInfo &L,unsigned Index) const; 496 MachO::nlist getSymbolTableEntry(DataRefImpl DRI) const; 497 MachO::nlist_64 getSymbol64TableEntry(DataRefImpl DRI) const; 498 499 MachO::linkedit_data_command 500 getLinkeditDataLoadCommand(const LoadCommandInfo &L) const; 501 MachO::segment_command 502 getSegmentLoadCommand(const LoadCommandInfo &L) const; 503 MachO::segment_command_64 504 getSegment64LoadCommand(const LoadCommandInfo &L) const; 505 MachO::linker_option_command 506 getLinkerOptionLoadCommand(const LoadCommandInfo &L) const; 507 MachO::version_min_command 508 getVersionMinLoadCommand(const LoadCommandInfo &L) const; 509 MachO::note_command 510 getNoteLoadCommand(const LoadCommandInfo &L) const; 511 MachO::build_version_command 512 getBuildVersionLoadCommand(const LoadCommandInfo &L) const; 513 MachO::build_tool_version 514 getBuildToolVersion(unsigned index) const; 515 MachO::dylib_command 516 getDylibIDLoadCommand(const LoadCommandInfo &L) const; 517 MachO::dyld_info_command 518 getDyldInfoLoadCommand(const LoadCommandInfo &L) const; 519 MachO::dylinker_command 520 getDylinkerCommand(const LoadCommandInfo &L) const; 521 MachO::uuid_command 522 getUuidCommand(const LoadCommandInfo &L) const; 523 MachO::rpath_command 524 getRpathCommand(const LoadCommandInfo &L) const; 525 MachO::source_version_command 526 getSourceVersionCommand(const LoadCommandInfo &L) const; 527 MachO::entry_point_command 528 getEntryPointCommand(const LoadCommandInfo &L) const; 529 MachO::encryption_info_command 530 getEncryptionInfoCommand(const LoadCommandInfo &L) const; 531 MachO::encryption_info_command_64 532 getEncryptionInfoCommand64(const LoadCommandInfo &L) const; 533 MachO::sub_framework_command 534 getSubFrameworkCommand(const LoadCommandInfo &L) const; 535 MachO::sub_umbrella_command 536 getSubUmbrellaCommand(const LoadCommandInfo &L) const; 537 MachO::sub_library_command 538 getSubLibraryCommand(const LoadCommandInfo &L) const; 539 MachO::sub_client_command 540 getSubClientCommand(const LoadCommandInfo &L) const; 541 MachO::routines_command 542 getRoutinesCommand(const LoadCommandInfo &L) const; 543 MachO::routines_command_64 544 getRoutinesCommand64(const LoadCommandInfo &L) const; 545 MachO::thread_command 546 getThreadCommand(const LoadCommandInfo &L) const; 547 548 MachO::any_relocation_info getRelocation(DataRefImpl Rel) const; 549 MachO::data_in_code_entry getDice(DataRefImpl Rel) const; 550 const MachO::mach_header &getHeader() const; 551 const MachO::mach_header_64 &getHeader64() const; 552 uint32_t 553 getIndirectSymbolTableEntry(const MachO::dysymtab_command &DLC, 554 unsigned Index) const; 555 MachO::data_in_code_entry getDataInCodeTableEntry(uint32_t DataOffset, 556 unsigned Index) const; 557 MachO::symtab_command getSymtabLoadCommand() const; 558 MachO::dysymtab_command getDysymtabLoadCommand() const; 559 MachO::linkedit_data_command getDataInCodeLoadCommand() const; 560 MachO::linkedit_data_command getLinkOptHintsLoadCommand() const; 561 ArrayRef<uint8_t> getDyldInfoRebaseOpcodes() const; 562 ArrayRef<uint8_t> getDyldInfoBindOpcodes() const; 563 ArrayRef<uint8_t> getDyldInfoWeakBindOpcodes() const; 564 ArrayRef<uint8_t> getDyldInfoLazyBindOpcodes() const; 565 ArrayRef<uint8_t> getDyldInfoExportsTrie() const; 566 ArrayRef<uint8_t> getUuid() const; 567 568 StringRef getStringTableData() const; 569 bool is64Bit() const; 570 void ReadULEB128s(uint64_t Index, SmallVectorImpl<uint64_t> &Out) const; 571 572 static StringRef guessLibraryShortName(StringRef Name, bool &isFramework, 573 StringRef &Suffix); 574 575 static Triple::ArchType getArch(uint32_t CPUType, uint32_t CPUSubType); 576 static Triple getArchTriple(uint32_t CPUType, uint32_t CPUSubType, 577 const char **McpuDefault = nullptr, 578 const char **ArchFlag = nullptr); 579 static bool isValidArch(StringRef ArchFlag); 580 static ArrayRef<StringRef> getValidArchs(); 581 static Triple getHostArch(); 582 583 bool isRelocatableObject() const override; 584 585 StringRef mapDebugSectionName(StringRef Name) const override; 586 587 llvm::binaryformat::Swift5ReflectionSectionKind 588 mapReflectionSectionNameToEnumValue(StringRef SectionName) const override; 589 590 bool hasPageZeroSegment() const { return HasPageZeroSegment; } 591 592 static bool classof(const Binary *v) { 593 return v->isMachO(); 594 } 595 596 static uint32_t 597 getVersionMinMajor(MachO::version_min_command &C, bool SDK) { 598 uint32_t VersionOrSDK = (SDK) ? C.sdk : C.version; 599 return (VersionOrSDK >> 16) & 0xffff; 600 } 601 602 static uint32_t 603 getVersionMinMinor(MachO::version_min_command &C, bool SDK) { 604 uint32_t VersionOrSDK = (SDK) ? C.sdk : C.version; 605 return (VersionOrSDK >> 8) & 0xff; 606 } 607 608 static uint32_t 609 getVersionMinUpdate(MachO::version_min_command &C, bool SDK) { 610 uint32_t VersionOrSDK = (SDK) ? C.sdk : C.version; 611 return VersionOrSDK & 0xff; 612 } 613 614 static std::string getBuildPlatform(uint32_t platform) { 615 switch (platform) { 616 case MachO::PLATFORM_MACOS: return "macos"; 617 case MachO::PLATFORM_IOS: return "ios"; 618 case MachO::PLATFORM_TVOS: return "tvos"; 619 case MachO::PLATFORM_WATCHOS: return "watchos"; 620 case MachO::PLATFORM_BRIDGEOS: return "bridgeos"; 621 case MachO::PLATFORM_MACCATALYST: return "macCatalyst"; 622 case MachO::PLATFORM_IOSSIMULATOR: return "iossimulator"; 623 case MachO::PLATFORM_TVOSSIMULATOR: return "tvossimulator"; 624 case MachO::PLATFORM_WATCHOSSIMULATOR: return "watchossimulator"; 625 case MachO::PLATFORM_DRIVERKIT: return "driverkit"; 626 default: 627 std::string ret; 628 raw_string_ostream ss(ret); 629 ss << format_hex(platform, 8, true); 630 return ss.str(); 631 } 632 } 633 634 static std::string getBuildTool(uint32_t tools) { 635 switch (tools) { 636 case MachO::TOOL_CLANG: return "clang"; 637 case MachO::TOOL_SWIFT: return "swift"; 638 case MachO::TOOL_LD: return "ld"; 639 default: 640 std::string ret; 641 raw_string_ostream ss(ret); 642 ss << format_hex(tools, 8, true); 643 return ss.str(); 644 } 645 } 646 647 static std::string getVersionString(uint32_t version) { 648 uint32_t major = (version >> 16) & 0xffff; 649 uint32_t minor = (version >> 8) & 0xff; 650 uint32_t update = version & 0xff; 651 652 SmallString<32> Version; 653 Version = utostr(major) + "." + utostr(minor); 654 if (update != 0) 655 Version += "." + utostr(update); 656 return std::string(std::string(Version.str())); 657 } 658 659 /// If the input path is a .dSYM bundle (as created by the dsymutil tool), 660 /// return the paths to the object files found in the bundle, otherwise return 661 /// an empty vector. If the path appears to be a .dSYM bundle but no objects 662 /// were found or there was a filesystem error, then return an error. 663 static Expected<std::vector<std::string>> 664 findDsymObjectMembers(StringRef Path); 665 666 private: 667 MachOObjectFile(MemoryBufferRef Object, bool IsLittleEndian, bool Is64Bits, 668 Error &Err, uint32_t UniversalCputype = 0, 669 uint32_t UniversalIndex = 0); 670 671 uint64_t getSymbolValueImpl(DataRefImpl Symb) const override; 672 673 union { 674 MachO::mach_header_64 Header64; 675 MachO::mach_header Header; 676 }; 677 using SectionList = SmallVector<const char*, 1>; 678 SectionList Sections; 679 using LibraryList = SmallVector<const char*, 1>; 680 LibraryList Libraries; 681 LoadCommandList LoadCommands; 682 using LibraryShortName = SmallVector<StringRef, 1>; 683 using BuildToolList = SmallVector<const char*, 1>; 684 BuildToolList BuildTools; 685 mutable LibraryShortName LibrariesShortNames; 686 std::unique_ptr<BindRebaseSegInfo> BindRebaseSectionTable; 687 const char *SymtabLoadCmd = nullptr; 688 const char *DysymtabLoadCmd = nullptr; 689 const char *DataInCodeLoadCmd = nullptr; 690 const char *LinkOptHintsLoadCmd = nullptr; 691 const char *DyldInfoLoadCmd = nullptr; 692 const char *UuidLoadCmd = nullptr; 693 bool HasPageZeroSegment = false; 694 }; 695 696 /// DiceRef 697 inline DiceRef::DiceRef(DataRefImpl DiceP, const ObjectFile *Owner) 698 : DicePimpl(DiceP) , OwningObject(Owner) {} 699 700 inline bool DiceRef::operator==(const DiceRef &Other) const { 701 return DicePimpl == Other.DicePimpl; 702 } 703 704 inline bool DiceRef::operator<(const DiceRef &Other) const { 705 return DicePimpl < Other.DicePimpl; 706 } 707 708 inline void DiceRef::moveNext() { 709 const MachO::data_in_code_entry *P = 710 reinterpret_cast<const MachO::data_in_code_entry *>(DicePimpl.p); 711 DicePimpl.p = reinterpret_cast<uintptr_t>(P + 1); 712 } 713 714 // Since a Mach-O data in code reference, a DiceRef, can only be created when 715 // the OwningObject ObjectFile is a MachOObjectFile a static_cast<> is used for 716 // the methods that get the values of the fields of the reference. 717 718 inline std::error_code DiceRef::getOffset(uint32_t &Result) const { 719 const MachOObjectFile *MachOOF = 720 static_cast<const MachOObjectFile *>(OwningObject); 721 MachO::data_in_code_entry Dice = MachOOF->getDice(DicePimpl); 722 Result = Dice.offset; 723 return std::error_code(); 724 } 725 726 inline std::error_code DiceRef::getLength(uint16_t &Result) const { 727 const MachOObjectFile *MachOOF = 728 static_cast<const MachOObjectFile *>(OwningObject); 729 MachO::data_in_code_entry Dice = MachOOF->getDice(DicePimpl); 730 Result = Dice.length; 731 return std::error_code(); 732 } 733 734 inline std::error_code DiceRef::getKind(uint16_t &Result) const { 735 const MachOObjectFile *MachOOF = 736 static_cast<const MachOObjectFile *>(OwningObject); 737 MachO::data_in_code_entry Dice = MachOOF->getDice(DicePimpl); 738 Result = Dice.kind; 739 return std::error_code(); 740 } 741 742 inline DataRefImpl DiceRef::getRawDataRefImpl() const { 743 return DicePimpl; 744 } 745 746 inline const ObjectFile *DiceRef::getObjectFile() const { 747 return OwningObject; 748 } 749 750 } // end namespace object 751 } // end namespace llvm 752 753 #endif // LLVM_OBJECT_MACHO_H 754