MachO.h 28 KB

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