MachO.h 28 KB

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